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