Consting and localizing: Part LXVIII
[p5sagit/p5-mst-13.2.git] / pp_sys.c
1 /*    pp_sys.c
2  *
3  *    Copyright (C) 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * But only a short way ahead its floor and the walls on either side were
13  * cloven by a great fissure, out of which the red glare came, now leaping
14  * up, now dying down into darkness; and all the while far below there was
15  * a rumour and a trouble as of great engines throbbing and labouring.
16  */
17
18 /* This file contains system pp ("push/pop") functions that
19  * execute the opcodes that make up a perl program. A typical pp function
20  * expects to find its arguments on the stack, and usually pushes its
21  * results onto the stack, hence the 'pp' terminology. Each OP structure
22  * contains a pointer to the relevant pp_foo() function.
23  *
24  * By 'system', we mean ops which interact with the OS, such as pp_open().
25  */
26
27 #include "EXTERN.h"
28 #define PERL_IN_PP_SYS_C
29 #include "perl.h"
30
31 #ifdef I_SHADOW
32 /* Shadow password support for solaris - pdo@cs.umd.edu
33  * Not just Solaris: at least HP-UX, IRIX, Linux.
34  * The API is from SysV.
35  *
36  * There are at least two more shadow interfaces,
37  * see the comments in pp_gpwent().
38  *
39  * --jhi */
40 #   ifdef __hpux__
41 /* There is a MAXINT coming from <shadow.h> <- <hpsecurity.h> <- <values.h>
42  * and another MAXINT from "perl.h" <- <sys/param.h>. */
43 #       undef MAXINT
44 #   endif
45 #   include <shadow.h>
46 #endif
47
48 #ifdef I_SYS_WAIT
49 # include <sys/wait.h>
50 #endif
51
52 #ifdef I_SYS_RESOURCE
53 # include <sys/resource.h>
54 #endif
55
56 #ifdef NETWARE
57 NETDB_DEFINE_CONTEXT
58 #endif
59
60 #ifdef HAS_SELECT
61 # ifdef I_SYS_SELECT
62 #  include <sys/select.h>
63 # endif
64 #endif
65
66 /* XXX Configure test needed.
67    h_errno might not be a simple 'int', especially for multi-threaded
68    applications, see "extern int errno in perl.h".  Creating such
69    a test requires taking into account the differences between
70    compiling multithreaded and singlethreaded ($ccflags et al).
71    HOST_NOT_FOUND is typically defined in <netdb.h>.
72 */
73 #if defined(HOST_NOT_FOUND) && !defined(h_errno) && !defined(__CYGWIN__)
74 extern int h_errno;
75 #endif
76
77 #ifdef HAS_PASSWD
78 # ifdef I_PWD
79 #  include <pwd.h>
80 # else
81 #  if !defined(VMS)
82     struct passwd *getpwnam (char *);
83     struct passwd *getpwuid (Uid_t);
84 #  endif
85 # endif
86 # ifdef HAS_GETPWENT
87 #ifndef getpwent
88   struct passwd *getpwent (void);
89 #elif defined (VMS) && defined (my_getpwent)
90   struct passwd *Perl_my_getpwent (pTHX);
91 #endif
92 # endif
93 #endif
94
95 #ifdef HAS_GROUP
96 # ifdef I_GRP
97 #  include <grp.h>
98 # else
99     struct group *getgrnam (char *);
100     struct group *getgrgid (Gid_t);
101 # endif
102 # ifdef HAS_GETGRENT
103 #ifndef getgrent
104     struct group *getgrent (void);
105 #endif
106 # endif
107 #endif
108
109 #ifdef I_UTIME
110 #  if defined(_MSC_VER) || defined(__MINGW32__)
111 #    include <sys/utime.h>
112 #  else
113 #    include <utime.h>
114 #  endif
115 #endif
116
117 #ifdef HAS_CHSIZE
118 # ifdef my_chsize  /* Probably #defined to Perl_my_chsize in embed.h */
119 #   undef my_chsize
120 # endif
121 # define my_chsize PerlLIO_chsize
122 #else
123 # ifdef HAS_TRUNCATE
124 #   define my_chsize PerlLIO_chsize
125 # else
126 I32 my_chsize(int fd, Off_t length);
127 # endif
128 #endif
129
130 #ifdef HAS_FLOCK
131 #  define FLOCK flock
132 #else /* no flock() */
133
134    /* fcntl.h might not have been included, even if it exists, because
135       the current Configure only sets I_FCNTL if it's needed to pick up
136       the *_OK constants.  Make sure it has been included before testing
137       the fcntl() locking constants. */
138 #  if defined(HAS_FCNTL) && !defined(I_FCNTL)
139 #    include <fcntl.h>
140 #  endif
141
142 #  if defined(HAS_FCNTL) && defined(FCNTL_CAN_LOCK)
143 #    define FLOCK fcntl_emulate_flock
144 #    define FCNTL_EMULATE_FLOCK
145 #  else /* no flock() or fcntl(F_SETLK,...) */
146 #    ifdef HAS_LOCKF
147 #      define FLOCK lockf_emulate_flock
148 #      define LOCKF_EMULATE_FLOCK
149 #    endif /* lockf */
150 #  endif /* no flock() or fcntl(F_SETLK,...) */
151
152 #  ifdef FLOCK
153      static int FLOCK (int, int);
154
155     /*
156      * These are the flock() constants.  Since this sytems doesn't have
157      * flock(), the values of the constants are probably not available.
158      */
159 #    ifndef LOCK_SH
160 #      define LOCK_SH 1
161 #    endif
162 #    ifndef LOCK_EX
163 #      define LOCK_EX 2
164 #    endif
165 #    ifndef LOCK_NB
166 #      define LOCK_NB 4
167 #    endif
168 #    ifndef LOCK_UN
169 #      define LOCK_UN 8
170 #    endif
171 #  endif /* emulating flock() */
172
173 #endif /* no flock() */
174
175 #define ZBTLEN 10
176 static const char zero_but_true[ZBTLEN + 1] = "0 but true";
177
178 #if defined(I_SYS_ACCESS) && !defined(R_OK)
179 #  include <sys/access.h>
180 #endif
181
182 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
183 #  define FD_CLOEXEC 1          /* NeXT needs this */
184 #endif
185
186 #include "reentr.h"
187
188 #ifdef __Lynx__
189 /* Missing protos on LynxOS */
190 void sethostent(int);
191 void endhostent(void);
192 void setnetent(int);
193 void endnetent(void);
194 void setprotoent(int);
195 void endprotoent(void);
196 void setservent(int);
197 void endservent(void);
198 #endif
199
200 #undef PERL_EFF_ACCESS  /* EFFective uid/gid ACCESS */
201
202 /* AIX 5.2 and below use mktime for localtime, and defines the edge case
203  * for time 0x7fffffff to be valid only in UTC. AIX 5.3 provides localtime64
204  * available in the 32bit environment, which could warrant Configure
205  * checks in the future.
206  */
207 #ifdef  _AIX
208 #define LOCALTIME_EDGECASE_BROKEN
209 #endif
210
211 /* F_OK unused: if stat() cannot find it... */
212
213 #if !defined(PERL_EFF_ACCESS) && defined(HAS_ACCESS) && defined(EFF_ONLY_OK) && !defined(NO_EFF_ONLY_OK)
214     /* Digital UNIX (when the EFF_ONLY_OK gets fixed), UnixWare */
215 #   define PERL_EFF_ACCESS(p,f) (access((p), (f) | EFF_ONLY_OK))
216 #endif
217
218 #if !defined(PERL_EFF_ACCESS) && defined(HAS_EACCESS)
219 #   ifdef I_SYS_SECURITY
220 #       include <sys/security.h>
221 #   endif
222 #   ifdef ACC_SELF
223         /* HP SecureWare */
224 #       define PERL_EFF_ACCESS(p,f) (eaccess((p), (f), ACC_SELF))
225 #   else
226         /* SCO */
227 #       define PERL_EFF_ACCESS(p,f) (eaccess((p), (f)))
228 #   endif
229 #endif
230
231 #if !defined(PERL_EFF_ACCESS) && defined(HAS_ACCESSX) && defined(ACC_SELF)
232     /* AIX */
233 #   define PERL_EFF_ACCESS(p,f) (accessx((p), (f), ACC_SELF))
234 #endif
235
236
237 #if !defined(PERL_EFF_ACCESS) && defined(HAS_ACCESS)    \
238     && (defined(HAS_SETREUID) || defined(HAS_SETRESUID)         \
239         || defined(HAS_SETREGID) || defined(HAS_SETRESGID))
240 /* The Hard Way. */
241 STATIC int
242 S_emulate_eaccess(pTHX_ const char* path, Mode_t mode)
243 {
244     const Uid_t ruid = getuid();
245     const Uid_t euid = geteuid();
246     const Gid_t rgid = getgid();
247     const Gid_t egid = getegid();
248     int res;
249
250     LOCK_CRED_MUTEX;
251 #if !defined(HAS_SETREUID) && !defined(HAS_SETRESUID)
252     Perl_croak(aTHX_ "switching effective uid is not implemented");
253 #else
254 #ifdef HAS_SETREUID
255     if (setreuid(euid, ruid))
256 #else
257 #ifdef HAS_SETRESUID
258     if (setresuid(euid, ruid, (Uid_t)-1))
259 #endif
260 #endif
261         Perl_croak(aTHX_ "entering effective uid failed");
262 #endif
263
264 #if !defined(HAS_SETREGID) && !defined(HAS_SETRESGID)
265     Perl_croak(aTHX_ "switching effective gid is not implemented");
266 #else
267 #ifdef HAS_SETREGID
268     if (setregid(egid, rgid))
269 #else
270 #ifdef HAS_SETRESGID
271     if (setresgid(egid, rgid, (Gid_t)-1))
272 #endif
273 #endif
274         Perl_croak(aTHX_ "entering effective gid failed");
275 #endif
276
277     res = access(path, mode);
278
279 #ifdef HAS_SETREUID
280     if (setreuid(ruid, euid))
281 #else
282 #ifdef HAS_SETRESUID
283     if (setresuid(ruid, euid, (Uid_t)-1))
284 #endif
285 #endif
286         Perl_croak(aTHX_ "leaving effective uid failed");
287
288 #ifdef HAS_SETREGID
289     if (setregid(rgid, egid))
290 #else
291 #ifdef HAS_SETRESGID
292     if (setresgid(rgid, egid, (Gid_t)-1))
293 #endif
294 #endif
295         Perl_croak(aTHX_ "leaving effective gid failed");
296     UNLOCK_CRED_MUTEX;
297
298     return res;
299 }
300 #   define PERL_EFF_ACCESS(p,f) (emulate_eaccess((p), (f)))
301 #endif
302
303 #if !defined(PERL_EFF_ACCESS)
304 /* With it or without it: anyway you get a warning: either that
305    it is unused, or it is declared static and never defined.
306  */
307 STATIC int
308 S_emulate_eaccess(pTHX_ const char* path, Mode_t mode)
309 {
310     (void)path;
311     (void)mode;
312     Perl_croak(aTHX_ "switching effective uid is not implemented");
313     /*NOTREACHED*/
314     return -1;
315 }
316 #endif
317
318 PP(pp_backtick)
319 {
320     dSP; dTARGET;
321     PerlIO *fp;
322     const char * const tmps = POPpconstx;
323     const I32 gimme = GIMME_V;
324     const char *mode = "r";
325
326     TAINT_PROPER("``");
327     if (PL_op->op_private & OPpOPEN_IN_RAW)
328         mode = "rb";
329     else if (PL_op->op_private & OPpOPEN_IN_CRLF)
330         mode = "rt";
331     fp = PerlProc_popen(tmps, mode);
332     if (fp) {
333         const char * const type = PL_curcop->cop_io ? SvPV_nolen_const(PL_curcop->cop_io) : NULL;
334         if (type && *type)
335             PerlIO_apply_layers(aTHX_ fp,mode,type);
336
337         if (gimme == G_VOID) {
338             char tmpbuf[256];
339             while (PerlIO_read(fp, tmpbuf, sizeof tmpbuf) > 0)
340                 ;
341         }
342         else if (gimme == G_SCALAR) {
343             ENTER;
344             SAVESPTR(PL_rs);
345             PL_rs = &PL_sv_undef;
346             sv_setpvn(TARG, "", 0);     /* note that this preserves previous buffer */
347             while (sv_gets(TARG, fp, SvCUR(TARG)) != Nullch)
348                 ;
349             LEAVE;
350             XPUSHs(TARG);
351             SvTAINTED_on(TARG);
352         }
353         else {
354             for (;;) {
355                 SV * const sv = NEWSV(56, 79);
356                 if (sv_gets(sv, fp, 0) == Nullch) {
357                     SvREFCNT_dec(sv);
358                     break;
359                 }
360                 XPUSHs(sv_2mortal(sv));
361                 if (SvLEN(sv) - SvCUR(sv) > 20) {
362                     SvPV_shrink_to_cur(sv);
363                 }
364                 SvTAINTED_on(sv);
365             }
366         }
367         STATUS_NATIVE_CHILD_SET(PerlProc_pclose(fp));
368         TAINT;          /* "I believe that this is not gratuitous!" */
369     }
370     else {
371         STATUS_NATIVE_CHILD_SET(-1);
372         if (gimme == G_SCALAR)
373             RETPUSHUNDEF;
374     }
375
376     RETURN;
377 }
378
379 PP(pp_glob)
380 {
381     dVAR;
382     OP *result;
383     tryAMAGICunTARGET(iter, -1);
384
385     /* Note that we only ever get here if File::Glob fails to load
386      * without at the same time croaking, for some reason, or if
387      * perl was built with PERL_EXTERNAL_GLOB */
388
389     ENTER;
390
391 #ifndef VMS
392     if (PL_tainting) {
393         /*
394          * The external globbing program may use things we can't control,
395          * so for security reasons we must assume the worst.
396          */
397         TAINT;
398         taint_proper(PL_no_security, "glob");
399     }
400 #endif /* !VMS */
401
402     SAVESPTR(PL_last_in_gv);    /* We don't want this to be permanent. */
403     PL_last_in_gv = (GV*)*PL_stack_sp--;
404
405     SAVESPTR(PL_rs);            /* This is not permanent, either. */
406     PL_rs = sv_2mortal(newSVpvn("\000", 1));
407 #ifndef DOSISH
408 #ifndef CSH
409     *SvPVX(PL_rs) = '\n';
410 #endif  /* !CSH */
411 #endif  /* !DOSISH */
412
413     result = do_readline();
414     LEAVE;
415     return result;
416 }
417
418 PP(pp_rcatline)
419 {
420     PL_last_in_gv = cGVOP_gv;
421     return do_readline();
422 }
423
424 PP(pp_warn)
425 {
426     dSP; dMARK;
427     SV *tmpsv;
428     const char *tmps;
429     STRLEN len;
430     if (SP - MARK > 1) {
431         dTARGET;
432         do_join(TARG, &PL_sv_no, MARK, SP);
433         tmpsv = TARG;
434         SP = MARK + 1;
435     }
436     else if (SP == MARK) {
437         tmpsv = &PL_sv_no;
438         EXTEND(SP, 1);
439     }
440     else {
441         tmpsv = TOPs;
442     }
443     tmps = SvPV_const(tmpsv, len);
444     if ((!tmps || !len) && PL_errgv) {
445         SV * const error = ERRSV;
446         SvUPGRADE(error, SVt_PV);
447         if (SvPOK(error) && SvCUR(error))
448             sv_catpv(error, "\t...caught");
449         tmpsv = error;
450         tmps = SvPV_const(tmpsv, len);
451     }
452     if (!tmps || !len)
453         tmpsv = sv_2mortal(newSVpvn("Warning: something's wrong", 26));
454
455     Perl_warn(aTHX_ "%"SVf, tmpsv);
456     RETSETYES;
457 }
458
459 PP(pp_die)
460 {
461     dSP; dMARK;
462     const char *tmps;
463     SV *tmpsv;
464     STRLEN len;
465     bool multiarg = 0;
466 #ifdef VMS
467     VMSISH_HUSHED  = VMSISH_HUSHED || (PL_op->op_private & OPpHUSH_VMSISH);
468 #endif
469     if (SP - MARK != 1) {
470         dTARGET;
471         do_join(TARG, &PL_sv_no, MARK, SP);
472         tmpsv = TARG;
473         tmps = SvPV_const(tmpsv, len);
474         multiarg = 1;
475         SP = MARK + 1;
476     }
477     else {
478         tmpsv = TOPs;
479         tmps = SvROK(tmpsv) ? Nullch : SvPV_const(tmpsv, len);
480     }
481     if (!tmps || !len) {
482         SV *error = ERRSV;
483         SvUPGRADE(error, SVt_PV);
484         if (multiarg ? SvROK(error) : SvROK(tmpsv)) {
485             if (!multiarg)
486                 SvSetSV(error,tmpsv);
487             else if (sv_isobject(error)) {
488                 HV * const stash = SvSTASH(SvRV(error));
489                 GV * const gv = gv_fetchmethod(stash, "PROPAGATE");
490                 if (gv) {
491                     SV * const file = sv_2mortal(newSVpv(CopFILE(PL_curcop),0));
492                     SV * const line = sv_2mortal(newSVuv(CopLINE(PL_curcop)));
493                     EXTEND(SP, 3);
494                     PUSHMARK(SP);
495                     PUSHs(error);
496                     PUSHs(file);
497                     PUSHs(line);
498                     PUTBACK;
499                     call_sv((SV*)GvCV(gv),
500                             G_SCALAR|G_EVAL|G_KEEPERR);
501                     sv_setsv(error,*PL_stack_sp--);
502                 }
503             }
504             DIE(aTHX_ Nullch);
505         }
506         else {
507             if (SvPOK(error) && SvCUR(error))
508                 sv_catpv(error, "\t...propagated");
509             tmpsv = error;
510             if (SvOK(tmpsv))
511                 tmps = SvPV_const(tmpsv, len);
512             else
513                 tmps = Nullch;
514         }
515     }
516     if (!tmps || !len)
517         tmpsv = sv_2mortal(newSVpvn("Died", 4));
518
519     DIE(aTHX_ "%"SVf, tmpsv);
520 }
521
522 /* I/O. */
523
524 PP(pp_open)
525 {
526     dVAR; dSP;
527     dMARK; dORIGMARK;
528     dTARGET;
529     SV *sv;
530     IO *io;
531     const char *tmps;
532     STRLEN len;
533     bool  ok;
534
535     GV * const gv = (GV *)*++MARK;
536
537     if (!isGV(gv))
538         DIE(aTHX_ PL_no_usym, "filehandle");
539     if ((io = GvIOp(gv)))
540         IoFLAGS(GvIOp(gv)) &= ~IOf_UNTAINT;
541
542     if (io) {
543         MAGIC * const mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar);
544         if (mg) {
545             /* Method's args are same as ours ... */
546             /* ... except handle is replaced by the object */
547             *MARK-- = SvTIED_obj((SV*)io, mg);
548             PUSHMARK(MARK);
549             PUTBACK;
550             ENTER;
551             call_method("OPEN", G_SCALAR);
552             LEAVE;
553             SPAGAIN;
554             RETURN;
555         }
556     }
557
558     if (MARK < SP) {
559         sv = *++MARK;
560     }
561     else {
562         sv = GvSVn(gv);
563     }
564
565     tmps = SvPV_const(sv, len);
566     ok = do_openn(gv, tmps, len, FALSE, O_RDONLY, 0, Nullfp, MARK+1, (SP-MARK));
567     SP = ORIGMARK;
568     if (ok)
569         PUSHi( (I32)PL_forkprocess );
570     else if (PL_forkprocess == 0)               /* we are a new child */
571         PUSHi(0);
572     else
573         RETPUSHUNDEF;
574     RETURN;
575 }
576
577 PP(pp_close)
578 {
579     dVAR; dSP;
580     IO *io;
581     MAGIC *mg;
582     GV * const gv = (MAXARG == 0) ? PL_defoutgv : (GV*)POPs;
583
584     if (gv && (io = GvIO(gv))
585         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
586     {
587         PUSHMARK(SP);
588         XPUSHs(SvTIED_obj((SV*)io, mg));
589         PUTBACK;
590         ENTER;
591         call_method("CLOSE", G_SCALAR);
592         LEAVE;
593         SPAGAIN;
594         RETURN;
595     }
596     EXTEND(SP, 1);
597     PUSHs(boolSV(do_close(gv, TRUE)));
598     RETURN;
599 }
600
601 PP(pp_pipe_op)
602 {
603 #ifdef HAS_PIPE
604     dSP;
605     register IO *rstio;
606     register IO *wstio;
607     int fd[2];
608
609     GV * const wgv = (GV*)POPs;
610     GV * const rgv = (GV*)POPs;
611
612     if (!rgv || !wgv)
613         goto badexit;
614
615     if (SvTYPE(rgv) != SVt_PVGV || SvTYPE(wgv) != SVt_PVGV)
616         DIE(aTHX_ PL_no_usym, "filehandle");
617     rstio = GvIOn(rgv);
618     wstio = GvIOn(wgv);
619
620     if (IoIFP(rstio))
621         do_close(rgv, FALSE);
622     if (IoIFP(wstio))
623         do_close(wgv, FALSE);
624
625     if (PerlProc_pipe(fd) < 0)
626         goto badexit;
627
628     IoIFP(rstio) = PerlIO_fdopen(fd[0], "r"PIPE_OPEN_MODE);
629     IoOFP(wstio) = PerlIO_fdopen(fd[1], "w"PIPE_OPEN_MODE);
630     IoOFP(rstio) = IoIFP(rstio);
631     IoIFP(wstio) = IoOFP(wstio);
632     IoTYPE(rstio) = IoTYPE_RDONLY;
633     IoTYPE(wstio) = IoTYPE_WRONLY;
634
635     if (!IoIFP(rstio) || !IoOFP(wstio)) {
636         if (IoIFP(rstio)) PerlIO_close(IoIFP(rstio));
637         else PerlLIO_close(fd[0]);
638         if (IoOFP(wstio)) PerlIO_close(IoOFP(wstio));
639         else PerlLIO_close(fd[1]);
640         goto badexit;
641     }
642 #if defined(HAS_FCNTL) && defined(F_SETFD)
643     fcntl(fd[0],F_SETFD,fd[0] > PL_maxsysfd);   /* ensure close-on-exec */
644     fcntl(fd[1],F_SETFD,fd[1] > PL_maxsysfd);   /* ensure close-on-exec */
645 #endif
646     RETPUSHYES;
647
648 badexit:
649     RETPUSHUNDEF;
650 #else
651     DIE(aTHX_ PL_no_func, "pipe");
652 #endif
653 }
654
655 PP(pp_fileno)
656 {
657     dVAR; dSP; dTARGET;
658     GV *gv;
659     IO *io;
660     PerlIO *fp;
661     MAGIC  *mg;
662
663     if (MAXARG < 1)
664         RETPUSHUNDEF;
665     gv = (GV*)POPs;
666
667     if (gv && (io = GvIO(gv))
668         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
669     {
670         PUSHMARK(SP);
671         XPUSHs(SvTIED_obj((SV*)io, mg));
672         PUTBACK;
673         ENTER;
674         call_method("FILENO", G_SCALAR);
675         LEAVE;
676         SPAGAIN;
677         RETURN;
678     }
679
680     if (!gv || !(io = GvIO(gv)) || !(fp = IoIFP(io))) {
681         /* Can't do this because people seem to do things like
682            defined(fileno($foo)) to check whether $foo is a valid fh.
683           if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
684               report_evil_fh(gv, io, PL_op->op_type);
685             */
686         RETPUSHUNDEF;
687     }
688
689     PUSHi(PerlIO_fileno(fp));
690     RETURN;
691 }
692
693 PP(pp_umask)
694 {
695     dSP;
696 #ifdef HAS_UMASK
697     dTARGET;
698     Mode_t anum;
699
700     if (MAXARG < 1) {
701         anum = PerlLIO_umask(0);
702         (void)PerlLIO_umask(anum);
703     }
704     else
705         anum = PerlLIO_umask(POPi);
706     TAINT_PROPER("umask");
707     XPUSHi(anum);
708 #else
709     /* Only DIE if trying to restrict permissions on "user" (self).
710      * Otherwise it's harmless and more useful to just return undef
711      * since 'group' and 'other' concepts probably don't exist here. */
712     if (MAXARG >= 1 && (POPi & 0700))
713         DIE(aTHX_ "umask not implemented");
714     XPUSHs(&PL_sv_undef);
715 #endif
716     RETURN;
717 }
718
719 PP(pp_binmode)
720 {
721     dVAR; dSP;
722     GV *gv;
723     IO *io;
724     PerlIO *fp;
725     MAGIC *mg;
726     SV *discp = Nullsv;
727
728     if (MAXARG < 1)
729         RETPUSHUNDEF;
730     if (MAXARG > 1) {
731         discp = POPs;
732     }
733
734     gv = (GV*)POPs;
735
736     if (gv && (io = GvIO(gv))
737         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
738     {
739         PUSHMARK(SP);
740         XPUSHs(SvTIED_obj((SV*)io, mg));
741         if (discp)
742             XPUSHs(discp);
743         PUTBACK;
744         ENTER;
745         call_method("BINMODE", G_SCALAR);
746         LEAVE;
747         SPAGAIN;
748         RETURN;
749     }
750
751     EXTEND(SP, 1);
752     if (!(io = GvIO(gv)) || !(fp = IoIFP(io))) {
753         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
754             report_evil_fh(gv, io, PL_op->op_type);
755         SETERRNO(EBADF,RMS_IFI);
756         RETPUSHUNDEF;
757     }
758
759     PUTBACK;
760     if (PerlIO_binmode(aTHX_ fp,IoTYPE(io),mode_from_discipline(discp),
761                        (discp) ? SvPV_nolen_const(discp) : Nullch)) {
762         if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {
763              if (!PerlIO_binmode(aTHX_ IoOFP(io),IoTYPE(io),
764                         mode_from_discipline(discp),
765                        (discp) ? SvPV_nolen_const(discp) : Nullch)) {
766                 SPAGAIN;
767                 RETPUSHUNDEF;
768              }
769         }
770         SPAGAIN;
771         RETPUSHYES;
772     }
773     else {
774         SPAGAIN;
775         RETPUSHUNDEF;
776     }
777 }
778
779 PP(pp_tie)
780 {
781     dVAR; dSP; dMARK;
782     HV* stash;
783     GV *gv;
784     SV *sv;
785     const I32 markoff = MARK - PL_stack_base;
786     const char *methname;
787     int how = PERL_MAGIC_tied;
788     U32 items;
789     SV *varsv = *++MARK;
790
791     switch(SvTYPE(varsv)) {
792         case SVt_PVHV:
793             methname = "TIEHASH";
794             HvEITER_set((HV *)varsv, 0);
795             break;
796         case SVt_PVAV:
797             methname = "TIEARRAY";
798             break;
799         case SVt_PVGV:
800 #ifdef GV_UNIQUE_CHECK
801             if (GvUNIQUE((GV*)varsv)) {
802                 Perl_croak(aTHX_ "Attempt to tie unique GV");
803             }
804 #endif
805             methname = "TIEHANDLE";
806             how = PERL_MAGIC_tiedscalar;
807             /* For tied filehandles, we apply tiedscalar magic to the IO
808                slot of the GP rather than the GV itself. AMS 20010812 */
809             if (!GvIOp(varsv))
810                 GvIOp(varsv) = newIO();
811             varsv = (SV *)GvIOp(varsv);
812             break;
813         default:
814             methname = "TIESCALAR";
815             how = PERL_MAGIC_tiedscalar;
816             break;
817     }
818     items = SP - MARK++;
819     if (sv_isobject(*MARK)) {
820         ENTER;
821         PUSHSTACKi(PERLSI_MAGIC);
822         PUSHMARK(SP);
823         EXTEND(SP,(I32)items);
824         while (items--)
825             PUSHs(*MARK++);
826         PUTBACK;
827         call_method(methname, G_SCALAR);
828     }
829     else {
830         /* Not clear why we don't call call_method here too.
831          * perhaps to get different error message ?
832          */
833         stash = gv_stashsv(*MARK, FALSE);
834         if (!stash || !(gv = gv_fetchmethod(stash, methname))) {
835             DIE(aTHX_ "Can't locate object method \"%s\" via package \"%"SVf"\"",
836                  methname, *MARK);
837         }
838         ENTER;
839         PUSHSTACKi(PERLSI_MAGIC);
840         PUSHMARK(SP);
841         EXTEND(SP,(I32)items);
842         while (items--)
843             PUSHs(*MARK++);
844         PUTBACK;
845         call_sv((SV*)GvCV(gv), G_SCALAR);
846     }
847     SPAGAIN;
848
849     sv = TOPs;
850     POPSTACK;
851     if (sv_isobject(sv)) {
852         sv_unmagic(varsv, how);
853         /* Croak if a self-tie on an aggregate is attempted. */
854         if (varsv == SvRV(sv) &&
855             (SvTYPE(varsv) == SVt_PVAV ||
856              SvTYPE(varsv) == SVt_PVHV))
857             Perl_croak(aTHX_
858                        "Self-ties of arrays and hashes are not supported");
859         sv_magic(varsv, (SvRV(sv) == varsv ? Nullsv : sv), how, Nullch, 0);
860     }
861     LEAVE;
862     SP = PL_stack_base + markoff;
863     PUSHs(sv);
864     RETURN;
865 }
866
867 PP(pp_untie)
868 {
869     dVAR; dSP;
870     MAGIC *mg;
871     SV *sv = POPs;
872     const char how = (SvTYPE(sv) == SVt_PVHV || SvTYPE(sv) == SVt_PVAV)
873                 ? PERL_MAGIC_tied : PERL_MAGIC_tiedscalar;
874
875     if (SvTYPE(sv) == SVt_PVGV && !(sv = (SV *)GvIOp(sv)))
876         RETPUSHYES;
877
878     if ((mg = SvTIED_mg(sv, how))) {
879         SV * const obj = SvRV(SvTIED_obj(sv, mg));
880         CV *cv;
881         if (obj) {
882             GV * const gv = gv_fetchmethod_autoload(SvSTASH(obj), "UNTIE", FALSE);
883             if (gv && isGV(gv) && (cv = GvCV(gv))) {
884                PUSHMARK(SP);
885                XPUSHs(SvTIED_obj((SV*)gv, mg));
886                XPUSHs(sv_2mortal(newSViv(SvREFCNT(obj)-1)));
887                PUTBACK;
888                ENTER;
889                call_sv((SV *)cv, G_VOID);
890                LEAVE;
891                SPAGAIN;
892             }
893             else if (mg && SvREFCNT(obj) > 1 && ckWARN(WARN_UNTIE)) {
894                   Perl_warner(aTHX_ packWARN(WARN_UNTIE),
895                       "untie attempted while %"UVuf" inner references still exist",
896                        (UV)SvREFCNT(obj) - 1 ) ;
897             }
898         }
899     }
900     sv_unmagic(sv, how) ;
901     RETPUSHYES;
902 }
903
904 PP(pp_tied)
905 {
906     dSP;
907     const MAGIC *mg;
908     SV *sv = POPs;
909     const char how = (SvTYPE(sv) == SVt_PVHV || SvTYPE(sv) == SVt_PVAV)
910                 ? PERL_MAGIC_tied : PERL_MAGIC_tiedscalar;
911
912     if (SvTYPE(sv) == SVt_PVGV && !(sv = (SV *)GvIOp(sv)))
913         RETPUSHUNDEF;
914
915     if ((mg = SvTIED_mg(sv, how))) {
916         SV *osv = SvTIED_obj(sv, mg);
917         if (osv == mg->mg_obj)
918             osv = sv_mortalcopy(osv);
919         PUSHs(osv);
920         RETURN;
921     }
922     RETPUSHUNDEF;
923 }
924
925 PP(pp_dbmopen)
926 {
927     dVAR; dSP;
928     dPOPPOPssrl;
929     HV* stash;
930     GV *gv;
931
932     HV * const hv = (HV*)POPs;
933     SV * const sv = sv_mortalcopy(&PL_sv_no);
934
935     sv_setpv(sv, "AnyDBM_File");
936     stash = gv_stashsv(sv, FALSE);
937     if (!stash || !(gv = gv_fetchmethod(stash, "TIEHASH"))) {
938         PUTBACK;
939         require_pv("AnyDBM_File.pm");
940         SPAGAIN;
941         if (!(gv = gv_fetchmethod(stash, "TIEHASH")))
942             DIE(aTHX_ "No dbm on this machine");
943     }
944
945     ENTER;
946     PUSHMARK(SP);
947
948     EXTEND(SP, 5);
949     PUSHs(sv);
950     PUSHs(left);
951     if (SvIV(right))
952         PUSHs(sv_2mortal(newSVuv(O_RDWR|O_CREAT)));
953     else
954         PUSHs(sv_2mortal(newSVuv(O_RDWR)));
955     PUSHs(right);
956     PUTBACK;
957     call_sv((SV*)GvCV(gv), G_SCALAR);
958     SPAGAIN;
959
960     if (!sv_isobject(TOPs)) {
961         SP--;
962         PUSHMARK(SP);
963         PUSHs(sv);
964         PUSHs(left);
965         PUSHs(sv_2mortal(newSVuv(O_RDONLY)));
966         PUSHs(right);
967         PUTBACK;
968         call_sv((SV*)GvCV(gv), G_SCALAR);
969         SPAGAIN;
970     }
971
972     if (sv_isobject(TOPs)) {
973         sv_unmagic((SV *) hv, PERL_MAGIC_tied);
974         sv_magic((SV*)hv, TOPs, PERL_MAGIC_tied, Nullch, 0);
975     }
976     LEAVE;
977     RETURN;
978 }
979
980 PP(pp_sselect)
981 {
982 #ifdef HAS_SELECT
983     dSP; dTARGET;
984     register I32 i;
985     register I32 j;
986     register char *s;
987     register SV *sv;
988     NV value;
989     I32 maxlen = 0;
990     I32 nfound;
991     struct timeval timebuf;
992     struct timeval *tbuf = &timebuf;
993     I32 growsize;
994     char *fd_sets[4];
995 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
996         I32 masksize;
997         I32 offset;
998         I32 k;
999
1000 #   if BYTEORDER & 0xf0000
1001 #       define ORDERBYTE (0x88888888 - BYTEORDER)
1002 #   else
1003 #       define ORDERBYTE (0x4444 - BYTEORDER)
1004 #   endif
1005
1006 #endif
1007
1008     SP -= 4;
1009     for (i = 1; i <= 3; i++) {
1010         SV * const sv = SP[i];
1011         if (!SvOK(sv))
1012             continue;
1013         if (SvREADONLY(sv)) {
1014             if (SvIsCOW(sv))
1015                 sv_force_normal_flags(sv, 0);
1016             if (SvREADONLY(sv) && !(SvPOK(sv) && SvCUR(sv) == 0))
1017                 DIE(aTHX_ PL_no_modify);
1018         }
1019         if (!SvPOK(sv)) {
1020             if (ckWARN(WARN_MISC))
1021                 Perl_warner(aTHX_ packWARN(WARN_MISC), "Non-string passed as bitmask");
1022             SvPV_force_nolen(sv);       /* force string conversion */
1023         }
1024         j = SvCUR(sv);
1025         if (maxlen < j)
1026             maxlen = j;
1027     }
1028
1029 /* little endians can use vecs directly */
1030 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
1031 #  ifdef NFDBITS
1032
1033 #    ifndef NBBY
1034 #     define NBBY 8
1035 #    endif
1036
1037     masksize = NFDBITS / NBBY;
1038 #  else
1039     masksize = sizeof(long);    /* documented int, everyone seems to use long */
1040 #  endif
1041     Zero(&fd_sets[0], 4, char*);
1042 #endif
1043
1044 #  if SELECT_MIN_BITS == 1
1045     growsize = sizeof(fd_set);
1046 #  else
1047 #   if defined(__GLIBC__) && defined(__FD_SETSIZE)
1048 #      undef SELECT_MIN_BITS
1049 #      define SELECT_MIN_BITS __FD_SETSIZE
1050 #   endif
1051     /* If SELECT_MIN_BITS is greater than one we most probably will want
1052      * to align the sizes with SELECT_MIN_BITS/8 because for example
1053      * in many little-endian (Intel, Alpha) systems (Linux, OS/2, Digital
1054      * UNIX, Solaris, NeXT, Darwin) the smallest quantum select() operates
1055      * on (sets/tests/clears bits) is 32 bits.  */
1056     growsize = maxlen + (SELECT_MIN_BITS/8 - (maxlen % (SELECT_MIN_BITS/8)));
1057 #  endif
1058
1059     sv = SP[4];
1060     if (SvOK(sv)) {
1061         value = SvNV(sv);
1062         if (value < 0.0)
1063             value = 0.0;
1064         timebuf.tv_sec = (long)value;
1065         value -= (NV)timebuf.tv_sec;
1066         timebuf.tv_usec = (long)(value * 1000000.0);
1067     }
1068     else
1069         tbuf = Null(struct timeval*);
1070
1071     for (i = 1; i <= 3; i++) {
1072         sv = SP[i];
1073         if (!SvOK(sv) || SvCUR(sv) == 0) {
1074             fd_sets[i] = 0;
1075             continue;
1076         }
1077         assert(SvPOK(sv));
1078         j = SvLEN(sv);
1079         if (j < growsize) {
1080             Sv_Grow(sv, growsize);
1081         }
1082         j = SvCUR(sv);
1083         s = SvPVX(sv) + j;
1084         while (++j <= growsize) {
1085             *s++ = '\0';
1086         }
1087
1088 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
1089         s = SvPVX(sv);
1090         Newx(fd_sets[i], growsize, char);
1091         for (offset = 0; offset < growsize; offset += masksize) {
1092             for (j = 0, k=ORDERBYTE; j < masksize; j++, (k >>= 4))
1093                 fd_sets[i][j+offset] = s[(k % masksize) + offset];
1094         }
1095 #else
1096         fd_sets[i] = SvPVX(sv);
1097 #endif
1098     }
1099
1100 #ifdef PERL_IRIX5_SELECT_TIMEVAL_VOID_CAST
1101     /* Can't make just the (void*) conditional because that would be
1102      * cpp #if within cpp macro, and not all compilers like that. */
1103     nfound = PerlSock_select(
1104         maxlen * 8,
1105         (Select_fd_set_t) fd_sets[1],
1106         (Select_fd_set_t) fd_sets[2],
1107         (Select_fd_set_t) fd_sets[3],
1108         (void*) tbuf); /* Workaround for compiler bug. */
1109 #else
1110     nfound = PerlSock_select(
1111         maxlen * 8,
1112         (Select_fd_set_t) fd_sets[1],
1113         (Select_fd_set_t) fd_sets[2],
1114         (Select_fd_set_t) fd_sets[3],
1115         tbuf);
1116 #endif
1117     for (i = 1; i <= 3; i++) {
1118         if (fd_sets[i]) {
1119             sv = SP[i];
1120 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
1121             s = SvPVX(sv);
1122             for (offset = 0; offset < growsize; offset += masksize) {
1123                 for (j = 0, k=ORDERBYTE; j < masksize; j++, (k >>= 4))
1124                     s[(k % masksize) + offset] = fd_sets[i][j+offset];
1125             }
1126             Safefree(fd_sets[i]);
1127 #endif
1128             SvSETMAGIC(sv);
1129         }
1130     }
1131
1132     PUSHi(nfound);
1133     if (GIMME == G_ARRAY && tbuf) {
1134         value = (NV)(timebuf.tv_sec) +
1135                 (NV)(timebuf.tv_usec) / 1000000.0;
1136         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
1137         sv_setnv(sv, value);
1138     }
1139     RETURN;
1140 #else
1141     DIE(aTHX_ "select not implemented");
1142 #endif
1143 }
1144
1145 void
1146 Perl_setdefout(pTHX_ GV *gv)
1147 {
1148     if (gv)
1149         (void)SvREFCNT_inc(gv);
1150     if (PL_defoutgv)
1151         SvREFCNT_dec(PL_defoutgv);
1152     PL_defoutgv = gv;
1153 }
1154
1155 PP(pp_select)
1156 {
1157     dSP; dTARGET;
1158     HV *hv;
1159     GV * const newdefout = (PL_op->op_private > 0) ? ((GV *) POPs) : (GV *) NULL;
1160     GV * egv = GvEGV(PL_defoutgv);
1161
1162     if (!egv)
1163         egv = PL_defoutgv;
1164     hv = GvSTASH(egv);
1165     if (! hv)
1166         XPUSHs(&PL_sv_undef);
1167     else {
1168         GV * const * const gvp = (GV**)hv_fetch(hv, GvNAME(egv), GvNAMELEN(egv), FALSE);
1169         if (gvp && *gvp == egv) {
1170             gv_efullname4(TARG, PL_defoutgv, Nullch, TRUE);
1171             XPUSHTARG;
1172         }
1173         else {
1174             XPUSHs(sv_2mortal(newRV((SV*)egv)));
1175         }
1176     }
1177
1178     if (newdefout) {
1179         if (!GvIO(newdefout))
1180             gv_IOadd(newdefout);
1181         setdefout(newdefout);
1182     }
1183
1184     RETURN;
1185 }
1186
1187 PP(pp_getc)
1188 {
1189     dVAR; dSP; dTARGET;
1190     IO *io = NULL;
1191     MAGIC *mg;
1192     GV * const gv = (MAXARG==0) ? PL_stdingv : (GV*)POPs;
1193
1194     if (gv && (io = GvIO(gv))
1195         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1196     {
1197         const I32 gimme = GIMME_V;
1198         PUSHMARK(SP);
1199         XPUSHs(SvTIED_obj((SV*)io, mg));
1200         PUTBACK;
1201         ENTER;
1202         call_method("GETC", gimme);
1203         LEAVE;
1204         SPAGAIN;
1205         if (gimme == G_SCALAR)
1206             SvSetMagicSV_nosteal(TARG, TOPs);
1207         RETURN;
1208     }
1209     if (!gv || do_eof(gv)) { /* make sure we have fp with something */
1210         if ((!io || (!IoIFP(io) && IoTYPE(io) != IoTYPE_WRONLY))
1211           && ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1212             report_evil_fh(gv, io, PL_op->op_type);
1213         SETERRNO(EBADF,RMS_IFI);
1214         RETPUSHUNDEF;
1215     }
1216     TAINT;
1217     sv_setpvn(TARG, " ", 1);
1218     *SvPVX(TARG) = PerlIO_getc(IoIFP(GvIOp(gv))); /* should never be EOF */
1219     if (PerlIO_isutf8(IoIFP(GvIOp(gv)))) {
1220         /* Find out how many bytes the char needs */
1221         Size_t len = UTF8SKIP(SvPVX_const(TARG));
1222         if (len > 1) {
1223             SvGROW(TARG,len+1);
1224             len = PerlIO_read(IoIFP(GvIOp(gv)),SvPVX(TARG)+1,len-1);
1225             SvCUR_set(TARG,1+len);
1226         }
1227         SvUTF8_on(TARG);
1228     }
1229     PUSHTARG;
1230     RETURN;
1231 }
1232
1233 STATIC OP *
1234 S_doform(pTHX_ CV *cv, GV *gv, OP *retop)
1235 {
1236     dVAR;
1237     register PERL_CONTEXT *cx;
1238     const I32 gimme = GIMME_V;
1239
1240     ENTER;
1241     SAVETMPS;
1242
1243     PUSHBLOCK(cx, CXt_FORMAT, PL_stack_sp);
1244     PUSHFORMAT(cx);
1245     cx->blk_sub.retop = retop;
1246     SAVECOMPPAD();
1247     PAD_SET_CUR_NOSAVE(CvPADLIST(cv), 1);
1248
1249     setdefout(gv);          /* locally select filehandle so $% et al work */
1250     return CvSTART(cv);
1251 }
1252
1253 PP(pp_enterwrite)
1254 {
1255     dSP;
1256     register GV *gv;
1257     register IO *io;
1258     GV *fgv;
1259     CV *cv;
1260
1261     if (MAXARG == 0)
1262         gv = PL_defoutgv;
1263     else {
1264         gv = (GV*)POPs;
1265         if (!gv)
1266             gv = PL_defoutgv;
1267     }
1268     EXTEND(SP, 1);
1269     io = GvIO(gv);
1270     if (!io) {
1271         RETPUSHNO;
1272     }
1273     if (IoFMT_GV(io))
1274         fgv = IoFMT_GV(io);
1275     else
1276         fgv = gv;
1277
1278     cv = GvFORM(fgv);
1279     if (!cv) {
1280         if (fgv) {
1281             SV * const tmpsv = sv_newmortal();
1282             const char *name;
1283             gv_efullname4(tmpsv, fgv, Nullch, FALSE);
1284             name = SvPV_nolen_const(tmpsv);
1285             if (name && *name)
1286                 DIE(aTHX_ "Undefined format \"%s\" called", name);
1287         }
1288         DIE(aTHX_ "Not a format reference");
1289     }
1290     if (CvCLONE(cv))
1291         cv = (CV*)sv_2mortal((SV*)cv_clone(cv));
1292
1293     IoFLAGS(io) &= ~IOf_DIDTOP;
1294     return doform(cv,gv,PL_op->op_next);
1295 }
1296
1297 PP(pp_leavewrite)
1298 {
1299     dVAR; dSP;
1300     GV * const gv = cxstack[cxstack_ix].blk_sub.gv;
1301     register IO * const io = GvIOp(gv);
1302     PerlIO * const ofp = IoOFP(io);
1303     PerlIO *fp;
1304     SV **newsp;
1305     I32 gimme;
1306     register PERL_CONTEXT *cx;
1307
1308     DEBUG_f(PerlIO_printf(Perl_debug_log, "left=%ld, todo=%ld\n",
1309           (long)IoLINES_LEFT(io), (long)FmLINES(PL_formtarget)));
1310     if (!io || !ofp)
1311         goto forget_top;
1312     if (IoLINES_LEFT(io) < FmLINES(PL_formtarget) &&
1313         PL_formtarget != PL_toptarget)
1314     {
1315         GV *fgv;
1316         CV *cv;
1317         if (!IoTOP_GV(io)) {
1318             GV *topgv;
1319
1320             if (!IoTOP_NAME(io)) {
1321                 SV *topname;
1322                 if (!IoFMT_NAME(io))
1323                     IoFMT_NAME(io) = savepv(GvNAME(gv));
1324                 topname = sv_2mortal(Perl_newSVpvf(aTHX_ "%s_TOP", GvNAME(gv)));
1325                 topgv = gv_fetchsv(topname, FALSE, SVt_PVFM);
1326                 if ((topgv && GvFORM(topgv)) ||
1327                   !gv_fetchpv("top",FALSE,SVt_PVFM))
1328                     IoTOP_NAME(io) = savesvpv(topname);
1329                 else
1330                     IoTOP_NAME(io) = savepvn("top", 3);
1331             }
1332             topgv = gv_fetchpv(IoTOP_NAME(io),FALSE, SVt_PVFM);
1333             if (!topgv || !GvFORM(topgv)) {
1334                 IoLINES_LEFT(io) = IoPAGE_LEN(io);
1335                 goto forget_top;
1336             }
1337             IoTOP_GV(io) = topgv;
1338         }
1339         if (IoFLAGS(io) & IOf_DIDTOP) { /* Oh dear.  It still doesn't fit. */
1340             I32 lines = IoLINES_LEFT(io);
1341             const char *s = SvPVX_const(PL_formtarget);
1342             if (lines <= 0)             /* Yow, header didn't even fit!!! */
1343                 goto forget_top;
1344             while (lines-- > 0) {
1345                 s = strchr(s, '\n');
1346                 if (!s)
1347                     break;
1348                 s++;
1349             }
1350             if (s) {
1351                 const STRLEN save = SvCUR(PL_formtarget);
1352                 SvCUR_set(PL_formtarget, s - SvPVX_const(PL_formtarget));
1353                 do_print(PL_formtarget, ofp);
1354                 SvCUR_set(PL_formtarget, save);
1355                 sv_chop(PL_formtarget, s);
1356                 FmLINES(PL_formtarget) -= IoLINES_LEFT(io);
1357             }
1358         }
1359         if (IoLINES_LEFT(io) >= 0 && IoPAGE(io) > 0)
1360             do_print(PL_formfeed, ofp);
1361         IoLINES_LEFT(io) = IoPAGE_LEN(io);
1362         IoPAGE(io)++;
1363         PL_formtarget = PL_toptarget;
1364         IoFLAGS(io) |= IOf_DIDTOP;
1365         fgv = IoTOP_GV(io);
1366         if (!fgv)
1367             DIE(aTHX_ "bad top format reference");
1368         cv = GvFORM(fgv);
1369         if (!cv) {
1370             SV * const sv = sv_newmortal();
1371             const char *name;
1372             gv_efullname4(sv, fgv, Nullch, FALSE);
1373             name = SvPV_nolen_const(sv);
1374             if (name && *name)
1375                 DIE(aTHX_ "Undefined top format \"%s\" called",name);
1376         }
1377         /* why no:
1378         else
1379             DIE(aTHX_ "Undefined top format called");
1380         ?*/
1381         if (CvCLONE(cv))
1382             cv = (CV*)sv_2mortal((SV*)cv_clone(cv));
1383         return doform(cv,gv,PL_op);
1384     }
1385
1386   forget_top:
1387     POPBLOCK(cx,PL_curpm);
1388     POPFORMAT(cx);
1389     LEAVE;
1390
1391     fp = IoOFP(io);
1392     if (!fp) {
1393         if (ckWARN2(WARN_CLOSED,WARN_IO)) {
1394             if (IoIFP(io))
1395                 report_evil_fh(gv, io, OP_phoney_INPUT_ONLY);
1396             else if (ckWARN(WARN_CLOSED))
1397                 report_evil_fh(gv, io, PL_op->op_type);
1398         }
1399         PUSHs(&PL_sv_no);
1400     }
1401     else {
1402         if ((IoLINES_LEFT(io) -= FmLINES(PL_formtarget)) < 0) {
1403             if (ckWARN(WARN_IO))
1404                 Perl_warner(aTHX_ packWARN(WARN_IO), "page overflow");
1405         }
1406         if (!do_print(PL_formtarget, fp))
1407             PUSHs(&PL_sv_no);
1408         else {
1409             FmLINES(PL_formtarget) = 0;
1410             SvCUR_set(PL_formtarget, 0);
1411             *SvEND(PL_formtarget) = '\0';
1412             if (IoFLAGS(io) & IOf_FLUSH)
1413                 (void)PerlIO_flush(fp);
1414             PUSHs(&PL_sv_yes);
1415         }
1416     }
1417     /* bad_ofp: */
1418     PL_formtarget = PL_bodytarget;
1419     PUTBACK;
1420     PERL_UNUSED_VAR(newsp);
1421     PERL_UNUSED_VAR(gimme);
1422     return cx->blk_sub.retop;
1423 }
1424
1425 PP(pp_prtf)
1426 {
1427     dVAR; dSP; dMARK; dORIGMARK;
1428     IO *io;
1429     PerlIO *fp;
1430     SV *sv;
1431     MAGIC *mg;
1432
1433     GV * const gv = (PL_op->op_flags & OPf_STACKED) ? (GV*)*++MARK : PL_defoutgv;
1434
1435     if (gv && (io = GvIO(gv))
1436         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1437     {
1438         if (MARK == ORIGMARK) {
1439             MEXTEND(SP, 1);
1440             ++MARK;
1441             Move(MARK, MARK + 1, (SP - MARK) + 1, SV*);
1442             ++SP;
1443         }
1444         PUSHMARK(MARK - 1);
1445         *MARK = SvTIED_obj((SV*)io, mg);
1446         PUTBACK;
1447         ENTER;
1448         call_method("PRINTF", G_SCALAR);
1449         LEAVE;
1450         SPAGAIN;
1451         MARK = ORIGMARK + 1;
1452         *MARK = *SP;
1453         SP = MARK;
1454         RETURN;
1455     }
1456
1457     sv = NEWSV(0,0);
1458     if (!(io = GvIO(gv))) {
1459         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1460             report_evil_fh(gv, io, PL_op->op_type);
1461         SETERRNO(EBADF,RMS_IFI);
1462         goto just_say_no;
1463     }
1464     else if (!(fp = IoOFP(io))) {
1465         if (ckWARN2(WARN_CLOSED,WARN_IO))  {
1466             if (IoIFP(io))
1467                 report_evil_fh(gv, io, OP_phoney_INPUT_ONLY);
1468             else if (ckWARN(WARN_CLOSED))
1469                 report_evil_fh(gv, io, PL_op->op_type);
1470         }
1471         SETERRNO(EBADF,IoIFP(io)?RMS_FAC:RMS_IFI);
1472         goto just_say_no;
1473     }
1474     else {
1475         do_sprintf(sv, SP - MARK, MARK + 1);
1476         if (!do_print(sv, fp))
1477             goto just_say_no;
1478
1479         if (IoFLAGS(io) & IOf_FLUSH)
1480             if (PerlIO_flush(fp) == EOF)
1481                 goto just_say_no;
1482     }
1483     SvREFCNT_dec(sv);
1484     SP = ORIGMARK;
1485     PUSHs(&PL_sv_yes);
1486     RETURN;
1487
1488   just_say_no:
1489     SvREFCNT_dec(sv);
1490     SP = ORIGMARK;
1491     PUSHs(&PL_sv_undef);
1492     RETURN;
1493 }
1494
1495 PP(pp_sysopen)
1496 {
1497     dSP;
1498     const int perm = (MAXARG > 3) ? POPi : 0666;
1499     const int mode = POPi;
1500     SV * const sv = POPs;
1501     GV * const gv = (GV *)POPs;
1502     STRLEN len;
1503
1504     /* Need TIEHANDLE method ? */
1505     const char * const tmps = SvPV_const(sv, len);
1506     /* FIXME? do_open should do const  */
1507     if (do_open(gv, tmps, len, TRUE, mode, perm, Nullfp)) {
1508         IoLINES(GvIOp(gv)) = 0;
1509         PUSHs(&PL_sv_yes);
1510     }
1511     else {
1512         PUSHs(&PL_sv_undef);
1513     }
1514     RETURN;
1515 }
1516
1517 PP(pp_sysread)
1518 {
1519     dVAR; dSP; dMARK; dORIGMARK; dTARGET;
1520     int offset;
1521     IO *io;
1522     char *buffer;
1523     SSize_t length;
1524     SSize_t count;
1525     Sock_size_t bufsize;
1526     SV *bufsv;
1527     STRLEN blen;
1528     int fp_utf8;
1529     int buffer_utf8;
1530     SV *read_target;
1531     Size_t got = 0;
1532     Size_t wanted;
1533     bool charstart = FALSE;
1534     STRLEN charskip = 0;
1535     STRLEN skip = 0;
1536
1537     GV * const gv = (GV*)*++MARK;
1538     if ((PL_op->op_type == OP_READ || PL_op->op_type == OP_SYSREAD)
1539         && gv && (io = GvIO(gv)) )
1540     {
1541         const MAGIC * mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar);
1542         if (mg) {
1543             SV *sv;
1544             PUSHMARK(MARK-1);
1545             *MARK = SvTIED_obj((SV*)io, mg);
1546             ENTER;
1547             call_method("READ", G_SCALAR);
1548             LEAVE;
1549             SPAGAIN;
1550             sv = POPs;
1551             SP = ORIGMARK;
1552             PUSHs(sv);
1553             RETURN;
1554         }
1555     }
1556
1557     if (!gv)
1558         goto say_undef;
1559     bufsv = *++MARK;
1560     if (! SvOK(bufsv))
1561         sv_setpvn(bufsv, "", 0);
1562     length = SvIVx(*++MARK);
1563     SETERRNO(0,0);
1564     if (MARK < SP)
1565         offset = SvIVx(*++MARK);
1566     else
1567         offset = 0;
1568     io = GvIO(gv);
1569     if (!io || !IoIFP(io)) {
1570         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1571             report_evil_fh(gv, io, PL_op->op_type);
1572         SETERRNO(EBADF,RMS_IFI);
1573         goto say_undef;
1574     }
1575     if ((fp_utf8 = PerlIO_isutf8(IoIFP(io))) && !IN_BYTES) {
1576         buffer = SvPVutf8_force(bufsv, blen);
1577         /* UTF-8 may not have been set if they are all low bytes */
1578         SvUTF8_on(bufsv);
1579         buffer_utf8 = 0;
1580     }
1581     else {
1582         buffer = SvPV_force(bufsv, blen);
1583         buffer_utf8 = !IN_BYTES && SvUTF8(bufsv);
1584     }
1585     if (length < 0)
1586         DIE(aTHX_ "Negative length");
1587     wanted = length;
1588
1589     charstart = TRUE;
1590     charskip  = 0;
1591     skip = 0;
1592
1593 #ifdef HAS_SOCKET
1594     if (PL_op->op_type == OP_RECV) {
1595         char namebuf[MAXPATHLEN];
1596 #if (defined(VMS_DO_SOCKETS) && defined(DECCRTL_SOCKETS)) || defined(MPE) || defined(__QNXNTO__)
1597         bufsize = sizeof (struct sockaddr_in);
1598 #else
1599         bufsize = sizeof namebuf;
1600 #endif
1601 #ifdef OS2      /* At least Warp3+IAK: only the first byte of bufsize set */
1602         if (bufsize >= 256)
1603             bufsize = 255;
1604 #endif
1605         buffer = SvGROW(bufsv, (STRLEN)(length+1));
1606         /* 'offset' means 'flags' here */
1607         count = PerlSock_recvfrom(PerlIO_fileno(IoIFP(io)), buffer, length, offset,
1608                           (struct sockaddr *)namebuf, &bufsize);
1609         if (count < 0)
1610             RETPUSHUNDEF;
1611 #ifdef EPOC
1612         /* Bogus return without padding */
1613         bufsize = sizeof (struct sockaddr_in);
1614 #endif
1615         SvCUR_set(bufsv, count);
1616         *SvEND(bufsv) = '\0';
1617         (void)SvPOK_only(bufsv);
1618         if (fp_utf8)
1619             SvUTF8_on(bufsv);
1620         SvSETMAGIC(bufsv);
1621         /* This should not be marked tainted if the fp is marked clean */
1622         if (!(IoFLAGS(io) & IOf_UNTAINT))
1623             SvTAINTED_on(bufsv);
1624         SP = ORIGMARK;
1625         sv_setpvn(TARG, namebuf, bufsize);
1626         PUSHs(TARG);
1627         RETURN;
1628     }
1629 #else
1630     if (PL_op->op_type == OP_RECV)
1631         DIE(aTHX_ PL_no_sock_func, "recv");
1632 #endif
1633     if (DO_UTF8(bufsv)) {
1634         /* offset adjust in characters not bytes */
1635         blen = sv_len_utf8(bufsv);
1636     }
1637     if (offset < 0) {
1638         if (-offset > (int)blen)
1639             DIE(aTHX_ "Offset outside string");
1640         offset += blen;
1641     }
1642     if (DO_UTF8(bufsv)) {
1643         /* convert offset-as-chars to offset-as-bytes */
1644         if (offset >= (int)blen)
1645             offset += SvCUR(bufsv) - blen;
1646         else
1647             offset = utf8_hop((U8 *)buffer,offset) - (U8 *) buffer;
1648     }
1649  more_bytes:
1650     bufsize = SvCUR(bufsv);
1651     /* Allocating length + offset + 1 isn't perfect in the case of reading
1652        bytes from a byte file handle into a UTF8 buffer, but it won't harm us
1653        unduly.
1654        (should be 2 * length + offset + 1, or possibly something longer if
1655        PL_encoding is true) */
1656     buffer  = SvGROW(bufsv, (STRLEN)(length+offset+1));
1657     if (offset > 0 && (Sock_size_t)offset > bufsize) { /* Zero any newly allocated space */
1658         Zero(buffer+bufsize, offset-bufsize, char);
1659     }
1660     buffer = buffer + offset;
1661     if (!buffer_utf8) {
1662         read_target = bufsv;
1663     } else {
1664         /* Best to read the bytes into a new SV, upgrade that to UTF8, then
1665            concatenate it to the current buffer.  */
1666
1667         /* Truncate the existing buffer to the start of where we will be
1668            reading to:  */
1669         SvCUR_set(bufsv, offset);
1670
1671         read_target = sv_newmortal();
1672         SvUPGRADE(read_target, SVt_PV);
1673         buffer = SvGROW(read_target, (STRLEN)(length + 1));
1674     }
1675
1676     if (PL_op->op_type == OP_SYSREAD) {
1677 #ifdef PERL_SOCK_SYSREAD_IS_RECV
1678         if (IoTYPE(io) == IoTYPE_SOCKET) {
1679             count = PerlSock_recv(PerlIO_fileno(IoIFP(io)),
1680                                    buffer, length, 0);
1681         }
1682         else
1683 #endif
1684         {
1685             count = PerlLIO_read(PerlIO_fileno(IoIFP(io)),
1686                                   buffer, length);
1687         }
1688     }
1689     else
1690 #ifdef HAS_SOCKET__bad_code_maybe
1691     if (IoTYPE(io) == IoTYPE_SOCKET) {
1692         char namebuf[MAXPATHLEN];
1693 #if defined(VMS_DO_SOCKETS) && defined(DECCRTL_SOCKETS)
1694         bufsize = sizeof (struct sockaddr_in);
1695 #else
1696         bufsize = sizeof namebuf;
1697 #endif
1698         count = PerlSock_recvfrom(PerlIO_fileno(IoIFP(io)), buffer, length, 0,
1699                           (struct sockaddr *)namebuf, &bufsize);
1700     }
1701     else
1702 #endif
1703     {
1704         count = PerlIO_read(IoIFP(io), buffer, length);
1705         /* PerlIO_read() - like fread() returns 0 on both error and EOF */
1706         if (count == 0 && PerlIO_error(IoIFP(io)))
1707             count = -1;
1708     }
1709     if (count < 0) {
1710         if ((IoTYPE(io) == IoTYPE_WRONLY) && ckWARN(WARN_IO))
1711                 report_evil_fh(gv, io, OP_phoney_OUTPUT_ONLY);
1712         goto say_undef;
1713     }
1714     SvCUR_set(read_target, count+(buffer - SvPVX_const(read_target)));
1715     *SvEND(read_target) = '\0';
1716     (void)SvPOK_only(read_target);
1717     if (fp_utf8 && !IN_BYTES) {
1718         /* Look at utf8 we got back and count the characters */
1719         const char *bend = buffer + count;
1720         while (buffer < bend) {
1721             if (charstart) {
1722                 skip = UTF8SKIP(buffer);
1723                 charskip = 0;
1724             }
1725             if (buffer - charskip + skip > bend) {
1726                 /* partial character - try for rest of it */
1727                 length = skip - (bend-buffer);
1728                 offset = bend - SvPVX_const(bufsv);
1729                 charstart = FALSE;
1730                 charskip += count;
1731                 goto more_bytes;
1732             }
1733             else {
1734                 got++;
1735                 buffer += skip;
1736                 charstart = TRUE;
1737                 charskip  = 0;
1738             }
1739         }
1740         /* If we have not 'got' the number of _characters_ we 'wanted' get some more
1741            provided amount read (count) was what was requested (length)
1742          */
1743         if (got < wanted && count == length) {
1744             length = wanted - got;
1745             offset = bend - SvPVX_const(bufsv);
1746             goto more_bytes;
1747         }
1748         /* return value is character count */
1749         count = got;
1750         SvUTF8_on(bufsv);
1751     }
1752     else if (buffer_utf8) {
1753         /* Let svcatsv upgrade the bytes we read in to utf8.
1754            The buffer is a mortal so will be freed soon.  */
1755         sv_catsv_nomg(bufsv, read_target);
1756     }
1757     SvSETMAGIC(bufsv);
1758     /* This should not be marked tainted if the fp is marked clean */
1759     if (!(IoFLAGS(io) & IOf_UNTAINT))
1760         SvTAINTED_on(bufsv);
1761     SP = ORIGMARK;
1762     PUSHi(count);
1763     RETURN;
1764
1765   say_undef:
1766     SP = ORIGMARK;
1767     RETPUSHUNDEF;
1768 }
1769
1770 PP(pp_send)
1771 {
1772     dVAR; dSP; dMARK; dORIGMARK; dTARGET;
1773     IO *io;
1774     SV *bufsv;
1775     const char *buffer;
1776     Size_t length = 0;
1777     SSize_t retval;
1778     STRLEN blen;
1779     MAGIC *mg;
1780     const int op_type = PL_op->op_type;
1781     
1782     GV *const gv = (GV*)*++MARK;
1783     if (PL_op->op_type == OP_SYSWRITE
1784         && gv && (io = GvIO(gv))
1785         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1786     {
1787         SV *sv;
1788
1789         if (MARK == SP - 1) {
1790             EXTEND(SP, 1000);
1791             sv = sv_2mortal(newSViv(sv_len(*SP)));
1792             PUSHs(sv);
1793             PUTBACK;
1794         }
1795         
1796         PUSHMARK(ORIGMARK);
1797         *(ORIGMARK+1) = SvTIED_obj((SV*)io, mg);
1798         ENTER;
1799         call_method("WRITE", G_SCALAR);
1800         LEAVE;
1801         SPAGAIN;
1802         sv = POPs;
1803         SP = ORIGMARK;
1804         PUSHs(sv);
1805         RETURN;
1806     }
1807     if (!gv)
1808         goto say_undef;
1809
1810     bufsv = *++MARK;
1811
1812     if (op_type == OP_SYSWRITE) {
1813         if (MARK >= SP) {
1814             length = (Size_t) sv_len(bufsv);
1815         } else {
1816 #if Size_t_size > IVSIZE
1817             length = (Size_t)SvNVx(*++MARK);
1818 #else
1819             length = (Size_t)SvIVx(*++MARK);
1820 #endif
1821             if ((SSize_t)length < 0)
1822                 DIE(aTHX_ "Negative length");
1823         }
1824     }
1825     SETERRNO(0,0);
1826     io = GvIO(gv);
1827     if (!io || !IoIFP(io)) {
1828         retval = -1;
1829         if (ckWARN(WARN_CLOSED))
1830             report_evil_fh(gv, io, PL_op->op_type);
1831         SETERRNO(EBADF,RMS_IFI);
1832         goto say_undef;
1833     }
1834
1835     if (PerlIO_isutf8(IoIFP(io))) {
1836         if (!SvUTF8(bufsv)) {
1837             bufsv = sv_2mortal(newSVsv(bufsv));
1838             buffer = sv_2pvutf8(bufsv, &blen);
1839         } else
1840             buffer = SvPV_const(bufsv, blen);
1841     }
1842     else {
1843          if (DO_UTF8(bufsv)) {
1844               /* Not modifying source SV, so making a temporary copy. */
1845               bufsv = sv_2mortal(newSVsv(bufsv));
1846               sv_utf8_downgrade(bufsv, FALSE);
1847          }
1848          buffer = SvPV_const(bufsv, blen);
1849     }
1850
1851     if (op_type == OP_SYSWRITE) {
1852         IV offset;
1853         if (DO_UTF8(bufsv)) {
1854             /* length and offset are in chars */
1855             blen   = sv_len_utf8(bufsv);
1856         }
1857         if (MARK < SP) {
1858             offset = SvIVx(*++MARK);
1859             if (offset < 0) {
1860                 if (-offset > (IV)blen)
1861                     DIE(aTHX_ "Offset outside string");
1862                 offset += blen;
1863             } else if (offset >= (IV)blen && blen > 0)
1864                 DIE(aTHX_ "Offset outside string");
1865         } else
1866             offset = 0;
1867         if (length > blen - offset)
1868             length = blen - offset;
1869         if (DO_UTF8(bufsv)) {
1870             buffer = (const char*)utf8_hop((const U8 *)buffer, offset);
1871             length = utf8_hop((U8 *)buffer, length) - (U8 *)buffer;
1872         }
1873         else {
1874             buffer = buffer+offset;
1875         }
1876 #ifdef PERL_SOCK_SYSWRITE_IS_SEND
1877         if (IoTYPE(io) == IoTYPE_SOCKET) {
1878             retval = PerlSock_send(PerlIO_fileno(IoIFP(io)),
1879                                    buffer, length, 0);
1880         }
1881         else
1882 #endif
1883         {
1884             /* See the note at doio.c:do_print about filesize limits. --jhi */
1885             retval = PerlLIO_write(PerlIO_fileno(IoIFP(io)),
1886                                    buffer, length);
1887         }
1888     }
1889 #ifdef HAS_SOCKET
1890     else {
1891         const int flags = SvIVx(*++MARK);
1892         if (SP > MARK) {
1893             STRLEN mlen;
1894             char * const sockbuf = SvPVx(*++MARK, mlen);
1895             retval = PerlSock_sendto(PerlIO_fileno(IoIFP(io)), buffer, blen,
1896                                      flags, (struct sockaddr *)sockbuf, mlen);
1897         }
1898         else {
1899             retval
1900                 = PerlSock_send(PerlIO_fileno(IoIFP(io)), buffer, blen, flags);
1901         }
1902     }
1903 #else
1904     else
1905         DIE(aTHX_ PL_no_sock_func, "send");
1906 #endif
1907     if (retval < 0)
1908         goto say_undef;
1909     SP = ORIGMARK;
1910     if (DO_UTF8(bufsv))
1911         retval = utf8_length((U8*)buffer, (U8*)buffer + retval);
1912 #if Size_t_size > IVSIZE
1913     PUSHn(retval);
1914 #else
1915     PUSHi(retval);
1916 #endif
1917     RETURN;
1918
1919   say_undef:
1920     SP = ORIGMARK;
1921     RETPUSHUNDEF;
1922 }
1923
1924 PP(pp_eof)
1925 {
1926     dVAR; dSP;
1927     GV *gv;
1928     IO *io;
1929     MAGIC *mg;
1930
1931     if (MAXARG == 0) {
1932         if (PL_op->op_flags & OPf_SPECIAL) {    /* eof() */
1933             IO *io;
1934             gv = PL_last_in_gv = GvEGV(PL_argvgv);
1935             io = GvIO(gv);
1936             if (io && !IoIFP(io)) {
1937                 if ((IoFLAGS(io) & IOf_START) && av_len(GvAVn(gv)) < 0) {
1938                     IoLINES(io) = 0;
1939                     IoFLAGS(io) &= ~IOf_START;
1940                     do_open(gv, "-", 1, FALSE, O_RDONLY, 0, Nullfp);
1941                     sv_setpvn(GvSV(gv), "-", 1);
1942                     SvSETMAGIC(GvSV(gv));
1943                 }
1944                 else if (!nextargv(gv))
1945                     RETPUSHYES;
1946             }
1947         }
1948         else
1949             gv = PL_last_in_gv;                 /* eof */
1950     }
1951     else
1952         gv = PL_last_in_gv = (GV*)POPs;         /* eof(FH) */
1953
1954     if (gv && (io = GvIO(gv))
1955         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1956     {
1957         PUSHMARK(SP);
1958         XPUSHs(SvTIED_obj((SV*)io, mg));
1959         PUTBACK;
1960         ENTER;
1961         call_method("EOF", G_SCALAR);
1962         LEAVE;
1963         SPAGAIN;
1964         RETURN;
1965     }
1966
1967     PUSHs(boolSV(!gv || do_eof(gv)));
1968     RETURN;
1969 }
1970
1971 PP(pp_tell)
1972 {
1973     dVAR; dSP; dTARGET;
1974     GV *gv;
1975     IO *io;
1976     MAGIC *mg;
1977
1978     if (MAXARG != 0)
1979         PL_last_in_gv = (GV*)POPs;
1980     gv = PL_last_in_gv;
1981
1982     if (gv && (io = GvIO(gv))
1983         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1984     {
1985         PUSHMARK(SP);
1986         XPUSHs(SvTIED_obj((SV*)io, mg));
1987         PUTBACK;
1988         ENTER;
1989         call_method("TELL", G_SCALAR);
1990         LEAVE;
1991         SPAGAIN;
1992         RETURN;
1993     }
1994
1995 #if LSEEKSIZE > IVSIZE
1996     PUSHn( do_tell(gv) );
1997 #else
1998     PUSHi( do_tell(gv) );
1999 #endif
2000     RETURN;
2001 }
2002
2003 PP(pp_sysseek)
2004 {
2005     dVAR; dSP;
2006     IO *io;
2007     const int whence = POPi;
2008 #if LSEEKSIZE > IVSIZE
2009     const Off_t offset = (Off_t)SvNVx(POPs);
2010 #else
2011     const Off_t offset = (Off_t)SvIVx(POPs);
2012 #endif
2013     MAGIC *mg;
2014
2015     GV * const gv = PL_last_in_gv = (GV*)POPs;
2016
2017     if (gv && (io = GvIO(gv))
2018         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
2019     {
2020         PUSHMARK(SP);
2021         XPUSHs(SvTIED_obj((SV*)io, mg));
2022 #if LSEEKSIZE > IVSIZE
2023         XPUSHs(sv_2mortal(newSVnv((NV) offset)));
2024 #else
2025         XPUSHs(sv_2mortal(newSViv(offset)));
2026 #endif
2027         XPUSHs(sv_2mortal(newSViv(whence)));
2028         PUTBACK;
2029         ENTER;
2030         call_method("SEEK", G_SCALAR);
2031         LEAVE;
2032         SPAGAIN;
2033         RETURN;
2034     }
2035
2036     if (PL_op->op_type == OP_SEEK)
2037         PUSHs(boolSV(do_seek(gv, offset, whence)));
2038     else {
2039         Off_t sought = do_sysseek(gv, offset, whence);
2040         if (sought < 0)
2041             PUSHs(&PL_sv_undef);
2042         else {
2043             SV* const sv = sought ?
2044 #if LSEEKSIZE > IVSIZE
2045                 newSVnv((NV)sought)
2046 #else
2047                 newSViv(sought)
2048 #endif
2049                 : newSVpvn(zero_but_true, ZBTLEN);
2050             PUSHs(sv_2mortal(sv));
2051         }
2052     }
2053     RETURN;
2054 }
2055
2056 PP(pp_truncate)
2057 {
2058     dSP;
2059     /* There seems to be no consensus on the length type of truncate()
2060      * and ftruncate(), both off_t and size_t have supporters. In
2061      * general one would think that when using large files, off_t is
2062      * at least as wide as size_t, so using an off_t should be okay. */
2063     /* XXX Configure probe for the length type of *truncate() needed XXX */
2064
2065 #if Off_t_size > IVSIZE
2066     const Off_t len = (Off_t)POPn;
2067 #else
2068     const Off_t len = (Off_t)POPi;
2069 #endif
2070     /* Checking for length < 0 is problematic as the type might or
2071      * might not be signed: if it is not, clever compilers will moan. */
2072     /* XXX Configure probe for the signedness of the length type of *truncate() needed? XXX */
2073     SETERRNO(0,0);
2074     {
2075         int result = 1;
2076         GV *tmpgv;
2077         IO *io;
2078
2079         if (PL_op->op_flags & OPf_SPECIAL) {
2080             tmpgv = gv_fetchsv(POPs, FALSE, SVt_PVIO);
2081
2082         do_ftruncate_gv:
2083             if (!GvIO(tmpgv))
2084                 result = 0;
2085             else {
2086                 PerlIO *fp;
2087                 io = GvIOp(tmpgv);
2088             do_ftruncate_io:
2089                 TAINT_PROPER("truncate");
2090                 if (!(fp = IoIFP(io))) {
2091                     result = 0;
2092                 }
2093                 else {
2094                     PerlIO_flush(fp);
2095 #ifdef HAS_TRUNCATE
2096                     if (ftruncate(PerlIO_fileno(fp), len) < 0)
2097 #else
2098                     if (my_chsize(PerlIO_fileno(fp), len) < 0)
2099 #endif
2100                         result = 0;
2101                 }
2102             }
2103         }
2104         else {
2105             SV * const sv = POPs;
2106             const char *name;
2107
2108             if (SvTYPE(sv) == SVt_PVGV) {
2109                 tmpgv = (GV*)sv;                /* *main::FRED for example */
2110                 goto do_ftruncate_gv;
2111             }
2112             else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV) {
2113                 tmpgv = (GV*) SvRV(sv); /* \*main::FRED for example */
2114                 goto do_ftruncate_gv;
2115             }
2116             else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
2117                 io = (IO*) SvRV(sv); /* *main::FRED{IO} for example */
2118                 goto do_ftruncate_io;
2119             }
2120
2121             name = SvPV_nolen_const(sv);
2122             TAINT_PROPER("truncate");
2123 #ifdef HAS_TRUNCATE
2124             if (truncate(name, len) < 0)
2125                 result = 0;
2126 #else
2127             {
2128                 const int tmpfd = PerlLIO_open(name, O_RDWR);
2129
2130                 if (tmpfd < 0)
2131                     result = 0;
2132                 else {
2133                     if (my_chsize(tmpfd, len) < 0)
2134                         result = 0;
2135                     PerlLIO_close(tmpfd);
2136                 }
2137             }
2138 #endif
2139         }
2140
2141         if (result)
2142             RETPUSHYES;
2143         if (!errno)
2144             SETERRNO(EBADF,RMS_IFI);
2145         RETPUSHUNDEF;
2146     }
2147 }
2148
2149 PP(pp_ioctl)
2150 {
2151     dSP; dTARGET;
2152     SV * const argsv = POPs;
2153     const unsigned int func = POPu;
2154     const int optype = PL_op->op_type;
2155     GV * const gv = (GV*)POPs;
2156     IO * const io = gv ? GvIOn(gv) : Null(IO*);
2157     char *s;
2158     IV retval;
2159
2160     if (!io || !argsv || !IoIFP(io)) {
2161         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2162             report_evil_fh(gv, io, PL_op->op_type);
2163         SETERRNO(EBADF,RMS_IFI);        /* well, sort of... */
2164         RETPUSHUNDEF;
2165     }
2166
2167     if (SvPOK(argsv) || !SvNIOK(argsv)) {
2168         STRLEN len;
2169         STRLEN need;
2170         s = SvPV_force(argsv, len);
2171         need = IOCPARM_LEN(func);
2172         if (len < need) {
2173             s = Sv_Grow(argsv, need + 1);
2174             SvCUR_set(argsv, need);
2175         }
2176
2177         s[SvCUR(argsv)] = 17;   /* a little sanity check here */
2178     }
2179     else {
2180         retval = SvIV(argsv);
2181         s = INT2PTR(char*,retval);              /* ouch */
2182     }
2183
2184     TAINT_PROPER(optype == OP_IOCTL ? "ioctl" : "fcntl");
2185
2186     if (optype == OP_IOCTL)
2187 #ifdef HAS_IOCTL
2188         retval = PerlLIO_ioctl(PerlIO_fileno(IoIFP(io)), func, s);
2189 #else
2190         DIE(aTHX_ "ioctl is not implemented");
2191 #endif
2192     else
2193 #ifndef HAS_FCNTL
2194       DIE(aTHX_ "fcntl is not implemented");
2195 #else
2196 #if defined(OS2) && defined(__EMX__)
2197         retval = fcntl(PerlIO_fileno(IoIFP(io)), func, (int)s);
2198 #else
2199         retval = fcntl(PerlIO_fileno(IoIFP(io)), func, s);
2200 #endif
2201 #endif
2202
2203 #if defined(HAS_IOCTL) || defined(HAS_FCNTL)
2204     if (SvPOK(argsv)) {
2205         if (s[SvCUR(argsv)] != 17)
2206             DIE(aTHX_ "Possible memory corruption: %s overflowed 3rd argument",
2207                 OP_NAME(PL_op));
2208         s[SvCUR(argsv)] = 0;            /* put our null back */
2209         SvSETMAGIC(argsv);              /* Assume it has changed */
2210     }
2211
2212     if (retval == -1)
2213         RETPUSHUNDEF;
2214     if (retval != 0) {
2215         PUSHi(retval);
2216     }
2217     else {
2218         PUSHp(zero_but_true, ZBTLEN);
2219     }
2220 #endif
2221     RETURN;
2222 }
2223
2224 PP(pp_flock)
2225 {
2226 #ifdef FLOCK
2227     dSP; dTARGET;
2228     I32 value;
2229     IO *io = NULL;
2230     PerlIO *fp;
2231     const int argtype = POPi;
2232     GV * const gv = (MAXARG == 0) ? PL_last_in_gv : (GV*)POPs;
2233
2234     if (gv && (io = GvIO(gv)))
2235         fp = IoIFP(io);
2236     else {
2237         fp = Nullfp;
2238         io = NULL;
2239     }
2240     if (fp) {
2241         (void)PerlIO_flush(fp);
2242         value = (I32)(PerlLIO_flock(PerlIO_fileno(fp), argtype) >= 0);
2243     }
2244     else {
2245         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2246             report_evil_fh(gv, io, PL_op->op_type);
2247         value = 0;
2248         SETERRNO(EBADF,RMS_IFI);
2249     }
2250     PUSHi(value);
2251     RETURN;
2252 #else
2253     DIE(aTHX_ PL_no_func, "flock()");
2254 #endif
2255 }
2256
2257 /* Sockets. */
2258
2259 PP(pp_socket)
2260 {
2261 #ifdef HAS_SOCKET
2262     dSP;
2263     const int protocol = POPi;
2264     const int type = POPi;
2265     const int domain = POPi;
2266     GV * const gv = (GV*)POPs;
2267     register IO * const io = gv ? GvIOn(gv) : NULL;
2268     int fd;
2269
2270     if (!gv || !io) {
2271         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2272             report_evil_fh(gv, io, PL_op->op_type);
2273         if (IoIFP(io))
2274             do_close(gv, FALSE);
2275         SETERRNO(EBADF,LIB_INVARG);
2276         RETPUSHUNDEF;
2277     }
2278
2279     if (IoIFP(io))
2280         do_close(gv, FALSE);
2281
2282     TAINT_PROPER("socket");
2283     fd = PerlSock_socket(domain, type, protocol);
2284     if (fd < 0)
2285         RETPUSHUNDEF;
2286     IoIFP(io) = PerlIO_fdopen(fd, "r"SOCKET_OPEN_MODE); /* stdio gets confused about sockets */
2287     IoOFP(io) = PerlIO_fdopen(fd, "w"SOCKET_OPEN_MODE);
2288     IoTYPE(io) = IoTYPE_SOCKET;
2289     if (!IoIFP(io) || !IoOFP(io)) {
2290         if (IoIFP(io)) PerlIO_close(IoIFP(io));
2291         if (IoOFP(io)) PerlIO_close(IoOFP(io));
2292         if (!IoIFP(io) && !IoOFP(io)) PerlLIO_close(fd);
2293         RETPUSHUNDEF;
2294     }
2295 #if defined(HAS_FCNTL) && defined(F_SETFD)
2296     fcntl(fd, F_SETFD, fd > PL_maxsysfd);       /* ensure close-on-exec */
2297 #endif
2298
2299 #ifdef EPOC
2300     setbuf( IoIFP(io), NULL); /* EPOC gets confused about sockets */
2301 #endif
2302
2303     RETPUSHYES;
2304 #else
2305     DIE(aTHX_ PL_no_sock_func, "socket");
2306 #endif
2307 }
2308
2309 PP(pp_sockpair)
2310 {
2311 #if defined (HAS_SOCKETPAIR) || (defined (HAS_SOCKET) && defined(SOCK_DGRAM) && defined(AF_INET) && defined(PF_INET))
2312     dSP;
2313     const int protocol = POPi;
2314     const int type = POPi;
2315     const int domain = POPi;
2316     GV * const gv2 = (GV*)POPs;
2317     GV * const gv1 = (GV*)POPs;
2318     register IO * const io1 = gv1 ? GvIOn(gv1) : NULL;
2319     register IO * const io2 = gv2 ? GvIOn(gv2) : NULL;
2320     int fd[2];
2321
2322     if (!gv1 || !gv2 || !io1 || !io2) {
2323         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED)) {
2324             if (!gv1 || !io1)
2325                 report_evil_fh(gv1, io1, PL_op->op_type);
2326             if (!gv2 || !io2)
2327                 report_evil_fh(gv1, io2, PL_op->op_type);
2328         }
2329         if (IoIFP(io1))
2330             do_close(gv1, FALSE);
2331         if (IoIFP(io2))
2332             do_close(gv2, FALSE);
2333         RETPUSHUNDEF;
2334     }
2335
2336     if (IoIFP(io1))
2337         do_close(gv1, FALSE);
2338     if (IoIFP(io2))
2339         do_close(gv2, FALSE);
2340
2341     TAINT_PROPER("socketpair");
2342     if (PerlSock_socketpair(domain, type, protocol, fd) < 0)
2343         RETPUSHUNDEF;
2344     IoIFP(io1) = PerlIO_fdopen(fd[0], "r"SOCKET_OPEN_MODE);
2345     IoOFP(io1) = PerlIO_fdopen(fd[0], "w"SOCKET_OPEN_MODE);
2346     IoTYPE(io1) = IoTYPE_SOCKET;
2347     IoIFP(io2) = PerlIO_fdopen(fd[1], "r"SOCKET_OPEN_MODE);
2348     IoOFP(io2) = PerlIO_fdopen(fd[1], "w"SOCKET_OPEN_MODE);
2349     IoTYPE(io2) = IoTYPE_SOCKET;
2350     if (!IoIFP(io1) || !IoOFP(io1) || !IoIFP(io2) || !IoOFP(io2)) {
2351         if (IoIFP(io1)) PerlIO_close(IoIFP(io1));
2352         if (IoOFP(io1)) PerlIO_close(IoOFP(io1));
2353         if (!IoIFP(io1) && !IoOFP(io1)) PerlLIO_close(fd[0]);
2354         if (IoIFP(io2)) PerlIO_close(IoIFP(io2));
2355         if (IoOFP(io2)) PerlIO_close(IoOFP(io2));
2356         if (!IoIFP(io2) && !IoOFP(io2)) PerlLIO_close(fd[1]);
2357         RETPUSHUNDEF;
2358     }
2359 #if defined(HAS_FCNTL) && defined(F_SETFD)
2360     fcntl(fd[0],F_SETFD,fd[0] > PL_maxsysfd);   /* ensure close-on-exec */
2361     fcntl(fd[1],F_SETFD,fd[1] > PL_maxsysfd);   /* ensure close-on-exec */
2362 #endif
2363
2364     RETPUSHYES;
2365 #else
2366     DIE(aTHX_ PL_no_sock_func, "socketpair");
2367 #endif
2368 }
2369
2370 PP(pp_bind)
2371 {
2372 #ifdef HAS_SOCKET
2373     dSP;
2374 #ifdef MPE /* Requires PRIV mode to bind() to ports < 1024 */
2375     extern void GETPRIVMODE();
2376     extern void GETUSERMODE();
2377 #endif
2378     SV * const addrsv = POPs;
2379     /* OK, so on what platform does bind modify addr?  */
2380     const char *addr;
2381     GV * const gv = (GV*)POPs;
2382     register IO * const io = GvIOn(gv);
2383     STRLEN len;
2384     int bind_ok = 0;
2385 #ifdef MPE
2386     int mpeprivmode = 0;
2387 #endif
2388
2389     if (!io || !IoIFP(io))
2390         goto nuts;
2391
2392     addr = SvPV_const(addrsv, len);
2393     TAINT_PROPER("bind");
2394 #ifdef MPE /* Deal with MPE bind() peculiarities */
2395     if (((struct sockaddr *)addr)->sa_family == AF_INET) {
2396         /* The address *MUST* stupidly be zero. */
2397         ((struct sockaddr_in *)addr)->sin_addr.s_addr = INADDR_ANY;
2398         /* PRIV mode is required to bind() to ports < 1024. */
2399         if (((struct sockaddr_in *)addr)->sin_port < 1024 &&
2400             ((struct sockaddr_in *)addr)->sin_port > 0) {
2401             GETPRIVMODE(); /* If this fails, we are aborted by MPE/iX. */
2402             mpeprivmode = 1;
2403         }
2404     }
2405 #endif /* MPE */
2406     if (PerlSock_bind(PerlIO_fileno(IoIFP(io)),
2407                       (struct sockaddr *)addr, len) >= 0)
2408         bind_ok = 1;
2409
2410 #ifdef MPE /* Switch back to USER mode */
2411     if (mpeprivmode)
2412         GETUSERMODE();
2413 #endif /* MPE */
2414
2415     if (bind_ok)
2416         RETPUSHYES;
2417     else
2418         RETPUSHUNDEF;
2419
2420 nuts:
2421     if (ckWARN(WARN_CLOSED))
2422         report_evil_fh(gv, io, PL_op->op_type);
2423     SETERRNO(EBADF,SS_IVCHAN);
2424     RETPUSHUNDEF;
2425 #else
2426     DIE(aTHX_ PL_no_sock_func, "bind");
2427 #endif
2428 }
2429
2430 PP(pp_connect)
2431 {
2432 #ifdef HAS_SOCKET
2433     dSP;
2434     SV * const addrsv = POPs;
2435     GV * const gv = (GV*)POPs;
2436     register IO * const io = GvIOn(gv);
2437     const char *addr;
2438     STRLEN len;
2439
2440     if (!io || !IoIFP(io))
2441         goto nuts;
2442
2443     addr = SvPV_const(addrsv, len);
2444     TAINT_PROPER("connect");
2445     if (PerlSock_connect(PerlIO_fileno(IoIFP(io)), (struct sockaddr *)addr, len) >= 0)
2446         RETPUSHYES;
2447     else
2448         RETPUSHUNDEF;
2449
2450 nuts:
2451     if (ckWARN(WARN_CLOSED))
2452         report_evil_fh(gv, io, PL_op->op_type);
2453     SETERRNO(EBADF,SS_IVCHAN);
2454     RETPUSHUNDEF;
2455 #else
2456     DIE(aTHX_ PL_no_sock_func, "connect");
2457 #endif
2458 }
2459
2460 PP(pp_listen)
2461 {
2462 #ifdef HAS_SOCKET
2463     dSP;
2464     const int backlog = POPi;
2465     GV * const gv = (GV*)POPs;
2466     register IO * const io = gv ? GvIOn(gv) : NULL;
2467
2468     if (!gv || !io || !IoIFP(io))
2469         goto nuts;
2470
2471     if (PerlSock_listen(PerlIO_fileno(IoIFP(io)), backlog) >= 0)
2472         RETPUSHYES;
2473     else
2474         RETPUSHUNDEF;
2475
2476 nuts:
2477     if (ckWARN(WARN_CLOSED))
2478         report_evil_fh(gv, io, PL_op->op_type);
2479     SETERRNO(EBADF,SS_IVCHAN);
2480     RETPUSHUNDEF;
2481 #else
2482     DIE(aTHX_ PL_no_sock_func, "listen");
2483 #endif
2484 }
2485
2486 PP(pp_accept)
2487 {
2488 #ifdef HAS_SOCKET
2489     dSP; dTARGET;
2490     register IO *nstio;
2491     register IO *gstio;
2492     char namebuf[MAXPATHLEN];
2493 #if (defined(VMS_DO_SOCKETS) && defined(DECCRTL_SOCKETS)) || defined(MPE) || defined(__QNXNTO__)
2494     Sock_size_t len = sizeof (struct sockaddr_in);
2495 #else
2496     Sock_size_t len = sizeof namebuf;
2497 #endif
2498     GV * const ggv = (GV*)POPs;
2499     GV * const ngv = (GV*)POPs;
2500     int fd;
2501
2502     if (!ngv)
2503         goto badexit;
2504     if (!ggv)
2505         goto nuts;
2506
2507     gstio = GvIO(ggv);
2508     if (!gstio || !IoIFP(gstio))
2509         goto nuts;
2510
2511     nstio = GvIOn(ngv);
2512     fd = PerlSock_accept(PerlIO_fileno(IoIFP(gstio)), (struct sockaddr *) namebuf, &len);
2513     if (fd < 0)
2514         goto badexit;
2515     if (IoIFP(nstio))
2516         do_close(ngv, FALSE);
2517     IoIFP(nstio) = PerlIO_fdopen(fd, "r"SOCKET_OPEN_MODE);
2518     IoOFP(nstio) = PerlIO_fdopen(fd, "w"SOCKET_OPEN_MODE);
2519     IoTYPE(nstio) = IoTYPE_SOCKET;
2520     if (!IoIFP(nstio) || !IoOFP(nstio)) {
2521         if (IoIFP(nstio)) PerlIO_close(IoIFP(nstio));
2522         if (IoOFP(nstio)) PerlIO_close(IoOFP(nstio));
2523         if (!IoIFP(nstio) && !IoOFP(nstio)) PerlLIO_close(fd);
2524         goto badexit;
2525     }
2526 #if defined(HAS_FCNTL) && defined(F_SETFD)
2527     fcntl(fd, F_SETFD, fd > PL_maxsysfd);       /* ensure close-on-exec */
2528 #endif
2529
2530 #ifdef EPOC
2531     len = sizeof (struct sockaddr_in); /* EPOC somehow truncates info */
2532     setbuf( IoIFP(nstio), NULL); /* EPOC gets confused about sockets */
2533 #endif
2534 #ifdef __SCO_VERSION__
2535     len = sizeof (struct sockaddr_in); /* OpenUNIX 8 somehow truncates info */
2536 #endif
2537
2538     PUSHp(namebuf, len);
2539     RETURN;
2540
2541 nuts:
2542     if (ckWARN(WARN_CLOSED))
2543         report_evil_fh(ggv, ggv ? GvIO(ggv) : 0, PL_op->op_type);
2544     SETERRNO(EBADF,SS_IVCHAN);
2545
2546 badexit:
2547     RETPUSHUNDEF;
2548
2549 #else
2550     DIE(aTHX_ PL_no_sock_func, "accept");
2551 #endif
2552 }
2553
2554 PP(pp_shutdown)
2555 {
2556 #ifdef HAS_SOCKET
2557     dSP; dTARGET;
2558     const int how = POPi;
2559     GV * const gv = (GV*)POPs;
2560     register IO * const io = GvIOn(gv);
2561
2562     if (!io || !IoIFP(io))
2563         goto nuts;
2564
2565     PUSHi( PerlSock_shutdown(PerlIO_fileno(IoIFP(io)), how) >= 0 );
2566     RETURN;
2567
2568 nuts:
2569     if (ckWARN(WARN_CLOSED))
2570         report_evil_fh(gv, io, PL_op->op_type);
2571     SETERRNO(EBADF,SS_IVCHAN);
2572     RETPUSHUNDEF;
2573 #else
2574     DIE(aTHX_ PL_no_sock_func, "shutdown");
2575 #endif
2576 }
2577
2578 PP(pp_ssockopt)
2579 {
2580 #ifdef HAS_SOCKET
2581     dSP;
2582     const int optype = PL_op->op_type;
2583     SV * const sv = (optype == OP_GSOCKOPT) ? sv_2mortal(NEWSV(22, 257)) : POPs;
2584     const unsigned int optname = (unsigned int) POPi;
2585     const unsigned int lvl = (unsigned int) POPi;
2586     GV * const gv = (GV*)POPs;
2587     register IO * const io = GvIOn(gv);
2588     int fd;
2589     Sock_size_t len;
2590
2591     if (!io || !IoIFP(io))
2592         goto nuts;
2593
2594     fd = PerlIO_fileno(IoIFP(io));
2595     switch (optype) {
2596     case OP_GSOCKOPT:
2597         SvGROW(sv, 257);
2598         (void)SvPOK_only(sv);
2599         SvCUR_set(sv,256);
2600         *SvEND(sv) ='\0';
2601         len = SvCUR(sv);
2602         if (PerlSock_getsockopt(fd, lvl, optname, SvPVX(sv), &len) < 0)
2603             goto nuts2;
2604         SvCUR_set(sv, len);
2605         *SvEND(sv) ='\0';
2606         PUSHs(sv);
2607         break;
2608     case OP_SSOCKOPT: {
2609 #if defined(__SYMBIAN32__)
2610 # define SETSOCKOPT_OPTION_VALUE_T void *
2611 #else
2612 # define SETSOCKOPT_OPTION_VALUE_T const char *
2613 #endif
2614         /* XXX TODO: We need to have a proper type (a Configure probe,
2615          * etc.) for what the C headers think of the third argument of
2616          * setsockopt(), the option_value read-only buffer: is it
2617          * a "char *", or a "void *", const or not.  Some compilers
2618          * don't take kindly to e.g. assuming that "char *" implicitly
2619          * promotes to a "void *", or to explicitly promoting/demoting
2620          * consts to non/vice versa.  The "const void *" is the SUS
2621          * definition, but that does not fly everywhere for the above
2622          * reasons. */
2623             SETSOCKOPT_OPTION_VALUE_T buf;
2624             int aint;
2625             if (SvPOKp(sv)) {
2626                 STRLEN l;
2627                 buf = (SETSOCKOPT_OPTION_VALUE_T) SvPV_const(sv, l);
2628                 len = l;
2629             }
2630             else {
2631                 aint = (int)SvIV(sv);
2632                 buf = (SETSOCKOPT_OPTION_VALUE_T) &aint;
2633                 len = sizeof(int);
2634             }
2635             if (PerlSock_setsockopt(fd, lvl, optname, buf, len) < 0)
2636                 goto nuts2;
2637             PUSHs(&PL_sv_yes);
2638         }
2639         break;
2640     }
2641     RETURN;
2642
2643 nuts:
2644     if (ckWARN(WARN_CLOSED))
2645         report_evil_fh(gv, io, optype);
2646     SETERRNO(EBADF,SS_IVCHAN);
2647 nuts2:
2648     RETPUSHUNDEF;
2649
2650 #else
2651     DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
2652 #endif
2653 }
2654
2655 PP(pp_getpeername)
2656 {
2657 #ifdef HAS_SOCKET
2658     dSP;
2659     const int optype = PL_op->op_type;
2660     GV * const gv = (GV*)POPs;
2661     register IO * const io = GvIOn(gv);
2662     Sock_size_t len;
2663     SV *sv;
2664     int fd;
2665
2666     if (!io || !IoIFP(io))
2667         goto nuts;
2668
2669     sv = sv_2mortal(NEWSV(22, 257));
2670     (void)SvPOK_only(sv);
2671     len = 256;
2672     SvCUR_set(sv, len);
2673     *SvEND(sv) ='\0';
2674     fd = PerlIO_fileno(IoIFP(io));
2675     switch (optype) {
2676     case OP_GETSOCKNAME:
2677         if (PerlSock_getsockname(fd, (struct sockaddr *)SvPVX(sv), &len) < 0)
2678             goto nuts2;
2679         break;
2680     case OP_GETPEERNAME:
2681         if (PerlSock_getpeername(fd, (struct sockaddr *)SvPVX(sv), &len) < 0)
2682             goto nuts2;
2683 #if defined(VMS_DO_SOCKETS) && defined (DECCRTL_SOCKETS)
2684         {
2685             static const char nowhere[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
2686             /* If the call succeeded, make sure we don't have a zeroed port/addr */
2687             if (((struct sockaddr *)SvPVX_const(sv))->sa_family == AF_INET &&
2688                 !memcmp(SvPVX_const(sv) + sizeof(u_short), nowhere,
2689                         sizeof(u_short) + sizeof(struct in_addr))) {
2690                 goto nuts2;     
2691             }
2692         }
2693 #endif
2694         break;
2695     }
2696 #ifdef BOGUS_GETNAME_RETURN
2697     /* Interactive Unix, getpeername() and getsockname()
2698       does not return valid namelen */
2699     if (len == BOGUS_GETNAME_RETURN)
2700         len = sizeof(struct sockaddr);
2701 #endif
2702     SvCUR_set(sv, len);
2703     *SvEND(sv) ='\0';
2704     PUSHs(sv);
2705     RETURN;
2706
2707 nuts:
2708     if (ckWARN(WARN_CLOSED))
2709         report_evil_fh(gv, io, optype);
2710     SETERRNO(EBADF,SS_IVCHAN);
2711 nuts2:
2712     RETPUSHUNDEF;
2713
2714 #else
2715     DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
2716 #endif
2717 }
2718
2719 /* Stat calls. */
2720
2721 PP(pp_stat)
2722 {
2723     dSP;
2724     GV *gv;
2725     I32 gimme;
2726     I32 max = 13;
2727
2728     if (PL_op->op_flags & OPf_REF) {
2729         gv = cGVOP_gv;
2730         if (PL_op->op_type == OP_LSTAT) {
2731             if (gv != PL_defgv) {
2732             do_fstat_warning_check:
2733                 if (ckWARN(WARN_IO))
2734                     Perl_warner(aTHX_ packWARN(WARN_IO),
2735                         "lstat() on filehandle %s", GvENAME(gv));
2736             } else if (PL_laststype != OP_LSTAT)
2737                 Perl_croak(aTHX_ "The stat preceding lstat() wasn't an lstat");
2738         }
2739
2740       do_fstat:
2741         if (gv != PL_defgv) {
2742             PL_laststype = OP_STAT;
2743             PL_statgv = gv;
2744             sv_setpvn(PL_statname, "", 0);
2745             PL_laststatval = (GvIO(gv) && IoIFP(GvIOp(gv))
2746                 ? PerlLIO_fstat(PerlIO_fileno(IoIFP(GvIOn(gv))), &PL_statcache) : -1);
2747         }
2748         if (PL_laststatval < 0) {
2749             if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2750                 report_evil_fh(gv, GvIO(gv), PL_op->op_type);
2751             max = 0;
2752         }
2753     }
2754     else {
2755         SV* const sv = POPs;
2756         if (SvTYPE(sv) == SVt_PVGV) {
2757             gv = (GV*)sv;
2758             goto do_fstat;
2759         }
2760         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV) {
2761             gv = (GV*)SvRV(sv);
2762             if (PL_op->op_type == OP_LSTAT)
2763                 goto do_fstat_warning_check;
2764             goto do_fstat;
2765         }
2766         sv_setpv(PL_statname, SvPV_nolen_const(sv));
2767         PL_statgv = Nullgv;
2768         PL_laststype = PL_op->op_type;
2769         if (PL_op->op_type == OP_LSTAT)
2770             PL_laststatval = PerlLIO_lstat(SvPV_nolen_const(PL_statname), &PL_statcache);
2771         else
2772             PL_laststatval = PerlLIO_stat(SvPV_nolen_const(PL_statname), &PL_statcache);
2773         if (PL_laststatval < 0) {
2774             if (ckWARN(WARN_NEWLINE) && strchr(SvPV_nolen_const(PL_statname), '\n'))
2775                 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
2776             max = 0;
2777         }
2778     }
2779
2780     gimme = GIMME_V;
2781     if (gimme != G_ARRAY) {
2782         if (gimme != G_VOID)
2783             XPUSHs(boolSV(max));
2784         RETURN;
2785     }
2786     if (max) {
2787         EXTEND(SP, max);
2788         EXTEND_MORTAL(max);
2789         PUSHs(sv_2mortal(newSViv(PL_statcache.st_dev)));
2790         PUSHs(sv_2mortal(newSViv(PL_statcache.st_ino)));
2791         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_mode)));
2792         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_nlink)));
2793 #if Uid_t_size > IVSIZE
2794         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_uid)));
2795 #else
2796 #   if Uid_t_sign <= 0
2797         PUSHs(sv_2mortal(newSViv(PL_statcache.st_uid)));
2798 #   else
2799         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_uid)));
2800 #   endif
2801 #endif
2802 #if Gid_t_size > IVSIZE
2803         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_gid)));
2804 #else
2805 #   if Gid_t_sign <= 0
2806         PUSHs(sv_2mortal(newSViv(PL_statcache.st_gid)));
2807 #   else
2808         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_gid)));
2809 #   endif
2810 #endif
2811 #ifdef USE_STAT_RDEV
2812         PUSHs(sv_2mortal(newSViv(PL_statcache.st_rdev)));
2813 #else
2814         PUSHs(sv_2mortal(newSVpvn("", 0)));
2815 #endif
2816 #if Off_t_size > IVSIZE
2817         PUSHs(sv_2mortal(newSVnv((NV)PL_statcache.st_size)));
2818 #else
2819         PUSHs(sv_2mortal(newSViv(PL_statcache.st_size)));
2820 #endif
2821 #ifdef BIG_TIME
2822         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_atime)));
2823         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_mtime)));
2824         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_ctime)));
2825 #else
2826         PUSHs(sv_2mortal(newSViv(PL_statcache.st_atime)));
2827         PUSHs(sv_2mortal(newSViv(PL_statcache.st_mtime)));
2828         PUSHs(sv_2mortal(newSViv(PL_statcache.st_ctime)));
2829 #endif
2830 #ifdef USE_STAT_BLOCKS
2831         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_blksize)));
2832         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_blocks)));
2833 #else
2834         PUSHs(sv_2mortal(newSVpvn("", 0)));
2835         PUSHs(sv_2mortal(newSVpvn("", 0)));
2836 #endif
2837     }
2838     RETURN;
2839 }
2840
2841 /* This macro is used by the stacked filetest operators :
2842  * if the previous filetest failed, short-circuit and pass its value.
2843  * Else, discard it from the stack and continue. --rgs
2844  */
2845 #define STACKED_FTEST_CHECK if (PL_op->op_private & OPpFT_STACKED) { \
2846         if (TOPs == &PL_sv_no || TOPs == &PL_sv_undef) { RETURN; } \
2847         else { (void)POPs; PUTBACK; } \
2848     }
2849
2850 PP(pp_ftrread)
2851 {
2852     I32 result;
2853     /* Not const, because things tweak this below. Not bool, because there's
2854        no guarantee that OPp_FT_ACCESS is <= CHAR_MAX  */
2855 #if defined(HAS_ACCESS) || defined (PERL_EFF_ACCESS)
2856     I32 use_access = PL_op->op_private & OPpFT_ACCESS;
2857     /* Giving some sort of initial value silences compilers.  */
2858 #  ifdef R_OK
2859     int access_mode = R_OK;
2860 #  else
2861     int access_mode = 0;
2862 #  endif
2863 #else
2864     /* access_mode is never used, but leaving use_access in makes the
2865        conditional compiling below much clearer.  */
2866     I32 use_access = 0;
2867 #endif
2868     int stat_mode = S_IRUSR;
2869
2870     bool effective = FALSE;
2871     dSP;
2872
2873     STACKED_FTEST_CHECK;
2874
2875     switch (PL_op->op_type) {
2876     case OP_FTRREAD:
2877 #if !(defined(HAS_ACCESS) && defined(R_OK))
2878         use_access = 0;
2879 #endif
2880         break;
2881
2882     case OP_FTRWRITE:
2883 #if defined(HAS_ACCESS) && defined(W_OK)
2884         access_mode = W_OK;
2885 #else
2886         use_access = 0;
2887 #endif
2888         stat_mode = S_IWUSR;
2889         break;
2890
2891     case OP_FTREXEC:
2892 #if defined(HAS_ACCESS) && defined(X_OK)
2893         access_mode = X_OK;
2894 #else
2895         use_access = 0;
2896 #endif
2897         stat_mode = S_IXUSR;
2898         break;
2899
2900     case OP_FTEWRITE:
2901 #ifdef PERL_EFF_ACCESS
2902         access_mode = W_OK;
2903 #endif
2904         stat_mode = S_IWUSR;
2905         /* Fall through  */
2906
2907     case OP_FTEREAD:
2908 #ifndef PERL_EFF_ACCESS
2909         use_access = 0;
2910 #endif
2911         effective = TRUE;
2912         break;
2913
2914
2915     case OP_FTEEXEC:
2916 #ifdef PERL_EFF_ACCESS
2917         access_mode = W_OK;
2918 #else
2919         use_access = 0;
2920 #endif
2921         stat_mode = S_IXUSR;
2922         effective = TRUE;
2923         break;
2924     }
2925
2926     if (use_access) {
2927 #if defined(HAS_ACCESS) || defined (PERL_EFF_ACCESS)
2928         const char *const name = POPpx;
2929         if (effective) {
2930 #  ifdef PERL_EFF_ACCESS
2931             result = PERL_EFF_ACCESS(name, access_mode);
2932 #  else
2933             DIE(aTHX_ "panic: attempt to call PERL_EFF_ACCESS in %s",
2934                 OP_NAME(PL_op));
2935 #  endif
2936         }
2937         else {
2938 #  ifdef HAS_ACCESS
2939             result = access(name, access_mode);
2940 #  else
2941             DIE(aTHX_ "panic: attempt to call access() in %s", OP_NAME(PL_op));
2942 #  endif
2943         }
2944         if (result == 0)
2945             RETPUSHYES;
2946         if (result < 0)
2947             RETPUSHUNDEF;
2948         RETPUSHNO;
2949 #endif
2950     }
2951
2952     result = my_stat();
2953     SPAGAIN;
2954     if (result < 0)
2955         RETPUSHUNDEF;
2956     if (cando(stat_mode, effective, &PL_statcache))
2957         RETPUSHYES;
2958     RETPUSHNO;
2959 }
2960
2961 PP(pp_ftis)
2962 {
2963     I32 result;
2964     const int op_type = PL_op->op_type;
2965     dSP;
2966     STACKED_FTEST_CHECK;
2967     result = my_stat();
2968     SPAGAIN;
2969     if (result < 0)
2970         RETPUSHUNDEF;
2971     if (op_type == OP_FTIS)
2972         RETPUSHYES;
2973     {
2974         /* You can't dTARGET inside OP_FTIS, because you'll get
2975            "panic: pad_sv po" - the op is not flagged to have a target.  */
2976         dTARGET;
2977         switch (op_type) {
2978         case OP_FTSIZE:
2979 #if Off_t_size > IVSIZE
2980             PUSHn(PL_statcache.st_size);
2981 #else
2982             PUSHi(PL_statcache.st_size);
2983 #endif
2984             break;
2985         case OP_FTMTIME:
2986             PUSHn( (((NV)PL_basetime - PL_statcache.st_mtime)) / 86400.0 );
2987             break;
2988         case OP_FTATIME:
2989             PUSHn( (((NV)PL_basetime - PL_statcache.st_atime)) / 86400.0 );
2990             break;
2991         case OP_FTCTIME:
2992             PUSHn( (((NV)PL_basetime - PL_statcache.st_ctime)) / 86400.0 );
2993             break;
2994         }
2995     }
2996     RETURN;
2997 }
2998
2999 PP(pp_ftrowned)
3000 {
3001     I32 result;
3002     dSP;
3003
3004     /* I believe that all these three are likely to be defined on most every
3005        system these days.  */
3006 #ifndef S_ISUID
3007     if(PL_op->op_type == OP_FTSUID)
3008         RETPUSHNO;
3009 #endif
3010 #ifndef S_ISGID
3011     if(PL_op->op_type == OP_FTSGID)
3012         RETPUSHNO;
3013 #endif
3014 #ifndef S_ISVTX
3015     if(PL_op->op_type == OP_FTSVTX)
3016         RETPUSHNO;
3017 #endif
3018
3019     STACKED_FTEST_CHECK;
3020     result = my_stat();
3021     SPAGAIN;
3022     if (result < 0)
3023         RETPUSHUNDEF;
3024     switch (PL_op->op_type) {
3025     case OP_FTROWNED:
3026         if (PL_statcache.st_uid == PL_uid)
3027             RETPUSHYES;
3028         break;
3029     case OP_FTEOWNED:
3030         if (PL_statcache.st_uid == PL_euid)
3031             RETPUSHYES;
3032         break;
3033     case OP_FTZERO:
3034         if (PL_statcache.st_size == 0)
3035             RETPUSHYES;
3036         break;
3037     case OP_FTSOCK:
3038         if (S_ISSOCK(PL_statcache.st_mode))
3039             RETPUSHYES;
3040         break;
3041     case OP_FTCHR:
3042         if (S_ISCHR(PL_statcache.st_mode))
3043             RETPUSHYES;
3044         break;
3045     case OP_FTBLK:
3046         if (S_ISBLK(PL_statcache.st_mode))
3047             RETPUSHYES;
3048         break;
3049     case OP_FTFILE:
3050         if (S_ISREG(PL_statcache.st_mode))
3051             RETPUSHYES;
3052         break;
3053     case OP_FTDIR:
3054         if (S_ISDIR(PL_statcache.st_mode))
3055             RETPUSHYES;
3056         break;
3057     case OP_FTPIPE:
3058         if (S_ISFIFO(PL_statcache.st_mode))
3059             RETPUSHYES;
3060         break;
3061 #ifdef S_ISUID
3062     case OP_FTSUID:
3063         if (PL_statcache.st_mode & S_ISUID)
3064             RETPUSHYES;
3065         break;
3066 #endif
3067 #ifdef S_ISGID
3068     case OP_FTSGID:
3069         if (PL_statcache.st_mode & S_ISGID)
3070             RETPUSHYES;
3071         break;
3072 #endif
3073 #ifdef S_ISVTX
3074     case OP_FTSVTX:
3075         if (PL_statcache.st_mode & S_ISVTX)
3076             RETPUSHYES;
3077         break;
3078 #endif
3079     }
3080     RETPUSHNO;
3081 }
3082
3083 PP(pp_ftlink)
3084 {
3085     I32 result = my_lstat();
3086     dSP;
3087     if (result < 0)
3088         RETPUSHUNDEF;
3089     if (S_ISLNK(PL_statcache.st_mode))
3090         RETPUSHYES;
3091     RETPUSHNO;
3092 }
3093
3094 PP(pp_fttty)
3095 {
3096     dSP;
3097     int fd;
3098     GV *gv;
3099     SV *tmpsv = Nullsv;
3100
3101     STACKED_FTEST_CHECK;
3102
3103     if (PL_op->op_flags & OPf_REF)
3104         gv = cGVOP_gv;
3105     else if (isGV(TOPs))
3106         gv = (GV*)POPs;
3107     else if (SvROK(TOPs) && isGV(SvRV(TOPs)))
3108         gv = (GV*)SvRV(POPs);
3109     else
3110         gv = gv_fetchsv(tmpsv = POPs, FALSE, SVt_PVIO);
3111
3112     if (GvIO(gv) && IoIFP(GvIOp(gv)))
3113         fd = PerlIO_fileno(IoIFP(GvIOp(gv)));
3114     else if (tmpsv && SvOK(tmpsv)) {
3115         const char *tmps = SvPV_nolen_const(tmpsv);
3116         if (isDIGIT(*tmps))
3117             fd = atoi(tmps);
3118         else 
3119             RETPUSHUNDEF;
3120     }
3121     else
3122         RETPUSHUNDEF;
3123     if (PerlLIO_isatty(fd))
3124         RETPUSHYES;
3125     RETPUSHNO;
3126 }
3127
3128 #if defined(atarist) /* this will work with atariST. Configure will
3129                         make guesses for other systems. */
3130 # define FILE_base(f) ((f)->_base)
3131 # define FILE_ptr(f) ((f)->_ptr)
3132 # define FILE_cnt(f) ((f)->_cnt)
3133 # define FILE_bufsiz(f) ((f)->_cnt + ((f)->_ptr - (f)->_base))
3134 #endif
3135
3136 PP(pp_fttext)
3137 {
3138     dSP;
3139     I32 i;
3140     I32 len;
3141     I32 odd = 0;
3142     STDCHAR tbuf[512];
3143     register STDCHAR *s;
3144     register IO *io;
3145     register SV *sv;
3146     GV *gv;
3147     PerlIO *fp;
3148
3149     STACKED_FTEST_CHECK;
3150
3151     if (PL_op->op_flags & OPf_REF)
3152         gv = cGVOP_gv;
3153     else if (isGV(TOPs))
3154         gv = (GV*)POPs;
3155     else if (SvROK(TOPs) && isGV(SvRV(TOPs)))
3156         gv = (GV*)SvRV(POPs);
3157     else
3158         gv = Nullgv;
3159
3160     if (gv) {
3161         EXTEND(SP, 1);
3162         if (gv == PL_defgv) {
3163             if (PL_statgv)
3164                 io = GvIO(PL_statgv);
3165             else {
3166                 sv = PL_statname;
3167                 goto really_filename;
3168             }
3169         }
3170         else {
3171             PL_statgv = gv;
3172             PL_laststatval = -1;
3173             sv_setpvn(PL_statname, "", 0);
3174             io = GvIO(PL_statgv);
3175         }
3176         if (io && IoIFP(io)) {
3177             if (! PerlIO_has_base(IoIFP(io)))
3178                 DIE(aTHX_ "-T and -B not implemented on filehandles");
3179             PL_laststatval = PerlLIO_fstat(PerlIO_fileno(IoIFP(io)), &PL_statcache);
3180             if (PL_laststatval < 0)
3181                 RETPUSHUNDEF;
3182             if (S_ISDIR(PL_statcache.st_mode)) { /* handle NFS glitch */
3183                 if (PL_op->op_type == OP_FTTEXT)
3184                     RETPUSHNO;
3185                 else
3186                     RETPUSHYES;
3187             }
3188             if (PerlIO_get_cnt(IoIFP(io)) <= 0) {
3189                 i = PerlIO_getc(IoIFP(io));
3190                 if (i != EOF)
3191                     (void)PerlIO_ungetc(IoIFP(io),i);
3192             }
3193             if (PerlIO_get_cnt(IoIFP(io)) <= 0) /* null file is anything */
3194                 RETPUSHYES;
3195             len = PerlIO_get_bufsiz(IoIFP(io));
3196             s = (STDCHAR *) PerlIO_get_base(IoIFP(io));
3197             /* sfio can have large buffers - limit to 512 */
3198             if (len > 512)
3199                 len = 512;
3200         }
3201         else {
3202             if (ckWARN2(WARN_UNOPENED,WARN_CLOSED)) {
3203                 gv = cGVOP_gv;
3204                 report_evil_fh(gv, GvIO(gv), PL_op->op_type);
3205             }
3206             SETERRNO(EBADF,RMS_IFI);
3207             RETPUSHUNDEF;
3208         }
3209     }
3210     else {
3211         sv = POPs;
3212       really_filename:
3213         PL_statgv = Nullgv;
3214         PL_laststype = OP_STAT;
3215         sv_setpv(PL_statname, SvPV_nolen_const(sv));
3216         if (!(fp = PerlIO_open(SvPVX_const(PL_statname), "r"))) {
3217             if (ckWARN(WARN_NEWLINE) && strchr(SvPV_nolen_const(PL_statname),
3218                                                '\n'))
3219                 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
3220             RETPUSHUNDEF;
3221         }
3222         PL_laststatval = PerlLIO_fstat(PerlIO_fileno(fp), &PL_statcache);
3223         if (PL_laststatval < 0) {
3224             (void)PerlIO_close(fp);
3225             RETPUSHUNDEF;
3226         }
3227         PerlIO_binmode(aTHX_ fp, '<', O_BINARY, Nullch);
3228         len = PerlIO_read(fp, tbuf, sizeof(tbuf));
3229         (void)PerlIO_close(fp);
3230         if (len <= 0) {
3231             if (S_ISDIR(PL_statcache.st_mode) && PL_op->op_type == OP_FTTEXT)
3232                 RETPUSHNO;              /* special case NFS directories */
3233             RETPUSHYES;         /* null file is anything */
3234         }
3235         s = tbuf;
3236     }
3237
3238     /* now scan s to look for textiness */
3239     /*   XXX ASCII dependent code */
3240
3241 #if defined(DOSISH) || defined(USEMYBINMODE)
3242     /* ignore trailing ^Z on short files */
3243     if (len && len < sizeof(tbuf) && tbuf[len-1] == 26)
3244         --len;
3245 #endif
3246
3247     for (i = 0; i < len; i++, s++) {
3248         if (!*s) {                      /* null never allowed in text */
3249             odd += len;
3250             break;
3251         }
3252 #ifdef EBCDIC
3253         else if (!(isPRINT(*s) || isSPACE(*s)))
3254             odd++;
3255 #else
3256         else if (*s & 128) {
3257 #ifdef USE_LOCALE
3258             if (IN_LOCALE_RUNTIME && isALPHA_LC(*s))
3259                 continue;
3260 #endif
3261             /* utf8 characters don't count as odd */
3262             if (UTF8_IS_START(*s)) {
3263                 int ulen = UTF8SKIP(s);
3264                 if (ulen < len - i) {
3265                     int j;
3266                     for (j = 1; j < ulen; j++) {
3267                         if (!UTF8_IS_CONTINUATION(s[j]))
3268                             goto not_utf8;
3269                     }
3270                     --ulen;     /* loop does extra increment */
3271                     s += ulen;
3272                     i += ulen;
3273                     continue;
3274                 }
3275             }
3276           not_utf8:
3277             odd++;
3278         }
3279         else if (*s < 32 &&
3280           *s != '\n' && *s != '\r' && *s != '\b' &&
3281           *s != '\t' && *s != '\f' && *s != 27)
3282             odd++;
3283 #endif
3284     }
3285
3286     if ((odd * 3 > len) == (PL_op->op_type == OP_FTTEXT)) /* allow 1/3 odd */
3287         RETPUSHNO;
3288     else
3289         RETPUSHYES;
3290 }
3291
3292 /* File calls. */
3293
3294 PP(pp_chdir)
3295 {
3296     dSP; dTARGET;
3297     const char *tmps = 0;
3298     GV *gv = NULL;
3299
3300     if( MAXARG == 1 ) {
3301         SV * const sv = POPs;
3302         if (SvTYPE(sv) == SVt_PVGV) {
3303             gv = (GV*)sv;
3304         }
3305         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV) {
3306             gv = (GV*)SvRV(sv);
3307         }
3308         else {
3309             tmps = SvPVx_nolen_const(sv);
3310         }
3311     }
3312
3313     if( !gv && (!tmps || !*tmps) ) {
3314         HV * const table = GvHVn(PL_envgv);
3315         SV **svp;
3316
3317         if (    (svp = hv_fetch(table, "HOME", 4, FALSE))
3318              || (svp = hv_fetch(table, "LOGDIR", 6, FALSE))
3319 #ifdef VMS
3320              || (svp = hv_fetch(table, "SYS$LOGIN", 9, FALSE))
3321 #endif
3322            )
3323         {
3324             if( MAXARG == 1 )
3325                 deprecate("chdir('') or chdir(undef) as chdir()");
3326             tmps = SvPV_nolen_const(*svp);
3327         }
3328         else {
3329             PUSHi(0);
3330             TAINT_PROPER("chdir");
3331             RETURN;
3332         }
3333     }
3334
3335     TAINT_PROPER("chdir");
3336     if (gv) {
3337 #ifdef HAS_FCHDIR
3338         IO* const io = GvIO(gv);
3339         if (io) {
3340             if (IoIFP(io)) {
3341                 PUSHi(fchdir(PerlIO_fileno(IoIFP(io))) >= 0);
3342             }
3343             else if (IoDIRP(io)) {
3344 #ifdef HAS_DIRFD
3345                 PUSHi(fchdir(dirfd(IoDIRP(io))) >= 0);
3346 #else
3347                 DIE(aTHX_ PL_no_func, "dirfd");
3348 #endif
3349             }
3350             else {
3351                 PUSHi(0);
3352             }
3353         }
3354         else {
3355             PUSHi(0);
3356         }
3357 #else
3358         DIE(aTHX_ PL_no_func, "fchdir");
3359 #endif
3360     }
3361     else 
3362         PUSHi( PerlDir_chdir(tmps) >= 0 );
3363 #ifdef VMS
3364     /* Clear the DEFAULT element of ENV so we'll get the new value
3365      * in the future. */
3366     hv_delete(GvHVn(PL_envgv),"DEFAULT",7,G_DISCARD);
3367 #endif
3368     RETURN;
3369 }
3370
3371 PP(pp_chown)
3372 {
3373     dSP; dMARK; dTARGET;
3374     const I32 value = (I32)apply(PL_op->op_type, MARK, SP);
3375
3376     SP = MARK;
3377     XPUSHi(value);
3378     RETURN;
3379 }
3380
3381 PP(pp_chroot)
3382 {
3383 #ifdef HAS_CHROOT
3384     dSP; dTARGET;
3385     char * const tmps = POPpx;
3386     TAINT_PROPER("chroot");
3387     PUSHi( chroot(tmps) >= 0 );
3388     RETURN;
3389 #else
3390     DIE(aTHX_ PL_no_func, "chroot");
3391 #endif
3392 }
3393
3394 PP(pp_rename)
3395 {
3396     dSP; dTARGET;
3397     int anum;
3398     const char * const tmps2 = POPpconstx;
3399     const char * const tmps = SvPV_nolen_const(TOPs);
3400     TAINT_PROPER("rename");
3401 #ifdef HAS_RENAME
3402     anum = PerlLIO_rename(tmps, tmps2);
3403 #else
3404     if (!(anum = PerlLIO_stat(tmps, &PL_statbuf))) {
3405         if (same_dirent(tmps2, tmps))   /* can always rename to same name */
3406             anum = 1;
3407         else {
3408             if (PL_euid || PerlLIO_stat(tmps2, &PL_statbuf) < 0 || !S_ISDIR(PL_statbuf.st_mode))
3409                 (void)UNLINK(tmps2);
3410             if (!(anum = link(tmps, tmps2)))
3411                 anum = UNLINK(tmps);
3412         }
3413     }
3414 #endif
3415     SETi( anum >= 0 );
3416     RETURN;
3417 }
3418
3419 #if defined(HAS_LINK) || defined(HAS_SYMLINK)
3420 PP(pp_link)
3421 {
3422     dSP; dTARGET;
3423     const int op_type = PL_op->op_type;
3424     int result;
3425
3426 #  ifndef HAS_LINK
3427     if (op_type == OP_LINK)
3428         DIE(aTHX_ PL_no_func, "link");
3429 #  endif
3430 #  ifndef HAS_SYMLINK
3431     if (op_type == OP_SYMLINK)
3432         DIE(aTHX_ PL_no_func, "symlink");
3433 #  endif
3434
3435     {
3436         const char * const tmps2 = POPpconstx;
3437         const char * const tmps = SvPV_nolen_const(TOPs);
3438         TAINT_PROPER(PL_op_desc[op_type]);
3439         result =
3440 #  if defined(HAS_LINK)
3441 #    if defined(HAS_SYMLINK)
3442             /* Both present - need to choose which.  */
3443             (op_type == OP_LINK) ?
3444             PerlLIO_link(tmps, tmps2) : symlink(tmps, tmps2);
3445 #    else
3446     /* Only have link, so calls to pp_symlink will have DIE()d above.  */
3447         PerlLIO_link(tmps, tmps2);
3448 #    endif
3449 #  else
3450 #    if defined(HAS_SYMLINK)
3451     /* Only have symlink, so calls to pp_link will have DIE()d above.  */
3452         symlink(tmps, tmps2);
3453 #    endif
3454 #  endif
3455     }
3456
3457     SETi( result >= 0 );
3458     RETURN;
3459 }
3460 #else
3461 PP(pp_link)
3462 {
3463     /* Have neither.  */
3464     DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
3465 }
3466 #endif
3467
3468 PP(pp_readlink)
3469 {
3470     dSP;
3471 #ifdef HAS_SYMLINK
3472     dTARGET;
3473     const char *tmps;
3474     char buf[MAXPATHLEN];
3475     int len;
3476
3477 #ifndef INCOMPLETE_TAINTS
3478     TAINT;
3479 #endif
3480     tmps = POPpconstx;
3481     len = readlink(tmps, buf, sizeof(buf) - 1);
3482     EXTEND(SP, 1);
3483     if (len < 0)
3484         RETPUSHUNDEF;
3485     PUSHp(buf, len);
3486     RETURN;
3487 #else
3488     EXTEND(SP, 1);
3489     RETSETUNDEF;                /* just pretend it's a normal file */
3490 #endif
3491 }
3492
3493 #if !defined(HAS_MKDIR) || !defined(HAS_RMDIR)
3494 STATIC int
3495 S_dooneliner(pTHX_ const char *cmd, const char *filename)
3496 {
3497     char * const save_filename = filename;
3498     char *cmdline;
3499     char *s;
3500     PerlIO *myfp;
3501     int anum = 1;
3502
3503     Newx(cmdline, strlen(cmd) + (strlen(filename) * 2) + 10, char);
3504     strcpy(cmdline, cmd);
3505     strcat(cmdline, " ");
3506     for (s = cmdline + strlen(cmdline); *filename; ) {
3507         *s++ = '\\';
3508         *s++ = *filename++;
3509     }
3510     strcpy(s, " 2>&1");
3511     myfp = PerlProc_popen(cmdline, "r");
3512     Safefree(cmdline);
3513
3514     if (myfp) {
3515         SV *tmpsv = sv_newmortal();
3516         /* Need to save/restore 'PL_rs' ?? */
3517         s = sv_gets(tmpsv, myfp, 0);
3518         (void)PerlProc_pclose(myfp);
3519         if (s != Nullch) {
3520             int e;
3521             for (e = 1;
3522 #ifdef HAS_SYS_ERRLIST
3523                  e <= sys_nerr
3524 #endif
3525                  ; e++)
3526             {
3527                 /* you don't see this */
3528                 char *errmsg =
3529 #ifdef HAS_SYS_ERRLIST
3530                     sys_errlist[e]
3531 #else
3532                     strerror(e)
3533 #endif
3534                     ;
3535                 if (!errmsg)
3536                     break;
3537                 if (instr(s, errmsg)) {
3538                     SETERRNO(e,0);
3539                     return 0;
3540                 }
3541             }
3542             SETERRNO(0,0);
3543 #ifndef EACCES
3544 #define EACCES EPERM
3545 #endif
3546             if (instr(s, "cannot make"))
3547                 SETERRNO(EEXIST,RMS_FEX);
3548             else if (instr(s, "existing file"))
3549                 SETERRNO(EEXIST,RMS_FEX);
3550             else if (instr(s, "ile exists"))
3551                 SETERRNO(EEXIST,RMS_FEX);
3552             else if (instr(s, "non-exist"))
3553                 SETERRNO(ENOENT,RMS_FNF);
3554             else if (instr(s, "does not exist"))
3555                 SETERRNO(ENOENT,RMS_FNF);
3556             else if (instr(s, "not empty"))
3557                 SETERRNO(EBUSY,SS_DEVOFFLINE);
3558             else if (instr(s, "cannot access"))
3559                 SETERRNO(EACCES,RMS_PRV);
3560             else
3561                 SETERRNO(EPERM,RMS_PRV);
3562             return 0;
3563         }
3564         else {  /* some mkdirs return no failure indication */
3565             anum = (PerlLIO_stat(save_filename, &PL_statbuf) >= 0);
3566             if (PL_op->op_type == OP_RMDIR)
3567                 anum = !anum;
3568             if (anum)
3569                 SETERRNO(0,0);
3570             else
3571                 SETERRNO(EACCES,RMS_PRV);       /* a guess */
3572         }
3573         return anum;
3574     }
3575     else
3576         return 0;
3577 }
3578 #endif
3579
3580 /* This macro removes trailing slashes from a directory name.
3581  * Different operating and file systems take differently to
3582  * trailing slashes.  According to POSIX 1003.1 1996 Edition
3583  * any number of trailing slashes should be allowed.
3584  * Thusly we snip them away so that even non-conforming
3585  * systems are happy.
3586  * We should probably do this "filtering" for all
3587  * the functions that expect (potentially) directory names:
3588  * -d, chdir(), chmod(), chown(), chroot(), fcntl()?,
3589  * (mkdir()), opendir(), rename(), rmdir(), stat(). --jhi */
3590
3591 #define TRIMSLASHES(tmps,len,copy) (tmps) = SvPV_const(TOPs, (len)); \
3592     if ((len) > 1 && (tmps)[(len)-1] == '/') { \
3593         do { \
3594             (len)--; \
3595         } while ((len) > 1 && (tmps)[(len)-1] == '/'); \
3596         (tmps) = savepvn((tmps), (len)); \
3597         (copy) = TRUE; \
3598     }
3599
3600 PP(pp_mkdir)
3601 {
3602     dSP; dTARGET;
3603 #ifndef HAS_MKDIR
3604     int oldumask;
3605 #endif
3606     STRLEN len;
3607     const char *tmps;
3608     bool copy = FALSE;
3609     const int mode = (MAXARG > 1) ? POPi : 0777;
3610
3611     TRIMSLASHES(tmps,len,copy);
3612
3613     TAINT_PROPER("mkdir");
3614 #ifdef HAS_MKDIR
3615     SETi( PerlDir_mkdir(tmps, mode) >= 0 );
3616 #else
3617     SETi( dooneliner("mkdir", tmps) );
3618     oldumask = PerlLIO_umask(0);
3619     PerlLIO_umask(oldumask);
3620     PerlLIO_chmod(tmps, (mode & ~oldumask) & 0777);
3621 #endif
3622     if (copy)
3623         Safefree(tmps);
3624     RETURN;
3625 }
3626
3627 PP(pp_rmdir)
3628 {
3629     dSP; dTARGET;
3630     STRLEN len;
3631     const char *tmps;
3632     bool copy = FALSE;
3633
3634     TRIMSLASHES(tmps,len,copy);
3635     TAINT_PROPER("rmdir");
3636 #ifdef HAS_RMDIR
3637     SETi( PerlDir_rmdir(tmps) >= 0 );
3638 #else
3639     SETi( dooneliner("rmdir", tmps) );
3640 #endif
3641     if (copy)
3642         Safefree(tmps);
3643     RETURN;
3644 }
3645
3646 /* Directory calls. */
3647
3648 PP(pp_open_dir)
3649 {
3650 #if defined(Direntry_t) && defined(HAS_READDIR)
3651     dSP;
3652     const char * const dirname = POPpconstx;
3653     GV * const gv = (GV*)POPs;
3654     register IO * const io = GvIOn(gv);
3655
3656     if (!io)
3657         goto nope;
3658
3659     if (IoDIRP(io))
3660         PerlDir_close(IoDIRP(io));
3661     if (!(IoDIRP(io) = PerlDir_open(dirname)))
3662         goto nope;
3663
3664     RETPUSHYES;
3665 nope:
3666     if (!errno)
3667         SETERRNO(EBADF,RMS_DIR);
3668     RETPUSHUNDEF;
3669 #else
3670     DIE(aTHX_ PL_no_dir_func, "opendir");
3671 #endif
3672 }
3673
3674 PP(pp_readdir)
3675 {
3676 #if !defined(Direntry_t) || !defined(HAS_READDIR)
3677     DIE(aTHX_ PL_no_dir_func, "readdir");
3678 #else
3679 #if !defined(I_DIRENT) && !defined(VMS)
3680     Direntry_t *readdir (DIR *);
3681 #endif
3682     dSP;
3683
3684     SV *sv;
3685     const I32 gimme = GIMME;
3686     GV * const gv = (GV *)POPs;
3687     register const Direntry_t *dp;
3688     register IO * const io = GvIOn(gv);
3689
3690     if (!io || !IoDIRP(io))
3691         goto nope;
3692
3693     do {
3694         dp = (Direntry_t *)PerlDir_read(IoDIRP(io));
3695         if (!dp)
3696             break;
3697 #ifdef DIRNAMLEN
3698         sv = newSVpvn(dp->d_name, dp->d_namlen);
3699 #else
3700         sv = newSVpv(dp->d_name, 0);
3701 #endif
3702 #ifndef INCOMPLETE_TAINTS
3703         if (!(IoFLAGS(io) & IOf_UNTAINT))
3704             SvTAINTED_on(sv);
3705 #endif
3706         XPUSHs(sv_2mortal(sv));
3707     }
3708     while (gimme == G_ARRAY);
3709
3710     if (!dp && gimme != G_ARRAY)
3711         goto nope;
3712
3713     RETURN;
3714
3715 nope:
3716     if (!errno)
3717         SETERRNO(EBADF,RMS_ISI);
3718     if (GIMME == G_ARRAY)
3719         RETURN;
3720     else
3721         RETPUSHUNDEF;
3722 #endif
3723 }
3724
3725 PP(pp_telldir)
3726 {
3727 #if defined(HAS_TELLDIR) || defined(telldir)
3728     dVAR; dSP; dTARGET;
3729  /* XXX does _anyone_ need this? --AD 2/20/1998 */
3730  /* XXX netbsd still seemed to.
3731     XXX HAS_TELLDIR_PROTO is new style, NEED_TELLDIR_PROTO is old style.
3732     --JHI 1999-Feb-02 */
3733 # if !defined(HAS_TELLDIR_PROTO) || defined(NEED_TELLDIR_PROTO)
3734     long telldir (DIR *);
3735 # endif
3736     GV * const gv = (GV*)POPs;
3737     register IO * const io = GvIOn(gv);
3738
3739     if (!io || !IoDIRP(io))
3740         goto nope;
3741
3742     PUSHi( PerlDir_tell(IoDIRP(io)) );
3743     RETURN;
3744 nope:
3745     if (!errno)
3746         SETERRNO(EBADF,RMS_ISI);
3747     RETPUSHUNDEF;
3748 #else
3749     DIE(aTHX_ PL_no_dir_func, "telldir");
3750 #endif
3751 }
3752
3753 PP(pp_seekdir)
3754 {
3755 #if defined(HAS_SEEKDIR) || defined(seekdir)
3756     dSP;
3757     const long along = POPl;
3758     GV * const gv = (GV*)POPs;
3759     register IO * const io = GvIOn(gv);
3760
3761     if (!io || !IoDIRP(io))
3762         goto nope;
3763
3764     (void)PerlDir_seek(IoDIRP(io), along);
3765
3766     RETPUSHYES;
3767 nope:
3768     if (!errno)
3769         SETERRNO(EBADF,RMS_ISI);
3770     RETPUSHUNDEF;
3771 #else
3772     DIE(aTHX_ PL_no_dir_func, "seekdir");
3773 #endif
3774 }
3775
3776 PP(pp_rewinddir)
3777 {
3778 #if defined(HAS_REWINDDIR) || defined(rewinddir)
3779     dSP;
3780     GV * const gv = (GV*)POPs;
3781     register IO * const io = GvIOn(gv);
3782
3783     if (!io || !IoDIRP(io))
3784         goto nope;
3785
3786     (void)PerlDir_rewind(IoDIRP(io));
3787     RETPUSHYES;
3788 nope:
3789     if (!errno)
3790         SETERRNO(EBADF,RMS_ISI);
3791     RETPUSHUNDEF;
3792 #else
3793     DIE(aTHX_ PL_no_dir_func, "rewinddir");
3794 #endif
3795 }
3796
3797 PP(pp_closedir)
3798 {
3799 #if defined(Direntry_t) && defined(HAS_READDIR)
3800     dSP;
3801     GV * const gv = (GV*)POPs;
3802     register IO * const io = GvIOn(gv);
3803
3804     if (!io || !IoDIRP(io))
3805         goto nope;
3806
3807 #ifdef VOID_CLOSEDIR
3808     PerlDir_close(IoDIRP(io));
3809 #else
3810     if (PerlDir_close(IoDIRP(io)) < 0) {
3811         IoDIRP(io) = 0; /* Don't try to close again--coredumps on SysV */
3812         goto nope;
3813     }
3814 #endif
3815     IoDIRP(io) = 0;
3816
3817     RETPUSHYES;
3818 nope:
3819     if (!errno)
3820         SETERRNO(EBADF,RMS_IFI);
3821     RETPUSHUNDEF;
3822 #else
3823     DIE(aTHX_ PL_no_dir_func, "closedir");
3824 #endif
3825 }
3826
3827 /* Process control. */
3828
3829 PP(pp_fork)
3830 {
3831 #ifdef HAS_FORK
3832     dSP; dTARGET;
3833     Pid_t childpid;
3834
3835     EXTEND(SP, 1);
3836     PERL_FLUSHALL_FOR_CHILD;
3837     childpid = PerlProc_fork();
3838     if (childpid < 0)
3839         RETSETUNDEF;
3840     if (!childpid) {
3841         GV * const tmpgv = gv_fetchpv("$", TRUE, SVt_PV);
3842         if (tmpgv) {
3843             SvREADONLY_off(GvSV(tmpgv));
3844             sv_setiv(GvSV(tmpgv), (IV)PerlProc_getpid());
3845             SvREADONLY_on(GvSV(tmpgv));
3846         }
3847 #ifdef THREADS_HAVE_PIDS
3848         PL_ppid = (IV)getppid();
3849 #endif
3850 #ifdef PERL_USES_PL_PIDSTATUS
3851         hv_clear(PL_pidstatus); /* no kids, so don't wait for 'em */
3852 #endif
3853     }
3854     PUSHi(childpid);
3855     RETURN;
3856 #else
3857 #  if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
3858     dSP; dTARGET;
3859     Pid_t childpid;
3860
3861     EXTEND(SP, 1);
3862     PERL_FLUSHALL_FOR_CHILD;
3863     childpid = PerlProc_fork();
3864     if (childpid == -1)
3865         RETSETUNDEF;
3866     PUSHi(childpid);
3867     RETURN;
3868 #  else
3869     DIE(aTHX_ PL_no_func, "fork");
3870 #  endif
3871 #endif
3872 }
3873
3874 PP(pp_wait)
3875 {
3876 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
3877     dSP; dTARGET;
3878     Pid_t childpid;
3879     int argflags;
3880
3881     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3882         childpid = wait4pid(-1, &argflags, 0);
3883     else {
3884         while ((childpid = wait4pid(-1, &argflags, 0)) == -1 &&
3885                errno == EINTR) {
3886           PERL_ASYNC_CHECK();
3887         }
3888     }
3889 #  if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
3890     /* 0 and -1 are both error returns (the former applies to WNOHANG case) */
3891     STATUS_NATIVE_CHILD_SET((childpid && childpid != -1) ? argflags : -1);
3892 #  else
3893     STATUS_NATIVE_CHILD_SET((childpid > 0) ? argflags : -1);
3894 #  endif
3895     XPUSHi(childpid);
3896     RETURN;
3897 #else
3898     DIE(aTHX_ PL_no_func, "wait");
3899 #endif
3900 }
3901
3902 PP(pp_waitpid)
3903 {
3904 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
3905     dSP; dTARGET;
3906     Pid_t pid;
3907     Pid_t result;
3908     int optype;
3909     int argflags;
3910
3911     optype = POPi;
3912     pid = TOPi;
3913     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3914         result = wait4pid(pid, &argflags, optype);
3915     else {
3916         while ((result = wait4pid(pid, &argflags, optype)) == -1 &&
3917                errno == EINTR) {
3918           PERL_ASYNC_CHECK();
3919         }
3920     }
3921 #  if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
3922     /* 0 and -1 are both error returns (the former applies to WNOHANG case) */
3923     STATUS_NATIVE_CHILD_SET((result && result != -1) ? argflags : -1);
3924 #  else
3925     STATUS_NATIVE_CHILD_SET((result > 0) ? argflags : -1);
3926 #  endif
3927     SETi(result);
3928     RETURN;
3929 #else
3930     DIE(aTHX_ PL_no_func, "waitpid");
3931 #endif
3932 }
3933
3934 PP(pp_system)
3935 {
3936     dSP; dMARK; dORIGMARK; dTARGET;
3937     I32 value;
3938     int result;
3939
3940     if (PL_tainting) {
3941         TAINT_ENV();
3942         while (++MARK <= SP) {
3943             (void)SvPV_nolen_const(*MARK);      /* stringify for taint check */
3944             if (PL_tainted)
3945                 break;
3946         }
3947         MARK = ORIGMARK;
3948         TAINT_PROPER("system");
3949     }
3950     PERL_FLUSHALL_FOR_CHILD;
3951 #if (defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(OS2) || defined(PERL_MICRO)
3952     {
3953         Pid_t childpid;
3954         int pp[2];
3955         I32 did_pipes = 0;
3956
3957         if (PerlProc_pipe(pp) >= 0)
3958             did_pipes = 1;
3959         while ((childpid = PerlProc_fork()) == -1) {
3960             if (errno != EAGAIN) {
3961                 value = -1;
3962                 SP = ORIGMARK;
3963                 XPUSHi(value);
3964                 if (did_pipes) {
3965                     PerlLIO_close(pp[0]);
3966                     PerlLIO_close(pp[1]);
3967                 }
3968                 RETURN;
3969             }
3970             sleep(5);
3971         }
3972         if (childpid > 0) {
3973             Sigsave_t ihand,qhand; /* place to save signals during system() */
3974             int status;
3975
3976             if (did_pipes)
3977                 PerlLIO_close(pp[1]);
3978 #ifndef PERL_MICRO
3979             rsignal_save(SIGINT,  (Sighandler_t) SIG_IGN, &ihand);
3980             rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qhand);
3981 #endif
3982             do {
3983                 result = wait4pid(childpid, &status, 0);
3984             } while (result == -1 && errno == EINTR);
3985 #ifndef PERL_MICRO
3986             (void)rsignal_restore(SIGINT, &ihand);
3987             (void)rsignal_restore(SIGQUIT, &qhand);
3988 #endif
3989             STATUS_NATIVE_CHILD_SET(result == -1 ? -1 : status);
3990             do_execfree();      /* free any memory child malloced on fork */
3991             SP = ORIGMARK;
3992             if (did_pipes) {
3993                 int errkid;
3994                 int n = 0, n1;
3995
3996                 while (n < sizeof(int)) {
3997                     n1 = PerlLIO_read(pp[0],
3998                                       (void*)(((char*)&errkid)+n),
3999                                       (sizeof(int)) - n);
4000                     if (n1 <= 0)
4001                         break;
4002                     n += n1;
4003                 }
4004                 PerlLIO_close(pp[0]);
4005                 if (n) {                        /* Error */
4006                     if (n != sizeof(int))
4007                         DIE(aTHX_ "panic: kid popen errno read");
4008                     errno = errkid;             /* Propagate errno from kid */
4009                     STATUS_NATIVE_CHILD_SET(-1);
4010                 }
4011             }
4012             XPUSHi(STATUS_CURRENT);
4013             RETURN;
4014         }
4015         if (did_pipes) {
4016             PerlLIO_close(pp[0]);
4017 #if defined(HAS_FCNTL) && defined(F_SETFD)
4018             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
4019 #endif
4020         }
4021         if (PL_op->op_flags & OPf_STACKED) {
4022             SV *really = *++MARK;
4023             value = (I32)do_aexec5(really, MARK, SP, pp[1], did_pipes);
4024         }
4025         else if (SP - MARK != 1)
4026             value = (I32)do_aexec5(Nullsv, MARK, SP, pp[1], did_pipes);
4027         else {
4028             value = (I32)do_exec3(SvPVx_nolen(sv_mortalcopy(*SP)), pp[1], did_pipes);
4029         }
4030         PerlProc__exit(-1);
4031     }
4032 #else /* ! FORK or VMS or OS/2 */
4033     PL_statusvalue = 0;
4034     result = 0;
4035     if (PL_op->op_flags & OPf_STACKED) {
4036         SV *really = *++MARK;
4037 #  if defined(WIN32) || defined(OS2) || defined(__SYMBIAN32__)
4038         value = (I32)do_aspawn(really, MARK, SP);
4039 #  else
4040         value = (I32)do_aspawn(really, (void **)MARK, (void **)SP);
4041 #  endif
4042     }
4043     else if (SP - MARK != 1) {
4044 #  if defined(WIN32) || defined(OS2) || defined(__SYMBIAN32__)
4045         value = (I32)do_aspawn(Nullsv, MARK, SP);
4046 #  else
4047         value = (I32)do_aspawn(Nullsv, (void **)MARK, (void **)SP);
4048 #  endif
4049     }
4050     else {
4051         value = (I32)do_spawn(SvPVx_nolen(sv_mortalcopy(*SP)));
4052     }
4053     if (PL_statusvalue == -1)   /* hint that value must be returned as is */
4054         result = 1;
4055     STATUS_NATIVE_CHILD_SET(value);
4056     do_execfree();
4057     SP = ORIGMARK;
4058     XPUSHi(result ? value : STATUS_CURRENT);
4059 #endif /* !FORK or VMS */
4060     RETURN;
4061 }
4062
4063 PP(pp_exec)
4064 {
4065     dSP; dMARK; dORIGMARK; dTARGET;
4066     I32 value;
4067
4068     if (PL_tainting) {
4069         TAINT_ENV();
4070         while (++MARK <= SP) {
4071             (void)SvPV_nolen_const(*MARK);      /* stringify for taint check */
4072             if (PL_tainted)
4073                 break;
4074         }
4075         MARK = ORIGMARK;
4076         TAINT_PROPER("exec");
4077     }
4078     PERL_FLUSHALL_FOR_CHILD;
4079     if (PL_op->op_flags & OPf_STACKED) {
4080         SV *really = *++MARK;
4081         value = (I32)do_aexec(really, MARK, SP);
4082     }
4083     else if (SP - MARK != 1)
4084 #ifdef VMS
4085         value = (I32)vms_do_aexec(Nullsv, MARK, SP);
4086 #else
4087 #  ifdef __OPEN_VM
4088         {
4089            (void ) do_aspawn(Nullsv, MARK, SP);
4090            value = 0;
4091         }
4092 #  else
4093         value = (I32)do_aexec(Nullsv, MARK, SP);
4094 #  endif
4095 #endif
4096     else {
4097 #ifdef VMS
4098         value = (I32)vms_do_exec(SvPVx_nolen(sv_mortalcopy(*SP)));
4099 #else
4100 #  ifdef __OPEN_VM
4101         (void) do_spawn(SvPVx_nolen(sv_mortalcopy(*SP)));
4102         value = 0;
4103 #  else
4104         value = (I32)do_exec(SvPVx_nolen(sv_mortalcopy(*SP)));
4105 #  endif
4106 #endif
4107     }
4108
4109     SP = ORIGMARK;
4110     XPUSHi(value);
4111     RETURN;
4112 }
4113
4114 PP(pp_getppid)
4115 {
4116 #ifdef HAS_GETPPID
4117     dSP; dTARGET;
4118 #   ifdef THREADS_HAVE_PIDS
4119     if (PL_ppid != 1 && getppid() == 1)
4120         /* maybe the parent process has died. Refresh ppid cache */
4121         PL_ppid = 1;
4122     XPUSHi( PL_ppid );
4123 #   else
4124     XPUSHi( getppid() );
4125 #   endif
4126     RETURN;
4127 #else
4128     DIE(aTHX_ PL_no_func, "getppid");
4129 #endif
4130 }
4131
4132 PP(pp_getpgrp)
4133 {
4134 #ifdef HAS_GETPGRP
4135     dSP; dTARGET;
4136     Pid_t pid;
4137     Pid_t pgrp;
4138
4139     if (MAXARG < 1)
4140         pid = 0;
4141     else
4142         pid = SvIVx(POPs);
4143 #ifdef BSD_GETPGRP
4144     pgrp = (I32)BSD_GETPGRP(pid);
4145 #else
4146     if (pid != 0 && pid != PerlProc_getpid())
4147         DIE(aTHX_ "POSIX getpgrp can't take an argument");
4148     pgrp = getpgrp();
4149 #endif
4150     XPUSHi(pgrp);
4151     RETURN;
4152 #else
4153     DIE(aTHX_ PL_no_func, "getpgrp()");
4154 #endif
4155 }
4156
4157 PP(pp_setpgrp)
4158 {
4159 #ifdef HAS_SETPGRP
4160     dSP; dTARGET;
4161     Pid_t pgrp;
4162     Pid_t pid;
4163     if (MAXARG < 2) {
4164         pgrp = 0;
4165         pid = 0;
4166     }
4167     else {
4168         pgrp = POPi;
4169         pid = TOPi;
4170     }
4171
4172     TAINT_PROPER("setpgrp");
4173 #ifdef BSD_SETPGRP
4174     SETi( BSD_SETPGRP(pid, pgrp) >= 0 );
4175 #else
4176     if ((pgrp != 0 && pgrp != PerlProc_getpid())
4177         || (pid != 0 && pid != PerlProc_getpid()))
4178     {
4179         DIE(aTHX_ "setpgrp can't take arguments");
4180     }
4181     SETi( setpgrp() >= 0 );
4182 #endif /* USE_BSDPGRP */
4183     RETURN;
4184 #else
4185     DIE(aTHX_ PL_no_func, "setpgrp()");
4186 #endif
4187 }
4188
4189 PP(pp_getpriority)
4190 {
4191 #ifdef HAS_GETPRIORITY
4192     dSP; dTARGET;
4193     int who = POPi;
4194     int which = TOPi;
4195     SETi( getpriority(which, who) );
4196     RETURN;
4197 #else
4198     DIE(aTHX_ PL_no_func, "getpriority()");
4199 #endif
4200 }
4201
4202 PP(pp_setpriority)
4203 {
4204 #ifdef HAS_SETPRIORITY
4205     dSP; dTARGET;
4206     int niceval = POPi;
4207     int who = POPi;
4208     int which = TOPi;
4209     TAINT_PROPER("setpriority");
4210     SETi( setpriority(which, who, niceval) >= 0 );
4211     RETURN;
4212 #else
4213     DIE(aTHX_ PL_no_func, "setpriority()");
4214 #endif
4215 }
4216
4217 /* Time calls. */
4218
4219 PP(pp_time)
4220 {
4221     dSP; dTARGET;
4222 #ifdef BIG_TIME
4223     XPUSHn( time(Null(Time_t*)) );
4224 #else
4225     XPUSHi( time(Null(Time_t*)) );
4226 #endif
4227     RETURN;
4228 }
4229
4230 PP(pp_tms)
4231 {
4232 #ifdef HAS_TIMES
4233     dSP;
4234     EXTEND(SP, 4);
4235 #ifndef VMS
4236     (void)PerlProc_times(&PL_timesbuf);
4237 #else
4238     (void)PerlProc_times((tbuffer_t *)&PL_timesbuf);  /* time.h uses different name for */
4239                                                    /* struct tms, though same data   */
4240                                                    /* is returned.                   */
4241 #endif
4242
4243     PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_utime)/(NV)PL_clocktick)));
4244     if (GIMME == G_ARRAY) {
4245         PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_stime)/(NV)PL_clocktick)));
4246         PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_cutime)/(NV)PL_clocktick)));
4247         PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_cstime)/(NV)PL_clocktick)));
4248     }
4249     RETURN;
4250 #else
4251 #   ifdef PERL_MICRO
4252     dSP;
4253     PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4254     EXTEND(SP, 4);
4255     if (GIMME == G_ARRAY) {
4256          PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4257          PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4258          PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4259     }
4260     RETURN;
4261 #   else
4262     DIE(aTHX_ "times not implemented");
4263 #   endif
4264 #endif /* HAS_TIMES */
4265 }
4266
4267 #ifdef LOCALTIME_EDGECASE_BROKEN
4268 static struct tm *S_my_localtime (pTHX_ Time_t *tp)
4269 {
4270     auto time_t     T;
4271     auto struct tm *P;
4272
4273     /* No workarounds in the valid range */
4274     if (!tp || *tp < 0x7fff573f || *tp >= 0x80000000)
4275         return (localtime (tp));
4276
4277     /* This edge case is to workaround the undefined behaviour, where the
4278      * TIMEZONE makes the time go beyond the defined range.
4279      * gmtime (0x7fffffff) => 2038-01-19 03:14:07
4280      * If there is a negative offset in TZ, like MET-1METDST, some broken
4281      * implementations of localtime () (like AIX 5.2) barf with bogus
4282      * return values:
4283      * 0x7fffffff gmtime               2038-01-19 03:14:07
4284      * 0x7fffffff localtime            1901-12-13 21:45:51
4285      * 0x7fffffff mylocaltime          2038-01-19 04:14:07
4286      * 0x3c19137f gmtime               2001-12-13 20:45:51
4287      * 0x3c19137f localtime            2001-12-13 21:45:51
4288      * 0x3c19137f mylocaltime          2001-12-13 21:45:51
4289      * Given that legal timezones are typically between GMT-12 and GMT+12
4290      * we turn back the clock 23 hours before calling the localtime
4291      * function, and add those to the return value. This will never cause
4292      * day wrapping problems, since the edge case is Tue Jan *19*
4293      */
4294     T = *tp - 82800; /* 23 hour. allows up to GMT-23 */
4295     P = localtime (&T);
4296     P->tm_hour += 23;
4297     if (P->tm_hour >= 24) {
4298         P->tm_hour -= 24;
4299         P->tm_mday++;   /* 18  -> 19  */
4300         P->tm_wday++;   /* Mon -> Tue */
4301         P->tm_yday++;   /* 18  -> 19  */
4302     }
4303     return (P);
4304 } /* S_my_localtime */
4305 #endif
4306
4307 PP(pp_gmtime)
4308 {
4309     dSP;
4310     Time_t when;
4311     const struct tm *tmbuf;
4312     static const char * const dayname[] =
4313         {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
4314     static const char * const monname[] =
4315         {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4316          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
4317
4318     if (MAXARG < 1)
4319         (void)time(&when);
4320     else
4321 #ifdef BIG_TIME
4322         when = (Time_t)SvNVx(POPs);
4323 #else
4324         when = (Time_t)SvIVx(POPs);
4325 #endif
4326
4327     if (PL_op->op_type == OP_LOCALTIME)
4328 #ifdef LOCALTIME_EDGECASE_BROKEN
4329         tmbuf = S_my_localtime(aTHX_ &when);
4330 #else
4331         tmbuf = localtime(&when);
4332 #endif
4333     else
4334         tmbuf = gmtime(&when);
4335
4336     if (GIMME != G_ARRAY) {
4337         SV *tsv;
4338         EXTEND(SP, 1);
4339         EXTEND_MORTAL(1);
4340         if (!tmbuf)
4341             RETPUSHUNDEF;
4342         tsv = Perl_newSVpvf(aTHX_ "%s %s %2d %02d:%02d:%02d %d",
4343                             dayname[tmbuf->tm_wday],
4344                             monname[tmbuf->tm_mon],
4345                             tmbuf->tm_mday,
4346                             tmbuf->tm_hour,
4347                             tmbuf->tm_min,
4348                             tmbuf->tm_sec,
4349                             tmbuf->tm_year + 1900);
4350         PUSHs(sv_2mortal(tsv));
4351     }
4352     else if (tmbuf) {
4353         EXTEND(SP, 9);
4354         EXTEND_MORTAL(9);
4355         PUSHs(sv_2mortal(newSViv(tmbuf->tm_sec)));
4356         PUSHs(sv_2mortal(newSViv(tmbuf->tm_min)));
4357         PUSHs(sv_2mortal(newSViv(tmbuf->tm_hour)));
4358         PUSHs(sv_2mortal(newSViv(tmbuf->tm_mday)));
4359         PUSHs(sv_2mortal(newSViv(tmbuf->tm_mon)));
4360         PUSHs(sv_2mortal(newSViv(tmbuf->tm_year)));
4361         PUSHs(sv_2mortal(newSViv(tmbuf->tm_wday)));
4362         PUSHs(sv_2mortal(newSViv(tmbuf->tm_yday)));
4363         PUSHs(sv_2mortal(newSViv(tmbuf->tm_isdst)));
4364     }
4365     RETURN;
4366 }
4367
4368 PP(pp_alarm)
4369 {
4370 #ifdef HAS_ALARM
4371     dSP; dTARGET;
4372     int anum;
4373     anum = POPi;
4374     anum = alarm((unsigned int)anum);
4375     EXTEND(SP, 1);
4376     if (anum < 0)
4377         RETPUSHUNDEF;
4378     PUSHi(anum);
4379     RETURN;
4380 #else
4381     DIE(aTHX_ PL_no_func, "alarm");
4382 #endif
4383 }
4384
4385 PP(pp_sleep)
4386 {
4387     dSP; dTARGET;
4388     I32 duration;
4389     Time_t lasttime;
4390     Time_t when;
4391
4392     (void)time(&lasttime);
4393     if (MAXARG < 1)
4394         PerlProc_pause();
4395     else {
4396         duration = POPi;
4397         PerlProc_sleep((unsigned int)duration);
4398     }
4399     (void)time(&when);
4400     XPUSHi(when - lasttime);
4401     RETURN;
4402 }
4403
4404 /* Shared memory. */
4405 /* Merged with some message passing. */
4406
4407 PP(pp_shmwrite)
4408 {
4409 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4410     dSP; dMARK; dTARGET;
4411     const int op_type = PL_op->op_type;
4412     I32 value;
4413
4414     switch (op_type) {
4415     case OP_MSGSND:
4416         value = (I32)(do_msgsnd(MARK, SP) >= 0);
4417         break;
4418     case OP_MSGRCV:
4419         value = (I32)(do_msgrcv(MARK, SP) >= 0);
4420         break;
4421     case OP_SEMOP:
4422         value = (I32)(do_semop(MARK, SP) >= 0);
4423         break;
4424     default:
4425         value = (I32)(do_shmio(op_type, MARK, SP) >= 0);
4426         break;
4427     }
4428
4429     SP = MARK;
4430     PUSHi(value);
4431     RETURN;
4432 #else
4433     return pp_semget();
4434 #endif
4435 }
4436
4437 /* Semaphores. */
4438
4439 PP(pp_semget)
4440 {
4441 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4442     dSP; dMARK; dTARGET;
4443     int anum = do_ipcget(PL_op->op_type, MARK, SP);
4444     SP = MARK;
4445     if (anum == -1)
4446         RETPUSHUNDEF;
4447     PUSHi(anum);
4448     RETURN;
4449 #else
4450     DIE(aTHX_ "System V IPC is not implemented on this machine");
4451 #endif
4452 }
4453
4454 PP(pp_semctl)
4455 {
4456 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4457     dSP; dMARK; dTARGET;
4458     int anum = do_ipcctl(PL_op->op_type, MARK, SP);
4459     SP = MARK;
4460     if (anum == -1)
4461         RETSETUNDEF;
4462     if (anum != 0) {
4463         PUSHi(anum);
4464     }
4465     else {
4466         PUSHp(zero_but_true, ZBTLEN);
4467     }
4468     RETURN;
4469 #else
4470     return pp_semget();
4471 #endif
4472 }
4473
4474 /* Get system info. */
4475
4476 PP(pp_ghostent)
4477 {
4478 #if defined(HAS_GETHOSTBYNAME) || defined(HAS_GETHOSTBYADDR) || defined(HAS_GETHOSTENT)
4479     dSP;
4480     I32 which = PL_op->op_type;
4481     register char **elem;
4482     register SV *sv;
4483 #ifndef HAS_GETHOST_PROTOS /* XXX Do we need individual probes? */
4484     struct hostent *gethostbyaddr(Netdb_host_t, Netdb_hlen_t, int);
4485     struct hostent *gethostbyname(Netdb_name_t);
4486     struct hostent *gethostent(void);
4487 #endif
4488     struct hostent *hent;
4489     unsigned long len;
4490
4491     EXTEND(SP, 10);
4492     if (which == OP_GHBYNAME) {
4493 #ifdef HAS_GETHOSTBYNAME
4494         char* name = POPpbytex;
4495         hent = PerlSock_gethostbyname(name);
4496 #else
4497         DIE(aTHX_ PL_no_sock_func, "gethostbyname");
4498 #endif
4499     }
4500     else if (which == OP_GHBYADDR) {
4501 #ifdef HAS_GETHOSTBYADDR
4502         int addrtype = POPi;
4503         SV *addrsv = POPs;
4504         STRLEN addrlen;
4505         Netdb_host_t addr = (Netdb_host_t) SvPVbyte(addrsv, addrlen);
4506
4507         hent = PerlSock_gethostbyaddr(addr, (Netdb_hlen_t) addrlen, addrtype);
4508 #else
4509         DIE(aTHX_ PL_no_sock_func, "gethostbyaddr");
4510 #endif
4511     }
4512     else
4513 #ifdef HAS_GETHOSTENT
4514         hent = PerlSock_gethostent();
4515 #else
4516         DIE(aTHX_ PL_no_sock_func, "gethostent");
4517 #endif
4518
4519 #ifdef HOST_NOT_FOUND
4520         if (!hent) {
4521 #ifdef USE_REENTRANT_API
4522 #   ifdef USE_GETHOSTENT_ERRNO
4523             h_errno = PL_reentrant_buffer->_gethostent_errno;
4524 #   endif
4525 #endif
4526             STATUS_UNIX_SET(h_errno);
4527         }
4528 #endif
4529
4530     if (GIMME != G_ARRAY) {
4531         PUSHs(sv = sv_newmortal());
4532         if (hent) {
4533             if (which == OP_GHBYNAME) {
4534                 if (hent->h_addr)
4535                     sv_setpvn(sv, hent->h_addr, hent->h_length);
4536             }
4537             else
4538                 sv_setpv(sv, (char*)hent->h_name);
4539         }
4540         RETURN;
4541     }
4542
4543     if (hent) {
4544         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4545         sv_setpv(sv, (char*)hent->h_name);
4546         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4547         for (elem = hent->h_aliases; elem && *elem; elem++) {
4548             sv_catpv(sv, *elem);
4549             if (elem[1])
4550                 sv_catpvn(sv, " ", 1);
4551         }
4552         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4553         sv_setiv(sv, (IV)hent->h_addrtype);
4554         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4555         len = hent->h_length;
4556         sv_setiv(sv, (IV)len);
4557 #ifdef h_addr
4558         for (elem = hent->h_addr_list; elem && *elem; elem++) {
4559             XPUSHs(sv = sv_mortalcopy(&PL_sv_no));
4560             sv_setpvn(sv, *elem, len);
4561         }
4562 #else
4563         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4564         if (hent->h_addr)
4565             sv_setpvn(sv, hent->h_addr, len);
4566 #endif /* h_addr */
4567     }
4568     RETURN;
4569 #else
4570     DIE(aTHX_ PL_no_sock_func, "gethostent");
4571 #endif
4572 }
4573
4574 PP(pp_gnetent)
4575 {
4576 #if defined(HAS_GETNETBYNAME) || defined(HAS_GETNETBYADDR) || defined(HAS_GETNETENT)
4577     dSP;
4578     I32 which = PL_op->op_type;
4579     register char **elem;
4580     register SV *sv;
4581 #ifndef HAS_GETNET_PROTOS /* XXX Do we need individual probes? */
4582     struct netent *getnetbyaddr(Netdb_net_t, int);
4583     struct netent *getnetbyname(Netdb_name_t);
4584     struct netent *getnetent(void);
4585 #endif
4586     struct netent *nent;
4587
4588     if (which == OP_GNBYNAME){
4589 #ifdef HAS_GETNETBYNAME
4590         char *name = POPpbytex;
4591         nent = PerlSock_getnetbyname(name);
4592 #else
4593         DIE(aTHX_ PL_no_sock_func, "getnetbyname");
4594 #endif
4595     }
4596     else if (which == OP_GNBYADDR) {
4597 #ifdef HAS_GETNETBYADDR
4598         int addrtype = POPi;
4599         Netdb_net_t addr = (Netdb_net_t) (U32)POPu;
4600         nent = PerlSock_getnetbyaddr(addr, addrtype);
4601 #else
4602         DIE(aTHX_ PL_no_sock_func, "getnetbyaddr");
4603 #endif
4604     }
4605     else
4606 #ifdef HAS_GETNETENT
4607         nent = PerlSock_getnetent();
4608 #else
4609         DIE(aTHX_ PL_no_sock_func, "getnetent");
4610 #endif
4611
4612 #ifdef HOST_NOT_FOUND
4613         if (!nent) {
4614 #ifdef USE_REENTRANT_API
4615 #   ifdef USE_GETNETENT_ERRNO
4616              h_errno = PL_reentrant_buffer->_getnetent_errno;
4617 #   endif
4618 #endif
4619             STATUS_UNIX_SET(h_errno);
4620         }
4621 #endif
4622
4623     EXTEND(SP, 4);
4624     if (GIMME != G_ARRAY) {
4625         PUSHs(sv = sv_newmortal());
4626         if (nent) {
4627             if (which == OP_GNBYNAME)
4628                 sv_setiv(sv, (IV)nent->n_net);
4629             else
4630                 sv_setpv(sv, nent->n_name);
4631         }
4632         RETURN;
4633     }
4634
4635     if (nent) {
4636         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4637         sv_setpv(sv, nent->n_name);
4638         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4639         for (elem = nent->n_aliases; elem && *elem; elem++) {
4640             sv_catpv(sv, *elem);
4641             if (elem[1])
4642                 sv_catpvn(sv, " ", 1);
4643         }
4644         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4645         sv_setiv(sv, (IV)nent->n_addrtype);
4646         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4647         sv_setiv(sv, (IV)nent->n_net);
4648     }
4649
4650     RETURN;
4651 #else
4652     DIE(aTHX_ PL_no_sock_func, "getnetent");
4653 #endif
4654 }
4655
4656 PP(pp_gprotoent)
4657 {
4658 #if defined(HAS_GETPROTOBYNAME) || defined(HAS_GETPROTOBYNUMBER) || defined(HAS_GETPROTOENT)
4659     dSP;
4660     I32 which = PL_op->op_type;
4661     register char **elem;
4662     register SV *sv;
4663 #ifndef HAS_GETPROTO_PROTOS /* XXX Do we need individual probes? */
4664     struct protoent *getprotobyname(Netdb_name_t);
4665     struct protoent *getprotobynumber(int);
4666     struct protoent *getprotoent(void);
4667 #endif
4668     struct protoent *pent;
4669
4670     if (which == OP_GPBYNAME) {
4671 #ifdef HAS_GETPROTOBYNAME
4672         char* name = POPpbytex;
4673         pent = PerlSock_getprotobyname(name);
4674 #else
4675         DIE(aTHX_ PL_no_sock_func, "getprotobyname");
4676 #endif
4677     }
4678     else if (which == OP_GPBYNUMBER) {
4679 #ifdef HAS_GETPROTOBYNUMBER
4680         int number = POPi;
4681         pent = PerlSock_getprotobynumber(number);
4682 #else
4683         DIE(aTHX_ PL_no_sock_func, "getprotobynumber");
4684 #endif
4685     }
4686     else
4687 #ifdef HAS_GETPROTOENT
4688         pent = PerlSock_getprotoent();
4689 #else
4690         DIE(aTHX_ PL_no_sock_func, "getprotoent");
4691 #endif
4692
4693     EXTEND(SP, 3);
4694     if (GIMME != G_ARRAY) {
4695         PUSHs(sv = sv_newmortal());
4696         if (pent) {
4697             if (which == OP_GPBYNAME)
4698                 sv_setiv(sv, (IV)pent->p_proto);
4699             else
4700                 sv_setpv(sv, pent->p_name);
4701         }
4702         RETURN;
4703     }
4704
4705     if (pent) {
4706         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4707         sv_setpv(sv, pent->p_name);
4708         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4709         for (elem = pent->p_aliases; elem && *elem; elem++) {
4710             sv_catpv(sv, *elem);
4711             if (elem[1])
4712                 sv_catpvn(sv, " ", 1);
4713         }
4714         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4715         sv_setiv(sv, (IV)pent->p_proto);
4716     }
4717
4718     RETURN;
4719 #else
4720     DIE(aTHX_ PL_no_sock_func, "getprotoent");
4721 #endif
4722 }
4723
4724 PP(pp_gservent)
4725 {
4726 #if defined(HAS_GETSERVBYNAME) || defined(HAS_GETSERVBYPORT) || defined(HAS_GETSERVENT)
4727     dSP;
4728     I32 which = PL_op->op_type;
4729     register char **elem;
4730     register SV *sv;
4731 #ifndef HAS_GETSERV_PROTOS /* XXX Do we need individual probes? */
4732     struct servent *getservbyname(Netdb_name_t, Netdb_name_t);
4733     struct servent *getservbyport(int, Netdb_name_t);
4734     struct servent *getservent(void);
4735 #endif
4736     struct servent *sent;
4737
4738     if (which == OP_GSBYNAME) {
4739 #ifdef HAS_GETSERVBYNAME
4740         char *proto = POPpbytex;
4741         char *name = POPpbytex;
4742
4743         if (proto && !*proto)
4744             proto = Nullch;
4745
4746         sent = PerlSock_getservbyname(name, proto);
4747 #else
4748         DIE(aTHX_ PL_no_sock_func, "getservbyname");
4749 #endif
4750     }
4751     else if (which == OP_GSBYPORT) {
4752 #ifdef HAS_GETSERVBYPORT
4753         char *proto = POPpbytex;
4754         unsigned short port = (unsigned short)POPu;
4755
4756         if (proto && !*proto)
4757             proto = Nullch;
4758
4759 #ifdef HAS_HTONS
4760         port = PerlSock_htons(port);
4761 #endif
4762         sent = PerlSock_getservbyport(port, proto);
4763 #else
4764         DIE(aTHX_ PL_no_sock_func, "getservbyport");
4765 #endif
4766     }
4767     else
4768 #ifdef HAS_GETSERVENT
4769         sent = PerlSock_getservent();
4770 #else
4771         DIE(aTHX_ PL_no_sock_func, "getservent");
4772 #endif
4773
4774     EXTEND(SP, 4);
4775     if (GIMME != G_ARRAY) {
4776         PUSHs(sv = sv_newmortal());
4777         if (sent) {
4778             if (which == OP_GSBYNAME) {
4779 #ifdef HAS_NTOHS
4780                 sv_setiv(sv, (IV)PerlSock_ntohs(sent->s_port));
4781 #else
4782                 sv_setiv(sv, (IV)(sent->s_port));
4783 #endif
4784             }
4785             else
4786                 sv_setpv(sv, sent->s_name);
4787         }
4788         RETURN;
4789     }
4790
4791     if (sent) {
4792         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4793         sv_setpv(sv, sent->s_name);
4794         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4795         for (elem = sent->s_aliases; elem && *elem; elem++) {
4796             sv_catpv(sv, *elem);
4797             if (elem[1])
4798                 sv_catpvn(sv, " ", 1);
4799         }
4800         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4801 #ifdef HAS_NTOHS
4802         sv_setiv(sv, (IV)PerlSock_ntohs(sent->s_port));
4803 #else
4804         sv_setiv(sv, (IV)(sent->s_port));
4805 #endif
4806         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4807         sv_setpv(sv, sent->s_proto);
4808     }
4809
4810     RETURN;
4811 #else
4812     DIE(aTHX_ PL_no_sock_func, "getservent");
4813 #endif
4814 }
4815
4816 PP(pp_shostent)
4817 {
4818 #ifdef HAS_SETHOSTENT
4819     dSP;
4820     PerlSock_sethostent(TOPi);
4821     RETSETYES;
4822 #else
4823     DIE(aTHX_ PL_no_sock_func, "sethostent");
4824 #endif
4825 }
4826
4827 PP(pp_snetent)
4828 {
4829 #ifdef HAS_SETNETENT
4830     dSP;
4831     PerlSock_setnetent(TOPi);
4832     RETSETYES;
4833 #else
4834     DIE(aTHX_ PL_no_sock_func, "setnetent");
4835 #endif
4836 }
4837
4838 PP(pp_sprotoent)
4839 {
4840 #ifdef HAS_SETPROTOENT
4841     dSP;
4842     PerlSock_setprotoent(TOPi);
4843     RETSETYES;
4844 #else
4845     DIE(aTHX_ PL_no_sock_func, "setprotoent");
4846 #endif
4847 }
4848
4849 PP(pp_sservent)
4850 {
4851 #ifdef HAS_SETSERVENT
4852     dSP;
4853     PerlSock_setservent(TOPi);
4854     RETSETYES;
4855 #else
4856     DIE(aTHX_ PL_no_sock_func, "setservent");
4857 #endif
4858 }
4859
4860 PP(pp_ehostent)
4861 {
4862 #ifdef HAS_ENDHOSTENT
4863     dSP;
4864     PerlSock_endhostent();
4865     EXTEND(SP,1);
4866     RETPUSHYES;
4867 #else
4868     DIE(aTHX_ PL_no_sock_func, "endhostent");
4869 #endif
4870 }
4871
4872 PP(pp_enetent)
4873 {
4874 #ifdef HAS_ENDNETENT
4875     dSP;
4876     PerlSock_endnetent();
4877     EXTEND(SP,1);
4878     RETPUSHYES;
4879 #else
4880     DIE(aTHX_ PL_no_sock_func, "endnetent");
4881 #endif
4882 }
4883
4884 PP(pp_eprotoent)
4885 {
4886 #ifdef HAS_ENDPROTOENT
4887     dSP;
4888     PerlSock_endprotoent();
4889     EXTEND(SP,1);
4890     RETPUSHYES;
4891 #else
4892     DIE(aTHX_ PL_no_sock_func, "endprotoent");
4893 #endif
4894 }
4895
4896 PP(pp_eservent)
4897 {
4898 #ifdef HAS_ENDSERVENT
4899     dSP;
4900     PerlSock_endservent();
4901     EXTEND(SP,1);
4902     RETPUSHYES;
4903 #else
4904     DIE(aTHX_ PL_no_sock_func, "endservent");
4905 #endif
4906 }
4907
4908 PP(pp_gpwent)
4909 {
4910 #ifdef HAS_PASSWD
4911     dSP;
4912     I32 which = PL_op->op_type;
4913     register SV *sv;
4914     struct passwd *pwent  = NULL;
4915     /*
4916      * We currently support only the SysV getsp* shadow password interface.
4917      * The interface is declared in <shadow.h> and often one needs to link
4918      * with -lsecurity or some such.
4919      * This interface is used at least by Solaris, HP-UX, IRIX, and Linux.
4920      * (and SCO?)
4921      *
4922      * AIX getpwnam() is clever enough to return the encrypted password
4923      * only if the caller (euid?) is root.
4924      *
4925      * There are at least three other shadow password APIs.  Many platforms
4926      * seem to contain more than one interface for accessing the shadow
4927      * password databases, possibly for compatibility reasons.
4928      * The getsp*() is by far he simplest one, the other two interfaces
4929      * are much more complicated, but also very similar to each other.
4930      *
4931      * <sys/types.h>
4932      * <sys/security.h>
4933      * <prot.h>
4934      * struct pr_passwd *getprpw*();
4935      * The password is in
4936      * char getprpw*(...).ufld.fd_encrypt[]
4937      * Mention HAS_GETPRPWNAM here so that Configure probes for it.
4938      *
4939      * <sys/types.h>
4940      * <sys/security.h>
4941      * <prot.h>
4942      * struct es_passwd *getespw*();
4943      * The password is in
4944      * char *(getespw*(...).ufld.fd_encrypt)
4945      * Mention HAS_GETESPWNAM here so that Configure probes for it.
4946      *
4947      * <userpw.h> (AIX)
4948      * struct userpw *getuserpw();
4949      * The password is in
4950      * char *(getuserpw(...)).spw_upw_passwd
4951      * (but the de facto standard getpwnam() should work okay)
4952      *
4953      * Mention I_PROT here so that Configure probes for it.
4954      *
4955      * In HP-UX for getprpw*() the manual page claims that one should include
4956      * <hpsecurity.h> instead of <sys/security.h>, but that is not needed
4957      * if one includes <shadow.h> as that includes <hpsecurity.h>,
4958      * and pp_sys.c already includes <shadow.h> if there is such.
4959      *
4960      * Note that <sys/security.h> is already probed for, but currently
4961      * it is only included in special cases.
4962      *
4963      * In Digital UNIX/Tru64 if using the getespw*() (which seems to be
4964      * be preferred interface, even though also the getprpw*() interface
4965      * is available) one needs to link with -lsecurity -ldb -laud -lm.
4966      * One also needs to call set_auth_parameters() in main() before
4967      * doing anything else, whether one is using getespw*() or getprpw*().
4968      *
4969      * Note that accessing the shadow databases can be magnitudes
4970      * slower than accessing the standard databases.
4971      *
4972      * --jhi
4973      */
4974
4975 #   if defined(__CYGWIN__) && defined(USE_REENTRANT_API)
4976     /* Cygwin 1.5.3-1 has buggy getpwnam_r() and getpwuid_r():
4977      * the pw_comment is left uninitialized. */
4978     PL_reentrant_buffer->_pwent_struct.pw_comment = NULL;
4979 #   endif
4980
4981     switch (which) {
4982     case OP_GPWNAM:
4983       {
4984         char* name = POPpbytex;
4985         pwent  = getpwnam(name);
4986       }
4987       break;
4988     case OP_GPWUID:
4989       {
4990         Uid_t uid = POPi;
4991         pwent = getpwuid(uid);
4992       }
4993         break;
4994     case OP_GPWENT:
4995 #   ifdef HAS_GETPWENT
4996         pwent  = getpwent();
4997 #ifdef POSIX_BC   /* In some cases pw_passwd has invalid addresses */
4998         if (pwent) pwent = getpwnam(pwent->pw_name);
4999 #endif
5000 #   else
5001         DIE(aTHX_ PL_no_func, "getpwent");
5002 #   endif
5003         break;
5004     }
5005
5006     EXTEND(SP, 10);
5007     if (GIMME != G_ARRAY) {
5008         PUSHs(sv = sv_newmortal());
5009         if (pwent) {
5010             if (which == OP_GPWNAM)
5011 #   if Uid_t_sign <= 0
5012                 sv_setiv(sv, (IV)pwent->pw_uid);
5013 #   else
5014                 sv_setuv(sv, (UV)pwent->pw_uid);
5015 #   endif
5016             else
5017                 sv_setpv(sv, pwent->pw_name);
5018         }
5019         RETURN;
5020     }
5021
5022     if (pwent) {
5023         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5024         sv_setpv(sv, pwent->pw_name);
5025
5026         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5027         SvPOK_off(sv);
5028         /* If we have getspnam(), we try to dig up the shadow
5029          * password.  If we are underprivileged, the shadow
5030          * interface will set the errno to EACCES or similar,
5031          * and return a null pointer.  If this happens, we will
5032          * use the dummy password (usually "*" or "x") from the
5033          * standard password database.
5034          *
5035          * In theory we could skip the shadow call completely
5036          * if euid != 0 but in practice we cannot know which
5037          * security measures are guarding the shadow databases
5038          * on a random platform.
5039          *
5040          * Resist the urge to use additional shadow interfaces.
5041          * Divert the urge to writing an extension instead.
5042          *
5043          * --jhi */
5044         /* Some AIX setups falsely(?) detect some getspnam(), which
5045          * has a different API than the Solaris/IRIX one. */
5046 #   if defined(HAS_GETSPNAM) && !defined(_AIX)
5047         {
5048             struct spwd *spwent;
5049             int saverrno; /* Save and restore errno so that
5050                            * underprivileged attempts seem
5051                            * to have never made the unsccessful
5052                            * attempt to retrieve the shadow password. */
5053
5054             saverrno = errno;
5055             spwent = getspnam(pwent->pw_name);
5056             errno = saverrno;
5057             if (spwent && spwent->sp_pwdp)
5058                 sv_setpv(sv, spwent->sp_pwdp);
5059         }
5060 #   endif
5061 #   ifdef PWPASSWD
5062         if (!SvPOK(sv)) /* Use the standard password, then. */
5063             sv_setpv(sv, pwent->pw_passwd);
5064 #   endif
5065
5066 #   ifndef INCOMPLETE_TAINTS
5067         /* passwd is tainted because user himself can diddle with it.
5068          * admittedly not much and in a very limited way, but nevertheless. */
5069         SvTAINTED_on(sv);
5070 #   endif
5071
5072         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5073 #   if Uid_t_sign <= 0
5074         sv_setiv(sv, (IV)pwent->pw_uid);
5075 #   else
5076         sv_setuv(sv, (UV)pwent->pw_uid);
5077 #   endif
5078
5079         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5080 #   if Uid_t_sign <= 0
5081         sv_setiv(sv, (IV)pwent->pw_gid);
5082 #   else
5083         sv_setuv(sv, (UV)pwent->pw_gid);
5084 #   endif
5085         /* pw_change, pw_quota, and pw_age are mutually exclusive--
5086          * because of the poor interface of the Perl getpw*(),
5087          * not because there's some standard/convention saying so.
5088          * A better interface would have been to return a hash,
5089          * but we are accursed by our history, alas. --jhi.  */
5090         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5091 #   ifdef PWCHANGE
5092         sv_setiv(sv, (IV)pwent->pw_change);
5093 #   else
5094 #       ifdef PWQUOTA
5095         sv_setiv(sv, (IV)pwent->pw_quota);
5096 #       else
5097 #           ifdef PWAGE
5098         sv_setpv(sv, pwent->pw_age);
5099 #           endif
5100 #       endif
5101 #   endif
5102
5103         /* pw_class and pw_comment are mutually exclusive--.
5104          * see the above note for pw_change, pw_quota, and pw_age. */
5105         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5106 #   ifdef PWCLASS
5107         sv_setpv(sv, pwent->pw_class);
5108 #   else
5109 #       ifdef PWCOMMENT
5110         sv_setpv(sv, pwent->pw_comment);
5111 #       endif
5112 #   endif
5113
5114         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5115 #   ifdef PWGECOS
5116         sv_setpv(sv, pwent->pw_gecos);
5117 #   endif
5118 #   ifndef INCOMPLETE_TAINTS
5119         /* pw_gecos is tainted because user himself can diddle with it. */
5120         SvTAINTED_on(sv);
5121 #   endif
5122
5123         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5124         sv_setpv(sv, pwent->pw_dir);
5125
5126         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5127         sv_setpv(sv, pwent->pw_shell);
5128 #   ifndef INCOMPLETE_TAINTS
5129         /* pw_shell is tainted because user himself can diddle with it. */
5130         SvTAINTED_on(sv);
5131 #   endif
5132
5133 #   ifdef PWEXPIRE
5134         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5135         sv_setiv(sv, (IV)pwent->pw_expire);
5136 #   endif
5137     }
5138     RETURN;
5139 #else
5140     DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5141 #endif
5142 }
5143
5144 PP(pp_spwent)
5145 {
5146 #if defined(HAS_PASSWD) && defined(HAS_SETPWENT)
5147     dSP;
5148     setpwent();
5149     RETPUSHYES;
5150 #else
5151     DIE(aTHX_ PL_no_func, "setpwent");
5152 #endif
5153 }
5154
5155 PP(pp_epwent)
5156 {
5157 #if defined(HAS_PASSWD) && defined(HAS_ENDPWENT)
5158     dSP;
5159     endpwent();
5160     RETPUSHYES;
5161 #else
5162     DIE(aTHX_ PL_no_func, "endpwent");
5163 #endif
5164 }
5165
5166 PP(pp_ggrent)
5167 {
5168 #ifdef HAS_GROUP
5169     dSP;
5170     I32 which = PL_op->op_type;
5171     register char **elem;
5172     register SV *sv;
5173     struct group *grent;
5174
5175     if (which == OP_GGRNAM) {
5176         char* name = POPpbytex;
5177         grent = (struct group *)getgrnam(name);
5178     }
5179     else if (which == OP_GGRGID) {
5180         Gid_t gid = POPi;
5181         grent = (struct group *)getgrgid(gid);
5182     }
5183     else
5184 #ifdef HAS_GETGRENT
5185         grent = (struct group *)getgrent();
5186 #else
5187         DIE(aTHX_ PL_no_func, "getgrent");
5188 #endif
5189
5190     EXTEND(SP, 4);
5191     if (GIMME != G_ARRAY) {
5192         PUSHs(sv = sv_newmortal());
5193         if (grent) {
5194             if (which == OP_GGRNAM)
5195                 sv_setiv(sv, (IV)grent->gr_gid);
5196             else
5197                 sv_setpv(sv, grent->gr_name);
5198         }
5199         RETURN;
5200     }
5201
5202     if (grent) {
5203         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5204         sv_setpv(sv, grent->gr_name);
5205
5206         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5207 #ifdef GRPASSWD
5208         sv_setpv(sv, grent->gr_passwd);
5209 #endif
5210
5211         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5212         sv_setiv(sv, (IV)grent->gr_gid);
5213
5214 #if !(defined(_CRAYMPP) && defined(USE_REENTRANT_API))
5215         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5216         /* In UNICOS/mk (_CRAYMPP) the multithreading
5217          * versions (getgrnam_r, getgrgid_r)
5218          * seem to return an illegal pointer
5219          * as the group members list, gr_mem.
5220          * getgrent() doesn't even have a _r version
5221          * but the gr_mem is poisonous anyway.
5222          * So yes, you cannot get the list of group
5223          * members if building multithreaded in UNICOS/mk. */
5224         for (elem = grent->gr_mem; elem && *elem; elem++) {
5225             sv_catpv(sv, *elem);
5226             if (elem[1])
5227                 sv_catpvn(sv, " ", 1);
5228         }
5229 #endif
5230     }
5231
5232     RETURN;
5233 #else
5234     DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5235 #endif
5236 }
5237
5238 PP(pp_sgrent)
5239 {
5240 #if defined(HAS_GROUP) && defined(HAS_SETGRENT)
5241     dSP;
5242     setgrent();
5243     RETPUSHYES;
5244 #else
5245     DIE(aTHX_ PL_no_func, "setgrent");
5246 #endif
5247 }
5248
5249 PP(pp_egrent)
5250 {
5251 #if defined(HAS_GROUP) && defined(HAS_ENDGRENT)
5252     dSP;
5253     endgrent();
5254     RETPUSHYES;
5255 #else
5256     DIE(aTHX_ PL_no_func, "endgrent");
5257 #endif
5258 }
5259
5260 PP(pp_getlogin)
5261 {
5262 #ifdef HAS_GETLOGIN
5263     dSP; dTARGET;
5264     char *tmps;
5265     EXTEND(SP, 1);
5266     if (!(tmps = PerlProc_getlogin()))
5267         RETPUSHUNDEF;
5268     PUSHp(tmps, strlen(tmps));
5269     RETURN;
5270 #else
5271     DIE(aTHX_ PL_no_func, "getlogin");
5272 #endif
5273 }
5274
5275 /* Miscellaneous. */
5276
5277 PP(pp_syscall)
5278 {
5279 #ifdef HAS_SYSCALL
5280     dSP; dMARK; dORIGMARK; dTARGET;
5281     register I32 items = SP - MARK;
5282     unsigned long a[20];
5283     register I32 i = 0;
5284     I32 retval = -1;
5285
5286     if (PL_tainting) {
5287         while (++MARK <= SP) {
5288             if (SvTAINTED(*MARK)) {
5289                 TAINT;
5290                 break;
5291             }
5292         }
5293         MARK = ORIGMARK;
5294         TAINT_PROPER("syscall");
5295     }
5296
5297     /* This probably won't work on machines where sizeof(long) != sizeof(int)
5298      * or where sizeof(long) != sizeof(char*).  But such machines will
5299      * not likely have syscall implemented either, so who cares?
5300      */
5301     while (++MARK <= SP) {
5302         if (SvNIOK(*MARK) || !i)
5303             a[i++] = SvIV(*MARK);
5304         else if (*MARK == &PL_sv_undef)
5305             a[i++] = 0;
5306         else
5307             a[i++] = (unsigned long)SvPV_force_nolen(*MARK);
5308         if (i > 15)
5309             break;
5310     }
5311     switch (items) {
5312     default:
5313         DIE(aTHX_ "Too many args to syscall");
5314     case 0:
5315         DIE(aTHX_ "Too few args to syscall");
5316     case 1:
5317         retval = syscall(a[0]);
5318         break;
5319     case 2:
5320         retval = syscall(a[0],a[1]);
5321         break;
5322     case 3:
5323         retval = syscall(a[0],a[1],a[2]);
5324         break;
5325     case 4:
5326         retval = syscall(a[0],a[1],a[2],a[3]);
5327         break;
5328     case 5:
5329         retval = syscall(a[0],a[1],a[2],a[3],a[4]);
5330         break;
5331     case 6:
5332         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5]);
5333         break;
5334     case 7:
5335         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6]);
5336         break;
5337     case 8:
5338         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]);
5339         break;
5340 #ifdef atarist
5341     case 9:
5342         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
5343         break;
5344     case 10:
5345         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9]);
5346         break;
5347     case 11:
5348         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5349           a[10]);
5350         break;
5351     case 12:
5352         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5353           a[10],a[11]);
5354         break;
5355     case 13:
5356         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5357           a[10],a[11],a[12]);
5358         break;
5359     case 14:
5360         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5361           a[10],a[11],a[12],a[13]);
5362         break;
5363 #endif /* atarist */
5364     }
5365     SP = ORIGMARK;
5366     PUSHi(retval);
5367     RETURN;
5368 #else
5369     DIE(aTHX_ PL_no_func, "syscall");
5370 #endif
5371 }
5372
5373 #ifdef FCNTL_EMULATE_FLOCK
5374
5375 /*  XXX Emulate flock() with fcntl().
5376     What's really needed is a good file locking module.
5377 */
5378
5379 static int
5380 fcntl_emulate_flock(int fd, int operation)
5381 {
5382     struct flock flock;
5383
5384     switch (operation & ~LOCK_NB) {
5385     case LOCK_SH:
5386         flock.l_type = F_RDLCK;
5387         break;
5388     case LOCK_EX:
5389         flock.l_type = F_WRLCK;
5390         break;
5391     case LOCK_UN:
5392         flock.l_type = F_UNLCK;
5393         break;
5394     default:
5395         errno = EINVAL;
5396         return -1;
5397     }
5398     flock.l_whence = SEEK_SET;
5399     flock.l_start = flock.l_len = (Off_t)0;
5400
5401     return fcntl(fd, (operation & LOCK_NB) ? F_SETLK : F_SETLKW, &flock);
5402 }
5403
5404 #endif /* FCNTL_EMULATE_FLOCK */
5405
5406 #ifdef LOCKF_EMULATE_FLOCK
5407
5408 /*  XXX Emulate flock() with lockf().  This is just to increase
5409     portability of scripts.  The calls are not completely
5410     interchangeable.  What's really needed is a good file
5411     locking module.
5412 */
5413
5414 /*  The lockf() constants might have been defined in <unistd.h>.
5415     Unfortunately, <unistd.h> causes troubles on some mixed
5416     (BSD/POSIX) systems, such as SunOS 4.1.3.
5417
5418    Further, the lockf() constants aren't POSIX, so they might not be
5419    visible if we're compiling with _POSIX_SOURCE defined.  Thus, we'll
5420    just stick in the SVID values and be done with it.  Sigh.
5421 */
5422
5423 # ifndef F_ULOCK
5424 #  define F_ULOCK       0       /* Unlock a previously locked region */
5425 # endif
5426 # ifndef F_LOCK
5427 #  define F_LOCK        1       /* Lock a region for exclusive use */
5428 # endif
5429 # ifndef F_TLOCK
5430 #  define F_TLOCK       2       /* Test and lock a region for exclusive use */
5431 # endif
5432 # ifndef F_TEST
5433 #  define F_TEST        3       /* Test a region for other processes locks */
5434 # endif
5435
5436 static int
5437 lockf_emulate_flock(int fd, int operation)
5438 {
5439     int i;
5440     int save_errno;
5441     Off_t pos;
5442
5443     /* flock locks entire file so for lockf we need to do the same      */
5444     save_errno = errno;
5445     pos = PerlLIO_lseek(fd, (Off_t)0, SEEK_CUR);    /* get pos to restore later */
5446     if (pos > 0)        /* is seekable and needs to be repositioned     */
5447         if (PerlLIO_lseek(fd, (Off_t)0, SEEK_SET) < 0)
5448             pos = -1;   /* seek failed, so don't seek back afterwards   */
5449     errno = save_errno;
5450
5451     switch (operation) {
5452
5453         /* LOCK_SH - get a shared lock */
5454         case LOCK_SH:
5455         /* LOCK_EX - get an exclusive lock */
5456         case LOCK_EX:
5457             i = lockf (fd, F_LOCK, 0);
5458             break;
5459
5460         /* LOCK_SH|LOCK_NB - get a non-blocking shared lock */
5461         case LOCK_SH|LOCK_NB:
5462         /* LOCK_EX|LOCK_NB - get a non-blocking exclusive lock */
5463         case LOCK_EX|LOCK_NB:
5464             i = lockf (fd, F_TLOCK, 0);
5465             if (i == -1)
5466                 if ((errno == EAGAIN) || (errno == EACCES))
5467                     errno = EWOULDBLOCK;
5468             break;
5469
5470         /* LOCK_UN - unlock (non-blocking is a no-op) */
5471         case LOCK_UN:
5472         case LOCK_UN|LOCK_NB:
5473             i = lockf (fd, F_ULOCK, 0);
5474             break;
5475
5476         /* Default - can't decipher operation */
5477         default:
5478             i = -1;
5479             errno = EINVAL;
5480             break;
5481     }
5482
5483     if (pos > 0)      /* need to restore position of the handle */
5484         PerlLIO_lseek(fd, pos, SEEK_SET);       /* ignore error here    */
5485
5486     return (i);
5487 }
5488
5489 #endif /* LOCKF_EMULATE_FLOCK */
5490
5491 /*
5492  * Local variables:
5493  * c-indentation-style: bsd
5494  * c-basic-offset: 4
5495  * indent-tabs-mode: t
5496  * End:
5497  *
5498  * ex: set ts=8 sts=4 sw=4 noet:
5499  */