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