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