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