This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add missing boundary check to grok_infnan
[perl5.git] / util.c
CommitLineData
a0d0e21e 1/* util.c
a687059c 2 *
1129b882
NC
3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
a687059c 5 *
d48672a2
LW
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
8d063cd8 8 *
8d063cd8 9 */
a0d0e21e
LW
10
11/*
4ac71550
TC
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
14 *
cdad3b53 15 * [p.598 of _The Lord of the Rings_, III/xi: "The Palantír"]
a0d0e21e 16 */
8d063cd8 17
166f8a29
DM
18/* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
22 */
23
8d063cd8 24#include "EXTERN.h"
864dbfa3 25#define PERL_IN_UTIL_C
8d063cd8 26#include "perl.h"
7dc86639 27#include "reentr.h"
62b28dd9 28
97cb92d6 29#if defined(USE_PERLIO)
2e0cfa16 30#include "perliol.h" /* For PerlIOUnix_refcnt */
6f408c34 31#endif
2e0cfa16 32
64ca3a65 33#ifndef PERL_MICRO
a687059c 34#include <signal.h>
36477c24
PP
35#ifndef SIG_ERR
36# define SIG_ERR ((Sighandler_t) -1)
37#endif
64ca3a65 38#endif
36477c24 39
3be8f094
TC
40#include <math.h>
41#include <stdlib.h>
42
172d2248
OS
43#ifdef __Lynx__
44/* Missing protos on LynxOS */
45int putenv(char *);
46#endif
47
40262ff4
AB
48#ifdef __amigaos__
49# include "amigaos4/amigaio.h"
50#endif
51
868439a2
JH
52#ifdef HAS_SELECT
53# ifdef I_SYS_SELECT
54# include <sys/select.h>
55# endif
56#endif
57
470dd224 58#ifdef USE_C_BACKTRACE
0762e42f
JH
59# ifdef I_BFD
60# define USE_BFD
61# ifdef PERL_DARWIN
62# undef USE_BFD /* BFD is useless in OS X. */
63# endif
64# ifdef USE_BFD
65# include <bfd.h>
66# endif
67# endif
470dd224
JH
68# ifdef I_DLFCN
69# include <dlfcn.h>
70# endif
71# ifdef I_EXECINFO
72# include <execinfo.h>
73# endif
74#endif
75
b001a0d1
FC
76#ifdef PERL_DEBUG_READONLY_COW
77# include <sys/mman.h>
78#endif
79
8d063cd8 80#define FLUSH
8d063cd8 81
a687059c
LW
82/* NOTE: Do not call the next three routines directly. Use the macros
83 * in handy.h, so that we can easily redefine everything to do tracking of
84 * allocated hunks back to the original New to track down any memory leaks.
20cec16a 85 * XXX This advice seems to be widely ignored :-( --AD August 1996.
a687059c
LW
86 */
87
79a92154 88#if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
1f4d2d4e
NC
89# define ALWAYS_NEED_THX
90#endif
91
b001a0d1
FC
92#if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
93static void
94S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
95{
96 if (header->readonly
97 && mprotect(header, header->size, PROT_READ|PROT_WRITE))
98 Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
99 header, header->size, errno);
100}
101
102static void
103S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
104{
105 if (header->readonly
106 && mprotect(header, header->size, PROT_READ))
107 Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
108 header, header->size, errno);
109}
110# define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
111# define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
112#else
113# define maybe_protect_rw(foo) NOOP
114# define maybe_protect_ro(foo) NOOP
115#endif
116
3f07c2bc
FC
117#if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
118 /* Use memory_debug_header */
119# define USE_MDH
120# if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
121 || defined(PERL_DEBUG_READONLY_COW)
122# define MDH_HAS_SIZE
123# endif
124#endif
125
26fa51c3
AMS
126/* paranoid version of system's malloc() */
127
bd4080b3 128Malloc_t
4f63d024 129Perl_safesysmalloc(MEM_SIZE size)
8d063cd8 130{
1f4d2d4e 131#ifdef ALWAYS_NEED_THX
54aff467 132 dTHX;
0cb20dae 133#endif
bd4080b3 134 Malloc_t ptr;
9f300641 135 dSAVEDERRNO;
9efda33a
TC
136
137#ifdef USE_MDH
138 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
139 goto out_of_memory;
a78adc84 140 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
9efda33a 141#endif
34de22dd 142#ifdef DEBUGGING
03c5309f 143 if ((SSize_t)size < 0)
147e3846 144 Perl_croak_nocontext("panic: malloc, size=%" UVuf, (UV) size);
34de22dd 145#endif
b001a0d1 146 if (!size) size = 1; /* malloc(0) is NASTY on our system */
9f300641 147 SAVE_ERRNO;
b001a0d1
FC
148#ifdef PERL_DEBUG_READONLY_COW
149 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
150 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
151 perror("mmap failed");
152 abort();
153 }
154#else
1ae509d1 155 ptr = (Malloc_t)PerlMem_malloc(size);
b001a0d1 156#endif
da927450 157 PERL_ALLOC_CHECK(ptr);
bd61b366 158 if (ptr != NULL) {
3f07c2bc 159#ifdef USE_MDH
7cb608b5
NC
160 struct perl_memory_debug_header *const header
161 = (struct perl_memory_debug_header *)ptr;
9a083ecf
NC
162#endif
163
164#ifdef PERL_POISON
7e337ee0 165 PoisonNew(((char *)ptr), size, char);
9a083ecf 166#endif
7cb608b5 167
9a083ecf 168#ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
169 header->interpreter = aTHX;
170 /* Link us into the list. */
171 header->prev = &PL_memory_debug_header;
172 header->next = PL_memory_debug_header.next;
173 PL_memory_debug_header.next = header;
b001a0d1 174 maybe_protect_rw(header->next);
7cb608b5 175 header->next->prev = header;
b001a0d1
FC
176 maybe_protect_ro(header->next);
177# ifdef PERL_DEBUG_READONLY_COW
178 header->readonly = 0;
cd1541b2 179# endif
e8dda941 180#endif
3f07c2bc 181#ifdef MDH_HAS_SIZE
b001a0d1
FC
182 header->size = size;
183#endif
b033d668 184 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
147e3846 185 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
b033d668 186
9f300641
TC
187 /* malloc() can modify errno() even on success, but since someone
188 writing perl code doesn't have any control over when perl calls
189 malloc() we need to hide that.
190 */
191 RESTORE_ERRNO;
b033d668 192 }
8d063cd8 193 else {
296f0d56 194#ifdef USE_MDH
9efda33a 195 out_of_memory:
296f0d56
TC
196#endif
197 {
198#ifndef ALWAYS_NEED_THX
199 dTHX;
200#endif
201 if (PL_nomemok)
202 ptr = NULL;
203 else
204 croak_no_mem();
205 }
8d063cd8 206 }
b033d668 207 return ptr;
8d063cd8
LW
208}
209
f2517201 210/* paranoid version of system's realloc() */
8d063cd8 211
bd4080b3 212Malloc_t
4f63d024 213Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
8d063cd8 214{
1f4d2d4e 215#ifdef ALWAYS_NEED_THX
54aff467 216 dTHX;
0cb20dae 217#endif
bd4080b3 218 Malloc_t ptr;
b001a0d1
FC
219#ifdef PERL_DEBUG_READONLY_COW
220 const MEM_SIZE oldsize = where
a78adc84 221 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
b001a0d1
FC
222 : 0;
223#endif
8d063cd8 224
7614df0c 225 if (!size) {
f2517201 226 safesysfree(where);
b033d668 227 ptr = NULL;
7614df0c 228 }
b033d668
DD
229 else if (!where) {
230 ptr = safesysmalloc(size);
231 }
232 else {
9f300641 233 dSAVE_ERRNO;
3f07c2bc 234#ifdef USE_MDH
b033d668 235 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
9efda33a
TC
236 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
237 goto out_of_memory;
b033d668
DD
238 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
239 {
240 struct perl_memory_debug_header *const header
241 = (struct perl_memory_debug_header *)where;
7cb608b5 242
b001a0d1 243# ifdef PERL_TRACK_MEMPOOL
b033d668
DD
244 if (header->interpreter != aTHX) {
245 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
246 header->interpreter, aTHX);
247 }
248 assert(header->next->prev == header);
249 assert(header->prev->next == header);
cd1541b2 250# ifdef PERL_POISON
b033d668
DD
251 if (header->size > size) {
252 const MEM_SIZE freed_up = header->size - size;
253 char *start_of_freed = ((char *)where) + size;
254 PoisonFree(start_of_freed, freed_up, char);
255 }
cd1541b2 256# endif
b001a0d1 257# endif
3f07c2bc 258# ifdef MDH_HAS_SIZE
b033d668 259 header->size = size;
b001a0d1 260# endif
b033d668 261 }
e8dda941 262#endif
34de22dd 263#ifdef DEBUGGING
b033d668 264 if ((SSize_t)size < 0)
147e3846 265 Perl_croak_nocontext("panic: realloc, size=%" UVuf, (UV)size);
34de22dd 266#endif
b001a0d1 267#ifdef PERL_DEBUG_READONLY_COW
b033d668
DD
268 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
269 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
270 perror("mmap failed");
271 abort();
272 }
273 Copy(where,ptr,oldsize < size ? oldsize : size,char);
274 if (munmap(where, oldsize)) {
275 perror("munmap failed");
276 abort();
277 }
b001a0d1 278#else
b033d668 279 ptr = (Malloc_t)PerlMem_realloc(where,size);
b001a0d1 280#endif
b033d668 281 PERL_ALLOC_CHECK(ptr);
a1d180c4 282
4fd0a9b8
NC
283 /* MUST do this fixup first, before doing ANYTHING else, as anything else
284 might allocate memory/free/move memory, and until we do the fixup, it
285 may well be chasing (and writing to) free memory. */
b033d668 286 if (ptr != NULL) {
b001a0d1 287#ifdef PERL_TRACK_MEMPOOL
b033d668
DD
288 struct perl_memory_debug_header *const header
289 = (struct perl_memory_debug_header *)ptr;
7cb608b5 290
9a083ecf 291# ifdef PERL_POISON
b033d668
DD
292 if (header->size < size) {
293 const MEM_SIZE fresh = size - header->size;
294 char *start_of_fresh = ((char *)ptr) + size;
295 PoisonNew(start_of_fresh, fresh, char);
296 }
9a083ecf
NC
297# endif
298
b033d668
DD
299 maybe_protect_rw(header->next);
300 header->next->prev = header;
301 maybe_protect_ro(header->next);
302 maybe_protect_rw(header->prev);
303 header->prev->next = header;
304 maybe_protect_ro(header->prev);
b001a0d1 305#endif
b033d668 306 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
9f300641
TC
307
308 /* realloc() can modify errno() even on success, but since someone
309 writing perl code doesn't have any control over when perl calls
310 realloc() we need to hide that.
311 */
312 RESTORE_ERRNO;
b033d668 313 }
4fd0a9b8
NC
314
315 /* In particular, must do that fixup above before logging anything via
316 *printf(), as it can reallocate memory, which can cause SEGVs. */
317
147e3846
KW
318 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
319 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
4fd0a9b8 320
b033d668 321 if (ptr == NULL) {
296f0d56 322#ifdef USE_MDH
9efda33a 323 out_of_memory:
296f0d56
TC
324#endif
325 {
326#ifndef ALWAYS_NEED_THX
327 dTHX;
328#endif
329 if (PL_nomemok)
330 ptr = NULL;
331 else
332 croak_no_mem();
333 }
0cb20dae 334 }
8d063cd8 335 }
b033d668 336 return ptr;
8d063cd8
LW
337}
338
f2517201 339/* safe version of system's free() */
8d063cd8 340
54310121 341Free_t
4f63d024 342Perl_safesysfree(Malloc_t where)
8d063cd8 343{
79a92154 344#ifdef ALWAYS_NEED_THX
54aff467 345 dTHX;
155aba94 346#endif
147e3846 347 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
378cc40b 348 if (where) {
3f07c2bc 349#ifdef USE_MDH
6edcbed6 350 Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
cd1541b2 351 {
7cb608b5 352 struct perl_memory_debug_header *const header
6edcbed6 353 = (struct perl_memory_debug_header *)where_intrn;
7cb608b5 354
3f07c2bc 355# ifdef MDH_HAS_SIZE
b001a0d1
FC
356 const MEM_SIZE size = header->size;
357# endif
358# ifdef PERL_TRACK_MEMPOOL
7cb608b5 359 if (header->interpreter != aTHX) {
5637ef5b
NC
360 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
361 header->interpreter, aTHX);
7cb608b5
NC
362 }
363 if (!header->prev) {
cd1541b2
NC
364 Perl_croak_nocontext("panic: duplicate free");
365 }
5637ef5b
NC
366 if (!(header->next))
367 Perl_croak_nocontext("panic: bad free, header->next==NULL");
368 if (header->next->prev != header || header->prev->next != header) {
369 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
370 "header=%p, ->prev->next=%p",
371 header->next->prev, header,
372 header->prev->next);
cd1541b2 373 }
7cb608b5 374 /* Unlink us from the chain. */
b001a0d1 375 maybe_protect_rw(header->next);
7cb608b5 376 header->next->prev = header->prev;
b001a0d1
FC
377 maybe_protect_ro(header->next);
378 maybe_protect_rw(header->prev);
7cb608b5 379 header->prev->next = header->next;
b001a0d1
FC
380 maybe_protect_ro(header->prev);
381 maybe_protect_rw(header);
7cb608b5 382# ifdef PERL_POISON
6edcbed6 383 PoisonNew(where_intrn, size, char);
cd1541b2 384# endif
7cb608b5
NC
385 /* Trigger the duplicate free warning. */
386 header->next = NULL;
b001a0d1
FC
387# endif
388# ifdef PERL_DEBUG_READONLY_COW
6edcbed6 389 if (munmap(where_intrn, size)) {
b001a0d1
FC
390 perror("munmap failed");
391 abort();
392 }
393# endif
7cb608b5 394 }
6edcbed6
DD
395#else
396 Malloc_t where_intrn = where;
397#endif /* USE_MDH */
b001a0d1 398#ifndef PERL_DEBUG_READONLY_COW
6edcbed6 399 PerlMem_free(where_intrn);
b001a0d1 400#endif
378cc40b 401 }
8d063cd8
LW
402}
403
f2517201 404/* safe version of system's calloc() */
1050c9ca 405
bd4080b3 406Malloc_t
4f63d024 407Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
1050c9ca 408{
1f4d2d4e 409#ifdef ALWAYS_NEED_THX
54aff467 410 dTHX;
0cb20dae 411#endif
bd4080b3 412 Malloc_t ptr;
3f07c2bc 413#if defined(USE_MDH) || defined(DEBUGGING)
ad7244db 414 MEM_SIZE total_size = 0;
4b1123b9 415#endif
1050c9ca 416
ad7244db 417 /* Even though calloc() for zero bytes is strange, be robust. */
4b1123b9 418 if (size && (count <= MEM_SIZE_MAX / size)) {
3f07c2bc 419#if defined(USE_MDH) || defined(DEBUGGING)
ad7244db 420 total_size = size * count;
4b1123b9
NC
421#endif
422 }
ad7244db 423 else
d1decf2b 424 croak_memory_wrap();
3f07c2bc 425#ifdef USE_MDH
a78adc84
DM
426 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
427 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
ad7244db 428 else
d1decf2b 429 croak_memory_wrap();
ad7244db 430#endif
1050c9ca 431#ifdef DEBUGGING
03c5309f 432 if ((SSize_t)size < 0 || (SSize_t)count < 0)
147e3846 433 Perl_croak_nocontext("panic: calloc, size=%" UVuf ", count=%" UVuf,
5637ef5b 434 (UV)size, (UV)count);
1050c9ca 435#endif
b001a0d1
FC
436#ifdef PERL_DEBUG_READONLY_COW
437 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
438 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
439 perror("mmap failed");
440 abort();
441 }
442#elif defined(PERL_TRACK_MEMPOOL)
e1a95402
NC
443 /* Have to use malloc() because we've added some space for our tracking
444 header. */
ad7244db
JH
445 /* malloc(0) is non-portable. */
446 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
e1a95402
NC
447#else
448 /* Use calloc() because it might save a memset() if the memory is fresh
449 and clean from the OS. */
ad7244db
JH
450 if (count && size)
451 ptr = (Malloc_t)PerlMem_calloc(count, size);
452 else /* calloc(0) is non-portable. */
453 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
e8dda941 454#endif
da927450 455 PERL_ALLOC_CHECK(ptr);
22730398 456 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) calloc %zu x %zu = %zu bytes\n",PTR2UV(ptr),(long)PL_an++, count, size, total_size));
bd61b366 457 if (ptr != NULL) {
3f07c2bc 458#ifdef USE_MDH
7cb608b5
NC
459 {
460 struct perl_memory_debug_header *const header
461 = (struct perl_memory_debug_header *)ptr;
462
b001a0d1 463# ifndef PERL_DEBUG_READONLY_COW
e1a95402 464 memset((void*)ptr, 0, total_size);
b001a0d1
FC
465# endif
466# ifdef PERL_TRACK_MEMPOOL
7cb608b5
NC
467 header->interpreter = aTHX;
468 /* Link us into the list. */
469 header->prev = &PL_memory_debug_header;
470 header->next = PL_memory_debug_header.next;
471 PL_memory_debug_header.next = header;
b001a0d1 472 maybe_protect_rw(header->next);
7cb608b5 473 header->next->prev = header;
b001a0d1
FC
474 maybe_protect_ro(header->next);
475# ifdef PERL_DEBUG_READONLY_COW
476 header->readonly = 0;
477# endif
478# endif
3f07c2bc 479# ifdef MDH_HAS_SIZE
e1a95402 480 header->size = total_size;
cd1541b2 481# endif
a78adc84 482 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
7cb608b5 483 }
e8dda941 484#endif
1050c9ca
PP
485 return ptr;
486 }
0cb20dae 487 else {
1f4d2d4e 488#ifndef ALWAYS_NEED_THX
0cb20dae
NC
489 dTHX;
490#endif
491 if (PL_nomemok)
492 return NULL;
4cbe3a7d 493 croak_no_mem();
0cb20dae 494 }
1050c9ca
PP
495}
496
cae6d0e5
GS
497/* These must be defined when not using Perl's malloc for binary
498 * compatibility */
499
500#ifndef MYMALLOC
501
502Malloc_t Perl_malloc (MEM_SIZE nbytes)
503{
20b7effb
JH
504#ifdef PERL_IMPLICIT_SYS
505 dTHX;
506#endif
077a72a9 507 return (Malloc_t)PerlMem_malloc(nbytes);
cae6d0e5
GS
508}
509
510Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
511{
20b7effb
JH
512#ifdef PERL_IMPLICIT_SYS
513 dTHX;
514#endif
077a72a9 515 return (Malloc_t)PerlMem_calloc(elements, size);
cae6d0e5
GS
516}
517
518Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
519{
20b7effb
JH
520#ifdef PERL_IMPLICIT_SYS
521 dTHX;
522#endif
077a72a9 523 return (Malloc_t)PerlMem_realloc(where, nbytes);
cae6d0e5
GS
524}
525
526Free_t Perl_mfree (Malloc_t where)
527{
20b7effb
JH
528#ifdef PERL_IMPLICIT_SYS
529 dTHX;
530#endif
cae6d0e5
GS
531 PerlMem_free(where);
532}
533
534#endif
535
19e16554
DM
536/* copy a string up to some (non-backslashed) delimiter, if any.
537 * With allow_escape, converts \<delimiter> to <delimiter>, while leaves
538 * \<non-delimiter> as-is.
539 * Returns the position in the src string of the closing delimiter, if
540 * any, or returns fromend otherwise.
541 * This is the internal implementation for Perl_delimcpy and
542 * Perl_delimcpy_no_escape.
543 */
8d063cd8 544
ba0a4150 545static char *
31ee10f1 546S_delimcpy_intern(char *to, const char *toend, const char *from,
ba0a4150
FC
547 const char *fromend, int delim, I32 *retlen,
548 const bool allow_escape)
8d063cd8 549{
eb578fdb 550 I32 tolen;
35da51f7 551
7918f24d
NC
552 PERL_ARGS_ASSERT_DELIMCPY;
553
fc36a67e 554 for (tolen = 0; from < fromend; from++, tolen++) {
19e16554 555 if (allow_escape && *from == '\\' && from + 1 < fromend) {
35da51f7 556 if (from[1] != delim) {
fc36a67e
PP
557 if (to < toend)
558 *to++ = *from;
559 tolen++;
fc36a67e 560 }
35da51f7 561 from++;
378cc40b 562 }
bedebaa5 563 else if (*from == delim)
8d063cd8 564 break;
fc36a67e
PP
565 if (to < toend)
566 *to++ = *from;
8d063cd8 567 }
bedebaa5
CS
568 if (to < toend)
569 *to = '\0';
fc36a67e 570 *retlen = tolen;
73d840c0 571 return (char *)from;
8d063cd8
LW
572}
573
ab017425
KW
574
575/*
576=for apidoc delimcpy_no_escape
577
578Copy a source buffer to a destination buffer, stopping at (but not including)
579the first occurrence of the delimiter byte C<delim>, in the source. The source
580is the bytes between C<from> and C<fromend> inclusive. The dest is C<to>
581through C<toend>.
582
583Nothing is copied beyond what fits between C<to> through C<toend>. If C<delim>
584doesn't occur in the source buffer, as much of the source as will fit is copied
585to the destination.
586
587The actual number of bytes copied is written to C<*retlen>.
588
589If there is room in the destination available after the copy, an extra
590terminating safety NUL byte is written (not included in the returned length).
591
592=cut
593*/
ba0a4150 594char *
ad9dfdb7
KW
595Perl_delimcpy_no_escape(char *to, const char *toend, const char *from,
596 const char *fromend, int delim, I32 *retlen)
ba0a4150 597{
ab017425
KW
598 const char * delim_pos;
599 Ptrdiff_t to_len = toend - to;
600
601 /* Only use the minimum of the available source/dest */
602 Ptrdiff_t copy_len = MIN(fromend - from, to_len);
603
ad9dfdb7 604 PERL_ARGS_ASSERT_DELIMCPY_NO_ESCAPE;
ba0a4150 605
ab017425
KW
606 assert(copy_len >= 0);
607
608 /* Look for the first delimiter in the portion of the source we are allowed
609 * to look at (determined by the input bounds). */
610 delim_pos = (const char *) memchr(from, delim, copy_len);
611 if (delim_pos) {
612 copy_len = delim_pos - from;
613 } /* else didn't find it: copy all of the source permitted */
614
615 Copy(from, to, copy_len, char);
616
617 if (retlen) {
618 *retlen = copy_len;
619 }
620
621 /* If there is extra space available, add a trailing NUL */
622 if (copy_len < to_len) {
623 to[copy_len] = '\0';
624 }
625
626 return (char *) from + copy_len;
ba0a4150
FC
627}
628
629char *
ad9dfdb7 630Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
ba0a4150 631{
ad9dfdb7 632 PERL_ARGS_ASSERT_DELIMCPY;
ba0a4150 633
ad9dfdb7 634 return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 1);
ba0a4150
FC
635}
636
fcfc5a27
KW
637/*
638=head1 Miscellaneous Functions
639
44170c9a 640=for apidoc ninstr
fcfc5a27
KW
641
642Find the first (leftmost) occurrence of a sequence of bytes within another
643sequence. This is the Perl version of C<strstr()>, extended to handle
644arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL>
645is what the initial C<n> in the function name stands for; some systems have an
646equivalent, C<memmem()>, but with a somewhat different API).
647
648Another way of thinking about this function is finding a needle in a haystack.
649C<big> points to the first byte in the haystack. C<big_end> points to one byte
650beyond the final byte in the haystack. C<little> points to the first byte in
651the needle. C<little_end> points to one byte beyond the final byte in the
652needle. All the parameters must be non-C<NULL>.
653
654The function returns C<NULL> if there is no occurrence of C<little> within
655C<big>. If C<little> is the empty string, C<big> is returned.
656
657Because this function operates at the byte level, and because of the inherent
658characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the
659needle and the haystack are strings with the same UTF-8ness, but not if the
660UTF-8ness differs.
661
662=cut
663
664*/
a687059c
LW
665
666char *
04c9e624 667Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
8d063cd8 668{
7918f24d 669 PERL_ARGS_ASSERT_NINSTR;
b8070b07
KW
670
671#ifdef HAS_MEMMEM
672 return ninstr(big, bigend, little, lend);
673#else
674
66256797
KW
675 if (little >= lend) {
676 return (char*) big;
677 }
678 else {
679 const U8 first = *little;
680 Size_t lsize;
681
682 /* No match can start closer to the end of the haystack than the length
683 * of the needle. */
684 bigend -= lend - little;
685 little++; /* Look for 'first', then the remainder is in here */
686 lsize = lend - little;
687
4c8626be 688 while (big <= bigend) {
66256797
KW
689 big = (char *) memchr((U8 *) big, first, bigend - big + 1);
690 if (big == NULL || big > bigend) {
691 return NULL;
4c8626be 692 }
66256797
KW
693
694 if (memEQ(big + 1, little, lsize)) {
695 return (char*) big;
696 }
697 big++;
4c8626be 698 }
378cc40b 699 }
66256797 700
bd61b366 701 return NULL;
b8070b07
KW
702
703#endif
704
a687059c
LW
705}
706
fcfc5a27
KW
707/*
708=head1 Miscellaneous Functions
709
44170c9a 710=for apidoc rninstr
fcfc5a27
KW
711
712Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a
713sequence of bytes within another sequence, returning C<NULL> if there is no
714such occurrence.
715
716=cut
717
718*/
a687059c
LW
719
720char *
5aaab254 721Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
a687059c 722{
eb578fdb
KW
723 const char *bigbeg;
724 const I32 first = *little;
725 const char * const littleend = lend;
a687059c 726
7918f24d
NC
727 PERL_ARGS_ASSERT_RNINSTR;
728
260d78c9 729 if (little >= littleend)
08105a92 730 return (char*)bigend;
a687059c
LW
731 bigbeg = big;
732 big = bigend - (littleend - little++);
733 while (big >= bigbeg) {
eb578fdb 734 const char *s, *x;
a687059c
LW
735 if (*big-- != first)
736 continue;
737 for (x=big+2,s=little; s < littleend; /**/ ) {
4fc877ac 738 if (*s != *x)
a687059c 739 break;
4fc877ac
AL
740 else {
741 x++;
742 s++;
a687059c
LW
743 }
744 }
745 if (s >= littleend)
08105a92 746 return (char*)(big+1);
378cc40b 747 }
bd61b366 748 return NULL;
378cc40b 749}
a687059c 750
cf93c79d
IZ
751/* As a space optimization, we do not compile tables for strings of length
752 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
753 special-cased in fbm_instr().
754
755 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
756
954c1994 757/*
ccfc67b7
JH
758=head1 Miscellaneous Functions
759
954c1994
GS
760=for apidoc fbm_compile
761
41715441 762Analyzes the string in order to make fast searches on it using C<fbm_instr()>
954c1994
GS
763-- the Boyer-Moore algorithm.
764
765=cut
766*/
767
378cc40b 768void
7506f9c3 769Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
378cc40b 770{
eb578fdb 771 const U8 *s;
ea725ce6 772 STRLEN i;
0b71040e 773 STRLEN len;
2bda37ba 774 MAGIC *mg;
79072805 775
7918f24d
NC
776 PERL_ARGS_ASSERT_FBM_COMPILE;
777
948d2370 778 if (isGV_with_GP(sv) || SvROK(sv))
4265b45d
NC
779 return;
780
9402563a
NC
781 if (SvVALID(sv))
782 return;
783
c517dc2b 784 if (flags & FBMcf_TAIL) {
890ce7af 785 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
396482e1 786 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
c517dc2b
JH
787 if (mg && mg->mg_len >= 0)
788 mg->mg_len++;
789 }
11609d9c 790 if (!SvPOK(sv) || SvNIOKp(sv))
66379c06
FC
791 s = (U8*)SvPV_force_mutable(sv, len);
792 else s = (U8 *)SvPV_mutable(sv, len);
d1be9408 793 if (len == 0) /* TAIL might be on a zero-length string. */
cf93c79d 794 return;
c13a5c80 795 SvUPGRADE(sv, SVt_PVMG);
78d0cf80 796 SvIOK_off(sv);
8eeaf79a 797 SvNOK_off(sv);
2bda37ba 798
a5c7cb08 799 /* add PERL_MAGIC_bm magic holding the FBM lookup table */
2bda37ba
NC
800
801 assert(!mg_find(sv, PERL_MAGIC_bm));
802 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
803 assert(mg);
804
02128f11 805 if (len > 2) {
21aeb718
NC
806 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
807 the BM table. */
66a1b24b 808 const U8 mlen = (len>255) ? 255 : (U8)len;
2bda37ba 809 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
eb578fdb 810 U8 *table;
cf93c79d 811
2bda37ba 812 Newx(table, 256, U8);
7506f9c3 813 memset((void*)table, mlen, 256);
2bda37ba
NC
814 mg->mg_ptr = (char *)table;
815 mg->mg_len = 256;
816
817 s += len - 1; /* last char */
02128f11 818 i = 0;
cf93c79d
IZ
819 while (s >= sb) {
820 if (table[*s] == mlen)
7506f9c3 821 table[*s] = (U8)i;
cf93c79d
IZ
822 s--, i++;
823 }
378cc40b 824 }
378cc40b 825
cf93c79d 826 BmUSEFUL(sv) = 100; /* Initial value */
b4204fb6 827 ((XPVNV*)SvANY(sv))->xnv_u.xnv_bm_tail = cBOOL(flags & FBMcf_TAIL);
378cc40b
LW
828}
829
cf93c79d 830
954c1994
GS
831/*
832=for apidoc fbm_instr
833
3f4963df 834Returns the location of the SV in the string delimited by C<big> and
41c8d07a
DM
835C<bigend> (C<bigend>) is the char following the last char).
836It returns C<NULL> if the string can't be found. The C<sv>
796b6530 837does not have to be C<fbm_compiled>, but the search will not be as fast
954c1994
GS
838then.
839
840=cut
41c8d07a 841
a3815e44 842If SvTAIL(littlestr) is true, a fake "\n" was appended to the string
41c8d07a
DM
843during FBM compilation due to FBMcf_TAIL in flags. It indicates that
844the littlestr must be anchored to the end of bigstr (or to any \n if
845FBMrf_MULTILINE).
846
847E.g. The regex compiler would compile /abc/ to a littlestr of "abc",
848while /abc$/ compiles to "abc\n" with SvTAIL() true.
849
850A littlestr of "abc", !SvTAIL matches as /abc/;
851a littlestr of "ab\n", SvTAIL matches as:
852 without FBMrf_MULTILINE: /ab\n?\z/
853 with FBMrf_MULTILINE: /ab\n/ || /ab\z/;
854
855(According to Ilya from 1999; I don't know if this is still true, DAPM 2015):
856 "If SvTAIL is actually due to \Z or \z, this gives false positives
857 if multiline".
954c1994
GS
858*/
859
41c8d07a 860
378cc40b 861char *
5aaab254 862Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
378cc40b 863{
eb578fdb 864 unsigned char *s;
cf93c79d 865 STRLEN l;
eb578fdb
KW
866 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
867 STRLEN littlelen = l;
868 const I32 multiline = flags & FBMrf_MULTILINE;
4e8879f3
DM
869 bool valid = SvVALID(littlestr);
870 bool tail = valid ? cBOOL(SvTAIL(littlestr)) : FALSE;
cf93c79d 871
7918f24d
NC
872 PERL_ARGS_ASSERT_FBM_INSTR;
873
bb152a4b
DM
874 assert(bigend >= big);
875
eb160463 876 if ((STRLEN)(bigend - big) < littlelen) {
e08d24ff 877 if ( tail
eb160463 878 && ((STRLEN)(bigend - big) == littlelen - 1)
a1d180c4 879 && (littlelen == 1
12ae5dfc 880 || (*big == *little &&
27da23d5 881 memEQ((char *)big, (char *)little, littlelen - 1))))
cf93c79d 882 return (char*)big;
bd61b366 883 return NULL;
cf93c79d 884 }
378cc40b 885
21aeb718
NC
886 switch (littlelen) { /* Special cases for 0, 1 and 2 */
887 case 0:
888 return (char*)big; /* Cannot be SvTAIL! */
41c8d07a 889
21aeb718 890 case 1:
e08d24ff 891 if (tail && !multiline) /* Anchor only! */
147f21b5
DM
892 /* [-1] is safe because we know that bigend != big. */
893 return (char *) (bigend - (bigend[-1] == '\n'));
894
895 s = (unsigned char *)memchr((void*)big, *little, bigend-big);
896 if (s)
897 return (char *)s;
e08d24ff 898 if (tail)
cf93c79d 899 return (char *) bigend;
bd61b366 900 return NULL;
41c8d07a 901
21aeb718 902 case 2:
e08d24ff 903 if (tail && !multiline) {
147f21b5
DM
904 /* a littlestr with SvTAIL must be of the form "X\n" (where X
905 * is a single char). It is anchored, and can only match
906 * "....X\n" or "....X" */
907 if (bigend[-2] == *little && bigend[-1] == '\n')
cf93c79d
IZ
908 return (char*)bigend - 2;
909 if (bigend[-1] == *little)
910 return (char*)bigend - 1;
bd61b366 911 return NULL;
cf93c79d 912 }
147f21b5 913
cf93c79d 914 {
147f21b5
DM
915 /* memchr() is likely to be very fast, possibly using whatever
916 * hardware support is available, such as checking a whole
917 * cache line in one instruction.
918 * So for a 2 char pattern, calling memchr() is likely to be
919 * faster than running FBM, or rolling our own. The previous
920 * version of this code was roll-your-own which typically
921 * only needed to read every 2nd char, which was good back in
922 * the day, but no longer.
923 */
924 unsigned char c1 = little[0];
925 unsigned char c2 = little[1];
926
927 /* *** for all this case, bigend points to the last char,
928 * not the trailing \0: this makes the conditions slightly
929 * simpler */
930 bigend--;
931 s = big;
932 if (c1 != c2) {
933 while (s < bigend) {
934 /* do a quick test for c1 before calling memchr();
935 * this avoids the expensive fn call overhead when
936 * there are lots of c1's */
937 if (LIKELY(*s != c1)) {
938 s++;
939 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
940 if (!s)
941 break;
942 }
943 if (s[1] == c2)
944 return (char*)s;
945
946 /* failed; try searching for c2 this time; that way
947 * we don't go pathologically slow when the string
948 * consists mostly of c1's or vice versa.
949 */
950 s += 2;
951 if (s > bigend)
952 break;
953 s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1);
954 if (!s)
955 break;
956 if (s[-1] == c1)
957 return (char*)s - 1;
958 }
959 }
960 else {
961 /* c1, c2 the same */
962 while (s < bigend) {
963 if (s[0] == c1) {
964 got_1char:
965 if (s[1] == c1)
966 return (char*)s;
967 s += 2;
968 }
969 else {
970 s++;
971 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
972 if (!s || s >= bigend)
973 break;
974 goto got_1char;
975 }
976 }
977 }
978
979 /* failed to find 2 chars; try anchored match at end without
980 * the \n */
e08d24ff 981 if (tail && bigend[0] == little[0])
147f21b5
DM
982 return (char *)bigend;
983 return NULL;
984 }
41c8d07a 985
21aeb718
NC
986 default:
987 break; /* Only lengths 0 1 and 2 have special-case code. */
d48672a2 988 }
21aeb718 989
e08d24ff 990 if (tail && !multiline) { /* tail anchored? */
bbce6d69 991 s = bigend - littlelen;
a1d180c4 992 if (s >= big && bigend[-1] == '\n' && *s == *little
cf93c79d
IZ
993 /* Automatically of length > 2 */
994 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
7506f9c3 995 {
bbce6d69 996 return (char*)s; /* how sweet it is */
7506f9c3
GS
997 }
998 if (s[1] == *little
999 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1000 {
cf93c79d 1001 return (char*)s + 1; /* how sweet it is */
7506f9c3 1002 }
bd61b366 1003 return NULL;
02128f11 1004 }
41c8d07a 1005
4e8879f3 1006 if (!valid) {
147f21b5 1007 /* not compiled; use Perl_ninstr() instead */
c4420975 1008 char * const b = ninstr((char*)big,(char*)bigend,
cf93c79d
IZ
1009 (char*)little, (char*)little + littlelen);
1010
add424da 1011 assert(!tail); /* valid => FBM; tail only set on SvVALID SVs */
cf93c79d 1012 return b;
a687059c 1013 }
a1d180c4 1014
3566a07d
NC
1015 /* Do actual FBM. */
1016 if (littlelen > (STRLEN)(bigend - big))
1017 return NULL;
1018
1019 {
2bda37ba 1020 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
eb578fdb 1021 const unsigned char *oldlittle;
cf93c79d 1022
316ebaf2
JH
1023 assert(mg);
1024
cf93c79d
IZ
1025 --littlelen; /* Last char found by table lookup */
1026
1027 s = big + littlelen;
1028 little += littlelen; /* last char */
1029 oldlittle = little;
1030 if (s < bigend) {
316ebaf2 1031 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
147f21b5 1032 const unsigned char lastc = *little;
eb578fdb 1033 I32 tmp;
cf93c79d
IZ
1034
1035 top2:
7506f9c3 1036 if ((tmp = table[*s])) {
147f21b5
DM
1037 /* *s != lastc; earliest position it could match now is
1038 * tmp slots further on */
1039 if ((s += tmp) >= bigend)
1040 goto check_end;
1041 if (LIKELY(*s != lastc)) {
1042 s++;
1043 s = (unsigned char *)memchr((void*)s, lastc, bigend - s);
1044 if (!s) {
1045 s = bigend;
1046 goto check_end;
1047 }
1048 goto top2;
1049 }
cf93c79d 1050 }
147f21b5
DM
1051
1052
1053 /* hand-rolled strncmp(): less expensive than calling the
1054 * real function (maybe???) */
1055 {
eb578fdb 1056 unsigned char * const olds = s;
cf93c79d
IZ
1057
1058 tmp = littlelen;
1059
1060 while (tmp--) {
1061 if (*--s == *--little)
1062 continue;
cf93c79d
IZ
1063 s = olds + 1; /* here we pay the price for failure */
1064 little = oldlittle;
1065 if (s < bigend) /* fake up continue to outer loop */
1066 goto top2;
1067 goto check_end;
1068 }
1069 return (char *)s;
a687059c 1070 }
378cc40b 1071 }
cf93c79d 1072 check_end:
c8029a41 1073 if ( s == bigend
e08d24ff 1074 && tail
12ae5dfc
JH
1075 && memEQ((char *)(bigend - littlelen),
1076 (char *)(oldlittle - littlelen), littlelen) )
cf93c79d 1077 return (char*)bigend - littlelen;
bd61b366 1078 return NULL;
378cc40b 1079 }
378cc40b
LW
1080}
1081
5e6ebb12
KW
1082const char *
1083Perl_cntrl_to_mnemonic(const U8 c)
1084{
1085 /* Returns the mnemonic string that represents character 'c', if one
1086 * exists; NULL otherwise. The only ones that exist for the purposes of
1087 * this routine are a few control characters */
1088
1089 switch (c) {
1090 case '\a': return "\\a";
1091 case '\b': return "\\b";
1092 case ESC_NATIVE: return "\\e";
1093 case '\f': return "\\f";
1094 case '\n': return "\\n";
1095 case '\r': return "\\r";
1096 case '\t': return "\\t";
1097 }
1098
1099 return NULL;
1100}
1101
8d063cd8
LW
1102/* copy a string to a safe spot */
1103
954c1994 1104/*
ccfc67b7
JH
1105=head1 Memory Management
1106
954c1994
GS
1107=for apidoc savepv
1108
72d33970
FC
1109Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1110string which is a duplicate of C<pv>. The size of the string is
30a15352 1111determined by C<strlen()>, which means it may not contain embedded C<NUL>
3e66cf74
KW
1112characters and must have a trailing C<NUL>. To prevent memory leaks, the
1113memory allocated for the new string needs to be freed when no longer needed.
2f07b2fb
KW
1114This can be done with the L</C<Safefree>> function, or
1115L<C<SAVEFREEPV>|perlguts/SAVEFREEPV(p)>.
954c1994 1116
0358c255
KW
1117On some platforms, Windows for example, all allocated memory owned by a thread
1118is deallocated when that thread ends. So if you need that not to happen, you
1119need to use the shared memory functions, such as C<L</savesharedpv>>.
1120
954c1994
GS
1121=cut
1122*/
1123
8d063cd8 1124char *
efdfce31 1125Perl_savepv(pTHX_ const char *pv)
8d063cd8 1126{
96a5add6 1127 PERL_UNUSED_CONTEXT;
e90e2364 1128 if (!pv)
bd61b366 1129 return NULL;
66a1b24b
AL
1130 else {
1131 char *newaddr;
1132 const STRLEN pvlen = strlen(pv)+1;
10edeb5d
JH
1133 Newx(newaddr, pvlen, char);
1134 return (char*)memcpy(newaddr, pv, pvlen);
66a1b24b 1135 }
8d063cd8
LW
1136}
1137
a687059c
LW
1138/* same thing but with a known length */
1139
954c1994
GS
1140/*
1141=for apidoc savepvn
1142
72d33970 1143Perl's version of what C<strndup()> would be if it existed. Returns a
61a925ed 1144pointer to a newly allocated string which is a duplicate of the first
72d33970 1145C<len> bytes from C<pv>, plus a trailing
6602b933 1146C<NUL> byte. The memory allocated for
cbf82dd0 1147the new string can be freed with the C<Safefree()> function.
954c1994 1148
0358c255
KW
1149On some platforms, Windows for example, all allocated memory owned by a thread
1150is deallocated when that thread ends. So if you need that not to happen, you
1151need to use the shared memory functions, such as C<L</savesharedpvn>>.
1152
954c1994
GS
1153=cut
1154*/
1155
a687059c 1156char *
052d9143 1157Perl_savepvn(pTHX_ const char *pv, Size_t len)
a687059c 1158{
eb578fdb 1159 char *newaddr;
96a5add6 1160 PERL_UNUSED_CONTEXT;
a687059c 1161
a02a5408 1162 Newx(newaddr,len+1,char);
92110913 1163 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
efdfce31 1164 if (pv) {
e90e2364
NC
1165 /* might not be null terminated */
1166 newaddr[len] = '\0';
07409e01 1167 return (char *) CopyD(pv,newaddr,len,char);
92110913
NIS
1168 }
1169 else {
07409e01 1170 return (char *) ZeroD(newaddr,len+1,char);
92110913 1171 }
a687059c
LW
1172}
1173
05ec9bb3
NIS
1174/*
1175=for apidoc savesharedpv
1176
61a925ed
AMS
1177A version of C<savepv()> which allocates the duplicate string in memory
1178which is shared between threads.
05ec9bb3
NIS
1179
1180=cut
1181*/
1182char *
efdfce31 1183Perl_savesharedpv(pTHX_ const char *pv)
05ec9bb3 1184{
eb578fdb 1185 char *newaddr;
490a0e98 1186 STRLEN pvlen;
dc3bf405
BF
1187
1188 PERL_UNUSED_CONTEXT;
1189
e90e2364 1190 if (!pv)
bd61b366 1191 return NULL;
e90e2364 1192
490a0e98
NC
1193 pvlen = strlen(pv)+1;
1194 newaddr = (char*)PerlMemShared_malloc(pvlen);
e90e2364 1195 if (!newaddr) {
4cbe3a7d 1196 croak_no_mem();
05ec9bb3 1197 }
10edeb5d 1198 return (char*)memcpy(newaddr, pv, pvlen);
05ec9bb3
NIS
1199}
1200
2e0de35c 1201/*
d9095cec
NC
1202=for apidoc savesharedpvn
1203
1204A version of C<savepvn()> which allocates the duplicate string in memory
796b6530 1205which is shared between threads. (With the specific difference that a C<NULL>
d9095cec
NC
1206pointer is not acceptable)
1207
1208=cut
1209*/
1210char *
1211Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1212{
1213 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
7918f24d 1214
dc3bf405 1215 PERL_UNUSED_CONTEXT;
6379d4a9 1216 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
7918f24d 1217
d9095cec 1218 if (!newaddr) {
4cbe3a7d 1219 croak_no_mem();
d9095cec
NC
1220 }
1221 newaddr[len] = '\0';
1222 return (char*)memcpy(newaddr, pv, len);
1223}
1224
1225/*
2e0de35c
NC
1226=for apidoc savesvpv
1227
6832267f 1228A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
2e0de35c
NC
1229the passed in SV using C<SvPV()>
1230
0358c255
KW
1231On some platforms, Windows for example, all allocated memory owned by a thread
1232is deallocated when that thread ends. So if you need that not to happen, you
1233need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1234
2e0de35c
NC
1235=cut
1236*/
1237
1238char *
1239Perl_savesvpv(pTHX_ SV *sv)
1240{
1241 STRLEN len;
7452cf6a 1242 const char * const pv = SvPV_const(sv, len);
eb578fdb 1243 char *newaddr;
2e0de35c 1244
7918f24d
NC
1245 PERL_ARGS_ASSERT_SAVESVPV;
1246
26866f99 1247 ++len;
a02a5408 1248 Newx(newaddr,len,char);
07409e01 1249 return (char *) CopyD(pv,newaddr,len,char);
2e0de35c 1250}
05ec9bb3 1251
9dcc53ea
Z
1252/*
1253=for apidoc savesharedsvpv
1254
1255A version of C<savesharedpv()> which allocates the duplicate string in
1256memory which is shared between threads.
1257
1258=cut
1259*/
1260
1261char *
1262Perl_savesharedsvpv(pTHX_ SV *sv)
1263{
1264 STRLEN len;
1265 const char * const pv = SvPV_const(sv, len);
1266
1267 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1268
1269 return savesharedpvn(pv, len);
1270}
05ec9bb3 1271
cea2e8a9 1272/* the SV for Perl_form() and mess() is not kept in an arena */
fc36a67e 1273
76e3520e 1274STATIC SV *
cea2e8a9 1275S_mess_alloc(pTHX)
fc36a67e
PP
1276{
1277 SV *sv;
1278 XPVMG *any;
1279
627364f1 1280 if (PL_phase != PERL_PHASE_DESTRUCT)
84bafc02 1281 return newSVpvs_flags("", SVs_TEMP);
e72dc28c 1282
0372dbb6
GS
1283 if (PL_mess_sv)
1284 return PL_mess_sv;
1285
fc36a67e 1286 /* Create as PVMG now, to avoid any upgrading later */
a02a5408
JC
1287 Newx(sv, 1, SV);
1288 Newxz(any, 1, XPVMG);
fc36a67e
PP
1289 SvFLAGS(sv) = SVt_PVMG;
1290 SvANY(sv) = (void*)any;
6136c704 1291 SvPV_set(sv, NULL);
fc36a67e 1292 SvREFCNT(sv) = 1 << 30; /* practically infinite */
e72dc28c 1293 PL_mess_sv = sv;
fc36a67e
PP
1294 return sv;
1295}
1296
c5be433b 1297#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1298char *
1299Perl_form_nocontext(const char* pat, ...)
1300{
1301 dTHX;
c5be433b 1302 char *retval;
cea2e8a9 1303 va_list args;
7918f24d 1304 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
cea2e8a9 1305 va_start(args, pat);
c5be433b 1306 retval = vform(pat, &args);
cea2e8a9 1307 va_end(args);
c5be433b 1308 return retval;
cea2e8a9 1309}
c5be433b 1310#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9 1311
7c9e965c 1312/*
ccfc67b7 1313=head1 Miscellaneous Functions
7c9e965c
JP
1314=for apidoc form
1315
1316Takes a sprintf-style format pattern and conventional
1317(non-SV) arguments and returns the formatted string.
1318
1319 (char *) Perl_form(pTHX_ const char* pat, ...)
1320
1321can be used any place a string (char *) is required:
1322
1323 char * s = Perl_form("%d.%d",major,minor);
1324
1325Uses a single private buffer so if you want to format several strings you
1326must explicitly copy the earlier strings away (and free the copies when you
1327are done).
1328
1329=cut
1330*/
1331
8990e307 1332char *
864dbfa3 1333Perl_form(pTHX_ const char* pat, ...)
8990e307 1334{
c5be433b 1335 char *retval;
46fc3d4c 1336 va_list args;
7918f24d 1337 PERL_ARGS_ASSERT_FORM;
46fc3d4c 1338 va_start(args, pat);
c5be433b 1339 retval = vform(pat, &args);
46fc3d4c 1340 va_end(args);
c5be433b
GS
1341 return retval;
1342}
1343
1344char *
1345Perl_vform(pTHX_ const char *pat, va_list *args)
1346{
2d03de9c 1347 SV * const sv = mess_alloc();
7918f24d 1348 PERL_ARGS_ASSERT_VFORM;
4608196e 1349 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
e72dc28c 1350 return SvPVX(sv);
46fc3d4c 1351}
a687059c 1352
c5df3096 1353/*
44170c9a 1354=for apidoc mess
c5df3096
Z
1355
1356Take a sprintf-style format pattern and argument list. These are used to
1357generate a string message. If the message does not end with a newline,
1358then it will be extended with some indication of the current location
1359in the code, as described for L</mess_sv>.
1360
1361Normally, the resulting message is returned in a new mortal SV.
1362During global destruction a single SV may be shared between uses of
1363this function.
1364
1365=cut
1366*/
1367
5a844595
GS
1368#if defined(PERL_IMPLICIT_CONTEXT)
1369SV *
1370Perl_mess_nocontext(const char *pat, ...)
1371{
1372 dTHX;
1373 SV *retval;
1374 va_list args;
7918f24d 1375 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
5a844595
GS
1376 va_start(args, pat);
1377 retval = vmess(pat, &args);
1378 va_end(args);
1379 return retval;
1380}
1381#endif /* PERL_IMPLICIT_CONTEXT */
1382
06bf62c7 1383SV *
5a844595
GS
1384Perl_mess(pTHX_ const char *pat, ...)
1385{
1386 SV *retval;
1387 va_list args;
7918f24d 1388 PERL_ARGS_ASSERT_MESS;
5a844595
GS
1389 va_start(args, pat);
1390 retval = vmess(pat, &args);
1391 va_end(args);
1392 return retval;
1393}
1394
25502127
FC
1395const COP*
1396Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1397 bool opnext)
ae7d165c 1398{
25502127
FC
1399 /* Look for curop starting from o. cop is the last COP we've seen. */
1400 /* opnext means that curop is actually the ->op_next of the op we are
1401 seeking. */
ae7d165c 1402
7918f24d
NC
1403 PERL_ARGS_ASSERT_CLOSEST_COP;
1404
25502127
FC
1405 if (!o || !curop || (
1406 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1407 ))
fabdb6c0 1408 return cop;
ae7d165c
PJ
1409
1410 if (o->op_flags & OPf_KIDS) {
5f66b61c 1411 const OP *kid;
e6dae479 1412 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
5f66b61c 1413 const COP *new_cop;
ae7d165c
PJ
1414
1415 /* If the OP_NEXTSTATE has been optimised away we can still use it
1416 * the get the file and line number. */
1417
1418 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
5f66b61c 1419 cop = (const COP *)kid;
ae7d165c
PJ
1420
1421 /* Keep searching, and return when we've found something. */
1422
25502127 1423 new_cop = closest_cop(cop, kid, curop, opnext);
fabdb6c0
AL
1424 if (new_cop)
1425 return new_cop;
ae7d165c
PJ
1426 }
1427 }
1428
1429 /* Nothing found. */
1430
5f66b61c 1431 return NULL;
ae7d165c
PJ
1432}
1433
c5df3096 1434/*
44170c9a 1435=for apidoc mess_sv
c5df3096
Z
1436
1437Expands a message, intended for the user, to include an indication of
1438the current location in the code, if the message does not already appear
1439to be complete.
1440
1441C<basemsg> is the initial message or object. If it is a reference, it
1442will be used as-is and will be the result of this function. Otherwise it
1443is used as a string, and if it already ends with a newline, it is taken
1444to be complete, and the result of this function will be the same string.
1445If the message does not end with a newline, then a segment such as C<at
1446foo.pl line 37> will be appended, and possibly other clauses indicating
1447the current state of execution. The resulting message will end with a
1448dot and a newline.
1449
1450Normally, the resulting message is returned in a new mortal SV.
1451During global destruction a single SV may be shared between uses of this
1452function. If C<consume> is true, then the function is permitted (but not
1453required) to modify and return C<basemsg> instead of allocating a new SV.
1454
1455=cut
1456*/
1457
5a844595 1458SV *
c5df3096 1459Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
46fc3d4c 1460{
c5df3096 1461 SV *sv;
46fc3d4c 1462
0762e42f 1463#if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
470dd224
JH
1464 {
1465 char *ws;
22ff3130 1466 UV wi;
470dd224 1467 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
22ff3130
HS
1468 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR"))
1469 && grok_atoUV(ws, &wi, NULL)
1470 && wi <= PERL_INT_MAX
1471 ) {
1472 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1);
470dd224
JH
1473 }
1474 }
1475#endif
1476
c5df3096
Z
1477 PERL_ARGS_ASSERT_MESS_SV;
1478
1479 if (SvROK(basemsg)) {
1480 if (consume) {
1481 sv = basemsg;
1482 }
1483 else {
1484 sv = mess_alloc();
1485 sv_setsv(sv, basemsg);
1486 }
1487 return sv;
1488 }
1489
1490 if (SvPOK(basemsg) && consume) {
1491 sv = basemsg;
1492 }
1493 else {
1494 sv = mess_alloc();
1495 sv_copypv(sv, basemsg);
1496 }
7918f24d 1497
46fc3d4c 1498 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
ae7d165c
PJ
1499 /*
1500 * Try and find the file and line for PL_op. This will usually be
1501 * PL_curcop, but it might be a cop that has been optimised away. We
1502 * can try to find such a cop by searching through the optree starting
1503 * from the sibling of PL_curcop.
1504 */
1505
f4c61774
DM
1506 if (PL_curcop) {
1507 const COP *cop =
1508 closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
1509 if (!cop)
1510 cop = PL_curcop;
1511
1512 if (CopLINE(cop))
1513 Perl_sv_catpvf(aTHX_ sv, " at %s line %" IVdf,
1514 OutCopFILE(cop), (IV)CopLINE(cop));
1515 }
1516
191f87d5
DH
1517 /* Seems that GvIO() can be untrustworthy during global destruction. */
1518 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1519 && IoLINES(GvIOp(PL_last_in_gv)))
1520 {
2748e602 1521 STRLEN l;
e1ec3a88 1522 const bool line_mode = (RsSIMPLE(PL_rs) &&
2748e602 1523 *SvPV_const(PL_rs,l) == '\n' && l == 1);
147e3846 1524 Perl_sv_catpvf(aTHX_ sv, ", <%" SVf "> %s %" IVdf,
3b46b707
BF
1525 SVfARG(PL_last_in_gv == PL_argvgv
1526 ? &PL_sv_no
1527 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
edc2eac3
JH
1528 line_mode ? "line" : "chunk",
1529 (IV)IoLINES(GvIOp(PL_last_in_gv)));
a687059c 1530 }
627364f1 1531 if (PL_phase == PERL_PHASE_DESTRUCT)
5f66b61c
AL
1532 sv_catpvs(sv, " during global destruction");
1533 sv_catpvs(sv, ".\n");
a687059c 1534 }
06bf62c7 1535 return sv;
a687059c
LW
1536}
1537
c5df3096 1538/*
44170c9a 1539=for apidoc vmess
c5df3096
Z
1540
1541C<pat> and C<args> are a sprintf-style format pattern and encapsulated
801caa78
KW
1542argument list, respectively. These are used to generate a string message. If
1543the
c5df3096
Z
1544message does not end with a newline, then it will be extended with
1545some indication of the current location in the code, as described for
1546L</mess_sv>.
1547
1548Normally, the resulting message is returned in a new mortal SV.
1549During global destruction a single SV may be shared between uses of
1550this function.
1551
1552=cut
1553*/
1554
1555SV *
1556Perl_vmess(pTHX_ const char *pat, va_list *args)
1557{
c5df3096
Z
1558 SV * const sv = mess_alloc();
1559
1560 PERL_ARGS_ASSERT_VMESS;
1561
1562 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1563 return mess_sv(sv, 1);
1564}
1565
7ff03255 1566void
7d0994e0 1567Perl_write_to_stderr(pTHX_ SV* msv)
7ff03255
SG
1568{
1569 IO *io;
1570 MAGIC *mg;
1571
7918f24d
NC
1572 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1573
7ff03255
SG
1574 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1575 && (io = GvIO(PL_stderrgv))
daba3364 1576 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
36925d9e 1577 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
d1d7a15d 1578 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
7ff03255 1579 else {
53c1dcc0 1580 PerlIO * const serr = Perl_error_log;
7ff03255 1581
83c55556 1582 do_print(msv, serr);
7ff03255 1583 (void)PerlIO_flush(serr);
7ff03255
SG
1584 }
1585}
1586
c5df3096
Z
1587/*
1588=head1 Warning and Dieing
1589*/
1590
1591/* Common code used in dieing and warning */
1592
1593STATIC SV *
1594S_with_queued_errors(pTHX_ SV *ex)
1595{
1596 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1597 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1598 sv_catsv(PL_errors, ex);
1599 ex = sv_mortalcopy(PL_errors);
1600 SvCUR_set(PL_errors, 0);
1601 }
1602 return ex;
1603}
3ab1ac99 1604
46d9c920 1605STATIC bool
c5df3096 1606S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
63315e18
NC
1607{
1608 HV *stash;
1609 GV *gv;
1610 CV *cv;
46d9c920
NC
1611 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1612 /* sv_2cv might call Perl_croak() or Perl_warner() */
1613 SV * const oldhook = *hook;
1614
2460a496 1615 if (!oldhook || oldhook == PERL_WARNHOOK_FATAL)
c5df3096 1616 return FALSE;
63315e18 1617
63315e18 1618 ENTER;
46d9c920
NC
1619 SAVESPTR(*hook);
1620 *hook = NULL;
1621 cv = sv_2cv(oldhook, &stash, &gv, 0);
63315e18
NC
1622 LEAVE;
1623 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1624 dSP;
c5df3096 1625 SV *exarg;
63315e18
NC
1626
1627 ENTER;
2782061f 1628 save_re_context();
46d9c920
NC
1629 if (warn) {
1630 SAVESPTR(*hook);
1631 *hook = NULL;
1632 }
c5df3096
Z
1633 exarg = newSVsv(ex);
1634 SvREADONLY_on(exarg);
1635 SAVEFREESV(exarg);
63315e18 1636
46d9c920 1637 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
63315e18 1638 PUSHMARK(SP);
c5df3096 1639 XPUSHs(exarg);
63315e18 1640 PUTBACK;
daba3364 1641 call_sv(MUTABLE_SV(cv), G_DISCARD);
63315e18
NC
1642 POPSTACK;
1643 LEAVE;
46d9c920 1644 return TRUE;
63315e18 1645 }
46d9c920 1646 return FALSE;
63315e18
NC
1647}
1648
c5df3096 1649/*
44170c9a 1650=for apidoc die_sv
e07360fa 1651
c5df3096
Z
1652Behaves the same as L</croak_sv>, except for the return type.
1653It should be used only where the C<OP *> return type is required.
1654The function never actually returns.
e07360fa 1655
c5df3096
Z
1656=cut
1657*/
e07360fa 1658
6879a07b
TK
1659/* silence __declspec(noreturn) warnings */
1660MSVC_DIAG_IGNORE(4646 4645)
c5df3096
Z
1661OP *
1662Perl_die_sv(pTHX_ SV *baseex)
36477c24 1663{
c5df3096
Z
1664 PERL_ARGS_ASSERT_DIE_SV;
1665 croak_sv(baseex);
e5964223 1666 /* NOTREACHED */
117af67d 1667 NORETURN_FUNCTION_END;
36477c24 1668}
6879a07b 1669MSVC_DIAG_RESTORE
36477c24 1670
c5df3096 1671/*
44170c9a 1672=for apidoc die
c5df3096
Z
1673
1674Behaves the same as L</croak>, except for the return type.
1675It should be used only where the C<OP *> return type is required.
1676The function never actually returns.
1677
1678=cut
1679*/
1680
c5be433b 1681#if defined(PERL_IMPLICIT_CONTEXT)
6879a07b
TK
1682
1683/* silence __declspec(noreturn) warnings */
1684MSVC_DIAG_IGNORE(4646 4645)
cea2e8a9
GS
1685OP *
1686Perl_die_nocontext(const char* pat, ...)
a687059c 1687{
cea2e8a9 1688 dTHX;
a687059c 1689 va_list args;
cea2e8a9 1690 va_start(args, pat);
c5df3096 1691 vcroak(pat, &args);
e5964223 1692 NOT_REACHED; /* NOTREACHED */
cea2e8a9 1693 va_end(args);
117af67d 1694 NORETURN_FUNCTION_END;
cea2e8a9 1695}
6879a07b
TK
1696MSVC_DIAG_RESTORE
1697
c5be433b 1698#endif /* PERL_IMPLICIT_CONTEXT */
cea2e8a9 1699
6879a07b
TK
1700/* silence __declspec(noreturn) warnings */
1701MSVC_DIAG_IGNORE(4646 4645)
cea2e8a9
GS
1702OP *
1703Perl_die(pTHX_ const char* pat, ...)
1704{
cea2e8a9
GS
1705 va_list args;
1706 va_start(args, pat);
c5df3096 1707 vcroak(pat, &args);
e5964223 1708 NOT_REACHED; /* NOTREACHED */
cea2e8a9 1709 va_end(args);
117af67d 1710 NORETURN_FUNCTION_END;
cea2e8a9 1711}
6879a07b 1712MSVC_DIAG_RESTORE
cea2e8a9 1713
c5df3096 1714/*
44170c9a 1715=for apidoc croak_sv
c5df3096
Z
1716
1717This is an XS interface to Perl's C<die> function.
1718
1719C<baseex> is the error message or object. If it is a reference, it
1720will be used as-is. Otherwise it is used as a string, and if it does
1721not end with a newline then it will be extended with some indication of
1722the current location in the code, as described for L</mess_sv>.
1723
1724The error message or object will be used as an exception, by default
1725returning control to the nearest enclosing C<eval>, but subject to
1726modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1727function never returns normally.
1728
1729To die with a simple string message, the L</croak> function may be
1730more convenient.
1731
1732=cut
1733*/
1734
c5be433b 1735void
c5df3096 1736Perl_croak_sv(pTHX_ SV *baseex)
cea2e8a9 1737{
c5df3096
Z
1738 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1739 PERL_ARGS_ASSERT_CROAK_SV;
1740 invoke_exception_hook(ex, FALSE);
1741 die_unwind(ex);
1742}
1743
1744/*
44170c9a 1745=for apidoc vcroak
c5df3096
Z
1746
1747This is an XS interface to Perl's C<die> function.
1748
1749C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1750argument list. These are used to generate a string message. If the
1751message does not end with a newline, then it will be extended with
1752some indication of the current location in the code, as described for
1753L</mess_sv>.
1754
1755The error message will be used as an exception, by default
1756returning control to the nearest enclosing C<eval>, but subject to
1757modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1758function never returns normally.
a687059c 1759
c5df3096
Z
1760For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1761(C<$@>) will be used as an error message or object instead of building an
1762error message from arguments. If you want to throw a non-string object,
1763or build an error message in an SV yourself, it is preferable to use
1764the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
5a844595 1765
c5df3096
Z
1766=cut
1767*/
1768
1769void
1770Perl_vcroak(pTHX_ const char* pat, va_list *args)
1771{
1772 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1773 invoke_exception_hook(ex, FALSE);
1774 die_unwind(ex);
a687059c
LW
1775}
1776
c5df3096 1777/*
44170c9a 1778=for apidoc croak
c5df3096
Z
1779
1780This is an XS interface to Perl's C<die> function.
1781
1782Take a sprintf-style format pattern and argument list. These are used to
1783generate a string message. If the message does not end with a newline,
1784then it will be extended with some indication of the current location
1785in the code, as described for L</mess_sv>.
1786
1787The error message will be used as an exception, by default
1788returning control to the nearest enclosing C<eval>, but subject to
1789modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1790function never returns normally.
1791
1792For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1793(C<$@>) will be used as an error message or object instead of building an
1794error message from arguments. If you want to throw a non-string object,
1795or build an error message in an SV yourself, it is preferable to use
1796the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1797
1798=cut
1799*/
1800
c5be433b 1801#if defined(PERL_IMPLICIT_CONTEXT)
8990e307 1802void
cea2e8a9 1803Perl_croak_nocontext(const char *pat, ...)
a687059c 1804{
cea2e8a9 1805 dTHX;
a687059c 1806 va_list args;
cea2e8a9 1807 va_start(args, pat);
c5be433b 1808 vcroak(pat, &args);
e5964223 1809 NOT_REACHED; /* NOTREACHED */
cea2e8a9
GS
1810 va_end(args);
1811}
1812#endif /* PERL_IMPLICIT_CONTEXT */
1813
d68c938a
KW
1814/* saves machine code for a common noreturn idiom typically used in Newx*() */
1815GCC_DIAG_IGNORE_DECL(-Wunused-function);
1816void
1817Perl_croak_memory_wrap(void)
1818{
1819 Perl_croak_nocontext("%s",PL_memory_wrap);
1820}
1821GCC_DIAG_RESTORE_DECL;
1822
c5df3096
Z
1823void
1824Perl_croak(pTHX_ const char *pat, ...)
1825{
1826 va_list args;
1827 va_start(args, pat);
1828 vcroak(pat, &args);
e5964223 1829 NOT_REACHED; /* NOTREACHED */
c5df3096
Z
1830 va_end(args);
1831}
1832
954c1994 1833/*
44170c9a 1834=for apidoc croak_no_modify
6ad8f254
NC
1835
1836Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
72d33970 1837terser object code than using C<Perl_croak>. Less code used on exception code
6ad8f254
NC
1838paths reduces CPU cache pressure.
1839
d8e47b5c 1840=cut
6ad8f254
NC
1841*/
1842
1843void
88772978 1844Perl_croak_no_modify(void)
6ad8f254 1845{
cb077ed2 1846 Perl_croak_nocontext( "%s", PL_no_modify);
6ad8f254
NC
1847}
1848
4cbe3a7d
DD
1849/* does not return, used in util.c perlio.c and win32.c
1850 This is typically called when malloc returns NULL.
1851*/
1852void
88772978 1853Perl_croak_no_mem(void)
4cbe3a7d
DD
1854{
1855 dTHX;
77c1c05b 1856
375ed12a
JH
1857 int fd = PerlIO_fileno(Perl_error_log);
1858 if (fd < 0)
1859 SETERRNO(EBADF,RMS_IFI);
1860 else {
1861 /* Can't use PerlIO to write as it allocates memory */
b469f1e0 1862 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
375ed12a 1863 }
4cbe3a7d
DD
1864 my_exit(1);
1865}
1866
3d04513d
DD
1867/* does not return, used only in POPSTACK */
1868void
1869Perl_croak_popstack(void)
1870{
1871 dTHX;
1872 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1873 my_exit(1);
1874}
1875
6ad8f254 1876/*
44170c9a 1877=for apidoc warn_sv
ccfc67b7 1878
c5df3096 1879This is an XS interface to Perl's C<warn> function.
954c1994 1880
c5df3096
Z
1881C<baseex> is the error message or object. If it is a reference, it
1882will be used as-is. Otherwise it is used as a string, and if it does
1883not end with a newline then it will be extended with some indication of
1884the current location in the code, as described for L</mess_sv>.
9983fa3c 1885
c5df3096
Z
1886The error message or object will by default be written to standard error,
1887but this is subject to modification by a C<$SIG{__WARN__}> handler.
9983fa3c 1888
c5df3096
Z
1889To warn with a simple string message, the L</warn> function may be
1890more convenient.
954c1994
GS
1891
1892=cut
1893*/
1894
cea2e8a9 1895void
c5df3096 1896Perl_warn_sv(pTHX_ SV *baseex)
cea2e8a9 1897{
c5df3096
Z
1898 SV *ex = mess_sv(baseex, 0);
1899 PERL_ARGS_ASSERT_WARN_SV;
1900 if (!invoke_exception_hook(ex, TRUE))
1901 write_to_stderr(ex);
cea2e8a9
GS
1902}
1903
c5df3096 1904/*
44170c9a 1905=for apidoc vwarn
c5df3096
Z
1906
1907This is an XS interface to Perl's C<warn> function.
1908
1909C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1910argument list. These are used to generate a string message. If the
1911message does not end with a newline, then it will be extended with
1912some indication of the current location in the code, as described for
1913L</mess_sv>.
1914
1915The error message or object will by default be written to standard error,
1916but this is subject to modification by a C<$SIG{__WARN__}> handler.
1917
1918Unlike with L</vcroak>, C<pat> is not permitted to be null.
1919
1920=cut
1921*/
1922
c5be433b
GS
1923void
1924Perl_vwarn(pTHX_ const char* pat, va_list *args)
cea2e8a9 1925{
c5df3096 1926 SV *ex = vmess(pat, args);
7918f24d 1927 PERL_ARGS_ASSERT_VWARN;
c5df3096
Z
1928 if (!invoke_exception_hook(ex, TRUE))
1929 write_to_stderr(ex);
1930}
7918f24d 1931
c5df3096 1932/*
44170c9a 1933=for apidoc warn
87582a92 1934
c5df3096
Z
1935This is an XS interface to Perl's C<warn> function.
1936
1937Take a sprintf-style format pattern and argument list. These are used to
1938generate a string message. If the message does not end with a newline,
1939then it will be extended with some indication of the current location
1940in the code, as described for L</mess_sv>.
1941
1942The error message or object will by default be written to standard error,
1943but this is subject to modification by a C<$SIG{__WARN__}> handler.
1944
1945Unlike with L</croak>, C<pat> is not permitted to be null.
1946
1947=cut
1948*/
8d063cd8 1949
c5be433b 1950#if defined(PERL_IMPLICIT_CONTEXT)
cea2e8a9
GS
1951void
1952Perl_warn_nocontext(const char *pat, ...)
1953{
1954 dTHX;
1955 va_list args;
7918f24d 1956 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
cea2e8a9 1957 va_start(args, pat);
c5be433b 1958 vwarn(pat, &args);
cea2e8a9
GS
1959 va_end(args);
1960}
1961#endif /* PERL_IMPLICIT_CONTEXT */
1962
1963void
1964Perl_warn(pTHX_ const char *pat, ...)
1965{
1966 va_list args;
7918f24d 1967 PERL_ARGS_ASSERT_WARN;
cea2e8a9 1968 va_start(args, pat);
c5be433b 1969 vwarn(pat, &args);
cea2e8a9
GS
1970 va_end(args);
1971}
1972
c5be433b
GS
1973#if defined(PERL_IMPLICIT_CONTEXT)
1974void
1975Perl_warner_nocontext(U32 err, const char *pat, ...)
1976{
27da23d5 1977 dTHX;
c5be433b 1978 va_list args;
7918f24d 1979 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
c5be433b
GS
1980 va_start(args, pat);
1981 vwarner(err, pat, &args);
1982 va_end(args);
1983}
1984#endif /* PERL_IMPLICIT_CONTEXT */
1985
599cee73 1986void
9b387841
NC
1987Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1988{
1989 PERL_ARGS_ASSERT_CK_WARNER_D;
1990
1991 if (Perl_ckwarn_d(aTHX_ err)) {
1992 va_list args;
1993 va_start(args, pat);
1994 vwarner(err, pat, &args);
1995 va_end(args);
1996 }
1997}
1998
1999void
a2a5de95
NC
2000Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
2001{
2002 PERL_ARGS_ASSERT_CK_WARNER;
2003
2004 if (Perl_ckwarn(aTHX_ err)) {
2005 va_list args;
2006 va_start(args, pat);
2007 vwarner(err, pat, &args);
2008 va_end(args);
2009 }
2010}
2011
2012void
864dbfa3 2013Perl_warner(pTHX_ U32 err, const char* pat,...)
599cee73
PM
2014{
2015 va_list args;
7918f24d 2016 PERL_ARGS_ASSERT_WARNER;
c5be433b
GS
2017 va_start(args, pat);
2018 vwarner(err, pat, &args);
2019 va_end(args);
2020}
2021
2022void
2023Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
2024{
7918f24d 2025 PERL_ARGS_ASSERT_VWARNER;
46b27d2f
LM
2026 if (
2027 (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) &&
2028 !(PL_in_eval & EVAL_KEEPERR)
2029 ) {
a3b680e6 2030 SV * const msv = vmess(pat, args);
599cee73 2031
594b6fac
LM
2032 if (PL_parser && PL_parser->error_count) {
2033 qerror(msv);
2034 }
2035 else {
2036 invoke_exception_hook(msv, FALSE);
2037 die_unwind(msv);
2038 }
599cee73
PM
2039 }
2040 else {
d13b0d77 2041 Perl_vwarn(aTHX_ pat, args);
599cee73
PM
2042 }
2043}
2044
f54ba1c2
DM
2045/* implements the ckWARN? macros */
2046
2047bool
2048Perl_ckwarn(pTHX_ U32 w)
2049{
ad287e37 2050 /* If lexical warnings have not been set, use $^W. */
3c3f8cd6
AB
2051 if (isLEXWARN_off)
2052 return PL_dowarn & G_WARN_ON;
ad287e37 2053
26c7b074 2054 return ckwarn_common(w);
f54ba1c2
DM
2055}
2056
2057/* implements the ckWARN?_d macro */
2058
2059bool
2060Perl_ckwarn_d(pTHX_ U32 w)
2061{
ad287e37 2062 /* If lexical warnings have not been set then default classes warn. */
3c3f8cd6
AB
2063 if (isLEXWARN_off)
2064 return TRUE;
ad287e37 2065
26c7b074
NC
2066 return ckwarn_common(w);
2067}
2068
2069static bool
2070S_ckwarn_common(pTHX_ U32 w)
2071{
3c3f8cd6
AB
2072 if (PL_curcop->cop_warnings == pWARN_ALL)
2073 return TRUE;
ad287e37
NC
2074
2075 if (PL_curcop->cop_warnings == pWARN_NONE)
2076 return FALSE;
2077
98fe6610
NC
2078 /* Check the assumption that at least the first slot is non-zero. */
2079 assert(unpackWARN1(w));
2080
2081 /* Check the assumption that it is valid to stop as soon as a zero slot is
2082 seen. */
2083 if (!unpackWARN2(w)) {
2084 assert(!unpackWARN3(w));
2085 assert(!unpackWARN4(w));
2086 } else if (!unpackWARN3(w)) {
2087 assert(!unpackWARN4(w));
2088 }
2089
26c7b074
NC
2090 /* Right, dealt with all the special cases, which are implemented as non-
2091 pointers, so there is a pointer to a real warnings mask. */
98fe6610
NC
2092 do {
2093 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
2094 return TRUE;
2095 } while (w >>= WARNshift);
2096
2097 return FALSE;
f54ba1c2
DM
2098}
2099
72dc9ed5
NC
2100/* Set buffer=NULL to get a new one. */
2101STRLEN *
8ee4cf24 2102Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
72dc9ed5 2103 STRLEN size) {
5af88345
FC
2104 const MEM_SIZE len_wanted =
2105 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
35da51f7 2106 PERL_UNUSED_CONTEXT;
7918f24d 2107 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
72dc9ed5 2108
10edeb5d
JH
2109 buffer = (STRLEN*)
2110 (specialWARN(buffer) ?
2111 PerlMemShared_malloc(len_wanted) :
2112 PerlMemShared_realloc(buffer, len_wanted));
72dc9ed5
NC
2113 buffer[0] = size;
2114 Copy(bits, (buffer + 1), size, char);
5af88345
FC
2115 if (size < WARNsize)
2116 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
72dc9ed5
NC
2117 return buffer;
2118}
f54ba1c2 2119
e6587932
DM
2120/* since we've already done strlen() for both nam and val
2121 * we can use that info to make things faster than
2122 * sprintf(s, "%s=%s", nam, val)
2123 */
2124#define my_setenv_format(s, nam, nlen, val, vlen) \
2125 Copy(nam, s, nlen, char); \
2126 *(s+nlen) = '='; \
2127 Copy(val, s+(nlen+1), vlen, char); \
2128 *(s+(nlen+1+vlen)) = '\0'
2129
adebb90d
DM
2130
2131
c5d12488 2132#ifdef USE_ENVIRON_ARRAY
de5576aa 2133/* NB: VMS' my_setenv() is in vms.c */
34716e2a 2134
3d50648c
DM
2135/* Configure doesn't test for HAS_SETENV yet, so decide based on platform.
2136 * For Solaris, setenv() and unsetenv() were introduced in Solaris 9, so
2137 * testing for HAS UNSETENV is sufficient.
2138 */
822c8b4d 2139# if defined(__CYGWIN__)|| defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN)
3d50648c
DM
2140# define MY_HAS_SETENV
2141# endif
2142
34716e2a
DM
2143/* small wrapper for use by Perl_my_setenv that mallocs, or reallocs if
2144 * 'current' is non-null, with up to three sizes that are added together.
2145 * It handles integer overflow.
2146 */
3d50648c 2147# ifndef MY_HAS_SETENV
34716e2a
DM
2148static char *
2149S_env_alloc(void *current, Size_t l1, Size_t l2, Size_t l3, Size_t size)
2150{
2151 void *p;
2152 Size_t sl, l = l1 + l2;
2153
2154 if (l < l2)
2155 goto panic;
2156 l += l3;
2157 if (l < l3)
2158 goto panic;
2159 sl = l * size;
2160 if (sl < l)
2161 goto panic;
2162
2163 p = current
2164 ? safesysrealloc(current, sl)
2165 : safesysmalloc(sl);
2166 if (p)
2167 return (char*)p;
2168
2169 panic:
2170 croak_memory_wrap();
2171}
3d50648c 2172# endif
34716e2a
DM
2173
2174
adebb90d 2175# if !defined(WIN32) && !defined(NETWARE)
34716e2a 2176
df641d45
KW
2177/*
2178=for apidoc my_setenv
2179
2180A wrapper for the C library L<setenv(3)>. Don't use the latter, as the perl
2181version has desirable safeguards
2182
2183=cut
2184*/
2185
8d063cd8 2186void
e1ec3a88 2187Perl_my_setenv(pTHX_ const char *nam, const char *val)
8d063cd8 2188{
adebb90d 2189# ifdef __amigaos4__
6e3136a6 2190 amigaos4_obtain_environ(__FUNCTION__);
adebb90d
DM
2191# endif
2192
2193# ifdef USE_ITHREADS
24f3e849
KW
2194 /* only parent thread can modify process environment, so no need to use a
2195 * mutex */
4efc5df6 2196 if (PL_curinterp == aTHX)
adebb90d 2197# endif
4efc5df6 2198 {
adebb90d
DM
2199
2200# ifndef PERL_USE_SAFE_PUTENV
50acdf95 2201 if (!PL_use_safe_putenv) {
b7d87861 2202 /* most putenv()s leak, so we manipulate environ directly */
34716e2a
DM
2203 UV i;
2204 Size_t vlen, nlen = strlen(nam);
b7d87861
JH
2205
2206 /* where does it go? */
2207 for (i = 0; environ[i]; i++) {
34716e2a 2208 if (strnEQ(environ[i], nam, nlen) && environ[i][nlen] == '=')
b7d87861
JH
2209 break;
2210 }
c5d12488 2211
b7d87861 2212 if (environ == PL_origenviron) { /* need we copy environment? */
34716e2a 2213 UV j, max;
b7d87861
JH
2214 char **tmpenv;
2215
2216 max = i;
2217 while (environ[max])
2218 max++;
adebb90d 2219
34716e2a
DM
2220 /* XXX shouldn't that be max+1 rather than max+2 ??? - DAPM */
2221 tmpenv = (char**)S_env_alloc(NULL, max, 2, 0, sizeof(char*));
adebb90d 2222
b7d87861 2223 for (j=0; j<max; j++) { /* copy environment */
34716e2a
DM
2224 const Size_t len = strlen(environ[j]);
2225 tmpenv[j] = S_env_alloc(NULL, len, 1, 0, 1);
b7d87861
JH
2226 Copy(environ[j], tmpenv[j], len+1, char);
2227 }
adebb90d 2228
b7d87861
JH
2229 tmpenv[max] = NULL;
2230 environ = tmpenv; /* tell exec where it is now */
2231 }
adebb90d 2232
b7d87861
JH
2233 if (!val) {
2234 safesysfree(environ[i]);
2235 while (environ[i]) {
2236 environ[i] = environ[i+1];
2237 i++;
2238 }
adebb90d 2239# ifdef __amigaos4__
6e3136a6 2240 goto my_setenv_out;
adebb90d 2241# else
b7d87861 2242 return;
adebb90d 2243# endif
b7d87861 2244 }
adebb90d 2245
b7d87861 2246 if (!environ[i]) { /* does not exist yet */
34716e2a 2247 environ = (char**)S_env_alloc(environ, i, 2, 0, sizeof(char*));
b7d87861
JH
2248 environ[i+1] = NULL; /* make sure it's null terminated */
2249 }
2250 else
2251 safesysfree(environ[i]);
34716e2a 2252
b7d87861
JH
2253 vlen = strlen(val);
2254
34716e2a 2255 environ[i] = S_env_alloc(NULL, nlen, vlen, 2, 1);
b7d87861
JH
2256 /* all that work just for this */
2257 my_setenv_format(environ[i], nam, nlen, val, vlen);
adebb90d
DM
2258 }
2259 else {
2260
2261# endif /* !PERL_USE_SAFE_PUTENV */
2262
3d50648c 2263# ifdef MY_HAS_SETENV
adebb90d 2264# if defined(HAS_UNSETENV)
88f5bc07
AB
2265 if (val == NULL) {
2266 (void)unsetenv(nam);
2267 } else {
2268 (void)setenv(nam, val, 1);
2269 }
adebb90d 2270# else /* ! HAS_UNSETENV */
88f5bc07 2271 (void)setenv(nam, val, 1);
adebb90d
DM
2272# endif /* HAS_UNSETENV */
2273
2274# elif defined(HAS_UNSETENV)
2275
88f5bc07 2276 if (val == NULL) {
ba88ff58
MJ
2277 if (environ) /* old glibc can crash with null environ */
2278 (void)unsetenv(nam);
88f5bc07 2279 } else {
34716e2a
DM
2280 const Size_t nlen = strlen(nam);
2281 const Size_t vlen = strlen(val);
2282 char * const new_env = S_env_alloc(NULL, nlen, vlen, 2, 1);
88f5bc07
AB
2283 my_setenv_format(new_env, nam, nlen, val, vlen);
2284 (void)putenv(new_env);
2285 }
adebb90d
DM
2286
2287# else /* ! HAS_UNSETENV */
2288
88f5bc07 2289 char *new_env;
34716e2a
DM
2290 const Size_t nlen = strlen(nam);
2291 Size_t vlen;
88f5bc07
AB
2292 if (!val) {
2293 val = "";
2294 }
2295 vlen = strlen(val);
34716e2a 2296 new_env = S_env_alloc(NULL, nlen, vlen, 2, 1);
88f5bc07
AB
2297 /* all that work just for this */
2298 my_setenv_format(new_env, nam, nlen, val, vlen);
2299 (void)putenv(new_env);
adebb90d 2300
3d50648c 2301# endif /* MY_HAS_SETENV */
adebb90d
DM
2302
2303# ifndef PERL_USE_SAFE_PUTENV
50acdf95 2304 }
adebb90d 2305# endif
4efc5df6 2306 }
adebb90d
DM
2307
2308# ifdef __amigaos4__
6e3136a6
AB
2309my_setenv_out:
2310 amigaos4_release_environ(__FUNCTION__);
adebb90d 2311# endif
8d063cd8
LW
2312}
2313
adebb90d 2314# else /* WIN32 || NETWARE */
68dc0745
PP
2315
2316void
72229eff 2317Perl_my_setenv(pTHX_ const char *nam, const char *val)
68dc0745 2318{
eb578fdb 2319 char *envstr;
34716e2a
DM
2320 const Size_t nlen = strlen(nam);
2321 Size_t vlen;
e6587932 2322
c5d12488
JH
2323 if (!val) {
2324 val = "";
ac5c734f 2325 }
c5d12488 2326 vlen = strlen(val);
34716e2a 2327 envstr = S_env_alloc(NULL, nlen, vlen, 2, 1);
c5d12488
JH
2328 my_setenv_format(envstr, nam, nlen, val, vlen);
2329 (void)PerlEnv_putenv(envstr);
ff69e883 2330 safesysfree(envstr);
3e3baf6d
TB
2331}
2332
adebb90d
DM
2333# endif /* WIN32 || NETWARE */
2334
2335#endif /* USE_ENVIRON_ARRAY */
2336
2337
3e3baf6d 2338
378cc40b 2339
16d20bd9 2340#ifdef UNLINK_ALL_VERSIONS
79072805 2341I32
6e732051 2342Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
378cc40b 2343{
35da51f7 2344 I32 retries = 0;
378cc40b 2345
7918f24d
NC
2346 PERL_ARGS_ASSERT_UNLNK;
2347
35da51f7
AL
2348 while (PerlLIO_unlink(f) >= 0)
2349 retries++;
2350 return retries ? 0 : -1;
378cc40b
LW
2351}
2352#endif
2353
4a7d1889 2354PerlIO *
c9289b7b 2355Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
4a7d1889 2356{
f6fb4e44 2357#if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
1f852d0d 2358 int p[2];
eb578fdb
KW
2359 I32 This, that;
2360 Pid_t pid;
1f852d0d
NIS
2361 SV *sv;
2362 I32 did_pipes = 0;
2363 int pp[2];
2364
7918f24d
NC
2365 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2366
1f852d0d
NIS
2367 PERL_FLUSHALL_FOR_CHILD;
2368 This = (*mode == 'w');
2369 that = !This;
284167a5 2370 if (TAINTING_get) {
1f852d0d
NIS
2371 taint_env();
2372 taint_proper("Insecure %s%s", "EXEC");
2373 }
884fc2d3 2374 if (PerlProc_pipe_cloexec(p) < 0)
4608196e 2375 return NULL;
1f852d0d 2376 /* Try for another pipe pair for error return */
74df577f 2377 if (PerlProc_pipe_cloexec(pp) >= 0)
1f852d0d 2378 did_pipes = 1;
52e18b1f 2379 while ((pid = PerlProc_fork()) < 0) {
1f852d0d
NIS
2380 if (errno != EAGAIN) {
2381 PerlLIO_close(p[This]);
4e6dfe71 2382 PerlLIO_close(p[that]);
1f852d0d
NIS
2383 if (did_pipes) {
2384 PerlLIO_close(pp[0]);
2385 PerlLIO_close(pp[1]);
2386 }
4608196e 2387 return NULL;
1f852d0d 2388 }
a2a5de95 2389 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
1f852d0d
NIS
2390 sleep(5);
2391 }
2392 if (pid == 0) {
2393 /* Child */
1f852d0d
NIS
2394#undef THIS
2395#undef THAT
2396#define THIS that
2397#define THAT This
1f852d0d 2398 /* Close parent's end of error status pipe (if any) */
74df577f 2399 if (did_pipes)
1f852d0d 2400 PerlLIO_close(pp[0]);
1f852d0d
NIS
2401 /* Now dup our end of _the_ pipe to right position */
2402 if (p[THIS] != (*mode == 'r')) {
2403 PerlLIO_dup2(p[THIS], *mode == 'r');
2404 PerlLIO_close(p[THIS]);
4e6dfe71
GS
2405 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2406 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1f852d0d 2407 }
30c869b8
LT
2408 else {
2409 setfd_cloexec_or_inhexec_by_sysfdness(p[THIS]);
4e6dfe71 2410 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
30c869b8 2411 }
1f852d0d
NIS
2412#if !defined(HAS_FCNTL) || !defined(F_SETFD)
2413 /* No automatic close - do it by hand */
b7953727
JH
2414# ifndef NOFILE
2415# define NOFILE 20
2416# endif
a080fe3d
NIS
2417 {
2418 int fd;
2419
2420 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
3aed30dc 2421 if (fd != pp[1])
a080fe3d
NIS
2422 PerlLIO_close(fd);
2423 }
1f852d0d
NIS
2424 }
2425#endif
a0714e2c 2426 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
1f852d0d
NIS
2427 PerlProc__exit(1);
2428#undef THIS
2429#undef THAT
2430 }
2431 /* Parent */
1f852d0d
NIS
2432 if (did_pipes)
2433 PerlLIO_close(pp[1]);
2434 /* Keep the lower of the two fd numbers */
2435 if (p[that] < p[This]) {
884fc2d3 2436 PerlLIO_dup2_cloexec(p[This], p[that]);
1f852d0d
NIS
2437 PerlLIO_close(p[This]);
2438 p[This] = p[that];
2439 }
4e6dfe71
GS
2440 else
2441 PerlLIO_close(p[that]); /* close child's end of pipe */
2442
1f852d0d 2443 sv = *av_fetch(PL_fdpid,p[This],TRUE);
862a34c6 2444 SvUPGRADE(sv,SVt_IV);
45977657 2445 SvIV_set(sv, pid);
1f852d0d
NIS
2446 PL_forkprocess = pid;
2447 /* If we managed to get status pipe check for exec fail */
2448 if (did_pipes && pid > 0) {
2449 int errkid;
35bc1e35 2450 unsigned read_total = 0;
1f852d0d 2451
35bc1e35 2452 while (read_total < sizeof(int)) {
19742f39 2453 const SSize_t n1 = PerlLIO_read(pp[0],
35bc1e35
JK
2454 (void*)(((char*)&errkid)+read_total),
2455 (sizeof(int)) - read_total);
1f852d0d
NIS
2456 if (n1 <= 0)
2457 break;
35bc1e35 2458 read_total += n1;
1f852d0d
NIS
2459 }
2460 PerlLIO_close(pp[0]);
2461 did_pipes = 0;
35bc1e35 2462 if (read_total) { /* Error */
1f852d0d 2463 int pid2, status;
8c51524e 2464 PerlLIO_close(p[This]);
35bc1e35
JK
2465 if (read_total != sizeof(int))
2466 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", read_total);
1f852d0d
NIS
2467 do {
2468 pid2 = wait4pid(pid, &status, 0);
2469 } while (pid2 == -1 && errno == EINTR);
2470 errno = errkid; /* Propagate errno from kid */
4608196e 2471 return NULL;
1f852d0d
NIS
2472 }
2473 }
2474 if (did_pipes)
2475 PerlLIO_close(pp[0]);
2476 return PerlIO_fdopen(p[This], mode);
2477#else
8492b23f 2478# if defined(OS2) /* Same, without fork()ing and all extra overhead... */
4e205ed6 2479 return my_syspopen4(aTHX_ NULL, mode, n, args);
8492b23f
TC
2480# elif defined(WIN32)
2481 return win32_popenlist(mode, n, args);
9d419b5f 2482# else
4a7d1889
NIS
2483 Perl_croak(aTHX_ "List form of piped open not implemented");
2484 return (PerlIO *) NULL;
9d419b5f 2485# endif
1f852d0d 2486#endif
4a7d1889
NIS
2487}
2488
4dd5370d
AB
2489 /* VMS' my_popen() is in VMS.c, same with OS/2 and AmigaOS 4. */
2490#if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
760ac839 2491PerlIO *
3dd43144 2492Perl_my_popen(pTHX_ const char *cmd, const char *mode)
a687059c
LW
2493{
2494 int p[2];
eb578fdb
KW
2495 I32 This, that;
2496 Pid_t pid;
79072805 2497 SV *sv;
bfce84ec 2498 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
e446cec8
IZ
2499 I32 did_pipes = 0;
2500 int pp[2];
a687059c 2501
7918f24d
NC
2502 PERL_ARGS_ASSERT_MY_POPEN;
2503
45bc9206 2504 PERL_FLUSHALL_FOR_CHILD;
ddcf38b7
IZ
2505#ifdef OS2
2506 if (doexec) {
23da6c43 2507 return my_syspopen(aTHX_ cmd,mode);
ddcf38b7 2508 }
a1d180c4 2509#endif
8ac85365
NIS
2510 This = (*mode == 'w');
2511 that = !This;
284167a5 2512 if (doexec && TAINTING_get) {
bbce6d69
PP
2513 taint_env();
2514 taint_proper("Insecure %s%s", "EXEC");
d48672a2 2515 }
884fc2d3 2516 if (PerlProc_pipe_cloexec(p) < 0)
4608196e 2517 return NULL;
74df577f 2518 if (doexec && PerlProc_pipe_cloexec(pp) >= 0)
e446cec8 2519 did_pipes = 1;
52e18b1f 2520 while ((pid = PerlProc_fork()) < 0) {
a687059c 2521 if (errno != EAGAIN) {
6ad3d225 2522 PerlLIO_close(p[This]);
b5ac89c3 2523 PerlLIO_close(p[that]);
e446cec8
IZ
2524 if (did_pipes) {
2525 PerlLIO_close(pp[0]);
2526 PerlLIO_close(pp[1]);
2527 }
a687059c 2528 if (!doexec)
b3647a36 2529 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
4608196e 2530 return NULL;
a687059c 2531 }
a2a5de95 2532 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
a687059c
LW
2533 sleep(5);
2534 }
2535 if (pid == 0) {
79072805 2536
30ac6d9b
GS
2537#undef THIS
2538#undef THAT
a687059c 2539#define THIS that
8ac85365 2540#define THAT This
74df577f 2541 if (did_pipes)
e446cec8 2542 PerlLIO_close(pp[0]);
a687059c 2543 if (p[THIS] != (*mode == 'r')) {
6ad3d225
GS
2544 PerlLIO_dup2(p[THIS], *mode == 'r');
2545 PerlLIO_close(p[THIS]);
b5ac89c3
NIS
2546 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2547 PerlLIO_close(p[THAT]);
a687059c 2548 }
c6fe5b98
LT
2549 else {
2550 setfd_cloexec_or_inhexec_by_sysfdness(p[THIS]);
b5ac89c3 2551 PerlLIO_close(p[THAT]);
c6fe5b98 2552 }
4435c477 2553#ifndef OS2
a687059c 2554 if (doexec) {
a0d0e21e 2555#if !defined(HAS_FCNTL) || !defined(F_SETFD)
ae986130
LW
2556#ifndef NOFILE
2557#define NOFILE 20
2558#endif
a080fe3d 2559 {
3aed30dc 2560 int fd;
a080fe3d
NIS
2561
2562 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2563 if (fd != pp[1])
3aed30dc 2564 PerlLIO_close(fd);
a080fe3d 2565 }
ae986130 2566#endif
a080fe3d
NIS
2567 /* may or may not use the shell */
2568 do_exec3(cmd, pp[1], did_pipes);
6ad3d225 2569 PerlProc__exit(1);
a687059c 2570 }
4435c477 2571#endif /* defined OS2 */
713cef20
IZ
2572
2573#ifdef PERLIO_USING_CRLF
2574 /* Since we circumvent IO layers when we manipulate low-level
2575 filedescriptors directly, need to manually switch to the
2576 default, binary, low-level mode; see PerlIOBuf_open(). */
2577 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2578#endif
3280af22 2579 PL_forkprocess = 0;
ca0c25f6 2580#ifdef PERL_USES_PL_PIDSTATUS
3280af22 2581 hv_clear(PL_pidstatus); /* we have no children */
ca0c25f6 2582#endif
4608196e 2583 return NULL;
a687059c
LW
2584#undef THIS
2585#undef THAT
2586 }
e446cec8
IZ
2587 if (did_pipes)
2588 PerlLIO_close(pp[1]);
8ac85365 2589 if (p[that] < p[This]) {
884fc2d3 2590 PerlLIO_dup2_cloexec(p[This], p[that]);
6ad3d225 2591 PerlLIO_close(p[This]);
8ac85365 2592 p[This] = p[that];
62b28dd9 2593 }
b5ac89c3
NIS
2594 else
2595 PerlLIO_close(p[that]);
2596
3280af22 2597 sv = *av_fetch(PL_fdpid,p[This],TRUE);
862a34c6 2598 SvUPGRADE(sv,SVt_IV);
45977657 2599 SvIV_set(sv, pid);
3280af22 2600 PL_forkprocess = pid;
e446cec8
IZ
2601 if (did_pipes && pid > 0) {
2602 int errkid;
bb7a0f54 2603 unsigned n = 0;
e446cec8
IZ
2604
2605 while (n < sizeof(int)) {
19742f39 2606 const SSize_t n1 = PerlLIO_read(pp[0],
e446cec8
IZ
2607 (void*)(((char*)&errkid)+n),
2608 (sizeof(int)) - n);
2609 if (n1 <= 0)
2610 break;
2611 n += n1;
2612 }
2f96c702
IZ
2613 PerlLIO_close(pp[0]);
2614 did_pipes = 0;
e446cec8 2615 if (n) { /* Error */
faa466a7 2616 int pid2, status;
8c51524e 2617 PerlLIO_close(p[This]);
e446cec8 2618 if (n != sizeof(int))
5637ef5b 2619 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
faa466a7
RG
2620 do {
2621 pid2 = wait4pid(pid, &status, 0);
2622 } while (pid2 == -1 && errno == EINTR);
e446cec8 2623 errno = errkid; /* Propagate errno from kid */
4608196e 2624 return NULL;
e446cec8
IZ
2625 }
2626 }
2627 if (did_pipes)
2628 PerlLIO_close(pp[0]);
8ac85365 2629 return PerlIO_fdopen(p[This], mode);
a687059c 2630}
8ad758c7 2631#elif defined(DJGPP)
2b96b0a5
JH
2632FILE *djgpp_popen();
2633PerlIO *
cef6ea9d 2634Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2b96b0a5
JH
2635{
2636 PERL_FLUSHALL_FOR_CHILD;
2637 /* Call system's popen() to get a FILE *, then import it.
2638 used 0 for 2nd parameter to PerlIO_importFILE;
2639 apparently not used
2640 */
2641 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2642}
8ad758c7 2643#elif defined(__LIBCATAMOUNT__)
9c12f1e5
RGS
2644PerlIO *
2645Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2646{
2647 return NULL;
2648}
7c0587c8
LW
2649
2650#endif /* !DOSISH */
a687059c 2651
52e18b1f
GS
2652/* this is called in parent before the fork() */
2653void
2654Perl_atfork_lock(void)
80b94025
JH
2655#if defined(USE_ITHREADS)
2656# ifdef USE_PERLIO
2657 PERL_TSA_ACQUIRE(PL_perlio_mutex)
2658# endif
2659# ifdef MYMALLOC
2660 PERL_TSA_ACQUIRE(PL_malloc_mutex)
2661# endif
2662 PERL_TSA_ACQUIRE(PL_op_mutex)
2663#endif
52e18b1f 2664{
3db8f154 2665#if defined(USE_ITHREADS)
52e18b1f 2666 /* locks must be held in locking order (if any) */
4da80956
P
2667# ifdef USE_PERLIO
2668 MUTEX_LOCK(&PL_perlio_mutex);
2669# endif
52e18b1f
GS
2670# ifdef MYMALLOC
2671 MUTEX_LOCK(&PL_malloc_mutex);
2672# endif
2673 OP_REFCNT_LOCK;
2674#endif
2675}
2676
2677/* this is called in both parent and child after the fork() */
2678void
2679Perl_atfork_unlock(void)
80b94025
JH
2680#if defined(USE_ITHREADS)
2681# ifdef USE_PERLIO
2682 PERL_TSA_RELEASE(PL_perlio_mutex)
2683# endif
2684# ifdef MYMALLOC
2685 PERL_TSA_RELEASE(PL_malloc_mutex)
2686# endif
2687 PERL_TSA_RELEASE(PL_op_mutex)
2688#endif
52e18b1f 2689{
3db8f154 2690#if defined(USE_ITHREADS)
52e18b1f 2691 /* locks must be released in same order as in atfork_lock() */
4da80956
P
2692# ifdef USE_PERLIO
2693 MUTEX_UNLOCK(&PL_perlio_mutex);
2694# endif
52e18b1f
GS
2695# ifdef MYMALLOC
2696 MUTEX_UNLOCK(&PL_malloc_mutex);
2697# endif
2698 OP_REFCNT_UNLOCK;
2699#endif
2700}
2701
2702Pid_t
2703Perl_my_fork(void)
2704{
2705#if defined(HAS_FORK)
2706 Pid_t pid;
3db8f154 2707#if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
52e18b1f
GS
2708 atfork_lock();
2709 pid = fork();
2710 atfork_unlock();
2711#else
2712 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2713 * handlers elsewhere in the code */
2714 pid = fork();
2715#endif
2716 return pid;
40262ff4
AB
2717#elif defined(__amigaos4__)
2718 return amigaos_fork();
52e18b1f
GS
2719#else
2720 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2721 Perl_croak_nocontext("fork() not available");
b961a566 2722 return 0;
52e18b1f
GS
2723#endif /* HAS_FORK */
2724}
2725
fe14fcc3 2726#ifndef HAS_DUP2
fec02dd3 2727int
ba106d47 2728dup2(int oldfd, int newfd)
a687059c 2729{
a0d0e21e 2730#if defined(HAS_FCNTL) && defined(F_DUPFD)
fec02dd3
AD
2731 if (oldfd == newfd)
2732 return oldfd;
6ad3d225 2733 PerlLIO_close(newfd);
fec02dd3 2734 return fcntl(oldfd, F_DUPFD, newfd);
62b28dd9 2735#else
fc36a67e
PP
2736#define DUP2_MAX_FDS 256
2737 int fdtmp[DUP2_MAX_FDS];
79072805 2738 I32 fdx = 0;
ae986130
LW
2739 int fd;
2740
fe14fcc3 2741 if (oldfd == newfd)
fec02dd3 2742 return oldfd;
6ad3d225 2743 PerlLIO_close(newfd);
fc36a67e 2744 /* good enough for low fd's... */
6ad3d225 2745 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
fc36a67e 2746 if (fdx >= DUP2_MAX_FDS) {
6ad3d225 2747 PerlLIO_close(fd);
fc36a67e
PP
2748 fd = -1;
2749 break;
2750 }
ae986130 2751 fdtmp[fdx++] = fd;
fc36a67e 2752 }
ae986130 2753 while (fdx > 0)
6ad3d225 2754 PerlLIO_close(fdtmp[--fdx]);
fec02dd3 2755 return fd;
62b28dd9 2756#endif
a687059c
LW
2757}
2758#endif
2759
64ca3a65 2760#ifndef PERL_MICRO
ff68c719
PP
2761#ifdef HAS_SIGACTION
2762
962fce0f
KW
2763/*
2764=for apidoc rsignal
2765
2766A wrapper for the C library L<signal(2)>. Don't use the latter, as the Perl
2767version knows things that interact with the rest of the perl interpreter.
2768
2769=cut
2770*/
2771
ff68c719 2772Sighandler_t
864dbfa3 2773Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719
PP
2774{
2775 struct sigaction act, oact;
2776
a10b1e10
JH
2777#ifdef USE_ITHREADS
2778 /* only "parent" interpreter can diddle signals */
2779 if (PL_curinterp != aTHX)
8aad04aa 2780 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2781#endif
2782
8d61efc5 2783 act.sa_handler = handler;
ff68c719
PP
2784 sigemptyset(&act.sa_mask);
2785 act.sa_flags = 0;
2786#ifdef SA_RESTART
4ffa73a3
JH
2787 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2788 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 2789#endif
358837b8 2790#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 2791 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
2792 act.sa_flags |= SA_NOCLDWAIT;
2793#endif
ff68c719 2794 if (sigaction(signo, &act, &oact) == -1)
8aad04aa 2795 return (Sighandler_t) SIG_ERR;
ff68c719 2796 else
8aad04aa 2797 return (Sighandler_t) oact.sa_handler;
ff68c719
PP
2798}
2799
2800Sighandler_t
864dbfa3 2801Perl_rsignal_state(pTHX_ int signo)
ff68c719
PP
2802{
2803 struct sigaction oact;
96a5add6 2804 PERL_UNUSED_CONTEXT;
ff68c719
PP
2805
2806 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
8aad04aa 2807 return (Sighandler_t) SIG_ERR;
ff68c719 2808 else
8aad04aa 2809 return (Sighandler_t) oact.sa_handler;
ff68c719
PP
2810}
2811
2812int
864dbfa3 2813Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 2814{
20b7effb 2815#ifdef USE_ITHREADS
20b7effb 2816#endif
ff68c719
PP
2817 struct sigaction act;
2818
7918f24d
NC
2819 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2820
a10b1e10
JH
2821#ifdef USE_ITHREADS
2822 /* only "parent" interpreter can diddle signals */
2823 if (PL_curinterp != aTHX)
2824 return -1;
2825#endif
2826
8d61efc5 2827 act.sa_handler = handler;
ff68c719
PP
2828 sigemptyset(&act.sa_mask);
2829 act.sa_flags = 0;
2830#ifdef SA_RESTART
4ffa73a3
JH
2831 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2832 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
0a8e0eff 2833#endif
36b5d377 2834#if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
8aad04aa 2835 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
85264bed
CS
2836 act.sa_flags |= SA_NOCLDWAIT;
2837#endif
ff68c719
PP
2838 return sigaction(signo, &act, save);
2839}
2840
2841int
864dbfa3 2842Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 2843{
20b7effb 2844#ifdef USE_ITHREADS
20b7effb
JH
2845#endif
2846 PERL_UNUSED_CONTEXT;
a10b1e10
JH
2847#ifdef USE_ITHREADS
2848 /* only "parent" interpreter can diddle signals */
2849 if (PL_curinterp != aTHX)
2850 return -1;
2851#endif
2852
ff68c719
PP
2853 return sigaction(signo, save, (struct sigaction *)NULL);
2854}
2855
2856#else /* !HAS_SIGACTION */
2857
2858Sighandler_t
864dbfa3 2859Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
ff68c719 2860{
39f1703b 2861#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2862 /* only "parent" interpreter can diddle signals */
2863 if (PL_curinterp != aTHX)
8aad04aa 2864 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2865#endif
2866
6ad3d225 2867 return PerlProc_signal(signo, handler);
ff68c719
PP
2868}
2869
fabdb6c0 2870static Signal_t
4e35701f 2871sig_trap(int signo)
ff68c719 2872{
27da23d5 2873 PL_sig_trapped++;
ff68c719
PP
2874}
2875
2876Sighandler_t
864dbfa3 2877Perl_rsignal_state(pTHX_ int signo)
ff68c719
PP
2878{
2879 Sighandler_t oldsig;
2880
39f1703b 2881#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2882 /* only "parent" interpreter can diddle signals */
2883 if (PL_curinterp != aTHX)
8aad04aa 2884 return (Sighandler_t) SIG_ERR;
a10b1e10
JH
2885#endif
2886
27da23d5 2887 PL_sig_trapped = 0;
6ad3d225
GS
2888 oldsig = PerlProc_signal(signo, sig_trap);
2889 PerlProc_signal(signo, oldsig);
27da23d5 2890 if (PL_sig_trapped)
3aed30dc 2891 PerlProc_kill(PerlProc_getpid(), signo);
ff68c719
PP
2892 return oldsig;
2893}
2894
2895int
864dbfa3 2896Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
ff68c719 2897{
39f1703b 2898#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2899 /* only "parent" interpreter can diddle signals */
2900 if (PL_curinterp != aTHX)
2901 return -1;
2902#endif
6ad3d225 2903 *save = PerlProc_signal(signo, handler);
8aad04aa 2904 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719
PP
2905}
2906
2907int
864dbfa3 2908Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
ff68c719 2909{
39f1703b 2910#if defined(USE_ITHREADS) && !defined(WIN32)
a10b1e10
JH
2911 /* only "parent" interpreter can diddle signals */
2912 if (PL_curinterp != aTHX)
2913 return -1;
2914#endif
8aad04aa 2915 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
ff68c719
PP
2916}
2917
2918#endif /* !HAS_SIGACTION */
64ca3a65 2919#endif /* !PERL_MICRO */
ff68c719 2920
5f05dabc 2921 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
53f73940 2922#if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
79072805 2923I32
864dbfa3 2924Perl_my_pclose(pTHX_ PerlIO *ptr)
a687059c 2925{
a687059c 2926 int status;
a0d0e21e 2927 SV **svp;
d8a83dd3 2928 Pid_t pid;
2e0cfa16 2929 Pid_t pid2 = 0;
03136e13 2930 bool close_failed;
4ee39169 2931 dSAVEDERRNO;
2e0cfa16 2932 const int fd = PerlIO_fileno(ptr);
e9d373c4
TC
2933 bool should_wait;
2934
2935 svp = av_fetch(PL_fdpid,fd,TRUE);
2936 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2937 SvREFCNT_dec(*svp);
2938 *svp = NULL;
2e0cfa16 2939
97cb92d6 2940#if defined(USE_PERLIO)
2e0cfa16
FC
2941 /* Find out whether the refcount is low enough for us to wait for the
2942 child proc without blocking. */
e9d373c4 2943 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
b6ae43b7 2944#else
e9d373c4 2945 should_wait = pid > 0;
b6ae43b7 2946#endif
a687059c 2947
ddcf38b7
IZ
2948#ifdef OS2
2949 if (pid == -1) { /* Opened by popen. */
2950 return my_syspclose(ptr);
2951 }
a1d180c4 2952#endif
f1618b10
CS
2953 close_failed = (PerlIO_close(ptr) == EOF);
2954 SAVE_ERRNO;
2e0cfa16 2955 if (should_wait) do {
1d3434b8
GS
2956 pid2 = wait4pid(pid, &status, 0);
2957 } while (pid2 == -1 && errno == EINTR);
03136e13 2958 if (close_failed) {
4ee39169 2959 RESTORE_ERRNO;
03136e13
CS
2960 return -1;
2961 }
2e0cfa16
FC
2962 return(
2963 should_wait
2964 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2965 : 0
2966 );
20188a90 2967}
8ad758c7 2968#elif defined(__LIBCATAMOUNT__)
9c12f1e5
RGS
2969I32
2970Perl_my_pclose(pTHX_ PerlIO *ptr)
2971{
2972 return -1;
2973}
4633a7c4
LW
2974#endif /* !DOSISH */
2975
e37778c2 2976#if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
79072805 2977I32
d8a83dd3 2978Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
20188a90 2979{
27da23d5 2980 I32 result = 0;
7918f24d 2981 PERL_ARGS_ASSERT_WAIT4PID;
ca0c25f6 2982#ifdef PERL_USES_PL_PIDSTATUS
d4c02743
TC
2983 if (!pid) {
2984 /* PERL_USES_PL_PIDSTATUS is only defined when neither
2985 waitpid() nor wait4() is available, or on OS/2, which
2986 doesn't appear to support waiting for a progress group
2987 member, so we can only treat a 0 pid as an unknown child.
2988 */
2989 errno = ECHILD;
2990 return -1;
2991 }
b7953727 2992 {
3aed30dc 2993 if (pid > 0) {
12072db5
NC
2994 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2995 pid, rather than a string form. */
c4420975 2996 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3aed30dc
HS
2997 if (svp && *svp != &PL_sv_undef) {
2998 *statusp = SvIVX(*svp);
12072db5
NC
2999 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3000 G_DISCARD);
3aed30dc
HS
3001 return pid;
3002 }
3003 }
3004 else {
3005 HE *entry;
3006
3007 hv_iterinit(PL_pidstatus);
3008 if ((entry = hv_iternext(PL_pidstatus))) {
c4420975 3009 SV * const sv = hv_iterval(PL_pidstatus,entry);
7ea75b61 3010 I32 len;
0bcc34c2 3011 const char * const spid = hv_iterkey(entry,&len);
27da23d5 3012
12072db5
NC
3013 assert (len == sizeof(Pid_t));
3014 memcpy((char *)&pid, spid, len);
3aed30dc 3015 *statusp = SvIVX(sv);
7b9a3241
NC
3016 /* The hash iterator is currently on this entry, so simply
3017 calling hv_delete would trigger the lazy delete, which on
f6bab5f6 3018 aggregate does more work, because next call to hv_iterinit()
7b9a3241
NC
3019 would spot the flag, and have to call the delete routine,
3020 while in the meantime any new entries can't re-use that
3021 memory. */
3022 hv_iterinit(PL_pidstatus);
7ea75b61 3023 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3aed30dc
HS
3024 return pid;
3025 }
20188a90
LW
3026 }
3027 }
68a29c53 3028#endif
79072805 3029#ifdef HAS_WAITPID
367f3c24
IZ
3030# ifdef HAS_WAITPID_RUNTIME
3031 if (!HAS_WAITPID_RUNTIME)
3032 goto hard_way;
3033# endif
cddd4526 3034 result = PerlProc_waitpid(pid,statusp,flags);
dfcfdb64 3035 goto finish;
367f3c24
IZ
3036#endif
3037#if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
d4c02743 3038 result = wait4(pid,statusp,flags,NULL);
dfcfdb64 3039 goto finish;
367f3c24 3040#endif
ca0c25f6 3041#ifdef PERL_USES_PL_PIDSTATUS
27da23d5 3042#if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
367f3c24 3043 hard_way:
27da23d5 3044#endif
a0d0e21e 3045 {
a0d0e21e 3046 if (flags)
cea2e8a9 3047 Perl_croak(aTHX_ "Can't do waitpid with flags");
a0d0e21e 3048 else {
76e3520e 3049 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
a0d0e21e
LW
3050 pidgone(result,*statusp);
3051 if (result < 0)
3052 *statusp = -1;
3053 }
a687059c
LW
3054 }
3055#endif
27da23d5 3056#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
dfcfdb64 3057 finish:
27da23d5 3058#endif
cddd4526
NIS
3059 if (result < 0 && errno == EINTR) {
3060 PERL_ASYNC_CHECK();
48dbb59e 3061 errno = EINTR; /* reset in case a signal handler changed $! */
cddd4526
NIS
3062 }
3063 return result;
a687059c 3064}
2986a63f 3065#endif /* !DOSISH || OS2 || WIN32 || NETWARE */
a687059c 3066
ca0c25f6 3067#ifdef PERL_USES_PL_PIDSTATUS
7c0587c8 3068void
ed4173ef 3069S_pidgone(pTHX_ Pid_t pid, int status)
a687059c 3070{
eb578fdb 3071 SV *sv;
a687059c 3072
12072db5 3073 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
862a34c6 3074 SvUPGRADE(sv,SVt_IV);
45977657 3075 SvIV_set(sv, status);
20188a90 3076 return;
a687059c 3077}
ca0c25f6 3078#endif
a687059c 3079
6de23f80 3080#if defined(OS2)
7c0587c8 3081int pclose();
ddcf38b7
IZ
3082#ifdef HAS_FORK
3083int /* Cannot prototype with I32
3084 in os2ish.h. */
ba106d47 3085my_syspclose(PerlIO *ptr)
ddcf38b7 3086#else
79072805 3087I32
864dbfa3 3088Perl_my_pclose(pTHX_ PerlIO *ptr)
a1d180c4 3089#endif
a687059c 3090{
760ac839 3091 /* Needs work for PerlIO ! */
c4420975 3092 FILE * const f = PerlIO_findFILE(ptr);
7452cf6a 3093 const I32 result = pclose(f);
2b96b0a5
JH
3094 PerlIO_releaseFILE(ptr,f);
3095 return result;
3096}
3097#endif
3098
933fea7f 3099#if defined(DJGPP)
2b96b0a5
JH
3100int djgpp_pclose();
3101I32
3102Perl_my_pclose(pTHX_ PerlIO *ptr)
3103{
3104 /* Needs work for PerlIO ! */
c4420975 3105 FILE * const f = PerlIO_findFILE(ptr);
2b96b0a5 3106 I32 result = djgpp_pclose(f);
933fea7f 3107 result = (result << 8) & 0xff00;
760ac839
LW
3108 PerlIO_releaseFILE(ptr,f);
3109 return result;
a687059c 3110}
7c0587c8 3111#endif
9f68db38 3112
16fa5c11 3113#define PERL_REPEATCPY_LINEAR 4
9f68db38 3114void
5aaab254 3115Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
9f68db38 3116{
7918f24d
NC
3117 PERL_ARGS_ASSERT_REPEATCPY;
3118
223f01db
KW
3119 assert(len >= 0);
3120
2709980d 3121 if (count < 0)
d1decf2b 3122 croak_memory_wrap();
2709980d 3123
16fa5c11
VP
3124 if (len == 1)
3125 memset(to, *from, count);
3126 else if (count) {
eb578fdb 3127 char *p = to;
26e1303d 3128 IV items, linear, half;
16fa5c11
VP
3129
3130 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3131 for (items = 0; items < linear; ++items) {
eb578fdb 3132 const char *q = from;
26e1303d 3133 IV todo;
16fa5c11
VP
3134 for (todo = len; todo > 0; todo--)
3135 *p++ = *q++;
3136 }
3137
3138 half = count / 2;
3139 while (items <= half) {
26e1303d 3140 IV size = items * len;
16fa5c11
VP
3141 memcpy(p, to, size);
3142 p += size;
3143 items *= 2;
9f68db38 3144 }
16fa5c11
VP
3145
3146 if (count > items)
3147 memcpy(p, to, (count - items) * len);
9f68db38
LW
3148 }
3149}
0f85fab0 3150
fe14fcc3 3151#ifndef HAS_RENAME
79072805 3152I32
4373e329 3153Perl_same_dirent(pTHX_ const char *a, const char *b)
62b28dd9 3154{
93a17b20
LW
3155 char *fa = strrchr(a,'/');
3156 char *fb = strrchr(b,'/');
c623ac67
GS
3157 Stat_t tmpstatbuf1;
3158 Stat_t tmpstatbuf2;
c4420975 3159 SV * const tmpsv = sv_newmortal();
62b28dd9 3160
7918f24d
NC
3161 PERL_ARGS_ASSERT_SAME_DIRENT;
3162
62b28dd9
LW
3163 if (fa)
3164 fa++;
3165 else
3166 fa = a;
3167 if (fb)
3168 fb++;
3169 else
3170 fb = b;
3171 if (strNE(a,b))
3172 return FALSE;
3173 if (fa == a)
76f68e9b 3174 sv_setpvs(tmpsv, ".");
62b28dd9 3175 else
46fc3d4c 3176 sv_setpvn(tmpsv, a, fa - a);
95a20fc0 3177 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
62b28dd9
LW
3178 return FALSE;
3179 if (fb == b)
76f68e9b 3180 sv_setpvs(tmpsv, ".");
62b28dd9 3181 else
46fc3d4c 3182 sv_setpvn(tmpsv, b, fb - b);
95a20fc0 3183 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
62b28dd9
LW
3184 return FALSE;
3185 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3186 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3187}
fe14fcc3
LW
3188#endif /* !HAS_RENAME */
3189
491527d0 3190char*
7f315aed
NC
3191Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3192 const char *const *const search_ext, I32 flags)
491527d0 3193{
bd61b366
SS
3194 const char *xfound = NULL;
3195 char *xfailed = NULL;
0f31cffe 3196 char tmpbuf[MAXPATHLEN];
eb578fdb 3197 char *s;
5f74f29c 3198 I32 len = 0;
491527d0 3199 int retval;
39a02377 3200 char *bufend;
7c458fae 3201#if defined(DOSISH) && !defined(OS2)
491527d0
GS
3202# define SEARCH_EXTS ".bat", ".cmd", NULL
3203# define MAX_EXT_LEN 4
3204#endif
3205#ifdef OS2
3206# define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3207# define MAX_EXT_LEN 4
3208#endif
3209#ifdef VMS
3210# define SEARCH_EXTS ".pl", ".com", NULL
3211# define MAX_EXT_LEN 4
3212#endif
3213 /* additional extensions to try in each dir if scriptname not found */
3214#ifdef SEARCH_EXTS
0bcc34c2 3215 static const char *const exts[] = { SEARCH_EXTS };
7f315aed 3216 const char *const *const ext = search_ext ? search_ext : exts;
491527d0 3217 int extidx = 0, i = 0;
bd61b366 3218 const char *curext = NULL;
491527d0 3219#else
53c1dcc0 3220 PERL_UNUSED_ARG(search_ext);
491527d0
GS
3221# define MAX_EXT_LEN 0
3222#endif
3223
7918f24d
NC
3224 PERL_ARGS_ASSERT_FIND_SCRIPT;
3225
491527d0
GS
3226 /*
3227 * If dosearch is true and if scriptname does not contain path
3228 * delimiters, search the PATH for scriptname.
3229 *
3230 * If SEARCH_EXTS is also defined, will look for each
3231 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3232 * while searching the PATH.
3233 *
3234 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3235 * proceeds as follows:
3236 * If DOSISH or VMSISH:
3237 * + look for ./scriptname{,.foo,.bar}
3238 * + search the PATH for scriptname{,.foo,.bar}
3239 *
3240 * If !DOSISH:
3241 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3242 * this will not look in '.' if it's not in the PATH)
3243 */
84486fc6 3244 tmpbuf[0] = '\0';
491527d0
GS
3245
3246#ifdef VMS
3247# ifdef ALWAYS_DEFTYPES
3248 len = strlen(scriptname);
3249 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
c4420975 3250 int idx = 0, deftypes = 1;
491527d0
GS
3251 bool seen_dot = 1;
3252
bd61b366 3253 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
3254# else
3255 if (dosearch) {
c4420975 3256 int idx = 0, deftypes = 1;
491527d0
GS
3257 bool seen_dot = 1;
3258
bd61b366 3259 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
491527d0
GS
3260# endif
3261 /* The first time through, just add SEARCH_EXTS to whatever we
3262 * already have, so we can check for default file types. */
3263 while (deftypes ||
84486fc6 3264 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
491527d0 3265 {
2aa28b86 3266 Stat_t statbuf;
491527d0
GS
3267 if (deftypes) {
3268 deftypes = 0;
84486fc6 3269 *tmpbuf = '\0';
491527d0 3270 }
84486fc6
GS
3271 if ((strlen(tmpbuf) + strlen(scriptname)
3272 + MAX_EXT_LEN) >= sizeof tmpbuf)
491527d0 3273 continue; /* don't search dir with too-long name */
6fca0082 3274 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
491527d0
GS
3275#else /* !VMS */
3276
3277#ifdef DOSISH
3278 if (strEQ(scriptname, "-"))
3279 dosearch = 0;
3280 if (dosearch) { /* Look in '.' first. */
fe2774ed 3281 const char *cur = scriptname;
491527d0
GS
3282#ifdef SEARCH_EXTS
3283 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3284 while (ext[i])
3285 if (strEQ(ext[i++],curext)) {
3286 extidx = -1; /* already has an ext */
3287 break;
3288 }
3289 do {
3290#endif
3291 DEBUG_p(PerlIO_printf(Perl_debug_log,
3292 "Looking for %s\n",cur));
45a23732 3293 {
0cc19a43 3294 Stat_t statbuf;
45a23732
DD
3295 if (PerlLIO_stat(cur,&statbuf) >= 0
3296 && !S_ISDIR(statbuf.st_mode)) {
3297 dosearch = 0;
3298 scriptname = cur;
491527d0 3299#ifdef SEARCH_EXTS
45a23732 3300 break;
491527d0 3301#endif
45a23732 3302 }
491527d0
GS
3303 }
3304#ifdef SEARCH_EXTS
3305 if (cur == scriptname) {
3306 len = strlen(scriptname);
84486fc6 3307 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
491527d0 3308 break;
9e4425f7
SH
3309 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3310 cur = tmpbuf;
491527d0
GS
3311 }
3312 } while (extidx >= 0 && ext[extidx] /* try an extension? */
6fca0082 3313 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
491527d0
GS
3314#endif
3315 }
3316#endif
3317
3318 if (dosearch && !strchr(scriptname, '/')
3319#ifdef DOSISH
3320 && !strchr(scriptname, '\\')
3321#endif
cd39f2b6 3322 && (s = PerlEnv_getenv("PATH")))
cd39f2b6 3323 {
491527d0 3324 bool seen_dot = 0;
92f0c265 3325
39a02377
DM
3326 bufend = s + strlen(s);
3327 while (s < bufend) {
45a23732 3328 Stat_t statbuf;
7c458fae 3329# ifdef DOSISH
491527d0 3330 for (len = 0; *s
491527d0 3331 && *s != ';'; len++, s++) {
84486fc6
GS
3332 if (len < sizeof tmpbuf)
3333 tmpbuf[len] = *s;
491527d0 3334 }
84486fc6
GS
3335 if (len < sizeof tmpbuf)
3336 tmpbuf[len] = '\0';
7c458fae 3337# else
e80af1fd
TC
3338 s = delimcpy_no_escape(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3339 ':', &len);
7c458fae 3340# endif
39a02377 3341 if (s < bufend)
491527d0 3342 s++;
84486fc6 3343 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
491527d0
GS
3344 continue; /* don't search dir with too-long name */
3345 if (len
7c458fae 3346# ifdef DOSISH
84486fc6
GS
3347 && tmpbuf[len - 1] != '/'
3348 && tmpbuf[len - 1] != '\\'
490a0e98 3349# endif
491527d0 3350 )
84486fc6
GS
3351 tmpbuf[len++] = '/';
3352 if (len == 2 && tmpbuf[0] == '.')
491527d0 3353 seen_dot = 1;
28f0d0ec 3354 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
491527d0
GS
3355#endif /* !VMS */
3356
3357#ifdef SEARCH_EXTS
84486fc6 3358 len = strlen(tmpbuf);
491527d0
GS
3359 if (extidx > 0) /* reset after previous loop */
3360 extidx = 0;
3361 do {
3362#endif
84486fc6 3363 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
45a23732
DD
3364 retval = PerlLIO_stat(tmpbuf,&statbuf);
3365 if (S_ISDIR(statbuf.st_mode)) {
017f25f1
IZ
3366 retval = -1;
3367 }
491527d0
GS
3368#ifdef SEARCH_EXTS
3369 } while ( retval < 0 /* not there */
3370 && extidx>=0 && ext[extidx] /* try an extension? */
6fca0082 3371 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
491527d0
GS
3372 );
3373#endif
3374 if (retval < 0)
3375 continue;
45a23732
DD
3376 if (S_ISREG(statbuf.st_mode)
3377 && cando(S_IRUSR,TRUE,&statbuf)
e37778c2 3378#if !defined(DOSISH)
45a23732 3379 && cando(S_IXUSR,TRUE,&statbuf)
491527d0
GS
3380#endif
3381 )
3382 {
3aed30dc 3383 xfound = tmpbuf; /* bingo! */
491527d0
GS
3384 break;
3385 }
3386 if (!xfailed)
84486fc6 3387 xfailed = savepv(tmpbuf);
491527d0
GS
3388 }
3389#ifndef DOSISH
45a23732
DD
3390 {
3391 Stat_t statbuf;
3392 if (!xfound && !seen_dot && !xfailed &&
3393 (PerlLIO_stat(scriptname,&statbuf) < 0
3394 || S_ISDIR(statbuf.st_mode)))
3395#endif
3396 seen_dot = 1; /* Disable message. */
3397#ifndef DOSISH
3398 }
491527d0 3399#endif
9ccb31f9
GS
3400 if (!xfound) {
3401 if (flags & 1) { /* do or die? */
6ad282c7 3402 /* diag_listed_as: Can't execute %s */
3aed30dc 3403 Perl_croak(aTHX_ "Can't %s %s%s%s",
9ccb31f9
GS
3404 (xfailed ? "execute" : "find"),
3405 (xfailed ? xfailed : scriptname),
3406 (xfailed ? "" : " on PATH"),
3407 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3408 }
bd61b366 3409 scriptname = NULL;
9ccb31f9 3410 }
43c5f42d 3411 Safefree(xfailed);
491527d0
GS
3412 scriptname = xfound;
3413 }
bd61b366 3414 return (scriptname ? savepv(scriptname) : NULL);
491527d0
GS
3415}
3416
ba869deb
GS
3417#ifndef PERL_GET_CONTEXT_DEFINED
3418
3419void *
3420Perl_get_context(void)
3421{
3db8f154 3422#if defined(USE_ITHREADS)
ba869deb
GS
3423# ifdef OLD_PTHREADS_API
3424 pthread_addr_t t;
6535c371 3425 int error = pthread_getspecific(PL_thr_key, &t);
5637ef5b
NC
3426 if (error)
3427 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
ba869deb 3428 return (void*)t;
8ad758c7 3429# elif defined(I_MACH_CTHREADS)
8b8b35ab 3430 return (void*)cthread_data(cthread_self());
8ad758c7 3431# else
8b8b35ab 3432 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
c44d3fdb 3433# endif
ba869deb
GS
3434#else
3435 return (void*)NULL;
3436#endif
3437}
3438
3439void
3440Perl_set_context(void *t)
3441{
20b7effb 3442#if defined(USE_ITHREADS)
20b7effb 3443#endif
7918f24d 3444 PERL_ARGS_ASSERT_SET_CONTEXT;
3db8f154 3445#if defined(USE_ITHREADS)
c44d3fdb
GS
3446# ifdef I_MACH_CTHREADS
3447 cthread_set_data(cthread_self(), t);
3448# else
5637ef5b
NC
3449 {
3450 const int error = pthread_setspecific(PL_thr_key, t);
3451 if (error)
3452 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3453 }
c44d3fdb 3454# endif
b464bac0 3455#else
8772537c 3456 PERL_UNUSED_ARG(t);
ba869deb
GS
3457#endif
3458}
3459
3460#endif /* !PERL_GET_CONTEXT_DEFINED */
491527d0 3461
1cb0ed9b 3462char **
864dbfa3 3463Perl_get_op_names(pTHX)
31fb1209 3464{
96a5add6
AL
3465 PERL_UNUSED_CONTEXT;
3466 return (char **)PL_op_name;
31fb1209
NIS
3467}
3468
1cb0ed9b 3469char **
864dbfa3 3470Perl_get_op_descs(pTHX)
31fb1209 3471{
96a5add6
AL
3472 PERL_UNUSED_CONTEXT;
3473 return (char **)PL_op_desc;
31fb1209 3474}
9e6b2b00 3475
e1ec3a88 3476const char *
864dbfa3 3477Perl_get_no_modify(pTHX)
9e6b2b00 3478{
96a5add6
AL
3479 PERL_UNUSED_CONTEXT;
3480 return PL_no_modify;
9e6b2b00
GS
3481}
3482
3483U32 *
864dbfa3 3484Perl_get_opargs(pTHX)
9e6b2b00 3485{
96a5add6
AL
3486 PERL_UNUSED_CONTEXT;
3487 return (U32 *)PL_opargs;
9e6b2b00 3488}
51aa15f3 3489
0cb96387
GS
3490PPADDR_t*
3491Perl_get_ppaddr(pTHX)
3492{
96a5add6
AL
3493 PERL_UNUSED_CONTEXT;
3494 return (PPADDR_t*)PL_ppaddr;
0cb96387
GS
3495}
3496
a6c40364
GS
3497#ifndef HAS_GETENV_LEN
3498char *
bf4acbe4 3499Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
a6c40364 3500{
8772537c 3501 char * const env_trans = PerlEnv_getenv(env_elem);
96a5add6 3502 PERL_UNUSED_CONTEXT;
7918f24d 3503 PERL_ARGS_ASSERT_GETENV_LEN;
a6c40364
GS
3504 if (env_trans)
3505 *len = strlen(env_trans);
3506 return env_trans;
f675dbe5
CB
3507}
3508#endif
3509
dc9e4912
GS
3510
3511MGVTBL*
864dbfa3 3512Perl_get_vtbl(pTHX_ int vtbl_id)
dc9e4912 3513{
96a5add6 3514 PERL_UNUSED_CONTEXT;
dc9e4912 3515
c7fdacb9 3516 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
31114fe9 3517 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
dc9e4912
GS
3518}
3519
767df6a1 3520I32
864dbfa3 3521Perl_my_fflush_all(pTHX)
767df6a1 3522{
97cb92d6 3523#if defined(USE_PERLIO) || defined(FFLUSH_NULL)
ce720889 3524 return PerlIO_flush(NULL);
767df6a1 3525#else
8fbdfb7c 3526# if defined(HAS__FWALK)
f13a2bc0 3527 extern int fflush(FILE *);
74cac757
JH
3528 /* undocumented, unprototyped, but very useful BSDism */
3529 extern void _fwalk(int (*)(FILE *));
8fbdfb7c 3530 _fwalk(&fflush);
74cac757 3531 return 0;
8fa7f367 3532# else
8fbdfb7c 3533# if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
8fa7f367 3534 long open_max = -1;
8fbdfb7c 3535# ifdef PERL_FFLUSH_ALL_FOPEN_MAX
d2201af2 3536 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
8ad758c7 3537# elif defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
767df6a1 3538 open_max = sysconf(_SC_OPEN_MAX);
8ad758c7 3539# elif defined(FOPEN_MAX)
74cac757 3540 open_max = FOPEN_MAX;
8ad758c7 3541# elif defined(OPEN_MAX)
74cac757 3542 open_max = OPEN_MAX;
8ad758c7 3543# elif defined(_NFILE)
d2201af2 3544 open_max = _NFILE;
8ad758c7 3545# endif
767df6a1
JH
3546 if (open_max > 0) {
3547 long i;
3548 for (i = 0; i < open_max; i++)
d2201af2
AD
3549 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3550 STDIO_STREAM_ARRAY[i]._file < open_max &&
3551 STDIO_STREAM_ARRAY[i]._flag)
3552 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
7