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