This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldelta: removed confusing XSLoader commentary
[perl5.git] / util.c
CommitLineData
a0d0e21e 1/* util.c
a687059c 2 *
1129b882
NC
3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
a687059c 5 *
d48672a2
LW
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.
8d063cd8 8 *
8d063cd8 9 */
a0d0e21e
LW
10
11/*
4ac71550
TC
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
14 *
15 * [p.598 of _The Lord of the Rings_, III/xi: "The Palantír"]
a0d0e21e 16 */
8d063cd8 17
166f8a29
DM
18/* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
22 */
23
8d063cd8 24#include "EXTERN.h"
864dbfa3 25#define PERL_IN_UTIL_C
8d063cd8 26#include "perl.h"
62b28dd9 27
6f408c34 28#ifdef USE_PERLIO
2e0cfa16 29#include "perliol.h" /* For PerlIOUnix_refcnt */
6f408c34 30#endif
2e0cfa16 31
64ca3a65 32#ifndef PERL_MICRO
a687059c 33#include <signal.h>
36477c24 34#ifndef SIG_ERR
35# define SIG_ERR ((Sighandler_t) -1)
36#endif
64ca3a65 37#endif
36477c24 38
172d2248
OS
39#ifdef __Lynx__
40/* Missing protos on LynxOS */
41int putenv(char *);
42#endif
43
ff68c719 44#ifdef I_SYS_WAIT
45# include <sys/wait.h>
46#endif
47
868439a2
JH
48#ifdef HAS_SELECT
49# ifdef I_SYS_SELECT
50# include <sys/select.h>
51# endif
52#endif
53
8d063cd8 54#define FLUSH
8d063cd8 55
16cebae2
GS
56#if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
57# define FD_CLOEXEC 1 /* NeXT needs this */
58#endif
59
a687059c
LW
60/* NOTE: Do not call the next three routines directly. Use the macros
61 * in handy.h, so that we can easily redefine everything to do tracking of
62 * allocated hunks back to the original New to track down any memory leaks.
20cec16a 63 * XXX This advice seems to be widely ignored :-( --AD August 1996.
a687059c
LW
64 */
65
ca8d8976
NC
66static char *
67S_write_no_mem(pTHX)
68{
97aff369 69 dVAR;
ca8d8976
NC
70 /* Can't use PerlIO to write as it allocates memory */
71 PerlLIO_write(PerlIO_fileno(Perl_error_log),
72 PL_no_mem, strlen(PL_no_mem));
73 my_exit(1);
1f440eb2 74 NORETURN_FUNCTION_END;
ca8d8976
NC
75}
76
79a92154 77#if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
1f4d2d4e
NC
78# define ALWAYS_NEED_THX
79#endif
80
26fa51c3
AMS
81/* paranoid version of system's malloc() */
82
bd4080b3 83Malloc_t
4f63d024 84Perl_safesysmalloc(MEM_SIZE size)
8d063cd8 85{
1f4d2d4e 86#ifdef ALWAYS_NEED_THX
54aff467 87 dTHX;
0cb20dae 88#endif
bd4080b3 89 Malloc_t ptr;
55497cff 90#ifdef HAS_64K_LIMIT
62b28dd9 91 if (size > 0xffff) {
bf49b057 92 PerlIO_printf(Perl_error_log,
16cebae2 93 "Allocation too large: %lx\n", size) FLUSH;
54aff467 94 my_exit(1);
62b28dd9 95 }
55497cff 96#endif /* HAS_64K_LIMIT */
e8dda941
JD
97#ifdef PERL_TRACK_MEMPOOL
98 size += sTHX;
99#endif
34de22dd
LW
100#ifdef DEBUGGING
101 if ((long)size < 0)
4f63d024 102 Perl_croak_nocontext("panic: malloc");
34de22dd 103#endif
12ae5dfc 104 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
da927450 105 PERL_ALLOC_CHECK(ptr);
bd61b366 106 if (ptr != NULL) {
e8dda941 107#ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
108 struct perl_memory_debug_header *const header
109 = (struct perl_memory_debug_header *)ptr;
9a083ecf
NC
110#endif
111
112#ifdef PERL_POISON
7e337ee0 113 PoisonNew(((char *)ptr), size, char);
9a083ecf 114#endif
7cb608b5 115
9a083ecf 116#ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
117 header->interpreter = aTHX;
118 /* Link us into the list. */
119 header->prev = &PL_memory_debug_header;
120 header->next = PL_memory_debug_header.next;
121 PL_memory_debug_header.next = header;
122 header->next->prev = header;
cd1541b2 123# ifdef PERL_POISON
7cb608b5 124 header->size = size;
cd1541b2 125# endif
e8dda941
JD
126 ptr = (Malloc_t)((char*)ptr+sTHX);
127#endif
5dfff8f3 128 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
8d063cd8 129 return ptr;
e8dda941 130}
8d063cd8 131 else {
1f4d2d4e 132#ifndef ALWAYS_NEED_THX
0cb20dae
NC
133 dTHX;
134#endif
135 if (PL_nomemok)
136 return NULL;
137 else {
138 return write_no_mem();
139 }
8d063cd8
LW
140 }
141 /*NOTREACHED*/
142}
143
f2517201 144/* paranoid version of system's realloc() */
8d063cd8 145
bd4080b3 146Malloc_t
4f63d024 147Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
8d063cd8 148{
1f4d2d4e 149#ifdef ALWAYS_NEED_THX
54aff467 150 dTHX;
0cb20dae 151#endif
bd4080b3 152 Malloc_t ptr;
9a34ef1d 153#if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
6ad3d225 154 Malloc_t PerlMem_realloc();
ecfc5424 155#endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
8d063cd8 156
a1d180c4 157#ifdef HAS_64K_LIMIT
5f05dabc 158 if (size > 0xffff) {
bf49b057 159 PerlIO_printf(Perl_error_log,
5f05dabc 160 "Reallocation too large: %lx\n", size) FLUSH;
54aff467 161 my_exit(1);
5f05dabc 162 }
55497cff 163#endif /* HAS_64K_LIMIT */
7614df0c 164 if (!size) {
f2517201 165 safesysfree(where);
7614df0c
JD
166 return NULL;
167 }
168
378cc40b 169 if (!where)
f2517201 170 return safesysmalloc(size);
e8dda941
JD
171#ifdef PERL_TRACK_MEMPOOL
172 where = (Malloc_t)((char*)where-sTHX);
173 size += sTHX;
7cb608b5
NC
174 {
175 struct perl_memory_debug_header *const header
176 = (struct perl_memory_debug_header *)where;
177
178 if (header->interpreter != aTHX) {
179 Perl_croak_nocontext("panic: realloc from wrong pool");
180 }
181 assert(header->next->prev == header);
182 assert(header->prev->next == header);
cd1541b2 183# ifdef PERL_POISON
7cb608b5
NC
184 if (header->size > size) {
185 const MEM_SIZE freed_up = header->size - size;
186 char *start_of_freed = ((char *)where) + size;
7e337ee0 187 PoisonFree(start_of_freed, freed_up, char);
7cb608b5
NC
188 }
189 header->size = size;
cd1541b2 190# endif
7cb608b5 191 }
e8dda941 192#endif
34de22dd
LW
193#ifdef DEBUGGING
194 if ((long)size < 0)
4f63d024 195 Perl_croak_nocontext("panic: realloc");
34de22dd 196#endif
12ae5dfc 197 ptr = (Malloc_t)PerlMem_realloc(where,size);
da927450 198 PERL_ALLOC_CHECK(ptr);
a1d180c4 199
4fd0a9b8
NC
200 /* MUST do this fixup first, before doing ANYTHING else, as anything else
201 might allocate memory/free/move memory, and until we do the fixup, it
202 may well be chasing (and writing to) free memory. */
e8dda941 203#ifdef PERL_TRACK_MEMPOOL
4fd0a9b8 204 if (ptr != NULL) {
7cb608b5
NC
205 struct perl_memory_debug_header *const header
206 = (struct perl_memory_debug_header *)ptr;
207
9a083ecf
NC
208# ifdef PERL_POISON
209 if (header->size < size) {
210 const MEM_SIZE fresh = size - header->size;
211 char *start_of_fresh = ((char *)ptr) + size;
7e337ee0 212 PoisonNew(start_of_fresh, fresh, char);
9a083ecf
NC
213 }
214# endif
215
7cb608b5
NC
216 header->next->prev = header;
217 header->prev->next = header;
218
e8dda941 219 ptr = (Malloc_t)((char*)ptr+sTHX);
4fd0a9b8 220 }
e8dda941 221#endif
4fd0a9b8
NC
222
223 /* In particular, must do that fixup above before logging anything via
224 *printf(), as it can reallocate memory, which can cause SEGVs. */
225
226 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
227 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
228
229
230 if (ptr != NULL) {
8d063cd8 231 return ptr;
e8dda941 232 }
8d063cd8 233 else {
1f4d2d4e 234#ifndef ALWAYS_NEED_THX
0cb20dae
NC
235 dTHX;
236#endif
237 if (PL_nomemok)
238 return NULL;
239 else {
240 return write_no_mem();
241 }
8d063cd8
LW
242 }
243 /*NOTREACHED*/
244}
245
f2517201 246/* safe version of system's free() */
8d063cd8 247
54310121 248Free_t
4f63d024 249Perl_safesysfree(Malloc_t where)
8d063cd8 250{
79a92154 251#ifdef ALWAYS_NEED_THX
54aff467 252 dTHX;
97aff369
JH
253#else
254 dVAR;
155aba94 255#endif
97835f67 256 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
378cc40b 257 if (where) {
e8dda941
JD
258#ifdef PERL_TRACK_MEMPOOL
259 where = (Malloc_t)((char*)where-sTHX);
cd1541b2 260 {
7cb608b5
NC
261 struct perl_memory_debug_header *const header
262 = (struct perl_memory_debug_header *)where;
263
264 if (header->interpreter != aTHX) {
265 Perl_croak_nocontext("panic: free from wrong pool");
266 }
267 if (!header->prev) {
cd1541b2
NC
268 Perl_croak_nocontext("panic: duplicate free");
269 }
7cb608b5
NC
270 if (!(header->next) || header->next->prev != header
271 || header->prev->next != header) {
272 Perl_croak_nocontext("panic: bad free");
cd1541b2 273 }
7cb608b5
NC
274 /* Unlink us from the chain. */
275 header->next->prev = header->prev;
276 header->prev->next = header->next;
277# ifdef PERL_POISON
7e337ee0 278 PoisonNew(where, header->size, char);
cd1541b2 279# endif
7cb608b5
NC
280 /* Trigger the duplicate free warning. */
281 header->next = NULL;
282 }
e8dda941 283#endif
6ad3d225 284 PerlMem_free(where);
378cc40b 285 }
8d063cd8
LW
286}
287
f2517201 288/* safe version of system's calloc() */
1050c9ca 289
bd4080b3 290Malloc_t
4f63d024 291Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
1050c9ca 292{
1f4d2d4e 293#ifdef ALWAYS_NEED_THX
54aff467 294 dTHX;
0cb20dae 295#endif
bd4080b3 296 Malloc_t ptr;
4b1123b9 297#if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
ad7244db 298 MEM_SIZE total_size = 0;
4b1123b9 299#endif
1050c9ca 300
ad7244db 301 /* Even though calloc() for zero bytes is strange, be robust. */
4b1123b9
NC
302 if (size && (count <= MEM_SIZE_MAX / size)) {
303#if defined(PERL_TRACK_MEMPOOL) || defined(HAS_64K_LIMIT) || defined(DEBUGGING)
ad7244db 304 total_size = size * count;
4b1123b9
NC
305#endif
306 }
ad7244db 307 else
f1f66076 308 Perl_croak_nocontext("%s", PL_memory_wrap);
ad7244db 309#ifdef PERL_TRACK_MEMPOOL
19a94d75 310 if (sTHX <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
ad7244db
JH
311 total_size += sTHX;
312 else
f1f66076 313 Perl_croak_nocontext("%s", PL_memory_wrap);
ad7244db 314#endif
55497cff 315#ifdef HAS_64K_LIMIT
e1a95402 316 if (total_size > 0xffff) {
bf49b057 317 PerlIO_printf(Perl_error_log,
e1a95402 318 "Allocation too large: %lx\n", total_size) FLUSH;
54aff467 319 my_exit(1);
5f05dabc 320 }
55497cff 321#endif /* HAS_64K_LIMIT */
1050c9ca 322#ifdef DEBUGGING
323 if ((long)size < 0 || (long)count < 0)
4f63d024 324 Perl_croak_nocontext("panic: calloc");
1050c9ca 325#endif
e8dda941 326#ifdef PERL_TRACK_MEMPOOL
e1a95402
NC
327 /* Have to use malloc() because we've added some space for our tracking
328 header. */
ad7244db
JH
329 /* malloc(0) is non-portable. */
330 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
e1a95402
NC
331#else
332 /* Use calloc() because it might save a memset() if the memory is fresh
333 and clean from the OS. */
ad7244db
JH
334 if (count && size)
335 ptr = (Malloc_t)PerlMem_calloc(count, size);
336 else /* calloc(0) is non-portable. */
337 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
e8dda941 338#endif
da927450 339 PERL_ALLOC_CHECK(ptr);
e1a95402 340 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
bd61b366 341 if (ptr != NULL) {
e8dda941 342#ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
343 {
344 struct perl_memory_debug_header *const header
345 = (struct perl_memory_debug_header *)ptr;
346
e1a95402 347 memset((void*)ptr, 0, total_size);
7cb608b5
NC
348 header->interpreter = aTHX;
349 /* Link us into the list. */
350 header->prev = &PL_memory_debug_header;
351 header->next = PL_memory_debug_header.next;
352 PL_memory_debug_header.next = header;
353 header->next->prev = header;
cd1541b2 354# ifdef PERL_POISON
e1a95402 355 header->size = total_size;
cd1541b2 356# endif
7cb608b5
NC
357 ptr = (Malloc_t)((char*)ptr+sTHX);
358 }
e8dda941 359#endif
1050c9ca 360 return ptr;
361 }
0cb20dae 362 else {
1f4d2d4e 363#ifndef ALWAYS_NEED_THX
0cb20dae
NC
364 dTHX;
365#endif
366 if (PL_nomemok)
367 return NULL;
368 return write_no_mem();
369 }
1050c9ca 370}
371
cae6d0e5
GS
372/* These must be defined when not using Perl's malloc for binary
373 * compatibility */
374
375#ifndef MYMALLOC
376
377Malloc_t Perl_malloc (MEM_SIZE nbytes)
378{
379 dTHXs;
077a72a9 380 return (Malloc_t)PerlMem_malloc(nbytes);
cae6d0e5
GS
381}
382
383Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
384{
385 dTHXs;
077a72a9 386 return (Malloc_t)PerlMem_calloc(elements, size);
cae6d0e5
GS
387}
388
389Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
390{
391 dTHXs;
077a72a9 392 return (Malloc_t)PerlMem_realloc(where, nbytes);
cae6d0e5
GS
393}
394
395Free_t Perl_mfree (Malloc_t where)
396{
397 dTHXs;
398 PerlMem_free(where);
399}
400
401#endif
402
8d063cd8
LW
403/* copy a string up to some (non-backslashed) delimiter, if any */
404
405char *
04c9e624 406Perl_delimcpy(register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
8d063cd8 407{
fc36a67e 408 register I32 tolen;
35da51f7 409
7918f24d
NC
410 PERL_ARGS_ASSERT_DELIMCPY;
411
fc36a67e 412 for (tolen = 0; from < fromend; from++, tolen++) {
378cc40b 413 if (*from == '\\') {
35da51f7 414 if (from[1] != delim) {
fc36a67e 415 if (to < toend)
416 *to++ = *from;
417 tolen++;
fc36a67e 418 }
35da51f7 419 from++;
378cc40b 420 }
bedebaa5 421 else if (*from == delim)
8d063cd8 422 break;
fc36a67e 423 if (to < toend)
424 *to++ = *from;
8d063cd8 425 }
bedebaa5
CS
426 if (to < toend)
427 *to = '\0';
fc36a67e 428 *retlen = tolen;
73d840c0 429 return (char *)from;
8d063cd8
LW
430}
431
432/* return ptr to little string in big string, NULL if not found */
378cc40b 433/* This routine was donated by Corey Satten. */
8d063cd8
LW
434
435char *
04c9e624 436Perl_instr(register const char *big, register const char *little)
378cc40b 437{
79072805 438 register I32 first;
378cc40b 439
7918f24d
NC
440 PERL_ARGS_ASSERT_INSTR;
441
a687059c 442 if (!little)
08105a92 443 return (char*)big;
a687059c 444 first = *little++;
378cc40b 445 if (!first)
08105a92 446 return (char*)big;
378cc40b 447 while (*big) {
66a1b24b 448 register const char *s, *x;
378cc40b
LW
449 if (*big++ != first)
450 continue;
451 for (x=big,s=little; *s; /**/ ) {
452 if (!*x)
bd61b366 453 return NULL;
4fc877ac 454 if (*s != *x)
378cc40b 455 break;
4fc877ac
AL
456 else {
457 s++;
458 x++;
378cc40b
LW
459 }
460 }
461 if (!*s)
08105a92 462 return (char*)(big-1);
378cc40b 463 }
bd61b366 464 return NULL;
378cc40b 465}
8d063cd8 466
a687059c
LW
467/* same as instr but allow embedded nulls */
468
469char *
04c9e624 470Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
8d063cd8 471{
7918f24d 472 PERL_ARGS_ASSERT_NINSTR;
4c8626be
GA
473 if (little >= lend)
474 return (char*)big;
475 {
8ba22ff4 476 const char first = *little;
4c8626be 477 const char *s, *x;
8ba22ff4 478 bigend -= lend - little++;
4c8626be
GA
479 OUTER:
480 while (big <= bigend) {
b0ca24ee
JH
481 if (*big++ == first) {
482 for (x=big,s=little; s < lend; x++,s++) {
483 if (*s != *x)
484 goto OUTER;
485 }
486 return (char*)(big-1);
4c8626be 487 }
4c8626be 488 }
378cc40b 489 }
bd61b366 490 return NULL;
a687059c
LW
491}
492
493/* reverse of the above--find last substring */
494
495char *
04c9e624 496Perl_rninstr(register const char *big, const char *bigend, const char *little, const char *lend)
a687059c 497{
08105a92 498 register const char *bigbeg;
e1ec3a88 499 register const I32 first = *little;
7452cf6a 500 register const char * const littleend = lend;
a687059c 501
7918f24d
NC
502 PERL_ARGS_ASSERT_RNINSTR;
503
260d78c9 504 if (little >= littleend)
08105a92 505 return (char*)bigend;
a687059c
LW
506 bigbeg = big;
507 big = bigend - (littleend - little++);
508 while (big >= bigbeg) {
66a1b24b 509 register const char *s, *x;
a687059c
LW
510 if (*big-- != first)
511 continue;
512 for (x=big+2,s=little; s < littleend; /**/ ) {
4fc877ac 513 if (*s != *x)
a687059c 514 break;
4fc877ac
AL
515 else {
516 x++;
517 s++;
a687059c
LW
518 }
519 }
520 if (s >= littleend)
08105a92 521 return (char*)(big+1);
378cc40b 522 }
bd61b366 523 return NULL;
378cc40b 524}
a687059c 525
cf93c79d
IZ
526/* As a space optimization, we do not compile tables for strings of length
527 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
528 special-cased in fbm_instr().
529
530 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
531
954c1994 532/*
ccfc67b7
JH
533=head1 Miscellaneous Functions
534
954c1994
GS
535=for apidoc fbm_compile
536
537Analyses the string in order to make fast searches on it using fbm_instr()
538-- the Boyer-Moore algorithm.
539
540=cut
541*/
542
378cc40b 543void
7506f9c3 544Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
378cc40b 545{
97aff369 546 dVAR;
0d46e09a 547 register const U8 *s;
ea725ce6 548 STRLEN i;
0b71040e 549 STRLEN len;
ea725ce6 550 STRLEN rarest = 0;
79072805 551 U32 frequency = 256;
2bda37ba 552 MAGIC *mg;
79072805 553
7918f24d
NC
554 PERL_ARGS_ASSERT_FBM_COMPILE;
555
4265b45d
NC
556 /* Refuse to fbm_compile a studied scalar, as this gives more flexibility in
557 SV flag usage. No real-world code would ever end up using a studied
558 scalar as a compile-time second argument to index, so this isn't a real
559 pessimisation. */
560 if (SvSCREAM(sv))
561 return;
562
9402563a
NC
563 if (SvVALID(sv))
564 return;
565
c517dc2b 566 if (flags & FBMcf_TAIL) {
890ce7af 567 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
396482e1 568 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
c517dc2b
JH
569 if (mg && mg->mg_len >= 0)
570 mg->mg_len++;
571 }
9cbe880b 572 s = (U8*)SvPV_force_mutable(sv, len);
d1be9408 573 if (len == 0) /* TAIL might be on a zero-length string. */
cf93c79d 574 return;
c13a5c80 575 SvUPGRADE(sv, SVt_PVMG);
78d0cf80 576 SvIOK_off(sv);
8eeaf79a
NC
577 SvNOK_off(sv);
578 SvVALID_on(sv);
2bda37ba
NC
579
580 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
581 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
582 to call SvVALID_off() if the scalar was assigned to.
583
584 The comment itself (and "deeper magic" below) date back to
585 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
586 str->str_pok |= 2;
587 where the magic (presumably) was that the scalar had a BM table hidden
588 inside itself.
589
590 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
591 the table instead of the previous (somewhat hacky) approach of co-opting
592 the string buffer and storing it after the string. */
593
594 assert(!mg_find(sv, PERL_MAGIC_bm));
595 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
596 assert(mg);
597
02128f11 598 if (len > 2) {
21aeb718
NC
599 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
600 the BM table. */
66a1b24b 601 const U8 mlen = (len>255) ? 255 : (U8)len;
2bda37ba 602 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
890ce7af 603 register U8 *table;
cf93c79d 604
2bda37ba 605 Newx(table, 256, U8);
7506f9c3 606 memset((void*)table, mlen, 256);
2bda37ba
NC
607 mg->mg_ptr = (char *)table;
608 mg->mg_len = 256;
609
610 s += len - 1; /* last char */
02128f11 611 i = 0;
cf93c79d
IZ
612 while (s >= sb) {
613 if (table[*s] == mlen)
7506f9c3 614 table[*s] = (U8)i;
cf93c79d
IZ
615 s--, i++;
616 }
378cc40b 617 }
378cc40b 618
9cbe880b 619 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
bbce6d69 620 for (i = 0; i < len; i++) {
22c35a8c 621 if (PL_freq[s[i]] < frequency) {
bbce6d69 622 rarest = i;
22c35a8c 623 frequency = PL_freq[s[i]];
378cc40b
LW
624 }
625 }
79072805 626 BmRARE(sv) = s[rarest];
44a10c71 627 BmPREVIOUS(sv) = rarest;
cf93c79d
IZ
628 BmUSEFUL(sv) = 100; /* Initial value */
629 if (flags & FBMcf_TAIL)
630 SvTAIL_on(sv);
ea725ce6
NC
631 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
632 BmRARE(sv), BmPREVIOUS(sv)));
378cc40b
LW
633}
634
cf93c79d
IZ
635/* If SvTAIL(littlestr), it has a fake '\n' at end. */
636/* If SvTAIL is actually due to \Z or \z, this gives false positives
637 if multiline */
638
954c1994
GS
639/*
640=for apidoc fbm_instr
641
642Returns the location of the SV in the string delimited by C<str> and
bd61b366 643C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
954c1994
GS
644does not have to be fbm_compiled, but the search will not be as fast
645then.
646
647=cut
648*/
649
378cc40b 650char *
864dbfa3 651Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
378cc40b 652{
a687059c 653 register unsigned char *s;
cf93c79d 654 STRLEN l;
9cbe880b
NC
655 register const unsigned char *little
656 = (const unsigned char *)SvPV_const(littlestr,l);
cf93c79d 657 register STRLEN littlelen = l;
e1ec3a88 658 register const I32 multiline = flags & FBMrf_MULTILINE;
cf93c79d 659
7918f24d
NC
660 PERL_ARGS_ASSERT_FBM_INSTR;
661
eb160463 662 if ((STRLEN)(bigend - big) < littlelen) {
a1d180c4 663 if ( SvTAIL(littlestr)
eb160463 664 && ((STRLEN)(bigend - big) == littlelen - 1)
a1d180c4 665 && (littlelen == 1
12ae5dfc 666 || (*big == *little &&
27da23d5 667 memEQ((char *)big, (char *)little, littlelen - 1))))
cf93c79d 668 return (char*)big;
bd61b366 669 return NULL;
cf93c79d 670 }
378cc40b 671
21aeb718
NC
672 switch (littlelen) { /* Special cases for 0, 1 and 2 */
673 case 0:
674 return (char*)big; /* Cannot be SvTAIL! */
675 case 1:
cf93c79d
IZ
676 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
677 /* Know that bigend != big. */
678 if (bigend[-1] == '\n')
679 return (char *)(bigend - 1);
680 return (char *) bigend;
681 }
682 s = big;
683 while (s < bigend) {
684 if (*s == *little)
685 return (char *)s;
686 s++;
687 }
688 if (SvTAIL(littlestr))
689 return (char *) bigend;
bd61b366 690 return NULL;
21aeb718 691 case 2:
cf93c79d
IZ
692 if (SvTAIL(littlestr) && !multiline) {
693 if (bigend[-1] == '\n' && bigend[-2] == *little)
694 return (char*)bigend - 2;
695 if (bigend[-1] == *little)
696 return (char*)bigend - 1;
bd61b366 697 return NULL;
cf93c79d
IZ
698 }
699 {
700 /* This should be better than FBM if c1 == c2, and almost
701 as good otherwise: maybe better since we do less indirection.
702 And we save a lot of memory by caching no table. */
66a1b24b
AL
703 const unsigned char c1 = little[0];
704 const unsigned char c2 = little[1];
cf93c79d
IZ
705
706 s = big + 1;
707 bigend--;
708 if (c1 != c2) {
709 while (s <= bigend) {
710 if (s[0] == c2) {
711 if (s[-1] == c1)
712 return (char*)s - 1;
713 s += 2;
714 continue;
3fe6f2dc 715 }
cf93c79d
IZ
716 next_chars:
717 if (s[0] == c1) {
718 if (s == bigend)
719 goto check_1char_anchor;
720 if (s[1] == c2)
721 return (char*)s;
722 else {
723 s++;
724 goto next_chars;
725 }
726 }
727 else
728 s += 2;
729 }
730 goto check_1char_anchor;
731 }
732 /* Now c1 == c2 */
733 while (s <= bigend) {
734 if (s[0] == c1) {
735 if (s[-1] == c1)
736 return (char*)s - 1;
737 if (s == bigend)
738 goto check_1char_anchor;
739 if (s[1] == c1)
740 return (char*)s;
741 s += 3;
02128f11 742 }
c277df42 743 else
cf93c79d 744 s += 2;
c277df42 745 }
c277df42 746 }
cf93c79d
IZ
747 check_1char_anchor: /* One char and anchor! */
748 if (SvTAIL(littlestr) && (*bigend == *little))
749 return (char *)bigend; /* bigend is already decremented. */
bd61b366 750 return NULL;
21aeb718
NC
751 default:
752 break; /* Only lengths 0 1 and 2 have special-case code. */
d48672a2 753 }
21aeb718 754
cf93c79d 755 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
bbce6d69 756 s = bigend - littlelen;
a1d180c4 757 if (s >= big && bigend[-1] == '\n' && *s == *little
cf93c79d
IZ
758 /* Automatically of length > 2 */
759 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
7506f9c3 760 {
bbce6d69 761 return (char*)s; /* how sweet it is */
7506f9c3
GS
762 }
763 if (s[1] == *little
764 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
765 {
cf93c79d 766 return (char*)s + 1; /* how sweet it is */
7506f9c3 767 }
bd61b366 768 return NULL;
02128f11 769 }
cecf5685 770 if (!SvVALID(littlestr)) {
c4420975 771 char * const b = ninstr((char*)big,(char*)bigend,
cf93c79d
IZ
772 (char*)little, (char*)little + littlelen);
773
774 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
775 /* Chop \n from littlestr: */
776 s = bigend - littlelen + 1;
7506f9c3
GS
777 if (*s == *little
778 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
779 {
3fe6f2dc 780 return (char*)s;
7506f9c3 781 }
bd61b366 782 return NULL;
a687059c 783 }
cf93c79d 784 return b;
a687059c 785 }
a1d180c4 786
3566a07d
NC
787 /* Do actual FBM. */
788 if (littlelen > (STRLEN)(bigend - big))
789 return NULL;
790
791 {
2bda37ba
NC
792 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
793 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
0d46e09a 794 register const unsigned char *oldlittle;
cf93c79d 795
cf93c79d
IZ
796 --littlelen; /* Last char found by table lookup */
797
798 s = big + littlelen;
799 little += littlelen; /* last char */
800 oldlittle = little;
801 if (s < bigend) {
802 register I32 tmp;
803
804 top2:
7506f9c3 805 if ((tmp = table[*s])) {
cf93c79d 806 if ((s += tmp) < bigend)
62b28dd9 807 goto top2;
cf93c79d
IZ
808 goto check_end;
809 }
810 else { /* less expensive than calling strncmp() */
66a1b24b 811 register unsigned char * const olds = s;
cf93c79d
IZ
812
813 tmp = littlelen;
814
815 while (tmp--) {
816 if (*--s == *--little)
817 continue;
cf93c79d
IZ
818 s = olds + 1; /* here we pay the price for failure */
819 little = oldlittle;
820 if (s < bigend) /* fake up continue to outer loop */
821 goto top2;
822 goto check_end;
823 }
824 return (char *)s;
a687059c 825 }
378cc40b 826 }
cf93c79d 827 check_end:
c8029a41 828 if ( s == bigend
cffe132d 829 && SvTAIL(littlestr)
12ae5dfc
JH
830 && memEQ((char *)(bigend - littlelen),
831 (char *)(oldlittle - littlelen), littlelen) )
cf93c79d 832 return (char*)bigend - littlelen;
bd61b366 833 return NULL;
378cc40b 834 }
378cc40b
LW
835}
836
c277df42
IZ
837/* start_shift, end_shift are positive quantities which give offsets
838 of ends of some substring of bigstr.
a0288114 839 If "last" we want the last occurrence.
c277df42 840 old_posp is the way of communication between consequent calls if
a1d180c4 841 the next call needs to find the .
c277df42 842 The initial *old_posp should be -1.
cf93c79d
IZ
843
844 Note that we take into account SvTAIL, so one can get extra
845 optimizations if _ALL flag is set.
c277df42
IZ
846 */
847
cf93c79d 848/* If SvTAIL is actually due to \Z or \z, this gives false positives
26fa51c3 849 if PL_multiline. In fact if !PL_multiline the authoritative answer
cf93c79d
IZ
850 is not supported yet. */
851
378cc40b 852char *
864dbfa3 853Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
378cc40b 854{
97aff369 855 dVAR;
0d46e09a 856 register const unsigned char *big;
79072805
LW
857 register I32 pos;
858 register I32 previous;
859 register I32 first;
0d46e09a 860 register const unsigned char *little;
c277df42 861 register I32 stop_pos;
0d46e09a 862 register const unsigned char *littleend;
c277df42 863 I32 found = 0;
378cc40b 864
7918f24d
NC
865 PERL_ARGS_ASSERT_SCREAMINSTR;
866
c13a5c80 867 assert(SvTYPE(littlestr) == SVt_PVMG);
cecf5685 868 assert(SvVALID(littlestr));
d372c834 869
c277df42 870 if (*old_posp == -1
3280af22 871 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
cf93c79d
IZ
872 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
873 cant_find:
a1d180c4 874 if ( BmRARE(littlestr) == '\n'
85c508c3 875 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
cfd0369c 876 little = (const unsigned char *)(SvPVX_const(littlestr));
cf93c79d
IZ
877 littleend = little + SvCUR(littlestr);
878 first = *little++;
879 goto check_tail;
880 }
bd61b366 881 return NULL;
cf93c79d
IZ
882 }
883
cfd0369c 884 little = (const unsigned char *)(SvPVX_const(littlestr));
79072805 885 littleend = little + SvCUR(littlestr);
378cc40b 886 first = *little++;
c277df42 887 /* The value of pos we can start at: */
79072805 888 previous = BmPREVIOUS(littlestr);
cfd0369c 889 big = (const unsigned char *)(SvPVX_const(bigstr));
c277df42
IZ
890 /* The value of pos we can stop at: */
891 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
cf93c79d 892 if (previous + start_shift > stop_pos) {
0fe87f7c
HS
893/*
894 stop_pos does not include SvTAIL in the count, so this check is incorrect
895 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
896*/
897#if 0
cf93c79d
IZ
898 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
899 goto check_tail;
0fe87f7c 900#endif
bd61b366 901 return NULL;
cf93c79d 902 }
c277df42 903 while (pos < previous + start_shift) {
3280af22 904 if (!(pos += PL_screamnext[pos]))
cf93c79d 905 goto cant_find;
378cc40b 906 }
de3bb511 907 big -= previous;
bbce6d69 908 do {
0d46e09a 909 register const unsigned char *s, *x;
ef64f398 910 if (pos >= stop_pos) break;
bbce6d69 911 if (big[pos] != first)
912 continue;
913 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
bbce6d69 914 if (*s++ != *x++) {
915 s--;
916 break;
378cc40b 917 }
bbce6d69 918 }
c277df42
IZ
919 if (s == littleend) {
920 *old_posp = pos;
921 if (!last) return (char *)(big+pos);
922 found = 1;
923 }
3280af22 924 } while ( pos += PL_screamnext[pos] );
a1d180c4 925 if (last && found)
cf93c79d 926 return (char *)(big+(*old_posp));
cf93c79d
IZ
927 check_tail:
928 if (!SvTAIL(littlestr) || (end_shift > 0))
bd61b366 929 return NULL;
cf93c79d 930 /* Ignore the trailing "\n". This code is not microoptimized */
cfd0369c 931 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
cf93c79d
IZ
932 stop_pos = littleend - little; /* Actual littlestr len */
933 if (stop_pos == 0)
934 return (char*)big;
935 big -= stop_pos;
936 if (*big == first
12ae5dfc
JH
937 && ((stop_pos == 1) ||
938 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
cf93c79d 939 return (char*)big;
bd61b366 940 return NULL;
8d063cd8
LW
941}
942
e6226b18
KW
943/*
944=for apidoc foldEQ
945
946Returns true if the leading len bytes of the strings s1 and s2 are the same
947case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
948match themselves and their opposite case counterparts. Non-cased and non-ASCII
949range bytes match only themselves.
950
951=cut
952*/
953
954
79072805 955I32
e6226b18 956Perl_foldEQ(const char *s1, const char *s2, register I32 len)
79072805 957{
e1ec3a88
AL
958 register const U8 *a = (const U8 *)s1;
959 register const U8 *b = (const U8 *)s2;
96a5add6 960
e6226b18 961 PERL_ARGS_ASSERT_FOLDEQ;
7918f24d 962
79072805 963 while (len--) {
22c35a8c 964 if (*a != *b && *a != PL_fold[*b])
e6226b18 965 return 0;
bbce6d69 966 a++,b++;
967 }
e6226b18 968 return 1;
bbce6d69 969}
1b9f127b
KW
970I32
971Perl_foldEQ_latin1(const char *s1, const char *s2, register I32 len)
972{
973 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
974 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
975 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
976 * does it check that the strings each have at least 'len' characters */
977
978 register const U8 *a = (const U8 *)s1;
979 register const U8 *b = (const U8 *)s2;
980
981 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
982
983 while (len--) {
984 if (*a != *b && *a != PL_fold_latin1[*b]) {
985 return 0;
986 }
987 a++, b++;
988 }
989 return 1;
990}
bbce6d69 991
e6226b18
KW
992/*
993=for apidoc foldEQ_locale
994
995Returns true if the leading len bytes of the strings s1 and s2 are the same
996case-insensitively in the current locale; false otherwise.
997
998=cut
999*/
1000
bbce6d69 1001I32
e6226b18 1002Perl_foldEQ_locale(const char *s1, const char *s2, register I32 len)
bbce6d69 1003{
27da23d5 1004 dVAR;
e1ec3a88
AL
1005 register const U8 *a = (const U8 *)s1;
1006 register const U8 *b = (const U8 *)s2;
96a5add6 1007
e6226b18 1008 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
7918f24d 1009
bbce6d69 1010 while (len--) {
22c35a8c 1011 if (*a != *b && *a != PL_fold_locale[*b])
e6226b18 1012 return 0;
bbce6d69 1013 a++,b++;
79072805 1014 }
e6226b18 1015 return 1;
79072805
LW
1016}
1017
8d063cd8
LW
1018/* copy a string to a safe spot */
1019
954c1994 1020/*
ccfc67b7
JH
1021=head1 Memory Management
1022
954c1994
GS
1023=for apidoc savepv
1024
61a925ed
AMS
1025Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1026string which is a duplicate of C<pv>. The size of the string is
1027determined by C<strlen()>. The memory allocated for the new string can
1028be freed with the C<Safefree()> function.
954c1994
GS
1029
1030=cut
1031*/
1032
8d063cd8 1033char *
efdfce31 1034Perl_savepv(pTHX_ const char *pv)
8d063cd8 1035{
96a5add6 1036 PERL_UNUSED_CONTEXT;
e90e2364 1037 if (!pv)
bd61b366 1038 return NULL;
66a1b24b
AL
1039 else {
1040 char *newaddr;
1041 const STRLEN pvlen = strlen(pv)+1;
10edeb5d
JH
1042 Newx(newaddr, pvlen, char);
1043 return (char*)memcpy(newaddr, pv, pvlen);
66a1b24b 1044 }
8d063cd8
LW
1045}
1046
a687059c
LW
1047/* same thing but with a known length */
1048
954c1994
GS
1049/*
1050=for apidoc savepvn
1051
61a925ed
AMS
1052Perl's version of what C<strndup()> would be if it existed. Returns a
1053pointer to a newly allocated string which is a duplicate of the first
cbf82dd0
NC
1054C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
1055the new string can be freed with the C<Safefree()> function.
954c1994
GS
1056
1057=cut
1058*/
1059
a687059c 1060char *
efdfce31 1061Perl_savepvn(pTHX_ const char *pv, register I32 len)
a687059c
LW
1062{
1063 register char *newaddr;
96a5add6 1064 PERL_UNUSED_CONTEXT;
a687059c 1065
a02a5408 1066 Newx(newaddr,len+1,char);
92110913 1067 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
efdfce31 1068 if (pv) {
e90e2364
NC
1069 /* might not be null terminated */
1070 newaddr[len] = '\0';
07409e01 1071 return (char *) CopyD(pv,newaddr,len,char);
92110913
NIS
1072 }
1073 else {
07409e01 1074 return (char *) ZeroD(newaddr,len+1,char);
92110913 1075 }
a687059c
LW
1076}
1077
05ec9bb3
NIS
1078/*
1079=for apidoc savesharedpv
1080
61a925ed
AMS
1081A version of C<savepv()> which allocates the duplicate string in memory
1082which is shared between threads.
05ec9bb3
NIS
1083
1084=cut
1085*/
1086char *
efdfce31 1087Perl_savesharedpv(pTHX_ const char *pv)
05ec9bb3 1088{
e90e2364 1089 register char *newaddr;
490a0e98 1090 STRLEN pvlen;
e90e2364 1091 if (!pv)
bd61b366 1092 return NULL;
e90e2364 1093
490a0e98
NC
1094 pvlen = strlen(pv)+1;
1095 newaddr = (char*)PerlMemShared_malloc(pvlen);
e90e2364 1096 if (!newaddr) {
0bd48802 1097 return write_no_mem();
05ec9bb3 1098 }
10edeb5d 1099 return (char*)memcpy(newaddr, pv, pvlen);
05ec9bb3
NIS
1100}
1101
2e0de35c 1102/*
d9095cec
NC
1103=for apidoc savesharedpvn
1104
1105A version of C<savepvn()> which allocates the duplicate string in memory
1106which is shared between threads. (With the specific difference that a NULL
1107pointer is not acceptable)
1108
1109=cut
1110*/
1111char *
1112Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1113{
1114 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
7918f24d
NC
1115
1116 PERL_ARGS_ASSERT_SAVESHAREDPVN;
1117
d9095cec
NC
1118 if (!newaddr) {
1119 return write_no_mem();
1120 }
1121 newaddr[len] = '\0';
1122 return (char*)memcpy(newaddr, pv, len);
1123}
1124
1125/*
2e0de35c
NC
1126=for apidoc savesvpv
1127
6832267f 1128A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
2e0de35c
NC
1129the passed in SV using C<SvPV()>
1130
1131=cut
1132*/
1133
1134char *
1135Perl_savesvpv(pTHX_ SV *sv)
1136{
1137 STRLEN len;
7452cf6a 1138 const char * const pv = SvPV_const(sv, len);
2e0de35c
NC
1139 register char *newaddr;
1140
7918f24d
NC
1141 PERL_ARGS_ASSERT_SAVESVPV;
1142
26866f99 1143 ++len;
a02a5408 1144 Newx(newaddr,len,char);
07409e01 1145 return (char *) CopyD(pv,newaddr,len,char);
2e0de35c 1146}
05ec9bb3 1147
9dcc53ea
Z
1148/*
1149=for apidoc savesharedsvpv
1150
1151A version of C<savesharedpv()> which allocates the duplicate string in
1152memory which is shared between threads.
1153
1154=cut
1155*/
1156
1157char *
1158Perl_savesharedsvpv(pTHX_ SV *sv)
1159{
1160 STRLEN len;
1161 const char * const pv = SvPV_const(sv, len);
1162
1163 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1164
1165 return savesharedpvn(pv, len);
1166}
05ec9bb3 1167
cea2e8a9 1168/* the SV for Perl_form() and mess() is not kept in an arena */
fc36a67e 1169
76e3520e 1170STATIC SV *
cea2e8a9 1171S_mess_alloc(pTHX)
fc36a67e 1172{
97aff369 1173 dVAR;
fc36a67e 1174 SV *sv;
1175 XPVMG *any;
1176
627364f1 1177 if (PL_phase != PERL_PHASE_DESTRUCT)
84bafc02 1178 return newSVpvs_flags("", SVs_TEMP);
e72dc28c 1179
0372dbb6
GS
1180 if (PL_mess_sv)
1181 return PL_mess_sv;
1182
fc36a67e 1183 /* Create as PVMG now, to avoid any upgrading later */
a02a5408
JC
1184 Newx(sv, 1, SV);
1185 Newxz(any, 1, XPVMG);
fc36a67e 1186 SvFLAGS(sv) = SVt_PVMG;
1187 SvANY(sv) = (void*)any;
6136c704 1188 SvPV_set(sv, NULL);
fc36a67e 1189 SvREFCNT(sv) = 1 << 30; /* practically infinite */
e72dc28c 1190 PL_mess_sv = sv;
fc36a67e 1191 return sv;
1192}
1193
c5be433b 1194#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1195char *
1196Perl_form_nocontext(const char* pat, ...)
1197{
1198 dTHX;
c5be433b 1199 char *retval;
cea2e8a9 1200 va_list args;
7918f24d 1201 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
cea2e8a9 1202 va_start(args, pat);
c5be433b 1203 retval = vform(pat, &args);
cea2e8a9 1204 va_end(args);
c5be433b 1205 return retval;
cea2e8a9 1206}
c5be433b 1207#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9 1208
7c9e965c 1209/*
ccfc67b7 1210=head1 Miscellaneous Functions
7c9e965c
JP
1211=for apidoc form
1212
1213Takes a sprintf-style format pattern and conventional
1214(non-SV) arguments and returns the formatted string.
1215
1216 (char *) Perl_form(pTHX_ const char* pat, ...)
1217
1218can be used any place a string (char *) is required:
1219
1220 char * s = Perl_form("%d.%d",major,minor);
1221
1222Uses a single private buffer so if you want to format several strings you
1223must explicitly copy the earlier strings away (and free the copies when you
1224are done).
1225
1226=cut
1227*/
1228
8990e307 1229char *
864dbfa3 1230Perl_form(pTHX_ const char* pat, ...)
8990e307 1231{
c5be433b 1232 char *retval;
46fc3d4c 1233 va_list args;
7918f24d 1234 PERL_ARGS_ASSERT_FORM;
46fc3d4c 1235 va_start(args, pat);
c5be433b 1236 retval = vform(pat, &args);
46fc3d4c 1237 va_end(args);
c5be433b
GS
1238 return retval;
1239}
1240
1241char *
1242Perl_vform(pTHX_ const char *pat, va_list *args)
1243{
2d03de9c 1244 SV * const sv = mess_alloc();
7918f24d 1245 PERL_ARGS_ASSERT_VFORM;
4608196e 1246 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
e72dc28c 1247 return SvPVX(sv);
46fc3d4c 1248}
a687059c 1249
c5df3096
Z
1250/*
1251=for apidoc Am|SV *|mess|const char *pat|...
1252
1253Take a sprintf-style format pattern and argument list. These are used to
1254generate a string message. If the message does not end with a newline,
1255then it will be extended with some indication of the current location
1256in the code, as described for L</mess_sv>.
1257
1258Normally, the resulting message is returned in a new mortal SV.
1259During global destruction a single SV may be shared between uses of
1260this function.
1261
1262=cut
1263*/
1264
5a844595
GS
1265#if defined(PERL_IMPLICIT_CONTEXT)
1266SV *
1267Perl_mess_nocontext(const char *pat, ...)
1268{
1269 dTHX;
1270 SV *retval;
1271 va_list args;
7918f24d 1272 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
5a844595
GS
1273 va_start(args, pat);
1274 retval = vmess(pat, &args);
1275 va_end(args);
1276 return retval;
1277}
1278#endif /* PERL_IMPLICIT_CONTEXT */
1279
06bf62c7 1280SV *
5a844595
GS
1281Perl_mess(pTHX_ const char *pat, ...)
1282{
1283 SV *retval;
1284 va_list args;
7918f24d 1285 PERL_ARGS_ASSERT_MESS;
5a844595
GS
1286 va_start(args, pat);
1287 retval = vmess(pat, &args);
1288 va_end(args);
1289 return retval;
1290}
1291
5f66b61c
AL
1292STATIC const COP*
1293S_closest_cop(pTHX_ const COP *cop, const OP *o)
ae7d165c 1294{
97aff369 1295 dVAR;
ae7d165c
PJ
1296 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1297
7918f24d
NC
1298 PERL_ARGS_ASSERT_CLOSEST_COP;
1299
fabdb6c0
AL
1300 if (!o || o == PL_op)
1301 return cop;
ae7d165c
PJ
1302
1303 if (o->op_flags & OPf_KIDS) {
5f66b61c 1304 const OP *kid;
fabdb6c0 1305 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
5f66b61c 1306 const COP *new_cop;
ae7d165c
PJ
1307
1308 /* If the OP_NEXTSTATE has been optimised away we can still use it
1309 * the get the file and line number. */
1310
1311 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
5f66b61c 1312 cop = (const COP *)kid;
ae7d165c
PJ
1313
1314 /* Keep searching, and return when we've found something. */
1315
1316 new_cop = closest_cop(cop, kid);
fabdb6c0
AL
1317 if (new_cop)
1318 return new_cop;
ae7d165c
PJ
1319 }
1320 }
1321
1322 /* Nothing found. */
1323
5f66b61c 1324 return NULL;
ae7d165c
PJ
1325}
1326
c5df3096
Z
1327/*
1328=for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1329
1330Expands a message, intended for the user, to include an indication of
1331the current location in the code, if the message does not already appear
1332to be complete.
1333
1334C<basemsg> is the initial message or object. If it is a reference, it
1335will be used as-is and will be the result of this function. Otherwise it
1336is used as a string, and if it already ends with a newline, it is taken
1337to be complete, and the result of this function will be the same string.
1338If the message does not end with a newline, then a segment such as C<at
1339foo.pl line 37> will be appended, and possibly other clauses indicating
1340the current state of execution. The resulting message will end with a
1341dot and a newline.
1342
1343Normally, the resulting message is returned in a new mortal SV.
1344During global destruction a single SV may be shared between uses of this
1345function. If C<consume> is true, then the function is permitted (but not
1346required) to modify and return C<basemsg> instead of allocating a new SV.
1347
1348=cut
1349*/
1350
5a844595 1351SV *
c5df3096 1352Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
46fc3d4c 1353{
97aff369 1354 dVAR;
c5df3096 1355 SV *sv;
46fc3d4c 1356
c5df3096
Z
1357 PERL_ARGS_ASSERT_MESS_SV;
1358
1359 if (SvROK(basemsg)) {
1360 if (consume) {
1361 sv = basemsg;
1362 }
1363 else {
1364 sv = mess_alloc();
1365 sv_setsv(sv, basemsg);
1366 }
1367 return sv;
1368 }
1369
1370 if (SvPOK(basemsg) && consume) {
1371 sv = basemsg;
1372 }
1373 else {
1374 sv = mess_alloc();
1375 sv_copypv(sv, basemsg);
1376 }
7918f24d 1377
46fc3d4c 1378 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
ae7d165c
PJ
1379 /*
1380 * Try and find the file and line for PL_op. This will usually be
1381 * PL_curcop, but it might be a cop that has been optimised away. We
1382 * can try to find such a cop by searching through the optree starting
1383 * from the sibling of PL_curcop.
1384 */
1385
e1ec3a88 1386 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
5f66b61c
AL
1387 if (!cop)
1388 cop = PL_curcop;
ae7d165c
PJ
1389
1390 if (CopLINE(cop))
ed094faf 1391 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
3aed30dc 1392 OutCopFILE(cop), (IV)CopLINE(cop));
191f87d5
DH
1393 /* Seems that GvIO() can be untrustworthy during global destruction. */
1394 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1395 && IoLINES(GvIOp(PL_last_in_gv)))
1396 {
e1ec3a88 1397 const bool line_mode = (RsSIMPLE(PL_rs) &&
95a20fc0 1398 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
57def98f 1399 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
5f66b61c 1400 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
edc2eac3
JH
1401 line_mode ? "line" : "chunk",
1402 (IV)IoLINES(GvIOp(PL_last_in_gv)));
a687059c 1403 }
627364f1 1404 if (PL_phase == PERL_PHASE_DESTRUCT)
5f66b61c
AL
1405 sv_catpvs(sv, " during global destruction");
1406 sv_catpvs(sv, ".\n");
a687059c 1407 }
06bf62c7 1408 return sv;
a687059c
LW
1409}
1410
c5df3096
Z
1411/*
1412=for apidoc Am|SV *|vmess|const char *pat|va_list *args
1413
1414C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1415argument list. These are used to generate a string message. If the
1416message does not end with a newline, then it will be extended with
1417some indication of the current location in the code, as described for
1418L</mess_sv>.
1419
1420Normally, the resulting message is returned in a new mortal SV.
1421During global destruction a single SV may be shared between uses of
1422this function.
1423
1424=cut
1425*/
1426
1427SV *
1428Perl_vmess(pTHX_ const char *pat, va_list *args)
1429{
1430 dVAR;
1431 SV * const sv = mess_alloc();
1432
1433 PERL_ARGS_ASSERT_VMESS;
1434
1435 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1436 return mess_sv(sv, 1);
1437}
1438
7ff03255 1439void
7d0994e0 1440Perl_write_to_stderr(pTHX_ SV* msv)
7ff03255 1441{
27da23d5 1442 dVAR;
7ff03255
SG
1443 IO *io;
1444 MAGIC *mg;
1445
7918f24d
NC
1446 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1447
7ff03255
SG
1448 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1449 && (io = GvIO(PL_stderrgv))
daba3364 1450 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
d1d7a15d
NC
1451 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, "PRINT",
1452 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
7ff03255
SG
1453 else {
1454#ifdef USE_SFIO
1455 /* SFIO can really mess with your errno */
4ee39169 1456 dSAVED_ERRNO;
7ff03255 1457#endif
53c1dcc0 1458 PerlIO * const serr = Perl_error_log;
7ff03255 1459
83c55556 1460 do_print(msv, serr);
7ff03255
SG
1461 (void)PerlIO_flush(serr);
1462#ifdef USE_SFIO
4ee39169 1463 RESTORE_ERRNO;
7ff03255
SG
1464#endif
1465 }
1466}
1467
c5df3096
Z
1468/*
1469=head1 Warning and Dieing
1470*/
1471
1472/* Common code used in dieing and warning */
1473
1474STATIC SV *
1475S_with_queued_errors(pTHX_ SV *ex)
1476{
1477 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1478 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1479 sv_catsv(PL_errors, ex);
1480 ex = sv_mortalcopy(PL_errors);
1481 SvCUR_set(PL_errors, 0);
1482 }
1483 return ex;
1484}
3ab1ac99 1485
46d9c920 1486STATIC bool
c5df3096 1487S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
63315e18 1488{
97aff369 1489 dVAR;
63315e18
NC
1490 HV *stash;
1491 GV *gv;
1492 CV *cv;
46d9c920
NC
1493 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1494 /* sv_2cv might call Perl_croak() or Perl_warner() */
1495 SV * const oldhook = *hook;
1496
c5df3096
Z
1497 if (!oldhook)
1498 return FALSE;
63315e18 1499
63315e18 1500 ENTER;
46d9c920
NC
1501 SAVESPTR(*hook);
1502 *hook = NULL;
1503 cv = sv_2cv(oldhook, &stash, &gv, 0);
63315e18
NC
1504 LEAVE;
1505 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1506 dSP;
c5df3096 1507 SV *exarg;
63315e18
NC
1508
1509 ENTER;
1510 save_re_context();
46d9c920
NC
1511 if (warn) {
1512 SAVESPTR(*hook);
1513 *hook = NULL;
1514 }
c5df3096
Z
1515 exarg = newSVsv(ex);
1516 SvREADONLY_on(exarg);
1517 SAVEFREESV(exarg);
63315e18 1518
46d9c920 1519 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
63315e18 1520 PUSHMARK(SP);
c5df3096 1521 XPUSHs(exarg);
63315e18 1522 PUTBACK;
daba3364 1523 call_sv(MUTABLE_SV(cv), G_DISCARD);
63315e18
NC
1524 POPSTACK;
1525 LEAVE;
46d9c920 1526 return TRUE;
63315e18 1527 }
46d9c920 1528 return FALSE;
63315e18
NC
1529}
1530
c5df3096
Z
1531/*
1532=for apidoc Am|OP *|die_sv|SV *baseex
e07360fa 1533
c5df3096
Z
1534Behaves the same as L</croak_sv>, except for the return type.
1535It should be used only where the C<OP *> return type is required.
1536The function never actually returns.
e07360fa 1537
c5df3096
Z
1538=cut
1539*/
e07360fa 1540
c5df3096
Z
1541OP *
1542Perl_die_sv(pTHX_ SV *baseex)
36477c24 1543{
c5df3096
Z
1544 PERL_ARGS_ASSERT_DIE_SV;
1545 croak_sv(baseex);
ad09800f
GG
1546 /* NOTREACHED */
1547 return NULL;
36477c24 1548}
1549
c5df3096
Z
1550/*
1551=for apidoc Am|OP *|die|const char *pat|...
1552
1553Behaves the same as L</croak>, except for the return type.
1554It should be used only where the C<OP *> return type is required.
1555The function never actually returns.
1556
1557=cut
1558*/
1559
c5be433b 1560#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1561OP *
1562Perl_die_nocontext(const char* pat, ...)
a687059c 1563{
cea2e8a9 1564 dTHX;
a687059c 1565 va_list args;
cea2e8a9 1566 va_start(args, pat);
c5df3096
Z
1567 vcroak(pat, &args);
1568 /* NOTREACHED */
cea2e8a9 1569 va_end(args);
c5df3096 1570 return NULL;
cea2e8a9 1571}
c5be433b 1572#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9
GS
1573
1574OP *
1575Perl_die(pTHX_ const char* pat, ...)
1576{
cea2e8a9
GS
1577 va_list args;
1578 va_start(args, pat);
c5df3096
Z
1579 vcroak(pat, &args);
1580 /* NOTREACHED */
cea2e8a9 1581 va_end(args);
c5df3096 1582 return NULL;
cea2e8a9
GS
1583}
1584
c5df3096
Z
1585/*
1586=for apidoc Am|void|croak_sv|SV *baseex
1587
1588This is an XS interface to Perl's C<die> function.
1589
1590C<baseex> is the error message or object. If it is a reference, it
1591will be used as-is. Otherwise it is used as a string, and if it does
1592not end with a newline then it will be extended with some indication of
1593the current location in the code, as described for L</mess_sv>.
1594
1595The error message or object will be used as an exception, by default
1596returning control to the nearest enclosing C<eval>, but subject to
1597modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1598function never returns normally.
1599
1600To die with a simple string message, the L</croak> function may be
1601more convenient.
1602
1603=cut
1604*/
1605
c5be433b 1606void
c5df3096 1607Perl_croak_sv(pTHX_ SV *baseex)
cea2e8a9 1608{
c5df3096
Z
1609 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1610 PERL_ARGS_ASSERT_CROAK_SV;
1611 invoke_exception_hook(ex, FALSE);
1612 die_unwind(ex);
1613}
1614
1615/*
1616=for apidoc Am|void|vcroak|const char *pat|va_list *args
1617
1618This is an XS interface to Perl's C<die> function.
1619
1620C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1621argument list. These are used to generate a string message. If the
1622message does not end with a newline, then it will be extended with
1623some indication of the current location in the code, as described for
1624L</mess_sv>.
1625
1626The error message will be used as an exception, by default
1627returning control to the nearest enclosing C<eval>, but subject to
1628modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1629function never returns normally.
a687059c 1630
c5df3096
Z
1631For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1632(C<$@>) will be used as an error message or object instead of building an
1633error message from arguments. If you want to throw a non-string object,
1634or build an error message in an SV yourself, it is preferable to use
1635the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
5a844595 1636
c5df3096
Z
1637=cut
1638*/
1639
1640void
1641Perl_vcroak(pTHX_ const char* pat, va_list *args)
1642{
1643 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1644 invoke_exception_hook(ex, FALSE);
1645 die_unwind(ex);
a687059c
LW
1646}
1647
c5df3096
Z
1648/*
1649=for apidoc Am|void|croak|const char *pat|...
1650
1651This is an XS interface to Perl's C<die> function.
1652
1653Take a sprintf-style format pattern and argument list. These are used to
1654generate a string message. If the message does not end with a newline,
1655then it will be extended with some indication of the current location
1656in the code, as described for L</mess_sv>.
1657
1658The error message will be used as an exception, by default
1659returning control to the nearest enclosing C<eval>, but subject to
1660modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1661function never returns normally.
1662
1663For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1664(C<$@>) will be used as an error message or object instead of building an
1665error message from arguments. If you want to throw a non-string object,
1666or build an error message in an SV yourself, it is preferable to use
1667the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1668
1669=cut
1670*/
1671
c5be433b 1672#if defined(PERL_IMPLICIT_CONTEXT)
8990e307 1673void
cea2e8a9 1674Perl_croak_nocontext(const char *pat, ...)
a687059c 1675{
cea2e8a9 1676 dTHX;
a687059c 1677 va_list args;
cea2e8a9 1678 va_start(args, pat);
c5be433b 1679 vcroak(pat, &args);
cea2e8a9
GS
1680 /* NOTREACHED */
1681 va_end(args);
1682}
1683#endif /* PERL_IMPLICIT_CONTEXT */
1684
c5df3096
Z
1685void
1686Perl_croak(pTHX_ const char *pat, ...)
1687{
1688 va_list args;
1689 va_start(args, pat);
1690 vcroak(pat, &args);
1691 /* NOTREACHED */
1692 va_end(args);
1693}
1694
954c1994 1695/*
6ad8f254
NC
1696=for apidoc Am|void|croak_no_modify
1697
1698Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1699terser object code than using C<Perl_croak>. Less code used on exception code
1700paths reduces CPU cache pressure.
1701
d8e47b5c 1702=cut
6ad8f254
NC
1703*/
1704
1705void
1706Perl_croak_no_modify(pTHX)
1707{
1708 Perl_croak(aTHX_ "%s", PL_no_modify);
1709}
1710
1711/*
c5df3096 1712=for apidoc Am|void|warn_sv|SV *baseex
ccfc67b7 1713
c5df3096 1714This is an XS interface to Perl's C<warn> function.
954c1994 1715
c5df3096
Z
1716C<baseex> is the error message or object. If it is a reference, it
1717will be used as-is. Otherwise it is used as a string, and if it does
1718not end with a newline then it will be extended with some indication of
1719the current location in the code, as described for L</mess_sv>.
9983fa3c 1720
c5df3096
Z
1721The error message or object will by default be written to standard error,
1722but this is subject to modification by a C<$SIG{__WARN__}> handler.
9983fa3c 1723
c5df3096
Z
1724To warn with a simple string message, the L</warn> function may be
1725more convenient.
954c1994
GS
1726
1727=cut
1728*/
1729
cea2e8a9 1730void
c5df3096 1731Perl_warn_sv(pTHX_ SV *baseex)
cea2e8a9 1732{
c5df3096
Z
1733 SV *ex = mess_sv(baseex, 0);
1734 PERL_ARGS_ASSERT_WARN_SV;
1735 if (!invoke_exception_hook(ex, TRUE))
1736 write_to_stderr(ex);
cea2e8a9
GS
1737}
1738
c5df3096
Z
1739/*
1740=for apidoc Am|void|vwarn|const char *pat|va_list *args
1741
1742This is an XS interface to Perl's C<warn> function.
1743
1744C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1745argument list. These are used to generate a string message. If the
1746message does not end with a newline, then it will be extended with
1747some indication of the current location in the code, as described for
1748L</mess_sv>.
1749
1750The error message or object will by default be written to standard error,
1751but this is subject to modification by a C<$SIG{__WARN__}> handler.
1752
1753Unlike with L</vcroak>, C<pat> is not permitted to be null.
1754
1755=cut
1756*/
1757
c5be433b
GS
1758void
1759Perl_vwarn(pTHX_ const char* pat, va_list *args)
cea2e8a9 1760{
c5df3096 1761 SV *ex = vmess(pat, args);
7918f24d 1762 PERL_ARGS_ASSERT_VWARN;
c5df3096
Z
1763 if (!invoke_exception_hook(ex, TRUE))
1764 write_to_stderr(ex);
1765}
7918f24d 1766
c5df3096
Z
1767/*
1768=for apidoc Am|void|warn|const char *pat|...
87582a92 1769
c5df3096
Z
1770This is an XS interface to Perl's C<warn> function.
1771
1772Take a sprintf-style format pattern and argument list. These are used to
1773generate a string message. If the message does not end with a newline,
1774then it will be extended with some indication of the current location
1775in the code, as described for L</mess_sv>.
1776
1777The error message or object will by default be written to standard error,
1778but this is subject to modification by a C<$SIG{__WARN__}> handler.
1779
1780Unlike with L</croak>, C<pat> is not permitted to be null.
1781
1782=cut
1783*/
8d063cd8 1784
c5be433b 1785#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1786void
1787Perl_warn_nocontext(const char *pat, ...)
1788{
1789 dTHX;
1790 va_list args;
7918f24d 1791 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
cea2e8a9 1792 va_start(args, pat);
c5be433b 1793 vwarn(pat, &args);
cea2e8a9
GS
1794 va_end(args);
1795}
1796#endif /* PERL_IMPLICIT_CONTEXT */
1797
1798void
1799Perl_warn(pTHX_ const char *pat, ...)
1800{
1801 va_list args;
7918f24d 1802 PERL_ARGS_ASSERT_WARN;
cea2e8a9 1803 va_start(args, pat);
c5be433b 1804 vwarn(pat, &args);
cea2e8a9
GS
1805 va_end(args);
1806}
1807
c5be433b
GS
1808#if defined(PERL_IMPLICIT_CONTEXT)
1809void
1810Perl_warner_nocontext(U32 err, const char *pat, ...)
1811{
27da23d5 1812 dTHX;
c5be433b 1813 va_list args;
7918f24d 1814 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
c5be433b
GS
1815 va_start(args, pat);
1816 vwarner(err, pat, &args);
1817 va_end(args);
1818}
1819#endif /* PERL_IMPLICIT_CONTEXT */
1820
599cee73 1821void
9b387841
NC
1822Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1823{
1824 PERL_ARGS_ASSERT_CK_WARNER_D;
1825
1826 if (Perl_ckwarn_d(aTHX_ err)) {
1827 va_list args;
1828 va_start(args, pat);
1829 vwarner(err, pat, &args);
1830 va_end(args);
1831 }
1832}
1833
1834void
a2a5de95
NC
1835Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1836{
1837 PERL_ARGS_ASSERT_CK_WARNER;
1838
1839 if (Perl_ckwarn(aTHX_ err)) {
1840 va_list args;
1841 va_start(args, pat);
1842 vwarner(err, pat, &args);
1843 va_end(args);
1844 }
1845}
1846
1847void
864dbfa3 1848Perl_warner(pTHX_ U32 err, const char* pat,...)
599cee73
PM
1849{
1850 va_list args;
7918f24d 1851 PERL_ARGS_ASSERT_WARNER;
c5be433b
GS
1852 va_start(args, pat);
1853 vwarner(err, pat, &args);
1854 va_end(args);
1855}
1856
1857void
1858Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1859{
27da23d5 1860 dVAR;
7918f24d 1861 PERL_ARGS_ASSERT_VWARNER;
5f2d9966 1862 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
a3b680e6 1863 SV * const msv = vmess(pat, args);
599cee73 1864
c5df3096
Z
1865 invoke_exception_hook(msv, FALSE);
1866 die_unwind(msv);
599cee73
PM
1867 }
1868 else {
d13b0d77 1869 Perl_vwarn(aTHX_ pat, args);
599cee73
PM
1870 }
1871}
1872
f54ba1c2
DM
1873/* implements the ckWARN? macros */
1874
1875bool
1876Perl_ckwarn(pTHX_ U32 w)
1877{
97aff369 1878 dVAR;
ad287e37
NC
1879 /* If lexical warnings have not been set, use $^W. */
1880 if (isLEXWARN_off)
1881 return PL_dowarn & G_WARN_ON;
1882
26c7b074 1883 return ckwarn_common(w);
f54ba1c2
DM
1884}
1885
1886/* implements the ckWARN?_d macro */
1887
1888bool
1889Perl_ckwarn_d(pTHX_ U32 w)
1890{
97aff369 1891 dVAR;
ad287e37
NC
1892 /* If lexical warnings have not been set then default classes warn. */
1893 if (isLEXWARN_off)
1894 return TRUE;
1895
26c7b074
NC
1896 return ckwarn_common(w);
1897}
1898
1899static bool
1900S_ckwarn_common(pTHX_ U32 w)
1901{
ad287e37
NC
1902 if (PL_curcop->cop_warnings == pWARN_ALL)
1903 return TRUE;
1904
1905 if (PL_curcop->cop_warnings == pWARN_NONE)
1906 return FALSE;
1907
98fe6610
NC
1908 /* Check the assumption that at least the first slot is non-zero. */
1909 assert(unpackWARN1(w));
1910
1911 /* Check the assumption that it is valid to stop as soon as a zero slot is
1912 seen. */
1913 if (!unpackWARN2(w)) {
1914 assert(!unpackWARN3(w));
1915 assert(!unpackWARN4(w));
1916 } else if (!unpackWARN3(w)) {
1917 assert(!unpackWARN4(w));
1918 }
1919
26c7b074
NC
1920 /* Right, dealt with all the special cases, which are implemented as non-
1921 pointers, so there is a pointer to a real warnings mask. */
98fe6610
NC
1922 do {
1923 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1924 return TRUE;
1925 } while (w >>= WARNshift);
1926
1927 return FALSE;
f54ba1c2
DM
1928}
1929
72dc9ed5
NC
1930/* Set buffer=NULL to get a new one. */
1931STRLEN *
8ee4cf24 1932Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
72dc9ed5
NC
1933 STRLEN size) {
1934 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
35da51f7 1935 PERL_UNUSED_CONTEXT;
7918f24d 1936 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
72dc9ed5 1937
10edeb5d
JH
1938 buffer = (STRLEN*)
1939 (specialWARN(buffer) ?
1940 PerlMemShared_malloc(len_wanted) :
1941 PerlMemShared_realloc(buffer, len_wanted));
72dc9ed5
NC
1942 buffer[0] = size;
1943 Copy(bits, (buffer + 1), size, char);
1944 return buffer;
1945}
f54ba1c2 1946
e6587932
DM
1947/* since we've already done strlen() for both nam and val
1948 * we can use that info to make things faster than
1949 * sprintf(s, "%s=%s", nam, val)
1950 */
1951#define my_setenv_format(s, nam, nlen, val, vlen) \
1952 Copy(nam, s, nlen, char); \
1953 *(s+nlen) = '='; \
1954 Copy(val, s+(nlen+1), vlen, char); \
1955 *(s+(nlen+1+vlen)) = '\0'
1956
c5d12488
JH
1957#ifdef USE_ENVIRON_ARRAY
1958 /* VMS' my_setenv() is in vms.c */
1959#if !defined(WIN32) && !defined(NETWARE)
8d063cd8 1960void
e1ec3a88 1961Perl_my_setenv(pTHX_ const char *nam, const char *val)
8d063cd8 1962{
27da23d5 1963 dVAR;
4efc5df6
GS
1964#ifdef USE_ITHREADS
1965 /* only parent thread can modify process environment */
1966 if (PL_curinterp == aTHX)
1967#endif
1968 {
f2517201 1969#ifndef PERL_USE_SAFE_PUTENV
50acdf95 1970 if (!PL_use_safe_putenv) {
c5d12488 1971 /* most putenv()s leak, so we manipulate environ directly */
3a9222be
JH
1972 register I32 i;
1973 register const I32 len = strlen(nam);
c5d12488
JH
1974 int nlen, vlen;
1975
3a9222be
JH
1976 /* where does it go? */
1977 for (i = 0; environ[i]; i++) {
1978 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
1979 break;
1980 }
1981
c5d12488
JH
1982 if (environ == PL_origenviron) { /* need we copy environment? */
1983 I32 j;
1984 I32 max;
1985 char **tmpenv;
1986
1987 max = i;
1988 while (environ[max])
1989 max++;
1990 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1991 for (j=0; j<max; j++) { /* copy environment */
1992 const int len = strlen(environ[j]);
1993 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1994 Copy(environ[j], tmpenv[j], len+1, char);
1995 }
1996 tmpenv[max] = NULL;
1997 environ = tmpenv; /* tell exec where it is now */
1998 }
1999 if (!val) {
2000 safesysfree(environ[i]);
2001 while (environ[i]) {
2002 environ[i] = environ[i+1];
2003 i++;
a687059c 2004 }
c5d12488
JH
2005 return;
2006 }
2007 if (!environ[i]) { /* does not exist yet */
2008 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2009 environ[i+1] = NULL; /* make sure it's null terminated */
2010 }
2011 else
2012 safesysfree(environ[i]);
2013 nlen = strlen(nam);
2014 vlen = strlen(val);
2015
2016 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2017 /* all that work just for this */
2018 my_setenv_format(environ[i], nam, nlen, val, vlen);
50acdf95 2019 } else {
c5d12488 2020# endif
7ee146b1 2021# if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
88f5bc07
AB
2022# if defined(HAS_UNSETENV)
2023 if (val == NULL) {
2024 (void)unsetenv(nam);
2025 } else {
2026 (void)setenv(nam, val, 1);
2027 }
2028# else /* ! HAS_UNSETENV */
2029 (void)setenv(nam, val, 1);
2030# endif /* HAS_UNSETENV */
47dafe4d 2031# else
88f5bc07
AB
2032# if defined(HAS_UNSETENV)
2033 if (val == NULL) {
2034 (void)unsetenv(nam);
2035 } else {
c4420975
AL
2036 const int nlen = strlen(nam);
2037 const int vlen = strlen(val);
2038 char * const new_env =
88f5bc07
AB
2039 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2040 my_setenv_format(new_env, nam, nlen, val, vlen);
2041 (void)putenv(new_env);
2042 }
2043# else /* ! HAS_UNSETENV */
2044 char *new_env;
c4420975
AL
2045 const int nlen = strlen(nam);
2046 int vlen;
88f5bc07
AB
2047 if (!val) {
2048 val = "";
2049 }
2050 vlen = strlen(val);
2051 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2052 /* all that work just for this */
2053 my_setenv_format(new_env, nam, nlen, val, vlen);
2054 (void)putenv(new_env);
2055# endif /* HAS_UNSETENV */
47dafe4d 2056# endif /* __CYGWIN__ */
50acdf95
MS
2057#ifndef PERL_USE_SAFE_PUTENV
2058 }
2059#endif
4efc5df6 2060 }
8d063cd8
LW
2061}
2062
c5d12488 2063#else /* WIN32 || NETWARE */
68dc0745 2064
2065void
72229eff 2066Perl_my_setenv(pTHX_ const char *nam, const char *val)
68dc0745 2067{
27da23d5 2068 dVAR;
c5d12488
JH
2069 register char *envstr;
2070 const int nlen = strlen(nam);
2071 int vlen;
e6587932 2072
c5d12488
JH
2073 if (!val) {
2074 val = "";
ac5c734f 2075 }
c5d12488
JH
2076 vlen = strlen(val);
2077 Newx(envstr, nlen+vlen+2, char);
2078 my_setenv_format(envstr, nam, nlen, val, vlen);
2079 (void)PerlEnv_putenv(envstr);
2080 Safefree(envstr);
3e3baf6d
TB
2081}
2082
c5d12488 2083#endif /* WIN32 || NETWARE */
3e3baf6d 2084
c5d12488 2085#endif /* !VMS && !EPOC*/
378cc40b 2086
16d20bd9 2087#ifdef UNLINK_ALL_VERSIONS
79072805 2088I32
6e732051 2089Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
378cc40b 2090{
35da51f7 2091 I32 retries = 0;
378cc40b 2092
7918f24d
NC
2093 PERL_ARGS_ASSERT_UNLNK;
2094
35da51f7
AL
2095 while (PerlLIO_unlink(f) >= 0)
2096 retries++;
2097 return retries ? 0 : -1;
378cc40b
LW
2098}
2099#endif
2100
7a3f2258 2101/* this is a drop-in replacement for bcopy() */
2253333f 2102#if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
378cc40b 2103char *
7a3f2258 2104Perl_my_bcopy(register const char *from,register char *to,register I32 len)
378cc40b 2105{
2d03de9c 2106 char * const retval = to;
378cc40b 2107
7918f24d
NC
2108 PERL_ARGS_ASSERT_MY_BCOPY;
2109
7c0587c8
LW
2110 if (from - to >= 0) {
2111 while (len--)
2112 *to++ = *from++;
2113 }
2114 else {
2115 to += len;
2116 from += len;
2117 while (len--)
faf8582f 2118 *(--to) = *(--from);
7c0587c8 2119 }
378cc40b
LW
2120 return retval;
2121}
ffed7fef 2122#endif
378cc40b 2123
7a3f2258 2124/* this is a drop-in replacement for memset() */
fc36a67e 2125#ifndef HAS_MEMSET
2126void *
7a3f2258 2127Perl_my_memset(register char *loc, register I32 ch, register I32 len)
fc36a67e 2128{
2d03de9c 2129 char * const retval = loc;
fc36a67e 2130
7918f24d
NC
2131 PERL_ARGS_ASSERT_MY_MEMSET;
2132
fc36a67e 2133 while (len--)
2134 *loc++ = ch;
2135 return retval;
2136}
2137#endif
2138
7a3f2258 2139/* this is a drop-in replacement for bzero() */
7c0587c8 2140#if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
378cc40b 2141char *
7a3f2258 2142Perl_my_bzero(register char *loc, register I32 len)
378cc40b 2143{
2d03de9c 2144 char * const retval = loc;
378cc40b 2145
7918f24d
NC
2146 PERL_ARGS_ASSERT_MY_BZERO;
2147
378cc40b
LW
2148 while (len--)
2149 *loc++ = 0;
2150 return retval;
2151}
2152#endif
7c0587c8 2153
7a3f2258 2154/* this is a drop-in replacement for memcmp() */
36477c24 2155#if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
79072805 2156I32
7a3f2258 2157Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
7c0587c8 2158{
e1ec3a88
AL
2159 register const U8 *a = (const U8 *)s1;
2160 register const U8 *b = (const U8 *)s2;
79072805 2161 register I32 tmp;
7c0587c8 2162
7918f24d
NC
2163 PERL_ARGS_ASSERT_MY_MEMCMP;
2164
7c0587c8 2165 while (len--) {
27da23d5 2166 if ((tmp = *a++ - *b++))
7c0587c8
LW
2167 return tmp;
2168 }
2169 return 0;
2170}
36477c24 2171#endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
a687059c 2172
fe14fcc3 2173#ifndef HAS_VPRINTF
d05d9be5
AD
2174/* This vsprintf replacement should generally never get used, since
2175 vsprintf was available in both System V and BSD 2.11. (There may
2176 be some cross-compilation or embedded set-ups where it is needed,
2177 however.)
2178
2179 If you encounter a problem in this function, it's probably a symptom
2180 that Configure failed to detect your system's vprintf() function.
2181 See the section on "item vsprintf" in the INSTALL file.
2182
2183 This version may compile on systems with BSD-ish <stdio.h>,
2184 but probably won't on others.
2185*/
a687059c 2186
85e6fe83 2187#ifdef USE_CHAR_VSPRINTF
a687059c
LW
2188char *
2189#else
2190int
2191#endif
d05d9be5 2192vsprintf(char *dest, const char *pat, void *args)
a687059c
LW
2193{
2194 FILE fakebuf;
2195
d05d9be5
AD
2196#if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2197 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2198 FILE_cnt(&fakebuf) = 32767;
2199#else
2200 /* These probably won't compile -- If you really need
2201 this, you'll have to figure out some other method. */
a687059c
LW
2202 fakebuf._ptr = dest;
2203 fakebuf._cnt = 32767;
d05d9be5 2204#endif
35c8bce7
LW
2205#ifndef _IOSTRG
2206#define _IOSTRG 0
2207#endif
a687059c
LW
2208 fakebuf._flag = _IOWRT|_IOSTRG;
2209 _doprnt(pat, args, &fakebuf); /* what a kludge */
d05d9be5
AD
2210#if defined(STDIO_PTR_LVALUE)
2211 *(FILE_ptr(&fakebuf)++) = '\0';
2212#else
2213 /* PerlIO has probably #defined away fputc, but we want it here. */
2214# ifdef fputc
2215# undef fputc /* XXX Should really restore it later */
2216# endif
2217 (void)fputc('\0', &fakebuf);
2218#endif
85e6fe83 2219#ifdef USE_CHAR_VSPRINTF
a687059c
LW
2220 return(dest);
2221#else
2222 return 0; /* perl doesn't use return value */
2223#endif
2224}
2225
fe14fcc3 2226#endif /* HAS_VPRINTF */
a687059c
LW
2227
2228#ifdef MYSWAP
ffed7fef 2229#if BYTEORDER != 0x4321
a687059c 2230short
864dbfa3 2231Perl_my_swap(pTHX_ short s)
a687059c
LW
2232{
2233#if (BYTEORDER & 1) == 0
2234 short result;
2235
2236 result = ((s & 255) << 8) + ((s >> 8) & 255);
2237 return result;
2238#else
2239 return s;
2240#endif
2241}
2242
2243long
864dbfa3 2244Perl_my_htonl(pTHX_ long l)
a687059c
LW
2245{
2246 union {
2247 long result;
ffed7fef 2248 char c[sizeof(long)];
a687059c
LW
2249 } u;
2250
cef6ea9d
JH
2251#if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
2252#if BYTEORDER == 0x12345678
2253 u.result = 0;
2254#endif
a687059c
LW
2255 u.c[0] = (l >> 24) & 255;
2256 u.c[1] = (l >> 16) & 255;
2257 u.c[2] = (l >> 8) & 255;
2258 u.c[3] = l & 255;
2259 return u.result;
2260#else
ffed7fef 2261#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 2262 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 2263#else
79072805
LW
2264 register I32 o;
2265 register I32 s;
a687059c 2266
ffed7fef
LW
2267 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2268 u.c[o & 0xf] = (l >> s) & 255;
a687059c
LW
2269 }
2270 return u.result;
2271#endif
2272#endif
2273}
2274
2275long
864dbfa3 2276Perl_my_ntohl(pTHX_ long l)
a687059c
LW
2277{
2278 union {
2279 long l;
ffed7fef 2280 char c[sizeof(long)];
a687059c
LW
2281 } u;
2282
ffed7fef 2283#if BYTEORDER == 0x1234
a687059c
LW
2284 u.c[0] = (l >> 24) & 255;
2285 u.c[1] = (l >> 16) & 255;
2286 u.c[2] = (l >> 8) & 255;
2287 u.c[3] = l & 255;
2288 return u.l;
2289#else
ffed7fef 2290#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
cea2e8a9 2291 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
a687059c 2292#else
79072805
LW
2293 register I32 o;
2294 register I32 s;
a687059c
LW
2295
2296 u.l = l;
2297 l = 0;
ffed7fef
LW
2298 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
2299 l |= (u.c[o & 0xf] & 255) << s;
a687059c
LW
2300 }
2301 return l;
2302#endif
2303#endif
2304}
2305
ffed7fef 2306#endif /* BYTEORDER != 0x4321 */
988174c1
LW
2307#endif /* MYSWAP */
2308
2309/*
2310 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
2311 * If these functions are defined,
2312 * the BYTEORDER is neither 0x1234 nor 0x4321.
2313 * However, this is not assumed.
2314 * -DWS
2315 */
2316
1109a392 2317#define HTOLE(name,type) \
988174c1 2318 type \
ba106d47 2319 name (register type n) \
988174c1
LW
2320 { \
2321 union { \
2322 type value; \
2323 char c[sizeof(type)]; \
2324 } u; \
bb7a0f54
MHM
2325 register U32 i; \
2326 register U32 s = 0; \
1109a392 2327 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
988174c1
LW
2328 u.c[i] = (n >> s) & 0xFF; \
2329 } \
2330 return u.value; \
2331 }
2332
1109a392 2333#define LETOH(name,type) \
988174c1 2334 type \
ba106d47 2335 name (register type n) \
988174c1
LW
2336 { \
2337 union { \
2338 type value; \
2339 char c[sizeof(type)]; \
2340 } u; \
bb7a0f54
MHM
2341 register U32 i; \
2342 register U32 s = 0; \
988174c1
LW
2343 u.value = n; \
2344 n = 0; \
1109a392
MHM
2345 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
2346 n |= ((type)(u.c[i] & 0xFF)) << s; \
988174c1
LW
2347 } \
2348 return n; \
2349 }
2350
1109a392
MHM
2351/*
2352 * Big-endian byte order functions.
2353 */
2354
2355#define HTOBE(name,type) \
2356 type \
2357 name (register type n) \
2358 { \
2359 union { \
2360 type value; \
2361 char c[sizeof(type)]; \
2362 } u; \
bb7a0f54
MHM
2363 register U32 i; \
2364 register U32 s = 8*(sizeof(u.c)-1); \
1109a392
MHM
2365 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2366 u.c[i] = (n >> s) & 0xFF; \
2367 } \
2368 return u.value; \
2369 }
2370
2371#define BETOH(name,type) \
2372 type \
2373 name (register type n) \
2374 { \
2375 union { \
2376 type value; \
2377 char c[sizeof(type)]; \
2378 } u; \
bb7a0f54
MHM
2379 register U32 i; \
2380 register U32 s = 8*(sizeof(u.c)-1); \
1109a392
MHM
2381 u.value = n; \
2382 n = 0; \
2383 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
2384 n |= ((type)(u.c[i] & 0xFF)) << s; \
2385 } \
2386 return n; \
2387 }
2388
2389/*
2390 * If we just can't do it...
2391 */
2392
2393#define NOT_AVAIL(name,type) \
2394 type \
2395 name (register type n) \
2396 { \
2397 Perl_croak_nocontext(#name "() not available"); \
2398 return n; /* not reached */ \
2399 }
2400
2401
988174c1 2402#if defined(HAS_HTOVS) && !defined(htovs)
1109a392 2403HTOLE(htovs,short)
988174c1
LW
2404#endif
2405#if defined(HAS_HTOVL) && !defined(htovl)
1109a392 2406HTOLE(htovl,long)
988174c1
LW
2407#endif
2408#if defined(HAS_VTOHS) && !defined(vtohs)
1109a392 2409LETOH(vtohs,short)
988174c1
LW
2410#endif
2411#if defined(HAS_VTOHL) && !defined(vtohl)
1109a392
MHM
2412LETOH(vtohl,long)
2413#endif
2414
2415#ifdef PERL_NEED_MY_HTOLE16
2416# if U16SIZE == 2
2417HTOLE(Perl_my_htole16,U16)
2418# else
2419NOT_AVAIL(Perl_my_htole16,U16)
2420# endif
2421#endif
2422#ifdef PERL_NEED_MY_LETOH16
2423# if U16SIZE == 2
2424LETOH(Perl_my_letoh16,U16)
2425# else
2426NOT_AVAIL(Perl_my_letoh16,U16)
2427# endif
2428#endif
2429#ifdef PERL_NEED_MY_HTOBE16
2430# if U16SIZE == 2
2431HTOBE(Perl_my_htobe16,U16)
2432# else
2433NOT_AVAIL(Perl_my_htobe16,U16)
2434# endif
2435#endif
2436#ifdef PERL_NEED_MY_BETOH16
2437# if U16SIZE == 2
2438BETOH(Perl_my_betoh16,U16)
2439# else
2440NOT_AVAIL(Perl_my_betoh16,U16)
2441# endif
2442#endif
2443
2444#ifdef PERL_NEED_MY_HTOLE32
2445# if U32SIZE == 4
2446HTOLE(Perl_my_htole32,U32)
2447# else
2448NOT_AVAIL(Perl_my_htole32,U32)
2449# endif
2450#endif
2451#ifdef PERL_NEED_MY_LETOH32
2452# if U32SIZE == 4
2453LETOH(Perl_my_letoh32,U32)
2454# else
2455NOT_AVAIL(Perl_my_letoh32,U32)
2456# endif
2457#endif
2458#ifdef PERL_NEED_MY_HTOBE32
2459# if U32SIZE == 4
2460HTOBE(Perl_my_htobe32,U32)
2461# else
2462NOT_AVAIL(Perl_my_htobe32,U32)
2463# endif
2464#endif
2465#ifdef PERL_NEED_MY_BETOH32
2466# if U32SIZE == 4
2467BETOH(Perl_my_betoh32,U32)
2468# else
2469NOT_AVAIL(Perl_my_betoh32,U32)
2470# endif
2471#endif
2472
2473#ifdef PERL_NEED_MY_HTOLE64
2474# if U64SIZE == 8
2475HTOLE(Perl_my_htole64,U64)
2476# else
2477NOT_AVAIL(Perl_my_htole64,U64)
2478# endif
2479#endif
2480#ifdef PERL_NEED_MY_LETOH64
2481# if U64SIZE == 8
2482LETOH(Perl_my_letoh64,U64)
2483# else
2484NOT_AVAIL(Perl_my_letoh64,U64)
2485# endif
2486#endif
2487#ifdef PERL_NEED_MY_HTOBE64
2488# if U64SIZE == 8
2489HTOBE(Perl_my_htobe64,U64)
2490# else
2491NOT_AVAIL(Perl_my_htobe64,U64)
2492# endif
2493#endif
2494#ifdef PERL_NEED_MY_BETOH64
2495# if U64SIZE == 8
2496BETOH(Perl_my_betoh64,U64)
2497# else
2498NOT_AVAIL(Perl_my_betoh64,U64)
2499# endif
988174c1 2500#endif
a687059c 2501
1109a392
MHM
2502#ifdef PERL_NEED_MY_HTOLES
2503HTOLE(Perl_my_htoles,short)
2504#endif
2505#ifdef PERL_NEED_MY_LETOHS
2506LETOH(Perl_my_letohs,short)
2507#endif
2508#ifdef PERL_NEED_MY_HTOBES
2509HTOBE(Perl_my_htobes,short)
2510#endif
2511#ifdef PERL_NEED_MY_BETOHS
2512BETOH(Perl_my_betohs,short)
2513#endif
2514
2515#ifdef PERL_NEED_MY_HTOLEI
2516HTOLE(Perl_my_htolei,int)
2517#endif
2518#ifdef PERL_NEED_MY_LETOHI
2519LETOH(Perl_my_letohi,int)
2520#endif
2521#ifdef PERL_NEED_MY_HTOBEI
2522HTOBE(Perl_my_htobei,int)
2523#endif
2524#ifdef PERL_NEED_MY_BETOHI
2525BETOH(Perl_my_betohi,int)
2526#endif
2527
2528#ifdef PERL_NEED_MY_HTOLEL
2529HTOLE(Perl_my_htolel,long)
2530#endif
2531#ifdef PERL_NEED_MY_LETOHL
2532LETOH(Perl_my_letohl,long)
2533#endif
2534#ifdef PERL_NEED_MY_HTOBEL
2535HTOBE(Perl_my_htobel,long)
2536#endif
2537#ifdef PERL_NEED_MY_BETOHL
2538BETOH(Perl_my_betohl,long)
2539#endif
2540
2541void
2542Perl_my_swabn(void *ptr, int n)
2543{
2544 register char *s = (char *)ptr;
2545 register char *e = s + (n-1);
2546 register char tc;
2547
7918f24d
NC
2548 PERL_ARGS_ASSERT_MY_SWABN;
2549
1109a392
MHM
2550 for (n /= 2; n > 0; s++, e--, n--) {
2551 tc = *s;
2552 *s = *e;
2553 *e = tc;
2554 }
2555}
2556
4a7d1889 2557PerlIO *
c9289b7b 2558Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
4a7d1889 2559{
e37778c2 2560#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
97aff369 2561 dVAR;
1f852d0d
NIS
2562 int p[2];
2563 register I32 This, that;
2564 register Pid_t pid;
2565 SV *sv;
2566 I32 did_pipes = 0;
2567 int pp[2];
2568
7918f24d
NC
2569 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2570
1f852d0d
NIS
2571 PERL_FLUSHALL_FOR_CHILD;
2572 This = (*mode == 'w');
2573 that = !This;
2574 if (PL_tainting) {
2575 taint_env();
2576 taint_proper("Insecure %s%s", "EXEC");
2577 }
2578 if (PerlProc_pipe(p) < 0)
4608196e 2579 return NULL;
1f852d0d
NIS
2580 /* Try for another pipe pair for error return */
2581 if (PerlProc_pipe(pp) >= 0)
2582 did_pipes = 1;
52e18b1f 2583 while ((pid = PerlProc_fork()) < 0) {
1f852d0d
NIS
2584 if (errno != EAGAIN) {
2585 PerlLIO_close(p[This]);
4e6dfe71 2586 PerlLIO_close(p[that]);
1f852d0d
NIS
2587 if (did_pipes) {
2588 PerlLIO_close(pp[0]);
2589 PerlLIO_close(pp[1]);
2590 }
4608196e 2591 return NULL;
1f852d0d 2592 }
a2a5de95 2593 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
1f852d0d
NIS
2594 sleep(5);
2595 }
2596 if (pid == 0) {
2597 /* Child */
1f852d0d
NIS
2598#undef THIS
2599#undef THAT
2600#define THIS that
2601#define THAT This
1f852d0d
NIS
2602 /* Close parent's end of error status pipe (if any) */
2603 if (did_pipes) {
2604 PerlLIO_close(pp[0]);
2605#if defined(HAS_FCNTL) && defined(F_SETFD)
2606 /* Close error pipe automatically if exec works */
2607 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2608#endif
2609 }
2610 /* Now dup our end of _the_ pipe to right position */
2611 if (p[THIS] != (*mode == 'r')) {
2612 PerlLIO_dup2(p[THIS], *mode == 'r');
2613 PerlLIO_close(p[THIS]);
4e6dfe71
GS
2614 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2615 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d 2616 }
4e6dfe71
GS
2617 else
2618 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d
NIS
2619#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2620 /* No automatic close - do it by hand */
b7953727
JH
2621# ifndef NOFILE
2622# define NOFILE 20
2623# endif
a080fe3d
NIS
2624 {
2625 int fd;
2626
2627 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
3aed30dc 2628 if (fd != pp[1])
a080fe3d
NIS
2629 PerlLIO_close(fd);
2630 }
1f852d0d
NIS
2631 }
2632#endif
a0714e2c 2633 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
1f852d0d
NIS
2634 PerlProc__exit(1);
2635#undef THIS
2636#undef THAT
2637 }
2638 /* Parent */
52e18b1f 2639 do_execfree(); /* free any memory malloced by child on fork */
1f852d0d
NIS
2640 if (did_pipes)
2641 PerlLIO_close(pp[1]);
2642 /* Keep the lower of the two fd numbers */
2643 if (p[that] < p[This]) {
2644 PerlLIO_dup2(p[This], p[that]);
2645 PerlLIO_close(p[This]);
2646 p[This] = p[that];
2647 }
4e6dfe71
GS
2648 else
2649 PerlLIO_close(p[that]); /* close child's end of pipe */
2650
1f852d0d 2651 sv = *av_fetch(PL_fdpid,p[This],TRUE);
862a34c6 2652 SvUPGRADE(sv,SVt_IV);
45977657 2653 SvIV_set(sv, pid);
1f852d0d
NIS
2654 PL_forkprocess = pid;
2655 /* If we managed to get status pipe check for exec fail */
2656 if (did_pipes && pid > 0) {
2657 int errkid;
bb7a0f54
MHM
2658 unsigned n = 0;
2659 SSize_t n1;
1f852d0d
NIS
2660
2661 while (n < sizeof(int)) {
2662 n1 = PerlLIO_read(pp[0],
2663 (void*)(((char*)&errkid)+n),
2664 (sizeof(int)) - n);
2665 if (n1 <= 0)
2666 break;
2667 n += n1;
2668 }
2669 PerlLIO_close(pp[0]);
2670 did_pipes = 0;
2671 if (n) { /* Error */
2672 int pid2, status;
8c51524e 2673 PerlLIO_close(p[This]);
1f852d0d
NIS
2674 if (n != sizeof(int))
2675 Perl_croak(aTHX_ "panic: kid popen errno read");
2676 do {
2677 pid2 = wait4pid(pid, &status, 0);
2678 } while (pid2 == -1 && errno == EINTR);
2679 errno = errkid; /* Propagate errno from kid */
4608196e 2680 return NULL;
1f852d0d
NIS
2681 }
2682 }
2683 if (did_pipes)
2684 PerlLIO_close(pp[0]);
2685 return PerlIO_fdopen(p[This], mode);
2686#else
9d419b5f 2687# ifdef OS2 /* Same, without fork()ing and all extra overhead... */
4e205ed6 2688 return my_syspopen4(aTHX_ NULL, mode, n, args);
9d419b5f 2689# else
4a7d1889
NIS
2690 Perl_croak(aTHX_ "List form of piped open not implemented");
2691 return (PerlIO *) NULL;
9d419b5f 2692# endif
1f852d0d 2693#endif
4a7d1889
NIS
2694}
2695
5f05dabc 2696 /* VMS' my_popen() is in VMS.c, same with OS/2. */
e37778c2 2697#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
760ac839 2698PerlIO *
3dd43144 2699Perl_my_popen(pTHX_ const char *cmd, const char *mode)
a687059c 2700{
97aff369 2701 dVAR;
a687059c 2702 int p[2];
8ac85365 2703 register I32 This, that;
d8a83dd3 2704 register Pid_t pid;
79072805 2705 SV *sv;
bfce84ec 2706 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
e446cec8
IZ
2707 I32 did_pipes = 0;
2708 int pp[2];
a687059c 2709
7918f24d
NC
2710 PERL_ARGS_ASSERT_MY_POPEN;
2711
45bc9206 2712 PERL_FLUSHALL_FOR_CHILD;
ddcf38b7
IZ
2713#ifdef OS2
2714 if (doexec) {
23da6c43 2715 return my_syspopen(aTHX_ cmd,mode);
ddcf38b7 2716 }
a1d180c4 2717#endif
8ac85365
NIS
2718 This = (*mode == 'w');
2719 that = !This;
3280af22 2720 if (doexec && PL_tainting) {
bbce6d69 2721 taint_env();
2722 taint_proper("Insecure %s%s", "EXEC");
d48672a2 2723 }
c2267164 2724 if (PerlProc_pipe(p) < 0)
4608196e 2725 return NULL;
e446cec8
IZ
2726 if (doexec && PerlProc_pipe(pp) >= 0)
2727 did_pipes = 1;
52e18b1f 2728 while ((pid = PerlProc_fork()) < 0) {
a687059c 2729 if (errno != EAGAIN) {
6ad3d225 2730 PerlLIO_close(p[This]);
b5ac89c3 2731 PerlLIO_close(p[that]);
e446cec8
IZ
2732 if (did_pipes) {
2733 PerlLIO_close(pp[0]);
2734 PerlLIO_close(pp[1]);
2735 }
a687059c 2736 if (!doexec)
b3647a36 2737 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
4608196e 2738 return NULL;
a687059c 2739 }
a2a5de95 2740 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
a687059c
LW
2741 sleep(5);
2742 }
2743 if (pid == 0) {
79072805 2744
30ac6d9b
GS
2745#undef THIS
2746#undef THAT
a687059c 2747#define THIS that
8ac85365 2748#define THAT This
e446cec8
IZ
2749 if (did_pipes) {
2750 PerlLIO_close(pp[0]);
2751#if defined(HAS_FCNTL) && defined(F_SETFD)
2752 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2753#endif
2754 }
a687059c 2755 if (p[THIS] != (*mode == 'r')) {
6ad3d225
GS
2756 PerlLIO_dup2(p[THIS], *mode == 'r');
2757 PerlLIO_close(p[THIS]);
b5ac89c3
NIS
2758 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2759 PerlLIO_close(p[THAT]);
a687059c 2760 }
b5ac89c3
NIS
2761 else
2762 PerlLIO_close(p[THAT]);
4435c477 2763#ifndef OS2
a687059c 2764 if (doexec) {
a0d0e21e 2765#if !defined(HAS_FCNTL) || !defined(F_SETFD)
ae986130
LW
2766#ifndef NOFILE
2767#define NOFILE 20
2768#endif
a080fe3d 2769 {
3aed30dc 2770 int fd;
a080fe3d
NIS
2771
2772 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2773 if (fd != pp[1])
3aed30dc 2774 PerlLIO_close(fd);
a080fe3d 2775 }
ae986130 2776#endif
a080fe3d
NIS
2777 /* may or may not use the shell */
2778 do_exec3(cmd, pp[1], did_pipes);
6ad3d225 2779 PerlProc__exit(1);
a687059c 2780 }
4435c477 2781#endif /* defined OS2 */
713cef20
IZ
2782
2783#ifdef PERLIO_USING_CRLF
2784 /* Since we circumvent IO layers when we manipulate low-level
2785 filedescriptors directly, need to manually switch to the
2786 default, binary, low-level mode; see PerlIOBuf_open(). */
2787 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2788#endif
4d76a344
RGS
2789#ifdef THREADS_HAVE_PIDS
2790 PL_ppid = (IV)getppid();
2791#endif
3280af22 2792 PL_forkprocess = 0;
ca0c25f6 2793#ifdef PERL_USES_PL_PIDSTATUS
3280af22 2794 hv_clear(PL_pidstatus); /* we have no children */
ca0c25f6 2795#endif
4608196e 2796 return NULL;
a687059c
LW
2797#undef THIS
2798#undef THAT
2799 }
b5ac89c3 2800 do_execfree(); /* free any memory malloced by child on vfork */
e446cec8
IZ
2801 if (did_pipes)
2802 PerlLIO_close(pp[1]);
8ac85365 2803 if (p[that] < p[This]) {
6ad3d225
GS
2804 PerlLIO_dup2(p[This], p[that]);
2805 PerlLIO_close(p[This]);
8ac85365 2806 p[This] = p[that];
62b28dd9 2807 }
b5ac89c3
NIS
2808 else
2809 PerlLIO_close(p[that]);
2810
3280af22 2811 sv = *av_fetch(PL_fdpid,p[This],TRUE);
862a34c6 2812 SvUPGRADE(sv,SVt_IV);
45977657 2813 SvIV_set(sv, pid);
3280af22 2814 PL_forkprocess = pid;
e446cec8
IZ
2815 if (did_pipes && pid > 0) {
2816 int errkid;
bb7a0f54
MHM
2817 unsigned n = 0;
2818 SSize_t n1;
e446cec8
IZ
2819
2820 while (n < sizeof(int)) {
2821 n1 = PerlLIO_read(pp[0],
2822 (void*)(((char*)&errkid)+n),
2823 (sizeof(int)) - n);
2824 if (n1 <= 0)
2825 break;
2826 n += n1;
2827 }
2f96c702
IZ
2828 PerlLIO_close(pp[0]);
2829 did_pipes = 0;
e446cec8 2830 if (n) { /* Error */
faa466a7 2831 int pid2, status;
8c51524e 2832 PerlLIO_close(p[This]);
e446cec8 2833 if (n != sizeof(int))
cea2e8a9 2834 Perl_croak(aTHX_ "panic: kid popen errno read");
faa466a7
RG
2835 do {
2836 pid2 = wait4pid(pid, &status, 0);
2837 } while (pid2 == -1 && errno == EINTR);
e446cec8 2838 errno = errkid; /* Propagate errno from kid */
4608196e 2839 return NULL;
e446cec8
IZ
2840 }
2841 }
2842 if (did_pipes)
2843 PerlLIO_close(pp[0]);
8ac85365 2844 return PerlIO_fdopen(p[This], mode);
a687059c 2845}
7c0587c8 2846#else
85ca448a 2847#if defined(atarist) || defined(EPOC)
7c0587c8 2848FILE *popen();
760ac839 2849PerlIO *
cef6ea9d 2850Perl_my_popen(pTHX_ const char *cmd, const char *mode)
7c0587c8 2851{
7918f24d 2852 PERL_ARGS_ASSERT_MY_POPEN;
45bc9206 2853 PERL_FLUSHALL_FOR_CHILD;
a1d180c4
NIS
2854 /* Call system's popen() to get a FILE *, then import it.
2855 used 0 for 2nd parameter to PerlIO_importFILE;
2856 apparently not used
2857 */
2858 return PerlIO_importFILE(popen(cmd, mode), 0);
7c0587c8 2859}
2b96b0a5
JH
2860#else
2861#if defined(DJGPP)
2862FILE *djgpp_popen();
2863PerlIO *
cef6ea9d 2864Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2b96b0a5
JH
2865{
2866 PERL_FLUSHALL_FOR_CHILD;
2867 /* Call system's popen() to get a FILE *, then import it.
2868 used 0 for 2nd parameter to PerlIO_importFILE;
2869 apparently not used
2870 */
2871 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2872}
9c12f1e5
RGS
2873#else
2874#if defined(__LIBCATAMOUNT__)
2875PerlIO *
2876Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2877{
2878 return NULL;
2879}
2880#endif
2b96b0a5 2881#endif
7c0587c8
LW
2882#endif
2883
2884#endif /* !DOSISH */
a687059c 2885
52e18b1f
GS
2886/* this is called in parent before the fork() */
2887void
2888Perl_atfork_lock(void)
2889{
27da23d5 2890 dVAR;
3db8f154 2891#if defined(USE_ITHREADS)
52e18b1f
GS
2892 /* locks must be held in locking order (if any) */
2893# ifdef MYMALLOC
2894 MUTEX_LOCK(&PL_malloc_mutex);
2895# endif
2896 OP_REFCNT_LOCK;
2897#endif
2898}
2899
2900/* this is called in both parent and child after the fork() */
2901void
2902Perl_atfork_unlock(void)
2903{
27da23d5 2904 dVAR;
3db8f154 2905#if defined(USE_ITHREADS)
52e18b1f
GS
2906 /* locks must be released in same order as in atfork_lock() */
2907# ifdef MYMALLOC
2908 MUTEX_UNLOCK(&PL_malloc_mutex);
2909# endif
2910 OP_REFCNT_UNLOCK;
2911#endif
2912}
2913
2914Pid_t
2915Perl_my_fork(void)
2916{
2917#if defined(HAS_FORK)
2918 Pid_t pid;
3db8f154 2919#if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
52e18b1f
GS
2920 atfork_lock();
2921 pid = fork();
2922 atfork_unlock();
2923#else
2924 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2925 * handlers elsewhere in the code */
2926 pid = fork();
2927#endif
2928 return pid;
2929#else
2930 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2931 Perl_croak_nocontext("fork() not available");
b961a566 2932 return 0;
52e18b1f
GS
2933#endif /* HAS_FORK */
2934}
2935
748a9306 2936#ifdef DUMP_FDS
35ff7856 2937void
c9289b7b 2938Perl_dump_fds(pTHX_ const char *const s)
ae986130
LW
2939{
2940 int fd;
c623ac67 2941 Stat_t tmpstatbuf;
ae986130 2942
7918f24d
NC
2943 PERL_ARGS_ASSERT_DUMP_FDS;
2944
bf49b057 2945 PerlIO_printf(Perl_debug_log,"%s", s);
ae986130 2946 for (fd = 0; fd < 32; fd++) {
6ad3d225 2947 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
bf49b057 2948 PerlIO_printf(Perl_debug_log," %d",fd);
ae986130 2949 }
bf49b057 2950 PerlIO_printf(Perl_debug_log,"\n");
27da23d5 2951 return;
ae986130 2952}
35ff7856 2953#endif /* DUMP_FDS */
ae986130 2954
fe14fcc3 2955#ifndef HAS_DUP2
fec02dd3 2956int
ba106d47 2957dup2(int oldfd, int newfd)
a687059c 2958{
a0d0e21e 2959#if defined(HAS_FCNTL) && defined(F_DUPFD)
fec02dd3
AD
2960 if (oldfd == newfd)
2961 return oldfd;
6ad3d225 2962 PerlLIO_close(newfd);
fec02dd3 2963 return fcntl(oldfd, F_DUPFD, newfd);
62b28dd9 2964#else
fc36a67e 2965#define DUP2_MAX_FDS 256
2966 int fdtmp[DUP2_MAX_FDS];
79072805 2967 I32 fdx = 0;
ae986130
LW
2968 int fd;
2969
fe14fcc3 2970 if (oldfd == newfd)
fec02dd3 2971 return oldfd;
6ad3d225 2972 PerlLIO_close(newfd);
fc36a67e 2973 /* good enough for low fd's... */
6ad3d225 2974 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
fc36a67e 2975 if (fdx >= DUP2_MAX_FDS) {
6ad3d225 2976 PerlLIO_close(fd);
fc36a67e 2977 fd = -1;
2978 break;
2979 }
ae986130 2980 fdtmp[fdx++] = fd;
fc36a67e 2981 }
ae986130 2982 while (fdx > 0)
6ad3d225 2983 PerlLIO_close(fdtmp[--fdx]);
fec02dd3 2984 return fd;
62b28dd9 2985#endif
a687059c
LW
2986}
2987#endif
2988
64ca3a65 2989#ifndef PERL_MICRO
ff68c719 2990#ifdef HAS_SIGACTION
2991
2992Sighandler_t
864dbfa3 2993Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 2994{
27da23d5 2995 dVAR;
ff68c719 2996 struct sigaction act, oact;
2997
a10b1e10
JH
2998#ifdef USE_ITHREADS
2999 /* only "parent" interpreter can diddle signals */
3000 if (PL_curinterp != aTHX)
8aad04aa 3001 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
3002#endif
3003
8aad04aa 3004 act.sa_handler = (void(*)(int))handler;
ff68c719 3005 sigemptyset(&act.sa_mask);
3006 act.sa_flags = 0;
3007#ifdef SA_RESTART
4ffa73a3
JH
3008 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3009 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 3010#endif
358837b8 3011#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 3012 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
3013 act.sa_flags |= SA_NOCLDWAIT;
3014#endif
ff68c719 3015 if (sigaction(signo, &act, &oact) == -1)
8aad04aa 3016 return (Sighandler_t) SIG_ERR;
ff68c719 3017 else
8aad04aa 3018 return (Sighandler_t) oact.sa_handler;
ff68c719 3019}
3020
3021Sighandler_t
864dbfa3 3022Perl_rsignal_state(pTHX_ int signo)
ff68c719 3023{
3024 struct sigaction oact;
96a5add6 3025 PERL_UNUSED_CONTEXT;
ff68c719 3026
3027 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
8aad04aa 3028 return (Sighandler_t) SIG_ERR;
ff68c719 3029 else
8aad04aa 3030 return (Sighandler_t) oact.sa_handler;
ff68c719 3031}
3032
3033int
864dbfa3 3034Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 3035{
27da23d5 3036 dVAR;
ff68c719 3037 struct sigaction act;
3038
7918f24d
NC
3039 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
3040
a10b1e10
JH
3041#ifdef USE_ITHREADS
3042 /* only "parent" interpreter can diddle signals */
3043 if (PL_curinterp != aTHX)
3044 return -1;
3045#endif
3046
8aad04aa 3047 act.sa_handler = (void(*)(int))handler;
ff68c719 3048 sigemptyset(&act.sa_mask);
3049 act.sa_flags = 0;
3050#ifdef SA_RESTART
4ffa73a3
JH
3051 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3052 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 3053#endif
36b5d377 3054#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 3055 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
3056 act.sa_flags |= SA_NOCLDWAIT;
3057#endif
ff68c719 3058 return sigaction(signo, &act, save);
3059}
3060
3061int
864dbfa3 3062Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 3063{
27da23d5 3064 dVAR;
a10b1e10
JH
3065#ifdef USE_ITHREADS
3066 /* only "parent" interpreter can diddle signals */
3067 if (PL_curinterp != aTHX)
3068 return -1;
3069#endif
3070
ff68c719 3071 return sigaction(signo, save, (struct sigaction *)NULL);
3072}
3073
3074#else /* !HAS_SIGACTION */
3075
3076Sighandler_t
864dbfa3 3077Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 3078{
39f1703b 3079#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3080 /* only "parent" interpreter can diddle signals */
3081 if (PL_curinterp != aTHX)
8aad04aa 3082 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
3083#endif
3084
6ad3d225 3085 return PerlProc_signal(signo, handler);
ff68c719 3086}
3087
fabdb6c0 3088static Signal_t
4e35701f 3089sig_trap(int signo)
ff68c719 3090{
27da23d5
JH
3091 dVAR;
3092 PL_sig_trapped++;
ff68c719 3093}
3094
3095Sighandler_t
864dbfa3 3096Perl_rsignal_state(pTHX_ int signo)
ff68c719 3097{
27da23d5 3098 dVAR;
ff68c719 3099 Sighandler_t oldsig;
3100
39f1703b 3101#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3102 /* only "parent" interpreter can diddle signals */
3103 if (PL_curinterp != aTHX)
8aad04aa 3104 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
3105#endif
3106
27da23d5 3107 PL_sig_trapped = 0;
6ad3d225
GS
3108 oldsig = PerlProc_signal(signo, sig_trap);
3109 PerlProc_signal(signo, oldsig);
27da23d5 3110 if (PL_sig_trapped)
3aed30dc 3111 PerlProc_kill(PerlProc_getpid(), signo);
ff68c719 3112 return oldsig;
3113}
3114
3115int
864dbfa3 3116Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 3117{
39f1703b 3118#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3119 /* only "parent" interpreter can diddle signals */
3120 if (PL_curinterp != aTHX)
3121 return -1;
3122#endif
6ad3d225 3123 *save = PerlProc_signal(signo, handler);
8aad04aa 3124 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719 3125}
3126
3127int
864dbfa3 3128Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 3129{
39f1703b 3130#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
3131 /* only "parent" interpreter can diddle signals */
3132 if (PL_curinterp != aTHX)
3133 return -1;
3134#endif
8aad04aa 3135 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719 3136}
3137
3138#endif /* !HAS_SIGACTION */
64ca3a65 3139#endif /* !PERL_MICRO */
ff68c719 3140
5f05dabc 3141 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
e37778c2 3142#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(__LIBCATAMOUNT__)
79072805 3143I32
864dbfa3 3144Perl_my_pclose(pTHX_ PerlIO *ptr)
a687059c 3145{
97aff369 3146 dVAR;
ff68c719 3147 Sigsave_t hstat, istat, qstat;
a687059c 3148 int status;
a0d0e21e 3149 SV **svp;
d8a83dd3 3150 Pid_t pid;
2e0cfa16 3151 Pid_t pid2 = 0;
03136e13 3152 bool close_failed;
4ee39169 3153 dSAVEDERRNO;
2e0cfa16
FC
3154 const int fd = PerlIO_fileno(ptr);
3155
b6ae43b7 3156#ifdef USE_PERLIO
2e0cfa16
FC
3157 /* Find out whether the refcount is low enough for us to wait for the
3158 child proc without blocking. */
3159 const bool should_wait = PerlIOUnix_refcnt(fd) == 1;
b6ae43b7
NC
3160#else
3161 const bool should_wait = 1;
3162#endif
a687059c 3163
2e0cfa16 3164 svp = av_fetch(PL_fdpid,fd,TRUE);
25d92023 3165 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
a0d0e21e 3166 SvREFCNT_dec(*svp);
3280af22 3167 *svp = &PL_sv_undef;
ddcf38b7
IZ
3168#ifdef OS2
3169 if (pid == -1) { /* Opened by popen. */
3170 return my_syspclose(ptr);
3171 }
a1d180c4 3172#endif
f1618b10
CS
3173 close_failed = (PerlIO_close(ptr) == EOF);
3174 SAVE_ERRNO;
7c0587c8 3175#ifdef UTS
6ad3d225 3176 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
7c0587c8 3177#endif
64ca3a65 3178#ifndef PERL_MICRO
8aad04aa
JH
3179 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
3180 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
3181 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
64ca3a65 3182#endif
2e0cfa16 3183 if (should_wait) do {
1d3434b8
GS
3184 pid2 = wait4pid(pid, &status, 0);
3185 } while (pid2 == -1 && errno == EINTR);
64ca3a65 3186#ifndef PERL_MICRO
ff68c719 3187 rsignal_restore(SIGHUP, &hstat);
3188 rsignal_restore(SIGINT, &istat);
3189 rsignal_restore(SIGQUIT, &qstat);
64ca3a65 3190#endif
03136e13 3191 if (close_failed) {
4ee39169 3192 RESTORE_ERRNO;
03136e13
CS
3193 return -1;
3194 }
2e0cfa16
FC
3195 return(
3196 should_wait
3197 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3198 : 0
3199 );
20188a90 3200}
9c12f1e5
RGS
3201#else
3202#if defined(__LIBCATAMOUNT__)
3203I32
3204Perl_my_pclose(pTHX_ PerlIO *ptr)
3205{
3206 return -1;
3207}
3208#endif
4633a7c4
LW
3209#endif /* !DOSISH */
3210
e37778c2 3211#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
79072805 3212I32
d8a83dd3 3213Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
20188a90 3214{
97aff369 3215 dVAR;
27da23d5 3216 I32 result = 0;
7918f24d 3217 PERL_ARGS_ASSERT_WAIT4PID;
b7953727
JH
3218 if (!pid)
3219 return -1;
ca0c25f6 3220#ifdef PERL_USES_PL_PIDSTATUS
b7953727 3221 {
3aed30dc 3222 if (pid > 0) {
12072db5
NC
3223 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3224 pid, rather than a string form. */
c4420975 3225 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3aed30dc
HS
3226 if (svp && *svp != &PL_sv_undef) {
3227 *statusp = SvIVX(*svp);
12072db5
NC
3228 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3229 G_DISCARD);
3aed30dc
HS
3230 return pid;
3231 }
3232 }
3233 else {
3234 HE *entry;
3235
3236 hv_iterinit(PL_pidstatus);
3237 if ((entry = hv_iternext(PL_pidstatus))) {
c4420975 3238 SV * const sv = hv_iterval(PL_pidstatus,entry);
7ea75b61 3239 I32 len;
0bcc34c2 3240 const char * const spid = hv_iterkey(entry,&len);
27da23d5 3241
12072db5
NC
3242 assert (len == sizeof(Pid_t));
3243 memcpy((char *)&pid, spid, len);
3aed30dc 3244 *statusp = SvIVX(sv);
7b9a3241
NC
3245 /* The hash iterator is currently on this entry, so simply
3246 calling hv_delete would trigger the lazy delete, which on
3247 aggregate does more work, beacuse next call to hv_iterinit()
3248 would spot the flag, and have to call the delete routine,
3249 while in the meantime any new entries can't re-use that
3250 memory. */
3251 hv_iterinit(PL_pidstatus);
7ea75b61 3252 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3aed30dc
HS
3253 return pid;
3254 }
20188a90
LW
3255 }
3256 }
68a29c53 3257#endif
79072805 3258#ifdef HAS_WAITPID
367f3c24
IZ
3259# ifdef HAS_WAITPID_RUNTIME
3260 if (!HAS_WAITPID_RUNTIME)
3261 goto hard_way;
3262# endif
cddd4526 3263 result = PerlProc_waitpid(pid,statusp,flags);
dfcfdb64 3264 goto finish;
367f3c24
IZ
3265#endif
3266#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
4608196e 3267 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
dfcfdb64 3268 goto finish;
367f3c24 3269#endif
ca0c25f6 3270#ifdef PERL_USES_PL_PIDSTATUS
27da23d5 3271#if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
367f3c24 3272 hard_way:
27da23d5 3273#endif
a0d0e21e 3274 {
a0d0e21e 3275 if (flags)
cea2e8a9 3276 Perl_croak(aTHX_ "Can't do waitpid with flags");
a0d0e21e 3277 else {
76e3520e 3278 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
a0d0e21e
LW
3279 pidgone(result,*statusp);
3280 if (result < 0)
3281 *statusp = -1;
3282 }
a687059c
LW
3283 }
3284#endif
27da23d5 3285#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
dfcfdb64 3286 finish:
27da23d5 3287#endif
cddd4526
NIS
3288 if (result < 0 && errno == EINTR) {
3289 PERL_ASYNC_CHECK();
48dbb59e 3290 errno = EINTR; /* reset in case a signal handler changed $! */
cddd4526
NIS
3291 }
3292 return result;
a687059c 3293}
2986a63f 3294#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
a687059c 3295
ca0c25f6 3296#ifdef PERL_USES_PL_PIDSTATUS
7c0587c8 3297void
ed4173ef 3298S_pidgone(pTHX_ Pid_t pid, int status)
a687059c 3299{
79072805 3300 register SV *sv;
a687059c 3301
12072db5 3302 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
862a34c6 3303 SvUPGRADE(sv,SVt_IV);
45977657 3304 SvIV_set(sv, status);
20188a90 3305 return;
a687059c 3306}
ca0c25f6 3307#endif
a687059c 3308
85ca448a 3309#if defined(atarist) || defined(OS2) || defined(EPOC)
7c0587c8 3310int pclose();
ddcf38b7
IZ
3311#ifdef HAS_FORK
3312int /* Cannot prototype with I32
3313 in os2ish.h. */
ba106d47 3314my_syspclose(PerlIO *ptr)
ddcf38b7 3315#else
79072805 3316I32
864dbfa3 3317Perl_my_pclose(pTHX_ PerlIO *ptr)
a1d180c4 3318#endif
a687059c 3319{
760ac839 3320 /* Needs work for PerlIO ! */
c4420975 3321 FILE * const f = PerlIO_findFILE(ptr);
7452cf6a 3322 const I32 result = pclose(f);
2b96b0a5
JH
3323 PerlIO_releaseFILE(ptr,f);
3324 return result;
3325}
3326#endif
3327
933fea7f 3328#if defined(DJGPP)
2b96b0a5
JH
3329int djgpp_pclose();
3330I32
3331Perl_my_pclose(pTHX_ PerlIO *ptr)
3332{
3333 /* Needs work for PerlIO ! */
c4420975 3334 FILE * const f = PerlIO_findFILE(ptr);
2b96b0a5 3335 I32 result = djgpp_pclose(f);
933fea7f 3336 result = (result << 8) & 0xff00;
760ac839
LW
3337 PerlIO_releaseFILE(ptr,f);
3338 return result;
a687059c 3339}
7c0587c8 3340#endif
9f68db38 3341
16fa5c11 3342#define PERL_REPEATCPY_LINEAR 4
9f68db38 3343void
16fa5c11 3344Perl_repeatcpy(register char *to, register const char *from, I32 len, register I32 count)
9f68db38 3345{
7918f24d
NC
3346 PERL_ARGS_ASSERT_REPEATCPY;
3347
16fa5c11
VP
3348 if (len == 1)
3349 memset(to, *from, count);
3350 else if (count) {
3351 register char *p = to;
3352 I32 items, linear, half;
3353
3354 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3355 for (items = 0; items < linear; ++items) {
3356 register const char *q = from;
3357 I32 todo;
3358 for (todo = len; todo > 0; todo--)
3359 *p++ = *q++;
3360 }
3361
3362 half = count / 2;
3363 while (items <= half) {
3364 I32 size = items * len;
3365 memcpy(p, to, size);
3366 p += size;
3367 items *= 2;
9f68db38 3368 }
16fa5c11
VP
3369
3370 if (count > items)
3371 memcpy(p, to, (count - items) * len);
9f68db38
LW
3372 }
3373}
0f85fab0 3374
fe14fcc3 3375#ifndef HAS_RENAME
79072805 3376I32
4373e329 3377Perl_same_dirent(pTHX_ const char *a, const char *b)
62b28dd9 3378{
93a17b20
LW
3379 char *fa = strrchr(a,'/');
3380 char *fb = strrchr(b,'/');
c623ac67
GS
3381 Stat_t tmpstatbuf1;
3382 Stat_t tmpstatbuf2;
c4420975 3383 SV * const tmpsv = sv_newmortal();
62b28dd9 3384
7918f24d
NC
3385 PERL_ARGS_ASSERT_SAME_DIRENT;
3386
62b28dd9
LW
3387 if (fa)
3388 fa++;
3389 else
3390 fa = a;
3391 if (fb)
3392 fb++;
3393 else
3394 fb = b;
3395 if (strNE(a,b))
3396 return FALSE;
3397 if (fa == a)
76f68e9b 3398 sv_setpvs(tmpsv, ".");
62b28dd9 3399 else
46fc3d4c 3400 sv_setpvn(tmpsv, a, fa - a);
95a20fc0 3401 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
62b28dd9
LW
3402 return FALSE;
3403 if (fb == b)
76f68e9b 3404 sv_setpvs(tmpsv, ".");
62b28dd9 3405 else
46fc3d4c 3406 sv_setpvn(tmpsv, b, fb - b);
95a20fc0 3407 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
62b28dd9
LW
3408 return FALSE;
3409 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3410 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3411}
fe14fcc3
LW
3412#endif /* !HAS_RENAME */
3413
491527d0 3414char*
7f315aed
NC
3415Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3416 const char *const *const search_ext, I32 flags)
491527d0 3417{
97aff369 3418 dVAR;
bd61b366
SS
3419 const char *xfound = NULL;
3420 char *xfailed = NULL;
0f31cffe 3421 char tmpbuf[MAXPATHLEN];
491527d0 3422 register char *s;
5f74f29c 3423 I32 len = 0;
491527d0 3424 int retval;
39a02377 3425 char *bufend;
491527d0
GS
3426#if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3427# define SEARCH_EXTS ".bat", ".cmd", NULL
3428# define MAX_EXT_LEN 4
3429#endif
3430#ifdef OS2
3431# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3432# define MAX_EXT_LEN 4
3433#endif
3434#ifdef VMS
3435# define SEARCH_EXTS ".pl", ".com", NULL
3436# define MAX_EXT_LEN 4
3437#endif
3438 /* additional extensions to try in each dir if scriptname not found */
3439#ifdef SEARCH_EXTS
0bcc34c2 3440 static const char *const exts[] = { SEARCH_EXTS };
7f315aed 3441 const char *const *const ext = search_ext ? search_ext : exts;
491527d0 3442 int extidx = 0, i = 0;
bd61b366 3443 const char *curext = NULL;
491527d0 3444#else
53c1dcc0 3445 PERL_UNUSED_ARG(search_ext);
491527d0
GS
3446# define MAX_EXT_LEN 0
3447#endif
3448
7918f24d
NC
3449 PERL_ARGS_ASSERT_FIND_SCRIPT;
3450
491527d0
GS
3451 /*
3452 * If dosearch is true and if scriptname does not contain path
3453 * delimiters, search the PATH for scriptname.
3454 *
3455 * If SEARCH_EXTS is also defined, will look for each
3456 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3457 * while searching the PATH.
3458 *
3459 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3460 * proceeds as follows:
3461 * If DOSISH or VMSISH:
3462 * + look for ./scriptname{,.foo,.bar}
3463 * + search the PATH for scriptname{,.foo,.bar}
3464 *
3465 * If !DOSISH:
3466 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3467 * this will not look in '.' if it's not in the PATH)
3468 */
84486fc6 3469 tmpbuf[0] = '\0';
491527d0
GS
3470
3471#ifdef VMS
3472# ifdef ALWAYS_DEFTYPES
3473 len = strlen(scriptname);
3474 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
c4420975 3475 int idx = 0, deftypes = 1;
491527d0
GS
3476 bool seen_dot = 1;
3477
bd61b366 3478 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
3479# else
3480 if (dosearch) {
c4420975 3481 int idx = 0, deftypes = 1;
491527d0
GS
3482 bool seen_dot = 1;
3483
bd61b366 3484 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
3485# endif
3486 /* The first time through, just add SEARCH_EXTS to whatever we
3487 * already have, so we can check for default file types. */
3488 while (deftypes ||
84486fc6 3489 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
491527d0
GS
3490 {
3491 if (deftypes) {
3492 deftypes = 0;
84486fc6 3493 *tmpbuf = '\0';
491527d0 3494 }
84486fc6
GS
3495 if ((strlen(tmpbuf) + strlen(scriptname)
3496 + MAX_EXT_LEN) >= sizeof tmpbuf)
491527d0 3497 continue; /* don't search dir with too-long name */
6fca0082 3498 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
491527d0
GS
3499#else /* !VMS */
3500
3501#ifdef DOSISH
3502 if (strEQ(scriptname, "-"))
3503 dosearch = 0;
3504 if (dosearch) { /* Look in '.' first. */
fe2774ed 3505 const char *cur = scriptname;
491527d0
GS
3506#ifdef SEARCH_EXTS
3507 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3508 while (ext[i])
3509 if (strEQ(ext[i++],curext)) {
3510 extidx = -1; /* already has an ext */
3511 break;
3512 }
3513 do {
3514#endif
3515 DEBUG_p(PerlIO_printf(Perl_debug_log,
3516 "Looking for %s\n",cur));
017f25f1
IZ
3517 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3518 && !S_ISDIR(PL_statbuf.st_mode)) {
491527d0
GS
3519 dosearch = 0;
3520 scriptname = cur;
3521#ifdef SEARCH_EXTS
3522 break;
3523#endif
3524 }
3525#ifdef SEARCH_EXTS
3526 if (cur == scriptname) {
3527 len = strlen(scriptname);
84486fc6 3528 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
491527d0 3529 break;
9e4425f7
SH
3530 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3531 cur = tmpbuf;
491527d0
GS
3532 }
3533 } while (extidx >= 0 && ext[extidx] /* try an extension? */
6fca0082 3534 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
491527d0
GS
3535#endif
3536 }
3537#endif
3538
3539 if (dosearch && !strchr(scriptname, '/')
3540#ifdef DOSISH
3541 && !strchr(scriptname, '\\')
3542#endif
cd39f2b6 3543 && (s = PerlEnv_getenv("PATH")))
cd39f2b6 3544 {
491527d0 3545 bool seen_dot = 0;
92f0c265 3546
39a02377
DM
3547 bufend = s + strlen(s);
3548 while (s < bufend) {
491527d0
GS
3549#if defined(atarist) || defined(DOSISH)
3550 for (len = 0; *s
3551# ifdef atarist
3552 && *s != ','
3553# endif
3554 && *s != ';'; len++, s++) {
84486fc6
GS
3555 if (len < sizeof tmpbuf)
3556 tmpbuf[len] = *s;
491527d0 3557 }
84486fc6
GS
3558 if (len < sizeof tmpbuf)
3559 tmpbuf[len] = '\0';
491527d0 3560#else /* ! (atarist || DOSISH) */
39a02377 3561 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
491527d0
GS
3562 ':',
3563 &len);
3564#endif /* ! (atarist || DOSISH) */
39a02377 3565 if (s < bufend)
491527d0 3566 s++;
84486fc6 3567 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
491527d0
GS
3568 continue; /* don't search dir with too-long name */
3569 if (len
cd86ed9d 3570# if defined(atarist) || defined(DOSISH)
84486fc6
GS
3571 && tmpbuf[len - 1] != '/'
3572 && tmpbuf[len - 1] != '\\'
490a0e98 3573# endif
491527d0 3574 )
84486fc6
GS
3575 tmpbuf[len++] = '/';
3576 if (len == 2 && tmpbuf[0] == '.')
491527d0 3577 seen_dot = 1;
28f0d0ec 3578 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
491527d0
GS
3579#endif /* !VMS */
3580
3581#ifdef SEARCH_EXTS
84486fc6 3582 len = strlen(tmpbuf);
491527d0
GS
3583 if (extidx > 0) /* reset after previous loop */
3584 extidx = 0;
3585 do {
3586#endif
84486fc6 3587 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3280af22 3588 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
017f25f1
IZ
3589 if (S_ISDIR(PL_statbuf.st_mode)) {
3590 retval = -1;
3591 }
491527d0
GS
3592#ifdef SEARCH_EXTS
3593 } while ( retval < 0 /* not there */
3594 && extidx>=0 && ext[extidx] /* try an extension? */
6fca0082 3595 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
491527d0
GS
3596 );
3597#endif
3598 if (retval < 0)
3599 continue;
3280af22
NIS
3600 if (S_ISREG(PL_statbuf.st_mode)
3601 && cando(S_IRUSR,TRUE,&PL_statbuf)
e37778c2 3602#if !defined(DOSISH)
3280af22 3603 && cando(S_IXUSR,TRUE,&PL_statbuf)
491527d0
GS
3604#endif
3605 )
3606 {
3aed30dc 3607 xfound = tmpbuf; /* bingo! */
491527d0
GS
3608 break;
3609 }
3610 if (!xfailed)
84486fc6 3611 xfailed = savepv(tmpbuf);
491527d0
GS
3612 }
3613#ifndef DOSISH
017f25f1 3614 if (!xfound && !seen_dot && !xfailed &&
a1d180c4 3615 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
017f25f1 3616 || S_ISDIR(PL_statbuf.st_mode)))
491527d0
GS
3617#endif
3618 seen_dot = 1; /* Disable message. */
9ccb31f9
GS
3619 if (!xfound) {
3620 if (flags & 1) { /* do or die? */
3aed30dc 3621 Perl_croak(aTHX_ "Can't %s %s%s%s",
9ccb31f9
GS
3622 (xfailed ? "execute" : "find"),
3623 (xfailed ? xfailed : scriptname),
3624 (xfailed ? "" : " on PATH"),
3625 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3626 }
bd61b366 3627 scriptname = NULL;
9ccb31f9 3628 }
43c5f42d 3629 Safefree(xfailed);
491527d0
GS
3630 scriptname = xfound;
3631 }
bd61b366 3632 return (scriptname ? savepv(scriptname) : NULL);
491527d0
GS
3633}
3634
ba869deb
GS
3635#ifndef PERL_GET_CONTEXT_DEFINED
3636
3637void *
3638Perl_get_context(void)
3639{
27da23d5 3640 dVAR;
3db8f154 3641#if defined(USE_ITHREADS)
ba869deb
GS
3642# ifdef OLD_PTHREADS_API
3643 pthread_addr_t t;
3644 if (pthread_getspecific(PL_thr_key, &t))
3645 Perl_croak_nocontext("panic: pthread_getspecific");
3646 return (void*)t;
3647# else
bce813aa 3648# ifdef I_MACH_CTHREADS
8b8b35ab 3649 return (void*)cthread_data(cthread_self());
bce813aa 3650# else
8b8b35ab
JH
3651 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3652# endif
c44d3fdb 3653# endif
ba869deb
GS
3654#else
3655 return (void*)NULL;
3656#endif
3657}
3658
3659void
3660Perl_set_context(void *t)
3661{
8772537c 3662 dVAR;
7918f24d 3663 PERL_ARGS_ASSERT_SET_CONTEXT;
3db8f154 3664#if defined(USE_ITHREADS)
c44d3fdb
GS
3665# ifdef I_MACH_CTHREADS
3666 cthread_set_data(cthread_self(), t);
3667# else
ba869deb
GS
3668 if (pthread_setspecific(PL_thr_key, t))
3669 Perl_croak_nocontext("panic: pthread_setspecific");
c44d3fdb 3670# endif
b464bac0 3671#else
8772537c 3672 PERL_UNUSED_ARG(t);
ba869deb
GS
3673#endif
3674}
3675
3676#endif /* !PERL_GET_CONTEXT_DEFINED */
491527d0 3677
27da23d5 3678#if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
22239a37 3679struct perl_vars *
864dbfa3 3680Perl_GetVars(pTHX)
22239a37 3681{
533c011a 3682 return &PL_Vars;
22239a37 3683}
31fb1209
NIS
3684#endif
3685
1cb0ed9b 3686char **
864dbfa3 3687Perl_get_op_names(pTHX)
31fb1209 3688{
96a5add6
AL
3689 PERL_UNUSED_CONTEXT;
3690 return (char **)PL_op_name;
31fb1209
NIS
3691}
3692
1cb0ed9b 3693char **
864dbfa3 3694Perl_get_op_descs(pTHX)
31fb1209 3695{
96a5add6
AL
3696 PERL_UNUSED_CONTEXT;
3697 return (char **)PL_op_desc;
31fb1209 3698}
9e6b2b00 3699
e1ec3a88 3700const char *
864dbfa3 3701Perl_get_no_modify(pTHX)
9e6b2b00 3702{
96a5add6
AL
3703 PERL_UNUSED_CONTEXT;
3704 return PL_no_modify;
9e6b2b00
GS
3705}
3706
3707U32 *
864dbfa3 3708Perl_get_opargs(pTHX)
9e6b2b00 3709{
96a5add6
AL
3710 PERL_UNUSED_CONTEXT;
3711 return (U32 *)PL_opargs;
9e6b2b00 3712}
51aa15f3 3713
0cb96387
GS
3714PPADDR_t*
3715Perl_get_ppaddr(pTHX)
3716{
96a5add6
AL
3717 dVAR;
3718 PERL_UNUSED_CONTEXT;
3719 return (PPADDR_t*)PL_ppaddr;
0cb96387
GS
3720}
3721
a6c40364
GS
3722#ifndef HAS_GETENV_LEN
3723char *
bf4acbe4 3724Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
a6c40364 3725{
8772537c 3726 char * const env_trans = PerlEnv_getenv(env_elem);
96a5add6 3727 PERL_UNUSED_CONTEXT;
7918f24d 3728 PERL_ARGS_ASSERT_GETENV_LEN;
a6c40364
GS
3729 if (env_trans)
3730 *len = strlen(env_trans);
3731 return env_trans;
f675dbe5
CB
3732}
3733#endif
3734
dc9e4912
GS
3735
3736MGVTBL*
864dbfa3 3737Perl_get_vtbl(pTHX_ int vtbl_id)
dc9e4912 3738{
96a5add6 3739 PERL_UNUSED_CONTEXT;
dc9e4912 3740
c7fdacb9
NC
3741 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3742 ? NULL : PL_magic_vtables + vtbl_id;
dc9e4912
GS
3743}
3744
767df6a1 3745I32
864dbfa3 3746Perl_my_fflush_all(pTHX)
767df6a1 3747{
f800e14d 3748#if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
ce720889 3749 return PerlIO_flush(NULL);
767df6a1 3750#else
8fbdfb7c 3751# if defined(HAS__FWALK)
f13a2bc0 3752 extern int fflush(FILE *);
74cac757
JH
3753 /* undocumented, unprototyped, but very useful BSDism */
3754 extern void _fwalk(int (*)(FILE *));
8fbdfb7c 3755 _fwalk(&fflush);
74cac757 3756 return 0;
8fa7f367 3757# else
8fbdfb7c 3758# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
8fa7f367 3759 long open_max = -1;
8fbdfb7c 3760# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
d2201af2 3761 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
8fbdfb7c 3762# else
8fa7f367 3763# if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
767df6a1 3764 open_max = sysconf(_SC_OPEN_MAX);
8fa7f367
JH
3765# else
3766# ifdef FOPEN_MAX
74cac757 3767 open_max = FOPEN_MAX;
8fa7f367
JH
3768# else
3769# ifdef OPEN_MAX
74cac757 3770 open_max = OPEN_MAX;
8fa7f367
JH
3771# else
3772# ifdef _NFILE
d2201af2 3773 open_max = _NFILE;
8fa7f367
JH
3774# endif
3775# endif
74cac757 3776# endif
767df6a1
JH
3777# endif
3778# endif
767df6a1
JH
3779 if (open_max > 0) {
3780 long i;
3781 for (i = 0; i < open_max; i++)
d2201af2
AD
3782 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3783 STDIO_STREAM_ARRAY[i]._file < open_max &&
3784 STDIO_STREAM_ARRAY[i]._flag)
3785 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
767df6a1
JH
3786 return 0;
3787 }
8fbdfb7c 3788# endif
93189314 3789 SETERRNO(EBADF,RMS_IFI);
767df6a1 3790 return EOF;
74cac757 3791# endif
767df6a1
JH
3792#endif
3793}
097ee67d 3794
69282e91 3795void
45219de6 3796Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
a5390457
NC
3797{
3798 if (ckWARN(WARN_IO)) {
3799 const char * const name
3800 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3801 const char * const direction = have == '>' ? "out" : "in";
3802
3803 if (name && *name)
3804 Perl_warner(aTHX_ packWARN(WARN_IO),
3805 "Filehandle %s opened only for %sput",
3806 name, direction);
3807 else
3808 Perl_warner(aTHX_ packWARN(WARN_IO),
3809 "Filehandle opened only for %sput", direction);
3810 }
3811}
3812
3813void
831e4cc3 3814Perl_report_evil_fh(pTHX_ const GV *gv)
bc37a18f 3815{
65820a28 3816 const IO *io = gv ? GvIO(gv) : NULL;
831e4cc3 3817 const PERL_BITFIELD16 op = PL_op->op_type;
a5390457
NC
3818 const char *vile;
3819 I32 warn_type;
3820
65820a28 3821 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
a5390457
NC
3822 vile = "closed";
3823 warn_type = WARN_CLOSED;
2dd78f96
JH
3824 }
3825 else {
a5390457
NC
3826 vile = "unopened";
3827 warn_type = WARN_UNOPENED;
3828 }
3829
3830 if (ckWARN(warn_type)) {
3831 const char * const name
3832 = gv && (isGV(gv) || isGV_with_GP(gv)) ? GvENAME(gv) : NULL;
3833 const char * const pars =
3834 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3835 const char * const func =
3836 (const char *)
3837 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3838 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
a5390457
NC
3839 PL_op_desc[op]);
3840 const char * const type =
3841 (const char *)
65820a28 3842 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
a5390457
NC
3843 ? "socket" : "filehandle");
3844 if (name && *name) {
3845 Perl_warner(aTHX_ packWARN(warn_type),
3846 "%s%s on %s %s %s", func, pars, vile, type, name);
3847 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3848 Perl_warner(
3849 aTHX_ packWARN(warn_type),
3850 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3851 func, pars, name
3852 );
3aed30dc
HS
3853 }
3854 else {
a5390457
NC
3855 Perl_warner(aTHX_ packWARN(warn_type),
3856 "%s%s on %s %s", func, pars, vile, type);
65820a28 3857 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
a5390457
NC
3858 Perl_warner(
3859 aTHX_ packWARN(warn_type),
3860 "\t(Are you trying to call %s%s on dirhandle?)\n",
3861 func, pars
3862 );
3aed30dc 3863 }
bc37a18f 3864 }
69282e91 3865}
a926ef6b 3866
f6adc668 3867/* To workaround core dumps from the uninitialised tm_zone we get the
e72cf795
JH
3868 * system to give us a reasonable struct to copy. This fix means that
3869 * strftime uses the tm_zone and tm_gmtoff values returned by
3870 * localtime(time()). That should give the desired result most of the
3871 * time. But probably not always!
3872 *
f6adc668
JH
3873 * This does not address tzname aspects of NETaa14816.
3874 *
e72cf795 3875 */
f6adc668 3876
e72cf795
JH
3877#ifdef HAS_GNULIBC
3878# ifndef STRUCT_TM_HASZONE
3879# define STRUCT_TM_HASZONE
3880# endif
3881#endif
3882
f6adc668
JH
3883#ifdef STRUCT_TM_HASZONE /* Backward compat */
3884# ifndef HAS_TM_TM_ZONE
3885# define HAS_TM_TM_ZONE
3886# endif
3887#endif
3888
e72cf795 3889void
f1208910 3890Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
e72cf795 3891{
f6adc668 3892#ifdef HAS_TM_TM_ZONE
e72cf795 3893 Time_t now;
1b6737cc 3894 const struct tm* my_tm;
7918f24d 3895 PERL_ARGS_ASSERT_INIT_TM;
e72cf795 3896 (void)time(&now);
82c57498 3897 my_tm = localtime(&now);
ca46b8ee
SP
3898 if (my_tm)
3899 Copy(my_tm, ptm, 1, struct tm);
1b6737cc 3900#else
7918f24d 3901 PERL_ARGS_ASSERT_INIT_TM;
1b6737cc 3902 PERL_UNUSED_ARG(ptm);
e72cf795
JH
3903#endif
3904}
3905
3906/*
3907 * mini_mktime - normalise struct tm values without the localtime()
3908 * semantics (and overhead) of mktime().
3909 */
3910void
f1208910 3911Perl_mini_mktime(pTHX_ struct tm *ptm)
e72cf795
JH
3912{
3913 int yearday;
3914 int secs;
3915 int month, mday, year, jday;
3916 int odd_cent, odd_year;
96a5add6 3917 PERL_UNUSED_CONTEXT;
e72cf795 3918
7918f24d
NC
3919 PERL_ARGS_ASSERT_MINI_MKTIME;
3920
e72cf795
JH
3921#define DAYS_PER_YEAR 365
3922#define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3923#define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3924#define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3925#define SECS_PER_HOUR (60*60)
3926#define SECS_PER_DAY (24*SECS_PER_HOUR)
3927/* parentheses deliberately absent on these two, otherwise they don't work */
3928#define MONTH_TO_DAYS 153/5
3929#define DAYS_TO_MONTH 5/153
3930/* offset to bias by March (month 4) 1st between month/mday & year finding */
3931#define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3932/* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3933#define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3934
3935/*
3936 * Year/day algorithm notes:
3937 *
3938 * With a suitable offset for numeric value of the month, one can find
3939 * an offset into the year by considering months to have 30.6 (153/5) days,
3940 * using integer arithmetic (i.e., with truncation). To avoid too much
3941 * messing about with leap days, we consider January and February to be
3942 * the 13th and 14th month of the previous year. After that transformation,
3943 * we need the month index we use to be high by 1 from 'normal human' usage,
3944 * so the month index values we use run from 4 through 15.
3945 *
3946 * Given that, and the rules for the Gregorian calendar (leap years are those
3947 * divisible by 4 unless also divisible by 100, when they must be divisible
3948 * by 400 instead), we can simply calculate the number of days since some
3949 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3950 * the days we derive from our month index, and adding in the day of the
3951 * month. The value used here is not adjusted for the actual origin which
3952 * it normally would use (1 January A.D. 1), since we're not exposing it.
3953 * We're only building the value so we can turn around and get the
3954 * normalised values for the year, month, day-of-month, and day-of-year.
3955 *
3956 * For going backward, we need to bias the value we're using so that we find
3957 * the right year value. (Basically, we don't want the contribution of
3958 * March 1st to the number to apply while deriving the year). Having done
3959 * that, we 'count up' the contribution to the year number by accounting for
3960 * full quadracenturies (400-year periods) with their extra leap days, plus
3961 * the contribution from full centuries (to avoid counting in the lost leap
3962 * days), plus the contribution from full quad-years (to count in the normal
3963 * leap days), plus the leftover contribution from any non-leap years.
3964 * At this point, if we were working with an actual leap day, we'll have 0
3965 * days left over. This is also true for March 1st, however. So, we have
3966 * to special-case that result, and (earlier) keep track of the 'odd'
3967 * century and year contributions. If we got 4 extra centuries in a qcent,
3968 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3969 * Otherwise, we add back in the earlier bias we removed (the 123 from
3970 * figuring in March 1st), find the month index (integer division by 30.6),
3971 * and the remainder is the day-of-month. We then have to convert back to
3972 * 'real' months (including fixing January and February from being 14/15 in
3973 * the previous year to being in the proper year). After that, to get
3974 * tm_yday, we work with the normalised year and get a new yearday value for
3975 * January 1st, which we subtract from the yearday value we had earlier,
3976 * representing the date we've re-built. This is done from January 1
3977 * because tm_yday is 0-origin.
3978 *
3979 * Since POSIX time routines are only guaranteed to work for times since the
3980 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3981 * applies Gregorian calendar rules even to dates before the 16th century
3982 * doesn't bother me. Besides, you'd need cultural context for a given
3983 * date to know whether it was Julian or Gregorian calendar, and that's
3984 * outside the scope for this routine. Since we convert back based on the
3985 * same rules we used to build the yearday, you'll only get strange results
3986 * for input which needed normalising, or for the 'odd' century years which
486ec47a 3987 * were leap years in the Julian calendar but not in the Gregorian one.
e72cf795
JH
3988 * I can live with that.
3989 *
3990 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3991 * that's still outside the scope for POSIX time manipulation, so I don't
3992 * care.
3993 */
3994
3995 year = 1900 + ptm->tm_year;
3996 month = ptm->tm_mon;
3997 mday = ptm->tm_mday;
3998 /* allow given yday with no month & mday to dominate the result */
3999 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
4000 month = 0;
4001 mday = 0;
4002 jday = 1 + ptm->tm_yday;
4003 }
4004 else {
4005 jday = 0;
4006 }
4007 if (month >= 2)
4008 month+=2;
4009 else
4010 month+=14, year--;
4011 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
4012 yearday += month*MONTH_TO_DAYS + mday + jday;
4013 /*
4014 * Note that we don't know when leap-seconds were or will be,
4015 * so we have to trust the user if we get something which looks
4016 * like a sensible leap-second. Wild values for seconds will
4017 * be rationalised, however.
4018 */
4019 if ((unsigned) ptm->tm_sec <= 60) {
4020 secs = 0;
4021 }
4022 else {
4023 secs = ptm->tm_sec;
4024 ptm->tm_sec = 0;
4025 }
4026 secs += 60 * ptm->tm_min;
4027 secs += SECS_PER_HOUR * ptm->tm_hour;
4028 if (secs < 0) {
4029 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
4030 /* got negative remainder, but need positive time */
4031 /* back off an extra day to compensate */
4032 yearday += (secs/SECS_PER_DAY)-1;
4033 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
4034 }
4035 else {
4036 yearday += (secs/SECS_PER_DAY);
4037 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
4038 }
4039 }
4040 else if (secs >= SECS_PER_DAY) {
4041 yearday += (secs/SECS_PER_DAY);
4042 secs %= SECS_PER_DAY;
4043 }
4044 ptm->tm_hour = secs/SECS_PER_HOUR;
4045 secs %= SECS_PER_HOUR;
4046 ptm->tm_min = secs/60;
4047 secs %= 60;
4048 ptm->tm_sec += secs;
4049 /* done with time of day effects */
4050 /*
4051 * The algorithm for yearday has (so far) left it high by 428.
4052 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
4053 * bias it by 123 while trying to figure out what year it
4054 * really represents. Even with this tweak, the reverse
4055 * translation fails for years before A.D. 0001.
4056 * It would still fail for Feb 29, but we catch that one below.
4057 */
4058 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
4059 yearday -= YEAR_ADJUST;
4060 year = (yearday / DAYS_PER_QCENT) * 400;
4061 yearday %= DAYS_PER_QCENT;
4062 odd_cent = yearday / DAYS_PER_CENT;
4063 year += odd_cent * 100;
4064 yearday %= DAYS_PER_CENT;
4065 year += (yearday / DAYS_PER_QYEAR) * 4;
4066 yearday %= DAYS_PER_QYEAR;
4067 odd_year = yearday / DAYS_PER_YEAR;
4068 year += odd_year;
4069 yearday %= DAYS_PER_YEAR;
4070 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
4071 month = 1;
4072 yearday = 29;
4073 }
4074 else {
4075 yearday += YEAR_ADJUST; /* recover March 1st crock */
4076 month = yearday*DAYS_TO_MONTH;
4077 yearday -= month*MONTH_TO_DAYS;
4078 /* recover other leap-year adjustment */
4079 if (month > 13) {
4080 month-=14;
4081 year++;
4082 }
4083 else {
4084 month-=2;
4085 }
4086 }
4087 ptm->tm_year = year - 1900;
4088 if (yearday) {
4089 ptm->tm_mday = yearday;
4090 ptm->tm_mon = month;
4091 }
4092 else {
4093 ptm->tm_mday = 31;
4094 ptm->tm_mon = month - 1;
4095 }
4096 /* re-build yearday based on Jan 1 to get tm_yday */
4097 year--;
4098 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
4099 yearday += 14*MONTH_TO_DAYS + 1;
4100 ptm->tm_yday = jday - yearday;
4101 /* fix tm_wday if not overridden by caller */
4102 if ((unsigned)ptm->tm_wday > 6)
4103 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
4104}
b3c85772
JH
4105
4106char *
e1ec3a88 4107Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
b3c85772
JH
4108{
4109#ifdef HAS_STRFTIME
4110 char *buf;
4111 int buflen;
4112 struct tm mytm;
4113 int len;
4114
7918f24d
NC
4115 PERL_ARGS_ASSERT_MY_STRFTIME;
4116
b3c85772
JH
4117 init_tm(&mytm); /* XXX workaround - see init_tm() above */
4118 mytm.tm_sec = sec;
4119 mytm.tm_min = min;
4120 mytm.tm_hour = hour;
4121 mytm.tm_mday = mday;
4122 mytm.tm_mon = mon;
4123 mytm.tm_year = year;
4124 mytm.tm_wday = wday;
4125 mytm.tm_yday = yday;
4126 mytm.tm_isdst = isdst;
4127 mini_mktime(&mytm);
c473feec
SR
4128 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
4129#if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
4130 STMT_START {
4131 struct tm mytm2;
4132 mytm2 = mytm;
4133 mktime(&mytm2);
4134#ifdef HAS_TM_TM_GMTOFF
4135 mytm.tm_gmtoff = mytm2.tm_gmtoff;
4136#endif
4137#ifdef HAS_TM_TM_ZONE
4138 mytm.tm_zone = mytm2.tm_zone;
4139#endif
4140 } STMT_END;
4141#endif
b3c85772 4142 buflen = 64;
a02a5408 4143 Newx(buf, buflen, char);
b3c85772
JH
4144 len = strftime(buf, buflen, fmt, &mytm);
4145 /*
877f6a72 4146 ** The following is needed to handle to the situation where
b3c85772
JH
4147 ** tmpbuf overflows. Basically we want to allocate a buffer
4148 ** and try repeatedly. The reason why it is so complicated
4149 ** is that getting a return value of 0 from strftime can indicate
4150 ** one of the following:
4151 ** 1. buffer overflowed,
4152 ** 2. illegal conversion specifier, or
4153 ** 3. the format string specifies nothing to be returned(not
4154 ** an error). This could be because format is an empty string
4155 ** or it specifies %p that yields an empty string in some locale.
4156 ** If there is a better way to make it portable, go ahead by
4157 ** all means.
4158 */
4159 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
4160 return buf;
4161 else {
4162 /* Possibly buf overflowed - try again with a bigger buf */
e1ec3a88 4163 const int fmtlen = strlen(fmt);
7743c307 4164 int bufsize = fmtlen + buflen;
877f6a72 4165
c4bc4aaa 4166 Renew(buf, bufsize, char);
b3c85772
JH
4167 while (buf) {
4168 buflen = strftime(buf, bufsize, fmt, &mytm);
4169 if (buflen > 0 && buflen < bufsize)
4170 break;
4171 /* heuristic to prevent out-of-memory errors */
4172 if (bufsize > 100*fmtlen) {
4173 Safefree(buf);
4174 buf = NULL;
4175 break;
4176 }
7743c307
SH
4177 bufsize *= 2;
4178 Renew(buf, bufsize, char);
b3c85772
JH
4179 }
4180 return buf;
4181 }
4182#else
4183 Perl_croak(aTHX_ "panic: no strftime");
27da23d5 4184 return NULL;
b3c85772
JH
4185#endif
4186}
4187
877f6a72
NIS
4188
4189#define SV_CWD_RETURN_UNDEF \
4190sv_setsv(sv, &PL_sv_undef); \
4191return FALSE
4192
4193#define SV_CWD_ISDOT(dp) \
4194 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3aed30dc 4195 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
877f6a72
NIS
4196
4197/*
ccfc67b7
JH
4198=head1 Miscellaneous Functions
4199
89423764 4200=for apidoc getcwd_sv
877f6a72
NIS
4201
4202Fill the sv with current working directory
4203
4204=cut
4205*/
4206
4207/* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4208 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4209 * getcwd(3) if available
4210 * Comments from the orignal:
4211 * This is a faster version of getcwd. It's also more dangerous
4212 * because you might chdir out of a directory that you can't chdir
4213 * back into. */
4214
877f6a72 4215int
89423764 4216Perl_getcwd_sv(pTHX_ register SV *sv)
877f6a72
NIS
4217{
4218#ifndef PERL_MICRO
97aff369 4219 dVAR;
ea715489
JH
4220#ifndef INCOMPLETE_TAINTS
4221 SvTAINTED_on(sv);
4222#endif
4223
7918f24d
NC
4224 PERL_ARGS_ASSERT_GETCWD_SV;
4225
8f95b30d
JH
4226#ifdef HAS_GETCWD
4227 {
60e110a8
DM
4228 char buf[MAXPATHLEN];
4229
3aed30dc 4230 /* Some getcwd()s automatically allocate a buffer of the given
60e110a8
DM
4231 * size from the heap if they are given a NULL buffer pointer.
4232 * The problem is that this behaviour is not portable. */
3aed30dc 4233 if (getcwd(buf, sizeof(buf) - 1)) {
42d9b98d 4234 sv_setpv(sv, buf);
3aed30dc
HS
4235 return TRUE;
4236 }
4237 else {
4238 sv_setsv(sv, &PL_sv_undef);
4239 return FALSE;
4240 }
8f95b30d
JH
4241 }
4242
4243#else
4244
c623ac67 4245 Stat_t statbuf;
877f6a72 4246 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4373e329 4247 int pathlen=0;
877f6a72 4248 Direntry_t *dp;
877f6a72 4249
862a34c6 4250 SvUPGRADE(sv, SVt_PV);
877f6a72 4251
877f6a72 4252 if (PerlLIO_lstat(".", &statbuf) < 0) {
3aed30dc 4253 SV_CWD_RETURN_UNDEF;
877f6a72
NIS
4254 }
4255
4256 orig_cdev = statbuf.st_dev;
4257 orig_cino = statbuf.st_ino;
4258 cdev = orig_cdev;
4259 cino = orig_cino;
4260
4261 for (;;) {
4373e329 4262 DIR *dir;
f56ed502 4263 int namelen;
3aed30dc
HS
4264 odev = cdev;
4265 oino = cino;
4266
4267 if (PerlDir_chdir("..") < 0) {
4268 SV_CWD_RETURN_UNDEF;
4269 }
4270 if (PerlLIO_stat(".", &statbuf) < 0) {
4271 SV_CWD_RETURN_UNDEF;
4272 }
4273
4274 cdev = statbuf.st_dev;
4275 cino = statbuf.st_ino;
4276
4277 if (odev == cdev && oino == cino) {
4278 break;
4279 }
4280 if (!(dir = PerlDir_open("."))) {
4281 SV_CWD_RETURN_UNDEF;
4282 }
4283
4284 while ((dp = PerlDir_read(dir)) != NULL) {
877f6a72 4285#ifdef DIRNAMLEN
f56ed502 4286 namelen = dp->d_namlen;
877f6a72 4287#else
f56ed502 4288 namelen = strlen(dp->d_name);
877f6a72 4289#endif
3aed30dc
HS
4290 /* skip . and .. */
4291 if (SV_CWD_ISDOT(dp)) {
4292 continue;
4293 }
4294
4295 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4296 SV_CWD_RETURN_UNDEF;
4297 }
4298
4299 tdev = statbuf.st_dev;
4300 tino = statbuf.st_ino;
4301 if (tino == oino && tdev == odev) {
4302 break;
4303 }
cb5953d6
JH
4304 }
4305
3aed30dc
HS
4306 if (!dp) {
4307 SV_CWD_RETURN_UNDEF;
4308 }
4309
4310 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4311 SV_CWD_RETURN_UNDEF;
4312 }
877f6a72 4313
3aed30dc
HS
4314 SvGROW(sv, pathlen + namelen + 1);
4315
4316 if (pathlen) {
4317 /* shift down */
95a20fc0 4318 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3aed30dc 4319 }
877f6a72 4320
3aed30dc
HS
4321 /* prepend current directory to the front */
4322 *SvPVX(sv) = '/';
4323 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4324 pathlen += (namelen + 1);
877f6a72
NIS
4325
4326#ifdef VOID_CLOSEDIR
3aed30dc 4327 PerlDir_close(dir);
877f6a72 4328#else
3aed30dc
HS
4329 if (PerlDir_close(dir) < 0) {
4330 SV_CWD_RETURN_UNDEF;
4331 }
877f6a72
NIS
4332#endif
4333 }
4334
60e110a8 4335 if (pathlen) {
3aed30dc
HS
4336 SvCUR_set(sv, pathlen);
4337 *SvEND(sv) = '\0';
4338 SvPOK_only(sv);
877f6a72 4339
95a20fc0 4340 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3aed30dc
HS
4341 SV_CWD_RETURN_UNDEF;
4342 }
877f6a72
NIS
4343 }
4344 if (PerlLIO_stat(".", &statbuf) < 0) {
3aed30dc 4345 SV_CWD_RETURN_UNDEF;
877f6a72
NIS
4346 }
4347
4348 cdev = statbuf.st_dev;
4349 cino = statbuf.st_ino;
4350
4351 if (cdev != orig_cdev || cino != orig_cino) {
3aed30dc
HS
4352 Perl_croak(aTHX_ "Unstable directory path, "
4353 "current directory changed unexpectedly");
877f6a72 4354 }
877f6a72
NIS
4355
4356 return TRUE;
793b8d8e
JH
4357#endif
4358
877f6a72
NIS
4359#else
4360 return FALSE;
4361#endif
4362}
4363
c812d146 4364#define VERSION_MAX 0x7FFFFFFF
91152fc1 4365
22f16304
RU
4366/*
4367=for apidoc prescan_version
4368
d54f8cf7
JP
4369Validate that a given string can be parsed as a version object, but doesn't
4370actually perform the parsing. Can use either strict or lax validation rules.
4371Can optionally set a number of hint variables to save the parsing code
4372some time when tokenizing.
4373
22f16304
RU
4374=cut
4375*/
91152fc1
DG
4376const char *
4377Perl_prescan_version(pTHX_ const char *s, bool strict,
4378 const char **errstr,
4379 bool *sqv, int *ssaw_decimal, int *swidth, bool *salpha) {
4380 bool qv = (sqv ? *sqv : FALSE);
4381 int width = 3;
4382 int saw_decimal = 0;
4383 bool alpha = FALSE;
4384 const char *d = s;
4385
4386 PERL_ARGS_ASSERT_PRESCAN_VERSION;
4387
4388 if (qv && isDIGIT(*d))
4389 goto dotted_decimal_version;
4390
4391 if (*d == 'v') { /* explicit v-string */
4392 d++;
4393 if (isDIGIT(*d)) {
4394 qv = TRUE;
4395 }
4396 else { /* degenerate v-string */
4397 /* requires v1.2.3 */
4398 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4399 }
4400
4401dotted_decimal_version:
4402 if (strict && d[0] == '0' && isDIGIT(d[1])) {
4403 /* no leading zeros allowed */
4404 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4405 }
4406
4407 while (isDIGIT(*d)) /* integer part */
4408 d++;
4409
4410 if (*d == '.')
4411 {
4412 saw_decimal++;
4413 d++; /* decimal point */
4414 }
4415 else
4416 {
4417 if (strict) {
4418 /* require v1.2.3 */
4419 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4420 }
4421 else {
4422 goto version_prescan_finish;
4423 }
4424 }
4425
4426 {
4427 int i = 0;
4428 int j = 0;
4429 while (isDIGIT(*d)) { /* just keep reading */
4430 i++;
4431 while (isDIGIT(*d)) {
4432 d++; j++;
4433 /* maximum 3 digits between decimal */
4434 if (strict && j > 3) {
4435 BADVERSION(s,errstr,"Invalid version format (maximum 3 digits between decimals)");
4436 }
4437 }
4438 if (*d == '_') {
4439 if (strict) {
4440 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4441 }
4442 if ( alpha ) {
4443 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4444 }
4445 d++;
4446 alpha = TRUE;
4447 }
4448 else if (*d == '.') {
4449 if (alpha) {
4450 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4451 }
4452 saw_decimal++;
4453 d++;
4454 }
4455 else if (!isDIGIT(*d)) {
4456 break;
4457 }
4458 j = 0;
4459 }
4460
4461 if (strict && i < 2) {
4462 /* requires v1.2.3 */
4463 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions require at least three parts)");
4464 }
4465 }
4466 } /* end if dotted-decimal */
4467 else
4468 { /* decimal versions */
4469 /* special strict case for leading '.' or '0' */
4470 if (strict) {
4471 if (*d == '.') {
4472 BADVERSION(s,errstr,"Invalid version format (0 before decimal required)");
4473 }
4474 if (*d == '0' && isDIGIT(d[1])) {
4475 BADVERSION(s,errstr,"Invalid version format (no leading zeros)");
4476 }
4477 }
4478
4479 /* consume all of the integer part */
4480 while (isDIGIT(*d))
4481 d++;
4482
4483 /* look for a fractional part */
4484 if (*d == '.') {
4485 /* we found it, so consume it */
4486 saw_decimal++;
4487 d++;
4488 }
4e4da3ac 4489 else if (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') {
91152fc1
DG
4490 if ( d == s ) {
4491 /* found nothing */
4492 BADVERSION(s,errstr,"Invalid version format (version required)");
4493 }
4494 /* found just an integer */
4495 goto version_prescan_finish;
4496 }
4497 else if ( d == s ) {
4498 /* didn't find either integer or period */
4499 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4500 }
4501 else if (*d == '_') {
4502 /* underscore can't come after integer part */
4503 if (strict) {
4504 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4505 }
4506 else if (isDIGIT(d[1])) {
4507 BADVERSION(s,errstr,"Invalid version format (alpha without decimal)");
4508 }
4509 else {
4510 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4511 }
4512 }
4513 else {
4514 /* anything else after integer part is just invalid data */
4515 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4516 }
4517
4518 /* scan the fractional part after the decimal point*/
4519
4e4da3ac 4520 if (!isDIGIT(*d) && (strict || ! (!*d || *d == ';' || isSPACE(*d) || *d == '{' || *d == '}') )) {
91152fc1
DG
4521 /* strict or lax-but-not-the-end */
4522 BADVERSION(s,errstr,"Invalid version format (fractional part required)");
4523 }
4524
4525 while (isDIGIT(*d)) {
4526 d++;
4527 if (*d == '.' && isDIGIT(d[-1])) {
4528 if (alpha) {
4529 BADVERSION(s,errstr,"Invalid version format (underscores before decimal)");
4530 }
4531 if (strict) {
4532 BADVERSION(s,errstr,"Invalid version format (dotted-decimal versions must begin with 'v')");
4533 }
4534 d = (char *)s; /* start all over again */
4535 qv = TRUE;
4536 goto dotted_decimal_version;
4537 }
4538 if (*d == '_') {
4539 if (strict) {
4540 BADVERSION(s,errstr,"Invalid version format (no underscores)");
4541 }
4542 if ( alpha ) {
4543 BADVERSION(s,errstr,"Invalid version format (multiple underscores)");
4544 }
4545 if ( ! isDIGIT(d[1]) ) {
4546 BADVERSION(s,errstr,"Invalid version format (misplaced underscore)");
4547 }
4548 d++;
4549 alpha = TRUE;
4550 }
4551 }
4552 }
4553
4554version_prescan_finish:
4555 while (isSPACE(*d))
4556 d++;
4557
4e4da3ac 4558 if (!isDIGIT(*d) && (! (!*d || *d == ';' || *d == '{' || *d == '}') )) {
91152fc1
DG
4559 /* trailing non-numeric data */
4560 BADVERSION(s,errstr,"Invalid version format (non-numeric data)");
4561 }
4562
4563 if (sqv)
4564 *sqv = qv;
4565 if (swidth)
4566 *swidth = width;
4567 if (ssaw_decimal)
4568 *ssaw_decimal = saw_decimal;
4569 if (salpha)
4570 *salpha = alpha;
4571 return d;
4572}
4573
f4758303 4574/*
b0f01acb
JP
4575=for apidoc scan_version
4576
4577Returns a pointer to the next character after the parsed
4578version string, as well as upgrading the passed in SV to
4579an RV.
4580
4581Function must be called with an already existing SV like
4582
137d6fc0 4583 sv = newSV(0);
abc25d8c 4584 s = scan_version(s, SV *sv, bool qv);
b0f01acb
JP
4585
4586Performs some preprocessing to the string to ensure that
4587it has the correct characteristics of a version. Flags the
4588object if it contains an underscore (which denotes this
abc25d8c 4589is an alpha version). The boolean qv denotes that the version
137d6fc0
JP
4590should be interpreted as if it had multiple decimals, even if
4591it doesn't.
b0f01acb
JP
4592
4593=cut
4594*/
4595
9137345a 4596const char *
e1ec3a88 4597Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
b0f01acb 4598{
e0218a61 4599 const char *start;
9137345a
JP
4600 const char *pos;
4601 const char *last;
91152fc1
DG
4602 const char *errstr = NULL;
4603 int saw_decimal = 0;
9137345a 4604 int width = 3;
91152fc1 4605 bool alpha = FALSE;
c812d146 4606 bool vinf = FALSE;
7452cf6a
AL
4607 AV * const av = newAV();
4608 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
7918f24d
NC
4609
4610 PERL_ARGS_ASSERT_SCAN_VERSION;
4611
9137345a 4612 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
cb5772bb 4613
91152fc1
DG
4614#ifndef NODEFAULT_SHAREKEYS
4615 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4616#endif
4617
e0218a61
JP
4618 while (isSPACE(*s)) /* leading whitespace is OK */
4619 s++;
4620
91152fc1
DG
4621 last = prescan_version(s, FALSE, &errstr, &qv, &saw_decimal, &width, &alpha);
4622 if (errstr) {
4623 /* "undef" is a special case and not an error */
4624 if ( ! ( *s == 'u' && strEQ(s,"undef")) ) {
4625 Perl_croak(aTHX_ "%s", errstr);
46314c13 4626 }
ad63d80f 4627 }
ad63d80f 4628
91152fc1
DG
4629 start = s;
4630 if (*s == 'v')
4631 s++;
9137345a
JP
4632 pos = s;
4633
4634 if ( qv )
ef8f7699 4635 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(qv));
cb5772bb 4636 if ( alpha )
ef8f7699 4637 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(alpha));
9137345a 4638 if ( !qv && width < 3 )
ef8f7699 4639 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
9137345a 4640
ad63d80f 4641 while (isDIGIT(*pos))
46314c13 4642 pos++;
ad63d80f
JP
4643 if (!isALPHA(*pos)) {
4644 I32 rev;
4645
ad63d80f
JP
4646 for (;;) {
4647 rev = 0;
4648 {
129318bd 4649 /* this is atoi() that delimits on underscores */
9137345a 4650 const char *end = pos;
129318bd 4651 I32 mult = 1;
c812d146 4652 I32 orev;
9137345a 4653
129318bd
JP
4654 /* the following if() will only be true after the decimal
4655 * point of a version originally created with a bare
4656 * floating point number, i.e. not quoted in any way
4657 */
91152fc1 4658 if ( !qv && s > start && saw_decimal == 1 ) {
c76df65e 4659 mult *= 100;
129318bd 4660 while ( s < end ) {
c812d146 4661 orev = rev;
129318bd
JP
4662 rev += (*s - '0') * mult;
4663 mult /= 10;
c812d146
JP
4664 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4665 || (PERL_ABS(rev) > VERSION_MAX )) {
a2a5de95
NC
4666 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4667 "Integer overflow in version %d",VERSION_MAX);
c812d146
JP
4668 s = end - 1;
4669 rev = VERSION_MAX;
4670 vinf = 1;
4671 }
129318bd 4672 s++;
9137345a
JP
4673 if ( *s == '_' )
4674 s++;
129318bd
JP
4675 }
4676 }
4677 else {
4678 while (--end >= s) {
c812d146 4679 orev = rev;
129318bd
JP
4680 rev += (*end - '0') * mult;
4681 mult *= 10;
c812d146
JP
4682 if ( (PERL_ABS(orev) > PERL_ABS(rev))
4683 || (PERL_ABS(rev) > VERSION_MAX )) {
a2a5de95
NC
4684 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4685 "Integer overflow in version");
c812d146
JP
4686 end = s - 1;
4687 rev = VERSION_MAX;
4688 vinf = 1;
4689 }
129318bd
JP
4690 }
4691 }
4692 }
9137345a 4693
129318bd 4694 /* Append revision */
9137345a 4695 av_push(av, newSViv(rev));
c812d146
JP
4696 if ( vinf ) {
4697 s = last;
4698 break;
4699 }
4700 else if ( *pos == '.' )
9137345a
JP
4701 s = ++pos;
4702 else if ( *pos == '_' && isDIGIT(pos[1]) )
ad63d80f 4703 s = ++pos;
f941e658
JP
4704 else if ( *pos == ',' && isDIGIT(pos[1]) )
4705 s = ++pos;
ad63d80f
JP
4706 else if ( isDIGIT(*pos) )
4707 s = pos;
b0f01acb 4708 else {
ad63d80f
JP
4709 s = pos;
4710 break;
4711 }
9137345a
JP
4712 if ( qv ) {
4713 while ( isDIGIT(*pos) )
4714 pos++;
4715 }
4716 else {
4717 int digits = 0;
4718 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4719 if ( *pos != '_' )
4720 digits++;
4721 pos++;
4722 }
b0f01acb
JP
4723 }
4724 }
4725 }
9137345a
JP
4726 if ( qv ) { /* quoted versions always get at least three terms*/
4727 I32 len = av_len(av);
4edfc503
NC
4728 /* This for loop appears to trigger a compiler bug on OS X, as it
4729 loops infinitely. Yes, len is negative. No, it makes no sense.
4730 Compiler in question is:
4731 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4732 for ( len = 2 - len; len > 0; len-- )
502c6561 4733 av_push(MUTABLE_AV(sv), newSViv(0));
4edfc503
NC
4734 */
4735 len = 2 - len;
4736 while (len-- > 0)
9137345a 4737 av_push(av, newSViv(0));
b9381830 4738 }
9137345a 4739
8cb289bd 4740 /* need to save off the current version string for later */
c812d146
JP
4741 if ( vinf ) {
4742 SV * orig = newSVpvn("v.Inf", sizeof("v.Inf")-1);
ef8f7699
NC
4743 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
4744 (void)hv_stores(MUTABLE_HV(hv), "vinf", newSViv(1));
c812d146
JP
4745 }
4746 else if ( s > start ) {
8cb289bd 4747 SV * orig = newSVpvn(start,s-start);
91152fc1 4748 if ( qv && saw_decimal == 1 && *start != 'v' ) {
8cb289bd
RGS
4749 /* need to insert a v to be consistent */
4750 sv_insert(orig, 0, 0, "v", 1);
4751 }
ef8f7699 4752 (void)hv_stores(MUTABLE_HV(hv), "original", orig);
8cb289bd
RGS
4753 }
4754 else {
76f68e9b 4755 (void)hv_stores(MUTABLE_HV(hv), "original", newSVpvs("0"));
9137345a 4756 av_push(av, newSViv(0));
8cb289bd
RGS
4757 }
4758
4759 /* And finally, store the AV in the hash */
daba3364 4760 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
9137345a 4761
92dcf8ce
JP
4762 /* fix RT#19517 - special case 'undef' as string */
4763 if ( *s == 'u' && strEQ(s,"undef") ) {
4764 s += 5;
4765 }
4766
9137345a 4767 return s;
b0f01acb
JP
4768}
4769
4770/*
4771=for apidoc new_version
4772
4773Returns a new version object based on the passed in SV:
4774
4775 SV *sv = new_version(SV *ver);
4776
4777Does not alter the passed in ver SV. See "upg_version" if you
4778want to upgrade the SV.
4779
4780=cut
4781*/
4782
4783SV *
4784Perl_new_version(pTHX_ SV *ver)
4785{
97aff369 4786 dVAR;
2d03de9c 4787 SV * const rv = newSV(0);
7918f24d 4788 PERL_ARGS_ASSERT_NEW_VERSION;
d7aa5382
JP
4789 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4790 {
4791 I32 key;
53c1dcc0 4792 AV * const av = newAV();
9137345a
JP
4793 AV *sav;
4794 /* This will get reblessed later if a derived class*/
e0218a61 4795 SV * const hv = newSVrv(rv, "version");
9137345a 4796 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
91152fc1
DG
4797#ifndef NODEFAULT_SHAREKEYS
4798 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4799#endif
9137345a
JP
4800
4801 if ( SvROK(ver) )
4802 ver = SvRV(ver);
4803
4804 /* Begin copying all of the elements */
ef8f7699
NC
4805 if ( hv_exists(MUTABLE_HV(ver), "qv", 2) )
4806 (void)hv_stores(MUTABLE_HV(hv), "qv", newSViv(1));
9137345a 4807
ef8f7699
NC
4808 if ( hv_exists(MUTABLE_HV(ver), "alpha", 5) )
4809 (void)hv_stores(MUTABLE_HV(hv), "alpha", newSViv(1));
9137345a 4810
ef8f7699 4811 if ( hv_exists(MUTABLE_HV(ver), "width", 5 ) )
d7aa5382 4812 {
ef8f7699
NC
4813 const I32 width = SvIV(*hv_fetchs(MUTABLE_HV(ver), "width", FALSE));
4814 (void)hv_stores(MUTABLE_HV(hv), "width", newSViv(width));
d7aa5382 4815 }
9137345a 4816
ef8f7699 4817 if ( hv_exists(MUTABLE_HV(ver), "original", 8 ) )
8cb289bd 4818 {
ef8f7699
NC
4819 SV * pv = *hv_fetchs(MUTABLE_HV(ver), "original", FALSE);
4820 (void)hv_stores(MUTABLE_HV(hv), "original", newSVsv(pv));
8cb289bd
RGS
4821 }
4822
502c6561 4823 sav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(ver), "version", FALSE)));
9137345a
JP
4824 /* This will get reblessed later if a derived class*/
4825 for ( key = 0; key <= av_len(sav); key++ )
4826 {
4827 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4828 av_push(av, newSViv(rev));
4829 }
4830
daba3364 4831 (void)hv_stores(MUTABLE_HV(hv), "version", newRV_noinc(MUTABLE_SV(av)));
d7aa5382
JP
4832 return rv;
4833 }
ad63d80f 4834#ifdef SvVOK
4f2da183 4835 {
3c21775b 4836 const MAGIC* const mg = SvVSTRING_mg(ver);
4f2da183
NC
4837 if ( mg ) { /* already a v-string */
4838 const STRLEN len = mg->mg_len;
4839 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4840 sv_setpvn(rv,version,len);
8cb289bd 4841 /* this is for consistency with the pure Perl class */
91152fc1 4842 if ( isDIGIT(*version) )
8cb289bd 4843 sv_insert(rv, 0, 0, "v", 1);
4f2da183
NC
4844 Safefree(version);
4845 }
4846 else {
ad63d80f 4847#endif
4f2da183 4848 sv_setsv(rv,ver); /* make a duplicate */
137d6fc0 4849#ifdef SvVOK
4f2da183 4850 }
26ec6fc3 4851 }
137d6fc0 4852#endif
ac0e6a2f 4853 return upg_version(rv, FALSE);
b0f01acb
JP
4854}
4855
4856/*
4857=for apidoc upg_version
4858
4859In-place upgrade of the supplied SV to a version object.
4860
ac0e6a2f 4861 SV *sv = upg_version(SV *sv, bool qv);
b0f01acb 4862
ac0e6a2f
RGS
4863Returns a pointer to the upgraded SV. Set the boolean qv if you want
4864to force this SV to be interpreted as an "extended" version.
b0f01acb
JP
4865
4866=cut
4867*/
4868
4869SV *
ac0e6a2f 4870Perl_upg_version(pTHX_ SV *ver, bool qv)
b0f01acb 4871{
cd57dc11 4872 const char *version, *s;
4f2da183
NC
4873#ifdef SvVOK
4874 const MAGIC *mg;
4875#endif
137d6fc0 4876
7918f24d
NC
4877 PERL_ARGS_ASSERT_UPG_VERSION;
4878
ac0e6a2f 4879 if ( SvNOK(ver) && !( SvPOK(ver) && sv_len(ver) == 3 ) )
137d6fc0 4880 {
ac0e6a2f 4881 /* may get too much accuracy */
137d6fc0 4882 char tbuf[64];
b5b5a8f0
RGS
4883#ifdef USE_LOCALE_NUMERIC
4884 char *loc = setlocale(LC_NUMERIC, "C");
4885#endif
63e3af20 4886 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
b5b5a8f0
RGS
4887#ifdef USE_LOCALE_NUMERIC
4888 setlocale(LC_NUMERIC, loc);
4889#endif
c8a14fb6 4890 while (tbuf[len-1] == '0' && len > 0) len--;
8cb289bd 4891 if ( tbuf[len-1] == '.' ) len--; /* eat the trailing decimal */
86c11942 4892 version = savepvn(tbuf, len);
137d6fc0 4893 }
ad63d80f 4894#ifdef SvVOK
666cce26 4895 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
ad63d80f 4896 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
91152fc1 4897 qv = TRUE;
b0f01acb 4898 }
ad63d80f 4899#endif
137d6fc0
JP
4900 else /* must be a string or something like a string */
4901 {
ac0e6a2f
RGS
4902 STRLEN len;
4903 version = savepv(SvPV(ver,len));
4904#ifndef SvVOK
4905# if PERL_VERSION > 5
4906 /* This will only be executed for 5.6.0 - 5.8.0 inclusive */
d54f8cf7 4907 if ( len >= 3 && !instr(version,".") && !instr(version,"_")) {
ac0e6a2f 4908 /* may be a v-string */
d54f8cf7
JP
4909 char *testv = (char *)version;
4910 STRLEN tlen = len;
4911 for (tlen=0; tlen < len; tlen++, testv++) {
4912 /* if one of the characters is non-text assume v-string */
4913 if (testv[0] < ' ') {
4914 SV * const nsv = sv_newmortal();
4915 const char *nver;
4916 const char *pos;
4917 int saw_decimal = 0;
4918 sv_setpvf(nsv,"v%vd",ver);
4919 pos = nver = savepv(SvPV_nolen(nsv));
4920
4921 /* scan the resulting formatted string */
4922 pos++; /* skip the leading 'v' */
4923 while ( *pos == '.' || isDIGIT(*pos) ) {
4924 if ( *pos == '.' )
4925 saw_decimal++ ;
4926 pos++;
4927 }
ac0e6a2f 4928
d54f8cf7
JP
4929 /* is definitely a v-string */
4930 if ( saw_decimal >= 2 ) {
4931 Safefree(version);
4932 version = nver;
4933 }
4934 break;
4935 }
ac0e6a2f
RGS
4936 }
4937 }
4938# endif
4939#endif
137d6fc0 4940 }
92dcf8ce 4941
cd57dc11 4942 s = scan_version(version, ver, qv);
808ee47e 4943 if ( *s != '\0' )
a2a5de95
NC
4944 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4945 "Version string '%s' contains invalid data; "
4946 "ignoring: '%s'", version, s);
137d6fc0 4947 Safefree(version);
ad63d80f 4948 return ver;
b0f01acb
JP
4949}
4950
e0218a61
JP
4951/*
4952=for apidoc vverify
4953
5de8bffd
DG
4954Validates that the SV contains valid internal structure for a version object.
4955It may be passed either the version object (RV) or the hash itself (HV). If
4956the structure is valid, it returns the HV. If the structure is invalid,
4957it returns NULL.
e0218a61 4958
5de8bffd 4959 SV *hv = vverify(sv);
e0218a61
JP
4960
4961Note that it only confirms the bare minimum structure (so as not to get
4962confused by derived classes which may contain additional hash entries):
4963
4964=over 4
4965
5de8bffd 4966=item * The SV is an HV or a reference to an HV
e0218a61
JP
4967
4968=item * The hash contains a "version" key
4969
5de8bffd 4970=item * The "version" key has a reference to an AV as its value
e0218a61
JP
4971
4972=back
4973
4974=cut
4975*/
4976
5de8bffd 4977SV *
e0218a61
JP
4978Perl_vverify(pTHX_ SV *vs)
4979{
4980 SV *sv;
7918f24d
NC
4981
4982 PERL_ARGS_ASSERT_VVERIFY;
4983
e0218a61
JP
4984 if ( SvROK(vs) )
4985 vs = SvRV(vs);
4986
4987 /* see if the appropriate elements exist */
4988 if ( SvTYPE(vs) == SVt_PVHV
ef8f7699
NC
4989 && hv_exists(MUTABLE_HV(vs), "version", 7)
4990 && (sv = SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)))
e0218a61 4991 && SvTYPE(sv) == SVt_PVAV )
5de8bffd 4992 return vs;
e0218a61 4993 else
5de8bffd 4994 return NULL;
e0218a61 4995}
b0f01acb
JP
4996
4997/*
4998=for apidoc vnumify
4999
ad63d80f
JP
5000Accepts a version object and returns the normalized floating
5001point representation. Call like:
b0f01acb 5002
ad63d80f 5003 sv = vnumify(rv);
b0f01acb 5004
ad63d80f
JP
5005NOTE: you can pass either the object directly or the SV
5006contained within the RV.
b0f01acb 5007
0f8e99e6
FC
5008The SV returned has a refcount of 1.
5009
b0f01acb
JP
5010=cut
5011*/
5012
5013SV *
ad63d80f 5014Perl_vnumify(pTHX_ SV *vs)
b0f01acb 5015{
ad63d80f 5016 I32 i, len, digit;
9137345a
JP
5017 int width;
5018 bool alpha = FALSE;
cb4a3036 5019 SV *sv;
9137345a 5020 AV *av;
7918f24d
NC
5021
5022 PERL_ARGS_ASSERT_VNUMIFY;
5023
5de8bffd
DG
5024 /* extract the HV from the object */
5025 vs = vverify(vs);
5026 if ( ! vs )
e0218a61
JP
5027 Perl_croak(aTHX_ "Invalid version object");
5028
9137345a 5029 /* see if various flags exist */
ef8f7699 5030 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
9137345a 5031 alpha = TRUE;
ef8f7699
NC
5032 if ( hv_exists(MUTABLE_HV(vs), "width", 5 ) )
5033 width = SvIV(*hv_fetchs(MUTABLE_HV(vs), "width", FALSE));
9137345a
JP
5034 else
5035 width = 3;
5036
5037
5038 /* attempt to retrieve the version array */
502c6561 5039 if ( !(av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE))) ) ) {
cb4a3036 5040 return newSVpvs("0");
9137345a
JP
5041 }
5042
5043 len = av_len(av);
46314c13
JP
5044 if ( len == -1 )
5045 {
cb4a3036 5046 return newSVpvs("0");
46314c13 5047 }
9137345a
JP
5048
5049 digit = SvIV(*av_fetch(av, 0, 0));
cb4a3036 5050 sv = Perl_newSVpvf(aTHX_ "%d.", (int)PERL_ABS(digit));
13f8f398 5051 for ( i = 1 ; i < len ; i++ )
b0f01acb 5052 {
9137345a
JP
5053 digit = SvIV(*av_fetch(av, i, 0));
5054 if ( width < 3 ) {
43eaf59d 5055 const int denom = (width == 2 ? 10 : 100);
53c1dcc0 5056 const div_t term = div((int)PERL_ABS(digit),denom);
261fcdab 5057 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
9137345a
JP
5058 }
5059 else {
261fcdab 5060 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
9137345a 5061 }
b0f01acb 5062 }
13f8f398
JP
5063
5064 if ( len > 0 )
5065 {
9137345a
JP
5066 digit = SvIV(*av_fetch(av, len, 0));
5067 if ( alpha && width == 3 ) /* alpha version */
396482e1 5068 sv_catpvs(sv,"_");
261fcdab 5069 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
13f8f398 5070 }
e0218a61 5071 else /* len == 0 */
13f8f398 5072 {
396482e1 5073 sv_catpvs(sv, "000");
13f8f398 5074 }
b0f01acb
JP
5075 return sv;
5076}
5077
5078/*
b9381830 5079=for apidoc vnormal
b0f01acb 5080
ad63d80f
JP
5081Accepts a version object and returns the normalized string
5082representation. Call like:
b0f01acb 5083
b9381830 5084 sv = vnormal(rv);
b0f01acb 5085
ad63d80f
JP
5086NOTE: you can pass either the object directly or the SV
5087contained within the RV.
b0f01acb 5088
0f8e99e6
FC
5089The SV returned has a refcount of 1.
5090
b0f01acb
JP
5091=cut
5092*/
5093
5094SV *
b9381830 5095Perl_vnormal(pTHX_ SV *vs)
b0f01acb 5096{
ad63d80f 5097 I32 i, len, digit;
9137345a 5098 bool alpha = FALSE;
cb4a3036 5099 SV *sv;
9137345a 5100 AV *av;
7918f24d
NC
5101
5102 PERL_ARGS_ASSERT_VNORMAL;
5103
5de8bffd
DG
5104 /* extract the HV from the object */
5105 vs = vverify(vs);
5106 if ( ! vs )
e0218a61
JP
5107 Perl_croak(aTHX_ "Invalid version object");
5108
ef8f7699 5109 if ( hv_exists(MUTABLE_HV(vs), "alpha", 5 ) )
9137345a 5110 alpha = TRUE;
502c6561 5111 av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(vs), "version", FALSE)));
9137345a
JP
5112
5113 len = av_len(av);
e0218a61
JP
5114 if ( len == -1 )
5115 {
cb4a3036 5116 return newSVpvs("");
46314c13 5117 }
9137345a 5118 digit = SvIV(*av_fetch(av, 0, 0));
cb4a3036 5119 sv = Perl_newSVpvf(aTHX_ "v%"IVdf, (IV)digit);
cb5772bb 5120 for ( i = 1 ; i < len ; i++ ) {
9137345a 5121 digit = SvIV(*av_fetch(av, i, 0));
261fcdab 5122 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
9137345a
JP
5123 }
5124
e0218a61
JP
5125 if ( len > 0 )
5126 {
9137345a
JP
5127 /* handle last digit specially */
5128 digit = SvIV(*av_fetch(av, len, 0));
5129 if ( alpha )
261fcdab 5130 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
ad63d80f 5131 else
261fcdab 5132 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
b0f01acb 5133 }
9137345a 5134
137d6fc0
JP
5135 if ( len <= 2 ) { /* short version, must be at least three */
5136 for ( len = 2 - len; len != 0; len-- )
396482e1 5137 sv_catpvs(sv,".0");
137d6fc0 5138 }
b0f01acb 5139 return sv;
9137345a 5140}
b0f01acb 5141
ad63d80f 5142/*
b9381830
JP
5143=for apidoc vstringify
5144
5145In order to maintain maximum compatibility with earlier versions
5146of Perl, this function will return either the floating point
5147notation or the multiple dotted notation, depending on whether
0f8e99e6
FC
5148the original version contained 1 or more dots, respectively.
5149
5150The SV returned has a refcount of 1.
b9381830
JP
5151
5152=cut
5153*/
5154
5155SV *
5156Perl_vstringify(pTHX_ SV *vs)
5157{
7918f24d
NC
5158 PERL_ARGS_ASSERT_VSTRINGIFY;
5159
5de8bffd
DG
5160 /* extract the HV from the object */
5161 vs = vverify(vs);
5162 if ( ! vs )
e0218a61
JP
5163 Perl_croak(aTHX_ "Invalid version object");
5164
ef8f7699 5165 if (hv_exists(MUTABLE_HV(vs), "original", sizeof("original") - 1)) {
219bf418 5166 SV *pv;
ef8f7699 5167 pv = *hv_fetchs(MUTABLE_HV(vs), "original", FALSE);
219bf418
RGS
5168 if ( SvPOK(pv) )
5169 return newSVsv(pv);
5170 else
5171 return &PL_sv_undef;
5172 }
5173 else {
ef8f7699 5174 if ( hv_exists(MUTABLE_HV(vs), "qv", 2) )
219bf418
RGS
5175 return vnormal(vs);
5176 else
5177 return vnumify(vs);
5178 }
b9381830
JP
5179}
5180
5181/*
ad63d80f
JP
5182=for apidoc vcmp
5183
5184Version object aware cmp. Both operands must already have been
5185converted into version objects.
5186
5187=cut
5188*/
5189
5190int
9137345a 5191Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
ad63d80f
JP
5192{
5193 I32 i,l,m,r,retval;
9137345a
JP
5194 bool lalpha = FALSE;
5195 bool ralpha = FALSE;
5196 I32 left = 0;
5197 I32 right = 0;
5198 AV *lav, *rav;
7918f24d
NC
5199
5200 PERL_ARGS_ASSERT_VCMP;
5201
5de8bffd
DG
5202 /* extract the HVs from the objects */
5203 lhv = vverify(lhv);
5204 rhv = vverify(rhv);
5205 if ( ! ( lhv && rhv ) )
e0218a61
JP
5206 Perl_croak(aTHX_ "Invalid version object");
5207
9137345a 5208 /* get the left hand term */
502c6561 5209 lav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(lhv), "version", FALSE)));
ef8f7699 5210 if ( hv_exists(MUTABLE_HV(lhv), "alpha", 5 ) )
9137345a
JP
5211 lalpha = TRUE;
5212
5213 /* and the right hand term */
502c6561 5214 rav = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rhv), "version", FALSE)));
ef8f7699 5215 if ( hv_exists(MUTABLE_HV(rhv), "alpha", 5 ) )
9137345a
JP
5216 ralpha = TRUE;
5217
5218 l = av_len(lav);
5219 r = av_len(rav);
ad63d80f
JP
5220 m = l < r ? l : r;
5221 retval = 0;
5222 i = 0;
5223 while ( i <= m && retval == 0 )
5224 {
9137345a
JP
5225 left = SvIV(*av_fetch(lav,i,0));
5226 right = SvIV(*av_fetch(rav,i,0));
5227 if ( left < right )
ad63d80f 5228 retval = -1;
9137345a 5229 if ( left > right )
ad63d80f
JP
5230 retval = +1;
5231 i++;
5232 }
5233
9137345a
JP
5234 /* tiebreaker for alpha with identical terms */
5235 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
5236 {
5237 if ( lalpha && !ralpha )
5238 {
5239 retval = -1;
5240 }
5241 else if ( ralpha && !lalpha)
5242 {
5243 retval = +1;
5244 }
5245 }
5246
137d6fc0 5247 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
129318bd 5248 {
137d6fc0 5249 if ( l < r )
129318bd 5250 {
137d6fc0
JP
5251 while ( i <= r && retval == 0 )
5252 {
9137345a 5253 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
137d6fc0
JP
5254 retval = -1; /* not a match after all */
5255 i++;
5256 }
5257 }
5258 else
5259 {
5260 while ( i <= l && retval == 0 )
5261 {
9137345a 5262 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
137d6fc0
JP
5263 retval = +1; /* not a match after all */
5264 i++;
5265 }
129318bd
JP
5266 }
5267 }
ad63d80f
JP
5268 return retval;
5269}
5270
c95c94b1 5271#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
2bc69dc4
NIS
5272# define EMULATE_SOCKETPAIR_UDP
5273#endif
5274
5275#ifdef EMULATE_SOCKETPAIR_UDP
02fc2eee
NC
5276static int
5277S_socketpair_udp (int fd[2]) {
e10bb1e9 5278 dTHX;
02fc2eee
NC
5279 /* Fake a datagram socketpair using UDP to localhost. */
5280 int sockets[2] = {-1, -1};
5281 struct sockaddr_in addresses[2];
5282 int i;
3aed30dc 5283 Sock_size_t size = sizeof(struct sockaddr_in);
ae92b34e 5284 unsigned short port;
02fc2eee
NC
5285 int got;
5286
3aed30dc 5287 memset(&addresses, 0, sizeof(addresses));
02fc2eee
NC
5288 i = 1;
5289 do {
3aed30dc
HS
5290 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
5291 if (sockets[i] == -1)
5292 goto tidy_up_and_fail;
5293
5294 addresses[i].sin_family = AF_INET;
5295 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5296 addresses[i].sin_port = 0; /* kernel choses port. */
5297 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
5298 sizeof(struct sockaddr_in)) == -1)
5299 goto tidy_up_and_fail;
02fc2eee
NC
5300 } while (i--);
5301
5302 /* Now have 2 UDP sockets. Find out which port each is connected to, and
5303 for each connect the other socket to it. */
5304 i = 1;
5305 do {
3aed30dc
HS
5306 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
5307 &size) == -1)
5308 goto tidy_up_and_fail;
5309 if (size != sizeof(struct sockaddr_in))
5310 goto abort_tidy_up_and_fail;
5311 /* !1 is 0, !0 is 1 */
5312 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
5313 sizeof(struct sockaddr_in)) == -1)
5314 goto tidy_up_and_fail;
02fc2eee
NC
5315 } while (i--);
5316
5317 /* Now we have 2 sockets connected to each other. I don't trust some other
5318 process not to have already sent a packet to us (by random) so send
5319 a packet from each to the other. */
5320 i = 1;
5321 do {
3aed30dc
HS
5322 /* I'm going to send my own port number. As a short.
5323 (Who knows if someone somewhere has sin_port as a bitfield and needs
5324 this routine. (I'm assuming crays have socketpair)) */
5325 port = addresses[i].sin_port;
5326 got = PerlLIO_write(sockets[i], &port, sizeof(port));
5327 if (got != sizeof(port)) {
5328 if (got == -1)
5329 goto tidy_up_and_fail;
5330 goto abort_tidy_up_and_fail;
5331 }
02fc2eee
NC
5332 } while (i--);
5333
5334 /* Packets sent. I don't trust them to have arrived though.
5335 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
5336 connect to localhost will use a second kernel thread. In 2.6 the
5337 first thread running the connect() returns before the second completes,
5338 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
5339 returns 0. Poor programs have tripped up. One poor program's authors'
5340 had a 50-1 reverse stock split. Not sure how connected these were.)
5341 So I don't trust someone not to have an unpredictable UDP stack.
5342 */
5343
5344 {
3aed30dc
HS
5345 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
5346 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
5347 fd_set rset;
5348
5349 FD_ZERO(&rset);
ea407a0c
NC
5350 FD_SET((unsigned int)sockets[0], &rset);
5351 FD_SET((unsigned int)sockets[1], &rset);
3aed30dc
HS
5352
5353 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
5354 if (got != 2 || !FD_ISSET(sockets[0], &rset)
5355 || !FD_ISSET(sockets[1], &rset)) {
5356 /* I hope this is portable and appropriate. */
5357 if (got == -1)
5358 goto tidy_up_and_fail;
5359 goto abort_tidy_up_and_fail;
5360 }
02fc2eee 5361 }
f4758303 5362
02fc2eee
NC
5363 /* And the paranoia department even now doesn't trust it to have arrive
5364 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
5365 {
3aed30dc
HS
5366 struct sockaddr_in readfrom;
5367 unsigned short buffer[2];
02fc2eee 5368
3aed30dc
HS
5369 i = 1;
5370 do {
02fc2eee 5371#ifdef MSG_DONTWAIT
3aed30dc
HS
5372 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5373 sizeof(buffer), MSG_DONTWAIT,
5374 (struct sockaddr *) &readfrom, &size);
02fc2eee 5375#else
3aed30dc
HS
5376 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
5377 sizeof(buffer), 0,
5378 (struct sockaddr *) &readfrom, &size);
e10bb1e9 5379#endif
02fc2eee 5380
3aed30dc
HS
5381 if (got == -1)
5382 goto tidy_up_and_fail;
5383 if (got != sizeof(port)
5384 || size != sizeof(struct sockaddr_in)
5385 /* Check other socket sent us its port. */
5386 || buffer[0] != (unsigned short) addresses[!i].sin_port
5387 /* Check kernel says we got the datagram from that socket */
5388 || readfrom.sin_family != addresses[!i].sin_family
5389 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
5390 || readfrom.sin_port != addresses[!i].sin_port)
5391 goto abort_tidy_up_and_fail;
5392 } while (i--);
02fc2eee
NC
5393 }
5394 /* My caller (my_socketpair) has validated that this is non-NULL */
5395 fd[0] = sockets[0];
5396 fd[1] = sockets[1];
5397 /* I hereby declare this connection open. May God bless all who cross
5398 her. */
5399 return 0;
5400
5401 abort_tidy_up_and_fail:
5402 errno = ECONNABORTED;
5403 tidy_up_and_fail:
5404 {
4ee39169 5405 dSAVE_ERRNO;
3aed30dc
HS
5406 if (sockets[0] != -1)
5407 PerlLIO_close(sockets[0]);
5408 if (sockets[1] != -1)
5409 PerlLIO_close(sockets[1]);
4ee39169 5410 RESTORE_ERRNO;
3aed30dc 5411 return -1;
02fc2eee
NC
5412 }
5413}
85ca448a 5414#endif /* EMULATE_SOCKETPAIR_UDP */
02fc2eee 5415
b5ac89c3 5416#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
02fc2eee
NC
5417int
5418Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
5419 /* Stevens says that family must be AF_LOCAL, protocol 0.
2948e0bd 5420 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
e10bb1e9 5421 dTHX;
02fc2eee
NC
5422 int listener = -1;
5423 int connector = -1;
5424 int acceptor = -1;
5425 struct sockaddr_in listen_addr;
5426 struct sockaddr_in connect_addr;
5427 Sock_size_t size;
5428
50458334
JH
5429 if (protocol
5430#ifdef AF_UNIX
5431 || family != AF_UNIX
5432#endif
3aed30dc
HS
5433 ) {
5434 errno = EAFNOSUPPORT;
5435 return -1;
02fc2eee 5436 }
2948e0bd 5437 if (!fd) {
3aed30dc
HS
5438 errno = EINVAL;
5439 return -1;
2948e0bd 5440 }
02fc2eee 5441
2bc69dc4 5442#ifdef EMULATE_SOCKETPAIR_UDP
02fc2eee 5443 if (type == SOCK_DGRAM)
3aed30dc 5444 return S_socketpair_udp(fd);
2bc69dc4 5445#endif
02fc2eee 5446
3aed30dc 5447 listener = PerlSock_socket(AF_INET, type, 0);
02fc2eee 5448 if (listener == -1)
3aed30dc
HS
5449 return -1;
5450 memset(&listen_addr, 0, sizeof(listen_addr));
02fc2eee 5451 listen_addr.sin_family = AF_INET;
3aed30dc 5452 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
02fc2eee 5453 listen_addr.sin_port = 0; /* kernel choses port. */
3aed30dc
HS
5454 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
5455 sizeof(listen_addr)) == -1)
5456 goto tidy_up_and_fail;
e10bb1e9 5457 if (PerlSock_listen(listener, 1) == -1)
3aed30dc 5458 goto tidy_up_and_fail;
02fc2eee 5459
3aed30dc 5460 connector = PerlSock_socket(AF_INET, type, 0);
02fc2eee 5461 if (connector == -1)
3aed30dc 5462 goto tidy_up_and_fail;
02fc2eee 5463 /* We want to find out the port number to connect to. */
3aed30dc
HS
5464 size = sizeof(connect_addr);
5465 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
5466 &size) == -1)
5467 goto tidy_up_and_fail;
5468 if (size != sizeof(connect_addr))
5469 goto abort_tidy_up_and_fail;
e10bb1e9 5470 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
3aed30dc
HS
5471 sizeof(connect_addr)) == -1)
5472 goto tidy_up_and_fail;
02fc2eee 5473
3aed30dc
HS
5474 size = sizeof(listen_addr);
5475 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
5476 &size);
02fc2eee 5477 if (acceptor == -1)
3aed30dc
HS
5478 goto tidy_up_and_fail;
5479 if (size != sizeof(listen_addr))
5480 goto abort_tidy_up_and_fail;
5481 PerlLIO_close(listener);
02fc2eee
NC
5482 /* Now check we are talking to ourself by matching port and host on the
5483 two sockets. */
3aed30dc
HS
5484 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
5485 &size) == -1)
5486 goto tidy_up_and_fail;
5487 if (size != sizeof(connect_addr)
5488 || listen_addr.sin_family != connect_addr.sin_family
5489 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
5490 || listen_addr.sin_port != connect_addr.sin_port) {
5491 goto abort_tidy_up_and_fail;
02fc2eee
NC
5492 }
5493 fd[0] = connector;
5494 fd[1] = acceptor;
5495 return 0;
5496
5497 abort_tidy_up_and_fail:
27da23d5
JH
5498#ifdef ECONNABORTED
5499 errno = ECONNABORTED; /* This would be the standard thing to do. */
5500#else
5501# ifdef ECONNREFUSED
5502 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
5503# else
5504 errno = ETIMEDOUT; /* Desperation time. */
5505# endif
5506#endif
02fc2eee
NC
5507 tidy_up_and_fail:
5508 {
4ee39169 5509 dSAVE_ERRNO;
3aed30dc
HS
5510 if (listener != -1)
5511 PerlLIO_close(listener);
5512 if (connector != -1)
5513 PerlLIO_close(connector);
5514 if (acceptor != -1)
5515 PerlLIO_close(acceptor);
4ee39169 5516 RESTORE_ERRNO;
3aed30dc 5517 return -1;
02fc2eee
NC
5518 }
5519}
85ca448a 5520#else
48ea76d1
JH
5521/* In any case have a stub so that there's code corresponding
5522 * to the my_socketpair in global.sym. */
5523int
5524Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
daf16542 5525#ifdef HAS_SOCKETPAIR
48ea76d1 5526 return socketpair(family, type, protocol, fd);
daf16542
JH
5527#else
5528 return -1;
5529#endif
48ea76d1
JH
5530}
5531#endif
5532
68795e93
NIS
5533/*
5534
5535=for apidoc sv_nosharing
5536
5537Dummy routine which "shares" an SV when there is no sharing module present.
d5b2b27b
NC
5538Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
5539Exists to avoid test for a NULL function pointer and because it could
5540potentially warn under some level of strict-ness.
68795e93
NIS
5541
5542=cut
5543*/
5544
5545void
5546Perl_sv_nosharing(pTHX_ SV *sv)
5547{
96a5add6 5548 PERL_UNUSED_CONTEXT;
53c1dcc0 5549 PERL_UNUSED_ARG(sv);
68795e93
NIS
5550}
5551
eba16661
JH
5552/*
5553
5554=for apidoc sv_destroyable
5555
5556Dummy routine which reports that object can be destroyed when there is no
5557sharing module present. It ignores its single SV argument, and returns
5558'true'. Exists to avoid test for a NULL function pointer and because it
5559could potentially warn under some level of strict-ness.
5560
5561=cut
5562*/
5563
5564bool
5565Perl_sv_destroyable(pTHX_ SV *sv)
5566{
5567 PERL_UNUSED_CONTEXT;
5568 PERL_UNUSED_ARG(sv);
5569 return TRUE;
5570}
5571
a05d7ebb 5572U32
e1ec3a88 5573Perl_parse_unicode_opts(pTHX_ const char **popt)
a05d7ebb 5574{
e1ec3a88 5575 const char *p = *popt;
a05d7ebb
JH
5576 U32 opt = 0;
5577
7918f24d
NC
5578 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
5579
a05d7ebb
JH
5580 if (*p) {
5581 if (isDIGIT(*p)) {
5582 opt = (U32) atoi(p);
35da51f7
AL
5583 while (isDIGIT(*p))
5584 p++;
d4a59e54
FC
5585 if (*p && *p != '\n' && *p != '\r') {
5586 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5587 else
a05d7ebb 5588 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
d4a59e54 5589 }
a05d7ebb
JH
5590 }
5591 else {
5592 for (; *p; p++) {
5593 switch (*p) {
5594 case PERL_UNICODE_STDIN:
5595 opt |= PERL_UNICODE_STDIN_FLAG; break;
5596 case PERL_UNICODE_STDOUT:
5597 opt |= PERL_UNICODE_STDOUT_FLAG; break;
5598 case PERL_UNICODE_STDERR:
5599 opt |= PERL_UNICODE_STDERR_FLAG; break;
5600 case PERL_UNICODE_STD:
5601 opt |= PERL_UNICODE_STD_FLAG; break;
5602 case PERL_UNICODE_IN:
5603 opt |= PERL_UNICODE_IN_FLAG; break;
5604 case PERL_UNICODE_OUT:
5605 opt |= PERL_UNICODE_OUT_FLAG; break;
5606 case PERL_UNICODE_INOUT:
5607 opt |= PERL_UNICODE_INOUT_FLAG; break;
5608 case PERL_UNICODE_LOCALE:
5609 opt |= PERL_UNICODE_LOCALE_FLAG; break;
5610 case PERL_UNICODE_ARGV:
5611 opt |= PERL_UNICODE_ARGV_FLAG; break;
5a22a2bb
NC
5612 case PERL_UNICODE_UTF8CACHEASSERT:
5613 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
a05d7ebb 5614 default:
d4a59e54
FC
5615 if (*p != '\n' && *p != '\r') {
5616 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
5617 else
7c91f477
JH
5618 Perl_croak(aTHX_
5619 "Unknown Unicode option letter '%c'", *p);
d4a59e54 5620 }
a05d7ebb
JH
5621 }
5622 }
5623 }
5624 }
5625 else
5626 opt = PERL_UNICODE_DEFAULT_FLAGS;
5627
d4a59e54
FC
5628 the_end_of_the_opts_parser:
5629
a05d7ebb 5630 if (opt & ~PERL_UNICODE_ALL_FLAGS)
06e66572 5631 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
a05d7ebb
JH
5632 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5633
5634 *popt = p;
5635
5636 return opt;
5637}
5638
132efe8b
JH
5639U32
5640Perl_seed(pTHX)
5641{
97aff369 5642 dVAR;
132efe8b
JH
5643 /*
5644 * This is really just a quick hack which grabs various garbage
5645 * values. It really should be a real hash algorithm which
5646 * spreads the effect of every input bit onto every output bit,
5647 * if someone who knows about such things would bother to write it.
5648 * Might be a good idea to add that function to CORE as well.
5649 * No numbers below come from careful analysis or anything here,
5650 * except they are primes and SEED_C1 > 1E6 to get a full-width
5651 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5652 * probably be bigger too.
5653 */
5654#if RANDBITS > 16
5655# define SEED_C1 1000003
5656#define SEED_C4 73819
5657#else
5658# define SEED_C1 25747
5659#define SEED_C4 20639
5660#endif
5661#define SEED_C2 3
5662#define SEED_C3 269
5663#define SEED_C5 26107
5664
5665#ifndef PERL_NO_DEV_RANDOM
5666 int fd;
5667#endif
5668 U32 u;
5669#ifdef VMS
5670# include <starlet.h>
5671 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5672 * in 100-ns units, typically incremented ever 10 ms. */
5673 unsigned int when[2];
5674#else
5675# ifdef HAS_GETTIMEOFDAY
5676 struct timeval when;
5677# else
5678 Time_t when;
5679# endif
5680#endif
5681
5682/* This test is an escape hatch, this symbol isn't set by Configure. */
5683#ifndef PERL_NO_DEV_RANDOM
5684#ifndef PERL_RANDOM_DEVICE
5685 /* /dev/random isn't used by default because reads from it will block
5686 * if there isn't enough entropy available. You can compile with
5687 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5688 * is enough real entropy to fill the seed. */
5689# define PERL_RANDOM_DEVICE "/dev/urandom"
5690#endif
5691 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5692 if (fd != -1) {
27da23d5 5693 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
132efe8b
JH
5694 u = 0;
5695 PerlLIO_close(fd);
5696 if (u)
5697 return u;
5698 }
5699#endif
5700
5701#ifdef VMS
5702 _ckvmssts(sys$gettim(when));
5703 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5704#else
5705# ifdef HAS_GETTIMEOFDAY
5706 PerlProc_gettimeofday(&when,NULL);
5707 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5708# else
5709 (void)time(&when);
5710 u = (U32)SEED_C1 * when;
5711# endif
5712#endif
5713 u += SEED_C3 * (U32)PerlProc_getpid();
5714 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5715#ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5716 u += SEED_C5 * (U32)PTR2UV(&when);
5717#endif
5718 return u;
5719}
5720
bed60192 5721UV
a783c5f4 5722Perl_get_hash_seed(pTHX)
bed60192 5723{
97aff369 5724 dVAR;
e1ec3a88 5725 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
bed60192
JH
5726 UV myseed = 0;
5727
5728 if (s)
35da51f7
AL
5729 while (isSPACE(*s))
5730 s++;
bed60192
JH
5731 if (s && isDIGIT(*s))
5732 myseed = (UV)Atoul(s);
5733 else
5734#ifdef USE_HASH_SEED_EXPLICIT
5735 if (s)
5736#endif
5737 {
5738 /* Compute a random seed */
5739 (void)seedDrand01((Rand_seed_t)seed());
bed60192
JH
5740 myseed = (UV)(Drand01() * (NV)UV_MAX);
5741#if RANDBITS < (UVSIZE * 8)
5742 /* Since there are not enough randbits to to reach all
5743 * the bits of a UV, the low bits might need extra
5744 * help. Sum in another random number that will
5745 * fill in the low bits. */
5746 myseed +=
fa58a56f 5747 (UV)(Drand01() * (NV)((((UV)1) << ((UVSIZE * 8 - RANDBITS))) - 1));
bed60192 5748#endif /* RANDBITS < (UVSIZE * 8) */
6cfd5ea7
JH
5749 if (myseed == 0) { /* Superparanoia. */
5750 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5751 if (myseed == 0)
5752 Perl_croak(aTHX_ "Your random numbers are not that random");
5753 }
bed60192 5754 }
008fb0c0 5755 PL_rehash_seed_set = TRUE;
bed60192
JH
5756
5757 return myseed;
5758}
27da23d5 5759
ed221c57
AL
5760#ifdef USE_ITHREADS
5761bool
5762Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5763{
5764 const char * const stashpv = CopSTASHPV(c);
5765 const char * const name = HvNAME_get(hv);
96a5add6 5766 PERL_UNUSED_CONTEXT;
7918f24d 5767 PERL_ARGS_ASSERT_STASHPV_HVNAME_MATCH;
ed221c57
AL
5768
5769 if (stashpv == name)
5770 return TRUE;
5771 if (stashpv && name)
5772 if (strEQ(stashpv, name))
5773 return TRUE;
5774 return FALSE;
5775}
5776#endif
5777
5778
27da23d5
JH
5779#ifdef PERL_GLOBAL_STRUCT
5780
bae1192d
JH
5781#define PERL_GLOBAL_STRUCT_INIT
5782#include "opcode.h" /* the ppaddr and check */
5783
27da23d5
JH
5784struct perl_vars *
5785Perl_init_global_struct(pTHX)
5786{
5787 struct perl_vars *plvarsp = NULL;
bae1192d 5788# ifdef PERL_GLOBAL_STRUCT
7452cf6a
AL
5789 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5790 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
27da23d5
JH
5791# ifdef PERL_GLOBAL_STRUCT_PRIVATE
5792 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5793 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5794 if (!plvarsp)
5795 exit(1);
5796# else
5797 plvarsp = PL_VarsPtr;
5798# endif /* PERL_GLOBAL_STRUCT_PRIVATE */
aadb217d
JH
5799# undef PERLVAR
5800# undef PERLVARA
5801# undef PERLVARI
5802# undef PERLVARIC
27da23d5
JH
5803# define PERLVAR(var,type) /**/
5804# define PERLVARA(var,n,type) /**/
5805# define PERLVARI(var,type,init) plvarsp->var = init;
5806# define PERLVARIC(var,type,init) plvarsp->var = init;
27da23d5
JH
5807# include "perlvars.h"
5808# undef PERLVAR
5809# undef PERLVARA
5810# undef PERLVARI
5811# undef PERLVARIC
27da23d5 5812# ifdef PERL_GLOBAL_STRUCT
bae1192d
JH
5813 plvarsp->Gppaddr =
5814 (Perl_ppaddr_t*)
5815 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
27da23d5
JH
5816 if (!plvarsp->Gppaddr)
5817 exit(1);
bae1192d
JH
5818 plvarsp->Gcheck =
5819 (Perl_check_t*)
5820 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
27da23d5
JH
5821 if (!plvarsp->Gcheck)
5822 exit(1);
5823 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5824 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5825# endif
5826# ifdef PERL_SET_VARS
5827 PERL_SET_VARS(plvarsp);
5828# endif
bae1192d
JH
5829# undef PERL_GLOBAL_STRUCT_INIT
5830# endif
27da23d5
JH
5831 return plvarsp;
5832}
5833
5834#endif /* PERL_GLOBAL_STRUCT */
5835
5836#ifdef PERL_GLOBAL_STRUCT
5837
5838void
5839Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5840{
7918f24d 5841 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
bae1192d 5842# ifdef PERL_GLOBAL_STRUCT
27da23d5
JH
5843# ifdef PERL_UNSET_VARS
5844 PERL_UNSET_VARS(plvarsp);
5845# endif
5846 free(plvarsp->Gppaddr);
5847 free(plvarsp->Gcheck);
bae1192d 5848# ifdef PERL_GLOBAL_STRUCT_PRIVATE
27da23d5 5849 free(plvarsp);
bae1192d
JH
5850# endif
5851# endif
27da23d5
JH
5852}
5853
5854#endif /* PERL_GLOBAL_STRUCT */
5855
fe4f188c
JH
5856#ifdef PERL_MEM_LOG
5857
1cd8acb5 5858/* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
73d1d973
JC
5859 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
5860 * given, and you supply your own implementation.
65ceff02 5861 *
2e5b5004 5862 * The default implementation reads a single env var, PERL_MEM_LOG,
1cd8acb5
JC
5863 * expecting one or more of the following:
5864 *
5865 * \d+ - fd fd to write to : must be 1st (atoi)
2e5b5004 5866 * 'm' - memlog was PERL_MEM_LOG=1
1cd8acb5
JC
5867 * 's' - svlog was PERL_SV_LOG=1
5868 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
0b0ab801 5869 *
1cd8acb5
JC
5870 * This makes the logger controllable enough that it can reasonably be
5871 * added to the system perl.
65ceff02
JH
5872 */
5873
1cd8acb5 5874/* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
65ceff02
JH
5875 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5876 */
e352bcff
JH
5877#define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5878
1cd8acb5
JC
5879/* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
5880 * writes to. In the default logger, this is settable at runtime.
65ceff02
JH
5881 */
5882#ifndef PERL_MEM_LOG_FD
5883# define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5884#endif
5885
73d1d973 5886#ifndef PERL_MEM_LOG_NOIMPL
d7a2c63c
MHM
5887
5888# ifdef DEBUG_LEAKING_SCALARS
5889# define SV_LOG_SERIAL_FMT " [%lu]"
5890# define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
5891# else
5892# define SV_LOG_SERIAL_FMT
5893# define _SV_LOG_SERIAL_ARG(sv)
5894# endif
5895
0b0ab801 5896static void
73d1d973
JC
5897S_mem_log_common(enum mem_log_type mlt, const UV n,
5898 const UV typesize, const char *type_name, const SV *sv,
5899 Malloc_t oldalloc, Malloc_t newalloc,
5900 const char *filename, const int linenumber,
5901 const char *funcname)
0b0ab801 5902{
1cd8acb5 5903 const char *pmlenv;
4ca7bcef 5904
1cd8acb5 5905 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4ca7bcef 5906
1cd8acb5
JC
5907 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
5908 if (!pmlenv)
5909 return;
5910 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
65ceff02
JH
5911 {
5912 /* We can't use SVs or PerlIO for obvious reasons,
5913 * so we'll use stdio and low-level IO instead. */
5914 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
1cd8acb5 5915
5b692037 5916# ifdef HAS_GETTIMEOFDAY
0b0ab801
MHM
5917# define MEM_LOG_TIME_FMT "%10d.%06d: "
5918# define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
5919 struct timeval tv;
65ceff02 5920 gettimeofday(&tv, 0);
0b0ab801
MHM
5921# else
5922# define MEM_LOG_TIME_FMT "%10d: "
5923# define MEM_LOG_TIME_ARG (int)when
5924 Time_t when;
5925 (void)time(&when);
5b692037
JH
5926# endif
5927 /* If there are other OS specific ways of hires time than
40d04ec4 5928 * gettimeofday() (see ext/Time-HiRes), the easiest way is
5b692037
JH
5929 * probably that they would be used to fill in the struct
5930 * timeval. */
65ceff02 5931 {
0b0ab801 5932 STRLEN len;
1cd8acb5
JC
5933 int fd = atoi(pmlenv);
5934 if (!fd)
5935 fd = PERL_MEM_LOG_FD;
0b0ab801 5936
1cd8acb5 5937 if (strchr(pmlenv, 't')) {
0b0ab801
MHM
5938 len = my_snprintf(buf, sizeof(buf),
5939 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
5940 PerlLIO_write(fd, buf, len);
5941 }
0b0ab801
MHM
5942 switch (mlt) {
5943 case MLT_ALLOC:
5944 len = my_snprintf(buf, sizeof(buf),
5945 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5946 " %s = %"IVdf": %"UVxf"\n",
5947 filename, linenumber, funcname, n, typesize,
bef8a128 5948 type_name, n * typesize, PTR2UV(newalloc));
0b0ab801
MHM
5949 break;
5950 case MLT_REALLOC:
5951 len = my_snprintf(buf, sizeof(buf),
5952 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5953 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5954 filename, linenumber, funcname, n, typesize,
bef8a128 5955 type_name, n * typesize, PTR2UV(oldalloc),
0b0ab801
MHM
5956 PTR2UV(newalloc));
5957 break;
5958 case MLT_FREE:
5959 len = my_snprintf(buf, sizeof(buf),
5960 "free: %s:%d:%s: %"UVxf"\n",
5961 filename, linenumber, funcname,
5962 PTR2UV(oldalloc));
5963 break;
d7a2c63c
MHM
5964 case MLT_NEW_SV:
5965 case MLT_DEL_SV:
5966 len = my_snprintf(buf, sizeof(buf),
5967 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
5968 mlt == MLT_NEW_SV ? "new" : "del",
5969 filename, linenumber, funcname,
5970 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
5971 break;
73d1d973
JC
5972 default:
5973 len = 0;
0b0ab801
MHM
5974 }
5975 PerlLIO_write(fd, buf, len);
65ceff02
JH
5976 }
5977 }
0b0ab801 5978}
73d1d973
JC
5979#endif /* !PERL_MEM_LOG_NOIMPL */
5980
5981#ifndef PERL_MEM_LOG_NOIMPL
5982# define \
5983 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
5984 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
5985#else
5986/* this is suboptimal, but bug compatible. User is providing their
486ec47a 5987 own implementation, but is getting these functions anyway, and they
73d1d973
JC
5988 do nothing. But _NOIMPL users should be able to cope or fix */
5989# define \
5990 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
5991 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
0b0ab801
MHM
5992#endif
5993
5994Malloc_t
73d1d973
JC
5995Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
5996 Malloc_t newalloc,
5997 const char *filename, const int linenumber,
5998 const char *funcname)
5999{
6000 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
6001 NULL, NULL, newalloc,
6002 filename, linenumber, funcname);
fe4f188c
JH
6003 return newalloc;
6004}
6005
6006Malloc_t
73d1d973
JC
6007Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
6008 Malloc_t oldalloc, Malloc_t newalloc,
6009 const char *filename, const int linenumber,
6010 const char *funcname)
6011{
6012 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
6013 NULL, oldalloc, newalloc,
6014 filename, linenumber, funcname);
fe4f188c
JH
6015 return newalloc;
6016}
6017
6018Malloc_t
73d1d973
JC
6019Perl_mem_log_free(Malloc_t oldalloc,
6020 const char *filename, const int linenumber,
6021 const char *funcname)
fe4f188c 6022{
73d1d973
JC
6023 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
6024 filename, linenumber, funcname);
fe4f188c
JH
6025 return oldalloc;
6026}
6027
d7a2c63c 6028void
73d1d973
JC
6029Perl_mem_log_new_sv(const SV *sv,
6030 const char *filename, const int linenumber,
6031 const char *funcname)
d7a2c63c 6032{
73d1d973
JC
6033 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
6034 filename, linenumber, funcname);
d7a2c63c
MHM
6035}
6036
6037void
73d1d973
JC
6038Perl_mem_log_del_sv(const SV *sv,
6039 const char *filename, const int linenumber,
6040 const char *funcname)
d7a2c63c 6041{
73d1d973
JC
6042 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
6043 filename, linenumber, funcname);
d7a2c63c
MHM
6044}
6045
fe4f188c
JH
6046#endif /* PERL_MEM_LOG */
6047
66610fdd 6048/*
ce582cee
NC
6049=for apidoc my_sprintf
6050
6051The C library C<sprintf>, wrapped if necessary, to ensure that it will return
6052the length of the string written to the buffer. Only rare pre-ANSI systems
6053need the wrapper function - usually this is a direct call to C<sprintf>.
6054
6055=cut
6056*/
6057#ifndef SPRINTF_RETURNS_STRLEN
6058int
6059Perl_my_sprintf(char *buffer, const char* pat, ...)
6060{
6061 va_list args;
7918f24d 6062 PERL_ARGS_ASSERT_MY_SPRINTF;
ce582cee
NC
6063 va_start(args, pat);
6064 vsprintf(buffer, pat, args);
6065 va_end(args);
6066 return strlen(buffer);
6067}
6068#endif
6069
d9fad198
JH
6070/*
6071=for apidoc my_snprintf
6072
6073The C library C<snprintf> functionality, if available and
5b692037 6074standards-compliant (uses C<vsnprintf>, actually). However, if the
d9fad198 6075C<vsnprintf> is not available, will unfortunately use the unsafe
5b692037
JH
6076C<vsprintf> which can overrun the buffer (there is an overrun check,
6077but that may be too late). Consider using C<sv_vcatpvf> instead, or
6078getting C<vsnprintf>.
d9fad198
JH
6079
6080=cut
6081*/
6082int
6083Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
d9fad198
JH
6084{
6085 dTHX;
6086 int retval;
6087 va_list ap;
7918f24d 6088 PERL_ARGS_ASSERT_MY_SNPRINTF;
d9fad198 6089 va_start(ap, format);
5b692037 6090#ifdef HAS_VSNPRINTF
d9fad198
JH
6091 retval = vsnprintf(buffer, len, format, ap);
6092#else
6093 retval = vsprintf(buffer, format, ap);
6094#endif
6095 va_end(ap);
7dac5c64
RB
6096 /* vsprintf() shows failure with < 0 */
6097 if (retval < 0
6098#ifdef HAS_VSNPRINTF
6099 /* vsnprintf() shows failure with >= len */
6100 ||
6101 (len > 0 && (Size_t)retval >= len)
6102#endif
6103 )
5b692037 6104 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
d9fad198
JH
6105 return retval;
6106}
6107
6108/*
6109=for apidoc my_vsnprintf
6110
5b692037
JH
6111The C library C<vsnprintf> if available and standards-compliant.
6112However, if if the C<vsnprintf> is not available, will unfortunately
6113use the unsafe C<vsprintf> which can overrun the buffer (there is an
6114overrun check, but that may be too late). Consider using
6115C<sv_vcatpvf> instead, or getting C<vsnprintf>.
d9fad198
JH
6116
6117=cut
6118*/
6119int
6120Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
d9fad198
JH
6121{
6122 dTHX;
6123 int retval;
d9fad198
JH
6124#ifdef NEED_VA_COPY
6125 va_list apc;
7918f24d
NC
6126
6127 PERL_ARGS_ASSERT_MY_VSNPRINTF;
6128
239fec62 6129 Perl_va_copy(ap, apc);
5b692037 6130# ifdef HAS_VSNPRINTF
d9fad198
JH
6131 retval = vsnprintf(buffer, len, format, apc);
6132# else
6133 retval = vsprintf(buffer, format, apc);
6134# endif
6135#else
5b692037 6136# ifdef HAS_VSNPRINTF
d9fad198
JH
6137 retval = vsnprintf(buffer, len, format, ap);
6138# else
6139 retval = vsprintf(buffer, format, ap);
6140# endif
5b692037 6141#endif /* #ifdef NEED_VA_COPY */
7dac5c64
RB
6142 /* vsprintf() shows failure with < 0 */
6143 if (retval < 0
6144#ifdef HAS_VSNPRINTF
6145 /* vsnprintf() shows failure with >= len */
6146 ||
6147 (len > 0 && (Size_t)retval >= len)
6148#endif
6149 )
5b692037 6150 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
d9fad198
JH
6151 return retval;
6152}
6153
b0269e46
AB
6154void
6155Perl_my_clearenv(pTHX)
6156{
6157 dVAR;
6158#if ! defined(PERL_MICRO)
6159# if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
6160 PerlEnv_clearenv();
6161# else /* ! (PERL_IMPLICIT_SYS || WIN32) */
6162# if defined(USE_ENVIRON_ARRAY)
6163# if defined(USE_ITHREADS)
6164 /* only the parent thread can clobber the process environment */
6165 if (PL_curinterp == aTHX)
6166# endif /* USE_ITHREADS */
6167 {
6168# if ! defined(PERL_USE_SAFE_PUTENV)
6169 if ( !PL_use_safe_putenv) {
6170 I32 i;
6171 if (environ == PL_origenviron)
6172 environ = (char**)safesysmalloc(sizeof(char*));
6173 else
6174 for (i = 0; environ[i]; i++)
6175 (void)safesysfree(environ[i]);
6176 }
6177 environ[0] = NULL;
6178# else /* PERL_USE_SAFE_PUTENV */
6179# if defined(HAS_CLEARENV)
6180 (void)clearenv();
6181# elif defined(HAS_UNSETENV)
6182 int bsiz = 80; /* Most envvar names will be shorter than this. */
d1307786
JH
6183 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
6184 char *buf = (char*)safesysmalloc(bufsiz);
b0269e46
AB
6185 while (*environ != NULL) {
6186 char *e = strchr(*environ, '=');
b57a0404 6187 int l = e ? e - *environ : (int)strlen(*environ);
b0269e46
AB
6188 if (bsiz < l + 1) {
6189 (void)safesysfree(buf);
1bdfa2de 6190 bsiz = l + 1; /* + 1 for the \0. */
d1307786 6191 buf = (char*)safesysmalloc(bufsiz);
b0269e46 6192 }
82d8bb49
NC
6193 memcpy(buf, *environ, l);
6194 buf[l] = '\0';
b0269e46
AB
6195 (void)unsetenv(buf);
6196 }
6197 (void)safesysfree(buf);
6198# else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
6199 /* Just null environ and accept the leakage. */
6200 *environ = NULL;
6201# endif /* HAS_CLEARENV || HAS_UNSETENV */
6202# endif /* ! PERL_USE_SAFE_PUTENV */
6203 }
6204# endif /* USE_ENVIRON_ARRAY */
6205# endif /* PERL_IMPLICIT_SYS || WIN32 */
6206#endif /* PERL_MICRO */
6207}
6208
f16dd614
DM
6209#ifdef PERL_IMPLICIT_CONTEXT
6210
53d44271 6211/* Implements the MY_CXT_INIT macro. The first time a module is loaded,
f16dd614
DM
6212the global PL_my_cxt_index is incremented, and that value is assigned to
6213that module's static my_cxt_index (who's address is passed as an arg).
6214Then, for each interpreter this function is called for, it makes sure a
6215void* slot is available to hang the static data off, by allocating or
6216extending the interpreter's PL_my_cxt_list array */
6217
53d44271 6218#ifndef PERL_GLOBAL_STRUCT_PRIVATE
f16dd614
DM
6219void *
6220Perl_my_cxt_init(pTHX_ int *index, size_t size)
6221{
97aff369 6222 dVAR;
f16dd614 6223 void *p;
7918f24d 6224 PERL_ARGS_ASSERT_MY_CXT_INIT;
f16dd614
DM
6225 if (*index == -1) {
6226 /* this module hasn't been allocated an index yet */
8703a9a4 6227#if defined(USE_ITHREADS)
f16dd614 6228 MUTEX_LOCK(&PL_my_ctx_mutex);
8703a9a4 6229#endif
f16dd614 6230 *index = PL_my_cxt_index++;
8703a9a4 6231#if defined(USE_ITHREADS)
f16dd614 6232 MUTEX_UNLOCK(&PL_my_ctx_mutex);
8703a9a4 6233#endif
f16dd614
DM
6234 }
6235
6236 /* make sure the array is big enough */
4c901e72
DM
6237 if (PL_my_cxt_size <= *index) {
6238 if (PL_my_cxt_size) {
6239 while (PL_my_cxt_size <= *index)
f16dd614
DM
6240 PL_my_cxt_size *= 2;
6241 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6242 }
6243 else {
6244 PL_my_cxt_size = 16;
6245 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6246 }
6247 }
6248 /* newSV() allocates one more than needed */
6249 p = (void*)SvPVX(newSV(size-1));
6250 PL_my_cxt_list[*index] = p;
6251 Zero(p, size, char);
6252 return p;
6253}
53d44271
JH
6254
6255#else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6256
6257int
6258Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
6259{
6260 dVAR;
6261 int index;
6262
7918f24d
NC
6263 PERL_ARGS_ASSERT_MY_CXT_INDEX;
6264
53d44271
JH
6265 for (index = 0; index < PL_my_cxt_index; index++) {
6266 const char *key = PL_my_cxt_keys[index];
6267 /* try direct pointer compare first - there are chances to success,
6268 * and it's much faster.
6269 */
6270 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
6271 return index;
6272 }
6273 return -1;
6274}
6275
6276void *
6277Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
6278{
6279 dVAR;
6280 void *p;
6281 int index;
6282
7918f24d
NC
6283 PERL_ARGS_ASSERT_MY_CXT_INIT;
6284
53d44271
JH
6285 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
6286 if (index == -1) {
6287 /* this module hasn't been allocated an index yet */
8703a9a4 6288#if defined(USE_ITHREADS)
53d44271 6289 MUTEX_LOCK(&PL_my_ctx_mutex);
8703a9a4 6290#endif
53d44271 6291 index = PL_my_cxt_index++;
8703a9a4 6292#if defined(USE_ITHREADS)
53d44271 6293 MUTEX_UNLOCK(&PL_my_ctx_mutex);
8703a9a4 6294#endif
53d44271
JH
6295 }
6296
6297 /* make sure the array is big enough */
6298 if (PL_my_cxt_size <= index) {
6299 int old_size = PL_my_cxt_size;
6300 int i;
6301 if (PL_my_cxt_size) {
6302 while (PL_my_cxt_size <= index)
6303 PL_my_cxt_size *= 2;
6304 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
6305 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6306 }
6307 else {
6308 PL_my_cxt_size = 16;
6309 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
6310 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
6311 }
6312 for (i = old_size; i < PL_my_cxt_size; i++) {
6313 PL_my_cxt_keys[i] = 0;
6314 PL_my_cxt_list[i] = 0;
6315 }
6316 }
6317 PL_my_cxt_keys[index] = my_cxt_key;
6318 /* newSV() allocates one more than needed */
6319 p = (void*)SvPVX(newSV(size-1));
6320 PL_my_cxt_list[index] = p;
6321 Zero(p, size, char);
6322 return p;
6323}
6324#endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
6325#endif /* PERL_IMPLICIT_CONTEXT */
f16dd614 6326
e9b067d9
NC
6327void
6328Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
6329 STRLEN xs_len)
6330{
6331 SV *sv;
6332 const char *vn = NULL;
a2f871a2 6333 SV *const module = PL_stack_base[ax];
e9b067d9
NC
6334
6335 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
6336
6337 if (items >= 2) /* version supplied as bootstrap arg */
6338 sv = PL_stack_base[ax + 1];
6339 else {
6340 /* XXX GV_ADDWARN */
a2f871a2
NC
6341 vn = "XS_VERSION";
6342 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6343 if (!sv || !SvOK(sv)) {
6344 vn = "VERSION";
6345 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", module, vn), 0);
6346 }
e9b067d9
NC
6347 }
6348 if (sv) {
f9cc56fa 6349 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
e9b067d9 6350 SV *pmsv = sv_derived_from(sv, "version")
f9cc56fa 6351 ? sv : sv_2mortal(new_version(sv));
e9b067d9
NC
6352 xssv = upg_version(xssv, 0);
6353 if ( vcmp(pmsv,xssv) ) {
a2f871a2
NC
6354 SV *string = vstringify(xssv);
6355 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
6356 " does not match ", module, string);
6357
6358 SvREFCNT_dec(string);
6359 string = vstringify(pmsv);
6360
6361 if (vn) {
6362 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, module, vn,
6363 string);
6364 } else {
6365 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, string);
6366 }
6367 SvREFCNT_dec(string);
6368
e9b067d9 6369 Perl_sv_2mortal(aTHX_ xpt);
e9b067d9 6370 Perl_croak_sv(aTHX_ xpt);
f9cc56fa 6371 }
e9b067d9
NC
6372 }
6373}
6374
379a8907
NC
6375void
6376Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
6377 STRLEN api_len)
6378{
6379 SV *xpt = NULL;
8a280620
NC
6380 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
6381 SV *runver;
379a8907
NC
6382
6383 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
6384
8a280620 6385 /* This might croak */
379a8907 6386 compver = upg_version(compver, 0);
8a280620
NC
6387 /* This should never croak */
6388 runver = new_version(PL_apiversion);
379a8907 6389 if (vcmp(compver, runver)) {
8a280620
NC
6390 SV *compver_string = vstringify(compver);
6391 SV *runver_string = vstringify(runver);
379a8907 6392 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
8a280620
NC
6393 " of %"SVf" does not match %"SVf,
6394 compver_string, module, runver_string);
379a8907 6395 Perl_sv_2mortal(aTHX_ xpt);
8a280620
NC
6396
6397 SvREFCNT_dec(compver_string);
6398 SvREFCNT_dec(runver_string);
379a8907 6399 }
379a8907
NC
6400 SvREFCNT_dec(runver);
6401 if (xpt)
6402 Perl_croak_sv(aTHX_ xpt);
6403}
6404
a6cc4119
SP
6405#ifndef HAS_STRLCAT
6406Size_t
6407Perl_my_strlcat(char *dst, const char *src, Size_t size)
6408{
6409 Size_t used, length, copy;
6410
6411 used = strlen(dst);
6412 length = strlen(src);
6413 if (size > 0 && used < size - 1) {
6414 copy = (length >= size - used) ? size - used - 1 : length;
6415 memcpy(dst + used, src, copy);
6416 dst[used + copy] = '\0';
6417 }
6418 return used + length;
6419}
6420#endif
6421
6422#ifndef HAS_STRLCPY
6423Size_t
6424Perl_my_strlcpy(char *dst, const char *src, Size_t size)
6425{
6426 Size_t length, copy;
6427
6428 length = strlen(src);
6429 if (size > 0) {
6430 copy = (length >= size) ? size - 1 : length;
6431 memcpy(dst, src, copy);
6432 dst[copy] = '\0';
6433 }
6434 return length;
6435}
6436#endif
6437
17dd9954
JH
6438#if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
6439/* VC7 or 7.1, building with pre-VC7 runtime libraries. */
6440long _ftol( double ); /* Defined by VC6 C libs. */
6441long _ftol2( double dblSource ) { return _ftol( dblSource ); }
6442#endif
6443
c51f309c
NC
6444void
6445Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
6446{
6447 dVAR;
6448 SV * const dbsv = GvSVn(PL_DBsub);
07004ebb
DM
6449 const bool save_taint = PL_tainted;
6450
c51f309c
NC
6451 /* We do not care about using sv to call CV;
6452 * it's for informational purposes only.
6453 */
6454
7918f24d
NC
6455 PERL_ARGS_ASSERT_GET_DB_SUB;
6456
07004ebb 6457 PL_tainted = FALSE;
c51f309c
NC
6458 save_item(dbsv);
6459 if (!PERLDB_SUB_NN) {
be1cc451 6460 GV *gv = CvGV(cv);
c51f309c
NC
6461
6462 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
6463 || strEQ(GvNAME(gv), "END")
6464 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
159b6efe 6465 !( (SvTYPE(*svp) == SVt_PVGV)
be1cc451
FC
6466 && (GvCV((const GV *)*svp) == cv)
6467 && (gv = (GV *)*svp)
6468 )
6469 )
6470 )) {
c51f309c
NC
6471 /* Use GV from the stack as a fallback. */
6472 /* GV is potentially non-unique, or contain different CV. */
daba3364 6473 SV * const tmp = newRV(MUTABLE_SV(cv));
c51f309c
NC
6474 sv_setsv(dbsv, tmp);
6475 SvREFCNT_dec(tmp);
6476 }
6477 else {
6478 gv_efullname3(dbsv, gv, NULL);
6479 }
6480 }
6481 else {
6482 const int type = SvTYPE(dbsv);
6483 if (type < SVt_PVIV && type != SVt_IV)
6484 sv_upgrade(dbsv, SVt_PVIV);
6485 (void)SvIOK_on(dbsv);
6486 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
6487 }
07004ebb 6488 TAINT_IF(save_taint);
c51f309c
NC
6489}
6490
3497a01f 6491int
08ea85eb 6492Perl_my_dirfd(pTHX_ DIR * dir) {
3497a01f
SP
6493
6494 /* Most dirfd implementations have problems when passed NULL. */
6495 if(!dir)
6496 return -1;
6497#ifdef HAS_DIRFD
6498 return dirfd(dir);
6499#elif defined(HAS_DIR_DD_FD)
6500 return dir->dd_fd;
6501#else
6502 Perl_die(aTHX_ PL_no_func, "dirfd");
6503 /* NOT REACHED */
6504 return 0;
6505#endif
6506}
6507
f7e71195
AB
6508REGEXP *
6509Perl_get_re_arg(pTHX_ SV *sv) {
f7e71195
AB
6510
6511 if (sv) {
6512 if (SvMAGICAL(sv))
6513 mg_get(sv);
df052ff8
BM
6514 if (SvROK(sv))
6515 sv = MUTABLE_SV(SvRV(sv));
6516 if (SvTYPE(sv) == SVt_REGEXP)
6517 return (REGEXP*) sv;
f7e71195
AB
6518 }
6519
6520 return NULL;
6521}
6522
ce582cee 6523/*
66610fdd
RGS
6524 * Local variables:
6525 * c-indentation-style: bsd
6526 * c-basic-offset: 4
6527 * indent-tabs-mode: t
6528 * End:
6529 *
37442d52
RGS
6530 * ex: set ts=8 sts=4 sw=4 noet:
6531 */