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