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