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