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