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