import -ko -b 1.1.3 XEmacs XEmacs-21_2 r21-2-35
[chise/xemacs-chise.git.1] / src / sysdep.c
1 /* Interfaces to system-dependent kernel and library entries.
2    Copyright (C) 1985-1988, 1992-1995 Free Software Foundation, Inc.
3    Copyright (C) 1995 Tinker Systems.
4
5 This file is part of XEmacs.
6
7 XEmacs is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
11
12 XEmacs is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with XEmacs; see the file COPYING.  If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 /* Synched up with: FSF 19.30 except for some Windows-NT crap. */
23
24 /* Substantially cleaned up by Ben Wing, Dec. 1994 / Jan. 1995. */
25
26 /* In this file, open, read and write refer to the system calls,
27    not our sugared interfaces sys_open, sys_read and sys_write.
28  */
29
30 #define DONT_ENCAPSULATE
31
32 #include <config.h>
33
34 #ifdef WIN32_NATIVE
35 #ifdef MINGW
36 #include <mingw32/process.h>
37 #else
38 /* <process.h> should not conflict with "process.h", as per ANSI definition.
39    This is not true with visual c though. The trick below works with
40    VC4.2b, 5.0 and 6.0. It assumes that VC is installed in a kind of
41    standard way, so include path ends with /include.
42
43    Unfortunately, this must go before lisp.h, since process.h defines abort()
44    which will conflict with the macro defined in lisp.h
45 */
46 #include <../include/process.h>
47 #endif /* MINGW */
48 #endif /* WIN32_NATIVE */
49
50 #include "lisp.h"
51
52 /* ------------------------------- */
53 /*          basic includes         */
54 /* ------------------------------- */
55
56 #ifdef HAVE_TTY
57 #include "console-tty.h"
58 #else
59 #include "syssignal.h"
60 #include "systty.h"
61 #endif /* HAVE_TTY */
62
63 #include "console-stream.h"
64
65 #include "buffer.h"
66 #include "events.h"
67 #include "frame.h"
68 #include "redisplay.h"
69 #include "process.h"
70 #include "sysdep.h"
71 #include "window.h"
72
73 #include <setjmp.h>
74 #ifdef HAVE_LIBGEN_H            /* Must come before sysfile.h */
75 #include <libgen.h>
76 #endif
77 #include "sysfile.h"
78 #include "syswait.h"
79 #include "sysdir.h"
80 #include "systime.h"
81 #if defined(WIN32_NATIVE) || defined(CYGWIN)
82 #include "syssignal.h"
83 #endif
84
85 #include "sysproc.h"
86
87 #ifndef WIN32_NATIVE
88 #include <sys/times.h>
89 #endif
90
91 #ifdef WIN32_NATIVE
92 #include <sys/utime.h>
93 #include "ntheap.h"
94 #include "nt.h"
95 #endif
96
97 /* ------------------------------- */
98 /*         TTY definitions         */
99 /* ------------------------------- */
100
101 #ifdef USG
102 #include <sys/utsname.h>
103 #if defined (TIOCGWINSZ) || defined (ISC4_0)
104 #ifdef NEED_SIOCTL
105 #include <sys/sioctl.h>
106 #endif
107 #ifdef NEED_PTEM_H
108 #include <sys/stream.h>
109 #include <sys/ptem.h>
110 #endif
111 #endif /* TIOCGWINSZ or ISC4_0 */
112 #endif /* USG */
113
114 #ifdef HAVE_SYS_STROPTS_H
115 #include <sys/stropts.h>
116 #endif /* HAVE_SYS_STROPTS_H */
117
118 /* LPASS8 is new in 4.3, and makes cbreak mode provide all 8 bits.  */
119 #ifndef LPASS8
120 #define LPASS8 0
121 #endif
122
123 #ifndef HAVE_H_ERRNO
124 int h_errno;
125 #endif
126
127 #ifdef HAVE_TTY
128
129 static int baud_convert[] =
130 #ifdef BAUD_CONVERT
131   BAUD_CONVERT;
132 #else
133   {
134     0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
135     1800, 2400, 4800, 9600, 19200, 38400
136   };
137 #endif
138
139 #endif
140
141 #ifdef AIXHFT
142 static void hft_init (struct console *c);
143 static void hft_reset (struct console *c);
144 #include <sys/termio.h>
145 #endif
146
147 /* ------------------------------- */
148 /*          miscellaneous          */
149 /* ------------------------------- */
150
151 #ifndef HAVE_UTIMES
152 #ifndef HAVE_STRUCT_UTIMBUF
153 /* We want to use utime rather than utimes, but we couldn't find the
154    structure declaration.  We'll use the traditional one.  */
155 struct utimbuf
156 {
157   long actime;
158   long modtime;
159 };
160 #endif
161 #endif
162
163 \f
164 /************************************************************************/
165 /*                         subprocess control                           */
166 /************************************************************************/
167
168 #ifdef HAVE_TTY
169
170 #ifdef SIGTSTP
171
172 /* Arrange for character C to be read as the next input from
173    the terminal.  */
174 void
175 stuff_char (struct console *con, int c)
176 {
177   int input_fd;
178
179   assert (CONSOLE_TTY_P (con));
180   input_fd = CONSOLE_TTY_DATA (con)->infd;
181 /* Should perhaps error if in batch mode */
182 #ifdef TIOCSTI
183   ioctl (input_fd, TIOCSTI, &c);
184 #else /* no TIOCSTI */
185   error ("Cannot stuff terminal input characters in this version of Unix.");
186 #endif /* no TIOCSTI */
187 }
188
189 #endif /* SIGTSTP */
190
191 #endif /* HAVE_TTY */
192
193 void
194 set_exclusive_use (int fd)
195 {
196 #ifdef FIOCLEX
197   ioctl (fd, FIOCLEX, 0);
198 #endif
199   /* Ok to do nothing if this feature does not exist */
200 }
201
202 void
203 set_descriptor_non_blocking (int fd)
204 {
205 /* Stride people say it's a mystery why this is needed
206    as well as the O_NDELAY, but that it fails without this.  */
207   /* For AIX: Apparently need this for non-blocking reads on sockets.
208      It seems that O_NONBLOCK applies only to FIFOs?  From
209      lowry@watson.ibm.com (Andy Lowry). */
210   /* #### Should this be conditionalized on FIONBIO? */
211 #if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS)) || defined (AIX)
212   {
213     int one = 1;
214     ioctl (fd, FIONBIO, &one);
215   }
216 #endif
217
218 #ifdef F_SETFL
219   fcntl (fd, F_SETFL, O_NONBLOCK);
220 #endif
221 }
222
223 #if defined (NO_SUBPROCESSES)
224
225 #ifdef BSD
226 void
227 wait_without_blocking (void)
228 {
229   wait3 (0, WNOHANG | WUNTRACED, 0);
230   synch_process_alive = 0;
231 }
232 #endif /* BSD */
233
234 #endif /* NO_SUBPROCESSES */
235
236
237 #ifdef WIN32_NATIVE
238 void wait_for_termination (HANDLE pHandle)
239 #else
240 void wait_for_termination (int pid)
241 #endif
242 {
243   /* #### With the new improved SIGCHLD handling stuff, there is much
244      less danger of race conditions and some of the comments below
245      don't apply.  This should be updated. */
246
247 #if defined (NO_SUBPROCESSES)
248   while (1)
249     {
250       /* No need to be tricky like below; we can just call wait(). */
251       /* #### should figure out how to write a wait_allowing_quit().
252          Since hardly any systems don't have subprocess support,
253          however, there doesn't seem to be much point. */
254       if (wait (0) == pid)
255         return;
256     }
257 #elif defined (HAVE_WAITPID)
258   /* Note that, whenever any subprocess terminates (asynch. or synch.),
259      the SIGCHLD handler will be called and it will call wait().  Thus
260      we cannot just call wait() ourselves, and we can't block SIGCHLD
261      and then call wait(), because then if an asynch.  process dies
262      while we're waiting for our synch. process, Emacs will never
263      notice that the asynch. process died.
264
265      So, the general approach we take is to repeatedly block until a
266      signal arrives, and then check if our process died using kill
267      (pid, 0).  (We could also check the value of `synch_process_alive',
268      since the SIGCHLD handler will reset that and we know that we're
269      only being called on synchronous processes, but this approach is
270      safer.  I don't trust the proper delivery of SIGCHLD.
271
272      Note also that we cannot use any form of waitpid().  A loop with
273      WNOHANG will chew up CPU time; better to use sleep().  A loop
274      without WNOWAIT will screw up the SIGCHLD handler (actually this
275      is not true, if you duplicate the exit-status-reaping code; see
276      below).  A loop with WNOWAIT will result in a race condition if
277      the process terminates between the process-status check and the
278      call to waitpid(). */
279
280   /* Formerly, immediate_quit was set around this function call, but
281      that could lead to problems if the QUIT happened when SIGCHLD was
282      blocked -- it would remain blocked.  Yet another reason why
283      immediate_quit is a bad idea.  In any case, there is no reason to
284      resort to this because either the SIGIO or the SIGALRM will stop
285      the block in EMACS_WAIT_FOR_SIGNAL(). */
286
287   /* Apparently there are bugs on some systems with the second method
288      used below (the EMACS_BLOCK_SIGNAL method), whereby zombie
289      processes get left around.  It appears in those cases that the
290      SIGCHLD handler is never getting invoked.  It's not clear whether
291      this is an Emacs bug or a kernel bug or both: on HPUX this
292      problem is observed only with XEmacs, but under Solaris 2.4 all
293      sorts of different programs have problems with zombies.  The
294      method we use here does not require a working SIGCHLD (but will
295      not break if it is working), and should be safe. */
296   /*
297      We use waitpid(), contrary to the remarks above.  There is no
298      race condition, because the three situations when sigchld_handler
299      is invoked should be handled OK:
300
301      - handler invoked before waitpid(): In this case, subprocess
302        status will be set by sigchld_handler.  waitpid() here will
303        return -1 with errno set to ECHILD, which is a valid exit
304        condition.
305
306      - handler invoked during waitpid(): as above, except that errno
307        here will be set to EINTR.  This will cause waitpid() to be
308        called again, and this time it will exit with ECHILD.
309
310      - handler invoked after waitpid(): The following code will reap
311        the subprocess. In the handler, wait() will return -1 because
312        there is no child to reap, and the handler will exit without
313        modifying child subprocess status.  */
314   int ret, status;
315
316   /* Because the SIGCHLD handler can potentially reap the synchronous
317      subprocess, we should take care of that.  */
318
319   /* Will stay in the do loop as long as:
320      1. Process is alive
321      2. Ctrl-G is not pressed */
322   do
323     {
324       QUIT;
325       ret = waitpid (pid, &status, 0);
326       /* waitpid returns 0 if the process is still alive. */
327     }
328   while (ret == 0 || (ret == -1 && errno == EINTR));
329
330   if (ret == pid) /* Success */
331     /* Set synch process globals.  This is can also happen
332        in sigchld_handler, and that code is duplicated. */
333     {
334       synch_process_alive = 0;
335       if (WIFEXITED (status))
336         synch_process_retcode = WEXITSTATUS (status);
337       else if (WIFSIGNALED (status))
338         synch_process_death = signal_name (WTERMSIG (status));
339     }
340   /* On exiting the loop, ret will be -1, with errno set to ECHILD if
341      the child has already been reaped, e.g. in the signal handler.  */
342
343   /* Otherwise, we've had some error condition here.
344      Per POSIX, the only other possibilities are:
345      - EFAULT (bus error accessing arg 2) or
346      - EINVAL (incorrect arguments),
347      which are both program bugs.
348
349      Since implementations may add their own error indicators on top,
350      we ignore it by default.  */
351 #elif defined (WIN32_NATIVE)
352   int ret = 0, status = 0;
353   if (pHandle == NULL)
354     {
355       warn_when_safe (Qprocess, Qwarning, "Cannot wait for unknown process to terminate");
356       return;
357     }
358   do
359     {
360       QUIT;
361       ret = WaitForSingleObject(pHandle, 100);
362     }
363   while (ret == WAIT_TIMEOUT);
364   if (ret == WAIT_FAILED)
365     {
366       warn_when_safe (Qprocess, Qwarning, "waiting for process failed");
367     }
368   if (ret == WAIT_ABANDONED)
369     {
370       warn_when_safe (Qprocess, Qwarning,
371                       "process to wait for has been abandoned");
372     }
373   if (ret == WAIT_OBJECT_0)
374     {
375       ret = GetExitCodeProcess(pHandle, &status);
376       if (ret)
377         {
378           synch_process_alive = 0;
379           synch_process_retcode = status;
380         }
381       else
382         {
383           /* GetExitCodeProcess() didn't return a valid exit status,
384              nothing to do.  APA */
385           warn_when_safe (Qprocess, Qwarning,
386                           "failure to obtain process exit value");
387         }
388     }
389   if (pHandle != NULL && !CloseHandle(pHandle))
390     {
391       warn_when_safe (Qprocess, Qwarning,
392                       "failure to close unknown process");
393     }
394 #elif defined (EMACS_BLOCK_SIGNAL) && !defined (BROKEN_WAIT_FOR_SIGNAL) && defined (SIGCHLD)
395   while (1)
396     {
397       static int wait_debugging = 0; /* Set nonzero to make following
398                            function work under dbx (at least for bsd).  */
399       QUIT;
400       if (wait_debugging)
401         return;
402
403       EMACS_BLOCK_SIGNAL (SIGCHLD);
404       /* Block SIGCHLD from happening during this check,
405          to avoid race conditions. */
406       if (kill (pid, 0) < 0)
407         {
408           EMACS_UNBLOCK_SIGNAL (SIGCHLD);
409           return;
410         }
411       else
412         /* WARNING: Whatever this macro does *must* not allow SIGCHLD
413            to happen between the time that it's reenabled and when we
414            begin to block.  Otherwise we may end up blocking for a
415            signal that has already arrived and isn't coming again.
416            Can you say "race condition"?
417
418            I assume that the system calls sigpause() or sigsuspend()
419            to provide this atomicness.  If you're getting hangs in
420            sigpause()/sigsuspend(), then your OS doesn't implement
421            this properly (this applies under hpux9, for example).
422            Try defining BROKEN_WAIT_FOR_SIGNAL. */
423         EMACS_WAIT_FOR_SIGNAL (SIGCHLD);
424     }
425 #else /* not HAVE_WAITPID and not WIN32_NATIVE and (not EMACS_BLOCK_SIGNAL or BROKEN_WAIT_FOR_SIGNAL) */
426   /* This approach is kind of cheesy but is guaranteed(?!) to work
427      for all systems. */
428   while (1)
429     {
430       QUIT;
431       if (kill (pid, 0) < 0)
432         return;
433       emacs_sleep (1);
434     }
435 #endif /* OS features */
436 }
437
438
439 #if !defined (NO_SUBPROCESSES)
440
441 /*
442  *      flush any pending output
443  *      (may flush input as well; it does not matter the way we use it)
444  */
445
446 void
447 flush_pending_output (int channel)
448 {
449 #ifdef HAVE_TERMIOS
450   /* If we try this, we get hit with SIGTTIN, because
451      the child's tty belongs to the child's pgrp. */
452 #elif defined (TCFLSH)
453   ioctl (channel, TCFLSH, 1);
454 #elif defined (TIOCFLUSH)
455   int zero = 0;
456   /* 3rd arg should be ignored
457      but some 4.2 kernels actually want the address of an int
458      and nonzero means something different.  */
459   ioctl (channel, TIOCFLUSH, &zero);
460 #endif
461 }
462
463 #ifndef WIN32_NATIVE
464 /*  Set up the terminal at the other end of a pseudo-terminal that
465     we will be controlling an inferior through.
466     It should not echo or do line-editing, since that is done
467     in Emacs.  No padding needed for insertion into an Emacs buffer.  */
468
469 void
470 child_setup_tty (int out)
471 {
472   struct emacs_tty s;
473   emacs_get_tty (out, &s);
474
475 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
476   assert (isatty(out));
477   s.main.c_oflag |= OPOST;      /* Enable output postprocessing */
478   s.main.c_oflag &= ~ONLCR;     /* Disable map of NL to CR-NL on output */
479 #ifdef NLDLY
480   s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
481                                 /* No output delays */
482 #endif
483   s.main.c_lflag &= ~ECHO;      /* Disable echo */
484   s.main.c_lflag |= ISIG;       /* Enable signals */
485 #ifdef IUCLC
486   s.main.c_iflag &= ~IUCLC;     /* Disable downcasing on input.  */
487 #endif
488 #ifdef OLCUC
489   s.main.c_oflag &= ~OLCUC;     /* Disable upcasing on output.  */
490 #endif
491   s.main.c_oflag &= ~TAB3;      /* Disable tab expansion */
492 #if defined (CSIZE) && defined (CS8)
493   s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
494 #endif
495 #ifdef ISTRIP
496   s.main.c_iflag &= ~ISTRIP;    /* Don't strip 8th bit on input */
497 #endif
498 #if 0
499   /* Unnecessary as long as ICANON is set */
500   s.main.c_cc[VMIN]  = 1;       /* minimum number of characters to accept  */
501   s.main.c_cc[VTIME] = 0;       /* wait forever for at least 1 character  */
502 #endif /* 0 */
503
504   s.main.c_lflag |= ICANON;     /* Enable erase/kill and eof processing */
505   s.main.c_cc[VEOF] = 04;       /* ensure that EOF is Control-D */
506   s.main.c_cc[VERASE] = _POSIX_VDISABLE; /* disable erase processing */
507   s.main.c_cc[VKILL]  = _POSIX_VDISABLE; /* disable kill processing */
508
509 #ifdef HPUX
510   s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
511 #endif /* HPUX */
512
513 #ifdef AIX
514 #ifndef IBMR2AIX
515   /* AIX enhanced edit loses NULs, so disable it. */
516   s.main.c_line = 0;
517   s.main.c_iflag &= ~ASCEDIT;
518 #endif /* IBMR2AIX */
519   /* Also, PTY overloads NUL and BREAK.
520      don't ignore break, but don't signal either, so it looks like NUL.
521      This really serves a purpose only if running in an XTERM window
522      or via TELNET or the like, but does no harm elsewhere.  */
523   s.main.c_iflag &= ~IGNBRK;
524   s.main.c_iflag &= ~BRKINT;
525 #endif /* AIX */
526 #ifdef SIGNALS_VIA_CHARACTERS
527   /* TTY `special characters' are used in process_send_signal
528      so set them here to something useful.  */
529   s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
530   s.main.c_cc[VINTR] = 'C' &037; /* Control-C */
531   s.main.c_cc[VSUSP] = 'Z' &037; /* Control-Z */
532 #else /* no TIOCGPGRP or no TIOCGLTC or no TIOCGETC */
533   /* TTY `special characters' work better as signals, so disable
534      character forms */
535   s.main.c_cc[VQUIT] = _POSIX_VDISABLE;
536   s.main.c_cc[VINTR] = _POSIX_VDISABLE;
537   s.main.c_cc[VSUSP] = _POSIX_VDISABLE;
538   s.main.c_lflag &= ~ISIG;
539 #endif /* no TIOCGPGRP or no TIOCGLTC or no TIOCGETC */
540   s.main.c_cc[VEOL] = _POSIX_VDISABLE;
541 #if defined (CBAUD)
542   /* <mdiers> #### This is not portable. ###
543      POSIX does not specify CBAUD, and 4.4BSD does not have it.
544      Instead, POSIX suggests to use cfset{i,o}speed().
545      [cf. D. Lewine, POSIX Programmer's Guide, Chapter 8: Terminal
546      I/O, O'Reilly 1991] */
547   s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
548 #else
549   /* <mdiers> What to do upon failure? Just ignoring rc is probably
550      not acceptable, is it? */
551   if (cfsetispeed (&s.main, B9600) == -1) /* ignore */;
552   if (cfsetospeed (&s.main, B9600) == -1) /* ignore */;
553 #endif /* defined (CBAUD) */
554
555 #else /* not HAVE_TERMIO */
556
557   s.main.sg_flags &= ~(ECHO | CRMOD | ANYP | ALLDELAY | RAW | LCASE
558                        | CBREAK | TANDEM);
559   s.main.sg_flags |= LPASS8;
560   s.main.sg_erase = 0377;
561   s.main.sg_kill  = 0377;
562   s.lmode = LLITOUT | s.lmode;        /* Don't strip 8th bit */
563
564 #endif /* not HAVE_TERMIO */
565   emacs_set_tty (out, &s, 0);
566
567 #ifdef RTU
568   {
569     int zero = 0;
570     ioctl (out, FIOASYNC, &zero);
571   }
572 #endif /* RTU */
573 }
574 #endif /* WIN32_NATIVE */
575
576 #endif /* not NO_SUBPROCESSES */
577
578 \f
579 #if !defined (SIGTSTP) && !defined (USG_JOBCTRL)
580
581 #if defined(__STDC__) || defined(_MSC_VER)
582 #define SIG_PARAM_TYPE int
583 #else
584 #define SIG_PARAM_TYPE
585 #endif
586
587 /* Record a signal code and the handler for it.  */
588 struct save_signal
589 {
590   int code;
591   SIGTYPE (*handler) (SIG_PARAM_TYPE);
592 };
593
594 static void
595 save_signal_handlers (struct save_signal *saved_handlers)
596 {
597   while (saved_handlers->code)
598     {
599       saved_handlers->handler
600         = (SIGTYPE (*) (SIG_PARAM_TYPE)) signal (saved_handlers->code, SIG_IGN);
601       saved_handlers++;
602     }
603 }
604
605 static void
606 restore_signal_handlers (struct save_signal *saved_handlers)
607 {
608   while (saved_handlers->code)
609     {
610       signal (saved_handlers->code, saved_handlers->handler);
611       saved_handlers++;
612     }
613 }
614
615 #ifdef WIN32_NATIVE
616
617 pid_t
618 sys_getpid (void)
619 {
620   return abs (getpid ());
621 }
622
623 #endif /* WIN32_NATIVE */
624
625 /* Fork a subshell.  */
626 static void
627 sys_subshell (void)
628 {
629 #ifndef WIN32_NATIVE
630   int pid;
631 #endif
632   struct save_signal saved_handlers[5];
633   Lisp_Object dir;
634   unsigned char *str = 0;
635   int len;
636   struct gcpro gcpro1;
637
638   saved_handlers[0].code = SIGINT;
639   saved_handlers[1].code = SIGQUIT;
640   saved_handlers[2].code = SIGTERM;
641 #ifdef SIGIO
642   saved_handlers[3].code = SIGIO;
643   saved_handlers[4].code = 0;
644 #else
645   saved_handlers[3].code = 0;
646 #endif
647
648   /* Mentioning current_buffer->buffer would mean including buffer.h,
649      which somehow wedges the hp compiler.  So instead...  */
650
651   if (NILP (Fboundp (Qdefault_directory)))
652     goto xyzzy;
653   dir = Fsymbol_value (Qdefault_directory);
654   if (!STRINGP (dir))
655     goto xyzzy;
656
657   GCPRO1 (dir);
658   dir = Funhandled_file_name_directory (dir);
659   dir = expand_and_dir_to_file (dir, Qnil);
660   UNGCPRO;
661   str = (unsigned char *) alloca (XSTRING_LENGTH (dir) + 2);
662   len = XSTRING_LENGTH (dir);
663   memcpy (str, XSTRING_DATA (dir), len);
664   if (!IS_ANY_SEP (str[len - 1]))
665     str[len++] = DIRECTORY_SEP;
666   str[len] = 0;
667  xyzzy:
668
669 #ifndef WIN32_NATIVE
670   pid = fork ();
671
672   if (pid == -1)
673     error ("Can't spawn subshell");
674   if (pid == 0)
675 #endif /* not WIN32_NATIVE */
676   {
677       char *sh = 0;
678
679       if (sh == 0)
680         sh = (char *) egetenv ("SHELL");
681       if (sh == 0)
682         sh = "sh";
683
684     /* Use our buffer's default directory for the subshell.  */
685     if (str)
686       sys_chdir (str);
687
688 #ifdef WIN32_NATIVE
689
690     /* Waits for process completion */
691     if (_spawnlp (_P_WAIT, sh, sh, NULL) != 0)
692       error ("Can't spawn subshell");
693     else
694       return; /* we're done, no need to wait for termination */
695   }
696
697 #else
698
699 #if !defined (NO_SUBPROCESSES)
700     close_process_descs ();     /* Close Emacs's pipes/ptys */
701 #endif
702
703 #ifdef SET_EMACS_PRIORITY
704     if (emacs_priority != 0)
705       nice (-emacs_priority);   /* Give the new shell the default priority */
706 #endif
707
708     execlp (sh, sh, 0);
709     write (1, "Can't execute subshell", 22);
710     _exit (1);
711   }
712
713   save_signal_handlers (saved_handlers);
714   synch_process_alive = 1;
715   wait_for_termination (pid);
716   restore_signal_handlers (saved_handlers);
717
718 #endif /* not WIN32_NATIVE */
719
720 }
721
722 #endif /* !defined (SIGTSTP) && !defined (USG_JOBCTRL) */
723
724
725 \f
726 /* Suspend the Emacs process; give terminal to its superior.  */
727 void
728 sys_suspend (void)
729 {
730 #if defined (SIGTSTP)
731   {
732     int pgrp = EMACS_GET_PROCESS_GROUP ();
733     EMACS_KILLPG (pgrp, SIGTSTP);
734   }
735
736 #elif defined (USG_JOBCTRL)
737   /* If you don't know what this is don't mess with it */
738   ptrace (0, 0, 0, 0);          /* set for ptrace - caught by csh */
739   kill (getpid (), SIGQUIT);
740
741 #else /* No SIGTSTP or USG_JOBCTRL */
742
743   /* On a system where suspending is not implemented,
744      instead fork a subshell and let it talk directly to the terminal
745      while we wait.  */
746   sys_subshell ();
747
748 #endif
749 }
750
751 /* Suspend a process if possible; give terminal to its superior.  */
752 void
753 sys_suspend_process (int process)
754 {
755     /* I don't doubt that it is possible to suspend processes on
756      * VMS machines or thost that use USG_JOBCTRL,
757      * but I don't know how to do it, so...
758      */
759 #if defined (SIGTSTP)
760     kill(process, SIGTSTP);
761 #endif
762 }
763 \f
764
765 /* Given FD, obtain pty buffer size. When no luck, a good guess is made,
766    so that the function works even when fd is not a pty. */
767
768 int
769 get_pty_max_bytes (int fd)
770 {
771   /* DEC OSF 4.0 fpathconf returns 255, but xemacs hangs on long shell
772      input lines if we return 253.  252 is OK!.  So let's leave a bit
773      of slack for the newline that xemacs will insert, and for those
774      inevitable vendor off-by-one-or-two-or-three bugs. */
775 #define MAX_CANON_SLACK 10
776 #define SAFE_MAX_CANON (127 - MAX_CANON_SLACK)
777 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
778   {
779     int max_canon = fpathconf (fd, _PC_MAX_CANON);
780     return (max_canon < 0 ? SAFE_MAX_CANON :
781             max_canon > SAFE_MAX_CANON ? max_canon - MAX_CANON_SLACK :
782             max_canon);
783   }
784 #elif defined (_POSIX_MAX_CANON)
785   return (_POSIX_MAX_CANON > SAFE_MAX_CANON ?
786           _POSIX_MAX_CANON - MAX_CANON_SLACK :
787           _POSIX_MAX_CANON);
788 #else
789   return SAFE_MAX_CANON;
790 #endif
791 }
792
793 /* Figure out the eof character for the FD. */
794
795 Bufbyte
796 get_eof_char (int fd)
797 {
798   const Bufbyte ctrl_d = (Bufbyte) '\004';
799
800   if (!isatty (fd))
801     return ctrl_d;
802 #ifdef HAVE_TERMIOS
803   {
804     struct termios t;
805     tcgetattr (fd, &t);
806 #if 0
807     /* What is the following line designed to do??? -mrb */
808     if (strlen ((const char *) t.c_cc) < (unsigned int) (VEOF + 1))
809       return ctrl_d;
810     else
811       return (Bufbyte) t.c_cc[VEOF];
812 #endif
813     return t.c_cc[VEOF] == _POSIX_VDISABLE ? ctrl_d : (Bufbyte) t.c_cc[VEOF];
814   }
815 #else /* ! HAVE_TERMIOS */
816   /* On Berkeley descendants, the following IOCTL's retrieve the
817     current control characters.  */
818 #if defined (TIOCGETC)
819   {
820     struct tchars c;
821     ioctl (fd, TIOCGETC, &c);
822     return (Bufbyte) c.t_eofc;
823   }
824 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
825   /* On SYSV descendants, the TCGETA ioctl retrieves the current control
826      characters.  */
827 #ifdef TCGETA
828   {
829     struct termio t;
830     ioctl (fd, TCGETA, &t);
831     if (strlen ((const char *) t.c_cc) < (unsigned int) (VINTR + 1))
832       return ctrl_d;
833     else
834       return (Bufbyte) t.c_cc[VINTR];
835   }
836 #else /* ! defined (TCGETA) */
837   /* Rather than complain, we'll just guess ^D, which is what
838    * earlier emacsen always used. */
839   return ctrl_d;
840 #endif /* ! defined (TCGETA) */
841 #endif /* ! defined (TIOCGETC) */
842 #endif /* ! defined (HAVE_TERMIOS) */
843 }
844
845 /* Set the logical window size associated with descriptor FD
846    to HEIGHT and WIDTH.  This is used mainly with ptys.  */
847
848 int
849 set_window_size (int fd, int height, int width)
850 {
851 #ifdef TIOCSWINSZ
852
853   /* BSD-style.  */
854   struct winsize size;
855   size.ws_row = height;
856   size.ws_col = width;
857
858   if (ioctl (fd, TIOCSWINSZ, &size) == -1)
859     return 0; /* error */
860   else
861     return 1;
862
863 #elif defined (TIOCSSIZE)
864
865   /* SunOS - style.  */
866   struct ttysize size;
867   size.ts_lines = height;
868   size.ts_cols = width;
869
870   if (ioctl (fd, TIOCGSIZE, &size) == -1)
871     return 0;
872   else
873     return 1;
874 #else
875   return -1;
876 #endif
877 }
878
879 #ifdef HAVE_PTYS
880
881 /* Set up the proper status flags for use of a pty.  */
882
883 void
884 setup_pty (int fd)
885 {
886   /* I'm told that TOICREMOTE does not mean control chars
887      "can't be sent" but rather that they don't have
888      input-editing or signaling effects.
889      That should be good, because we have other ways
890      to do those things in Emacs.
891      However, telnet mode seems not to work on 4.2.
892      So TIOCREMOTE is turned off now. */
893
894   /* Under hp-ux, if TIOCREMOTE is turned on, some calls
895      will hang.  In particular, the "timeout" feature (which
896      causes a read to return if there is no data available)
897      does this.  Also it is known that telnet mode will hang
898      in such a way that Emacs must be stopped (perhaps this
899      is the same problem).
900
901      If TIOCREMOTE is turned off, then there is a bug in
902      hp-ux which sometimes loses data.  Apparently the
903      code which blocks the master process when the internal
904      buffer fills up does not work.  Other than this,
905      though, everything else seems to work fine.
906
907      Since the latter lossage is more benign, we may as well
908      lose that way.  -- cph */
909 #if defined (FIONBIO) && defined (SYSV_PTYS)
910   {
911     int on = 1;
912     ioctl (fd, FIONBIO, &on);
913   }
914 #endif
915 #ifdef IBMRTAIX
916   /* On AIX, the parent gets SIGHUP when a pty attached child dies.  So, we */
917   /* ignore SIGHUP once we've started a child on a pty.  Note that this may */
918   /* cause EMACS not to die when it should, i.e., when its own controlling  */
919   /* tty goes away.  I've complained to the AIX developers, and they may    */
920   /* change this behavior, but I'm not going to hold my breath.             */
921   signal (SIGHUP, SIG_IGN);
922 #endif
923 #ifdef TIOCPKT
924   /* In some systems (Linux through 2.0.0, at least), packet mode doesn't
925      get cleared when a pty is closed, so we need to clear it here.
926      Linux pre2.0.13 contained an attempted fix for this (from Ted Ts'o,
927      tytso@mit.edu), but apparently it messed up rlogind and telnetd, so he
928      removed the fix in pre2.0.14.     - dkindred@cs.cmu.edu
929    */
930   {
931     int off = 0;
932     ioctl (fd, TIOCPKT, (char *)&off);
933   }
934 #endif
935 }
936 #endif /* HAVE_PTYS */
937
938 \f
939 /************************************************************************/
940 /*                            TTY control                               */
941 /************************************************************************/
942
943 /* ------------------------------------------------------ */
944 /*                     get baud rate                      */
945 /* ------------------------------------------------------ */
946
947 /* It really makes more sense for the baud-rate to be console-specific
948    and not device-specific, but it's (at least potentially) used for output
949    decisions. */
950
951 void
952 init_baud_rate (struct device *d)
953 {
954   struct console *con = XCONSOLE (DEVICE_CONSOLE (d));
955   if (DEVICE_WIN_P (d) || DEVICE_STREAM_P (d))
956     {
957       DEVICE_BAUD_RATE (d) = 38400;
958       return;
959     }
960
961 #ifdef HAVE_TTY
962   assert (DEVICE_TTY_P (d));
963   {
964     int input_fd = CONSOLE_TTY_DATA (con)->infd;
965 #if defined (WIN32_NATIVE)
966     DEVICE_TTY_DATA (d)->ospeed = 15;
967 #elif defined (HAVE_TERMIOS)
968     struct termios sg;
969
970     sg.c_cflag = B9600;
971     tcgetattr (input_fd, &sg);
972     DEVICE_TTY_DATA (d)->ospeed = cfgetospeed (&sg);
973 # if defined (USE_GETOBAUD) && defined (getobaud)
974     /* m88k-motorola-sysv3 needs this (ghazi@noc.rutgers.edu) 9/1/94. */
975     if (DEVICE_TTY_DATA (d)->ospeed == 0)
976       DEVICE_TTY_DATA (d)->ospeed = getobaud (sg.c_cflag);
977 # endif
978 #elif defined (HAVE_TERMIO)
979     struct termio sg;
980
981     sg.c_cflag = B9600;
982 # ifdef HAVE_TCATTR
983     tcgetattr (input_fd, &sg);
984 # else
985     ioctl (input_fd, TCGETA, &sg);
986 # endif
987     DEVICE_TTY_DATA (d)->ospeed = sg.c_cflag & CBAUD;
988 #else /* neither TERMIOS nor TERMIO */
989     struct sgttyb sg;
990
991     sg.sg_ospeed = B9600;
992     if (ioctl (input_fd, TIOCGETP, &sg) < 0)
993       abort ();
994     DEVICE_TTY_DATA (d)->ospeed = sg.sg_ospeed;
995 #endif
996   }
997
998   DEVICE_BAUD_RATE (d) =
999     (DEVICE_TTY_DATA (d)->ospeed < countof (baud_convert)
1000      ? baud_convert[DEVICE_TTY_DATA (d)->ospeed]
1001      : 9600);
1002
1003   if (DEVICE_BAUD_RATE (d) == 0)
1004     DEVICE_BAUD_RATE (d) = 1200;
1005 #endif /* HAVE_TTY */
1006 }
1007
1008 \f
1009 /* ------------------------------------------------------ */
1010 /*                       SIGIO control                    */
1011 /* ------------------------------------------------------ */
1012
1013 #if defined(SIGIO) && !defined(BROKEN_SIGIO)
1014
1015 static void
1016 init_sigio_on_device (struct device *d)
1017 {
1018   int filedesc = DEVICE_INFD (d);
1019
1020 #if defined (FIOSSAIOOWN)
1021   { /* HPUX stuff */
1022     int owner = getpid ();
1023     int ioctl_status;
1024     if (DEVICE_TTY_P (d))
1025         {
1026           ioctl_status = ioctl (filedesc, FIOGSAIOOWN,
1027                                 &DEVICE_OLD_FCNTL_OWNER (d));
1028           ioctl_status = ioctl (filedesc, FIOSSAIOOWN, &owner);
1029         }
1030 #ifdef HAVE_WINDOW_SYSTEM
1031     else if (!DEVICE_STREAM_P (d))
1032       {
1033         ioctl_status = ioctl (filedesc, SIOCGPGRP,
1034                               &DEVICE_OLD_FCNTL_OWNER (d));
1035         ioctl_status = ioctl (filedesc, SIOCSPGRP, &owner);
1036       }
1037 #endif
1038   }
1039 #elif defined (F_SETOWN) && !defined (F_SETOWN_BUG)
1040   DEVICE_OLD_FCNTL_OWNER (d) = fcntl (filedesc, F_GETOWN, 0);
1041 # ifdef F_SETOWN_SOCK_NEG
1042   /* stdin is a socket here */
1043   fcntl (filedesc, F_SETOWN, -getpid ());
1044 # else
1045   fcntl (filedesc, F_SETOWN, getpid ());
1046 # endif
1047 #endif
1048 }
1049
1050 static void
1051 reset_sigio_on_device (struct device *d)
1052 {
1053   int filedesc = DEVICE_INFD (d);
1054
1055 #if defined (FIOSSAIOOWN)
1056   { /* HPUX stuff */
1057     int ioctl_status;
1058     if (DEVICE_TTY_P (d))
1059       {
1060         ioctl_status = ioctl (filedesc, FIOSSAIOOWN,
1061                               &DEVICE_OLD_FCNTL_OWNER (d));
1062       }
1063 #ifdef HAVE_WINDOW_SYSTEM
1064     else if (!DEVICE_STREAM_P (d))
1065       {
1066         ioctl_status = ioctl (filedesc, SIOCSPGRP,
1067                               &DEVICE_OLD_FCNTL_OWNER (d));
1068       }
1069 #endif
1070   }
1071 #elif defined (F_SETOWN) && !defined (F_SETOWN_BUG)
1072   fcntl (filedesc, F_SETOWN, DEVICE_OLD_FCNTL_OWNER (d));
1073 #endif
1074 }
1075
1076 static void
1077 request_sigio_on_device (struct device *d)
1078 {
1079   int filedesc = DEVICE_INFD (d);
1080
1081 #if defined (I_SETSIG) && !defined(HPUX10) && !defined(LINUX)
1082   {
1083     int events=0;
1084     ioctl (filedesc, I_GETSIG, &events);
1085     ioctl (filedesc, I_SETSIG, events | S_INPUT);
1086   }
1087 #elif defined (FASYNC)
1088   fcntl (filedesc, F_SETFL, fcntl (filedesc, F_GETFL, 0) | FASYNC);
1089 #elif defined (FIOSSAIOSTAT)
1090   {
1091       /* DG: Changed for HP-UX. HP-UX uses different IOCTLs for
1092          sockets and other devices for some bizarre reason. We guess
1093          that an X device is a socket, and tty devices aren't. We then
1094          use the following crud to do the appropriate thing. */
1095     int on = 1;
1096     int ioctl_status;           /* ####DG: check if IOCTL succeeds here. */
1097
1098     if (DEVICE_TTY_P (d))
1099       {
1100         ioctl_status = ioctl (filedesc, FIOSSAIOSTAT, &on);
1101       }
1102 #ifdef HAVE_WINDOW_SYSTEM
1103     else if (!DEVICE_STREAM_P (d))
1104       {
1105         ioctl_status = ioctl (filedesc, FIOASYNC, &on);
1106       }
1107 #endif
1108   }
1109 #elif defined (FIOASYNC)
1110   {
1111     int on = 1;
1112     ioctl (filedesc, FIOASYNC, &on);
1113   }
1114 #endif
1115
1116 #if defined (_CX_UX) /* #### Is this crap necessary? */
1117   EMACS_UNBLOCK_SIGNAL (SIGIO);
1118 #endif
1119 }
1120
1121 static void
1122 unrequest_sigio_on_device (struct device *d)
1123 {
1124   int filedesc = DEVICE_INFD (d);
1125
1126 #if defined (I_SETSIG) && !defined(HPUX10)
1127   {
1128     int events=0;
1129     ioctl (filedesc, I_GETSIG, &events);
1130     ioctl (filedesc, I_SETSIG, events & ~S_INPUT);
1131   }
1132 #elif defined (FASYNC)
1133   fcntl (filedesc, F_SETFL, fcntl (filedesc, F_GETFL, 0) & ~FASYNC);
1134 #elif defined (FIOSSAIOSTAT)
1135   {
1136       /* DG: Changed for HP-UX. HP-UX uses different IOCTLs for
1137          sockets and other devices for some bizarre reason. We guess
1138          that an X device is a socket, and tty devices aren't. We then
1139          use the following crud to do the appropriate thing. */
1140
1141     int off = 0;
1142     int ioctl_status;
1143
1144     /* See comment for request_sigio_on_device */
1145
1146     if (DEVICE_TTY_P (d))
1147       {
1148         ioctl_status = ioctl (filedesc, FIOSSAIOSTAT, &off);
1149       }
1150     else
1151       {
1152         ioctl_status = ioctl (filedesc, FIOASYNC, &off);
1153       }
1154   }
1155 #elif defined (FIOASYNC)
1156   {
1157     int off = 0;
1158     ioctl (filedesc, FIOASYNC, &off);
1159   }
1160 #endif
1161 }
1162
1163 void
1164 request_sigio (void)
1165 {
1166   Lisp_Object devcons, concons;
1167
1168   DEVICE_LOOP_NO_BREAK (devcons, concons)
1169     {
1170       struct device *d;
1171
1172       d = XDEVICE (XCAR (devcons));
1173
1174       if (!DEVICE_STREAM_P (d))
1175         request_sigio_on_device (d);
1176     }
1177 }
1178
1179 void
1180 unrequest_sigio (void)
1181 {
1182   Lisp_Object devcons, concons;
1183
1184   DEVICE_LOOP_NO_BREAK (devcons, concons)
1185     {
1186       struct device *d;
1187
1188       d = XDEVICE (XCAR (devcons));
1189
1190       if (!DEVICE_STREAM_P (d))
1191         unrequest_sigio_on_device (d);
1192     }
1193 }
1194
1195 #endif /* SIGIO */
1196 \f
1197 /* ------------------------------------------------------ */
1198 /*             Changing Emacs's process group             */
1199 /* ------------------------------------------------------ */
1200
1201 /* Saving and restoring the process group of Emacs's terminal.  */
1202
1203 /* On some systems, apparently (?!) Emacs must be in its own process
1204    group in order to receive SIGIO correctly.  On other systems
1205    (e.g. Solaris), it's not required and doing it makes things
1206    get fucked up.  So, we only do it when
1207    SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP is defined.  Basically,
1208    this is only required for BSD 4.2 systems. (Actually, I bet
1209    we don't have to do this at all -- those systems also
1210    required interrupt input, which we don't support.)
1211
1212    If Emacs was in its own process group (i.e. inherited_pgroup ==
1213    getpid ()), then we know we're running under a shell with job
1214    control (Emacs would never be run as part of a pipeline).
1215    Everything is fine.
1216
1217    If Emacs was not in its own process group, then we know we're
1218    running under a shell (or a caller) that doesn't know how to
1219    separate itself from Emacs (like sh).  Emacs must be in its own
1220    process group in order to receive SIGIO correctly.  In this
1221    situation, we put ourselves in our own pgroup, forcibly set the
1222    tty's pgroup to our pgroup, and make sure to restore and reinstate
1223    the tty's pgroup just like any other terminal setting.  If
1224    inherited_group was not the tty's pgroup, then we'll get a
1225    SIGTTmumble when we try to change the tty's pgroup, and a CONT if
1226    it goes foreground in the future, which is what should happen.  */
1227
1228 #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
1229
1230 static int inherited_pgroup;
1231 static int inherited_tty_pgroup;
1232
1233 #endif
1234
1235 void
1236 munge_tty_process_group (void)
1237 {
1238 #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
1239   if (noninteractive)
1240     return;
1241
1242   /* Only do this munging if we have a device on the controlling
1243      terminal.  See the large comment below. */
1244
1245   if (CONSOLEP (Vcontrolling_terminal) &&
1246       CONSOLE_LIVE_P (XCONSOLE (Vcontrolling_terminal)))
1247     {
1248       int fd = open ("/dev/tty", O_RDWR, 0);
1249       int me = getpid ();
1250       EMACS_BLOCK_SIGNAL (SIGTTOU);
1251       EMACS_SET_TTY_PROCESS_GROUP (fd, &me);
1252       EMACS_UNBLOCK_SIGNAL (SIGTTOU);
1253       close (fd);
1254     }
1255 #endif
1256 }
1257
1258 /* Split off the foreground process group to Emacs alone.
1259    When we are in the foreground, but not started in our own process
1260    group, redirect the TTY to point to our own process group.  We need
1261    to be in our own process group to receive SIGIO properly.  */
1262 static void
1263 munge_process_groups (void)
1264 {
1265 #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
1266   if (noninteractive)
1267     return;
1268
1269   EMACS_SEPARATE_PROCESS_GROUP ();
1270
1271   munge_tty_process_group ();
1272 #endif
1273 }
1274
1275 void
1276 unmunge_tty_process_group (void)
1277 {
1278 #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
1279   {
1280     int fd = open ("/dev/tty", O_RDWR, 0);
1281     EMACS_BLOCK_SIGNAL (SIGTTOU);
1282     EMACS_SET_TTY_PROCESS_GROUP (fd, &inherited_tty_pgroup);
1283     EMACS_UNBLOCK_SIGNAL (SIGTTOU);
1284     close (fd);
1285   }
1286 #endif
1287 }
1288
1289 /* Set the tty to our original foreground group.
1290    Also restore the original process group (put us back into sh's
1291    process group), so that ^Z will suspend both us and sh. */
1292 static void
1293 unmunge_process_groups (void)
1294 {
1295 #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
1296   if (noninteractive)
1297     return;
1298
1299   unmunge_tty_process_group ();
1300
1301   EMACS_SET_PROCESS_GROUP (inherited_pgroup);
1302 #endif
1303 }
1304
1305 /* According to some old wisdom, we need to be in a separate process
1306    group for SIGIO to work correctly (at least on some systems ...).
1307    So go ahead and put ourselves into our own process group.  This
1308    will fail if we're already in our own process group, but who cares.
1309    Also record whether we were in our own process group. (In general,
1310    we will already be in our own process group if we were started from
1311    a job-control shell like csh, but not if we were started from sh).
1312
1313    If we succeeded in changing our process group, then we will no
1314    longer be in the foreground process group of our controlling
1315    terminal.  Therefore, if we have a console open onto this terminal,
1316    we have to change the controlling terminal's foreground process
1317    group (otherwise we will get stopped with a SIGTTIN signal when
1318    attempting to read from the terminal).  It's important,
1319    however, that we do this *only* when we have a console open onto
1320    the terminal.  It's a decidedly bad idea to do so otherwise,
1321    especially if XEmacs was started from the background. */
1322
1323 void
1324 init_process_group (void)
1325 {
1326 #ifdef SIGIO_REQUIRES_SEPARATE_PROCESS_GROUP
1327   if (! noninteractive)
1328     {
1329       int fd = open ("/dev/tty", O_RDWR, 0);
1330       inherited_pgroup = EMACS_GET_PROCESS_GROUP ();
1331       EMACS_GET_TTY_PROCESS_GROUP (fd, &inherited_tty_pgroup);
1332       close (fd);
1333       EMACS_SEPARATE_PROCESS_GROUP ();
1334     }
1335 #endif
1336 }
1337
1338 void
1339 disconnect_controlling_terminal (void)
1340 {
1341 #  ifdef HAVE_SETSID
1342   /* Controlling terminals are attached to a session.
1343      Create a new session for us; it will have no controlling
1344      terminal.  This also, of course, puts us in our own
1345      process group. */
1346   setsid ();
1347 #  else
1348   /* Put us in our own process group. */
1349   EMACS_SEPARATE_PROCESS_GROUP ();
1350 #    if defined (TIOCNOTTY)
1351   /* This is the older way of disconnecting the controlling
1352      terminal, on 4.3 BSD.  We must open /dev/tty; using
1353      filedesc 0 is not sufficient because it could be
1354      something else (e.g. our stdin was redirected to
1355      another terminal).
1356      */
1357   {
1358     int j = open ("/dev/tty", O_RDWR, 0);
1359     ioctl (j, TIOCNOTTY, 0);
1360     close (j);
1361   }
1362 #    endif /* TIOCNOTTY */
1363   /*
1364      On systems without TIOCNOTTY and without
1365      setsid(), we don't need to do anything more to
1366      disconnect our controlling terminal.  Here is
1367      what the man page for termio(7) from a SYSV 3.2
1368      system says:
1369
1370      "The first terminal file opened by the process group leader
1371      of a terminal file not already associated with a process
1372      group becomes the control terminal for that process group.
1373      The control terminal plays a special role in handling quit
1374      and interrupt signals, as discussed below.  The control
1375      terminal is inherited by a child process during a fork(2).
1376      A process can break this association by changing its process
1377      group using setpgrp(2)."
1378
1379      */
1380 #  endif /* not HAVE_SETSID */
1381 }
1382
1383 \f
1384 /* ------------------------------------------------------ */
1385 /*        Getting and setting emacs_tty structures        */
1386 /* ------------------------------------------------------ */
1387
1388 /* It's wrong to encase these into #ifdef HAVE_TTY because we need
1389    them for child TTY processes.  */
1390 /* However, this does break NT support while we don't do child TTY processes */
1391 #ifndef WIN32_NATIVE
1392
1393 /* Set *TC to the parameters associated with the terminal FD.
1394    Return zero if all's well, or -1 if we ran into an error we
1395    couldn't deal with.  */
1396 int
1397 emacs_get_tty (int fd, struct emacs_tty *settings)
1398 {
1399   /* Retrieve the primary parameters - baud rate, character size, etcetera.  */
1400 #ifdef HAVE_TCATTR
1401   /* We have those nifty POSIX tcmumbleattr functions.  */
1402   if (tcgetattr (fd, &settings->main) < 0)
1403     return -1;
1404
1405 #elif defined HAVE_TERMIO
1406   /* The SYSV-style interface?  */
1407   if (ioctl (fd, TCGETA, &settings->main) < 0)
1408     return -1;
1409
1410 #elif !defined (WIN32_NATIVE)
1411   /* I give up - I hope you have the BSD ioctls.  */
1412   if (ioctl (fd, TIOCGETP, &settings->main) < 0)
1413     return -1;
1414 #endif /* HAVE_TCATTR */
1415
1416   /* Suivant - Do we have to get struct ltchars data?  */
1417 #ifdef HAVE_LTCHARS
1418   if (ioctl (fd, TIOCGLTC, &settings->ltchars) < 0)
1419     return -1;
1420 #endif
1421
1422   /* How about a struct tchars and a wordful of lmode bits?  */
1423 #ifdef HAVE_TCHARS
1424   if (ioctl (fd, TIOCGETC, &settings->tchars) < 0
1425       || ioctl (fd, TIOCLGET, &settings->lmode) < 0)
1426     return -1;
1427 #endif
1428
1429   /* We have survived the tempest.  */
1430   return 0;
1431 }
1432
1433 /* Set the parameters of the tty on FD according to the contents of
1434    *SETTINGS.  If FLUSHP is non-zero, we discard input.
1435    Return 0 if all went well, and -1 if anything failed.
1436    #### All current callers use FLUSHP == 0. */
1437
1438 int
1439 emacs_set_tty (int fd, struct emacs_tty *settings, int flushp)
1440 {
1441   /* Set the primary parameters - baud rate, character size, etcetera.  */
1442 #ifdef HAVE_TCATTR
1443   int i;
1444   /* We have those nifty POSIX tcmumbleattr functions.
1445      William J. Smith <wjs@wiis.wang.com> writes:
1446      "POSIX 1003.1 defines tcsetattr() to return success if it was
1447      able to perform any of the requested actions, even if some
1448      of the requested actions could not be performed.
1449      We must read settings back to ensure tty setup properly.
1450      AIX requires this to keep tty from hanging occasionally."  */
1451   /* This makes sure that we don't loop indefinitely in here.  */
1452   for (i = 0 ; i < 10 ; i++)
1453     if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
1454       {
1455         if (errno == EINTR)
1456           continue;
1457         else
1458           return -1;
1459       }
1460     else
1461       {
1462         struct termios new;
1463
1464         /* Get the current settings, and see if they're what we asked for.  */
1465         tcgetattr (fd, &new);
1466         /* We cannot use memcmp on the whole structure here because under
1467          * aix386 the termios structure has some reserved field that may
1468          * not be filled in.
1469          */
1470         if (   new.c_iflag == settings->main.c_iflag
1471             && new.c_oflag == settings->main.c_oflag
1472             && new.c_cflag == settings->main.c_cflag
1473             && new.c_lflag == settings->main.c_lflag
1474             && memcmp(new.c_cc, settings->main.c_cc, NCCS) == 0)
1475           break;
1476         else
1477           continue;
1478       }
1479 #elif defined HAVE_TERMIO
1480   /* The SYSV-style interface?  */
1481   if (ioctl (fd, flushp ? TCSETAF : TCSETAW, &settings->main) < 0)
1482     return -1;
1483
1484 #elif !defined (WIN32_NATIVE)
1485   /* I give up - I hope you have the BSD ioctls.  */
1486   if (ioctl (fd, (flushp) ? TIOCSETP : TIOCSETN, &settings->main) < 0)
1487     return -1;
1488 #endif /* HAVE_TCATTR */
1489
1490   /* Suivant - Do we have to get struct ltchars data?  */
1491 #ifdef HAVE_LTCHARS
1492   if (ioctl (fd, TIOCSLTC, &settings->ltchars) < 0)
1493     return -1;
1494 #endif
1495
1496   /* How about a struct tchars and a wordful of lmode bits?  */
1497 #ifdef HAVE_TCHARS
1498   if (ioctl (fd, TIOCSETC, &settings->tchars) < 0
1499       || ioctl (fd, TIOCLSET, &settings->lmode) < 0)
1500     return -1;
1501 #endif
1502
1503   /* We have survived the tempest.  */
1504   return 0;
1505 }
1506
1507 #endif /* WIN32_NATIVE */
1508 \f
1509 /* ------------------------------------------------------ */
1510 /*                 Initializing a device                  */
1511 /* ------------------------------------------------------ */
1512
1513 #ifdef HAVE_TTY
1514
1515 /* This may also be defined in stdio,
1516    but if so, this does no harm,
1517    and using the same name avoids wasting the other one's space.  */
1518
1519 #if ((defined(USG) || defined(DGUX)) && !defined(__STDC__))
1520 char _sobuf[BUFSIZ+8];
1521 #elif (defined(USG) && !defined(LINUX) && !defined(_SCO_DS)) || defined(IRIX5)
1522 extern unsigned char _sobuf[BUFSIZ+8];
1523 #else
1524 char _sobuf[BUFSIZ];
1525 #endif
1526
1527 #if defined (TIOCGLTC) && defined (HAVE_LTCHARS) /* HAVE_LTCHARS */
1528 static struct ltchars new_ltchars = {-1,-1,-1,-1,-1,-1};
1529 #endif
1530 #ifdef TIOCGETC /* HAVE_TCHARS */
1531 #ifdef HAVE_TCHARS
1532 static struct tchars new_tchars = {-1,-1,-1,-1,-1,-1};
1533 #endif
1534 #endif
1535
1536 static void
1537 tty_init_sys_modes_on_device (struct device *d)
1538 {
1539   struct emacs_tty tty;
1540   int input_fd, output_fd;
1541   struct console *con = XCONSOLE (DEVICE_CONSOLE (d));
1542
1543   input_fd = CONSOLE_TTY_DATA (con)->infd;
1544   output_fd = CONSOLE_TTY_DATA (con)->outfd;
1545
1546   emacs_get_tty (input_fd, &CONSOLE_TTY_DATA (con)->old_tty);
1547   tty = CONSOLE_TTY_DATA (con)->old_tty;
1548
1549   con->tty_erase_char = Qnil;
1550
1551 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
1552   /* after all those years... */
1553   con->tty_erase_char = make_char (tty.main.c_cc[VERASE]);
1554 #ifdef DGUX
1555   /* This allows meta to be sent on 8th bit.  */
1556   tty.main.c_iflag &= ~INPCK;   /* don't check input for parity */
1557 #endif
1558   tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1559   tty.main.c_iflag &= ~ICRNL;   /* Disable map of CR to NL on input */
1560 #ifdef ISTRIP
1561   tty.main.c_iflag &= ~ISTRIP;  /* don't strip 8th bit on input */
1562 #endif
1563   tty.main.c_lflag &= ~ECHO;    /* Disable echo */
1564   tty.main.c_lflag &= ~ICANON;  /* Disable erase/kill processing */
1565 #ifdef IEXTEN
1566   tty.main.c_lflag &= ~IEXTEN;  /* Disable other editing characters.  */
1567 #endif
1568   tty.main.c_lflag |= ISIG;     /* Enable signals */
1569   if (TTY_FLAGS (con).flow_control)
1570     {
1571       tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1572 #ifdef IXANY
1573       tty.main.c_iflag &= ~IXANY;
1574 #endif /* IXANY */
1575     }
1576   else
1577     tty.main.c_iflag &= ~IXON;  /* Disable start/stop output control */
1578   tty.main.c_oflag &= ~ONLCR;   /* Disable map of NL to CR-NL
1579                                    on output */
1580   tty.main.c_oflag &= ~TAB3;    /* Disable tab expansion */
1581 #ifdef CS8
1582   if (TTY_FLAGS (con).meta_key)
1583     {
1584       tty.main.c_cflag |= CS8;  /* allow 8th bit on input */
1585       tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1586     }
1587 #endif
1588   if (CONSOLE_TTY_DATA (con)->controlling_terminal)
1589     {
1590       tty.main.c_cc[VINTR] =
1591         CONSOLE_QUIT_CHAR (con); /* C-g (usually) gives SIGINT */
1592       /* Set up C-g for both SIGQUIT and SIGINT.
1593          We don't know which we will get, but we handle both alike
1594          so which one it really gives us does not matter.  */
1595       tty.main.c_cc[VQUIT] = CONSOLE_QUIT_CHAR (con);
1596     }
1597   else
1598     {
1599       tty.main.c_cc[VINTR] = _POSIX_VDISABLE;
1600       tty.main.c_cc[VQUIT] = _POSIX_VDISABLE;
1601     }
1602   tty.main.c_cc[VMIN] = 1;      /* Input should wait for at
1603                                    least 1 char */
1604   tty.main.c_cc[VTIME] = 0;     /* no matter how long that takes.  */
1605 #ifdef VSWTCH
1606   tty.main.c_cc[VSWTCH] = _POSIX_VDISABLE; /* Turn off shell layering use
1607                                               of C-z */
1608 #endif /* VSWTCH */
1609   /* There was some conditionalizing here on (mips or TCATTR), but
1610      I think that's wrong.  There was one report of C-y (DSUSP) not being
1611      disabled on HP9000s700 systems, and this might fix it. */
1612 #ifdef VSUSP
1613   tty.main.c_cc[VSUSP] = _POSIX_VDISABLE; /* Turn off mips handling of C-z. */
1614 #endif /* VSUSP */
1615 #ifdef V_DSUSP
1616   tty.main.c_cc[V_DSUSP] = _POSIX_VDISABLE; /* Turn off mips handling of C-y. */
1617 #endif /* V_DSUSP */
1618 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP.  */
1619   tty.main.c_cc[VDSUSP] = _POSIX_VDISABLE;
1620 #endif /* VDSUSP */
1621 #ifdef VLNEXT
1622   tty.main.c_cc[VLNEXT] = _POSIX_VDISABLE;
1623 #endif /* VLNEXT */
1624 #ifdef VREPRINT
1625   tty.main.c_cc[VREPRINT] = _POSIX_VDISABLE;
1626 #endif /* VREPRINT */
1627 #ifdef VWERASE
1628   tty.main.c_cc[VWERASE] = _POSIX_VDISABLE;
1629 #endif /* VWERASE */
1630 #ifdef VDISCARD
1631   tty.main.c_cc[VDISCARD] = _POSIX_VDISABLE;
1632 #endif /* VDISCARD */
1633 #ifdef VSTART
1634   tty.main.c_cc[VSTART] = _POSIX_VDISABLE;
1635 #endif /* VSTART */
1636 #ifdef VSTRT
1637   tty.main.c_cc[VSTRT] = _POSIX_VDISABLE; /* called VSTRT on some systems */
1638 #endif /* VSTART */
1639 #ifdef VSTOP
1640   tty.main.c_cc[VSTOP] = _POSIX_VDISABLE;
1641 #endif /* VSTOP */
1642 #ifdef SET_LINE_DISCIPLINE
1643   /* Need to explicitly request TERMIODISC line discipline or
1644      Ultrix's termios does not work correctly.  */
1645   tty.main.c_line = SET_LINE_DISCIPLINE;
1646 #endif
1647
1648 #ifdef AIX
1649 #ifndef IBMR2AIX
1650   /* AIX enhanced edit loses NULs, so disable it. */
1651   tty.main.c_line = 0;
1652   tty.main.c_iflag &= ~ASCEDIT;
1653 #else
1654   tty.main.c_cc[VSTRT] = 255;
1655   tty.main.c_cc[VSTOP] = 255;
1656   tty.main.c_cc[VSUSP] = 255;
1657   tty.main.c_cc[VDSUSP] = 255;
1658 #endif /* IBMR2AIX */
1659   /* Also, PTY overloads NUL and BREAK.
1660      don't ignore break, but don't signal either, so it looks like NUL.
1661      This really serves a purpose only if running in an XTERM window
1662      or via TELNET or the like, but does no harm elsewhere.  */
1663   tty.main.c_iflag &= ~IGNBRK;
1664   tty.main.c_iflag &= ~BRKINT;
1665 #endif /* AIX */
1666 #else /* if not HAVE_TERMIO */
1667 #if !defined (WIN32_NATIVE)
1668   con->tty_erase_char = make_char (tty.main.sg_erase);
1669   tty.main.sg_flags &= ~(ECHO | CRMOD | XTABS);
1670   if (TTY_FLAGS (con).meta_key)
1671     tty.main.sg_flags |= ANYP;
1672   /* #### should we be using RAW mode here? */
1673   tty.main.sg_flags |= /* interrupt_input ? RAW : */ CBREAK;
1674 #endif /* not WIN32_NATIVE */
1675 #endif /* not HAVE_TERMIO */
1676
1677   /* If going to use CBREAK mode, we must request C-g to interrupt
1678      and turn off start and stop chars, etc.  If not going to use
1679      CBREAK mode, do this anyway so as to turn off local flow
1680      control for user coming over network on 4.2; in this case,
1681      only t_stopc and t_startc really matter.  */
1682 #ifndef HAVE_TERMIO
1683 #ifdef HAVE_TCHARS
1684   /* Note: if not using CBREAK mode, it makes no difference how we
1685      set this */
1686   tty.tchars = new_tchars;
1687   tty.tchars.t_intrc = CONSOLE_QUIT_CHAR (con);
1688   if (TTY_FLAGS (con).flow_control)
1689     {
1690       tty.tchars.t_startc = '\021';
1691       tty.tchars.t_stopc = '\023';
1692     }
1693
1694   tty.lmode = LDECCTQ | LLITOUT | LPASS8 | LNOFLSH |
1695     CONSOLE_TTY_DATA (con)->old_tty.lmode;
1696
1697 #if defined (ultrix) || defined (__bsdi__)
1698   /* Under Ultrix 4.2a, leaving this out doesn't seem to hurt
1699      anything, and leaving it in breaks the meta key.  Go figure.  */
1700   /* Turning off ONLCR is enough under BSD/386.  Leave the general
1701      output post-processing flag alone since for some reason it
1702      doesn't get reset after XEmacs goes away. */
1703   tty.lmode &= ~LLITOUT;
1704 #endif
1705
1706 #endif /* HAVE_TCHARS */
1707 #endif /* not HAVE_TERMIO */
1708
1709 #ifdef HAVE_LTCHARS
1710   tty.ltchars = new_ltchars;
1711 #endif /* HAVE_LTCHARS */
1712
1713   emacs_set_tty (input_fd, &tty, 0);
1714
1715   /* This code added to insure that, if flow-control is not to be used,
1716      we have an unlocked terminal at the start. */
1717
1718 #ifdef TCXONC
1719   if (!TTY_FLAGS (con).flow_control) ioctl (input_fd, TCXONC, 1);
1720 #endif
1721 #ifdef TIOCSTART
1722   if (!TTY_FLAGS (con).flow_control) ioctl (input_fd, TIOCSTART, 0);
1723 #endif
1724
1725 #if defined (HAVE_TERMIOS) || defined (HPUX9)
1726 #ifdef TCOON
1727   if (!TTY_FLAGS (con).flow_control) tcflow (input_fd, TCOON);
1728 #endif
1729 #endif
1730 #ifdef AIXHFT
1731   hft_init (con);
1732 #ifdef IBMR2AIX
1733   {
1734     /* IBM's HFT device usually thinks a ^J should be LF/CR.
1735        We need it to be only LF.  This is the way that is
1736        done. */
1737     struct termio tty;
1738
1739     if (ioctl (output_fd, HFTGETID, &tty) != -1)
1740       write (output_fd, "\033[20l", 5);
1741   }
1742 #endif
1743 #endif
1744
1745 #if 0 /* We do our own buffering with lstreams. */
1746 #ifdef _IOFBF
1747   /* This symbol is defined on recent USG systems.
1748      Someone says without this call USG won't really buffer the file
1749      even with a call to setbuf. */
1750   setvbuf (CONSOLE_TTY_DATA (con)->outfd, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1751 #else
1752   setbuf (CONSOLE_TTY_DATA (con)->outfd, (char *) _sobuf);
1753 #endif
1754 #endif
1755   set_tty_modes (con);
1756 }
1757
1758 #endif /* HAVE_TTY */
1759
1760 void
1761 init_one_device (struct device *d)
1762 {
1763 #ifdef HAVE_TTY
1764   if (DEVICE_TTY_P (d))
1765     tty_init_sys_modes_on_device (d);
1766 #endif
1767 #if defined(SIGIO) && !defined(BROKEN_SIGIO)
1768   if (!DEVICE_STREAM_P (d))
1769     {
1770       init_sigio_on_device (d);
1771       request_sigio_on_device (d);
1772     }
1773 #endif
1774 }
1775
1776 void
1777 init_one_console (struct console *con)
1778 {
1779   Lisp_Object devcons;
1780
1781   CONSOLE_DEVICE_LOOP (devcons, con)
1782     {
1783       struct device *d = XDEVICE (XCAR (devcons));
1784
1785       init_one_device (d);
1786     }
1787 }
1788
1789 void
1790 reinit_initial_console (void)
1791 {
1792   munge_process_groups ();
1793   if (CONSOLEP (Vcontrolling_terminal) &&
1794       CONSOLE_LIVE_P (XCONSOLE (Vcontrolling_terminal)))
1795     init_one_console (XCONSOLE (Vcontrolling_terminal));
1796 }
1797
1798 \f
1799 /* ------------------------------------------------------ */
1800 /*                   Other TTY functions                  */
1801 /* ------------------------------------------------------ */
1802
1803 #ifdef HAVE_TTY
1804
1805 #if 0 /* not currently used */
1806
1807 /* Return nonzero if safe to use tabs in output.
1808    At the time this is called, init_sys_modes has not been done yet.  */
1809
1810 int
1811 tabs_safe_p (struct device *d)
1812 {
1813 #ifdef HAVE_TTY
1814   if (DEVICE_TTY_P (d))
1815     {
1816       struct emacs_tty tty;
1817
1818       emacs_get_tty (DEVICE_INFD (d), &tty);
1819       return EMACS_TTY_TABS_OK (&tty);
1820     }
1821 #endif
1822   return 1;
1823 }
1824
1825 #endif /* 0 */
1826
1827 /* Get terminal size from system.
1828    Store number of lines into *heightp and width into *widthp.
1829    If zero or a negative number is stored, the value is not valid.  */
1830
1831 void
1832 get_tty_device_size (struct device *d, int *widthp, int *heightp)
1833 {
1834   int input_fd = DEVICE_INFD (d);
1835
1836   assert (DEVICE_TTY_P (d));
1837
1838 #ifdef TIOCGWINSZ
1839   {
1840     /* BSD-style.  */
1841     struct winsize size;
1842
1843     if (ioctl (input_fd, TIOCGWINSZ, &size) == -1)
1844       *widthp = *heightp = 0;
1845     else
1846       {
1847         *widthp = size.ws_col;
1848         *heightp = size.ws_row;
1849       }
1850   }
1851 #elif defined TIOCGSIZE
1852   {
1853     /* SunOS - style.  */
1854     struct ttysize size;
1855
1856     if (ioctl (input_fd, TIOCGSIZE, &size) == -1)
1857       *widthp = *heightp = 0;
1858     else
1859       {
1860         *widthp = size.ts_cols;
1861         *heightp = size.ts_lines;
1862       }
1863   }
1864 #else /* system doesn't know size */
1865
1866   *widthp = 0;
1867   *heightp = 0;
1868
1869 #endif /* not !TIOCGWINSZ */
1870 }
1871
1872 #endif /* HAVE_TTY */
1873
1874 \f
1875 /* ------------------------------------------------------ */
1876 /*                   Is device 8 bit ?                    */
1877 /* ------------------------------------------------------ */
1878
1879 #ifdef HAVE_TTY
1880
1881 int
1882 eight_bit_tty (struct device *d)
1883 {
1884   struct emacs_tty s;
1885   int input_fd;
1886   int eight_bit = 0;
1887
1888   assert (DEVICE_TTY_P (d));
1889   input_fd = DEVICE_INFD (d);
1890
1891   emacs_get_tty (input_fd, &s);
1892
1893 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
1894   eight_bit = (s.main.c_cflag & CSIZE) == CS8;
1895 #else
1896   eight_bit = 0;        /* I don't know how to do it */
1897 #endif
1898   return eight_bit;
1899 }
1900
1901 #endif /* HAVE_TTY */
1902
1903 \f
1904 /* ------------------------------------------------------ */
1905 /*                   Resetting a device                   */
1906 /* ------------------------------------------------------ */
1907
1908 #ifdef HAVE_TTY
1909
1910 /* Prepare the terminal for exiting Emacs; move the cursor to the
1911    bottom of the frame, turn off interrupt-driven I/O, etc.  */
1912 static void
1913 tty_reset_sys_modes_on_device (struct device *d)
1914 {
1915   int input_fd, output_fd;
1916   struct console *con = XCONSOLE (DEVICE_CONSOLE (d));
1917
1918   input_fd = CONSOLE_TTY_DATA (con)->infd;
1919   output_fd = CONSOLE_TTY_DATA (con)->outfd;
1920
1921 #if defined (IBMR2AIX) && defined (AIXHFT)
1922   {
1923     /* HFT consoles normally use ^J as a LF/CR.  We forced it to
1924        do the LF only.  Now, we need to reset it. */
1925     struct termio tty;
1926
1927     if (ioctl (output_fd, HFTGETID, &tty) != -1)
1928       write (output_fd, "\033[20h", 5);
1929   }
1930 #endif
1931
1932   tty_redisplay_shutdown (con);
1933   /* reset_tty_modes() flushes the connection at its end. */
1934   reset_tty_modes (con);
1935
1936 #if defined (BSD)
1937   /* Avoid possible loss of output when changing terminal modes.  */
1938   fsync (output_fd);
1939 #endif
1940
1941   while (emacs_set_tty (input_fd, &CONSOLE_TTY_DATA (con)->old_tty, 0)
1942          < 0 && errno == EINTR)
1943     ;
1944
1945 #ifdef SET_LINE_DISCIPLINE
1946   /* Ultrix's termios *ignores* any line discipline except TERMIODISC.
1947      A different old line discipline is therefore not restored, yet.
1948      Restore the old line discipline by hand.  */
1949   ioctl (input_fd, TIOCSETD, &old_tty.main.c_line);
1950 #endif
1951
1952 #ifdef AIXHFT
1953   hft_reset (con);
1954 #endif
1955
1956 }
1957
1958 #endif /* HAVE_TTY */
1959
1960 void
1961 reset_one_device (struct device *d)
1962 {
1963 #ifdef HAVE_TTY
1964   if (DEVICE_TTY_P (d))
1965     tty_reset_sys_modes_on_device (d);
1966   else
1967 #endif
1968   if (DEVICE_STREAM_P (d))
1969     fflush (CONSOLE_STREAM_DATA (XCONSOLE (DEVICE_CONSOLE (d)))->out);
1970 #if defined(SIGIO) && !defined(BROKEN_SIGIO)
1971   if (!DEVICE_STREAM_P (d))
1972     {
1973       unrequest_sigio_on_device (d);
1974       reset_sigio_on_device (d);
1975     }
1976 #endif
1977 }
1978
1979 void
1980 reset_one_console (struct console *con)
1981 {
1982   /* Note: this can be called during GC. */
1983   Lisp_Object devcons;
1984
1985   CONSOLE_DEVICE_LOOP (devcons, con)
1986     {
1987       struct device *d = XDEVICE (XCAR (devcons));
1988
1989       reset_one_device (d);
1990     }
1991 }
1992
1993 void
1994 reset_all_consoles (void)
1995 {
1996   /* Note: this can be called during GC. */
1997   Lisp_Object concons;
1998
1999   CONSOLE_LOOP (concons)
2000     {
2001       struct console *con = XCONSOLE (XCAR (concons));
2002
2003       reset_one_console (con);
2004     }
2005
2006   unmunge_process_groups ();
2007 }
2008
2009 void
2010 reset_initial_console (void)
2011 {
2012   if (CONSOLEP (Vcontrolling_terminal) &&
2013       CONSOLE_LIVE_P (XCONSOLE (Vcontrolling_terminal)))
2014     reset_one_console (XCONSOLE (Vcontrolling_terminal));
2015   unmunge_process_groups ();
2016 }
2017
2018 \f
2019 /* ------------------------------------------------------ */
2020 /*                 extra TTY stuff under AIX              */
2021 /* ------------------------------------------------------ */
2022
2023 #ifdef AIXHFT
2024
2025 /* Called from init_sys_modes.  */
2026 static void
2027 hft_init (struct console *con)
2028 {
2029   int junk;
2030   int input_fd;
2031
2032   assert (CONSOLE_TTY_P (con));
2033   input_fd = CONSOLE_TTY_DATA (con)->infd;
2034
2035   /* If we're not on an HFT we shouldn't do any of this.  We determine
2036      if we are on an HFT by trying to get an HFT error code.  If this
2037      call fails, we're not on an HFT. */
2038 #ifdef IBMR2AIX
2039   if (ioctl (input_fd, HFQERROR, &junk) < 0)
2040     return;
2041 #else /* not IBMR2AIX */
2042   if (ioctl (input_fd, HFQEIO, 0) < 0)
2043     return;
2044 #endif /* not IBMR2AIX */
2045
2046   /* On AIX the default hft keyboard mapping uses backspace rather than delete
2047      as the rubout key's ASCII code.  Here this is changed.  The bug is that
2048      there's no way to determine the old mapping, so in reset_one_console
2049      we need to assume that the normal map had been present.  Of course, this
2050      code also doesn't help if on a terminal emulator which doesn't understand
2051      HFT VTD's. */
2052   {
2053     struct hfbuf buf;
2054     struct hfkeymap keymap;
2055
2056     buf.hf_bufp = (char *)&keymap;
2057     buf.hf_buflen = sizeof (keymap);
2058     keymap.hf_nkeys = 2;
2059     keymap.hfkey[0].hf_kpos = 15;
2060     keymap.hfkey[0].hf_kstate = HFMAPCHAR | HFSHFNONE;
2061 #ifdef IBMR2AIX
2062     keymap.hfkey[0].hf_keyidh = '<';
2063 #else /* not IBMR2AIX */
2064     keymap.hfkey[0].hf_page = '<';
2065 #endif /* not IBMR2AIX */
2066     keymap.hfkey[0].hf_char = 127;
2067     keymap.hfkey[1].hf_kpos = 15;
2068     keymap.hfkey[1].hf_kstate = HFMAPCHAR | HFSHFSHFT;
2069 #ifdef IBMR2AIX
2070     keymap.hfkey[1].hf_keyidh = '<';
2071 #else /* not IBMR2AIX */
2072     keymap.hfkey[1].hf_page = '<';
2073 #endif /* not IBMR2AIX */
2074     keymap.hfkey[1].hf_char = 127;
2075     hftctl (input_fd, HFSKBD, &buf);
2076   }
2077   /* #### Should probably set a console TTY flag here. */
2078 #if 0
2079   /* The HFT system on AIX doesn't optimize for scrolling, so it's really ugly
2080      at times. */
2081   line_ins_del_ok = char_ins_del_ok = 0;
2082 #endif /* 0 */
2083 }
2084
2085 /* Reset the rubout key to backspace. */
2086
2087 static void
2088 hft_reset (struct console *con)
2089 {
2090   struct hfbuf buf;
2091   struct hfkeymap keymap;
2092   int junk;
2093   int input_fd;
2094
2095   assert (CONSOLE_TTY_P (con));
2096   input_fd = CONSOLE_TTY_DATA (con)->infd;
2097
2098 #ifdef IBMR2AIX
2099   if (ioctl (input_fd, HFQERROR, &junk) < 0)
2100     return;
2101 #else /* not IBMR2AIX */
2102   if (ioctl (input_fd, HFQEIO, 0) < 0)
2103     return;
2104 #endif /* not IBMR2AIX */
2105
2106   buf.hf_bufp = (char *)&keymap;
2107   buf.hf_buflen = sizeof (keymap);
2108   keymap.hf_nkeys = 2;
2109   keymap.hfkey[0].hf_kpos = 15;
2110   keymap.hfkey[0].hf_kstate = HFMAPCHAR | HFSHFNONE;
2111 #ifdef IBMR2AIX
2112   keymap.hfkey[0].hf_keyidh = '<';
2113 #else /* not IBMR2AIX */
2114   keymap.hfkey[0].hf_page = '<';
2115 #endif /* not IBMR2AIX */
2116   keymap.hfkey[0].hf_char = 8;
2117   keymap.hfkey[1].hf_kpos = 15;
2118   keymap.hfkey[1].hf_kstate = HFMAPCHAR | HFSHFSHFT;
2119 #ifdef IBMR2AIX
2120   keymap.hfkey[1].hf_keyidh = '<';
2121 #else /* not IBMR2AIX */
2122   keymap.hfkey[1].hf_page = '<';
2123 #endif /* not IBMR2AIX */
2124   keymap.hfkey[1].hf_char = 8;
2125   hftctl (input_fd, HFSKBD, &buf);
2126 }
2127
2128 #endif /* AIXHFT */
2129
2130 \f
2131 /************************************************************************/
2132 /*                    limits of text/data segments                      */
2133 /************************************************************************/
2134
2135 #if !defined(CANNOT_DUMP) && !defined(PDUMP)
2136 #define NEED_STARTS
2137 #endif
2138
2139 #ifndef SYSTEM_MALLOC
2140 #ifndef NEED_STARTS
2141 #define NEED_STARTS
2142 #endif
2143 #endif
2144
2145 #ifdef NEED_STARTS
2146 /* Some systems that cannot dump also cannot implement these.  */
2147
2148 /*
2149  *      Return the address of the start of the text segment prior to
2150  *      doing an unexec.  After unexec the return value is undefined.
2151  *      See crt0.c for further explanation and _start.
2152  *
2153  */
2154
2155 #if !defined(HAVE_TEXT_START) && !defined(PDUMP)
2156
2157 EXTERN_C int _start (void);
2158
2159 char *
2160 start_of_text (void)
2161 {
2162 #ifdef TEXT_START
2163   return (char *) TEXT_START;
2164 #else
2165   return (char *) _start;
2166 #endif /* TEXT_START */
2167 }
2168 #endif /* !defined(HAVE_TEXT_START) && !defined(PDUMP) */
2169
2170 /*
2171  *      Return the address of the start of the data segment prior to
2172  *      doing an unexec.  After unexec the return value is undefined.
2173  *      See crt0.c for further information and definition of data_start.
2174  *
2175  *      Apparently, on BSD systems this is etext at startup.  On
2176  *      USG systems (swapping) this is highly mmu dependent and
2177  *      is also dependent on whether or not the program is running
2178  *      with shared text.  Generally there is a (possibly large)
2179  *      gap between end of text and start of data with shared text.
2180  *
2181  *      On Uniplus+ systems with shared text, data starts at a
2182  *      fixed address.  Each port (from a given oem) is generally
2183  *      different, and the specific value of the start of data can
2184  *      be obtained via the UniPlus+ specific "uvar" system call,
2185  *      however the method outlined in crt0.c seems to be more portable.
2186  *
2187  *      Probably what will have to happen when a USG unexec is available,
2188  *      at least on UniPlus, is temacs will have to be made unshared so
2189  *      that text and data are contiguous.  Then once loadup is complete,
2190  *      unexec will produce a shared executable where the data can be
2191  *      at the normal shared text boundary and the startofdata variable
2192  *      will be patched by unexec to the correct value.
2193  *
2194  */
2195
2196 #if defined(ORDINARY_LINK) && !defined(MINGW)
2197 extern char **environ;
2198 #endif
2199
2200 void *
2201 start_of_data (void)
2202 {
2203 #ifdef DATA_START
2204   return ((char *) DATA_START);
2205 #else
2206 #ifdef ORDINARY_LINK
2207   /*
2208    * This is a hack.  Since we're not linking crt0.c or pre_crt0.c,
2209    * data_start isn't defined.  We take the address of environ, which
2210    * is known to live at or near the start of the system crt0.c, and
2211    * we don't sweat the handful of bytes that might lose.
2212    */
2213 #if defined (HEAP_IN_DATA) && !defined(PDUMP)
2214   extern char* static_heap_base;
2215   if (!initialized)
2216     return static_heap_base;
2217 #endif
2218   return((char *) &environ);
2219 #else
2220   extern int data_start;
2221   return ((char *) &data_start);
2222 #endif /* ORDINARY_LINK */
2223 #endif /* DATA_START */
2224 }
2225 #endif /* NEED_STARTS (not CANNOT_DUMP or not SYSTEM_MALLOC) */
2226
2227 #if !defined(CANNOT_DUMP) && !defined(PDUMP)
2228 /* Some systems that cannot dump also cannot implement these.  */
2229
2230 /*
2231  *      Return the address of the end of the text segment prior to
2232  *      doing an unexec.  After unexec the return value is undefined.
2233  */
2234
2235 char *
2236 end_of_text (void)
2237 {
2238 #ifdef TEXT_END
2239   return ((char *) TEXT_END);
2240 #else
2241   extern int etext;
2242   return ((char *) &etext);
2243 #endif
2244 }
2245
2246 /*
2247  *      Return the address of the end of the data segment prior to
2248  *      doing an unexec.  After unexec the return value is undefined.
2249  */
2250
2251 char *
2252 end_of_data (void)
2253 {
2254 #ifdef DATA_END
2255   return ((char *) DATA_END);
2256 #else
2257   extern int edata;
2258   return ((char *) &edata);
2259 #endif
2260 }
2261
2262 #endif /* !defined(CANNOT_DUMP) && !defined(PDUMP) */
2263
2264 \f
2265 /************************************************************************/
2266 /*                          get the system name                         */
2267 /************************************************************************/
2268
2269 /* init_system_name sets up the string for the Lisp function
2270    system-name to return. */
2271
2272 extern Lisp_Object Vsystem_name;
2273
2274 void
2275 init_system_name (void)
2276 {
2277 #if defined (WIN32_NATIVE)
2278   char hostname [MAX_COMPUTERNAME_LENGTH + 1];
2279   size_t size = sizeof (hostname);
2280   GetComputerName (hostname, &size);
2281   Vsystem_name = build_string (hostname);
2282 #elif !defined (HAVE_GETHOSTNAME)
2283   struct utsname uts;
2284   uname (&uts);
2285   Vsystem_name = build_string (uts.nodename);
2286 #else /* HAVE_GETHOSTNAME */
2287   unsigned int hostname_size = 256;
2288   char *hostname = (char *) alloca (hostname_size);
2289
2290   /* Try to get the host name; if the buffer is too short, try
2291      again.  Apparently, the only indication gethostname gives of
2292      whether the buffer was large enough is the presence or absence
2293      of a '\0' in the string.  Eech.  */
2294   for (;;)
2295     {
2296       gethostname (hostname, hostname_size - 1);
2297       hostname[hostname_size - 1] = '\0';
2298
2299       /* Was the buffer large enough for the '\0'?  */
2300       if (strlen (hostname) < (size_t) (hostname_size - 1))
2301         break;
2302
2303       hostname_size <<= 1;
2304       hostname = (char *) alloca (hostname_size);
2305     }
2306 # if defined( HAVE_SOCKETS) && !defined(BROKEN_CYGWIN)
2307   /* Turn the hostname into the official, fully-qualified hostname.
2308      Don't do this if we're going to dump; this can confuse system
2309      libraries on some machines and make the dumped emacs core dump. */
2310 #  ifndef CANNOT_DUMP
2311   if (initialized)
2312 #  endif /* not CANNOT_DUMP */
2313     if (!strchr (hostname, '.'))
2314       {
2315 #  if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
2316         struct hostent *hp = NULL;
2317         int count;
2318 #   ifdef TRY_AGAIN
2319         for (count = 0; count < 10; count++)
2320           {
2321             h_errno = 0;
2322 #   endif
2323             /* Some systems can't handle SIGALARM/SIGIO in gethostbyname(). */
2324             stop_interrupts ();
2325             hp = gethostbyname (hostname);
2326             start_interrupts ();
2327 #   ifdef TRY_AGAIN
2328             if (! (hp == 0 && h_errno == TRY_AGAIN))
2329               break;
2330             Fsleep_for (make_int (1));
2331           }
2332 #   endif
2333         if (hp)
2334           {
2335             const char *fqdn = (const char *) hp->h_name;
2336
2337             if (!strchr (fqdn, '.'))
2338               {
2339                 /* We still don't have a fully qualified domain name.
2340                    Try to find one in the list of alternate names */
2341                 char **alias = hp->h_aliases;
2342                 while (*alias && !strchr (*alias, '.'))
2343                   alias++;
2344                 if (*alias)
2345                   fqdn = *alias;
2346               }
2347             hostname = (char *) alloca (strlen (fqdn) + 1);
2348             strcpy (hostname, fqdn);
2349           }
2350 #  else /* !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
2351         struct addrinfo hints, *res;
2352
2353         xzero (hints);
2354         hints.ai_flags = AI_CANONNAME;
2355         hints.ai_family = AF_UNSPEC;
2356         hints.ai_socktype = SOCK_STREAM;
2357         hints.ai_protocol = 0;
2358         if (!getaddrinfo (hostname, NULL, &hints, &res))
2359           {
2360             hostname = (char *) alloca (strlen (res->ai_canonname) + 1);
2361             strcpy (hostname, res->ai_canonname);
2362
2363             freeaddrinfo (res);
2364           }
2365 #  endif  /* !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
2366       }
2367 # endif /* HAVE_SOCKETS */
2368   Vsystem_name = build_string (hostname);
2369 #endif /* HAVE_GETHOSTNAME  */
2370   {
2371     Bufbyte *p;
2372     Bytecount i;
2373
2374     for (i = 0, p = XSTRING_DATA (Vsystem_name);
2375          i < XSTRING_LENGTH (Vsystem_name);
2376          i++, p++)
2377       {
2378         if (*p == ' ' || *p == '\t')
2379           *p = '-';
2380       }
2381   }
2382 }
2383
2384 \f
2385 /************************************************************************/
2386 /*                        Emulation of select()                         */
2387 /************************************************************************/
2388
2389 #ifndef HAVE_SELECT
2390
2391 ERROR: XEmacs requires a working select().
2392
2393 #endif /* not HAVE_SELECT */
2394
2395 \f
2396 /************************************************************************/
2397 /*                      Emulation of signal stuff                       */
2398 /************************************************************************/
2399
2400 /* BSD 4.1 crap deleted.  4.2 was released in 1983, for God's sake!  I
2401    can't imagine that anyone is actually running that OS any more.
2402    You can't use X under it (I think) because there's no select().
2403    Anyway, the signal stuff has all been changed.  If someone wants to
2404    get this stuff working again, look in the FSF Emacs sources. */
2405
2406 /* POSIX signals support - DJB */
2407
2408 #ifdef HAVE_SIGPROCMASK
2409
2410 /* #### Is there any reason this is static global rather than local? */
2411 static struct sigaction new_action, old_action;
2412
2413 signal_handler_t
2414 sys_do_signal (int signal_number, signal_handler_t action)
2415 {
2416 #if 0
2417
2418   /* XEmacs works better if system calls are *not* restarted.
2419      This allows C-g to interrupt reads and writes, on most systems.
2420
2421      #### Another possibility is to just longjmp() out of the signal
2422      handler.  According to W.R. Stevens, this should be OK on all
2423      systems.  However, I don't want to deal with the potential
2424      evil ramifications of this at this point. */
2425
2426 #ifdef DGUX
2427   /* This gets us restartable system calls for efficiency.
2428      The "else" code will work as well. */
2429   return (berk_signal (signal_number, action));
2430 #else
2431   sigemptyset (&new_action.sa_mask);
2432   new_action.sa_handler = action;
2433 #if defined (SA_RESTART)
2434   /* Emacs mostly works better with restartable system services. If this
2435    * flag exists, we probably want to turn it on here.
2436    */
2437   new_action.sa_flags = SA_RESTART;
2438 #else
2439   new_action.sa_flags = 0;
2440 #endif
2441   sigaction (signal_number, &new_action, &old_action);
2442   return (old_action.sa_handler);
2443 #endif /* DGUX */
2444
2445 #else /* not 0 */
2446
2447   sigemptyset (&new_action.sa_mask);
2448   new_action.sa_handler = action;
2449 #if defined (SA_INTERRUPT) /* don't restart system calls, under SunOS */
2450   new_action.sa_flags = SA_INTERRUPT;
2451 #else
2452   new_action.sa_flags = 0;
2453 #endif
2454   sigaction (signal_number, &new_action, &old_action);
2455   return (signal_handler_t) (old_action.sa_handler);
2456
2457 #endif /* not 0 */
2458 }
2459
2460 #elif defined (HAVE_SIGBLOCK)
2461
2462 /* We use sigvec() rather than signal() if we have it, because
2463    it lets us specify interruptible system calls. */
2464 signal_handler_t
2465 sys_do_signal (int signal_number, signal_handler_t action)
2466 {
2467   struct sigvec vec, ovec;
2468
2469   vec.sv_handler = action;
2470   vec.sv_mask = 0;
2471 #ifdef SV_INTERRUPT /* don't restart system calls */
2472   vec.sv_flags = SV_INTERRUPT;
2473 #else
2474   vec.sv_flags = 0;
2475 #endif
2476
2477   sigvec (signal_number, &vec, &ovec);
2478
2479   return (ovec.sv_handler);
2480 }
2481
2482 #endif /* HAVE_SIGBLOCK (HAVE_SIGPROCMASK) */
2483
2484 \f
2485 /************************************************************************/
2486 /*           Emulation of strerror() and errno support                  */
2487 /************************************************************************/
2488
2489 #ifndef HAVE_STRERROR
2490
2491 #if !defined(NeXT) && !defined(__alpha) && !defined(MACH) && !defined(LINUX) && !defined(IRIX) && !defined(__NetBSD__)
2492 /* Linux added here by Raymond L. Toy <toy@alydar.crd.ge.com> for XEmacs. */
2493 /* Irix added here by gparker@sni-usa.com for XEmacs. */
2494 /* NetBSD added here by James R Grinter <jrg@doc.ic.ac.uk> for XEmacs */
2495 extern const char *sys_errlist[];
2496 extern int sys_nerr;
2497 #endif
2498
2499 #ifdef __NetBSD__
2500 extern char *sys_errlist[];
2501 extern int sys_nerr;
2502 #endif
2503
2504
2505 const char *
2506 strerror (int errnum)
2507 {
2508   if (errnum >= 0 && errnum < sys_nerr)
2509     return sys_errlist[errnum];
2510   return ((const char *) GETTEXT ("Unknown error"));
2511 }
2512
2513 #endif /* ! HAVE_STRERROR */
2514
2515 #ifdef WIN32_NATIVE
2516
2517 struct errentry {
2518   unsigned long oscode;  /* Win32 error */
2519   int errnocode;         /* unix errno */
2520 };
2521
2522 static struct errentry errtable[] = {
2523   {  ERROR_INVALID_FUNCTION,       EINVAL    },  /* 1 */
2524   {  ERROR_FILE_NOT_FOUND,         ENOENT    },  /* 2 */
2525   {  ERROR_PATH_NOT_FOUND,         ENOENT    },  /* 3 */
2526   {  ERROR_TOO_MANY_OPEN_FILES,    EMFILE    },  /* 4 */
2527   {  ERROR_ACCESS_DENIED,          EACCES    },  /* 5 */
2528   {  ERROR_INVALID_HANDLE,         EBADF     },  /* 6 */
2529   {  ERROR_ARENA_TRASHED,          ENOMEM    },  /* 7 */
2530   {  ERROR_NOT_ENOUGH_MEMORY,      ENOMEM    },  /* 8 */
2531   {  ERROR_INVALID_BLOCK,          ENOMEM    },  /* 9 */
2532   {  ERROR_BAD_ENVIRONMENT,        E2BIG     },  /* 10 */
2533   {  ERROR_BAD_FORMAT,             ENOEXEC   },  /* 11 */
2534   {  ERROR_INVALID_ACCESS,         EINVAL    },  /* 12 */
2535   {  ERROR_INVALID_DATA,           EINVAL    },  /* 13 */
2536   {  ERROR_INVALID_DRIVE,          ENOENT    },  /* 15 */
2537   {  ERROR_CURRENT_DIRECTORY,      EACCES    },  /* 16 */
2538   {  ERROR_NOT_SAME_DEVICE,        EXDEV     },  /* 17 */
2539   {  ERROR_NO_MORE_FILES,          ENOENT    },  /* 18 */
2540   {  ERROR_LOCK_VIOLATION,         EACCES    },  /* 33 */
2541   {  ERROR_BAD_NETPATH,            ENOENT    },  /* 53 */
2542   {  ERROR_NETWORK_ACCESS_DENIED,  EACCES    },  /* 65 */
2543   {  ERROR_BAD_NET_NAME,           ENOENT    },  /* 67 */
2544   {  ERROR_FILE_EXISTS,            EEXIST    },  /* 80 */
2545   {  ERROR_CANNOT_MAKE,            EACCES    },  /* 82 */
2546   {  ERROR_FAIL_I24,               EACCES    },  /* 83 */
2547   {  ERROR_INVALID_PARAMETER,      EINVAL    },  /* 87 */
2548   {  ERROR_NO_PROC_SLOTS,          EAGAIN    },  /* 89 */
2549   {  ERROR_DRIVE_LOCKED,           EACCES    },  /* 108 */
2550   {  ERROR_BROKEN_PIPE,            EPIPE     },  /* 109 */
2551   {  ERROR_DISK_FULL,              ENOSPC    },  /* 112 */
2552   {  ERROR_INVALID_TARGET_HANDLE,  EBADF     },  /* 114 */
2553   {  ERROR_INVALID_HANDLE,         EINVAL    },  /* 124 */
2554   {  ERROR_WAIT_NO_CHILDREN,       ECHILD    },  /* 128 */
2555   {  ERROR_CHILD_NOT_COMPLETE,     ECHILD    },  /* 129 */
2556   {  ERROR_DIRECT_ACCESS_HANDLE,   EBADF     },  /* 130 */
2557   {  ERROR_NEGATIVE_SEEK,          EINVAL    },  /* 131 */
2558   {  ERROR_SEEK_ON_DEVICE,         EACCES    },  /* 132 */
2559   {  ERROR_DIR_NOT_EMPTY,          ENOTEMPTY },  /* 145 */
2560   {  ERROR_NOT_LOCKED,             EACCES    },  /* 158 */
2561   {  ERROR_BAD_PATHNAME,           ENOENT    },  /* 161 */
2562   {  ERROR_MAX_THRDS_REACHED,      EAGAIN    },  /* 164 */
2563   {  ERROR_LOCK_FAILED,            EACCES    },  /* 167 */
2564   {  ERROR_ALREADY_EXISTS,         EEXIST    },  /* 183 */
2565   {  ERROR_FILENAME_EXCED_RANGE,   ENOENT    },  /* 206 */
2566   {  ERROR_NESTING_NOT_ALLOWED,    EAGAIN    },  /* 215 */
2567   {  ERROR_NOT_ENOUGH_QUOTA,       ENOMEM    }    /* 1816 */
2568 };
2569
2570 /* The following two constants must be the minimum and maximum
2571    values in the (contiguous) range of Exec Failure errors. */
2572 #define MIN_EXEC_ERROR ERROR_INVALID_STARTING_CODESEG
2573 #define MAX_EXEC_ERROR ERROR_INFLOOP_IN_RELOC_CHAIN
2574
2575 /* These are the low and high value in the range of errors that are
2576    access violations */
2577 #define MIN_EACCES_RANGE ERROR_WRITE_PROTECT
2578 #define MAX_EACCES_RANGE ERROR_SHARING_BUFFER_EXCEEDED
2579
2580 void
2581 mswindows_set_errno (unsigned long win32_error)
2582 {
2583   int i;
2584
2585   /* check the table for the OS error code */
2586   for (i = 0; i < countof (errtable); ++i)
2587     {
2588       if (win32_error == errtable[i].oscode)
2589         {
2590           errno = errtable[i].errnocode;
2591           return;
2592         }
2593     }
2594
2595   /* The error code wasn't in the table.  We check for a range of
2596    * EACCES errors or exec failure errors (ENOEXEC).  Otherwise EINVAL is
2597    * returned. */
2598   if (win32_error >= MIN_EACCES_RANGE && win32_error <= MAX_EACCES_RANGE)
2599     errno = EACCES;
2600   else if (win32_error >= MIN_EXEC_ERROR && win32_error <= MAX_EXEC_ERROR)
2601     errno = ENOEXEC;
2602   else
2603     errno = EINVAL;
2604 }
2605
2606 void
2607 mswindows_set_last_errno (void)
2608 {
2609   mswindows_set_errno (GetLastError ());
2610 }
2611
2612 #endif /* WIN32_NATIVE */
2613
2614 \f
2615 /************************************************************************/
2616 /*                    Encapsulations of system calls                    */
2617 /************************************************************************/
2618
2619 #define PATHNAME_CONVERT_OUT(path) \
2620   TO_EXTERNAL_FORMAT (C_STRING, (path), C_STRING_ALLOCA, (path), Qfile_name);
2621
2622 /***************** low-level calls ****************/
2623
2624 /*
2625  *      On USG systems the system calls are INTERRUPTIBLE by signals
2626  *      that the user program has elected to catch.  Thus the system call
2627  *      must be retried in these cases.  To handle this without massive
2628  *      changes in the source code, we remap the standard system call names
2629  *      to names for our own functions in sysdep.c that do the system call
2630  *      with retries.  Actually, for portability reasons, it is good
2631  *      programming practice, as this example shows, to limit all actual
2632  *      system calls to a single occurrence in the source.  Sure, this
2633  *      adds an extra level of function call overhead but it is almost
2634  *      always negligible.   Fred Fish, Unisoft Systems Inc.
2635  */
2636
2637 /* Ben sez: read Dick Gabriel's essay about the Worse Is Better
2638    approach to programming and its connection to the silly
2639    interruptible-system-call business.  To find it, look on
2640    Jamie's home page (http://www.jwz.org/worse-is-better.html). */
2641
2642 #ifdef ENCAPSULATE_OPEN
2643 int
2644 sys_open (const char *path, int oflag, ...)
2645 {
2646   int mode;
2647   va_list ap;
2648
2649   va_start (ap, oflag);
2650   mode = va_arg (ap, int);
2651   va_end (ap);
2652
2653   PATHNAME_CONVERT_OUT (path);
2654
2655 #ifdef WIN32_NATIVE
2656   /* Make all handles non-inheritable */
2657   oflag |= _O_NOINHERIT;
2658 #endif
2659
2660 #ifdef INTERRUPTIBLE_OPEN
2661   {
2662     int rtnval;
2663     while ((rtnval = open (path, oflag, mode)) == -1
2664            && (errno == EINTR))
2665       DO_NOTHING;
2666     return rtnval;
2667   }
2668 #else
2669   return open (path, oflag, mode);
2670 #endif
2671 }
2672 #endif /* ENCAPSULATE_OPEN */
2673
2674 /* Like sys_open, only when open() is interrupted by EINTR, check for
2675    QUIT.  This allows the callers of this function to be interrupted
2676    with C-g when, say, reading from named pipes.  However, this should
2677    be used with caution, as it can GC.
2678
2679    This function will not function as expected on systems where open()
2680    is not interrupted by C-g.  However, the worst that can happen is
2681    the fallback to simple open().  */
2682 int
2683 interruptible_open (const char *path, int oflag, int mode)
2684 {
2685   /* This function can GC */
2686   size_t len = strlen (path);
2687   char *nonreloc = (char *) alloca (len + 1);
2688
2689   /* Must copy PATH, because it might be the data of a Lisp_String,
2690      which could be relocated by GC when checking for QUIT.  */
2691   memcpy (nonreloc, path, len + 1);
2692
2693   PATHNAME_CONVERT_OUT (nonreloc);
2694
2695 #ifdef WIN32_NATIVE
2696   /* Make all handles non-inheritable */
2697   oflag |= _O_NOINHERIT;
2698 #endif
2699
2700   for (;;)
2701     {
2702       int rtnval = open (nonreloc, oflag, mode);
2703       if (!(rtnval == -1 && errno == EINTR))
2704         return rtnval;
2705       /* open() was interrupted.  Was QUIT responsible?  */
2706       QUIT;
2707     }
2708 }
2709
2710 #ifdef ENCAPSULATE_CLOSE
2711 int
2712 sys_close (int filedes)
2713 {
2714 #ifdef INTERRUPTIBLE_CLOSE
2715   int did_retry = 0;
2716   REGISTER int rtnval;
2717
2718   while ((rtnval = close (filedes)) == -1
2719          && (errno == EINTR))
2720     did_retry = 1;
2721
2722   /* If close is interrupted SunOS 4.1 may or may not have closed the
2723      file descriptor.  If it did the second close will fail with
2724      errno = EBADF.  That means we have succeeded.  */
2725   if (rtnval == -1 && did_retry && errno == EBADF)
2726     return 0;
2727
2728   return rtnval;
2729 #else
2730   return close (filedes);
2731 #endif
2732 }
2733 #endif /* ENCAPSULATE_CLOSE */
2734
2735 ssize_t
2736 sys_read_1 (int fildes, void *buf, size_t nbyte, int allow_quit)
2737 {
2738   ssize_t rtnval;
2739
2740   /* No harm in looping regardless of the INTERRUPTIBLE_IO setting. */
2741   while ((rtnval = read (fildes, buf, nbyte)) == -1
2742          && (errno == EINTR))
2743     {
2744       if (allow_quit)
2745         REALLY_QUIT;
2746     }
2747   return rtnval;
2748 }
2749
2750 #ifdef ENCAPSULATE_READ
2751 ssize_t
2752 sys_read (int fildes, void *buf, size_t nbyte)
2753 {
2754   return sys_read_1 (fildes, buf, nbyte, 0);
2755 }
2756 #endif /* ENCAPSULATE_READ */
2757
2758 ssize_t
2759 sys_write_1 (int fildes, const void *buf, size_t nbyte, int allow_quit)
2760 {
2761   ssize_t bytes_written = 0;
2762   const char *b = (const char *) buf;
2763
2764   /* No harm in looping regardless of the INTERRUPTIBLE_IO setting. */
2765   while (nbyte > 0)
2766     {
2767       ssize_t rtnval = write (fildes, b, nbyte);
2768
2769       if (allow_quit)
2770         REALLY_QUIT;
2771
2772       if (rtnval == -1)
2773         {
2774           if (errno == EINTR)
2775             continue;
2776           else
2777             return bytes_written ? bytes_written : -1;
2778         }
2779       b += rtnval;
2780       nbyte -= rtnval;
2781       bytes_written += rtnval;
2782     }
2783   return bytes_written;
2784 }
2785
2786 #ifdef ENCAPSULATE_WRITE
2787 ssize_t
2788 sys_write (int fildes, const void *buf, size_t nbyte)
2789 {
2790   return sys_write_1 (fildes, buf, nbyte, 0);
2791 }
2792 #endif /* ENCAPSULATE_WRITE */
2793
2794
2795 /**************** stdio calls ****************/
2796
2797 /* There is at least some evidence that the stdio calls are interruptible
2798    just like the normal system calls, at least on some systems.  In any
2799    case, it doesn't hurt to encapsulate them. */
2800
2801 /* #### Should also encapsulate fflush().
2802    #### Should conceivably encapsulate getchar() etc.  What a pain! */
2803
2804 #ifdef ENCAPSULATE_FOPEN
2805 FILE *
2806 sys_fopen (const char *path, const char *type)
2807 {
2808   PATHNAME_CONVERT_OUT (path);
2809 #if defined (WIN32_NATIVE)
2810   {
2811     int fd;
2812     int oflag;
2813     const char * type_save = type;
2814
2815     /* Force all file handles to be non-inheritable.  This is necessary to
2816        ensure child processes don't unwittingly inherit handles that might
2817        prevent future file access. */
2818
2819     if (type[0] == 'r')
2820       oflag = O_RDONLY;
2821     else if (type[0] == 'w' || type[0] == 'a')
2822       oflag = O_WRONLY | O_CREAT | O_TRUNC;
2823     else
2824       return 0;
2825
2826     /* Only do simplistic option parsing. */
2827     while (*++type)
2828       if (type[0] == '+')
2829         {
2830           oflag &= ~(O_RDONLY | O_WRONLY);
2831           oflag |= O_RDWR;
2832         }
2833       else if (type[0] == 'b')
2834         {
2835           oflag &= ~O_TEXT;
2836           oflag |= O_BINARY;
2837         }
2838       else if (type[0] == 't')
2839         {
2840           oflag &= ~O_BINARY;
2841           oflag |= O_TEXT;
2842         }
2843       else break;
2844
2845     fd = open (path, oflag | _O_NOINHERIT, 0644);
2846     if (fd < 0)
2847       return NULL;
2848
2849     return _fdopen (fd, type_save);
2850   }
2851 #elif defined (INTERRUPTIBLE_OPEN)
2852   {
2853     FILE *rtnval;
2854     while (!(rtnval = fopen (path, type)) && (errno == EINTR))
2855       DO_NOTHING;
2856     return rtnval;
2857   }
2858 #else
2859   return fopen (path, type);
2860 #endif
2861 }
2862 #endif /* ENCAPSULATE_FOPEN */
2863
2864
2865 #ifdef ENCAPSULATE_FCLOSE
2866 int
2867 sys_fclose (FILE *stream)
2868 {
2869 #ifdef INTERRUPTIBLE_CLOSE
2870   int rtnval;
2871
2872   while ((rtnval = fclose (stream)) == EOF
2873          && (errno == EINTR))
2874     ;
2875   return rtnval;
2876 #else
2877   return fclose (stream);
2878 #endif
2879 }
2880 #endif /* ENCAPSULATE_FCLOSE */
2881
2882
2883 #ifdef ENCAPSULATE_FREAD
2884 size_t
2885 sys_fread (void *ptr, size_t size, size_t nitem, FILE *stream)
2886 {
2887 #ifdef INTERRUPTIBLE_IO
2888   size_t rtnval;
2889   size_t items_read = 0;
2890   char *b = (char *) ptr;
2891
2892   while (nitem > 0)
2893     {
2894       rtnval = fread (b, size, nitem, stream);
2895       if (rtnval == 0)
2896         {
2897           if (ferror (stream) && errno == EINTR)
2898             continue;
2899           else
2900             return items_read;
2901         }
2902       b += size*rtnval;
2903       nitem -= rtnval;
2904       items_read += rtnval;
2905     }
2906   return (items_read);
2907 #else
2908   return fread (ptr, size, nitem, stream);
2909 #endif
2910 }
2911 #endif /* ENCAPSULATE_FREAD */
2912
2913
2914 #ifdef ENCAPSULATE_FWRITE
2915 size_t
2916 sys_fwrite (const void *ptr, size_t size, size_t nitem, FILE *stream)
2917 {
2918 #ifdef INTERRUPTIBLE_IO
2919   size_t rtnval;
2920   size_t items_written = 0;
2921   const char *b = (const char *) ptr;
2922
2923   while (nitem > 0)
2924     {
2925       rtnval = fwrite (b, size, nitem, stream);
2926       if (rtnval == 0)
2927         {
2928           if (ferror (stream) && errno == EINTR)
2929             continue;
2930           else
2931             return items_written;
2932         }
2933       b += size*rtnval;
2934       nitem -= rtnval;
2935       items_written += rtnval;
2936     }
2937   return (items_written);
2938 #else
2939   return fwrite (ptr, size, nitem, stream);
2940 #endif
2941 }
2942 #endif /* ENCAPSULATE_FWRITE */
2943
2944
2945 /********************* directory calls *******************/
2946
2947 #ifdef ENCAPSULATE_CHDIR
2948 int
2949 sys_chdir (const char *path)
2950 {
2951   PATHNAME_CONVERT_OUT (path);
2952   return chdir (path);
2953 }
2954 #endif /* ENCAPSULATE_CHDIR */
2955
2956
2957 #ifdef ENCAPSULATE_MKDIR
2958 int
2959 sys_mkdir (const char *path, mode_t mode)
2960 {
2961   PATHNAME_CONVERT_OUT (path);
2962 #ifdef WIN32_NATIVE
2963   return mkdir (path);
2964 #else
2965   return mkdir (path, mode);
2966 #endif
2967 }
2968 #endif /* ENCAPSULATE_MKDIR */
2969
2970
2971 #ifdef ENCAPSULATE_OPENDIR
2972 DIR *
2973 sys_opendir (const char *filename)
2974 {
2975   DIR *rtnval;
2976   PATHNAME_CONVERT_OUT (filename);
2977
2978   while (!(rtnval = opendir (filename))
2979          && (errno == EINTR))
2980     ;
2981   return rtnval;
2982 }
2983 #endif /* ENCAPSULATE_OPENDIR */
2984
2985
2986 #ifdef ENCAPSULATE_READDIR
2987 DIRENTRY *
2988 sys_readdir (DIR *dirp)
2989 {
2990   DIRENTRY *rtnval;
2991
2992   /* Apparently setting errno is necessary on some systems?
2993      Maybe readdir() doesn't always set errno ?! */
2994   while (!(errno = 0, rtnval = readdir (dirp))
2995          && (errno == EINTR))
2996     ;
2997 #ifndef MULE
2998   return rtnval;
2999 #else /* MULE */
3000   if (rtnval == NULL)           /* End of directory */
3001     return NULL;
3002   {
3003     Extcount external_len;
3004     int ascii_filename_p = 1;
3005     const Extbyte * const external_name = (const Extbyte *) rtnval->d_name;
3006
3007     /* Optimize for the common all-ASCII case, computing len en passant */
3008     for (external_len = 0; external_name[external_len] ; external_len++)
3009       {
3010         if (!BYTE_ASCII_P (external_name[external_len]))
3011           ascii_filename_p = 0;
3012       }
3013     if (ascii_filename_p)
3014       return rtnval;
3015
3016     { /* Non-ASCII filename */
3017       static Bufbyte_dynarr *internal_DIRENTRY;
3018       const Bufbyte *internal_name;
3019       Bytecount internal_len;
3020       if (!internal_DIRENTRY)
3021         internal_DIRENTRY = Dynarr_new (Bufbyte);
3022       else
3023         Dynarr_reset (internal_DIRENTRY);
3024
3025       Dynarr_add_many (internal_DIRENTRY, (Bufbyte *) rtnval,
3026                        offsetof (DIRENTRY, d_name));
3027
3028       TO_INTERNAL_FORMAT (DATA, (external_name, external_len),
3029                           ALLOCA, (internal_name, internal_len),
3030                           Qfile_name);
3031
3032       Dynarr_add_many (internal_DIRENTRY, internal_name, internal_len);
3033       Dynarr_add (internal_DIRENTRY, 0); /* zero-terminate */
3034       return (DIRENTRY *) Dynarr_atp (internal_DIRENTRY, 0);
3035     }
3036   }
3037 #endif /* MULE */
3038 }
3039 #endif /* ENCAPSULATE_READDIR */
3040
3041
3042 #ifdef ENCAPSULATE_CLOSEDIR
3043 int
3044 sys_closedir (DIR *dirp)
3045 {
3046   int rtnval;
3047
3048   while ((rtnval = closedir (dirp)) == -1
3049          && (errno == EINTR))
3050     ;
3051   return rtnval;
3052 }
3053 #endif /* ENCAPSULATE_CLOSEDIR */
3054
3055
3056 #ifdef ENCAPSULATE_RMDIR
3057 int
3058 sys_rmdir (const char *path)
3059 {
3060   PATHNAME_CONVERT_OUT (path);
3061   return rmdir (path);
3062 }
3063 #endif /* ENCAPSULATE_RMDIR */
3064
3065
3066 /***************** file-information calls ******************/
3067
3068 #ifdef ENCAPSULATE_ACCESS
3069 int
3070 sys_access (const char *path, int mode)
3071 {
3072   PATHNAME_CONVERT_OUT (path);
3073   return access (path, mode);
3074 }
3075 #endif /* ENCAPSULATE_ACCESS */
3076
3077
3078 #ifdef HAVE_EACCESS
3079 #ifdef ENCAPSULATE_EACCESS
3080 int
3081 sys_eaccess (const char *path, int mode)
3082 {
3083   PATHNAME_CONVERT_OUT (path);
3084   return eaccess (path, mode);
3085 }
3086 #endif /* ENCAPSULATE_EACCESS */
3087 #endif /* HAVE_EACCESS */
3088
3089
3090 #ifdef ENCAPSULATE_LSTAT
3091 int
3092 sys_lstat (const char *path, struct stat *buf)
3093 {
3094   PATHNAME_CONVERT_OUT (path);
3095   return lstat (path, buf);
3096 }
3097 #endif /* ENCAPSULATE_LSTAT */
3098
3099
3100 #ifdef ENCAPSULATE_READLINK
3101 int
3102 sys_readlink (const char *path, char *buf, size_t bufsiz)
3103 {
3104   PATHNAME_CONVERT_OUT (path);
3105   /* #### currently we don't do conversions on the incoming data */
3106   return readlink (path, buf, bufsiz);
3107 }
3108 #endif /* ENCAPSULATE_READLINK */
3109
3110 #ifdef ENCAPSULATE_FSTAT
3111 int
3112 sys_fstat (int fd, struct stat *buf)
3113 {
3114 #ifdef WIN32_NATIVE
3115   return mswindows_fstat (fd, buf);
3116 #else
3117   return fstat (fd, buf);
3118 #endif
3119 }
3120 #endif /* ENCAPSULATE_FSTAT */
3121
3122 #ifdef ENCAPSULATE_STAT
3123 int
3124 sys_stat (const char *path, struct stat *buf)
3125 {
3126   PATHNAME_CONVERT_OUT (path);
3127 #ifdef WIN32_NATIVE
3128   return mswindows_stat (path, buf);
3129 #else
3130   return stat (path, buf);
3131 #endif
3132 }
3133 #endif /* ENCAPSULATE_STAT */
3134
3135 /****************** file-manipulation calls *****************/
3136
3137 #ifdef ENCAPSULATE_CHMOD
3138 int
3139 sys_chmod (const char *path, mode_t mode)
3140 {
3141   PATHNAME_CONVERT_OUT (path);
3142   return chmod (path, mode);
3143 }
3144 #endif /* ENCAPSULATE_CHMOD */
3145
3146
3147 #ifdef ENCAPSULATE_CREAT
3148 int
3149 sys_creat (const char *path, mode_t mode)
3150 {
3151   PATHNAME_CONVERT_OUT (path);
3152   return creat (path, mode);
3153 }
3154 #endif /* ENCAPSULATE_CREAT */
3155
3156
3157 #ifdef ENCAPSULATE_LINK
3158 int
3159 sys_link (const char *existing, const char *new)
3160 {
3161   PATHNAME_CONVERT_OUT (existing);
3162   PATHNAME_CONVERT_OUT (new);
3163   return link (existing, new);
3164 }
3165 #endif /* ENCAPSULATE_LINK */
3166
3167
3168 #ifdef ENCAPSULATE_RENAME
3169 int
3170 sys_rename (const char *old, const char *new)
3171 {
3172   PATHNAME_CONVERT_OUT (old);
3173   PATHNAME_CONVERT_OUT (new);
3174 #ifdef WIN32_NATIVE
3175   /* Windows rename fails if NEW exists */
3176   if (rename (old, new) == 0)
3177     return 0;
3178   if (errno != EEXIST)
3179     return -1;
3180   unlink (new);
3181 #endif /* WIN32_NATIVE */
3182   return rename (old, new);
3183 }
3184 #endif /* ENCAPSULATE_RENAME */
3185
3186
3187 #ifdef ENCAPSULATE_SYMLINK
3188 int
3189 sys_symlink (const char *name1, const char *name2)
3190 {
3191   PATHNAME_CONVERT_OUT (name1);
3192   PATHNAME_CONVERT_OUT (name2);
3193   return symlink (name1, name2);
3194 }
3195 #endif /* ENCAPSULATE_SYMLINK */
3196
3197
3198 #ifdef ENCAPSULATE_UNLINK
3199 int
3200 sys_unlink (const char *path)
3201 {
3202   PATHNAME_CONVERT_OUT (path);
3203   return unlink (path);
3204 }
3205 #endif /* ENCAPSULATE_UNLINK */
3206
3207
3208 #ifdef ENCAPSULATE_EXECVP
3209 int
3210 sys_execvp (const char *path, char * const * argv)
3211 {
3212   int i, argc;
3213   char ** new_argv;
3214
3215   PATHNAME_CONVERT_OUT (path);
3216   for (argc = 0; argv[argc]; argc++)
3217     ;
3218   new_argv = alloca_array (char *, argc + 1);
3219   for (i = 0; i < argc; i++)
3220     {
3221       new_argv[i] = argv[i];
3222       PATHNAME_CONVERT_OUT (new_argv[i]);
3223     }
3224   new_argv[argc] = NULL;
3225   return execvp (path, new_argv);
3226 }
3227 #endif /* ENCAPSULATE_EXECVP */
3228
3229 \f
3230 /************************************************************************/
3231 /*                  Emulations of missing system calls                  */
3232 /************************************************************************/
3233
3234 /***** (these are primarily required for USG, it seems) *****/
3235
3236 #ifndef HAVE_GETCWD
3237 char *
3238 getcwd (char *pathname, size_t size)
3239 {
3240   return getwd (pathname);
3241 }
3242 #endif /* emulate getcwd */
3243
3244
3245 #if 0 /* mrb */
3246 /*
3247  *      Warning, this function may not duplicate BSD 4.2 action properly
3248  *      under error conditions.
3249  */
3250
3251 #ifndef HAVE_GETWD
3252 char *
3253 getwd (char *pathname)
3254 {
3255   char *npath, *spath;
3256 #if !__STDC__ && !defined(STDC_HEADERS)
3257   extern char *getcwd ();
3258 #endif
3259
3260   spath = npath = getcwd ((char *) 0, MAXPATHLEN);
3261   if (spath == 0)
3262     return spath;
3263   /* On Altos 3068, getcwd can return @hostname/dir, so discard
3264      up to first slash.  Should be harmless on other systems.  */
3265   while (*npath && *npath != '/')
3266     npath++;
3267   strcpy (pathname, npath);
3268   xfree (spath);                  /* getcwd uses malloc */
3269   return pathname;
3270 }
3271 #endif /* HAVE_GETWD */
3272 #endif /* 0 - mrb */
3273
3274 /*
3275  *      Emulate rename using unlink/link.  Note that this is
3276  *      only partially correct.  Also, doesn't enforce restriction
3277  *      that files be of same type (regular->regular, dir->dir, etc).
3278  */
3279
3280 #ifndef HAVE_RENAME
3281 int
3282 rename (const char *from, const char *to)
3283 {
3284   if (access (from, 0) == 0)
3285     {
3286       unlink (to);
3287       if (link (from, to) == 0)
3288         if (unlink (from) == 0)
3289           return (0);
3290     }
3291   return (-1);
3292 }
3293 #endif /* HAVE_RENAME */
3294
3295 #ifdef HPUX
3296 #ifndef HAVE_PERROR
3297
3298 /* HPUX curses library references perror, but as far as we know
3299    it won't be called.  Anyway this definition will do for now.  */
3300
3301 perror (void)
3302 {
3303 }
3304
3305 #endif /* not HAVE_PERROR */
3306 #endif /* HPUX */
3307
3308 #ifndef HAVE_DUP2
3309
3310 /*
3311  *      Emulate BSD dup2.  First close newd if it already exists.
3312  *      Then, attempt to dup oldd.  If not successful, call dup2 recursively
3313  *      until we are, then close the unsuccessful ones.
3314  */
3315
3316 int
3317 dup2 (int oldd, int newd)
3318 {
3319   int fd, ret;
3320
3321   sys_close (newd);
3322
3323 #ifdef F_DUPFD
3324   fd = fcntl (oldd, F_DUPFD, newd);
3325   if (fd != newd)
3326     error ("can't dup2 (%i,%i) : %s", oldd, newd, strerror (errno));
3327 #else
3328   fd = dup (old);
3329   if (fd == -1)
3330     return -1;
3331   if (fd == new)
3332     return new;
3333   ret = dup2 (old, new);
3334   sys_close (fd);
3335   return ret;
3336 #endif /*  F_DUPFD */
3337 }
3338
3339 #endif /* not HAVE_DUP2 */
3340
3341 /*
3342  *      Gettimeofday.  Simulate as much as possible.  Only accurate
3343  *      to nearest second.  Emacs doesn't use tzp so ignore it for now.
3344  */
3345
3346 #if !defined (HAVE_GETTIMEOFDAY)
3347
3348 int
3349 gettimeofday (struct timeval *tp, struct timezone *tzp)
3350 {
3351   extern long time ();
3352
3353   tp->tv_sec = time ((long *)0);
3354   tp->tv_usec = 0;
3355   if (tzp != 0)
3356     tzp->tz_minuteswest = -1;
3357   return (0);
3358 }
3359
3360 #endif /* !HAVE_GETTIMEOFDAY */
3361
3362 /* No need to encapsulate utime and utimes explicitly because all
3363    access to those functions goes through the following. */
3364
3365 int
3366 set_file_times (char *filename, EMACS_TIME atime, EMACS_TIME mtime)
3367 {
3368 #ifdef HAVE_UTIMES
3369   struct timeval tv[2];
3370   tv[0] = atime;
3371   tv[1] = mtime;
3372   return utimes (filename, tv);
3373 #else /* not HAVE_UTIMES */
3374   struct utimbuf utb;
3375   utb.actime = EMACS_SECS (atime);
3376   utb.modtime = EMACS_SECS (mtime);
3377   return utime (filename, &utb);
3378 #endif /* not HAVE_UTIMES */
3379 }
3380
3381 /* */
3382
3383 static long ticks_per_second;
3384 static long orig_user_ticks, orig_system_ticks;
3385 EMACS_TIME orig_real_time;
3386
3387 static int process_times_available;
3388
3389 /* Return the relative user and system tick count.  We try to
3390    maintain calculations in terms of integers as long as possible
3391    for increased accuracy. */
3392
3393 static int
3394 get_process_times_1 (long *user_ticks, long *system_ticks)
3395 {
3396 #if defined (_SC_CLK_TCK) || defined (CLK_TCK) && !defined(WIN32_NATIVE)
3397   /* We have the POSIX times() function available. */
3398   struct tms tttt;
3399   times (&tttt);
3400   *user_ticks = (long) tttt.tms_utime;
3401   *system_ticks = (long) tttt.tms_stime;
3402   return 1;
3403 #elif defined (CLOCKS_PER_SEC)
3404   *user_ticks = (long) clock ();
3405   *system_ticks = 0;
3406   return 1;
3407 #else
3408   return 0;
3409 #endif
3410 }
3411
3412 void
3413 init_process_times_very_early (void)
3414 {
3415 #if defined (_SC_CLK_TCK)
3416   ticks_per_second = sysconf (_SC_CLK_TCK);
3417 #elif defined (CLK_TCK)
3418   ticks_per_second = CLK_TCK;
3419 #elif defined (CLOCKS_PER_SEC)
3420   ticks_per_second = CLOCKS_PER_SEC;
3421 #endif
3422
3423   process_times_available = get_process_times_1 (&orig_user_ticks,
3424                                                  &orig_system_ticks);
3425   EMACS_GET_TIME (orig_real_time);
3426 }
3427
3428 /* Return the user and system times used up by this process so far. */
3429 void
3430 get_process_times (double *user_time, double *system_time, double *real_time)
3431 {
3432   EMACS_TIME curr_real_time;
3433   EMACS_TIME elapsed_time;
3434   long curr_user_ticks, curr_system_ticks;
3435
3436   EMACS_GET_TIME (curr_real_time);
3437   EMACS_SUB_TIME (elapsed_time, curr_real_time, orig_real_time);
3438   *real_time = (EMACS_SECS (elapsed_time)
3439                 + ((double) EMACS_USECS (elapsed_time)) / 1000000);
3440   if (get_process_times_1 (&curr_user_ticks, &curr_system_ticks))
3441     {
3442       *user_time = (((double) (curr_user_ticks - orig_user_ticks))
3443                     / ticks_per_second);
3444       *system_time = (((double) (curr_system_ticks - orig_system_ticks))
3445                       / ticks_per_second);
3446     }
3447   else
3448     {
3449       /* A lame OS */
3450       *user_time = *real_time;
3451       *system_time = 0;
3452     }
3453 }
3454
3455 #ifndef HAVE_RANDOM
3456 #ifdef random
3457 #define HAVE_RANDOM
3458 #endif
3459 #endif
3460
3461 /* Figure out how many bits the system's random number generator uses.
3462    `random' and `lrand48' are assumed to return 31 usable bits.
3463    BSD `rand' returns a 31 bit value but the low order bits are unusable;
3464    so we'll shift it and treat it like the 15-bit USG `rand'.  */
3465
3466 #ifndef RAND_BITS
3467 # ifdef HAVE_RANDOM
3468 #  define RAND_BITS 31
3469 # else /* !HAVE_RANDOM */
3470 #  ifdef HAVE_LRAND48
3471 #   define RAND_BITS 31
3472 #   define random lrand48
3473 #  else /* !HAVE_LRAND48 */
3474 #   define RAND_BITS 15
3475 #   if RAND_MAX == 32767
3476 #    define random rand
3477 #   else /* RAND_MAX != 32767 */
3478 #    if RAND_MAX == 2147483647
3479 #     define random() (rand () >> 16)
3480 #    else /* RAND_MAX != 2147483647 */
3481 #     ifdef USG
3482 #      define random rand
3483 #     else
3484 #      define random() (rand () >> 16)
3485 #     endif /* !BSD */
3486 #    endif /* RAND_MAX != 2147483647 */
3487 #   endif /* RAND_MAX != 32767 */
3488 #  endif /* !HAVE_LRAND48 */
3489 # endif /* !HAVE_RANDOM */
3490 #endif /* !RAND_BITS */
3491
3492 void seed_random (long arg);
3493 void
3494 seed_random (long arg)
3495 {
3496 #ifdef HAVE_RANDOM
3497   srandom ((unsigned int)arg);
3498 #else
3499 # ifdef HAVE_LRAND48
3500   srand48 (arg);
3501 # else
3502   srand ((unsigned int)arg);
3503 # endif
3504 #endif
3505 }
3506
3507 /*
3508  * Build a full Emacs-sized word out of whatever we've got.
3509  * This suffices even for a 64-bit architecture with a 15-bit rand.
3510  */
3511 long get_random (void);
3512 long
3513 get_random (void)
3514 {
3515   long val = random ();
3516 #if VALBITS > RAND_BITS
3517   val = (val << RAND_BITS) ^ random ();
3518 #if VALBITS > 2*RAND_BITS
3519   val = (val << RAND_BITS) ^ random ();
3520 #if VALBITS > 3*RAND_BITS
3521   val = (val << RAND_BITS) ^ random ();
3522 #if VALBITS > 4*RAND_BITS
3523   val = (val << RAND_BITS) ^ random ();
3524 #endif /* need at least 5 */
3525 #endif /* need at least 4 */
3526 #endif /* need at least 3 */
3527 #endif /* need at least 2 */
3528   return val & ((1L << VALBITS) - 1);
3529 }
3530
3531 \f
3532 /************************************************************************/
3533 /*               Strings corresponding to defined signals               */
3534 /************************************************************************/
3535
3536 #if !defined (SYS_SIGLIST_DECLARED) && !defined (HAVE_SYS_SIGLIST)
3537
3538 #if defined(WIN32_NATIVE) || defined(CYGWIN)
3539 const char *sys_siglist[] =
3540   {
3541     "bum signal!!",
3542     "hangup",
3543     "interrupt",
3544     "quit",
3545     "illegal instruction",
3546     "trace trap",
3547     "iot instruction",
3548     "emt instruction",
3549     "floating point exception",
3550     "kill",
3551     "bus error",
3552     "segmentation violation",
3553     "bad argument to system call",
3554     "write on a pipe with no one to read it",
3555     "alarm clock",
3556     "software termination signal from kill",
3557     "status signal",
3558     "sendable stop signal not from tty",
3559     "stop signal from tty",
3560     "continue a stopped process",
3561     "child status has changed",
3562     "background read attempted from control tty",
3563     "background write attempted from control tty",
3564     "input record available at control tty",
3565     "exceeded CPU time limit",
3566     "exceeded file size limit"
3567     };
3568 #endif
3569
3570 #ifdef USG
3571 #ifdef AIX
3572 const char *sys_siglist[NSIG + 1] =
3573   {
3574     /* AIX has changed the signals a bit */
3575     DEFER_GETTEXT ("bogus signal"),                     /* 0 */
3576     DEFER_GETTEXT ("hangup"),                           /* 1  SIGHUP */
3577     DEFER_GETTEXT ("interrupt"),                        /* 2  SIGINT */
3578     DEFER_GETTEXT ("quit"),                             /* 3  SIGQUIT */
3579     DEFER_GETTEXT ("illegal instruction"),              /* 4  SIGILL */
3580     DEFER_GETTEXT ("trace trap"),                       /* 5  SIGTRAP */
3581     DEFER_GETTEXT ("IOT instruction"),                  /* 6  SIGIOT */
3582     DEFER_GETTEXT ("crash likely"),                     /* 7  SIGDANGER */
3583     DEFER_GETTEXT ("floating point exception"),         /* 8  SIGFPE */
3584     DEFER_GETTEXT ("kill"),                             /* 9  SIGKILL */
3585     DEFER_GETTEXT ("bus error"),                        /* 10 SIGBUS */
3586     DEFER_GETTEXT ("segmentation violation"),           /* 11 SIGSEGV */
3587     DEFER_GETTEXT ("bad argument to system call"),      /* 12 SIGSYS */
3588     DEFER_GETTEXT ("write on a pipe with no one to read it"), /* 13 SIGPIPE */
3589     DEFER_GETTEXT ("alarm clock"),                      /* 14 SIGALRM */
3590     DEFER_GETTEXT ("software termination signum"),      /* 15 SIGTERM */
3591     DEFER_GETTEXT ("user defined signal 1"),            /* 16 SIGUSR1 */
3592     DEFER_GETTEXT ("user defined signal 2"),            /* 17 SIGUSR2 */
3593     DEFER_GETTEXT ("death of a child"),                 /* 18 SIGCLD */
3594     DEFER_GETTEXT ("power-fail restart"),               /* 19 SIGPWR */
3595     DEFER_GETTEXT ("bogus signal"),                     /* 20 */
3596     DEFER_GETTEXT ("bogus signal"),                     /* 21 */
3597     DEFER_GETTEXT ("bogus signal"),                     /* 22 */
3598     DEFER_GETTEXT ("bogus signal"),                     /* 23 */
3599     DEFER_GETTEXT ("bogus signal"),                     /* 24 */
3600     DEFER_GETTEXT ("LAN I/O interrupt"),                /* 25 SIGAIO */
3601     DEFER_GETTEXT ("PTY I/O interrupt"),                /* 26 SIGPTY */
3602     DEFER_GETTEXT ("I/O intervention required"),        /* 27 SIGIOINT */
3603 #ifdef AIXHFT
3604     DEFER_GETTEXT ("HFT grant"),                        /* 28 SIGGRANT */
3605     DEFER_GETTEXT ("HFT retract"),                      /* 29 SIGRETRACT */
3606     DEFER_GETTEXT ("HFT sound done"),                   /* 30 SIGSOUND */
3607     DEFER_GETTEXT ("HFT input ready"),                  /* 31 SIGMSG */
3608 #endif
3609     0
3610   };
3611 #else /* USG, not AIX */
3612 const char *sys_siglist[NSIG + 1] =
3613   {
3614     DEFER_GETTEXT ("bogus signal"),                     /* 0 */
3615     DEFER_GETTEXT ("hangup"),                           /* 1  SIGHUP */
3616     DEFER_GETTEXT ("interrupt"),                        /* 2  SIGINT */
3617     DEFER_GETTEXT ("quit"),                             /* 3  SIGQUIT */
3618     DEFER_GETTEXT ("illegal instruction"),              /* 4  SIGILL */
3619     DEFER_GETTEXT ("trace trap"),                       /* 5  SIGTRAP */
3620     DEFER_GETTEXT ("IOT instruction"),                  /* 6  SIGIOT */
3621     DEFER_GETTEXT ("EMT instruction"),                  /* 7  SIGEMT */
3622     DEFER_GETTEXT ("floating point exception"),         /* 8  SIGFPE */
3623     DEFER_GETTEXT ("kill"),                             /* 9  SIGKILL */
3624     DEFER_GETTEXT ("bus error"),                        /* 10 SIGBUS */
3625     DEFER_GETTEXT ("segmentation violation"),           /* 11 SIGSEGV */
3626     DEFER_GETTEXT ("bad argument to system call"),      /* 12 SIGSYS */
3627     DEFER_GETTEXT ("write on a pipe with no one to read it"), /* 13 SIGPIPE */
3628     DEFER_GETTEXT ("alarm clock"),                      /* 14 SIGALRM */
3629     DEFER_GETTEXT ("software termination signum"),      /* 15 SIGTERM */
3630     DEFER_GETTEXT ("user defined signal 1"),            /* 16 SIGUSR1 */
3631     DEFER_GETTEXT ("user defined signal 2"),            /* 17 SIGUSR2 */
3632     DEFER_GETTEXT ("death of a child"),                 /* 18 SIGCLD */
3633     DEFER_GETTEXT ("power-fail restart"),               /* 19 SIGPWR */
3634 #ifdef sun
3635     DEFER_GETTEXT ("window size changed"),              /* 20 SIGWINCH */
3636     DEFER_GETTEXT ("urgent socket condition"),          /* 21 SIGURG */
3637     DEFER_GETTEXT ("pollable event occurred"),          /* 22 SIGPOLL */
3638     DEFER_GETTEXT ("stop (cannot be caught or ignored)"), /*  23 SIGSTOP */
3639     DEFER_GETTEXT ("user stop requested from tty"),     /* 24 SIGTSTP */
3640     DEFER_GETTEXT ("stopped process has been continued"), /* 25 SIGCONT */
3641     DEFER_GETTEXT ("background tty read attempted"),    /* 26 SIGTTIN */
3642     DEFER_GETTEXT ("background tty write attempted"),   /* 27 SIGTTOU */
3643     DEFER_GETTEXT ("virtual timer expired"),            /* 28 SIGVTALRM */
3644     DEFER_GETTEXT ("profiling timer expired"),          /* 29 SIGPROF */
3645     DEFER_GETTEXT ("exceeded cpu limit"),               /* 30 SIGXCPU */
3646     DEFER_GETTEXT ("exceeded file size limit"),         /* 31 SIGXFSZ */
3647     DEFER_GETTEXT ("process's lwps are blocked"),       /* 32 SIGWAITING */
3648     DEFER_GETTEXT ("special signal used by thread library"), /* 33 SIGLWP */
3649 #ifdef SIGFREEZE
3650     DEFER_GETTEXT ("special signal used by CPR"),        /* 34 SIGFREEZE */
3651 #endif
3652 #ifdef SIGTHAW
3653     DEFER_GETTEXT ("special signal used by CPR"),        /* 35 SIGTHAW */
3654 #endif
3655 #endif /* sun */
3656     0
3657   };
3658 #endif /* not AIX */
3659 #endif /* USG */
3660 #ifdef DGUX
3661 const char *sys_siglist[NSIG + 1] =
3662   {
3663     DEFER_GETTEXT ("null signal"),                       /*  0 SIGNULL   */
3664     DEFER_GETTEXT ("hangup"),                            /*  1 SIGHUP    */
3665     DEFER_GETTEXT ("interrupt"),                         /*  2 SIGINT    */
3666     DEFER_GETTEXT ("quit"),                              /*  3 SIGQUIT   */
3667     DEFER_GETTEXT ("illegal instruction"),               /*  4 SIGILL    */
3668     DEFER_GETTEXT ("trace trap"),                        /*  5 SIGTRAP   */
3669     DEFER_GETTEXT ("abort termination"),                 /*  6 SIGABRT   */
3670     DEFER_GETTEXT ("SIGEMT"),                            /*  7 SIGEMT    */
3671     DEFER_GETTEXT ("floating point exception"),          /*  8 SIGFPE    */
3672     DEFER_GETTEXT ("kill"),                              /*  9 SIGKILL   */
3673     DEFER_GETTEXT ("bus error"),                         /* 10 SIGBUS    */
3674     DEFER_GETTEXT ("segmentation violation"),            /* 11 SIGSEGV   */
3675     DEFER_GETTEXT ("bad argument to system call"),       /* 12 SIGSYS    */
3676     DEFER_GETTEXT ("write on a pipe with no reader"),    /* 13 SIGPIPE   */
3677     DEFER_GETTEXT ("alarm clock"),                       /* 14 SIGALRM   */
3678     DEFER_GETTEXT ("software termination signal"),       /* 15 SIGTERM   */
3679     DEFER_GETTEXT ("user defined signal 1"),             /* 16 SIGUSR1   */
3680     DEFER_GETTEXT ("user defined signal 2"),             /* 17 SIGUSR2   */
3681     DEFER_GETTEXT ("child stopped or terminated"),       /* 18 SIGCLD    */
3682     DEFER_GETTEXT ("power-fail restart"),                /* 19 SIGPWR    */
3683     DEFER_GETTEXT ("window size changed"),               /* 20 SIGWINCH  */
3684     DEFER_GETTEXT ("undefined"),                         /* 21           */
3685     DEFER_GETTEXT ("pollable event occurred"),           /* 22 SIGPOLL   */
3686     DEFER_GETTEXT ("sendable stop signal not from tty"), /* 23 SIGSTOP   */
3687     DEFER_GETTEXT ("stop signal from tty"),              /* 24 SIGSTP    */
3688     DEFER_GETTEXT ("continue a stopped process"),        /* 25 SIGCONT   */
3689     DEFER_GETTEXT ("attempted background tty read"),     /* 26 SIGTTIN   */
3690     DEFER_GETTEXT ("attempted background tty write"),    /* 27 SIGTTOU   */
3691     DEFER_GETTEXT ("undefined"),                         /* 28           */
3692     DEFER_GETTEXT ("undefined"),                         /* 29           */
3693     DEFER_GETTEXT ("undefined"),                         /* 30           */
3694     DEFER_GETTEXT ("undefined"),                         /* 31           */
3695     DEFER_GETTEXT ("undefined"),                         /* 32           */
3696     DEFER_GETTEXT ("socket (TCP/IP) urgent data arrival"), /* 33 SIGURG    */
3697     DEFER_GETTEXT ("I/O is possible"),                   /* 34 SIGIO     */
3698     DEFER_GETTEXT ("exceeded cpu time limit"),           /* 35 SIGXCPU   */
3699     DEFER_GETTEXT ("exceeded file size limit"),          /* 36 SIGXFSZ   */
3700     DEFER_GETTEXT ("virtual time alarm"),                /* 37 SIGVTALRM */
3701     DEFER_GETTEXT ("profiling time alarm"),              /* 38 SIGPROF   */
3702     DEFER_GETTEXT ("undefined"),                         /* 39           */
3703     DEFER_GETTEXT ("file record locks revoked"),         /* 40 SIGLOST   */
3704     DEFER_GETTEXT ("undefined"),                         /* 41           */
3705     DEFER_GETTEXT ("undefined"),                         /* 42           */
3706     DEFER_GETTEXT ("undefined"),                         /* 43           */
3707     DEFER_GETTEXT ("undefined"),                         /* 44           */
3708     DEFER_GETTEXT ("undefined"),                         /* 45           */
3709     DEFER_GETTEXT ("undefined"),                         /* 46           */
3710     DEFER_GETTEXT ("undefined"),                         /* 47           */
3711     DEFER_GETTEXT ("undefined"),                         /* 48           */
3712     DEFER_GETTEXT ("undefined"),                         /* 49           */
3713     DEFER_GETTEXT ("undefined"),                         /* 50           */
3714     DEFER_GETTEXT ("undefined"),                         /* 51           */
3715     DEFER_GETTEXT ("undefined"),                         /* 52           */
3716     DEFER_GETTEXT ("undefined"),                         /* 53           */
3717     DEFER_GETTEXT ("undefined"),                         /* 54           */
3718     DEFER_GETTEXT ("undefined"),                         /* 55           */
3719     DEFER_GETTEXT ("undefined"),                         /* 56           */
3720     DEFER_GETTEXT ("undefined"),                         /* 57           */
3721     DEFER_GETTEXT ("undefined"),                         /* 58           */
3722     DEFER_GETTEXT ("undefined"),                         /* 59           */
3723     DEFER_GETTEXT ("undefined"),                         /* 60           */
3724     DEFER_GETTEXT ("undefined"),                         /* 61           */
3725     DEFER_GETTEXT ("undefined"),                         /* 62           */
3726     DEFER_GETTEXT ("undefined"),                         /* 63           */
3727     DEFER_GETTEXT ("notification message in mess. queue"), /* 64 SIGDGNOTIFY */
3728     0
3729   };
3730 #endif /* DGUX */
3731
3732 #endif /* ! SYS_SIGLIST_DECLARED && ! HAVE_SYS_SIGLIST */
3733
3734 \f
3735 /************************************************************************/
3736 /*         Directory routines for systems that don't have them          */
3737 /************************************************************************/
3738
3739 #ifdef SYSV_SYSTEM_DIR
3740
3741 #include <dirent.h>
3742
3743 #if defined(BROKEN_CLOSEDIR) || !defined(HAVE_CLOSEDIR)
3744 int
3745 closedir (DIR *dirp)  /* stream from opendir */
3746 {
3747   int rtnval;
3748
3749   rtnval = sys_close (dirp->dd_fd);
3750
3751   /* Some systems (like Solaris) allocate the buffer and the DIR all
3752      in one block.  Why in the world are we freeing this ourselves
3753      anyway?  */
3754 #if ! (defined (sun) && defined (USG5_4))
3755   xfree ((char *) dirp->dd_buf); /* directory block defined in <dirent.h> */
3756 #endif
3757   xfree ((char *) dirp);
3758   return (rtnval);
3759 }
3760 #endif /* BROKEN_CLOSEDIR or not HAVE_CLOSEDIR */
3761 #endif /* SYSV_SYSTEM_DIR */
3762
3763 #ifdef NONSYSTEM_DIR_LIBRARY
3764
3765 DIR *
3766 opendir (const char *filename)  /* name of directory */
3767 {
3768   DIR *dirp;            /* -> malloc'ed storage */
3769   int fd;               /* file descriptor for read */
3770   struct stat sbuf;             /* result of fstat */
3771
3772   fd = sys_open (filename, O_RDONLY);
3773   if (fd < 0)
3774     return 0;
3775
3776   if (fstat (fd, &sbuf) < 0
3777       || (sbuf.st_mode & S_IFMT) != S_IFDIR
3778       || (dirp = (DIR *) malloc (sizeof (DIR))) == 0)
3779     {
3780       sys_close (fd);
3781       return 0;         /* bad luck today */
3782     }
3783
3784   dirp->dd_fd = fd;
3785   dirp->dd_loc = dirp->dd_size = 0;     /* refill needed */
3786
3787   return dirp;
3788 }
3789
3790 void
3791 closedir (DIR *dirp)            /* stream from opendir */
3792 {
3793   sys_close (dirp->dd_fd);
3794   xfree (dirp);
3795 }
3796
3797
3798 #define DIRSIZ  14
3799 struct olddir
3800   {
3801     ino_t od_ino;               /* inode */
3802     char od_name[DIRSIZ];       /* filename */
3803   };
3804
3805 static struct direct dir_static; /* simulated directory contents */
3806
3807 /* ARGUSED */
3808 struct direct *
3809 readdir (DIR *dirp)     /* stream from opendir */
3810 {
3811   struct olddir *dp;    /* -> directory data */
3812
3813   for (; ;)
3814     {
3815       if (dirp->dd_loc >= dirp->dd_size)
3816         dirp->dd_loc = dirp->dd_size = 0;
3817
3818       if (dirp->dd_size == 0    /* refill buffer */
3819           && (dirp->dd_size = sys_read (dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ)) <= 0)
3820         return 0;
3821
3822       dp = (struct olddir *) &dirp->dd_buf[dirp->dd_loc];
3823       dirp->dd_loc += sizeof (struct olddir);
3824
3825       if (dp->od_ino != 0)      /* not deleted entry */
3826         {
3827           dir_static.d_ino = dp->od_ino;
3828           strncpy (dir_static.d_name, dp->od_name, DIRSIZ);
3829           dir_static.d_name[DIRSIZ] = '\0';
3830           dir_static.d_namlen = strlen (dir_static.d_name);
3831           dir_static.d_reclen = sizeof (struct direct)
3832             - MAXNAMLEN + 3
3833               + dir_static.d_namlen - dir_static.d_namlen % 4;
3834           return &dir_static;   /* -> simulated structure */
3835         }
3836     }
3837 }
3838
3839
3840 #endif /* NONSYSTEM_DIR_LIBRARY */
3841
3842 \f
3843 /* mkdir and rmdir functions, for systems which don't have them.  */
3844
3845 #ifndef HAVE_MKDIR
3846 /*
3847  * Written by Robert Rother, Mariah Corporation, August 1985.
3848  *
3849  * If you want it, it's yours.  All I ask in return is that if you
3850  * figure out how to do this in a Bourne Shell script you send me
3851  * a copy.
3852  *                                      sdcsvax!rmr or rmr@uscd
3853  *
3854  * Severely hacked over by John Gilmore to make a 4.2BSD compatible
3855  * subroutine.  11Mar86; hoptoad!gnu
3856  *
3857  * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
3858  * subroutine didn't return EEXIST.  It does now.
3859  */
3860
3861 /*
3862  * Make a directory.
3863  */
3864 #ifdef MKDIR_PROTOTYPE
3865 MKDIR_PROTOTYPE
3866 #else
3867 int
3868 mkdir (const char *dpath, int dmode)
3869 #endif
3870 {
3871   int cpid, status, fd;
3872   struct stat statbuf;
3873
3874   if (stat (dpath, &statbuf) == 0)
3875     {
3876       errno = EEXIST;           /* Stat worked, so it already exists */
3877       return -1;
3878     }
3879
3880   /* If stat fails for a reason other than non-existence, return error */
3881   if (errno != ENOENT)
3882     return -1;
3883
3884   synch_process_alive = 1;
3885   switch (cpid = fork ())
3886     {
3887
3888     case -1:                    /* Error in fork() */
3889       return -1;                /* Errno is set already */
3890
3891     case 0:                     /* Child process */
3892     {
3893       /*
3894        * Cheap hack to set mode of new directory.  Since this
3895        * child process is going away anyway, we zap its umask.
3896        * ####, this won't suffice to set SUID, SGID, etc. on this
3897        * directory.  Does anybody care?
3898        */
3899       status = umask (0);       /* Get current umask */
3900       status = umask (status | (0777 & ~dmode));        /* Set for mkdir */
3901       fd = sys_open ("/dev/null", O_RDWR);
3902       if (fd >= 0)
3903         {
3904           if (fd != STDIN_FILENO)  dup2 (fd, STDIN_FILENO);
3905           if (fd != STDOUT_FILENO) dup2 (fd, STDOUT_FILENO);
3906           if (fd != STDERR_FILENO) dup2 (fd, STDERR_FILENO);
3907         }
3908       execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
3909       _exit (-1);               /* Can't exec /bin/mkdir */
3910     }
3911
3912     default:                    /* Parent process */
3913       wait_for_termination (cpid);
3914     }
3915
3916   if (synch_process_death != 0 || synch_process_retcode != 0)
3917     {
3918       errno = EIO;              /* We don't know why, but */
3919       return -1;                /* /bin/mkdir failed */
3920     }
3921
3922   return 0;
3923 }
3924 #endif /* not HAVE_MKDIR */
3925
3926 #ifndef HAVE_RMDIR
3927 int
3928 rmdir (const char *dpath)
3929 {
3930   int cpid, status, fd;
3931   struct stat statbuf;
3932
3933   if (stat (dpath, &statbuf) != 0)
3934     {
3935       /* Stat just set errno.  We don't have to */
3936       return -1;
3937     }
3938
3939   synch_process_alive = 1;
3940   switch (cpid = fork ())
3941     {
3942
3943     case -1:                    /* Error in fork() */
3944       return (-1);              /* Errno is set already */
3945
3946     case 0:                     /* Child process */
3947       fd = sys_open("/dev/null", O_RDWR);
3948       if (fd >= 0)
3949         {
3950           if (fd != STDIN_FILENO)  dup2 (fd, STDIN_FILENO);
3951           if (fd != STDOUT_FILENO) dup2 (fd, STDOUT_FILENO);
3952           if (fd != STDERR_FILENO) dup2 (fd, STDERR_FILENO);
3953         }
3954       execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
3955       _exit (-1);               /* Can't exec /bin/mkdir */
3956
3957     default:                    /* Parent process */
3958       wait_for_termination (cpid);
3959     }
3960
3961   if (synch_process_death   != 0 ||
3962       synch_process_retcode != 0)
3963     {
3964       errno = EIO;              /* We don't know why, but */
3965       return -1;                /* /bin/rmdir failed */
3966     }
3967
3968   return 0;
3969 }
3970 #endif /* !HAVE_RMDIR */
3971
3972 \f
3973 /************************************************************************/
3974 /*                            Misc. SunOS crap                          */
3975 /************************************************************************/
3976
3977 #ifdef USE_DL_STUBS
3978
3979 /* These are included on Sunos 4.1 when we do not use shared libraries.
3980    X11 libraries may refer to these functions but (we hope) do not
3981    actually call them.  */
3982
3983 void *
3984 dlopen (void)
3985 {
3986   return 0;
3987 }
3988
3989 void *
3990 dlsym (void)
3991 {
3992   return 0;
3993 }
3994
3995 int
3996 dlclose (void)
3997 {
3998   return -1;
3999 }
4000
4001 #endif /* USE_DL_STUBS */
4002
4003 \f
4004
4005 #ifndef HAVE_STRCASECMP
4006 /*
4007  * From BSD
4008  */
4009 static unsigned char charmap[] = {
4010         '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
4011         '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
4012         '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
4013         '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
4014         '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
4015         '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
4016         '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
4017         '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
4018         '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
4019         '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
4020         '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
4021         '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
4022         '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
4023         '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
4024         '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
4025         '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
4026         '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
4027         '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
4028         '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
4029         '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
4030         '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
4031         '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
4032         '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
4033         '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
4034         '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
4035         '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
4036         '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
4037         '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
4038         '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
4039         '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
4040         '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
4041         '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
4042 };
4043
4044 int
4045 strcasecmp (char *s1, char *s2)
4046 {
4047   unsigned char *cm = charmap;
4048   unsigned char *us1 = (unsigned char *) s1;
4049   unsigned char *us2 = (unsigned char *)s2;
4050
4051   while (cm[*us1] == cm[*us2++])
4052     if (*us1++ == '\0')
4053       return (0);
4054
4055   return (cm[*us1] - cm[*--us2]);
4056 }
4057 #endif /* !HAVE_STRCASECMP */