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