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