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