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