Simplify SELECT_TYPE-related code.
[emacs.git] / src / sysdep.c
blob6439697501e022bcbf21180578d52ec08f0bf0b4
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2013 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #define SYSTIME_INLINE EXTERN_INLINE
24 #include <execinfo.h>
25 #include "sysstdio.h"
26 #ifdef HAVE_PWD_H
27 #include <pwd.h>
28 #include <grp.h>
29 #endif /* HAVE_PWD_H */
30 #include <limits.h>
31 #include <unistd.h>
33 #include <c-ctype.h>
34 #include <utimens.h>
36 #include "lisp.h"
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #if defined DARWIN_OS || defined __FreeBSD__
41 # include <sys/sysctl.h>
42 #endif
44 #ifdef __FreeBSD__
45 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
46 'struct frame', so rename it. */
47 # define frame freebsd_frame
48 # include <sys/user.h>
49 # undef frame
51 # include <sys/resource.h>
52 # include <math.h>
53 #endif
55 #ifdef WINDOWSNT
56 #define read sys_read
57 #define write sys_write
58 #ifndef STDERR_FILENO
59 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
60 #endif
61 #include <windows.h>
62 #endif /* not WINDOWSNT */
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <errno.h>
68 /* Get SI_SRPC_DOMAIN, if it is available. */
69 #ifdef HAVE_SYS_SYSTEMINFO_H
70 #include <sys/systeminfo.h>
71 #endif
73 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
74 #include "msdos.h"
75 #endif
77 #include <sys/param.h>
78 #include <sys/file.h>
79 #include <fcntl.h>
81 #include "systty.h"
82 #include "syswait.h"
84 #ifdef HAVE_SYS_UTSNAME_H
85 #include <sys/utsname.h>
86 #include <memory.h>
87 #endif /* HAVE_SYS_UTSNAME_H */
89 #include "keyboard.h"
90 #include "frame.h"
91 #include "window.h"
92 #include "termhooks.h"
93 #include "termchar.h"
94 #include "termopts.h"
95 #include "dispextern.h"
96 #include "process.h"
97 #include "cm.h" /* for reset_sys_modes */
99 #ifdef WINDOWSNT
100 #include <direct.h>
101 /* In process.h which conflicts with the local copy. */
102 #define _P_WAIT 0
103 int _cdecl _spawnlp (int, const char *, const char *, ...);
104 int _cdecl _getpid (void);
105 #endif
107 #include "syssignal.h"
108 #include "systime.h"
110 static void emacs_get_tty (int, struct emacs_tty *);
111 static int emacs_set_tty (int, struct emacs_tty *, bool);
113 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
114 #ifndef ULLONG_MAX
115 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
116 #endif
118 /* Declare here, including term.h is problematic on some systems. */
119 extern void tputs (const char *, int, int (*)(int));
121 static const int baud_convert[] =
123 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
124 1800, 2400, 4800, 9600, 19200, 38400
128 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
130 /* Return the current working directory. Returns NULL on errors.
131 Any other returned value must be freed with free. This is used
132 only when get_current_dir_name is not defined on the system. */
133 char*
134 get_current_dir_name (void)
136 char *buf;
137 char *pwd = getenv ("PWD");
138 struct stat dotstat, pwdstat;
139 /* If PWD is accurate, use it instead of calling getcwd. PWD is
140 sometimes a nicer name, and using it may avoid a fatal error if a
141 parent directory is searchable but not readable. */
142 if (pwd
143 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
144 && stat (pwd, &pwdstat) == 0
145 && stat (".", &dotstat) == 0
146 && dotstat.st_ino == pwdstat.st_ino
147 && dotstat.st_dev == pwdstat.st_dev
148 #ifdef MAXPATHLEN
149 && strlen (pwd) < MAXPATHLEN
150 #endif
153 buf = malloc (strlen (pwd) + 1);
154 if (!buf)
155 return NULL;
156 strcpy (buf, pwd);
158 else
160 size_t buf_size = 1024;
161 buf = malloc (buf_size);
162 if (!buf)
163 return NULL;
164 for (;;)
166 if (getcwd (buf, buf_size) == buf)
167 break;
168 if (errno != ERANGE)
170 int tmp_errno = errno;
171 free (buf);
172 errno = tmp_errno;
173 return NULL;
175 buf_size *= 2;
176 buf = realloc (buf, buf_size);
177 if (!buf)
178 return NULL;
181 return buf;
183 #endif
186 /* Discard pending input on all input descriptors. */
188 void
189 discard_tty_input (void)
191 #ifndef WINDOWSNT
192 struct emacs_tty buf;
194 if (noninteractive)
195 return;
197 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
198 while (dos_keyread () != -1)
200 #else /* not MSDOS */
202 struct tty_display_info *tty;
203 for (tty = tty_list; tty; tty = tty->next)
205 if (tty->input) /* Is the device suspended? */
207 emacs_get_tty (fileno (tty->input), &buf);
208 emacs_set_tty (fileno (tty->input), &buf, 0);
212 #endif /* not MSDOS */
213 #endif /* not WINDOWSNT */
217 #ifdef SIGTSTP
219 /* Arrange for character C to be read as the next input from
220 the terminal.
221 XXX What if we have multiple ttys?
224 void
225 stuff_char (char c)
227 if (! FRAME_TERMCAP_P (SELECTED_FRAME ()))
228 return;
230 /* Should perhaps error if in batch mode */
231 #ifdef TIOCSTI
232 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
233 #else /* no TIOCSTI */
234 error ("Cannot stuff terminal input characters in this version of Unix");
235 #endif /* no TIOCSTI */
238 #endif /* SIGTSTP */
240 void
241 init_baud_rate (int fd)
243 int emacs_ospeed;
245 if (noninteractive)
246 emacs_ospeed = 0;
247 else
249 #ifdef DOS_NT
250 emacs_ospeed = 15;
251 #else /* not DOS_NT */
252 struct termios sg;
254 sg.c_cflag = B9600;
255 tcgetattr (fd, &sg);
256 emacs_ospeed = cfgetospeed (&sg);
257 #endif /* not DOS_NT */
260 baud_rate = (emacs_ospeed < sizeof baud_convert / sizeof baud_convert[0]
261 ? baud_convert[emacs_ospeed] : 9600);
262 if (baud_rate == 0)
263 baud_rate = 1200;
268 #ifndef MSDOS
270 /* Wait for the subprocess with process id CHILD to terminate or change status.
271 CHILD must be a child process that has not been reaped.
272 If STATUS is non-null, store the waitpid-style exit status into *STATUS
273 and tell wait_reading_process_output that it needs to look around.
274 Use waitpid-style OPTIONS when waiting.
275 If INTERRUPTIBLE, this function is interruptible by a signal.
277 Return CHILD if successful, 0 if no status is available;
278 the latter is possible only when options & NOHANG. */
279 static pid_t
280 get_child_status (pid_t child, int *status, int options, bool interruptible)
282 pid_t pid;
284 /* Invoke waitpid only with a known process ID; do not invoke
285 waitpid with a nonpositive argument. Otherwise, Emacs might
286 reap an unwanted process by mistake. For example, invoking
287 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
288 so that another thread running glib won't find them. */
289 eassert (child > 0);
291 while ((pid = waitpid (child, status, options)) < 0)
293 /* Check that CHILD is a child process that has not been reaped,
294 and that STATUS and OPTIONS are valid. Otherwise abort,
295 as continuing after this internal error could cause Emacs to
296 become confused and kill innocent-victim processes. */
297 if (errno != EINTR)
298 emacs_abort ();
300 /* Note: the MS-Windows emulation of waitpid calls QUIT
301 internally. */
302 if (interruptible)
303 QUIT;
306 /* If successful and status is requested, tell wait_reading_process_output
307 that it needs to wake up and look around. */
308 if (pid && status && input_available_clear_time)
309 *input_available_clear_time = make_timespec (0, 0);
311 return pid;
314 /* Wait for the subprocess with process id CHILD to terminate.
315 CHILD must be a child process that has not been reaped.
316 If STATUS is non-null, store the waitpid-style exit status into *STATUS
317 and tell wait_reading_process_output that it needs to look around.
318 If INTERRUPTIBLE, this function is interruptible by a signal. */
319 void
320 wait_for_termination (pid_t child, int *status, bool interruptible)
322 get_child_status (child, status, 0, interruptible);
325 /* Report whether the subprocess with process id CHILD has changed status.
326 Termination counts as a change of status.
327 CHILD must be a child process that has not been reaped.
328 If STATUS is non-null, store the waitpid-style exit status into *STATUS
329 and tell wait_reading_process_output that it needs to look around.
330 Use waitpid-style OPTIONS to check status, but do not wait.
332 Return CHILD if successful, 0 if no status is available because
333 the process's state has not changed. */
334 pid_t
335 child_status_changed (pid_t child, int *status, int options)
337 return get_child_status (child, status, WNOHANG | options, 0);
341 /* Set up the terminal at the other end of a pseudo-terminal that
342 we will be controlling an inferior through.
343 It should not echo or do line-editing, since that is done
344 in Emacs. No padding needed for insertion into an Emacs buffer. */
346 void
347 child_setup_tty (int out)
349 #ifndef WINDOWSNT
350 struct emacs_tty s;
352 emacs_get_tty (out, &s);
353 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
354 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
355 #ifdef NLDLY
356 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
357 Some versions of GNU Hurd do not have FFDLY? */
358 #ifdef FFDLY
359 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
360 /* No output delays */
361 #else
362 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
363 /* No output delays */
364 #endif
365 #endif
366 s.main.c_lflag &= ~ECHO; /* Disable echo */
367 s.main.c_lflag |= ISIG; /* Enable signals */
368 #ifdef IUCLC
369 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
370 #endif
371 #ifdef ISTRIP
372 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
373 #endif
374 #ifdef OLCUC
375 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
376 #endif
377 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
378 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
379 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
380 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
382 #ifdef HPUX
383 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
384 #endif /* HPUX */
386 #ifdef SIGNALS_VIA_CHARACTERS
387 /* the QUIT and INTR character are used in process_send_signal
388 so set them here to something useful. */
389 if (s.main.c_cc[VQUIT] == CDISABLE)
390 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
391 if (s.main.c_cc[VINTR] == CDISABLE)
392 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
393 #endif /* not SIGNALS_VIA_CHARACTERS */
395 #ifdef AIX
396 /* Also, PTY overloads NUL and BREAK.
397 don't ignore break, but don't signal either, so it looks like NUL. */
398 s.main.c_iflag &= ~IGNBRK;
399 s.main.c_iflag &= ~BRKINT;
400 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
401 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
402 would force it to 0377. That looks like duplicated code. */
403 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
404 #endif /* AIX */
406 /* We originally enabled ICANON (and set VEOF to 04), and then had
407 process.c send additional EOF chars to flush the output when faced
408 with long lines, but this leads to weird effects when the
409 subprocess has disabled ICANON and ends up seeing those spurious
410 extra EOFs. So we don't send EOFs any more in
411 process.c:send_process. First we tried to disable ICANON by
412 default, so if a subsprocess sets up ICANON, it's his problem (or
413 the Elisp package that talks to it) to deal with lines that are
414 too long. But this disables some features, such as the ability
415 to send EOF signals. So we re-enabled ICANON but there is no
416 more "send eof to flush" going on (which is wrong and unportable
417 in itself). The correct way to handle too much output is to
418 buffer what could not be written and then write it again when
419 select returns ok for writing. This has it own set of
420 problems. Write is now asynchronous, is that a problem? How much
421 do we buffer, and what do we do when that limit is reached? */
423 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
424 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
425 #if 0 /* These settings only apply to non-ICANON mode. */
426 s.main.c_cc[VMIN] = 1;
427 s.main.c_cc[VTIME] = 0;
428 #endif
430 emacs_set_tty (out, &s, 0);
431 #endif /* not WINDOWSNT */
433 #endif /* not MSDOS */
436 /* Record a signal code and the action for it. */
437 struct save_signal
439 int code;
440 struct sigaction action;
443 static void save_signal_handlers (struct save_signal *);
444 static void restore_signal_handlers (struct save_signal *);
446 /* Suspend the Emacs process; give terminal to its superior. */
448 void
449 sys_suspend (void)
451 #ifndef DOS_NT
452 kill (0, SIGTSTP);
453 #else
454 /* On a system where suspending is not implemented,
455 instead fork a subshell and let it talk directly to the terminal
456 while we wait. */
457 sys_subshell ();
459 #endif
462 /* Fork a subshell. */
464 void
465 sys_subshell (void)
467 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
468 int st;
469 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
470 #endif
471 pid_t pid;
472 int status;
473 struct save_signal saved_handlers[5];
474 char *str = SSDATA (encode_current_directory ());
476 #ifdef DOS_NT
477 pid = 0;
478 #else
480 char *volatile str_volatile = str;
481 pid = vfork ();
482 str = str_volatile;
484 #endif
486 if (pid < 0)
487 error ("Can't spawn subshell");
489 saved_handlers[0].code = SIGINT;
490 saved_handlers[1].code = SIGQUIT;
491 saved_handlers[2].code = SIGTERM;
492 #ifdef USABLE_SIGIO
493 saved_handlers[3].code = SIGIO;
494 saved_handlers[4].code = 0;
495 #else
496 saved_handlers[3].code = 0;
497 #endif
499 #ifdef DOS_NT
500 save_signal_handlers (saved_handlers);
501 #endif
503 if (pid == 0)
505 const char *sh = 0;
507 #ifdef DOS_NT /* MW, Aug 1993 */
508 getcwd (oldwd, sizeof oldwd);
509 if (sh == 0)
510 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
511 #endif
512 if (sh == 0)
513 sh = egetenv ("SHELL");
514 if (sh == 0)
515 sh = "sh";
517 /* Use our buffer's default directory for the subshell. */
518 if (chdir (str) != 0)
520 #ifndef DOS_NT
521 emacs_perror (str);
522 _exit (EXIT_CANCELED);
523 #endif
526 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
528 char *epwd = getenv ("PWD");
529 char old_pwd[MAXPATHLEN+1+4];
531 /* If PWD is set, pass it with corrected value. */
532 if (epwd)
534 strcpy (old_pwd, epwd);
535 setenv ("PWD", str, 1);
537 st = system (sh);
538 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
539 if (epwd)
540 putenv (old_pwd); /* restore previous value */
542 #else /* not MSDOS */
543 #ifdef WINDOWSNT
544 /* Waits for process completion */
545 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
546 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
547 if (pid == -1)
548 write (1, "Can't execute subshell", 22);
549 #else /* not WINDOWSNT */
550 execlp (sh, sh, (char *) 0);
551 emacs_perror (sh);
552 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
553 #endif /* not WINDOWSNT */
554 #endif /* not MSDOS */
557 /* Do this now if we did not do it before. */
558 #ifndef MSDOS
559 save_signal_handlers (saved_handlers);
560 #endif
562 #ifndef DOS_NT
563 wait_for_termination (pid, &status, 0);
564 #endif
565 restore_signal_handlers (saved_handlers);
568 static void
569 save_signal_handlers (struct save_signal *saved_handlers)
571 while (saved_handlers->code)
573 struct sigaction action;
574 emacs_sigaction_init (&action, SIG_IGN);
575 sigaction (saved_handlers->code, &action, &saved_handlers->action);
576 saved_handlers++;
580 static void
581 restore_signal_handlers (struct save_signal *saved_handlers)
583 while (saved_handlers->code)
585 sigaction (saved_handlers->code, &saved_handlers->action, 0);
586 saved_handlers++;
590 #ifdef USABLE_SIGIO
591 static int old_fcntl_flags[FD_SETSIZE];
592 #endif
594 void
595 init_sigio (int fd)
597 #ifdef USABLE_SIGIO
598 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
599 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
600 interrupts_deferred = 0;
601 #endif
604 static void
605 reset_sigio (int fd)
607 #ifdef USABLE_SIGIO
608 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
609 #endif
612 void
613 request_sigio (void)
615 #ifdef USABLE_SIGIO
616 sigset_t unblocked;
618 if (noninteractive)
619 return;
621 sigemptyset (&unblocked);
622 # ifdef SIGWINCH
623 sigaddset (&unblocked, SIGWINCH);
624 # endif
625 sigaddset (&unblocked, SIGIO);
626 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
628 interrupts_deferred = 0;
629 #endif
632 void
633 unrequest_sigio (void)
635 #ifdef USABLE_SIGIO
636 sigset_t blocked;
638 if (noninteractive)
639 return;
641 sigemptyset (&blocked);
642 # ifdef SIGWINCH
643 sigaddset (&blocked, SIGWINCH);
644 # endif
645 sigaddset (&blocked, SIGIO);
646 pthread_sigmask (SIG_BLOCK, &blocked, 0);
647 interrupts_deferred = 1;
648 #endif
651 void
652 ignore_sigio (void)
654 #ifdef USABLE_SIGIO
655 signal (SIGIO, SIG_IGN);
656 #endif
660 /* Saving and restoring the process group of Emacs's terminal. */
662 /* The process group of which Emacs was a member when it initially
663 started.
665 If Emacs was in its own process group (i.e. inherited_pgroup ==
666 getpid ()), then we know we're running under a shell with job
667 control (Emacs would never be run as part of a pipeline).
668 Everything is fine.
670 If Emacs was not in its own process group, then we know we're
671 running under a shell (or a caller) that doesn't know how to
672 separate itself from Emacs (like sh). Emacs must be in its own
673 process group in order to receive SIGIO correctly. In this
674 situation, we put ourselves in our own pgroup, forcibly set the
675 tty's pgroup to our pgroup, and make sure to restore and reinstate
676 the tty's pgroup just like any other terminal setting. If
677 inherited_group was not the tty's pgroup, then we'll get a
678 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
679 it goes foreground in the future, which is what should happen. */
681 static pid_t inherited_pgroup;
683 void
684 init_foreground_group (void)
686 pid_t pgrp = getpgrp ();
687 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
690 /* Block and unblock SIGTTOU. */
692 void
693 block_tty_out_signal (void)
695 #ifdef SIGTTOU
696 sigset_t blocked;
697 sigemptyset (&blocked);
698 sigaddset (&blocked, SIGTTOU);
699 pthread_sigmask (SIG_BLOCK, &blocked, 0);
700 #endif
703 void
704 unblock_tty_out_signal (void)
706 #ifdef SIGTTOU
707 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
708 #endif
711 /* Safely set a controlling terminal FD's process group to PGID.
712 If we are not in the foreground already, POSIX requires tcsetpgrp
713 to deliver a SIGTTOU signal, which would stop us. This is an
714 annoyance, so temporarily ignore the signal.
716 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
717 skip all this unless SIGTTOU is defined. */
718 static void
719 tcsetpgrp_without_stopping (int fd, pid_t pgid)
721 #ifdef SIGTTOU
722 block_input ();
723 block_tty_out_signal ();
724 tcsetpgrp (fd, pgid);
725 unblock_tty_out_signal ();
726 unblock_input ();
727 #endif
730 /* Split off the foreground process group to Emacs alone. When we are
731 in the foreground, but not started in our own process group,
732 redirect the tty device handle FD to point to our own process
733 group. FD must be the file descriptor of the controlling tty. */
734 static void
735 narrow_foreground_group (int fd)
737 if (inherited_pgroup && setpgid (0, 0) == 0)
738 tcsetpgrp_without_stopping (fd, getpid ());
741 /* Set the tty to our original foreground group. */
742 static void
743 widen_foreground_group (int fd)
745 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
746 tcsetpgrp_without_stopping (fd, inherited_pgroup);
749 /* Getting and setting emacs_tty structures. */
751 /* Set *TC to the parameters associated with the terminal FD,
752 or clear it if the parameters are not available. */
753 static void
754 emacs_get_tty (int fd, struct emacs_tty *settings)
756 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
757 #ifndef DOS_NT
758 /* We have those nifty POSIX tcmumbleattr functions. */
759 memset (&settings->main, 0, sizeof (settings->main));
760 tcgetattr (fd, &settings->main);
761 #endif
765 /* Set the parameters of the tty on FD according to the contents of
766 *SETTINGS. If FLUSHP, discard input.
767 Return 0 if all went well, and -1 (setting errno) if anything failed. */
769 static int
770 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
772 /* Set the primary parameters - baud rate, character size, etcetera. */
773 #ifndef DOS_NT
774 int i;
775 /* We have those nifty POSIX tcmumbleattr functions.
776 William J. Smith <wjs@wiis.wang.com> writes:
777 "POSIX 1003.1 defines tcsetattr to return success if it was
778 able to perform any of the requested actions, even if some
779 of the requested actions could not be performed.
780 We must read settings back to ensure tty setup properly.
781 AIX requires this to keep tty from hanging occasionally." */
782 /* This make sure that we don't loop indefinitely in here. */
783 for (i = 0 ; i < 10 ; i++)
784 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
786 if (errno == EINTR)
787 continue;
788 else
789 return -1;
791 else
793 struct termios new;
795 memset (&new, 0, sizeof (new));
796 /* Get the current settings, and see if they're what we asked for. */
797 tcgetattr (fd, &new);
798 /* We cannot use memcmp on the whole structure here because under
799 * aix386 the termios structure has some reserved field that may
800 * not be filled in.
802 if ( new.c_iflag == settings->main.c_iflag
803 && new.c_oflag == settings->main.c_oflag
804 && new.c_cflag == settings->main.c_cflag
805 && new.c_lflag == settings->main.c_lflag
806 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
807 break;
808 else
809 continue;
811 #endif
813 /* We have survived the tempest. */
814 return 0;
819 #ifdef F_SETOWN
820 static int old_fcntl_owner[FD_SETSIZE];
821 #endif /* F_SETOWN */
823 /* This may also be defined in stdio,
824 but if so, this does no harm,
825 and using the same name avoids wasting the other one's space. */
827 #if defined (USG)
828 unsigned char _sobuf[BUFSIZ+8];
829 #else
830 char _sobuf[BUFSIZ];
831 #endif
833 /* Initialize the terminal mode on all tty devices that are currently
834 open. */
836 void
837 init_all_sys_modes (void)
839 struct tty_display_info *tty;
840 for (tty = tty_list; tty; tty = tty->next)
841 init_sys_modes (tty);
844 /* Initialize the terminal mode on the given tty device. */
846 void
847 init_sys_modes (struct tty_display_info *tty_out)
849 struct emacs_tty tty;
850 Lisp_Object terminal;
852 Vtty_erase_char = Qnil;
854 if (noninteractive)
855 return;
857 if (!tty_out->output)
858 return; /* The tty is suspended. */
860 narrow_foreground_group (fileno (tty_out->input));
862 if (! tty_out->old_tty)
863 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
865 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
867 tty = *tty_out->old_tty;
869 #if !defined (DOS_NT)
870 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
872 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
873 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
874 #ifdef INLCR /* I'm just being cautious,
875 since I can't check how widespread INLCR is--rms. */
876 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
877 #endif
878 #ifdef ISTRIP
879 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
880 #endif
881 tty.main.c_lflag &= ~ECHO; /* Disable echo */
882 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
883 #ifdef IEXTEN
884 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
885 #endif
886 tty.main.c_lflag |= ISIG; /* Enable signals */
887 if (tty_out->flow_control)
889 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
890 #ifdef IXANY
891 tty.main.c_iflag &= ~IXANY;
892 #endif /* IXANY */
894 else
895 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
896 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
897 on output */
898 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
899 #ifdef CS8
900 if (tty_out->meta_key)
902 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
903 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
905 #endif
907 XSETTERMINAL(terminal, tty_out->terminal);
908 if (!NILP (Fcontrolling_tty_p (terminal)))
910 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
911 /* Set up C-g for both SIGQUIT and SIGINT.
912 We don't know which we will get, but we handle both alike
913 so which one it really gives us does not matter. */
914 tty.main.c_cc[VQUIT] = quit_char;
916 else
918 /* We normally don't get interrupt or quit signals from tty
919 devices other than our controlling terminal; therefore,
920 we must handle C-g as normal input. Unfortunately, this
921 means that the interrupt and quit feature must be
922 disabled on secondary ttys, or we would not even see the
923 keypress.
925 Note that even though emacsclient could have special code
926 to pass SIGINT to Emacs, we should _not_ enable
927 interrupt/quit keys for emacsclient frames. This means
928 that we can't break out of loops in C code from a
929 secondary tty frame, but we can always decide what
930 display the C-g came from, which is more important from a
931 usability point of view. (Consider the case when two
932 people work together using the same Emacs instance.) */
933 tty.main.c_cc[VINTR] = CDISABLE;
934 tty.main.c_cc[VQUIT] = CDISABLE;
936 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
937 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
938 #ifdef VSWTCH
939 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
940 of C-z */
941 #endif /* VSWTCH */
943 #ifdef VSUSP
944 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
945 #endif /* VSUSP */
946 #ifdef V_DSUSP
947 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
948 #endif /* V_DSUSP */
949 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
950 tty.main.c_cc[VDSUSP] = CDISABLE;
951 #endif /* VDSUSP */
952 #ifdef VLNEXT
953 tty.main.c_cc[VLNEXT] = CDISABLE;
954 #endif /* VLNEXT */
955 #ifdef VREPRINT
956 tty.main.c_cc[VREPRINT] = CDISABLE;
957 #endif /* VREPRINT */
958 #ifdef VWERASE
959 tty.main.c_cc[VWERASE] = CDISABLE;
960 #endif /* VWERASE */
961 #ifdef VDISCARD
962 tty.main.c_cc[VDISCARD] = CDISABLE;
963 #endif /* VDISCARD */
965 if (tty_out->flow_control)
967 #ifdef VSTART
968 tty.main.c_cc[VSTART] = '\021';
969 #endif /* VSTART */
970 #ifdef VSTOP
971 tty.main.c_cc[VSTOP] = '\023';
972 #endif /* VSTOP */
974 else
976 #ifdef VSTART
977 tty.main.c_cc[VSTART] = CDISABLE;
978 #endif /* VSTART */
979 #ifdef VSTOP
980 tty.main.c_cc[VSTOP] = CDISABLE;
981 #endif /* VSTOP */
984 #ifdef AIX
985 tty.main.c_cc[VSTRT] = CDISABLE;
986 tty.main.c_cc[VSTOP] = CDISABLE;
987 tty.main.c_cc[VSUSP] = CDISABLE;
988 tty.main.c_cc[VDSUSP] = CDISABLE;
989 if (tty_out->flow_control)
991 #ifdef VSTART
992 tty.main.c_cc[VSTART] = '\021';
993 #endif /* VSTART */
994 #ifdef VSTOP
995 tty.main.c_cc[VSTOP] = '\023';
996 #endif /* VSTOP */
998 /* Also, PTY overloads NUL and BREAK.
999 don't ignore break, but don't signal either, so it looks like NUL.
1000 This really serves a purpose only if running in an XTERM window
1001 or via TELNET or the like, but does no harm elsewhere. */
1002 tty.main.c_iflag &= ~IGNBRK;
1003 tty.main.c_iflag &= ~BRKINT;
1004 #endif
1005 #endif /* not DOS_NT */
1007 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1008 if (!tty_out->term_initted)
1009 internal_terminal_init ();
1010 dos_ttraw (tty_out);
1011 #endif
1013 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1015 /* This code added to insure that, if flow-control is not to be used,
1016 we have an unlocked terminal at the start. */
1018 #ifdef TCXONC
1019 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1020 #endif
1021 #ifdef TIOCSTART
1022 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1023 #endif
1025 #if !defined (DOS_NT)
1026 #ifdef TCOON
1027 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1028 #endif
1029 #endif
1031 #ifdef F_GETOWN
1032 if (interrupt_input)
1034 old_fcntl_owner[fileno (tty_out->input)] =
1035 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1036 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1037 init_sigio (fileno (tty_out->input));
1038 #ifdef HAVE_GPM
1039 if (gpm_tty == tty_out)
1041 /* Arrange for mouse events to give us SIGIO signals. */
1042 fcntl (gpm_fd, F_SETOWN, getpid ());
1043 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1044 init_sigio (gpm_fd);
1046 #endif /* HAVE_GPM */
1048 #endif /* F_GETOWN */
1050 #ifdef _IOFBF
1051 /* This symbol is defined on recent USG systems.
1052 Someone says without this call USG won't really buffer the file
1053 even with a call to setbuf. */
1054 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1055 #else
1056 setbuf (tty_out->output, (char *) _sobuf);
1057 #endif
1059 if (tty_out->terminal->set_terminal_modes_hook)
1060 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1062 if (!tty_out->term_initted)
1064 Lisp_Object tail, frame;
1065 FOR_EACH_FRAME (tail, frame)
1067 /* XXX This needs to be revised. */
1068 if (FRAME_TERMCAP_P (XFRAME (frame))
1069 && FRAME_TTY (XFRAME (frame)) == tty_out)
1070 init_frame_faces (XFRAME (frame));
1074 if (tty_out->term_initted && no_redraw_on_reenter)
1076 /* We used to call "direct_output_forward_char(0)" here,
1077 but it's not clear why, since it may not do anything anyway. */
1079 else
1081 Lisp_Object tail, frame;
1082 frame_garbaged = 1;
1083 FOR_EACH_FRAME (tail, frame)
1085 if ((FRAME_TERMCAP_P (XFRAME (frame))
1086 || FRAME_MSDOS_P (XFRAME (frame)))
1087 && FRAME_TTY (XFRAME (frame)) == tty_out)
1088 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1092 tty_out->term_initted = 1;
1095 /* Return true if safe to use tabs in output.
1096 At the time this is called, init_sys_modes has not been done yet. */
1098 bool
1099 tabs_safe_p (int fd)
1101 struct emacs_tty etty;
1103 emacs_get_tty (fd, &etty);
1104 #ifndef DOS_NT
1105 #ifdef TABDLY
1106 return ((etty.main.c_oflag & TABDLY) != TAB3);
1107 #else /* not TABDLY */
1108 return 1;
1109 #endif /* not TABDLY */
1110 #else /* DOS_NT */
1111 return 0;
1112 #endif /* DOS_NT */
1115 /* Get terminal size from system.
1116 Store number of lines into *HEIGHTP and width into *WIDTHP.
1117 We store 0 if there's no valid information. */
1119 void
1120 get_tty_size (int fd, int *widthp, int *heightp)
1122 #if defined TIOCGWINSZ
1124 /* BSD-style. */
1125 struct winsize size;
1127 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1128 *widthp = *heightp = 0;
1129 else
1131 *widthp = size.ws_col;
1132 *heightp = size.ws_row;
1135 #elif defined TIOCGSIZE
1137 /* SunOS - style. */
1138 struct ttysize size;
1140 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1141 *widthp = *heightp = 0;
1142 else
1144 *widthp = size.ts_cols;
1145 *heightp = size.ts_lines;
1148 #elif defined WINDOWSNT
1150 CONSOLE_SCREEN_BUFFER_INFO info;
1151 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1153 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1154 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1156 else
1157 *widthp = *heightp = 0;
1159 #elif defined MSDOS
1161 *widthp = ScreenCols ();
1162 *heightp = ScreenRows ();
1164 #else /* system doesn't know size */
1166 *widthp = 0;
1167 *heightp = 0;
1169 #endif
1172 /* Set the logical window size associated with descriptor FD
1173 to HEIGHT and WIDTH. This is used mainly with ptys.
1174 Return a negative value on failure. */
1177 set_window_size (int fd, int height, int width)
1179 #ifdef TIOCSWINSZ
1181 /* BSD-style. */
1182 struct winsize size;
1183 size.ws_row = height;
1184 size.ws_col = width;
1186 return ioctl (fd, TIOCSWINSZ, &size);
1188 #else
1189 #ifdef TIOCSSIZE
1191 /* SunOS - style. */
1192 struct ttysize size;
1193 size.ts_lines = height;
1194 size.ts_cols = width;
1196 return ioctl (fd, TIOCGSIZE, &size);
1197 #else
1198 return -1;
1199 #endif /* not SunOS-style */
1200 #endif /* not BSD-style */
1205 /* Prepare all terminal devices for exiting Emacs. */
1207 void
1208 reset_all_sys_modes (void)
1210 struct tty_display_info *tty;
1211 for (tty = tty_list; tty; tty = tty->next)
1212 reset_sys_modes (tty);
1215 /* Prepare the terminal for closing it; move the cursor to the
1216 bottom of the frame, turn off interrupt-driven I/O, etc. */
1218 void
1219 reset_sys_modes (struct tty_display_info *tty_out)
1221 if (noninteractive)
1223 fflush (stdout);
1224 return;
1226 if (!tty_out->term_initted)
1227 return;
1229 if (!tty_out->output)
1230 return; /* The tty is suspended. */
1232 /* Go to and clear the last line of the terminal. */
1234 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1236 /* Code adapted from tty_clear_end_of_line. */
1237 if (tty_out->TS_clr_line)
1239 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1241 else
1242 { /* have to do it the hard way */
1243 int i;
1244 tty_turn_off_insert (tty_out);
1246 for (i = curX (tty_out); i < FrameCols (tty_out) - 1; i++)
1248 fputc (' ', tty_out->output);
1252 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1253 fflush (tty_out->output);
1255 if (tty_out->terminal->reset_terminal_modes_hook)
1256 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1258 /* Avoid possible loss of output when changing terminal modes. */
1259 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1260 continue;
1262 #ifndef DOS_NT
1263 #ifdef F_SETOWN
1264 if (interrupt_input)
1266 reset_sigio (fileno (tty_out->input));
1267 fcntl (fileno (tty_out->input), F_SETOWN,
1268 old_fcntl_owner[fileno (tty_out->input)]);
1270 #endif /* F_SETOWN */
1271 fcntl (fileno (tty_out->input), F_SETFL,
1272 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1273 #endif
1275 if (tty_out->old_tty)
1276 while (emacs_set_tty (fileno (tty_out->input),
1277 tty_out->old_tty, 0) < 0 && errno == EINTR)
1280 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1281 dos_ttcooked ();
1282 #endif
1284 widen_foreground_group (fileno (tty_out->input));
1287 #ifdef HAVE_PTYS
1289 /* Set up the proper status flags for use of a pty. */
1291 void
1292 setup_pty (int fd)
1294 /* I'm told that TOICREMOTE does not mean control chars
1295 "can't be sent" but rather that they don't have
1296 input-editing or signaling effects.
1297 That should be good, because we have other ways
1298 to do those things in Emacs.
1299 However, telnet mode seems not to work on 4.2.
1300 So TIOCREMOTE is turned off now. */
1302 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1303 will hang. In particular, the "timeout" feature (which
1304 causes a read to return if there is no data available)
1305 does this. Also it is known that telnet mode will hang
1306 in such a way that Emacs must be stopped (perhaps this
1307 is the same problem).
1309 If TIOCREMOTE is turned off, then there is a bug in
1310 hp-ux which sometimes loses data. Apparently the
1311 code which blocks the master process when the internal
1312 buffer fills up does not work. Other than this,
1313 though, everything else seems to work fine.
1315 Since the latter lossage is more benign, we may as well
1316 lose that way. -- cph */
1317 #ifdef FIONBIO
1318 #if defined (UNIX98_PTYS)
1320 int on = 1;
1321 ioctl (fd, FIONBIO, &on);
1323 #endif
1324 #endif
1326 #endif /* HAVE_PTYS */
1328 #ifdef HAVE_SOCKETS
1329 #include <sys/socket.h>
1330 #include <netdb.h>
1331 #endif /* HAVE_SOCKETS */
1333 #ifdef TRY_AGAIN
1334 #ifndef HAVE_H_ERRNO
1335 extern int h_errno;
1336 #endif
1337 #endif /* TRY_AGAIN */
1339 void
1340 init_system_name (void)
1342 #ifndef HAVE_GETHOSTNAME
1343 struct utsname uts;
1344 uname (&uts);
1345 Vsystem_name = build_string (uts.nodename);
1346 #else /* HAVE_GETHOSTNAME */
1347 char *hostname_alloc = NULL;
1348 char hostname_buf[256];
1349 ptrdiff_t hostname_size = sizeof hostname_buf;
1350 char *hostname = hostname_buf;
1352 /* Try to get the host name; if the buffer is too short, try
1353 again. Apparently, the only indication gethostname gives of
1354 whether the buffer was large enough is the presence or absence
1355 of a '\0' in the string. Eech. */
1356 for (;;)
1358 gethostname (hostname, hostname_size - 1);
1359 hostname[hostname_size - 1] = '\0';
1361 /* Was the buffer large enough for the '\0'? */
1362 if (strlen (hostname) < hostname_size - 1)
1363 break;
1365 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1366 min (PTRDIFF_MAX, SIZE_MAX), 1);
1368 #ifdef HAVE_SOCKETS
1369 /* Turn the hostname into the official, fully-qualified hostname.
1370 Don't do this if we're going to dump; this can confuse system
1371 libraries on some machines and make the dumped emacs core dump. */
1372 #ifndef CANNOT_DUMP
1373 if (initialized)
1374 #endif /* not CANNOT_DUMP */
1375 if (! strchr (hostname, '.'))
1377 int count;
1378 #ifdef HAVE_GETADDRINFO
1379 struct addrinfo *res;
1380 struct addrinfo hints;
1381 int ret;
1383 memset (&hints, 0, sizeof (hints));
1384 hints.ai_socktype = SOCK_STREAM;
1385 hints.ai_flags = AI_CANONNAME;
1387 for (count = 0;; count++)
1389 if ((ret = getaddrinfo (hostname, NULL, &hints, &res)) == 0
1390 || ret != EAI_AGAIN)
1391 break;
1393 if (count >= 5)
1394 break;
1395 Fsleep_for (make_number (1), Qnil);
1398 if (ret == 0)
1400 struct addrinfo *it = res;
1401 while (it)
1403 char *fqdn = it->ai_canonname;
1404 if (fqdn && strchr (fqdn, '.')
1405 && strcmp (fqdn, "localhost.localdomain") != 0)
1406 break;
1407 it = it->ai_next;
1409 if (it)
1411 ptrdiff_t len = strlen (it->ai_canonname);
1412 if (hostname_size <= len)
1414 hostname_size = len + 1;
1415 hostname = hostname_alloc = xrealloc (hostname_alloc,
1416 hostname_size);
1418 strcpy (hostname, it->ai_canonname);
1420 freeaddrinfo (res);
1422 #else /* !HAVE_GETADDRINFO */
1423 struct hostent *hp;
1424 for (count = 0;; count++)
1427 #ifdef TRY_AGAIN
1428 h_errno = 0;
1429 #endif
1430 hp = gethostbyname (hostname);
1431 #ifdef TRY_AGAIN
1432 if (! (hp == 0 && h_errno == TRY_AGAIN))
1433 #endif
1435 break;
1437 if (count >= 5)
1438 break;
1439 Fsleep_for (make_number (1), Qnil);
1442 if (hp)
1444 char *fqdn = (char *) hp->h_name;
1446 if (!strchr (fqdn, '.'))
1448 /* We still don't have a fully qualified domain name.
1449 Try to find one in the list of alternate names */
1450 char **alias = hp->h_aliases;
1451 while (*alias
1452 && (!strchr (*alias, '.')
1453 || !strcmp (*alias, "localhost.localdomain")))
1454 alias++;
1455 if (*alias)
1456 fqdn = *alias;
1458 hostname = fqdn;
1460 #endif /* !HAVE_GETADDRINFO */
1462 #endif /* HAVE_SOCKETS */
1463 Vsystem_name = build_string (hostname);
1464 xfree (hostname_alloc);
1465 #endif /* HAVE_GETHOSTNAME */
1467 char *p;
1468 for (p = SSDATA (Vsystem_name); *p; p++)
1469 if (*p == ' ' || *p == '\t')
1470 *p = '-';
1474 sigset_t empty_mask;
1476 static struct sigaction process_fatal_action;
1478 static int
1479 emacs_sigaction_flags (void)
1481 #ifdef SA_RESTART
1482 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1483 'select') to reset their timeout on some platforms (e.g.,
1484 HP-UX 11), which is not what we want. Also, when Emacs is
1485 interactive, we don't want SA_RESTART because we need to poll
1486 for pending input so we need long-running syscalls to be interrupted
1487 after a signal that sets pending_signals.
1489 Non-interactive keyboard input goes through stdio, where we
1490 always want restartable system calls. */
1491 if (noninteractive)
1492 return SA_RESTART;
1493 #endif
1494 return 0;
1497 /* Store into *ACTION a signal action suitable for Emacs, with handler
1498 HANDLER. */
1499 void
1500 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1502 sigemptyset (&action->sa_mask);
1504 /* When handling a signal, block nonfatal system signals that are caught
1505 by Emacs. This makes race conditions less likely. */
1506 sigaddset (&action->sa_mask, SIGALRM);
1507 sigaddset (&action->sa_mask, SIGCHLD);
1508 #ifdef SIGDANGER
1509 sigaddset (&action->sa_mask, SIGDANGER);
1510 #endif
1511 #ifdef PROFILER_CPU_SUPPORT
1512 sigaddset (&action->sa_mask, SIGPROF);
1513 #endif
1514 #ifdef SIGWINCH
1515 sigaddset (&action->sa_mask, SIGWINCH);
1516 #endif
1517 if (! noninteractive)
1519 sigaddset (&action->sa_mask, SIGINT);
1520 sigaddset (&action->sa_mask, SIGQUIT);
1521 #ifdef USABLE_SIGIO
1522 sigaddset (&action->sa_mask, SIGIO);
1523 #endif
1526 if (! IEEE_FLOATING_POINT)
1527 sigaddset (&action->sa_mask, SIGFPE);
1529 action->sa_handler = handler;
1530 action->sa_flags = emacs_sigaction_flags ();
1533 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1534 static pthread_t main_thread;
1535 #endif
1537 /* SIG has arrived at the current process. Deliver it to the main
1538 thread, which should handle it with HANDLER.
1540 If we are on the main thread, handle the signal SIG with HANDLER.
1541 Otherwise, redirect the signal to the main thread, blocking it from
1542 this thread. POSIX says any thread can receive a signal that is
1543 associated with a process, process group, or asynchronous event.
1544 On GNU/Linux that is not true, but for other systems (FreeBSD at
1545 least) it is. */
1546 void
1547 deliver_process_signal (int sig, signal_handler_t handler)
1549 /* Preserve errno, to avoid race conditions with signal handlers that
1550 might change errno. Races can occur even in single-threaded hosts. */
1551 int old_errno = errno;
1553 bool on_main_thread = true;
1554 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1555 if (! pthread_equal (pthread_self (), main_thread))
1557 sigset_t blocked;
1558 sigemptyset (&blocked);
1559 sigaddset (&blocked, sig);
1560 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1561 pthread_kill (main_thread, sig);
1562 on_main_thread = false;
1564 #endif
1565 if (on_main_thread)
1566 handler (sig);
1568 errno = old_errno;
1571 /* Static location to save a fatal backtrace in a thread.
1572 FIXME: If two subsidiary threads fail simultaneously, the resulting
1573 backtrace may be garbage. */
1574 enum { BACKTRACE_LIMIT_MAX = 500 };
1575 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1576 static int thread_backtrace_npointers;
1578 /* SIG has arrived at the current thread.
1579 If we are on the main thread, handle the signal SIG with HANDLER.
1580 Otherwise, this is a fatal error in the handling thread. */
1581 static void
1582 deliver_thread_signal (int sig, signal_handler_t handler)
1584 int old_errno = errno;
1586 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1587 if (! pthread_equal (pthread_self (), main_thread))
1589 thread_backtrace_npointers
1590 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1591 sigaction (sig, &process_fatal_action, 0);
1592 pthread_kill (main_thread, sig);
1594 /* Avoid further damage while the main thread is exiting. */
1595 while (1)
1596 sigsuspend (&empty_mask);
1598 #endif
1600 handler (sig);
1601 errno = old_errno;
1604 #if !HAVE_DECL_SYS_SIGLIST
1605 # undef sys_siglist
1606 # ifdef _sys_siglist
1607 # define sys_siglist _sys_siglist
1608 # elif HAVE_DECL___SYS_SIGLIST
1609 # define sys_siglist __sys_siglist
1610 # else
1611 # define sys_siglist my_sys_siglist
1612 static char const *sys_siglist[NSIG];
1613 # endif
1614 #endif
1616 #ifdef _sys_nsig
1617 # define sys_siglist_entries _sys_nsig
1618 #else
1619 # define sys_siglist_entries NSIG
1620 #endif
1622 /* Handle bus errors, invalid instruction, etc. */
1623 static void
1624 handle_fatal_signal (int sig)
1626 terminate_due_to_signal (sig, 40);
1629 static void
1630 deliver_fatal_signal (int sig)
1632 deliver_process_signal (sig, handle_fatal_signal);
1635 static void
1636 deliver_fatal_thread_signal (int sig)
1638 deliver_thread_signal (sig, handle_fatal_signal);
1641 static _Noreturn void
1642 handle_arith_signal (int sig)
1644 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1645 xsignal0 (Qarith_error);
1648 static void
1649 deliver_arith_signal (int sig)
1651 deliver_thread_signal (sig, handle_arith_signal);
1654 #ifdef SIGDANGER
1656 /* Handler for SIGDANGER. */
1657 static void
1658 handle_danger_signal (int sig)
1660 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1662 /* It might be unsafe to call do_auto_save now. */
1663 force_auto_save_soon ();
1666 static void
1667 deliver_danger_signal (int sig)
1669 deliver_process_signal (sig, handle_danger_signal);
1671 #endif
1673 /* Treat SIG as a terminating signal, unless it is already ignored and
1674 we are in --batch mode. Among other things, this makes nohup work. */
1675 static void
1676 maybe_fatal_sig (int sig)
1678 bool catch_sig = !noninteractive;
1679 if (!catch_sig)
1681 struct sigaction old_action;
1682 sigaction (sig, 0, &old_action);
1683 catch_sig = old_action.sa_handler != SIG_IGN;
1685 if (catch_sig)
1686 sigaction (sig, &process_fatal_action, 0);
1689 void
1690 init_signals (bool dumping)
1692 struct sigaction thread_fatal_action;
1693 struct sigaction action;
1695 sigemptyset (&empty_mask);
1697 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1698 main_thread = pthread_self ();
1699 #endif
1701 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1702 if (! initialized)
1704 sys_siglist[SIGABRT] = "Aborted";
1705 # ifdef SIGAIO
1706 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1707 # endif
1708 sys_siglist[SIGALRM] = "Alarm clock";
1709 # ifdef SIGBUS
1710 sys_siglist[SIGBUS] = "Bus error";
1711 # endif
1712 sys_siglist[SIGCHLD] = "Child status changed";
1713 # ifdef SIGCONT
1714 sys_siglist[SIGCONT] = "Continued";
1715 # endif
1716 # ifdef SIGDANGER
1717 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1718 # endif
1719 # ifdef SIGDGNOTIFY
1720 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1721 # endif
1722 # ifdef SIGEMT
1723 sys_siglist[SIGEMT] = "Emulation trap";
1724 # endif
1725 sys_siglist[SIGFPE] = "Arithmetic exception";
1726 # ifdef SIGFREEZE
1727 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1728 # endif
1729 # ifdef SIGGRANT
1730 sys_siglist[SIGGRANT] = "Monitor mode granted";
1731 # endif
1732 sys_siglist[SIGHUP] = "Hangup";
1733 sys_siglist[SIGILL] = "Illegal instruction";
1734 sys_siglist[SIGINT] = "Interrupt";
1735 # ifdef SIGIO
1736 sys_siglist[SIGIO] = "I/O possible";
1737 # endif
1738 # ifdef SIGIOINT
1739 sys_siglist[SIGIOINT] = "I/O intervention required";
1740 # endif
1741 # ifdef SIGIOT
1742 sys_siglist[SIGIOT] = "IOT trap";
1743 # endif
1744 sys_siglist[SIGKILL] = "Killed";
1745 # ifdef SIGLOST
1746 sys_siglist[SIGLOST] = "Resource lost";
1747 # endif
1748 # ifdef SIGLWP
1749 sys_siglist[SIGLWP] = "SIGLWP";
1750 # endif
1751 # ifdef SIGMSG
1752 sys_siglist[SIGMSG] = "Monitor mode data available";
1753 # endif
1754 # ifdef SIGPHONE
1755 sys_siglist[SIGWIND] = "SIGPHONE";
1756 # endif
1757 sys_siglist[SIGPIPE] = "Broken pipe";
1758 # ifdef SIGPOLL
1759 sys_siglist[SIGPOLL] = "Pollable event occurred";
1760 # endif
1761 # ifdef SIGPROF
1762 sys_siglist[SIGPROF] = "Profiling timer expired";
1763 # endif
1764 # ifdef SIGPTY
1765 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1766 # endif
1767 # ifdef SIGPWR
1768 sys_siglist[SIGPWR] = "Power-fail restart";
1769 # endif
1770 sys_siglist[SIGQUIT] = "Quit";
1771 # ifdef SIGRETRACT
1772 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1773 # endif
1774 # ifdef SIGSAK
1775 sys_siglist[SIGSAK] = "Secure attention";
1776 # endif
1777 sys_siglist[SIGSEGV] = "Segmentation violation";
1778 # ifdef SIGSOUND
1779 sys_siglist[SIGSOUND] = "Sound completed";
1780 # endif
1781 # ifdef SIGSTOP
1782 sys_siglist[SIGSTOP] = "Stopped (signal)";
1783 # endif
1784 # ifdef SIGSTP
1785 sys_siglist[SIGSTP] = "Stopped (user)";
1786 # endif
1787 # ifdef SIGSYS
1788 sys_siglist[SIGSYS] = "Bad argument to system call";
1789 # endif
1790 sys_siglist[SIGTERM] = "Terminated";
1791 # ifdef SIGTHAW
1792 sys_siglist[SIGTHAW] = "SIGTHAW";
1793 # endif
1794 # ifdef SIGTRAP
1795 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1796 # endif
1797 # ifdef SIGTSTP
1798 sys_siglist[SIGTSTP] = "Stopped (user)";
1799 # endif
1800 # ifdef SIGTTIN
1801 sys_siglist[SIGTTIN] = "Stopped (tty input)";
1802 # endif
1803 # ifdef SIGTTOU
1804 sys_siglist[SIGTTOU] = "Stopped (tty output)";
1805 # endif
1806 # ifdef SIGURG
1807 sys_siglist[SIGURG] = "Urgent I/O condition";
1808 # endif
1809 # ifdef SIGUSR1
1810 sys_siglist[SIGUSR1] = "User defined signal 1";
1811 # endif
1812 # ifdef SIGUSR2
1813 sys_siglist[SIGUSR2] = "User defined signal 2";
1814 # endif
1815 # ifdef SIGVTALRM
1816 sys_siglist[SIGVTALRM] = "Virtual timer expired";
1817 # endif
1818 # ifdef SIGWAITING
1819 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
1820 # endif
1821 # ifdef SIGWINCH
1822 sys_siglist[SIGWINCH] = "Window size changed";
1823 # endif
1824 # ifdef SIGWIND
1825 sys_siglist[SIGWIND] = "SIGWIND";
1826 # endif
1827 # ifdef SIGXCPU
1828 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
1829 # endif
1830 # ifdef SIGXFSZ
1831 sys_siglist[SIGXFSZ] = "File size limit exceeded";
1832 # endif
1834 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
1836 /* Don't alter signal handlers if dumping. On some machines,
1837 changing signal handlers sets static data that would make signals
1838 fail to work right when the dumped Emacs is run. */
1839 if (dumping)
1840 return;
1842 sigfillset (&process_fatal_action.sa_mask);
1843 process_fatal_action.sa_handler = deliver_fatal_signal;
1844 process_fatal_action.sa_flags = emacs_sigaction_flags ();
1846 sigfillset (&thread_fatal_action.sa_mask);
1847 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
1848 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
1850 /* SIGINT may need special treatment on MS-Windows. See
1851 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
1852 Please update the doc of kill-emacs, kill-emacs-hook, and
1853 NEWS if you change this. */
1855 maybe_fatal_sig (SIGHUP);
1856 maybe_fatal_sig (SIGINT);
1857 maybe_fatal_sig (SIGTERM);
1859 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
1860 However, in batch mode leave SIGPIPE alone, as that causes Emacs
1861 to behave more like typical batch applications do. */
1862 if (! noninteractive)
1863 signal (SIGPIPE, SIG_IGN);
1865 sigaction (SIGQUIT, &process_fatal_action, 0);
1866 sigaction (SIGILL, &thread_fatal_action, 0);
1867 sigaction (SIGTRAP, &thread_fatal_action, 0);
1869 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
1870 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
1871 interpreter's floating point operations, so treat SIGFPE as an
1872 arith-error if it arises in the main thread. */
1873 if (IEEE_FLOATING_POINT)
1874 sigaction (SIGFPE, &thread_fatal_action, 0);
1875 else
1877 emacs_sigaction_init (&action, deliver_arith_signal);
1878 sigaction (SIGFPE, &action, 0);
1881 #ifdef SIGUSR1
1882 add_user_signal (SIGUSR1, "sigusr1");
1883 #endif
1884 #ifdef SIGUSR2
1885 add_user_signal (SIGUSR2, "sigusr2");
1886 #endif
1887 sigaction (SIGABRT, &thread_fatal_action, 0);
1888 #ifdef SIGPRE
1889 sigaction (SIGPRE, &thread_fatal_action, 0);
1890 #endif
1891 #ifdef SIGORE
1892 sigaction (SIGORE, &thread_fatal_action, 0);
1893 #endif
1894 #ifdef SIGUME
1895 sigaction (SIGUME, &thread_fatal_action, 0);
1896 #endif
1897 #ifdef SIGDLK
1898 sigaction (SIGDLK, &process_fatal_action, 0);
1899 #endif
1900 #ifdef SIGCPULIM
1901 sigaction (SIGCPULIM, &process_fatal_action, 0);
1902 #endif
1903 #ifdef SIGIOT
1904 sigaction (SIGIOT, &thread_fatal_action, 0);
1905 #endif
1906 #ifdef SIGEMT
1907 sigaction (SIGEMT, &thread_fatal_action, 0);
1908 #endif
1909 #ifdef SIGBUS
1910 sigaction (SIGBUS, &thread_fatal_action, 0);
1911 #endif
1912 sigaction (SIGSEGV, &thread_fatal_action, 0);
1913 #ifdef SIGSYS
1914 sigaction (SIGSYS, &thread_fatal_action, 0);
1915 #endif
1916 sigaction (SIGTERM, &process_fatal_action, 0);
1917 #ifdef SIGPROF
1918 signal (SIGPROF, SIG_IGN);
1919 #endif
1920 #ifdef SIGVTALRM
1921 sigaction (SIGVTALRM, &process_fatal_action, 0);
1922 #endif
1923 #ifdef SIGXCPU
1924 sigaction (SIGXCPU, &process_fatal_action, 0);
1925 #endif
1926 #ifdef SIGXFSZ
1927 sigaction (SIGXFSZ, &process_fatal_action, 0);
1928 #endif
1930 #ifdef SIGDANGER
1931 /* This just means available memory is getting low. */
1932 emacs_sigaction_init (&action, deliver_danger_signal);
1933 sigaction (SIGDANGER, &action, 0);
1934 #endif
1936 /* AIX-specific signals. */
1937 #ifdef SIGGRANT
1938 sigaction (SIGGRANT, &process_fatal_action, 0);
1939 #endif
1940 #ifdef SIGMIGRATE
1941 sigaction (SIGMIGRATE, &process_fatal_action, 0);
1942 #endif
1943 #ifdef SIGMSG
1944 sigaction (SIGMSG, &process_fatal_action, 0);
1945 #endif
1946 #ifdef SIGRETRACT
1947 sigaction (SIGRETRACT, &process_fatal_action, 0);
1948 #endif
1949 #ifdef SIGSAK
1950 sigaction (SIGSAK, &process_fatal_action, 0);
1951 #endif
1952 #ifdef SIGSOUND
1953 sigaction (SIGSOUND, &process_fatal_action, 0);
1954 #endif
1955 #ifdef SIGTALRM
1956 sigaction (SIGTALRM, &thread_fatal_action, 0);
1957 #endif
1960 #ifndef HAVE_RANDOM
1961 #ifdef random
1962 #define HAVE_RANDOM
1963 #endif
1964 #endif
1966 /* Figure out how many bits the system's random number generator uses.
1967 `random' and `lrand48' are assumed to return 31 usable bits.
1968 BSD `rand' returns a 31 bit value but the low order bits are unusable;
1969 so we'll shift it and treat it like the 15-bit USG `rand'. */
1971 #ifndef RAND_BITS
1972 # ifdef HAVE_RANDOM
1973 # define RAND_BITS 31
1974 # else /* !HAVE_RANDOM */
1975 # ifdef HAVE_LRAND48
1976 # define RAND_BITS 31
1977 # define random lrand48
1978 # else /* !HAVE_LRAND48 */
1979 # define RAND_BITS 15
1980 # if RAND_MAX == 32767
1981 # define random rand
1982 # else /* RAND_MAX != 32767 */
1983 # if RAND_MAX == 2147483647
1984 # define random() (rand () >> 16)
1985 # else /* RAND_MAX != 2147483647 */
1986 # ifdef USG
1987 # define random rand
1988 # else
1989 # define random() (rand () >> 16)
1990 # endif /* !USG */
1991 # endif /* RAND_MAX != 2147483647 */
1992 # endif /* RAND_MAX != 32767 */
1993 # endif /* !HAVE_LRAND48 */
1994 # endif /* !HAVE_RANDOM */
1995 #endif /* !RAND_BITS */
1997 void
1998 seed_random (void *seed, ptrdiff_t seed_size)
2000 #if defined HAVE_RANDOM || ! defined HAVE_LRAND48
2001 unsigned int arg = 0;
2002 #else
2003 long int arg = 0;
2004 #endif
2005 unsigned char *argp = (unsigned char *) &arg;
2006 unsigned char *seedp = seed;
2007 ptrdiff_t i;
2008 for (i = 0; i < seed_size; i++)
2009 argp[i % sizeof arg] ^= seedp[i];
2010 #ifdef HAVE_RANDOM
2011 srandom (arg);
2012 #else
2013 # ifdef HAVE_LRAND48
2014 srand48 (arg);
2015 # else
2016 srand (arg);
2017 # endif
2018 #endif
2021 void
2022 init_random (void)
2024 struct timespec t = current_timespec ();
2025 uintmax_t v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2026 seed_random (&v, sizeof v);
2030 * Return a nonnegative random integer out of whatever we've got.
2031 * It contains enough bits to make a random (signed) Emacs fixnum.
2032 * This suffices even for a 64-bit architecture with a 15-bit rand.
2034 EMACS_INT
2035 get_random (void)
2037 EMACS_UINT val = 0;
2038 int i;
2039 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2040 val = (random () ^ (val << RAND_BITS)
2041 ^ (val >> (BITS_PER_EMACS_INT - RAND_BITS)));
2042 val ^= val >> (BITS_PER_EMACS_INT - FIXNUM_BITS);
2043 return val & INTMASK;
2046 #ifndef HAVE_SNPRINTF
2047 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2049 snprintf (char *buf, size_t bufsize, char const *format, ...)
2051 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2052 ptrdiff_t nbytes = size - 1;
2053 va_list ap;
2055 if (size)
2057 va_start (ap, format);
2058 nbytes = doprnt (buf, size, format, 0, ap);
2059 va_end (ap);
2062 if (nbytes == size - 1)
2064 /* Calculate the length of the string that would have been created
2065 had the buffer been large enough. */
2066 char stackbuf[4000];
2067 char *b = stackbuf;
2068 ptrdiff_t bsize = sizeof stackbuf;
2069 va_start (ap, format);
2070 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2071 va_end (ap);
2072 if (b != stackbuf)
2073 xfree (b);
2076 if (INT_MAX < nbytes)
2078 #ifdef EOVERFLOW
2079 errno = EOVERFLOW;
2080 #else
2081 errno = EDOM;
2082 #endif
2083 return -1;
2085 return nbytes;
2087 #endif
2089 /* If a backtrace is available, output the top lines of it to stderr.
2090 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2091 This function may be called from a signal handler, so it should
2092 not invoke async-unsafe functions like malloc. */
2093 void
2094 emacs_backtrace (int backtrace_limit)
2096 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2097 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2098 void *buffer;
2099 int npointers;
2101 if (thread_backtrace_npointers)
2103 buffer = thread_backtrace_buffer;
2104 npointers = thread_backtrace_npointers;
2106 else
2108 buffer = main_backtrace_buffer;
2109 npointers = backtrace (buffer, bounded_limit + 1);
2112 if (npointers)
2114 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2115 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2116 if (bounded_limit < npointers)
2117 emacs_write (STDERR_FILENO, "...\n", 4);
2121 #ifndef HAVE_NTGUI
2122 void
2123 emacs_abort (void)
2125 terminate_due_to_signal (SIGABRT, 40);
2127 #endif
2129 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2130 Arrange for subprograms to not inherit the file descriptor.
2131 Prefer a method that is multithread-safe, if available.
2132 Do not fail merely because the open was interrupted by a signal.
2133 Allow the user to quit. */
2136 emacs_open (const char *file, int oflags, int mode)
2138 int fd;
2139 oflags |= O_CLOEXEC;
2140 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2141 QUIT;
2142 if (! O_CLOEXEC && 0 <= fd)
2143 fcntl (fd, F_SETFD, FD_CLOEXEC);
2144 return fd;
2147 /* Open FILE as a stream for Emacs use, with mode MODE.
2148 Act like emacs_open with respect to threads, signals, and quits. */
2150 FILE *
2151 emacs_fopen (char const *file, char const *mode)
2153 int fd, omode, oflags;
2154 int bflag = 0;
2155 char const *m = mode;
2157 switch (*m++)
2159 case 'r': omode = O_RDONLY; oflags = 0; break;
2160 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2161 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2162 default: emacs_abort ();
2165 while (*m)
2166 switch (*m++)
2168 case '+': omode = O_RDWR; break;
2169 case 'b': bflag = O_BINARY; break;
2170 case 't': bflag = O_TEXT; break;
2171 default: /* Ignore. */ break;
2174 fd = emacs_open (file, omode | oflags | bflag, 0666);
2175 return fd < 0 ? 0 : fdopen (fd, mode);
2178 /* Create a pipe for Emacs use. */
2181 emacs_pipe (int fd[2])
2183 int result = pipe2 (fd, O_CLOEXEC);
2184 if (! O_CLOEXEC && result == 0)
2186 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2187 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2189 return result;
2192 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2193 For the background behind this mess, please see Austin Group defect 529
2194 <http://austingroupbugs.net/view.php?id=529>. */
2196 #ifndef POSIX_CLOSE_RESTART
2197 # define POSIX_CLOSE_RESTART 1
2198 static int
2199 posix_close (int fd, int flag)
2201 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2202 eassert (flag == POSIX_CLOSE_RESTART);
2204 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2205 on a system that does not define POSIX_CLOSE_RESTART.
2207 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2208 closed, and retrying the close could inadvertently close a file
2209 descriptor allocated by some other thread. In other systems
2210 (e.g., HP/UX) FD is not closed. And in still other systems
2211 (e.g., OS X, Solaris), maybe FD is closed, maybe not, and in a
2212 multithreaded program there can be no way to tell.
2214 So, in this case, pretend that the close succeeded. This works
2215 well on systems like GNU/Linux that close FD. Although it may
2216 leak a file descriptor on other systems, the leak is unlikely and
2217 it's better to leak than to close a random victim. */
2218 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2220 #endif
2222 /* Close FD, retrying if interrupted. If successful, return 0;
2223 otherwise, return -1 and set errno to a non-EINTR value. Consider
2224 an EINPROGRESS error to be successful, as that's merely a signal
2225 arriving. FD is always closed when this function returns, even
2226 when it returns -1.
2228 Do not call this function if FD is nonnegative and might already be closed,
2229 as that might close an innocent victim opened by some other thread. */
2232 emacs_close (int fd)
2234 while (1)
2236 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2237 if (r == 0)
2238 return r;
2239 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2241 eassert (errno != EBADF || fd < 0);
2242 return errno == EINPROGRESS ? 0 : r;
2247 /* Maximum number of bytes to read or write in a single system call.
2248 This works around a serious bug in Linux kernels before 2.6.16; see
2249 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2250 It's likely to work around similar bugs in other operating systems, so do it
2251 on all platforms. Round INT_MAX down to a page size, with the conservative
2252 assumption that page sizes are at most 2**18 bytes (any kernel with a
2253 page size larger than that shouldn't have the bug). */
2254 #ifndef MAX_RW_COUNT
2255 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2256 #endif
2258 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2259 Return the number of bytes read, which might be less than NBYTE.
2260 On error, set errno and return -1. */
2261 ptrdiff_t
2262 emacs_read (int fildes, char *buf, ptrdiff_t nbyte)
2264 register ssize_t rtnval;
2266 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2267 passes a size that large to emacs_read. */
2269 while ((rtnval = read (fildes, buf, nbyte)) == -1
2270 && (errno == EINTR))
2271 QUIT;
2272 return (rtnval);
2275 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2276 or if a partial write occurs. If interrupted, process pending
2277 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2278 errno if this is less than NBYTE. */
2279 static ptrdiff_t
2280 emacs_full_write (int fildes, char const *buf, ptrdiff_t nbyte,
2281 bool process_signals)
2283 ptrdiff_t bytes_written = 0;
2285 while (nbyte > 0)
2287 ssize_t n = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
2289 if (n < 0)
2291 if (errno == EINTR)
2293 /* I originally used `QUIT' but that might causes files to
2294 be truncated if you hit C-g in the middle of it. --Stef */
2295 if (process_signals && pending_signals)
2296 process_pending_signals ();
2297 continue;
2299 else
2300 break;
2303 buf += n;
2304 nbyte -= n;
2305 bytes_written += n;
2308 return bytes_written;
2311 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2312 interrupted or if a partial write occurs. Return the number of
2313 bytes written, setting errno if this is less than NBYTE. */
2314 ptrdiff_t
2315 emacs_write (int fildes, char const *buf, ptrdiff_t nbyte)
2317 return emacs_full_write (fildes, buf, nbyte, 0);
2320 /* Like emacs_write, but also process pending signals if interrupted. */
2321 ptrdiff_t
2322 emacs_write_sig (int fildes, char const *buf, ptrdiff_t nbyte)
2324 return emacs_full_write (fildes, buf, nbyte, 1);
2327 /* Write a diagnostic to standard error that contains MESSAGE and a
2328 string derived from errno. Preserve errno. Do not buffer stderr.
2329 Do not process pending signals if interrupted. */
2330 void
2331 emacs_perror (char const *message)
2333 int err = errno;
2334 char const *error_string = strerror (err);
2335 char const *command = (initial_argv && initial_argv[0]
2336 ? initial_argv[0] : "emacs");
2337 /* Write it out all at once, if it's short; this is less likely to
2338 be interleaved with other output. */
2339 char buf[BUFSIZ];
2340 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2341 command, message, error_string);
2342 if (0 <= nbytes && nbytes < BUFSIZ)
2343 emacs_write (STDERR_FILENO, buf, nbytes);
2344 else
2346 emacs_write (STDERR_FILENO, command, strlen (command));
2347 emacs_write (STDERR_FILENO, ": ", 2);
2348 emacs_write (STDERR_FILENO, message, strlen (message));
2349 emacs_write (STDERR_FILENO, ": ", 2);
2350 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2351 emacs_write (STDERR_FILENO, "\n", 1);
2353 errno = err;
2356 /* Return a struct timeval that is roughly equivalent to T.
2357 Use the least timeval not less than T.
2358 Return an extremal value if the result would overflow. */
2359 struct timeval
2360 make_timeval (struct timespec t)
2362 struct timeval tv;
2363 tv.tv_sec = t.tv_sec;
2364 tv.tv_usec = t.tv_nsec / 1000;
2366 if (t.tv_nsec % 1000 != 0)
2368 if (tv.tv_usec < 999999)
2369 tv.tv_usec++;
2370 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2372 tv.tv_sec++;
2373 tv.tv_usec = 0;
2377 return tv;
2380 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2381 ATIME and MTIME, respectively.
2382 FD must be either negative -- in which case it is ignored --
2383 or a file descriptor that is open on FILE.
2384 If FD is nonnegative, then FILE can be NULL. */
2386 set_file_times (int fd, const char *filename,
2387 struct timespec atime, struct timespec mtime)
2389 struct timespec timespec[2];
2390 timespec[0] = atime;
2391 timespec[1] = mtime;
2392 return fdutimens (fd, filename, timespec);
2395 /* Like strsignal, except async-signal-safe, and this function typically
2396 returns a string in the C locale rather than the current locale. */
2397 char const *
2398 safe_strsignal (int code)
2400 char const *signame = 0;
2402 if (0 <= code && code < sys_siglist_entries)
2403 signame = sys_siglist[code];
2404 if (! signame)
2405 signame = "Unknown signal";
2407 return signame;
2410 #ifndef DOS_NT
2411 /* For make-serial-process */
2413 serial_open (Lisp_Object port)
2415 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2416 if (fd < 0)
2417 report_file_error ("Opening serial port", port);
2418 #ifdef TIOCEXCL
2419 ioctl (fd, TIOCEXCL, (char *) 0);
2420 #endif
2422 return fd;
2425 #if !defined (HAVE_CFMAKERAW)
2426 /* Workaround for targets which are missing cfmakeraw. */
2427 /* Pasted from man page. */
2428 static void
2429 cfmakeraw (struct termios *termios_p)
2431 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2432 termios_p->c_oflag &= ~OPOST;
2433 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2434 termios_p->c_cflag &= ~(CSIZE|PARENB);
2435 termios_p->c_cflag |= CS8;
2437 #endif /* !defined (HAVE_CFMAKERAW */
2439 #if !defined (HAVE_CFSETSPEED)
2440 /* Workaround for targets which are missing cfsetspeed. */
2441 static int
2442 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2444 return (cfsetispeed (termios_p, vitesse)
2445 + cfsetospeed (termios_p, vitesse));
2447 #endif
2449 /* For serial-process-configure */
2450 void
2451 serial_configure (struct Lisp_Process *p,
2452 Lisp_Object contact)
2454 Lisp_Object childp2 = Qnil;
2455 Lisp_Object tem = Qnil;
2456 struct termios attr;
2457 int err;
2458 char summary[4] = "???"; /* This usually becomes "8N1". */
2460 childp2 = Fcopy_sequence (p->childp);
2462 /* Read port attributes and prepare default configuration. */
2463 err = tcgetattr (p->outfd, &attr);
2464 if (err != 0)
2465 report_file_error ("Failed tcgetattr", Qnil);
2466 cfmakeraw (&attr);
2467 #if defined (CLOCAL)
2468 attr.c_cflag |= CLOCAL;
2469 #endif
2470 #if defined (CREAD)
2471 attr.c_cflag |= CREAD;
2472 #endif
2474 /* Configure speed. */
2475 if (!NILP (Fplist_member (contact, QCspeed)))
2476 tem = Fplist_get (contact, QCspeed);
2477 else
2478 tem = Fplist_get (p->childp, QCspeed);
2479 CHECK_NUMBER (tem);
2480 err = cfsetspeed (&attr, XINT (tem));
2481 if (err != 0)
2482 report_file_error ("Failed cfsetspeed", tem);
2483 childp2 = Fplist_put (childp2, QCspeed, tem);
2485 /* Configure bytesize. */
2486 if (!NILP (Fplist_member (contact, QCbytesize)))
2487 tem = Fplist_get (contact, QCbytesize);
2488 else
2489 tem = Fplist_get (p->childp, QCbytesize);
2490 if (NILP (tem))
2491 tem = make_number (8);
2492 CHECK_NUMBER (tem);
2493 if (XINT (tem) != 7 && XINT (tem) != 8)
2494 error (":bytesize must be nil (8), 7, or 8");
2495 summary[0] = XINT (tem) + '0';
2496 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2497 attr.c_cflag &= ~CSIZE;
2498 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2499 #else
2500 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2501 if (XINT (tem) != 8)
2502 error ("Bytesize cannot be changed");
2503 #endif
2504 childp2 = Fplist_put (childp2, QCbytesize, tem);
2506 /* Configure parity. */
2507 if (!NILP (Fplist_member (contact, QCparity)))
2508 tem = Fplist_get (contact, QCparity);
2509 else
2510 tem = Fplist_get (p->childp, QCparity);
2511 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2512 error (":parity must be nil (no parity), `even', or `odd'");
2513 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2514 attr.c_cflag &= ~(PARENB | PARODD);
2515 attr.c_iflag &= ~(IGNPAR | INPCK);
2516 if (NILP (tem))
2518 summary[1] = 'N';
2520 else if (EQ (tem, Qeven))
2522 summary[1] = 'E';
2523 attr.c_cflag |= PARENB;
2524 attr.c_iflag |= (IGNPAR | INPCK);
2526 else if (EQ (tem, Qodd))
2528 summary[1] = 'O';
2529 attr.c_cflag |= (PARENB | PARODD);
2530 attr.c_iflag |= (IGNPAR | INPCK);
2532 #else
2533 /* Don't error on no parity, which should be set by cfmakeraw. */
2534 if (!NILP (tem))
2535 error ("Parity cannot be configured");
2536 #endif
2537 childp2 = Fplist_put (childp2, QCparity, tem);
2539 /* Configure stopbits. */
2540 if (!NILP (Fplist_member (contact, QCstopbits)))
2541 tem = Fplist_get (contact, QCstopbits);
2542 else
2543 tem = Fplist_get (p->childp, QCstopbits);
2544 if (NILP (tem))
2545 tem = make_number (1);
2546 CHECK_NUMBER (tem);
2547 if (XINT (tem) != 1 && XINT (tem) != 2)
2548 error (":stopbits must be nil (1 stopbit), 1, or 2");
2549 summary[2] = XINT (tem) + '0';
2550 #if defined (CSTOPB)
2551 attr.c_cflag &= ~CSTOPB;
2552 if (XINT (tem) == 2)
2553 attr.c_cflag |= CSTOPB;
2554 #else
2555 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2556 if (XINT (tem) != 1)
2557 error ("Stopbits cannot be configured");
2558 #endif
2559 childp2 = Fplist_put (childp2, QCstopbits, tem);
2561 /* Configure flowcontrol. */
2562 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2563 tem = Fplist_get (contact, QCflowcontrol);
2564 else
2565 tem = Fplist_get (p->childp, QCflowcontrol);
2566 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2567 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2568 #if defined (CRTSCTS)
2569 attr.c_cflag &= ~CRTSCTS;
2570 #endif
2571 #if defined (CNEW_RTSCTS)
2572 attr.c_cflag &= ~CNEW_RTSCTS;
2573 #endif
2574 #if defined (IXON) && defined (IXOFF)
2575 attr.c_iflag &= ~(IXON | IXOFF);
2576 #endif
2577 if (NILP (tem))
2579 /* Already configured. */
2581 else if (EQ (tem, Qhw))
2583 #if defined (CRTSCTS)
2584 attr.c_cflag |= CRTSCTS;
2585 #elif defined (CNEW_RTSCTS)
2586 attr.c_cflag |= CNEW_RTSCTS;
2587 #else
2588 error ("Hardware flowcontrol (RTS/CTS) not supported");
2589 #endif
2591 else if (EQ (tem, Qsw))
2593 #if defined (IXON) && defined (IXOFF)
2594 attr.c_iflag |= (IXON | IXOFF);
2595 #else
2596 error ("Software flowcontrol (XON/XOFF) not supported");
2597 #endif
2599 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2601 /* Activate configuration. */
2602 err = tcsetattr (p->outfd, TCSANOW, &attr);
2603 if (err != 0)
2604 report_file_error ("Failed tcsetattr", Qnil);
2606 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2607 pset_childp (p, childp2);
2609 #endif /* not DOS_NT */
2611 /* System depended enumeration of and access to system processes a-la ps(1). */
2613 #ifdef HAVE_PROCFS
2615 /* Process enumeration and access via /proc. */
2617 Lisp_Object
2618 list_system_processes (void)
2620 Lisp_Object procdir, match, proclist, next;
2621 struct gcpro gcpro1, gcpro2;
2622 register Lisp_Object tail;
2624 GCPRO2 (procdir, match);
2625 /* For every process on the system, there's a directory in the
2626 "/proc" pseudo-directory whose name is the numeric ID of that
2627 process. */
2628 procdir = build_string ("/proc");
2629 match = build_string ("[0-9]+");
2630 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2632 /* `proclist' gives process IDs as strings. Destructively convert
2633 each string into a number. */
2634 for (tail = proclist; CONSP (tail); tail = next)
2636 next = XCDR (tail);
2637 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2639 UNGCPRO;
2641 /* directory_files_internal returns the files in reverse order; undo
2642 that. */
2643 proclist = Fnreverse (proclist);
2644 return proclist;
2647 #elif defined DARWIN_OS || defined __FreeBSD__
2649 Lisp_Object
2650 list_system_processes (void)
2652 #ifdef DARWIN_OS
2653 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2654 #else
2655 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2656 #endif
2657 size_t len;
2658 struct kinfo_proc *procs;
2659 size_t i;
2661 struct gcpro gcpro1;
2662 Lisp_Object proclist = Qnil;
2664 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2665 return proclist;
2667 procs = xmalloc (len);
2668 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2670 xfree (procs);
2671 return proclist;
2674 GCPRO1 (proclist);
2675 len /= sizeof (struct kinfo_proc);
2676 for (i = 0; i < len; i++)
2678 #ifdef DARWIN_OS
2679 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2680 #else
2681 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2682 #endif
2684 UNGCPRO;
2686 xfree (procs);
2688 return proclist;
2691 /* The WINDOWSNT implementation is in w32.c.
2692 The MSDOS implementation is in dosfns.c. */
2693 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2695 Lisp_Object
2696 list_system_processes (void)
2698 return Qnil;
2701 #endif /* !defined (WINDOWSNT) */
2703 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2704 static struct timespec
2705 time_from_jiffies (unsigned long long tval, long hz)
2707 unsigned long long s = tval / hz;
2708 unsigned long long frac = tval % hz;
2709 int ns;
2711 if (TYPE_MAXIMUM (time_t) < s)
2712 time_overflow ();
2713 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2714 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2715 ns = frac * TIMESPEC_RESOLUTION / hz;
2716 else
2718 /* This is reachable only in the unlikely case that HZ * HZ
2719 exceeds ULLONG_MAX. It calculates an approximation that is
2720 guaranteed to be in range. */
2721 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
2722 + (hz % TIMESPEC_RESOLUTION != 0));
2723 ns = frac / hz_per_ns;
2726 return make_timespec (s, ns);
2729 static Lisp_Object
2730 ltime_from_jiffies (unsigned long long tval, long hz)
2732 struct timespec t = time_from_jiffies (tval, hz);
2733 return make_lisp_time (t);
2736 static struct timespec
2737 get_up_time (void)
2739 FILE *fup;
2740 struct timespec up = make_timespec (0, 0);
2742 block_input ();
2743 fup = emacs_fopen ("/proc/uptime", "r");
2745 if (fup)
2747 unsigned long long upsec, upfrac, idlesec, idlefrac;
2748 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
2750 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
2751 &upsec, &upfrac_start, &upfrac, &upfrac_end,
2752 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
2753 == 4)
2755 if (TYPE_MAXIMUM (time_t) < upsec)
2757 upsec = TYPE_MAXIMUM (time_t);
2758 upfrac = TIMESPEC_RESOLUTION - 1;
2760 else
2762 int upfraclen = upfrac_end - upfrac_start;
2763 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
2764 upfrac *= 10;
2765 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
2766 upfrac /= 10;
2767 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
2769 up = make_timespec (upsec, upfrac);
2771 fclose (fup);
2773 unblock_input ();
2775 return up;
2778 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2779 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2781 static Lisp_Object
2782 procfs_ttyname (int rdev)
2784 FILE *fdev;
2785 char name[PATH_MAX];
2787 block_input ();
2788 fdev = emacs_fopen ("/proc/tty/drivers", "r");
2789 name[0] = 0;
2791 if (fdev)
2793 unsigned major;
2794 unsigned long minor_beg, minor_end;
2795 char minor[25]; /* 2 32-bit numbers + dash */
2796 char *endp;
2798 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
2800 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
2801 && major == MAJOR (rdev))
2803 minor_beg = strtoul (minor, &endp, 0);
2804 if (*endp == '\0')
2805 minor_end = minor_beg;
2806 else if (*endp == '-')
2807 minor_end = strtoul (endp + 1, &endp, 0);
2808 else
2809 continue;
2811 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
2813 sprintf (name + strlen (name), "%u", MINOR (rdev));
2814 break;
2818 fclose (fdev);
2820 unblock_input ();
2821 return build_string (name);
2824 static uintmax_t
2825 procfs_get_total_memory (void)
2827 FILE *fmem;
2828 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
2829 int c;
2831 block_input ();
2832 fmem = emacs_fopen ("/proc/meminfo", "r");
2834 if (fmem)
2836 uintmax_t entry_value;
2837 bool done;
2840 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
2842 case 1:
2843 retval = entry_value;
2844 done = 1;
2845 break;
2847 case 0:
2848 while ((c = getc (fmem)) != EOF && c != '\n')
2849 continue;
2850 done = c == EOF;
2851 break;
2853 default:
2854 done = 1;
2855 break;
2857 while (!done);
2859 fclose (fmem);
2861 unblock_input ();
2862 return retval;
2865 Lisp_Object
2866 system_process_attributes (Lisp_Object pid)
2868 char procfn[PATH_MAX], fn[PATH_MAX];
2869 struct stat st;
2870 struct passwd *pw;
2871 struct group *gr;
2872 long clocks_per_sec;
2873 char *procfn_end;
2874 char procbuf[1025], *p, *q;
2875 int fd;
2876 ssize_t nread;
2877 static char const default_cmd[] = "???";
2878 const char *cmd = default_cmd;
2879 int cmdsize = sizeof default_cmd - 1;
2880 char *cmdline = NULL;
2881 ptrdiff_t cmdline_size;
2882 char c;
2883 printmax_t proc_id;
2884 int ppid, pgrp, sess, tty, tpgid, thcount;
2885 uid_t uid;
2886 gid_t gid;
2887 unsigned long long u_time, s_time, cutime, cstime, start;
2888 long priority, niceness, rss;
2889 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
2890 struct timespec tnow, tstart, tboot, telapsed, us_time;
2891 double pcpu, pmem;
2892 Lisp_Object attrs = Qnil;
2893 Lisp_Object cmd_str, decoded_cmd;
2894 ptrdiff_t count;
2895 struct gcpro gcpro1, gcpro2;
2897 CHECK_NUMBER_OR_FLOAT (pid);
2898 CONS_TO_INTEGER (pid, pid_t, proc_id);
2899 sprintf (procfn, "/proc/%"pMd, proc_id);
2900 if (stat (procfn, &st) < 0)
2901 return attrs;
2903 GCPRO2 (attrs, decoded_cmd);
2905 /* euid egid */
2906 uid = st.st_uid;
2907 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
2908 block_input ();
2909 pw = getpwuid (uid);
2910 unblock_input ();
2911 if (pw)
2912 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
2914 gid = st.st_gid;
2915 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
2916 block_input ();
2917 gr = getgrgid (gid);
2918 unblock_input ();
2919 if (gr)
2920 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
2922 count = SPECPDL_INDEX ();
2923 strcpy (fn, procfn);
2924 procfn_end = fn + strlen (fn);
2925 strcpy (procfn_end, "/stat");
2926 fd = emacs_open (fn, O_RDONLY, 0);
2927 if (fd < 0)
2928 nread = 0;
2929 else
2931 record_unwind_protect_int (close_file_unwind, fd);
2932 nread = emacs_read (fd, procbuf, sizeof procbuf - 1);
2934 if (0 < nread)
2936 procbuf[nread] = '\0';
2937 p = procbuf;
2939 p = strchr (p, '(');
2940 if (p != NULL)
2942 q = strrchr (p + 1, ')');
2943 /* comm */
2944 if (q != NULL)
2946 cmd = p + 1;
2947 cmdsize = q - cmd;
2950 else
2951 q = NULL;
2952 /* Command name is encoded in locale-coding-system; decode it. */
2953 cmd_str = make_unibyte_string (cmd, cmdsize);
2954 decoded_cmd = code_convert_string_norecord (cmd_str,
2955 Vlocale_coding_system, 0);
2956 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
2958 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
2959 utime stime cutime cstime priority nice thcount . start vsize rss */
2960 if (q
2961 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
2962 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
2963 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
2964 &minflt, &cminflt, &majflt, &cmajflt,
2965 &u_time, &s_time, &cutime, &cstime,
2966 &priority, &niceness, &thcount, &start, &vsize, &rss)
2967 == 20))
2969 char state_str[2];
2970 state_str[0] = c;
2971 state_str[1] = '\0';
2972 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
2973 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
2974 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
2975 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
2976 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
2977 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
2978 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
2979 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
2980 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
2981 attrs);
2982 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
2983 attrs);
2984 clocks_per_sec = sysconf (_SC_CLK_TCK);
2985 if (clocks_per_sec < 0)
2986 clocks_per_sec = 100;
2987 attrs = Fcons (Fcons (Qutime,
2988 ltime_from_jiffies (u_time, clocks_per_sec)),
2989 attrs);
2990 attrs = Fcons (Fcons (Qstime,
2991 ltime_from_jiffies (s_time, clocks_per_sec)),
2992 attrs);
2993 attrs = Fcons (Fcons (Qtime,
2994 ltime_from_jiffies (s_time + u_time,
2995 clocks_per_sec)),
2996 attrs);
2997 attrs = Fcons (Fcons (Qcutime,
2998 ltime_from_jiffies (cutime, clocks_per_sec)),
2999 attrs);
3000 attrs = Fcons (Fcons (Qcstime,
3001 ltime_from_jiffies (cstime, clocks_per_sec)),
3002 attrs);
3003 attrs = Fcons (Fcons (Qctime,
3004 ltime_from_jiffies (cstime + cutime,
3005 clocks_per_sec)),
3006 attrs);
3007 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3008 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3009 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3010 attrs);
3011 tnow = current_timespec ();
3012 telapsed = get_up_time ();
3013 tboot = timespec_sub (tnow, telapsed);
3014 tstart = time_from_jiffies (start, clocks_per_sec);
3015 tstart = timespec_add (tboot, tstart);
3016 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3017 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3018 attrs);
3019 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3020 telapsed = timespec_sub (tnow, tstart);
3021 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3022 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3023 pcpu = timespectod (us_time) / timespectod (telapsed);
3024 if (pcpu > 1.0)
3025 pcpu = 1.0;
3026 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3027 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3028 if (pmem > 100)
3029 pmem = 100;
3030 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3033 unbind_to (count, Qnil);
3035 /* args */
3036 strcpy (procfn_end, "/cmdline");
3037 fd = emacs_open (fn, O_RDONLY, 0);
3038 if (fd >= 0)
3040 ptrdiff_t readsize, nread_incr;
3041 record_unwind_protect_int (close_file_unwind, fd);
3042 record_unwind_protect_nothing ();
3043 nread = cmdline_size = 0;
3047 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3048 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3050 /* Leave room even if every byte needs escaping below. */
3051 readsize = (cmdline_size >> 1) - nread;
3053 nread_incr = emacs_read (fd, cmdline + nread, readsize);
3054 nread += max (0, nread_incr);
3056 while (nread_incr == readsize);
3058 if (nread)
3060 /* We don't want trailing null characters. */
3061 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3062 continue;
3064 /* Escape-quote whitespace and backslashes. */
3065 q = cmdline + cmdline_size;
3066 while (cmdline < p)
3068 char c = *--p;
3069 *--q = c ? c : ' ';
3070 if (c_isspace (c) || c == '\\')
3071 *--q = '\\';
3074 nread = cmdline + cmdline_size - q;
3077 if (!nread)
3079 nread = cmdsize + 2;
3080 cmdline_size = nread + 1;
3081 q = cmdline = xrealloc (cmdline, cmdline_size);
3082 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3083 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3085 /* Command line is encoded in locale-coding-system; decode it. */
3086 cmd_str = make_unibyte_string (q, nread);
3087 decoded_cmd = code_convert_string_norecord (cmd_str,
3088 Vlocale_coding_system, 0);
3089 unbind_to (count, Qnil);
3090 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3093 UNGCPRO;
3094 return attrs;
3097 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3099 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3100 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3101 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3102 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3103 #undef _FILE_OFFSET_BITS
3104 #else
3105 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3106 #endif
3108 #include <procfs.h>
3110 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3111 #define _FILE_OFFSET_BITS 64
3112 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3113 #endif
3114 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3116 Lisp_Object
3117 system_process_attributes (Lisp_Object pid)
3119 char procfn[PATH_MAX], fn[PATH_MAX];
3120 struct stat st;
3121 struct passwd *pw;
3122 struct group *gr;
3123 char *procfn_end;
3124 struct psinfo pinfo;
3125 int fd;
3126 ssize_t nread;
3127 printmax_t proc_id;
3128 uid_t uid;
3129 gid_t gid;
3130 Lisp_Object attrs = Qnil;
3131 Lisp_Object decoded_cmd;
3132 struct gcpro gcpro1, gcpro2;
3133 ptrdiff_t count;
3135 CHECK_NUMBER_OR_FLOAT (pid);
3136 CONS_TO_INTEGER (pid, pid_t, proc_id);
3137 sprintf (procfn, "/proc/%"pMd, proc_id);
3138 if (stat (procfn, &st) < 0)
3139 return attrs;
3141 GCPRO2 (attrs, decoded_cmd);
3143 /* euid egid */
3144 uid = st.st_uid;
3145 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3146 block_input ();
3147 pw = getpwuid (uid);
3148 unblock_input ();
3149 if (pw)
3150 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3152 gid = st.st_gid;
3153 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3154 block_input ();
3155 gr = getgrgid (gid);
3156 unblock_input ();
3157 if (gr)
3158 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3160 count = SPECPDL_INDEX ();
3161 strcpy (fn, procfn);
3162 procfn_end = fn + strlen (fn);
3163 strcpy (procfn_end, "/psinfo");
3164 fd = emacs_open (fn, O_RDONLY, 0);
3165 if (fd < 0)
3166 nread = 0;
3167 else
3169 record_unwind_protect (close_file_unwind, fd);
3170 nread = emacs_read (fd, &pinfo, sizeof pinfo);
3173 if (nread == sizeof pinfo)
3175 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3176 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3177 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3180 char state_str[2];
3181 state_str[0] = pinfo.pr_lwp.pr_sname;
3182 state_str[1] = '\0';
3183 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3186 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3187 need to get a string from it. */
3189 /* FIXME: missing: Qtpgid */
3191 /* FIXME: missing:
3192 Qminflt
3193 Qmajflt
3194 Qcminflt
3195 Qcmajflt
3197 Qutime
3198 Qcutime
3199 Qstime
3200 Qcstime
3201 Are they available? */
3203 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3204 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3205 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3206 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3207 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3208 attrs);
3210 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3211 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3212 attrs);
3213 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3214 attrs);
3216 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3217 range 0 .. 2**15, representing 0.0 .. 1.0. */
3218 attrs = Fcons (Fcons (Qpcpu,
3219 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3220 attrs);
3221 attrs = Fcons (Fcons (Qpmem,
3222 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3223 attrs);
3225 decoded_cmd = (code_convert_string_norecord
3226 (build_unibyte_string (pinfo.pr_fname),
3227 Vlocale_coding_system, 0));
3228 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3229 decoded_cmd = (code_convert_string_norecord
3230 (build_unibyte_string (pinfo.pr_psargs),
3231 Vlocale_coding_system, 0));
3232 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3234 unbind_to (count, Qnil);
3235 UNGCPRO;
3236 return attrs;
3239 #elif defined __FreeBSD__
3241 static struct timespec
3242 timeval_to_timespec (struct timeval t)
3244 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3247 static Lisp_Object
3248 make_lisp_timeval (struct timeval t)
3250 return make_lisp_time (timeval_to_timespec (t));
3253 Lisp_Object
3254 system_process_attributes (Lisp_Object pid)
3256 int proc_id;
3257 int pagesize = getpagesize ();
3258 unsigned long npages;
3259 int fscale;
3260 struct passwd *pw;
3261 struct group *gr;
3262 char *ttyname;
3263 size_t len;
3264 char args[MAXPATHLEN];
3265 struct timespec t, now;
3267 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3268 struct kinfo_proc proc;
3269 size_t proclen = sizeof proc;
3271 struct gcpro gcpro1, gcpro2;
3272 Lisp_Object attrs = Qnil;
3273 Lisp_Object decoded_comm;
3275 CHECK_NUMBER_OR_FLOAT (pid);
3276 CONS_TO_INTEGER (pid, int, proc_id);
3277 mib[3] = proc_id;
3279 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3280 return attrs;
3282 GCPRO2 (attrs, decoded_comm);
3284 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3286 block_input ();
3287 pw = getpwuid (proc.ki_uid);
3288 unblock_input ();
3289 if (pw)
3290 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3292 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3294 block_input ();
3295 gr = getgrgid (proc.ki_svgid);
3296 unblock_input ();
3297 if (gr)
3298 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3300 decoded_comm = (code_convert_string_norecord
3301 (build_unibyte_string (proc.ki_comm),
3302 Vlocale_coding_system, 0));
3304 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3306 char state[2] = {'\0', '\0'};
3307 switch (proc.ki_stat)
3309 case SRUN:
3310 state[0] = 'R';
3311 break;
3313 case SSLEEP:
3314 state[0] = 'S';
3315 break;
3317 case SLOCK:
3318 state[0] = 'D';
3319 break;
3321 case SZOMB:
3322 state[0] = 'Z';
3323 break;
3325 case SSTOP:
3326 state[0] = 'T';
3327 break;
3329 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3332 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3333 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3334 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3336 block_input ();
3337 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3338 unblock_input ();
3339 if (ttyname)
3340 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3342 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3343 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3344 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3345 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3346 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3348 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3349 attrs);
3350 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3351 attrs);
3352 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3353 timeval_to_timespec (proc.ki_rusage.ru_stime));
3354 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3356 attrs = Fcons (Fcons (Qcutime,
3357 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3358 attrs);
3359 attrs = Fcons (Fcons (Qcstime,
3360 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3361 attrs);
3362 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3363 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3364 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3366 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3367 attrs);
3368 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3369 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3370 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3371 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3372 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3373 attrs);
3375 now = current_timespec ();
3376 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3377 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3379 len = sizeof fscale;
3380 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3382 double pcpu;
3383 fixpt_t ccpu;
3384 len = sizeof ccpu;
3385 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3387 pcpu = (100.0 * proc.ki_pctcpu / fscale
3388 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3389 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3393 len = sizeof npages;
3394 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3396 double pmem = (proc.ki_flag & P_INMEM
3397 ? 100.0 * proc.ki_rssize / npages
3398 : 0);
3399 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3402 mib[2] = KERN_PROC_ARGS;
3403 len = MAXPATHLEN;
3404 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3406 int i;
3407 for (i = 0; i < len; i++)
3409 if (! args[i] && i < len - 1)
3410 args[i] = ' ';
3413 decoded_comm =
3414 (code_convert_string_norecord
3415 (build_unibyte_string (args),
3416 Vlocale_coding_system, 0));
3418 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3421 UNGCPRO;
3422 return attrs;
3425 /* The WINDOWSNT implementation is in w32.c.
3426 The MSDOS implementation is in dosfns.c. */
3427 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3429 Lisp_Object
3430 system_process_attributes (Lisp_Object pid)
3432 return Qnil;
3435 #endif /* !defined (WINDOWSNT) */