Convert (most) functions in src to standard C.
[bpt/emacs.git] / src / sysdep.c
CommitLineData
86a5659e 1/* Interfaces to system-dependent kernel and library entries.
275464e7 2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1999, 2000, 2001,
114f9c96 3 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
8cabe764 4 Free Software Foundation, Inc.
86a5659e
JB
5
6This file is part of GNU Emacs.
7
9ec0b715 8GNU Emacs is free software: you can redistribute it and/or modify
86a5659e 9it under the terms of the GNU General Public License as published by
9ec0b715
GM
10the Free Software Foundation, either version 3 of the License, or
11(at your option) any later version.
86a5659e
JB
12
13GNU Emacs is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
9ec0b715 19along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
86a5659e 20
4838e624
PJ
21#ifdef HAVE_CONFIG_H
22#include <config.h>
23#endif
86a5659e 24
2c55aacf 25#include <ctype.h>
86a5659e 26#include <signal.h>
5890e9f7 27#include <stdio.h>
86a5659e 28#include <setjmp.h>
06e111a6
DN
29#ifdef HAVE_PWD_H
30#include <pwd.h>
31#include <grp.h>
32#endif /* HAVE_PWD_H */
33#ifdef HAVE_LIMITS_H
34#include <limits.h>
35#endif /* HAVE_LIMITS_H */
d3eb3bfa
DL
36#ifdef HAVE_UNISTD_H
37#include <unistd.h>
38#endif
53934c98 39
86a5659e 40#include "lisp.h"
8296bbf8
DL
41/* Including stdlib.h isn't necessarily enough to get srandom
42 declared, e.g. without __USE_XOPEN_EXTENDED with glibc 2. */
8296bbf8 43
4d395425
EZ
44/* The w32 build defines select stuff in w32.h, which is included by
45 sys/select.h (included below). */
46#ifndef WINDOWSNT
819b8f00 47#include "sysselect.h"
4d395425 48#endif
819b8f00 49
9ac0d9e0 50#include "blockinput.h"
86a5659e 51
fe03522b 52#ifdef WINDOWSNT
e15b6288
JR
53#define read sys_read
54#define write sys_write
fe03522b 55#include <windows.h>
e36ec798
AI
56#ifndef NULL
57#define NULL 0
58#endif
fe03522b
RS
59#endif /* not WINDOWSNT */
60
86a5659e
JB
61#include <sys/types.h>
62#include <sys/stat.h>
63#include <errno.h>
64
f95c3f91 65#ifdef HAVE_SETPGID
58eb6cf0 66#if !defined (USG)
c8875a65 67#undef setpgrp
f95c3f91
GM
68#define setpgrp setpgid
69#endif
2b7e8799 70#endif
f95c3f91 71
b05af5d3
PE
72/* Get SI_SRPC_DOMAIN, if it is available. */
73#ifdef HAVE_SYS_SYSTEMINFO_H
74#include <sys/systeminfo.h>
75#endif
76
207bdbdb
RS
77#ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
78#include <dos.h>
79#include "dosfns.h"
80#include "msdos.h"
81#include <sys/param.h>
15614e61 82
15614e61
RS
83extern int etext;
84extern unsigned start __asm__ ("start");
85#endif
207bdbdb 86
bb4bc8e2 87#include <sys/file.h>
7ce1c4de 88
612221ab 89#ifdef HAVE_FCNTL_H
bb4bc8e2
RM
90#include <fcntl.h>
91#endif
86a5659e 92
207bdbdb 93#ifndef MSDOS
86a5659e 94#include <sys/ioctl.h>
207bdbdb 95#endif
2a633456 96
e04a4e0d 97#include "systty.h"
94c8642a 98#include "syswait.h"
86a5659e 99
e39a993c 100#if defined (USG)
86a5659e 101#include <sys/utsname.h>
86a5659e 102#include <memory.h>
e39a993c 103#endif /* USG */
86a5659e 104
86a5659e
JB
105extern int quit_char;
106
e36ec798 107#include "keyboard.h"
0137dbf7 108#include "frame.h"
86a5659e
JB
109#include "window.h"
110#include "termhooks.h"
111#include "termchar.h"
112#include "termopts.h"
113#include "dispextern.h"
114#include "process.h"
0a125897 115#include "cm.h" /* for reset_sys_modes */
86a5659e 116
1eb8fd91 117/* For serial_configure and serial_open. */
d888760c
GM
118extern Lisp_Object QCport, QCspeed, QCprocess;
119extern Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
120extern Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
121
fe03522b
RS
122#ifdef WINDOWSNT
123#include <direct.h>
124/* In process.h which conflicts with the local copy. */
125#define _P_WAIT 0
43db14bb
JB
126int _cdecl _spawnlp (int, const char *, const char *, ...);
127int _cdecl _getpid (void);
b6682dd9 128extern char *getwd (char *);
fe03522b
RS
129#endif
130
91bac16a
JB
131#include "syssignal.h"
132#include "systime.h"
d79998bc
KH
133#ifdef HAVE_UTIME_H
134#include <utime.h>
135#endif
136
137#ifndef HAVE_UTIMES
138#ifndef HAVE_STRUCT_UTIMBUF
139/* We want to use utime rather than utimes, but we couldn't find the
140 structure declaration. We'll use the traditional one. */
141struct utimbuf {
142 long actime;
143 long modtime;
144};
145#endif
146#endif
86a5659e 147
a00d5589
RS
148/* LPASS8 is new in 4.3, and makes cbreak mode provide all 8 bits. */
149#ifndef LPASS8
150#define LPASS8 0
151#endif
152
91433552 153static const int baud_convert[] =
86a5659e
JB
154 {
155 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
156 1800, 2400, 4800, 9600, 19200, 38400
157 };
86a5659e 158
f0d21750
GM
159#ifdef HAVE_SPEED_T
160#include <termios.h>
f0d21750 161#else
ba5971b3 162#if defined (HAVE_LIBNCURSES) && ! defined (NCURSES_OSPEED_T)
ba5971b3 163#else
8a2a6032 164#if defined (HAVE_TERMIOS_H) && defined (GNU_LINUX)
515b04d0 165#include <termios.h>
f2361c60 166#endif
ba5971b3 167#endif
f0d21750 168#endif
86a5659e 169
5bdd7bdd
GM
170int emacs_ospeed;
171
f57e2426 172void croak (char *) NO_RETURN;
b9c4113e 173
89723395
GM
174/* Temporary used by `sigblock' when defined in terms of signprocmask. */
175
176SIGMASKTYPE sigprocmask_set;
177
f78f1a83 178
3480d92b 179#if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
f78f1a83 180
b6682dd9 181/* Return the current working directory. Returns NULL on errors.
f78f1a83
EZ
182 Any other returned value must be freed with free. This is used
183 only when get_current_dir_name is not defined on the system. */
184char*
185get_current_dir_name ()
186{
187 char *buf;
188 char *pwd;
189 struct stat dotstat, pwdstat;
190 /* If PWD is accurate, use it instead of calling getwd. PWD is
191 sometimes a nicer name, and using it may avoid a fatal error if a
192 parent directory is searchable but not readable. */
193 if ((pwd = getenv ("PWD")) != 0
194 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
195 && stat (pwd, &pwdstat) == 0
196 && stat (".", &dotstat) == 0
197 && dotstat.st_ino == pwdstat.st_ino
198 && dotstat.st_dev == pwdstat.st_dev
199#ifdef MAXPATHLEN
200 && strlen (pwd) < MAXPATHLEN
201#endif
202 )
203 {
204 buf = (char *) malloc (strlen (pwd) + 1);
205 if (!buf)
206 return NULL;
207 strcpy (buf, pwd);
208 }
209#ifdef HAVE_GETCWD
210 else
211 {
212 size_t buf_size = 1024;
b6682dd9 213 buf = (char *) malloc (buf_size);
f78f1a83
EZ
214 if (!buf)
215 return NULL;
216 for (;;)
217 {
218 if (getcwd (buf, buf_size) == buf)
219 break;
220 if (errno != ERANGE)
221 {
222 int tmp_errno = errno;
223 free (buf);
224 errno = tmp_errno;
225 return NULL;
226 }
227 buf_size *= 2;
228 buf = (char *) realloc (buf, buf_size);
229 if (!buf)
230 return NULL;
231 }
232 }
233#else
234 else
235 {
236 /* We need MAXPATHLEN here. */
237 buf = (char *) malloc (MAXPATHLEN + 1);
238 if (!buf)
239 return NULL;
240 if (getwd (buf) == NULL)
241 {
242 int tmp_errno = errno;
243 free (buf);
244 errno = tmp_errno;
245 return NULL;
246 }
247 }
248#endif
249 return buf;
250}
251#endif
252
64e971c3 253\f
9628b887 254/* Discard pending input on all input descriptors. */
91bac16a 255
08633194 256void
971de7fb 257discard_tty_input (void)
86a5659e 258{
fe03522b 259#ifndef WINDOWSNT
91bac16a 260 struct emacs_tty buf;
86a5659e
JB
261
262 if (noninteractive)
263 return;
264
fe03522b 265#ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
207bdbdb 266 while (dos_keyread () != -1)
fe03522b 267 ;
207bdbdb 268#else /* not MSDOS */
9628b887 269 {
28d7d09f 270 struct tty_display_info *tty;
9628b887
KL
271 for (tty = tty_list; tty; tty = tty->next)
272 {
0b0d3e0b
KL
273 if (tty->input) /* Is the device suspended? */
274 {
275 EMACS_GET_TTY (fileno (tty->input), &buf);
276 EMACS_SET_TTY (fileno (tty->input), &buf, 0);
277 }
9628b887
KL
278 }
279 }
207bdbdb 280#endif /* not MSDOS */
fe03522b 281#endif /* not WINDOWSNT */
86a5659e
JB
282}
283
16c290d8 284\f
86a5659e
JB
285#ifdef SIGTSTP
286
64e971c3 287/* Arrange for character C to be read as the next input from
16c290d8
KL
288 the terminal.
289 XXX What if we have multiple ttys?
290*/
64e971c3 291
dfcf069d 292void
0c2338d8 293stuff_char (char c)
86a5659e 294{
428a555e 295 if (! FRAME_TERMCAP_P (SELECTED_FRAME ()))
23dab951
RS
296 return;
297
86a5659e
JB
298/* Should perhaps error if in batch mode */
299#ifdef TIOCSTI
0b0d3e0b 300 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
86a5659e 301#else /* no TIOCSTI */
71f06467 302 error ("Cannot stuff terminal input characters in this version of Unix");
86a5659e
JB
303#endif /* no TIOCSTI */
304}
305
306#endif /* SIGTSTP */
64e971c3 307\f
08633194 308void
16c290d8 309init_baud_rate (int fd)
86a5659e 310{
86a5659e 311 if (noninteractive)
5bdd7bdd 312 emacs_ospeed = 0;
86a5659e
JB
313 else
314 {
fe03522b 315#ifdef DOS_NT
5bdd7bdd 316 emacs_ospeed = 15;
fe03522b 317#else /* not DOS_NT */
e04a4e0d
JB
318#ifdef HAVE_TERMIOS
319 struct termios sg;
91bac16a 320
71f06467 321 sg.c_cflag = B9600;
16c290d8 322 tcgetattr (fd, &sg);
5bdd7bdd 323 emacs_ospeed = cfgetospeed (&sg);
7c2fb837 324#else /* not TERMIOS */
e04a4e0d
JB
325#ifdef HAVE_TERMIO
326 struct termio sg;
91bac16a 327
71f06467 328 sg.c_cflag = B9600;
e04a4e0d 329#ifdef HAVE_TCATTR
16c290d8 330 tcgetattr (fd, &sg);
e04a4e0d 331#else
16c290d8 332 ioctl (fd, TCGETA, &sg);
e04a4e0d 333#endif
5bdd7bdd 334 emacs_ospeed = sg.c_cflag & CBAUD;
7c2fb837 335#else /* neither TERMIOS nor TERMIO */
91bac16a 336 struct sgttyb sg;
177c0ea7 337
91bac16a 338 sg.sg_ospeed = B9600;
16c290d8 339 if (ioctl (fd, TIOCGETP, &sg) < 0)
d7272cff 340 abort ();
5bdd7bdd 341 emacs_ospeed = sg.sg_ospeed;
91bac16a 342#endif /* not HAVE_TERMIO */
e04a4e0d 343#endif /* not HAVE_TERMIOS */
fe03522b 344#endif /* not DOS_NT */
86a5659e 345 }
177c0ea7 346
5bdd7bdd
GM
347 baud_rate = (emacs_ospeed < sizeof baud_convert / sizeof baud_convert[0]
348 ? baud_convert[emacs_ospeed] : 9600);
86a5659e
JB
349 if (baud_rate == 0)
350 baud_rate = 1200;
351}
352
16c290d8 353\f
86a5659e 354/*ARGSUSED*/
dfcf069d 355void
971de7fb 356set_exclusive_use (int fd)
86a5659e
JB
357{
358#ifdef FIOCLEX
359 ioctl (fd, FIOCLEX, 0);
360#endif
361 /* Ok to do nothing if this feature does not exist */
362}
64e971c3 363\f
86a5659e
JB
364#ifndef subprocesses
365
366wait_without_blocking ()
367{
86a5659e 368 croak ("wait_without_blocking");
86a5659e
JB
369 synch_process_alive = 0;
370}
371
372#endif /* not subprocesses */
373
374int wait_debugging; /* Set nonzero to make following function work under dbx
fe03522b 375 (at least for bsd). */
86a5659e
JB
376
377SIGTYPE
971de7fb 378wait_for_termination_signal (void)
86a5659e
JB
379{}
380
381/* Wait for subprocess with process id `pid' to terminate and
382 make sure it will get eliminated (not remain forever as a zombie) */
383
08633194 384void
971de7fb 385wait_for_termination (int pid)
86a5659e
JB
386{
387 while (1)
388 {
389#ifdef subprocesses
f2a77c3a 390#if defined (BSD_SYSTEM) || defined (HPUX)
4c8975ad
RS
391 /* Note that kill returns -1 even if the process is just a zombie now.
392 But inevitably a SIGCHLD interrupt should be generated
393 and child_sig will do wait3 and make the process go away. */
394 /* There is some indication that there is a bug involved with
395 termination of subprocesses, perhaps involving a kernel bug too,
396 but no idea what it is. Just as a hunch we signal SIGCHLD to see
397 if that causes the problem to go away or get worse. */
398 sigsetmask (sigmask (SIGCHLD));
399 if (0 > kill (pid, 0))
fe03522b 400 {
4c8975ad
RS
401 sigsetmask (SIGEMPTYMASK);
402 kill (getpid (), SIGCHLD);
403 break;
404 }
405 if (wait_debugging)
406 sleep (1);
407 else
408 sigpause (SIGEMPTYMASK);
2a633456 409#else /* not BSD_SYSTEM, and not HPUX version >= 6 */
d6dae14b
EZ
410#ifdef WINDOWSNT
411 wait (0);
412 break;
413#else /* not WINDOWSNT */
9ab714c7 414 sigblock (sigmask (SIGCHLD));
59957f85
GM
415 errno = 0;
416 if (kill (pid, 0) == -1 && errno == ESRCH)
9ab714c7
RS
417 {
418 sigunblock (sigmask (SIGCHLD));
419 break;
420 }
ac3ac859 421
0fdcb867 422 sigsuspend (&empty_mask);
d6dae14b 423#endif /* not WINDOWSNT */
2a633456 424#endif /* not BSD_SYSTEM, and not HPUX version >= 6 */
86a5659e 425#else /* not subprocesses */
15614e61 426 break;
86a5659e
JB
427#endif /* not subprocesses */
428 }
429}
430
431#ifdef subprocesses
432
433/*
434 * flush any pending output
435 * (may flush input as well; it does not matter the way we use it)
436 */
177c0ea7 437
08633194 438void
971de7fb 439flush_pending_output (int channel)
86a5659e
JB
440{
441#ifdef HAVE_TERMIOS
442 /* If we try this, we get hit with SIGTTIN, because
443 the child's tty belongs to the child's pgrp. */
444#else
445#ifdef TCFLSH
446 ioctl (channel, TCFLSH, 1);
447#else
448#ifdef TIOCFLUSH
449 int zero = 0;
450 /* 3rd arg should be ignored
451 but some 4.2 kernels actually want the address of an int
452 and nonzero means something different. */
453 ioctl (channel, TIOCFLUSH, &zero);
454#endif
455#endif
456#endif
457}
64e971c3 458\f
86a5659e
JB
459/* Set up the terminal at the other end of a pseudo-terminal that
460 we will be controlling an inferior through.
461 It should not echo or do line-editing, since that is done
462 in Emacs. No padding needed for insertion into an Emacs buffer. */
463
08633194 464void
971de7fb 465child_setup_tty (int out)
86a5659e 466{
fe03522b 467#ifndef DOS_NT
91bac16a
JB
468 struct emacs_tty s;
469
470 EMACS_GET_TTY (out, &s);
86a5659e 471
31be8d24 472#if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
91bac16a
JB
473 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
474 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
9d4e5eea 475#ifdef NLDLY
07cfc4e7
GM
476 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
477 Some versions of GNU Hurd do not have FFDLY? */
478#ifdef FFDLY
91bac16a
JB
479 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
480 /* No output delays */
07cfc4e7
GM
481#else
482 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
483 /* No output delays */
484#endif
9d4e5eea 485#endif
91bac16a
JB
486 s.main.c_lflag &= ~ECHO; /* Disable echo */
487 s.main.c_lflag |= ISIG; /* Enable signals */
9d4e5eea
RS
488#ifdef IUCLC
489 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
490#endif
f7097b2a
RS
491#ifdef ISTRIP
492 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
493#endif
23e4c8be 494#ifdef OLCUC
9d4e5eea
RS
495 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
496#endif
f7097b2a 497 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1bf96fb5 498 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
441f6399
RS
499 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
500 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
91bac16a 501
86a5659e 502#ifdef HPUX
91bac16a 503 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
86a5659e 504#endif /* HPUX */
91bac16a 505
dfe598b5
RS
506#ifdef SIGNALS_VIA_CHARACTERS
507 /* the QUIT and INTR character are used in process_send_signal
508 so set them here to something useful. */
fa51fa32 509 if (s.main.c_cc[VQUIT] == CDISABLE)
dfe598b5 510 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
fa51fa32 511 if (s.main.c_cc[VINTR] == CDISABLE)
dfe598b5
RS
512 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
513#endif /* not SIGNALS_VIA_CHARACTERS */
514
86a5659e 515#ifdef AIX
86a5659e
JB
516 /* Also, PTY overloads NUL and BREAK.
517 don't ignore break, but don't signal either, so it looks like NUL. */
91bac16a
JB
518 s.main.c_iflag &= ~IGNBRK;
519 s.main.c_iflag &= ~BRKINT;
dfe598b5
RS
520 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
521 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
522 would force it to 0377. That looks like duplicated code. */
91bac16a 523 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
86a5659e
JB
524#endif /* AIX */
525
2b0a91e7
SM
526 /* We used to enable ICANON (and set VEOF to 04), but this leads to
527 problems where process.c wants to send EOFs every once in a while
528 to force the output, which leads to weird effects when the
529 subprocess has disabled ICANON and ends up seeing those spurious
530 extra EOFs. So we don't send EOFs any more in
531 process.c:send_process, and instead we disable ICANON by default,
532 so if a subsprocess sets up ICANON, it's his problem (or the Elisp
533 package that talks to it) to deal with lines that are too long. */
534 s.main.c_lflag &= ~ICANON; /* Disable line editing and eof processing */
535 s.main.c_cc[VMIN] = 1;
536 s.main.c_cc[VTIME] = 0;
537
06ac62b4
SM
538#else /* not HAVE_TERMIO */
539
540 s.main.sg_flags &= ~(ECHO | CRMOD | ANYP | ALLDELAY | RAW | LCASE
541 | CBREAK | TANDEM);
542 s.main.sg_flags |= LPASS8;
543 s.main.sg_erase = 0377;
544 s.main.sg_kill = 0377;
545 s.lmode = LLITOUT | s.lmode; /* Don't strip 8th bit */
546
86a5659e
JB
547#endif /* not HAVE_TERMIO */
548
91bac16a 549 EMACS_SET_TTY (out, &s, 0);
86a5659e 550
fe03522b 551#endif /* not DOS_NT */
86a5659e 552}
86a5659e
JB
553
554#endif /* subprocesses */
64e971c3 555\f
86a5659e
JB
556/* Record a signal code and the handler for it. */
557struct save_signal
558{
559 int code;
f57e2426 560 SIGTYPE (*handler) (int);
86a5659e
JB
561};
562
f57e2426
J
563static void save_signal_handlers (struct save_signal *);
564static void restore_signal_handlers (struct save_signal *);
35a05cca 565
86a5659e
JB
566/* Suspend the Emacs process; give terminal to its superior. */
567
08633194 568void
971de7fb 569sys_suspend (void)
86a5659e 570{
c4ea52a6 571#if defined (SIGTSTP) && !defined (MSDOS)
86a5659e 572
5a570e37 573 {
e89a2cd5 574 int pgrp = EMACS_GETPGRP (0);
5a570e37
JB
575 EMACS_KILLPG (pgrp, SIGTSTP);
576 }
86a5659e
JB
577
578#else /* No SIGTSTP */
86a5659e
JB
579/* On a system where suspending is not implemented,
580 instead fork a subshell and let it talk directly to the terminal
581 while we wait. */
a0932daa
KH
582 sys_subshell ();
583
a0932daa 584#endif /* no SIGTSTP */
a0932daa
KH
585}
586
587/* Fork a subshell. */
588
08633194 589void
971de7fb 590sys_subshell (void)
a0932daa 591{
ad00c243 592#ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
a0932daa
KH
593 int st;
594 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
595#endif
efa04277 596 int pid;
86a5659e 597 struct save_signal saved_handlers[5];
efa04277
RS
598 Lisp_Object dir;
599 unsigned char *str = 0;
600 int len;
86a5659e
JB
601
602 saved_handlers[0].code = SIGINT;
603 saved_handlers[1].code = SIGQUIT;
604 saved_handlers[2].code = SIGTERM;
605#ifdef SIGIO
606 saved_handlers[3].code = SIGIO;
607 saved_handlers[4].code = 0;
608#else
609 saved_handlers[3].code = 0;
610#endif
611
efa04277
RS
612 /* Mentioning current_buffer->buffer would mean including buffer.h,
613 which somehow wedges the hp compiler. So instead... */
614
615 dir = intern ("default-directory");
0e7e7a58 616 if (NILP (Fboundp (dir)))
efa04277
RS
617 goto xyzzy;
618 dir = Fsymbol_value (dir);
914e81a2 619 if (!STRINGP (dir))
efa04277
RS
620 goto xyzzy;
621
622 dir = expand_and_dir_to_file (Funhandled_file_name_directory (dir), Qnil);
d5db4077
KR
623 str = (unsigned char *) alloca (SCHARS (dir) + 2);
624 len = SCHARS (dir);
625 bcopy (SDATA (dir), str, len);
efa04277
RS
626 if (str[len - 1] != '/') str[len++] = '/';
627 str[len] = 0;
628 xyzzy:
629
ad00c243 630#ifdef DOS_NT
7964ba9e 631 pid = 0;
718ca3cf
RS
632 save_signal_handlers (saved_handlers);
633 synch_process_alive = 1;
177c0ea7 634#else
efa04277 635 pid = vfork ();
86a5659e
JB
636 if (pid == -1)
637 error ("Can't spawn subshell");
7964ba9e
RS
638#endif
639
86a5659e
JB
640 if (pid == 0)
641 {
7964ba9e 642 char *sh = 0;
86a5659e 643
ad00c243 644#ifdef DOS_NT /* MW, Aug 1993 */
207bdbdb 645 getwd (oldwd);
7964ba9e
RS
646 if (sh == 0)
647 sh = (char *) egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
207bdbdb 648#endif
7964ba9e
RS
649 if (sh == 0)
650 sh = (char *) egetenv ("SHELL");
86a5659e
JB
651 if (sh == 0)
652 sh = "sh";
207bdbdb 653
86a5659e 654 /* Use our buffer's default directory for the subshell. */
efa04277 655 if (str)
074c438c 656 chdir ((char *) str);
efa04277 657
86a5659e
JB
658#ifdef subprocesses
659 close_process_descs (); /* Close Emacs's pipes/ptys */
660#endif
1593c2fe 661
6f8b4d01 662#ifdef SET_EMACS_PRIORITY
1593c2fe 663 {
31ade731 664 extern EMACS_INT emacs_priority;
1593c2fe 665
6f8b4d01 666 if (emacs_priority < 0)
1593c2fe
JB
667 nice (-emacs_priority);
668 }
669#endif
670
fe03522b 671#ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
c0917202 672 {
48178f9a
EZ
673 char *epwd = getenv ("PWD");
674 char old_pwd[MAXPATHLEN+1+4];
c0917202
EZ
675
676 /* If PWD is set, pass it with corrected value. */
48178f9a 677 if (epwd)
c0917202 678 {
48178f9a 679 strcpy (old_pwd, epwd);
c0917202
EZ
680 if (str[len - 1] == '/')
681 str[len - 1] = '\0';
682 setenv ("PWD", str, 1);
683 }
684 st = system (sh);
685 chdir (oldwd);
48178f9a 686 if (epwd)
c0917202
EZ
687 putenv (old_pwd); /* restore previous value */
688 }
207bdbdb 689#else /* not MSDOS */
fe03522b 690#ifdef WINDOWSNT
fe03522b
RS
691 /* Waits for process completion */
692 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
ad00c243 693 chdir (oldwd);
fe03522b
RS
694 if (pid == -1)
695 write (1, "Can't execute subshell", 22);
fe03522b 696#else /* not WINDOWSNT */
e120ea40 697 execlp (sh, sh, (char *) 0);
86a5659e
JB
698 write (1, "Can't execute subshell", 22);
699 _exit (1);
fe03522b 700#endif /* not WINDOWSNT */
207bdbdb 701#endif /* not MSDOS */
86a5659e
JB
702 }
703
718ca3cf 704 /* Do this now if we did not do it before. */
ed68db4d 705#ifndef MSDOS
86a5659e 706 save_signal_handlers (saved_handlers);
ffafc793 707 synch_process_alive = 1;
718ca3cf
RS
708#endif
709
ad00c243 710#ifndef DOS_NT
86a5659e 711 wait_for_termination (pid);
7964ba9e 712#endif
86a5659e 713 restore_signal_handlers (saved_handlers);
718ca3cf 714 synch_process_alive = 0;
86a5659e
JB
715}
716
35a05cca 717static void
971de7fb 718save_signal_handlers (struct save_signal *saved_handlers)
86a5659e
JB
719{
720 while (saved_handlers->code)
721 {
508b171c 722 saved_handlers->handler
f57e2426 723 = (SIGTYPE (*) (int)) signal (saved_handlers->code, SIG_IGN);
86a5659e
JB
724 saved_handlers++;
725 }
726}
727
35a05cca 728static void
971de7fb 729restore_signal_handlers (struct save_signal *saved_handlers)
86a5659e
JB
730{
731 while (saved_handlers->code)
732 {
733 signal (saved_handlers->code, saved_handlers->handler);
734 saved_handlers++;
735 }
736}
737\f
4d553a13
KL
738#ifndef SIGIO
739/* If SIGIO is broken, don't do anything. */
740void
741init_sigio (int fd)
742{
743}
744
745void
746reset_sigio (int fd)
747{
748}
749
750void
751request_sigio (void)
752{
753}
754
755void
756unrequest_sigio (void)
757{
758}
759
760#else
86a5659e
JB
761#ifdef F_SETFL
762
819b8f00 763int old_fcntl_flags[MAXDESC];
86a5659e 764
08633194 765void
971de7fb 766init_sigio (int fd)
86a5659e
JB
767{
768#ifdef FASYNC
819b8f00
KL
769 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
770 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
86a5659e 771#endif
23dab951 772 interrupts_deferred = 0;
86a5659e
JB
773}
774
590034f9 775void
971de7fb 776reset_sigio (int fd)
86a5659e 777{
4d553a13 778#ifdef FASYNC
819b8f00 779 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
4d553a13 780#endif
86a5659e
JB
781}
782
eb8c3be9 783#ifdef FASYNC /* F_SETFL does not imply existence of FASYNC */
428a555e 784/* XXX Uhm, FASYNC is not used anymore here. */
6d8cf830 785/* XXX Yeah, but you need it for SIGIO, don't you? */
86a5659e 786
08633194 787void
971de7fb 788request_sigio (void)
86a5659e 789{
6bbba5a6 790 if (noninteractive)
23dab951
RS
791 return;
792
86a5659e 793#ifdef SIGWINCH
e065a56e 794 sigunblock (sigmask (SIGWINCH));
86a5659e 795#endif
0a125897 796 sigunblock (sigmask (SIGIO));
86a5659e
JB
797
798 interrupts_deferred = 0;
799}
800
08633194 801void
0a125897 802unrequest_sigio (void)
428a555e 803{
6bbba5a6
KL
804 if (noninteractive)
805 return;
806
807#if 0 /* XXX What's wrong with blocking SIGIO under X? */
808 if (x_display_list)
23dab951 809 return;
428a555e 810#endif
6bbba5a6 811
86a5659e 812#ifdef SIGWINCH
e065a56e 813 sigblock (sigmask (SIGWINCH));
86a5659e 814#endif
0a125897 815 sigblock (sigmask (SIGIO));
86a5659e
JB
816 interrupts_deferred = 1;
817}
818
819#else /* no FASYNC */
feb67dfe 820#ifndef MSDOS
25ab68af 821
08633194 822void
86a5659e
JB
823request_sigio ()
824{
6e5b2385 825 if (noninteractive || read_socket_hook)
23dab951
RS
826 return;
827
86a5659e
JB
828 croak ("request_sigio");
829}
177c0ea7 830
08633194 831void
86a5659e
JB
832unrequest_sigio ()
833{
6e5b2385 834 if (noninteractive || read_socket_hook)
23dab951
RS
835 return;
836
86a5659e
JB
837 croak ("unrequest_sigio");
838}
feb67dfe
EZ
839
840#endif /* MSDOS */
86a5659e
JB
841#endif /* FASYNC */
842#endif /* F_SETFL */
4d553a13 843#endif /* SIGIO */
9ae8f997 844
9ae8f997 845\f
68936329
JB
846/* Getting and setting emacs_tty structures. */
847
848/* Set *TC to the parameters associated with the terminal FD.
849 Return zero if all's well, or -1 if we ran into an error we
850 couldn't deal with. */
851int
971de7fb 852emacs_get_tty (int fd, struct emacs_tty *settings)
68936329
JB
853{
854 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
855#ifdef HAVE_TCATTR
856 /* We have those nifty POSIX tcmumbleattr functions. */
1d9f9f9e 857 bzero (&settings->main, sizeof (settings->main));
68936329
JB
858 if (tcgetattr (fd, &settings->main) < 0)
859 return -1;
860
861#else
862#ifdef HAVE_TERMIO
863 /* The SYSV-style interface? */
864 if (ioctl (fd, TCGETA, &settings->main) < 0)
865 return -1;
866
68936329 867#else
fe03522b 868#ifndef DOS_NT
68936329
JB
869 /* I give up - I hope you have the BSD ioctls. */
870 if (ioctl (fd, TIOCGETP, &settings->main) < 0)
871 return -1;
fe03522b 872#endif /* not DOS_NT */
68936329 873#endif
68936329
JB
874#endif
875
876 /* Suivant - Do we have to get struct ltchars data? */
50b8cf60 877#ifdef HAVE_LTCHARS
68936329
JB
878 if (ioctl (fd, TIOCGLTC, &settings->ltchars) < 0)
879 return -1;
880#endif
881
882 /* How about a struct tchars and a wordful of lmode bits? */
50b8cf60 883#ifdef HAVE_TCHARS
68936329
JB
884 if (ioctl (fd, TIOCGETC, &settings->tchars) < 0
885 || ioctl (fd, TIOCLGET, &settings->lmode) < 0)
886 return -1;
887#endif
888
889 /* We have survived the tempest. */
890 return 0;
891}
892
893
894/* Set the parameters of the tty on FD according to the contents of
394049ec 895 *SETTINGS. If FLUSHP is non-zero, we discard input.
68936329 896 Return 0 if all went well, and -1 if anything failed. */
394049ec 897
68936329 898int
971de7fb 899emacs_set_tty (int fd, struct emacs_tty *settings, int flushp)
68936329
JB
900{
901 /* Set the primary parameters - baud rate, character size, etcetera. */
902#ifdef HAVE_TCATTR
e6cc3307 903 int i;
68936329
JB
904 /* We have those nifty POSIX tcmumbleattr functions.
905 William J. Smith <wjs@wiis.wang.com> writes:
c4ea52a6 906 "POSIX 1003.1 defines tcsetattr to return success if it was
68936329
JB
907 able to perform any of the requested actions, even if some
908 of the requested actions could not be performed.
909 We must read settings back to ensure tty setup properly.
910 AIX requires this to keep tty from hanging occasionally." */
eb8c3be9 911 /* This make sure that we don't loop indefinitely in here. */
e6cc3307 912 for (i = 0 ; i < 10 ; i++)
394049ec 913 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
68936329
JB
914 {
915 if (errno == EINTR)
916 continue;
917 else
918 return -1;
919 }
920 else
921 {
922 struct termios new;
923
1d9f9f9e 924 bzero (&new, sizeof (new));
68936329
JB
925 /* Get the current settings, and see if they're what we asked for. */
926 tcgetattr (fd, &new);
e6cc3307
RS
927 /* We cannot use memcmp on the whole structure here because under
928 * aix386 the termios structure has some reserved field that may
929 * not be filled in.
930 */
931 if ( new.c_iflag == settings->main.c_iflag
932 && new.c_oflag == settings->main.c_oflag
933 && new.c_cflag == settings->main.c_cflag
934 && new.c_lflag == settings->main.c_lflag
c4ea52a6 935 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
68936329 936 break;
e6cc3307
RS
937 else
938 continue;
68936329
JB
939 }
940
941#else
942#ifdef HAVE_TERMIO
943 /* The SYSV-style interface? */
394049ec 944 if (ioctl (fd, flushp ? TCSETAF : TCSETAW, &settings->main) < 0)
68936329
JB
945 return -1;
946
68936329 947#else
fe03522b 948#ifndef DOS_NT
68936329 949 /* I give up - I hope you have the BSD ioctls. */
394049ec 950 if (ioctl (fd, (flushp) ? TIOCSETP : TIOCSETN, &settings->main) < 0)
68936329 951 return -1;
fe03522b 952#endif /* not DOS_NT */
68936329 953
68936329
JB
954#endif
955#endif
956
957 /* Suivant - Do we have to get struct ltchars data? */
50b8cf60 958#ifdef HAVE_LTCHARS
68936329
JB
959 if (ioctl (fd, TIOCSLTC, &settings->ltchars) < 0)
960 return -1;
961#endif
962
963 /* How about a struct tchars and a wordful of lmode bits? */
50b8cf60 964#ifdef HAVE_TCHARS
68936329
JB
965 if (ioctl (fd, TIOCSETC, &settings->tchars) < 0
966 || ioctl (fd, TIOCLSET, &settings->lmode) < 0)
967 return -1;
968#endif
177c0ea7 969
68936329
JB
970 /* We have survived the tempest. */
971 return 0;
972}
973
974\f
86a5659e
JB
975
976#ifdef F_SETOWN
819b8f00 977int old_fcntl_owner[MAXDESC];
86a5659e
JB
978#endif /* F_SETOWN */
979
86a5659e
JB
980/* This may also be defined in stdio,
981 but if so, this does no harm,
982 and using the same name avoids wasting the other one's space. */
983
9d9a7716 984#if defined (USG)
86a5659e
JB
985unsigned char _sobuf[BUFSIZ+8];
986#else
987char _sobuf[BUFSIZ];
988#endif
177c0ea7 989
50b8cf60 990#ifdef HAVE_LTCHARS
86a5659e
JB
991static struct ltchars new_ltchars = {-1,-1,-1,-1,-1,-1};
992#endif
50b8cf60 993#ifdef HAVE_TCHARS
4ec5cb58 994static struct tchars new_tchars = {-1,-1,-1,-1,-1,-1};
177c0ea7 995#endif
86a5659e 996
da8e1115
KL
997/* Initialize the terminal mode on all tty devices that are currently
998 open. */
999
08633194 1000void
28d440ab
KL
1001init_all_sys_modes (void)
1002{
28d7d09f 1003 struct tty_display_info *tty;
16c290d8 1004 for (tty = tty_list; tty; tty = tty->next)
28d440ab 1005 init_sys_modes (tty);
28d440ab
KL
1006}
1007
da8e1115
KL
1008/* Initialize the terminal mode on the given tty device. */
1009
28d440ab 1010void
971de7fb 1011init_sys_modes (struct tty_display_info *tty_out)
86a5659e 1012{
91bac16a
JB
1013 struct emacs_tty tty;
1014
4ec5cb58
RS
1015 Vtty_erase_char = Qnil;
1016
86a5659e
JB
1017 if (noninteractive)
1018 return;
1019
0b0d3e0b
KL
1020 if (!tty_out->output)
1021 return; /* The tty is suspended. */
1022
2246281f
KL
1023 if (! tty_out->old_tty)
1024 tty_out->old_tty = (struct emacs_tty *) xmalloc (sizeof (struct emacs_tty));
fca177d4 1025
0b0d3e0b 1026 EMACS_GET_TTY (fileno (tty_out->input), tty_out->old_tty);
23dab951 1027
2246281f 1028 tty = *tty_out->old_tty;
86a5659e 1029
31be8d24 1030#if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
2246281f 1031 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
4ec5cb58 1032
2246281f
KL
1033 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1034 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
7f371164
RS
1035#ifdef INLCR /* I'm just being cautious,
1036 since I can't check how widespread INLCR is--rms. */
2246281f 1037 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
7f371164 1038#endif
86a5659e 1039#ifdef ISTRIP
2246281f 1040 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
86a5659e 1041#endif
2246281f
KL
1042 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1043 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
e2b40c23 1044#ifdef IEXTEN
2246281f 1045 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
e2b40c23 1046#endif
2246281f
KL
1047 tty.main.c_lflag |= ISIG; /* Enable signals */
1048 if (tty_out->flow_control)
1049 {
1050 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
86a5659e 1051#ifdef IXANY
2246281f 1052 tty.main.c_iflag &= ~IXANY;
86a5659e 1053#endif /* IXANY */
2246281f
KL
1054 }
1055 else
1056 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1057 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1058 on output */
1059 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
86a5659e 1060#ifdef CS8
2246281f
KL
1061 if (tty_out->meta_key)
1062 {
1063 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1064 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1065 }
86a5659e 1066#endif
2246281f
KL
1067 if (tty_out->input == stdin)
1068 {
1069 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1070 /* Set up C-g for both SIGQUIT and SIGINT.
1071 We don't know which we will get, but we handle both alike
1072 so which one it really gives us does not matter. */
1073 tty.main.c_cc[VQUIT] = quit_char;
1074 }
1075 else
1076 {
1077 /* We normally don't get interrupt or quit signals from tty
1078 devices other than our controlling terminal; therefore,
1079 we must handle C-g as normal input. Unfortunately, this
1080 means that the interrupt and quit feature must be
1081 disabled on secondary ttys, or we would not even see the
1082 keypress.
1083
1084 Note that even though emacsclient could have special code
1085 to pass SIGINT to Emacs, we should _not_ enable
1086 interrupt/quit keys for emacsclient frames. This means
1087 that we can't break out of loops in C code from a
1088 secondary tty frame, but we can always decide what
1089 display the C-g came from, which is more important from a
1090 usability point of view. (Consider the case when two
1091 people work together using the same Emacs instance.) */
1092 tty.main.c_cc[VINTR] = CDISABLE;
1093 tty.main.c_cc[VQUIT] = CDISABLE;
1094 }
1095 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1096 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
86a5659e 1097#ifdef VSWTCH
2246281f 1098 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
91bac16a 1099 of C-z */
86a5659e 1100#endif /* VSWTCH */
2246281f 1101
b8ff87cc 1102#if defined (__mips__) || defined (HAVE_TCATTR)
86a5659e 1103#ifdef VSUSP
2246281f 1104 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off mips handling of C-z. */
86a5659e
JB
1105#endif /* VSUSP */
1106#ifdef V_DSUSP
2246281f 1107 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off mips handling of C-y. */
86a5659e 1108#endif /* V_DSUSP */
e2b40c23 1109#ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
2246281f 1110 tty.main.c_cc[VDSUSP] = CDISABLE;
e2b40c23 1111#endif /* VDSUSP */
92c995de 1112#ifdef VLNEXT
2246281f 1113 tty.main.c_cc[VLNEXT] = CDISABLE;
92c995de
RS
1114#endif /* VLNEXT */
1115#ifdef VREPRINT
2246281f 1116 tty.main.c_cc[VREPRINT] = CDISABLE;
92c995de
RS
1117#endif /* VREPRINT */
1118#ifdef VWERASE
2246281f 1119 tty.main.c_cc[VWERASE] = CDISABLE;
92c995de
RS
1120#endif /* VWERASE */
1121#ifdef VDISCARD
2246281f 1122 tty.main.c_cc[VDISCARD] = CDISABLE;
92c995de 1123#endif /* VDISCARD */
c179a6d1 1124
2246281f
KL
1125 if (tty_out->flow_control)
1126 {
421dd92f 1127#ifdef VSTART
2246281f 1128 tty.main.c_cc[VSTART] = '\021';
421dd92f
RS
1129#endif /* VSTART */
1130#ifdef VSTOP
2246281f 1131 tty.main.c_cc[VSTOP] = '\023';
421dd92f 1132#endif /* VSTOP */
2246281f
KL
1133 }
1134 else
1135 {
c179a6d1 1136#ifdef VSTART
2246281f 1137 tty.main.c_cc[VSTART] = CDISABLE;
c179a6d1
RS
1138#endif /* VSTART */
1139#ifdef VSTOP
2246281f 1140 tty.main.c_cc[VSTOP] = CDISABLE;
c179a6d1 1141#endif /* VSTOP */
2246281f 1142 }
86a5659e 1143#endif /* mips or HAVE_TCATTR */
c179a6d1 1144
86a5659e 1145#ifdef AIX
f5272227
KL
1146 tty.main.c_cc[VSTRT] = CDISABLE;
1147 tty.main.c_cc[VSTOP] = CDISABLE;
1148 tty.main.c_cc[VSUSP] = CDISABLE;
1149 tty.main.c_cc[VDSUSP] = CDISABLE;
2246281f
KL
1150 if (tty_out->flow_control)
1151 {
ac567c95 1152#ifdef VSTART
2246281f 1153 tty.main.c_cc[VSTART] = '\021';
ac567c95
RS
1154#endif /* VSTART */
1155#ifdef VSTOP
2246281f 1156 tty.main.c_cc[VSTOP] = '\023';
ac567c95 1157#endif /* VSTOP */
2246281f
KL
1158 }
1159 /* Also, PTY overloads NUL and BREAK.
1160 don't ignore break, but don't signal either, so it looks like NUL.
1161 This really serves a purpose only if running in an XTERM window
1162 or via TELNET or the like, but does no harm elsewhere. */
1163 tty.main.c_iflag &= ~IGNBRK;
1164 tty.main.c_iflag &= ~BRKINT;
86a5659e
JB
1165#endif
1166#else /* if not HAVE_TERMIO */
fe03522b 1167#ifndef DOS_NT
2246281f
KL
1168 XSETINT (Vtty_erase_char, tty.main.sg_erase);
1169 tty.main.sg_flags &= ~(ECHO | CRMOD | XTABS);
1170 if (meta_key)
1171 tty.main.sg_flags |= ANYP;
1172 tty.main.sg_flags |= interrupt_input ? RAW : CBREAK;
fe03522b 1173#endif /* not DOS_NT */
86a5659e
JB
1174#endif /* not HAVE_TERMIO */
1175
2246281f
KL
1176 /* If going to use CBREAK mode, we must request C-g to interrupt
1177 and turn off start and stop chars, etc. If not going to use
1178 CBREAK mode, do this anyway so as to turn off local flow
1179 control for user coming over network on 4.2; in this case,
1180 only t_stopc and t_startc really matter. */
91bac16a 1181#ifndef HAVE_TERMIO
50b8cf60 1182#ifdef HAVE_TCHARS
2246281f
KL
1183 /* Note: if not using CBREAK mode, it makes no difference how we
1184 set this */
1185 tty.tchars = new_tchars;
1186 tty.tchars.t_intrc = quit_char;
1187 if (tty_out->flow_control)
1188 {
1189 tty.tchars.t_startc = '\021';
1190 tty.tchars.t_stopc = '\023';
1191 }
1192
1193 tty.lmode = LDECCTQ | LLITOUT | LPASS8 | LNOFLSH | tty_out->old_tty.lmode;
2246281f 1194
50b8cf60 1195#endif /* HAVE_TCHARS */
91bac16a
JB
1196#endif /* not HAVE_TERMIO */
1197
50b8cf60 1198#ifdef HAVE_LTCHARS
2246281f 1199 tty.ltchars = new_ltchars;
50b8cf60 1200#endif /* HAVE_LTCHARS */
207bdbdb 1201#ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
2246281f
KL
1202 if (!tty_out->term_initted)
1203 internal_terminal_init ();
4e389d32 1204 dos_ttraw (tty_out);
207bdbdb 1205#endif
91bac16a 1206
0b0d3e0b 1207 EMACS_SET_TTY (fileno (tty_out->input), &tty, 0);
86a5659e 1208
2246281f
KL
1209 /* This code added to insure that, if flow-control is not to be used,
1210 we have an unlocked terminal at the start. */
91bac16a 1211
86a5659e 1212#ifdef TCXONC
0b0d3e0b 1213 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
86a5659e 1214#endif
86a5659e 1215#ifdef TIOCSTART
0b0d3e0b 1216 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
86a5659e 1217#endif
86a5659e 1218
f2a77c3a 1219#if defined (HAVE_TERMIOS) || defined (HPUX)
51417996 1220#ifdef TCOON
0b0d3e0b 1221 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
d228f207 1222#endif
51417996 1223#endif
d228f207 1224
86a5659e 1225#ifdef F_SETFL
eb8c3be9 1226#ifdef F_GETOWN /* F_SETFL does not imply existence of F_GETOWN */
2246281f 1227 if (interrupt_input)
86a5659e 1228 {
0b0d3e0b
KL
1229 old_fcntl_owner[fileno (tty_out->input)] =
1230 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1231 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1232 init_sigio (fileno (tty_out->input));
7e5a23bd 1233#ifdef HAVE_GPM
75a8734b 1234 if (gpm_tty == tty_out)
3e748bcb 1235 {
75a8734b 1236 /* Arrange for mouse events to give us SIGIO signals. */
3e748bcb 1237 fcntl (gpm_fd, F_SETOWN, getpid ());
57669cf1 1238 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
3e748bcb
NR
1239 init_sigio (gpm_fd);
1240 }
7e5a23bd 1241#endif /* HAVE_GPM */
86a5659e
JB
1242 }
1243#endif /* F_GETOWN */
1244#endif /* F_SETFL */
1245
86a5659e
JB
1246#ifdef _IOFBF
1247 /* This symbol is defined on recent USG systems.
1248 Someone says without this call USG won't really buffer the file
1249 even with a call to setbuf. */
0b0d3e0b 1250 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
86a5659e 1251#else
0b0d3e0b 1252 setbuf (tty_out->output, (char *) _sobuf);
86a5659e 1253#endif
4d553a13 1254
69fb5031
JR
1255 if (tty_out->terminal->set_terminal_modes_hook)
1256 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
4b311aaf 1257
9628b887
KL
1258 if (!tty_out->term_initted)
1259 {
1260 Lisp_Object tail, frame;
1261 FOR_EACH_FRAME (tail, frame)
1262 {
daf01701 1263 /* XXX This needs to be revised. */
9628b887
KL
1264 if (FRAME_TERMCAP_P (XFRAME (frame))
1265 && FRAME_TTY (XFRAME (frame)) == tty_out)
1266 init_frame_faces (XFRAME (frame));
1267 }
1268 }
045942b2 1269
9628b887 1270 if (tty_out->term_initted && no_redraw_on_reenter)
86a5659e 1271 {
855a0da7
SM
1272 /* We used to call "direct_output_forward_char(0)" here,
1273 but it's not clear why, since it may not do anything anyway. */
86a5659e
JB
1274 }
1275 else
1276 {
9628b887 1277 Lisp_Object tail, frame;
0137dbf7 1278 frame_garbaged = 1;
9628b887
KL
1279 FOR_EACH_FRAME (tail, frame)
1280 {
7ab98847
EZ
1281 if ((FRAME_TERMCAP_P (XFRAME (frame))
1282 || FRAME_MSDOS_P (XFRAME (frame)))
9628b887
KL
1283 && FRAME_TTY (XFRAME (frame)) == tty_out)
1284 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1285 }
86a5659e 1286 }
91bac16a 1287
9628b887 1288 tty_out->term_initted = 1;
86a5659e
JB
1289}
1290
1291/* Return nonzero if safe to use tabs in output.
1292 At the time this is called, init_sys_modes has not been done yet. */
177c0ea7 1293
dfcf069d 1294int
16c290d8 1295tabs_safe_p (int fd)
86a5659e 1296{
6548cf00 1297 struct emacs_tty etty;
91bac16a 1298
16c290d8 1299 EMACS_GET_TTY (fd, &etty);
6548cf00 1300 return EMACS_TTY_TABS_OK (&etty);
86a5659e 1301}
73d5358f 1302\f
86a5659e 1303/* Get terminal size from system.
73d5358f
RS
1304 Store number of lines into *HEIGHTP and width into *WIDTHP.
1305 We store 0 if there's no valid information. */
86a5659e 1306
08633194 1307void
16c290d8 1308get_tty_size (int fd, int *widthp, int *heightp)
86a5659e 1309{
86a5659e 1310
86a5659e 1311#ifdef TIOCGWINSZ
91bac16a
JB
1312
1313 /* BSD-style. */
86a5659e 1314 struct winsize size;
91bac16a 1315
16c290d8 1316 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
91bac16a
JB
1317 *widthp = *heightp = 0;
1318 else
1319 {
1320 *widthp = size.ws_col;
1321 *heightp = size.ws_row;
1322 }
1323
1324#else
1325#ifdef TIOCGSIZE
1326
1327 /* SunOS - style. */
177c0ea7 1328 struct ttysize size;
91bac16a 1329
16c290d8 1330 if (ioctl (fd, TIOCGSIZE, &size) == -1)
91bac16a
JB
1331 *widthp = *heightp = 0;
1332 else
1333 {
1334 *widthp = size.ts_cols;
1335 *heightp = size.ts_lines;
1336 }
1337
207bdbdb
RS
1338#else
1339#ifdef MSDOS
1340 *widthp = ScreenCols ();
1341 *heightp = ScreenRows ();
86a5659e
JB
1342#else /* system doesn't know size */
1343 *widthp = 0;
1344 *heightp = 0;
207bdbdb 1345#endif
91bac16a
JB
1346#endif /* not SunOS-style */
1347#endif /* not BSD-style */
86a5659e 1348}
91bac16a 1349
73d5358f
RS
1350/* Set the logical window size associated with descriptor FD
1351 to HEIGHT and WIDTH. This is used mainly with ptys. */
1352
1353int
971de7fb 1354set_window_size (int fd, int height, int width)
73d5358f
RS
1355{
1356#ifdef TIOCSWINSZ
1357
1358 /* BSD-style. */
1359 struct winsize size;
1360 size.ws_row = height;
1361 size.ws_col = width;
1362
1363 if (ioctl (fd, TIOCSWINSZ, &size) == -1)
1364 return 0; /* error */
1365 else
1366 return 1;
1367
1368#else
1369#ifdef TIOCSSIZE
1370
1371 /* SunOS - style. */
177c0ea7 1372 struct ttysize size;
73d5358f
RS
1373 size.ts_lines = height;
1374 size.ts_cols = width;
1375
1376 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1377 return 0;
1378 else
1379 return 1;
1380#else
1381 return -1;
1382#endif /* not SunOS-style */
1383#endif /* not BSD-style */
1384}
1385
86a5659e 1386\f
da8e1115
KL
1387
1388/* Prepare all terminal devices for exiting Emacs. */
1389
28d440ab
KL
1390void
1391reset_all_sys_modes (void)
1392{
28d7d09f 1393 struct tty_display_info *tty;
16c290d8 1394 for (tty = tty_list; tty; tty = tty->next)
28d440ab 1395 reset_sys_modes (tty);
28d440ab
KL
1396}
1397
0a125897 1398/* Prepare the terminal for closing it; move the cursor to the
0137dbf7 1399 bottom of the frame, turn off interrupt-driven I/O, etc. */
da8e1115 1400
08633194 1401void
971de7fb 1402reset_sys_modes (struct tty_display_info *tty_out)
86a5659e
JB
1403{
1404 if (noninteractive)
1405 {
1406 fflush (stdout);
1407 return;
1408 }
9628b887 1409 if (!tty_out->term_initted)
86a5659e 1410 return;
da8e1115 1411
0b0d3e0b
KL
1412 if (!tty_out->output)
1413 return; /* The tty is suspended. */
1414
da8e1115
KL
1415 /* Go to and clear the last line of the terminal. */
1416
0a125897 1417 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
0b0d3e0b 1418
da8e1115
KL
1419 /* Code adapted from tty_clear_end_of_line. */
1420 if (tty_out->TS_clr_line)
1421 {
1422 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1423 }
1424 else
1425 { /* have to do it the hard way */
1426 int i;
ed8dad6b 1427 tty_turn_off_insert (tty_out);
0b0d3e0b 1428
da8e1115 1429 for (i = curX (tty_out); i < FrameCols (tty_out) - 1; i++)
0b0d3e0b
KL
1430 {
1431 fputc (' ', tty_out->output);
1432 }
da8e1115 1433 }
0b0d3e0b 1434
0a125897 1435 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
819b8f00
KL
1436 fflush (tty_out->output);
1437
69fb5031
JR
1438 if (tty_out->terminal->reset_terminal_modes_hook)
1439 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
2f98e6e3 1440
2a633456 1441#ifdef BSD_SYSTEM
86a5659e 1442 /* Avoid possible loss of output when changing terminal modes. */
0b0d3e0b 1443 fsync (fileno (tty_out->output));
86a5659e 1444#endif
91bac16a 1445
86a5659e 1446#ifdef F_SETFL
eb8c3be9 1447#ifdef F_SETOWN /* F_SETFL does not imply existence of F_SETOWN */
86a5659e
JB
1448 if (interrupt_input)
1449 {
0b0d3e0b
KL
1450 reset_sigio (fileno (tty_out->input));
1451 fcntl (fileno (tty_out->input), F_SETOWN,
1452 old_fcntl_owner[fileno (tty_out->input)]);
86a5659e
JB
1453 }
1454#endif /* F_SETOWN */
a6b00318 1455#ifdef O_NDELAY
0b0d3e0b
KL
1456 fcntl (fileno (tty_out->input), F_SETFL,
1457 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NDELAY);
a6b00318 1458#endif
86a5659e 1459#endif /* F_SETFL */
91bac16a 1460
fca177d4 1461 if (tty_out->old_tty)
0b0d3e0b 1462 while (EMACS_SET_TTY (fileno (tty_out->input),
fca177d4 1463 tty_out->old_tty, 0) < 0 && errno == EINTR)
7e32a4fb 1464 ;
86a5659e 1465
207bdbdb
RS
1466#ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1467 dos_ttcooked ();
1468#endif
1469
86a5659e
JB
1470}
1471\f
1472#ifdef HAVE_PTYS
1473
1474/* Set up the proper status flags for use of a pty. */
1475
08633194 1476void
971de7fb 1477setup_pty (int fd)
86a5659e
JB
1478{
1479 /* I'm told that TOICREMOTE does not mean control chars
1480 "can't be sent" but rather that they don't have
1481 input-editing or signaling effects.
1482 That should be good, because we have other ways
1483 to do those things in Emacs.
1484 However, telnet mode seems not to work on 4.2.
1485 So TIOCREMOTE is turned off now. */
1486
1487 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1488 will hang. In particular, the "timeout" feature (which
1489 causes a read to return if there is no data available)
1490 does this. Also it is known that telnet mode will hang
1491 in such a way that Emacs must be stopped (perhaps this
1492 is the same problem).
177c0ea7 1493
86a5659e
JB
1494 If TIOCREMOTE is turned off, then there is a bug in
1495 hp-ux which sometimes loses data. Apparently the
1496 code which blocks the master process when the internal
1497 buffer fills up does not work. Other than this,
1498 though, everything else seems to work fine.
177c0ea7 1499
86a5659e
JB
1500 Since the latter lossage is more benign, we may as well
1501 lose that way. -- cph */
1502#ifdef FIONBIO
bdee2ef3 1503#if defined(UNIX98_PTYS)
86a5659e
JB
1504 {
1505 int on = 1;
1506 ioctl (fd, FIONBIO, &on);
1507 }
1508#endif
1509#endif
86a5659e
JB
1510}
1511#endif /* HAVE_PTYS */
1512\f
7c2fb837 1513#if !defined(CANNOT_DUMP) || !defined(SYSTEM_MALLOC)
86a5659e
JB
1514/* Some systems that cannot dump also cannot implement these. */
1515
1516/*
1517 * Return the address of the start of the text segment prior to
1518 * doing an unexec. After unexec the return value is undefined.
1519 * See crt0.c for further explanation and _start.
1520 *
1521 */
1522
c0c9ac48 1523#if !(defined (__NetBSD__) && defined (__ELF__))
260fe597 1524#ifndef HAVE_TEXT_START
86a5659e 1525char *
971de7fb 1526start_of_text (void)
86a5659e
JB
1527{
1528#ifdef TEXT_START
1529 return ((char *) TEXT_START);
1530#else
86a5659e
JB
1531 extern int _start ();
1532 return ((char *) _start);
86a5659e
JB
1533#endif /* TEXT_START */
1534}
260fe597 1535#endif /* not HAVE_TEXT_START */
c0c9ac48 1536#endif
86a5659e
JB
1537
1538/*
1539 * Return the address of the start of the data segment prior to
1540 * doing an unexec. After unexec the return value is undefined.
1541 * See crt0.c for further information and definition of data_start.
1542 *
1543 * Apparently, on BSD systems this is etext at startup. On
1544 * USG systems (swapping) this is highly mmu dependent and
1545 * is also dependent on whether or not the program is running
1546 * with shared text. Generally there is a (possibly large)
1547 * gap between end of text and start of data with shared text.
1548 *
1549 * On Uniplus+ systems with shared text, data starts at a
1550 * fixed address. Each port (from a given oem) is generally
1551 * different, and the specific value of the start of data can
1552 * be obtained via the UniPlus+ specific "uvar" system call,
1553 * however the method outlined in crt0.c seems to be more portable.
1554 *
1555 * Probably what will have to happen when a USG unexec is available,
1556 * at least on UniPlus, is temacs will have to be made unshared so
1557 * that text and data are contiguous. Then once loadup is complete,
1558 * unexec will produce a shared executable where the data can be
ea5a0917 1559 * at the normal shared text boundary and the startofdata variable
86a5659e
JB
1560 * will be patched by unexec to the correct value.
1561 *
1562 */
177c0ea7 1563
be3abfa2 1564#ifndef start_of_data
86a5659e 1565char *
971de7fb 1566start_of_data (void)
86a5659e
JB
1567{
1568#ifdef DATA_START
1569 return ((char *) DATA_START);
6c65530f
JB
1570#else
1571#ifdef ORDINARY_LINK
1572 /*
1573 * This is a hack. Since we're not linking crt0.c or pre_crt0.c,
1574 * data_start isn't defined. We take the address of environ, which
1575 * is known to live at or near the start of the system crt0.c, and
1576 * we don't sweat the handful of bytes that might lose.
1577 */
1578 extern char **environ;
1579
c4ea52a6 1580 return ((char *) &environ);
86a5659e
JB
1581#else
1582 extern int data_start;
1583 return ((char *) &data_start);
6c65530f
JB
1584#endif /* ORDINARY_LINK */
1585#endif /* DATA_START */
86a5659e 1586}
be3abfa2 1587#endif /* start_of_data */
86a5659e 1588#endif /* NEED_STARTS (not CANNOT_DUMP or not SYSTEM_MALLOC) */
86a5659e 1589\f
c0c86835
KH
1590/* init_system_name sets up the string for the Lisp function
1591 system-name to return. */
86a5659e 1592
c0c86835 1593extern Lisp_Object Vsystem_name;
86a5659e 1594
f8a80313
RS
1595#ifdef HAVE_SOCKETS
1596#include <sys/socket.h>
1597#include <netdb.h>
1598#endif /* HAVE_SOCKETS */
f8a80313 1599
8581cd64
KH
1600#ifdef TRY_AGAIN
1601#ifndef HAVE_H_ERRNO
1602extern int h_errno;
1603#endif
1604#endif /* TRY_AGAIN */
1605
c0c86835 1606void
971de7fb 1607init_system_name (void)
86a5659e 1608{
210b2b4f 1609#ifndef HAVE_GETHOSTNAME
c0c86835
KH
1610 struct utsname uts;
1611 uname (&uts);
1612 Vsystem_name = build_string (uts.nodename);
67004ffb 1613#else /* HAVE_GETHOSTNAME */
cc6e7269 1614 unsigned int hostname_size = 256;
c0c86835
KH
1615 char *hostname = (char *) alloca (hostname_size);
1616
1617 /* Try to get the host name; if the buffer is too short, try
1618 again. Apparently, the only indication gethostname gives of
1619 whether the buffer was large enough is the presence or absence
1620 of a '\0' in the string. Eech. */
1621 for (;;)
1622 {
1623 gethostname (hostname, hostname_size - 1);
1624 hostname[hostname_size - 1] = '\0';
1625
1626 /* Was the buffer large enough for the '\0'? */
1627 if (strlen (hostname) < hostname_size - 1)
1628 break;
1629
1630 hostname_size <<= 1;
1631 hostname = (char *) alloca (hostname_size);
1632 }
67004ffb 1633#ifdef HAVE_SOCKETS
c0c86835
KH
1634 /* Turn the hostname into the official, fully-qualified hostname.
1635 Don't do this if we're going to dump; this can confuse system
1636 libraries on some machines and make the dumped emacs core dump. */
67004ffb 1637#ifndef CANNOT_DUMP
c0c86835 1638 if (initialized)
67004ffb 1639#endif /* not CANNOT_DUMP */
960d894c
KH
1640 if (! index (hostname, '.'))
1641 {
960d894c 1642 int count;
3d66b985
JD
1643#ifdef HAVE_GETADDRINFO
1644 struct addrinfo *res;
1645 struct addrinfo hints;
1646 int ret;
1647
1648 memset (&hints, 0, sizeof(hints));
1649 hints.ai_socktype = SOCK_STREAM;
1650 hints.ai_flags = AI_CANONNAME;
1651
960d894c
KH
1652 for (count = 0;; count++)
1653 {
3d66b985
JD
1654 if ((ret = getaddrinfo (hostname, NULL, &hints, &res)) == 0
1655 || ret != EAI_AGAIN)
1656 break;
1657
1658 if (count >= 5)
1659 break;
1660 Fsleep_for (make_number (1), Qnil);
1661 }
1662
1663 if (ret == 0)
1664 {
1665 struct addrinfo *it = res;
1666 while (it)
1667 {
1668 char *fqdn = it->ai_canonname;
1669 if (fqdn && index (fqdn, '.')
1670 && strcmp (fqdn, "localhost.localdomain") != 0)
1671 break;
1672 it = it->ai_next;
1673 }
1674 if (it)
1675 {
1676 hostname = alloca (strlen (it->ai_canonname) + 1);
1677 strcpy (hostname, it->ai_canonname);
1678 }
1679 freeaddrinfo (res);
1680 }
1681#else /* !HAVE_GETADDRINFO */
1682 struct hostent *hp;
1683 for (count = 0;; count++)
1684 {
1685
e24f1d55 1686#ifdef TRY_AGAIN
960d894c 1687 h_errno = 0;
e24f1d55 1688#endif
960d894c 1689 hp = gethostbyname (hostname);
efa04277 1690#ifdef TRY_AGAIN
960d894c
KH
1691 if (! (hp == 0 && h_errno == TRY_AGAIN))
1692#endif
3d66b985 1693
960d894c 1694 break;
3d66b985 1695
960d894c
KH
1696 if (count >= 5)
1697 break;
1698 Fsleep_for (make_number (1), Qnil);
1699 }
3d66b985 1700
960d894c
KH
1701 if (hp)
1702 {
1703 char *fqdn = (char *) hp->h_name;
960d894c
KH
1704
1705 if (!index (fqdn, '.'))
1706 {
1707 /* We still don't have a fully qualified domain name.
1708 Try to find one in the list of alternate names */
1709 char **alias = hp->h_aliases;
923721f4
CY
1710 while (*alias
1711 && (!index (*alias, '.')
1712 || !strcmp (*alias, "localhost.localdomain")))
960d894c
KH
1713 alias++;
1714 if (*alias)
1715 fqdn = *alias;
1716 }
1717 hostname = fqdn;
960d894c 1718 }
3d66b985 1719#endif /* !HAVE_GETADDRINFO */
960d894c 1720 }
67004ffb 1721#endif /* HAVE_SOCKETS */
c0c86835 1722 Vsystem_name = build_string (hostname);
67004ffb 1723#endif /* HAVE_GETHOSTNAME */
c0c86835
KH
1724 {
1725 unsigned char *p;
d5db4077 1726 for (p = SDATA (Vsystem_name); *p; p++)
c0c86835
KH
1727 if (*p == ' ' || *p == '\t')
1728 *p = '-';
1729 }
67004ffb 1730}
86a5659e 1731\f
7964ba9e 1732#ifndef MSDOS
4624371d 1733#if !defined (HAVE_SELECT)
86a5659e 1734
86d1f23a
KH
1735#include "sysselect.h"
1736#undef select
1737
1738#if defined (HAVE_X_WINDOWS) && !defined (HAVE_SELECT)
86a5659e
JB
1739/* Cause explanatory error message at compile time,
1740 since the select emulation is not good enough for X. */
1741int *x = &x_windows_lose_if_no_select_system_call;
1742#endif
1743
1744/* Emulate as much as select as is possible under 4.1 and needed by Gnu Emacs
1745 * Only checks read descriptors.
1746 */
1747/* How long to wait between checking fds in select */
1748#define SELECT_PAUSE 1
1749int select_alarmed;
1750
1751/* For longjmp'ing back to read_input_waiting. */
1752
1753jmp_buf read_alarm_throw;
1754
1755/* Nonzero if the alarm signal should throw back to read_input_waiting.
1756 The read_socket_hook function sets this to 1 while it is waiting. */
1757
1758int read_alarm_should_throw;
1759
1760SIGTYPE
1761select_alarm ()
1762{
1763 select_alarmed = 1;
86a5659e 1764 signal (SIGALRM, SIG_IGN);
333f1b6f 1765 SIGNAL_THREAD_CHECK (SIGALRM);
86a5659e
JB
1766 if (read_alarm_should_throw)
1767 longjmp (read_alarm_throw, 1);
1768}
1769
9d9f1812 1770#ifndef WINDOWSNT
86a5659e
JB
1771/* Only rfds are checked. */
1772int
86d1f23a 1773sys_select (nfds, rfds, wfds, efds, timeout)
86a5659e 1774 int nfds;
86d1f23a
KH
1775 SELECT_TYPE *rfds, *wfds, *efds;
1776 EMACS_TIME *timeout;
86a5659e 1777{
2246281f
KL
1778 /* XXX This needs to be updated for multi-tty support. Is there
1779 anybody who needs to emulate select these days? */
1780 int ravail = 0;
86d1f23a
KH
1781 SELECT_TYPE orfds;
1782 int timeoutval;
1783 int *local_timeout;
86a5659e
JB
1784 extern int proc_buffered_char[];
1785#ifndef subprocesses
1786 int process_tick = 0, update_tick = 0;
1787#else
1788 extern int process_tick, update_tick;
1789#endif
86a5659e
JB
1790 unsigned char buf;
1791
86d1f23a
KH
1792#if defined (HAVE_SELECT) && defined (HAVE_X_WINDOWS)
1793 /* If we're using X, then the native select will work; we only need the
1794 emulation for non-X usage. */
2246281f 1795 if (!NILP (Vinitial_window_system))
86d1f23a
KH
1796 return select (nfds, rfds, wfds, efds, timeout);
1797#endif
1798 timeoutval = timeout ? EMACS_SECS (*timeout) : 100000;
1799 local_timeout = &timeoutval;
1800 FD_ZERO (&orfds);
86a5659e
JB
1801 if (rfds)
1802 {
1803 orfds = *rfds;
86d1f23a 1804 FD_ZERO (rfds);
86a5659e
JB
1805 }
1806 if (wfds)
86d1f23a 1807 FD_ZERO (wfds);
86a5659e 1808 if (efds)
86d1f23a 1809 FD_ZERO (efds);
86a5659e
JB
1810
1811 /* If we are looking only for the terminal, with no timeout,
1812 just read it and wait -- that's more efficient. */
86d1f23a
KH
1813 if (*local_timeout == 100000 && process_tick == update_tick
1814 && FD_ISSET (0, &orfds))
86a5659e 1815 {
86d1f23a
KH
1816 int fd;
1817 for (fd = 1; fd < nfds; ++fd)
1818 if (FD_ISSET (fd, &orfds))
1819 goto hardway;
86a5659e
JB
1820 if (! detect_input_pending ())
1821 read_input_waiting ();
86d1f23a 1822 FD_SET (0, rfds);
86a5659e
JB
1823 return 1;
1824 }
1825
86d1f23a 1826 hardway:
86a5659e
JB
1827 /* Once a second, till the timer expires, check all the flagged read
1828 * descriptors to see if any input is available. If there is some then
1829 * set the corresponding bit in the return copy of rfds.
177c0ea7 1830 */
86a5659e
JB
1831 while (1)
1832 {
86d1f23a 1833 register int to_check, fd;
86a5659e
JB
1834
1835 if (rfds)
1836 {
86d1f23a 1837 for (to_check = nfds, fd = 0; --to_check >= 0; fd++)
86a5659e 1838 {
86d1f23a 1839 if (FD_ISSET (fd, &orfds))
86a5659e
JB
1840 {
1841 int avail = 0, status = 0;
1842
86d1f23a 1843 if (fd == 0)
86a5659e
JB
1844 avail = detect_input_pending (); /* Special keyboard handler */
1845 else
1846 {
1847#ifdef FIONREAD
1848 status = ioctl (fd, FIONREAD, &avail);
1849#else /* no FIONREAD */
1850 /* Hoping it will return -1 if nothing available
1851 or 0 if all 0 chars requested are read. */
1852 if (proc_buffered_char[fd] >= 0)
1853 avail = 1;
1854 else
1855 {
1856 avail = read (fd, &buf, 1);
1857 if (avail > 0)
1858 proc_buffered_char[fd] = buf;
1859 }
1860#endif /* no FIONREAD */
1861 }
1862 if (status >= 0 && avail > 0)
1863 {
86d1f23a 1864 FD_SET (fd, rfds);
86a5659e
JB
1865 ravail++;
1866 }
1867 }
1868 }
1869 }
1870 if (*local_timeout == 0 || ravail != 0 || process_tick != update_tick)
1871 break;
ffdcc91d
GM
1872
1873 turn_on_atimers (0);
1874 signal (SIGALRM, select_alarm);
86a5659e
JB
1875 select_alarmed = 0;
1876 alarm (SELECT_PAUSE);
177c0ea7 1877
86a5659e
JB
1878 /* Wait for a SIGALRM (or maybe a SIGTINT) */
1879 while (select_alarmed == 0 && *local_timeout != 0
1880 && process_tick == update_tick)
1881 {
1882 /* If we are interested in terminal input,
1883 wait by reading the terminal.
1884 That makes instant wakeup for terminal input at least. */
86d1f23a 1885 if (FD_ISSET (0, &orfds))
86a5659e
JB
1886 {
1887 read_input_waiting ();
1888 if (detect_input_pending ())
1889 select_alarmed = 1;
1890 }
1891 else
1892 pause ();
1893 }
1894 (*local_timeout) -= SELECT_PAUSE;
177c0ea7 1895
ffdcc91d
GM
1896 /* Reset the old alarm if there was one. */
1897 turn_on_atimers (1);
177c0ea7 1898
86a5659e
JB
1899 if (*local_timeout == 0) /* Stop on timer being cleared */
1900 break;
1901 }
1902 return ravail;
1903}
30790a37 1904#endif /* not WINDOWSNT */
86a5659e
JB
1905
1906/* Read keyboard input into the standard buffer,
1907 waiting for at least one character. */
1908
dfcf069d 1909void
86a5659e
JB
1910read_input_waiting ()
1911{
2246281f
KL
1912 /* XXX This needs to be updated for multi-tty support. Is there
1913 anybody who needs to emulate select these days? */
34567704
JB
1914 int nread, i;
1915 extern int quit_char;
86a5659e
JB
1916
1917 if (read_socket_hook)
1918 {
9f893fc6
KS
1919 struct input_event hold_quit;
1920
1921 EVENT_INIT (hold_quit);
1922 hold_quit.kind = NO_EVENT;
1923
86a5659e
JB
1924 read_alarm_should_throw = 0;
1925 if (! setjmp (read_alarm_throw))
9f893fc6 1926 nread = (*read_socket_hook) (0, 1, &hold_quit);
86a5659e
JB
1927 else
1928 nread = -1;
f4a7e5bd 1929
9f893fc6
KS
1930 if (hold_quit.kind != NO_EVENT)
1931 kbd_buffer_store_event (&hold_quit);
86a5659e
JB
1932 }
1933 else
86a5659e 1934 {
50acda85 1935 struct input_event e;
f4a7e5bd
RS
1936 char buf[3];
1937 nread = read (fileno (stdin), buf, 1);
50acda85 1938 EVENT_INIT (e);
f4a7e5bd
RS
1939
1940 /* Scan the chars for C-g and store them in kbd_buffer. */
e43bd4f5 1941 e.kind = ASCII_KEYSTROKE_EVENT;
2d064114 1942 e.frame_or_window = selected_frame;
f4a7e5bd
RS
1943 e.modifiers = 0;
1944 for (i = 0; i < nread; i++)
a00d5589 1945 {
f4a7e5bd
RS
1946 /* Convert chars > 0177 to meta events if desired.
1947 We do this under the same conditions that read_avail_input does. */
1948 if (read_socket_hook == 0)
1949 {
1950 /* If the user says she has a meta key, then believe her. */
1951 if (meta_key == 1 && (buf[i] & 0x80))
1952 e.modifiers = meta_modifier;
1953 if (meta_key != 2)
1954 buf[i] &= ~0x80;
1955 }
b95520f5 1956
c81d47b4 1957 XSETINT (e.code, buf[i]);
f4a7e5bd
RS
1958 kbd_buffer_store_event (&e);
1959 /* Don't look at input that follows a C-g too closely.
1960 This reduces lossage due to autorepeat on C-g. */
1961 if (buf[i] == quit_char)
1962 break;
1963 }
86a5659e
JB
1964 }
1965}
1966
4624371d 1967#if !defined (HAVE_SELECT)
819b8f00
KL
1968#define select sys_select
1969#endif
1970
86a5659e 1971#endif /* not HAVE_SELECT */
7964ba9e 1972#endif /* not MSDOS */
86a5659e 1973\f
86a5659e
JB
1974/* POSIX signals support - DJB */
1975/* Anyone with POSIX signals should have ANSI C declarations */
1976
c639b0e3 1977sigset_t empty_mask, full_mask;
86a5659e 1978
d6dae14b
EZ
1979#ifndef WINDOWSNT
1980
86a5659e
JB
1981signal_handler_t
1982sys_signal (int signal_number, signal_handler_t action)
1983{
c639b0e3 1984 struct sigaction new_action, old_action;
86a5659e 1985 sigemptyset (&new_action.sa_mask);
e5c99298 1986 new_action.sa_handler = action;
ef874e3d
AS
1987 new_action.sa_flags = 0;
1988#if defined (SA_RESTART)
25ab68af 1989 /* Emacs mostly works better with restartable system services. If this
55fafcf0
RS
1990 flag exists, we probably want to turn it on here.
1991 However, on some systems this resets the timeout of `select'
1992 which means that `select' never finishes if it keeps getting signals.
1993 BROKEN_SA_RESTART is defined on those systems. */
275464e7
SM
1994 /* It's not clear why the comment above says "mostly works better". --Stef
1995 When SYNC_INPUT is set, we don't want SA_RESTART because we need to poll
1996 for pending input so we need long-running syscalls to be interrupted
1997 after a signal that sets the interrupt_input_pending flag. */
766f52ec
AS
1998 /* Non-interactive keyboard input goes through stdio, where we always
1999 want restartable system calls. */
ef874e3d
AS
2000# if defined (BROKEN_SA_RESTART) || defined(SYNC_INPUT)
2001 if (noninteractive)
2002# endif
2003 new_action.sa_flags = SA_RESTART;
25ab68af 2004#endif
d32b2f3c 2005 sigaction (signal_number, &new_action, &old_action);
e5c99298 2006 return (old_action.sa_handler);
86a5659e
JB
2007}
2008
d6dae14b
EZ
2009#endif /* WINDOWSNT */
2010
e065a56e
JB
2011#ifndef __GNUC__
2012/* If we're compiling with GCC, we don't need this function, since it
2013 can be written as a macro. */
2014sigset_t
2015sys_sigmask (int sig)
2016{
2017 sigset_t mask;
2018 sigemptyset (&mask);
2019 sigaddset (&mask, sig);
2020 return mask;
2021}
2022#endif
2023
86a5659e
JB
2024/* I'd like to have these guys return pointers to the mask storage in here,
2025 but there'd be trouble if the code was saving multiple masks. I'll be
2026 safe and pass the structure. It normally won't be more than 2 bytes
2027 anyhow. - DJB */
2028
2029sigset_t
2030sys_sigblock (sigset_t new_mask)
2031{
2032 sigset_t old_mask;
2033 sigprocmask (SIG_BLOCK, &new_mask, &old_mask);
2034 return (old_mask);
2035}
2036
2037sigset_t
2038sys_sigunblock (sigset_t new_mask)
2039{
2040 sigset_t old_mask;
2041 sigprocmask (SIG_UNBLOCK, &new_mask, &old_mask);
2042 return (old_mask);
2043}
2044
2045sigset_t
2046sys_sigsetmask (sigset_t new_mask)
2047{
2048 sigset_t old_mask;
2049 sigprocmask (SIG_SETMASK, &new_mask, &old_mask);
2050 return (old_mask);
2051}
2052
86a5659e 2053\f
b80263be 2054#if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
ca9c0567
PE
2055static char *my_sys_siglist[NSIG];
2056# ifdef sys_siglist
2057# undef sys_siglist
2058# endif
2059# define sys_siglist my_sys_siglist
2060#endif
2061
2062void
971de7fb 2063init_signals (void)
ca9c0567 2064{
ca9c0567
PE
2065 sigemptyset (&empty_mask);
2066 sigfillset (&full_mask);
ca9c0567 2067
b80263be 2068#if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
ca9c0567
PE
2069 if (! initialized)
2070 {
2071# ifdef SIGABRT
2072 sys_siglist[SIGABRT] = "Aborted";
2073# endif
2074# ifdef SIGAIO
2075 sys_siglist[SIGAIO] = "LAN I/O interrupt";
2076# endif
2077# ifdef SIGALRM
2078 sys_siglist[SIGALRM] = "Alarm clock";
2079# endif
2080# ifdef SIGBUS
2081 sys_siglist[SIGBUS] = "Bus error";
2082# endif
2083# ifdef SIGCLD
2084 sys_siglist[SIGCLD] = "Child status changed";
2085# endif
2086# ifdef SIGCHLD
2087 sys_siglist[SIGCHLD] = "Child status changed";
2088# endif
2089# ifdef SIGCONT
2090 sys_siglist[SIGCONT] = "Continued";
2091# endif
2092# ifdef SIGDANGER
2093 sys_siglist[SIGDANGER] = "Swap space dangerously low";
2094# endif
2095# ifdef SIGDGNOTIFY
2096 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
2097# endif
2098# ifdef SIGEMT
2099 sys_siglist[SIGEMT] = "Emulation trap";
2100# endif
2101# ifdef SIGFPE
2102 sys_siglist[SIGFPE] = "Arithmetic exception";
2103# endif
2104# ifdef SIGFREEZE
2105 sys_siglist[SIGFREEZE] = "SIGFREEZE";
2106# endif
2107# ifdef SIGGRANT
2108 sys_siglist[SIGGRANT] = "Monitor mode granted";
2109# endif
2110# ifdef SIGHUP
2111 sys_siglist[SIGHUP] = "Hangup";
2112# endif
2113# ifdef SIGILL
2114 sys_siglist[SIGILL] = "Illegal instruction";
2115# endif
2116# ifdef SIGINT
2117 sys_siglist[SIGINT] = "Interrupt";
2118# endif
2119# ifdef SIGIO
2120 sys_siglist[SIGIO] = "I/O possible";
2121# endif
2122# ifdef SIGIOINT
2123 sys_siglist[SIGIOINT] = "I/O intervention required";
2124# endif
2125# ifdef SIGIOT
2126 sys_siglist[SIGIOT] = "IOT trap";
2127# endif
2128# ifdef SIGKILL
2129 sys_siglist[SIGKILL] = "Killed";
2130# endif
2131# ifdef SIGLOST
2132 sys_siglist[SIGLOST] = "Resource lost";
2133# endif
2134# ifdef SIGLWP
2135 sys_siglist[SIGLWP] = "SIGLWP";
2136# endif
2137# ifdef SIGMSG
2138 sys_siglist[SIGMSG] = "Monitor mode data available";
2139# endif
2140# ifdef SIGPHONE
2141 sys_siglist[SIGWIND] = "SIGPHONE";
2142# endif
2143# ifdef SIGPIPE
2144 sys_siglist[SIGPIPE] = "Broken pipe";
2145# endif
2146# ifdef SIGPOLL
2147 sys_siglist[SIGPOLL] = "Pollable event occurred";
2148# endif
2149# ifdef SIGPROF
2150 sys_siglist[SIGPROF] = "Profiling timer expired";
2151# endif
2152# ifdef SIGPTY
2153 sys_siglist[SIGPTY] = "PTY I/O interrupt";
2154# endif
2155# ifdef SIGPWR
2156 sys_siglist[SIGPWR] = "Power-fail restart";
2157# endif
2158# ifdef SIGQUIT
2159 sys_siglist[SIGQUIT] = "Quit";
2160# endif
2161# ifdef SIGRETRACT
2162 sys_siglist[SIGRETRACT] = "Need to relinguish monitor mode";
2163# endif
2164# ifdef SIGSAK
2165 sys_siglist[SIGSAK] = "Secure attention";
2166# endif
2167# ifdef SIGSEGV
2168 sys_siglist[SIGSEGV] = "Segmentation violation";
2169# endif
2170# ifdef SIGSOUND
2171 sys_siglist[SIGSOUND] = "Sound completed";
2172# endif
2173# ifdef SIGSTOP
2174 sys_siglist[SIGSTOP] = "Stopped (signal)";
2175# endif
2176# ifdef SIGSTP
2177 sys_siglist[SIGSTP] = "Stopped (user)";
2178# endif
2179# ifdef SIGSYS
2180 sys_siglist[SIGSYS] = "Bad argument to system call";
2181# endif
2182# ifdef SIGTERM
2183 sys_siglist[SIGTERM] = "Terminated";
2184# endif
2185# ifdef SIGTHAW
2186 sys_siglist[SIGTHAW] = "SIGTHAW";
2187# endif
2188# ifdef SIGTRAP
2189 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2190# endif
2191# ifdef SIGTSTP
2192 sys_siglist[SIGTSTP] = "Stopped (user)";
2193# endif
2194# ifdef SIGTTIN
2195 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2196# endif
2197# ifdef SIGTTOU
2198 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2199# endif
2200# ifdef SIGURG
2201 sys_siglist[SIGURG] = "Urgent I/O condition";
2202# endif
2203# ifdef SIGUSR1
2204 sys_siglist[SIGUSR1] = "User defined signal 1";
2205# endif
2206# ifdef SIGUSR2
2207 sys_siglist[SIGUSR2] = "User defined signal 2";
2208# endif
2209# ifdef SIGVTALRM
2210 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2211# endif
2212# ifdef SIGWAITING
2213 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2214# endif
2215# ifdef SIGWINCH
2216 sys_siglist[SIGWINCH] = "Window size changed";
2217# endif
2218# ifdef SIGWIND
2219 sys_siglist[SIGWIND] = "SIGWIND";
2220# endif
2221# ifdef SIGXCPU
2222 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2223# endif
2224# ifdef SIGXFSZ
2225 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2226# endif
2227 }
b80263be 2228#endif /* !defined HAVE_STRSIGNAL && !defined HAVE_DECL_SYS_SIGLIST */
ca9c0567
PE
2229}
2230\f
9927a7b1 2231#ifndef HAVE_RANDOM
4bb8c8b7
KH
2232#ifdef random
2233#define HAVE_RANDOM
2234#endif
2235#endif
2236
2237/* Figure out how many bits the system's random number generator uses.
2238 `random' and `lrand48' are assumed to return 31 usable bits.
2239 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2240 so we'll shift it and treat it like the 15-bit USG `rand'. */
2241
2242#ifndef RAND_BITS
2243# ifdef HAVE_RANDOM
2244# define RAND_BITS 31
2245# else /* !HAVE_RANDOM */
2246# ifdef HAVE_LRAND48
2247# define RAND_BITS 31
2248# define random lrand48
2249# else /* !HAVE_LRAND48 */
2250# define RAND_BITS 15
2251# if RAND_MAX == 32767
2252# define random rand
2253# else /* RAND_MAX != 32767 */
2254# if RAND_MAX == 2147483647
2255# define random() (rand () >> 16)
2256# else /* RAND_MAX != 2147483647 */
2257# ifdef USG
2258# define random rand
2259# else
2260# define random() (rand () >> 16)
2a633456 2261# endif /* !USG */
4bb8c8b7
KH
2262# endif /* RAND_MAX != 2147483647 */
2263# endif /* RAND_MAX != 32767 */
2264# endif /* !HAVE_LRAND48 */
2265# endif /* !HAVE_RANDOM */
2266#endif /* !RAND_BITS */
2e46c7c6 2267
4bb8c8b7 2268void
971de7fb 2269seed_random (long int arg)
86a5659e 2270{
4bb8c8b7
KH
2271#ifdef HAVE_RANDOM
2272 srandom ((unsigned int)arg);
f8b53a82 2273#else
4bb8c8b7 2274# ifdef HAVE_LRAND48
76425a49 2275 srand48 (arg);
4bb8c8b7
KH
2276# else
2277 srand ((unsigned int)arg);
2278# endif
2e46c7c6 2279#endif
86a5659e
JB
2280}
2281
4bb8c8b7
KH
2282/*
2283 * Build a full Emacs-sized word out of whatever we've got.
2284 * This suffices even for a 64-bit architecture with a 15-bit rand.
2285 */
2286long
971de7fb 2287get_random (void)
4bb8c8b7
KH
2288{
2289 long val = random ();
2290#if VALBITS > RAND_BITS
2291 val = (val << RAND_BITS) ^ random ();
2292#if VALBITS > 2*RAND_BITS
2293 val = (val << RAND_BITS) ^ random ();
2294#if VALBITS > 3*RAND_BITS
2295 val = (val << RAND_BITS) ^ random ();
2296#if VALBITS > 4*RAND_BITS
2297 val = (val << RAND_BITS) ^ random ();
2298#endif /* need at least 5 */
2299#endif /* need at least 4 */
2300#endif /* need at least 3 */
2301#endif /* need at least 2 */
2302 return val & ((1L << VALBITS) - 1);
2303}
7088d1ca
RM
2304
2305#ifndef HAVE_STRERROR
fe03522b 2306#ifndef WINDOWSNT
7088d1ca
RM
2307char *
2308strerror (errnum)
2309 int errnum;
2310{
2311 extern char *sys_errlist[];
2312 extern int sys_nerr;
2313
2314 if (errnum >= 0 && errnum < sys_nerr)
2315 return sys_errlist[errnum];
2316 return (char *) "Unknown error";
2317}
fe03522b 2318#endif /* not WINDOWSNT */
7088d1ca 2319#endif /* ! HAVE_STRERROR */
86a5659e 2320\f
86a5659e 2321int
971de7fb 2322emacs_open (const char *path, int oflag, int mode)
86a5659e
JB
2323{
2324 register int rtnval;
68c45bf0 2325
86a5659e 2326 while ((rtnval = open (path, oflag, mode)) == -1
275464e7
SM
2327 && (errno == EINTR))
2328 QUIT;
86a5659e
JB
2329 return (rtnval);
2330}
2331
dfcf069d 2332int
971de7fb 2333emacs_close (int fd)
86a5659e 2334{
fe111daf 2335 int did_retry = 0;
86a5659e
JB
2336 register int rtnval;
2337
2338 while ((rtnval = close (fd)) == -1
fe111daf
KH
2339 && (errno == EINTR))
2340 did_retry = 1;
2341
2342 /* If close is interrupted SunOS 4.1 may or may not have closed the
2343 file descriptor. If it did the second close will fail with
2344 errno = EBADF. That means we have succeeded. */
2345 if (rtnval == -1 && did_retry && errno == EBADF)
2346 return 0;
2347
86a5659e
JB
2348 return rtnval;
2349}
2350
86a5659e 2351int
971de7fb 2352emacs_read (int fildes, char *buf, unsigned int nbyte)
86a5659e
JB
2353{
2354 register int rtnval;
177c0ea7 2355
86a5659e 2356 while ((rtnval = read (fildes, buf, nbyte)) == -1
275464e7
SM
2357 && (errno == EINTR))
2358 QUIT;
86a5659e
JB
2359 return (rtnval);
2360}
2361
2362int
971de7fb 2363emacs_write (int fildes, const char *buf, unsigned int nbyte)
86a5659e 2364{
b95520f5 2365 register int rtnval, bytes_written;
86a5659e 2366
b95520f5
BF
2367 bytes_written = 0;
2368
2369 while (nbyte > 0)
2370 {
2371 rtnval = write (fildes, buf, nbyte);
2372
2373 if (rtnval == -1)
2374 {
2375 if (errno == EINTR)
77220eeb
SM
2376 {
2377#ifdef SYNC_INPUT
2378 /* I originally used `QUIT' but that might causes files to
2379 be truncated if you hit C-g in the middle of it. --Stef */
55310b94 2380 process_pending_signals ();
77220eeb
SM
2381#endif
2382 continue;
2383 }
b95520f5 2384 else
aa670904 2385 return (bytes_written ? bytes_written : -1);
b95520f5
BF
2386 }
2387
2388 buf += rtnval;
2389 nbyte -= rtnval;
2390 bytes_written += rtnval;
2391 }
2392 return (bytes_written);
86a5659e 2393}
86a5659e
JB
2394\f
2395#ifdef USG
2396/*
2397 * All of the following are for USG.
2398 *
2399 * On USG systems the system calls are INTERRUPTIBLE by signals
2400 * that the user program has elected to catch. Thus the system call
2401 * must be retried in these cases. To handle this without massive
2402 * changes in the source code, we remap the standard system call names
2403 * to names for our own functions in sysdep.c that do the system call
2404 * with retries. Actually, for portability reasons, it is good
2405 * programming practice, as this example shows, to limit all actual
eb8c3be9 2406 * system calls to a single occurrence in the source. Sure, this
86a5659e
JB
2407 * adds an extra level of function call overhead but it is almost
2408 * always negligible. Fred Fish, Unisoft Systems Inc.
2409 */
2410
86a5659e
JB
2411/*
2412 * Warning, this function may not duplicate 4.2 action properly
2413 * under error conditions.
2414 */
2415
2416#ifndef MAXPATHLEN
2417/* In 4.1, param.h fails to define this. */
2418#define MAXPATHLEN 1024
2419#endif
2420
2421#ifndef HAVE_GETWD
2422
2423char *
2424getwd (pathname)
2425 char *pathname;
2426{
2427 char *npath, *spath;
2428 extern char *getcwd ();
2429
9ac0d9e0 2430 BLOCK_INPUT; /* getcwd uses malloc */
86a5659e 2431 spath = npath = getcwd ((char *) 0, MAXPATHLEN);
f4a7e5bd 2432 if (spath == 0)
18b6bc73
GM
2433 {
2434 UNBLOCK_INPUT;
2435 return spath;
2436 }
86a5659e
JB
2437 /* On Altos 3068, getcwd can return @hostname/dir, so discard
2438 up to first slash. Should be harmless on other systems. */
2439 while (*npath && *npath != '/')
2440 npath++;
2441 strcpy (pathname, npath);
2442 free (spath); /* getcwd uses malloc */
9ac0d9e0 2443 UNBLOCK_INPUT;
86a5659e
JB
2444 return pathname;
2445}
2446
2447#endif /* HAVE_GETWD */
2448
2449/*
2450 * Emulate rename using unlink/link. Note that this is
2451 * only partially correct. Also, doesn't enforce restriction
2452 * that files be of same type (regular->regular, dir->dir, etc).
2453 */
2454
4746118a
JB
2455#ifndef HAVE_RENAME
2456
86a5659e 2457rename (from, to)
19c7afdf
JB
2458 const char *from;
2459 const char *to;
86a5659e
JB
2460{
2461 if (access (from, 0) == 0)
2462 {
2463 unlink (to);
2464 if (link (from, to) == 0)
2465 if (unlink (from) == 0)
2466 return (0);
2467 }
2468 return (-1);
2469}
2470
4746118a
JB
2471#endif
2472
86a5659e 2473
69ab3201 2474#if defined(HPUX) && !defined(HAVE_PERROR)
86a5659e
JB
2475
2476/* HPUX curses library references perror, but as far as we know
2477 it won't be called. Anyway this definition will do for now. */
2478
2479perror ()
2480{
2481}
69ab3201 2482#endif /* HPUX and not HAVE_PERROR */
86a5659e
JB
2483
2484#ifndef HAVE_DUP2
2485
2486/*
2487 * Emulate BSD dup2. First close newd if it already exists.
2488 * Then, attempt to dup oldd. If not successful, call dup2 recursively
2489 * until we are, then close the unsuccessful ones.
2490 */
2491
2492dup2 (oldd, newd)
2493 int oldd;
2494 int newd;
2495{
2496 register int fd, ret;
177c0ea7 2497
68c45bf0 2498 emacs_close (newd);
86a5659e
JB
2499
2500#ifdef F_DUPFD
68c45bf0 2501 return fcntl (oldd, F_DUPFD, newd);
86a5659e
JB
2502#else
2503 fd = dup (old);
2504 if (fd == -1)
2505 return -1;
2506 if (fd == new)
2507 return new;
2508 ret = dup2 (old,new);
68c45bf0 2509 emacs_close (fd);
86a5659e
JB
2510 return ret;
2511#endif
2512}
2513
2514#endif /* not HAVE_DUP2 */
2515
2516/*
2517 * Gettimeofday. Simulate as much as possible. Only accurate
2518 * to nearest second. Emacs doesn't use tzp so ignore it for now.
2519 * Only needed when subprocesses are defined.
2520 */
2521
2522#ifdef subprocesses
86a5659e
JB
2523#ifndef HAVE_GETTIMEOFDAY
2524#ifdef HAVE_TIMEVAL
177c0ea7 2525
86a5659e 2526/* ARGSUSED */
dfcf069d 2527int
86a5659e
JB
2528gettimeofday (tp, tzp)
2529 struct timeval *tp;
2530 struct timezone *tzp;
2531{
2532 extern long time ();
2533
177c0ea7 2534 tp->tv_sec = time ((long *)0);
86a5659e 2535 tp->tv_usec = 0;
4ca7594f
RS
2536 if (tzp != 0)
2537 tzp->tz_minuteswest = -1;
dfcf069d 2538 return 0;
86a5659e 2539}
177c0ea7 2540
86a5659e
JB
2541#endif
2542#endif
7c2fb837 2543#endif /* subprocess && !HAVE_GETTIMEOFDAY && HAVE_TIMEVAL */
177c0ea7 2544
86a5659e
JB
2545/*
2546 * This function will go away as soon as all the stubs fixed. (fnf)
2547 */
2548
dfcf069d 2549void
971de7fb 2550croak (char *badfunc)
86a5659e
JB
2551{
2552 printf ("%s not yet implemented\r\n", badfunc);
28d440ab 2553 reset_all_sys_modes ();
86a5659e
JB
2554 exit (1);
2555}
2556
2557#endif /* USG */
2558\f
86a5659e
JB
2559/* Directory routines for systems that don't have them. */
2560
2561#ifdef SYSV_SYSTEM_DIR
2562
2563#include <dirent.h>
2564
9d9a7716 2565#if !defined (HAVE_CLOSEDIR)
cfdc57af 2566
86a5659e 2567int
9d9a7716 2568closedir (DIR *dirp /* stream from opendir */)
86a5659e 2569{
cfdc57af
RS
2570 int rtnval;
2571
68c45bf0 2572 rtnval = emacs_close (dirp->dd_fd);
9ac0d9e0 2573 xfree ((char *) dirp);
cfdc57af
RS
2574
2575 return rtnval;
86a5659e 2576}
9d9a7716 2577#endif /* not HAVE_CLOSEDIR */
86a5659e
JB
2578#endif /* SYSV_SYSTEM_DIR */
2579
23524fb9 2580\f
53ea491a 2581int
971de7fb 2582set_file_times (const char *filename, struct timeval atime, struct timeval mtime)
53ea491a
KH
2583{
2584#ifdef HAVE_UTIMES
2585 struct timeval tv[2];
2586 tv[0] = atime;
2587 tv[1] = mtime;
8334eb21
RS
2588 return utimes (filename, tv);
2589#else /* not HAVE_UTIMES */
53ea491a
KH
2590 struct utimbuf utb;
2591 utb.actime = EMACS_SECS (atime);
2592 utb.modtime = EMACS_SECS (mtime);
8334eb21
RS
2593 return utime (filename, &utb);
2594#endif /* not HAVE_UTIMES */
53ea491a
KH
2595}
2596\f
23524fb9
JB
2597/* mkdir and rmdir functions, for systems which don't have them. */
2598
2599#ifndef HAVE_MKDIR
2600/*
2601 * Written by Robert Rother, Mariah Corporation, August 1985.
2602 *
2603 * If you want it, it's yours. All I ask in return is that if you
2604 * figure out how to do this in a Bourne Shell script you send me
2605 * a copy.
2606 * sdcsvax!rmr or rmr@uscd
2607 *
2608 * Severely hacked over by John Gilmore to make a 4.2BSD compatible
db9cd97a 2609 * subroutine. 11Mar86; hoptoad!gnu
23524fb9
JB
2610 *
2611 * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
2612 * subroutine didn't return EEXIST. It does now.
2613 */
2614
2615/*
2616 * Make a directory.
2617 */
2618int
2619mkdir (dpath, dmode)
2620 char *dpath;
2621 int dmode;
2622{
039f26a4 2623 int cpid, status, fd;
23524fb9
JB
2624 struct stat statbuf;
2625
2626 if (stat (dpath, &statbuf) == 0)
2627 {
2628 errno = EEXIST; /* Stat worked, so it already exists */
2629 return -1;
2630 }
2631
2632 /* If stat fails for a reason other than non-existence, return error */
2633 if (errno != ENOENT)
2634 return -1;
2635
039f26a4 2636 synch_process_alive = 1;
23524fb9
JB
2637 switch (cpid = fork ())
2638 {
2639
039f26a4 2640 case -1: /* Error in fork */
23524fb9
JB
2641 return (-1); /* Errno is set already */
2642
2643 case 0: /* Child process */
2644 /*
2645 * Cheap hack to set mode of new directory. Since this
2646 * child process is going away anyway, we zap its umask.
2647 * FIXME, this won't suffice to set SUID, SGID, etc. on this
2648 * directory. Does anybody care?
2649 */
2650 status = umask (0); /* Get current umask */
2651 status = umask (status | (0777 & ~dmode)); /* Set for mkdir */
68c45bf0 2652 fd = emacs_open ("/dev/null", O_RDWR, 0);
039f26a4
RS
2653 if (fd >= 0)
2654 {
2655 dup2 (fd, 0);
2656 dup2 (fd, 1);
2657 dup2 (fd, 2);
2658 }
23524fb9
JB
2659 execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
2660 _exit (-1); /* Can't exec /bin/mkdir */
2661
2662 default: /* Parent process */
039f26a4 2663 wait_for_termination (cpid);
23524fb9
JB
2664 }
2665
6b0824c9
JD
2666 if (synch_process_death != 0 || synch_process_retcode != 0
2667 || synch_process_termsig != 0)
23524fb9
JB
2668 {
2669 errno = EIO; /* We don't know why, but */
2670 return -1; /* /bin/mkdir failed */
2671 }
2672
2673 return 0;
2674}
2675#endif /* not HAVE_MKDIR */
2676
2677#ifndef HAVE_RMDIR
2678int
2679rmdir (dpath)
2680 char *dpath;
2681{
039f26a4 2682 int cpid, status, fd;
23524fb9
JB
2683 struct stat statbuf;
2684
2685 if (stat (dpath, &statbuf) != 0)
2686 {
2687 /* Stat just set errno. We don't have to */
2688 return -1;
2689 }
2690
039f26a4 2691 synch_process_alive = 1;
23524fb9
JB
2692 switch (cpid = fork ())
2693 {
2694
039f26a4 2695 case -1: /* Error in fork */
23524fb9
JB
2696 return (-1); /* Errno is set already */
2697
2698 case 0: /* Child process */
68c45bf0 2699 fd = emacs_open ("/dev/null", O_RDWR, 0);
039f26a4
RS
2700 if (fd >= 0)
2701 {
2702 dup2 (fd, 0);
2703 dup2 (fd, 1);
2704 dup2 (fd, 2);
2705 }
f560db78
RS
2706 execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
2707 _exit (-1); /* Can't exec /bin/rmdir */
2708
207bdbdb 2709 default: /* Parent process */
f560db78 2710 wait_for_termination (cpid);
23524fb9
JB
2711 }
2712
6b0824c9
JD
2713 if (synch_process_death != 0 || synch_process_retcode != 0
2714 || synch_process_termsig != 0)
23524fb9
JB
2715 {
2716 errno = EIO; /* We don't know why, but */
f560db78 2717 return -1; /* /bin/rmdir failed */
23524fb9
JB
2718 }
2719
2720 return 0;
2721}
2722#endif /* !HAVE_RMDIR */
2723
86a5659e 2724\f
68c45bf0
PE
2725#ifndef HAVE_STRSIGNAL
2726char *
2727strsignal (code)
2728 int code;
2729{
2730 char *signame = 0;
2731
2732 if (0 <= code && code < NSIG)
2733 {
68c45bf0
PE
2734 /* Cast to suppress warning if the table has const char *. */
2735 signame = (char *) sys_siglist[code];
68c45bf0 2736 }
c4ea52a6 2737
68c45bf0
PE
2738 return signame;
2739}
2740#endif /* HAVE_STRSIGNAL */
d888760c
GM
2741\f
2742#ifdef HAVE_TERMIOS
2743/* For make-serial-process */
2744int serial_open (char *port)
2745{
2746 int fd = -1;
2747
2748 fd = emacs_open ((char*) port,
2749 O_RDWR
2750#ifdef O_NONBLOCK
2751 | O_NONBLOCK
2752#else
2753 | O_NDELAY
2754#endif
2755#ifdef O_NOCTTY
2756 | O_NOCTTY
2757#endif
2758 , 0);
2759 if (fd < 0)
2760 {
2761 error ("Could not open %s: %s",
2762 port, emacs_strerror (errno));
2763 }
2764#ifdef TIOCEXCL
2765 ioctl (fd, TIOCEXCL, (char *) 0);
2766#endif
2767
2768 return fd;
2769}
2770#endif /* TERMIOS */
2771
2772#ifdef HAVE_TERMIOS
759d3f32
SM
2773
2774#if !defined (HAVE_CFMAKERAW)
2775/* Workaround for targets which are missing cfmakeraw. */
2776/* Pasted from man page. */
2777static void cfmakeraw (struct termios *termios_p)
2778{
2779 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2780 termios_p->c_oflag &= ~OPOST;
2781 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2782 termios_p->c_cflag &= ~(CSIZE|PARENB);
2783 termios_p->c_cflag |= CS8;
2784}
2785#endif /* !defined (HAVE_CFMAKERAW */
2786
2787#if !defined (HAVE_CFSETSPEED)
2788/* Workaround for targets which are missing cfsetspeed. */
2789static int cfsetspeed (struct termios *termios_p, speed_t vitesse)
2790{
2791 return (cfsetispeed (termios_p, vitesse)
2792 + cfsetospeed (termios_p, vitesse));
2793}
2794#endif
2795
d888760c
GM
2796/* For serial-process-configure */
2797void
2798serial_configure (struct Lisp_Process *p,
2799 Lisp_Object contact)
2800{
2801 Lisp_Object childp2 = Qnil;
2802 Lisp_Object tem = Qnil;
2803 struct termios attr;
2804 int err = -1;
2805 char summary[4] = "???"; /* This usually becomes "8N1". */
2806
2807 childp2 = Fcopy_sequence (p->childp);
2808
2809 /* Read port attributes and prepare default configuration. */
2810 err = tcgetattr (p->outfd, &attr);
2811 if (err != 0)
2812 error ("tcgetattr() failed: %s", emacs_strerror (errno));
2813 cfmakeraw (&attr);
2814#if defined (CLOCAL)
2815 attr.c_cflag |= CLOCAL;
2816#endif
2817#if defined (CREAD)
6d1921be 2818 attr.c_cflag |= CREAD;
d888760c
GM
2819#endif
2820
2821 /* Configure speed. */
2822 if (!NILP (Fplist_member (contact, QCspeed)))
2823 tem = Fplist_get (contact, QCspeed);
2824 else
2825 tem = Fplist_get (p->childp, QCspeed);
2826 CHECK_NUMBER (tem);
2827 err = cfsetspeed (&attr, XINT (tem));
2828 if (err != 0)
2829 error ("cfsetspeed(%d) failed: %s", XINT (tem), emacs_strerror (errno));
2830 childp2 = Fplist_put (childp2, QCspeed, tem);
2831
2832 /* Configure bytesize. */
2833 if (!NILP (Fplist_member (contact, QCbytesize)))
2834 tem = Fplist_get (contact, QCbytesize);
2835 else
2836 tem = Fplist_get (p->childp, QCbytesize);
2837 if (NILP (tem))
2838 tem = make_number (8);
2839 CHECK_NUMBER (tem);
2840 if (XINT (tem) != 7 && XINT (tem) != 8)
2841 error (":bytesize must be nil (8), 7, or 8");
2842 summary[0] = XINT(tem) + '0';
2843#if defined (CSIZE) && defined (CS7) && defined (CS8)
2844 attr.c_cflag &= ~CSIZE;
2845 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2846#else
16bad4dd 2847 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
d888760c
GM
2848 if (XINT (tem) != 8)
2849 error ("Bytesize cannot be changed");
2850#endif
2851 childp2 = Fplist_put (childp2, QCbytesize, tem);
2852
2853 /* Configure parity. */
2854 if (!NILP (Fplist_member (contact, QCparity)))
2855 tem = Fplist_get (contact, QCparity);
2856 else
2857 tem = Fplist_get (p->childp, QCparity);
2858 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2859 error (":parity must be nil (no parity), `even', or `odd'");
2860#if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2861 attr.c_cflag &= ~(PARENB | PARODD);
2862 attr.c_iflag &= ~(IGNPAR | INPCK);
2863 if (NILP (tem))
2864 {
2865 summary[1] = 'N';
2866 }
2867 else if (EQ (tem, Qeven))
2868 {
2869 summary[1] = 'E';
2870 attr.c_cflag |= PARENB;
2871 attr.c_iflag |= (IGNPAR | INPCK);
2872 }
2873 else if (EQ (tem, Qodd))
2874 {
2875 summary[1] = 'O';
2876 attr.c_cflag |= (PARENB | PARODD);
2877 attr.c_iflag |= (IGNPAR | INPCK);
2878 }
2879#else
16bad4dd 2880 /* Don't error on no parity, which should be set by cfmakeraw. */
d888760c
GM
2881 if (!NILP (tem))
2882 error ("Parity cannot be configured");
2883#endif
2884 childp2 = Fplist_put (childp2, QCparity, tem);
2885
2886 /* Configure stopbits. */
2887 if (!NILP (Fplist_member (contact, QCstopbits)))
2888 tem = Fplist_get (contact, QCstopbits);
2889 else
2890 tem = Fplist_get (p->childp, QCstopbits);
2891 if (NILP (tem))
2892 tem = make_number (1);
2893 CHECK_NUMBER (tem);
2894 if (XINT (tem) != 1 && XINT (tem) != 2)
2895 error (":stopbits must be nil (1 stopbit), 1, or 2");
2896 summary[2] = XINT (tem) + '0';
2897#if defined (CSTOPB)
2898 attr.c_cflag &= ~CSTOPB;
2899 if (XINT (tem) == 2)
2900 attr.c_cflag |= CSTOPB;
2901#else
16bad4dd 2902 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
d888760c
GM
2903 if (XINT (tem) != 1)
2904 error ("Stopbits cannot be configured");
2905#endif
2906 childp2 = Fplist_put (childp2, QCstopbits, tem);
2907
2908 /* Configure flowcontrol. */
2909 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2910 tem = Fplist_get (contact, QCflowcontrol);
2911 else
2912 tem = Fplist_get (p->childp, QCflowcontrol);
2913 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2914 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2915#if defined (CRTSCTS)
2916 attr.c_cflag &= ~CRTSCTS;
2917#endif
2918#if defined (CNEW_RTSCTS)
2919 attr.c_cflag &= ~CNEW_RTSCTS;
2920#endif
2921#if defined (IXON) && defined (IXOFF)
2922 attr.c_iflag &= ~(IXON | IXOFF);
2923#endif
2924 if (NILP (tem))
2925 {
2926 /* Already configured. */
2927 }
2928 else if (EQ (tem, Qhw))
2929 {
2930#if defined (CRTSCTS)
2931 attr.c_cflag |= CRTSCTS;
2932#elif defined (CNEW_RTSCTS)
2933 attr.c_cflag |= CNEW_RTSCTS;
2934#else
2935 error ("Hardware flowcontrol (RTS/CTS) not supported");
2936#endif
2937 }
2938 else if (EQ (tem, Qsw))
2939 {
2940#if defined (IXON) && defined (IXOFF)
2941 attr.c_iflag |= (IXON | IXOFF);
2942#else
2943 error ("Software flowcontrol (XON/XOFF) not supported");
2944#endif
2945 }
2946 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2947
2948 /* Activate configuration. */
2949 err = tcsetattr (p->outfd, TCSANOW, &attr);
2950 if (err != 0)
2951 error ("tcsetattr() failed: %s", emacs_strerror (errno));
2952
2953 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2954 p->childp = childp2;
2955
2956}
2957#endif /* TERMIOS */
06e111a6
DN
2958\f
2959/* System depended enumeration of and access to system processes a-la ps(1). */
2960
2961#ifdef HAVE_PROCFS
2962
2963/* Process enumeration and access via /proc. */
2964
2965Lisp_Object
971de7fb 2966list_system_processes (void)
06e111a6
DN
2967{
2968 Lisp_Object procdir, match, proclist, next;
2969 struct gcpro gcpro1, gcpro2;
2970 register Lisp_Object tail;
2971
2972 GCPRO2 (procdir, match);
2973 /* For every process on the system, there's a directory in the
2974 "/proc" pseudo-directory whose name is the numeric ID of that
2975 process. */
2976 procdir = build_string ("/proc");
2977 match = build_string ("[0-9]+");
2978 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2979
2980 /* `proclist' gives process IDs as strings. Destructively convert
2981 each string into a number. */
2982 for (tail = proclist; CONSP (tail); tail = next)
2983 {
2984 next = XCDR (tail);
2985 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2986 }
2987 UNGCPRO;
2988
2989 /* directory_files_internal returns the files in reverse order; undo
2990 that. */
2991 proclist = Fnreverse (proclist);
2992 return proclist;
2993}
2994
f8d23104
DN
2995/* The WINDOWSNT implementation is in w32.c.
2996 The MSDOS implementation is in dosfns.c. */
c4605e09 2997#elif !defined (WINDOWSNT) && !defined (MSDOS)
06e111a6
DN
2998
2999Lisp_Object
3000list_system_processes ()
3001{
3002 return Qnil;
3003}
91c85b70
EZ
3004
3005#endif /* !defined (WINDOWSNT) */
06e111a6
DN
3006
3007#ifdef GNU_LINUX
3008static void
3009time_from_jiffies (unsigned long long tval, long hz,
3010 time_t *sec, unsigned *usec)
3011{
3012 unsigned long long ullsec;
3013
3014 *sec = tval / hz;
3015 ullsec = *sec;
3016 tval -= ullsec * hz;
3017 /* Careful: if HZ > 1 million, then integer division by it yields zero. */
3018 if (hz <= 1000000)
3019 *usec = tval * 1000000 / hz;
3020 else
3021 *usec = tval / (hz / 1000000);
3022}
3023
3024static Lisp_Object
3025ltime_from_jiffies (unsigned long long tval, long hz)
3026{
3027 time_t sec;
3028 unsigned usec;
3029
3030 time_from_jiffies (tval, hz, &sec, &usec);
3031
3032 return list3 (make_number ((sec >> 16) & 0xffff),
3033 make_number (sec & 0xffff),
3034 make_number (usec));
3035}
3036
3037static void
3038get_up_time (time_t *sec, unsigned *usec)
3039{
3040 FILE *fup;
3041
3042 *sec = *usec = 0;
3043
3044 BLOCK_INPUT;
3045 fup = fopen ("/proc/uptime", "r");
3046
3047 if (fup)
3048 {
3049 double uptime, idletime;
3050
3051 /* The numbers in /proc/uptime use C-locale decimal point, but
3052 we already set ourselves to the C locale (see `fixup_locale'
3053 in emacs.c). */
3054 if (2 <= fscanf (fup, "%lf %lf", &uptime, &idletime))
3055 {
3056 *sec = uptime;
3057 *usec = (uptime - *sec) * 1000000;
3058 }
3059 fclose (fup);
3060 }
3061 UNBLOCK_INPUT;
3062}
3063
3064#define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3065#define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3066
3067static Lisp_Object
f4f634e8 3068procfs_ttyname (int rdev)
06e111a6
DN
3069{
3070 FILE *fdev = NULL;
3071 char name[PATH_MAX];
3072
3073 BLOCK_INPUT;
3074 fdev = fopen ("/proc/tty/drivers", "r");
3075
3076 if (fdev)
3077 {
3078 unsigned major;
3079 unsigned long minor_beg, minor_end;
3080 char minor[25]; /* 2 32-bit numbers + dash */
3081 char *endp;
3082
3083 while (!feof (fdev) && !ferror (fdev))
3084 {
3085 if (3 <= fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor)
3086 && major == MAJOR (rdev))
3087 {
3088 minor_beg = strtoul (minor, &endp, 0);
3089 if (*endp == '\0')
3090 minor_end = minor_beg;
3091 else if (*endp == '-')
3092 minor_end = strtoul (endp + 1, &endp, 0);
3093 else
3094 continue;
3095
3096 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3097 {
10d66ec0 3098 sprintf (name + strlen (name), "%u", MINOR (rdev));
06e111a6
DN
3099 break;
3100 }
3101 }
3102 }
3103 fclose (fdev);
3104 }
3105 UNBLOCK_INPUT;
3106 return build_string (name);
3107}
3108
3109static unsigned long
3110procfs_get_total_memory (void)
3111{
3112 FILE *fmem = NULL;
3113 unsigned long retval = 2 * 1024 * 1024; /* default: 2GB */
3114
3115 BLOCK_INPUT;
3116 fmem = fopen ("/proc/meminfo", "r");
3117
3118 if (fmem)
3119 {
3120 unsigned long entry_value;
3121 char entry_name[20]; /* the longest I saw is 13+1 */
3122
3123 while (!feof (fmem) && !ferror (fmem))
3124 {
3125 if (2 <= fscanf (fmem, "%s %lu kB\n", entry_name, &entry_value)
3126 && strcmp (entry_name, "MemTotal:") == 0)
3127 {
3128 retval = entry_value;
3129 break;
3130 }
3131 }
3132 fclose (fmem);
3133 }
3134 UNBLOCK_INPUT;
3135 return retval;
3136}
3137
3138Lisp_Object
f4f634e8 3139system_process_attributes (Lisp_Object pid)
06e111a6
DN
3140{
3141 char procfn[PATH_MAX], fn[PATH_MAX];
3142 struct stat st;
3143 struct passwd *pw;
3144 struct group *gr;
3145 long clocks_per_sec;
3146 char *procfn_end;
3147 char procbuf[1025], *p, *q;
3148 int fd;
3149 ssize_t nread;
3150 const char *cmd = NULL;
3151 char *cmdline = NULL;
3152 size_t cmdsize = 0, cmdline_size;
3153 unsigned char c;
3154 int proc_id, ppid, uid, gid, pgrp, sess, tty, tpgid, thcount;
3155 unsigned long long utime, stime, cutime, cstime, start;
3156 long priority, nice, rss;
3157 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3158 time_t sec;
3159 unsigned usec;
2b0a91e7 3160 EMACS_TIME tnow, tstart, tboot, telapsed;
06e111a6
DN
3161 double pcpu, pmem;
3162 Lisp_Object attrs = Qnil;
3163 Lisp_Object cmd_str, decoded_cmd, tem;
3164 struct gcpro gcpro1, gcpro2;
3165 EMACS_INT uid_eint, gid_eint;
3166
3167 CHECK_NUMBER_OR_FLOAT (pid);
3168 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
10d66ec0 3169 sprintf (procfn, "/proc/%u", proc_id);
06e111a6
DN
3170 if (stat (procfn, &st) < 0)
3171 return attrs;
3172
3173 GCPRO2 (attrs, decoded_cmd);
3174
3175 /* euid egid */
3176 uid = st.st_uid;
3177 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
3178 uid_eint = uid;
3179 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
3180 BLOCK_INPUT;
3181 pw = getpwuid (uid);
3182 UNBLOCK_INPUT;
3183 if (pw)
3184 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3185
3186 gid = st.st_gid;
3187 gid_eint = gid;
3188 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
3189 BLOCK_INPUT;
3190 gr = getgrgid (gid);
3191 UNBLOCK_INPUT;
3192 if (gr)
3193 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3194
3195 strcpy (fn, procfn);
3196 procfn_end = fn + strlen (fn);
3197 strcpy (procfn_end, "/stat");
3198 fd = emacs_open (fn, O_RDONLY, 0);
3199 if (fd >= 0 && (nread = emacs_read (fd, procbuf, sizeof(procbuf) - 1)) > 0)
3200 {
3201 procbuf[nread] = '\0';
3202 p = procbuf;
3203
3204 p = strchr (p, '(');
3205 if (p != NULL)
3206 {
3207 q = strrchr (p + 1, ')');
3208 /* comm */
3209 if (q != NULL)
3210 {
3211 cmd = p + 1;
3212 cmdsize = q - cmd;
3213 }
3214 }
3215 else
3216 q = NULL;
3217 if (cmd == NULL)
3218 {
3219 cmd = "???";
3220 cmdsize = 3;
3221 }
3222 /* Command name is encoded in locale-coding-system; decode it. */
3223 cmd_str = make_unibyte_string (cmd, cmdsize);
3224 decoded_cmd = code_convert_string_norecord (cmd_str,
3225 Vlocale_coding_system, 0);
3226 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3227
3228 if (q)
3229 {
3230 EMACS_INT ppid_eint, pgrp_eint, sess_eint, tpgid_eint, thcount_eint;
3231 p = q + 2;
3232 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt utime stime cutime cstime priority nice thcount . start vsize rss */
3233 sscanf (p, "%c %d %d %d %d %d %*u %lu %lu %lu %lu %Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld",
3234 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3235 &minflt, &cminflt, &majflt, &cmajflt,
3236 &utime, &stime, &cutime, &cstime,
3237 &priority, &nice, &thcount, &start, &vsize, &rss);
3238 {
3239 char state_str[2];
3240
3241 state_str[0] = c;
3242 state_str[1] = '\0';
3243 tem = build_string (state_str);
3244 attrs = Fcons (Fcons (Qstate, tem), attrs);
3245 }
3246 /* Stops GCC whining about limited range of data type. */
3247 ppid_eint = ppid;
3248 pgrp_eint = pgrp;
3249 sess_eint = sess;
3250 tpgid_eint = tpgid;
3251 thcount_eint = thcount;
3252 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid_eint)), attrs);
3253 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp_eint)), attrs);
3254 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess_eint)), attrs);
3255 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3256 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid_eint)), attrs);
3257 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3258 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3259 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)), attrs);
3260 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)), attrs);
3261 clocks_per_sec = sysconf (_SC_CLK_TCK);
3262 if (clocks_per_sec < 0)
3263 clocks_per_sec = 100;
3264 attrs = Fcons (Fcons (Qutime,
3265 ltime_from_jiffies (utime, clocks_per_sec)),
3266 attrs);
3267 attrs = Fcons (Fcons (Qstime,
3268 ltime_from_jiffies (stime, clocks_per_sec)),
3269 attrs);
ac1e4171
EZ
3270 attrs = Fcons (Fcons (Qtime,
3271 ltime_from_jiffies (stime+utime, clocks_per_sec)),
3272 attrs);
06e111a6
DN
3273 attrs = Fcons (Fcons (Qcutime,
3274 ltime_from_jiffies (cutime, clocks_per_sec)),
3275 attrs);
3276 attrs = Fcons (Fcons (Qcstime,
3277 ltime_from_jiffies (cstime, clocks_per_sec)),
ac1e4171
EZ
3278 attrs);
3279 attrs = Fcons (Fcons (Qctime,
3280 ltime_from_jiffies (cstime+cutime, clocks_per_sec)),
06e111a6
DN
3281 attrs);
3282 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3283 attrs = Fcons (Fcons (Qnice, make_number (nice)), attrs);
3284 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount_eint)), attrs);
3285 EMACS_GET_TIME (tnow);
3286 get_up_time (&sec, &usec);
3287 EMACS_SET_SECS (telapsed, sec);
3288 EMACS_SET_USECS (telapsed, usec);
3289 EMACS_SUB_TIME (tboot, tnow, telapsed);
3290 time_from_jiffies (start, clocks_per_sec, &sec, &usec);
3291 EMACS_SET_SECS (tstart, sec);
3292 EMACS_SET_USECS (tstart, usec);
3293 EMACS_ADD_TIME (tstart, tboot, tstart);
3294 attrs = Fcons (Fcons (Qstart,
3295 list3 (make_number
3296 ((EMACS_SECS (tstart) >> 16) & 0xffff),
3297 make_number
3298 (EMACS_SECS (tstart) & 0xffff),
3299 make_number
3300 (EMACS_USECS (tstart)))),
3301 attrs);
3302 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize/1024)), attrs);
3303 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4*rss)), attrs);
3304 EMACS_SUB_TIME (telapsed, tnow, tstart);
3305 attrs = Fcons (Fcons (Qetime,
3306 list3 (make_number
3307 ((EMACS_SECS (telapsed) >> 16) & 0xffff),
3308 make_number
3309 (EMACS_SECS (telapsed) & 0xffff),
3310 make_number
3311 (EMACS_USECS (telapsed)))),
3312 attrs);
3313 time_from_jiffies (utime + stime, clocks_per_sec, &sec, &usec);
3314 pcpu = (sec + usec / 1000000.0) / (EMACS_SECS (telapsed) + EMACS_USECS (telapsed) / 1000000.0);
3315 if (pcpu > 1.0)
3316 pcpu = 1.0;
3317 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3318 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3319 if (pmem > 100)
3320 pmem = 100;
3321 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3322 }
3323 }
3324 if (fd >= 0)
3325 emacs_close (fd);
3326
3327 /* args */
3328 strcpy (procfn_end, "/cmdline");
3329 fd = emacs_open (fn, O_RDONLY, 0);
3330 if (fd >= 0)
3331 {
3332 for (cmdline_size = 0; emacs_read (fd, &c, 1) == 1; cmdline_size++)
3333 {
3334 if (isspace (c) || c == '\\')
3335 cmdline_size++; /* for later quoting, see below */
3336 }
3337 if (cmdline_size)
3338 {
3339 cmdline = xmalloc (cmdline_size + 1);
3340 lseek (fd, 0L, SEEK_SET);
3341 cmdline[0] = '\0';
3342 if ((nread = read (fd, cmdline, cmdline_size)) >= 0)
3343 cmdline[nread++] = '\0';
3344 else
3345 {
3346 /* Assigning zero to `nread' makes us skip the following
3347 two loops, assign zero to cmdline_size, and enter the
3348 following `if' clause that handles unknown command
3349 lines. */
3350 nread = 0;
3351 }
3352 /* We don't want trailing null characters. */
3353 for (p = cmdline + nread - 1; p > cmdline && !*p; p--)
3354 nread--;
3355 for (p = cmdline; p < cmdline + nread; p++)
3356 {
3357 /* Escape-quote whitespace and backslashes. */
3358 if (isspace (*p) || *p == '\\')
3359 {
3360 memmove (p + 1, p, nread - (p - cmdline));
3361 nread++;
3362 *p++ = '\\';
3363 }
3364 else if (*p == '\0')
3365 *p = ' ';
3366 }
3367 cmdline_size = nread;
3368 }
3369 if (!cmdline_size)
3370 {
3371 if (!cmd)
3372 cmd = "???";
3373 if (!cmdsize)
3374 cmdsize = strlen (cmd);
3375 cmdline_size = cmdsize + 2;
3376 cmdline = xmalloc (cmdline_size + 1);
3377 strcpy (cmdline, "[");
3378 strcat (strncat (cmdline, cmd, cmdsize), "]");
3379 }
3380 emacs_close (fd);
3381 /* Command line is encoded in locale-coding-system; decode it. */
3382 cmd_str = make_unibyte_string (cmdline, cmdline_size);
3383 decoded_cmd = code_convert_string_norecord (cmd_str,
3384 Vlocale_coding_system, 0);
3385 xfree (cmdline);
3386 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3387 }
3388
3389 UNGCPRO;
3390 return attrs;
3391}
91c85b70 3392
f4f634e8
DN
3393#elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3394
3395/* The <procfs.h> header does not like to be included if _LP64 is defined and
3396 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3397#if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3398#define PROCFS_FILE_OFFSET_BITS_HACK 1
3399#undef _FILE_OFFSET_BITS
3400#else
3401#define PROCFS_FILE_OFFSET_BITS_HACK 0
3402#endif
3403
3404#include <procfs.h>
3405
3406#if PROCFS_FILE_OFFSET_BITS_HACK == 1
3407#define _FILE_OFFSET_BITS 64
3408#endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3409
3410Lisp_Object
3411system_process_attributes (Lisp_Object pid)
3412{
3413 char procfn[PATH_MAX], fn[PATH_MAX];
3414 struct stat st;
3415 struct passwd *pw;
3416 struct group *gr;
3417 char *procfn_end;
3418 struct psinfo pinfo;
3419 int fd;
3420 ssize_t nread;
3421 int proc_id, uid, gid;
3422 Lisp_Object attrs = Qnil;
3423 Lisp_Object decoded_cmd, tem;
3424 struct gcpro gcpro1, gcpro2;
3425 EMACS_INT uid_eint, gid_eint;
3426
3427 CHECK_NUMBER_OR_FLOAT (pid);
3428 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
3429 sprintf (procfn, "/proc/%u", proc_id);
3430 if (stat (procfn, &st) < 0)
3431 return attrs;
3432
3433 GCPRO2 (attrs, decoded_cmd);
3434
3435 /* euid egid */
3436 uid = st.st_uid;
3437 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
3438 uid_eint = uid;
3439 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
3440 BLOCK_INPUT;
3441 pw = getpwuid (uid);
3442 UNBLOCK_INPUT;
3443 if (pw)
3444 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3445
3446 gid = st.st_gid;
3447 gid_eint = gid;
3448 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
3449 BLOCK_INPUT;
3450 gr = getgrgid (gid);
3451 UNBLOCK_INPUT;
3452 if (gr)
3453 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3454
3455 strcpy (fn, procfn);
3456 procfn_end = fn + strlen (fn);
3457 strcpy (procfn_end, "/psinfo");
3458 fd = emacs_open (fn, O_RDONLY, 0);
3459 if (fd >= 0
3460 && (nread = read (fd, (char*)&pinfo, sizeof(struct psinfo)) > 0))
3461 {
3462 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3463 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3464 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3465
3466 {
3467 char state_str[2];
3468 state_str[0] = pinfo.pr_lwp.pr_sname;
3469 state_str[1] = '\0';
3470 tem = build_string (state_str);
3471 attrs = Fcons (Fcons (Qstate, tem), attrs);
3472 }
3473
3474 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3475 need to get a string from it. */
3476
3477 /* FIXME: missing: Qtpgid */
3478
3479 /* FIXME: missing:
3480 Qminflt
3481 Qmajflt
3482 Qcminflt
3483 Qcmajflt
3484
bfe11752
DN
3485 Qutime
3486 Qcutime
f4f634e8
DN
3487 Qstime
3488 Qcstime
3489 Are they available? */
3490
bfe11752 3491 attrs = Fcons (Fcons (Qtime,
f4f634e8
DN
3492 list3 (make_number (pinfo.pr_time.tv_sec >> 16),
3493 make_number (pinfo.pr_time.tv_sec & 0xffff),
3494 make_number (pinfo.pr_time.tv_nsec))),
3495 attrs);
3496
bfe11752 3497 attrs = Fcons (Fcons (Qctime,
f4f634e8
DN
3498 list3 (make_number (pinfo.pr_ctime.tv_sec >> 16),
3499 make_number (pinfo.pr_ctime.tv_sec & 0xffff),
3500 make_number (pinfo.pr_ctime.tv_nsec))),
3501 attrs);
3502
3503 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3504 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3505 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)), attrs);
3506
3507 attrs = Fcons (Fcons (Qstart,
3508 list3 (make_number (pinfo.pr_start.tv_sec >> 16),
3509 make_number (pinfo.pr_start.tv_sec & 0xffff),
3510 make_number (pinfo.pr_start.tv_nsec))),
3511 attrs);
3512 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)), attrs);
3513 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)), attrs);
3514
3515 /* pr_pctcpu and pr_pctmem are encoded as a fixed point 16 bit number in [0 ... 1]. */
3516 attrs = Fcons (Fcons (Qpcpu, (pinfo.pr_pctcpu * 100.0) / (double)0x8000), attrs);
3517 attrs = Fcons (Fcons (Qpmem, (pinfo.pr_pctmem * 100.0) / (double)0x8000), attrs);
3518
3519 decoded_cmd
3520 = code_convert_string_norecord (make_unibyte_string (pinfo.pr_fname,
3521 strlen (pinfo.pr_fname)),
3522 Vlocale_coding_system, 0);
3523 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3524 decoded_cmd
3525 = code_convert_string_norecord (make_unibyte_string (pinfo.pr_psargs,
3526 strlen (pinfo.pr_psargs)),
3527 Vlocale_coding_system, 0);
3528 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3529 }
3530
2d2d05d8
DN
3531 if (fd >= 0)
3532 emacs_close (fd);
3533
f4f634e8
DN
3534 UNGCPRO;
3535 return attrs;
3536}
06e111a6 3537
f8d23104
DN
3538/* The WINDOWSNT implementation is in w32.c.
3539 The MSDOS implementation is in dosfns.c. */
c4605e09 3540#elif !defined (WINDOWSNT) && !defined (MSDOS)
06e111a6
DN
3541
3542Lisp_Object
3543system_process_attributes (Lisp_Object pid)
3544{
9dcbe89b 3545 return Qnil;
06e111a6
DN
3546}
3547
3548#endif /* !defined (WINDOWSNT) */
3549
c4ea52a6 3550
ab5796a9
MB
3551/* arch-tag: edb43589-4e09-4544-b325-978b5b121dcf
3552 (do not change this comment) */