b31bc349afdeed084382490849adbffbfa6d3b4c
[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_send)
1772 {
1773     dVAR; dSP; dMARK; dORIGMARK; dTARGET;
1774     GV *gv;
1775     IO *io;
1776     SV *bufsv;
1777     const char *buffer;
1778     Size_t length = 0;
1779     SSize_t retval;
1780     STRLEN blen;
1781     MAGIC *mg;
1782     const int op_type = PL_op->op_type;
1783     
1784     gv = (GV*)*++MARK;
1785     if (PL_op->op_type == OP_SYSWRITE
1786         && gv && (io = GvIO(gv))
1787         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1788     {
1789         SV *sv;
1790
1791         if (MARK == SP - 1) {
1792             EXTEND(SP, 1000);
1793             sv = sv_2mortal(newSViv(sv_len(*SP)));
1794             PUSHs(sv);
1795             PUTBACK;
1796         }
1797         
1798         PUSHMARK(ORIGMARK);
1799         *(ORIGMARK+1) = SvTIED_obj((SV*)io, mg);
1800         ENTER;
1801         call_method("WRITE", G_SCALAR);
1802         LEAVE;
1803         SPAGAIN;
1804         sv = POPs;
1805         SP = ORIGMARK;
1806         PUSHs(sv);
1807         RETURN;
1808     }
1809     if (!gv)
1810         goto say_undef;
1811
1812     bufsv = *++MARK;
1813
1814     if (op_type == OP_SYSWRITE) {
1815         if (MARK >= SP) {
1816             length = (Size_t) sv_len(bufsv);
1817         } else {
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         }
1826     }
1827     SETERRNO(0,0);
1828     io = GvIO(gv);
1829     if (!io || !IoIFP(io)) {
1830         retval = -1;
1831         if (ckWARN(WARN_CLOSED))
1832             report_evil_fh(gv, io, PL_op->op_type);
1833         SETERRNO(EBADF,RMS_IFI);
1834         goto say_undef;
1835     }
1836
1837     if (PerlIO_isutf8(IoIFP(io))) {
1838         if (!SvUTF8(bufsv)) {
1839             bufsv = sv_2mortal(newSVsv(bufsv));
1840             buffer = sv_2pvutf8(bufsv, &blen);
1841         } else
1842             buffer = SvPV_const(bufsv, blen);
1843     }
1844     else {
1845          if (DO_UTF8(bufsv)) {
1846               /* Not modifying source SV, so making a temporary copy. */
1847               bufsv = sv_2mortal(newSVsv(bufsv));
1848               sv_utf8_downgrade(bufsv, FALSE);
1849          }
1850          buffer = SvPV_const(bufsv, blen);
1851     }
1852
1853     if (op_type == OP_SYSWRITE) {
1854         IV offset;
1855         if (DO_UTF8(bufsv)) {
1856             /* length and offset are in chars */
1857             blen   = sv_len_utf8(bufsv);
1858         }
1859         if (MARK < SP) {
1860             offset = SvIVx(*++MARK);
1861             if (offset < 0) {
1862                 if (-offset > (IV)blen)
1863                     DIE(aTHX_ "Offset outside string");
1864                 offset += blen;
1865             } else if (offset >= (IV)blen && blen > 0)
1866                 DIE(aTHX_ "Offset outside string");
1867         } else
1868             offset = 0;
1869         if (length > blen - offset)
1870             length = blen - offset;
1871         if (DO_UTF8(bufsv)) {
1872             buffer = (const char*)utf8_hop((const U8 *)buffer, offset);
1873             length = utf8_hop((U8 *)buffer, length) - (U8 *)buffer;
1874         }
1875         else {
1876             buffer = buffer+offset;
1877         }
1878 #ifdef PERL_SOCK_SYSWRITE_IS_SEND
1879         if (IoTYPE(io) == IoTYPE_SOCKET) {
1880             retval = PerlSock_send(PerlIO_fileno(IoIFP(io)),
1881                                    buffer, length, 0);
1882         }
1883         else
1884 #endif
1885         {
1886             /* See the note at doio.c:do_print about filesize limits. --jhi */
1887             retval = PerlLIO_write(PerlIO_fileno(IoIFP(io)),
1888                                    buffer, length);
1889         }
1890     }
1891 #ifdef HAS_SOCKET
1892     else {
1893         const int flags = SvIVx(*++MARK);
1894         if (SP > MARK) {
1895             STRLEN mlen;
1896             char * const sockbuf = SvPVx(*++MARK, mlen);
1897             retval = PerlSock_sendto(PerlIO_fileno(IoIFP(io)), buffer, blen,
1898                                      flags, (struct sockaddr *)sockbuf, mlen);
1899         }
1900         else {
1901             retval
1902                 = PerlSock_send(PerlIO_fileno(IoIFP(io)), buffer, blen, flags);
1903         }
1904     }
1905 #else
1906     else
1907         DIE(aTHX_ PL_no_sock_func, "send");
1908 #endif
1909     if (retval < 0)
1910         goto say_undef;
1911     SP = ORIGMARK;
1912     if (DO_UTF8(bufsv))
1913         retval = utf8_length((U8*)buffer, (U8*)buffer + retval);
1914 #if Size_t_size > IVSIZE
1915     PUSHn(retval);
1916 #else
1917     PUSHi(retval);
1918 #endif
1919     RETURN;
1920
1921   say_undef:
1922     SP = ORIGMARK;
1923     RETPUSHUNDEF;
1924 }
1925
1926 PP(pp_eof)
1927 {
1928     dVAR; dSP;
1929     GV *gv;
1930     IO *io;
1931     MAGIC *mg;
1932
1933     if (MAXARG == 0) {
1934         if (PL_op->op_flags & OPf_SPECIAL) {    /* eof() */
1935             IO *io;
1936             gv = PL_last_in_gv = GvEGV(PL_argvgv);
1937             io = GvIO(gv);
1938             if (io && !IoIFP(io)) {
1939                 if ((IoFLAGS(io) & IOf_START) && av_len(GvAVn(gv)) < 0) {
1940                     IoLINES(io) = 0;
1941                     IoFLAGS(io) &= ~IOf_START;
1942                     do_open(gv, "-", 1, FALSE, O_RDONLY, 0, Nullfp);
1943                     sv_setpvn(GvSV(gv), "-", 1);
1944                     SvSETMAGIC(GvSV(gv));
1945                 }
1946                 else if (!nextargv(gv))
1947                     RETPUSHYES;
1948             }
1949         }
1950         else
1951             gv = PL_last_in_gv;                 /* eof */
1952     }
1953     else
1954         gv = PL_last_in_gv = (GV*)POPs;         /* eof(FH) */
1955
1956     if (gv && (io = GvIO(gv))
1957         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1958     {
1959         PUSHMARK(SP);
1960         XPUSHs(SvTIED_obj((SV*)io, mg));
1961         PUTBACK;
1962         ENTER;
1963         call_method("EOF", G_SCALAR);
1964         LEAVE;
1965         SPAGAIN;
1966         RETURN;
1967     }
1968
1969     PUSHs(boolSV(!gv || do_eof(gv)));
1970     RETURN;
1971 }
1972
1973 PP(pp_tell)
1974 {
1975     dVAR; dSP; dTARGET;
1976     GV *gv;
1977     IO *io;
1978     MAGIC *mg;
1979
1980     if (MAXARG != 0)
1981         PL_last_in_gv = (GV*)POPs;
1982     gv = PL_last_in_gv;
1983
1984     if (gv && (io = GvIO(gv))
1985         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1986     {
1987         PUSHMARK(SP);
1988         XPUSHs(SvTIED_obj((SV*)io, mg));
1989         PUTBACK;
1990         ENTER;
1991         call_method("TELL", G_SCALAR);
1992         LEAVE;
1993         SPAGAIN;
1994         RETURN;
1995     }
1996
1997 #if LSEEKSIZE > IVSIZE
1998     PUSHn( do_tell(gv) );
1999 #else
2000     PUSHi( do_tell(gv) );
2001 #endif
2002     RETURN;
2003 }
2004
2005 PP(pp_sysseek)
2006 {
2007     dVAR; dSP;
2008     GV *gv;
2009     IO *io;
2010     const int whence = POPi;
2011 #if LSEEKSIZE > IVSIZE
2012     Off_t offset = (Off_t)SvNVx(POPs);
2013 #else
2014     Off_t offset = (Off_t)SvIVx(POPs);
2015 #endif
2016     MAGIC *mg;
2017
2018     gv = PL_last_in_gv = (GV*)POPs;
2019
2020     if (gv && (io = GvIO(gv))
2021         && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
2022     {
2023         PUSHMARK(SP);
2024         XPUSHs(SvTIED_obj((SV*)io, mg));
2025 #if LSEEKSIZE > IVSIZE
2026         XPUSHs(sv_2mortal(newSVnv((NV) offset)));
2027 #else
2028         XPUSHs(sv_2mortal(newSViv(offset)));
2029 #endif
2030         XPUSHs(sv_2mortal(newSViv(whence)));
2031         PUTBACK;
2032         ENTER;
2033         call_method("SEEK", G_SCALAR);
2034         LEAVE;
2035         SPAGAIN;
2036         RETURN;
2037     }
2038
2039     if (PL_op->op_type == OP_SEEK)
2040         PUSHs(boolSV(do_seek(gv, offset, whence)));
2041     else {
2042         Off_t sought = do_sysseek(gv, offset, whence);
2043         if (sought < 0)
2044             PUSHs(&PL_sv_undef);
2045         else {
2046             SV* sv = sought ?
2047 #if LSEEKSIZE > IVSIZE
2048                 newSVnv((NV)sought)
2049 #else
2050                 newSViv(sought)
2051 #endif
2052                 : newSVpvn(zero_but_true, ZBTLEN);
2053             PUSHs(sv_2mortal(sv));
2054         }
2055     }
2056     RETURN;
2057 }
2058
2059 PP(pp_truncate)
2060 {
2061     dSP;
2062     /* There seems to be no consensus on the length type of truncate()
2063      * and ftruncate(), both off_t and size_t have supporters. In
2064      * general one would think that when using large files, off_t is
2065      * at least as wide as size_t, so using an off_t should be okay. */
2066     /* XXX Configure probe for the length type of *truncate() needed XXX */
2067     Off_t len;
2068
2069 #if Off_t_size > IVSIZE
2070     len = (Off_t)POPn;
2071 #else
2072     len = (Off_t)POPi;
2073 #endif
2074     /* Checking for length < 0 is problematic as the type might or
2075      * might not be signed: if it is not, clever compilers will moan. */
2076     /* XXX Configure probe for the signedness of the length type of *truncate() needed? XXX */
2077     SETERRNO(0,0);
2078     {
2079         int result = 1;
2080         GV *tmpgv;
2081         IO *io;
2082
2083         if (PL_op->op_flags & OPf_SPECIAL) {
2084             tmpgv = gv_fetchsv(POPs, FALSE, SVt_PVIO);
2085
2086         do_ftruncate_gv:
2087             if (!GvIO(tmpgv))
2088                 result = 0;
2089             else {
2090                 PerlIO *fp;
2091                 io = GvIOp(tmpgv);
2092             do_ftruncate_io:
2093                 TAINT_PROPER("truncate");
2094                 if (!(fp = IoIFP(io))) {
2095                     result = 0;
2096                 }
2097                 else {
2098                     PerlIO_flush(fp);
2099 #ifdef HAS_TRUNCATE
2100                     if (ftruncate(PerlIO_fileno(fp), len) < 0)
2101 #else
2102                     if (my_chsize(PerlIO_fileno(fp), len) < 0)
2103 #endif
2104                         result = 0;
2105                 }
2106             }
2107         }
2108         else {
2109             SV *sv = POPs;
2110             const char *name;
2111
2112             if (SvTYPE(sv) == SVt_PVGV) {
2113                 tmpgv = (GV*)sv;                /* *main::FRED for example */
2114                 goto do_ftruncate_gv;
2115             }
2116             else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV) {
2117                 tmpgv = (GV*) SvRV(sv); /* \*main::FRED for example */
2118                 goto do_ftruncate_gv;
2119             }
2120             else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
2121                 io = (IO*) SvRV(sv); /* *main::FRED{IO} for example */
2122                 goto do_ftruncate_io;
2123             }
2124
2125             name = SvPV_nolen_const(sv);
2126             TAINT_PROPER("truncate");
2127 #ifdef HAS_TRUNCATE
2128             if (truncate(name, len) < 0)
2129                 result = 0;
2130 #else
2131             {
2132                 int tmpfd;
2133
2134                 if ((tmpfd = PerlLIO_open(name, O_RDWR)) < 0)
2135                     result = 0;
2136                 else {
2137                     if (my_chsize(tmpfd, len) < 0)
2138                         result = 0;
2139                     PerlLIO_close(tmpfd);
2140                 }
2141             }
2142 #endif
2143         }
2144
2145         if (result)
2146             RETPUSHYES;
2147         if (!errno)
2148             SETERRNO(EBADF,RMS_IFI);
2149         RETPUSHUNDEF;
2150     }
2151 }
2152
2153 PP(pp_ioctl)
2154 {
2155     dSP; dTARGET;
2156     SV *argsv = POPs;
2157     const unsigned int func = POPu;
2158     const int optype = PL_op->op_type;
2159     char *s;
2160     IV retval;
2161     GV *gv = (GV*)POPs;
2162     IO *io = gv ? GvIOn(gv) : 0;
2163
2164     if (!io || !argsv || !IoIFP(io)) {
2165         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2166             report_evil_fh(gv, io, PL_op->op_type);
2167         SETERRNO(EBADF,RMS_IFI);        /* well, sort of... */
2168         RETPUSHUNDEF;
2169     }
2170
2171     if (SvPOK(argsv) || !SvNIOK(argsv)) {
2172         STRLEN len;
2173         STRLEN need;
2174         s = SvPV_force(argsv, len);
2175         need = IOCPARM_LEN(func);
2176         if (len < need) {
2177             s = Sv_Grow(argsv, need + 1);
2178             SvCUR_set(argsv, need);
2179         }
2180
2181         s[SvCUR(argsv)] = 17;   /* a little sanity check here */
2182     }
2183     else {
2184         retval = SvIV(argsv);
2185         s = INT2PTR(char*,retval);              /* ouch */
2186     }
2187
2188     TAINT_PROPER(optype == OP_IOCTL ? "ioctl" : "fcntl");
2189
2190     if (optype == OP_IOCTL)
2191 #ifdef HAS_IOCTL
2192         retval = PerlLIO_ioctl(PerlIO_fileno(IoIFP(io)), func, s);
2193 #else
2194         DIE(aTHX_ "ioctl is not implemented");
2195 #endif
2196     else
2197 #ifndef HAS_FCNTL
2198       DIE(aTHX_ "fcntl is not implemented");
2199 #else
2200 #if defined(OS2) && defined(__EMX__)
2201         retval = fcntl(PerlIO_fileno(IoIFP(io)), func, (int)s);
2202 #else
2203         retval = fcntl(PerlIO_fileno(IoIFP(io)), func, s);
2204 #endif
2205 #endif
2206
2207 #if defined(HAS_IOCTL) || defined(HAS_FCNTL)
2208     if (SvPOK(argsv)) {
2209         if (s[SvCUR(argsv)] != 17)
2210             DIE(aTHX_ "Possible memory corruption: %s overflowed 3rd argument",
2211                 OP_NAME(PL_op));
2212         s[SvCUR(argsv)] = 0;            /* put our null back */
2213         SvSETMAGIC(argsv);              /* Assume it has changed */
2214     }
2215
2216     if (retval == -1)
2217         RETPUSHUNDEF;
2218     if (retval != 0) {
2219         PUSHi(retval);
2220     }
2221     else {
2222         PUSHp(zero_but_true, ZBTLEN);
2223     }
2224 #endif
2225     RETURN;
2226 }
2227
2228 PP(pp_flock)
2229 {
2230 #ifdef FLOCK
2231     dSP; dTARGET;
2232     I32 value;
2233     int argtype;
2234     GV *gv;
2235     IO *io = NULL;
2236     PerlIO *fp;
2237
2238     argtype = POPi;
2239     if (MAXARG == 0)
2240         gv = PL_last_in_gv;
2241     else
2242         gv = (GV*)POPs;
2243     if (gv && (io = GvIO(gv)))
2244         fp = IoIFP(io);
2245     else {
2246         fp = Nullfp;
2247         io = NULL;
2248     }
2249     if (fp) {
2250         (void)PerlIO_flush(fp);
2251         value = (I32)(PerlLIO_flock(PerlIO_fileno(fp), argtype) >= 0);
2252     }
2253     else {
2254         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2255             report_evil_fh(gv, io, PL_op->op_type);
2256         value = 0;
2257         SETERRNO(EBADF,RMS_IFI);
2258     }
2259     PUSHi(value);
2260     RETURN;
2261 #else
2262     DIE(aTHX_ PL_no_func, "flock()");
2263 #endif
2264 }
2265
2266 /* Sockets. */
2267
2268 PP(pp_socket)
2269 {
2270 #ifdef HAS_SOCKET
2271     dSP;
2272     GV *gv;
2273     register IO *io;
2274     int protocol = POPi;
2275     int type = POPi;
2276     int domain = POPi;
2277     int fd;
2278
2279     gv = (GV*)POPs;
2280     io = gv ? GvIOn(gv) : NULL;
2281
2282     if (!gv || !io) {
2283         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2284             report_evil_fh(gv, io, PL_op->op_type);
2285         if (IoIFP(io))
2286             do_close(gv, FALSE);
2287         SETERRNO(EBADF,LIB_INVARG);
2288         RETPUSHUNDEF;
2289     }
2290
2291     if (IoIFP(io))
2292         do_close(gv, FALSE);
2293
2294     TAINT_PROPER("socket");
2295     fd = PerlSock_socket(domain, type, protocol);
2296     if (fd < 0)
2297         RETPUSHUNDEF;
2298     IoIFP(io) = PerlIO_fdopen(fd, "r"SOCKET_OPEN_MODE); /* stdio gets confused about sockets */
2299     IoOFP(io) = PerlIO_fdopen(fd, "w"SOCKET_OPEN_MODE);
2300     IoTYPE(io) = IoTYPE_SOCKET;
2301     if (!IoIFP(io) || !IoOFP(io)) {
2302         if (IoIFP(io)) PerlIO_close(IoIFP(io));
2303         if (IoOFP(io)) PerlIO_close(IoOFP(io));
2304         if (!IoIFP(io) && !IoOFP(io)) PerlLIO_close(fd);
2305         RETPUSHUNDEF;
2306     }
2307 #if defined(HAS_FCNTL) && defined(F_SETFD)
2308     fcntl(fd, F_SETFD, fd > PL_maxsysfd);       /* ensure close-on-exec */
2309 #endif
2310
2311 #ifdef EPOC
2312     setbuf( IoIFP(io), NULL); /* EPOC gets confused about sockets */
2313 #endif
2314
2315     RETPUSHYES;
2316 #else
2317     DIE(aTHX_ PL_no_sock_func, "socket");
2318 #endif
2319 }
2320
2321 PP(pp_sockpair)
2322 {
2323 #if defined (HAS_SOCKETPAIR) || (defined (HAS_SOCKET) && defined(SOCK_DGRAM) && defined(AF_INET) && defined(PF_INET))
2324     dSP;
2325     GV *gv1;
2326     GV *gv2;
2327     register IO *io1;
2328     register IO *io2;
2329     int protocol = POPi;
2330     int type = POPi;
2331     int domain = POPi;
2332     int fd[2];
2333
2334     gv2 = (GV*)POPs;
2335     gv1 = (GV*)POPs;
2336     io1 = gv1 ? GvIOn(gv1) : NULL;
2337     io2 = gv2 ? GvIOn(gv2) : NULL;
2338     if (!gv1 || !gv2 || !io1 || !io2) {
2339         if (ckWARN2(WARN_UNOPENED,WARN_CLOSED)) {
2340             if (!gv1 || !io1)
2341                 report_evil_fh(gv1, io1, PL_op->op_type);
2342             if (!gv2 || !io2)
2343                 report_evil_fh(gv1, io2, PL_op->op_type);
2344         }
2345         if (IoIFP(io1))
2346             do_close(gv1, FALSE);
2347         if (IoIFP(io2))
2348             do_close(gv2, FALSE);
2349         RETPUSHUNDEF;
2350     }
2351
2352     if (IoIFP(io1))
2353         do_close(gv1, FALSE);
2354     if (IoIFP(io2))
2355         do_close(gv2, FALSE);
2356
2357     TAINT_PROPER("socketpair");
2358     if (PerlSock_socketpair(domain, type, protocol, fd) < 0)
2359         RETPUSHUNDEF;
2360     IoIFP(io1) = PerlIO_fdopen(fd[0], "r"SOCKET_OPEN_MODE);
2361     IoOFP(io1) = PerlIO_fdopen(fd[0], "w"SOCKET_OPEN_MODE);
2362     IoTYPE(io1) = IoTYPE_SOCKET;
2363     IoIFP(io2) = PerlIO_fdopen(fd[1], "r"SOCKET_OPEN_MODE);
2364     IoOFP(io2) = PerlIO_fdopen(fd[1], "w"SOCKET_OPEN_MODE);
2365     IoTYPE(io2) = IoTYPE_SOCKET;
2366     if (!IoIFP(io1) || !IoOFP(io1) || !IoIFP(io2) || !IoOFP(io2)) {
2367         if (IoIFP(io1)) PerlIO_close(IoIFP(io1));
2368         if (IoOFP(io1)) PerlIO_close(IoOFP(io1));
2369         if (!IoIFP(io1) && !IoOFP(io1)) PerlLIO_close(fd[0]);
2370         if (IoIFP(io2)) PerlIO_close(IoIFP(io2));
2371         if (IoOFP(io2)) PerlIO_close(IoOFP(io2));
2372         if (!IoIFP(io2) && !IoOFP(io2)) PerlLIO_close(fd[1]);
2373         RETPUSHUNDEF;
2374     }
2375 #if defined(HAS_FCNTL) && defined(F_SETFD)
2376     fcntl(fd[0],F_SETFD,fd[0] > PL_maxsysfd);   /* ensure close-on-exec */
2377     fcntl(fd[1],F_SETFD,fd[1] > PL_maxsysfd);   /* ensure close-on-exec */
2378 #endif
2379
2380     RETPUSHYES;
2381 #else
2382     DIE(aTHX_ PL_no_sock_func, "socketpair");
2383 #endif
2384 }
2385
2386 PP(pp_bind)
2387 {
2388 #ifdef HAS_SOCKET
2389     dSP;
2390 #ifdef MPE /* Requires PRIV mode to bind() to ports < 1024 */
2391     extern void GETPRIVMODE();
2392     extern void GETUSERMODE();
2393 #endif
2394     SV *addrsv = POPs;
2395     /* OK, so on what platform does bind modify addr?  */
2396     const char *addr;
2397     GV *gv = (GV*)POPs;
2398     register IO *io = GvIOn(gv);
2399     STRLEN len;
2400     int bind_ok = 0;
2401 #ifdef MPE
2402     int mpeprivmode = 0;
2403 #endif
2404
2405     if (!io || !IoIFP(io))
2406         goto nuts;
2407
2408     addr = SvPV_const(addrsv, len);
2409     TAINT_PROPER("bind");
2410 #ifdef MPE /* Deal with MPE bind() peculiarities */
2411     if (((struct sockaddr *)addr)->sa_family == AF_INET) {
2412         /* The address *MUST* stupidly be zero. */
2413         ((struct sockaddr_in *)addr)->sin_addr.s_addr = INADDR_ANY;
2414         /* PRIV mode is required to bind() to ports < 1024. */
2415         if (((struct sockaddr_in *)addr)->sin_port < 1024 &&
2416             ((struct sockaddr_in *)addr)->sin_port > 0) {
2417             GETPRIVMODE(); /* If this fails, we are aborted by MPE/iX. */
2418             mpeprivmode = 1;
2419         }
2420     }
2421 #endif /* MPE */
2422     if (PerlSock_bind(PerlIO_fileno(IoIFP(io)),
2423                       (struct sockaddr *)addr, len) >= 0)
2424         bind_ok = 1;
2425
2426 #ifdef MPE /* Switch back to USER mode */
2427     if (mpeprivmode)
2428         GETUSERMODE();
2429 #endif /* MPE */
2430
2431     if (bind_ok)
2432         RETPUSHYES;
2433     else
2434         RETPUSHUNDEF;
2435
2436 nuts:
2437     if (ckWARN(WARN_CLOSED))
2438         report_evil_fh(gv, io, PL_op->op_type);
2439     SETERRNO(EBADF,SS_IVCHAN);
2440     RETPUSHUNDEF;
2441 #else
2442     DIE(aTHX_ PL_no_sock_func, "bind");
2443 #endif
2444 }
2445
2446 PP(pp_connect)
2447 {
2448 #ifdef HAS_SOCKET
2449     dSP;
2450     SV *addrsv = POPs;
2451     const char *addr;
2452     GV *gv = (GV*)POPs;
2453     register IO *io = GvIOn(gv);
2454     STRLEN len;
2455
2456     if (!io || !IoIFP(io))
2457         goto nuts;
2458
2459     addr = SvPV_const(addrsv, len);
2460     TAINT_PROPER("connect");
2461     if (PerlSock_connect(PerlIO_fileno(IoIFP(io)), (struct sockaddr *)addr, len) >= 0)
2462         RETPUSHYES;
2463     else
2464         RETPUSHUNDEF;
2465
2466 nuts:
2467     if (ckWARN(WARN_CLOSED))
2468         report_evil_fh(gv, io, PL_op->op_type);
2469     SETERRNO(EBADF,SS_IVCHAN);
2470     RETPUSHUNDEF;
2471 #else
2472     DIE(aTHX_ PL_no_sock_func, "connect");
2473 #endif
2474 }
2475
2476 PP(pp_listen)
2477 {
2478 #ifdef HAS_SOCKET
2479     dSP;
2480     int backlog = POPi;
2481     GV *gv = (GV*)POPs;
2482     register IO *io = gv ? GvIOn(gv) : NULL;
2483
2484     if (!gv || !io || !IoIFP(io))
2485         goto nuts;
2486
2487     if (PerlSock_listen(PerlIO_fileno(IoIFP(io)), backlog) >= 0)
2488         RETPUSHYES;
2489     else
2490         RETPUSHUNDEF;
2491
2492 nuts:
2493     if (ckWARN(WARN_CLOSED))
2494         report_evil_fh(gv, io, PL_op->op_type);
2495     SETERRNO(EBADF,SS_IVCHAN);
2496     RETPUSHUNDEF;
2497 #else
2498     DIE(aTHX_ PL_no_sock_func, "listen");
2499 #endif
2500 }
2501
2502 PP(pp_accept)
2503 {
2504 #ifdef HAS_SOCKET
2505     dSP; dTARGET;
2506     GV *ngv;
2507     GV *ggv;
2508     register IO *nstio;
2509     register IO *gstio;
2510     char namebuf[MAXPATHLEN];
2511 #if (defined(VMS_DO_SOCKETS) && defined(DECCRTL_SOCKETS)) || defined(MPE) || defined(__QNXNTO__)
2512     Sock_size_t len = sizeof (struct sockaddr_in);
2513 #else
2514     Sock_size_t len = sizeof namebuf;
2515 #endif
2516     int fd;
2517
2518     ggv = (GV*)POPs;
2519     ngv = (GV*)POPs;
2520
2521     if (!ngv)
2522         goto badexit;
2523     if (!ggv)
2524         goto nuts;
2525
2526     gstio = GvIO(ggv);
2527     if (!gstio || !IoIFP(gstio))
2528         goto nuts;
2529
2530     nstio = GvIOn(ngv);
2531     fd = PerlSock_accept(PerlIO_fileno(IoIFP(gstio)), (struct sockaddr *) namebuf, &len);
2532     if (fd < 0)
2533         goto badexit;
2534     if (IoIFP(nstio))
2535         do_close(ngv, FALSE);
2536     IoIFP(nstio) = PerlIO_fdopen(fd, "r"SOCKET_OPEN_MODE);
2537     IoOFP(nstio) = PerlIO_fdopen(fd, "w"SOCKET_OPEN_MODE);
2538     IoTYPE(nstio) = IoTYPE_SOCKET;
2539     if (!IoIFP(nstio) || !IoOFP(nstio)) {
2540         if (IoIFP(nstio)) PerlIO_close(IoIFP(nstio));
2541         if (IoOFP(nstio)) PerlIO_close(IoOFP(nstio));
2542         if (!IoIFP(nstio) && !IoOFP(nstio)) PerlLIO_close(fd);
2543         goto badexit;
2544     }
2545 #if defined(HAS_FCNTL) && defined(F_SETFD)
2546     fcntl(fd, F_SETFD, fd > PL_maxsysfd);       /* ensure close-on-exec */
2547 #endif
2548
2549 #ifdef EPOC
2550     len = sizeof (struct sockaddr_in); /* EPOC somehow truncates info */
2551     setbuf( IoIFP(nstio), NULL); /* EPOC gets confused about sockets */
2552 #endif
2553 #ifdef __SCO_VERSION__
2554     len = sizeof (struct sockaddr_in); /* OpenUNIX 8 somehow truncates info */
2555 #endif
2556
2557     PUSHp(namebuf, len);
2558     RETURN;
2559
2560 nuts:
2561     if (ckWARN(WARN_CLOSED))
2562         report_evil_fh(ggv, ggv ? GvIO(ggv) : 0, PL_op->op_type);
2563     SETERRNO(EBADF,SS_IVCHAN);
2564
2565 badexit:
2566     RETPUSHUNDEF;
2567
2568 #else
2569     DIE(aTHX_ PL_no_sock_func, "accept");
2570 #endif
2571 }
2572
2573 PP(pp_shutdown)
2574 {
2575 #ifdef HAS_SOCKET
2576     dSP; dTARGET;
2577     int how = POPi;
2578     GV *gv = (GV*)POPs;
2579     register IO *io = GvIOn(gv);
2580
2581     if (!io || !IoIFP(io))
2582         goto nuts;
2583
2584     PUSHi( PerlSock_shutdown(PerlIO_fileno(IoIFP(io)), how) >= 0 );
2585     RETURN;
2586
2587 nuts:
2588     if (ckWARN(WARN_CLOSED))
2589         report_evil_fh(gv, io, PL_op->op_type);
2590     SETERRNO(EBADF,SS_IVCHAN);
2591     RETPUSHUNDEF;
2592 #else
2593     DIE(aTHX_ PL_no_sock_func, "shutdown");
2594 #endif
2595 }
2596
2597 PP(pp_ssockopt)
2598 {
2599 #ifdef HAS_SOCKET
2600     dSP;
2601     int optype = PL_op->op_type;
2602     SV *sv;
2603     int fd;
2604     unsigned int optname;
2605     unsigned int lvl;
2606     GV *gv;
2607     register IO *io;
2608     Sock_size_t len;
2609
2610     if (optype == OP_GSOCKOPT)
2611         sv = sv_2mortal(NEWSV(22, 257));
2612     else
2613         sv = POPs;
2614     optname = (unsigned int) POPi;
2615     lvl = (unsigned int) POPi;
2616
2617     gv = (GV*)POPs;
2618     io = GvIOn(gv);
2619     if (!io || !IoIFP(io))
2620         goto nuts;
2621
2622     fd = PerlIO_fileno(IoIFP(io));
2623     switch (optype) {
2624     case OP_GSOCKOPT:
2625         SvGROW(sv, 257);
2626         (void)SvPOK_only(sv);
2627         SvCUR_set(sv,256);
2628         *SvEND(sv) ='\0';
2629         len = SvCUR(sv);
2630         if (PerlSock_getsockopt(fd, lvl, optname, SvPVX(sv), &len) < 0)
2631             goto nuts2;
2632         SvCUR_set(sv, len);
2633         *SvEND(sv) ='\0';
2634         PUSHs(sv);
2635         break;
2636     case OP_SSOCKOPT: {
2637 #if defined(__SYMBIAN32__)
2638 # define SETSOCKOPT_OPTION_VALUE_T void *
2639 #else
2640 # define SETSOCKOPT_OPTION_VALUE_T const char *
2641 #endif
2642         /* XXX TODO: We need to have a proper type (a Configure probe,
2643          * etc.) for what the C headers think of the third argument of
2644          * setsockopt(), the option_value read-only buffer: is it
2645          * a "char *", or a "void *", const or not.  Some compilers
2646          * don't take kindly to e.g. assuming that "char *" implicitly
2647          * promotes to a "void *", or to explicitly promoting/demoting
2648          * consts to non/vice versa.  The "const void *" is the SUS
2649          * definition, but that does not fly everywhere for the above
2650          * reasons. */
2651             SETSOCKOPT_OPTION_VALUE_T buf;
2652             int aint;
2653             if (SvPOKp(sv)) {
2654                 STRLEN l;
2655                 buf = (SETSOCKOPT_OPTION_VALUE_T) SvPV_const(sv, l);
2656                 len = l;
2657             }
2658             else {
2659                 aint = (int)SvIV(sv);
2660                 buf = (SETSOCKOPT_OPTION_VALUE_T) &aint;
2661                 len = sizeof(int);
2662             }
2663             if (PerlSock_setsockopt(fd, lvl, optname, buf, len) < 0)
2664                 goto nuts2;
2665             PUSHs(&PL_sv_yes);
2666         }
2667         break;
2668     }
2669     RETURN;
2670
2671 nuts:
2672     if (ckWARN(WARN_CLOSED))
2673         report_evil_fh(gv, io, optype);
2674     SETERRNO(EBADF,SS_IVCHAN);
2675 nuts2:
2676     RETPUSHUNDEF;
2677
2678 #else
2679     DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
2680 #endif
2681 }
2682
2683 PP(pp_getpeername)
2684 {
2685 #ifdef HAS_SOCKET
2686     dSP;
2687     int optype = PL_op->op_type;
2688     SV *sv;
2689     int fd;
2690     GV *gv = (GV*)POPs;
2691     register IO *io = GvIOn(gv);
2692     Sock_size_t len;
2693
2694     if (!io || !IoIFP(io))
2695         goto nuts;
2696
2697     sv = sv_2mortal(NEWSV(22, 257));
2698     (void)SvPOK_only(sv);
2699     len = 256;
2700     SvCUR_set(sv, len);
2701     *SvEND(sv) ='\0';
2702     fd = PerlIO_fileno(IoIFP(io));
2703     switch (optype) {
2704     case OP_GETSOCKNAME:
2705         if (PerlSock_getsockname(fd, (struct sockaddr *)SvPVX(sv), &len) < 0)
2706             goto nuts2;
2707         break;
2708     case OP_GETPEERNAME:
2709         if (PerlSock_getpeername(fd, (struct sockaddr *)SvPVX(sv), &len) < 0)
2710             goto nuts2;
2711 #if defined(VMS_DO_SOCKETS) && defined (DECCRTL_SOCKETS)
2712         {
2713             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";
2714             /* If the call succeeded, make sure we don't have a zeroed port/addr */
2715             if (((struct sockaddr *)SvPVX_const(sv))->sa_family == AF_INET &&
2716                 !memcmp(SvPVX_const(sv) + sizeof(u_short), nowhere,
2717                         sizeof(u_short) + sizeof(struct in_addr))) {
2718                 goto nuts2;     
2719             }
2720         }
2721 #endif
2722         break;
2723     }
2724 #ifdef BOGUS_GETNAME_RETURN
2725     /* Interactive Unix, getpeername() and getsockname()
2726       does not return valid namelen */
2727     if (len == BOGUS_GETNAME_RETURN)
2728         len = sizeof(struct sockaddr);
2729 #endif
2730     SvCUR_set(sv, len);
2731     *SvEND(sv) ='\0';
2732     PUSHs(sv);
2733     RETURN;
2734
2735 nuts:
2736     if (ckWARN(WARN_CLOSED))
2737         report_evil_fh(gv, io, optype);
2738     SETERRNO(EBADF,SS_IVCHAN);
2739 nuts2:
2740     RETPUSHUNDEF;
2741
2742 #else
2743     DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
2744 #endif
2745 }
2746
2747 /* Stat calls. */
2748
2749 PP(pp_stat)
2750 {
2751     dSP;
2752     GV *gv;
2753     I32 gimme;
2754     I32 max = 13;
2755
2756     if (PL_op->op_flags & OPf_REF) {
2757         gv = cGVOP_gv;
2758         if (PL_op->op_type == OP_LSTAT) {
2759             if (gv != PL_defgv) {
2760             do_fstat_warning_check:
2761                 if (ckWARN(WARN_IO))
2762                     Perl_warner(aTHX_ packWARN(WARN_IO),
2763                         "lstat() on filehandle %s", GvENAME(gv));
2764             } else if (PL_laststype != OP_LSTAT)
2765                 Perl_croak(aTHX_ "The stat preceding lstat() wasn't an lstat");
2766         }
2767
2768       do_fstat:
2769         if (gv != PL_defgv) {
2770             PL_laststype = OP_STAT;
2771             PL_statgv = gv;
2772             sv_setpvn(PL_statname, "", 0);
2773             PL_laststatval = (GvIO(gv) && IoIFP(GvIOp(gv))
2774                 ? PerlLIO_fstat(PerlIO_fileno(IoIFP(GvIOn(gv))), &PL_statcache) : -1);
2775         }
2776         if (PL_laststatval < 0) {
2777             if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
2778                 report_evil_fh(gv, GvIO(gv), PL_op->op_type);
2779             max = 0;
2780         }
2781     }
2782     else {
2783         SV* sv = POPs;
2784         if (SvTYPE(sv) == SVt_PVGV) {
2785             gv = (GV*)sv;
2786             goto do_fstat;
2787         }
2788         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV) {
2789             gv = (GV*)SvRV(sv);
2790             if (PL_op->op_type == OP_LSTAT)
2791                 goto do_fstat_warning_check;
2792             goto do_fstat;
2793         }
2794         sv_setpv(PL_statname, SvPV_nolen_const(sv));
2795         PL_statgv = Nullgv;
2796         PL_laststype = PL_op->op_type;
2797         if (PL_op->op_type == OP_LSTAT)
2798             PL_laststatval = PerlLIO_lstat(SvPV_nolen_const(PL_statname), &PL_statcache);
2799         else
2800             PL_laststatval = PerlLIO_stat(SvPV_nolen_const(PL_statname), &PL_statcache);
2801         if (PL_laststatval < 0) {
2802             if (ckWARN(WARN_NEWLINE) && strchr(SvPV_nolen_const(PL_statname), '\n'))
2803                 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
2804             max = 0;
2805         }
2806     }
2807
2808     gimme = GIMME_V;
2809     if (gimme != G_ARRAY) {
2810         if (gimme != G_VOID)
2811             XPUSHs(boolSV(max));
2812         RETURN;
2813     }
2814     if (max) {
2815         EXTEND(SP, max);
2816         EXTEND_MORTAL(max);
2817         PUSHs(sv_2mortal(newSViv(PL_statcache.st_dev)));
2818         PUSHs(sv_2mortal(newSViv(PL_statcache.st_ino)));
2819         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_mode)));
2820         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_nlink)));
2821 #if Uid_t_size > IVSIZE
2822         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_uid)));
2823 #else
2824 #   if Uid_t_sign <= 0
2825         PUSHs(sv_2mortal(newSViv(PL_statcache.st_uid)));
2826 #   else
2827         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_uid)));
2828 #   endif
2829 #endif
2830 #if Gid_t_size > IVSIZE
2831         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_gid)));
2832 #else
2833 #   if Gid_t_sign <= 0
2834         PUSHs(sv_2mortal(newSViv(PL_statcache.st_gid)));
2835 #   else
2836         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_gid)));
2837 #   endif
2838 #endif
2839 #ifdef USE_STAT_RDEV
2840         PUSHs(sv_2mortal(newSViv(PL_statcache.st_rdev)));
2841 #else
2842         PUSHs(sv_2mortal(newSVpvn("", 0)));
2843 #endif
2844 #if Off_t_size > IVSIZE
2845         PUSHs(sv_2mortal(newSVnv((NV)PL_statcache.st_size)));
2846 #else
2847         PUSHs(sv_2mortal(newSViv(PL_statcache.st_size)));
2848 #endif
2849 #ifdef BIG_TIME
2850         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_atime)));
2851         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_mtime)));
2852         PUSHs(sv_2mortal(newSVnv(PL_statcache.st_ctime)));
2853 #else
2854         PUSHs(sv_2mortal(newSViv(PL_statcache.st_atime)));
2855         PUSHs(sv_2mortal(newSViv(PL_statcache.st_mtime)));
2856         PUSHs(sv_2mortal(newSViv(PL_statcache.st_ctime)));
2857 #endif
2858 #ifdef USE_STAT_BLOCKS
2859         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_blksize)));
2860         PUSHs(sv_2mortal(newSVuv(PL_statcache.st_blocks)));
2861 #else
2862         PUSHs(sv_2mortal(newSVpvn("", 0)));
2863         PUSHs(sv_2mortal(newSVpvn("", 0)));
2864 #endif
2865     }
2866     RETURN;
2867 }
2868
2869 /* This macro is used by the stacked filetest operators :
2870  * if the previous filetest failed, short-circuit and pass its value.
2871  * Else, discard it from the stack and continue. --rgs
2872  */
2873 #define STACKED_FTEST_CHECK if (PL_op->op_private & OPpFT_STACKED) { \
2874         if (TOPs == &PL_sv_no || TOPs == &PL_sv_undef) { RETURN; } \
2875         else { (void)POPs; PUTBACK; } \
2876     }
2877
2878 PP(pp_ftrread)
2879 {
2880     I32 result;
2881     /* Not const, because things tweak this below. Not bool, because there's
2882        no guarantee that OPp_FT_ACCESS is <= CHAR_MAX  */
2883 #if defined(HAS_ACCESS) || defined (PERL_EFF_ACCESS)
2884     I32 use_access = PL_op->op_private & OPpFT_ACCESS;
2885     /* Giving some sort of initial value silences compilers.  */
2886 #  ifdef R_OK
2887     int access_mode = R_OK;
2888 #  else
2889     int access_mode = 0;
2890 #  endif
2891 #else
2892     /* access_mode is never used, but leaving use_access in makes the
2893        conditional compiling below much clearer.  */
2894     I32 use_access = 0;
2895 #endif
2896     int stat_mode = S_IRUSR;
2897
2898     bool effective = FALSE;
2899     dSP;
2900
2901     STACKED_FTEST_CHECK;
2902
2903     switch (PL_op->op_type) {
2904     case OP_FTRREAD:
2905 #if !(defined(HAS_ACCESS) && defined(R_OK))
2906         use_access = 0;
2907 #endif
2908         break;
2909
2910     case OP_FTRWRITE:
2911 #if defined(HAS_ACCESS) && defined(W_OK)
2912         access_mode = W_OK;
2913 #else
2914         use_access = 0;
2915 #endif
2916         stat_mode = S_IWUSR;
2917         break;
2918
2919     case OP_FTREXEC:
2920 #if defined(HAS_ACCESS) && defined(X_OK)
2921         access_mode = X_OK;
2922 #else
2923         use_access = 0;
2924 #endif
2925         stat_mode = S_IXUSR;
2926         break;
2927
2928     case OP_FTEWRITE:
2929 #ifdef PERL_EFF_ACCESS
2930         access_mode = W_OK;
2931 #endif
2932         stat_mode = S_IWUSR;
2933         /* Fall through  */
2934
2935     case OP_FTEREAD:
2936 #ifndef PERL_EFF_ACCESS
2937         use_access = 0;
2938 #endif
2939         effective = TRUE;
2940         break;
2941
2942
2943     case OP_FTEEXEC:
2944 #ifdef PERL_EFF_ACCESS
2945         access_mode = W_OK;
2946 #else
2947         use_access = 0;
2948 #endif
2949         stat_mode = S_IXUSR;
2950         effective = TRUE;
2951         break;
2952     }
2953
2954     if (use_access) {
2955 #if defined(HAS_ACCESS) || defined (PERL_EFF_ACCESS)
2956         const char *const name = POPpx;
2957         if (effective) {
2958 #  ifdef PERL_EFF_ACCESS
2959             result = PERL_EFF_ACCESS(name, access_mode);
2960 #  else
2961             DIE(aTHX_ "panic: attempt to call PERL_EFF_ACCESS in %s",
2962                 OP_NAME(PL_op));
2963 #  endif
2964         }
2965         else {
2966 #  ifdef HAS_ACCESS
2967             result = access(name, access_mode);
2968 #  else
2969             DIE(aTHX_ "panic: attempt to call access() in %s", OP_NAME(PL_op));
2970 #  endif
2971         }
2972         if (result == 0)
2973             RETPUSHYES;
2974         if (result < 0)
2975             RETPUSHUNDEF;
2976         RETPUSHNO;
2977 #endif
2978     }
2979
2980     result = my_stat();
2981     SPAGAIN;
2982     if (result < 0)
2983         RETPUSHUNDEF;
2984     if (cando(stat_mode, effective, &PL_statcache))
2985         RETPUSHYES;
2986     RETPUSHNO;
2987 }
2988
2989 PP(pp_ftis)
2990 {
2991     I32 result;
2992     const int op_type = PL_op->op_type;
2993     dSP;
2994     STACKED_FTEST_CHECK;
2995     result = my_stat();
2996     SPAGAIN;
2997     if (result < 0)
2998         RETPUSHUNDEF;
2999     if (op_type == OP_FTIS)
3000         RETPUSHYES;
3001     {
3002         /* You can't dTARGET inside OP_FTIS, because you'll get
3003            "panic: pad_sv po" - the op is not flagged to have a target.  */
3004         dTARGET;
3005         switch (op_type) {
3006         case OP_FTSIZE:
3007 #if Off_t_size > IVSIZE
3008             PUSHn(PL_statcache.st_size);
3009 #else
3010             PUSHi(PL_statcache.st_size);
3011 #endif
3012             break;
3013         case OP_FTMTIME:
3014             PUSHn( (((NV)PL_basetime - PL_statcache.st_mtime)) / 86400.0 );
3015             break;
3016         case OP_FTATIME:
3017             PUSHn( (((NV)PL_basetime - PL_statcache.st_atime)) / 86400.0 );
3018             break;
3019         case OP_FTCTIME:
3020             PUSHn( (((NV)PL_basetime - PL_statcache.st_ctime)) / 86400.0 );
3021             break;
3022         }
3023     }
3024     RETURN;
3025 }
3026
3027 PP(pp_ftrowned)
3028 {
3029     I32 result;
3030     dSP;
3031
3032     /* I believe that all these three are likely to be defined on most every
3033        system these days.  */
3034 #ifndef S_ISUID
3035     if(PL_op->op_type == OP_FTSUID)
3036         RETPUSHNO;
3037 #endif
3038 #ifndef S_ISGID
3039     if(PL_op->op_type == OP_FTSGID)
3040         RETPUSHNO;
3041 #endif
3042 #ifndef S_ISVTX
3043     if(PL_op->op_type == OP_FTSVTX)
3044         RETPUSHNO;
3045 #endif
3046
3047     STACKED_FTEST_CHECK;
3048     result = my_stat();
3049     SPAGAIN;
3050     if (result < 0)
3051         RETPUSHUNDEF;
3052     switch (PL_op->op_type) {
3053     case OP_FTROWNED:
3054         if (PL_statcache.st_uid == PL_uid)
3055             RETPUSHYES;
3056         break;
3057     case OP_FTEOWNED:
3058         if (PL_statcache.st_uid == PL_euid)
3059             RETPUSHYES;
3060         break;
3061     case OP_FTZERO:
3062         if (PL_statcache.st_size == 0)
3063             RETPUSHYES;
3064         break;
3065     case OP_FTSOCK:
3066         if (S_ISSOCK(PL_statcache.st_mode))
3067             RETPUSHYES;
3068         break;
3069     case OP_FTCHR:
3070         if (S_ISCHR(PL_statcache.st_mode))
3071             RETPUSHYES;
3072         break;
3073     case OP_FTBLK:
3074         if (S_ISBLK(PL_statcache.st_mode))
3075             RETPUSHYES;
3076         break;
3077     case OP_FTFILE:
3078         if (S_ISREG(PL_statcache.st_mode))
3079             RETPUSHYES;
3080         break;
3081     case OP_FTDIR:
3082         if (S_ISDIR(PL_statcache.st_mode))
3083             RETPUSHYES;
3084         break;
3085     case OP_FTPIPE:
3086         if (S_ISFIFO(PL_statcache.st_mode))
3087             RETPUSHYES;
3088         break;
3089 #ifdef S_ISUID
3090     case OP_FTSUID:
3091         if (PL_statcache.st_mode & S_ISUID)
3092             RETPUSHYES;
3093         break;
3094 #endif
3095 #ifdef S_ISGID
3096     case OP_FTSGID:
3097         if (PL_statcache.st_mode & S_ISGID)
3098             RETPUSHYES;
3099         break;
3100 #endif
3101 #ifdef S_ISVTX
3102     case OP_FTSVTX:
3103         if (PL_statcache.st_mode & S_ISVTX)
3104             RETPUSHYES;
3105         break;
3106 #endif
3107     }
3108     RETPUSHNO;
3109 }
3110
3111 PP(pp_ftlink)
3112 {
3113     I32 result = my_lstat();
3114     dSP;
3115     if (result < 0)
3116         RETPUSHUNDEF;
3117     if (S_ISLNK(PL_statcache.st_mode))
3118         RETPUSHYES;
3119     RETPUSHNO;
3120 }
3121
3122 PP(pp_fttty)
3123 {
3124     dSP;
3125     int fd;
3126     GV *gv;
3127     SV *tmpsv = Nullsv;
3128
3129     STACKED_FTEST_CHECK;
3130
3131     if (PL_op->op_flags & OPf_REF)
3132         gv = cGVOP_gv;
3133     else if (isGV(TOPs))
3134         gv = (GV*)POPs;
3135     else if (SvROK(TOPs) && isGV(SvRV(TOPs)))
3136         gv = (GV*)SvRV(POPs);
3137     else
3138         gv = gv_fetchsv(tmpsv = POPs, FALSE, SVt_PVIO);
3139
3140     if (GvIO(gv) && IoIFP(GvIOp(gv)))
3141         fd = PerlIO_fileno(IoIFP(GvIOp(gv)));
3142     else if (tmpsv && SvOK(tmpsv)) {
3143         const char *tmps = SvPV_nolen_const(tmpsv);
3144         if (isDIGIT(*tmps))
3145             fd = atoi(tmps);
3146         else 
3147             RETPUSHUNDEF;
3148     }
3149     else
3150         RETPUSHUNDEF;
3151     if (PerlLIO_isatty(fd))
3152         RETPUSHYES;
3153     RETPUSHNO;
3154 }
3155
3156 #if defined(atarist) /* this will work with atariST. Configure will
3157                         make guesses for other systems. */
3158 # define FILE_base(f) ((f)->_base)
3159 # define FILE_ptr(f) ((f)->_ptr)
3160 # define FILE_cnt(f) ((f)->_cnt)
3161 # define FILE_bufsiz(f) ((f)->_cnt + ((f)->_ptr - (f)->_base))
3162 #endif
3163
3164 PP(pp_fttext)
3165 {
3166     dSP;
3167     I32 i;
3168     I32 len;
3169     I32 odd = 0;
3170     STDCHAR tbuf[512];
3171     register STDCHAR *s;
3172     register IO *io;
3173     register SV *sv;
3174     GV *gv;
3175     PerlIO *fp;
3176
3177     STACKED_FTEST_CHECK;
3178
3179     if (PL_op->op_flags & OPf_REF)
3180         gv = cGVOP_gv;
3181     else if (isGV(TOPs))
3182         gv = (GV*)POPs;
3183     else if (SvROK(TOPs) && isGV(SvRV(TOPs)))
3184         gv = (GV*)SvRV(POPs);
3185     else
3186         gv = Nullgv;
3187
3188     if (gv) {
3189         EXTEND(SP, 1);
3190         if (gv == PL_defgv) {
3191             if (PL_statgv)
3192                 io = GvIO(PL_statgv);
3193             else {
3194                 sv = PL_statname;
3195                 goto really_filename;
3196             }
3197         }
3198         else {
3199             PL_statgv = gv;
3200             PL_laststatval = -1;
3201             sv_setpvn(PL_statname, "", 0);
3202             io = GvIO(PL_statgv);
3203         }
3204         if (io && IoIFP(io)) {
3205             if (! PerlIO_has_base(IoIFP(io)))
3206                 DIE(aTHX_ "-T and -B not implemented on filehandles");
3207             PL_laststatval = PerlLIO_fstat(PerlIO_fileno(IoIFP(io)), &PL_statcache);
3208             if (PL_laststatval < 0)
3209                 RETPUSHUNDEF;
3210             if (S_ISDIR(PL_statcache.st_mode)) { /* handle NFS glitch */
3211                 if (PL_op->op_type == OP_FTTEXT)
3212                     RETPUSHNO;
3213                 else
3214                     RETPUSHYES;
3215             }
3216             if (PerlIO_get_cnt(IoIFP(io)) <= 0) {
3217                 i = PerlIO_getc(IoIFP(io));
3218                 if (i != EOF)
3219                     (void)PerlIO_ungetc(IoIFP(io),i);
3220             }
3221             if (PerlIO_get_cnt(IoIFP(io)) <= 0) /* null file is anything */
3222                 RETPUSHYES;
3223             len = PerlIO_get_bufsiz(IoIFP(io));
3224             s = (STDCHAR *) PerlIO_get_base(IoIFP(io));
3225             /* sfio can have large buffers - limit to 512 */
3226             if (len > 512)
3227                 len = 512;
3228         }
3229         else {
3230             if (ckWARN2(WARN_UNOPENED,WARN_CLOSED)) {
3231                 gv = cGVOP_gv;
3232                 report_evil_fh(gv, GvIO(gv), PL_op->op_type);
3233             }
3234             SETERRNO(EBADF,RMS_IFI);
3235             RETPUSHUNDEF;
3236         }
3237     }
3238     else {
3239         sv = POPs;
3240       really_filename:
3241         PL_statgv = Nullgv;
3242         PL_laststype = OP_STAT;
3243         sv_setpv(PL_statname, SvPV_nolen_const(sv));
3244         if (!(fp = PerlIO_open(SvPVX_const(PL_statname), "r"))) {
3245             if (ckWARN(WARN_NEWLINE) && strchr(SvPV_nolen_const(PL_statname),
3246                                                '\n'))
3247                 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
3248             RETPUSHUNDEF;
3249         }
3250         PL_laststatval = PerlLIO_fstat(PerlIO_fileno(fp), &PL_statcache);
3251         if (PL_laststatval < 0) {
3252             (void)PerlIO_close(fp);
3253             RETPUSHUNDEF;
3254         }
3255         PerlIO_binmode(aTHX_ fp, '<', O_BINARY, Nullch);
3256         len = PerlIO_read(fp, tbuf, sizeof(tbuf));
3257         (void)PerlIO_close(fp);
3258         if (len <= 0) {
3259             if (S_ISDIR(PL_statcache.st_mode) && PL_op->op_type == OP_FTTEXT)
3260                 RETPUSHNO;              /* special case NFS directories */
3261             RETPUSHYES;         /* null file is anything */
3262         }
3263         s = tbuf;
3264     }
3265
3266     /* now scan s to look for textiness */
3267     /*   XXX ASCII dependent code */
3268
3269 #if defined(DOSISH) || defined(USEMYBINMODE)
3270     /* ignore trailing ^Z on short files */
3271     if (len && len < sizeof(tbuf) && tbuf[len-1] == 26)
3272         --len;
3273 #endif
3274
3275     for (i = 0; i < len; i++, s++) {
3276         if (!*s) {                      /* null never allowed in text */
3277             odd += len;
3278             break;
3279         }
3280 #ifdef EBCDIC
3281         else if (!(isPRINT(*s) || isSPACE(*s)))
3282             odd++;
3283 #else
3284         else if (*s & 128) {
3285 #ifdef USE_LOCALE
3286             if (IN_LOCALE_RUNTIME && isALPHA_LC(*s))
3287                 continue;
3288 #endif
3289             /* utf8 characters don't count as odd */
3290             if (UTF8_IS_START(*s)) {
3291                 int ulen = UTF8SKIP(s);
3292                 if (ulen < len - i) {
3293                     int j;
3294                     for (j = 1; j < ulen; j++) {
3295                         if (!UTF8_IS_CONTINUATION(s[j]))
3296                             goto not_utf8;
3297                     }
3298                     --ulen;     /* loop does extra increment */
3299                     s += ulen;
3300                     i += ulen;
3301                     continue;
3302                 }
3303             }
3304           not_utf8:
3305             odd++;
3306         }
3307         else if (*s < 32 &&
3308           *s != '\n' && *s != '\r' && *s != '\b' &&
3309           *s != '\t' && *s != '\f' && *s != 27)
3310             odd++;
3311 #endif
3312     }
3313
3314     if ((odd * 3 > len) == (PL_op->op_type == OP_FTTEXT)) /* allow 1/3 odd */
3315         RETPUSHNO;
3316     else
3317         RETPUSHYES;
3318 }
3319
3320 /* File calls. */
3321
3322 PP(pp_chdir)
3323 {
3324     dSP; dTARGET;
3325     const char *tmps = 0;
3326     GV *gv = NULL;
3327
3328     if( MAXARG == 1 ) {
3329         SV * const sv = POPs;
3330         if (SvTYPE(sv) == SVt_PVGV) {
3331             gv = (GV*)sv;
3332         }
3333         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV) {
3334             gv = (GV*)SvRV(sv);
3335         }
3336         else {
3337             tmps = SvPVx_nolen_const(sv);
3338         }
3339     }
3340
3341     if( !gv && (!tmps || !*tmps) ) {
3342         HV * const table = GvHVn(PL_envgv);
3343         SV **svp;
3344
3345         if (    (svp = hv_fetch(table, "HOME", 4, FALSE))
3346              || (svp = hv_fetch(table, "LOGDIR", 6, FALSE))
3347 #ifdef VMS
3348              || (svp = hv_fetch(table, "SYS$LOGIN", 9, FALSE))
3349 #endif
3350            )
3351         {
3352             if( MAXARG == 1 )
3353                 deprecate("chdir('') or chdir(undef) as chdir()");
3354             tmps = SvPV_nolen_const(*svp);
3355         }
3356         else {
3357             PUSHi(0);
3358             TAINT_PROPER("chdir");
3359             RETURN;
3360         }
3361     }
3362
3363     TAINT_PROPER("chdir");
3364     if (gv) {
3365 #ifdef HAS_FCHDIR
3366         IO* const io = GvIO(gv);
3367         if (io) {
3368             if (IoIFP(io)) {
3369                 PUSHi(fchdir(PerlIO_fileno(IoIFP(io))) >= 0);
3370             }
3371             else if (IoDIRP(io)) {
3372 #ifdef HAS_DIRFD
3373                 PUSHi(fchdir(dirfd(IoDIRP(io))) >= 0);
3374 #else
3375                 DIE(aTHX_ PL_no_func, "dirfd");
3376 #endif
3377             }
3378             else {
3379                 PUSHi(0);
3380             }
3381         }
3382         else {
3383             PUSHi(0);
3384         }
3385 #else
3386         DIE(aTHX_ PL_no_func, "fchdir");
3387 #endif
3388     }
3389     else 
3390         PUSHi( PerlDir_chdir(tmps) >= 0 );
3391 #ifdef VMS
3392     /* Clear the DEFAULT element of ENV so we'll get the new value
3393      * in the future. */
3394     hv_delete(GvHVn(PL_envgv),"DEFAULT",7,G_DISCARD);
3395 #endif
3396     RETURN;
3397 }
3398
3399 PP(pp_chown)
3400 {
3401     dSP; dMARK; dTARGET;
3402     const I32 value = (I32)apply(PL_op->op_type, MARK, SP);
3403
3404     SP = MARK;
3405     PUSHi(value);
3406     RETURN;
3407 }
3408
3409 PP(pp_chroot)
3410 {
3411 #ifdef HAS_CHROOT
3412     dSP; dTARGET;
3413     char *tmps = POPpx;
3414     TAINT_PROPER("chroot");
3415     PUSHi( chroot(tmps) >= 0 );
3416     RETURN;
3417 #else
3418     DIE(aTHX_ PL_no_func, "chroot");
3419 #endif
3420 }
3421
3422 PP(pp_rename)
3423 {
3424     dSP; dTARGET;
3425     int anum;
3426     const char *tmps2 = POPpconstx;
3427     const char *tmps = SvPV_nolen_const(TOPs);
3428     TAINT_PROPER("rename");
3429 #ifdef HAS_RENAME
3430     anum = PerlLIO_rename(tmps, tmps2);
3431 #else
3432     if (!(anum = PerlLIO_stat(tmps, &PL_statbuf))) {
3433         if (same_dirent(tmps2, tmps))   /* can always rename to same name */
3434             anum = 1;
3435         else {
3436             if (PL_euid || PerlLIO_stat(tmps2, &PL_statbuf) < 0 || !S_ISDIR(PL_statbuf.st_mode))
3437                 (void)UNLINK(tmps2);
3438             if (!(anum = link(tmps, tmps2)))
3439                 anum = UNLINK(tmps);
3440         }
3441     }
3442 #endif
3443     SETi( anum >= 0 );
3444     RETURN;
3445 }
3446
3447 #if defined(HAS_LINK) || defined(HAS_SYMLINK)
3448 PP(pp_link)
3449 {
3450     dSP; dTARGET;
3451     const int op_type = PL_op->op_type;
3452     int result;
3453
3454 #  ifndef HAS_LINK
3455     if (op_type == OP_LINK)
3456         DIE(aTHX_ PL_no_func, "link");
3457 #  endif
3458 #  ifndef HAS_SYMLINK
3459     if (op_type == OP_SYMLINK)
3460         DIE(aTHX_ PL_no_func, "symlink");
3461 #  endif
3462
3463     {
3464         const char *tmps2 = POPpconstx;
3465         const char *tmps = SvPV_nolen_const(TOPs);
3466         TAINT_PROPER(PL_op_desc[op_type]);
3467         result =
3468 #  if defined(HAS_LINK)
3469 #    if defined(HAS_SYMLINK)
3470             /* Both present - need to choose which.  */
3471             (op_type == OP_LINK) ?
3472             PerlLIO_link(tmps, tmps2) : symlink(tmps, tmps2);
3473 #    else
3474     /* Only have link, so calls to pp_symlink will have DIE()d above.  */
3475         PerlLIO_link(tmps, tmps2);
3476 #    endif
3477 #  else
3478 #    if defined(HAS_SYMLINK)
3479     /* Only have symlink, so calls to pp_link will have DIE()d above.  */
3480         symlink(tmps, tmps2);
3481 #    endif
3482 #  endif
3483     }
3484
3485     SETi( result >= 0 );
3486     RETURN;
3487 }
3488 #else
3489 PP(pp_link)
3490 {
3491     /* Have neither.  */
3492     DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
3493 }
3494 #endif
3495
3496 PP(pp_readlink)
3497 {
3498     dSP;
3499 #ifdef HAS_SYMLINK
3500     dTARGET;
3501     const char *tmps;
3502     char buf[MAXPATHLEN];
3503     int len;
3504
3505 #ifndef INCOMPLETE_TAINTS
3506     TAINT;
3507 #endif
3508     tmps = POPpconstx;
3509     len = readlink(tmps, buf, sizeof(buf) - 1);
3510     EXTEND(SP, 1);
3511     if (len < 0)
3512         RETPUSHUNDEF;
3513     PUSHp(buf, len);
3514     RETURN;
3515 #else
3516     EXTEND(SP, 1);
3517     RETSETUNDEF;                /* just pretend it's a normal file */
3518 #endif
3519 }
3520
3521 #if !defined(HAS_MKDIR) || !defined(HAS_RMDIR)
3522 STATIC int
3523 S_dooneliner(pTHX_ const char *cmd, const char *filename)
3524 {
3525     char * const save_filename = filename;
3526     char *cmdline;
3527     char *s;
3528     PerlIO *myfp;
3529     int anum = 1;
3530
3531     Newx(cmdline, strlen(cmd) + (strlen(filename) * 2) + 10, char);
3532     strcpy(cmdline, cmd);
3533     strcat(cmdline, " ");
3534     for (s = cmdline + strlen(cmdline); *filename; ) {
3535         *s++ = '\\';
3536         *s++ = *filename++;
3537     }
3538     strcpy(s, " 2>&1");
3539     myfp = PerlProc_popen(cmdline, "r");
3540     Safefree(cmdline);
3541
3542     if (myfp) {
3543         SV *tmpsv = sv_newmortal();
3544         /* Need to save/restore 'PL_rs' ?? */
3545         s = sv_gets(tmpsv, myfp, 0);
3546         (void)PerlProc_pclose(myfp);
3547         if (s != Nullch) {
3548             int e;
3549             for (e = 1;
3550 #ifdef HAS_SYS_ERRLIST
3551                  e <= sys_nerr
3552 #endif
3553                  ; e++)
3554             {
3555                 /* you don't see this */
3556                 char *errmsg =
3557 #ifdef HAS_SYS_ERRLIST
3558                     sys_errlist[e]
3559 #else
3560                     strerror(e)
3561 #endif
3562                     ;
3563                 if (!errmsg)
3564                     break;
3565                 if (instr(s, errmsg)) {
3566                     SETERRNO(e,0);
3567                     return 0;
3568                 }
3569             }
3570             SETERRNO(0,0);
3571 #ifndef EACCES
3572 #define EACCES EPERM
3573 #endif
3574             if (instr(s, "cannot make"))
3575                 SETERRNO(EEXIST,RMS_FEX);
3576             else if (instr(s, "existing file"))
3577                 SETERRNO(EEXIST,RMS_FEX);
3578             else if (instr(s, "ile exists"))
3579                 SETERRNO(EEXIST,RMS_FEX);
3580             else if (instr(s, "non-exist"))
3581                 SETERRNO(ENOENT,RMS_FNF);
3582             else if (instr(s, "does not exist"))
3583                 SETERRNO(ENOENT,RMS_FNF);
3584             else if (instr(s, "not empty"))
3585                 SETERRNO(EBUSY,SS_DEVOFFLINE);
3586             else if (instr(s, "cannot access"))
3587                 SETERRNO(EACCES,RMS_PRV);
3588             else
3589                 SETERRNO(EPERM,RMS_PRV);
3590             return 0;
3591         }
3592         else {  /* some mkdirs return no failure indication */
3593             anum = (PerlLIO_stat(save_filename, &PL_statbuf) >= 0);
3594             if (PL_op->op_type == OP_RMDIR)
3595                 anum = !anum;
3596             if (anum)
3597                 SETERRNO(0,0);
3598             else
3599                 SETERRNO(EACCES,RMS_PRV);       /* a guess */
3600         }
3601         return anum;
3602     }
3603     else
3604         return 0;
3605 }
3606 #endif
3607
3608 /* This macro removes trailing slashes from a directory name.
3609  * Different operating and file systems take differently to
3610  * trailing slashes.  According to POSIX 1003.1 1996 Edition
3611  * any number of trailing slashes should be allowed.
3612  * Thusly we snip them away so that even non-conforming
3613  * systems are happy.
3614  * We should probably do this "filtering" for all
3615  * the functions that expect (potentially) directory names:
3616  * -d, chdir(), chmod(), chown(), chroot(), fcntl()?,
3617  * (mkdir()), opendir(), rename(), rmdir(), stat(). --jhi */
3618
3619 #define TRIMSLASHES(tmps,len,copy) (tmps) = SvPV_const(TOPs, (len)); \
3620     if ((len) > 1 && (tmps)[(len)-1] == '/') { \
3621         do { \
3622             (len)--; \
3623         } while ((len) > 1 && (tmps)[(len)-1] == '/'); \
3624         (tmps) = savepvn((tmps), (len)); \
3625         (copy) = TRUE; \
3626     }
3627
3628 PP(pp_mkdir)
3629 {
3630     dSP; dTARGET;
3631     int mode;
3632 #ifndef HAS_MKDIR
3633     int oldumask;
3634 #endif
3635     STRLEN len;
3636     const char *tmps;
3637     bool copy = FALSE;
3638
3639     if (MAXARG > 1)
3640         mode = POPi;
3641     else
3642         mode = 0777;
3643
3644     TRIMSLASHES(tmps,len,copy);
3645
3646     TAINT_PROPER("mkdir");
3647 #ifdef HAS_MKDIR
3648     SETi( PerlDir_mkdir(tmps, mode) >= 0 );
3649 #else
3650     SETi( dooneliner("mkdir", tmps) );
3651     oldumask = PerlLIO_umask(0);
3652     PerlLIO_umask(oldumask);
3653     PerlLIO_chmod(tmps, (mode & ~oldumask) & 0777);
3654 #endif
3655     if (copy)
3656         Safefree(tmps);
3657     RETURN;
3658 }
3659
3660 PP(pp_rmdir)
3661 {
3662     dSP; dTARGET;
3663     STRLEN len;
3664     const char *tmps;
3665     bool copy = FALSE;
3666
3667     TRIMSLASHES(tmps,len,copy);
3668     TAINT_PROPER("rmdir");
3669 #ifdef HAS_RMDIR
3670     SETi( PerlDir_rmdir(tmps) >= 0 );
3671 #else
3672     SETi( dooneliner("rmdir", tmps) );
3673 #endif
3674     if (copy)
3675         Safefree(tmps);
3676     RETURN;
3677 }
3678
3679 /* Directory calls. */
3680
3681 PP(pp_open_dir)
3682 {
3683 #if defined(Direntry_t) && defined(HAS_READDIR)
3684     dSP;
3685     const char *dirname = POPpconstx;
3686     GV *gv = (GV*)POPs;
3687     register IO *io = GvIOn(gv);
3688
3689     if (!io)
3690         goto nope;
3691
3692     if (IoDIRP(io))
3693         PerlDir_close(IoDIRP(io));
3694     if (!(IoDIRP(io) = PerlDir_open(dirname)))
3695         goto nope;
3696
3697     RETPUSHYES;
3698 nope:
3699     if (!errno)
3700         SETERRNO(EBADF,RMS_DIR);
3701     RETPUSHUNDEF;
3702 #else
3703     DIE(aTHX_ PL_no_dir_func, "opendir");
3704 #endif
3705 }
3706
3707 PP(pp_readdir)
3708 {
3709 #if !defined(Direntry_t) || !defined(HAS_READDIR)
3710     DIE(aTHX_ PL_no_dir_func, "readdir");
3711 #else
3712 #if !defined(I_DIRENT) && !defined(VMS)
3713     Direntry_t *readdir (DIR *);
3714 #endif
3715     dSP;
3716
3717     SV *sv;
3718     const I32 gimme = GIMME;
3719     GV *gv = (GV *)POPs;
3720     register Direntry_t *dp;
3721     register IO *io = GvIOn(gv);
3722
3723     if (!io || !IoDIRP(io))
3724         goto nope;
3725
3726     do {
3727         dp = (Direntry_t *)PerlDir_read(IoDIRP(io));
3728         if (!dp)
3729             break;
3730 #ifdef DIRNAMLEN
3731         sv = newSVpvn(dp->d_name, dp->d_namlen);
3732 #else
3733         sv = newSVpv(dp->d_name, 0);
3734 #endif
3735 #ifndef INCOMPLETE_TAINTS
3736         if (!(IoFLAGS(io) & IOf_UNTAINT))
3737             SvTAINTED_on(sv);
3738 #endif
3739         XPUSHs(sv_2mortal(sv));
3740     }
3741     while (gimme == G_ARRAY);
3742
3743     if (!dp && gimme != G_ARRAY)
3744         goto nope;
3745
3746     RETURN;
3747
3748 nope:
3749     if (!errno)
3750         SETERRNO(EBADF,RMS_ISI);
3751     if (GIMME == G_ARRAY)
3752         RETURN;
3753     else
3754         RETPUSHUNDEF;
3755 #endif
3756 }
3757
3758 PP(pp_telldir)
3759 {
3760 #if defined(HAS_TELLDIR) || defined(telldir)
3761     dVAR; dSP; dTARGET;
3762  /* XXX does _anyone_ need this? --AD 2/20/1998 */
3763  /* XXX netbsd still seemed to.
3764     XXX HAS_TELLDIR_PROTO is new style, NEED_TELLDIR_PROTO is old style.
3765     --JHI 1999-Feb-02 */
3766 # if !defined(HAS_TELLDIR_PROTO) || defined(NEED_TELLDIR_PROTO)
3767     long telldir (DIR *);
3768 # endif
3769     GV *gv = (GV*)POPs;
3770     register IO *io = GvIOn(gv);
3771
3772     if (!io || !IoDIRP(io))
3773         goto nope;
3774
3775     PUSHi( PerlDir_tell(IoDIRP(io)) );
3776     RETURN;
3777 nope:
3778     if (!errno)
3779         SETERRNO(EBADF,RMS_ISI);
3780     RETPUSHUNDEF;
3781 #else
3782     DIE(aTHX_ PL_no_dir_func, "telldir");
3783 #endif
3784 }
3785
3786 PP(pp_seekdir)
3787 {
3788 #if defined(HAS_SEEKDIR) || defined(seekdir)
3789     dSP;
3790     long along = POPl;
3791     GV *gv = (GV*)POPs;
3792     register IO *io = GvIOn(gv);
3793
3794     if (!io || !IoDIRP(io))
3795         goto nope;
3796
3797     (void)PerlDir_seek(IoDIRP(io), along);
3798
3799     RETPUSHYES;
3800 nope:
3801     if (!errno)
3802         SETERRNO(EBADF,RMS_ISI);
3803     RETPUSHUNDEF;
3804 #else
3805     DIE(aTHX_ PL_no_dir_func, "seekdir");
3806 #endif
3807 }
3808
3809 PP(pp_rewinddir)
3810 {
3811 #if defined(HAS_REWINDDIR) || defined(rewinddir)
3812     dSP;
3813     GV *gv = (GV*)POPs;
3814     register IO *io = GvIOn(gv);
3815
3816     if (!io || !IoDIRP(io))
3817         goto nope;
3818
3819     (void)PerlDir_rewind(IoDIRP(io));
3820     RETPUSHYES;
3821 nope:
3822     if (!errno)
3823         SETERRNO(EBADF,RMS_ISI);
3824     RETPUSHUNDEF;
3825 #else
3826     DIE(aTHX_ PL_no_dir_func, "rewinddir");
3827 #endif
3828 }
3829
3830 PP(pp_closedir)
3831 {
3832 #if defined(Direntry_t) && defined(HAS_READDIR)
3833     dSP;
3834     GV *gv = (GV*)POPs;
3835     register IO *io = GvIOn(gv);
3836
3837     if (!io || !IoDIRP(io))
3838         goto nope;
3839
3840 #ifdef VOID_CLOSEDIR
3841     PerlDir_close(IoDIRP(io));
3842 #else
3843     if (PerlDir_close(IoDIRP(io)) < 0) {
3844         IoDIRP(io) = 0; /* Don't try to close again--coredumps on SysV */
3845         goto nope;
3846     }
3847 #endif
3848     IoDIRP(io) = 0;
3849
3850     RETPUSHYES;
3851 nope:
3852     if (!errno)
3853         SETERRNO(EBADF,RMS_IFI);
3854     RETPUSHUNDEF;
3855 #else
3856     DIE(aTHX_ PL_no_dir_func, "closedir");
3857 #endif
3858 }
3859
3860 /* Process control. */
3861
3862 PP(pp_fork)
3863 {
3864 #ifdef HAS_FORK
3865     dSP; dTARGET;
3866     Pid_t childpid;
3867     GV *tmpgv;
3868
3869     EXTEND(SP, 1);
3870     PERL_FLUSHALL_FOR_CHILD;
3871     childpid = PerlProc_fork();
3872     if (childpid < 0)
3873         RETSETUNDEF;
3874     if (!childpid) {
3875         if ((tmpgv = gv_fetchpv("$", TRUE, SVt_PV))) {
3876             SvREADONLY_off(GvSV(tmpgv));
3877             sv_setiv(GvSV(tmpgv), (IV)PerlProc_getpid());
3878             SvREADONLY_on(GvSV(tmpgv));
3879         }
3880 #ifdef THREADS_HAVE_PIDS
3881         PL_ppid = (IV)getppid();
3882 #endif
3883 #ifdef PERL_USES_PL_PIDSTATUS
3884         hv_clear(PL_pidstatus); /* no kids, so don't wait for 'em */
3885 #endif
3886     }
3887     PUSHi(childpid);
3888     RETURN;
3889 #else
3890 #  if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
3891     dSP; dTARGET;
3892     Pid_t childpid;
3893
3894     EXTEND(SP, 1);
3895     PERL_FLUSHALL_FOR_CHILD;
3896     childpid = PerlProc_fork();
3897     if (childpid == -1)
3898         RETSETUNDEF;
3899     PUSHi(childpid);
3900     RETURN;
3901 #  else
3902     DIE(aTHX_ PL_no_func, "fork");
3903 #  endif
3904 #endif
3905 }
3906
3907 PP(pp_wait)
3908 {
3909 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
3910     dSP; dTARGET;
3911     Pid_t childpid;
3912     int argflags;
3913
3914     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3915         childpid = wait4pid(-1, &argflags, 0);
3916     else {
3917         while ((childpid = wait4pid(-1, &argflags, 0)) == -1 &&
3918                errno == EINTR) {
3919           PERL_ASYNC_CHECK();
3920         }
3921     }
3922 #  if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
3923     /* 0 and -1 are both error returns (the former applies to WNOHANG case) */
3924     STATUS_NATIVE_CHILD_SET((childpid && childpid != -1) ? argflags : -1);
3925 #  else
3926     STATUS_NATIVE_CHILD_SET((childpid > 0) ? argflags : -1);
3927 #  endif
3928     XPUSHi(childpid);
3929     RETURN;
3930 #else
3931     DIE(aTHX_ PL_no_func, "wait");
3932 #endif
3933 }
3934
3935 PP(pp_waitpid)
3936 {
3937 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(MACOS_TRADITIONAL)
3938     dSP; dTARGET;
3939     Pid_t pid;
3940     Pid_t result;
3941     int optype;
3942     int argflags;
3943
3944     optype = POPi;
3945     pid = TOPi;
3946     if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
3947         result = wait4pid(pid, &argflags, optype);
3948     else {
3949         while ((result = wait4pid(pid, &argflags, optype)) == -1 &&
3950                errno == EINTR) {
3951           PERL_ASYNC_CHECK();
3952         }
3953     }
3954 #  if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
3955     /* 0 and -1 are both error returns (the former applies to WNOHANG case) */
3956     STATUS_NATIVE_CHILD_SET((result && result != -1) ? argflags : -1);
3957 #  else
3958     STATUS_NATIVE_CHILD_SET((result > 0) ? argflags : -1);
3959 #  endif
3960     SETi(result);
3961     RETURN;
3962 #else
3963     DIE(aTHX_ PL_no_func, "waitpid");
3964 #endif
3965 }
3966
3967 PP(pp_system)
3968 {
3969     dSP; dMARK; dORIGMARK; dTARGET;
3970     I32 value;
3971     int result;
3972
3973     if (PL_tainting) {
3974         TAINT_ENV();
3975         while (++MARK <= SP) {
3976             (void)SvPV_nolen_const(*MARK);      /* stringify for taint check */
3977             if (PL_tainted)
3978                 break;
3979         }
3980         MARK = ORIGMARK;
3981         TAINT_PROPER("system");
3982     }
3983     PERL_FLUSHALL_FOR_CHILD;
3984 #if (defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(OS2) || defined(PERL_MICRO)
3985     {
3986         Pid_t childpid;
3987         int pp[2];
3988         I32 did_pipes = 0;
3989
3990         if (PerlProc_pipe(pp) >= 0)
3991             did_pipes = 1;
3992         while ((childpid = PerlProc_fork()) == -1) {
3993             if (errno != EAGAIN) {
3994                 value = -1;
3995                 SP = ORIGMARK;
3996                 PUSHi(value);
3997                 if (did_pipes) {
3998                     PerlLIO_close(pp[0]);
3999                     PerlLIO_close(pp[1]);
4000                 }
4001                 RETURN;
4002             }
4003             sleep(5);
4004         }
4005         if (childpid > 0) {
4006             Sigsave_t ihand,qhand; /* place to save signals during system() */
4007             int status;
4008
4009             if (did_pipes)
4010                 PerlLIO_close(pp[1]);
4011 #ifndef PERL_MICRO
4012             rsignal_save(SIGINT,  (Sighandler_t) SIG_IGN, &ihand);
4013             rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qhand);
4014 #endif
4015             do {
4016                 result = wait4pid(childpid, &status, 0);
4017             } while (result == -1 && errno == EINTR);
4018 #ifndef PERL_MICRO
4019             (void)rsignal_restore(SIGINT, &ihand);
4020             (void)rsignal_restore(SIGQUIT, &qhand);
4021 #endif
4022             STATUS_NATIVE_CHILD_SET(result == -1 ? -1 : status);
4023             do_execfree();      /* free any memory child malloced on fork */
4024             SP = ORIGMARK;
4025             if (did_pipes) {
4026                 int errkid;
4027                 int n = 0, n1;
4028
4029                 while (n < sizeof(int)) {
4030                     n1 = PerlLIO_read(pp[0],
4031                                       (void*)(((char*)&errkid)+n),
4032                                       (sizeof(int)) - n);
4033                     if (n1 <= 0)
4034                         break;
4035                     n += n1;
4036                 }
4037                 PerlLIO_close(pp[0]);
4038                 if (n) {                        /* Error */
4039                     if (n != sizeof(int))
4040                         DIE(aTHX_ "panic: kid popen errno read");
4041                     errno = errkid;             /* Propagate errno from kid */
4042                     STATUS_NATIVE_CHILD_SET(-1);
4043                 }
4044             }
4045             PUSHi(STATUS_CURRENT);
4046             RETURN;
4047         }
4048         if (did_pipes) {
4049             PerlLIO_close(pp[0]);
4050 #if defined(HAS_FCNTL) && defined(F_SETFD)
4051             fcntl(pp[1], F_SETFD, FD_CLOEXEC);
4052 #endif
4053         }
4054         if (PL_op->op_flags & OPf_STACKED) {
4055             SV *really = *++MARK;
4056             value = (I32)do_aexec5(really, MARK, SP, pp[1], did_pipes);
4057         }
4058         else if (SP - MARK != 1)
4059             value = (I32)do_aexec5(Nullsv, MARK, SP, pp[1], did_pipes);
4060         else {
4061             value = (I32)do_exec3(SvPVx_nolen(sv_mortalcopy(*SP)), pp[1], did_pipes);
4062         }
4063         PerlProc__exit(-1);
4064     }
4065 #else /* ! FORK or VMS or OS/2 */
4066     PL_statusvalue = 0;
4067     result = 0;
4068     if (PL_op->op_flags & OPf_STACKED) {
4069         SV *really = *++MARK;
4070 #  if defined(WIN32) || defined(OS2) || defined(__SYMBIAN32__)
4071         value = (I32)do_aspawn(really, MARK, SP);
4072 #  else
4073         value = (I32)do_aspawn(really, (void **)MARK, (void **)SP);
4074 #  endif
4075     }
4076     else if (SP - MARK != 1) {
4077 #  if defined(WIN32) || defined(OS2) || defined(__SYMBIAN32__)
4078         value = (I32)do_aspawn(Nullsv, MARK, SP);
4079 #  else
4080         value = (I32)do_aspawn(Nullsv, (void **)MARK, (void **)SP);
4081 #  endif
4082     }
4083     else {
4084         value = (I32)do_spawn(SvPVx_nolen(sv_mortalcopy(*SP)));
4085     }
4086     if (PL_statusvalue == -1)   /* hint that value must be returned as is */
4087         result = 1;
4088     STATUS_NATIVE_CHILD_SET(value);
4089     do_execfree();
4090     SP = ORIGMARK;
4091     PUSHi(result ? value : STATUS_CURRENT);
4092 #endif /* !FORK or VMS */
4093     RETURN;
4094 }
4095
4096 PP(pp_exec)
4097 {
4098     dSP; dMARK; dORIGMARK; dTARGET;
4099     I32 value;
4100
4101     if (PL_tainting) {
4102         TAINT_ENV();
4103         while (++MARK <= SP) {
4104             (void)SvPV_nolen_const(*MARK);      /* stringify for taint check */
4105             if (PL_tainted)
4106                 break;
4107         }
4108         MARK = ORIGMARK;
4109         TAINT_PROPER("exec");
4110     }
4111     PERL_FLUSHALL_FOR_CHILD;
4112     if (PL_op->op_flags & OPf_STACKED) {
4113         SV *really = *++MARK;
4114         value = (I32)do_aexec(really, MARK, SP);
4115     }
4116     else if (SP - MARK != 1)
4117 #ifdef VMS
4118         value = (I32)vms_do_aexec(Nullsv, MARK, SP);
4119 #else
4120 #  ifdef __OPEN_VM
4121         {
4122            (void ) do_aspawn(Nullsv, MARK, SP);
4123            value = 0;
4124         }
4125 #  else
4126         value = (I32)do_aexec(Nullsv, MARK, SP);
4127 #  endif
4128 #endif
4129     else {
4130 #ifdef VMS
4131         value = (I32)vms_do_exec(SvPVx_nolen(sv_mortalcopy(*SP)));
4132 #else
4133 #  ifdef __OPEN_VM
4134         (void) do_spawn(SvPVx_nolen(sv_mortalcopy(*SP)));
4135         value = 0;
4136 #  else
4137         value = (I32)do_exec(SvPVx_nolen(sv_mortalcopy(*SP)));
4138 #  endif
4139 #endif
4140     }
4141
4142     SP = ORIGMARK;
4143     PUSHi(value);
4144     RETURN;
4145 }
4146
4147 PP(pp_getppid)
4148 {
4149 #ifdef HAS_GETPPID
4150     dSP; dTARGET;
4151 #   ifdef THREADS_HAVE_PIDS
4152     if (PL_ppid != 1 && getppid() == 1)
4153         /* maybe the parent process has died. Refresh ppid cache */
4154         PL_ppid = 1;
4155     XPUSHi( PL_ppid );
4156 #   else
4157     XPUSHi( getppid() );
4158 #   endif
4159     RETURN;
4160 #else
4161     DIE(aTHX_ PL_no_func, "getppid");
4162 #endif
4163 }
4164
4165 PP(pp_getpgrp)
4166 {
4167 #ifdef HAS_GETPGRP
4168     dSP; dTARGET;
4169     Pid_t pid;
4170     Pid_t pgrp;
4171
4172     if (MAXARG < 1)
4173         pid = 0;
4174     else
4175         pid = SvIVx(POPs);
4176 #ifdef BSD_GETPGRP
4177     pgrp = (I32)BSD_GETPGRP(pid);
4178 #else
4179     if (pid != 0 && pid != PerlProc_getpid())
4180         DIE(aTHX_ "POSIX getpgrp can't take an argument");
4181     pgrp = getpgrp();
4182 #endif
4183     XPUSHi(pgrp);
4184     RETURN;
4185 #else
4186     DIE(aTHX_ PL_no_func, "getpgrp()");
4187 #endif
4188 }
4189
4190 PP(pp_setpgrp)
4191 {
4192 #ifdef HAS_SETPGRP
4193     dSP; dTARGET;
4194     Pid_t pgrp;
4195     Pid_t pid;
4196     if (MAXARG < 2) {
4197         pgrp = 0;
4198         pid = 0;
4199     }
4200     else {
4201         pgrp = POPi;
4202         pid = TOPi;
4203     }
4204
4205     TAINT_PROPER("setpgrp");
4206 #ifdef BSD_SETPGRP
4207     SETi( BSD_SETPGRP(pid, pgrp) >= 0 );
4208 #else
4209     if ((pgrp != 0 && pgrp != PerlProc_getpid())
4210         || (pid != 0 && pid != PerlProc_getpid()))
4211     {
4212         DIE(aTHX_ "setpgrp can't take arguments");
4213     }
4214     SETi( setpgrp() >= 0 );
4215 #endif /* USE_BSDPGRP */
4216     RETURN;
4217 #else
4218     DIE(aTHX_ PL_no_func, "setpgrp()");
4219 #endif
4220 }
4221
4222 PP(pp_getpriority)
4223 {
4224 #ifdef HAS_GETPRIORITY
4225     dSP; dTARGET;
4226     int who = POPi;
4227     int which = TOPi;
4228     SETi( getpriority(which, who) );
4229     RETURN;
4230 #else
4231     DIE(aTHX_ PL_no_func, "getpriority()");
4232 #endif
4233 }
4234
4235 PP(pp_setpriority)
4236 {
4237 #ifdef HAS_SETPRIORITY
4238     dSP; dTARGET;
4239     int niceval = POPi;
4240     int who = POPi;
4241     int which = TOPi;
4242     TAINT_PROPER("setpriority");
4243     SETi( setpriority(which, who, niceval) >= 0 );
4244     RETURN;
4245 #else
4246     DIE(aTHX_ PL_no_func, "setpriority()");
4247 #endif
4248 }
4249
4250 /* Time calls. */
4251
4252 PP(pp_time)
4253 {
4254     dSP; dTARGET;
4255 #ifdef BIG_TIME
4256     XPUSHn( time(Null(Time_t*)) );
4257 #else
4258     XPUSHi( time(Null(Time_t*)) );
4259 #endif
4260     RETURN;
4261 }
4262
4263 PP(pp_tms)
4264 {
4265 #ifdef HAS_TIMES
4266     dSP;
4267     EXTEND(SP, 4);
4268 #ifndef VMS
4269     (void)PerlProc_times(&PL_timesbuf);
4270 #else
4271     (void)PerlProc_times((tbuffer_t *)&PL_timesbuf);  /* time.h uses different name for */
4272                                                    /* struct tms, though same data   */
4273                                                    /* is returned.                   */
4274 #endif
4275
4276     PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_utime)/(NV)PL_clocktick)));
4277     if (GIMME == G_ARRAY) {
4278         PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_stime)/(NV)PL_clocktick)));
4279         PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_cutime)/(NV)PL_clocktick)));
4280         PUSHs(sv_2mortal(newSVnv(((NV)PL_timesbuf.tms_cstime)/(NV)PL_clocktick)));
4281     }
4282     RETURN;
4283 #else
4284 #   ifdef PERL_MICRO
4285     dSP;
4286     PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4287     EXTEND(SP, 4);
4288     if (GIMME == G_ARRAY) {
4289          PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4290          PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4291          PUSHs(sv_2mortal(newSVnv((NV)0.0)));
4292     }
4293     RETURN;
4294 #   else
4295     DIE(aTHX_ "times not implemented");
4296 #   endif
4297 #endif /* HAS_TIMES */
4298 }
4299
4300 #ifdef LOCALTIME_EDGECASE_BROKEN
4301 static struct tm *S_my_localtime (pTHX_ Time_t *tp)
4302 {
4303     auto time_t     T;
4304     auto struct tm *P;
4305
4306     /* No workarounds in the valid range */
4307     if (!tp || *tp < 0x7fff573f || *tp >= 0x80000000)
4308         return (localtime (tp));
4309
4310     /* This edge case is to workaround the undefined behaviour, where the
4311      * TIMEZONE makes the time go beyond the defined range.
4312      * gmtime (0x7fffffff) => 2038-01-19 03:14:07
4313      * If there is a negative offset in TZ, like MET-1METDST, some broken
4314      * implementations of localtime () (like AIX 5.2) barf with bogus
4315      * return values:
4316      * 0x7fffffff gmtime               2038-01-19 03:14:07
4317      * 0x7fffffff localtime            1901-12-13 21:45:51
4318      * 0x7fffffff mylocaltime          2038-01-19 04:14:07
4319      * 0x3c19137f gmtime               2001-12-13 20:45:51
4320      * 0x3c19137f localtime            2001-12-13 21:45:51
4321      * 0x3c19137f mylocaltime          2001-12-13 21:45:51
4322      * Given that legal timezones are typically between GMT-12 and GMT+12
4323      * we turn back the clock 23 hours before calling the localtime
4324      * function, and add those to the return value. This will never cause
4325      * day wrapping problems, since the edge case is Tue Jan *19*
4326      */
4327     T = *tp - 82800; /* 23 hour. allows up to GMT-23 */
4328     P = localtime (&T);
4329     P->tm_hour += 23;
4330     if (P->tm_hour >= 24) {
4331         P->tm_hour -= 24;
4332         P->tm_mday++;   /* 18  -> 19  */
4333         P->tm_wday++;   /* Mon -> Tue */
4334         P->tm_yday++;   /* 18  -> 19  */
4335     }
4336     return (P);
4337 } /* S_my_localtime */
4338 #endif
4339
4340 PP(pp_gmtime)
4341 {
4342     dSP;
4343     Time_t when;
4344     const struct tm *tmbuf;
4345     static const char * const dayname[] =
4346         {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
4347     static const char * const monname[] =
4348         {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4349          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
4350
4351     if (MAXARG < 1)
4352         (void)time(&when);
4353     else
4354 #ifdef BIG_TIME
4355         when = (Time_t)SvNVx(POPs);
4356 #else
4357         when = (Time_t)SvIVx(POPs);
4358 #endif
4359
4360     if (PL_op->op_type == OP_LOCALTIME)
4361 #ifdef LOCALTIME_EDGECASE_BROKEN
4362         tmbuf = S_my_localtime(aTHX_ &when);
4363 #else
4364         tmbuf = localtime(&when);
4365 #endif
4366     else
4367         tmbuf = gmtime(&when);
4368
4369     if (GIMME != G_ARRAY) {
4370         SV *tsv;
4371         EXTEND(SP, 1);
4372         EXTEND_MORTAL(1);
4373         if (!tmbuf)
4374             RETPUSHUNDEF;
4375         tsv = Perl_newSVpvf(aTHX_ "%s %s %2d %02d:%02d:%02d %d",
4376                             dayname[tmbuf->tm_wday],
4377                             monname[tmbuf->tm_mon],
4378                             tmbuf->tm_mday,
4379                             tmbuf->tm_hour,
4380                             tmbuf->tm_min,
4381                             tmbuf->tm_sec,
4382                             tmbuf->tm_year + 1900);
4383         PUSHs(sv_2mortal(tsv));
4384     }
4385     else if (tmbuf) {
4386         EXTEND(SP, 9);
4387         EXTEND_MORTAL(9);
4388         PUSHs(sv_2mortal(newSViv(tmbuf->tm_sec)));
4389         PUSHs(sv_2mortal(newSViv(tmbuf->tm_min)));
4390         PUSHs(sv_2mortal(newSViv(tmbuf->tm_hour)));
4391         PUSHs(sv_2mortal(newSViv(tmbuf->tm_mday)));
4392         PUSHs(sv_2mortal(newSViv(tmbuf->tm_mon)));
4393         PUSHs(sv_2mortal(newSViv(tmbuf->tm_year)));
4394         PUSHs(sv_2mortal(newSViv(tmbuf->tm_wday)));
4395         PUSHs(sv_2mortal(newSViv(tmbuf->tm_yday)));
4396         PUSHs(sv_2mortal(newSViv(tmbuf->tm_isdst)));
4397     }
4398     RETURN;
4399 }
4400
4401 PP(pp_alarm)
4402 {
4403 #ifdef HAS_ALARM
4404     dSP; dTARGET;
4405     int anum;
4406     anum = POPi;
4407     anum = alarm((unsigned int)anum);
4408     EXTEND(SP, 1);
4409     if (anum < 0)
4410         RETPUSHUNDEF;
4411     PUSHi(anum);
4412     RETURN;
4413 #else
4414     DIE(aTHX_ PL_no_func, "alarm");
4415 #endif
4416 }
4417
4418 PP(pp_sleep)
4419 {
4420     dSP; dTARGET;
4421     I32 duration;
4422     Time_t lasttime;
4423     Time_t when;
4424
4425     (void)time(&lasttime);
4426     if (MAXARG < 1)
4427         PerlProc_pause();
4428     else {
4429         duration = POPi;
4430         PerlProc_sleep((unsigned int)duration);
4431     }
4432     (void)time(&when);
4433     XPUSHi(when - lasttime);
4434     RETURN;
4435 }
4436
4437 /* Shared memory. */
4438 /* Merged with some message passing. */
4439
4440 PP(pp_shmwrite)
4441 {
4442 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4443     dSP; dMARK; dTARGET;
4444     const int op_type = PL_op->op_type;
4445     I32 value;
4446
4447     switch (op_type) {
4448     case OP_MSGSND:
4449         value = (I32)(do_msgsnd(MARK, SP) >= 0);
4450         break;
4451     case OP_MSGRCV:
4452         value = (I32)(do_msgrcv(MARK, SP) >= 0);
4453         break;
4454     default:
4455         value = (I32)(do_shmio(op_type, MARK, SP) >= 0);
4456         break;
4457     }
4458
4459     SP = MARK;
4460     PUSHi(value);
4461     RETURN;
4462 #else
4463     return pp_semget();
4464 #endif
4465 }
4466
4467 /* Semaphores. */
4468
4469 PP(pp_semget)
4470 {
4471 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4472     dSP; dMARK; dTARGET;
4473     int anum = do_ipcget(PL_op->op_type, MARK, SP);
4474     SP = MARK;
4475     if (anum == -1)
4476         RETPUSHUNDEF;
4477     PUSHi(anum);
4478     RETURN;
4479 #else
4480     DIE(aTHX_ "System V IPC is not implemented on this machine");
4481 #endif
4482 }
4483
4484 PP(pp_semctl)
4485 {
4486 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4487     dSP; dMARK; dTARGET;
4488     int anum = do_ipcctl(PL_op->op_type, MARK, SP);
4489     SP = MARK;
4490     if (anum == -1)
4491         RETSETUNDEF;
4492     if (anum != 0) {
4493         PUSHi(anum);
4494     }
4495     else {
4496         PUSHp(zero_but_true, ZBTLEN);
4497     }
4498     RETURN;
4499 #else
4500     return pp_semget();
4501 #endif
4502 }
4503
4504 PP(pp_semop)
4505 {
4506 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4507     dSP; dMARK; dTARGET;
4508     I32 value = (I32)(do_semop(MARK, SP) >= 0);
4509     SP = MARK;
4510     PUSHi(value);
4511     RETURN;
4512 #else
4513     return pp_semget();
4514 #endif
4515 }
4516
4517 /* Get system info. */
4518
4519 PP(pp_ghostent)
4520 {
4521 #if defined(HAS_GETHOSTBYNAME) || defined(HAS_GETHOSTBYADDR) || defined(HAS_GETHOSTENT)
4522     dSP;
4523     I32 which = PL_op->op_type;
4524     register char **elem;
4525     register SV *sv;
4526 #ifndef HAS_GETHOST_PROTOS /* XXX Do we need individual probes? */
4527     struct hostent *gethostbyaddr(Netdb_host_t, Netdb_hlen_t, int);
4528     struct hostent *gethostbyname(Netdb_name_t);
4529     struct hostent *gethostent(void);
4530 #endif
4531     struct hostent *hent;
4532     unsigned long len;
4533
4534     EXTEND(SP, 10);
4535     if (which == OP_GHBYNAME) {
4536 #ifdef HAS_GETHOSTBYNAME
4537         char* name = POPpbytex;
4538         hent = PerlSock_gethostbyname(name);
4539 #else
4540         DIE(aTHX_ PL_no_sock_func, "gethostbyname");
4541 #endif
4542     }
4543     else if (which == OP_GHBYADDR) {
4544 #ifdef HAS_GETHOSTBYADDR
4545         int addrtype = POPi;
4546         SV *addrsv = POPs;
4547         STRLEN addrlen;
4548         Netdb_host_t addr = (Netdb_host_t) SvPVbyte(addrsv, addrlen);
4549
4550         hent = PerlSock_gethostbyaddr(addr, (Netdb_hlen_t) addrlen, addrtype);
4551 #else
4552         DIE(aTHX_ PL_no_sock_func, "gethostbyaddr");
4553 #endif
4554     }
4555     else
4556 #ifdef HAS_GETHOSTENT
4557         hent = PerlSock_gethostent();
4558 #else
4559         DIE(aTHX_ PL_no_sock_func, "gethostent");
4560 #endif
4561
4562 #ifdef HOST_NOT_FOUND
4563         if (!hent) {
4564 #ifdef USE_REENTRANT_API
4565 #   ifdef USE_GETHOSTENT_ERRNO
4566             h_errno = PL_reentrant_buffer->_gethostent_errno;
4567 #   endif
4568 #endif
4569             STATUS_UNIX_SET(h_errno);
4570         }
4571 #endif
4572
4573     if (GIMME != G_ARRAY) {
4574         PUSHs(sv = sv_newmortal());
4575         if (hent) {
4576             if (which == OP_GHBYNAME) {
4577                 if (hent->h_addr)
4578                     sv_setpvn(sv, hent->h_addr, hent->h_length);
4579             }
4580             else
4581                 sv_setpv(sv, (char*)hent->h_name);
4582         }
4583         RETURN;
4584     }
4585
4586     if (hent) {
4587         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4588         sv_setpv(sv, (char*)hent->h_name);
4589         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4590         for (elem = hent->h_aliases; elem && *elem; elem++) {
4591             sv_catpv(sv, *elem);
4592             if (elem[1])
4593                 sv_catpvn(sv, " ", 1);
4594         }
4595         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4596         sv_setiv(sv, (IV)hent->h_addrtype);
4597         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4598         len = hent->h_length;
4599         sv_setiv(sv, (IV)len);
4600 #ifdef h_addr
4601         for (elem = hent->h_addr_list; elem && *elem; elem++) {
4602             XPUSHs(sv = sv_mortalcopy(&PL_sv_no));
4603             sv_setpvn(sv, *elem, len);
4604         }
4605 #else
4606         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4607         if (hent->h_addr)
4608             sv_setpvn(sv, hent->h_addr, len);
4609 #endif /* h_addr */
4610     }
4611     RETURN;
4612 #else
4613     DIE(aTHX_ PL_no_sock_func, "gethostent");
4614 #endif
4615 }
4616
4617 PP(pp_gnetent)
4618 {
4619 #if defined(HAS_GETNETBYNAME) || defined(HAS_GETNETBYADDR) || defined(HAS_GETNETENT)
4620     dSP;
4621     I32 which = PL_op->op_type;
4622     register char **elem;
4623     register SV *sv;
4624 #ifndef HAS_GETNET_PROTOS /* XXX Do we need individual probes? */
4625     struct netent *getnetbyaddr(Netdb_net_t, int);
4626     struct netent *getnetbyname(Netdb_name_t);
4627     struct netent *getnetent(void);
4628 #endif
4629     struct netent *nent;
4630
4631     if (which == OP_GNBYNAME){
4632 #ifdef HAS_GETNETBYNAME
4633         char *name = POPpbytex;
4634         nent = PerlSock_getnetbyname(name);
4635 #else
4636         DIE(aTHX_ PL_no_sock_func, "getnetbyname");
4637 #endif
4638     }
4639     else if (which == OP_GNBYADDR) {
4640 #ifdef HAS_GETNETBYADDR
4641         int addrtype = POPi;
4642         Netdb_net_t addr = (Netdb_net_t) (U32)POPu;
4643         nent = PerlSock_getnetbyaddr(addr, addrtype);
4644 #else
4645         DIE(aTHX_ PL_no_sock_func, "getnetbyaddr");
4646 #endif
4647     }
4648     else
4649 #ifdef HAS_GETNETENT
4650         nent = PerlSock_getnetent();
4651 #else
4652         DIE(aTHX_ PL_no_sock_func, "getnetent");
4653 #endif
4654
4655 #ifdef HOST_NOT_FOUND
4656         if (!nent) {
4657 #ifdef USE_REENTRANT_API
4658 #   ifdef USE_GETNETENT_ERRNO
4659              h_errno = PL_reentrant_buffer->_getnetent_errno;
4660 #   endif
4661 #endif
4662             STATUS_UNIX_SET(h_errno);
4663         }
4664 #endif
4665
4666     EXTEND(SP, 4);
4667     if (GIMME != G_ARRAY) {
4668         PUSHs(sv = sv_newmortal());
4669         if (nent) {
4670             if (which == OP_GNBYNAME)
4671                 sv_setiv(sv, (IV)nent->n_net);
4672             else
4673                 sv_setpv(sv, nent->n_name);
4674         }
4675         RETURN;
4676     }
4677
4678     if (nent) {
4679         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4680         sv_setpv(sv, nent->n_name);
4681         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4682         for (elem = nent->n_aliases; elem && *elem; elem++) {
4683             sv_catpv(sv, *elem);
4684             if (elem[1])
4685                 sv_catpvn(sv, " ", 1);
4686         }
4687         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4688         sv_setiv(sv, (IV)nent->n_addrtype);
4689         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4690         sv_setiv(sv, (IV)nent->n_net);
4691     }
4692
4693     RETURN;
4694 #else
4695     DIE(aTHX_ PL_no_sock_func, "getnetent");
4696 #endif
4697 }
4698
4699 PP(pp_gprotoent)
4700 {
4701 #if defined(HAS_GETPROTOBYNAME) || defined(HAS_GETPROTOBYNUMBER) || defined(HAS_GETPROTOENT)
4702     dSP;
4703     I32 which = PL_op->op_type;
4704     register char **elem;
4705     register SV *sv;
4706 #ifndef HAS_GETPROTO_PROTOS /* XXX Do we need individual probes? */
4707     struct protoent *getprotobyname(Netdb_name_t);
4708     struct protoent *getprotobynumber(int);
4709     struct protoent *getprotoent(void);
4710 #endif
4711     struct protoent *pent;
4712
4713     if (which == OP_GPBYNAME) {
4714 #ifdef HAS_GETPROTOBYNAME
4715         char* name = POPpbytex;
4716         pent = PerlSock_getprotobyname(name);
4717 #else
4718         DIE(aTHX_ PL_no_sock_func, "getprotobyname");
4719 #endif
4720     }
4721     else if (which == OP_GPBYNUMBER) {
4722 #ifdef HAS_GETPROTOBYNUMBER
4723         int number = POPi;
4724         pent = PerlSock_getprotobynumber(number);
4725 #else
4726         DIE(aTHX_ PL_no_sock_func, "getprotobynumber");
4727 #endif
4728     }
4729     else
4730 #ifdef HAS_GETPROTOENT
4731         pent = PerlSock_getprotoent();
4732 #else
4733         DIE(aTHX_ PL_no_sock_func, "getprotoent");
4734 #endif
4735
4736     EXTEND(SP, 3);
4737     if (GIMME != G_ARRAY) {
4738         PUSHs(sv = sv_newmortal());
4739         if (pent) {
4740             if (which == OP_GPBYNAME)
4741                 sv_setiv(sv, (IV)pent->p_proto);
4742             else
4743                 sv_setpv(sv, pent->p_name);
4744         }
4745         RETURN;
4746     }
4747
4748     if (pent) {
4749         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4750         sv_setpv(sv, pent->p_name);
4751         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4752         for (elem = pent->p_aliases; elem && *elem; elem++) {
4753             sv_catpv(sv, *elem);
4754             if (elem[1])
4755                 sv_catpvn(sv, " ", 1);
4756         }
4757         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4758         sv_setiv(sv, (IV)pent->p_proto);
4759     }
4760
4761     RETURN;
4762 #else
4763     DIE(aTHX_ PL_no_sock_func, "getprotoent");
4764 #endif
4765 }
4766
4767 PP(pp_gservent)
4768 {
4769 #if defined(HAS_GETSERVBYNAME) || defined(HAS_GETSERVBYPORT) || defined(HAS_GETSERVENT)
4770     dSP;
4771     I32 which = PL_op->op_type;
4772     register char **elem;
4773     register SV *sv;
4774 #ifndef HAS_GETSERV_PROTOS /* XXX Do we need individual probes? */
4775     struct servent *getservbyname(Netdb_name_t, Netdb_name_t);
4776     struct servent *getservbyport(int, Netdb_name_t);
4777     struct servent *getservent(void);
4778 #endif
4779     struct servent *sent;
4780
4781     if (which == OP_GSBYNAME) {
4782 #ifdef HAS_GETSERVBYNAME
4783         char *proto = POPpbytex;
4784         char *name = POPpbytex;
4785
4786         if (proto && !*proto)
4787             proto = Nullch;
4788
4789         sent = PerlSock_getservbyname(name, proto);
4790 #else
4791         DIE(aTHX_ PL_no_sock_func, "getservbyname");
4792 #endif
4793     }
4794     else if (which == OP_GSBYPORT) {
4795 #ifdef HAS_GETSERVBYPORT
4796         char *proto = POPpbytex;
4797         unsigned short port = (unsigned short)POPu;
4798
4799         if (proto && !*proto)
4800             proto = Nullch;
4801
4802 #ifdef HAS_HTONS
4803         port = PerlSock_htons(port);
4804 #endif
4805         sent = PerlSock_getservbyport(port, proto);
4806 #else
4807         DIE(aTHX_ PL_no_sock_func, "getservbyport");
4808 #endif
4809     }
4810     else
4811 #ifdef HAS_GETSERVENT
4812         sent = PerlSock_getservent();
4813 #else
4814         DIE(aTHX_ PL_no_sock_func, "getservent");
4815 #endif
4816
4817     EXTEND(SP, 4);
4818     if (GIMME != G_ARRAY) {
4819         PUSHs(sv = sv_newmortal());
4820         if (sent) {
4821             if (which == OP_GSBYNAME) {
4822 #ifdef HAS_NTOHS
4823                 sv_setiv(sv, (IV)PerlSock_ntohs(sent->s_port));
4824 #else
4825                 sv_setiv(sv, (IV)(sent->s_port));
4826 #endif
4827             }
4828             else
4829                 sv_setpv(sv, sent->s_name);
4830         }
4831         RETURN;
4832     }
4833
4834     if (sent) {
4835         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4836         sv_setpv(sv, sent->s_name);
4837         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4838         for (elem = sent->s_aliases; elem && *elem; elem++) {
4839             sv_catpv(sv, *elem);
4840             if (elem[1])
4841                 sv_catpvn(sv, " ", 1);
4842         }
4843         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4844 #ifdef HAS_NTOHS
4845         sv_setiv(sv, (IV)PerlSock_ntohs(sent->s_port));
4846 #else
4847         sv_setiv(sv, (IV)(sent->s_port));
4848 #endif
4849         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
4850         sv_setpv(sv, sent->s_proto);
4851     }
4852
4853     RETURN;
4854 #else
4855     DIE(aTHX_ PL_no_sock_func, "getservent");
4856 #endif
4857 }
4858
4859 PP(pp_shostent)
4860 {
4861 #ifdef HAS_SETHOSTENT
4862     dSP;
4863     PerlSock_sethostent(TOPi);
4864     RETSETYES;
4865 #else
4866     DIE(aTHX_ PL_no_sock_func, "sethostent");
4867 #endif
4868 }
4869
4870 PP(pp_snetent)
4871 {
4872 #ifdef HAS_SETNETENT
4873     dSP;
4874     PerlSock_setnetent(TOPi);
4875     RETSETYES;
4876 #else
4877     DIE(aTHX_ PL_no_sock_func, "setnetent");
4878 #endif
4879 }
4880
4881 PP(pp_sprotoent)
4882 {
4883 #ifdef HAS_SETPROTOENT
4884     dSP;
4885     PerlSock_setprotoent(TOPi);
4886     RETSETYES;
4887 #else
4888     DIE(aTHX_ PL_no_sock_func, "setprotoent");
4889 #endif
4890 }
4891
4892 PP(pp_sservent)
4893 {
4894 #ifdef HAS_SETSERVENT
4895     dSP;
4896     PerlSock_setservent(TOPi);
4897     RETSETYES;
4898 #else
4899     DIE(aTHX_ PL_no_sock_func, "setservent");
4900 #endif
4901 }
4902
4903 PP(pp_ehostent)
4904 {
4905 #ifdef HAS_ENDHOSTENT
4906     dSP;
4907     PerlSock_endhostent();
4908     EXTEND(SP,1);
4909     RETPUSHYES;
4910 #else
4911     DIE(aTHX_ PL_no_sock_func, "endhostent");
4912 #endif
4913 }
4914
4915 PP(pp_enetent)
4916 {
4917 #ifdef HAS_ENDNETENT
4918     dSP;
4919     PerlSock_endnetent();
4920     EXTEND(SP,1);
4921     RETPUSHYES;
4922 #else
4923     DIE(aTHX_ PL_no_sock_func, "endnetent");
4924 #endif
4925 }
4926
4927 PP(pp_eprotoent)
4928 {
4929 #ifdef HAS_ENDPROTOENT
4930     dSP;
4931     PerlSock_endprotoent();
4932     EXTEND(SP,1);
4933     RETPUSHYES;
4934 #else
4935     DIE(aTHX_ PL_no_sock_func, "endprotoent");
4936 #endif
4937 }
4938
4939 PP(pp_eservent)
4940 {
4941 #ifdef HAS_ENDSERVENT
4942     dSP;
4943     PerlSock_endservent();
4944     EXTEND(SP,1);
4945     RETPUSHYES;
4946 #else
4947     DIE(aTHX_ PL_no_sock_func, "endservent");
4948 #endif
4949 }
4950
4951 PP(pp_gpwent)
4952 {
4953 #ifdef HAS_PASSWD
4954     dSP;
4955     I32 which = PL_op->op_type;
4956     register SV *sv;
4957     struct passwd *pwent  = NULL;
4958     /*
4959      * We currently support only the SysV getsp* shadow password interface.
4960      * The interface is declared in <shadow.h> and often one needs to link
4961      * with -lsecurity or some such.
4962      * This interface is used at least by Solaris, HP-UX, IRIX, and Linux.
4963      * (and SCO?)
4964      *
4965      * AIX getpwnam() is clever enough to return the encrypted password
4966      * only if the caller (euid?) is root.
4967      *
4968      * There are at least three other shadow password APIs.  Many platforms
4969      * seem to contain more than one interface for accessing the shadow
4970      * password databases, possibly for compatibility reasons.
4971      * The getsp*() is by far he simplest one, the other two interfaces
4972      * are much more complicated, but also very similar to each other.
4973      *
4974      * <sys/types.h>
4975      * <sys/security.h>
4976      * <prot.h>
4977      * struct pr_passwd *getprpw*();
4978      * The password is in
4979      * char getprpw*(...).ufld.fd_encrypt[]
4980      * Mention HAS_GETPRPWNAM here so that Configure probes for it.
4981      *
4982      * <sys/types.h>
4983      * <sys/security.h>
4984      * <prot.h>
4985      * struct es_passwd *getespw*();
4986      * The password is in
4987      * char *(getespw*(...).ufld.fd_encrypt)
4988      * Mention HAS_GETESPWNAM here so that Configure probes for it.
4989      *
4990      * <userpw.h> (AIX)
4991      * struct userpw *getuserpw();
4992      * The password is in
4993      * char *(getuserpw(...)).spw_upw_passwd
4994      * (but the de facto standard getpwnam() should work okay)
4995      *
4996      * Mention I_PROT here so that Configure probes for it.
4997      *
4998      * In HP-UX for getprpw*() the manual page claims that one should include
4999      * <hpsecurity.h> instead of <sys/security.h>, but that is not needed
5000      * if one includes <shadow.h> as that includes <hpsecurity.h>,
5001      * and pp_sys.c already includes <shadow.h> if there is such.
5002      *
5003      * Note that <sys/security.h> is already probed for, but currently
5004      * it is only included in special cases.
5005      *
5006      * In Digital UNIX/Tru64 if using the getespw*() (which seems to be
5007      * be preferred interface, even though also the getprpw*() interface
5008      * is available) one needs to link with -lsecurity -ldb -laud -lm.
5009      * One also needs to call set_auth_parameters() in main() before
5010      * doing anything else, whether one is using getespw*() or getprpw*().
5011      *
5012      * Note that accessing the shadow databases can be magnitudes
5013      * slower than accessing the standard databases.
5014      *
5015      * --jhi
5016      */
5017
5018 #   if defined(__CYGWIN__) && defined(USE_REENTRANT_API)
5019     /* Cygwin 1.5.3-1 has buggy getpwnam_r() and getpwuid_r():
5020      * the pw_comment is left uninitialized. */
5021     PL_reentrant_buffer->_pwent_struct.pw_comment = NULL;
5022 #   endif
5023
5024     switch (which) {
5025     case OP_GPWNAM:
5026       {
5027         char* name = POPpbytex;
5028         pwent  = getpwnam(name);
5029       }
5030       break;
5031     case OP_GPWUID:
5032       {
5033         Uid_t uid = POPi;
5034         pwent = getpwuid(uid);
5035       }
5036         break;
5037     case OP_GPWENT:
5038 #   ifdef HAS_GETPWENT
5039         pwent  = getpwent();
5040 #ifdef POSIX_BC   /* In some cases pw_passwd has invalid addresses */
5041         if (pwent) pwent = getpwnam(pwent->pw_name);
5042 #endif
5043 #   else
5044         DIE(aTHX_ PL_no_func, "getpwent");
5045 #   endif
5046         break;
5047     }
5048
5049     EXTEND(SP, 10);
5050     if (GIMME != G_ARRAY) {
5051         PUSHs(sv = sv_newmortal());
5052         if (pwent) {
5053             if (which == OP_GPWNAM)
5054 #   if Uid_t_sign <= 0
5055                 sv_setiv(sv, (IV)pwent->pw_uid);
5056 #   else
5057                 sv_setuv(sv, (UV)pwent->pw_uid);
5058 #   endif
5059             else
5060                 sv_setpv(sv, pwent->pw_name);
5061         }
5062         RETURN;
5063     }
5064
5065     if (pwent) {
5066         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5067         sv_setpv(sv, pwent->pw_name);
5068
5069         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5070         SvPOK_off(sv);
5071         /* If we have getspnam(), we try to dig up the shadow
5072          * password.  If we are underprivileged, the shadow
5073          * interface will set the errno to EACCES or similar,
5074          * and return a null pointer.  If this happens, we will
5075          * use the dummy password (usually "*" or "x") from the
5076          * standard password database.
5077          *
5078          * In theory we could skip the shadow call completely
5079          * if euid != 0 but in practice we cannot know which
5080          * security measures are guarding the shadow databases
5081          * on a random platform.
5082          *
5083          * Resist the urge to use additional shadow interfaces.
5084          * Divert the urge to writing an extension instead.
5085          *
5086          * --jhi */
5087         /* Some AIX setups falsely(?) detect some getspnam(), which
5088          * has a different API than the Solaris/IRIX one. */
5089 #   if defined(HAS_GETSPNAM) && !defined(_AIX)
5090         {
5091             struct spwd *spwent;
5092             int saverrno; /* Save and restore errno so that
5093                            * underprivileged attempts seem
5094                            * to have never made the unsccessful
5095                            * attempt to retrieve the shadow password. */
5096
5097             saverrno = errno;
5098             spwent = getspnam(pwent->pw_name);
5099             errno = saverrno;
5100             if (spwent && spwent->sp_pwdp)
5101                 sv_setpv(sv, spwent->sp_pwdp);
5102         }
5103 #   endif
5104 #   ifdef PWPASSWD
5105         if (!SvPOK(sv)) /* Use the standard password, then. */
5106             sv_setpv(sv, pwent->pw_passwd);
5107 #   endif
5108
5109 #   ifndef INCOMPLETE_TAINTS
5110         /* passwd is tainted because user himself can diddle with it.
5111          * admittedly not much and in a very limited way, but nevertheless. */
5112         SvTAINTED_on(sv);
5113 #   endif
5114
5115         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5116 #   if Uid_t_sign <= 0
5117         sv_setiv(sv, (IV)pwent->pw_uid);
5118 #   else
5119         sv_setuv(sv, (UV)pwent->pw_uid);
5120 #   endif
5121
5122         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5123 #   if Uid_t_sign <= 0
5124         sv_setiv(sv, (IV)pwent->pw_gid);
5125 #   else
5126         sv_setuv(sv, (UV)pwent->pw_gid);
5127 #   endif
5128         /* pw_change, pw_quota, and pw_age are mutually exclusive--
5129          * because of the poor interface of the Perl getpw*(),
5130          * not because there's some standard/convention saying so.
5131          * A better interface would have been to return a hash,
5132          * but we are accursed by our history, alas. --jhi.  */
5133         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5134 #   ifdef PWCHANGE
5135         sv_setiv(sv, (IV)pwent->pw_change);
5136 #   else
5137 #       ifdef PWQUOTA
5138         sv_setiv(sv, (IV)pwent->pw_quota);
5139 #       else
5140 #           ifdef PWAGE
5141         sv_setpv(sv, pwent->pw_age);
5142 #           endif
5143 #       endif
5144 #   endif
5145
5146         /* pw_class and pw_comment are mutually exclusive--.
5147          * see the above note for pw_change, pw_quota, and pw_age. */
5148         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5149 #   ifdef PWCLASS
5150         sv_setpv(sv, pwent->pw_class);
5151 #   else
5152 #       ifdef PWCOMMENT
5153         sv_setpv(sv, pwent->pw_comment);
5154 #       endif
5155 #   endif
5156
5157         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5158 #   ifdef PWGECOS
5159         sv_setpv(sv, pwent->pw_gecos);
5160 #   endif
5161 #   ifndef INCOMPLETE_TAINTS
5162         /* pw_gecos is tainted because user himself can diddle with it. */
5163         SvTAINTED_on(sv);
5164 #   endif
5165
5166         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5167         sv_setpv(sv, pwent->pw_dir);
5168
5169         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5170         sv_setpv(sv, pwent->pw_shell);
5171 #   ifndef INCOMPLETE_TAINTS
5172         /* pw_shell is tainted because user himself can diddle with it. */
5173         SvTAINTED_on(sv);
5174 #   endif
5175
5176 #   ifdef PWEXPIRE
5177         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5178         sv_setiv(sv, (IV)pwent->pw_expire);
5179 #   endif
5180     }
5181     RETURN;
5182 #else
5183     DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5184 #endif
5185 }
5186
5187 PP(pp_spwent)
5188 {
5189 #if defined(HAS_PASSWD) && defined(HAS_SETPWENT)
5190     dSP;
5191     setpwent();
5192     RETPUSHYES;
5193 #else
5194     DIE(aTHX_ PL_no_func, "setpwent");
5195 #endif
5196 }
5197
5198 PP(pp_epwent)
5199 {
5200 #if defined(HAS_PASSWD) && defined(HAS_ENDPWENT)
5201     dSP;
5202     endpwent();
5203     RETPUSHYES;
5204 #else
5205     DIE(aTHX_ PL_no_func, "endpwent");
5206 #endif
5207 }
5208
5209 PP(pp_ggrent)
5210 {
5211 #ifdef HAS_GROUP
5212     dSP;
5213     I32 which = PL_op->op_type;
5214     register char **elem;
5215     register SV *sv;
5216     struct group *grent;
5217
5218     if (which == OP_GGRNAM) {
5219         char* name = POPpbytex;
5220         grent = (struct group *)getgrnam(name);
5221     }
5222     else if (which == OP_GGRGID) {
5223         Gid_t gid = POPi;
5224         grent = (struct group *)getgrgid(gid);
5225     }
5226     else
5227 #ifdef HAS_GETGRENT
5228         grent = (struct group *)getgrent();
5229 #else
5230         DIE(aTHX_ PL_no_func, "getgrent");
5231 #endif
5232
5233     EXTEND(SP, 4);
5234     if (GIMME != G_ARRAY) {
5235         PUSHs(sv = sv_newmortal());
5236         if (grent) {
5237             if (which == OP_GGRNAM)
5238                 sv_setiv(sv, (IV)grent->gr_gid);
5239             else
5240                 sv_setpv(sv, grent->gr_name);
5241         }
5242         RETURN;
5243     }
5244
5245     if (grent) {
5246         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5247         sv_setpv(sv, grent->gr_name);
5248
5249         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5250 #ifdef GRPASSWD
5251         sv_setpv(sv, grent->gr_passwd);
5252 #endif
5253
5254         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5255         sv_setiv(sv, (IV)grent->gr_gid);
5256
5257 #if !(defined(_CRAYMPP) && defined(USE_REENTRANT_API))
5258         PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5259         /* In UNICOS/mk (_CRAYMPP) the multithreading
5260          * versions (getgrnam_r, getgrgid_r)
5261          * seem to return an illegal pointer
5262          * as the group members list, gr_mem.
5263          * getgrent() doesn't even have a _r version
5264          * but the gr_mem is poisonous anyway.
5265          * So yes, you cannot get the list of group
5266          * members if building multithreaded in UNICOS/mk. */
5267         for (elem = grent->gr_mem; elem && *elem; elem++) {
5268             sv_catpv(sv, *elem);
5269             if (elem[1])
5270                 sv_catpvn(sv, " ", 1);
5271         }
5272 #endif
5273     }
5274
5275     RETURN;
5276 #else
5277     DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5278 #endif
5279 }
5280
5281 PP(pp_sgrent)
5282 {
5283 #if defined(HAS_GROUP) && defined(HAS_SETGRENT)
5284     dSP;
5285     setgrent();
5286     RETPUSHYES;
5287 #else
5288     DIE(aTHX_ PL_no_func, "setgrent");
5289 #endif
5290 }
5291
5292 PP(pp_egrent)
5293 {
5294 #if defined(HAS_GROUP) && defined(HAS_ENDGRENT)
5295     dSP;
5296     endgrent();
5297     RETPUSHYES;
5298 #else
5299     DIE(aTHX_ PL_no_func, "endgrent");
5300 #endif
5301 }
5302
5303 PP(pp_getlogin)
5304 {
5305 #ifdef HAS_GETLOGIN
5306     dSP; dTARGET;
5307     char *tmps;
5308     EXTEND(SP, 1);
5309     if (!(tmps = PerlProc_getlogin()))
5310         RETPUSHUNDEF;
5311     PUSHp(tmps, strlen(tmps));
5312     RETURN;
5313 #else
5314     DIE(aTHX_ PL_no_func, "getlogin");
5315 #endif
5316 }
5317
5318 /* Miscellaneous. */
5319
5320 PP(pp_syscall)
5321 {
5322 #ifdef HAS_SYSCALL
5323     dSP; dMARK; dORIGMARK; dTARGET;
5324     register I32 items = SP - MARK;
5325     unsigned long a[20];
5326     register I32 i = 0;
5327     I32 retval = -1;
5328
5329     if (PL_tainting) {
5330         while (++MARK <= SP) {
5331             if (SvTAINTED(*MARK)) {
5332                 TAINT;
5333                 break;
5334             }
5335         }
5336         MARK = ORIGMARK;
5337         TAINT_PROPER("syscall");
5338     }
5339
5340     /* This probably won't work on machines where sizeof(long) != sizeof(int)
5341      * or where sizeof(long) != sizeof(char*).  But such machines will
5342      * not likely have syscall implemented either, so who cares?
5343      */
5344     while (++MARK <= SP) {
5345         if (SvNIOK(*MARK) || !i)
5346             a[i++] = SvIV(*MARK);
5347         else if (*MARK == &PL_sv_undef)
5348             a[i++] = 0;
5349         else
5350             a[i++] = (unsigned long)SvPV_force_nolen(*MARK);
5351         if (i > 15)
5352             break;
5353     }
5354     switch (items) {
5355     default:
5356         DIE(aTHX_ "Too many args to syscall");
5357     case 0:
5358         DIE(aTHX_ "Too few args to syscall");
5359     case 1:
5360         retval = syscall(a[0]);
5361         break;
5362     case 2:
5363         retval = syscall(a[0],a[1]);
5364         break;
5365     case 3:
5366         retval = syscall(a[0],a[1],a[2]);
5367         break;
5368     case 4:
5369         retval = syscall(a[0],a[1],a[2],a[3]);
5370         break;
5371     case 5:
5372         retval = syscall(a[0],a[1],a[2],a[3],a[4]);
5373         break;
5374     case 6:
5375         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5]);
5376         break;
5377     case 7:
5378         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6]);
5379         break;
5380     case 8:
5381         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]);
5382         break;
5383 #ifdef atarist
5384     case 9:
5385         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
5386         break;
5387     case 10:
5388         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9]);
5389         break;
5390     case 11:
5391         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5392           a[10]);
5393         break;
5394     case 12:
5395         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5396           a[10],a[11]);
5397         break;
5398     case 13:
5399         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5400           a[10],a[11],a[12]);
5401         break;
5402     case 14:
5403         retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
5404           a[10],a[11],a[12],a[13]);
5405         break;
5406 #endif /* atarist */
5407     }
5408     SP = ORIGMARK;
5409     PUSHi(retval);
5410     RETURN;
5411 #else
5412     DIE(aTHX_ PL_no_func, "syscall");
5413 #endif
5414 }
5415
5416 #ifdef FCNTL_EMULATE_FLOCK
5417
5418 /*  XXX Emulate flock() with fcntl().
5419     What's really needed is a good file locking module.
5420 */
5421
5422 static int
5423 fcntl_emulate_flock(int fd, int operation)
5424 {
5425     struct flock flock;
5426
5427     switch (operation & ~LOCK_NB) {
5428     case LOCK_SH:
5429         flock.l_type = F_RDLCK;
5430         break;
5431     case LOCK_EX:
5432         flock.l_type = F_WRLCK;
5433         break;
5434     case LOCK_UN:
5435         flock.l_type = F_UNLCK;
5436         break;
5437     default:
5438         errno = EINVAL;
5439         return -1;
5440     }
5441     flock.l_whence = SEEK_SET;
5442     flock.l_start = flock.l_len = (Off_t)0;
5443
5444     return fcntl(fd, (operation & LOCK_NB) ? F_SETLK : F_SETLKW, &flock);
5445 }
5446
5447 #endif /* FCNTL_EMULATE_FLOCK */
5448
5449 #ifdef LOCKF_EMULATE_FLOCK
5450
5451 /*  XXX Emulate flock() with lockf().  This is just to increase
5452     portability of scripts.  The calls are not completely
5453     interchangeable.  What's really needed is a good file
5454     locking module.
5455 */
5456
5457 /*  The lockf() constants might have been defined in <unistd.h>.
5458     Unfortunately, <unistd.h> causes troubles on some mixed
5459     (BSD/POSIX) systems, such as SunOS 4.1.3.
5460
5461    Further, the lockf() constants aren't POSIX, so they might not be
5462    visible if we're compiling with _POSIX_SOURCE defined.  Thus, we'll
5463    just stick in the SVID values and be done with it.  Sigh.
5464 */
5465
5466 # ifndef F_ULOCK
5467 #  define F_ULOCK       0       /* Unlock a previously locked region */
5468 # endif
5469 # ifndef F_LOCK
5470 #  define F_LOCK        1       /* Lock a region for exclusive use */
5471 # endif
5472 # ifndef F_TLOCK
5473 #  define F_TLOCK       2       /* Test and lock a region for exclusive use */
5474 # endif
5475 # ifndef F_TEST
5476 #  define F_TEST        3       /* Test a region for other processes locks */
5477 # endif
5478
5479 static int
5480 lockf_emulate_flock(int fd, int operation)
5481 {
5482     int i;
5483     int save_errno;
5484     Off_t pos;
5485
5486     /* flock locks entire file so for lockf we need to do the same      */
5487     save_errno = errno;
5488     pos = PerlLIO_lseek(fd, (Off_t)0, SEEK_CUR);    /* get pos to restore later */
5489     if (pos > 0)        /* is seekable and needs to be repositioned     */
5490         if (PerlLIO_lseek(fd, (Off_t)0, SEEK_SET) < 0)
5491             pos = -1;   /* seek failed, so don't seek back afterwards   */
5492     errno = save_errno;
5493
5494     switch (operation) {
5495
5496         /* LOCK_SH - get a shared lock */
5497         case LOCK_SH:
5498         /* LOCK_EX - get an exclusive lock */
5499         case LOCK_EX:
5500             i = lockf (fd, F_LOCK, 0);
5501             break;
5502
5503         /* LOCK_SH|LOCK_NB - get a non-blocking shared lock */
5504         case LOCK_SH|LOCK_NB:
5505         /* LOCK_EX|LOCK_NB - get a non-blocking exclusive lock */
5506         case LOCK_EX|LOCK_NB:
5507             i = lockf (fd, F_TLOCK, 0);
5508             if (i == -1)
5509                 if ((errno == EAGAIN) || (errno == EACCES))
5510                     errno = EWOULDBLOCK;
5511             break;
5512
5513         /* LOCK_UN - unlock (non-blocking is a no-op) */
5514         case LOCK_UN:
5515         case LOCK_UN|LOCK_NB:
5516             i = lockf (fd, F_ULOCK, 0);
5517             break;
5518
5519         /* Default - can't decipher operation */
5520         default:
5521             i = -1;
5522             errno = EINVAL;
5523             break;
5524     }
5525
5526     if (pos > 0)      /* need to restore position of the handle */
5527         PerlLIO_lseek(fd, pos, SEEK_SET);       /* ignore error here    */
5528
5529     return (i);
5530 }
5531
5532 #endif /* LOCKF_EMULATE_FLOCK */
5533
5534 /*
5535  * Local variables:
5536  * c-indentation-style: bsd
5537  * c-basic-offset: 4
5538  * indent-tabs-mode: t
5539  * End:
5540  *
5541  * ex: set ts=8 sts=4 sw=4 noet:
5542  */