This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[PATCH] Removing example layers from MIME::QuotedPrint
[perl5.git] / util.c
... / ...
CommitLineData
1/* util.c
2 *
3 * Copyright (c) 1991-2002, Larry Wall
4 *
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
7 *
8 */
9
10/*
11 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
12 * not content." --Gandalf
13 */
14
15#include "EXTERN.h"
16#define PERL_IN_UTIL_C
17#include "perl.h"
18
19#ifndef PERL_MICRO
20#if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
21#include <signal.h>
22#endif
23
24#ifndef SIG_ERR
25# define SIG_ERR ((Sighandler_t) -1)
26#endif
27#endif
28
29#ifdef I_SYS_WAIT
30# include <sys/wait.h>
31#endif
32
33#ifdef HAS_SELECT
34# ifdef I_SYS_SELECT
35# include <sys/select.h>
36# endif
37#endif
38
39#define FLUSH
40
41#ifdef LEAKTEST
42
43long xcount[MAXXCOUNT];
44long lastxcount[MAXXCOUNT];
45long xycount[MAXXCOUNT][MAXYCOUNT];
46long lastxycount[MAXXCOUNT][MAXYCOUNT];
47
48#endif
49
50#if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51# define FD_CLOEXEC 1 /* NeXT needs this */
52#endif
53
54/* NOTE: Do not call the next three routines directly. Use the macros
55 * in handy.h, so that we can easily redefine everything to do tracking of
56 * allocated hunks back to the original New to track down any memory leaks.
57 * XXX This advice seems to be widely ignored :-( --AD August 1996.
58 */
59
60/* paranoid version of system's malloc() */
61
62Malloc_t
63Perl_safesysmalloc(MEM_SIZE size)
64{
65 dTHX;
66 Malloc_t ptr;
67#ifdef HAS_64K_LIMIT
68 if (size > 0xffff) {
69 PerlIO_printf(Perl_error_log,
70 "Allocation too large: %lx\n", size) FLUSH;
71 my_exit(1);
72 }
73#endif /* HAS_64K_LIMIT */
74#ifdef DEBUGGING
75 if ((long)size < 0)
76 Perl_croak_nocontext("panic: malloc");
77#endif
78 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
79 PERL_ALLOC_CHECK(ptr);
80 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
81 if (ptr != Nullch)
82 return ptr;
83 else if (PL_nomemok)
84 return Nullch;
85 else {
86 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
87 my_exit(1);
88 return Nullch;
89 }
90 /*NOTREACHED*/
91}
92
93/* paranoid version of system's realloc() */
94
95Malloc_t
96Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
97{
98 dTHX;
99 Malloc_t ptr;
100#if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
101 Malloc_t PerlMem_realloc();
102#endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
103
104#ifdef HAS_64K_LIMIT
105 if (size > 0xffff) {
106 PerlIO_printf(Perl_error_log,
107 "Reallocation too large: %lx\n", size) FLUSH;
108 my_exit(1);
109 }
110#endif /* HAS_64K_LIMIT */
111 if (!size) {
112 safesysfree(where);
113 return NULL;
114 }
115
116 if (!where)
117 return safesysmalloc(size);
118#ifdef DEBUGGING
119 if ((long)size < 0)
120 Perl_croak_nocontext("panic: realloc");
121#endif
122 ptr = (Malloc_t)PerlMem_realloc(where,size);
123 PERL_ALLOC_CHECK(ptr);
124
125 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
126 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
127
128 if (ptr != Nullch)
129 return ptr;
130 else if (PL_nomemok)
131 return Nullch;
132 else {
133 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
134 my_exit(1);
135 return Nullch;
136 }
137 /*NOTREACHED*/
138}
139
140/* safe version of system's free() */
141
142Free_t
143Perl_safesysfree(Malloc_t where)
144{
145#ifdef PERL_IMPLICIT_SYS
146 dTHX;
147#endif
148 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
149 if (where) {
150 /*SUPPRESS 701*/
151 PerlMem_free(where);
152 }
153}
154
155/* safe version of system's calloc() */
156
157Malloc_t
158Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
159{
160 dTHX;
161 Malloc_t ptr;
162
163#ifdef HAS_64K_LIMIT
164 if (size * count > 0xffff) {
165 PerlIO_printf(Perl_error_log,
166 "Allocation too large: %lx\n", size * count) FLUSH;
167 my_exit(1);
168 }
169#endif /* HAS_64K_LIMIT */
170#ifdef DEBUGGING
171 if ((long)size < 0 || (long)count < 0)
172 Perl_croak_nocontext("panic: calloc");
173#endif
174 size *= count;
175 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
176 PERL_ALLOC_CHECK(ptr);
177 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
178 if (ptr != Nullch) {
179 memset((void*)ptr, 0, size);
180 return ptr;
181 }
182 else if (PL_nomemok)
183 return Nullch;
184 else {
185 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
186 my_exit(1);
187 return Nullch;
188 }
189 /*NOTREACHED*/
190}
191
192#ifdef LEAKTEST
193
194struct mem_test_strut {
195 union {
196 long type;
197 char c[2];
198 } u;
199 long size;
200};
201
202# define ALIGN sizeof(struct mem_test_strut)
203
204# define sizeof_chunk(ch) (((struct mem_test_strut*) (ch))->size)
205# define typeof_chunk(ch) \
206 (((struct mem_test_strut*) (ch))->u.c[0] + ((struct mem_test_strut*) (ch))->u.c[1]*100)
207# define set_typeof_chunk(ch,t) \
208 (((struct mem_test_strut*) (ch))->u.c[0] = t % 100, ((struct mem_test_strut*) (ch))->u.c[1] = t / 100)
209#define SIZE_TO_Y(size) ( (size) > MAXY_SIZE \
210 ? MAXYCOUNT - 1 \
211 : ( (size) > 40 \
212 ? ((size) - 1)/8 + 5 \
213 : ((size) - 1)/4))
214
215Malloc_t
216Perl_safexmalloc(I32 x, MEM_SIZE size)
217{
218 register char* where = (char*)safemalloc(size + ALIGN);
219
220 xcount[x] += size;
221 xycount[x][SIZE_TO_Y(size)]++;
222 set_typeof_chunk(where, x);
223 sizeof_chunk(where) = size;
224 return (Malloc_t)(where + ALIGN);
225}
226
227Malloc_t
228Perl_safexrealloc(Malloc_t wh, MEM_SIZE size)
229{
230 char *where = (char*)wh;
231
232 if (!wh)
233 return safexmalloc(0,size);
234
235 {
236 MEM_SIZE old = sizeof_chunk(where - ALIGN);
237 int t = typeof_chunk(where - ALIGN);
238 register char* new = (char*)saferealloc(where - ALIGN, size + ALIGN);
239
240 xycount[t][SIZE_TO_Y(old)]--;
241 xycount[t][SIZE_TO_Y(size)]++;
242 xcount[t] += size - old;
243 sizeof_chunk(new) = size;
244 return (Malloc_t)(new + ALIGN);
245 }
246}
247
248void
249Perl_safexfree(Malloc_t wh)
250{
251 I32 x;
252 char *where = (char*)wh;
253 MEM_SIZE size;
254
255 if (!where)
256 return;
257 where -= ALIGN;
258 size = sizeof_chunk(where);
259 x = where[0] + 100 * where[1];
260 xcount[x] -= size;
261 xycount[x][SIZE_TO_Y(size)]--;
262 safefree(where);
263}
264
265Malloc_t
266Perl_safexcalloc(I32 x,MEM_SIZE count, MEM_SIZE size)
267{
268 register char * where = (char*)safexmalloc(x, size * count + ALIGN);
269 xcount[x] += size;
270 xycount[x][SIZE_TO_Y(size)]++;
271 memset((void*)(where + ALIGN), 0, size * count);
272 set_typeof_chunk(where, x);
273 sizeof_chunk(where) = size;
274 return (Malloc_t)(where + ALIGN);
275}
276
277STATIC void
278S_xstat(pTHX_ int flag)
279{
280 register I32 i, j, total = 0;
281 I32 subtot[MAXYCOUNT];
282
283 for (j = 0; j < MAXYCOUNT; j++) {
284 subtot[j] = 0;
285 }
286
287 PerlIO_printf(Perl_debug_log, " Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+\n", total);
288 for (i = 0; i < MAXXCOUNT; i++) {
289 total += xcount[i];
290 for (j = 0; j < MAXYCOUNT; j++) {
291 subtot[j] += xycount[i][j];
292 }
293 if (flag == 0
294 ? xcount[i] /* Have something */
295 : (flag == 2
296 ? xcount[i] != lastxcount[i] /* Changed */
297 : xcount[i] > lastxcount[i])) { /* Growed */
298 PerlIO_printf(Perl_debug_log,"%2d %02d %7ld ", i / 100, i % 100,
299 flag == 2 ? xcount[i] - lastxcount[i] : xcount[i]);
300 lastxcount[i] = xcount[i];
301 for (j = 0; j < MAXYCOUNT; j++) {
302 if ( flag == 0
303 ? xycount[i][j] /* Have something */
304 : (flag == 2
305 ? xycount[i][j] != lastxycount[i][j] /* Changed */
306 : xycount[i][j] > lastxycount[i][j])) { /* Growed */
307 PerlIO_printf(Perl_debug_log,"%3ld ",
308 flag == 2
309 ? xycount[i][j] - lastxycount[i][j]
310 : xycount[i][j]);
311 lastxycount[i][j] = xycount[i][j];
312 } else {
313 PerlIO_printf(Perl_debug_log, " . ", xycount[i][j]);
314 }
315 }
316 PerlIO_printf(Perl_debug_log, "\n");
317 }
318 }
319 if (flag != 2) {
320 PerlIO_printf(Perl_debug_log, "Total %7ld ", total);
321 for (j = 0; j < MAXYCOUNT; j++) {
322 if (subtot[j]) {
323 PerlIO_printf(Perl_debug_log, "%3ld ", subtot[j]);
324 } else {
325 PerlIO_printf(Perl_debug_log, " . ");
326 }
327 }
328 PerlIO_printf(Perl_debug_log, "\n");
329 }
330}
331
332#endif /* LEAKTEST */
333
334/* These must be defined when not using Perl's malloc for binary
335 * compatibility */
336
337#ifndef MYMALLOC
338
339Malloc_t Perl_malloc (MEM_SIZE nbytes)
340{
341 dTHXs;
342 return (Malloc_t)PerlMem_malloc(nbytes);
343}
344
345Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
346{
347 dTHXs;
348 return (Malloc_t)PerlMem_calloc(elements, size);
349}
350
351Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
352{
353 dTHXs;
354 return (Malloc_t)PerlMem_realloc(where, nbytes);
355}
356
357Free_t Perl_mfree (Malloc_t where)
358{
359 dTHXs;
360 PerlMem_free(where);
361}
362
363#endif
364
365/* copy a string up to some (non-backslashed) delimiter, if any */
366
367char *
368Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
369{
370 register I32 tolen;
371 for (tolen = 0; from < fromend; from++, tolen++) {
372 if (*from == '\\') {
373 if (from[1] == delim)
374 from++;
375 else {
376 if (to < toend)
377 *to++ = *from;
378 tolen++;
379 from++;
380 }
381 }
382 else if (*from == delim)
383 break;
384 if (to < toend)
385 *to++ = *from;
386 }
387 if (to < toend)
388 *to = '\0';
389 *retlen = tolen;
390 return from;
391}
392
393/* return ptr to little string in big string, NULL if not found */
394/* This routine was donated by Corey Satten. */
395
396char *
397Perl_instr(pTHX_ register const char *big, register const char *little)
398{
399 register const char *s, *x;
400 register I32 first;
401
402 if (!little)
403 return (char*)big;
404 first = *little++;
405 if (!first)
406 return (char*)big;
407 while (*big) {
408 if (*big++ != first)
409 continue;
410 for (x=big,s=little; *s; /**/ ) {
411 if (!*x)
412 return Nullch;
413 if (*s++ != *x++) {
414 s--;
415 break;
416 }
417 }
418 if (!*s)
419 return (char*)(big-1);
420 }
421 return Nullch;
422}
423
424/* same as instr but allow embedded nulls */
425
426char *
427Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
428{
429 register const char *s, *x;
430 register I32 first = *little;
431 register const char *littleend = lend;
432
433 if (!first && little >= littleend)
434 return (char*)big;
435 if (bigend - big < littleend - little)
436 return Nullch;
437 bigend -= littleend - little++;
438 while (big <= bigend) {
439 if (*big++ != first)
440 continue;
441 for (x=big,s=little; s < littleend; /**/ ) {
442 if (*s++ != *x++) {
443 s--;
444 break;
445 }
446 }
447 if (s >= littleend)
448 return (char*)(big-1);
449 }
450 return Nullch;
451}
452
453/* reverse of the above--find last substring */
454
455char *
456Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
457{
458 register const char *bigbeg;
459 register const char *s, *x;
460 register I32 first = *little;
461 register const char *littleend = lend;
462
463 if (!first && little >= littleend)
464 return (char*)bigend;
465 bigbeg = big;
466 big = bigend - (littleend - little++);
467 while (big >= bigbeg) {
468 if (*big-- != first)
469 continue;
470 for (x=big+2,s=little; s < littleend; /**/ ) {
471 if (*s++ != *x++) {
472 s--;
473 break;
474 }
475 }
476 if (s >= littleend)
477 return (char*)(big+1);
478 }
479 return Nullch;
480}
481
482#define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
483
484/* As a space optimization, we do not compile tables for strings of length
485 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
486 special-cased in fbm_instr().
487
488 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
489
490/*
491=head1 Miscellaneous Functions
492
493=for apidoc fbm_compile
494
495Analyses the string in order to make fast searches on it using fbm_instr()
496-- the Boyer-Moore algorithm.
497
498=cut
499*/
500
501void
502Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
503{
504 register U8 *s;
505 register U8 *table;
506 register U32 i;
507 STRLEN len;
508 I32 rarest = 0;
509 U32 frequency = 256;
510
511 if (flags & FBMcf_TAIL)
512 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
513 s = (U8*)SvPV_force(sv, len);
514 (void)SvUPGRADE(sv, SVt_PVBM);
515 if (len == 0) /* TAIL might be on a zero-length string. */
516 return;
517 if (len > 2) {
518 U8 mlen;
519 unsigned char *sb;
520
521 if (len > 255)
522 mlen = 255;
523 else
524 mlen = (U8)len;
525 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
526 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
527 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
528 memset((void*)table, mlen, 256);
529 table[-1] = (U8)flags;
530 i = 0;
531 sb = s - mlen + 1; /* first char (maybe) */
532 while (s >= sb) {
533 if (table[*s] == mlen)
534 table[*s] = (U8)i;
535 s--, i++;
536 }
537 }
538 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
539 SvVALID_on(sv);
540
541 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
542 for (i = 0; i < len; i++) {
543 if (PL_freq[s[i]] < frequency) {
544 rarest = i;
545 frequency = PL_freq[s[i]];
546 }
547 }
548 BmRARE(sv) = s[rarest];
549 BmPREVIOUS(sv) = (U16)rarest;
550 BmUSEFUL(sv) = 100; /* Initial value */
551 if (flags & FBMcf_TAIL)
552 SvTAIL_on(sv);
553 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
554 BmRARE(sv),BmPREVIOUS(sv)));
555}
556
557/* If SvTAIL(littlestr), it has a fake '\n' at end. */
558/* If SvTAIL is actually due to \Z or \z, this gives false positives
559 if multiline */
560
561/*
562=for apidoc fbm_instr
563
564Returns the location of the SV in the string delimited by C<str> and
565C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
566does not have to be fbm_compiled, but the search will not be as fast
567then.
568
569=cut
570*/
571
572char *
573Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
574{
575 register unsigned char *s;
576 STRLEN l;
577 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
578 register STRLEN littlelen = l;
579 register I32 multiline = flags & FBMrf_MULTILINE;
580
581 if ((STRLEN)(bigend - big) < littlelen) {
582 if ( SvTAIL(littlestr)
583 && ((STRLEN)(bigend - big) == littlelen - 1)
584 && (littlelen == 1
585 || (*big == *little &&
586 memEQ((char *)big, (char *)little, littlelen - 1))))
587 return (char*)big;
588 return Nullch;
589 }
590
591 if (littlelen <= 2) { /* Special-cased */
592
593 if (littlelen == 1) {
594 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
595 /* Know that bigend != big. */
596 if (bigend[-1] == '\n')
597 return (char *)(bigend - 1);
598 return (char *) bigend;
599 }
600 s = big;
601 while (s < bigend) {
602 if (*s == *little)
603 return (char *)s;
604 s++;
605 }
606 if (SvTAIL(littlestr))
607 return (char *) bigend;
608 return Nullch;
609 }
610 if (!littlelen)
611 return (char*)big; /* Cannot be SvTAIL! */
612
613 /* littlelen is 2 */
614 if (SvTAIL(littlestr) && !multiline) {
615 if (bigend[-1] == '\n' && bigend[-2] == *little)
616 return (char*)bigend - 2;
617 if (bigend[-1] == *little)
618 return (char*)bigend - 1;
619 return Nullch;
620 }
621 {
622 /* This should be better than FBM if c1 == c2, and almost
623 as good otherwise: maybe better since we do less indirection.
624 And we save a lot of memory by caching no table. */
625 register unsigned char c1 = little[0];
626 register unsigned char c2 = little[1];
627
628 s = big + 1;
629 bigend--;
630 if (c1 != c2) {
631 while (s <= bigend) {
632 if (s[0] == c2) {
633 if (s[-1] == c1)
634 return (char*)s - 1;
635 s += 2;
636 continue;
637 }
638 next_chars:
639 if (s[0] == c1) {
640 if (s == bigend)
641 goto check_1char_anchor;
642 if (s[1] == c2)
643 return (char*)s;
644 else {
645 s++;
646 goto next_chars;
647 }
648 }
649 else
650 s += 2;
651 }
652 goto check_1char_anchor;
653 }
654 /* Now c1 == c2 */
655 while (s <= bigend) {
656 if (s[0] == c1) {
657 if (s[-1] == c1)
658 return (char*)s - 1;
659 if (s == bigend)
660 goto check_1char_anchor;
661 if (s[1] == c1)
662 return (char*)s;
663 s += 3;
664 }
665 else
666 s += 2;
667 }
668 }
669 check_1char_anchor: /* One char and anchor! */
670 if (SvTAIL(littlestr) && (*bigend == *little))
671 return (char *)bigend; /* bigend is already decremented. */
672 return Nullch;
673 }
674 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
675 s = bigend - littlelen;
676 if (s >= big && bigend[-1] == '\n' && *s == *little
677 /* Automatically of length > 2 */
678 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
679 {
680 return (char*)s; /* how sweet it is */
681 }
682 if (s[1] == *little
683 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
684 {
685 return (char*)s + 1; /* how sweet it is */
686 }
687 return Nullch;
688 }
689 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
690 char *b = ninstr((char*)big,(char*)bigend,
691 (char*)little, (char*)little + littlelen);
692
693 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
694 /* Chop \n from littlestr: */
695 s = bigend - littlelen + 1;
696 if (*s == *little
697 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
698 {
699 return (char*)s;
700 }
701 return Nullch;
702 }
703 return b;
704 }
705
706 { /* Do actual FBM. */
707 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
708 register unsigned char *oldlittle;
709
710 if (littlelen > (STRLEN)(bigend - big))
711 return Nullch;
712 --littlelen; /* Last char found by table lookup */
713
714 s = big + littlelen;
715 little += littlelen; /* last char */
716 oldlittle = little;
717 if (s < bigend) {
718 register I32 tmp;
719
720 top2:
721 /*SUPPRESS 560*/
722 if ((tmp = table[*s])) {
723 if ((s += tmp) < bigend)
724 goto top2;
725 goto check_end;
726 }
727 else { /* less expensive than calling strncmp() */
728 register unsigned char *olds = s;
729
730 tmp = littlelen;
731
732 while (tmp--) {
733 if (*--s == *--little)
734 continue;
735 s = olds + 1; /* here we pay the price for failure */
736 little = oldlittle;
737 if (s < bigend) /* fake up continue to outer loop */
738 goto top2;
739 goto check_end;
740 }
741 return (char *)s;
742 }
743 }
744 check_end:
745 if ( s == bigend && (table[-1] & FBMcf_TAIL)
746 && memEQ((char *)(bigend - littlelen),
747 (char *)(oldlittle - littlelen), littlelen) )
748 return (char*)bigend - littlelen;
749 return Nullch;
750 }
751}
752
753/* start_shift, end_shift are positive quantities which give offsets
754 of ends of some substring of bigstr.
755 If `last' we want the last occurrence.
756 old_posp is the way of communication between consequent calls if
757 the next call needs to find the .
758 The initial *old_posp should be -1.
759
760 Note that we take into account SvTAIL, so one can get extra
761 optimizations if _ALL flag is set.
762 */
763
764/* If SvTAIL is actually due to \Z or \z, this gives false positives
765 if PL_multiline. In fact if !PL_multiline the authoritative answer
766 is not supported yet. */
767
768char *
769Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
770{
771 register unsigned char *s, *x;
772 register unsigned char *big;
773 register I32 pos;
774 register I32 previous;
775 register I32 first;
776 register unsigned char *little;
777 register I32 stop_pos;
778 register unsigned char *littleend;
779 I32 found = 0;
780
781 if (*old_posp == -1
782 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
783 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
784 cant_find:
785 if ( BmRARE(littlestr) == '\n'
786 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
787 little = (unsigned char *)(SvPVX(littlestr));
788 littleend = little + SvCUR(littlestr);
789 first = *little++;
790 goto check_tail;
791 }
792 return Nullch;
793 }
794
795 little = (unsigned char *)(SvPVX(littlestr));
796 littleend = little + SvCUR(littlestr);
797 first = *little++;
798 /* The value of pos we can start at: */
799 previous = BmPREVIOUS(littlestr);
800 big = (unsigned char *)(SvPVX(bigstr));
801 /* The value of pos we can stop at: */
802 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
803 if (previous + start_shift > stop_pos) {
804/*
805 stop_pos does not include SvTAIL in the count, so this check is incorrect
806 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
807*/
808#if 0
809 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
810 goto check_tail;
811#endif
812 return Nullch;
813 }
814 while (pos < previous + start_shift) {
815 if (!(pos += PL_screamnext[pos]))
816 goto cant_find;
817 }
818 big -= previous;
819 do {
820 if (pos >= stop_pos) break;
821 if (big[pos] != first)
822 continue;
823 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
824 if (*s++ != *x++) {
825 s--;
826 break;
827 }
828 }
829 if (s == littleend) {
830 *old_posp = pos;
831 if (!last) return (char *)(big+pos);
832 found = 1;
833 }
834 } while ( pos += PL_screamnext[pos] );
835 if (last && found)
836 return (char *)(big+(*old_posp));
837 check_tail:
838 if (!SvTAIL(littlestr) || (end_shift > 0))
839 return Nullch;
840 /* Ignore the trailing "\n". This code is not microoptimized */
841 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
842 stop_pos = littleend - little; /* Actual littlestr len */
843 if (stop_pos == 0)
844 return (char*)big;
845 big -= stop_pos;
846 if (*big == first
847 && ((stop_pos == 1) ||
848 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
849 return (char*)big;
850 return Nullch;
851}
852
853I32
854Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
855{
856 register U8 *a = (U8 *)s1;
857 register U8 *b = (U8 *)s2;
858 while (len--) {
859 if (*a != *b && *a != PL_fold[*b])
860 return 1;
861 a++,b++;
862 }
863 return 0;
864}
865
866I32
867Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
868{
869 register U8 *a = (U8 *)s1;
870 register U8 *b = (U8 *)s2;
871 while (len--) {
872 if (*a != *b && *a != PL_fold_locale[*b])
873 return 1;
874 a++,b++;
875 }
876 return 0;
877}
878
879/* copy a string to a safe spot */
880
881/*
882=head1 Memory Management
883
884=for apidoc savepv
885
886Perl's version of C<strdup()>. Returns a pointer to a newly allocated
887string which is a duplicate of C<pv>. The size of the string is
888determined by C<strlen()>. The memory allocated for the new string can
889be freed with the C<Safefree()> function.
890
891=cut
892*/
893
894char *
895Perl_savepv(pTHX_ const char *pv)
896{
897 register char *newaddr = Nullch;
898 if (pv) {
899 New(902,newaddr,strlen(pv)+1,char);
900 (void)strcpy(newaddr,pv);
901 }
902 return newaddr;
903}
904
905/* same thing but with a known length */
906
907/*
908=for apidoc savepvn
909
910Perl's version of what C<strndup()> would be if it existed. Returns a
911pointer to a newly allocated string which is a duplicate of the first
912C<len> bytes from C<pv>. The memory allocated for the new string can be
913freed with the C<Safefree()> function.
914
915=cut
916*/
917
918char *
919Perl_savepvn(pTHX_ const char *pv, register I32 len)
920{
921 register char *newaddr;
922
923 New(903,newaddr,len+1,char);
924 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
925 if (pv) {
926 Copy(pv,newaddr,len,char); /* might not be null terminated */
927 newaddr[len] = '\0'; /* is now */
928 }
929 else {
930 Zero(newaddr,len+1,char);
931 }
932 return newaddr;
933}
934
935/*
936=for apidoc savesharedpv
937
938A version of C<savepv()> which allocates the duplicate string in memory
939which is shared between threads.
940
941=cut
942*/
943char *
944Perl_savesharedpv(pTHX_ const char *pv)
945{
946 register char *newaddr = Nullch;
947 if (pv) {
948 newaddr = (char*)PerlMemShared_malloc(strlen(pv)+1);
949 (void)strcpy(newaddr,pv);
950 }
951 return newaddr;
952}
953
954
955
956/* the SV for Perl_form() and mess() is not kept in an arena */
957
958STATIC SV *
959S_mess_alloc(pTHX)
960{
961 SV *sv;
962 XPVMG *any;
963
964 if (!PL_dirty)
965 return sv_2mortal(newSVpvn("",0));
966
967 if (PL_mess_sv)
968 return PL_mess_sv;
969
970 /* Create as PVMG now, to avoid any upgrading later */
971 New(905, sv, 1, SV);
972 Newz(905, any, 1, XPVMG);
973 SvFLAGS(sv) = SVt_PVMG;
974 SvANY(sv) = (void*)any;
975 SvREFCNT(sv) = 1 << 30; /* practically infinite */
976 PL_mess_sv = sv;
977 return sv;
978}
979
980#if defined(PERL_IMPLICIT_CONTEXT)
981char *
982Perl_form_nocontext(const char* pat, ...)
983{
984 dTHX;
985 char *retval;
986 va_list args;
987 va_start(args, pat);
988 retval = vform(pat, &args);
989 va_end(args);
990 return retval;
991}
992#endif /* PERL_IMPLICIT_CONTEXT */
993
994/*
995=head1 Miscellaneous Functions
996=for apidoc form
997
998Takes a sprintf-style format pattern and conventional
999(non-SV) arguments and returns the formatted string.
1000
1001 (char *) Perl_form(pTHX_ const char* pat, ...)
1002
1003can be used any place a string (char *) is required:
1004
1005 char * s = Perl_form("%d.%d",major,minor);
1006
1007Uses a single private buffer so if you want to format several strings you
1008must explicitly copy the earlier strings away (and free the copies when you
1009are done).
1010
1011=cut
1012*/
1013
1014char *
1015Perl_form(pTHX_ const char* pat, ...)
1016{
1017 char *retval;
1018 va_list args;
1019 va_start(args, pat);
1020 retval = vform(pat, &args);
1021 va_end(args);
1022 return retval;
1023}
1024
1025char *
1026Perl_vform(pTHX_ const char *pat, va_list *args)
1027{
1028 SV *sv = mess_alloc();
1029 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1030 return SvPVX(sv);
1031}
1032
1033#if defined(PERL_IMPLICIT_CONTEXT)
1034SV *
1035Perl_mess_nocontext(const char *pat, ...)
1036{
1037 dTHX;
1038 SV *retval;
1039 va_list args;
1040 va_start(args, pat);
1041 retval = vmess(pat, &args);
1042 va_end(args);
1043 return retval;
1044}
1045#endif /* PERL_IMPLICIT_CONTEXT */
1046
1047SV *
1048Perl_mess(pTHX_ const char *pat, ...)
1049{
1050 SV *retval;
1051 va_list args;
1052 va_start(args, pat);
1053 retval = vmess(pat, &args);
1054 va_end(args);
1055 return retval;
1056}
1057
1058STATIC COP*
1059S_closest_cop(pTHX_ COP *cop, OP *o)
1060{
1061 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1062
1063 if (!o || o == PL_op) return cop;
1064
1065 if (o->op_flags & OPf_KIDS) {
1066 OP *kid;
1067 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1068 {
1069 COP *new_cop;
1070
1071 /* If the OP_NEXTSTATE has been optimised away we can still use it
1072 * the get the file and line number. */
1073
1074 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1075 cop = (COP *)kid;
1076
1077 /* Keep searching, and return when we've found something. */
1078
1079 new_cop = closest_cop(cop, kid);
1080 if (new_cop) return new_cop;
1081 }
1082 }
1083
1084 /* Nothing found. */
1085
1086 return 0;
1087}
1088
1089SV *
1090Perl_vmess(pTHX_ const char *pat, va_list *args)
1091{
1092 SV *sv = mess_alloc();
1093 static char dgd[] = " during global destruction.\n";
1094 COP *cop;
1095
1096 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1097 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1098
1099 /*
1100 * Try and find the file and line for PL_op. This will usually be
1101 * PL_curcop, but it might be a cop that has been optimised away. We
1102 * can try to find such a cop by searching through the optree starting
1103 * from the sibling of PL_curcop.
1104 */
1105
1106 cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1107 if (!cop) cop = PL_curcop;
1108
1109 if (CopLINE(cop))
1110 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1111 OutCopFILE(cop), (IV)CopLINE(cop));
1112 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1113 bool line_mode = (RsSIMPLE(PL_rs) &&
1114 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
1115 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1116 PL_last_in_gv == PL_argvgv ?
1117 "" : GvNAME(PL_last_in_gv),
1118 line_mode ? "line" : "chunk",
1119 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1120 }
1121#ifdef USE_5005THREADS
1122 if (thr->tid)
1123 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
1124#endif
1125 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1126 }
1127 return sv;
1128}
1129
1130OP *
1131Perl_vdie(pTHX_ const char* pat, va_list *args)
1132{
1133 char *message;
1134 int was_in_eval = PL_in_eval;
1135 HV *stash;
1136 GV *gv;
1137 CV *cv;
1138 SV *msv;
1139 STRLEN msglen;
1140
1141 DEBUG_S(PerlIO_printf(Perl_debug_log,
1142 "%p: die: curstack = %p, mainstack = %p\n",
1143 thr, PL_curstack, PL_mainstack));
1144
1145 if (pat) {
1146 msv = vmess(pat, args);
1147 if (PL_errors && SvCUR(PL_errors)) {
1148 sv_catsv(PL_errors, msv);
1149 message = SvPV(PL_errors, msglen);
1150 SvCUR_set(PL_errors, 0);
1151 }
1152 else
1153 message = SvPV(msv,msglen);
1154 }
1155 else {
1156 message = Nullch;
1157 msglen = 0;
1158 }
1159
1160 DEBUG_S(PerlIO_printf(Perl_debug_log,
1161 "%p: die: message = %s\ndiehook = %p\n",
1162 thr, message, PL_diehook));
1163 if (PL_diehook) {
1164 /* sv_2cv might call Perl_croak() */
1165 SV *olddiehook = PL_diehook;
1166 ENTER;
1167 SAVESPTR(PL_diehook);
1168 PL_diehook = Nullsv;
1169 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1170 LEAVE;
1171 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1172 dSP;
1173 SV *msg;
1174
1175 ENTER;
1176 save_re_context();
1177 if (message) {
1178 msg = newSVpvn(message, msglen);
1179 SvREADONLY_on(msg);
1180 SAVEFREESV(msg);
1181 }
1182 else {
1183 msg = ERRSV;
1184 }
1185
1186 PUSHSTACKi(PERLSI_DIEHOOK);
1187 PUSHMARK(SP);
1188 XPUSHs(msg);
1189 PUTBACK;
1190 call_sv((SV*)cv, G_DISCARD);
1191 POPSTACK;
1192 LEAVE;
1193 }
1194 }
1195
1196 PL_restartop = die_where(message, msglen);
1197 DEBUG_S(PerlIO_printf(Perl_debug_log,
1198 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1199 thr, PL_restartop, was_in_eval, PL_top_env));
1200 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1201 JMPENV_JUMP(3);
1202 return PL_restartop;
1203}
1204
1205#if defined(PERL_IMPLICIT_CONTEXT)
1206OP *
1207Perl_die_nocontext(const char* pat, ...)
1208{
1209 dTHX;
1210 OP *o;
1211 va_list args;
1212 va_start(args, pat);
1213 o = vdie(pat, &args);
1214 va_end(args);
1215 return o;
1216}
1217#endif /* PERL_IMPLICIT_CONTEXT */
1218
1219OP *
1220Perl_die(pTHX_ const char* pat, ...)
1221{
1222 OP *o;
1223 va_list args;
1224 va_start(args, pat);
1225 o = vdie(pat, &args);
1226 va_end(args);
1227 return o;
1228}
1229
1230void
1231Perl_vcroak(pTHX_ const char* pat, va_list *args)
1232{
1233 char *message;
1234 HV *stash;
1235 GV *gv;
1236 CV *cv;
1237 SV *msv;
1238 STRLEN msglen;
1239
1240 if (pat) {
1241 msv = vmess(pat, args);
1242 if (PL_errors && SvCUR(PL_errors)) {
1243 sv_catsv(PL_errors, msv);
1244 message = SvPV(PL_errors, msglen);
1245 SvCUR_set(PL_errors, 0);
1246 }
1247 else
1248 message = SvPV(msv,msglen);
1249 }
1250 else {
1251 message = Nullch;
1252 msglen = 0;
1253 }
1254
1255 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1256 PTR2UV(thr), message));
1257
1258 if (PL_diehook) {
1259 /* sv_2cv might call Perl_croak() */
1260 SV *olddiehook = PL_diehook;
1261 ENTER;
1262 SAVESPTR(PL_diehook);
1263 PL_diehook = Nullsv;
1264 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1265 LEAVE;
1266 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1267 dSP;
1268 SV *msg;
1269
1270 ENTER;
1271 save_re_context();
1272 if (message) {
1273 msg = newSVpvn(message, msglen);
1274 SvREADONLY_on(msg);
1275 SAVEFREESV(msg);
1276 }
1277 else {
1278 msg = ERRSV;
1279 }
1280
1281 PUSHSTACKi(PERLSI_DIEHOOK);
1282 PUSHMARK(SP);
1283 XPUSHs(msg);
1284 PUTBACK;
1285 call_sv((SV*)cv, G_DISCARD);
1286 POPSTACK;
1287 LEAVE;
1288 }
1289 }
1290 if (PL_in_eval) {
1291 PL_restartop = die_where(message, msglen);
1292 JMPENV_JUMP(3);
1293 }
1294 else if (!message)
1295 message = SvPVx(ERRSV, msglen);
1296
1297 {
1298#ifdef USE_SFIO
1299 /* SFIO can really mess with your errno */
1300 int e = errno;
1301#endif
1302 PerlIO *serr = Perl_error_log;
1303
1304 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1305 (void)PerlIO_flush(serr);
1306#ifdef USE_SFIO
1307 errno = e;
1308#endif
1309 }
1310 my_failure_exit();
1311}
1312
1313#if defined(PERL_IMPLICIT_CONTEXT)
1314void
1315Perl_croak_nocontext(const char *pat, ...)
1316{
1317 dTHX;
1318 va_list args;
1319 va_start(args, pat);
1320 vcroak(pat, &args);
1321 /* NOTREACHED */
1322 va_end(args);
1323}
1324#endif /* PERL_IMPLICIT_CONTEXT */
1325
1326/*
1327=head1 Warning and Dieing
1328
1329=for apidoc croak
1330
1331This is the XSUB-writer's interface to Perl's C<die> function.
1332Normally use this function the same way you use the C C<printf>
1333function. See C<warn>.
1334
1335If you want to throw an exception object, assign the object to
1336C<$@> and then pass C<Nullch> to croak():
1337
1338 errsv = get_sv("@", TRUE);
1339 sv_setsv(errsv, exception_object);
1340 croak(Nullch);
1341
1342=cut
1343*/
1344
1345void
1346Perl_croak(pTHX_ const char *pat, ...)
1347{
1348 va_list args;
1349 va_start(args, pat);
1350 vcroak(pat, &args);
1351 /* NOTREACHED */
1352 va_end(args);
1353}
1354
1355void
1356Perl_vwarn(pTHX_ const char* pat, va_list *args)
1357{
1358 char *message;
1359 HV *stash;
1360 GV *gv;
1361 CV *cv;
1362 SV *msv;
1363 STRLEN msglen;
1364 IO *io;
1365 MAGIC *mg;
1366
1367 msv = vmess(pat, args);
1368 message = SvPV(msv, msglen);
1369
1370 if (PL_warnhook) {
1371 /* sv_2cv might call Perl_warn() */
1372 SV *oldwarnhook = PL_warnhook;
1373 ENTER;
1374 SAVESPTR(PL_warnhook);
1375 PL_warnhook = Nullsv;
1376 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1377 LEAVE;
1378 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1379 dSP;
1380 SV *msg;
1381
1382 ENTER;
1383 save_re_context();
1384 msg = newSVpvn(message, msglen);
1385 SvREADONLY_on(msg);
1386 SAVEFREESV(msg);
1387
1388 PUSHSTACKi(PERLSI_WARNHOOK);
1389 PUSHMARK(SP);
1390 XPUSHs(msg);
1391 PUTBACK;
1392 call_sv((SV*)cv, G_DISCARD);
1393 POPSTACK;
1394 LEAVE;
1395 return;
1396 }
1397 }
1398
1399 /* if STDERR is tied, use it instead */
1400 if (PL_stderrgv && (io = GvIOp(PL_stderrgv))
1401 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar))) {
1402 dSP; ENTER;
1403 PUSHMARK(SP);
1404 XPUSHs(SvTIED_obj((SV*)io, mg));
1405 XPUSHs(sv_2mortal(newSVpvn(message, msglen)));
1406 PUTBACK;
1407 call_method("PRINT", G_SCALAR);
1408 LEAVE;
1409 return;
1410 }
1411
1412 {
1413 PerlIO *serr = Perl_error_log;
1414
1415 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1416#ifdef LEAKTEST
1417 DEBUG_L(*message == '!'
1418 ? (xstat(message[1]=='!'
1419 ? (message[2]=='!' ? 2 : 1)
1420 : 0)
1421 , 0)
1422 : 0);
1423#endif
1424 (void)PerlIO_flush(serr);
1425 }
1426}
1427
1428#if defined(PERL_IMPLICIT_CONTEXT)
1429void
1430Perl_warn_nocontext(const char *pat, ...)
1431{
1432 dTHX;
1433 va_list args;
1434 va_start(args, pat);
1435 vwarn(pat, &args);
1436 va_end(args);
1437}
1438#endif /* PERL_IMPLICIT_CONTEXT */
1439
1440/*
1441=for apidoc warn
1442
1443This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1444function the same way you use the C C<printf> function. See
1445C<croak>.
1446
1447=cut
1448*/
1449
1450void
1451Perl_warn(pTHX_ const char *pat, ...)
1452{
1453 va_list args;
1454 va_start(args, pat);
1455 vwarn(pat, &args);
1456 va_end(args);
1457}
1458
1459#if defined(PERL_IMPLICIT_CONTEXT)
1460void
1461Perl_warner_nocontext(U32 err, const char *pat, ...)
1462{
1463 dTHX;
1464 va_list args;
1465 va_start(args, pat);
1466 vwarner(err, pat, &args);
1467 va_end(args);
1468}
1469#endif /* PERL_IMPLICIT_CONTEXT */
1470
1471void
1472Perl_warner(pTHX_ U32 err, const char* pat,...)
1473{
1474 va_list args;
1475 va_start(args, pat);
1476 vwarner(err, pat, &args);
1477 va_end(args);
1478}
1479
1480void
1481Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1482{
1483 char *message;
1484 HV *stash;
1485 GV *gv;
1486 CV *cv;
1487 SV *msv;
1488 STRLEN msglen;
1489
1490 msv = vmess(pat, args);
1491 message = SvPV(msv, msglen);
1492
1493 if (ckDEAD(err)) {
1494#ifdef USE_5005THREADS
1495 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1496#endif /* USE_5005THREADS */
1497 if (PL_diehook) {
1498 /* sv_2cv might call Perl_croak() */
1499 SV *olddiehook = PL_diehook;
1500 ENTER;
1501 SAVESPTR(PL_diehook);
1502 PL_diehook = Nullsv;
1503 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1504 LEAVE;
1505 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1506 dSP;
1507 SV *msg;
1508
1509 ENTER;
1510 save_re_context();
1511 msg = newSVpvn(message, msglen);
1512 SvREADONLY_on(msg);
1513 SAVEFREESV(msg);
1514
1515 PUSHSTACKi(PERLSI_DIEHOOK);
1516 PUSHMARK(sp);
1517 XPUSHs(msg);
1518 PUTBACK;
1519 call_sv((SV*)cv, G_DISCARD);
1520 POPSTACK;
1521 LEAVE;
1522 }
1523 }
1524 if (PL_in_eval) {
1525 PL_restartop = die_where(message, msglen);
1526 JMPENV_JUMP(3);
1527 }
1528 {
1529 PerlIO *serr = Perl_error_log;
1530 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1531 (void)PerlIO_flush(serr);
1532 }
1533 my_failure_exit();
1534
1535 }
1536 else {
1537 if (PL_warnhook) {
1538 /* sv_2cv might call Perl_warn() */
1539 SV *oldwarnhook = PL_warnhook;
1540 ENTER;
1541 SAVESPTR(PL_warnhook);
1542 PL_warnhook = Nullsv;
1543 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1544 LEAVE;
1545 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1546 dSP;
1547 SV *msg;
1548
1549 ENTER;
1550 save_re_context();
1551 msg = newSVpvn(message, msglen);
1552 SvREADONLY_on(msg);
1553 SAVEFREESV(msg);
1554
1555 PUSHSTACKi(PERLSI_WARNHOOK);
1556 PUSHMARK(sp);
1557 XPUSHs(msg);
1558 PUTBACK;
1559 call_sv((SV*)cv, G_DISCARD);
1560 POPSTACK;
1561 LEAVE;
1562 return;
1563 }
1564 }
1565 {
1566 PerlIO *serr = Perl_error_log;
1567 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1568#ifdef LEAKTEST
1569 DEBUG_L(*message == '!'
1570 ? (xstat(message[1]=='!'
1571 ? (message[2]=='!' ? 2 : 1)
1572 : 0)
1573 , 0)
1574 : 0);
1575#endif
1576 (void)PerlIO_flush(serr);
1577 }
1578 }
1579}
1580
1581/* since we've already done strlen() for both nam and val
1582 * we can use that info to make things faster than
1583 * sprintf(s, "%s=%s", nam, val)
1584 */
1585#define my_setenv_format(s, nam, nlen, val, vlen) \
1586 Copy(nam, s, nlen, char); \
1587 *(s+nlen) = '='; \
1588 Copy(val, s+(nlen+1), vlen, char); \
1589 *(s+(nlen+1+vlen)) = '\0'
1590
1591#ifdef USE_ENVIRON_ARRAY
1592 /* VMS' my_setenv() is in vms.c */
1593#if !defined(WIN32) && !defined(NETWARE)
1594void
1595Perl_my_setenv(pTHX_ char *nam, char *val)
1596{
1597#ifdef USE_ITHREADS
1598 /* only parent thread can modify process environment */
1599 if (PL_curinterp == aTHX)
1600#endif
1601 {
1602#ifndef PERL_USE_SAFE_PUTENV
1603 /* most putenv()s leak, so we manipulate environ directly */
1604 register I32 i=setenv_getix(nam); /* where does it go? */
1605 int nlen, vlen;
1606
1607 if (environ == PL_origenviron) { /* need we copy environment? */
1608 I32 j;
1609 I32 max;
1610 char **tmpenv;
1611
1612 /*SUPPRESS 530*/
1613 for (max = i; environ[max]; max++) ;
1614 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1615 for (j=0; j<max; j++) { /* copy environment */
1616 int len = strlen(environ[j]);
1617 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1618 Copy(environ[j], tmpenv[j], len+1, char);
1619 }
1620 tmpenv[max] = Nullch;
1621 environ = tmpenv; /* tell exec where it is now */
1622 }
1623 if (!val) {
1624 safesysfree(environ[i]);
1625 while (environ[i]) {
1626 environ[i] = environ[i+1];
1627 i++;
1628 }
1629 return;
1630 }
1631 if (!environ[i]) { /* does not exist yet */
1632 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1633 environ[i+1] = Nullch; /* make sure it's null terminated */
1634 }
1635 else
1636 safesysfree(environ[i]);
1637 nlen = strlen(nam);
1638 vlen = strlen(val);
1639
1640 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1641 /* all that work just for this */
1642 my_setenv_format(environ[i], nam, nlen, val, vlen);
1643
1644#else /* PERL_USE_SAFE_PUTENV */
1645# if defined(__CYGWIN__) || defined( EPOC)
1646 setenv(nam, val, 1);
1647# else
1648 char *new_env;
1649 int nlen = strlen(nam), vlen;
1650 if (!val) {
1651 val = "";
1652 }
1653 vlen = strlen(val);
1654 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1655 /* all that work just for this */
1656 my_setenv_format(new_env, nam, nlen, val, vlen);
1657 (void)putenv(new_env);
1658# endif /* __CYGWIN__ */
1659#endif /* PERL_USE_SAFE_PUTENV */
1660 }
1661}
1662
1663#else /* WIN32 || NETWARE */
1664
1665void
1666Perl_my_setenv(pTHX_ char *nam,char *val)
1667{
1668 register char *envstr;
1669 int nlen = strlen(nam), vlen;
1670
1671 if (!val) {
1672 val = "";
1673 }
1674 vlen = strlen(val);
1675 New(904, envstr, nlen+vlen+2, char);
1676 my_setenv_format(envstr, nam, nlen, val, vlen);
1677 (void)PerlEnv_putenv(envstr);
1678 Safefree(envstr);
1679}
1680
1681#endif /* WIN32 || NETWARE */
1682
1683I32
1684Perl_setenv_getix(pTHX_ char *nam)
1685{
1686 register I32 i, len = strlen(nam);
1687
1688 for (i = 0; environ[i]; i++) {
1689 if (
1690#ifdef WIN32
1691 strnicmp(environ[i],nam,len) == 0
1692#else
1693 strnEQ(environ[i],nam,len)
1694#endif
1695 && environ[i][len] == '=')
1696 break; /* strnEQ must come first to avoid */
1697 } /* potential SEGV's */
1698 return i;
1699}
1700
1701#endif /* !VMS && !EPOC*/
1702
1703#ifdef UNLINK_ALL_VERSIONS
1704I32
1705Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1706{
1707 I32 i;
1708
1709 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1710 return i ? 0 : -1;
1711}
1712#endif
1713
1714/* this is a drop-in replacement for bcopy() */
1715#if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1716char *
1717Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1718{
1719 char *retval = to;
1720
1721 if (from - to >= 0) {
1722 while (len--)
1723 *to++ = *from++;
1724 }
1725 else {
1726 to += len;
1727 from += len;
1728 while (len--)
1729 *(--to) = *(--from);
1730 }
1731 return retval;
1732}
1733#endif
1734
1735/* this is a drop-in replacement for memset() */
1736#ifndef HAS_MEMSET
1737void *
1738Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1739{
1740 char *retval = loc;
1741
1742 while (len--)
1743 *loc++ = ch;
1744 return retval;
1745}
1746#endif
1747
1748/* this is a drop-in replacement for bzero() */
1749#if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1750char *
1751Perl_my_bzero(register char *loc, register I32 len)
1752{
1753 char *retval = loc;
1754
1755 while (len--)
1756 *loc++ = 0;
1757 return retval;
1758}
1759#endif
1760
1761/* this is a drop-in replacement for memcmp() */
1762#if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1763I32
1764Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1765{
1766 register U8 *a = (U8 *)s1;
1767 register U8 *b = (U8 *)s2;
1768 register I32 tmp;
1769
1770 while (len--) {
1771 if (tmp = *a++ - *b++)
1772 return tmp;
1773 }
1774 return 0;
1775}
1776#endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1777
1778#ifndef HAS_VPRINTF
1779
1780#ifdef USE_CHAR_VSPRINTF
1781char *
1782#else
1783int
1784#endif
1785vsprintf(char *dest, const char *pat, char *args)
1786{
1787 FILE fakebuf;
1788
1789 fakebuf._ptr = dest;
1790 fakebuf._cnt = 32767;
1791#ifndef _IOSTRG
1792#define _IOSTRG 0
1793#endif
1794 fakebuf._flag = _IOWRT|_IOSTRG;
1795 _doprnt(pat, args, &fakebuf); /* what a kludge */
1796 (void)putc('\0', &fakebuf);
1797#ifdef USE_CHAR_VSPRINTF
1798 return(dest);
1799#else
1800 return 0; /* perl doesn't use return value */
1801#endif
1802}
1803
1804#endif /* HAS_VPRINTF */
1805
1806#ifdef MYSWAP
1807#if BYTEORDER != 0x4321
1808short
1809Perl_my_swap(pTHX_ short s)
1810{
1811#if (BYTEORDER & 1) == 0
1812 short result;
1813
1814 result = ((s & 255) << 8) + ((s >> 8) & 255);
1815 return result;
1816#else
1817 return s;
1818#endif
1819}
1820
1821long
1822Perl_my_htonl(pTHX_ long l)
1823{
1824 union {
1825 long result;
1826 char c[sizeof(long)];
1827 } u;
1828
1829#if BYTEORDER == 0x1234
1830 u.c[0] = (l >> 24) & 255;
1831 u.c[1] = (l >> 16) & 255;
1832 u.c[2] = (l >> 8) & 255;
1833 u.c[3] = l & 255;
1834 return u.result;
1835#else
1836#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1837 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1838#else
1839 register I32 o;
1840 register I32 s;
1841
1842 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1843 u.c[o & 0xf] = (l >> s) & 255;
1844 }
1845 return u.result;
1846#endif
1847#endif
1848}
1849
1850long
1851Perl_my_ntohl(pTHX_ long l)
1852{
1853 union {
1854 long l;
1855 char c[sizeof(long)];
1856 } u;
1857
1858#if BYTEORDER == 0x1234
1859 u.c[0] = (l >> 24) & 255;
1860 u.c[1] = (l >> 16) & 255;
1861 u.c[2] = (l >> 8) & 255;
1862 u.c[3] = l & 255;
1863 return u.l;
1864#else
1865#if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1866 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1867#else
1868 register I32 o;
1869 register I32 s;
1870
1871 u.l = l;
1872 l = 0;
1873 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1874 l |= (u.c[o & 0xf] & 255) << s;
1875 }
1876 return l;
1877#endif
1878#endif
1879}
1880
1881#endif /* BYTEORDER != 0x4321 */
1882#endif /* MYSWAP */
1883
1884/*
1885 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1886 * If these functions are defined,
1887 * the BYTEORDER is neither 0x1234 nor 0x4321.
1888 * However, this is not assumed.
1889 * -DWS
1890 */
1891
1892#define HTOV(name,type) \
1893 type \
1894 name (register type n) \
1895 { \
1896 union { \
1897 type value; \
1898 char c[sizeof(type)]; \
1899 } u; \
1900 register I32 i; \
1901 register I32 s; \
1902 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1903 u.c[i] = (n >> s) & 0xFF; \
1904 } \
1905 return u.value; \
1906 }
1907
1908#define VTOH(name,type) \
1909 type \
1910 name (register type n) \
1911 { \
1912 union { \
1913 type value; \
1914 char c[sizeof(type)]; \
1915 } u; \
1916 register I32 i; \
1917 register I32 s; \
1918 u.value = n; \
1919 n = 0; \
1920 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1921 n += (u.c[i] & 0xFF) << s; \
1922 } \
1923 return n; \
1924 }
1925
1926#if defined(HAS_HTOVS) && !defined(htovs)
1927HTOV(htovs,short)
1928#endif
1929#if defined(HAS_HTOVL) && !defined(htovl)
1930HTOV(htovl,long)
1931#endif
1932#if defined(HAS_VTOHS) && !defined(vtohs)
1933VTOH(vtohs,short)
1934#endif
1935#if defined(HAS_VTOHL) && !defined(vtohl)
1936VTOH(vtohl,long)
1937#endif
1938
1939PerlIO *
1940Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1941{
1942#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1943 int p[2];
1944 register I32 This, that;
1945 register Pid_t pid;
1946 SV *sv;
1947 I32 did_pipes = 0;
1948 int pp[2];
1949
1950 PERL_FLUSHALL_FOR_CHILD;
1951 This = (*mode == 'w');
1952 that = !This;
1953 if (PL_tainting) {
1954 taint_env();
1955 taint_proper("Insecure %s%s", "EXEC");
1956 }
1957 if (PerlProc_pipe(p) < 0)
1958 return Nullfp;
1959 /* Try for another pipe pair for error return */
1960 if (PerlProc_pipe(pp) >= 0)
1961 did_pipes = 1;
1962 while ((pid = PerlProc_fork()) < 0) {
1963 if (errno != EAGAIN) {
1964 PerlLIO_close(p[This]);
1965 if (did_pipes) {
1966 PerlLIO_close(pp[0]);
1967 PerlLIO_close(pp[1]);
1968 }
1969 return Nullfp;
1970 }
1971 sleep(5);
1972 }
1973 if (pid == 0) {
1974 /* Child */
1975#undef THIS
1976#undef THAT
1977#define THIS that
1978#define THAT This
1979 /* Close parent's end of _the_ pipe */
1980 PerlLIO_close(p[THAT]);
1981 /* Close parent's end of error status pipe (if any) */
1982 if (did_pipes) {
1983 PerlLIO_close(pp[0]);
1984#if defined(HAS_FCNTL) && defined(F_SETFD)
1985 /* Close error pipe automatically if exec works */
1986 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1987#endif
1988 }
1989 /* Now dup our end of _the_ pipe to right position */
1990 if (p[THIS] != (*mode == 'r')) {
1991 PerlLIO_dup2(p[THIS], *mode == 'r');
1992 PerlLIO_close(p[THIS]);
1993 }
1994#if !defined(HAS_FCNTL) || !defined(F_SETFD)
1995 /* No automatic close - do it by hand */
1996# ifndef NOFILE
1997# define NOFILE 20
1998# endif
1999 {
2000 int fd;
2001
2002 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2003 if (fd != pp[1])
2004 PerlLIO_close(fd);
2005 }
2006 }
2007#endif
2008 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2009 PerlProc__exit(1);
2010#undef THIS
2011#undef THAT
2012 }
2013 /* Parent */
2014 do_execfree(); /* free any memory malloced by child on fork */
2015 /* Close child's end of pipe */
2016 PerlLIO_close(p[that]);
2017 if (did_pipes)
2018 PerlLIO_close(pp[1]);
2019 /* Keep the lower of the two fd numbers */
2020 if (p[that] < p[This]) {
2021 PerlLIO_dup2(p[This], p[that]);
2022 PerlLIO_close(p[This]);
2023 p[This] = p[that];
2024 }
2025 LOCK_FDPID_MUTEX;
2026 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2027 UNLOCK_FDPID_MUTEX;
2028 (void)SvUPGRADE(sv,SVt_IV);
2029 SvIVX(sv) = pid;
2030 PL_forkprocess = pid;
2031 /* If we managed to get status pipe check for exec fail */
2032 if (did_pipes && pid > 0) {
2033 int errkid;
2034 int n = 0, n1;
2035
2036 while (n < sizeof(int)) {
2037 n1 = PerlLIO_read(pp[0],
2038 (void*)(((char*)&errkid)+n),
2039 (sizeof(int)) - n);
2040 if (n1 <= 0)
2041 break;
2042 n += n1;
2043 }
2044 PerlLIO_close(pp[0]);
2045 did_pipes = 0;
2046 if (n) { /* Error */
2047 int pid2, status;
2048 PerlLIO_close(p[This]);
2049 if (n != sizeof(int))
2050 Perl_croak(aTHX_ "panic: kid popen errno read");
2051 do {
2052 pid2 = wait4pid(pid, &status, 0);
2053 } while (pid2 == -1 && errno == EINTR);
2054 errno = errkid; /* Propagate errno from kid */
2055 return Nullfp;
2056 }
2057 }
2058 if (did_pipes)
2059 PerlLIO_close(pp[0]);
2060 return PerlIO_fdopen(p[This], mode);
2061#else
2062 Perl_croak(aTHX_ "List form of piped open not implemented");
2063 return (PerlIO *) NULL;
2064#endif
2065}
2066
2067 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2068#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2069PerlIO *
2070Perl_my_popen(pTHX_ char *cmd, char *mode)
2071{
2072 int p[2];
2073 register I32 This, that;
2074 register Pid_t pid;
2075 SV *sv;
2076 I32 doexec = strNE(cmd,"-");
2077 I32 did_pipes = 0;
2078 int pp[2];
2079
2080 PERL_FLUSHALL_FOR_CHILD;
2081#ifdef OS2
2082 if (doexec) {
2083 return my_syspopen(aTHX_ cmd,mode);
2084 }
2085#endif
2086 This = (*mode == 'w');
2087 that = !This;
2088 if (doexec && PL_tainting) {
2089 taint_env();
2090 taint_proper("Insecure %s%s", "EXEC");
2091 }
2092 if (PerlProc_pipe(p) < 0)
2093 return Nullfp;
2094 if (doexec && PerlProc_pipe(pp) >= 0)
2095 did_pipes = 1;
2096 while ((pid = PerlProc_fork()) < 0) {
2097 if (errno != EAGAIN) {
2098 PerlLIO_close(p[This]);
2099 PerlLIO_close(p[that]);
2100 if (did_pipes) {
2101 PerlLIO_close(pp[0]);
2102 PerlLIO_close(pp[1]);
2103 }
2104 if (!doexec)
2105 Perl_croak(aTHX_ "Can't fork");
2106 return Nullfp;
2107 }
2108 sleep(5);
2109 }
2110 if (pid == 0) {
2111 GV* tmpgv;
2112
2113#undef THIS
2114#undef THAT
2115#define THIS that
2116#define THAT This
2117 if (did_pipes) {
2118 PerlLIO_close(pp[0]);
2119#if defined(HAS_FCNTL) && defined(F_SETFD)
2120 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2121#endif
2122 }
2123 if (p[THIS] != (*mode == 'r')) {
2124 PerlLIO_dup2(p[THIS], *mode == 'r');
2125 PerlLIO_close(p[THIS]);
2126 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2127 PerlLIO_close(p[THAT]);
2128 }
2129 else
2130 PerlLIO_close(p[THAT]);
2131#ifndef OS2
2132 if (doexec) {
2133#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2134 int fd;
2135
2136#ifndef NOFILE
2137#define NOFILE 20
2138#endif
2139 {
2140 int fd;
2141
2142 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2143 if (fd != pp[1])
2144 PerlLIO_close(fd);
2145 }
2146#endif
2147 /* may or may not use the shell */
2148 do_exec3(cmd, pp[1], did_pipes);
2149 PerlProc__exit(1);
2150 }
2151#endif /* defined OS2 */
2152 /*SUPPRESS 560*/
2153 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2154 SvREADONLY_off(GvSV(tmpgv));
2155 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2156 SvREADONLY_on(GvSV(tmpgv));
2157 }
2158 PL_forkprocess = 0;
2159 hv_clear(PL_pidstatus); /* we have no children */
2160 return Nullfp;
2161#undef THIS
2162#undef THAT
2163 }
2164 do_execfree(); /* free any memory malloced by child on vfork */
2165 if (did_pipes)
2166 PerlLIO_close(pp[1]);
2167 if (p[that] < p[This]) {
2168 PerlLIO_dup2(p[This], p[that]);
2169 PerlLIO_close(p[This]);
2170 p[This] = p[that];
2171 }
2172 else
2173 PerlLIO_close(p[that]);
2174
2175 LOCK_FDPID_MUTEX;
2176 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2177 UNLOCK_FDPID_MUTEX;
2178 (void)SvUPGRADE(sv,SVt_IV);
2179 SvIVX(sv) = pid;
2180 PL_forkprocess = pid;
2181 if (did_pipes && pid > 0) {
2182 int errkid;
2183 int n = 0, n1;
2184
2185 while (n < sizeof(int)) {
2186 n1 = PerlLIO_read(pp[0],
2187 (void*)(((char*)&errkid)+n),
2188 (sizeof(int)) - n);
2189 if (n1 <= 0)
2190 break;
2191 n += n1;
2192 }
2193 PerlLIO_close(pp[0]);
2194 did_pipes = 0;
2195 if (n) { /* Error */
2196 int pid2, status;
2197 PerlLIO_close(p[This]);
2198 if (n != sizeof(int))
2199 Perl_croak(aTHX_ "panic: kid popen errno read");
2200 do {
2201 pid2 = wait4pid(pid, &status, 0);
2202 } while (pid2 == -1 && errno == EINTR);
2203 errno = errkid; /* Propagate errno from kid */
2204 return Nullfp;
2205 }
2206 }
2207 if (did_pipes)
2208 PerlLIO_close(pp[0]);
2209 return PerlIO_fdopen(p[This], mode);
2210}
2211#else
2212#if defined(atarist) || defined(EPOC)
2213FILE *popen();
2214PerlIO *
2215Perl_my_popen(pTHX_ char *cmd, char *mode)
2216{
2217 PERL_FLUSHALL_FOR_CHILD;
2218 /* Call system's popen() to get a FILE *, then import it.
2219 used 0 for 2nd parameter to PerlIO_importFILE;
2220 apparently not used
2221 */
2222 return PerlIO_importFILE(popen(cmd, mode), 0);
2223}
2224#else
2225#if defined(DJGPP)
2226FILE *djgpp_popen();
2227PerlIO *
2228Perl_my_popen(pTHX_ char *cmd, char *mode)
2229{
2230 PERL_FLUSHALL_FOR_CHILD;
2231 /* Call system's popen() to get a FILE *, then import it.
2232 used 0 for 2nd parameter to PerlIO_importFILE;
2233 apparently not used
2234 */
2235 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2236}
2237#endif
2238#endif
2239
2240#endif /* !DOSISH */
2241
2242/* this is called in parent before the fork() */
2243void
2244Perl_atfork_lock(void)
2245{
2246#if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2247 /* locks must be held in locking order (if any) */
2248# ifdef MYMALLOC
2249 MUTEX_LOCK(&PL_malloc_mutex);
2250# endif
2251 OP_REFCNT_LOCK;
2252#endif
2253}
2254
2255/* this is called in both parent and child after the fork() */
2256void
2257Perl_atfork_unlock(void)
2258{
2259#if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2260 /* locks must be released in same order as in atfork_lock() */
2261# ifdef MYMALLOC
2262 MUTEX_UNLOCK(&PL_malloc_mutex);
2263# endif
2264 OP_REFCNT_UNLOCK;
2265#endif
2266}
2267
2268Pid_t
2269Perl_my_fork(void)
2270{
2271#if defined(HAS_FORK)
2272 Pid_t pid;
2273#if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2274 atfork_lock();
2275 pid = fork();
2276 atfork_unlock();
2277#else
2278 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2279 * handlers elsewhere in the code */
2280 pid = fork();
2281#endif
2282 return pid;
2283#else
2284 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2285 Perl_croak_nocontext("fork() not available");
2286 return 0;
2287#endif /* HAS_FORK */
2288}
2289
2290#ifdef DUMP_FDS
2291void
2292Perl_dump_fds(pTHX_ char *s)
2293{
2294 int fd;
2295 Stat_t tmpstatbuf;
2296
2297 PerlIO_printf(Perl_debug_log,"%s", s);
2298 for (fd = 0; fd < 32; fd++) {
2299 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2300 PerlIO_printf(Perl_debug_log," %d",fd);
2301 }
2302 PerlIO_printf(Perl_debug_log,"\n");
2303}
2304#endif /* DUMP_FDS */
2305
2306#ifndef HAS_DUP2
2307int
2308dup2(int oldfd, int newfd)
2309{
2310#if defined(HAS_FCNTL) && defined(F_DUPFD)
2311 if (oldfd == newfd)
2312 return oldfd;
2313 PerlLIO_close(newfd);
2314 return fcntl(oldfd, F_DUPFD, newfd);
2315#else
2316#define DUP2_MAX_FDS 256
2317 int fdtmp[DUP2_MAX_FDS];
2318 I32 fdx = 0;
2319 int fd;
2320
2321 if (oldfd == newfd)
2322 return oldfd;
2323 PerlLIO_close(newfd);
2324 /* good enough for low fd's... */
2325 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2326 if (fdx >= DUP2_MAX_FDS) {
2327 PerlLIO_close(fd);
2328 fd = -1;
2329 break;
2330 }
2331 fdtmp[fdx++] = fd;
2332 }
2333 while (fdx > 0)
2334 PerlLIO_close(fdtmp[--fdx]);
2335 return fd;
2336#endif
2337}
2338#endif
2339
2340#ifndef PERL_MICRO
2341#ifdef HAS_SIGACTION
2342
2343Sighandler_t
2344Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2345{
2346 struct sigaction act, oact;
2347
2348 act.sa_handler = handler;
2349 sigemptyset(&act.sa_mask);
2350 act.sa_flags = 0;
2351#ifdef SA_RESTART
2352#if defined(PERL_OLD_SIGNALS)
2353 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2354#endif
2355#endif
2356#ifdef SA_NOCLDWAIT
2357 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2358 act.sa_flags |= SA_NOCLDWAIT;
2359#endif
2360 if (sigaction(signo, &act, &oact) == -1)
2361 return SIG_ERR;
2362 else
2363 return oact.sa_handler;
2364}
2365
2366Sighandler_t
2367Perl_rsignal_state(pTHX_ int signo)
2368{
2369 struct sigaction oact;
2370
2371 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2372 return SIG_ERR;
2373 else
2374 return oact.sa_handler;
2375}
2376
2377int
2378Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2379{
2380 struct sigaction act;
2381
2382 act.sa_handler = handler;
2383 sigemptyset(&act.sa_mask);
2384 act.sa_flags = 0;
2385#ifdef SA_RESTART
2386#if defined(PERL_OLD_SIGNALS)
2387 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2388#endif
2389#endif
2390#ifdef SA_NOCLDWAIT
2391 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2392 act.sa_flags |= SA_NOCLDWAIT;
2393#endif
2394 return sigaction(signo, &act, save);
2395}
2396
2397int
2398Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2399{
2400 return sigaction(signo, save, (struct sigaction *)NULL);
2401}
2402
2403#else /* !HAS_SIGACTION */
2404
2405Sighandler_t
2406Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2407{
2408 return PerlProc_signal(signo, handler);
2409}
2410
2411static int sig_trapped; /* XXX signals are process-wide anyway, so we
2412 ignore the implications of this for threading */
2413
2414static
2415Signal_t
2416sig_trap(int signo)
2417{
2418 sig_trapped++;
2419}
2420
2421Sighandler_t
2422Perl_rsignal_state(pTHX_ int signo)
2423{
2424 Sighandler_t oldsig;
2425
2426 sig_trapped = 0;
2427 oldsig = PerlProc_signal(signo, sig_trap);
2428 PerlProc_signal(signo, oldsig);
2429 if (sig_trapped)
2430 PerlProc_kill(PerlProc_getpid(), signo);
2431 return oldsig;
2432}
2433
2434int
2435Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2436{
2437 *save = PerlProc_signal(signo, handler);
2438 return (*save == SIG_ERR) ? -1 : 0;
2439}
2440
2441int
2442Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2443{
2444 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2445}
2446
2447#endif /* !HAS_SIGACTION */
2448#endif /* !PERL_MICRO */
2449
2450 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2451#if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2452I32
2453Perl_my_pclose(pTHX_ PerlIO *ptr)
2454{
2455 Sigsave_t hstat, istat, qstat;
2456 int status;
2457 SV **svp;
2458 Pid_t pid;
2459 Pid_t pid2;
2460 bool close_failed;
2461 int saved_errno = 0;
2462#ifdef VMS
2463 int saved_vaxc_errno;
2464#endif
2465#ifdef WIN32
2466 int saved_win32_errno;
2467#endif
2468
2469 LOCK_FDPID_MUTEX;
2470 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2471 UNLOCK_FDPID_MUTEX;
2472 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2473 SvREFCNT_dec(*svp);
2474 *svp = &PL_sv_undef;
2475#ifdef OS2
2476 if (pid == -1) { /* Opened by popen. */
2477 return my_syspclose(ptr);
2478 }
2479#endif
2480 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2481 saved_errno = errno;
2482#ifdef VMS
2483 saved_vaxc_errno = vaxc$errno;
2484#endif
2485#ifdef WIN32
2486 saved_win32_errno = GetLastError();
2487#endif
2488 }
2489#ifdef UTS
2490 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2491#endif
2492#ifndef PERL_MICRO
2493 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2494 rsignal_save(SIGINT, SIG_IGN, &istat);
2495 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2496#endif
2497 do {
2498 pid2 = wait4pid(pid, &status, 0);
2499 } while (pid2 == -1 && errno == EINTR);
2500#ifndef PERL_MICRO
2501 rsignal_restore(SIGHUP, &hstat);
2502 rsignal_restore(SIGINT, &istat);
2503 rsignal_restore(SIGQUIT, &qstat);
2504#endif
2505 if (close_failed) {
2506 SETERRNO(saved_errno, saved_vaxc_errno);
2507 return -1;
2508 }
2509 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2510}
2511#endif /* !DOSISH */
2512
2513#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2514I32
2515Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2516{
2517 I32 result;
2518 if (!pid)
2519 return -1;
2520#if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2521 {
2522 SV *sv;
2523 SV** svp;
2524 char spid[TYPE_CHARS(int)];
2525
2526 if (pid > 0) {
2527 sprintf(spid, "%"IVdf, (IV)pid);
2528 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2529 if (svp && *svp != &PL_sv_undef) {
2530 *statusp = SvIVX(*svp);
2531 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2532 return pid;
2533 }
2534 }
2535 else {
2536 HE *entry;
2537
2538 hv_iterinit(PL_pidstatus);
2539 if ((entry = hv_iternext(PL_pidstatus))) {
2540 SV *sv;
2541 char spid[TYPE_CHARS(int)];
2542
2543 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2544 sv = hv_iterval(PL_pidstatus,entry);
2545 *statusp = SvIVX(sv);
2546 sprintf(spid, "%"IVdf, (IV)pid);
2547 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2548 return pid;
2549 }
2550 }
2551 }
2552#endif
2553#ifdef HAS_WAITPID
2554# ifdef HAS_WAITPID_RUNTIME
2555 if (!HAS_WAITPID_RUNTIME)
2556 goto hard_way;
2557# endif
2558 result = PerlProc_waitpid(pid,statusp,flags);
2559 goto finish;
2560#endif
2561#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2562 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2563 goto finish;
2564#endif
2565#if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2566 hard_way:
2567 {
2568 if (flags)
2569 Perl_croak(aTHX_ "Can't do waitpid with flags");
2570 else {
2571 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2572 pidgone(result,*statusp);
2573 if (result < 0)
2574 *statusp = -1;
2575 }
2576 }
2577#endif
2578 finish:
2579 if (result < 0 && errno == EINTR) {
2580 PERL_ASYNC_CHECK();
2581 }
2582 return result;
2583}
2584#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2585
2586void
2587/*SUPPRESS 590*/
2588Perl_pidgone(pTHX_ Pid_t pid, int status)
2589{
2590 register SV *sv;
2591 char spid[TYPE_CHARS(int)];
2592
2593 sprintf(spid, "%"IVdf, (IV)pid);
2594 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2595 (void)SvUPGRADE(sv,SVt_IV);
2596 SvIVX(sv) = status;
2597 return;
2598}
2599
2600#if defined(atarist) || defined(OS2) || defined(EPOC)
2601int pclose();
2602#ifdef HAS_FORK
2603int /* Cannot prototype with I32
2604 in os2ish.h. */
2605my_syspclose(PerlIO *ptr)
2606#else
2607I32
2608Perl_my_pclose(pTHX_ PerlIO *ptr)
2609#endif
2610{
2611 /* Needs work for PerlIO ! */
2612 FILE *f = PerlIO_findFILE(ptr);
2613 I32 result = pclose(f);
2614 PerlIO_releaseFILE(ptr,f);
2615 return result;
2616}
2617#endif
2618
2619#if defined(DJGPP)
2620int djgpp_pclose();
2621I32
2622Perl_my_pclose(pTHX_ PerlIO *ptr)
2623{
2624 /* Needs work for PerlIO ! */
2625 FILE *f = PerlIO_findFILE(ptr);
2626 I32 result = djgpp_pclose(f);
2627 result = (result << 8) & 0xff00;
2628 PerlIO_releaseFILE(ptr,f);
2629 return result;
2630}
2631#endif
2632
2633void
2634Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2635{
2636 register I32 todo;
2637 register const char *frombase = from;
2638
2639 if (len == 1) {
2640 register const char c = *from;
2641 while (count-- > 0)
2642 *to++ = c;
2643 return;
2644 }
2645 while (count-- > 0) {
2646 for (todo = len; todo > 0; todo--) {
2647 *to++ = *from++;
2648 }
2649 from = frombase;
2650 }
2651}
2652
2653#ifndef HAS_RENAME
2654I32
2655Perl_same_dirent(pTHX_ char *a, char *b)
2656{
2657 char *fa = strrchr(a,'/');
2658 char *fb = strrchr(b,'/');
2659 Stat_t tmpstatbuf1;
2660 Stat_t tmpstatbuf2;
2661 SV *tmpsv = sv_newmortal();
2662
2663 if (fa)
2664 fa++;
2665 else
2666 fa = a;
2667 if (fb)
2668 fb++;
2669 else
2670 fb = b;
2671 if (strNE(a,b))
2672 return FALSE;
2673 if (fa == a)
2674 sv_setpv(tmpsv, ".");
2675 else
2676 sv_setpvn(tmpsv, a, fa - a);
2677 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2678 return FALSE;
2679 if (fb == b)
2680 sv_setpv(tmpsv, ".");
2681 else
2682 sv_setpvn(tmpsv, b, fb - b);
2683 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2684 return FALSE;
2685 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2686 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2687}
2688#endif /* !HAS_RENAME */
2689
2690char*
2691Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2692{
2693 char *xfound = Nullch;
2694 char *xfailed = Nullch;
2695 char tmpbuf[MAXPATHLEN];
2696 register char *s;
2697 I32 len = 0;
2698 int retval;
2699#if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2700# define SEARCH_EXTS ".bat", ".cmd", NULL
2701# define MAX_EXT_LEN 4
2702#endif
2703#ifdef OS2
2704# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2705# define MAX_EXT_LEN 4
2706#endif
2707#ifdef VMS
2708# define SEARCH_EXTS ".pl", ".com", NULL
2709# define MAX_EXT_LEN 4
2710#endif
2711 /* additional extensions to try in each dir if scriptname not found */
2712#ifdef SEARCH_EXTS
2713 char *exts[] = { SEARCH_EXTS };
2714 char **ext = search_ext ? search_ext : exts;
2715 int extidx = 0, i = 0;
2716 char *curext = Nullch;
2717#else
2718# define MAX_EXT_LEN 0
2719#endif
2720
2721 /*
2722 * If dosearch is true and if scriptname does not contain path
2723 * delimiters, search the PATH for scriptname.
2724 *
2725 * If SEARCH_EXTS is also defined, will look for each
2726 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2727 * while searching the PATH.
2728 *
2729 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2730 * proceeds as follows:
2731 * If DOSISH or VMSISH:
2732 * + look for ./scriptname{,.foo,.bar}
2733 * + search the PATH for scriptname{,.foo,.bar}
2734 *
2735 * If !DOSISH:
2736 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2737 * this will not look in '.' if it's not in the PATH)
2738 */
2739 tmpbuf[0] = '\0';
2740
2741#ifdef VMS
2742# ifdef ALWAYS_DEFTYPES
2743 len = strlen(scriptname);
2744 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2745 int hasdir, idx = 0, deftypes = 1;
2746 bool seen_dot = 1;
2747
2748 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2749# else
2750 if (dosearch) {
2751 int hasdir, idx = 0, deftypes = 1;
2752 bool seen_dot = 1;
2753
2754 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2755# endif
2756 /* The first time through, just add SEARCH_EXTS to whatever we
2757 * already have, so we can check for default file types. */
2758 while (deftypes ||
2759 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2760 {
2761 if (deftypes) {
2762 deftypes = 0;
2763 *tmpbuf = '\0';
2764 }
2765 if ((strlen(tmpbuf) + strlen(scriptname)
2766 + MAX_EXT_LEN) >= sizeof tmpbuf)
2767 continue; /* don't search dir with too-long name */
2768 strcat(tmpbuf, scriptname);
2769#else /* !VMS */
2770
2771#ifdef DOSISH
2772 if (strEQ(scriptname, "-"))
2773 dosearch = 0;
2774 if (dosearch) { /* Look in '.' first. */
2775 char *cur = scriptname;
2776#ifdef SEARCH_EXTS
2777 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2778 while (ext[i])
2779 if (strEQ(ext[i++],curext)) {
2780 extidx = -1; /* already has an ext */
2781 break;
2782 }
2783 do {
2784#endif
2785 DEBUG_p(PerlIO_printf(Perl_debug_log,
2786 "Looking for %s\n",cur));
2787 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2788 && !S_ISDIR(PL_statbuf.st_mode)) {
2789 dosearch = 0;
2790 scriptname = cur;
2791#ifdef SEARCH_EXTS
2792 break;
2793#endif
2794 }
2795#ifdef SEARCH_EXTS
2796 if (cur == scriptname) {
2797 len = strlen(scriptname);
2798 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2799 break;
2800 cur = strcpy(tmpbuf, scriptname);
2801 }
2802 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2803 && strcpy(tmpbuf+len, ext[extidx++]));
2804#endif
2805 }
2806#endif
2807
2808#ifdef MACOS_TRADITIONAL
2809 if (dosearch && !strchr(scriptname, ':') &&
2810 (s = PerlEnv_getenv("Commands")))
2811#else
2812 if (dosearch && !strchr(scriptname, '/')
2813#ifdef DOSISH
2814 && !strchr(scriptname, '\\')
2815#endif
2816 && (s = PerlEnv_getenv("PATH")))
2817#endif
2818 {
2819 bool seen_dot = 0;
2820
2821 PL_bufend = s + strlen(s);
2822 while (s < PL_bufend) {
2823#ifdef MACOS_TRADITIONAL
2824 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2825 ',',
2826 &len);
2827#else
2828#if defined(atarist) || defined(DOSISH)
2829 for (len = 0; *s
2830# ifdef atarist
2831 && *s != ','
2832# endif
2833 && *s != ';'; len++, s++) {
2834 if (len < sizeof tmpbuf)
2835 tmpbuf[len] = *s;
2836 }
2837 if (len < sizeof tmpbuf)
2838 tmpbuf[len] = '\0';
2839#else /* ! (atarist || DOSISH) */
2840 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2841 ':',
2842 &len);
2843#endif /* ! (atarist || DOSISH) */
2844#endif /* MACOS_TRADITIONAL */
2845 if (s < PL_bufend)
2846 s++;
2847 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2848 continue; /* don't search dir with too-long name */
2849#ifdef MACOS_TRADITIONAL
2850 if (len && tmpbuf[len - 1] != ':')
2851 tmpbuf[len++] = ':';
2852#else
2853 if (len
2854#if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2855 && tmpbuf[len - 1] != '/'
2856 && tmpbuf[len - 1] != '\\'
2857#endif
2858 )
2859 tmpbuf[len++] = '/';
2860 if (len == 2 && tmpbuf[0] == '.')
2861 seen_dot = 1;
2862#endif
2863 (void)strcpy(tmpbuf + len, scriptname);
2864#endif /* !VMS */
2865
2866#ifdef SEARCH_EXTS
2867 len = strlen(tmpbuf);
2868 if (extidx > 0) /* reset after previous loop */
2869 extidx = 0;
2870 do {
2871#endif
2872 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2873 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2874 if (S_ISDIR(PL_statbuf.st_mode)) {
2875 retval = -1;
2876 }
2877#ifdef SEARCH_EXTS
2878 } while ( retval < 0 /* not there */
2879 && extidx>=0 && ext[extidx] /* try an extension? */
2880 && strcpy(tmpbuf+len, ext[extidx++])
2881 );
2882#endif
2883 if (retval < 0)
2884 continue;
2885 if (S_ISREG(PL_statbuf.st_mode)
2886 && cando(S_IRUSR,TRUE,&PL_statbuf)
2887#if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2888 && cando(S_IXUSR,TRUE,&PL_statbuf)
2889#endif
2890 )
2891 {
2892 xfound = tmpbuf; /* bingo! */
2893 break;
2894 }
2895 if (!xfailed)
2896 xfailed = savepv(tmpbuf);
2897 }
2898#ifndef DOSISH
2899 if (!xfound && !seen_dot && !xfailed &&
2900 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2901 || S_ISDIR(PL_statbuf.st_mode)))
2902#endif
2903 seen_dot = 1; /* Disable message. */
2904 if (!xfound) {
2905 if (flags & 1) { /* do or die? */
2906 Perl_croak(aTHX_ "Can't %s %s%s%s",
2907 (xfailed ? "execute" : "find"),
2908 (xfailed ? xfailed : scriptname),
2909 (xfailed ? "" : " on PATH"),
2910 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2911 }
2912 scriptname = Nullch;
2913 }
2914 if (xfailed)
2915 Safefree(xfailed);
2916 scriptname = xfound;
2917 }
2918 return (scriptname ? savepv(scriptname) : Nullch);
2919}
2920
2921#ifndef PERL_GET_CONTEXT_DEFINED
2922
2923void *
2924Perl_get_context(void)
2925{
2926#if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2927# ifdef OLD_PTHREADS_API
2928 pthread_addr_t t;
2929 if (pthread_getspecific(PL_thr_key, &t))
2930 Perl_croak_nocontext("panic: pthread_getspecific");
2931 return (void*)t;
2932# else
2933# ifdef I_MACH_CTHREADS
2934 return (void*)cthread_data(cthread_self());
2935# else
2936 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2937# endif
2938# endif
2939#else
2940 return (void*)NULL;
2941#endif
2942}
2943
2944void
2945Perl_set_context(void *t)
2946{
2947#if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2948# ifdef I_MACH_CTHREADS
2949 cthread_set_data(cthread_self(), t);
2950# else
2951 if (pthread_setspecific(PL_thr_key, t))
2952 Perl_croak_nocontext("panic: pthread_setspecific");
2953# endif
2954#endif
2955}
2956
2957#endif /* !PERL_GET_CONTEXT_DEFINED */
2958
2959#ifdef USE_5005THREADS
2960
2961#ifdef FAKE_THREADS
2962/* Very simplistic scheduler for now */
2963void
2964schedule(void)
2965{
2966 thr = thr->i.next_run;
2967}
2968
2969void
2970Perl_cond_init(pTHX_ perl_cond *cp)
2971{
2972 *cp = 0;
2973}
2974
2975void
2976Perl_cond_signal(pTHX_ perl_cond *cp)
2977{
2978 perl_os_thread t;
2979 perl_cond cond = *cp;
2980
2981 if (!cond)
2982 return;
2983 t = cond->thread;
2984 /* Insert t in the runnable queue just ahead of us */
2985 t->i.next_run = thr->i.next_run;
2986 thr->i.next_run->i.prev_run = t;
2987 t->i.prev_run = thr;
2988 thr->i.next_run = t;
2989 thr->i.wait_queue = 0;
2990 /* Remove from the wait queue */
2991 *cp = cond->next;
2992 Safefree(cond);
2993}
2994
2995void
2996Perl_cond_broadcast(pTHX_ perl_cond *cp)
2997{
2998 perl_os_thread t;
2999 perl_cond cond, cond_next;
3000
3001 for (cond = *cp; cond; cond = cond_next) {
3002 t = cond->thread;
3003 /* Insert t in the runnable queue just ahead of us */
3004 t->i.next_run = thr->i.next_run;
3005 thr->i.next_run->i.prev_run = t;
3006 t->i.prev_run = thr;
3007 thr->i.next_run = t;
3008 thr->i.wait_queue = 0;
3009 /* Remove from the wait queue */
3010 cond_next = cond->next;
3011 Safefree(cond);
3012 }
3013 *cp = 0;
3014}
3015
3016void
3017Perl_cond_wait(pTHX_ perl_cond *cp)
3018{
3019 perl_cond cond;
3020
3021 if (thr->i.next_run == thr)
3022 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
3023
3024 New(666, cond, 1, struct perl_wait_queue);
3025 cond->thread = thr;
3026 cond->next = *cp;
3027 *cp = cond;
3028 thr->i.wait_queue = cond;
3029 /* Remove ourselves from runnable queue */
3030 thr->i.next_run->i.prev_run = thr->i.prev_run;
3031 thr->i.prev_run->i.next_run = thr->i.next_run;
3032}
3033#endif /* FAKE_THREADS */
3034
3035MAGIC *
3036Perl_condpair_magic(pTHX_ SV *sv)
3037{
3038 MAGIC *mg;
3039
3040 (void)SvUPGRADE(sv, SVt_PVMG);
3041 mg = mg_find(sv, PERL_MAGIC_mutex);
3042 if (!mg) {
3043 condpair_t *cp;
3044
3045 New(53, cp, 1, condpair_t);
3046 MUTEX_INIT(&cp->mutex);
3047 COND_INIT(&cp->owner_cond);
3048 COND_INIT(&cp->cond);
3049 cp->owner = 0;
3050 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
3051 mg = mg_find(sv, PERL_MAGIC_mutex);
3052 if (mg) {
3053 /* someone else beat us to initialising it */
3054 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3055 MUTEX_DESTROY(&cp->mutex);
3056 COND_DESTROY(&cp->owner_cond);
3057 COND_DESTROY(&cp->cond);
3058 Safefree(cp);
3059 }
3060 else {
3061 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
3062 mg = SvMAGIC(sv);
3063 mg->mg_ptr = (char *)cp;
3064 mg->mg_len = sizeof(cp);
3065 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
3066 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
3067 "%p: condpair_magic %p\n", thr, sv)));
3068 }
3069 }
3070 return mg;
3071}
3072
3073SV *
3074Perl_sv_lock(pTHX_ SV *osv)
3075{
3076 MAGIC *mg;
3077 SV *sv = osv;
3078
3079 LOCK_SV_LOCK_MUTEX;
3080 if (SvROK(sv)) {
3081 sv = SvRV(sv);
3082 }
3083
3084 mg = condpair_magic(sv);
3085 MUTEX_LOCK(MgMUTEXP(mg));
3086 if (MgOWNER(mg) == thr)
3087 MUTEX_UNLOCK(MgMUTEXP(mg));
3088 else {
3089 while (MgOWNER(mg))
3090 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
3091 MgOWNER(mg) = thr;
3092 DEBUG_S(PerlIO_printf(Perl_debug_log,
3093 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
3094 PTR2UV(thr), PTR2UV(sv)));
3095 MUTEX_UNLOCK(MgMUTEXP(mg));
3096 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
3097 }
3098 UNLOCK_SV_LOCK_MUTEX;
3099 return sv;
3100}
3101
3102/*
3103 * Make a new perl thread structure using t as a prototype. Some of the
3104 * fields for the new thread are copied from the prototype thread, t,
3105 * so t should not be running in perl at the time this function is
3106 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
3107 * thread calling new_struct_thread) clearly satisfies this constraint.
3108 */
3109struct perl_thread *
3110Perl_new_struct_thread(pTHX_ struct perl_thread *t)
3111{
3112#if !defined(PERL_IMPLICIT_CONTEXT)
3113 struct perl_thread *thr;
3114#endif
3115 SV *sv;
3116 SV **svp;
3117 I32 i;
3118
3119 sv = newSVpvn("", 0);
3120 SvGROW(sv, sizeof(struct perl_thread) + 1);
3121 SvCUR_set(sv, sizeof(struct perl_thread));
3122 thr = (Thread) SvPVX(sv);
3123#ifdef DEBUGGING
3124 Poison(thr, 1, struct perl_thread);
3125 PL_markstack = 0;
3126 PL_scopestack = 0;
3127 PL_savestack = 0;
3128 PL_retstack = 0;
3129 PL_dirty = 0;
3130 PL_localizing = 0;
3131 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3132 PL_efloatbuf = (char*)NULL;
3133 PL_efloatsize = 0;
3134#else
3135 Zero(thr, 1, struct perl_thread);
3136#endif
3137
3138 thr->oursv = sv;
3139 init_stacks();
3140
3141 PL_curcop = &PL_compiling;
3142 thr->interp = t->interp;
3143 thr->cvcache = newHV();
3144 thr->threadsv = newAV();
3145 thr->specific = newAV();
3146 thr->errsv = newSVpvn("", 0);
3147 thr->flags = THRf_R_JOINABLE;
3148 thr->thr_done = 0;
3149 MUTEX_INIT(&thr->mutex);
3150
3151 JMPENV_BOOTSTRAP;
3152
3153 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3154 PL_restartop = 0;
3155
3156 PL_statname = NEWSV(66,0);
3157 PL_errors = newSVpvn("", 0);
3158 PL_maxscream = -1;
3159 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3160 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3161 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3162 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3163 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3164 PL_regindent = 0;
3165 PL_reginterp_cnt = 0;
3166 PL_lastscream = Nullsv;
3167 PL_screamfirst = 0;
3168 PL_screamnext = 0;
3169 PL_reg_start_tmp = 0;
3170 PL_reg_start_tmpl = 0;
3171 PL_reg_poscache = Nullch;
3172
3173 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3174
3175 /* parent thread's data needs to be locked while we make copy */
3176 MUTEX_LOCK(&t->mutex);
3177
3178#ifdef PERL_FLEXIBLE_EXCEPTIONS
3179 PL_protect = t->Tprotect;
3180#endif
3181
3182 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3183 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3184 PL_curstash = t->Tcurstash; /* always be set to main? */
3185
3186 PL_tainted = t->Ttainted;
3187 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3188 PL_rs = newSVsv(t->Trs);
3189 PL_last_in_gv = Nullgv;
3190 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3191 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3192 PL_chopset = t->Tchopset;
3193 PL_bodytarget = newSVsv(t->Tbodytarget);
3194 PL_toptarget = newSVsv(t->Ttoptarget);
3195 if (t->Tformtarget == t->Ttoptarget)
3196 PL_formtarget = PL_toptarget;
3197 else
3198 PL_formtarget = PL_bodytarget;
3199
3200 /* Initialise all per-thread SVs that the template thread used */
3201 svp = AvARRAY(t->threadsv);
3202 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3203 if (*svp && *svp != &PL_sv_undef) {
3204 SV *sv = newSVsv(*svp);
3205 av_store(thr->threadsv, i, sv);
3206 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3207 DEBUG_S(PerlIO_printf(Perl_debug_log,
3208 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3209 (IV)i, t, thr));
3210 }
3211 }
3212 thr->threadsvp = AvARRAY(thr->threadsv);
3213
3214 MUTEX_LOCK(&PL_threads_mutex);
3215 PL_nthreads++;
3216 thr->tid = ++PL_threadnum;
3217 thr->next = t->next;
3218 thr->prev = t;
3219 t->next = thr;
3220 thr->next->prev = thr;
3221 MUTEX_UNLOCK(&PL_threads_mutex);
3222
3223 /* done copying parent's state */
3224 MUTEX_UNLOCK(&t->mutex);
3225
3226#ifdef HAVE_THREAD_INTERN
3227 Perl_init_thread_intern(thr);
3228#endif /* HAVE_THREAD_INTERN */
3229 return thr;
3230}
3231#endif /* USE_5005THREADS */
3232
3233#ifdef PERL_GLOBAL_STRUCT
3234struct perl_vars *
3235Perl_GetVars(pTHX)
3236{
3237 return &PL_Vars;
3238}
3239#endif
3240
3241char **
3242Perl_get_op_names(pTHX)
3243{
3244 return PL_op_name;
3245}
3246
3247char **
3248Perl_get_op_descs(pTHX)
3249{
3250 return PL_op_desc;
3251}
3252
3253char *
3254Perl_get_no_modify(pTHX)
3255{
3256 return (char*)PL_no_modify;
3257}
3258
3259U32 *
3260Perl_get_opargs(pTHX)
3261{
3262 return PL_opargs;
3263}
3264
3265PPADDR_t*
3266Perl_get_ppaddr(pTHX)
3267{
3268 return (PPADDR_t*)PL_ppaddr;
3269}
3270
3271#ifndef HAS_GETENV_LEN
3272char *
3273Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3274{
3275 char *env_trans = PerlEnv_getenv(env_elem);
3276 if (env_trans)
3277 *len = strlen(env_trans);
3278 return env_trans;
3279}
3280#endif
3281
3282
3283MGVTBL*
3284Perl_get_vtbl(pTHX_ int vtbl_id)
3285{
3286 MGVTBL* result = Null(MGVTBL*);
3287
3288 switch(vtbl_id) {
3289 case want_vtbl_sv:
3290 result = &PL_vtbl_sv;
3291 break;
3292 case want_vtbl_env:
3293 result = &PL_vtbl_env;
3294 break;
3295 case want_vtbl_envelem:
3296 result = &PL_vtbl_envelem;
3297 break;
3298 case want_vtbl_sig:
3299 result = &PL_vtbl_sig;
3300 break;
3301 case want_vtbl_sigelem:
3302 result = &PL_vtbl_sigelem;
3303 break;
3304 case want_vtbl_pack:
3305 result = &PL_vtbl_pack;
3306 break;
3307 case want_vtbl_packelem:
3308 result = &PL_vtbl_packelem;
3309 break;
3310 case want_vtbl_dbline:
3311 result = &PL_vtbl_dbline;
3312 break;
3313 case want_vtbl_isa:
3314 result = &PL_vtbl_isa;
3315 break;
3316 case want_vtbl_isaelem:
3317 result = &PL_vtbl_isaelem;
3318 break;
3319 case want_vtbl_arylen:
3320 result = &PL_vtbl_arylen;
3321 break;
3322 case want_vtbl_glob:
3323 result = &PL_vtbl_glob;
3324 break;
3325 case want_vtbl_mglob:
3326 result = &PL_vtbl_mglob;
3327 break;
3328 case want_vtbl_nkeys:
3329 result = &PL_vtbl_nkeys;
3330 break;
3331 case want_vtbl_taint:
3332 result = &PL_vtbl_taint;
3333 break;
3334 case want_vtbl_substr:
3335 result = &PL_vtbl_substr;
3336 break;
3337 case want_vtbl_vec:
3338 result = &PL_vtbl_vec;
3339 break;
3340 case want_vtbl_pos:
3341 result = &PL_vtbl_pos;
3342 break;
3343 case want_vtbl_bm:
3344 result = &PL_vtbl_bm;
3345 break;
3346 case want_vtbl_fm:
3347 result = &PL_vtbl_fm;
3348 break;
3349 case want_vtbl_uvar:
3350 result = &PL_vtbl_uvar;
3351 break;
3352#ifdef USE_5005THREADS
3353 case want_vtbl_mutex:
3354 result = &PL_vtbl_mutex;
3355 break;
3356#endif
3357 case want_vtbl_defelem:
3358 result = &PL_vtbl_defelem;
3359 break;
3360 case want_vtbl_regexp:
3361 result = &PL_vtbl_regexp;
3362 break;
3363 case want_vtbl_regdata:
3364 result = &PL_vtbl_regdata;
3365 break;
3366 case want_vtbl_regdatum:
3367 result = &PL_vtbl_regdatum;
3368 break;
3369#ifdef USE_LOCALE_COLLATE
3370 case want_vtbl_collxfrm:
3371 result = &PL_vtbl_collxfrm;
3372 break;
3373#endif
3374 case want_vtbl_amagic:
3375 result = &PL_vtbl_amagic;
3376 break;
3377 case want_vtbl_amagicelem:
3378 result = &PL_vtbl_amagicelem;
3379 break;
3380 case want_vtbl_backref:
3381 result = &PL_vtbl_backref;
3382 break;
3383 }
3384 return result;
3385}
3386
3387I32
3388Perl_my_fflush_all(pTHX)
3389{
3390#if defined(FFLUSH_NULL)
3391 return PerlIO_flush(NULL);
3392#else
3393# if defined(HAS__FWALK)
3394 /* undocumented, unprototyped, but very useful BSDism */
3395 extern void _fwalk(int (*)(FILE *));
3396 _fwalk(&fflush);
3397 return 0;
3398# else
3399# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3400 long open_max = -1;
3401# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3402 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3403# else
3404# if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3405 open_max = sysconf(_SC_OPEN_MAX);
3406# else
3407# ifdef FOPEN_MAX
3408 open_max = FOPEN_MAX;
3409# else
3410# ifdef OPEN_MAX
3411 open_max = OPEN_MAX;
3412# else
3413# ifdef _NFILE
3414 open_max = _NFILE;
3415# endif
3416# endif
3417# endif
3418# endif
3419# endif
3420 if (open_max > 0) {
3421 long i;
3422 for (i = 0; i < open_max; i++)
3423 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3424 STDIO_STREAM_ARRAY[i]._file < open_max &&
3425 STDIO_STREAM_ARRAY[i]._flag)
3426 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3427 return 0;
3428 }
3429# endif
3430 SETERRNO(EBADF,RMS$_IFI);
3431 return EOF;
3432# endif
3433#endif
3434}
3435
3436void
3437Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3438{
3439 char *vile;
3440 I32 warn_type;
3441 char *func =
3442 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3443 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3444 PL_op_desc[op];
3445 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3446 char *type = OP_IS_SOCKET(op) ||
3447 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3448 "socket" : "filehandle";
3449 char *name = NULL;
3450
3451 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3452 vile = "closed";
3453 warn_type = WARN_CLOSED;
3454 }
3455 else {
3456 vile = "unopened";
3457 warn_type = WARN_UNOPENED;
3458 }
3459
3460 if (gv && isGV(gv)) {
3461 name = GvENAME(gv);
3462 }
3463
3464 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3465 if (name && *name)
3466 Perl_warner(aTHX_ packWARN(WARN_IO), "Filehandle %s opened only for %sput",
3467 name,
3468 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3469 else
3470 Perl_warner(aTHX_ packWARN(WARN_IO), "Filehandle opened only for %sput",
3471 (op == OP_phoney_INPUT_ONLY ? "in" : "out"));
3472 } else if (name && *name) {
3473 Perl_warner(aTHX_ packWARN(warn_type),
3474 "%s%s on %s %s %s", func, pars, vile, type, name);
3475 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3476 Perl_warner(aTHX_ packWARN(warn_type),
3477 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3478 func, pars, name);
3479 }
3480 else {
3481 Perl_warner(aTHX_ packWARN(warn_type),
3482 "%s%s on %s %s", func, pars, vile, type);
3483 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3484 Perl_warner(aTHX_ packWARN(warn_type),
3485 "\t(Are you trying to call %s%s on dirhandle?)\n",
3486 func, pars);
3487 }
3488}
3489
3490#ifdef EBCDIC
3491/* in ASCII order, not that it matters */
3492static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3493
3494int
3495Perl_ebcdic_control(pTHX_ int ch)
3496{
3497 if (ch > 'a') {
3498 char *ctlp;
3499
3500 if (islower(ch))
3501 ch = toupper(ch);
3502
3503 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3504 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3505 }
3506
3507 if (ctlp == controllablechars)
3508 return('\177'); /* DEL */
3509 else
3510 return((unsigned char)(ctlp - controllablechars - 1));
3511 } else { /* Want uncontrol */
3512 if (ch == '\177' || ch == -1)
3513 return('?');
3514 else if (ch == '\157')
3515 return('\177');
3516 else if (ch == '\174')
3517 return('\000');
3518 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3519 return('\036');
3520 else if (ch == '\155')
3521 return('\037');
3522 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3523 return(controllablechars[ch+1]);
3524 else
3525 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3526 }
3527}
3528#endif
3529
3530/* To workaround core dumps from the uninitialised tm_zone we get the
3531 * system to give us a reasonable struct to copy. This fix means that
3532 * strftime uses the tm_zone and tm_gmtoff values returned by
3533 * localtime(time()). That should give the desired result most of the
3534 * time. But probably not always!
3535 *
3536 * This does not address tzname aspects of NETaa14816.
3537 *
3538 */
3539
3540#ifdef HAS_GNULIBC
3541# ifndef STRUCT_TM_HASZONE
3542# define STRUCT_TM_HASZONE
3543# endif
3544#endif
3545
3546#ifdef STRUCT_TM_HASZONE /* Backward compat */
3547# ifndef HAS_TM_TM_ZONE
3548# define HAS_TM_TM_ZONE
3549# endif
3550#endif
3551
3552void
3553Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3554{
3555#ifdef HAS_TM_TM_ZONE
3556 Time_t now;
3557 (void)time(&now);
3558 Copy(localtime(&now), ptm, 1, struct tm);
3559#endif
3560}
3561
3562/*
3563 * mini_mktime - normalise struct tm values without the localtime()
3564 * semantics (and overhead) of mktime().
3565 */
3566void
3567Perl_mini_mktime(pTHX_ struct tm *ptm)
3568{
3569 int yearday;
3570 int secs;
3571 int month, mday, year, jday;
3572 int odd_cent, odd_year;
3573
3574#define DAYS_PER_YEAR 365
3575#define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3576#define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3577#define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3578#define SECS_PER_HOUR (60*60)
3579#define SECS_PER_DAY (24*SECS_PER_HOUR)
3580/* parentheses deliberately absent on these two, otherwise they don't work */
3581#define MONTH_TO_DAYS 153/5
3582#define DAYS_TO_MONTH 5/153
3583/* offset to bias by March (month 4) 1st between month/mday & year finding */
3584#define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3585/* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3586#define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3587
3588/*
3589 * Year/day algorithm notes:
3590 *
3591 * With a suitable offset for numeric value of the month, one can find
3592 * an offset into the year by considering months to have 30.6 (153/5) days,
3593 * using integer arithmetic (i.e., with truncation). To avoid too much
3594 * messing about with leap days, we consider January and February to be
3595 * the 13th and 14th month of the previous year. After that transformation,
3596 * we need the month index we use to be high by 1 from 'normal human' usage,
3597 * so the month index values we use run from 4 through 15.
3598 *
3599 * Given that, and the rules for the Gregorian calendar (leap years are those
3600 * divisible by 4 unless also divisible by 100, when they must be divisible
3601 * by 400 instead), we can simply calculate the number of days since some
3602 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3603 * the days we derive from our month index, and adding in the day of the
3604 * month. The value used here is not adjusted for the actual origin which
3605 * it normally would use (1 January A.D. 1), since we're not exposing it.
3606 * We're only building the value so we can turn around and get the
3607 * normalised values for the year, month, day-of-month, and day-of-year.
3608 *
3609 * For going backward, we need to bias the value we're using so that we find
3610 * the right year value. (Basically, we don't want the contribution of
3611 * March 1st to the number to apply while deriving the year). Having done
3612 * that, we 'count up' the contribution to the year number by accounting for
3613 * full quadracenturies (400-year periods) with their extra leap days, plus
3614 * the contribution from full centuries (to avoid counting in the lost leap
3615 * days), plus the contribution from full quad-years (to count in the normal
3616 * leap days), plus the leftover contribution from any non-leap years.
3617 * At this point, if we were working with an actual leap day, we'll have 0
3618 * days left over. This is also true for March 1st, however. So, we have
3619 * to special-case that result, and (earlier) keep track of the 'odd'
3620 * century and year contributions. If we got 4 extra centuries in a qcent,
3621 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3622 * Otherwise, we add back in the earlier bias we removed (the 123 from
3623 * figuring in March 1st), find the month index (integer division by 30.6),
3624 * and the remainder is the day-of-month. We then have to convert back to
3625 * 'real' months (including fixing January and February from being 14/15 in
3626 * the previous year to being in the proper year). After that, to get
3627 * tm_yday, we work with the normalised year and get a new yearday value for
3628 * January 1st, which we subtract from the yearday value we had earlier,
3629 * representing the date we've re-built. This is done from January 1
3630 * because tm_yday is 0-origin.
3631 *
3632 * Since POSIX time routines are only guaranteed to work for times since the
3633 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3634 * applies Gregorian calendar rules even to dates before the 16th century
3635 * doesn't bother me. Besides, you'd need cultural context for a given
3636 * date to know whether it was Julian or Gregorian calendar, and that's
3637 * outside the scope for this routine. Since we convert back based on the
3638 * same rules we used to build the yearday, you'll only get strange results
3639 * for input which needed normalising, or for the 'odd' century years which
3640 * were leap years in the Julian calander but not in the Gregorian one.
3641 * I can live with that.
3642 *
3643 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3644 * that's still outside the scope for POSIX time manipulation, so I don't
3645 * care.
3646 */
3647
3648 year = 1900 + ptm->tm_year;
3649 month = ptm->tm_mon;
3650 mday = ptm->tm_mday;
3651 /* allow given yday with no month & mday to dominate the result */
3652 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3653 month = 0;
3654 mday = 0;
3655 jday = 1 + ptm->tm_yday;
3656 }
3657 else {
3658 jday = 0;
3659 }
3660 if (month >= 2)
3661 month+=2;
3662 else
3663 month+=14, year--;
3664 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3665 yearday += month*MONTH_TO_DAYS + mday + jday;
3666 /*
3667 * Note that we don't know when leap-seconds were or will be,
3668 * so we have to trust the user if we get something which looks
3669 * like a sensible leap-second. Wild values for seconds will
3670 * be rationalised, however.
3671 */
3672 if ((unsigned) ptm->tm_sec <= 60) {
3673 secs = 0;
3674 }
3675 else {
3676 secs = ptm->tm_sec;
3677 ptm->tm_sec = 0;
3678 }
3679 secs += 60 * ptm->tm_min;
3680 secs += SECS_PER_HOUR * ptm->tm_hour;
3681 if (secs < 0) {
3682 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3683 /* got negative remainder, but need positive time */
3684 /* back off an extra day to compensate */
3685 yearday += (secs/SECS_PER_DAY)-1;
3686 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3687 }
3688 else {
3689 yearday += (secs/SECS_PER_DAY);
3690 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3691 }
3692 }
3693 else if (secs >= SECS_PER_DAY) {
3694 yearday += (secs/SECS_PER_DAY);
3695 secs %= SECS_PER_DAY;
3696 }
3697 ptm->tm_hour = secs/SECS_PER_HOUR;
3698 secs %= SECS_PER_HOUR;
3699 ptm->tm_min = secs/60;
3700 secs %= 60;
3701 ptm->tm_sec += secs;
3702 /* done with time of day effects */
3703 /*
3704 * The algorithm for yearday has (so far) left it high by 428.
3705 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3706 * bias it by 123 while trying to figure out what year it
3707 * really represents. Even with this tweak, the reverse
3708 * translation fails for years before A.D. 0001.
3709 * It would still fail for Feb 29, but we catch that one below.
3710 */
3711 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3712 yearday -= YEAR_ADJUST;
3713 year = (yearday / DAYS_PER_QCENT) * 400;
3714 yearday %= DAYS_PER_QCENT;
3715 odd_cent = yearday / DAYS_PER_CENT;
3716 year += odd_cent * 100;
3717 yearday %= DAYS_PER_CENT;
3718 year += (yearday / DAYS_PER_QYEAR) * 4;
3719 yearday %= DAYS_PER_QYEAR;
3720 odd_year = yearday / DAYS_PER_YEAR;
3721 year += odd_year;
3722 yearday %= DAYS_PER_YEAR;
3723 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3724 month = 1;
3725 yearday = 29;
3726 }
3727 else {
3728 yearday += YEAR_ADJUST; /* recover March 1st crock */
3729 month = yearday*DAYS_TO_MONTH;
3730 yearday -= month*MONTH_TO_DAYS;
3731 /* recover other leap-year adjustment */
3732 if (month > 13) {
3733 month-=14;
3734 year++;
3735 }
3736 else {
3737 month-=2;
3738 }
3739 }
3740 ptm->tm_year = year - 1900;
3741 if (yearday) {
3742 ptm->tm_mday = yearday;
3743 ptm->tm_mon = month;
3744 }
3745 else {
3746 ptm->tm_mday = 31;
3747 ptm->tm_mon = month - 1;
3748 }
3749 /* re-build yearday based on Jan 1 to get tm_yday */
3750 year--;
3751 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3752 yearday += 14*MONTH_TO_DAYS + 1;
3753 ptm->tm_yday = jday - yearday;
3754 /* fix tm_wday if not overridden by caller */
3755 if ((unsigned)ptm->tm_wday > 6)
3756 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3757}
3758
3759char *
3760Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3761{
3762#ifdef HAS_STRFTIME
3763 char *buf;
3764 int buflen;
3765 struct tm mytm;
3766 int len;
3767
3768 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3769 mytm.tm_sec = sec;
3770 mytm.tm_min = min;
3771 mytm.tm_hour = hour;
3772 mytm.tm_mday = mday;
3773 mytm.tm_mon = mon;
3774 mytm.tm_year = year;
3775 mytm.tm_wday = wday;
3776 mytm.tm_yday = yday;
3777 mytm.tm_isdst = isdst;
3778 mini_mktime(&mytm);
3779 buflen = 64;
3780 New(0, buf, buflen, char);
3781 len = strftime(buf, buflen, fmt, &mytm);
3782 /*
3783 ** The following is needed to handle to the situation where
3784 ** tmpbuf overflows. Basically we want to allocate a buffer
3785 ** and try repeatedly. The reason why it is so complicated
3786 ** is that getting a return value of 0 from strftime can indicate
3787 ** one of the following:
3788 ** 1. buffer overflowed,
3789 ** 2. illegal conversion specifier, or
3790 ** 3. the format string specifies nothing to be returned(not
3791 ** an error). This could be because format is an empty string
3792 ** or it specifies %p that yields an empty string in some locale.
3793 ** If there is a better way to make it portable, go ahead by
3794 ** all means.
3795 */
3796 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3797 return buf;
3798 else {
3799 /* Possibly buf overflowed - try again with a bigger buf */
3800 int fmtlen = strlen(fmt);
3801 int bufsize = fmtlen + buflen;
3802
3803 New(0, buf, bufsize, char);
3804 while (buf) {
3805 buflen = strftime(buf, bufsize, fmt, &mytm);
3806 if (buflen > 0 && buflen < bufsize)
3807 break;
3808 /* heuristic to prevent out-of-memory errors */
3809 if (bufsize > 100*fmtlen) {
3810 Safefree(buf);
3811 buf = NULL;
3812 break;
3813 }
3814 bufsize *= 2;
3815 Renew(buf, bufsize, char);
3816 }
3817 return buf;
3818 }
3819#else
3820 Perl_croak(aTHX_ "panic: no strftime");
3821#endif
3822}
3823
3824
3825#define SV_CWD_RETURN_UNDEF \
3826sv_setsv(sv, &PL_sv_undef); \
3827return FALSE
3828
3829#define SV_CWD_ISDOT(dp) \
3830 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3831 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3832
3833/*
3834=head1 Miscellaneous Functions
3835
3836=for apidoc getcwd_sv
3837
3838Fill the sv with current working directory
3839
3840=cut
3841*/
3842
3843/* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3844 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3845 * getcwd(3) if available
3846 * Comments from the orignal:
3847 * This is a faster version of getcwd. It's also more dangerous
3848 * because you might chdir out of a directory that you can't chdir
3849 * back into. */
3850
3851int
3852Perl_getcwd_sv(pTHX_ register SV *sv)
3853{
3854#ifndef PERL_MICRO
3855
3856#ifndef INCOMPLETE_TAINTS
3857 SvTAINTED_on(sv);
3858#endif
3859
3860#ifdef HAS_GETCWD
3861 {
3862 char buf[MAXPATHLEN];
3863
3864 /* Some getcwd()s automatically allocate a buffer of the given
3865 * size from the heap if they are given a NULL buffer pointer.
3866 * The problem is that this behaviour is not portable. */
3867 if (getcwd(buf, sizeof(buf) - 1)) {
3868 STRLEN len = strlen(buf);
3869 sv_setpvn(sv, buf, len);
3870 return TRUE;
3871 }
3872 else {
3873 sv_setsv(sv, &PL_sv_undef);
3874 return FALSE;
3875 }
3876 }
3877
3878#else
3879
3880 Stat_t statbuf;
3881 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3882 int namelen, pathlen=0;
3883 DIR *dir;
3884 Direntry_t *dp;
3885
3886 (void)SvUPGRADE(sv, SVt_PV);
3887
3888 if (PerlLIO_lstat(".", &statbuf) < 0) {
3889 SV_CWD_RETURN_UNDEF;
3890 }
3891
3892 orig_cdev = statbuf.st_dev;
3893 orig_cino = statbuf.st_ino;
3894 cdev = orig_cdev;
3895 cino = orig_cino;
3896
3897 for (;;) {
3898 odev = cdev;
3899 oino = cino;
3900
3901 if (PerlDir_chdir("..") < 0) {
3902 SV_CWD_RETURN_UNDEF;
3903 }
3904 if (PerlLIO_stat(".", &statbuf) < 0) {
3905 SV_CWD_RETURN_UNDEF;
3906 }
3907
3908 cdev = statbuf.st_dev;
3909 cino = statbuf.st_ino;
3910
3911 if (odev == cdev && oino == cino) {
3912 break;
3913 }
3914 if (!(dir = PerlDir_open("."))) {
3915 SV_CWD_RETURN_UNDEF;
3916 }
3917
3918 while ((dp = PerlDir_read(dir)) != NULL) {
3919#ifdef DIRNAMLEN
3920 namelen = dp->d_namlen;
3921#else
3922 namelen = strlen(dp->d_name);
3923#endif
3924 /* skip . and .. */
3925 if (SV_CWD_ISDOT(dp)) {
3926 continue;
3927 }
3928
3929 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3930 SV_CWD_RETURN_UNDEF;
3931 }
3932
3933 tdev = statbuf.st_dev;
3934 tino = statbuf.st_ino;
3935 if (tino == oino && tdev == odev) {
3936 break;
3937 }
3938 }
3939
3940 if (!dp) {
3941 SV_CWD_RETURN_UNDEF;
3942 }
3943
3944 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3945 SV_CWD_RETURN_UNDEF;
3946 }
3947
3948 SvGROW(sv, pathlen + namelen + 1);
3949
3950 if (pathlen) {
3951 /* shift down */
3952 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3953 }
3954
3955 /* prepend current directory to the front */
3956 *SvPVX(sv) = '/';
3957 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3958 pathlen += (namelen + 1);
3959
3960#ifdef VOID_CLOSEDIR
3961 PerlDir_close(dir);
3962#else
3963 if (PerlDir_close(dir) < 0) {
3964 SV_CWD_RETURN_UNDEF;
3965 }
3966#endif
3967 }
3968
3969 if (pathlen) {
3970 SvCUR_set(sv, pathlen);
3971 *SvEND(sv) = '\0';
3972 SvPOK_only(sv);
3973
3974 if (PerlDir_chdir(SvPVX(sv)) < 0) {
3975 SV_CWD_RETURN_UNDEF;
3976 }
3977 }
3978 if (PerlLIO_stat(".", &statbuf) < 0) {
3979 SV_CWD_RETURN_UNDEF;
3980 }
3981
3982 cdev = statbuf.st_dev;
3983 cino = statbuf.st_ino;
3984
3985 if (cdev != orig_cdev || cino != orig_cino) {
3986 Perl_croak(aTHX_ "Unstable directory path, "
3987 "current directory changed unexpectedly");
3988 }
3989
3990 return TRUE;
3991#endif
3992
3993#else
3994 return FALSE;
3995#endif
3996}
3997
3998/*
3999=head1 SV Manipulation Functions
4000
4001=for apidoc new_vstring
4002
4003Returns a pointer to the next character after the parsed
4004vstring, as well as updating the passed in sv.
4005
4006Function must be called like
4007
4008 sv = NEWSV(92,5);
4009 s = new_vstring(s,sv);
4010
4011The sv must already be large enough to store the vstring
4012passed in.
4013
4014=cut
4015*/
4016
4017char *
4018Perl_new_vstring(pTHX_ char *s, SV *sv)
4019{
4020 char *pos = s;
4021 if (*pos == 'v') pos++; /* get past 'v' */
4022 while (isDIGIT(*pos) || *pos == '_')
4023 pos++;
4024 if (!isALPHA(*pos)) {
4025 UV rev;
4026 U8 tmpbuf[UTF8_MAXLEN+1];
4027 U8 *tmpend;
4028
4029 if (*s == 'v') s++; /* get past 'v' */
4030
4031 sv_setpvn(sv, "", 0);
4032
4033 for (;;) {
4034 rev = 0;
4035 {
4036 /* this is atoi() that tolerates underscores */
4037 char *end = pos;
4038 UV mult = 1;
4039 if ( s > pos && *(s-1) == '_') {
4040 mult = 10;
4041 }
4042 while (--end >= s) {
4043 UV orev;
4044 orev = rev;
4045 rev += (*end - '0') * mult;
4046 mult *= 10;
4047 if (orev > rev && ckWARN_d(WARN_OVERFLOW))
4048 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
4049 "Integer overflow in decimal number");
4050 }
4051 }
4052#ifdef EBCDIC
4053 if (rev > 0x7FFFFFFF)
4054 Perl_croak(aTHX "In EBCDIC the v-string components cannot exceed 2147483647");
4055#endif
4056 /* Append native character for the rev point */
4057 tmpend = uvchr_to_utf8(tmpbuf, rev);
4058 sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
4059 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(rev)))
4060 SvUTF8_on(sv);
4061 if ( (*pos == '.' || *pos == '_') && isDIGIT(pos[1]))
4062 s = ++pos;
4063 else {
4064 s = pos;
4065 break;
4066 }
4067 while (isDIGIT(*pos) )
4068 pos++;
4069 }
4070 SvPOK_on(sv);
4071 SvREADONLY_on(sv);
4072 }
4073 return s;
4074}
4075
4076#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4077# define EMULATE_SOCKETPAIR_UDP
4078#endif
4079
4080#ifdef EMULATE_SOCKETPAIR_UDP
4081static int
4082S_socketpair_udp (int fd[2]) {
4083 dTHX;
4084 /* Fake a datagram socketpair using UDP to localhost. */
4085 int sockets[2] = {-1, -1};
4086 struct sockaddr_in addresses[2];
4087 int i;
4088 Sock_size_t size = sizeof (struct sockaddr_in);
4089 unsigned short port;
4090 int got;
4091
4092 memset (&addresses, 0, sizeof (addresses));
4093 i = 1;
4094 do {
4095 sockets[i] = PerlSock_socket (AF_INET, SOCK_DGRAM, PF_INET);
4096 if (sockets[i] == -1)
4097 goto tidy_up_and_fail;
4098
4099 addresses[i].sin_family = AF_INET;
4100 addresses[i].sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4101 addresses[i].sin_port = 0; /* kernel choses port. */
4102 if (PerlSock_bind (sockets[i], (struct sockaddr *) &addresses[i],
4103 sizeof (struct sockaddr_in))
4104 == -1)
4105 goto tidy_up_and_fail;
4106 } while (i--);
4107
4108 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4109 for each connect the other socket to it. */
4110 i = 1;
4111 do {
4112 if (PerlSock_getsockname (sockets[i], (struct sockaddr *) &addresses[i], &size)
4113 == -1)
4114 goto tidy_up_and_fail;
4115 if (size != sizeof (struct sockaddr_in))
4116 goto abort_tidy_up_and_fail;
4117 /* !1 is 0, !0 is 1 */
4118 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4119 sizeof (struct sockaddr_in)) == -1)
4120 goto tidy_up_and_fail;
4121 } while (i--);
4122
4123 /* Now we have 2 sockets connected to each other. I don't trust some other
4124 process not to have already sent a packet to us (by random) so send
4125 a packet from each to the other. */
4126 i = 1;
4127 do {
4128 /* I'm going to send my own port number. As a short.
4129 (Who knows if someone somewhere has sin_port as a bitfield and needs
4130 this routine. (I'm assuming crays have socketpair)) */
4131 port = addresses[i].sin_port;
4132 got = PerlLIO_write (sockets[i], &port, sizeof(port));
4133 if (got != sizeof(port)) {
4134 if (got == -1)
4135 goto tidy_up_and_fail;
4136 goto abort_tidy_up_and_fail;
4137 }
4138 } while (i--);
4139
4140 /* Packets sent. I don't trust them to have arrived though.
4141 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4142 connect to localhost will use a second kernel thread. In 2.6 the
4143 first thread running the connect() returns before the second completes,
4144 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4145 returns 0. Poor programs have tripped up. One poor program's authors'
4146 had a 50-1 reverse stock split. Not sure how connected these were.)
4147 So I don't trust someone not to have an unpredictable UDP stack.
4148 */
4149
4150 {
4151 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4152 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4153 fd_set rset;
4154
4155 FD_ZERO (&rset);
4156 FD_SET (sockets[0], &rset);
4157 FD_SET (sockets[1], &rset);
4158
4159 got = PerlSock_select (max + 1, &rset, NULL, NULL, &waitfor);
4160 if (got != 2 || !FD_ISSET (sockets[0], &rset)
4161 || !FD_ISSET (sockets[1], &rset)) {
4162 /* I hope this is portable and appropriate. */
4163 if (got == -1)
4164 goto tidy_up_and_fail;
4165 goto abort_tidy_up_and_fail;
4166 }
4167 }
4168
4169 /* And the paranoia department even now doesn't trust it to have arrive
4170 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4171 {
4172 struct sockaddr_in readfrom;
4173 unsigned short buffer[2];
4174
4175 i = 1;
4176 do {
4177#ifdef MSG_DONTWAIT
4178 got = PerlSock_recvfrom (sockets[i], (char *) &buffer, sizeof(buffer),
4179 MSG_DONTWAIT,
4180 (struct sockaddr *) &readfrom, &size);
4181#else
4182 got = PerlSock_recvfrom (sockets[i], (char *) &buffer, sizeof(buffer),
4183 0,
4184 (struct sockaddr *) &readfrom, &size);
4185#endif
4186
4187 if (got == -1)
4188 goto tidy_up_and_fail;
4189 if (got != sizeof(port)
4190 || size != sizeof (struct sockaddr_in)
4191 /* Check other socket sent us its port. */
4192 || buffer[0] != (unsigned short) addresses[!i].sin_port
4193 /* Check kernel says we got the datagram from that socket. */
4194 || readfrom.sin_family != addresses[!i].sin_family
4195 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4196 || readfrom.sin_port != addresses[!i].sin_port)
4197 goto abort_tidy_up_and_fail;
4198 } while (i--);
4199 }
4200 /* My caller (my_socketpair) has validated that this is non-NULL */
4201 fd[0] = sockets[0];
4202 fd[1] = sockets[1];
4203 /* I hereby declare this connection open. May God bless all who cross
4204 her. */
4205 return 0;
4206
4207 abort_tidy_up_and_fail:
4208 errno = ECONNABORTED;
4209 tidy_up_and_fail:
4210 {
4211 int save_errno = errno;
4212 if (sockets[0] != -1)
4213 PerlLIO_close (sockets[0]);
4214 if (sockets[1] != -1)
4215 PerlLIO_close (sockets[1]);
4216 errno = save_errno;
4217 return -1;
4218 }
4219}
4220#endif /* EMULATE_SOCKETPAIR_UDP */
4221
4222#if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4223int
4224Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4225 /* Stevens says that family must be AF_LOCAL, protocol 0.
4226 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4227 dTHX;
4228 int listener = -1;
4229 int connector = -1;
4230 int acceptor = -1;
4231 struct sockaddr_in listen_addr;
4232 struct sockaddr_in connect_addr;
4233 Sock_size_t size;
4234
4235 if (protocol
4236#ifdef AF_UNIX
4237 || family != AF_UNIX
4238#endif
4239 ) {
4240 errno = EAFNOSUPPORT;
4241 return -1;
4242 }
4243 if (!fd) {
4244 errno = EINVAL;
4245 return -1;
4246 }
4247
4248#ifdef EMULATE_SOCKETPAIR_UDP
4249 if (type == SOCK_DGRAM)
4250 return S_socketpair_udp (fd);
4251#endif
4252
4253 listener = PerlSock_socket (AF_INET, type, 0);
4254 if (listener == -1)
4255 return -1;
4256 memset (&listen_addr, 0, sizeof (listen_addr));
4257 listen_addr.sin_family = AF_INET;
4258 listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
4259 listen_addr.sin_port = 0; /* kernel choses port. */
4260 if (PerlSock_bind (listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
4261 == -1)
4262 goto tidy_up_and_fail;
4263 if (PerlSock_listen(listener, 1) == -1)
4264 goto tidy_up_and_fail;
4265
4266 connector = PerlSock_socket (AF_INET, type, 0);
4267 if (connector == -1)
4268 goto tidy_up_and_fail;
4269 /* We want to find out the port number to connect to. */
4270 size = sizeof (connect_addr);
4271 if (PerlSock_getsockname (listener, (struct sockaddr *) &connect_addr, &size) == -1)
4272 goto tidy_up_and_fail;
4273 if (size != sizeof (connect_addr))
4274 goto abort_tidy_up_and_fail;
4275 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4276 sizeof (connect_addr)) == -1)
4277 goto tidy_up_and_fail;
4278
4279 size = sizeof (listen_addr);
4280 acceptor = PerlSock_accept (listener, (struct sockaddr *) &listen_addr, &size);
4281 if (acceptor == -1)
4282 goto tidy_up_and_fail;
4283 if (size != sizeof (listen_addr))
4284 goto abort_tidy_up_and_fail;
4285 PerlLIO_close (listener);
4286 /* Now check we are talking to ourself by matching port and host on the
4287 two sockets. */
4288 if (PerlSock_getsockname (connector, (struct sockaddr *) &connect_addr, &size) == -1)
4289 goto tidy_up_and_fail;
4290 if (size != sizeof (connect_addr)
4291 || listen_addr.sin_family != connect_addr.sin_family
4292 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4293 || listen_addr.sin_port != connect_addr.sin_port) {
4294 goto abort_tidy_up_and_fail;
4295 }
4296 fd[0] = connector;
4297 fd[1] = acceptor;
4298 return 0;
4299
4300 abort_tidy_up_and_fail:
4301 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4302 tidy_up_and_fail:
4303 {
4304 int save_errno = errno;
4305 if (listener != -1)
4306 PerlLIO_close (listener);
4307 if (connector != -1)
4308 PerlLIO_close (connector);
4309 if (acceptor != -1)
4310 PerlLIO_close (acceptor);
4311 errno = save_errno;
4312 return -1;
4313 }
4314}
4315#else
4316/* In any case have a stub so that there's code corresponding
4317 * to the my_socketpair in global.sym. */
4318int
4319Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4320#ifdef HAS_SOCKETPAIR
4321 return socketpair(family, type, protocol, fd);
4322#else
4323 return -1;
4324#endif
4325}
4326#endif
4327
4328/*
4329
4330=for apidoc sv_nosharing
4331
4332Dummy routine which "shares" an SV when there is no sharing module present.
4333Exists to avoid test for a NULL function pointer and because it could potentially warn under
4334some level of strict-ness.
4335
4336=cut
4337*/
4338
4339void
4340Perl_sv_nosharing(pTHX_ SV *sv)
4341{
4342}
4343
4344/*
4345=for apidoc sv_nolocking
4346
4347Dummy routine which "locks" an SV when there is no locking module present.
4348Exists to avoid test for a NULL function pointer and because it could potentially warn under
4349some level of strict-ness.
4350
4351=cut
4352*/
4353
4354void
4355Perl_sv_nolocking(pTHX_ SV *sv)
4356{
4357}
4358
4359
4360/*
4361=for apidoc sv_nounlocking
4362
4363Dummy routine which "unlocks" an SV when there is no locking module present.
4364Exists to avoid test for a NULL function pointer and because it could potentially warn under
4365some level of strict-ness.
4366
4367=cut
4368*/
4369
4370void
4371Perl_sv_nounlocking(pTHX_ SV *sv)
4372{
4373}
4374