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