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