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