This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #37946] preserve the referent associated with a shared RV.
[perl5.git] / util.c
... / ...
CommitLineData
1/* util.c
2 *
3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
5 *
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.
8 *
9 */
10
11/*
12 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content." --Gandalf
14 */
15
16/* This file contains assorted utility routines.
17 * Which is a polite way of saying any stuff that people couldn't think of
18 * a better place for. Amongst other things, it includes the warning and
19 * dieing stuff, plus wrappers for malloc code.
20 */
21
22#include "EXTERN.h"
23#define PERL_IN_UTIL_C
24#include "perl.h"
25
26#ifndef PERL_MICRO
27#include <signal.h>
28#ifndef SIG_ERR
29# define SIG_ERR ((Sighandler_t) -1)
30#endif
31#endif
32
33#ifdef __Lynx__
34/* Missing protos on LynxOS */
35int putenv(char *);
36#endif
37
38#ifdef I_SYS_WAIT
39# include <sys/wait.h>
40#endif
41
42#ifdef HAS_SELECT
43# ifdef I_SYS_SELECT
44# include <sys/select.h>
45# endif
46#endif
47
48#define FLUSH
49
50#if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51# define FD_CLOEXEC 1 /* NeXT needs this */
52#endif
53
54/* NOTE: Do not call the next three routines directly. Use the macros
55 * in handy.h, so that we can easily redefine everything to do tracking of
56 * allocated hunks back to the original New to track down any memory leaks.
57 * XXX This advice seems to be widely ignored :-( --AD August 1996.
58 */
59
60static char *
61S_write_no_mem(pTHX)
62{
63 dVAR;
64 /* Can't use PerlIO to write as it allocates memory */
65 PerlLIO_write(PerlIO_fileno(Perl_error_log),
66 PL_no_mem, strlen(PL_no_mem));
67 my_exit(1);
68 NORETURN_FUNCTION_END;
69}
70
71/* paranoid version of system's malloc() */
72
73Malloc_t
74Perl_safesysmalloc(MEM_SIZE size)
75{
76 dTHX;
77 Malloc_t ptr;
78#ifdef HAS_64K_LIMIT
79 if (size > 0xffff) {
80 PerlIO_printf(Perl_error_log,
81 "Allocation too large: %lx\n", size) FLUSH;
82 my_exit(1);
83 }
84#endif /* HAS_64K_LIMIT */
85#ifdef PERL_TRACK_MEMPOOL
86 size += sTHX;
87#endif
88#ifdef DEBUGGING
89 if ((long)size < 0)
90 Perl_croak_nocontext("panic: malloc");
91#endif
92 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
93 PERL_ALLOC_CHECK(ptr);
94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
95 if (ptr != Nullch) {
96#ifdef PERL_TRACK_MEMPOOL
97 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
98# ifdef PERL_POISON
99 ((struct perl_memory_debug_header *)ptr)->size = size;
100 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
101# endif
102 ptr = (Malloc_t)((char*)ptr+sTHX);
103#endif
104 return ptr;
105}
106 else if (PL_nomemok)
107 return Nullch;
108 else {
109 return write_no_mem();
110 }
111 /*NOTREACHED*/
112}
113
114/* paranoid version of system's realloc() */
115
116Malloc_t
117Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
118{
119 dTHX;
120 Malloc_t ptr;
121#if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
122 Malloc_t PerlMem_realloc();
123#endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
124
125#ifdef HAS_64K_LIMIT
126 if (size > 0xffff) {
127 PerlIO_printf(Perl_error_log,
128 "Reallocation too large: %lx\n", size) FLUSH;
129 my_exit(1);
130 }
131#endif /* HAS_64K_LIMIT */
132 if (!size) {
133 safesysfree(where);
134 return NULL;
135 }
136
137 if (!where)
138 return safesysmalloc(size);
139#ifdef PERL_TRACK_MEMPOOL
140 where = (Malloc_t)((char*)where-sTHX);
141 size += sTHX;
142 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
143 Perl_croak_nocontext("panic: realloc from wrong pool");
144 }
145# ifdef PERL_POISON
146 if (((struct perl_memory_debug_header *)where)->size > size) {
147 const MEM_SIZE freed_up =
148 ((struct perl_memory_debug_header *)where)->size - size;
149 char *start_of_freed = ((char *)where) + size;
150 Poison(start_of_freed, freed_up, char);
151 }
152 ((struct perl_memory_debug_header *)where)->size = size;
153# endif
154#endif
155#ifdef DEBUGGING
156 if ((long)size < 0)
157 Perl_croak_nocontext("panic: realloc");
158#endif
159 ptr = (Malloc_t)PerlMem_realloc(where,size);
160 PERL_ALLOC_CHECK(ptr);
161
162 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
163 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
164
165 if (ptr != Nullch) {
166#ifdef PERL_TRACK_MEMPOOL
167 ptr = (Malloc_t)((char*)ptr+sTHX);
168#endif
169 return ptr;
170 }
171 else if (PL_nomemok)
172 return Nullch;
173 else {
174 return write_no_mem();
175 }
176 /*NOTREACHED*/
177}
178
179/* safe version of system's free() */
180
181Free_t
182Perl_safesysfree(Malloc_t where)
183{
184#if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
185 dTHX;
186#else
187 dVAR;
188#endif
189 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
190 if (where) {
191#ifdef PERL_TRACK_MEMPOOL
192 where = (Malloc_t)((char*)where-sTHX);
193 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
194 Perl_croak_nocontext("panic: free from wrong pool");
195 }
196# ifdef PERL_POISON
197 {
198 if (((struct perl_memory_debug_header *)where)->in_use
199 == PERL_POISON_FREE) {
200 Perl_croak_nocontext("panic: duplicate free");
201 }
202 if (((struct perl_memory_debug_header *)where)->in_use
203 != PERL_POISON_INUSE) {
204 Perl_croak_nocontext("panic: bad free ");
205 }
206 ((struct perl_memory_debug_header *)where)->in_use
207 = PERL_POISON_FREE;
208 }
209 Poison(where, ((struct perl_memory_debug_header *)where)->size, char);
210# endif
211#endif
212 PerlMem_free(where);
213 }
214}
215
216/* safe version of system's calloc() */
217
218Malloc_t
219Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
220{
221 dTHX;
222 Malloc_t ptr;
223
224#ifdef HAS_64K_LIMIT
225 if (size * count > 0xffff) {
226 PerlIO_printf(Perl_error_log,
227 "Allocation too large: %lx\n", size * count) FLUSH;
228 my_exit(1);
229 }
230#endif /* HAS_64K_LIMIT */
231#ifdef DEBUGGING
232 if ((long)size < 0 || (long)count < 0)
233 Perl_croak_nocontext("panic: calloc");
234#endif
235 size *= count;
236#ifdef PERL_TRACK_MEMPOOL
237 size += sTHX;
238#endif
239 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
240 PERL_ALLOC_CHECK(ptr);
241 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
242 if (ptr != Nullch) {
243 memset((void*)ptr, 0, size);
244#ifdef PERL_TRACK_MEMPOOL
245 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
246# ifdef PERL_POISON
247 ((struct perl_memory_debug_header *)ptr)->size = size;
248 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
249# endif
250 ptr = (Malloc_t)((char*)ptr+sTHX);
251#endif
252 return ptr;
253 }
254 else if (PL_nomemok)
255 return Nullch;
256 return write_no_mem();
257}
258
259/* These must be defined when not using Perl's malloc for binary
260 * compatibility */
261
262#ifndef MYMALLOC
263
264Malloc_t Perl_malloc (MEM_SIZE nbytes)
265{
266 dTHXs;
267 return (Malloc_t)PerlMem_malloc(nbytes);
268}
269
270Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
271{
272 dTHXs;
273 return (Malloc_t)PerlMem_calloc(elements, size);
274}
275
276Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
277{
278 dTHXs;
279 return (Malloc_t)PerlMem_realloc(where, nbytes);
280}
281
282Free_t Perl_mfree (Malloc_t where)
283{
284 dTHXs;
285 PerlMem_free(where);
286}
287
288#endif
289
290/* copy a string up to some (non-backslashed) delimiter, if any */
291
292char *
293Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
294{
295 register I32 tolen;
296 for (tolen = 0; from < fromend; from++, tolen++) {
297 if (*from == '\\') {
298 if (from[1] == delim)
299 from++;
300 else {
301 if (to < toend)
302 *to++ = *from;
303 tolen++;
304 from++;
305 }
306 }
307 else if (*from == delim)
308 break;
309 if (to < toend)
310 *to++ = *from;
311 }
312 if (to < toend)
313 *to = '\0';
314 *retlen = tolen;
315 return (char *)from;
316}
317
318/* return ptr to little string in big string, NULL if not found */
319/* This routine was donated by Corey Satten. */
320
321char *
322Perl_instr(pTHX_ register const char *big, register const char *little)
323{
324 register I32 first;
325
326 if (!little)
327 return (char*)big;
328 first = *little++;
329 if (!first)
330 return (char*)big;
331 while (*big) {
332 register const char *s, *x;
333 if (*big++ != first)
334 continue;
335 for (x=big,s=little; *s; /**/ ) {
336 if (!*x)
337 return Nullch;
338 if (*s != *x)
339 break;
340 else {
341 s++;
342 x++;
343 }
344 }
345 if (!*s)
346 return (char*)(big-1);
347 }
348 return Nullch;
349}
350
351/* same as instr but allow embedded nulls */
352
353char *
354Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
355{
356 if (little >= lend)
357 return (char*)big;
358 {
359 char first = *little++;
360 const char *s, *x;
361 bigend -= lend - little;
362 OUTER:
363 while (big <= bigend) {
364 if (*big++ != first)
365 goto OUTER;
366 for (x=big,s=little; s < lend; x++,s++) {
367 if (*s != *x)
368 goto OUTER;
369 }
370 return (char*)(big-1);
371 }
372 }
373 return Nullch;
374}
375
376/* reverse of the above--find last substring */
377
378char *
379Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
380{
381 register const char *bigbeg;
382 register const I32 first = *little;
383 register const char * const littleend = lend;
384
385 if (little >= littleend)
386 return (char*)bigend;
387 bigbeg = big;
388 big = bigend - (littleend - little++);
389 while (big >= bigbeg) {
390 register const char *s, *x;
391 if (*big-- != first)
392 continue;
393 for (x=big+2,s=little; s < littleend; /**/ ) {
394 if (*s != *x)
395 break;
396 else {
397 x++;
398 s++;
399 }
400 }
401 if (s >= littleend)
402 return (char*)(big+1);
403 }
404 return Nullch;
405}
406
407#define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
408
409/* As a space optimization, we do not compile tables for strings of length
410 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
411 special-cased in fbm_instr().
412
413 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
414
415/*
416=head1 Miscellaneous Functions
417
418=for apidoc fbm_compile
419
420Analyses the string in order to make fast searches on it using fbm_instr()
421-- the Boyer-Moore algorithm.
422
423=cut
424*/
425
426void
427Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
428{
429 dVAR;
430 register const U8 *s;
431 register U32 i;
432 STRLEN len;
433 I32 rarest = 0;
434 U32 frequency = 256;
435
436 if (flags & FBMcf_TAIL) {
437 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
438 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
439 if (mg && mg->mg_len >= 0)
440 mg->mg_len++;
441 }
442 s = (U8*)SvPV_force_mutable(sv, len);
443 SvUPGRADE(sv, SVt_PVBM);
444 if (len == 0) /* TAIL might be on a zero-length string. */
445 return;
446 if (len > 2) {
447 const unsigned char *sb;
448 const U8 mlen = (len>255) ? 255 : (U8)len;
449 register U8 *table;
450
451 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
452 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
453 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
454 memset((void*)table, mlen, 256);
455 table[-1] = (U8)flags;
456 i = 0;
457 sb = s - mlen + 1; /* first char (maybe) */
458 while (s >= sb) {
459 if (table[*s] == mlen)
460 table[*s] = (U8)i;
461 s--, i++;
462 }
463 }
464 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
465 SvVALID_on(sv);
466
467 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
468 for (i = 0; i < len; i++) {
469 if (PL_freq[s[i]] < frequency) {
470 rarest = i;
471 frequency = PL_freq[s[i]];
472 }
473 }
474 BmRARE(sv) = s[rarest];
475 BmPREVIOUS(sv) = (U16)rarest;
476 BmUSEFUL(sv) = 100; /* Initial value */
477 if (flags & FBMcf_TAIL)
478 SvTAIL_on(sv);
479 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
480 BmRARE(sv),BmPREVIOUS(sv)));
481}
482
483/* If SvTAIL(littlestr), it has a fake '\n' at end. */
484/* If SvTAIL is actually due to \Z or \z, this gives false positives
485 if multiline */
486
487/*
488=for apidoc fbm_instr
489
490Returns the location of the SV in the string delimited by C<str> and
491C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
492does not have to be fbm_compiled, but the search will not be as fast
493then.
494
495=cut
496*/
497
498char *
499Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
500{
501 register unsigned char *s;
502 STRLEN l;
503 register const unsigned char *little
504 = (const unsigned char *)SvPV_const(littlestr,l);
505 register STRLEN littlelen = l;
506 register const I32 multiline = flags & FBMrf_MULTILINE;
507
508 if ((STRLEN)(bigend - big) < littlelen) {
509 if ( SvTAIL(littlestr)
510 && ((STRLEN)(bigend - big) == littlelen - 1)
511 && (littlelen == 1
512 || (*big == *little &&
513 memEQ((char *)big, (char *)little, littlelen - 1))))
514 return (char*)big;
515 return Nullch;
516 }
517
518 if (littlelen <= 2) { /* Special-cased */
519
520 if (littlelen == 1) {
521 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
522 /* Know that bigend != big. */
523 if (bigend[-1] == '\n')
524 return (char *)(bigend - 1);
525 return (char *) bigend;
526 }
527 s = big;
528 while (s < bigend) {
529 if (*s == *little)
530 return (char *)s;
531 s++;
532 }
533 if (SvTAIL(littlestr))
534 return (char *) bigend;
535 return Nullch;
536 }
537 if (!littlelen)
538 return (char*)big; /* Cannot be SvTAIL! */
539
540 /* littlelen is 2 */
541 if (SvTAIL(littlestr) && !multiline) {
542 if (bigend[-1] == '\n' && bigend[-2] == *little)
543 return (char*)bigend - 2;
544 if (bigend[-1] == *little)
545 return (char*)bigend - 1;
546 return Nullch;
547 }
548 {
549 /* This should be better than FBM if c1 == c2, and almost
550 as good otherwise: maybe better since we do less indirection.
551 And we save a lot of memory by caching no table. */
552 const unsigned char c1 = little[0];
553 const unsigned char c2 = little[1];
554
555 s = big + 1;
556 bigend--;
557 if (c1 != c2) {
558 while (s <= bigend) {
559 if (s[0] == c2) {
560 if (s[-1] == c1)
561 return (char*)s - 1;
562 s += 2;
563 continue;
564 }
565 next_chars:
566 if (s[0] == c1) {
567 if (s == bigend)
568 goto check_1char_anchor;
569 if (s[1] == c2)
570 return (char*)s;
571 else {
572 s++;
573 goto next_chars;
574 }
575 }
576 else
577 s += 2;
578 }
579 goto check_1char_anchor;
580 }
581 /* Now c1 == c2 */
582 while (s <= bigend) {
583 if (s[0] == c1) {
584 if (s[-1] == c1)
585 return (char*)s - 1;
586 if (s == bigend)
587 goto check_1char_anchor;
588 if (s[1] == c1)
589 return (char*)s;
590 s += 3;
591 }
592 else
593 s += 2;
594 }
595 }
596 check_1char_anchor: /* One char and anchor! */
597 if (SvTAIL(littlestr) && (*bigend == *little))
598 return (char *)bigend; /* bigend is already decremented. */
599 return Nullch;
600 }
601 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
602 s = bigend - littlelen;
603 if (s >= big && bigend[-1] == '\n' && *s == *little
604 /* Automatically of length > 2 */
605 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
606 {
607 return (char*)s; /* how sweet it is */
608 }
609 if (s[1] == *little
610 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
611 {
612 return (char*)s + 1; /* how sweet it is */
613 }
614 return Nullch;
615 }
616 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
617 char * const b = ninstr((char*)big,(char*)bigend,
618 (char*)little, (char*)little + littlelen);
619
620 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
621 /* Chop \n from littlestr: */
622 s = bigend - littlelen + 1;
623 if (*s == *little
624 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
625 {
626 return (char*)s;
627 }
628 return Nullch;
629 }
630 return b;
631 }
632
633 { /* Do actual FBM. */
634 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
635 register const unsigned char *oldlittle;
636
637 if (littlelen > (STRLEN)(bigend - big))
638 return Nullch;
639 --littlelen; /* Last char found by table lookup */
640
641 s = big + littlelen;
642 little += littlelen; /* last char */
643 oldlittle = little;
644 if (s < bigend) {
645 register I32 tmp;
646
647 top2:
648 if ((tmp = table[*s])) {
649 if ((s += tmp) < bigend)
650 goto top2;
651 goto check_end;
652 }
653 else { /* less expensive than calling strncmp() */
654 register unsigned char * const olds = s;
655
656 tmp = littlelen;
657
658 while (tmp--) {
659 if (*--s == *--little)
660 continue;
661 s = olds + 1; /* here we pay the price for failure */
662 little = oldlittle;
663 if (s < bigend) /* fake up continue to outer loop */
664 goto top2;
665 goto check_end;
666 }
667 return (char *)s;
668 }
669 }
670 check_end:
671 if ( s == bigend && (table[-1] & FBMcf_TAIL)
672 && memEQ((char *)(bigend - littlelen),
673 (char *)(oldlittle - littlelen), littlelen) )
674 return (char*)bigend - littlelen;
675 return Nullch;
676 }
677}
678
679/* start_shift, end_shift are positive quantities which give offsets
680 of ends of some substring of bigstr.
681 If "last" we want the last occurrence.
682 old_posp is the way of communication between consequent calls if
683 the next call needs to find the .
684 The initial *old_posp should be -1.
685
686 Note that we take into account SvTAIL, so one can get extra
687 optimizations if _ALL flag is set.
688 */
689
690/* If SvTAIL is actually due to \Z or \z, this gives false positives
691 if PL_multiline. In fact if !PL_multiline the authoritative answer
692 is not supported yet. */
693
694char *
695Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
696{
697 dVAR;
698 register const unsigned char *big;
699 register I32 pos;
700 register I32 previous;
701 register I32 first;
702 register const unsigned char *little;
703 register I32 stop_pos;
704 register const unsigned char *littleend;
705 I32 found = 0;
706
707 if (*old_posp == -1
708 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
709 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
710 cant_find:
711 if ( BmRARE(littlestr) == '\n'
712 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
713 little = (const unsigned char *)(SvPVX_const(littlestr));
714 littleend = little + SvCUR(littlestr);
715 first = *little++;
716 goto check_tail;
717 }
718 return Nullch;
719 }
720
721 little = (const unsigned char *)(SvPVX_const(littlestr));
722 littleend = little + SvCUR(littlestr);
723 first = *little++;
724 /* The value of pos we can start at: */
725 previous = BmPREVIOUS(littlestr);
726 big = (const unsigned char *)(SvPVX_const(bigstr));
727 /* The value of pos we can stop at: */
728 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
729 if (previous + start_shift > stop_pos) {
730/*
731 stop_pos does not include SvTAIL in the count, so this check is incorrect
732 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
733*/
734#if 0
735 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
736 goto check_tail;
737#endif
738 return Nullch;
739 }
740 while (pos < previous + start_shift) {
741 if (!(pos += PL_screamnext[pos]))
742 goto cant_find;
743 }
744 big -= previous;
745 do {
746 register const unsigned char *s, *x;
747 if (pos >= stop_pos) break;
748 if (big[pos] != first)
749 continue;
750 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
751 if (*s++ != *x++) {
752 s--;
753 break;
754 }
755 }
756 if (s == littleend) {
757 *old_posp = pos;
758 if (!last) return (char *)(big+pos);
759 found = 1;
760 }
761 } while ( pos += PL_screamnext[pos] );
762 if (last && found)
763 return (char *)(big+(*old_posp));
764 check_tail:
765 if (!SvTAIL(littlestr) || (end_shift > 0))
766 return Nullch;
767 /* Ignore the trailing "\n". This code is not microoptimized */
768 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
769 stop_pos = littleend - little; /* Actual littlestr len */
770 if (stop_pos == 0)
771 return (char*)big;
772 big -= stop_pos;
773 if (*big == first
774 && ((stop_pos == 1) ||
775 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
776 return (char*)big;
777 return Nullch;
778}
779
780I32
781Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
782{
783 register const U8 *a = (const U8 *)s1;
784 register const U8 *b = (const U8 *)s2;
785 while (len--) {
786 if (*a != *b && *a != PL_fold[*b])
787 return 1;
788 a++,b++;
789 }
790 return 0;
791}
792
793I32
794Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
795{
796 dVAR;
797 register const U8 *a = (const U8 *)s1;
798 register const U8 *b = (const U8 *)s2;
799 while (len--) {
800 if (*a != *b && *a != PL_fold_locale[*b])
801 return 1;
802 a++,b++;
803 }
804 return 0;
805}
806
807/* copy a string to a safe spot */
808
809/*
810=head1 Memory Management
811
812=for apidoc savepv
813
814Perl's version of C<strdup()>. Returns a pointer to a newly allocated
815string which is a duplicate of C<pv>. The size of the string is
816determined by C<strlen()>. The memory allocated for the new string can
817be freed with the C<Safefree()> function.
818
819=cut
820*/
821
822char *
823Perl_savepv(pTHX_ const char *pv)
824{
825 if (!pv)
826 return Nullch;
827 else {
828 char *newaddr;
829 const STRLEN pvlen = strlen(pv)+1;
830 Newx(newaddr,pvlen,char);
831 return memcpy(newaddr,pv,pvlen);
832 }
833
834}
835
836/* same thing but with a known length */
837
838/*
839=for apidoc savepvn
840
841Perl's version of what C<strndup()> would be if it existed. Returns a
842pointer to a newly allocated string which is a duplicate of the first
843C<len> bytes from C<pv>. The memory allocated for the new string can be
844freed with the C<Safefree()> function.
845
846=cut
847*/
848
849char *
850Perl_savepvn(pTHX_ const char *pv, register I32 len)
851{
852 register char *newaddr;
853
854 Newx(newaddr,len+1,char);
855 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
856 if (pv) {
857 /* might not be null terminated */
858 newaddr[len] = '\0';
859 return (char *) CopyD(pv,newaddr,len,char);
860 }
861 else {
862 return (char *) ZeroD(newaddr,len+1,char);
863 }
864}
865
866/*
867=for apidoc savesharedpv
868
869A version of C<savepv()> which allocates the duplicate string in memory
870which is shared between threads.
871
872=cut
873*/
874char *
875Perl_savesharedpv(pTHX_ const char *pv)
876{
877 register char *newaddr;
878 STRLEN pvlen;
879 if (!pv)
880 return Nullch;
881
882 pvlen = strlen(pv)+1;
883 newaddr = (char*)PerlMemShared_malloc(pvlen);
884 if (!newaddr) {
885 return write_no_mem();
886 }
887 return memcpy(newaddr,pv,pvlen);
888}
889
890/*
891=for apidoc savesvpv
892
893A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
894the passed in SV using C<SvPV()>
895
896=cut
897*/
898
899char *
900Perl_savesvpv(pTHX_ SV *sv)
901{
902 STRLEN len;
903 const char * const pv = SvPV_const(sv, len);
904 register char *newaddr;
905
906 ++len;
907 Newx(newaddr,len,char);
908 return (char *) CopyD(pv,newaddr,len,char);
909}
910
911
912/* the SV for Perl_form() and mess() is not kept in an arena */
913
914STATIC SV *
915S_mess_alloc(pTHX)
916{
917 dVAR;
918 SV *sv;
919 XPVMG *any;
920
921 if (!PL_dirty)
922 return sv_2mortal(newSVpvs(""));
923
924 if (PL_mess_sv)
925 return PL_mess_sv;
926
927 /* Create as PVMG now, to avoid any upgrading later */
928 Newx(sv, 1, SV);
929 Newxz(any, 1, XPVMG);
930 SvFLAGS(sv) = SVt_PVMG;
931 SvANY(sv) = (void*)any;
932 SvPV_set(sv, 0);
933 SvREFCNT(sv) = 1 << 30; /* practically infinite */
934 PL_mess_sv = sv;
935 return sv;
936}
937
938#if defined(PERL_IMPLICIT_CONTEXT)
939char *
940Perl_form_nocontext(const char* pat, ...)
941{
942 dTHX;
943 char *retval;
944 va_list args;
945 va_start(args, pat);
946 retval = vform(pat, &args);
947 va_end(args);
948 return retval;
949}
950#endif /* PERL_IMPLICIT_CONTEXT */
951
952/*
953=head1 Miscellaneous Functions
954=for apidoc form
955
956Takes a sprintf-style format pattern and conventional
957(non-SV) arguments and returns the formatted string.
958
959 (char *) Perl_form(pTHX_ const char* pat, ...)
960
961can be used any place a string (char *) is required:
962
963 char * s = Perl_form("%d.%d",major,minor);
964
965Uses a single private buffer so if you want to format several strings you
966must explicitly copy the earlier strings away (and free the copies when you
967are done).
968
969=cut
970*/
971
972char *
973Perl_form(pTHX_ const char* pat, ...)
974{
975 char *retval;
976 va_list args;
977 va_start(args, pat);
978 retval = vform(pat, &args);
979 va_end(args);
980 return retval;
981}
982
983char *
984Perl_vform(pTHX_ const char *pat, va_list *args)
985{
986 SV * const sv = mess_alloc();
987 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
988 return SvPVX(sv);
989}
990
991#if defined(PERL_IMPLICIT_CONTEXT)
992SV *
993Perl_mess_nocontext(const char *pat, ...)
994{
995 dTHX;
996 SV *retval;
997 va_list args;
998 va_start(args, pat);
999 retval = vmess(pat, &args);
1000 va_end(args);
1001 return retval;
1002}
1003#endif /* PERL_IMPLICIT_CONTEXT */
1004
1005SV *
1006Perl_mess(pTHX_ const char *pat, ...)
1007{
1008 SV *retval;
1009 va_list args;
1010 va_start(args, pat);
1011 retval = vmess(pat, &args);
1012 va_end(args);
1013 return retval;
1014}
1015
1016STATIC COP*
1017S_closest_cop(pTHX_ COP *cop, const OP *o)
1018{
1019 dVAR;
1020 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1021
1022 if (!o || o == PL_op)
1023 return cop;
1024
1025 if (o->op_flags & OPf_KIDS) {
1026 OP *kid;
1027 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1028 COP *new_cop;
1029
1030 /* If the OP_NEXTSTATE has been optimised away we can still use it
1031 * the get the file and line number. */
1032
1033 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1034 cop = (COP *)kid;
1035
1036 /* Keep searching, and return when we've found something. */
1037
1038 new_cop = closest_cop(cop, kid);
1039 if (new_cop)
1040 return new_cop;
1041 }
1042 }
1043
1044 /* Nothing found. */
1045
1046 return Null(COP *);
1047}
1048
1049SV *
1050Perl_vmess(pTHX_ const char *pat, va_list *args)
1051{
1052 dVAR;
1053 SV * const sv = mess_alloc();
1054 static const char dgd[] = " during global destruction.\n";
1055
1056 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1057 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1058
1059 /*
1060 * Try and find the file and line for PL_op. This will usually be
1061 * PL_curcop, but it might be a cop that has been optimised away. We
1062 * can try to find such a cop by searching through the optree starting
1063 * from the sibling of PL_curcop.
1064 */
1065
1066 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1067 if (!cop) cop = PL_curcop;
1068
1069 if (CopLINE(cop))
1070 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1071 OutCopFILE(cop), (IV)CopLINE(cop));
1072 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1073 const bool line_mode = (RsSIMPLE(PL_rs) &&
1074 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1075 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1076 PL_last_in_gv == PL_argvgv ?
1077 "" : GvNAME(PL_last_in_gv),
1078 line_mode ? "line" : "chunk",
1079 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1080 }
1081 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1082 }
1083 return sv;
1084}
1085
1086void
1087Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1088{
1089 dVAR;
1090 IO *io;
1091 MAGIC *mg;
1092
1093 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1094 && (io = GvIO(PL_stderrgv))
1095 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1096 {
1097 dSP;
1098 ENTER;
1099 SAVETMPS;
1100
1101 save_re_context();
1102 SAVESPTR(PL_stderrgv);
1103 PL_stderrgv = Nullgv;
1104
1105 PUSHSTACKi(PERLSI_MAGIC);
1106
1107 PUSHMARK(SP);
1108 EXTEND(SP,2);
1109 PUSHs(SvTIED_obj((SV*)io, mg));
1110 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1111 PUTBACK;
1112 call_method("PRINT", G_SCALAR);
1113
1114 POPSTACK;
1115 FREETMPS;
1116 LEAVE;
1117 }
1118 else {
1119#ifdef USE_SFIO
1120 /* SFIO can really mess with your errno */
1121 const int e = errno;
1122#endif
1123 PerlIO * const serr = Perl_error_log;
1124
1125 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1126 (void)PerlIO_flush(serr);
1127#ifdef USE_SFIO
1128 errno = e;
1129#endif
1130 }
1131}
1132
1133/* Common code used by vcroak, vdie and vwarner */
1134
1135STATIC void
1136S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1137{
1138 dVAR;
1139 HV *stash;
1140 GV *gv;
1141 CV *cv;
1142 /* sv_2cv might call Perl_croak() */
1143 SV * const olddiehook = PL_diehook;
1144
1145 assert(PL_diehook);
1146 ENTER;
1147 SAVESPTR(PL_diehook);
1148 PL_diehook = Nullsv;
1149 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1150 LEAVE;
1151 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1152 dSP;
1153 SV *msg;
1154
1155 ENTER;
1156 save_re_context();
1157 if (message) {
1158 msg = newSVpvn(message, msglen);
1159 SvFLAGS(msg) |= utf8;
1160 SvREADONLY_on(msg);
1161 SAVEFREESV(msg);
1162 }
1163 else {
1164 msg = ERRSV;
1165 }
1166
1167 PUSHSTACKi(PERLSI_DIEHOOK);
1168 PUSHMARK(SP);
1169 XPUSHs(msg);
1170 PUTBACK;
1171 call_sv((SV*)cv, G_DISCARD);
1172 POPSTACK;
1173 LEAVE;
1174 }
1175}
1176
1177STATIC const char *
1178S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1179 I32* utf8)
1180{
1181 dVAR;
1182 const char *message;
1183
1184 if (pat) {
1185 SV * const msv = vmess(pat, args);
1186 if (PL_errors && SvCUR(PL_errors)) {
1187 sv_catsv(PL_errors, msv);
1188 message = SvPV_const(PL_errors, *msglen);
1189 SvCUR_set(PL_errors, 0);
1190 }
1191 else
1192 message = SvPV_const(msv,*msglen);
1193 *utf8 = SvUTF8(msv);
1194 }
1195 else {
1196 message = Nullch;
1197 }
1198
1199 DEBUG_S(PerlIO_printf(Perl_debug_log,
1200 "%p: die/croak: message = %s\ndiehook = %p\n",
1201 thr, message, PL_diehook));
1202 if (PL_diehook) {
1203 S_vdie_common(aTHX_ message, *msglen, *utf8);
1204 }
1205 return message;
1206}
1207
1208OP *
1209Perl_vdie(pTHX_ const char* pat, va_list *args)
1210{
1211 dVAR;
1212 const char *message;
1213 const int was_in_eval = PL_in_eval;
1214 STRLEN msglen;
1215 I32 utf8 = 0;
1216
1217 DEBUG_S(PerlIO_printf(Perl_debug_log,
1218 "%p: die: curstack = %p, mainstack = %p\n",
1219 thr, PL_curstack, PL_mainstack));
1220
1221 message = vdie_croak_common(pat, args, &msglen, &utf8);
1222
1223 PL_restartop = die_where(message, msglen);
1224 SvFLAGS(ERRSV) |= utf8;
1225 DEBUG_S(PerlIO_printf(Perl_debug_log,
1226 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1227 thr, PL_restartop, was_in_eval, PL_top_env));
1228 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1229 JMPENV_JUMP(3);
1230 return PL_restartop;
1231}
1232
1233#if defined(PERL_IMPLICIT_CONTEXT)
1234OP *
1235Perl_die_nocontext(const char* pat, ...)
1236{
1237 dTHX;
1238 OP *o;
1239 va_list args;
1240 va_start(args, pat);
1241 o = vdie(pat, &args);
1242 va_end(args);
1243 return o;
1244}
1245#endif /* PERL_IMPLICIT_CONTEXT */
1246
1247OP *
1248Perl_die(pTHX_ const char* pat, ...)
1249{
1250 OP *o;
1251 va_list args;
1252 va_start(args, pat);
1253 o = vdie(pat, &args);
1254 va_end(args);
1255 return o;
1256}
1257
1258void
1259Perl_vcroak(pTHX_ const char* pat, va_list *args)
1260{
1261 dVAR;
1262 const char *message;
1263 STRLEN msglen;
1264 I32 utf8 = 0;
1265
1266 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1267
1268 if (PL_in_eval) {
1269 PL_restartop = die_where(message, msglen);
1270 SvFLAGS(ERRSV) |= utf8;
1271 JMPENV_JUMP(3);
1272 }
1273 else if (!message)
1274 message = SvPVx_const(ERRSV, msglen);
1275
1276 write_to_stderr(message, msglen);
1277 my_failure_exit();
1278}
1279
1280#if defined(PERL_IMPLICIT_CONTEXT)
1281void
1282Perl_croak_nocontext(const char *pat, ...)
1283{
1284 dTHX;
1285 va_list args;
1286 va_start(args, pat);
1287 vcroak(pat, &args);
1288 /* NOTREACHED */
1289 va_end(args);
1290}
1291#endif /* PERL_IMPLICIT_CONTEXT */
1292
1293/*
1294=head1 Warning and Dieing
1295
1296=for apidoc croak
1297
1298This is the XSUB-writer's interface to Perl's C<die> function.
1299Normally call this function the same way you call the C C<printf>
1300function. Calling C<croak> returns control directly to Perl,
1301sidestepping the normal C order of execution. See C<warn>.
1302
1303If you want to throw an exception object, assign the object to
1304C<$@> and then pass C<Nullch> to croak():
1305
1306 errsv = get_sv("@", TRUE);
1307 sv_setsv(errsv, exception_object);
1308 croak(Nullch);
1309
1310=cut
1311*/
1312
1313void
1314Perl_croak(pTHX_ const char *pat, ...)
1315{
1316 va_list args;
1317 va_start(args, pat);
1318 vcroak(pat, &args);
1319 /* NOTREACHED */
1320 va_end(args);
1321}
1322
1323void
1324Perl_vwarn(pTHX_ const char* pat, va_list *args)
1325{
1326 dVAR;
1327 STRLEN msglen;
1328 SV * const msv = vmess(pat, args);
1329 const I32 utf8 = SvUTF8(msv);
1330 const char * const message = SvPV_const(msv, msglen);
1331
1332 if (PL_warnhook) {
1333 /* sv_2cv might call Perl_warn() */
1334 SV * const oldwarnhook = PL_warnhook;
1335 CV * cv;
1336 HV * stash;
1337 GV * gv;
1338
1339 ENTER;
1340 SAVESPTR(PL_warnhook);
1341 PL_warnhook = Nullsv;
1342 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1343 LEAVE;
1344 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1345 dSP;
1346 SV *msg;
1347
1348 ENTER;
1349 SAVESPTR(PL_warnhook);
1350 PL_warnhook = Nullsv;
1351 save_re_context();
1352 msg = newSVpvn(message, msglen);
1353 SvFLAGS(msg) |= utf8;
1354 SvREADONLY_on(msg);
1355 SAVEFREESV(msg);
1356
1357 PUSHSTACKi(PERLSI_WARNHOOK);
1358 PUSHMARK(SP);
1359 XPUSHs(msg);
1360 PUTBACK;
1361 call_sv((SV*)cv, G_DISCARD);
1362 POPSTACK;
1363 LEAVE;
1364 return;
1365 }
1366 }
1367
1368 write_to_stderr(message, msglen);
1369}
1370
1371#if defined(PERL_IMPLICIT_CONTEXT)
1372void
1373Perl_warn_nocontext(const char *pat, ...)
1374{
1375 dTHX;
1376 va_list args;
1377 va_start(args, pat);
1378 vwarn(pat, &args);
1379 va_end(args);
1380}
1381#endif /* PERL_IMPLICIT_CONTEXT */
1382
1383/*
1384=for apidoc warn
1385
1386This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1387function the same way you call the C C<printf> function. See C<croak>.
1388
1389=cut
1390*/
1391
1392void
1393Perl_warn(pTHX_ const char *pat, ...)
1394{
1395 va_list args;
1396 va_start(args, pat);
1397 vwarn(pat, &args);
1398 va_end(args);
1399}
1400
1401#if defined(PERL_IMPLICIT_CONTEXT)
1402void
1403Perl_warner_nocontext(U32 err, const char *pat, ...)
1404{
1405 dTHX;
1406 va_list args;
1407 va_start(args, pat);
1408 vwarner(err, pat, &args);
1409 va_end(args);
1410}
1411#endif /* PERL_IMPLICIT_CONTEXT */
1412
1413void
1414Perl_warner(pTHX_ U32 err, const char* pat,...)
1415{
1416 va_list args;
1417 va_start(args, pat);
1418 vwarner(err, pat, &args);
1419 va_end(args);
1420}
1421
1422void
1423Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1424{
1425 dVAR;
1426 if (ckDEAD(err)) {
1427 SV * const msv = vmess(pat, args);
1428 STRLEN msglen;
1429 const char * const message = SvPV_const(msv, msglen);
1430 const I32 utf8 = SvUTF8(msv);
1431
1432 if (PL_diehook) {
1433 assert(message);
1434 S_vdie_common(aTHX_ message, msglen, utf8);
1435 }
1436 if (PL_in_eval) {
1437 PL_restartop = die_where(message, msglen);
1438 SvFLAGS(ERRSV) |= utf8;
1439 JMPENV_JUMP(3);
1440 }
1441 write_to_stderr(message, msglen);
1442 my_failure_exit();
1443 }
1444 else {
1445 Perl_vwarn(aTHX_ pat, args);
1446 }
1447}
1448
1449/* implements the ckWARN? macros */
1450
1451bool
1452Perl_ckwarn(pTHX_ U32 w)
1453{
1454 dVAR;
1455 return
1456 (
1457 isLEXWARN_on
1458 && PL_curcop->cop_warnings != pWARN_NONE
1459 && (
1460 PL_curcop->cop_warnings == pWARN_ALL
1461 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1462 || (unpackWARN2(w) &&
1463 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1464 || (unpackWARN3(w) &&
1465 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1466 || (unpackWARN4(w) &&
1467 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1468 )
1469 )
1470 ||
1471 (
1472 isLEXWARN_off && PL_dowarn & G_WARN_ON
1473 )
1474 ;
1475}
1476
1477/* implements the ckWARN?_d macro */
1478
1479bool
1480Perl_ckwarn_d(pTHX_ U32 w)
1481{
1482 dVAR;
1483 return
1484 isLEXWARN_off
1485 || PL_curcop->cop_warnings == pWARN_ALL
1486 || (
1487 PL_curcop->cop_warnings != pWARN_NONE
1488 && (
1489 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1490 || (unpackWARN2(w) &&
1491 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1492 || (unpackWARN3(w) &&
1493 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1494 || (unpackWARN4(w) &&
1495 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1496 )
1497 )
1498 ;
1499}
1500
1501
1502
1503/* since we've already done strlen() for both nam and val
1504 * we can use that info to make things faster than
1505 * sprintf(s, "%s=%s", nam, val)
1506 */
1507#define my_setenv_format(s, nam, nlen, val, vlen) \
1508 Copy(nam, s, nlen, char); \
1509 *(s+nlen) = '='; \
1510 Copy(val, s+(nlen+1), vlen, char); \
1511 *(s+(nlen+1+vlen)) = '\0'
1512
1513#ifdef USE_ENVIRON_ARRAY
1514 /* VMS' my_setenv() is in vms.c */
1515#if !defined(WIN32) && !defined(NETWARE)
1516void
1517Perl_my_setenv(pTHX_ const char *nam, const char *val)
1518{
1519 dVAR;
1520#ifdef USE_ITHREADS
1521 /* only parent thread can modify process environment */
1522 if (PL_curinterp == aTHX)
1523#endif
1524 {
1525#ifndef PERL_USE_SAFE_PUTENV
1526 if (!PL_use_safe_putenv) {
1527 /* most putenv()s leak, so we manipulate environ directly */
1528 register I32 i=setenv_getix(nam); /* where does it go? */
1529 int nlen, vlen;
1530
1531 if (environ == PL_origenviron) { /* need we copy environment? */
1532 I32 j;
1533 I32 max;
1534 char **tmpenv;
1535
1536 for (max = i; environ[max]; max++) ;
1537 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1538 for (j=0; j<max; j++) { /* copy environment */
1539 const int len = strlen(environ[j]);
1540 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1541 Copy(environ[j], tmpenv[j], len+1, char);
1542 }
1543 tmpenv[max] = Nullch;
1544 environ = tmpenv; /* tell exec where it is now */
1545 }
1546 if (!val) {
1547 safesysfree(environ[i]);
1548 while (environ[i]) {
1549 environ[i] = environ[i+1];
1550 i++;
1551 }
1552 return;
1553 }
1554 if (!environ[i]) { /* does not exist yet */
1555 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1556 environ[i+1] = Nullch; /* make sure it's null terminated */
1557 }
1558 else
1559 safesysfree(environ[i]);
1560 nlen = strlen(nam);
1561 vlen = strlen(val);
1562
1563 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1564 /* all that work just for this */
1565 my_setenv_format(environ[i], nam, nlen, val, vlen);
1566 } else {
1567# endif
1568# if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
1569# if defined(HAS_UNSETENV)
1570 if (val == NULL) {
1571 (void)unsetenv(nam);
1572 } else {
1573 (void)setenv(nam, val, 1);
1574 }
1575# else /* ! HAS_UNSETENV */
1576 (void)setenv(nam, val, 1);
1577# endif /* HAS_UNSETENV */
1578# else
1579# if defined(HAS_UNSETENV)
1580 if (val == NULL) {
1581 (void)unsetenv(nam);
1582 } else {
1583 const int nlen = strlen(nam);
1584 const int vlen = strlen(val);
1585 char * const new_env =
1586 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1587 my_setenv_format(new_env, nam, nlen, val, vlen);
1588 (void)putenv(new_env);
1589 }
1590# else /* ! HAS_UNSETENV */
1591 char *new_env;
1592 const int nlen = strlen(nam);
1593 int vlen;
1594 if (!val) {
1595 val = "";
1596 }
1597 vlen = strlen(val);
1598 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1599 /* all that work just for this */
1600 my_setenv_format(new_env, nam, nlen, val, vlen);
1601 (void)putenv(new_env);
1602# endif /* HAS_UNSETENV */
1603# endif /* __CYGWIN__ */
1604#ifndef PERL_USE_SAFE_PUTENV
1605 }
1606#endif
1607 }
1608}
1609
1610#else /* WIN32 || NETWARE */
1611
1612void
1613Perl_my_setenv(pTHX_ const char *nam, const char *val)
1614{
1615 dVAR;
1616 register char *envstr;
1617 const int nlen = strlen(nam);
1618 int vlen;
1619
1620 if (!val) {
1621 val = "";
1622 }
1623 vlen = strlen(val);
1624 Newx(envstr, nlen+vlen+2, char);
1625 my_setenv_format(envstr, nam, nlen, val, vlen);
1626 (void)PerlEnv_putenv(envstr);
1627 Safefree(envstr);
1628}
1629
1630#endif /* WIN32 || NETWARE */
1631
1632#ifndef PERL_MICRO
1633I32
1634Perl_setenv_getix(pTHX_ const char *nam)
1635{
1636 register I32 i;
1637 register const I32 len = strlen(nam);
1638
1639 for (i = 0; environ[i]; i++) {
1640 if (
1641#ifdef WIN32
1642 strnicmp(environ[i],nam,len) == 0
1643#else
1644 strnEQ(environ[i],nam,len)
1645#endif
1646 && environ[i][len] == '=')
1647 break; /* strnEQ must come first to avoid */
1648 } /* potential SEGV's */
1649 return i;
1650}
1651#endif /* !PERL_MICRO */
1652
1653#endif /* !VMS && !EPOC*/
1654
1655#ifdef UNLINK_ALL_VERSIONS
1656I32
1657Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1658{
1659 I32 i;
1660
1661 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1662 return i ? 0 : -1;
1663}
1664#endif
1665
1666/* this is a drop-in replacement for bcopy() */
1667#if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1668char *
1669Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1670{
1671 char * const retval = to;
1672
1673 if (from - to >= 0) {
1674 while (len--)
1675 *to++ = *from++;
1676 }
1677 else {
1678 to += len;
1679 from += len;
1680 while (len--)
1681 *(--to) = *(--from);
1682 }
1683 return retval;
1684}
1685#endif
1686
1687/* this is a drop-in replacement for memset() */
1688#ifndef HAS_MEMSET
1689void *
1690Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1691{
1692 char * const retval = loc;
1693
1694 while (len--)
1695 *loc++ = ch;
1696 return retval;
1697}
1698#endif
1699
1700/* this is a drop-in replacement for bzero() */
1701#if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1702char *
1703Perl_my_bzero(register char *loc, register I32 len)
1704{
1705 char * const retval = loc;
1706
1707 while (len--)
1708 *loc++ = 0;
1709 return retval;
1710}
1711#endif
1712
1713/* this is a drop-in replacement for memcmp() */
1714#if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1715I32
1716Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1717{
1718 register const U8 *a = (const U8 *)s1;
1719 register const U8 *b = (const U8 *)s2;
1720 register I32 tmp;
1721
1722 while (len--) {
1723 if ((tmp = *a++ - *b++))
1724 return tmp;
1725 }
1726 return 0;
1727}
1728#endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1729
1730#ifndef HAS_VPRINTF
1731
1732#ifdef USE_CHAR_VSPRINTF
1733char *
1734#else
1735int
1736#endif
1737vsprintf(char *dest, const char *pat, char *args)
1738{
1739 FILE fakebuf;
1740
1741 fakebuf._ptr = dest;
1742 fakebuf._cnt = 32767;
1743#ifndef _IOSTRG
1744#define _IOSTRG 0
1745#endif
1746 fakebuf._flag = _IOWRT|_IOSTRG;
1747 _doprnt(pat, args, &fakebuf); /* what a kludge */
1748 (void)putc('\0', &fakebuf);
1749#ifdef USE_CHAR_VSPRINTF
1750 return(dest);
1751#else
1752 return 0; /* perl doesn't use return value */
1753#endif
1754}
1755
1756#endif /* HAS_VPRINTF */
1757
1758#ifdef MYSWAP
1759#if BYTEORDER != 0x4321
1760short
1761Perl_my_swap(pTHX_ short s)
1762{
1763#if (BYTEORDER & 1) == 0
1764 short result;
1765
1766 result = ((s & 255) << 8) + ((s >> 8) & 255);
1767 return result;
1768#else
1769 return s;
1770#endif
1771}
1772
1773long
1774Perl_my_htonl(pTHX_ long l)
1775{
1776 union {
1777 long result;
1778 char c[sizeof(long)];
1779 } u;
1780
1781#if BYTEORDER == 0x1234
1782 u.c[0] = (l >> 24) & 255;
1783 u.c[1] = (l >> 16) & 255;
1784 u.c[2] = (l >> 8) & 255;
1785 u.c[3] = l & 255;
1786 return u.result;
1787#else
1788#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1789 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1790#else
1791 register I32 o;
1792 register I32 s;
1793
1794 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1795 u.c[o & 0xf] = (l >> s) & 255;
1796 }
1797 return u.result;
1798#endif
1799#endif
1800}
1801
1802long
1803Perl_my_ntohl(pTHX_ long l)
1804{
1805 union {
1806 long l;
1807 char c[sizeof(long)];
1808 } u;
1809
1810#if BYTEORDER == 0x1234
1811 u.c[0] = (l >> 24) & 255;
1812 u.c[1] = (l >> 16) & 255;
1813 u.c[2] = (l >> 8) & 255;
1814 u.c[3] = l & 255;
1815 return u.l;
1816#else
1817#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1818 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1819#else
1820 register I32 o;
1821 register I32 s;
1822
1823 u.l = l;
1824 l = 0;
1825 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1826 l |= (u.c[o & 0xf] & 255) << s;
1827 }
1828 return l;
1829#endif
1830#endif
1831}
1832
1833#endif /* BYTEORDER != 0x4321 */
1834#endif /* MYSWAP */
1835
1836/*
1837 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1838 * If these functions are defined,
1839 * the BYTEORDER is neither 0x1234 nor 0x4321.
1840 * However, this is not assumed.
1841 * -DWS
1842 */
1843
1844#define HTOLE(name,type) \
1845 type \
1846 name (register type n) \
1847 { \
1848 union { \
1849 type value; \
1850 char c[sizeof(type)]; \
1851 } u; \
1852 register I32 i; \
1853 register I32 s = 0; \
1854 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1855 u.c[i] = (n >> s) & 0xFF; \
1856 } \
1857 return u.value; \
1858 }
1859
1860#define LETOH(name,type) \
1861 type \
1862 name (register type n) \
1863 { \
1864 union { \
1865 type value; \
1866 char c[sizeof(type)]; \
1867 } u; \
1868 register I32 i; \
1869 register I32 s = 0; \
1870 u.value = n; \
1871 n = 0; \
1872 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1873 n |= ((type)(u.c[i] & 0xFF)) << s; \
1874 } \
1875 return n; \
1876 }
1877
1878/*
1879 * Big-endian byte order functions.
1880 */
1881
1882#define HTOBE(name,type) \
1883 type \
1884 name (register type n) \
1885 { \
1886 union { \
1887 type value; \
1888 char c[sizeof(type)]; \
1889 } u; \
1890 register I32 i; \
1891 register I32 s = 8*(sizeof(u.c)-1); \
1892 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1893 u.c[i] = (n >> s) & 0xFF; \
1894 } \
1895 return u.value; \
1896 }
1897
1898#define BETOH(name,type) \
1899 type \
1900 name (register type n) \
1901 { \
1902 union { \
1903 type value; \
1904 char c[sizeof(type)]; \
1905 } u; \
1906 register I32 i; \
1907 register I32 s = 8*(sizeof(u.c)-1); \
1908 u.value = n; \
1909 n = 0; \
1910 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1911 n |= ((type)(u.c[i] & 0xFF)) << s; \
1912 } \
1913 return n; \
1914 }
1915
1916/*
1917 * If we just can't do it...
1918 */
1919
1920#define NOT_AVAIL(name,type) \
1921 type \
1922 name (register type n) \
1923 { \
1924 Perl_croak_nocontext(#name "() not available"); \
1925 return n; /* not reached */ \
1926 }
1927
1928
1929#if defined(HAS_HTOVS) && !defined(htovs)
1930HTOLE(htovs,short)
1931#endif
1932#if defined(HAS_HTOVL) && !defined(htovl)
1933HTOLE(htovl,long)
1934#endif
1935#if defined(HAS_VTOHS) && !defined(vtohs)
1936LETOH(vtohs,short)
1937#endif
1938#if defined(HAS_VTOHL) && !defined(vtohl)
1939LETOH(vtohl,long)
1940#endif
1941
1942#ifdef PERL_NEED_MY_HTOLE16
1943# if U16SIZE == 2
1944HTOLE(Perl_my_htole16,U16)
1945# else
1946NOT_AVAIL(Perl_my_htole16,U16)
1947# endif
1948#endif
1949#ifdef PERL_NEED_MY_LETOH16
1950# if U16SIZE == 2
1951LETOH(Perl_my_letoh16,U16)
1952# else
1953NOT_AVAIL(Perl_my_letoh16,U16)
1954# endif
1955#endif
1956#ifdef PERL_NEED_MY_HTOBE16
1957# if U16SIZE == 2
1958HTOBE(Perl_my_htobe16,U16)
1959# else
1960NOT_AVAIL(Perl_my_htobe16,U16)
1961# endif
1962#endif
1963#ifdef PERL_NEED_MY_BETOH16
1964# if U16SIZE == 2
1965BETOH(Perl_my_betoh16,U16)
1966# else
1967NOT_AVAIL(Perl_my_betoh16,U16)
1968# endif
1969#endif
1970
1971#ifdef PERL_NEED_MY_HTOLE32
1972# if U32SIZE == 4
1973HTOLE(Perl_my_htole32,U32)
1974# else
1975NOT_AVAIL(Perl_my_htole32,U32)
1976# endif
1977#endif
1978#ifdef PERL_NEED_MY_LETOH32
1979# if U32SIZE == 4
1980LETOH(Perl_my_letoh32,U32)
1981# else
1982NOT_AVAIL(Perl_my_letoh32,U32)
1983# endif
1984#endif
1985#ifdef PERL_NEED_MY_HTOBE32
1986# if U32SIZE == 4
1987HTOBE(Perl_my_htobe32,U32)
1988# else
1989NOT_AVAIL(Perl_my_htobe32,U32)
1990# endif
1991#endif
1992#ifdef PERL_NEED_MY_BETOH32
1993# if U32SIZE == 4
1994BETOH(Perl_my_betoh32,U32)
1995# else
1996NOT_AVAIL(Perl_my_betoh32,U32)
1997# endif
1998#endif
1999
2000#ifdef PERL_NEED_MY_HTOLE64
2001# if U64SIZE == 8
2002HTOLE(Perl_my_htole64,U64)
2003# else
2004NOT_AVAIL(Perl_my_htole64,U64)
2005# endif
2006#endif
2007#ifdef PERL_NEED_MY_LETOH64
2008# if U64SIZE == 8
2009LETOH(Perl_my_letoh64,U64)
2010# else
2011NOT_AVAIL(Perl_my_letoh64,U64)
2012# endif
2013#endif
2014#ifdef PERL_NEED_MY_HTOBE64
2015# if U64SIZE == 8
2016HTOBE(Perl_my_htobe64,U64)
2017# else
2018NOT_AVAIL(Perl_my_htobe64,U64)
2019# endif
2020#endif
2021#ifdef PERL_NEED_MY_BETOH64
2022# if U64SIZE == 8
2023BETOH(Perl_my_betoh64,U64)
2024# else
2025NOT_AVAIL(Perl_my_betoh64,U64)
2026# endif
2027#endif
2028
2029#ifdef PERL_NEED_MY_HTOLES
2030HTOLE(Perl_my_htoles,short)
2031#endif
2032#ifdef PERL_NEED_MY_LETOHS
2033LETOH(Perl_my_letohs,short)
2034#endif
2035#ifdef PERL_NEED_MY_HTOBES
2036HTOBE(Perl_my_htobes,short)
2037#endif
2038#ifdef PERL_NEED_MY_BETOHS
2039BETOH(Perl_my_betohs,short)
2040#endif
2041
2042#ifdef PERL_NEED_MY_HTOLEI
2043HTOLE(Perl_my_htolei,int)
2044#endif
2045#ifdef PERL_NEED_MY_LETOHI
2046LETOH(Perl_my_letohi,int)
2047#endif
2048#ifdef PERL_NEED_MY_HTOBEI
2049HTOBE(Perl_my_htobei,int)
2050#endif
2051#ifdef PERL_NEED_MY_BETOHI
2052BETOH(Perl_my_betohi,int)
2053#endif
2054
2055#ifdef PERL_NEED_MY_HTOLEL
2056HTOLE(Perl_my_htolel,long)
2057#endif
2058#ifdef PERL_NEED_MY_LETOHL
2059LETOH(Perl_my_letohl,long)
2060#endif
2061#ifdef PERL_NEED_MY_HTOBEL
2062HTOBE(Perl_my_htobel,long)
2063#endif
2064#ifdef PERL_NEED_MY_BETOHL
2065BETOH(Perl_my_betohl,long)
2066#endif
2067
2068void
2069Perl_my_swabn(void *ptr, int n)
2070{
2071 register char *s = (char *)ptr;
2072 register char *e = s + (n-1);
2073 register char tc;
2074
2075 for (n /= 2; n > 0; s++, e--, n--) {
2076 tc = *s;
2077 *s = *e;
2078 *e = tc;
2079 }
2080}
2081
2082PerlIO *
2083Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2084{
2085#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2086 dVAR;
2087 int p[2];
2088 register I32 This, that;
2089 register Pid_t pid;
2090 SV *sv;
2091 I32 did_pipes = 0;
2092 int pp[2];
2093
2094 PERL_FLUSHALL_FOR_CHILD;
2095 This = (*mode == 'w');
2096 that = !This;
2097 if (PL_tainting) {
2098 taint_env();
2099 taint_proper("Insecure %s%s", "EXEC");
2100 }
2101 if (PerlProc_pipe(p) < 0)
2102 return Nullfp;
2103 /* Try for another pipe pair for error return */
2104 if (PerlProc_pipe(pp) >= 0)
2105 did_pipes = 1;
2106 while ((pid = PerlProc_fork()) < 0) {
2107 if (errno != EAGAIN) {
2108 PerlLIO_close(p[This]);
2109 PerlLIO_close(p[that]);
2110 if (did_pipes) {
2111 PerlLIO_close(pp[0]);
2112 PerlLIO_close(pp[1]);
2113 }
2114 return Nullfp;
2115 }
2116 sleep(5);
2117 }
2118 if (pid == 0) {
2119 /* Child */
2120#undef THIS
2121#undef THAT
2122#define THIS that
2123#define THAT This
2124 /* Close parent's end of error status pipe (if any) */
2125 if (did_pipes) {
2126 PerlLIO_close(pp[0]);
2127#if defined(HAS_FCNTL) && defined(F_SETFD)
2128 /* Close error pipe automatically if exec works */
2129 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2130#endif
2131 }
2132 /* Now dup our end of _the_ pipe to right position */
2133 if (p[THIS] != (*mode == 'r')) {
2134 PerlLIO_dup2(p[THIS], *mode == 'r');
2135 PerlLIO_close(p[THIS]);
2136 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2137 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2138 }
2139 else
2140 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2141#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2142 /* No automatic close - do it by hand */
2143# ifndef NOFILE
2144# define NOFILE 20
2145# endif
2146 {
2147 int fd;
2148
2149 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2150 if (fd != pp[1])
2151 PerlLIO_close(fd);
2152 }
2153 }
2154#endif
2155 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2156 PerlProc__exit(1);
2157#undef THIS
2158#undef THAT
2159 }
2160 /* Parent */
2161 do_execfree(); /* free any memory malloced by child on fork */
2162 if (did_pipes)
2163 PerlLIO_close(pp[1]);
2164 /* Keep the lower of the two fd numbers */
2165 if (p[that] < p[This]) {
2166 PerlLIO_dup2(p[This], p[that]);
2167 PerlLIO_close(p[This]);
2168 p[This] = p[that];
2169 }
2170 else
2171 PerlLIO_close(p[that]); /* close child's end of pipe */
2172
2173 LOCK_FDPID_MUTEX;
2174 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2175 UNLOCK_FDPID_MUTEX;
2176 SvUPGRADE(sv,SVt_IV);
2177 SvIV_set(sv, pid);
2178 PL_forkprocess = pid;
2179 /* If we managed to get status pipe check for exec fail */
2180 if (did_pipes && pid > 0) {
2181 int errkid;
2182 int n = 0, n1;
2183
2184 while (n < sizeof(int)) {
2185 n1 = PerlLIO_read(pp[0],
2186 (void*)(((char*)&errkid)+n),
2187 (sizeof(int)) - n);
2188 if (n1 <= 0)
2189 break;
2190 n += n1;
2191 }
2192 PerlLIO_close(pp[0]);
2193 did_pipes = 0;
2194 if (n) { /* Error */
2195 int pid2, status;
2196 PerlLIO_close(p[This]);
2197 if (n != sizeof(int))
2198 Perl_croak(aTHX_ "panic: kid popen errno read");
2199 do {
2200 pid2 = wait4pid(pid, &status, 0);
2201 } while (pid2 == -1 && errno == EINTR);
2202 errno = errkid; /* Propagate errno from kid */
2203 return Nullfp;
2204 }
2205 }
2206 if (did_pipes)
2207 PerlLIO_close(pp[0]);
2208 return PerlIO_fdopen(p[This], mode);
2209#else
2210 Perl_croak(aTHX_ "List form of piped open not implemented");
2211 return (PerlIO *) NULL;
2212#endif
2213}
2214
2215 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2216#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2217PerlIO *
2218Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2219{
2220 dVAR;
2221 int p[2];
2222 register I32 This, that;
2223 register Pid_t pid;
2224 SV *sv;
2225 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2226 I32 did_pipes = 0;
2227 int pp[2];
2228
2229 PERL_FLUSHALL_FOR_CHILD;
2230#ifdef OS2
2231 if (doexec) {
2232 return my_syspopen(aTHX_ cmd,mode);
2233 }
2234#endif
2235 This = (*mode == 'w');
2236 that = !This;
2237 if (doexec && PL_tainting) {
2238 taint_env();
2239 taint_proper("Insecure %s%s", "EXEC");
2240 }
2241 if (PerlProc_pipe(p) < 0)
2242 return Nullfp;
2243 if (doexec && PerlProc_pipe(pp) >= 0)
2244 did_pipes = 1;
2245 while ((pid = PerlProc_fork()) < 0) {
2246 if (errno != EAGAIN) {
2247 PerlLIO_close(p[This]);
2248 PerlLIO_close(p[that]);
2249 if (did_pipes) {
2250 PerlLIO_close(pp[0]);
2251 PerlLIO_close(pp[1]);
2252 }
2253 if (!doexec)
2254 Perl_croak(aTHX_ "Can't fork");
2255 return Nullfp;
2256 }
2257 sleep(5);
2258 }
2259 if (pid == 0) {
2260 GV* tmpgv;
2261
2262#undef THIS
2263#undef THAT
2264#define THIS that
2265#define THAT This
2266 if (did_pipes) {
2267 PerlLIO_close(pp[0]);
2268#if defined(HAS_FCNTL) && defined(F_SETFD)
2269 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2270#endif
2271 }
2272 if (p[THIS] != (*mode == 'r')) {
2273 PerlLIO_dup2(p[THIS], *mode == 'r');
2274 PerlLIO_close(p[THIS]);
2275 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2276 PerlLIO_close(p[THAT]);
2277 }
2278 else
2279 PerlLIO_close(p[THAT]);
2280#ifndef OS2
2281 if (doexec) {
2282#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2283#ifndef NOFILE
2284#define NOFILE 20
2285#endif
2286 {
2287 int fd;
2288
2289 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2290 if (fd != pp[1])
2291 PerlLIO_close(fd);
2292 }
2293#endif
2294 /* may or may not use the shell */
2295 do_exec3(cmd, pp[1], did_pipes);
2296 PerlProc__exit(1);
2297 }
2298#endif /* defined OS2 */
2299 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2300 SvREADONLY_off(GvSV(tmpgv));
2301 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2302 SvREADONLY_on(GvSV(tmpgv));
2303 }
2304#ifdef THREADS_HAVE_PIDS
2305 PL_ppid = (IV)getppid();
2306#endif
2307 PL_forkprocess = 0;
2308#ifdef PERL_USES_PL_PIDSTATUS
2309 hv_clear(PL_pidstatus); /* we have no children */
2310#endif
2311 return Nullfp;
2312#undef THIS
2313#undef THAT
2314 }
2315 do_execfree(); /* free any memory malloced by child on vfork */
2316 if (did_pipes)
2317 PerlLIO_close(pp[1]);
2318 if (p[that] < p[This]) {
2319 PerlLIO_dup2(p[This], p[that]);
2320 PerlLIO_close(p[This]);
2321 p[This] = p[that];
2322 }
2323 else
2324 PerlLIO_close(p[that]);
2325
2326 LOCK_FDPID_MUTEX;
2327 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2328 UNLOCK_FDPID_MUTEX;
2329 SvUPGRADE(sv,SVt_IV);
2330 SvIV_set(sv, pid);
2331 PL_forkprocess = pid;
2332 if (did_pipes && pid > 0) {
2333 int errkid;
2334 int n = 0, n1;
2335
2336 while (n < sizeof(int)) {
2337 n1 = PerlLIO_read(pp[0],
2338 (void*)(((char*)&errkid)+n),
2339 (sizeof(int)) - n);
2340 if (n1 <= 0)
2341 break;
2342 n += n1;
2343 }
2344 PerlLIO_close(pp[0]);
2345 did_pipes = 0;
2346 if (n) { /* Error */
2347 int pid2, status;
2348 PerlLIO_close(p[This]);
2349 if (n != sizeof(int))
2350 Perl_croak(aTHX_ "panic: kid popen errno read");
2351 do {
2352 pid2 = wait4pid(pid, &status, 0);
2353 } while (pid2 == -1 && errno == EINTR);
2354 errno = errkid; /* Propagate errno from kid */
2355 return Nullfp;
2356 }
2357 }
2358 if (did_pipes)
2359 PerlLIO_close(pp[0]);
2360 return PerlIO_fdopen(p[This], mode);
2361}
2362#else
2363#if defined(atarist) || defined(EPOC)
2364FILE *popen();
2365PerlIO *
2366Perl_my_popen(pTHX_ char *cmd, char *mode)
2367{
2368 PERL_FLUSHALL_FOR_CHILD;
2369 /* Call system's popen() to get a FILE *, then import it.
2370 used 0 for 2nd parameter to PerlIO_importFILE;
2371 apparently not used
2372 */
2373 return PerlIO_importFILE(popen(cmd, mode), 0);
2374}
2375#else
2376#if defined(DJGPP)
2377FILE *djgpp_popen();
2378PerlIO *
2379Perl_my_popen(pTHX_ char *cmd, char *mode)
2380{
2381 PERL_FLUSHALL_FOR_CHILD;
2382 /* Call system's popen() to get a FILE *, then import it.
2383 used 0 for 2nd parameter to PerlIO_importFILE;
2384 apparently not used
2385 */
2386 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2387}
2388#endif
2389#endif
2390
2391#endif /* !DOSISH */
2392
2393/* this is called in parent before the fork() */
2394void
2395Perl_atfork_lock(void)
2396{
2397 dVAR;
2398#if defined(USE_ITHREADS)
2399 /* locks must be held in locking order (if any) */
2400# ifdef MYMALLOC
2401 MUTEX_LOCK(&PL_malloc_mutex);
2402# endif
2403 OP_REFCNT_LOCK;
2404#endif
2405}
2406
2407/* this is called in both parent and child after the fork() */
2408void
2409Perl_atfork_unlock(void)
2410{
2411 dVAR;
2412#if defined(USE_ITHREADS)
2413 /* locks must be released in same order as in atfork_lock() */
2414# ifdef MYMALLOC
2415 MUTEX_UNLOCK(&PL_malloc_mutex);
2416# endif
2417 OP_REFCNT_UNLOCK;
2418#endif
2419}
2420
2421Pid_t
2422Perl_my_fork(void)
2423{
2424#if defined(HAS_FORK)
2425 Pid_t pid;
2426#if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2427 atfork_lock();
2428 pid = fork();
2429 atfork_unlock();
2430#else
2431 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2432 * handlers elsewhere in the code */
2433 pid = fork();
2434#endif
2435 return pid;
2436#else
2437 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2438 Perl_croak_nocontext("fork() not available");
2439 return 0;
2440#endif /* HAS_FORK */
2441}
2442
2443#ifdef DUMP_FDS
2444void
2445Perl_dump_fds(pTHX_ char *s)
2446{
2447 int fd;
2448 Stat_t tmpstatbuf;
2449
2450 PerlIO_printf(Perl_debug_log,"%s", s);
2451 for (fd = 0; fd < 32; fd++) {
2452 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2453 PerlIO_printf(Perl_debug_log," %d",fd);
2454 }
2455 PerlIO_printf(Perl_debug_log,"\n");
2456 return;
2457}
2458#endif /* DUMP_FDS */
2459
2460#ifndef HAS_DUP2
2461int
2462dup2(int oldfd, int newfd)
2463{
2464#if defined(HAS_FCNTL) && defined(F_DUPFD)
2465 if (oldfd == newfd)
2466 return oldfd;
2467 PerlLIO_close(newfd);
2468 return fcntl(oldfd, F_DUPFD, newfd);
2469#else
2470#define DUP2_MAX_FDS 256
2471 int fdtmp[DUP2_MAX_FDS];
2472 I32 fdx = 0;
2473 int fd;
2474
2475 if (oldfd == newfd)
2476 return oldfd;
2477 PerlLIO_close(newfd);
2478 /* good enough for low fd's... */
2479 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2480 if (fdx >= DUP2_MAX_FDS) {
2481 PerlLIO_close(fd);
2482 fd = -1;
2483 break;
2484 }
2485 fdtmp[fdx++] = fd;
2486 }
2487 while (fdx > 0)
2488 PerlLIO_close(fdtmp[--fdx]);
2489 return fd;
2490#endif
2491}
2492#endif
2493
2494#ifndef PERL_MICRO
2495#ifdef HAS_SIGACTION
2496
2497#ifdef MACOS_TRADITIONAL
2498/* We don't want restart behavior on MacOS */
2499#undef SA_RESTART
2500#endif
2501
2502Sighandler_t
2503Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2504{
2505 dVAR;
2506 struct sigaction act, oact;
2507
2508#ifdef USE_ITHREADS
2509 /* only "parent" interpreter can diddle signals */
2510 if (PL_curinterp != aTHX)
2511 return (Sighandler_t) SIG_ERR;
2512#endif
2513
2514 act.sa_handler = (void(*)(int))handler;
2515 sigemptyset(&act.sa_mask);
2516 act.sa_flags = 0;
2517#ifdef SA_RESTART
2518 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2519 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2520#endif
2521#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2522 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2523 act.sa_flags |= SA_NOCLDWAIT;
2524#endif
2525 if (sigaction(signo, &act, &oact) == -1)
2526 return (Sighandler_t) SIG_ERR;
2527 else
2528 return (Sighandler_t) oact.sa_handler;
2529}
2530
2531Sighandler_t
2532Perl_rsignal_state(pTHX_ int signo)
2533{
2534 struct sigaction oact;
2535
2536 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2537 return (Sighandler_t) SIG_ERR;
2538 else
2539 return (Sighandler_t) oact.sa_handler;
2540}
2541
2542int
2543Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2544{
2545 dVAR;
2546 struct sigaction act;
2547
2548#ifdef USE_ITHREADS
2549 /* only "parent" interpreter can diddle signals */
2550 if (PL_curinterp != aTHX)
2551 return -1;
2552#endif
2553
2554 act.sa_handler = (void(*)(int))handler;
2555 sigemptyset(&act.sa_mask);
2556 act.sa_flags = 0;
2557#ifdef SA_RESTART
2558 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2559 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2560#endif
2561#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2562 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2563 act.sa_flags |= SA_NOCLDWAIT;
2564#endif
2565 return sigaction(signo, &act, save);
2566}
2567
2568int
2569Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2570{
2571 dVAR;
2572#ifdef USE_ITHREADS
2573 /* only "parent" interpreter can diddle signals */
2574 if (PL_curinterp != aTHX)
2575 return -1;
2576#endif
2577
2578 return sigaction(signo, save, (struct sigaction *)NULL);
2579}
2580
2581#else /* !HAS_SIGACTION */
2582
2583Sighandler_t
2584Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2585{
2586#if defined(USE_ITHREADS) && !defined(WIN32)
2587 /* only "parent" interpreter can diddle signals */
2588 if (PL_curinterp != aTHX)
2589 return (Sighandler_t) SIG_ERR;
2590#endif
2591
2592 return PerlProc_signal(signo, handler);
2593}
2594
2595static Signal_t
2596sig_trap(int signo)
2597{
2598 dVAR;
2599 PL_sig_trapped++;
2600}
2601
2602Sighandler_t
2603Perl_rsignal_state(pTHX_ int signo)
2604{
2605 dVAR;
2606 Sighandler_t oldsig;
2607
2608#if defined(USE_ITHREADS) && !defined(WIN32)
2609 /* only "parent" interpreter can diddle signals */
2610 if (PL_curinterp != aTHX)
2611 return (Sighandler_t) SIG_ERR;
2612#endif
2613
2614 PL_sig_trapped = 0;
2615 oldsig = PerlProc_signal(signo, sig_trap);
2616 PerlProc_signal(signo, oldsig);
2617 if (PL_sig_trapped)
2618 PerlProc_kill(PerlProc_getpid(), signo);
2619 return oldsig;
2620}
2621
2622int
2623Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2624{
2625#if defined(USE_ITHREADS) && !defined(WIN32)
2626 /* only "parent" interpreter can diddle signals */
2627 if (PL_curinterp != aTHX)
2628 return -1;
2629#endif
2630 *save = PerlProc_signal(signo, handler);
2631 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2632}
2633
2634int
2635Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2636{
2637#if defined(USE_ITHREADS) && !defined(WIN32)
2638 /* only "parent" interpreter can diddle signals */
2639 if (PL_curinterp != aTHX)
2640 return -1;
2641#endif
2642 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2643}
2644
2645#endif /* !HAS_SIGACTION */
2646#endif /* !PERL_MICRO */
2647
2648 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2649#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2650I32
2651Perl_my_pclose(pTHX_ PerlIO *ptr)
2652{
2653 dVAR;
2654 Sigsave_t hstat, istat, qstat;
2655 int status;
2656 SV **svp;
2657 Pid_t pid;
2658 Pid_t pid2;
2659 bool close_failed;
2660 int saved_errno = 0;
2661#ifdef WIN32
2662 int saved_win32_errno;
2663#endif
2664
2665 LOCK_FDPID_MUTEX;
2666 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2667 UNLOCK_FDPID_MUTEX;
2668 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2669 SvREFCNT_dec(*svp);
2670 *svp = &PL_sv_undef;
2671#ifdef OS2
2672 if (pid == -1) { /* Opened by popen. */
2673 return my_syspclose(ptr);
2674 }
2675#endif
2676 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2677 saved_errno = errno;
2678#ifdef WIN32
2679 saved_win32_errno = GetLastError();
2680#endif
2681 }
2682#ifdef UTS
2683 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2684#endif
2685#ifndef PERL_MICRO
2686 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2687 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2688 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2689#endif
2690 do {
2691 pid2 = wait4pid(pid, &status, 0);
2692 } while (pid2 == -1 && errno == EINTR);
2693#ifndef PERL_MICRO
2694 rsignal_restore(SIGHUP, &hstat);
2695 rsignal_restore(SIGINT, &istat);
2696 rsignal_restore(SIGQUIT, &qstat);
2697#endif
2698 if (close_failed) {
2699 SETERRNO(saved_errno, 0);
2700 return -1;
2701 }
2702 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2703}
2704#endif /* !DOSISH */
2705
2706#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2707I32
2708Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2709{
2710 dVAR;
2711 I32 result = 0;
2712 if (!pid)
2713 return -1;
2714#ifdef PERL_USES_PL_PIDSTATUS
2715 {
2716 if (pid > 0) {
2717 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2718 pid, rather than a string form. */
2719 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2720 if (svp && *svp != &PL_sv_undef) {
2721 *statusp = SvIVX(*svp);
2722 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2723 G_DISCARD);
2724 return pid;
2725 }
2726 }
2727 else {
2728 HE *entry;
2729
2730 hv_iterinit(PL_pidstatus);
2731 if ((entry = hv_iternext(PL_pidstatus))) {
2732 SV * const sv = hv_iterval(PL_pidstatus,entry);
2733 I32 len;
2734 const char * const spid = hv_iterkey(entry,&len);
2735
2736 assert (len == sizeof(Pid_t));
2737 memcpy((char *)&pid, spid, len);
2738 *statusp = SvIVX(sv);
2739 /* The hash iterator is currently on this entry, so simply
2740 calling hv_delete would trigger the lazy delete, which on
2741 aggregate does more work, beacuse next call to hv_iterinit()
2742 would spot the flag, and have to call the delete routine,
2743 while in the meantime any new entries can't re-use that
2744 memory. */
2745 hv_iterinit(PL_pidstatus);
2746 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2747 return pid;
2748 }
2749 }
2750 }
2751#endif
2752#ifdef HAS_WAITPID
2753# ifdef HAS_WAITPID_RUNTIME
2754 if (!HAS_WAITPID_RUNTIME)
2755 goto hard_way;
2756# endif
2757 result = PerlProc_waitpid(pid,statusp,flags);
2758 goto finish;
2759#endif
2760#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2761 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2762 goto finish;
2763#endif
2764#ifdef PERL_USES_PL_PIDSTATUS
2765#if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2766 hard_way:
2767#endif
2768 {
2769 if (flags)
2770 Perl_croak(aTHX_ "Can't do waitpid with flags");
2771 else {
2772 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2773 pidgone(result,*statusp);
2774 if (result < 0)
2775 *statusp = -1;
2776 }
2777 }
2778#endif
2779#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2780 finish:
2781#endif
2782 if (result < 0 && errno == EINTR) {
2783 PERL_ASYNC_CHECK();
2784 }
2785 return result;
2786}
2787#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2788
2789#ifdef PERL_USES_PL_PIDSTATUS
2790void
2791Perl_pidgone(pTHX_ Pid_t pid, int status)
2792{
2793 register SV *sv;
2794
2795 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2796 SvUPGRADE(sv,SVt_IV);
2797 SvIV_set(sv, status);
2798 return;
2799}
2800#endif
2801
2802#if defined(atarist) || defined(OS2) || defined(EPOC)
2803int pclose();
2804#ifdef HAS_FORK
2805int /* Cannot prototype with I32
2806 in os2ish.h. */
2807my_syspclose(PerlIO *ptr)
2808#else
2809I32
2810Perl_my_pclose(pTHX_ PerlIO *ptr)
2811#endif
2812{
2813 /* Needs work for PerlIO ! */
2814 FILE * const f = PerlIO_findFILE(ptr);
2815 const I32 result = pclose(f);
2816 PerlIO_releaseFILE(ptr,f);
2817 return result;
2818}
2819#endif
2820
2821#if defined(DJGPP)
2822int djgpp_pclose();
2823I32
2824Perl_my_pclose(pTHX_ PerlIO *ptr)
2825{
2826 /* Needs work for PerlIO ! */
2827 FILE * const f = PerlIO_findFILE(ptr);
2828 I32 result = djgpp_pclose(f);
2829 result = (result << 8) & 0xff00;
2830 PerlIO_releaseFILE(ptr,f);
2831 return result;
2832}
2833#endif
2834
2835void
2836Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2837{
2838 register I32 todo;
2839 register const char * const frombase = from;
2840
2841 if (len == 1) {
2842 register const char c = *from;
2843 while (count-- > 0)
2844 *to++ = c;
2845 return;
2846 }
2847 while (count-- > 0) {
2848 for (todo = len; todo > 0; todo--) {
2849 *to++ = *from++;
2850 }
2851 from = frombase;
2852 }
2853}
2854
2855#ifndef HAS_RENAME
2856I32
2857Perl_same_dirent(pTHX_ const char *a, const char *b)
2858{
2859 char *fa = strrchr(a,'/');
2860 char *fb = strrchr(b,'/');
2861 Stat_t tmpstatbuf1;
2862 Stat_t tmpstatbuf2;
2863 SV * const tmpsv = sv_newmortal();
2864
2865 if (fa)
2866 fa++;
2867 else
2868 fa = a;
2869 if (fb)
2870 fb++;
2871 else
2872 fb = b;
2873 if (strNE(a,b))
2874 return FALSE;
2875 if (fa == a)
2876 sv_setpvn(tmpsv, ".", 1);
2877 else
2878 sv_setpvn(tmpsv, a, fa - a);
2879 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2880 return FALSE;
2881 if (fb == b)
2882 sv_setpvn(tmpsv, ".", 1);
2883 else
2884 sv_setpvn(tmpsv, b, fb - b);
2885 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2886 return FALSE;
2887 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2888 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2889}
2890#endif /* !HAS_RENAME */
2891
2892char*
2893Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2894 const char *const *const search_ext, I32 flags)
2895{
2896 dVAR;
2897 const char *xfound = Nullch;
2898 char *xfailed = Nullch;
2899 char tmpbuf[MAXPATHLEN];
2900 register char *s;
2901 I32 len = 0;
2902 int retval;
2903#if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2904# define SEARCH_EXTS ".bat", ".cmd", NULL
2905# define MAX_EXT_LEN 4
2906#endif
2907#ifdef OS2
2908# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2909# define MAX_EXT_LEN 4
2910#endif
2911#ifdef VMS
2912# define SEARCH_EXTS ".pl", ".com", NULL
2913# define MAX_EXT_LEN 4
2914#endif
2915 /* additional extensions to try in each dir if scriptname not found */
2916#ifdef SEARCH_EXTS
2917 static const char *const exts[] = { SEARCH_EXTS };
2918 const char *const *const ext = search_ext ? search_ext : exts;
2919 int extidx = 0, i = 0;
2920 const char *curext = Nullch;
2921#else
2922 PERL_UNUSED_ARG(search_ext);
2923# define MAX_EXT_LEN 0
2924#endif
2925
2926 /*
2927 * If dosearch is true and if scriptname does not contain path
2928 * delimiters, search the PATH for scriptname.
2929 *
2930 * If SEARCH_EXTS is also defined, will look for each
2931 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2932 * while searching the PATH.
2933 *
2934 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2935 * proceeds as follows:
2936 * If DOSISH or VMSISH:
2937 * + look for ./scriptname{,.foo,.bar}
2938 * + search the PATH for scriptname{,.foo,.bar}
2939 *
2940 * If !DOSISH:
2941 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2942 * this will not look in '.' if it's not in the PATH)
2943 */
2944 tmpbuf[0] = '\0';
2945
2946#ifdef VMS
2947# ifdef ALWAYS_DEFTYPES
2948 len = strlen(scriptname);
2949 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2950 int idx = 0, deftypes = 1;
2951 bool seen_dot = 1;
2952
2953 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch);
2954# else
2955 if (dosearch) {
2956 int idx = 0, deftypes = 1;
2957 bool seen_dot = 1;
2958
2959 const int hasdir = (strpbrk(scriptname,":[</") != Nullch);
2960# endif
2961 /* The first time through, just add SEARCH_EXTS to whatever we
2962 * already have, so we can check for default file types. */
2963 while (deftypes ||
2964 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2965 {
2966 if (deftypes) {
2967 deftypes = 0;
2968 *tmpbuf = '\0';
2969 }
2970 if ((strlen(tmpbuf) + strlen(scriptname)
2971 + MAX_EXT_LEN) >= sizeof tmpbuf)
2972 continue; /* don't search dir with too-long name */
2973 strcat(tmpbuf, scriptname);
2974#else /* !VMS */
2975
2976#ifdef DOSISH
2977 if (strEQ(scriptname, "-"))
2978 dosearch = 0;
2979 if (dosearch) { /* Look in '.' first. */
2980 const char *cur = scriptname;
2981#ifdef SEARCH_EXTS
2982 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2983 while (ext[i])
2984 if (strEQ(ext[i++],curext)) {
2985 extidx = -1; /* already has an ext */
2986 break;
2987 }
2988 do {
2989#endif
2990 DEBUG_p(PerlIO_printf(Perl_debug_log,
2991 "Looking for %s\n",cur));
2992 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2993 && !S_ISDIR(PL_statbuf.st_mode)) {
2994 dosearch = 0;
2995 scriptname = cur;
2996#ifdef SEARCH_EXTS
2997 break;
2998#endif
2999 }
3000#ifdef SEARCH_EXTS
3001 if (cur == scriptname) {
3002 len = strlen(scriptname);
3003 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3004 break;
3005 /* FIXME? Convert to memcpy */
3006 cur = strcpy(tmpbuf, scriptname);
3007 }
3008 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3009 && strcpy(tmpbuf+len, ext[extidx++]));
3010#endif
3011 }
3012#endif
3013
3014#ifdef MACOS_TRADITIONAL
3015 if (dosearch && !strchr(scriptname, ':') &&
3016 (s = PerlEnv_getenv("Commands")))
3017#else
3018 if (dosearch && !strchr(scriptname, '/')
3019#ifdef DOSISH
3020 && !strchr(scriptname, '\\')
3021#endif
3022 && (s = PerlEnv_getenv("PATH")))
3023#endif
3024 {
3025 bool seen_dot = 0;
3026
3027 PL_bufend = s + strlen(s);
3028 while (s < PL_bufend) {
3029#ifdef MACOS_TRADITIONAL
3030 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3031 ',',
3032 &len);
3033#else
3034#if defined(atarist) || defined(DOSISH)
3035 for (len = 0; *s
3036# ifdef atarist
3037 && *s != ','
3038# endif
3039 && *s != ';'; len++, s++) {
3040 if (len < sizeof tmpbuf)
3041 tmpbuf[len] = *s;
3042 }
3043 if (len < sizeof tmpbuf)
3044 tmpbuf[len] = '\0';
3045#else /* ! (atarist || DOSISH) */
3046 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3047 ':',
3048 &len);
3049#endif /* ! (atarist || DOSISH) */
3050#endif /* MACOS_TRADITIONAL */
3051 if (s < PL_bufend)
3052 s++;
3053 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3054 continue; /* don't search dir with too-long name */
3055#ifdef MACOS_TRADITIONAL
3056 if (len && tmpbuf[len - 1] != ':')
3057 tmpbuf[len++] = ':';
3058#else
3059 if (len
3060# if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3061 && tmpbuf[len - 1] != '/'
3062 && tmpbuf[len - 1] != '\\'
3063# endif
3064 )
3065 tmpbuf[len++] = '/';
3066 if (len == 2 && tmpbuf[0] == '.')
3067 seen_dot = 1;
3068#endif
3069 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3070 */
3071 (void)strcpy(tmpbuf + len, scriptname);
3072#endif /* !VMS */
3073
3074#ifdef SEARCH_EXTS
3075 len = strlen(tmpbuf);
3076 if (extidx > 0) /* reset after previous loop */
3077 extidx = 0;
3078 do {
3079#endif
3080 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3081 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3082 if (S_ISDIR(PL_statbuf.st_mode)) {
3083 retval = -1;
3084 }
3085#ifdef SEARCH_EXTS
3086 } while ( retval < 0 /* not there */
3087 && extidx>=0 && ext[extidx] /* try an extension? */
3088 && strcpy(tmpbuf+len, ext[extidx++])
3089 );
3090#endif
3091 if (retval < 0)
3092 continue;
3093 if (S_ISREG(PL_statbuf.st_mode)
3094 && cando(S_IRUSR,TRUE,&PL_statbuf)
3095#if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3096 && cando(S_IXUSR,TRUE,&PL_statbuf)
3097#endif
3098 )
3099 {
3100 xfound = tmpbuf; /* bingo! */
3101 break;
3102 }
3103 if (!xfailed)
3104 xfailed = savepv(tmpbuf);
3105 }
3106#ifndef DOSISH
3107 if (!xfound && !seen_dot && !xfailed &&
3108 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3109 || S_ISDIR(PL_statbuf.st_mode)))
3110#endif
3111 seen_dot = 1; /* Disable message. */
3112 if (!xfound) {
3113 if (flags & 1) { /* do or die? */
3114 Perl_croak(aTHX_ "Can't %s %s%s%s",
3115 (xfailed ? "execute" : "find"),
3116 (xfailed ? xfailed : scriptname),
3117 (xfailed ? "" : " on PATH"),
3118 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3119 }
3120 scriptname = Nullch;
3121 }
3122 Safefree(xfailed);
3123 scriptname = xfound;
3124 }
3125 return (scriptname ? savepv(scriptname) : Nullch);
3126}
3127
3128#ifndef PERL_GET_CONTEXT_DEFINED
3129
3130void *
3131Perl_get_context(void)
3132{
3133 dVAR;
3134#if defined(USE_ITHREADS)
3135# ifdef OLD_PTHREADS_API
3136 pthread_addr_t t;
3137 if (pthread_getspecific(PL_thr_key, &t))
3138 Perl_croak_nocontext("panic: pthread_getspecific");
3139 return (void*)t;
3140# else
3141# ifdef I_MACH_CTHREADS
3142 return (void*)cthread_data(cthread_self());
3143# else
3144 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3145# endif
3146# endif
3147#else
3148 return (void*)NULL;
3149#endif
3150}
3151
3152void
3153Perl_set_context(void *t)
3154{
3155 dVAR;
3156#if defined(USE_ITHREADS)
3157# ifdef I_MACH_CTHREADS
3158 cthread_set_data(cthread_self(), t);
3159# else
3160 if (pthread_setspecific(PL_thr_key, t))
3161 Perl_croak_nocontext("panic: pthread_setspecific");
3162# endif
3163#else
3164 PERL_UNUSED_ARG(t);
3165#endif
3166}
3167
3168#endif /* !PERL_GET_CONTEXT_DEFINED */
3169
3170#if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3171struct perl_vars *
3172Perl_GetVars(pTHX)
3173{
3174 return &PL_Vars;
3175}
3176#endif
3177
3178char **
3179Perl_get_op_names(pTHX)
3180{
3181 return (char **)PL_op_name;
3182}
3183
3184char **
3185Perl_get_op_descs(pTHX)
3186{
3187 return (char **)PL_op_desc;
3188}
3189
3190const char *
3191Perl_get_no_modify(pTHX)
3192{
3193 return PL_no_modify;
3194}
3195
3196U32 *
3197Perl_get_opargs(pTHX)
3198{
3199 return (U32 *)PL_opargs;
3200}
3201
3202PPADDR_t*
3203Perl_get_ppaddr(pTHX)
3204{
3205 dVAR;
3206 return (PPADDR_t*)PL_ppaddr;
3207}
3208
3209#ifndef HAS_GETENV_LEN
3210char *
3211Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3212{
3213 char * const env_trans = PerlEnv_getenv(env_elem);
3214 if (env_trans)
3215 *len = strlen(env_trans);
3216 return env_trans;
3217}
3218#endif
3219
3220
3221MGVTBL*
3222Perl_get_vtbl(pTHX_ int vtbl_id)
3223{
3224 const MGVTBL* result;
3225
3226 switch(vtbl_id) {
3227 case want_vtbl_sv:
3228 result = &PL_vtbl_sv;
3229 break;
3230 case want_vtbl_env:
3231 result = &PL_vtbl_env;
3232 break;
3233 case want_vtbl_envelem:
3234 result = &PL_vtbl_envelem;
3235 break;
3236 case want_vtbl_sig:
3237 result = &PL_vtbl_sig;
3238 break;
3239 case want_vtbl_sigelem:
3240 result = &PL_vtbl_sigelem;
3241 break;
3242 case want_vtbl_pack:
3243 result = &PL_vtbl_pack;
3244 break;
3245 case want_vtbl_packelem:
3246 result = &PL_vtbl_packelem;
3247 break;
3248 case want_vtbl_dbline:
3249 result = &PL_vtbl_dbline;
3250 break;
3251 case want_vtbl_isa:
3252 result = &PL_vtbl_isa;
3253 break;
3254 case want_vtbl_isaelem:
3255 result = &PL_vtbl_isaelem;
3256 break;
3257 case want_vtbl_arylen:
3258 result = &PL_vtbl_arylen;
3259 break;
3260 case want_vtbl_glob:
3261 result = &PL_vtbl_glob;
3262 break;
3263 case want_vtbl_mglob:
3264 result = &PL_vtbl_mglob;
3265 break;
3266 case want_vtbl_nkeys:
3267 result = &PL_vtbl_nkeys;
3268 break;
3269 case want_vtbl_taint:
3270 result = &PL_vtbl_taint;
3271 break;
3272 case want_vtbl_substr:
3273 result = &PL_vtbl_substr;
3274 break;
3275 case want_vtbl_vec:
3276 result = &PL_vtbl_vec;
3277 break;
3278 case want_vtbl_pos:
3279 result = &PL_vtbl_pos;
3280 break;
3281 case want_vtbl_bm:
3282 result = &PL_vtbl_bm;
3283 break;
3284 case want_vtbl_fm:
3285 result = &PL_vtbl_fm;
3286 break;
3287 case want_vtbl_uvar:
3288 result = &PL_vtbl_uvar;
3289 break;
3290 case want_vtbl_defelem:
3291 result = &PL_vtbl_defelem;
3292 break;
3293 case want_vtbl_regexp:
3294 result = &PL_vtbl_regexp;
3295 break;
3296 case want_vtbl_regdata:
3297 result = &PL_vtbl_regdata;
3298 break;
3299 case want_vtbl_regdatum:
3300 result = &PL_vtbl_regdatum;
3301 break;
3302#ifdef USE_LOCALE_COLLATE
3303 case want_vtbl_collxfrm:
3304 result = &PL_vtbl_collxfrm;
3305 break;
3306#endif
3307 case want_vtbl_amagic:
3308 result = &PL_vtbl_amagic;
3309 break;
3310 case want_vtbl_amagicelem:
3311 result = &PL_vtbl_amagicelem;
3312 break;
3313 case want_vtbl_backref:
3314 result = &PL_vtbl_backref;
3315 break;
3316 case want_vtbl_utf8:
3317 result = &PL_vtbl_utf8;
3318 break;
3319 default:
3320 result = Null(MGVTBL*);
3321 break;
3322 }
3323 return (MGVTBL*)result;
3324}
3325
3326I32
3327Perl_my_fflush_all(pTHX)
3328{
3329#if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3330 return PerlIO_flush(NULL);
3331#else
3332# if defined(HAS__FWALK)
3333 extern int fflush(FILE *);
3334 /* undocumented, unprototyped, but very useful BSDism */
3335 extern void _fwalk(int (*)(FILE *));
3336 _fwalk(&fflush);
3337 return 0;
3338# else
3339# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3340 long open_max = -1;
3341# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3342 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3343# else
3344# if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3345 open_max = sysconf(_SC_OPEN_MAX);
3346# else
3347# ifdef FOPEN_MAX
3348 open_max = FOPEN_MAX;
3349# else
3350# ifdef OPEN_MAX
3351 open_max = OPEN_MAX;
3352# else
3353# ifdef _NFILE
3354 open_max = _NFILE;
3355# endif
3356# endif
3357# endif
3358# endif
3359# endif
3360 if (open_max > 0) {
3361 long i;
3362 for (i = 0; i < open_max; i++)
3363 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3364 STDIO_STREAM_ARRAY[i]._file < open_max &&
3365 STDIO_STREAM_ARRAY[i]._flag)
3366 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3367 return 0;
3368 }
3369# endif
3370 SETERRNO(EBADF,RMS_IFI);
3371 return EOF;
3372# endif
3373#endif
3374}
3375
3376void
3377Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3378{
3379 const char * const func =
3380 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3381 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3382 PL_op_desc[op];
3383 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3384 const char * const type = OP_IS_SOCKET(op)
3385 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3386 ? "socket" : "filehandle";
3387 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3388
3389 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3390 if (ckWARN(WARN_IO)) {
3391 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3392 if (name && *name)
3393 Perl_warner(aTHX_ packWARN(WARN_IO),
3394 "Filehandle %s opened only for %sput",
3395 name, direction);
3396 else
3397 Perl_warner(aTHX_ packWARN(WARN_IO),
3398 "Filehandle opened only for %sput", direction);
3399 }
3400 }
3401 else {
3402 const char *vile;
3403 I32 warn_type;
3404
3405 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3406 vile = "closed";
3407 warn_type = WARN_CLOSED;
3408 }
3409 else {
3410 vile = "unopened";
3411 warn_type = WARN_UNOPENED;
3412 }
3413
3414 if (ckWARN(warn_type)) {
3415 if (name && *name) {
3416 Perl_warner(aTHX_ packWARN(warn_type),
3417 "%s%s on %s %s %s", func, pars, vile, type, name);
3418 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3419 Perl_warner(
3420 aTHX_ packWARN(warn_type),
3421 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3422 func, pars, name
3423 );
3424 }
3425 else {
3426 Perl_warner(aTHX_ packWARN(warn_type),
3427 "%s%s on %s %s", func, pars, vile, type);
3428 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3429 Perl_warner(
3430 aTHX_ packWARN(warn_type),
3431 "\t(Are you trying to call %s%s on dirhandle?)\n",
3432 func, pars
3433 );
3434 }
3435 }
3436 }
3437}
3438
3439#ifdef EBCDIC
3440/* in ASCII order, not that it matters */
3441static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3442
3443int
3444Perl_ebcdic_control(pTHX_ int ch)
3445{
3446 if (ch > 'a') {
3447 const char *ctlp;
3448
3449 if (islower(ch))
3450 ch = toupper(ch);
3451
3452 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3453 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3454 }
3455
3456 if (ctlp == controllablechars)
3457 return('\177'); /* DEL */
3458 else
3459 return((unsigned char)(ctlp - controllablechars - 1));
3460 } else { /* Want uncontrol */
3461 if (ch == '\177' || ch == -1)
3462 return('?');
3463 else if (ch == '\157')
3464 return('\177');
3465 else if (ch == '\174')
3466 return('\000');
3467 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3468 return('\036');
3469 else if (ch == '\155')
3470 return('\037');
3471 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3472 return(controllablechars[ch+1]);
3473 else
3474 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3475 }
3476}
3477#endif
3478
3479/* To workaround core dumps from the uninitialised tm_zone we get the
3480 * system to give us a reasonable struct to copy. This fix means that
3481 * strftime uses the tm_zone and tm_gmtoff values returned by
3482 * localtime(time()). That should give the desired result most of the
3483 * time. But probably not always!
3484 *
3485 * This does not address tzname aspects of NETaa14816.
3486 *
3487 */
3488
3489#ifdef HAS_GNULIBC
3490# ifndef STRUCT_TM_HASZONE
3491# define STRUCT_TM_HASZONE
3492# endif
3493#endif
3494
3495#ifdef STRUCT_TM_HASZONE /* Backward compat */
3496# ifndef HAS_TM_TM_ZONE
3497# define HAS_TM_TM_ZONE
3498# endif
3499#endif
3500
3501void
3502Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3503{
3504#ifdef HAS_TM_TM_ZONE
3505 Time_t now;
3506 const struct tm* my_tm;
3507 (void)time(&now);
3508 my_tm = localtime(&now);
3509 if (my_tm)
3510 Copy(my_tm, ptm, 1, struct tm);
3511#else
3512 PERL_UNUSED_ARG(ptm);
3513#endif
3514}
3515
3516/*
3517 * mini_mktime - normalise struct tm values without the localtime()
3518 * semantics (and overhead) of mktime().
3519 */
3520void
3521Perl_mini_mktime(pTHX_ struct tm *ptm)
3522{
3523 int yearday;
3524 int secs;
3525 int month, mday, year, jday;
3526 int odd_cent, odd_year;
3527
3528#define DAYS_PER_YEAR 365
3529#define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3530#define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3531#define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3532#define SECS_PER_HOUR (60*60)
3533#define SECS_PER_DAY (24*SECS_PER_HOUR)
3534/* parentheses deliberately absent on these two, otherwise they don't work */
3535#define MONTH_TO_DAYS 153/5
3536#define DAYS_TO_MONTH 5/153
3537/* offset to bias by March (month 4) 1st between month/mday & year finding */
3538#define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3539/* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3540#define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3541
3542/*
3543 * Year/day algorithm notes:
3544 *
3545 * With a suitable offset for numeric value of the month, one can find
3546 * an offset into the year by considering months to have 30.6 (153/5) days,
3547 * using integer arithmetic (i.e., with truncation). To avoid too much
3548 * messing about with leap days, we consider January and February to be
3549 * the 13th and 14th month of the previous year. After that transformation,
3550 * we need the month index we use to be high by 1 from 'normal human' usage,
3551 * so the month index values we use run from 4 through 15.
3552 *
3553 * Given that, and the rules for the Gregorian calendar (leap years are those
3554 * divisible by 4 unless also divisible by 100, when they must be divisible
3555 * by 400 instead), we can simply calculate the number of days since some
3556 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3557 * the days we derive from our month index, and adding in the day of the
3558 * month. The value used here is not adjusted for the actual origin which
3559 * it normally would use (1 January A.D. 1), since we're not exposing it.
3560 * We're only building the value so we can turn around and get the
3561 * normalised values for the year, month, day-of-month, and day-of-year.
3562 *
3563 * For going backward, we need to bias the value we're using so that we find
3564 * the right year value. (Basically, we don't want the contribution of
3565 * March 1st to the number to apply while deriving the year). Having done
3566 * that, we 'count up' the contribution to the year number by accounting for
3567 * full quadracenturies (400-year periods) with their extra leap days, plus
3568 * the contribution from full centuries (to avoid counting in the lost leap
3569 * days), plus the contribution from full quad-years (to count in the normal
3570 * leap days), plus the leftover contribution from any non-leap years.
3571 * At this point, if we were working with an actual leap day, we'll have 0
3572 * days left over. This is also true for March 1st, however. So, we have
3573 * to special-case that result, and (earlier) keep track of the 'odd'
3574 * century and year contributions. If we got 4 extra centuries in a qcent,
3575 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3576 * Otherwise, we add back in the earlier bias we removed (the 123 from
3577 * figuring in March 1st), find the month index (integer division by 30.6),
3578 * and the remainder is the day-of-month. We then have to convert back to
3579 * 'real' months (including fixing January and February from being 14/15 in
3580 * the previous year to being in the proper year). After that, to get
3581 * tm_yday, we work with the normalised year and get a new yearday value for
3582 * January 1st, which we subtract from the yearday value we had earlier,
3583 * representing the date we've re-built. This is done from January 1
3584 * because tm_yday is 0-origin.
3585 *
3586 * Since POSIX time routines are only guaranteed to work for times since the
3587 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3588 * applies Gregorian calendar rules even to dates before the 16th century
3589 * doesn't bother me. Besides, you'd need cultural context for a given
3590 * date to know whether it was Julian or Gregorian calendar, and that's
3591 * outside the scope for this routine. Since we convert back based on the
3592 * same rules we used to build the yearday, you'll only get strange results
3593 * for input which needed normalising, or for the 'odd' century years which
3594 * were leap years in the Julian calander but not in the Gregorian one.
3595 * I can live with that.
3596 *
3597 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3598 * that's still outside the scope for POSIX time manipulation, so I don't
3599 * care.
3600 */
3601
3602 year = 1900 + ptm->tm_year;
3603 month = ptm->tm_mon;
3604 mday = ptm->tm_mday;
3605 /* allow given yday with no month & mday to dominate the result */
3606 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3607 month = 0;
3608 mday = 0;
3609 jday = 1 + ptm->tm_yday;
3610 }
3611 else {
3612 jday = 0;
3613 }
3614 if (month >= 2)
3615 month+=2;
3616 else
3617 month+=14, year--;
3618 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3619 yearday += month*MONTH_TO_DAYS + mday + jday;
3620 /*
3621 * Note that we don't know when leap-seconds were or will be,
3622 * so we have to trust the user if we get something which looks
3623 * like a sensible leap-second. Wild values for seconds will
3624 * be rationalised, however.
3625 */
3626 if ((unsigned) ptm->tm_sec <= 60) {
3627 secs = 0;
3628 }
3629 else {
3630 secs = ptm->tm_sec;
3631 ptm->tm_sec = 0;
3632 }
3633 secs += 60 * ptm->tm_min;
3634 secs += SECS_PER_HOUR * ptm->tm_hour;
3635 if (secs < 0) {
3636 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3637 /* got negative remainder, but need positive time */
3638 /* back off an extra day to compensate */
3639 yearday += (secs/SECS_PER_DAY)-1;
3640 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3641 }
3642 else {
3643 yearday += (secs/SECS_PER_DAY);
3644 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3645 }
3646 }
3647 else if (secs >= SECS_PER_DAY) {
3648 yearday += (secs/SECS_PER_DAY);
3649 secs %= SECS_PER_DAY;
3650 }
3651 ptm->tm_hour = secs/SECS_PER_HOUR;
3652 secs %= SECS_PER_HOUR;
3653 ptm->tm_min = secs/60;
3654 secs %= 60;
3655 ptm->tm_sec += secs;
3656 /* done with time of day effects */
3657 /*
3658 * The algorithm for yearday has (so far) left it high by 428.
3659 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3660 * bias it by 123 while trying to figure out what year it
3661 * really represents. Even with this tweak, the reverse
3662 * translation fails for years before A.D. 0001.
3663 * It would still fail for Feb 29, but we catch that one below.
3664 */
3665 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3666 yearday -= YEAR_ADJUST;
3667 year = (yearday / DAYS_PER_QCENT) * 400;
3668 yearday %= DAYS_PER_QCENT;
3669 odd_cent = yearday / DAYS_PER_CENT;
3670 year += odd_cent * 100;
3671 yearday %= DAYS_PER_CENT;
3672 year += (yearday / DAYS_PER_QYEAR) * 4;
3673 yearday %= DAYS_PER_QYEAR;
3674 odd_year = yearday / DAYS_PER_YEAR;
3675 year += odd_year;
3676 yearday %= DAYS_PER_YEAR;
3677 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3678 month = 1;
3679 yearday = 29;
3680 }
3681 else {
3682 yearday += YEAR_ADJUST; /* recover March 1st crock */
3683 month = yearday*DAYS_TO_MONTH;
3684 yearday -= month*MONTH_TO_DAYS;
3685 /* recover other leap-year adjustment */
3686 if (month > 13) {
3687 month-=14;
3688 year++;
3689 }
3690 else {
3691 month-=2;
3692 }
3693 }
3694 ptm->tm_year = year - 1900;
3695 if (yearday) {
3696 ptm->tm_mday = yearday;
3697 ptm->tm_mon = month;
3698 }
3699 else {
3700 ptm->tm_mday = 31;
3701 ptm->tm_mon = month - 1;
3702 }
3703 /* re-build yearday based on Jan 1 to get tm_yday */
3704 year--;
3705 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3706 yearday += 14*MONTH_TO_DAYS + 1;
3707 ptm->tm_yday = jday - yearday;
3708 /* fix tm_wday if not overridden by caller */
3709 if ((unsigned)ptm->tm_wday > 6)
3710 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3711}
3712
3713char *
3714Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3715{
3716#ifdef HAS_STRFTIME
3717 char *buf;
3718 int buflen;
3719 struct tm mytm;
3720 int len;
3721
3722 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3723 mytm.tm_sec = sec;
3724 mytm.tm_min = min;
3725 mytm.tm_hour = hour;
3726 mytm.tm_mday = mday;
3727 mytm.tm_mon = mon;
3728 mytm.tm_year = year;
3729 mytm.tm_wday = wday;
3730 mytm.tm_yday = yday;
3731 mytm.tm_isdst = isdst;
3732 mini_mktime(&mytm);
3733 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3734#if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3735 STMT_START {
3736 struct tm mytm2;
3737 mytm2 = mytm;
3738 mktime(&mytm2);
3739#ifdef HAS_TM_TM_GMTOFF
3740 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3741#endif
3742#ifdef HAS_TM_TM_ZONE
3743 mytm.tm_zone = mytm2.tm_zone;
3744#endif
3745 } STMT_END;
3746#endif
3747 buflen = 64;
3748 Newx(buf, buflen, char);
3749 len = strftime(buf, buflen, fmt, &mytm);
3750 /*
3751 ** The following is needed to handle to the situation where
3752 ** tmpbuf overflows. Basically we want to allocate a buffer
3753 ** and try repeatedly. The reason why it is so complicated
3754 ** is that getting a return value of 0 from strftime can indicate
3755 ** one of the following:
3756 ** 1. buffer overflowed,
3757 ** 2. illegal conversion specifier, or
3758 ** 3. the format string specifies nothing to be returned(not
3759 ** an error). This could be because format is an empty string
3760 ** or it specifies %p that yields an empty string in some locale.
3761 ** If there is a better way to make it portable, go ahead by
3762 ** all means.
3763 */
3764 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3765 return buf;
3766 else {
3767 /* Possibly buf overflowed - try again with a bigger buf */
3768 const int fmtlen = strlen(fmt);
3769 const int bufsize = fmtlen + buflen;
3770
3771 Newx(buf, bufsize, char);
3772 while (buf) {
3773 buflen = strftime(buf, bufsize, fmt, &mytm);
3774 if (buflen > 0 && buflen < bufsize)
3775 break;
3776 /* heuristic to prevent out-of-memory errors */
3777 if (bufsize > 100*fmtlen) {
3778 Safefree(buf);
3779 buf = NULL;
3780 break;
3781 }
3782 Renew(buf, bufsize*2, char);
3783 }
3784 return buf;
3785 }
3786#else
3787 Perl_croak(aTHX_ "panic: no strftime");
3788 return NULL;
3789#endif
3790}
3791
3792
3793#define SV_CWD_RETURN_UNDEF \
3794sv_setsv(sv, &PL_sv_undef); \
3795return FALSE
3796
3797#define SV_CWD_ISDOT(dp) \
3798 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3799 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3800
3801/*
3802=head1 Miscellaneous Functions
3803
3804=for apidoc getcwd_sv
3805
3806Fill the sv with current working directory
3807
3808=cut
3809*/
3810
3811/* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3812 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3813 * getcwd(3) if available
3814 * Comments from the orignal:
3815 * This is a faster version of getcwd. It's also more dangerous
3816 * because you might chdir out of a directory that you can't chdir
3817 * back into. */
3818
3819int
3820Perl_getcwd_sv(pTHX_ register SV *sv)
3821{
3822#ifndef PERL_MICRO
3823 dVAR;
3824#ifndef INCOMPLETE_TAINTS
3825 SvTAINTED_on(sv);
3826#endif
3827
3828#ifdef HAS_GETCWD
3829 {
3830 char buf[MAXPATHLEN];
3831
3832 /* Some getcwd()s automatically allocate a buffer of the given
3833 * size from the heap if they are given a NULL buffer pointer.
3834 * The problem is that this behaviour is not portable. */
3835 if (getcwd(buf, sizeof(buf) - 1)) {
3836 sv_setpv(sv, buf);
3837 return TRUE;
3838 }
3839 else {
3840 sv_setsv(sv, &PL_sv_undef);
3841 return FALSE;
3842 }
3843 }
3844
3845#else
3846
3847 Stat_t statbuf;
3848 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3849 int pathlen=0;
3850 Direntry_t *dp;
3851
3852 SvUPGRADE(sv, SVt_PV);
3853
3854 if (PerlLIO_lstat(".", &statbuf) < 0) {
3855 SV_CWD_RETURN_UNDEF;
3856 }
3857
3858 orig_cdev = statbuf.st_dev;
3859 orig_cino = statbuf.st_ino;
3860 cdev = orig_cdev;
3861 cino = orig_cino;
3862
3863 for (;;) {
3864 DIR *dir;
3865 odev = cdev;
3866 oino = cino;
3867
3868 if (PerlDir_chdir("..") < 0) {
3869 SV_CWD_RETURN_UNDEF;
3870 }
3871 if (PerlLIO_stat(".", &statbuf) < 0) {
3872 SV_CWD_RETURN_UNDEF;
3873 }
3874
3875 cdev = statbuf.st_dev;
3876 cino = statbuf.st_ino;
3877
3878 if (odev == cdev && oino == cino) {
3879 break;
3880 }
3881 if (!(dir = PerlDir_open("."))) {
3882 SV_CWD_RETURN_UNDEF;
3883 }
3884
3885 while ((dp = PerlDir_read(dir)) != NULL) {
3886#ifdef DIRNAMLEN
3887 const int namelen = dp->d_namlen;
3888#else
3889 const int namelen = strlen(dp->d_name);
3890#endif
3891 /* skip . and .. */
3892 if (SV_CWD_ISDOT(dp)) {
3893 continue;
3894 }
3895
3896 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3897 SV_CWD_RETURN_UNDEF;
3898 }
3899
3900 tdev = statbuf.st_dev;
3901 tino = statbuf.st_ino;
3902 if (tino == oino && tdev == odev) {
3903 break;
3904 }
3905 }
3906
3907 if (!dp) {
3908 SV_CWD_RETURN_UNDEF;
3909 }
3910
3911 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3912 SV_CWD_RETURN_UNDEF;
3913 }
3914
3915 SvGROW(sv, pathlen + namelen + 1);
3916
3917 if (pathlen) {
3918 /* shift down */
3919 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3920 }
3921
3922 /* prepend current directory to the front */
3923 *SvPVX(sv) = '/';
3924 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3925 pathlen += (namelen + 1);
3926
3927#ifdef VOID_CLOSEDIR
3928 PerlDir_close(dir);
3929#else
3930 if (PerlDir_close(dir) < 0) {
3931 SV_CWD_RETURN_UNDEF;
3932 }
3933#endif
3934 }
3935
3936 if (pathlen) {
3937 SvCUR_set(sv, pathlen);
3938 *SvEND(sv) = '\0';
3939 SvPOK_only(sv);
3940
3941 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3942 SV_CWD_RETURN_UNDEF;
3943 }
3944 }
3945 if (PerlLIO_stat(".", &statbuf) < 0) {
3946 SV_CWD_RETURN_UNDEF;
3947 }
3948
3949 cdev = statbuf.st_dev;
3950 cino = statbuf.st_ino;
3951
3952 if (cdev != orig_cdev || cino != orig_cino) {
3953 Perl_croak(aTHX_ "Unstable directory path, "
3954 "current directory changed unexpectedly");
3955 }
3956
3957 return TRUE;
3958#endif
3959
3960#else
3961 return FALSE;
3962#endif
3963}
3964
3965/*
3966=for apidoc scan_version
3967
3968Returns a pointer to the next character after the parsed
3969version string, as well as upgrading the passed in SV to
3970an RV.
3971
3972Function must be called with an already existing SV like
3973
3974 sv = newSV(0);
3975 s = scan_version(s,SV *sv, bool qv);
3976
3977Performs some preprocessing to the string to ensure that
3978it has the correct characteristics of a version. Flags the
3979object if it contains an underscore (which denotes this
3980is a alpha version). The boolean qv denotes that the version
3981should be interpreted as if it had multiple decimals, even if
3982it doesn't.
3983
3984=cut
3985*/
3986
3987const char *
3988Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
3989{
3990 const char *start;
3991 const char *pos;
3992 const char *last;
3993 int saw_period = 0;
3994 int alpha = 0;
3995 int width = 3;
3996 AV * const av = newAV();
3997 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
3998 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
3999
4000#ifndef NODEFAULT_SHAREKEYS
4001 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4002#endif
4003
4004 while (isSPACE(*s)) /* leading whitespace is OK */
4005 s++;
4006
4007 if (*s == 'v') {
4008 s++; /* get past 'v' */
4009 qv = 1; /* force quoted version processing */
4010 }
4011
4012 start = last = pos = s;
4013
4014 /* pre-scan the input string to check for decimals/underbars */
4015 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4016 {
4017 if ( *pos == '.' )
4018 {
4019 if ( alpha )
4020 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4021 saw_period++ ;
4022 last = pos;
4023 }
4024 else if ( *pos == '_' )
4025 {
4026 if ( alpha )
4027 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4028 alpha = 1;
4029 width = pos - last - 1; /* natural width of sub-version */
4030 }
4031 pos++;
4032 }
4033
4034 if ( alpha && !saw_period )
4035 Perl_croak(aTHX_ "Invalid version format (alpha without decimal)");
4036
4037 if ( saw_period > 1 )
4038 qv = 1; /* force quoted version processing */
4039
4040 pos = s;
4041
4042 if ( qv )
4043 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
4044 if ( alpha )
4045 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
4046 if ( !qv && width < 3 )
4047 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4048
4049 while (isDIGIT(*pos))
4050 pos++;
4051 if (!isALPHA(*pos)) {
4052 I32 rev;
4053
4054 for (;;) {
4055 rev = 0;
4056 {
4057 /* this is atoi() that delimits on underscores */
4058 const char *end = pos;
4059 I32 mult = 1;
4060 I32 orev;
4061
4062 /* the following if() will only be true after the decimal
4063 * point of a version originally created with a bare
4064 * floating point number, i.e. not quoted in any way
4065 */
4066 if ( !qv && s > start && saw_period == 1 ) {
4067 mult *= 100;
4068 while ( s < end ) {
4069 orev = rev;
4070 rev += (*s - '0') * mult;
4071 mult /= 10;
4072 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4073 Perl_croak(aTHX_ "Integer overflow in version");
4074 s++;
4075 if ( *s == '_' )
4076 s++;
4077 }
4078 }
4079 else {
4080 while (--end >= s) {
4081 orev = rev;
4082 rev += (*end - '0') * mult;
4083 mult *= 10;
4084 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4085 Perl_croak(aTHX_ "Integer overflow in version");
4086 }
4087 }
4088 }
4089
4090 /* Append revision */
4091 av_push(av, newSViv(rev));
4092 if ( *pos == '.' && isDIGIT(pos[1]) )
4093 s = ++pos;
4094 else if ( *pos == '_' && isDIGIT(pos[1]) )
4095 s = ++pos;
4096 else if ( isDIGIT(*pos) )
4097 s = pos;
4098 else {
4099 s = pos;
4100 break;
4101 }
4102 if ( qv ) {
4103 while ( isDIGIT(*pos) )
4104 pos++;
4105 }
4106 else {
4107 int digits = 0;
4108 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4109 if ( *pos != '_' )
4110 digits++;
4111 pos++;
4112 }
4113 }
4114 }
4115 }
4116 if ( qv ) { /* quoted versions always get at least three terms*/
4117 I32 len = av_len(av);
4118 /* This for loop appears to trigger a compiler bug on OS X, as it
4119 loops infinitely. Yes, len is negative. No, it makes no sense.
4120 Compiler in question is:
4121 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4122 for ( len = 2 - len; len > 0; len-- )
4123 av_push((AV *)sv, newSViv(0));
4124 */
4125 len = 2 - len;
4126 while (len-- > 0)
4127 av_push(av, newSViv(0));
4128 }
4129
4130 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4131 av_push(av, newSViv(0));
4132
4133 /* And finally, store the AV in the hash */
4134 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4135 return s;
4136}
4137
4138/*
4139=for apidoc new_version
4140
4141Returns a new version object based on the passed in SV:
4142
4143 SV *sv = new_version(SV *ver);
4144
4145Does not alter the passed in ver SV. See "upg_version" if you
4146want to upgrade the SV.
4147
4148=cut
4149*/
4150
4151SV *
4152Perl_new_version(pTHX_ SV *ver)
4153{
4154 dVAR;
4155 SV * const rv = newSV(0);
4156 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4157 {
4158 I32 key;
4159 AV * const av = newAV();
4160 AV *sav;
4161 /* This will get reblessed later if a derived class*/
4162 SV * const hv = newSVrv(rv, "version");
4163 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4164#ifndef NODEFAULT_SHAREKEYS
4165 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4166#endif
4167
4168 if ( SvROK(ver) )
4169 ver = SvRV(ver);
4170
4171 /* Begin copying all of the elements */
4172 if ( hv_exists((HV *)ver, "qv", 2) )
4173 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4174
4175 if ( hv_exists((HV *)ver, "alpha", 5) )
4176 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4177
4178 if ( hv_exists((HV*)ver, "width", 5 ) )
4179 {
4180 const I32 width = SvIV(*hv_fetch((HV*)ver, "width", 5, FALSE));
4181 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4182 }
4183
4184 sav = (AV *)SvRV(*hv_fetch((HV*)ver, "version", 7, FALSE));
4185 /* This will get reblessed later if a derived class*/
4186 for ( key = 0; key <= av_len(sav); key++ )
4187 {
4188 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4189 av_push(av, newSViv(rev));
4190 }
4191
4192 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4193 return rv;
4194 }
4195#ifdef SvVOK
4196 if ( SvVOK(ver) ) { /* already a v-string */
4197 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4198 const STRLEN len = mg->mg_len;
4199 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4200 sv_setpvn(rv,version,len);
4201 Safefree(version);
4202 }
4203 else {
4204#endif
4205 sv_setsv(rv,ver); /* make a duplicate */
4206#ifdef SvVOK
4207 }
4208#endif
4209 upg_version(rv);
4210 return rv;
4211}
4212
4213/*
4214=for apidoc upg_version
4215
4216In-place upgrade of the supplied SV to a version object.
4217
4218 SV *sv = upg_version(SV *sv);
4219
4220Returns a pointer to the upgraded SV.
4221
4222=cut
4223*/
4224
4225SV *
4226Perl_upg_version(pTHX_ SV *ver)
4227{
4228 char *version;
4229 bool qv = 0;
4230
4231 if ( SvNOK(ver) ) /* may get too much accuracy */
4232 {
4233 char tbuf[64];
4234 const STRLEN len = my_sprintf(tbuf,"%.9"NVgf, SvNVX(ver));
4235 version = savepvn(tbuf, len);
4236 }
4237#ifdef SvVOK
4238 else if ( SvVOK(ver) ) { /* already a v-string */
4239 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4240 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4241 qv = 1;
4242 }
4243#endif
4244 else /* must be a string or something like a string */
4245 {
4246 version = savepv(SvPV_nolen(ver));
4247 }
4248 (void)scan_version(version, ver, qv);
4249 Safefree(version);
4250 return ver;
4251}
4252
4253/*
4254=for apidoc vverify
4255
4256Validates that the SV contains a valid version object.
4257
4258 bool vverify(SV *vobj);
4259
4260Note that it only confirms the bare minimum structure (so as not to get
4261confused by derived classes which may contain additional hash entries):
4262
4263=over 4
4264
4265=item * The SV contains a [reference to a] hash
4266
4267=item * The hash contains a "version" key
4268
4269=item * The "version" key has [a reference to] an AV as its value
4270
4271=back
4272
4273=cut
4274*/
4275
4276bool
4277Perl_vverify(pTHX_ SV *vs)
4278{
4279 SV *sv;
4280 if ( SvROK(vs) )
4281 vs = SvRV(vs);
4282
4283 /* see if the appropriate elements exist */
4284 if ( SvTYPE(vs) == SVt_PVHV
4285 && hv_exists((HV*)vs, "version", 7)
4286 && (sv = SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)))
4287 && SvTYPE(sv) == SVt_PVAV )
4288 return TRUE;
4289 else
4290 return FALSE;
4291}
4292
4293/*
4294=for apidoc vnumify
4295
4296Accepts a version object and returns the normalized floating
4297point representation. Call like:
4298
4299 sv = vnumify(rv);
4300
4301NOTE: you can pass either the object directly or the SV
4302contained within the RV.
4303
4304=cut
4305*/
4306
4307SV *
4308Perl_vnumify(pTHX_ SV *vs)
4309{
4310 I32 i, len, digit;
4311 int width;
4312 bool alpha = FALSE;
4313 SV * const sv = newSV(0);
4314 AV *av;
4315 if ( SvROK(vs) )
4316 vs = SvRV(vs);
4317
4318 if ( !vverify(vs) )
4319 Perl_croak(aTHX_ "Invalid version object");
4320
4321 /* see if various flags exist */
4322 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4323 alpha = TRUE;
4324 if ( hv_exists((HV*)vs, "width", 5 ) )
4325 width = SvIV(*hv_fetch((HV*)vs, "width", 5, FALSE));
4326 else
4327 width = 3;
4328
4329
4330 /* attempt to retrieve the version array */
4331 if ( !(av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)) ) ) {
4332 sv_catpvs(sv,"0");
4333 return sv;
4334 }
4335
4336 len = av_len(av);
4337 if ( len == -1 )
4338 {
4339 sv_catpvs(sv,"0");
4340 return sv;
4341 }
4342
4343 digit = SvIV(*av_fetch(av, 0, 0));
4344 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4345 for ( i = 1 ; i < len ; i++ )
4346 {
4347 digit = SvIV(*av_fetch(av, i, 0));
4348 if ( width < 3 ) {
4349 const int denom = (width == 2 ? 10 : 100);
4350 const div_t term = div((int)PERL_ABS(digit),denom);
4351 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4352 }
4353 else {
4354 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4355 }
4356 }
4357
4358 if ( len > 0 )
4359 {
4360 digit = SvIV(*av_fetch(av, len, 0));
4361 if ( alpha && width == 3 ) /* alpha version */
4362 sv_catpvs(sv,"_");
4363 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4364 }
4365 else /* len == 0 */
4366 {
4367 sv_catpvs(sv, "000");
4368 }
4369 return sv;
4370}
4371
4372/*
4373=for apidoc vnormal
4374
4375Accepts a version object and returns the normalized string
4376representation. Call like:
4377
4378 sv = vnormal(rv);
4379
4380NOTE: you can pass either the object directly or the SV
4381contained within the RV.
4382
4383=cut
4384*/
4385
4386SV *
4387Perl_vnormal(pTHX_ SV *vs)
4388{
4389 I32 i, len, digit;
4390 bool alpha = FALSE;
4391 SV * const sv = newSV(0);
4392 AV *av;
4393 if ( SvROK(vs) )
4394 vs = SvRV(vs);
4395
4396 if ( !vverify(vs) )
4397 Perl_croak(aTHX_ "Invalid version object");
4398
4399 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4400 alpha = TRUE;
4401 av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE));
4402
4403 len = av_len(av);
4404 if ( len == -1 )
4405 {
4406 sv_catpvs(sv,"");
4407 return sv;
4408 }
4409 digit = SvIV(*av_fetch(av, 0, 0));
4410 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4411 for ( i = 1 ; i < len ; i++ ) {
4412 digit = SvIV(*av_fetch(av, i, 0));
4413 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4414 }
4415
4416 if ( len > 0 )
4417 {
4418 /* handle last digit specially */
4419 digit = SvIV(*av_fetch(av, len, 0));
4420 if ( alpha )
4421 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4422 else
4423 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4424 }
4425
4426 if ( len <= 2 ) { /* short version, must be at least three */
4427 for ( len = 2 - len; len != 0; len-- )
4428 sv_catpvs(sv,".0");
4429 }
4430 return sv;
4431}
4432
4433/*
4434=for apidoc vstringify
4435
4436In order to maintain maximum compatibility with earlier versions
4437of Perl, this function will return either the floating point
4438notation or the multiple dotted notation, depending on whether
4439the original version contained 1 or more dots, respectively
4440
4441=cut
4442*/
4443
4444SV *
4445Perl_vstringify(pTHX_ SV *vs)
4446{
4447 if ( SvROK(vs) )
4448 vs = SvRV(vs);
4449
4450 if ( !vverify(vs) )
4451 Perl_croak(aTHX_ "Invalid version object");
4452
4453 if ( hv_exists((HV *)vs, "qv", 2) )
4454 return vnormal(vs);
4455 else
4456 return vnumify(vs);
4457}
4458
4459/*
4460=for apidoc vcmp
4461
4462Version object aware cmp. Both operands must already have been
4463converted into version objects.
4464
4465=cut
4466*/
4467
4468int
4469Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4470{
4471 I32 i,l,m,r,retval;
4472 bool lalpha = FALSE;
4473 bool ralpha = FALSE;
4474 I32 left = 0;
4475 I32 right = 0;
4476 AV *lav, *rav;
4477 if ( SvROK(lhv) )
4478 lhv = SvRV(lhv);
4479 if ( SvROK(rhv) )
4480 rhv = SvRV(rhv);
4481
4482 if ( !vverify(lhv) )
4483 Perl_croak(aTHX_ "Invalid version object");
4484
4485 if ( !vverify(rhv) )
4486 Perl_croak(aTHX_ "Invalid version object");
4487
4488 /* get the left hand term */
4489 lav = (AV *)SvRV(*hv_fetch((HV*)lhv, "version", 7, FALSE));
4490 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4491 lalpha = TRUE;
4492
4493 /* and the right hand term */
4494 rav = (AV *)SvRV(*hv_fetch((HV*)rhv, "version", 7, FALSE));
4495 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4496 ralpha = TRUE;
4497
4498 l = av_len(lav);
4499 r = av_len(rav);
4500 m = l < r ? l : r;
4501 retval = 0;
4502 i = 0;
4503 while ( i <= m && retval == 0 )
4504 {
4505 left = SvIV(*av_fetch(lav,i,0));
4506 right = SvIV(*av_fetch(rav,i,0));
4507 if ( left < right )
4508 retval = -1;
4509 if ( left > right )
4510 retval = +1;
4511 i++;
4512 }
4513
4514 /* tiebreaker for alpha with identical terms */
4515 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4516 {
4517 if ( lalpha && !ralpha )
4518 {
4519 retval = -1;
4520 }
4521 else if ( ralpha && !lalpha)
4522 {
4523 retval = +1;
4524 }
4525 }
4526
4527 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4528 {
4529 if ( l < r )
4530 {
4531 while ( i <= r && retval == 0 )
4532 {
4533 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4534 retval = -1; /* not a match after all */
4535 i++;
4536 }
4537 }
4538 else
4539 {
4540 while ( i <= l && retval == 0 )
4541 {
4542 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4543 retval = +1; /* not a match after all */
4544 i++;
4545 }
4546 }
4547 }
4548 return retval;
4549}
4550
4551#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4552# define EMULATE_SOCKETPAIR_UDP
4553#endif
4554
4555#ifdef EMULATE_SOCKETPAIR_UDP
4556static int
4557S_socketpair_udp (int fd[2]) {
4558 dTHX;
4559 /* Fake a datagram socketpair using UDP to localhost. */
4560 int sockets[2] = {-1, -1};
4561 struct sockaddr_in addresses[2];
4562 int i;
4563 Sock_size_t size = sizeof(struct sockaddr_in);
4564 unsigned short port;
4565 int got;
4566
4567 memset(&addresses, 0, sizeof(addresses));
4568 i = 1;
4569 do {
4570 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4571 if (sockets[i] == -1)
4572 goto tidy_up_and_fail;
4573
4574 addresses[i].sin_family = AF_INET;
4575 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4576 addresses[i].sin_port = 0; /* kernel choses port. */
4577 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4578 sizeof(struct sockaddr_in)) == -1)
4579 goto tidy_up_and_fail;
4580 } while (i--);
4581
4582 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4583 for each connect the other socket to it. */
4584 i = 1;
4585 do {
4586 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4587 &size) == -1)
4588 goto tidy_up_and_fail;
4589 if (size != sizeof(struct sockaddr_in))
4590 goto abort_tidy_up_and_fail;
4591 /* !1 is 0, !0 is 1 */
4592 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4593 sizeof(struct sockaddr_in)) == -1)
4594 goto tidy_up_and_fail;
4595 } while (i--);
4596
4597 /* Now we have 2 sockets connected to each other. I don't trust some other
4598 process not to have already sent a packet to us (by random) so send
4599 a packet from each to the other. */
4600 i = 1;
4601 do {
4602 /* I'm going to send my own port number. As a short.
4603 (Who knows if someone somewhere has sin_port as a bitfield and needs
4604 this routine. (I'm assuming crays have socketpair)) */
4605 port = addresses[i].sin_port;
4606 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4607 if (got != sizeof(port)) {
4608 if (got == -1)
4609 goto tidy_up_and_fail;
4610 goto abort_tidy_up_and_fail;
4611 }
4612 } while (i--);
4613
4614 /* Packets sent. I don't trust them to have arrived though.
4615 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4616 connect to localhost will use a second kernel thread. In 2.6 the
4617 first thread running the connect() returns before the second completes,
4618 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4619 returns 0. Poor programs have tripped up. One poor program's authors'
4620 had a 50-1 reverse stock split. Not sure how connected these were.)
4621 So I don't trust someone not to have an unpredictable UDP stack.
4622 */
4623
4624 {
4625 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4626 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4627 fd_set rset;
4628
4629 FD_ZERO(&rset);
4630 FD_SET(sockets[0], &rset);
4631 FD_SET(sockets[1], &rset);
4632
4633 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4634 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4635 || !FD_ISSET(sockets[1], &rset)) {
4636 /* I hope this is portable and appropriate. */
4637 if (got == -1)
4638 goto tidy_up_and_fail;
4639 goto abort_tidy_up_and_fail;
4640 }
4641 }
4642
4643 /* And the paranoia department even now doesn't trust it to have arrive
4644 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4645 {
4646 struct sockaddr_in readfrom;
4647 unsigned short buffer[2];
4648
4649 i = 1;
4650 do {
4651#ifdef MSG_DONTWAIT
4652 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4653 sizeof(buffer), MSG_DONTWAIT,
4654 (struct sockaddr *) &readfrom, &size);
4655#else
4656 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4657 sizeof(buffer), 0,
4658 (struct sockaddr *) &readfrom, &size);
4659#endif
4660
4661 if (got == -1)
4662 goto tidy_up_and_fail;
4663 if (got != sizeof(port)
4664 || size != sizeof(struct sockaddr_in)
4665 /* Check other socket sent us its port. */
4666 || buffer[0] != (unsigned short) addresses[!i].sin_port
4667 /* Check kernel says we got the datagram from that socket */
4668 || readfrom.sin_family != addresses[!i].sin_family
4669 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4670 || readfrom.sin_port != addresses[!i].sin_port)
4671 goto abort_tidy_up_and_fail;
4672 } while (i--);
4673 }
4674 /* My caller (my_socketpair) has validated that this is non-NULL */
4675 fd[0] = sockets[0];
4676 fd[1] = sockets[1];
4677 /* I hereby declare this connection open. May God bless all who cross
4678 her. */
4679 return 0;
4680
4681 abort_tidy_up_and_fail:
4682 errno = ECONNABORTED;
4683 tidy_up_and_fail:
4684 {
4685 const int save_errno = errno;
4686 if (sockets[0] != -1)
4687 PerlLIO_close(sockets[0]);
4688 if (sockets[1] != -1)
4689 PerlLIO_close(sockets[1]);
4690 errno = save_errno;
4691 return -1;
4692 }
4693}
4694#endif /* EMULATE_SOCKETPAIR_UDP */
4695
4696#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4697int
4698Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4699 /* Stevens says that family must be AF_LOCAL, protocol 0.
4700 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4701 dTHX;
4702 int listener = -1;
4703 int connector = -1;
4704 int acceptor = -1;
4705 struct sockaddr_in listen_addr;
4706 struct sockaddr_in connect_addr;
4707 Sock_size_t size;
4708
4709 if (protocol
4710#ifdef AF_UNIX
4711 || family != AF_UNIX
4712#endif
4713 ) {
4714 errno = EAFNOSUPPORT;
4715 return -1;
4716 }
4717 if (!fd) {
4718 errno = EINVAL;
4719 return -1;
4720 }
4721
4722#ifdef EMULATE_SOCKETPAIR_UDP
4723 if (type == SOCK_DGRAM)
4724 return S_socketpair_udp(fd);
4725#endif
4726
4727 listener = PerlSock_socket(AF_INET, type, 0);
4728 if (listener == -1)
4729 return -1;
4730 memset(&listen_addr, 0, sizeof(listen_addr));
4731 listen_addr.sin_family = AF_INET;
4732 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4733 listen_addr.sin_port = 0; /* kernel choses port. */
4734 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4735 sizeof(listen_addr)) == -1)
4736 goto tidy_up_and_fail;
4737 if (PerlSock_listen(listener, 1) == -1)
4738 goto tidy_up_and_fail;
4739
4740 connector = PerlSock_socket(AF_INET, type, 0);
4741 if (connector == -1)
4742 goto tidy_up_and_fail;
4743 /* We want to find out the port number to connect to. */
4744 size = sizeof(connect_addr);
4745 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4746 &size) == -1)
4747 goto tidy_up_and_fail;
4748 if (size != sizeof(connect_addr))
4749 goto abort_tidy_up_and_fail;
4750 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4751 sizeof(connect_addr)) == -1)
4752 goto tidy_up_and_fail;
4753
4754 size = sizeof(listen_addr);
4755 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4756 &size);
4757 if (acceptor == -1)
4758 goto tidy_up_and_fail;
4759 if (size != sizeof(listen_addr))
4760 goto abort_tidy_up_and_fail;
4761 PerlLIO_close(listener);
4762 /* Now check we are talking to ourself by matching port and host on the
4763 two sockets. */
4764 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4765 &size) == -1)
4766 goto tidy_up_and_fail;
4767 if (size != sizeof(connect_addr)
4768 || listen_addr.sin_family != connect_addr.sin_family
4769 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4770 || listen_addr.sin_port != connect_addr.sin_port) {
4771 goto abort_tidy_up_and_fail;
4772 }
4773 fd[0] = connector;
4774 fd[1] = acceptor;
4775 return 0;
4776
4777 abort_tidy_up_and_fail:
4778#ifdef ECONNABORTED
4779 errno = ECONNABORTED; /* This would be the standard thing to do. */
4780#else
4781# ifdef ECONNREFUSED
4782 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4783# else
4784 errno = ETIMEDOUT; /* Desperation time. */
4785# endif
4786#endif
4787 tidy_up_and_fail:
4788 {
4789 const int save_errno = errno;
4790 if (listener != -1)
4791 PerlLIO_close(listener);
4792 if (connector != -1)
4793 PerlLIO_close(connector);
4794 if (acceptor != -1)
4795 PerlLIO_close(acceptor);
4796 errno = save_errno;
4797 return -1;
4798 }
4799}
4800#else
4801/* In any case have a stub so that there's code corresponding
4802 * to the my_socketpair in global.sym. */
4803int
4804Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4805#ifdef HAS_SOCKETPAIR
4806 return socketpair(family, type, protocol, fd);
4807#else
4808 return -1;
4809#endif
4810}
4811#endif
4812
4813/*
4814
4815=for apidoc sv_nosharing
4816
4817Dummy routine which "shares" an SV when there is no sharing module present.
4818Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4819Exists to avoid test for a NULL function pointer and because it could
4820potentially warn under some level of strict-ness.
4821
4822=cut
4823*/
4824
4825void
4826Perl_sv_nosharing(pTHX_ SV *sv)
4827{
4828 PERL_UNUSED_ARG(sv);
4829}
4830
4831U32
4832Perl_parse_unicode_opts(pTHX_ const char **popt)
4833{
4834 const char *p = *popt;
4835 U32 opt = 0;
4836
4837 if (*p) {
4838 if (isDIGIT(*p)) {
4839 opt = (U32) atoi(p);
4840 while (isDIGIT(*p)) p++;
4841 if (*p && *p != '\n' && *p != '\r')
4842 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4843 }
4844 else {
4845 for (; *p; p++) {
4846 switch (*p) {
4847 case PERL_UNICODE_STDIN:
4848 opt |= PERL_UNICODE_STDIN_FLAG; break;
4849 case PERL_UNICODE_STDOUT:
4850 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4851 case PERL_UNICODE_STDERR:
4852 opt |= PERL_UNICODE_STDERR_FLAG; break;
4853 case PERL_UNICODE_STD:
4854 opt |= PERL_UNICODE_STD_FLAG; break;
4855 case PERL_UNICODE_IN:
4856 opt |= PERL_UNICODE_IN_FLAG; break;
4857 case PERL_UNICODE_OUT:
4858 opt |= PERL_UNICODE_OUT_FLAG; break;
4859 case PERL_UNICODE_INOUT:
4860 opt |= PERL_UNICODE_INOUT_FLAG; break;
4861 case PERL_UNICODE_LOCALE:
4862 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4863 case PERL_UNICODE_ARGV:
4864 opt |= PERL_UNICODE_ARGV_FLAG; break;
4865 default:
4866 if (*p != '\n' && *p != '\r')
4867 Perl_croak(aTHX_
4868 "Unknown Unicode option letter '%c'", *p);
4869 }
4870 }
4871 }
4872 }
4873 else
4874 opt = PERL_UNICODE_DEFAULT_FLAGS;
4875
4876 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4877 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4878 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4879
4880 *popt = p;
4881
4882 return opt;
4883}
4884
4885U32
4886Perl_seed(pTHX)
4887{
4888 dVAR;
4889 /*
4890 * This is really just a quick hack which grabs various garbage
4891 * values. It really should be a real hash algorithm which
4892 * spreads the effect of every input bit onto every output bit,
4893 * if someone who knows about such things would bother to write it.
4894 * Might be a good idea to add that function to CORE as well.
4895 * No numbers below come from careful analysis or anything here,
4896 * except they are primes and SEED_C1 > 1E6 to get a full-width
4897 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4898 * probably be bigger too.
4899 */
4900#if RANDBITS > 16
4901# define SEED_C1 1000003
4902#define SEED_C4 73819
4903#else
4904# define SEED_C1 25747
4905#define SEED_C4 20639
4906#endif
4907#define SEED_C2 3
4908#define SEED_C3 269
4909#define SEED_C5 26107
4910
4911#ifndef PERL_NO_DEV_RANDOM
4912 int fd;
4913#endif
4914 U32 u;
4915#ifdef VMS
4916# include <starlet.h>
4917 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4918 * in 100-ns units, typically incremented ever 10 ms. */
4919 unsigned int when[2];
4920#else
4921# ifdef HAS_GETTIMEOFDAY
4922 struct timeval when;
4923# else
4924 Time_t when;
4925# endif
4926#endif
4927
4928/* This test is an escape hatch, this symbol isn't set by Configure. */
4929#ifndef PERL_NO_DEV_RANDOM
4930#ifndef PERL_RANDOM_DEVICE
4931 /* /dev/random isn't used by default because reads from it will block
4932 * if there isn't enough entropy available. You can compile with
4933 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4934 * is enough real entropy to fill the seed. */
4935# define PERL_RANDOM_DEVICE "/dev/urandom"
4936#endif
4937 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4938 if (fd != -1) {
4939 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4940 u = 0;
4941 PerlLIO_close(fd);
4942 if (u)
4943 return u;
4944 }
4945#endif
4946
4947#ifdef VMS
4948 _ckvmssts(sys$gettim(when));
4949 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4950#else
4951# ifdef HAS_GETTIMEOFDAY
4952 PerlProc_gettimeofday(&when,NULL);
4953 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4954# else
4955 (void)time(&when);
4956 u = (U32)SEED_C1 * when;
4957# endif
4958#endif
4959 u += SEED_C3 * (U32)PerlProc_getpid();
4960 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4961#ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4962 u += SEED_C5 * (U32)PTR2UV(&when);
4963#endif
4964 return u;
4965}
4966
4967UV
4968Perl_get_hash_seed(pTHX)
4969{
4970 dVAR;
4971 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4972 UV myseed = 0;
4973
4974 if (s)
4975 while (isSPACE(*s)) s++;
4976 if (s && isDIGIT(*s))
4977 myseed = (UV)Atoul(s);
4978 else
4979#ifdef USE_HASH_SEED_EXPLICIT
4980 if (s)
4981#endif
4982 {
4983 /* Compute a random seed */
4984 (void)seedDrand01((Rand_seed_t)seed());
4985 myseed = (UV)(Drand01() * (NV)UV_MAX);
4986#if RANDBITS < (UVSIZE * 8)
4987 /* Since there are not enough randbits to to reach all
4988 * the bits of a UV, the low bits might need extra
4989 * help. Sum in another random number that will
4990 * fill in the low bits. */
4991 myseed +=
4992 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4993#endif /* RANDBITS < (UVSIZE * 8) */
4994 if (myseed == 0) { /* Superparanoia. */
4995 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4996 if (myseed == 0)
4997 Perl_croak(aTHX_ "Your random numbers are not that random");
4998 }
4999 }
5000 PL_rehash_seed_set = TRUE;
5001
5002 return myseed;
5003}
5004
5005#ifdef USE_ITHREADS
5006bool
5007Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5008{
5009 const char * const stashpv = CopSTASHPV(c);
5010 const char * const name = HvNAME_get(hv);
5011
5012 if (stashpv == name)
5013 return TRUE;
5014 if (stashpv && name)
5015 if (strEQ(stashpv, name))
5016 return TRUE;
5017 return FALSE;
5018}
5019#endif
5020
5021
5022#ifdef PERL_GLOBAL_STRUCT
5023
5024struct perl_vars *
5025Perl_init_global_struct(pTHX)
5026{
5027 struct perl_vars *plvarsp = NULL;
5028#ifdef PERL_GLOBAL_STRUCT
5029# define PERL_GLOBAL_STRUCT_INIT
5030# include "opcode.h" /* the ppaddr and check */
5031 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5032 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5033# ifdef PERL_GLOBAL_STRUCT_PRIVATE
5034 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5035 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5036 if (!plvarsp)
5037 exit(1);
5038# else
5039 plvarsp = PL_VarsPtr;
5040# endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5041# undef PERLVAR
5042# undef PERLVARA
5043# undef PERLVARI
5044# undef PERLVARIC
5045# undef PERLVARISC
5046# define PERLVAR(var,type) /**/
5047# define PERLVARA(var,n,type) /**/
5048# define PERLVARI(var,type,init) plvarsp->var = init;
5049# define PERLVARIC(var,type,init) plvarsp->var = init;
5050# define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5051# include "perlvars.h"
5052# undef PERLVAR
5053# undef PERLVARA
5054# undef PERLVARI
5055# undef PERLVARIC
5056# undef PERLVARISC
5057# ifdef PERL_GLOBAL_STRUCT
5058 plvarsp->Gppaddr = PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5059 if (!plvarsp->Gppaddr)
5060 exit(1);
5061 plvarsp->Gcheck = PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5062 if (!plvarsp->Gcheck)
5063 exit(1);
5064 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5065 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5066# endif
5067# ifdef PERL_SET_VARS
5068 PERL_SET_VARS(plvarsp);
5069# endif
5070# undef PERL_GLOBAL_STRUCT_INIT
5071#endif
5072 return plvarsp;
5073}
5074
5075#endif /* PERL_GLOBAL_STRUCT */
5076
5077#ifdef PERL_GLOBAL_STRUCT
5078
5079void
5080Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5081{
5082#ifdef PERL_GLOBAL_STRUCT
5083# ifdef PERL_UNSET_VARS
5084 PERL_UNSET_VARS(plvarsp);
5085# endif
5086 free(plvarsp->Gppaddr);
5087 free(plvarsp->Gcheck);
5088# ifdef PERL_GLOBAL_STRUCT_PRIVATE
5089 free(plvarsp);
5090# endif
5091#endif
5092}
5093
5094#endif /* PERL_GLOBAL_STRUCT */
5095
5096#ifdef PERL_MEM_LOG
5097
5098#define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5099
5100Malloc_t
5101Perl_mem_log_alloc(const UV n, const UV typesize, const char *typename, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5102{
5103#ifdef PERL_MEM_LOG_STDERR
5104 /* We can't use PerlIO for obvious reasons. */
5105 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5106 const STRLEN len = my_sprintf(buf,
5107 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5108 " %s = %"IVdf": %"UVxf"\n",
5109 filename, linenumber, funcname, n, typesize,
5110 typename, n * typesize, PTR2UV(newalloc));
5111 PerlLIO_write(2, buf, len);
5112#endif
5113 return newalloc;
5114}
5115
5116Malloc_t
5117Perl_mem_log_realloc(const UV n, const UV typesize, const char *typename, Malloc_t oldalloc, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5118{
5119#ifdef PERL_MEM_LOG_STDERR
5120 /* We can't use PerlIO for obvious reasons. */
5121 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5122 const STRLEN len = my_sprintf(buf, "realloc: %s:%d:%s: %"IVdf" %"UVuf
5123 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5124 filename, linenumber, funcname, n, typesize,
5125 typename, n * typesize, PTR2UV(oldalloc),
5126 PTR2UV(newalloc));
5127 PerlLIO_write(2, buf, len);
5128#endif
5129 return newalloc;
5130}
5131
5132Malloc_t
5133Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5134{
5135#ifdef PERL_MEM_LOG_STDERR
5136 /* We can't use PerlIO for obvious reasons. */
5137 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5138 const STRLEN len = my_sprintf(buf, "free: %s:%d:%s: %"UVxf"\n",
5139 filename, linenumber, funcname,
5140 PTR2UV(oldalloc));
5141 PerlLIO_write(2, buf, len);
5142#endif
5143 return oldalloc;
5144}
5145
5146#endif /* PERL_MEM_LOG */
5147
5148/*
5149=for apidoc my_sprintf
5150
5151The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5152the length of the string written to the buffer. Only rare pre-ANSI systems
5153need the wrapper function - usually this is a direct call to C<sprintf>.
5154
5155=cut
5156*/
5157#ifndef SPRINTF_RETURNS_STRLEN
5158int
5159Perl_my_sprintf(char *buffer, const char* pat, ...)
5160{
5161 va_list args;
5162 va_start(args, pat);
5163 vsprintf(buffer, pat, args);
5164 va_end(args);
5165 return strlen(buffer);
5166}
5167#endif
5168
5169void
5170Perl_my_clearenv(pTHX)
5171{
5172 dVAR;
5173#if ! defined(PERL_MICRO)
5174# if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5175 PerlEnv_clearenv();
5176# else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5177# if defined(USE_ENVIRON_ARRAY)
5178# if defined(USE_ITHREADS)
5179 /* only the parent thread can clobber the process environment */
5180 if (PL_curinterp == aTHX)
5181# endif /* USE_ITHREADS */
5182 {
5183# if ! defined(PERL_USE_SAFE_PUTENV)
5184 if ( !PL_use_safe_putenv) {
5185 I32 i;
5186 if (environ == PL_origenviron)
5187 environ = (char**)safesysmalloc(sizeof(char*));
5188 else
5189 for (i = 0; environ[i]; i++)
5190 (void)safesysfree(environ[i]);
5191 }
5192 environ[0] = NULL;
5193# else /* PERL_USE_SAFE_PUTENV */
5194# if defined(HAS_CLEARENV)
5195 (void)clearenv();
5196# elif defined(HAS_UNSETENV)
5197 int bsiz = 80; /* Most envvar names will be shorter than this. */
5198 char *buf = (char*)safesysmalloc(bsiz * sizeof(char));
5199 while (*environ != NULL) {
5200 char *e = strchr(*environ, '=');
5201 int l = e ? e - *environ : strlen(*environ);
5202 if (bsiz < l + 1) {
5203 (void)safesysfree(buf);
5204 bsiz = l + 1;
5205 buf = (char*)safesysmalloc(bsiz * sizeof(char));
5206 }
5207 strncpy(buf, *environ, l);
5208 *(buf + l) = '\0';
5209 (void)unsetenv(buf);
5210 }
5211 (void)safesysfree(buf);
5212# else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5213 /* Just null environ and accept the leakage. */
5214 *environ = NULL;
5215# endif /* HAS_CLEARENV || HAS_UNSETENV */
5216# endif /* ! PERL_USE_SAFE_PUTENV */
5217 }
5218# endif /* USE_ENVIRON_ARRAY */
5219# endif /* PERL_IMPLICIT_SYS || WIN32 */
5220#endif /* PERL_MICRO */
5221}
5222
5223#ifdef PERL_IMPLICIT_CONTEXT
5224
5225/* implements the MY_CXT_INIT macro. The first time a module is loaded,
5226the global PL_my_cxt_index is incremented, and that value is assigned to
5227that module's static my_cxt_index (who's address is passed as an arg).
5228Then, for each interpreter this function is called for, it makes sure a
5229void* slot is available to hang the static data off, by allocating or
5230extending the interpreter's PL_my_cxt_list array */
5231
5232void *
5233Perl_my_cxt_init(pTHX_ int *index, size_t size)
5234{
5235 dVAR;
5236 void *p;
5237 if (*index == -1) {
5238 /* this module hasn't been allocated an index yet */
5239 MUTEX_LOCK(&PL_my_ctx_mutex);
5240 *index = PL_my_cxt_index++;
5241 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5242 }
5243
5244 /* make sure the array is big enough */
5245 if (PL_my_cxt_size <= *index) {
5246 if (PL_my_cxt_size) {
5247 while (PL_my_cxt_size <= *index)
5248 PL_my_cxt_size *= 2;
5249 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5250 }
5251 else {
5252 PL_my_cxt_size = 16;
5253 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5254 }
5255 }
5256 /* newSV() allocates one more than needed */
5257 p = (void*)SvPVX(newSV(size-1));
5258 PL_my_cxt_list[*index] = p;
5259 Zero(p, size, char);
5260 return p;
5261}
5262#endif
5263
5264/*
5265 * Local variables:
5266 * c-indentation-style: bsd
5267 * c-basic-offset: 4
5268 * indent-tabs-mode: t
5269 * End:
5270 *
5271 * ex: set ts=8 sts=4 sw=4 noet:
5272 */