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