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