This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
t/op/coreamp.t: Generalize for non-ASCII platfomrs
[perl5.git] / doio.c
... / ...
CommitLineData
1/* doio.c
2 *
3 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 * 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5 *
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.
8 *
9 */
10
11/*
12 * Far below them they saw the white waters pour into a foaming bowl, and
13 * then swirl darkly about a deep oval basin in the rocks, until they found
14 * their way out again through a narrow gate, and flowed away, fuming and
15 * chattering, into calmer and more level reaches.
16 *
17 * [p.684 of _The Lord of the Rings_, IV/vi: "The Forbidden Pool"]
18 */
19
20/* This file contains functions that do the actual I/O on behalf of ops.
21 * For example, pp_print() calls the do_print() function in this file for
22 * each argument needing printing.
23 */
24
25#include "EXTERN.h"
26#define PERL_IN_DOIO_C
27#include "perl.h"
28
29#if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
30#ifndef HAS_SEM
31#include <sys/ipc.h>
32#endif
33#ifdef HAS_MSG
34#include <sys/msg.h>
35#endif
36#ifdef HAS_SHM
37#include <sys/shm.h>
38# ifndef HAS_SHMAT_PROTOTYPE
39 extern Shmat_t shmat (int, char *, int);
40# endif
41#endif
42#endif
43
44#ifdef I_UTIME
45# if defined(_MSC_VER) || defined(__MINGW32__)
46# include <sys/utime.h>
47# else
48# include <utime.h>
49# endif
50#endif
51
52#ifdef O_EXCL
53# define OPEN_EXCL O_EXCL
54#else
55# define OPEN_EXCL 0
56#endif
57
58#define PERL_MODE_MAX 8
59#define PERL_FLAGS_MAX 10
60
61#include <signal.h>
62
63static IO *
64S_openn_setup(pTHX_ GV *gv, char *mode, PerlIO **saveifp, PerlIO **saveofp,
65 int *savefd, char *savetype)
66{
67 IO * const io = GvIOn(gv);
68
69 PERL_ARGS_ASSERT_OPENN_SETUP;
70
71 *saveifp = NULL;
72 *saveofp = NULL;
73 *savefd = -1;
74 *savetype = IoTYPE_CLOSED;
75
76 Zero(mode,sizeof(mode),char);
77 PL_forkprocess = 1; /* assume true if no fork */
78
79 /* If currently open - close before we re-open */
80 if (IoIFP(io)) {
81 if (IoTYPE(io) == IoTYPE_STD) {
82 /* This is a clone of one of STD* handles */
83 }
84 else {
85 const int old_fd = PerlIO_fileno(IoIFP(io));
86
87 if (old_fd >= 0 && old_fd <= PL_maxsysfd) {
88 /* This is one of the original STD* handles */
89 *saveifp = IoIFP(io);
90 *saveofp = IoOFP(io);
91 *savetype = IoTYPE(io);
92 *savefd = old_fd;
93 }
94 else {
95 int result;
96
97 if (IoTYPE(io) == IoTYPE_PIPE)
98 result = PerlProc_pclose(IoIFP(io));
99 else if (IoIFP(io) != IoOFP(io)) {
100 if (IoOFP(io)) {
101 result = PerlIO_close(IoOFP(io));
102 PerlIO_close(IoIFP(io)); /* clear stdio, fd already closed */
103 }
104 else
105 result = PerlIO_close(IoIFP(io));
106 }
107 else
108 result = PerlIO_close(IoIFP(io));
109
110 if (result == EOF && old_fd > PL_maxsysfd) {
111 /* Why is this not Perl_warn*() call ? */
112 PerlIO_printf(Perl_error_log,
113 "Warning: unable to close filehandle %"HEKf" properly.\n",
114 HEKfARG(GvENAME_HEK(gv))
115 );
116 }
117 }
118 }
119 IoOFP(io) = IoIFP(io) = NULL;
120 }
121 return io;
122}
123
124bool
125Perl_do_openn(pTHX_ GV *gv, const char *oname, I32 len, int as_raw,
126 int rawmode, int rawperm, PerlIO *supplied_fp, SV **svp,
127 I32 num_svs)
128{
129 PERL_ARGS_ASSERT_DO_OPENN;
130
131 if (as_raw) {
132 /* sysopen style args, i.e. integer mode and permissions */
133
134 if (num_svs != 0) {
135 Perl_croak(aTHX_ "panic: sysopen with multiple args, num_svs=%ld",
136 (long) num_svs);
137 }
138 return do_open_raw(gv, oname, len, rawmode, rawperm);
139 }
140 return do_open6(gv, oname, len, supplied_fp, svp, num_svs);
141}
142
143bool
144Perl_do_open_raw(pTHX_ GV *gv, const char *oname, STRLEN len,
145 int rawmode, int rawperm)
146{
147 PerlIO *saveifp;
148 PerlIO *saveofp;
149 int savefd;
150 char savetype;
151 char mode[PERL_MODE_MAX]; /* file mode ("r\0", "rb\0", "ab\0" etc.) */
152 IO * const io = openn_setup(gv, mode, &saveifp, &saveofp, &savefd, &savetype);
153 int writing = 0;
154 PerlIO *fp;
155
156 PERL_ARGS_ASSERT_DO_OPEN_RAW;
157
158 /* For ease of blame back to 5.000, keep the existing indenting. */
159 {
160 /* sysopen style args, i.e. integer mode and permissions */
161 STRLEN ix = 0;
162 const int appendtrunc =
163 0
164#ifdef O_APPEND /* Not fully portable. */
165 |O_APPEND
166#endif
167#ifdef O_TRUNC /* Not fully portable. */
168 |O_TRUNC
169#endif
170 ;
171 const int modifyingmode = O_WRONLY|O_RDWR|O_CREAT|appendtrunc;
172 int ismodifying;
173 SV *namesv;
174
175 /* It's not always
176
177 O_RDONLY 0
178 O_WRONLY 1
179 O_RDWR 2
180
181 It might be (in OS/390 and Mac OS Classic it is)
182
183 O_WRONLY 1
184 O_RDONLY 2
185 O_RDWR 3
186
187 This means that simple & with O_RDWR would look
188 like O_RDONLY is present. Therefore we have to
189 be more careful.
190 */
191 if ((ismodifying = (rawmode & modifyingmode))) {
192 if ((ismodifying & O_WRONLY) == O_WRONLY ||
193 (ismodifying & O_RDWR) == O_RDWR ||
194 (ismodifying & (O_CREAT|appendtrunc)))
195 TAINT_PROPER("sysopen");
196 }
197 mode[ix++] = IoTYPE_NUMERIC; /* Marker to openn to use numeric "sysopen" */
198
199#if defined(USE_64_BIT_RAWIO) && defined(O_LARGEFILE)
200 rawmode |= O_LARGEFILE; /* Transparently largefiley. */
201#endif
202
203 IoTYPE(io) = PerlIO_intmode2str(rawmode, &mode[ix], &writing);
204
205 namesv = newSVpvn_flags(oname, len, SVs_TEMP);
206 fp = PerlIO_openn(aTHX_ NULL, mode, -1, rawmode, rawperm, NULL, 1, &namesv);
207 }
208 return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
209 savetype, writing, 0, NULL);
210}
211
212bool
213Perl_do_open6(pTHX_ GV *gv, const char *oname, STRLEN len,
214 PerlIO *supplied_fp, SV **svp, U32 num_svs)
215{
216 PerlIO *saveifp;
217 PerlIO *saveofp;
218 int savefd;
219 char savetype;
220 char mode[PERL_MODE_MAX]; /* file mode ("r\0", "rb\0", "ab\0" etc.) */
221 IO * const io = openn_setup(gv, mode, &saveifp, &saveofp, &savefd, &savetype);
222 int writing = 0;
223 PerlIO *fp;
224 bool was_fdopen = FALSE;
225 char *type = NULL;
226
227 PERL_ARGS_ASSERT_DO_OPEN6;
228
229 /* For ease of blame back to 5.000, keep the existing indenting. */
230 {
231 /* Regular (non-sys) open */
232 char *name;
233 STRLEN olen = len;
234 char *tend;
235 int dodup = 0;
236 bool in_raw = 0, in_crlf = 0, out_raw = 0, out_crlf = 0;
237
238 /* Collect default raw/crlf info from the op */
239 if (PL_op && PL_op->op_type == OP_OPEN) {
240 /* set up IO layers */
241 const U8 flags = PL_op->op_private;
242 in_raw = (flags & OPpOPEN_IN_RAW);
243 in_crlf = (flags & OPpOPEN_IN_CRLF);
244 out_raw = (flags & OPpOPEN_OUT_RAW);
245 out_crlf = (flags & OPpOPEN_OUT_CRLF);
246 }
247
248 type = savepvn(oname, len);
249 tend = type+len;
250 SAVEFREEPV(type);
251
252 /* Lose leading and trailing white space */
253 while (isSPACE(*type))
254 type++;
255 while (tend > type && isSPACE(tend[-1]))
256 *--tend = '\0';
257
258 if (num_svs) {
259 const char *p;
260 STRLEN nlen = 0;
261 /* New style explicit name, type is just mode and layer info */
262#ifdef USE_STDIO
263 if (SvROK(*svp) && !strchr(oname,'&')) {
264 if (ckWARN(WARN_IO))
265 Perl_warner(aTHX_ packWARN(WARN_IO),
266 "Can't open a reference");
267 SETERRNO(EINVAL, LIB_INVARG);
268 fp = NULL;
269 goto say_false;
270 }
271#endif /* USE_STDIO */
272 p = (SvOK(*svp) || SvGMAGICAL(*svp)) ? SvPV(*svp, nlen) : NULL;
273
274 if (p && !IS_SAFE_PATHNAME(p, nlen, "open")) {
275 fp = NULL;
276 goto say_false;
277 }
278
279 name = p ? savepvn(p, nlen) : savepvs("");
280
281 SAVEFREEPV(name);
282 }
283 else {
284 name = type;
285 len = tend-type;
286 }
287 IoTYPE(io) = *type;
288 if ((*type == IoTYPE_RDWR) && /* scary */
289 (*(type+1) == IoTYPE_RDONLY || *(type+1) == IoTYPE_WRONLY) &&
290 ((!num_svs || (tend > type+1 && tend[-1] != IoTYPE_PIPE)))) {
291 TAINT_PROPER("open");
292 mode[1] = *type++;
293 writing = 1;
294 }
295
296 if (*type == IoTYPE_PIPE) {
297 if (num_svs) {
298 if (type[1] != IoTYPE_STD) {
299 unknown_open_mode:
300 Perl_croak(aTHX_ "Unknown open() mode '%.*s'", (int)olen, oname);
301 }
302 type++;
303 }
304 do {
305 type++;
306 } while (isSPACE(*type));
307 if (!num_svs) {
308 name = type;
309 len = tend-type;
310 }
311 if (*name == '\0') {
312 /* command is missing 19990114 */
313 if (ckWARN(WARN_PIPE))
314 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
315 errno = EPIPE;
316 fp = NULL;
317 goto say_false;
318 }
319 if (!(*name == '-' && name[1] == '\0') || num_svs)
320 TAINT_ENV();
321 TAINT_PROPER("piped open");
322 if (!num_svs && name[len-1] == '|') {
323 name[--len] = '\0' ;
324 if (ckWARN(WARN_PIPE))
325 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Can't open bidirectional pipe");
326 }
327 mode[0] = 'w';
328 writing = 1;
329 if (out_raw)
330 mode[1] = 'b';
331 else if (out_crlf)
332 mode[1] = 't';
333 if (num_svs > 1) {
334 fp = PerlProc_popen_list(mode, num_svs, svp);
335 }
336 else {
337 fp = PerlProc_popen(name,mode);
338 }
339 if (num_svs) {
340 if (*type) {
341 if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
342 fp = NULL;
343 goto say_false;
344 }
345 }
346 }
347 } /* IoTYPE_PIPE */
348 else if (*type == IoTYPE_WRONLY) {
349 TAINT_PROPER("open");
350 type++;
351 if (*type == IoTYPE_WRONLY) {
352 /* Two IoTYPE_WRONLYs in a row make for an IoTYPE_APPEND. */
353 mode[0] = IoTYPE(io) = IoTYPE_APPEND;
354 type++;
355 }
356 else {
357 mode[0] = 'w';
358 }
359 writing = 1;
360
361 if (out_raw)
362 mode[1] = 'b';
363 else if (out_crlf)
364 mode[1] = 't';
365 if (*type == '&') {
366 duplicity:
367 dodup = PERLIO_DUP_FD;
368 type++;
369 if (*type == '=') {
370 dodup = 0;
371 type++;
372 }
373 if (!num_svs && !*type && supplied_fp) {
374 /* "<+&" etc. is used by typemaps */
375 fp = supplied_fp;
376 }
377 else {
378 PerlIO *that_fp = NULL;
379 int wanted_fd;
380 if (num_svs > 1) {
381 /* diag_listed_as: More than one argument to '%s' open */
382 Perl_croak(aTHX_ "More than one argument to '%c&' open",IoTYPE(io));
383 }
384 while (isSPACE(*type))
385 type++;
386 if (num_svs && (
387 SvIOK(*svp)
388 || (SvPOKp(*svp) && looks_like_number(*svp))
389 )) {
390 wanted_fd = SvUV(*svp);
391 num_svs = 0;
392 }
393 else if (isDIGIT(*type)) {
394 wanted_fd = grok_atou(type, NULL);
395 }
396 else {
397 const IO* thatio;
398 if (num_svs) {
399 thatio = sv_2io(*svp);
400 }
401 else {
402 GV * const thatgv = gv_fetchpvn_flags(type, tend - type,
403 0, SVt_PVIO);
404 thatio = GvIO(thatgv);
405 }
406 if (!thatio) {
407#ifdef EINVAL
408 SETERRNO(EINVAL,SS_IVCHAN);
409#endif
410 fp = NULL;
411 goto say_false;
412 }
413 if ((that_fp = IoIFP(thatio))) {
414 /* Flush stdio buffer before dup. --mjd
415 * Unfortunately SEEK_CURing 0 seems to
416 * be optimized away on most platforms;
417 * only Solaris and Linux seem to flush
418 * on that. --jhi */
419 /* On the other hand, do all platforms
420 * take gracefully to flushing a read-only
421 * filehandle? Perhaps we should do
422 * fsetpos(src)+fgetpos(dst)? --nik */
423 PerlIO_flush(that_fp);
424 wanted_fd = PerlIO_fileno(that_fp);
425 /* When dup()ing STDIN, STDOUT or STDERR
426 * explicitly set appropriate access mode */
427 if (that_fp == PerlIO_stdout()
428 || that_fp == PerlIO_stderr())
429 IoTYPE(io) = IoTYPE_WRONLY;
430 else if (that_fp == PerlIO_stdin())
431 IoTYPE(io) = IoTYPE_RDONLY;
432 /* When dup()ing a socket, say result is
433 * one as well */
434 else if (IoTYPE(thatio) == IoTYPE_SOCKET)
435 IoTYPE(io) = IoTYPE_SOCKET;
436 }
437 else
438 wanted_fd = -1;
439 }
440 if (!num_svs)
441 type = NULL;
442 if (that_fp) {
443 fp = PerlIO_fdupopen(aTHX_ that_fp, NULL, dodup);
444 }
445 else {
446 if (dodup)
447 wanted_fd = PerlLIO_dup(wanted_fd);
448 else
449 was_fdopen = TRUE;
450 if (!(fp = PerlIO_openn(aTHX_ type,mode,wanted_fd,0,0,NULL,num_svs,svp))) {
451 if (dodup && wanted_fd >= 0)
452 PerlLIO_close(wanted_fd);
453 }
454 }
455 }
456 } /* & */
457 else {
458 while (isSPACE(*type))
459 type++;
460 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
461 type++;
462 fp = PerlIO_stdout();
463 IoTYPE(io) = IoTYPE_STD;
464 if (num_svs > 1) {
465 /* diag_listed_as: More than one argument to '%s' open */
466 Perl_croak(aTHX_ "More than one argument to '>%c' open",IoTYPE_STD);
467 }
468 }
469 else {
470 if (num_svs) {
471 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
472 }
473 else {
474 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
475 type = NULL;
476 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
477 }
478 }
479 } /* !& */
480 if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
481 goto unknown_open_mode;
482 } /* IoTYPE_WRONLY */
483 else if (*type == IoTYPE_RDONLY) {
484 do {
485 type++;
486 } while (isSPACE(*type));
487 mode[0] = 'r';
488 if (in_raw)
489 mode[1] = 'b';
490 else if (in_crlf)
491 mode[1] = 't';
492 if (*type == '&') {
493 goto duplicity;
494 }
495 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
496 type++;
497 fp = PerlIO_stdin();
498 IoTYPE(io) = IoTYPE_STD;
499 if (num_svs > 1) {
500 /* diag_listed_as: More than one argument to '%s' open */
501 Perl_croak(aTHX_ "More than one argument to '<%c' open",IoTYPE_STD);
502 }
503 }
504 else {
505 if (num_svs) {
506 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
507 }
508 else {
509 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
510 type = NULL;
511 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
512 }
513 }
514 if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
515 goto unknown_open_mode;
516 } /* IoTYPE_RDONLY */
517 else if ((num_svs && /* '-|...' or '...|' */
518 type[0] == IoTYPE_STD && type[1] == IoTYPE_PIPE) ||
519 (!num_svs && tend > type+1 && tend[-1] == IoTYPE_PIPE)) {
520 if (num_svs) {
521 type += 2; /* skip over '-|' */
522 }
523 else {
524 *--tend = '\0';
525 while (tend > type && isSPACE(tend[-1]))
526 *--tend = '\0';
527 for (; isSPACE(*type); type++)
528 ;
529 name = type;
530 len = tend-type;
531 }
532 if (*name == '\0') {
533 /* command is missing 19990114 */
534 if (ckWARN(WARN_PIPE))
535 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
536 errno = EPIPE;
537 fp = NULL;
538 goto say_false;
539 }
540 if (!(*name == '-' && name[1] == '\0') || num_svs)
541 TAINT_ENV();
542 TAINT_PROPER("piped open");
543 mode[0] = 'r';
544
545 if (in_raw)
546 mode[1] = 'b';
547 else if (in_crlf)
548 mode[1] = 't';
549
550 if (num_svs > 1) {
551 fp = PerlProc_popen_list(mode,num_svs,svp);
552 }
553 else {
554 fp = PerlProc_popen(name,mode);
555 }
556 IoTYPE(io) = IoTYPE_PIPE;
557 if (num_svs) {
558 while (isSPACE(*type))
559 type++;
560 if (*type) {
561 if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
562 fp = NULL;
563 goto say_false;
564 }
565 }
566 }
567 }
568 else { /* layer(Args) */
569 if (num_svs)
570 goto unknown_open_mode;
571 name = type;
572 IoTYPE(io) = IoTYPE_RDONLY;
573 for (; isSPACE(*name); name++)
574 ;
575 mode[0] = 'r';
576
577 if (in_raw)
578 mode[1] = 'b';
579 else if (in_crlf)
580 mode[1] = 't';
581
582 if (*name == '-' && name[1] == '\0') {
583 fp = PerlIO_stdin();
584 IoTYPE(io) = IoTYPE_STD;
585 }
586 else {
587 if (num_svs) {
588 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
589 }
590 else {
591 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
592 type = NULL;
593 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
594 }
595 }
596 }
597 }
598
599 say_false:
600 return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
601 savetype, writing, was_fdopen, type);
602}
603
604/* Yes, this is ugly, but it's private, and I don't see a cleaner way to
605 simplify the two-headed public interface of do_openn. */
606static bool
607S_openn_cleanup(pTHX_ GV *gv, IO *io, PerlIO *fp, char *mode, const char *oname,
608 PerlIO *saveifp, PerlIO *saveofp, int savefd, char savetype,
609 int writing, bool was_fdopen, const char *type)
610{
611 int fd;
612
613 PERL_ARGS_ASSERT_OPENN_CLEANUP;
614
615 if (!fp) {
616 if (IoTYPE(io) == IoTYPE_RDONLY && ckWARN(WARN_NEWLINE)
617 && should_warn_nl(oname)
618
619 )
620 {
621 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
622 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
623 GCC_DIAG_RESTORE;
624 }
625 goto say_false;
626 }
627
628 if (ckWARN(WARN_IO)) {
629 if ((IoTYPE(io) == IoTYPE_RDONLY) &&
630 (fp == PerlIO_stdout() || fp == PerlIO_stderr())) {
631 Perl_warner(aTHX_ packWARN(WARN_IO),
632 "Filehandle STD%s reopened as %"HEKf
633 " only for input",
634 ((fp == PerlIO_stdout()) ? "OUT" : "ERR"),
635 HEKfARG(GvENAME_HEK(gv)));
636 }
637 else if ((IoTYPE(io) == IoTYPE_WRONLY) && fp == PerlIO_stdin()) {
638 Perl_warner(aTHX_ packWARN(WARN_IO),
639 "Filehandle STDIN reopened as %"HEKf" only for output",
640 HEKfARG(GvENAME_HEK(gv))
641 );
642 }
643 }
644
645 fd = PerlIO_fileno(fp);
646 /* Do NOT do: "if (fd < 0) goto say_false;" here. If there is no
647 * fd assume it isn't a socket - this covers PerlIO::scalar -
648 * otherwise unless we "know" the type probe for socket-ness.
649 */
650 if (IoTYPE(io) && IoTYPE(io) != IoTYPE_PIPE && IoTYPE(io) != IoTYPE_STD && fd >= 0) {
651 if (PerlLIO_fstat(fd,&PL_statbuf) < 0) {
652 /* If PerlIO claims to have fd we had better be able to fstat() it. */
653 (void) PerlIO_close(fp);
654 goto say_false;
655 }
656#ifndef PERL_MICRO
657 if (S_ISSOCK(PL_statbuf.st_mode))
658 IoTYPE(io) = IoTYPE_SOCKET; /* in case a socket was passed in to us */
659#ifdef HAS_SOCKET
660 else if (
661 !(PL_statbuf.st_mode & S_IFMT)
662 && IoTYPE(io) != IoTYPE_WRONLY /* Dups of STD* filehandles already have */
663 && IoTYPE(io) != IoTYPE_RDONLY /* type so they aren't marked as sockets */
664 ) { /* on OS's that return 0 on fstat()ed pipe */
665 char tmpbuf[256];
666 Sock_size_t buflen = sizeof tmpbuf;
667 if (PerlSock_getsockname(fd, (struct sockaddr *)tmpbuf, &buflen) >= 0
668 || errno != ENOTSOCK)
669 IoTYPE(io) = IoTYPE_SOCKET; /* some OS's return 0 on fstat()ed socket */
670 /* but some return 0 for streams too, sigh */
671 }
672#endif /* HAS_SOCKET */
673#endif /* !PERL_MICRO */
674 }
675
676 /* Eeek - FIXME !!!
677 * If this is a standard handle we discard all the layer stuff
678 * and just dup the fd into whatever was on the handle before !
679 */
680
681 if (saveifp) { /* must use old fp? */
682 /* If fd is less that PL_maxsysfd i.e. STDIN..STDERR
683 then dup the new fileno down
684 */
685 if (saveofp) {
686 PerlIO_flush(saveofp); /* emulate PerlIO_close() */
687 if (saveofp != saveifp) { /* was a socket? */
688 PerlIO_close(saveofp);
689 }
690 }
691 if (savefd != fd) {
692 /* Still a small can-of-worms here if (say) PerlIO::scalar
693 is assigned to (say) STDOUT - for now let dup2() fail
694 and provide the error
695 */
696 if (fd < 0) {
697 SETERRNO(EBADF,RMS_IFI);
698 goto say_false;
699 } else if (PerlLIO_dup2(fd, savefd) < 0) {
700 (void)PerlIO_close(fp);
701 goto say_false;
702 }
703#ifdef VMS
704 if (savefd != PerlIO_fileno(PerlIO_stdin())) {
705 char newname[FILENAME_MAX+1];
706 if (PerlIO_getname(fp, newname)) {
707 if (fd == PerlIO_fileno(PerlIO_stdout()))
708 vmssetuserlnm("SYS$OUTPUT", newname);
709 if (fd == PerlIO_fileno(PerlIO_stderr()))
710 vmssetuserlnm("SYS$ERROR", newname);
711 }
712 }
713#endif
714
715#if !defined(WIN32)
716 /* PL_fdpid isn't used on Windows, so avoid this useless work.
717 * XXX Probably the same for a lot of other places. */
718 {
719 Pid_t pid;
720 SV *sv;
721
722 sv = *av_fetch(PL_fdpid,fd,TRUE);
723 SvUPGRADE(sv, SVt_IV);
724 pid = SvIVX(sv);
725 SvIV_set(sv, 0);
726 sv = *av_fetch(PL_fdpid,savefd,TRUE);
727 SvUPGRADE(sv, SVt_IV);
728 SvIV_set(sv, pid);
729 }
730#endif
731
732 if (was_fdopen) {
733 /* need to close fp without closing underlying fd */
734 int ofd = PerlIO_fileno(fp);
735 int dupfd = ofd >= 0 ? PerlLIO_dup(ofd) : -1;
736#if defined(HAS_FCNTL) && defined(F_SETFD)
737 /* Assume if we have F_SETFD we have F_GETFD */
738 int coe = ofd >= 0 ? fcntl(ofd, F_GETFD) : -1;
739 if (coe < 0) {
740 if (dupfd >= 0)
741 PerlLIO_close(dupfd);
742 goto say_false;
743 }
744#endif
745 if (ofd < 0 || dupfd < 0) {
746 if (dupfd >= 0)
747 PerlLIO_close(dupfd);
748 goto say_false;
749 }
750 PerlIO_close(fp);
751 PerlLIO_dup2(dupfd, ofd);
752#if defined(HAS_FCNTL) && defined(F_SETFD)
753 /* The dup trick has lost close-on-exec on ofd */
754 fcntl(ofd,F_SETFD, coe);
755#endif
756 PerlLIO_close(dupfd);
757 }
758 else
759 PerlIO_close(fp);
760 }
761 fp = saveifp;
762 PerlIO_clearerr(fp);
763 fd = PerlIO_fileno(fp);
764 }
765#if defined(HAS_FCNTL) && defined(F_SETFD)
766 if (fd >= 0) {
767 if (fcntl(fd, F_SETFD, fd > PL_maxsysfd) < 0) {
768 PerlLIO_close(fd);
769 goto say_false;
770 }
771 }
772#endif
773 IoIFP(io) = fp;
774
775 IoFLAGS(io) &= ~IOf_NOLINE;
776 if (writing) {
777 if (IoTYPE(io) == IoTYPE_SOCKET
778 || (IoTYPE(io) == IoTYPE_WRONLY && fd >= 0 && S_ISCHR(PL_statbuf.st_mode)) ) {
779 char *s = mode;
780 if (*s == IoTYPE_IMPLICIT || *s == IoTYPE_NUMERIC)
781 s++;
782 *s = 'w';
783 if (!(IoOFP(io) = PerlIO_openn(aTHX_ type,s,fd,0,0,NULL,0,NULL))) {
784 PerlIO_close(fp);
785 goto say_false;
786 }
787 }
788 else
789 IoOFP(io) = fp;
790 }
791 return TRUE;
792
793 say_false:
794 IoIFP(io) = saveifp;
795 IoOFP(io) = saveofp;
796 IoTYPE(io) = savetype;
797 return FALSE;
798}
799
800PerlIO *
801Perl_nextargv(pTHX_ GV *gv, bool nomagicopen)
802{
803 IO * const io = GvIOp(gv);
804
805 PERL_ARGS_ASSERT_NEXTARGV;
806
807 if (!PL_argvoutgv)
808 PL_argvoutgv = gv_fetchpvs("ARGVOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
809 if (io && (IoFLAGS(io) & (IOf_ARGV|IOf_START)) == (IOf_ARGV|IOf_START)) {
810 IoFLAGS(io) &= ~IOf_START;
811 if (PL_inplace) {
812 assert(PL_defoutgv);
813 Perl_av_create_and_push(aTHX_ &PL_argvout_stack,
814 SvREFCNT_inc_simple_NN(PL_defoutgv));
815 }
816 }
817 if (PL_filemode & (S_ISUID|S_ISGID)) {
818 PerlIO_flush(IoIFP(GvIOn(PL_argvoutgv))); /* chmod must follow last write */
819#ifdef HAS_FCHMOD
820 if (PL_lastfd != -1)
821 (void)fchmod(PL_lastfd,PL_filemode);
822#else
823 (void)PerlLIO_chmod(PL_oldname,PL_filemode);
824#endif
825 }
826 PL_lastfd = -1;
827 PL_filemode = 0;
828 if (!GvAV(gv))
829 return NULL;
830 while (av_tindex(GvAV(gv)) >= 0) {
831 STRLEN oldlen;
832 SV *const sv = av_shift(GvAV(gv));
833 SAVEFREESV(sv);
834 SvTAINTED_off(GvSVn(gv)); /* previous tainting irrelevant */
835 sv_setsv(GvSVn(gv),sv);
836 SvSETMAGIC(GvSV(gv));
837 PL_oldname = SvPVx(GvSV(gv), oldlen);
838 if (LIKELY(!PL_inplace)) {
839 if (nomagicopen
840 ? do_open6(gv, "<", 1, NULL, &GvSV(gv), 1)
841 : do_open6(gv, PL_oldname, oldlen, NULL, NULL, 0)
842 ) {
843 return IoIFP(GvIOp(gv));
844 }
845 }
846 else {
847 /* This very long block ends with return IoIFP(GvIOp(gv));
848 Both this block and the block above fall through on open
849 failure to the warning code, and then the while loop above tries
850 the next entry. */
851 if (do_open_raw(gv, PL_oldname, oldlen, O_RDONLY, 0)) {
852#ifndef FLEXFILENAMES
853 int filedev;
854 int fileino;
855#endif
856 Uid_t fileuid;
857 Gid_t filegid;
858
859 TAINT_PROPER("inplace open");
860 if (oldlen == 1 && *PL_oldname == '-') {
861 setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL,
862 SVt_PVIO));
863 return IoIFP(GvIOp(gv));
864 }
865#ifndef FLEXFILENAMES
866 filedev = PL_statbuf.st_dev;
867 fileino = PL_statbuf.st_ino;
868#endif
869 PL_filemode = PL_statbuf.st_mode;
870 fileuid = PL_statbuf.st_uid;
871 filegid = PL_statbuf.st_gid;
872 if (!S_ISREG(PL_filemode)) {
873 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
874 "Can't do inplace edit: %s is not a regular file",
875 PL_oldname );
876 do_close(gv,FALSE);
877 continue;
878 }
879 if (*PL_inplace && strNE(PL_inplace, "*")) {
880 const char *star = strchr(PL_inplace, '*');
881 if (star) {
882 const char *begin = PL_inplace;
883 sv_setpvs(sv, "");
884 do {
885 sv_catpvn(sv, begin, star - begin);
886 sv_catpvn(sv, PL_oldname, oldlen);
887 begin = ++star;
888 } while ((star = strchr(begin, '*')));
889 if (*begin)
890 sv_catpv(sv,begin);
891 }
892 else {
893 sv_catpv(sv,PL_inplace);
894 }
895#ifndef FLEXFILENAMES
896 if ((PerlLIO_stat(SvPVX_const(sv),&PL_statbuf) >= 0
897 && PL_statbuf.st_dev == filedev
898 && PL_statbuf.st_ino == fileino)
899#ifdef DJGPP
900 || ((_djstat_fail_bits & _STFAIL_TRUENAME)!=0)
901#endif
902 )
903 {
904 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
905 "Can't do inplace edit: %"SVf" would not be unique",
906 SVfARG(sv));
907 do_close(gv,FALSE);
908 continue;
909 }
910#endif
911#ifdef HAS_RENAME
912#if !defined(DOSISH) && !defined(__CYGWIN__)
913 if (PerlLIO_rename(PL_oldname,SvPVX_const(sv)) < 0) {
914 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
915 "Can't rename %s to %"SVf": %s, skipping file",
916 PL_oldname, SVfARG(sv), Strerror(errno));
917 do_close(gv,FALSE);
918 continue;
919 }
920#else
921 do_close(gv,FALSE);
922 (void)PerlLIO_unlink(SvPVX_const(sv));
923 (void)PerlLIO_rename(PL_oldname,SvPVX_const(sv));
924 do_open_raw(gv, SvPVX_const(sv), SvCUR(sv), O_RDONLY, 0);
925#endif /* DOSISH */
926#else
927 (void)UNLINK(SvPVX_const(sv));
928 if (link(PL_oldname,SvPVX_const(sv)) < 0) {
929 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
930 "Can't rename %s to %"SVf": %s, skipping file",
931 PL_oldname, SVfARG(sv), Strerror(errno) );
932 do_close(gv,FALSE);
933 continue;
934 }
935 (void)UNLINK(PL_oldname);
936#endif
937 }
938 else {
939#if !defined(DOSISH) && !defined(AMIGAOS)
940# ifndef VMS /* Don't delete; use automatic file versioning */
941 if (UNLINK(PL_oldname) < 0) {
942 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
943 "Can't remove %s: %s, skipping file",
944 PL_oldname, Strerror(errno) );
945 do_close(gv,FALSE);
946 continue;
947 }
948# endif
949#else
950 Perl_croak(aTHX_ "Can't do inplace edit without backup");
951#endif
952 }
953
954 sv_setpvn(sv,PL_oldname,oldlen);
955 SETERRNO(0,0); /* in case sprintf set errno */
956 if (!Perl_do_open_raw(aTHX_ PL_argvoutgv, SvPVX_const(sv),
957 SvCUR(sv),
958#ifdef VMS
959 O_WRONLY|O_CREAT|O_TRUNC, 0
960#else
961 O_WRONLY|O_CREAT|OPEN_EXCL, 0600
962#endif
963 )) {
964 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE), "Can't do inplace edit on %s: %s",
965 PL_oldname, Strerror(errno) );
966 do_close(gv,FALSE);
967 continue;
968 }
969 setdefout(PL_argvoutgv);
970 PL_lastfd = PerlIO_fileno(IoIFP(GvIOp(PL_argvoutgv)));
971 if (PL_lastfd >= 0) {
972 (void)PerlLIO_fstat(PL_lastfd,&PL_statbuf);
973#ifdef HAS_FCHMOD
974 (void)fchmod(PL_lastfd,PL_filemode);
975#else
976 (void)PerlLIO_chmod(PL_oldname,PL_filemode);
977#endif
978 if (fileuid != PL_statbuf.st_uid || filegid != PL_statbuf.st_gid) {
979 /* XXX silently ignore failures */
980#ifdef HAS_FCHOWN
981 PERL_UNUSED_RESULT(fchown(PL_lastfd,fileuid,filegid));
982#else
983#ifdef HAS_CHOWN
984 PERL_UNUSED_RESULT(PerlLIO_chown(PL_oldname,fileuid,filegid));
985#endif
986#endif
987 }
988 }
989 return IoIFP(GvIOp(gv));
990 }
991 } /* successful do_open_raw(), PL_inplace non-NULL */
992
993 if (ckWARN_d(WARN_INPLACE)) {
994 const int eno = errno;
995 if (PerlLIO_stat(PL_oldname, &PL_statbuf) >= 0
996 && !S_ISREG(PL_statbuf.st_mode)) {
997 Perl_warner(aTHX_ packWARN(WARN_INPLACE),
998 "Can't do inplace edit: %s is not a regular file",
999 PL_oldname);
1000 }
1001 else {
1002 Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't open %s: %s",
1003 PL_oldname, Strerror(eno));
1004 }
1005 }
1006 }
1007 if (io && (IoFLAGS(io) & IOf_ARGV))
1008 IoFLAGS(io) |= IOf_START;
1009 if (PL_inplace) {
1010 (void)do_close(PL_argvoutgv,FALSE);
1011 if (io && (IoFLAGS(io) & IOf_ARGV)
1012 && PL_argvout_stack && AvFILLp(PL_argvout_stack) >= 0)
1013 {
1014 GV * const oldout = MUTABLE_GV(av_pop(PL_argvout_stack));
1015 setdefout(oldout);
1016 SvREFCNT_dec_NN(oldout);
1017 return NULL;
1018 }
1019 setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO));
1020 }
1021 return NULL;
1022}
1023
1024/* explicit renamed to avoid C++ conflict -- kja */
1025bool
1026Perl_do_close(pTHX_ GV *gv, bool not_implicit)
1027{
1028 bool retval;
1029 IO *io;
1030
1031 if (!gv)
1032 gv = PL_argvgv;
1033 if (!gv || !isGV_with_GP(gv)) {
1034 if (not_implicit)
1035 SETERRNO(EBADF,SS_IVCHAN);
1036 return FALSE;
1037 }
1038 io = GvIO(gv);
1039 if (!io) { /* never opened */
1040 if (not_implicit) {
1041 report_evil_fh(gv);
1042 SETERRNO(EBADF,SS_IVCHAN);
1043 }
1044 return FALSE;
1045 }
1046 retval = io_close(io, NULL, not_implicit, FALSE);
1047 if (not_implicit) {
1048 IoLINES(io) = 0;
1049 IoPAGE(io) = 0;
1050 IoLINES_LEFT(io) = IoPAGE_LEN(io);
1051 }
1052 IoTYPE(io) = IoTYPE_CLOSED;
1053 return retval;
1054}
1055
1056bool
1057Perl_io_close(pTHX_ IO *io, GV *gv, bool not_implicit, bool warn_on_fail)
1058{
1059 bool retval = FALSE;
1060
1061 PERL_ARGS_ASSERT_IO_CLOSE;
1062
1063 if (IoIFP(io)) {
1064 if (IoTYPE(io) == IoTYPE_PIPE) {
1065 const int status = PerlProc_pclose(IoIFP(io));
1066 if (not_implicit) {
1067 STATUS_NATIVE_CHILD_SET(status);
1068 retval = (STATUS_UNIX == 0);
1069 }
1070 else {
1071 retval = (status != -1);
1072 }
1073 }
1074 else if (IoTYPE(io) == IoTYPE_STD)
1075 retval = TRUE;
1076 else {
1077 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) { /* a socket */
1078 const bool prev_err = PerlIO_error(IoOFP(io));
1079#ifdef USE_PERLIO
1080 if (prev_err)
1081 PerlIO_restore_errno(IoOFP(io));
1082#endif
1083 retval = (PerlIO_close(IoOFP(io)) != EOF && !prev_err);
1084 PerlIO_close(IoIFP(io)); /* clear stdio, fd already closed */
1085 }
1086 else {
1087 const bool prev_err = PerlIO_error(IoIFP(io));
1088#ifdef USE_PERLIO
1089 if (prev_err)
1090 PerlIO_restore_errno(IoIFP(io));
1091#endif
1092 retval = (PerlIO_close(IoIFP(io)) != EOF && !prev_err);
1093 }
1094 }
1095 IoOFP(io) = IoIFP(io) = NULL;
1096
1097 if (warn_on_fail && !retval) {
1098 if (gv)
1099 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1100 "Warning: unable to close filehandle %"
1101 HEKf" properly: %"SVf,
1102 GvNAME_HEK(gv), get_sv("!",GV_ADD));
1103 else
1104 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1105 "Warning: unable to close filehandle "
1106 "properly: %"SVf,
1107 get_sv("!",GV_ADD));
1108 }
1109 }
1110 else if (not_implicit) {
1111 SETERRNO(EBADF,SS_IVCHAN);
1112 }
1113
1114 return retval;
1115}
1116
1117bool
1118Perl_do_eof(pTHX_ GV *gv)
1119{
1120 IO * const io = GvIO(gv);
1121
1122 PERL_ARGS_ASSERT_DO_EOF;
1123
1124 if (!io)
1125 return TRUE;
1126 else if (IoTYPE(io) == IoTYPE_WRONLY)
1127 report_wrongway_fh(gv, '>');
1128
1129 while (IoIFP(io)) {
1130 if (PerlIO_has_cntptr(IoIFP(io))) { /* (the code works without this) */
1131 if (PerlIO_get_cnt(IoIFP(io)) > 0) /* cheat a little, since */
1132 return FALSE; /* this is the most usual case */
1133 }
1134
1135 {
1136 /* getc and ungetc can stomp on errno */
1137 dSAVE_ERRNO;
1138 const int ch = PerlIO_getc(IoIFP(io));
1139 if (ch != EOF) {
1140 (void)PerlIO_ungetc(IoIFP(io),ch);
1141 RESTORE_ERRNO;
1142 return FALSE;
1143 }
1144 RESTORE_ERRNO;
1145 }
1146
1147 if (PerlIO_has_cntptr(IoIFP(io)) && PerlIO_canset_cnt(IoIFP(io))) {
1148 if (PerlIO_get_cnt(IoIFP(io)) < -1)
1149 PerlIO_set_cnt(IoIFP(io),-1);
1150 }
1151 if (PL_op->op_flags & OPf_SPECIAL) { /* not necessarily a real EOF yet? */
1152 if (gv != PL_argvgv || !nextargv(gv, FALSE)) /* get another fp handy */
1153 return TRUE;
1154 }
1155 else
1156 return TRUE; /* normal fp, definitely end of file */
1157 }
1158 return TRUE;
1159}
1160
1161Off_t
1162Perl_do_tell(pTHX_ GV *gv)
1163{
1164 IO *const io = GvIO(gv);
1165 PerlIO *fp;
1166
1167 PERL_ARGS_ASSERT_DO_TELL;
1168
1169 if (io && (fp = IoIFP(io))) {
1170 return PerlIO_tell(fp);
1171 }
1172 report_evil_fh(gv);
1173 SETERRNO(EBADF,RMS_IFI);
1174 return (Off_t)-1;
1175}
1176
1177bool
1178Perl_do_seek(pTHX_ GV *gv, Off_t pos, int whence)
1179{
1180 IO *const io = GvIO(gv);
1181 PerlIO *fp;
1182
1183 if (io && (fp = IoIFP(io))) {
1184 return PerlIO_seek(fp, pos, whence) >= 0;
1185 }
1186 report_evil_fh(gv);
1187 SETERRNO(EBADF,RMS_IFI);
1188 return FALSE;
1189}
1190
1191Off_t
1192Perl_do_sysseek(pTHX_ GV *gv, Off_t pos, int whence)
1193{
1194 IO *const io = GvIO(gv);
1195 PerlIO *fp;
1196
1197 PERL_ARGS_ASSERT_DO_SYSSEEK;
1198
1199 if (io && (fp = IoIFP(io))) {
1200 int fd = PerlIO_fileno(fp);
1201 if (fd >= 0) {
1202 return PerlLIO_lseek(fd, pos, whence);
1203 }
1204 }
1205 report_evil_fh(gv);
1206 SETERRNO(EBADF,RMS_IFI);
1207 return (Off_t)-1;
1208}
1209
1210int
1211Perl_mode_from_discipline(pTHX_ const char *s, STRLEN len)
1212{
1213 int mode = O_BINARY;
1214 PERL_UNUSED_CONTEXT;
1215 if (s) {
1216 while (*s) {
1217 if (*s == ':') {
1218 switch (s[1]) {
1219 case 'r':
1220 if (s[2] == 'a' && s[3] == 'w'
1221 && (!s[4] || s[4] == ':' || isSPACE(s[4])))
1222 {
1223 mode = O_BINARY;
1224 s += 4;
1225 len -= 4;
1226 break;
1227 }
1228 /* FALLTHROUGH */
1229 case 'c':
1230 if (s[2] == 'r' && s[3] == 'l' && s[4] == 'f'
1231 && (!s[5] || s[5] == ':' || isSPACE(s[5])))
1232 {
1233 mode = O_TEXT;
1234 s += 5;
1235 len -= 5;
1236 break;
1237 }
1238 /* FALLTHROUGH */
1239 default:
1240 goto fail_discipline;
1241 }
1242 }
1243 else if (isSPACE(*s)) {
1244 ++s;
1245 --len;
1246 }
1247 else {
1248 const char *end;
1249 fail_discipline:
1250 end = strchr(s+1, ':');
1251 if (!end)
1252 end = s+len;
1253#ifndef PERLIO_LAYERS
1254 Perl_croak(aTHX_ "IO layers (like '%.*s') unavailable", end-s, s);
1255#else
1256 len -= end-s;
1257 s = end;
1258#endif
1259 }
1260 }
1261 }
1262 return mode;
1263}
1264
1265#if !defined(HAS_TRUNCATE) && !defined(HAS_CHSIZE)
1266I32
1267my_chsize(int fd, Off_t length)
1268{
1269#ifdef F_FREESP
1270 /* code courtesy of William Kucharski */
1271#define HAS_CHSIZE
1272
1273 Stat_t filebuf;
1274
1275 if (PerlLIO_fstat(fd, &filebuf) < 0)
1276 return -1;
1277
1278 if (filebuf.st_size < length) {
1279
1280 /* extend file length */
1281
1282 if ((PerlLIO_lseek(fd, (length - 1), 0)) < 0)
1283 return -1;
1284
1285 /* write a "0" byte */
1286
1287 if ((PerlLIO_write(fd, "", 1)) != 1)
1288 return -1;
1289 }
1290 else {
1291 /* truncate length */
1292 struct flock fl;
1293 fl.l_whence = 0;
1294 fl.l_len = 0;
1295 fl.l_start = length;
1296 fl.l_type = F_WRLCK; /* write lock on file space */
1297
1298 /*
1299 * This relies on the UNDOCUMENTED F_FREESP argument to
1300 * fcntl(2), which truncates the file so that it ends at the
1301 * position indicated by fl.l_start.
1302 *
1303 * Will minor miracles never cease?
1304 */
1305
1306 if (fcntl(fd, F_FREESP, &fl) < 0)
1307 return -1;
1308
1309 }
1310 return 0;
1311#else
1312 Perl_croak_nocontext("truncate not implemented");
1313#endif /* F_FREESP */
1314 return -1;
1315}
1316#endif /* !HAS_TRUNCATE && !HAS_CHSIZE */
1317
1318bool
1319Perl_do_print(pTHX_ SV *sv, PerlIO *fp)
1320{
1321 PERL_ARGS_ASSERT_DO_PRINT;
1322
1323 /* assuming fp is checked earlier */
1324 if (!sv)
1325 return TRUE;
1326 if (SvTYPE(sv) == SVt_IV && SvIOK(sv)) {
1327 assert(!SvGMAGICAL(sv));
1328 if (SvIsUV(sv))
1329 PerlIO_printf(fp, "%"UVuf, (UV)SvUVX(sv));
1330 else
1331 PerlIO_printf(fp, "%"IVdf, (IV)SvIVX(sv));
1332 return !PerlIO_error(fp);
1333 }
1334 else {
1335 STRLEN len;
1336 /* Do this first to trigger any overloading. */
1337 const char *tmps = SvPV_const(sv, len);
1338 U8 *tmpbuf = NULL;
1339 bool happy = TRUE;
1340
1341 if (PerlIO_isutf8(fp)) { /* If the stream is utf8 ... */
1342 if (!SvUTF8(sv)) { /* Convert to utf8 if necessary */
1343 /* We don't modify the original scalar. */
1344 tmpbuf = bytes_to_utf8((const U8*) tmps, &len);
1345 tmps = (char *) tmpbuf;
1346 }
1347 else if (ckWARN4_d(WARN_UTF8, WARN_SURROGATE, WARN_NON_UNICODE, WARN_NONCHAR)) {
1348 (void) check_utf8_print((const U8*) tmps, len);
1349 }
1350 } /* else stream isn't utf8 */
1351 else if (DO_UTF8(sv)) { /* But if is utf8 internally, attempt to
1352 convert to bytes */
1353 STRLEN tmplen = len;
1354 bool utf8 = TRUE;
1355 U8 * const result = bytes_from_utf8((const U8*) tmps, &tmplen, &utf8);
1356 if (!utf8) {
1357
1358 /* Here, succeeded in downgrading from utf8. Set up to below
1359 * output the converted value */
1360 tmpbuf = result;
1361 tmps = (char *) tmpbuf;
1362 len = tmplen;
1363 }
1364 else { /* Non-utf8 output stream, but string only representable in
1365 utf8 */
1366 assert((char *)result == tmps);
1367 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1368 "Wide character in %s",
1369 PL_op ? OP_DESC(PL_op) : "print"
1370 );
1371 /* Could also check that isn't one of the things to avoid
1372 * in utf8 by using check_utf8_print(), but not doing so,
1373 * since the stream isn't a UTF8 stream */
1374 }
1375 }
1376 /* To detect whether the process is about to overstep its
1377 * filesize limit we would need getrlimit(). We could then
1378 * also transparently raise the limit with setrlimit() --
1379 * but only until the system hard limit/the filesystem limit,
1380 * at which we would get EPERM. Note that when using buffered
1381 * io the write failure can be delayed until the flush/close. --jhi */
1382 if (len && (PerlIO_write(fp,tmps,len) == 0))
1383 happy = FALSE;
1384 Safefree(tmpbuf);
1385 return happy ? !PerlIO_error(fp) : FALSE;
1386 }
1387}
1388
1389I32
1390Perl_my_stat_flags(pTHX_ const U32 flags)
1391{
1392 dSP;
1393 IO *io;
1394 GV* gv;
1395
1396 if (PL_op->op_flags & OPf_REF) {
1397 gv = cGVOP_gv;
1398 do_fstat:
1399 if (gv == PL_defgv)
1400 return PL_laststatval;
1401 io = GvIO(gv);
1402 do_fstat_have_io:
1403 PL_laststype = OP_STAT;
1404 PL_statgv = gv ? gv : (GV *)io;
1405 sv_setpvs(PL_statname, "");
1406 if (io) {
1407 if (IoIFP(io)) {
1408 int fd = PerlIO_fileno(IoIFP(io));
1409 if (fd < 0) {
1410 /* E.g. PerlIO::scalar has no real fd. */
1411 return (PL_laststatval = -1);
1412 } else {
1413 return (PL_laststatval = PerlLIO_fstat(fd, &PL_statcache));
1414 }
1415 } else if (IoDIRP(io)) {
1416 return (PL_laststatval = PerlLIO_fstat(my_dirfd(IoDIRP(io)), &PL_statcache));
1417 }
1418 }
1419 PL_laststatval = -1;
1420 report_evil_fh(gv);
1421 return -1;
1422 }
1423 else if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
1424 == OPpFT_STACKED)
1425 return PL_laststatval;
1426 else {
1427 SV* const sv = TOPs;
1428 const char *s;
1429 STRLEN len;
1430 if ((gv = MAYBE_DEREF_GV_flags(sv,flags))) {
1431 goto do_fstat;
1432 }
1433 else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
1434 io = MUTABLE_IO(SvRV(sv));
1435 gv = NULL;
1436 goto do_fstat_have_io;
1437 }
1438
1439 s = SvPV_flags_const(sv, len, flags);
1440 PL_statgv = NULL;
1441 sv_setpvn(PL_statname, s, len);
1442 s = SvPVX_const(PL_statname); /* s now NUL-terminated */
1443 PL_laststype = OP_STAT;
1444 PL_laststatval = PerlLIO_stat(s, &PL_statcache);
1445 if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(s)) {
1446 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
1447 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
1448 GCC_DIAG_RESTORE;
1449 }
1450 return PL_laststatval;
1451 }
1452}
1453
1454
1455I32
1456Perl_my_lstat_flags(pTHX_ const U32 flags)
1457{
1458 static const char* const no_prev_lstat = "The stat preceding -l _ wasn't an lstat";
1459 dSP;
1460 const char *file;
1461 SV* const sv = TOPs;
1462 bool isio = FALSE;
1463 if (PL_op->op_flags & OPf_REF) {
1464 if (cGVOP_gv == PL_defgv) {
1465 if (PL_laststype != OP_LSTAT)
1466 Perl_croak(aTHX_ "%s", no_prev_lstat);
1467 return PL_laststatval;
1468 }
1469 PL_laststatval = -1;
1470 if (ckWARN(WARN_IO)) {
1471 /* diag_listed_as: Use of -l on filehandle%s */
1472 Perl_warner(aTHX_ packWARN(WARN_IO),
1473 "Use of -l on filehandle %"HEKf,
1474 HEKfARG(GvENAME_HEK(cGVOP_gv)));
1475 }
1476 return -1;
1477 }
1478 if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
1479 == OPpFT_STACKED) {
1480 if (PL_laststype != OP_LSTAT)
1481 Perl_croak(aTHX_ "%s", no_prev_lstat);
1482 return PL_laststatval;
1483 }
1484
1485 PL_laststype = OP_LSTAT;
1486 PL_statgv = NULL;
1487 if ( ( (SvROK(sv) && ( isGV_with_GP(SvRV(sv))
1488 || (isio = SvTYPE(SvRV(sv)) == SVt_PVIO) )
1489 )
1490 || isGV_with_GP(sv)
1491 )
1492 && ckWARN(WARN_IO)) {
1493 if (isio)
1494 /* diag_listed_as: Use of -l on filehandle%s */
1495 Perl_warner(aTHX_ packWARN(WARN_IO),
1496 "Use of -l on filehandle");
1497 else
1498 /* diag_listed_as: Use of -l on filehandle%s */
1499 Perl_warner(aTHX_ packWARN(WARN_IO),
1500 "Use of -l on filehandle %"HEKf,
1501 HEKfARG(GvENAME_HEK((const GV *)
1502 (SvROK(sv) ? SvRV(sv) : sv))));
1503 }
1504 file = SvPV_flags_const_nolen(sv, flags);
1505 sv_setpv(PL_statname,file);
1506 PL_laststatval = PerlLIO_lstat(file,&PL_statcache);
1507 if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(file)) {
1508 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
1509 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "lstat");
1510 GCC_DIAG_RESTORE;
1511 }
1512 return PL_laststatval;
1513}
1514
1515static void
1516S_exec_failed(pTHX_ const char *cmd, int fd, int do_report)
1517{
1518 const int e = errno;
1519 PERL_ARGS_ASSERT_EXEC_FAILED;
1520 if (ckWARN(WARN_EXEC))
1521 Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't exec \"%s\": %s",
1522 cmd, Strerror(e));
1523 if (do_report) {
1524 /* XXX silently ignore failures */
1525 PERL_UNUSED_RESULT(PerlLIO_write(fd, (void*)&e, sizeof(int)));
1526 PerlLIO_close(fd);
1527 }
1528}
1529
1530bool
1531Perl_do_aexec5(pTHX_ SV *really, SV **mark, SV **sp,
1532 int fd, int do_report)
1533{
1534 dVAR;
1535 PERL_ARGS_ASSERT_DO_AEXEC5;
1536#if defined(__SYMBIAN32__) || defined(__LIBCATAMOUNT__)
1537 Perl_croak(aTHX_ "exec? I'm not *that* kind of operating system");
1538#else
1539 if (sp > mark) {
1540 const char **a;
1541 const char *tmps = NULL;
1542 Newx(PL_Argv, sp - mark + 1, const char*);
1543 a = PL_Argv;
1544
1545 while (++mark <= sp) {
1546 if (*mark)
1547 *a++ = SvPV_nolen_const(*mark);
1548 else
1549 *a++ = "";
1550 }
1551 *a = NULL;
1552 if (really)
1553 tmps = SvPV_nolen_const(really);
1554 if ((!really && *PL_Argv[0] != '/') ||
1555 (really && *tmps != '/')) /* will execvp use PATH? */
1556 TAINT_ENV(); /* testing IFS here is overkill, probably */
1557 PERL_FPU_PRE_EXEC
1558 if (really && *tmps)
1559 PerlProc_execvp(tmps,EXEC_ARGV_CAST(PL_Argv));
1560 else
1561 PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1562 PERL_FPU_POST_EXEC
1563 S_exec_failed(aTHX_ (really ? tmps : PL_Argv[0]), fd, do_report);
1564 }
1565 do_execfree();
1566#endif
1567 return FALSE;
1568}
1569
1570void
1571Perl_do_execfree(pTHX)
1572{
1573 Safefree(PL_Argv);
1574 PL_Argv = NULL;
1575 Safefree(PL_Cmd);
1576 PL_Cmd = NULL;
1577}
1578
1579#ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
1580
1581bool
1582Perl_do_exec3(pTHX_ const char *incmd, int fd, int do_report)
1583{
1584 dVAR;
1585 const char **a;
1586 char *s;
1587 char *buf;
1588 char *cmd;
1589 /* Make a copy so we can change it */
1590 const Size_t cmdlen = strlen(incmd) + 1;
1591
1592 PERL_ARGS_ASSERT_DO_EXEC3;
1593
1594 Newx(buf, cmdlen, char);
1595 cmd = buf;
1596 memcpy(cmd, incmd, cmdlen);
1597
1598 while (*cmd && isSPACE(*cmd))
1599 cmd++;
1600
1601 /* save an extra exec if possible */
1602
1603#ifdef CSH
1604 {
1605 char flags[PERL_FLAGS_MAX];
1606 if (strnEQ(cmd,PL_cshname,PL_cshlen) &&
1607 strnEQ(cmd+PL_cshlen," -c",3)) {
1608 my_strlcpy(flags, "-c", PERL_FLAGS_MAX);
1609 s = cmd+PL_cshlen+3;
1610 if (*s == 'f') {
1611 s++;
1612 my_strlcat(flags, "f", PERL_FLAGS_MAX - 2);
1613 }
1614 if (*s == ' ')
1615 s++;
1616 if (*s++ == '\'') {
1617 char * const ncmd = s;
1618
1619 while (*s)
1620 s++;
1621 if (s[-1] == '\n')
1622 *--s = '\0';
1623 if (s[-1] == '\'') {
1624 *--s = '\0';
1625 PERL_FPU_PRE_EXEC
1626 PerlProc_execl(PL_cshname, "csh", flags, ncmd, (char*)NULL);
1627 PERL_FPU_POST_EXEC
1628 *s = '\'';
1629 S_exec_failed(aTHX_ PL_cshname, fd, do_report);
1630 Safefree(buf);
1631 return FALSE;
1632 }
1633 }
1634 }
1635 }
1636#endif /* CSH */
1637
1638 /* see if there are shell metacharacters in it */
1639
1640 if (*cmd == '.' && isSPACE(cmd[1]))
1641 goto doshell;
1642
1643 if (strnEQ(cmd,"exec",4) && isSPACE(cmd[4]))
1644 goto doshell;
1645
1646 s = cmd;
1647 while (isWORDCHAR(*s))
1648 s++; /* catch VAR=val gizmo */
1649 if (*s == '=')
1650 goto doshell;
1651
1652 for (s = cmd; *s; s++) {
1653 if (*s != ' ' && !isALPHA(*s) &&
1654 strchr("$&*(){}[]'\";\\|?<>~`\n",*s)) {
1655 if (*s == '\n' && !s[1]) {
1656 *s = '\0';
1657 break;
1658 }
1659 /* handle the 2>&1 construct at the end */
1660 if (*s == '>' && s[1] == '&' && s[2] == '1'
1661 && s > cmd + 1 && s[-1] == '2' && isSPACE(s[-2])
1662 && (!s[3] || isSPACE(s[3])))
1663 {
1664 const char *t = s + 3;
1665
1666 while (*t && isSPACE(*t))
1667 ++t;
1668 if (!*t && (PerlLIO_dup2(1,2) != -1)) {
1669 s[-2] = '\0';
1670 break;
1671 }
1672 }
1673 doshell:
1674 PERL_FPU_PRE_EXEC
1675 PerlProc_execl(PL_sh_path, "sh", "-c", cmd, (char *)NULL);
1676 PERL_FPU_POST_EXEC
1677 S_exec_failed(aTHX_ PL_sh_path, fd, do_report);
1678 Safefree(buf);
1679 return FALSE;
1680 }
1681 }
1682
1683 Newx(PL_Argv, (s - cmd) / 2 + 2, const char*);
1684 PL_Cmd = savepvn(cmd, s-cmd);
1685 a = PL_Argv;
1686 for (s = PL_Cmd; *s;) {
1687 while (isSPACE(*s))
1688 s++;
1689 if (*s)
1690 *(a++) = s;
1691 while (*s && !isSPACE(*s))
1692 s++;
1693 if (*s)
1694 *s++ = '\0';
1695 }
1696 *a = NULL;
1697 if (PL_Argv[0]) {
1698 PERL_FPU_PRE_EXEC
1699 PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1700 PERL_FPU_POST_EXEC
1701 if (errno == ENOEXEC) { /* for system V NIH syndrome */
1702 do_execfree();
1703 goto doshell;
1704 }
1705 S_exec_failed(aTHX_ PL_Argv[0], fd, do_report);
1706 }
1707 do_execfree();
1708 Safefree(buf);
1709 return FALSE;
1710}
1711
1712#endif /* OS2 || WIN32 */
1713
1714#ifdef VMS
1715#include <starlet.h> /* for sys$delprc */
1716#endif
1717
1718I32
1719Perl_apply(pTHX_ I32 type, SV **mark, SV **sp)
1720{
1721 I32 val;
1722 I32 tot = 0;
1723 const char *const what = PL_op_name[type];
1724 const char *s;
1725 STRLEN len;
1726 SV ** const oldmark = mark;
1727 bool killgp = FALSE;
1728
1729 PERL_ARGS_ASSERT_APPLY;
1730
1731 PERL_UNUSED_VAR(what); /* may not be used depending on compile options */
1732
1733 /* Doing this ahead of the switch statement preserves the old behaviour,
1734 where attempting to use kill as a taint test test would fail on
1735 platforms where kill was not defined. */
1736#ifndef HAS_KILL
1737 if (type == OP_KILL)
1738 Perl_die(aTHX_ PL_no_func, what);
1739#endif
1740#ifndef HAS_CHOWN
1741 if (type == OP_CHOWN)
1742 Perl_die(aTHX_ PL_no_func, what);
1743#endif
1744
1745
1746#define APPLY_TAINT_PROPER() \
1747 STMT_START { \
1748 if (TAINT_get) { TAINT_PROPER(what); } \
1749 } STMT_END
1750
1751 /* This is a first heuristic; it doesn't catch tainting magic. */
1752 if (TAINTING_get) {
1753 while (++mark <= sp) {
1754 if (SvTAINTED(*mark)) {
1755 TAINT;
1756 break;
1757 }
1758 }
1759 mark = oldmark;
1760 }
1761 switch (type) {
1762 case OP_CHMOD:
1763 APPLY_TAINT_PROPER();
1764 if (++mark <= sp) {
1765 val = SvIV(*mark);
1766 APPLY_TAINT_PROPER();
1767 tot = sp - mark;
1768 while (++mark <= sp) {
1769 GV* gv;
1770 if ((gv = MAYBE_DEREF_GV(*mark))) {
1771 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1772#ifdef HAS_FCHMOD
1773 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
1774 APPLY_TAINT_PROPER();
1775 if (fd < 0) {
1776 SETERRNO(EBADF,RMS_IFI);
1777 tot--;
1778 } else if (fchmod(fd, val))
1779 tot--;
1780#else
1781 Perl_die(aTHX_ PL_no_func, "fchmod");
1782#endif
1783 }
1784 else {
1785 SETERRNO(EBADF,RMS_IFI);
1786 tot--;
1787 }
1788 }
1789 else {
1790 const char *name = SvPV_nomg_const(*mark, len);
1791 APPLY_TAINT_PROPER();
1792 if (!IS_SAFE_PATHNAME(name, len, "chmod") ||
1793 PerlLIO_chmod(name, val)) {
1794 tot--;
1795 }
1796 }
1797 }
1798 }
1799 break;
1800#ifdef HAS_CHOWN
1801 case OP_CHOWN:
1802 APPLY_TAINT_PROPER();
1803 if (sp - mark > 2) {
1804 I32 val2;
1805 val = SvIVx(*++mark);
1806 val2 = SvIVx(*++mark);
1807 APPLY_TAINT_PROPER();
1808 tot = sp - mark;
1809 while (++mark <= sp) {
1810 GV* gv;
1811 if ((gv = MAYBE_DEREF_GV(*mark))) {
1812 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1813#ifdef HAS_FCHOWN
1814 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
1815 APPLY_TAINT_PROPER();
1816 if (fd < 0) {
1817 SETERRNO(EBADF,RMS_IFI);
1818 tot--;
1819 } else if (fchown(fd, val, val2))
1820 tot--;
1821#else
1822 Perl_die(aTHX_ PL_no_func, "fchown");
1823#endif
1824 }
1825 else {
1826 SETERRNO(EBADF,RMS_IFI);
1827 tot--;
1828 }
1829 }
1830 else {
1831 const char *name = SvPV_nomg_const(*mark, len);
1832 APPLY_TAINT_PROPER();
1833 if (!IS_SAFE_PATHNAME(name, len, "chown") ||
1834 PerlLIO_chown(name, val, val2)) {
1835 tot--;
1836 }
1837 }
1838 }
1839 }
1840 break;
1841#endif
1842/*
1843XXX Should we make lchown() directly available from perl?
1844For now, we'll let Configure test for HAS_LCHOWN, but do
1845nothing in the core.
1846 --AD 5/1998
1847*/
1848#ifdef HAS_KILL
1849 case OP_KILL:
1850 APPLY_TAINT_PROPER();
1851 if (mark == sp)
1852 break;
1853 s = SvPVx_const(*++mark, len);
1854 if (*s == '-' && isALPHA(s[1]))
1855 {
1856 s++;
1857 len--;
1858 killgp = TRUE;
1859 }
1860 if (isALPHA(*s)) {
1861 if (*s == 'S' && s[1] == 'I' && s[2] == 'G') {
1862 s += 3;
1863 len -= 3;
1864 }
1865 if ((val = whichsig_pvn(s, len)) < 0)
1866 Perl_croak(aTHX_ "Unrecognized signal name \"%"SVf"\"", SVfARG(*mark));
1867 }
1868 else
1869 {
1870 val = SvIV(*mark);
1871 if (val < 0)
1872 {
1873 killgp = TRUE;
1874 val = -val;
1875 }
1876 }
1877 APPLY_TAINT_PROPER();
1878 tot = sp - mark;
1879#ifdef VMS
1880 /* kill() doesn't do process groups (job trees?) under VMS */
1881 if (val == SIGKILL) {
1882 /* Use native sys$delprc() to insure that target process is
1883 * deleted; supervisor-mode images don't pay attention to
1884 * CRTL's emulation of Unix-style signals and kill()
1885 */
1886 while (++mark <= sp) {
1887 I32 proc;
1888 unsigned long int __vmssts;
1889 SvGETMAGIC(*mark);
1890 if (!(SvIOK(*mark) || SvNOK(*mark) || looks_like_number(*mark)))
1891 Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
1892 proc = SvIV_nomg(*mark);
1893 APPLY_TAINT_PROPER();
1894 if (!((__vmssts = sys$delprc(&proc,0)) & 1)) {
1895 tot--;
1896 switch (__vmssts) {
1897 case SS$_NONEXPR:
1898 case SS$_NOSUCHNODE:
1899 SETERRNO(ESRCH,__vmssts);
1900 break;
1901 case SS$_NOPRIV:
1902 SETERRNO(EPERM,__vmssts);
1903 break;
1904 default:
1905 SETERRNO(EVMSERR,__vmssts);
1906 }
1907 }
1908 }
1909 PERL_ASYNC_CHECK();
1910 break;
1911 }
1912#endif
1913 while (++mark <= sp) {
1914 Pid_t proc;
1915 SvGETMAGIC(*mark);
1916 if (!(SvNIOK(*mark) || looks_like_number(*mark)))
1917 Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
1918 proc = SvIV_nomg(*mark);
1919 APPLY_TAINT_PROPER();
1920#ifdef HAS_KILLPG
1921 /* use killpg in preference, as the killpg() wrapper for Win32
1922 * understands process groups, but the kill() wrapper doesn't */
1923 if (killgp ? PerlProc_killpg(proc, val)
1924 : PerlProc_kill(proc, val))
1925#else
1926 if (PerlProc_kill(killgp ? -proc: proc, val))
1927#endif
1928 tot--;
1929 }
1930 PERL_ASYNC_CHECK();
1931 break;
1932#endif
1933 case OP_UNLINK:
1934 APPLY_TAINT_PROPER();
1935 tot = sp - mark;
1936 while (++mark <= sp) {
1937 s = SvPV_const(*mark, len);
1938 APPLY_TAINT_PROPER();
1939 if (!IS_SAFE_PATHNAME(s, len, "unlink")) {
1940 tot--;
1941 }
1942 else if (PL_unsafe) {
1943 if (UNLINK(s))
1944 tot--;
1945 }
1946 else { /* don't let root wipe out directories without -U */
1947 if (PerlLIO_lstat(s,&PL_statbuf) < 0)
1948 tot--;
1949 else if (S_ISDIR(PL_statbuf.st_mode)) {
1950 tot--;
1951 SETERRNO(EISDIR, SS_NOPRIV);
1952 }
1953 else {
1954 if (UNLINK(s))
1955 tot--;
1956 }
1957 }
1958 }
1959 break;
1960#if defined(HAS_UTIME) || defined(HAS_FUTIMES)
1961 case OP_UTIME:
1962 APPLY_TAINT_PROPER();
1963 if (sp - mark > 2) {
1964#if defined(HAS_FUTIMES)
1965 struct timeval utbuf[2];
1966 void *utbufp = utbuf;
1967#elif defined(I_UTIME) || defined(VMS)
1968 struct utimbuf utbuf;
1969 struct utimbuf *utbufp = &utbuf;
1970#else
1971 struct {
1972 Time_t actime;
1973 Time_t modtime;
1974 } utbuf;
1975 void *utbufp = &utbuf;
1976#endif
1977
1978 SV* const accessed = *++mark;
1979 SV* const modified = *++mark;
1980
1981 /* Be like C, and if both times are undefined, let the C
1982 * library figure out what to do. This usually means
1983 * "current time". */
1984
1985 if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1986 utbufp = NULL;
1987 else {
1988 Zero(&utbuf, sizeof utbuf, char);
1989#ifdef HAS_FUTIMES
1990 utbuf[0].tv_sec = (long)SvIV(accessed); /* time accessed */
1991 utbuf[0].tv_usec = 0;
1992 utbuf[1].tv_sec = (long)SvIV(modified); /* time modified */
1993 utbuf[1].tv_usec = 0;
1994#elif defined(BIG_TIME)
1995 utbuf.actime = (Time_t)SvNV(accessed); /* time accessed */
1996 utbuf.modtime = (Time_t)SvNV(modified); /* time modified */
1997#else
1998 utbuf.actime = (Time_t)SvIV(accessed); /* time accessed */
1999 utbuf.modtime = (Time_t)SvIV(modified); /* time modified */
2000#endif
2001 }
2002 APPLY_TAINT_PROPER();
2003 tot = sp - mark;
2004 while (++mark <= sp) {
2005 GV* gv;
2006 if ((gv = MAYBE_DEREF_GV(*mark))) {
2007 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
2008#ifdef HAS_FUTIMES
2009 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
2010 APPLY_TAINT_PROPER();
2011 if (fd < 0) {
2012 SETERRNO(EBADF,RMS_IFI);
2013 tot--;
2014 } else if (futimes(fd, (struct timeval *) utbufp))
2015 tot--;
2016#else
2017 Perl_die(aTHX_ PL_no_func, "futimes");
2018#endif
2019 }
2020 else {
2021 tot--;
2022 }
2023 }
2024 else {
2025 const char * const name = SvPV_nomg_const(*mark, len);
2026 APPLY_TAINT_PROPER();
2027 if (!IS_SAFE_PATHNAME(name, len, "utime")) {
2028 tot--;
2029 }
2030 else
2031#ifdef HAS_FUTIMES
2032 if (utimes(name, (struct timeval *)utbufp))
2033#else
2034 if (PerlLIO_utime(name, utbufp))
2035#endif
2036 tot--;
2037 }
2038
2039 }
2040 }
2041 else
2042 tot = 0;
2043 break;
2044#endif
2045 }
2046 return tot;
2047
2048#undef APPLY_TAINT_PROPER
2049}
2050
2051/* Do the permissions allow some operation? Assumes statcache already set. */
2052#ifndef VMS /* VMS' cando is in vms.c */
2053bool
2054Perl_cando(pTHX_ Mode_t mode, bool effective, const Stat_t *statbufp)
2055/* effective is a flag, true for EUID, or for checking if the effective gid
2056 * is in the list of groups returned from getgroups().
2057 */
2058{
2059 PERL_ARGS_ASSERT_CANDO;
2060 PERL_UNUSED_CONTEXT;
2061
2062#ifdef DOSISH
2063 /* [Comments and code from Len Reed]
2064 * MS-DOS "user" is similar to UNIX's "superuser," but can't write
2065 * to write-protected files. The execute permission bit is set
2066 * by the Microsoft C library stat() function for the following:
2067 * .exe files
2068 * .com files
2069 * .bat files
2070 * directories
2071 * All files and directories are readable.
2072 * Directories and special files, e.g. "CON", cannot be
2073 * write-protected.
2074 * [Comment by Tom Dinger -- a directory can have the write-protect
2075 * bit set in the file system, but DOS permits changes to
2076 * the directory anyway. In addition, all bets are off
2077 * here for networked software, such as Novell and
2078 * Sun's PC-NFS.]
2079 */
2080
2081 /* Atari stat() does pretty much the same thing. we set x_bit_set_in_stat
2082 * too so it will actually look into the files for magic numbers
2083 */
2084 return (mode & statbufp->st_mode) ? TRUE : FALSE;
2085
2086#else /* ! DOSISH */
2087# ifdef __CYGWIN__
2088 if (ingroup(544,effective)) { /* member of Administrators */
2089# else
2090 if ((effective ? PerlProc_geteuid() : PerlProc_getuid()) == 0) { /* root is special */
2091# endif
2092 if (mode == S_IXUSR) {
2093 if (statbufp->st_mode & 0111 || S_ISDIR(statbufp->st_mode))
2094 return TRUE;
2095 }
2096 else
2097 return TRUE; /* root reads and writes anything */
2098 return FALSE;
2099 }
2100 if (statbufp->st_uid == (effective ? PerlProc_geteuid() : PerlProc_getuid()) ) {
2101 if (statbufp->st_mode & mode)
2102 return TRUE; /* ok as "user" */
2103 }
2104 else if (ingroup(statbufp->st_gid,effective)) {
2105 if (statbufp->st_mode & mode >> 3)
2106 return TRUE; /* ok as "group" */
2107 }
2108 else if (statbufp->st_mode & mode >> 6)
2109 return TRUE; /* ok as "other" */
2110 return FALSE;
2111#endif /* ! DOSISH */
2112}
2113#endif /* ! VMS */
2114
2115static bool
2116S_ingroup(pTHX_ Gid_t testgid, bool effective)
2117{
2118#ifndef PERL_IMPLICIT_SYS
2119 /* PERL_IMPLICIT_SYS like Win32: getegid() etc. require the context. */
2120 PERL_UNUSED_CONTEXT;
2121#endif
2122 if (testgid == (effective ? PerlProc_getegid() : PerlProc_getgid()))
2123 return TRUE;
2124#ifdef HAS_GETGROUPS
2125 {
2126 Groups_t *gary = NULL;
2127 I32 anum;
2128 bool rc = FALSE;
2129
2130 anum = getgroups(0, gary);
2131 if (anum > 0) {
2132 Newx(gary, anum, Groups_t);
2133 anum = getgroups(anum, gary);
2134 while (--anum >= 0)
2135 if (gary[anum] == testgid) {
2136 rc = TRUE;
2137 break;
2138 }
2139
2140 Safefree(gary);
2141 }
2142 return rc;
2143 }
2144#else
2145 return FALSE;
2146#endif
2147}
2148
2149#if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
2150
2151I32
2152Perl_do_ipcget(pTHX_ I32 optype, SV **mark, SV **sp)
2153{
2154 const key_t key = (key_t)SvNVx(*++mark);
2155 SV *nsv = optype == OP_MSGGET ? NULL : *++mark;
2156 const I32 flags = SvIVx(*++mark);
2157
2158 PERL_ARGS_ASSERT_DO_IPCGET;
2159 PERL_UNUSED_ARG(sp);
2160
2161 SETERRNO(0,0);
2162 switch (optype)
2163 {
2164#ifdef HAS_MSG
2165 case OP_MSGGET:
2166 return msgget(key, flags);
2167#endif
2168#ifdef HAS_SEM
2169 case OP_SEMGET:
2170 return semget(key, (int) SvIV(nsv), flags);
2171#endif
2172#ifdef HAS_SHM
2173 case OP_SHMGET:
2174 return shmget(key, (size_t) SvUV(nsv), flags);
2175#endif
2176#if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2177 default:
2178 /* diag_listed_as: msg%s not implemented */
2179 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2180#endif
2181 }
2182 return -1; /* should never happen */
2183}
2184
2185I32
2186Perl_do_ipcctl(pTHX_ I32 optype, SV **mark, SV **sp)
2187{
2188 char *a;
2189 I32 ret = -1;
2190 const I32 id = SvIVx(*++mark);
2191#ifdef Semctl
2192 const I32 n = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
2193#endif
2194 const I32 cmd = SvIVx(*++mark);
2195 SV * const astr = *++mark;
2196 STRLEN infosize = 0;
2197 I32 getinfo = (cmd == IPC_STAT);
2198
2199 PERL_ARGS_ASSERT_DO_IPCCTL;
2200 PERL_UNUSED_ARG(sp);
2201
2202 switch (optype)
2203 {
2204#ifdef HAS_MSG
2205 case OP_MSGCTL:
2206 if (cmd == IPC_STAT || cmd == IPC_SET)
2207 infosize = sizeof(struct msqid_ds);
2208 break;
2209#endif
2210#ifdef HAS_SHM
2211 case OP_SHMCTL:
2212 if (cmd == IPC_STAT || cmd == IPC_SET)
2213 infosize = sizeof(struct shmid_ds);
2214 break;
2215#endif
2216#ifdef HAS_SEM
2217 case OP_SEMCTL:
2218#ifdef Semctl
2219 if (cmd == IPC_STAT || cmd == IPC_SET)
2220 infosize = sizeof(struct semid_ds);
2221 else if (cmd == GETALL || cmd == SETALL)
2222 {
2223 struct semid_ds semds;
2224 union semun semun;
2225#ifdef EXTRA_F_IN_SEMUN_BUF
2226 semun.buff = &semds;
2227#else
2228 semun.buf = &semds;
2229#endif
2230 getinfo = (cmd == GETALL);
2231 if (Semctl(id, 0, IPC_STAT, semun) == -1)
2232 return -1;
2233 infosize = semds.sem_nsems * sizeof(short);
2234 /* "short" is technically wrong but much more portable
2235 than guessing about u_?short(_t)? */
2236 }
2237#else
2238 /* diag_listed_as: sem%s not implemented */
2239 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2240#endif
2241 break;
2242#endif
2243#if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2244 default:
2245 /* diag_listed_as: shm%s not implemented */
2246 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2247#endif
2248 }
2249
2250 if (infosize)
2251 {
2252 if (getinfo)
2253 {
2254 SvPV_force_nolen(astr);
2255 a = SvGROW(astr, infosize+1);
2256 }
2257 else
2258 {
2259 STRLEN len;
2260 a = SvPV(astr, len);
2261 if (len != infosize)
2262 Perl_croak(aTHX_ "Bad arg length for %s, is %lu, should be %ld",
2263 PL_op_desc[optype],
2264 (unsigned long)len,
2265 (long)infosize);
2266 }
2267 }
2268 else
2269 {
2270 const IV i = SvIV(astr);
2271 a = INT2PTR(char *,i); /* ouch */
2272 }
2273 SETERRNO(0,0);
2274 switch (optype)
2275 {
2276#ifdef HAS_MSG
2277 case OP_MSGCTL:
2278 ret = msgctl(id, cmd, (struct msqid_ds *)a);
2279 break;
2280#endif
2281#ifdef HAS_SEM
2282 case OP_SEMCTL: {
2283#ifdef Semctl
2284 union semun unsemds;
2285
2286 if(cmd == SETVAL) {
2287 unsemds.val = PTR2nat(a);
2288 }
2289 else {
2290#ifdef EXTRA_F_IN_SEMUN_BUF
2291 unsemds.buff = (struct semid_ds *)a;
2292#else
2293 unsemds.buf = (struct semid_ds *)a;
2294#endif
2295 }
2296 ret = Semctl(id, n, cmd, unsemds);
2297#else
2298 /* diag_listed_as: sem%s not implemented */
2299 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2300#endif
2301 }
2302 break;
2303#endif
2304#ifdef HAS_SHM
2305 case OP_SHMCTL:
2306 ret = shmctl(id, cmd, (struct shmid_ds *)a);
2307 break;
2308#endif
2309 }
2310 if (getinfo && ret >= 0) {
2311 SvCUR_set(astr, infosize);
2312 *SvEND(astr) = '\0';
2313 SvSETMAGIC(astr);
2314 }
2315 return ret;
2316}
2317
2318I32
2319Perl_do_msgsnd(pTHX_ SV **mark, SV **sp)
2320{
2321#ifdef HAS_MSG
2322 STRLEN len;
2323 const I32 id = SvIVx(*++mark);
2324 SV * const mstr = *++mark;
2325 const I32 flags = SvIVx(*++mark);
2326 const char * const mbuf = SvPV_const(mstr, len);
2327 const I32 msize = len - sizeof(long);
2328
2329 PERL_ARGS_ASSERT_DO_MSGSND;
2330 PERL_UNUSED_ARG(sp);
2331
2332 if (msize < 0)
2333 Perl_croak(aTHX_ "Arg too short for msgsnd");
2334 SETERRNO(0,0);
2335 return msgsnd(id, (struct msgbuf *)mbuf, msize, flags);
2336#else
2337 PERL_UNUSED_ARG(sp);
2338 PERL_UNUSED_ARG(mark);
2339 /* diag_listed_as: msg%s not implemented */
2340 Perl_croak(aTHX_ "msgsnd not implemented");
2341 return -1;
2342#endif
2343}
2344
2345I32
2346Perl_do_msgrcv(pTHX_ SV **mark, SV **sp)
2347{
2348#ifdef HAS_MSG
2349 char *mbuf;
2350 long mtype;
2351 I32 msize, flags, ret;
2352 const I32 id = SvIVx(*++mark);
2353 SV * const mstr = *++mark;
2354
2355 PERL_ARGS_ASSERT_DO_MSGRCV;
2356 PERL_UNUSED_ARG(sp);
2357
2358 /* suppress warning when reading into undef var --jhi */
2359 if (! SvOK(mstr))
2360 sv_setpvs(mstr, "");
2361 msize = SvIVx(*++mark);
2362 mtype = (long)SvIVx(*++mark);
2363 flags = SvIVx(*++mark);
2364 SvPV_force_nolen(mstr);
2365 mbuf = SvGROW(mstr, sizeof(long)+msize+1);
2366
2367 SETERRNO(0,0);
2368 ret = msgrcv(id, (struct msgbuf *)mbuf, msize, mtype, flags);
2369 if (ret >= 0) {
2370 SvCUR_set(mstr, sizeof(long)+ret);
2371 *SvEND(mstr) = '\0';
2372 /* who knows who has been playing with this message? */
2373 SvTAINTED_on(mstr);
2374 }
2375 return ret;
2376#else
2377 PERL_UNUSED_ARG(sp);
2378 PERL_UNUSED_ARG(mark);
2379 /* diag_listed_as: msg%s not implemented */
2380 Perl_croak(aTHX_ "msgrcv not implemented");
2381 return -1;
2382#endif
2383}
2384
2385I32
2386Perl_do_semop(pTHX_ SV **mark, SV **sp)
2387{
2388#ifdef HAS_SEM
2389 STRLEN opsize;
2390 const I32 id = SvIVx(*++mark);
2391 SV * const opstr = *++mark;
2392 const char * const opbuf = SvPV_const(opstr, opsize);
2393
2394 PERL_ARGS_ASSERT_DO_SEMOP;
2395 PERL_UNUSED_ARG(sp);
2396
2397 if (opsize < 3 * SHORTSIZE
2398 || (opsize % (3 * SHORTSIZE))) {
2399 SETERRNO(EINVAL,LIB_INVARG);
2400 return -1;
2401 }
2402 SETERRNO(0,0);
2403 /* We can't assume that sizeof(struct sembuf) == 3 * sizeof(short). */
2404 {
2405 const int nsops = opsize / (3 * sizeof (short));
2406 int i = nsops;
2407 short * const ops = (short *) opbuf;
2408 short *o = ops;
2409 struct sembuf *temps, *t;
2410 I32 result;
2411
2412 Newx (temps, nsops, struct sembuf);
2413 t = temps;
2414 while (i--) {
2415 t->sem_num = *o++;
2416 t->sem_op = *o++;
2417 t->sem_flg = *o++;
2418 t++;
2419 }
2420 result = semop(id, temps, nsops);
2421 Safefree(temps);
2422 return result;
2423 }
2424#else
2425 /* diag_listed_as: sem%s not implemented */
2426 Perl_croak(aTHX_ "semop not implemented");
2427#endif
2428}
2429
2430I32
2431Perl_do_shmio(pTHX_ I32 optype, SV **mark, SV **sp)
2432{
2433#ifdef HAS_SHM
2434 char *shm;
2435 struct shmid_ds shmds;
2436 const I32 id = SvIVx(*++mark);
2437 SV * const mstr = *++mark;
2438 const I32 mpos = SvIVx(*++mark);
2439 const I32 msize = SvIVx(*++mark);
2440
2441 PERL_ARGS_ASSERT_DO_SHMIO;
2442 PERL_UNUSED_ARG(sp);
2443
2444 SETERRNO(0,0);
2445 if (shmctl(id, IPC_STAT, &shmds) == -1)
2446 return -1;
2447 if (mpos < 0 || msize < 0
2448 || (size_t)mpos + msize > (size_t)shmds.shm_segsz) {
2449 SETERRNO(EFAULT,SS_ACCVIO); /* can't do as caller requested */
2450 return -1;
2451 }
2452 shm = (char *)shmat(id, NULL, (optype == OP_SHMREAD) ? SHM_RDONLY : 0);
2453 if (shm == (char *)-1) /* I hate System V IPC, I really do */
2454 return -1;
2455 if (optype == OP_SHMREAD) {
2456 char *mbuf;
2457 /* suppress warning when reading into undef var (tchrist 3/Mar/00) */
2458 SvGETMAGIC(mstr);
2459 SvUPGRADE(mstr, SVt_PV);
2460 if (! SvOK(mstr))
2461 sv_setpvs(mstr, "");
2462 SvPOK_only(mstr);
2463 mbuf = SvGROW(mstr, (STRLEN)msize+1);
2464
2465 Copy(shm + mpos, mbuf, msize, char);
2466 SvCUR_set(mstr, msize);
2467 *SvEND(mstr) = '\0';
2468 SvSETMAGIC(mstr);
2469 /* who knows who has been playing with this shared memory? */
2470 SvTAINTED_on(mstr);
2471 }
2472 else {
2473 STRLEN len;
2474
2475 const char *mbuf = SvPV_const(mstr, len);
2476 const I32 n = ((I32)len > msize) ? msize : (I32)len;
2477 Copy(mbuf, shm + mpos, n, char);
2478 if (n < msize)
2479 memzero(shm + mpos + n, msize - n);
2480 }
2481 return shmdt(shm);
2482#else
2483 /* diag_listed_as: shm%s not implemented */
2484 Perl_croak(aTHX_ "shm I/O not implemented");
2485 return -1;
2486#endif
2487}
2488
2489#endif /* SYSV IPC */
2490
2491/*
2492=head1 IO Functions
2493
2494=for apidoc start_glob
2495
2496Function called by C<do_readline> to spawn a glob (or do the glob inside
2497perl on VMS). This code used to be inline, but now perl uses C<File::Glob>
2498this glob starter is only used by miniperl during the build process.
2499Moving it away shrinks pp_hot.c; shrinking pp_hot.c helps speed perl up.
2500
2501=cut
2502*/
2503
2504PerlIO *
2505Perl_start_glob (pTHX_ SV *tmpglob, IO *io)
2506{
2507 SV * const tmpcmd = newSV(0);
2508 PerlIO *fp;
2509 STRLEN len;
2510 const char *s = SvPV(tmpglob, len);
2511
2512 PERL_ARGS_ASSERT_START_GLOB;
2513
2514 if (!IS_SAFE_SYSCALL(s, len, "pattern", "glob"))
2515 return NULL;
2516
2517 ENTER;
2518 SAVEFREESV(tmpcmd);
2519#ifdef VMS /* expand the wildcards right here, rather than opening a pipe, */
2520 /* since spawning off a process is a real performance hit */
2521
2522PerlIO *
2523Perl_vms_start_glob
2524 (pTHX_ SV *tmpglob,
2525 IO *io);
2526
2527 fp = Perl_vms_start_glob(aTHX_ tmpglob, io);
2528
2529#else /* !VMS */
2530#ifdef DOSISH
2531#ifdef OS2
2532 sv_setpv(tmpcmd, "for a in ");
2533 sv_catsv(tmpcmd, tmpglob);
2534 sv_catpv(tmpcmd, "; do echo \"$a\\0\\c\"; done |");
2535#else
2536#ifdef DJGPP
2537 sv_setpv(tmpcmd, "/dev/dosglob/"); /* File System Extension */
2538 sv_catsv(tmpcmd, tmpglob);
2539#else
2540 sv_setpv(tmpcmd, "perlglob ");
2541 sv_catsv(tmpcmd, tmpglob);
2542 sv_catpv(tmpcmd, " |");
2543#endif /* !DJGPP */
2544#endif /* !OS2 */
2545#else /* !DOSISH */
2546#if defined(CSH)
2547 sv_setpvn(tmpcmd, PL_cshname, PL_cshlen);
2548 sv_catpv(tmpcmd, " -cf 'set nonomatch; glob ");
2549 sv_catsv(tmpcmd, tmpglob);
2550 sv_catpv(tmpcmd, "' 2>/dev/null |");
2551#else
2552 sv_setpv(tmpcmd, "echo ");
2553 sv_catsv(tmpcmd, tmpglob);
2554 sv_catpv(tmpcmd, "|tr -s ' \t\f\r' '\\n\\n\\n\\n'|");
2555#endif /* !CSH */
2556#endif /* !DOSISH */
2557 {
2558 GV * const envgv = gv_fetchpvs("ENV", 0, SVt_PVHV);
2559 SV ** const home = hv_fetchs(GvHV(envgv), "HOME", 0);
2560 SV ** const path = hv_fetchs(GvHV(envgv), "PATH", 0);
2561 if (home && *home) SvGETMAGIC(*home);
2562 if (path && *path) SvGETMAGIC(*path);
2563 save_hash(gv_fetchpvs("ENV", 0, SVt_PVHV));
2564 if (home && *home) SvSETMAGIC(*home);
2565 if (path && *path) SvSETMAGIC(*path);
2566 }
2567 (void)do_open6(PL_last_in_gv, SvPVX_const(tmpcmd), SvCUR(tmpcmd),
2568 NULL, NULL, 0);
2569 fp = IoIFP(io);
2570#endif /* !VMS */
2571 LEAVE;
2572
2573 if (!fp && ckWARN(WARN_GLOB)) {
2574 Perl_warner(aTHX_ packWARN(WARN_GLOB), "glob failed (can't start child: %s)",
2575 Strerror(errno));
2576 }
2577
2578 return fp;
2579}
2580
2581/*
2582 * Local variables:
2583 * c-indentation-style: bsd
2584 * c-basic-offset: 4
2585 * indent-tabs-mode: nil
2586 * End:
2587 *
2588 * ex: set ts=8 sts=4 sw=4 et:
2589 */