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