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