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