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