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