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