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