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