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