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