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