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