* lisp/mail/footnote.el: Use lexical-binding
[emacs.git] / src / sysdep.c
blob9522aa4b04b87a4b7e8797a90a9041ff13bb5106
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2017 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 (at
10 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 <https://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <execinfo.h>
23 #include "sysstdio.h"
24 #ifdef HAVE_PWD_H
25 #include <pwd.h>
26 #include <grp.h>
27 #endif /* HAVE_PWD_H */
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
33 #include <utimens.h>
35 #include "lisp.h"
36 #include "sheap.h"
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #ifdef HAVE_LINUX_FS_H
41 # include <linux/fs.h>
42 # include <sys/syscall.h>
43 #endif
45 #ifdef CYGWIN
46 # include <cygwin/fs.h>
47 #endif
49 #if defined DARWIN_OS || defined __FreeBSD__
50 # include <sys/sysctl.h>
51 #endif
53 #ifdef __FreeBSD__
54 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
55 'struct frame', so rename it. */
56 # define frame freebsd_frame
57 # include <sys/user.h>
58 # undef frame
60 # include <math.h>
61 #endif
63 #ifdef HAVE_SOCKETS
64 #include <sys/socket.h>
65 #include <netdb.h>
66 #endif /* HAVE_SOCKETS */
68 #ifdef WINDOWSNT
69 #define read sys_read
70 #define write sys_write
71 #ifndef STDERR_FILENO
72 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
73 #endif
74 #include "w32.h"
75 #endif /* WINDOWSNT */
77 #include <sys/types.h>
78 #include <sys/stat.h>
79 #include <errno.h>
81 /* Get SI_SRPC_DOMAIN, if it is available. */
82 #ifdef HAVE_SYS_SYSTEMINFO_H
83 #include <sys/systeminfo.h>
84 #endif
86 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
87 #include "msdos.h"
88 #endif
90 #include <sys/param.h>
91 #include <sys/file.h>
92 #include <fcntl.h>
94 #include "systty.h"
95 #include "syswait.h"
97 #ifdef HAVE_SYS_UTSNAME_H
98 #include <sys/utsname.h>
99 #include <memory.h>
100 #endif /* HAVE_SYS_UTSNAME_H */
102 #include "keyboard.h"
103 #include "frame.h"
104 #include "termhooks.h"
105 #include "termchar.h"
106 #include "termopts.h"
107 #include "process.h"
108 #include "cm.h"
110 #include "gnutls.h"
111 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
112 do that during startup just to call gnutls_rnd. */
113 #if defined HAVE_GNUTLS && !defined WINDOWSNT
114 # include <gnutls/crypto.h>
115 #else
116 # define emacs_gnutls_global_init() Qnil
117 # define gnutls_rnd(level, data, len) (-1)
118 #endif
120 #ifdef WINDOWSNT
121 #include <direct.h>
122 /* In process.h which conflicts with the local copy. */
123 #define _P_WAIT 0
124 int _cdecl _spawnlp (int, const char *, const char *, ...);
125 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
126 several prototypes of functions called below. */
127 #include <sys/socket.h>
128 #endif
130 #include "syssignal.h"
131 #include "systime.h"
133 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
134 #ifndef ULLONG_MAX
135 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
136 #endif
138 /* Declare here, including term.h is problematic on some systems. */
139 extern void tputs (const char *, int, int (*)(int));
141 static const int baud_convert[] =
143 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
144 1800, 2400, 4800, 9600, 19200, 38400
147 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
148 # include <sys/personality.h>
150 /* Disable address randomization in the current process. Return true
151 if addresses were randomized but this has been disabled, false
152 otherwise. */
153 bool
154 disable_address_randomization (void)
156 int pers = personality (0xffffffff);
157 if (pers < 0)
158 return false;
159 int desired_pers = pers | ADDR_NO_RANDOMIZE;
161 /* Call 'personality' twice, to detect buggy platforms like WSL
162 where 'personality' always returns 0. */
163 return (pers != desired_pers
164 && personality (desired_pers) == pers
165 && personality (0xffffffff) == desired_pers);
167 #endif
169 /* Execute the program in FILE, with argument vector ARGV and environ
170 ENVP. Return an error number if unsuccessful. This is like execve
171 except it reenables ASLR in the executed program if necessary, and
172 on error it returns an error number rather than -1. */
174 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
176 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
177 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
178 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
179 if (change_personality)
180 personality (pers & ~ADDR_NO_RANDOMIZE);
181 #endif
183 execve (file, argv, envp);
184 int err = errno;
186 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
187 if (change_personality)
188 personality (pers);
189 #endif
191 return err;
194 /* If FD is not already open, arrange for it to be open with FLAGS. */
195 static void
196 force_open (int fd, int flags)
198 if (dup2 (fd, fd) < 0 && errno == EBADF)
200 int n = open (NULL_DEVICE, flags);
201 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
203 emacs_perror (NULL_DEVICE);
204 exit (EXIT_FAILURE);
209 /* Make sure stdin, stdout, and stderr are open to something, so that
210 their file descriptors are not hijacked by later system calls. */
211 void
212 init_standard_fds (void)
214 /* Open stdin for *writing*, and stdout and stderr for *reading*.
215 That way, any attempt to do normal I/O will result in an error,
216 just as if the files were closed, and the file descriptors will
217 not be reused by later opens. */
218 force_open (STDIN_FILENO, O_WRONLY);
219 force_open (STDOUT_FILENO, O_RDONLY);
220 force_open (STDERR_FILENO, O_RDONLY);
223 /* Return the current working directory. The result should be freed
224 with 'free'. Return NULL (setting errno) on errors. If the
225 current directory is unreachable, return either NULL or a string
226 beginning with '('. */
228 static char *
229 get_current_dir_name_or_unreachable (void)
231 /* Use malloc, not xmalloc, since this function can be called before
232 the xmalloc exception machinery is available. */
234 char *pwd;
236 /* The maximum size of a directory name, including the terminating null.
237 Leave room so that the caller can append a trailing slash. */
238 ptrdiff_t dirsize_max = min (PTRDIFF_MAX, SIZE_MAX) - 1;
240 /* The maximum size of a buffer for a file name, including the
241 terminating null. This is bounded by MAXPATHLEN, if available. */
242 ptrdiff_t bufsize_max = dirsize_max;
243 #ifdef MAXPATHLEN
244 bufsize_max = min (bufsize_max, MAXPATHLEN);
245 #endif
247 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
248 # ifdef HYBRID_MALLOC
249 bool use_libc = bss_sbrk_did_unexec;
250 # else
251 bool use_libc = true;
252 # endif
253 if (use_libc)
255 /* For an unreachable directory, this returns a string that starts
256 with "(unreachable)"; see Bug#27871. */
257 pwd = get_current_dir_name ();
258 if (pwd)
260 if (strlen (pwd) < dirsize_max)
261 return pwd;
262 free (pwd);
263 errno = ERANGE;
265 return NULL;
267 # endif
269 size_t pwdlen;
270 struct stat dotstat, pwdstat;
271 pwd = getenv ("PWD");
273 /* If PWD is accurate, use it instead of calling getcwd. PWD is
274 sometimes a nicer name, and using it may avoid a fatal error if a
275 parent directory is searchable but not readable. */
276 if (pwd
277 && (pwdlen = strlen (pwd)) < bufsize_max
278 && IS_DIRECTORY_SEP (pwd[pwdlen && IS_DEVICE_SEP (pwd[1]) ? 2 : 0])
279 && stat (pwd, &pwdstat) == 0
280 && stat (".", &dotstat) == 0
281 && dotstat.st_ino == pwdstat.st_ino
282 && dotstat.st_dev == pwdstat.st_dev)
284 char *buf = malloc (pwdlen + 1);
285 if (!buf)
286 return NULL;
287 return memcpy (buf, pwd, pwdlen + 1);
289 else
291 ptrdiff_t buf_size = min (bufsize_max, 1024);
292 char *buf = malloc (buf_size);
293 if (!buf)
294 return NULL;
295 for (;;)
297 if (getcwd (buf, buf_size) == buf)
298 return buf;
299 int getcwd_errno = errno;
300 if (getcwd_errno != ERANGE || buf_size == bufsize_max)
302 free (buf);
303 errno = getcwd_errno;
304 return NULL;
306 buf_size = buf_size <= bufsize_max / 2 ? 2 * buf_size : bufsize_max;
307 buf = realloc (buf, buf_size);
308 if (!buf)
309 return NULL;
314 /* Return the current working directory. The result should be freed
315 with 'free'. Return NULL (setting errno) on errors; an unreachable
316 directory (e.g., its name starts with '(') counts as an error. */
318 char *
319 emacs_get_current_dir_name (void)
321 char *dir = get_current_dir_name_or_unreachable ();
322 if (dir && *dir == '(')
324 free (dir);
325 errno = ENOENT;
326 return NULL;
328 return dir;
332 /* Discard pending input on all input descriptors. */
334 void
335 discard_tty_input (void)
337 #ifndef WINDOWSNT
338 struct emacs_tty buf;
340 if (noninteractive)
341 return;
343 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
344 while (dos_keyread () != -1)
346 #else /* not MSDOS */
348 struct tty_display_info *tty;
349 for (tty = tty_list; tty; tty = tty->next)
351 if (tty->input) /* Is the device suspended? */
353 emacs_get_tty (fileno (tty->input), &buf);
354 emacs_set_tty (fileno (tty->input), &buf, 0);
358 #endif /* not MSDOS */
359 #endif /* not WINDOWSNT */
363 #ifdef SIGTSTP
365 /* Arrange for character C to be read as the next input from
366 the terminal.
367 XXX What if we have multiple ttys?
370 void
371 stuff_char (char c)
373 if (! (FRAMEP (selected_frame)
374 && FRAME_LIVE_P (XFRAME (selected_frame))
375 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
376 return;
378 /* Should perhaps error if in batch mode */
379 #ifdef TIOCSTI
380 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
381 #else /* no TIOCSTI */
382 error ("Cannot stuff terminal input characters in this version of Unix");
383 #endif /* no TIOCSTI */
386 #endif /* SIGTSTP */
388 void
389 init_baud_rate (int fd)
391 int emacs_ospeed;
393 if (noninteractive)
394 emacs_ospeed = 0;
395 else
397 #ifdef DOS_NT
398 emacs_ospeed = 15;
399 #else /* not DOS_NT */
400 struct termios sg;
402 sg.c_cflag = B9600;
403 tcgetattr (fd, &sg);
404 emacs_ospeed = cfgetospeed (&sg);
405 #endif /* not DOS_NT */
408 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
409 ? baud_convert[emacs_ospeed] : 9600);
410 if (baud_rate == 0)
411 baud_rate = 1200;
416 #ifndef MSDOS
418 /* Wait for the subprocess with process id CHILD to terminate or change status.
419 CHILD must be a child process that has not been reaped.
420 If STATUS is non-null, store the waitpid-style exit status into *STATUS
421 and tell wait_reading_process_output that it needs to look around.
422 Use waitpid-style OPTIONS when waiting.
423 If INTERRUPTIBLE, this function is interruptible by a signal.
425 Return CHILD if successful, 0 if no status is available, and a
426 negative value (setting errno) if waitpid is buggy. */
427 static pid_t
428 get_child_status (pid_t child, int *status, int options, bool interruptible)
430 pid_t pid;
432 /* Invoke waitpid only with a known process ID; do not invoke
433 waitpid with a nonpositive argument. Otherwise, Emacs might
434 reap an unwanted process by mistake. For example, invoking
435 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
436 so that another thread running glib won't find them. */
437 eassert (child > 0);
439 while (true)
441 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
442 internally. */
443 if (interruptible)
444 maybe_quit ();
446 pid = waitpid (child, status, options);
447 if (0 <= pid)
448 break;
449 if (errno != EINTR)
451 /* Most likely, waitpid is buggy and the operating system
452 lost track of the child somehow. Return -1 and let the
453 caller try to figure things out. Possibly the bug could
454 cause Emacs to kill the wrong process. Oh well. */
455 return pid;
459 /* If successful and status is requested, tell wait_reading_process_output
460 that it needs to wake up and look around. */
461 if (pid && status && input_available_clear_time)
462 *input_available_clear_time = make_timespec (0, 0);
464 return pid;
467 /* Wait for the subprocess with process id CHILD to terminate.
468 CHILD must be a child process that has not been reaped.
469 If STATUS is non-null, store the waitpid-style exit status into *STATUS
470 and tell wait_reading_process_output that it needs to look around.
471 If INTERRUPTIBLE, this function is interruptible by a signal.
472 Return true if successful, false (setting errno) if CHILD cannot be
473 waited for because waitpid is buggy. */
474 bool
475 wait_for_termination (pid_t child, int *status, bool interruptible)
477 return 0 <= get_child_status (child, status, 0, interruptible);
480 /* Report whether the subprocess with process id CHILD has changed status.
481 Termination counts as a change of status.
482 CHILD must be a child process that has not been reaped.
483 If STATUS is non-null, store the waitpid-style exit status into *STATUS
484 and tell wait_reading_process_output that it needs to look around.
485 Use waitpid-style OPTIONS to check status, but do not wait.
487 Return CHILD if successful, 0 if no status is available because
488 the process's state has not changed. */
489 pid_t
490 child_status_changed (pid_t child, int *status, int options)
492 return get_child_status (child, status, WNOHANG | options, 0);
496 /* Set up the terminal at the other end of a pseudo-terminal that
497 we will be controlling an inferior through.
498 It should not echo or do line-editing, since that is done
499 in Emacs. No padding needed for insertion into an Emacs buffer. */
501 void
502 child_setup_tty (int out)
504 #ifndef WINDOWSNT
505 struct emacs_tty s;
507 emacs_get_tty (out, &s);
508 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
509 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
510 #ifdef NLDLY
511 /* https://lists.gnu.org/r/emacs-devel/2008-05/msg00406.html
512 Some versions of GNU Hurd do not have FFDLY? */
513 #ifdef FFDLY
514 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
515 /* No output delays */
516 #else
517 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
518 /* No output delays */
519 #endif
520 #endif
521 s.main.c_lflag &= ~ECHO; /* Disable echo */
522 s.main.c_lflag |= ISIG; /* Enable signals */
523 #ifdef IUCLC
524 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
525 #endif
526 #ifdef ISTRIP
527 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
528 #endif
529 #ifdef OLCUC
530 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
531 #endif
532 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
533 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
534 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
535 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
537 #ifdef HPUX
538 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
539 #endif /* HPUX */
541 #ifdef SIGNALS_VIA_CHARACTERS
542 /* the QUIT and INTR character are used in process_send_signal
543 so set them here to something useful. */
544 if (s.main.c_cc[VQUIT] == CDISABLE)
545 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
546 if (s.main.c_cc[VINTR] == CDISABLE)
547 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
548 #endif /* not SIGNALS_VIA_CHARACTERS */
550 #ifdef AIX
551 /* Also, PTY overloads NUL and BREAK.
552 don't ignore break, but don't signal either, so it looks like NUL. */
553 s.main.c_iflag &= ~IGNBRK;
554 s.main.c_iflag &= ~BRKINT;
555 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
556 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
557 would force it to 0377. That looks like duplicated code. */
558 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
559 #endif /* AIX */
561 /* We originally enabled ICANON (and set VEOF to 04), and then had
562 process.c send additional EOF chars to flush the output when faced
563 with long lines, but this leads to weird effects when the
564 subprocess has disabled ICANON and ends up seeing those spurious
565 extra EOFs. So we don't send EOFs any more in
566 process.c:send_process. First we tried to disable ICANON by
567 default, so if a subsprocess sets up ICANON, it's his problem (or
568 the Elisp package that talks to it) to deal with lines that are
569 too long. But this disables some features, such as the ability
570 to send EOF signals. So we re-enabled ICANON but there is no
571 more "send eof to flush" going on (which is wrong and unportable
572 in itself). The correct way to handle too much output is to
573 buffer what could not be written and then write it again when
574 select returns ok for writing. This has it own set of
575 problems. Write is now asynchronous, is that a problem? How much
576 do we buffer, and what do we do when that limit is reached? */
578 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
579 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
580 #if 0 /* These settings only apply to non-ICANON mode. */
581 s.main.c_cc[VMIN] = 1;
582 s.main.c_cc[VTIME] = 0;
583 #endif
585 emacs_set_tty (out, &s, 0);
586 #endif /* not WINDOWSNT */
588 #endif /* not MSDOS */
591 /* Record a signal code and the action for it. */
592 struct save_signal
594 int code;
595 struct sigaction action;
598 static void save_signal_handlers (struct save_signal *);
599 static void restore_signal_handlers (struct save_signal *);
601 /* Suspend the Emacs process; give terminal to its superior. */
603 void
604 sys_suspend (void)
606 #ifndef DOS_NT
607 kill (0, SIGTSTP);
608 #else
609 /* On a system where suspending is not implemented,
610 instead fork a subshell and let it talk directly to the terminal
611 while we wait. */
612 sys_subshell ();
614 #endif
617 /* Fork a subshell. */
619 void
620 sys_subshell (void)
622 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
623 #ifdef MSDOS
624 int st;
625 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
626 #else
627 char oldwd[MAX_UTF8_PATH];
628 #endif /* MSDOS */
629 #else /* !DOS_NT */
630 int status;
631 #endif
632 pid_t pid;
633 struct save_signal saved_handlers[5];
634 char *str = SSDATA (encode_current_directory ());
636 #ifdef DOS_NT
637 pid = 0;
638 #else
640 char *volatile str_volatile = str;
641 pid = vfork ();
642 str = str_volatile;
644 #endif
646 if (pid < 0)
647 error ("Can't spawn subshell");
649 saved_handlers[0].code = SIGINT;
650 saved_handlers[1].code = SIGQUIT;
651 saved_handlers[2].code = SIGTERM;
652 #ifdef USABLE_SIGIO
653 saved_handlers[3].code = SIGIO;
654 saved_handlers[4].code = 0;
655 #else
656 saved_handlers[3].code = 0;
657 #endif
659 #ifdef DOS_NT
660 save_signal_handlers (saved_handlers);
661 #endif
663 if (pid == 0)
665 const char *sh = 0;
667 #ifdef DOS_NT /* MW, Aug 1993 */
668 getcwd (oldwd, sizeof oldwd);
669 if (sh == 0)
670 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
671 #endif
672 if (sh == 0)
673 sh = egetenv ("SHELL");
674 if (sh == 0)
675 sh = "sh";
677 /* Use our buffer's default directory for the subshell. */
678 if (chdir (str) != 0)
680 #ifndef DOS_NT
681 emacs_perror (str);
682 _exit (EXIT_CANCELED);
683 #endif
686 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
688 char *epwd = getenv ("PWD");
689 char old_pwd[MAXPATHLEN+1+4];
691 /* If PWD is set, pass it with corrected value. */
692 if (epwd)
694 strcpy (old_pwd, epwd);
695 setenv ("PWD", str, 1);
697 st = system (sh);
698 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
699 if (epwd)
700 putenv (old_pwd); /* restore previous value */
702 #else /* not MSDOS */
703 #ifdef WINDOWSNT
704 /* Waits for process completion */
705 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
706 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
707 if (pid == -1)
708 write (1, "Can't execute subshell", 22);
709 #else /* not WINDOWSNT */
710 execlp (sh, sh, (char *) 0);
711 emacs_perror (sh);
712 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
713 #endif /* not WINDOWSNT */
714 #endif /* not MSDOS */
717 /* Do this now if we did not do it before. */
718 #ifndef MSDOS
719 save_signal_handlers (saved_handlers);
720 #endif
722 #ifndef DOS_NT
723 wait_for_termination (pid, &status, 0);
724 #endif
725 restore_signal_handlers (saved_handlers);
728 static void
729 save_signal_handlers (struct save_signal *saved_handlers)
731 while (saved_handlers->code)
733 struct sigaction action;
734 emacs_sigaction_init (&action, SIG_IGN);
735 sigaction (saved_handlers->code, &action, &saved_handlers->action);
736 saved_handlers++;
740 static void
741 restore_signal_handlers (struct save_signal *saved_handlers)
743 while (saved_handlers->code)
745 sigaction (saved_handlers->code, &saved_handlers->action, 0);
746 saved_handlers++;
750 #ifdef USABLE_SIGIO
751 static int old_fcntl_flags[FD_SETSIZE];
752 #endif
754 void
755 init_sigio (int fd)
757 #ifdef USABLE_SIGIO
758 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
759 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
760 interrupts_deferred = 0;
761 #endif
764 #ifndef DOS_NT
765 static void
766 reset_sigio (int fd)
768 #ifdef USABLE_SIGIO
769 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
770 #endif
772 #endif
774 void
775 request_sigio (void)
777 #ifdef USABLE_SIGIO
778 sigset_t unblocked;
780 if (noninteractive)
781 return;
783 sigemptyset (&unblocked);
784 # ifdef SIGWINCH
785 sigaddset (&unblocked, SIGWINCH);
786 # endif
787 sigaddset (&unblocked, SIGIO);
788 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
790 interrupts_deferred = 0;
791 #endif
794 void
795 unrequest_sigio (void)
797 #ifdef USABLE_SIGIO
798 sigset_t blocked;
800 if (noninteractive)
801 return;
803 sigemptyset (&blocked);
804 # ifdef SIGWINCH
805 sigaddset (&blocked, SIGWINCH);
806 # endif
807 sigaddset (&blocked, SIGIO);
808 pthread_sigmask (SIG_BLOCK, &blocked, 0);
809 interrupts_deferred = 1;
810 #endif
813 #ifndef MSDOS
814 /* Block SIGCHLD. */
816 void
817 block_child_signal (sigset_t *oldset)
819 sigset_t blocked;
820 sigemptyset (&blocked);
821 sigaddset (&blocked, SIGCHLD);
822 sigaddset (&blocked, SIGINT);
823 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
826 /* Unblock SIGCHLD. */
828 void
829 unblock_child_signal (sigset_t const *oldset)
831 pthread_sigmask (SIG_SETMASK, oldset, 0);
834 #endif /* !MSDOS */
836 /* Block SIGINT. */
837 void
838 block_interrupt_signal (sigset_t *oldset)
840 sigset_t blocked;
841 sigemptyset (&blocked);
842 sigaddset (&blocked, SIGINT);
843 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
846 /* Restore previously saved signal mask. */
847 void
848 restore_signal_mask (sigset_t const *oldset)
850 pthread_sigmask (SIG_SETMASK, oldset, 0);
854 /* Saving and restoring the process group of Emacs's terminal. */
856 /* The process group of which Emacs was a member when it initially
857 started.
859 If Emacs was in its own process group (i.e. inherited_pgroup ==
860 getpid ()), then we know we're running under a shell with job
861 control (Emacs would never be run as part of a pipeline).
862 Everything is fine.
864 If Emacs was not in its own process group, then we know we're
865 running under a shell (or a caller) that doesn't know how to
866 separate itself from Emacs (like sh). Emacs must be in its own
867 process group in order to receive SIGIO correctly. In this
868 situation, we put ourselves in our own pgroup, forcibly set the
869 tty's pgroup to our pgroup, and make sure to restore and reinstate
870 the tty's pgroup just like any other terminal setting. If
871 inherited_group was not the tty's pgroup, then we'll get a
872 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
873 it goes foreground in the future, which is what should happen. */
875 static pid_t inherited_pgroup;
877 void
878 init_foreground_group (void)
880 pid_t pgrp = getpgrp ();
881 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
884 /* Block and unblock SIGTTOU. */
886 void
887 block_tty_out_signal (sigset_t *oldset)
889 #ifdef SIGTTOU
890 sigset_t blocked;
891 sigemptyset (&blocked);
892 sigaddset (&blocked, SIGTTOU);
893 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
894 #endif
897 void
898 unblock_tty_out_signal (sigset_t const *oldset)
900 #ifdef SIGTTOU
901 pthread_sigmask (SIG_SETMASK, oldset, 0);
902 #endif
905 /* Safely set a controlling terminal FD's process group to PGID.
906 If we are not in the foreground already, POSIX requires tcsetpgrp
907 to deliver a SIGTTOU signal, which would stop us. This is an
908 annoyance, so temporarily ignore the signal.
910 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
911 skip all this unless SIGTTOU is defined. */
912 static void
913 tcsetpgrp_without_stopping (int fd, pid_t pgid)
915 #ifdef SIGTTOU
916 sigset_t oldset;
917 block_input ();
918 block_tty_out_signal (&oldset);
919 tcsetpgrp (fd, pgid);
920 unblock_tty_out_signal (&oldset);
921 unblock_input ();
922 #endif
925 /* Split off the foreground process group to Emacs alone. When we are
926 in the foreground, but not started in our own process group,
927 redirect the tty device handle FD to point to our own process
928 group. FD must be the file descriptor of the controlling tty. */
929 static void
930 narrow_foreground_group (int fd)
932 if (inherited_pgroup && setpgid (0, 0) == 0)
933 tcsetpgrp_without_stopping (fd, getpid ());
936 /* Set the tty to our original foreground group. */
937 static void
938 widen_foreground_group (int fd)
940 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
941 tcsetpgrp_without_stopping (fd, inherited_pgroup);
944 /* Getting and setting emacs_tty structures. */
946 /* Set *TC to the parameters associated with the terminal FD,
947 or clear it if the parameters are not available.
948 Return 0 on success, -1 on failure. */
950 emacs_get_tty (int fd, struct emacs_tty *settings)
952 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
953 memset (&settings->main, 0, sizeof (settings->main));
954 #ifdef DOS_NT
955 #ifdef WINDOWSNT
956 HANDLE h = (HANDLE)_get_osfhandle (fd);
957 DWORD console_mode;
959 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
961 settings->main = console_mode;
962 return 0;
964 #endif /* WINDOWSNT */
965 return -1;
966 #else /* !DOS_NT */
967 /* We have those nifty POSIX tcmumbleattr functions. */
968 return tcgetattr (fd, &settings->main);
969 #endif
973 /* Set the parameters of the tty on FD according to the contents of
974 *SETTINGS. If FLUSHP, discard input.
975 Return 0 if all went well, and -1 (setting errno) if anything failed. */
978 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
980 /* Set the primary parameters - baud rate, character size, etcetera. */
981 #ifdef DOS_NT
982 #ifdef WINDOWSNT
983 HANDLE h = (HANDLE)_get_osfhandle (fd);
985 if (h && h != INVALID_HANDLE_VALUE)
987 DWORD new_mode;
989 /* Assume the handle is open for input. */
990 if (flushp)
991 FlushConsoleInputBuffer (h);
992 new_mode = settings->main;
993 SetConsoleMode (h, new_mode);
995 #endif /* WINDOWSNT */
996 #else /* !DOS_NT */
997 int i;
998 /* We have those nifty POSIX tcmumbleattr functions.
999 William J. Smith <wjs@wiis.wang.com> writes:
1000 "POSIX 1003.1 defines tcsetattr to return success if it was
1001 able to perform any of the requested actions, even if some
1002 of the requested actions could not be performed.
1003 We must read settings back to ensure tty setup properly.
1004 AIX requires this to keep tty from hanging occasionally." */
1005 /* This make sure that we don't loop indefinitely in here. */
1006 for (i = 0 ; i < 10 ; i++)
1007 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
1009 if (errno == EINTR)
1010 continue;
1011 else
1012 return -1;
1014 else
1016 struct termios new;
1018 memset (&new, 0, sizeof (new));
1019 /* Get the current settings, and see if they're what we asked for. */
1020 tcgetattr (fd, &new);
1021 /* We cannot use memcmp on the whole structure here because under
1022 * aix386 the termios structure has some reserved field that may
1023 * not be filled in.
1025 if ( new.c_iflag == settings->main.c_iflag
1026 && new.c_oflag == settings->main.c_oflag
1027 && new.c_cflag == settings->main.c_cflag
1028 && new.c_lflag == settings->main.c_lflag
1029 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
1030 break;
1031 else
1032 continue;
1034 #endif
1036 /* We have survived the tempest. */
1037 return 0;
1042 #ifdef F_SETOWN
1043 static int old_fcntl_owner[FD_SETSIZE];
1044 #endif /* F_SETOWN */
1046 /* This may also be defined in stdio,
1047 but if so, this does no harm,
1048 and using the same name avoids wasting the other one's space. */
1050 #if defined (USG)
1051 unsigned char _sobuf[BUFSIZ+8];
1052 #else
1053 char _sobuf[BUFSIZ];
1054 #endif
1056 /* Initialize the terminal mode on all tty devices that are currently
1057 open. */
1059 void
1060 init_all_sys_modes (void)
1062 struct tty_display_info *tty;
1063 for (tty = tty_list; tty; tty = tty->next)
1064 init_sys_modes (tty);
1067 /* Initialize the terminal mode on the given tty device. */
1069 void
1070 init_sys_modes (struct tty_display_info *tty_out)
1072 struct emacs_tty tty;
1073 #ifndef DOS_NT
1074 Lisp_Object terminal;
1075 #endif
1077 Vtty_erase_char = Qnil;
1079 if (noninteractive)
1080 return;
1082 if (!tty_out->output)
1083 return; /* The tty is suspended. */
1085 narrow_foreground_group (fileno (tty_out->input));
1087 if (! tty_out->old_tty)
1088 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1090 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1092 tty = *tty_out->old_tty;
1094 #if !defined (DOS_NT)
1095 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1097 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1098 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1099 #ifdef INLCR /* I'm just being cautious,
1100 since I can't check how widespread INLCR is--rms. */
1101 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1102 #endif
1103 #ifdef ISTRIP
1104 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1105 #endif
1106 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1107 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1108 #ifdef IEXTEN
1109 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1110 #endif
1111 tty.main.c_lflag |= ISIG; /* Enable signals */
1112 if (tty_out->flow_control)
1114 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1115 #ifdef IXANY
1116 tty.main.c_iflag &= ~IXANY;
1117 #endif /* IXANY */
1119 else
1120 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1121 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1122 on output */
1123 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1124 #ifdef CS8
1125 if (tty_out->meta_key)
1127 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1128 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1130 #endif
1132 XSETTERMINAL(terminal, tty_out->terminal);
1133 if (!NILP (Fcontrolling_tty_p (terminal)))
1135 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1136 /* Set up C-g for both SIGQUIT and SIGINT.
1137 We don't know which we will get, but we handle both alike
1138 so which one it really gives us does not matter. */
1139 tty.main.c_cc[VQUIT] = quit_char;
1141 else
1143 /* We normally don't get interrupt or quit signals from tty
1144 devices other than our controlling terminal; therefore,
1145 we must handle C-g as normal input. Unfortunately, this
1146 means that the interrupt and quit feature must be
1147 disabled on secondary ttys, or we would not even see the
1148 keypress.
1150 Note that even though emacsclient could have special code
1151 to pass SIGINT to Emacs, we should _not_ enable
1152 interrupt/quit keys for emacsclient frames. This means
1153 that we can't break out of loops in C code from a
1154 secondary tty frame, but we can always decide what
1155 display the C-g came from, which is more important from a
1156 usability point of view. (Consider the case when two
1157 people work together using the same Emacs instance.) */
1158 tty.main.c_cc[VINTR] = CDISABLE;
1159 tty.main.c_cc[VQUIT] = CDISABLE;
1161 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1162 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1163 #ifdef VSWTCH
1164 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1165 of C-z */
1166 #endif /* VSWTCH */
1168 #ifdef VSUSP
1169 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1170 #endif /* VSUSP */
1171 #ifdef V_DSUSP
1172 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1173 #endif /* V_DSUSP */
1174 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1175 tty.main.c_cc[VDSUSP] = CDISABLE;
1176 #endif /* VDSUSP */
1177 #ifdef VLNEXT
1178 tty.main.c_cc[VLNEXT] = CDISABLE;
1179 #endif /* VLNEXT */
1180 #ifdef VREPRINT
1181 tty.main.c_cc[VREPRINT] = CDISABLE;
1182 #endif /* VREPRINT */
1183 #ifdef VWERASE
1184 tty.main.c_cc[VWERASE] = CDISABLE;
1185 #endif /* VWERASE */
1186 #ifdef VDISCARD
1187 tty.main.c_cc[VDISCARD] = CDISABLE;
1188 #endif /* VDISCARD */
1190 if (tty_out->flow_control)
1192 #ifdef VSTART
1193 tty.main.c_cc[VSTART] = '\021';
1194 #endif /* VSTART */
1195 #ifdef VSTOP
1196 tty.main.c_cc[VSTOP] = '\023';
1197 #endif /* VSTOP */
1199 else
1201 #ifdef VSTART
1202 tty.main.c_cc[VSTART] = CDISABLE;
1203 #endif /* VSTART */
1204 #ifdef VSTOP
1205 tty.main.c_cc[VSTOP] = CDISABLE;
1206 #endif /* VSTOP */
1209 #ifdef AIX
1210 tty.main.c_cc[VSTRT] = CDISABLE;
1211 tty.main.c_cc[VSTOP] = CDISABLE;
1212 tty.main.c_cc[VSUSP] = CDISABLE;
1213 tty.main.c_cc[VDSUSP] = CDISABLE;
1214 if (tty_out->flow_control)
1216 #ifdef VSTART
1217 tty.main.c_cc[VSTART] = '\021';
1218 #endif /* VSTART */
1219 #ifdef VSTOP
1220 tty.main.c_cc[VSTOP] = '\023';
1221 #endif /* VSTOP */
1223 /* Also, PTY overloads NUL and BREAK.
1224 don't ignore break, but don't signal either, so it looks like NUL.
1225 This really serves a purpose only if running in an XTERM window
1226 or via TELNET or the like, but does no harm elsewhere. */
1227 tty.main.c_iflag &= ~IGNBRK;
1228 tty.main.c_iflag &= ~BRKINT;
1229 #endif
1230 #endif /* not DOS_NT */
1232 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1233 if (!tty_out->term_initted)
1234 internal_terminal_init ();
1235 dos_ttraw (tty_out);
1236 #endif
1238 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1240 /* This code added to insure that, if flow-control is not to be used,
1241 we have an unlocked terminal at the start. */
1243 #ifdef TCXONC
1244 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1245 #endif
1246 #ifdef TIOCSTART
1247 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1248 #endif
1250 #if !defined (DOS_NT)
1251 #ifdef TCOON
1252 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1253 #endif
1254 #endif
1256 #ifdef F_GETOWN
1257 if (interrupt_input)
1259 old_fcntl_owner[fileno (tty_out->input)] =
1260 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1261 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1262 init_sigio (fileno (tty_out->input));
1263 #ifdef HAVE_GPM
1264 if (gpm_tty == tty_out)
1266 /* Arrange for mouse events to give us SIGIO signals. */
1267 fcntl (gpm_fd, F_SETOWN, getpid ());
1268 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1269 init_sigio (gpm_fd);
1271 #endif /* HAVE_GPM */
1273 #endif /* F_GETOWN */
1275 #ifdef _IOFBF
1276 /* This symbol is defined on recent USG systems.
1277 Someone says without this call USG won't really buffer the file
1278 even with a call to setbuf. */
1279 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1280 #else
1281 setbuf (tty_out->output, (char *) _sobuf);
1282 #endif
1284 if (tty_out->terminal->set_terminal_modes_hook)
1285 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1287 if (!tty_out->term_initted)
1289 Lisp_Object tail, frame;
1290 FOR_EACH_FRAME (tail, frame)
1292 /* XXX This needs to be revised. */
1293 if (FRAME_TERMCAP_P (XFRAME (frame))
1294 && FRAME_TTY (XFRAME (frame)) == tty_out)
1295 init_frame_faces (XFRAME (frame));
1299 if (tty_out->term_initted && no_redraw_on_reenter)
1301 /* We used to call "direct_output_forward_char(0)" here,
1302 but it's not clear why, since it may not do anything anyway. */
1304 else
1306 Lisp_Object tail, frame;
1307 frame_garbaged = 1;
1308 FOR_EACH_FRAME (tail, frame)
1310 if ((FRAME_TERMCAP_P (XFRAME (frame))
1311 || FRAME_MSDOS_P (XFRAME (frame)))
1312 && FRAME_TTY (XFRAME (frame)) == tty_out)
1313 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1317 tty_out->term_initted = 1;
1320 /* Return true if safe to use tabs in output.
1321 At the time this is called, init_sys_modes has not been done yet. */
1323 bool
1324 tabs_safe_p (int fd)
1326 struct emacs_tty etty;
1328 emacs_get_tty (fd, &etty);
1329 #ifndef DOS_NT
1330 #ifdef TABDLY
1331 return ((etty.main.c_oflag & TABDLY) != TAB3);
1332 #else /* not TABDLY */
1333 return 1;
1334 #endif /* not TABDLY */
1335 #else /* DOS_NT */
1336 return 0;
1337 #endif /* DOS_NT */
1340 /* Discard echoing. */
1342 void
1343 suppress_echo_on_tty (int fd)
1345 struct emacs_tty etty;
1347 emacs_get_tty (fd, &etty);
1348 #ifdef DOS_NT
1349 /* Set raw input mode. */
1350 etty.main = 0;
1351 #else
1352 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1353 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1354 #endif /* ! WINDOWSNT */
1355 emacs_set_tty (fd, &etty, 0);
1358 /* Get terminal size from system.
1359 Store number of lines into *HEIGHTP and width into *WIDTHP.
1360 We store 0 if there's no valid information. */
1362 void
1363 get_tty_size (int fd, int *widthp, int *heightp)
1365 #if defined TIOCGWINSZ
1367 /* BSD-style. */
1368 struct winsize size;
1370 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1371 *widthp = *heightp = 0;
1372 else
1374 *widthp = size.ws_col;
1375 *heightp = size.ws_row;
1378 #elif defined TIOCGSIZE
1380 /* SunOS - style. */
1381 struct ttysize size;
1383 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1384 *widthp = *heightp = 0;
1385 else
1387 *widthp = size.ts_cols;
1388 *heightp = size.ts_lines;
1391 #elif defined WINDOWSNT
1393 CONSOLE_SCREEN_BUFFER_INFO info;
1394 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1396 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1397 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1399 else
1400 *widthp = *heightp = 0;
1402 #elif defined MSDOS
1404 *widthp = ScreenCols ();
1405 *heightp = ScreenRows ();
1407 #else /* system doesn't know size */
1409 *widthp = 0;
1410 *heightp = 0;
1412 #endif
1415 /* Set the logical window size associated with descriptor FD
1416 to HEIGHT and WIDTH. This is used mainly with ptys.
1417 Return a negative value on failure. */
1420 set_window_size (int fd, int height, int width)
1422 #ifdef TIOCSWINSZ
1424 /* BSD-style. */
1425 struct winsize size;
1426 size.ws_row = height;
1427 size.ws_col = width;
1429 return ioctl (fd, TIOCSWINSZ, &size);
1431 #else
1432 #ifdef TIOCSSIZE
1434 /* SunOS - style. */
1435 struct ttysize size;
1436 size.ts_lines = height;
1437 size.ts_cols = width;
1439 return ioctl (fd, TIOCGSIZE, &size);
1440 #else
1441 return -1;
1442 #endif /* not SunOS-style */
1443 #endif /* not BSD-style */
1448 /* Prepare all terminal devices for exiting Emacs. */
1450 void
1451 reset_all_sys_modes (void)
1453 struct tty_display_info *tty;
1454 for (tty = tty_list; tty; tty = tty->next)
1455 reset_sys_modes (tty);
1458 /* Prepare the terminal for closing it; move the cursor to the
1459 bottom of the frame, turn off interrupt-driven I/O, etc. */
1461 void
1462 reset_sys_modes (struct tty_display_info *tty_out)
1464 if (noninteractive)
1466 fflush_unlocked (stdout);
1467 return;
1469 if (!tty_out->term_initted)
1470 return;
1472 if (!tty_out->output)
1473 return; /* The tty is suspended. */
1475 /* Go to and clear the last line of the terminal. */
1477 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1479 /* Code adapted from tty_clear_end_of_line. */
1480 if (tty_out->TS_clr_line)
1482 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1484 else
1485 { /* have to do it the hard way */
1486 tty_turn_off_insert (tty_out);
1488 for (int i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1489 fputc_unlocked (' ', tty_out->output);
1492 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1493 fflush_unlocked (tty_out->output);
1495 if (tty_out->terminal->reset_terminal_modes_hook)
1496 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1498 /* Avoid possible loss of output when changing terminal modes. */
1499 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1500 continue;
1502 #ifndef DOS_NT
1503 #ifdef F_SETOWN
1504 if (interrupt_input)
1506 reset_sigio (fileno (tty_out->input));
1507 fcntl (fileno (tty_out->input), F_SETOWN,
1508 old_fcntl_owner[fileno (tty_out->input)]);
1510 #endif /* F_SETOWN */
1511 fcntl (fileno (tty_out->input), F_SETFL,
1512 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1513 #endif
1515 if (tty_out->old_tty)
1516 while (emacs_set_tty (fileno (tty_out->input),
1517 tty_out->old_tty, 0) < 0 && errno == EINTR)
1520 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1521 dos_ttcooked ();
1522 #endif
1524 widen_foreground_group (fileno (tty_out->input));
1527 #ifdef HAVE_PTYS
1529 /* Set up the proper status flags for use of a pty. */
1531 void
1532 setup_pty (int fd)
1534 /* I'm told that TOICREMOTE does not mean control chars
1535 "can't be sent" but rather that they don't have
1536 input-editing or signaling effects.
1537 That should be good, because we have other ways
1538 to do those things in Emacs.
1539 However, telnet mode seems not to work on 4.2.
1540 So TIOCREMOTE is turned off now. */
1542 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1543 will hang. In particular, the "timeout" feature (which
1544 causes a read to return if there is no data available)
1545 does this. Also it is known that telnet mode will hang
1546 in such a way that Emacs must be stopped (perhaps this
1547 is the same problem).
1549 If TIOCREMOTE is turned off, then there is a bug in
1550 hp-ux which sometimes loses data. Apparently the
1551 code which blocks the master process when the internal
1552 buffer fills up does not work. Other than this,
1553 though, everything else seems to work fine.
1555 Since the latter lossage is more benign, we may as well
1556 lose that way. -- cph */
1557 #ifdef FIONBIO
1558 #if defined (UNIX98_PTYS)
1560 int on = 1;
1561 ioctl (fd, FIONBIO, &on);
1563 #endif
1564 #endif
1566 #endif /* HAVE_PTYS */
1568 void
1569 init_system_name (void)
1571 if (!build_details)
1573 /* Set system-name to nil so that the build is deterministic. */
1574 Vsystem_name = Qnil;
1575 return;
1577 char *hostname_alloc = NULL;
1578 char *hostname;
1579 #ifndef HAVE_GETHOSTNAME
1580 struct utsname uts;
1581 uname (&uts);
1582 hostname = uts.nodename;
1583 #else /* HAVE_GETHOSTNAME */
1584 char hostname_buf[256];
1585 ptrdiff_t hostname_size = sizeof hostname_buf;
1586 hostname = hostname_buf;
1588 /* Try to get the host name; if the buffer is too short, try
1589 again. Apparently, the only indication gethostname gives of
1590 whether the buffer was large enough is the presence or absence
1591 of a '\0' in the string. Eech. */
1592 for (;;)
1594 gethostname (hostname, hostname_size - 1);
1595 hostname[hostname_size - 1] = '\0';
1597 /* Was the buffer large enough for the '\0'? */
1598 if (strlen (hostname) < hostname_size - 1)
1599 break;
1601 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1602 min (PTRDIFF_MAX, SIZE_MAX), 1);
1604 #endif /* HAVE_GETHOSTNAME */
1605 char *p;
1606 for (p = hostname; *p; p++)
1607 if (*p == ' ' || *p == '\t')
1608 *p = '-';
1609 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1610 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1611 Vsystem_name = build_string (hostname);
1612 xfree (hostname_alloc);
1615 sigset_t empty_mask;
1617 static struct sigaction process_fatal_action;
1619 static int
1620 emacs_sigaction_flags (void)
1622 #ifdef SA_RESTART
1623 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1624 'select') to reset their timeout on some platforms (e.g.,
1625 HP-UX 11), which is not what we want. Also, when Emacs is
1626 interactive, we don't want SA_RESTART because we need to poll
1627 for pending input so we need long-running syscalls to be interrupted
1628 after a signal that sets pending_signals.
1630 Non-interactive keyboard input goes through stdio, where we
1631 always want restartable system calls. */
1632 if (noninteractive)
1633 return SA_RESTART;
1634 #endif
1635 return 0;
1638 /* Store into *ACTION a signal action suitable for Emacs, with handler
1639 HANDLER. */
1640 void
1641 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1643 sigemptyset (&action->sa_mask);
1645 /* When handling a signal, block nonfatal system signals that are caught
1646 by Emacs. This makes race conditions less likely. */
1647 sigaddset (&action->sa_mask, SIGALRM);
1648 #ifdef SIGCHLD
1649 sigaddset (&action->sa_mask, SIGCHLD);
1650 #endif
1651 #ifdef SIGDANGER
1652 sigaddset (&action->sa_mask, SIGDANGER);
1653 #endif
1654 #ifdef PROFILER_CPU_SUPPORT
1655 sigaddset (&action->sa_mask, SIGPROF);
1656 #endif
1657 #ifdef SIGWINCH
1658 sigaddset (&action->sa_mask, SIGWINCH);
1659 #endif
1660 if (! noninteractive)
1662 sigaddset (&action->sa_mask, SIGINT);
1663 sigaddset (&action->sa_mask, SIGQUIT);
1664 #ifdef USABLE_SIGIO
1665 sigaddset (&action->sa_mask, SIGIO);
1666 #endif
1669 action->sa_handler = handler;
1670 action->sa_flags = emacs_sigaction_flags ();
1673 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1674 static pthread_t main_thread_id;
1675 #endif
1677 /* SIG has arrived at the current process. Deliver it to the main
1678 thread, which should handle it with HANDLER. (Delivering the
1679 signal to some other thread might not work if the other thread is
1680 about to exit.)
1682 If we are on the main thread, handle the signal SIG with HANDLER.
1683 Otherwise, redirect the signal to the main thread, blocking it from
1684 this thread. POSIX says any thread can receive a signal that is
1685 associated with a process, process group, or asynchronous event.
1686 On GNU/Linux the main thread typically gets a process signal unless
1687 it's blocked, but other systems (FreeBSD at least) can deliver the
1688 signal to other threads. */
1689 void
1690 deliver_process_signal (int sig, signal_handler_t handler)
1692 /* Preserve errno, to avoid race conditions with signal handlers that
1693 might change errno. Races can occur even in single-threaded hosts. */
1694 int old_errno = errno;
1696 bool on_main_thread = true;
1697 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1698 if (! pthread_equal (pthread_self (), main_thread_id))
1700 sigset_t blocked;
1701 sigemptyset (&blocked);
1702 sigaddset (&blocked, sig);
1703 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1704 pthread_kill (main_thread_id, sig);
1705 on_main_thread = false;
1707 #endif
1708 if (on_main_thread)
1709 handler (sig);
1711 errno = old_errno;
1714 /* Static location to save a fatal backtrace in a thread.
1715 FIXME: If two subsidiary threads fail simultaneously, the resulting
1716 backtrace may be garbage. */
1717 enum { BACKTRACE_LIMIT_MAX = 500 };
1718 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1719 static int thread_backtrace_npointers;
1721 /* SIG has arrived at the current thread.
1722 If we are on the main thread, handle the signal SIG with HANDLER.
1723 Otherwise, this is a fatal error in the handling thread. */
1724 static void
1725 deliver_thread_signal (int sig, signal_handler_t handler)
1727 int old_errno = errno;
1729 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1730 if (! pthread_equal (pthread_self (), main_thread_id))
1732 thread_backtrace_npointers
1733 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1734 sigaction (sig, &process_fatal_action, 0);
1735 pthread_kill (main_thread_id, sig);
1737 /* Avoid further damage while the main thread is exiting. */
1738 while (1)
1739 sigsuspend (&empty_mask);
1741 #endif
1743 handler (sig);
1744 errno = old_errno;
1747 #if !HAVE_DECL_SYS_SIGLIST
1748 # undef sys_siglist
1749 # ifdef _sys_siglist
1750 # define sys_siglist _sys_siglist
1751 # elif HAVE_DECL___SYS_SIGLIST
1752 # define sys_siglist __sys_siglist
1753 # else
1754 # define sys_siglist my_sys_siglist
1755 static char const *sys_siglist[NSIG];
1756 # endif
1757 #endif
1759 #ifdef _sys_nsig
1760 # define sys_siglist_entries _sys_nsig
1761 #else
1762 # define sys_siglist_entries NSIG
1763 #endif
1765 /* Handle bus errors, invalid instruction, etc. */
1766 static void
1767 handle_fatal_signal (int sig)
1769 terminate_due_to_signal (sig, 40);
1772 static void
1773 deliver_fatal_signal (int sig)
1775 deliver_process_signal (sig, handle_fatal_signal);
1778 static void
1779 deliver_fatal_thread_signal (int sig)
1781 deliver_thread_signal (sig, handle_fatal_signal);
1784 static _Noreturn void
1785 handle_arith_signal (int sig)
1787 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1788 xsignal0 (Qarith_error);
1791 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1793 /* Alternate stack used by SIGSEGV handler below. */
1795 static unsigned char sigsegv_stack[SIGSTKSZ];
1798 /* Return true if SIGINFO indicates a stack overflow. */
1800 static bool
1801 stack_overflow (siginfo_t *siginfo)
1803 if (!attempt_stack_overflow_recovery)
1804 return false;
1806 /* In theory, a more-accurate heuristic can be obtained by using
1807 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1808 and pthread_attr_getguardsize to find the location and size of the
1809 guard area. In practice, though, these functions are so hard to
1810 use reliably that they're not worth bothering with. E.g., see:
1811 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1812 Other operating systems also have problems, e.g., Solaris's
1813 stack_violation function is tailor-made for this problem, but it
1814 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1816 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1817 candidate here. */
1819 if (!siginfo)
1820 return false;
1822 /* The faulting address. */
1823 char *addr = siginfo->si_addr;
1824 if (!addr)
1825 return false;
1827 /* The known top and bottom of the stack. The actual stack may
1828 extend a bit beyond these boundaries. */
1829 char *bot = stack_bottom;
1830 char *top = current_thread->stack_top;
1832 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1833 of the known stack divided by the size of the guard area past the
1834 end of the stack top. The heuristic is that a bad address is
1835 considered to be a stack overflow if it occurs within
1836 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1837 stack. This heuristic is not exactly correct but it's good
1838 enough in practice. */
1839 enum { LG_STACK_HEURISTIC = 8 };
1841 if (bot < top)
1842 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1843 else
1844 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1848 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1850 static void
1851 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1853 /* Hard GC error may lead to stack overflow caused by
1854 too nested calls to mark_object. No way to survive. */
1855 bool fatal = gc_in_progress;
1857 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1858 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1859 fatal = true;
1860 #endif
1862 if (!fatal && stack_overflow (siginfo))
1863 siglongjmp (return_to_command_loop, 1);
1865 /* Otherwise we can't do anything with this. */
1866 deliver_fatal_thread_signal (sig);
1869 /* Return true if we have successfully set up SIGSEGV handler on alternate
1870 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1872 static bool
1873 init_sigsegv (void)
1875 struct sigaction sa;
1876 stack_t ss;
1878 ss.ss_sp = sigsegv_stack;
1879 ss.ss_size = sizeof (sigsegv_stack);
1880 ss.ss_flags = 0;
1881 if (sigaltstack (&ss, NULL) < 0)
1882 return 0;
1884 sigfillset (&sa.sa_mask);
1885 sa.sa_sigaction = handle_sigsegv;
1886 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1887 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1890 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1892 static bool
1893 init_sigsegv (void)
1895 return 0;
1898 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1900 static void
1901 deliver_arith_signal (int sig)
1903 deliver_thread_signal (sig, handle_arith_signal);
1906 #ifdef SIGDANGER
1908 /* Handler for SIGDANGER. */
1909 static void
1910 handle_danger_signal (int sig)
1912 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1914 /* It might be unsafe to call do_auto_save now. */
1915 force_auto_save_soon ();
1918 static void
1919 deliver_danger_signal (int sig)
1921 deliver_process_signal (sig, handle_danger_signal);
1923 #endif
1925 /* Treat SIG as a terminating signal, unless it is already ignored and
1926 we are in --batch mode. Among other things, this makes nohup work. */
1927 static void
1928 maybe_fatal_sig (int sig)
1930 bool catch_sig = !noninteractive;
1931 if (!catch_sig)
1933 struct sigaction old_action;
1934 sigaction (sig, 0, &old_action);
1935 catch_sig = old_action.sa_handler != SIG_IGN;
1937 if (catch_sig)
1938 sigaction (sig, &process_fatal_action, 0);
1941 void
1942 init_signals (bool dumping)
1944 struct sigaction thread_fatal_action;
1945 struct sigaction action;
1947 sigemptyset (&empty_mask);
1949 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1950 main_thread_id = pthread_self ();
1951 #endif
1953 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1954 if (! initialized)
1956 sys_siglist[SIGABRT] = "Aborted";
1957 # ifdef SIGAIO
1958 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1959 # endif
1960 sys_siglist[SIGALRM] = "Alarm clock";
1961 # ifdef SIGBUS
1962 sys_siglist[SIGBUS] = "Bus error";
1963 # endif
1964 # ifdef SIGCHLD
1965 sys_siglist[SIGCHLD] = "Child status changed";
1966 # endif
1967 # ifdef SIGCONT
1968 sys_siglist[SIGCONT] = "Continued";
1969 # endif
1970 # ifdef SIGDANGER
1971 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1972 # endif
1973 # ifdef SIGDGNOTIFY
1974 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1975 # endif
1976 # ifdef SIGEMT
1977 sys_siglist[SIGEMT] = "Emulation trap";
1978 # endif
1979 sys_siglist[SIGFPE] = "Arithmetic exception";
1980 # ifdef SIGFREEZE
1981 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1982 # endif
1983 # ifdef SIGGRANT
1984 sys_siglist[SIGGRANT] = "Monitor mode granted";
1985 # endif
1986 sys_siglist[SIGHUP] = "Hangup";
1987 sys_siglist[SIGILL] = "Illegal instruction";
1988 sys_siglist[SIGINT] = "Interrupt";
1989 # ifdef SIGIO
1990 sys_siglist[SIGIO] = "I/O possible";
1991 # endif
1992 # ifdef SIGIOINT
1993 sys_siglist[SIGIOINT] = "I/O intervention required";
1994 # endif
1995 # ifdef SIGIOT
1996 sys_siglist[SIGIOT] = "IOT trap";
1997 # endif
1998 sys_siglist[SIGKILL] = "Killed";
1999 # ifdef SIGLOST
2000 sys_siglist[SIGLOST] = "Resource lost";
2001 # endif
2002 # ifdef SIGLWP
2003 sys_siglist[SIGLWP] = "SIGLWP";
2004 # endif
2005 # ifdef SIGMSG
2006 sys_siglist[SIGMSG] = "Monitor mode data available";
2007 # endif
2008 # ifdef SIGPHONE
2009 sys_siglist[SIGWIND] = "SIGPHONE";
2010 # endif
2011 sys_siglist[SIGPIPE] = "Broken pipe";
2012 # ifdef SIGPOLL
2013 sys_siglist[SIGPOLL] = "Pollable event occurred";
2014 # endif
2015 # ifdef SIGPROF
2016 sys_siglist[SIGPROF] = "Profiling timer expired";
2017 # endif
2018 # ifdef SIGPTY
2019 sys_siglist[SIGPTY] = "PTY I/O interrupt";
2020 # endif
2021 # ifdef SIGPWR
2022 sys_siglist[SIGPWR] = "Power-fail restart";
2023 # endif
2024 sys_siglist[SIGQUIT] = "Quit";
2025 # ifdef SIGRETRACT
2026 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
2027 # endif
2028 # ifdef SIGSAK
2029 sys_siglist[SIGSAK] = "Secure attention";
2030 # endif
2031 sys_siglist[SIGSEGV] = "Segmentation violation";
2032 # ifdef SIGSOUND
2033 sys_siglist[SIGSOUND] = "Sound completed";
2034 # endif
2035 # ifdef SIGSTOP
2036 sys_siglist[SIGSTOP] = "Stopped (signal)";
2037 # endif
2038 # ifdef SIGSTP
2039 sys_siglist[SIGSTP] = "Stopped (user)";
2040 # endif
2041 # ifdef SIGSYS
2042 sys_siglist[SIGSYS] = "Bad argument to system call";
2043 # endif
2044 sys_siglist[SIGTERM] = "Terminated";
2045 # ifdef SIGTHAW
2046 sys_siglist[SIGTHAW] = "SIGTHAW";
2047 # endif
2048 # ifdef SIGTRAP
2049 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2050 # endif
2051 # ifdef SIGTSTP
2052 sys_siglist[SIGTSTP] = "Stopped (user)";
2053 # endif
2054 # ifdef SIGTTIN
2055 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2056 # endif
2057 # ifdef SIGTTOU
2058 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2059 # endif
2060 # ifdef SIGURG
2061 sys_siglist[SIGURG] = "Urgent I/O condition";
2062 # endif
2063 # ifdef SIGUSR1
2064 sys_siglist[SIGUSR1] = "User defined signal 1";
2065 # endif
2066 # ifdef SIGUSR2
2067 sys_siglist[SIGUSR2] = "User defined signal 2";
2068 # endif
2069 # ifdef SIGVTALRM
2070 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2071 # endif
2072 # ifdef SIGWAITING
2073 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2074 # endif
2075 # ifdef SIGWINCH
2076 sys_siglist[SIGWINCH] = "Window size changed";
2077 # endif
2078 # ifdef SIGWIND
2079 sys_siglist[SIGWIND] = "SIGWIND";
2080 # endif
2081 # ifdef SIGXCPU
2082 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2083 # endif
2084 # ifdef SIGXFSZ
2085 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2086 # endif
2088 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2090 /* Don't alter signal handlers if dumping. On some machines,
2091 changing signal handlers sets static data that would make signals
2092 fail to work right when the dumped Emacs is run. */
2093 if (dumping)
2094 return;
2096 sigfillset (&process_fatal_action.sa_mask);
2097 process_fatal_action.sa_handler = deliver_fatal_signal;
2098 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2100 sigfillset (&thread_fatal_action.sa_mask);
2101 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2102 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2104 /* SIGINT may need special treatment on MS-Windows. See
2105 https://lists.gnu.org/r/emacs-devel/2010-09/msg01062.html
2106 Please update the doc of kill-emacs, kill-emacs-hook, and
2107 NEWS if you change this. */
2109 maybe_fatal_sig (SIGHUP);
2110 maybe_fatal_sig (SIGINT);
2111 maybe_fatal_sig (SIGTERM);
2113 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2114 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2115 to behave more like typical batch applications do. */
2116 if (! noninteractive)
2117 signal (SIGPIPE, SIG_IGN);
2119 sigaction (SIGQUIT, &process_fatal_action, 0);
2120 sigaction (SIGILL, &thread_fatal_action, 0);
2121 sigaction (SIGTRAP, &thread_fatal_action, 0);
2123 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2124 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2125 interpreter's floating point operations, so treat SIGFPE as an
2126 arith-error if it arises in the main thread. */
2127 if (IEEE_FLOATING_POINT)
2128 sigaction (SIGFPE, &thread_fatal_action, 0);
2129 else
2131 emacs_sigaction_init (&action, deliver_arith_signal);
2132 sigaction (SIGFPE, &action, 0);
2135 #ifdef SIGUSR1
2136 add_user_signal (SIGUSR1, "sigusr1");
2137 #endif
2138 #ifdef SIGUSR2
2139 add_user_signal (SIGUSR2, "sigusr2");
2140 #endif
2141 sigaction (SIGABRT, &thread_fatal_action, 0);
2142 #ifdef SIGPRE
2143 sigaction (SIGPRE, &thread_fatal_action, 0);
2144 #endif
2145 #ifdef SIGORE
2146 sigaction (SIGORE, &thread_fatal_action, 0);
2147 #endif
2148 #ifdef SIGUME
2149 sigaction (SIGUME, &thread_fatal_action, 0);
2150 #endif
2151 #ifdef SIGDLK
2152 sigaction (SIGDLK, &process_fatal_action, 0);
2153 #endif
2154 #ifdef SIGCPULIM
2155 sigaction (SIGCPULIM, &process_fatal_action, 0);
2156 #endif
2157 #ifdef SIGIOT
2158 sigaction (SIGIOT, &thread_fatal_action, 0);
2159 #endif
2160 #ifdef SIGEMT
2161 sigaction (SIGEMT, &thread_fatal_action, 0);
2162 #endif
2163 #ifdef SIGBUS
2164 sigaction (SIGBUS, &thread_fatal_action, 0);
2165 #endif
2166 if (!init_sigsegv ())
2167 sigaction (SIGSEGV, &thread_fatal_action, 0);
2168 #ifdef SIGSYS
2169 sigaction (SIGSYS, &thread_fatal_action, 0);
2170 #endif
2171 sigaction (SIGTERM, &process_fatal_action, 0);
2172 #ifdef SIGPROF
2173 signal (SIGPROF, SIG_IGN);
2174 #endif
2175 #ifdef SIGVTALRM
2176 sigaction (SIGVTALRM, &process_fatal_action, 0);
2177 #endif
2178 #ifdef SIGXCPU
2179 sigaction (SIGXCPU, &process_fatal_action, 0);
2180 #endif
2181 #ifdef SIGXFSZ
2182 sigaction (SIGXFSZ, &process_fatal_action, 0);
2183 #endif
2185 #ifdef SIGDANGER
2186 /* This just means available memory is getting low. */
2187 emacs_sigaction_init (&action, deliver_danger_signal);
2188 sigaction (SIGDANGER, &action, 0);
2189 #endif
2191 /* AIX-specific signals. */
2192 #ifdef SIGGRANT
2193 sigaction (SIGGRANT, &process_fatal_action, 0);
2194 #endif
2195 #ifdef SIGMIGRATE
2196 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2197 #endif
2198 #ifdef SIGMSG
2199 sigaction (SIGMSG, &process_fatal_action, 0);
2200 #endif
2201 #ifdef SIGRETRACT
2202 sigaction (SIGRETRACT, &process_fatal_action, 0);
2203 #endif
2204 #ifdef SIGSAK
2205 sigaction (SIGSAK, &process_fatal_action, 0);
2206 #endif
2207 #ifdef SIGSOUND
2208 sigaction (SIGSOUND, &process_fatal_action, 0);
2209 #endif
2210 #ifdef SIGTALRM
2211 sigaction (SIGTALRM, &thread_fatal_action, 0);
2212 #endif
2215 #ifndef HAVE_RANDOM
2216 #ifdef random
2217 #define HAVE_RANDOM
2218 #endif
2219 #endif
2221 /* Figure out how many bits the system's random number generator uses.
2222 `random' and `lrand48' are assumed to return 31 usable bits.
2223 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2224 so we'll shift it and treat it like the 15-bit USG `rand'. */
2226 #ifndef RAND_BITS
2227 # ifdef HAVE_RANDOM
2228 # define RAND_BITS 31
2229 # else /* !HAVE_RANDOM */
2230 # ifdef HAVE_LRAND48
2231 # define RAND_BITS 31
2232 # define random lrand48
2233 # else /* !HAVE_LRAND48 */
2234 # define RAND_BITS 15
2235 # if RAND_MAX == 32767
2236 # define random rand
2237 # else /* RAND_MAX != 32767 */
2238 # if RAND_MAX == 2147483647
2239 # define random() (rand () >> 16)
2240 # else /* RAND_MAX != 2147483647 */
2241 # ifdef USG
2242 # define random rand
2243 # else
2244 # define random() (rand () >> 16)
2245 # endif /* !USG */
2246 # endif /* RAND_MAX != 2147483647 */
2247 # endif /* RAND_MAX != 32767 */
2248 # endif /* !HAVE_LRAND48 */
2249 # endif /* !HAVE_RANDOM */
2250 #endif /* !RAND_BITS */
2252 #ifdef HAVE_RANDOM
2253 typedef unsigned int random_seed;
2254 static void set_random_seed (random_seed arg) { srandom (arg); }
2255 #elif defined HAVE_LRAND48
2256 /* Although srand48 uses a long seed, this is unsigned long to avoid
2257 undefined behavior on signed integer overflow in init_random. */
2258 typedef unsigned long int random_seed;
2259 static void set_random_seed (random_seed arg) { srand48 (arg); }
2260 #else
2261 typedef unsigned int random_seed;
2262 static void set_random_seed (random_seed arg) { srand (arg); }
2263 #endif
2265 void
2266 seed_random (void *seed, ptrdiff_t seed_size)
2268 random_seed arg = 0;
2269 unsigned char *argp = (unsigned char *) &arg;
2270 unsigned char *seedp = seed;
2271 for (ptrdiff_t i = 0; i < seed_size; i++)
2272 argp[i % sizeof arg] ^= seedp[i];
2273 set_random_seed (arg);
2276 void
2277 init_random (void)
2279 random_seed v;
2280 bool success = false;
2282 /* First, try seeding the PRNG from the operating system's entropy
2283 source. This approach is both fast and secure. */
2284 #ifdef WINDOWSNT
2285 success = w32_init_random (&v, sizeof v) == 0;
2286 #else
2287 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2288 if (0 <= fd)
2290 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2291 close (fd);
2293 #endif
2295 /* If that didn't work, try using GnuTLS, which is secure, but on
2296 some systems, can be somewhat slow. */
2297 if (!success)
2298 success = EQ (emacs_gnutls_global_init (), Qt)
2299 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2301 /* If _that_ didn't work, just use the current time value and PID.
2302 It's at least better than XKCD 221. */
2303 if (!success)
2305 struct timespec t = current_timespec ();
2306 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2309 set_random_seed (v);
2313 * Return a nonnegative random integer out of whatever we've got.
2314 * It contains enough bits to make a random (signed) Emacs fixnum.
2315 * This suffices even for a 64-bit architecture with a 15-bit rand.
2317 EMACS_INT
2318 get_random (void)
2320 EMACS_UINT val = 0;
2321 int i;
2322 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2323 val = (random () ^ (val << RAND_BITS)
2324 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2325 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2326 return val & INTMASK;
2329 #ifndef HAVE_SNPRINTF
2330 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2332 snprintf (char *buf, size_t bufsize, char const *format, ...)
2334 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2335 ptrdiff_t nbytes = size - 1;
2336 va_list ap;
2338 if (size)
2340 va_start (ap, format);
2341 nbytes = doprnt (buf, size, format, 0, ap);
2342 va_end (ap);
2345 if (nbytes == size - 1)
2347 /* Calculate the length of the string that would have been created
2348 had the buffer been large enough. */
2349 char stackbuf[4000];
2350 char *b = stackbuf;
2351 ptrdiff_t bsize = sizeof stackbuf;
2352 va_start (ap, format);
2353 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2354 va_end (ap);
2355 if (b != stackbuf)
2356 xfree (b);
2359 if (INT_MAX < nbytes)
2361 #ifdef EOVERFLOW
2362 errno = EOVERFLOW;
2363 #else
2364 errno = EDOM;
2365 #endif
2366 return -1;
2368 return nbytes;
2370 #endif
2372 /* If a backtrace is available, output the top lines of it to stderr.
2373 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2374 This function may be called from a signal handler, so it should
2375 not invoke async-unsafe functions like malloc.
2377 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2378 but do not output anything. This avoids some problems that can
2379 otherwise occur if the malloc arena is corrupted before 'backtrace'
2380 is called, since 'backtrace' may call malloc if the tables are not
2381 initialized.
2383 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2384 fatal error has occurred in some other thread; generate a thread
2385 backtrace instead, ignoring BACKTRACE_LIMIT. */
2386 void
2387 emacs_backtrace (int backtrace_limit)
2389 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2390 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2391 void *buffer;
2392 int npointers;
2394 if (thread_backtrace_npointers)
2396 buffer = thread_backtrace_buffer;
2397 npointers = thread_backtrace_npointers;
2399 else
2401 buffer = main_backtrace_buffer;
2403 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2404 if (bounded_limit < 0)
2406 backtrace (buffer, 1);
2407 return;
2410 npointers = backtrace (buffer, bounded_limit + 1);
2413 if (npointers)
2415 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2416 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2417 if (bounded_limit < npointers)
2418 emacs_write (STDERR_FILENO, "...\n", 4);
2422 #ifndef HAVE_NTGUI
2423 void
2424 emacs_abort (void)
2426 terminate_due_to_signal (SIGABRT, 40);
2428 #endif
2430 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2431 Use binary I/O on systems that care about text vs binary I/O.
2432 Arrange for subprograms to not inherit the file descriptor.
2433 Prefer a method that is multithread-safe, if available.
2434 Do not fail merely because the open was interrupted by a signal.
2435 Allow the user to quit. */
2438 emacs_open (const char *file, int oflags, int mode)
2440 int fd;
2441 if (! (oflags & O_TEXT))
2442 oflags |= O_BINARY;
2443 oflags |= O_CLOEXEC;
2444 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2445 maybe_quit ();
2446 return fd;
2449 /* Open FILE as a stream for Emacs use, with mode MODE.
2450 Act like emacs_open with respect to threads, signals, and quits. */
2452 FILE *
2453 emacs_fopen (char const *file, char const *mode)
2455 int fd, omode, oflags;
2456 int bflag = 0;
2457 char const *m = mode;
2459 switch (*m++)
2461 case 'r': omode = O_RDONLY; oflags = 0; break;
2462 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2463 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2464 default: emacs_abort ();
2467 while (*m)
2468 switch (*m++)
2470 case '+': omode = O_RDWR; break;
2471 case 't': bflag = O_TEXT; break;
2472 default: /* Ignore. */ break;
2475 fd = emacs_open (file, omode | oflags | bflag, 0666);
2476 return fd < 0 ? 0 : fdopen (fd, mode);
2479 /* Create a pipe for Emacs use. */
2482 emacs_pipe (int fd[2])
2484 #ifdef MSDOS
2485 return pipe (fd);
2486 #else /* !MSDOS */
2487 return pipe2 (fd, O_BINARY | O_CLOEXEC);
2488 #endif /* !MSDOS */
2491 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2492 For the background behind this mess, please see Austin Group defect 529
2493 <http://austingroupbugs.net/view.php?id=529>. */
2495 #ifndef POSIX_CLOSE_RESTART
2496 # define POSIX_CLOSE_RESTART 1
2497 static int
2498 posix_close (int fd, int flag)
2500 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2501 eassert (flag == POSIX_CLOSE_RESTART);
2503 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2504 on a system that does not define POSIX_CLOSE_RESTART.
2506 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2507 closed, and retrying the close could inadvertently close a file
2508 descriptor allocated by some other thread. In other systems
2509 (e.g., HP/UX) FD is not closed. And in still other systems
2510 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2511 multithreaded program there can be no way to tell.
2513 So, in this case, pretend that the close succeeded. This works
2514 well on systems like GNU/Linux that close FD. Although it may
2515 leak a file descriptor on other systems, the leak is unlikely and
2516 it's better to leak than to close a random victim. */
2517 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2519 #endif
2521 /* Close FD, retrying if interrupted. If successful, return 0;
2522 otherwise, return -1 and set errno to a non-EINTR value. Consider
2523 an EINPROGRESS error to be successful, as that's merely a signal
2524 arriving. FD is always closed when this function returns, even
2525 when it returns -1.
2527 Do not call this function if FD is nonnegative and might already be closed,
2528 as that might close an innocent victim opened by some other thread. */
2531 emacs_close (int fd)
2533 while (1)
2535 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2536 if (r == 0)
2537 return r;
2538 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2540 eassert (errno != EBADF || fd < 0);
2541 return errno == EINPROGRESS ? 0 : r;
2546 /* Maximum number of bytes to read or write in a single system call.
2547 This works around a serious bug in Linux kernels before 2.6.16; see
2548 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2549 It's likely to work around similar bugs in other operating systems, so do it
2550 on all platforms. Round INT_MAX down to a page size, with the conservative
2551 assumption that page sizes are at most 2**18 bytes (any kernel with a
2552 page size larger than that shouldn't have the bug). */
2553 #ifndef MAX_RW_COUNT
2554 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2555 #endif
2557 /* Read from FD to a buffer BUF with size NBYTE.
2558 If interrupted, process any quits and pending signals immediately
2559 if INTERRUPTIBLE, and then retry the read unless quitting.
2560 Return the number of bytes read, which might be less than NBYTE.
2561 On error, set errno to a value other than EINTR, and return -1. */
2562 static ptrdiff_t
2563 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2565 ssize_t result;
2567 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2568 passes a size that large to emacs_read. */
2571 if (interruptible)
2572 maybe_quit ();
2573 result = read (fd, buf, nbyte);
2575 while (result < 0 && errno == EINTR);
2577 return result;
2580 /* Read from FD to a buffer BUF with size NBYTE.
2581 If interrupted, retry the read. Return the number of bytes read,
2582 which might be less than NBYTE. On error, set errno to a value
2583 other than EINTR, and return -1. */
2584 ptrdiff_t
2585 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2587 return emacs_intr_read (fd, buf, nbyte, false);
2590 /* Like emacs_read, but also process quits and pending signals. */
2591 ptrdiff_t
2592 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2594 return emacs_intr_read (fd, buf, nbyte, true);
2597 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2598 interrupted or if a partial write occurs. Process any quits
2599 immediately if INTERRUPTIBLE is positive, and process any pending
2600 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2601 of bytes written; if this is less than NBYTE, set errno to a value
2602 other than EINTR. */
2603 static ptrdiff_t
2604 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2605 int interruptible)
2607 ptrdiff_t bytes_written = 0;
2609 while (nbyte > 0)
2611 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2613 if (n < 0)
2615 if (errno != EINTR)
2616 break;
2618 if (interruptible)
2620 if (0 < interruptible)
2621 maybe_quit ();
2622 if (pending_signals)
2623 process_pending_signals ();
2626 else
2628 buf += n;
2629 nbyte -= n;
2630 bytes_written += n;
2634 return bytes_written;
2637 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2638 interrupted or if a partial write occurs. Do not process quits or
2639 pending signals. Return the number of bytes written, setting errno
2640 if this is less than NBYTE. */
2641 ptrdiff_t
2642 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2644 return emacs_full_write (fd, buf, nbyte, 0);
2647 /* Like emacs_write, but also process pending signals. */
2648 ptrdiff_t
2649 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2651 return emacs_full_write (fd, buf, nbyte, -1);
2654 /* Like emacs_write, but also process quits and pending signals. */
2655 ptrdiff_t
2656 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2658 return emacs_full_write (fd, buf, nbyte, 1);
2661 /* Write a diagnostic to standard error that contains MESSAGE and a
2662 string derived from errno. Preserve errno. Do not buffer stderr.
2663 Do not process quits or pending signals if interrupted. */
2664 void
2665 emacs_perror (char const *message)
2667 int err = errno;
2668 char const *error_string = emacs_strerror (err);
2669 char const *command = (initial_argv && initial_argv[0]
2670 ? initial_argv[0] : "emacs");
2671 /* Write it out all at once, if it's short; this is less likely to
2672 be interleaved with other output. */
2673 char buf[BUFSIZ];
2674 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2675 command, message, error_string);
2676 if (0 <= nbytes && nbytes < BUFSIZ)
2677 emacs_write (STDERR_FILENO, buf, nbytes);
2678 else
2680 emacs_write (STDERR_FILENO, command, strlen (command));
2681 emacs_write (STDERR_FILENO, ": ", 2);
2682 emacs_write (STDERR_FILENO, message, strlen (message));
2683 emacs_write (STDERR_FILENO, ": ", 2);
2684 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2685 emacs_write (STDERR_FILENO, "\n", 1);
2687 errno = err;
2690 /* Return a struct timeval that is roughly equivalent to T.
2691 Use the least timeval not less than T.
2692 Return an extremal value if the result would overflow. */
2693 struct timeval
2694 make_timeval (struct timespec t)
2696 struct timeval tv;
2697 tv.tv_sec = t.tv_sec;
2698 tv.tv_usec = t.tv_nsec / 1000;
2700 if (t.tv_nsec % 1000 != 0)
2702 if (tv.tv_usec < 999999)
2703 tv.tv_usec++;
2704 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2706 tv.tv_sec++;
2707 tv.tv_usec = 0;
2711 return tv;
2714 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2715 ATIME and MTIME, respectively.
2716 FD must be either negative -- in which case it is ignored --
2717 or a file descriptor that is open on FILE.
2718 If FD is nonnegative, then FILE can be NULL. */
2720 set_file_times (int fd, const char *filename,
2721 struct timespec atime, struct timespec mtime)
2723 struct timespec timespec[2];
2724 timespec[0] = atime;
2725 timespec[1] = mtime;
2726 return fdutimens (fd, filename, timespec);
2729 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2730 This is like renameat except that it fails if DST already exists,
2731 or if this operation is not supported atomically. Return 0 if
2732 successful, -1 (setting errno) otherwise. */
2734 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2736 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2737 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2738 #elif defined CYGWIN && defined RENAME_NOREPLACE
2739 return renameat2 (srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2740 #elif defined RENAME_EXCL
2741 return renameatx_np (srcfd, src, dstfd, dst, RENAME_EXCL);
2742 #else
2743 # ifdef WINDOWSNT
2744 if (srcfd == AT_FDCWD && dstfd == AT_FDCWD)
2745 return sys_rename_replace (src, dst, 0);
2746 # endif
2747 errno = ENOSYS;
2748 return -1;
2749 #endif
2752 /* Like strsignal, except async-signal-safe, and this function typically
2753 returns a string in the C locale rather than the current locale. */
2754 char const *
2755 safe_strsignal (int code)
2757 char const *signame = 0;
2759 if (0 <= code && code < sys_siglist_entries)
2760 signame = sys_siglist[code];
2761 if (! signame)
2762 signame = "Unknown signal";
2764 return signame;
2767 #ifndef DOS_NT
2768 /* For make-serial-process */
2770 serial_open (Lisp_Object port)
2772 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2773 if (fd < 0)
2774 report_file_error ("Opening serial port", port);
2775 #ifdef TIOCEXCL
2776 ioctl (fd, TIOCEXCL, (char *) 0);
2777 #endif
2779 return fd;
2782 #if !defined (HAVE_CFMAKERAW)
2783 /* Workaround for targets which are missing cfmakeraw. */
2784 /* Pasted from man page. */
2785 static void
2786 cfmakeraw (struct termios *termios_p)
2788 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2789 termios_p->c_oflag &= ~OPOST;
2790 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2791 termios_p->c_cflag &= ~(CSIZE|PARENB);
2792 termios_p->c_cflag |= CS8;
2794 #endif /* !defined (HAVE_CFMAKERAW */
2796 #if !defined (HAVE_CFSETSPEED)
2797 /* Workaround for targets which are missing cfsetspeed. */
2798 static int
2799 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2801 return (cfsetispeed (termios_p, vitesse)
2802 + cfsetospeed (termios_p, vitesse));
2804 #endif
2806 /* For serial-process-configure */
2807 void
2808 serial_configure (struct Lisp_Process *p,
2809 Lisp_Object contact)
2811 Lisp_Object childp2 = Qnil;
2812 Lisp_Object tem = Qnil;
2813 struct termios attr;
2814 int err;
2815 char summary[4] = "???"; /* This usually becomes "8N1". */
2817 childp2 = Fcopy_sequence (p->childp);
2819 /* Read port attributes and prepare default configuration. */
2820 err = tcgetattr (p->outfd, &attr);
2821 if (err != 0)
2822 report_file_error ("Failed tcgetattr", Qnil);
2823 cfmakeraw (&attr);
2824 #if defined (CLOCAL)
2825 attr.c_cflag |= CLOCAL;
2826 #endif
2827 #if defined (CREAD)
2828 attr.c_cflag |= CREAD;
2829 #endif
2831 /* Configure speed. */
2832 if (!NILP (Fplist_member (contact, QCspeed)))
2833 tem = Fplist_get (contact, QCspeed);
2834 else
2835 tem = Fplist_get (p->childp, QCspeed);
2836 CHECK_NUMBER (tem);
2837 err = cfsetspeed (&attr, XINT (tem));
2838 if (err != 0)
2839 report_file_error ("Failed cfsetspeed", tem);
2840 childp2 = Fplist_put (childp2, QCspeed, tem);
2842 /* Configure bytesize. */
2843 if (!NILP (Fplist_member (contact, QCbytesize)))
2844 tem = Fplist_get (contact, QCbytesize);
2845 else
2846 tem = Fplist_get (p->childp, QCbytesize);
2847 if (NILP (tem))
2848 tem = make_number (8);
2849 CHECK_NUMBER (tem);
2850 if (XINT (tem) != 7 && XINT (tem) != 8)
2851 error (":bytesize must be nil (8), 7, or 8");
2852 summary[0] = XINT (tem) + '0';
2853 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2854 attr.c_cflag &= ~CSIZE;
2855 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2856 #else
2857 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2858 if (XINT (tem) != 8)
2859 error ("Bytesize cannot be changed");
2860 #endif
2861 childp2 = Fplist_put (childp2, QCbytesize, tem);
2863 /* Configure parity. */
2864 if (!NILP (Fplist_member (contact, QCparity)))
2865 tem = Fplist_get (contact, QCparity);
2866 else
2867 tem = Fplist_get (p->childp, QCparity);
2868 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2869 error (":parity must be nil (no parity), `even', or `odd'");
2870 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2871 attr.c_cflag &= ~(PARENB | PARODD);
2872 attr.c_iflag &= ~(IGNPAR | INPCK);
2873 if (NILP (tem))
2875 summary[1] = 'N';
2877 else if (EQ (tem, Qeven))
2879 summary[1] = 'E';
2880 attr.c_cflag |= PARENB;
2881 attr.c_iflag |= (IGNPAR | INPCK);
2883 else if (EQ (tem, Qodd))
2885 summary[1] = 'O';
2886 attr.c_cflag |= (PARENB | PARODD);
2887 attr.c_iflag |= (IGNPAR | INPCK);
2889 #else
2890 /* Don't error on no parity, which should be set by cfmakeraw. */
2891 if (!NILP (tem))
2892 error ("Parity cannot be configured");
2893 #endif
2894 childp2 = Fplist_put (childp2, QCparity, tem);
2896 /* Configure stopbits. */
2897 if (!NILP (Fplist_member (contact, QCstopbits)))
2898 tem = Fplist_get (contact, QCstopbits);
2899 else
2900 tem = Fplist_get (p->childp, QCstopbits);
2901 if (NILP (tem))
2902 tem = make_number (1);
2903 CHECK_NUMBER (tem);
2904 if (XINT (tem) != 1 && XINT (tem) != 2)
2905 error (":stopbits must be nil (1 stopbit), 1, or 2");
2906 summary[2] = XINT (tem) + '0';
2907 #if defined (CSTOPB)
2908 attr.c_cflag &= ~CSTOPB;
2909 if (XINT (tem) == 2)
2910 attr.c_cflag |= CSTOPB;
2911 #else
2912 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2913 if (XINT (tem) != 1)
2914 error ("Stopbits cannot be configured");
2915 #endif
2916 childp2 = Fplist_put (childp2, QCstopbits, tem);
2918 /* Configure flowcontrol. */
2919 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2920 tem = Fplist_get (contact, QCflowcontrol);
2921 else
2922 tem = Fplist_get (p->childp, QCflowcontrol);
2923 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2924 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2925 #if defined (CRTSCTS)
2926 attr.c_cflag &= ~CRTSCTS;
2927 #endif
2928 #if defined (CNEW_RTSCTS)
2929 attr.c_cflag &= ~CNEW_RTSCTS;
2930 #endif
2931 #if defined (IXON) && defined (IXOFF)
2932 attr.c_iflag &= ~(IXON | IXOFF);
2933 #endif
2934 if (NILP (tem))
2936 /* Already configured. */
2938 else if (EQ (tem, Qhw))
2940 #if defined (CRTSCTS)
2941 attr.c_cflag |= CRTSCTS;
2942 #elif defined (CNEW_RTSCTS)
2943 attr.c_cflag |= CNEW_RTSCTS;
2944 #else
2945 error ("Hardware flowcontrol (RTS/CTS) not supported");
2946 #endif
2948 else if (EQ (tem, Qsw))
2950 #if defined (IXON) && defined (IXOFF)
2951 attr.c_iflag |= (IXON | IXOFF);
2952 #else
2953 error ("Software flowcontrol (XON/XOFF) not supported");
2954 #endif
2956 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2958 /* Activate configuration. */
2959 err = tcsetattr (p->outfd, TCSANOW, &attr);
2960 if (err != 0)
2961 report_file_error ("Failed tcsetattr", Qnil);
2963 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2964 pset_childp (p, childp2);
2966 #endif /* not DOS_NT */
2968 /* System depended enumeration of and access to system processes a-la ps(1). */
2970 #ifdef HAVE_PROCFS
2972 /* Process enumeration and access via /proc. */
2974 Lisp_Object
2975 list_system_processes (void)
2977 Lisp_Object procdir, match, proclist, next;
2978 Lisp_Object tail;
2980 /* For every process on the system, there's a directory in the
2981 "/proc" pseudo-directory whose name is the numeric ID of that
2982 process. */
2983 procdir = build_string ("/proc");
2984 match = build_string ("[0-9]+");
2985 proclist = directory_files_internal (procdir, Qnil, match, Qt, false, Qnil);
2987 /* `proclist' gives process IDs as strings. Destructively convert
2988 each string into a number. */
2989 for (tail = proclist; CONSP (tail); tail = next)
2991 next = XCDR (tail);
2992 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2995 /* directory_files_internal returns the files in reverse order; undo
2996 that. */
2997 proclist = Fnreverse (proclist);
2998 return proclist;
3001 #elif defined DARWIN_OS || defined __FreeBSD__
3003 Lisp_Object
3004 list_system_processes (void)
3006 #ifdef DARWIN_OS
3007 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
3008 #else
3009 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
3010 #endif
3011 size_t len;
3012 struct kinfo_proc *procs;
3013 size_t i;
3015 Lisp_Object proclist = Qnil;
3017 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
3018 return proclist;
3020 procs = xmalloc (len);
3021 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
3023 xfree (procs);
3024 return proclist;
3027 len /= sizeof (struct kinfo_proc);
3028 for (i = 0; i < len; i++)
3030 #ifdef DARWIN_OS
3031 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
3032 #else
3033 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
3034 #endif
3037 xfree (procs);
3039 return proclist;
3042 /* The WINDOWSNT implementation is in w32.c.
3043 The MSDOS implementation is in dosfns.c. */
3044 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3046 Lisp_Object
3047 list_system_processes (void)
3049 return Qnil;
3052 #endif /* !defined (WINDOWSNT) */
3054 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3055 static struct timespec
3056 time_from_jiffies (unsigned long long tval, long hz)
3058 unsigned long long s = tval / hz;
3059 unsigned long long frac = tval % hz;
3060 int ns;
3062 if (TYPE_MAXIMUM (time_t) < s)
3063 time_overflow ();
3064 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
3065 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
3066 ns = frac * TIMESPEC_RESOLUTION / hz;
3067 else
3069 /* This is reachable only in the unlikely case that HZ * HZ
3070 exceeds ULLONG_MAX. It calculates an approximation that is
3071 guaranteed to be in range. */
3072 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3073 + (hz % TIMESPEC_RESOLUTION != 0));
3074 ns = frac / hz_per_ns;
3077 return make_timespec (s, ns);
3080 static Lisp_Object
3081 ltime_from_jiffies (unsigned long long tval, long hz)
3083 struct timespec t = time_from_jiffies (tval, hz);
3084 return make_lisp_time (t);
3087 static struct timespec
3088 get_up_time (void)
3090 FILE *fup;
3091 struct timespec up = make_timespec (0, 0);
3093 block_input ();
3094 fup = emacs_fopen ("/proc/uptime", "r");
3096 if (fup)
3098 unsigned long long upsec, upfrac, idlesec, idlefrac;
3099 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3101 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3102 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3103 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3104 == 4)
3106 if (TYPE_MAXIMUM (time_t) < upsec)
3108 upsec = TYPE_MAXIMUM (time_t);
3109 upfrac = TIMESPEC_RESOLUTION - 1;
3111 else
3113 int upfraclen = upfrac_end - upfrac_start;
3114 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3115 upfrac *= 10;
3116 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3117 upfrac /= 10;
3118 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3120 up = make_timespec (upsec, upfrac);
3122 fclose (fup);
3124 unblock_input ();
3126 return up;
3129 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3130 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3132 static Lisp_Object
3133 procfs_ttyname (int rdev)
3135 FILE *fdev;
3136 char name[PATH_MAX];
3138 block_input ();
3139 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3140 name[0] = 0;
3142 if (fdev)
3144 unsigned major;
3145 unsigned long minor_beg, minor_end;
3146 char minor[25]; /* 2 32-bit numbers + dash */
3147 char *endp;
3149 for (; !feof_unlocked (fdev) && !ferror_unlocked (fdev); name[0] = 0)
3151 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3152 && major == MAJOR (rdev))
3154 minor_beg = strtoul (minor, &endp, 0);
3155 if (*endp == '\0')
3156 minor_end = minor_beg;
3157 else if (*endp == '-')
3158 minor_end = strtoul (endp + 1, &endp, 0);
3159 else
3160 continue;
3162 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3164 sprintf (name + strlen (name), "%u", MINOR (rdev));
3165 break;
3169 fclose (fdev);
3171 unblock_input ();
3172 return build_string (name);
3175 static uintmax_t
3176 procfs_get_total_memory (void)
3178 FILE *fmem;
3179 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3180 int c;
3182 block_input ();
3183 fmem = emacs_fopen ("/proc/meminfo", "r");
3185 if (fmem)
3187 uintmax_t entry_value;
3188 bool done;
3191 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3193 case 1:
3194 retval = entry_value;
3195 done = 1;
3196 break;
3198 case 0:
3199 while ((c = getc_unlocked (fmem)) != EOF && c != '\n')
3200 continue;
3201 done = c == EOF;
3202 break;
3204 default:
3205 done = 1;
3206 break;
3208 while (!done);
3210 fclose (fmem);
3212 unblock_input ();
3213 return retval;
3216 Lisp_Object
3217 system_process_attributes (Lisp_Object pid)
3219 char procfn[PATH_MAX], fn[PATH_MAX];
3220 struct stat st;
3221 struct passwd *pw;
3222 struct group *gr;
3223 long clocks_per_sec;
3224 char *procfn_end;
3225 char procbuf[1025], *p, *q;
3226 int fd;
3227 ssize_t nread;
3228 static char const default_cmd[] = "???";
3229 const char *cmd = default_cmd;
3230 int cmdsize = sizeof default_cmd - 1;
3231 char *cmdline = NULL;
3232 ptrdiff_t cmdline_size;
3233 char c;
3234 printmax_t proc_id;
3235 int ppid, pgrp, sess, tty, tpgid, thcount;
3236 uid_t uid;
3237 gid_t gid;
3238 unsigned long long u_time, s_time, cutime, cstime, start;
3239 long priority, niceness, rss;
3240 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3241 struct timespec tnow, tstart, tboot, telapsed, us_time;
3242 double pcpu, pmem;
3243 Lisp_Object attrs = Qnil;
3244 Lisp_Object decoded_cmd;
3245 ptrdiff_t count;
3247 CHECK_NUMBER_OR_FLOAT (pid);
3248 CONS_TO_INTEGER (pid, pid_t, proc_id);
3249 sprintf (procfn, "/proc/%"pMd, proc_id);
3250 if (stat (procfn, &st) < 0)
3251 return attrs;
3253 /* euid egid */
3254 uid = st.st_uid;
3255 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3256 block_input ();
3257 pw = getpwuid (uid);
3258 unblock_input ();
3259 if (pw)
3260 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3262 gid = st.st_gid;
3263 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3264 block_input ();
3265 gr = getgrgid (gid);
3266 unblock_input ();
3267 if (gr)
3268 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3270 count = SPECPDL_INDEX ();
3271 strcpy (fn, procfn);
3272 procfn_end = fn + strlen (fn);
3273 strcpy (procfn_end, "/stat");
3274 fd = emacs_open (fn, O_RDONLY, 0);
3275 if (fd < 0)
3276 nread = 0;
3277 else
3279 record_unwind_protect_int (close_file_unwind, fd);
3280 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3282 if (0 < nread)
3284 procbuf[nread] = '\0';
3285 p = procbuf;
3287 p = strchr (p, '(');
3288 if (p != NULL)
3290 q = strrchr (p + 1, ')');
3291 /* comm */
3292 if (q != NULL)
3294 cmd = p + 1;
3295 cmdsize = q - cmd;
3298 else
3299 q = NULL;
3300 /* Command name is encoded in locale-coding-system; decode it. */
3301 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3302 decoded_cmd = code_convert_string_norecord (cmd_str,
3303 Vlocale_coding_system, 0);
3304 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3306 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3307 utime stime cutime cstime priority nice thcount . start vsize rss */
3308 if (q
3309 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3310 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3311 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3312 &minflt, &cminflt, &majflt, &cmajflt,
3313 &u_time, &s_time, &cutime, &cstime,
3314 &priority, &niceness, &thcount, &start, &vsize, &rss)
3315 == 20))
3317 char state_str[2];
3318 state_str[0] = c;
3319 state_str[1] = '\0';
3320 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3321 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3322 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3323 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3324 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3325 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3326 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3327 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3328 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3329 attrs);
3330 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3331 attrs);
3332 clocks_per_sec = sysconf (_SC_CLK_TCK);
3333 if (clocks_per_sec < 0)
3334 clocks_per_sec = 100;
3335 attrs = Fcons (Fcons (Qutime,
3336 ltime_from_jiffies (u_time, clocks_per_sec)),
3337 attrs);
3338 attrs = Fcons (Fcons (Qstime,
3339 ltime_from_jiffies (s_time, clocks_per_sec)),
3340 attrs);
3341 attrs = Fcons (Fcons (Qtime,
3342 ltime_from_jiffies (s_time + u_time,
3343 clocks_per_sec)),
3344 attrs);
3345 attrs = Fcons (Fcons (Qcutime,
3346 ltime_from_jiffies (cutime, clocks_per_sec)),
3347 attrs);
3348 attrs = Fcons (Fcons (Qcstime,
3349 ltime_from_jiffies (cstime, clocks_per_sec)),
3350 attrs);
3351 attrs = Fcons (Fcons (Qctime,
3352 ltime_from_jiffies (cstime + cutime,
3353 clocks_per_sec)),
3354 attrs);
3355 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3356 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3357 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3358 attrs);
3359 tnow = current_timespec ();
3360 telapsed = get_up_time ();
3361 tboot = timespec_sub (tnow, telapsed);
3362 tstart = time_from_jiffies (start, clocks_per_sec);
3363 tstart = timespec_add (tboot, tstart);
3364 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3365 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3366 attrs);
3367 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3368 telapsed = timespec_sub (tnow, tstart);
3369 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3370 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3371 pcpu = timespectod (us_time) / timespectod (telapsed);
3372 if (pcpu > 1.0)
3373 pcpu = 1.0;
3374 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3375 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3376 if (pmem > 100)
3377 pmem = 100;
3378 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3381 unbind_to (count, Qnil);
3383 /* args */
3384 strcpy (procfn_end, "/cmdline");
3385 fd = emacs_open (fn, O_RDONLY, 0);
3386 if (fd >= 0)
3388 ptrdiff_t readsize, nread_incr;
3389 record_unwind_protect_int (close_file_unwind, fd);
3390 record_unwind_protect_nothing ();
3391 nread = cmdline_size = 0;
3395 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3396 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3398 /* Leave room even if every byte needs escaping below. */
3399 readsize = (cmdline_size >> 1) - nread;
3401 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3402 nread += max (0, nread_incr);
3404 while (nread_incr == readsize);
3406 if (nread)
3408 /* We don't want trailing null characters. */
3409 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3410 continue;
3412 /* Escape-quote whitespace and backslashes. */
3413 q = cmdline + cmdline_size;
3414 while (cmdline < p)
3416 char c = *--p;
3417 *--q = c ? c : ' ';
3418 if (c_isspace (c) || c == '\\')
3419 *--q = '\\';
3422 nread = cmdline + cmdline_size - q;
3425 if (!nread)
3427 nread = cmdsize + 2;
3428 cmdline_size = nread + 1;
3429 q = cmdline = xrealloc (cmdline, cmdline_size);
3430 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3431 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3433 /* Command line is encoded in locale-coding-system; decode it. */
3434 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3435 decoded_cmd = code_convert_string_norecord (cmd_str,
3436 Vlocale_coding_system, 0);
3437 unbind_to (count, Qnil);
3438 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3441 return attrs;
3444 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3446 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3447 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3448 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3449 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3450 #undef _FILE_OFFSET_BITS
3451 #else
3452 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3453 #endif
3455 #include <procfs.h>
3457 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3458 #define _FILE_OFFSET_BITS 64
3459 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3460 #endif
3461 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3463 Lisp_Object
3464 system_process_attributes (Lisp_Object pid)
3466 char procfn[PATH_MAX], fn[PATH_MAX];
3467 struct stat st;
3468 struct passwd *pw;
3469 struct group *gr;
3470 char *procfn_end;
3471 struct psinfo pinfo;
3472 int fd;
3473 ssize_t nread;
3474 printmax_t proc_id;
3475 uid_t uid;
3476 gid_t gid;
3477 Lisp_Object attrs = Qnil;
3478 Lisp_Object decoded_cmd;
3479 ptrdiff_t count;
3481 CHECK_NUMBER_OR_FLOAT (pid);
3482 CONS_TO_INTEGER (pid, pid_t, proc_id);
3483 sprintf (procfn, "/proc/%"pMd, proc_id);
3484 if (stat (procfn, &st) < 0)
3485 return attrs;
3487 /* euid egid */
3488 uid = st.st_uid;
3489 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3490 block_input ();
3491 pw = getpwuid (uid);
3492 unblock_input ();
3493 if (pw)
3494 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3496 gid = st.st_gid;
3497 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3498 block_input ();
3499 gr = getgrgid (gid);
3500 unblock_input ();
3501 if (gr)
3502 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3504 count = SPECPDL_INDEX ();
3505 strcpy (fn, procfn);
3506 procfn_end = fn + strlen (fn);
3507 strcpy (procfn_end, "/psinfo");
3508 fd = emacs_open (fn, O_RDONLY, 0);
3509 if (fd < 0)
3510 nread = 0;
3511 else
3513 record_unwind_protect_int (close_file_unwind, fd);
3514 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3517 if (nread == sizeof pinfo)
3519 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3520 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3521 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3524 char state_str[2];
3525 state_str[0] = pinfo.pr_lwp.pr_sname;
3526 state_str[1] = '\0';
3527 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3530 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3531 need to get a string from it. */
3533 /* FIXME: missing: Qtpgid */
3535 /* FIXME: missing:
3536 Qminflt
3537 Qmajflt
3538 Qcminflt
3539 Qcmajflt
3541 Qutime
3542 Qcutime
3543 Qstime
3544 Qcstime
3545 Are they available? */
3547 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3548 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3549 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3550 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3551 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3552 attrs);
3554 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3555 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3556 attrs);
3557 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3558 attrs);
3560 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3561 range 0 .. 2**15, representing 0.0 .. 1.0. */
3562 attrs = Fcons (Fcons (Qpcpu,
3563 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3564 attrs);
3565 attrs = Fcons (Fcons (Qpmem,
3566 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3567 attrs);
3569 AUTO_STRING (fname, pinfo.pr_fname);
3570 decoded_cmd = code_convert_string_norecord (fname,
3571 Vlocale_coding_system, 0);
3572 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3573 AUTO_STRING (psargs, pinfo.pr_psargs);
3574 decoded_cmd = code_convert_string_norecord (psargs,
3575 Vlocale_coding_system, 0);
3576 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3578 unbind_to (count, Qnil);
3579 return attrs;
3582 #elif defined __FreeBSD__
3584 static struct timespec
3585 timeval_to_timespec (struct timeval t)
3587 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3590 static Lisp_Object
3591 make_lisp_timeval (struct timeval t)
3593 return make_lisp_time (timeval_to_timespec (t));
3596 Lisp_Object
3597 system_process_attributes (Lisp_Object pid)
3599 int proc_id;
3600 int pagesize = getpagesize ();
3601 unsigned long npages;
3602 int fscale;
3603 struct passwd *pw;
3604 struct group *gr;
3605 char *ttyname;
3606 size_t len;
3607 char args[MAXPATHLEN];
3608 struct timespec t, now;
3610 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3611 struct kinfo_proc proc;
3612 size_t proclen = sizeof proc;
3614 Lisp_Object attrs = Qnil;
3615 Lisp_Object decoded_comm;
3617 CHECK_NUMBER_OR_FLOAT (pid);
3618 CONS_TO_INTEGER (pid, int, proc_id);
3619 mib[3] = proc_id;
3621 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3622 return attrs;
3624 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3626 block_input ();
3627 pw = getpwuid (proc.ki_uid);
3628 unblock_input ();
3629 if (pw)
3630 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3632 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3634 block_input ();
3635 gr = getgrgid (proc.ki_svgid);
3636 unblock_input ();
3637 if (gr)
3638 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3640 AUTO_STRING (comm, proc.ki_comm);
3641 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3643 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3645 char state[2] = {'\0', '\0'};
3646 switch (proc.ki_stat)
3648 case SRUN:
3649 state[0] = 'R';
3650 break;
3652 case SSLEEP:
3653 state[0] = 'S';
3654 break;
3656 case SLOCK:
3657 state[0] = 'D';
3658 break;
3660 case SZOMB:
3661 state[0] = 'Z';
3662 break;
3664 case SSTOP:
3665 state[0] = 'T';
3666 break;
3668 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3671 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3672 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3673 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3675 block_input ();
3676 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3677 unblock_input ();
3678 if (ttyname)
3679 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3681 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3682 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3683 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3684 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3685 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3687 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3688 attrs);
3689 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3690 attrs);
3691 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3692 timeval_to_timespec (proc.ki_rusage.ru_stime));
3693 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3695 attrs = Fcons (Fcons (Qcutime,
3696 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3697 attrs);
3698 attrs = Fcons (Fcons (Qcstime,
3699 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3700 attrs);
3701 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3702 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3703 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3705 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3706 attrs);
3707 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3708 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3709 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3710 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3711 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3712 attrs);
3714 now = current_timespec ();
3715 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3716 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3718 len = sizeof fscale;
3719 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3721 double pcpu;
3722 fixpt_t ccpu;
3723 len = sizeof ccpu;
3724 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3726 pcpu = (100.0 * proc.ki_pctcpu / fscale
3727 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3728 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3732 len = sizeof npages;
3733 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3735 double pmem = (proc.ki_flag & P_INMEM
3736 ? 100.0 * proc.ki_rssize / npages
3737 : 0);
3738 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3741 mib[2] = KERN_PROC_ARGS;
3742 len = MAXPATHLEN;
3743 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3745 int i;
3746 for (i = 0; i < len; i++)
3748 if (! args[i] && i < len - 1)
3749 args[i] = ' ';
3752 AUTO_STRING (comm, args);
3753 decoded_comm = code_convert_string_norecord (comm,
3754 Vlocale_coding_system, 0);
3756 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3759 return attrs;
3762 #elif defined DARWIN_OS
3764 static struct timespec
3765 timeval_to_timespec (struct timeval t)
3767 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3770 static Lisp_Object
3771 make_lisp_timeval (struct timeval t)
3773 return make_lisp_time (timeval_to_timespec (t));
3776 Lisp_Object
3777 system_process_attributes (Lisp_Object pid)
3779 int proc_id;
3780 struct passwd *pw;
3781 struct group *gr;
3782 char *ttyname;
3783 struct timeval starttime;
3784 struct timespec t, now;
3785 struct rusage *rusage;
3786 dev_t tdev;
3787 uid_t uid;
3788 gid_t gid;
3790 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3791 struct kinfo_proc proc;
3792 size_t proclen = sizeof proc;
3794 Lisp_Object attrs = Qnil;
3795 Lisp_Object decoded_comm;
3797 CHECK_NUMBER_OR_FLOAT (pid);
3798 CONS_TO_INTEGER (pid, int, proc_id);
3799 mib[3] = proc_id;
3801 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3802 return attrs;
3804 uid = proc.kp_eproc.e_ucred.cr_uid;
3805 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3807 block_input ();
3808 pw = getpwuid (uid);
3809 unblock_input ();
3810 if (pw)
3811 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3813 gid = proc.kp_eproc.e_pcred.p_svgid;
3814 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3816 block_input ();
3817 gr = getgrgid (gid);
3818 unblock_input ();
3819 if (gr)
3820 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3822 decoded_comm = (code_convert_string_norecord
3823 (build_unibyte_string (proc.kp_proc.p_comm),
3824 Vlocale_coding_system, 0));
3826 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3828 char state[2] = {'\0', '\0'};
3829 switch (proc.kp_proc.p_stat)
3831 case SRUN:
3832 state[0] = 'R';
3833 break;
3835 case SSLEEP:
3836 state[0] = 'S';
3837 break;
3839 case SZOMB:
3840 state[0] = 'Z';
3841 break;
3843 case SSTOP:
3844 state[0] = 'T';
3845 break;
3847 case SIDL:
3848 state[0] = 'I';
3849 break;
3851 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3854 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3855 attrs);
3856 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3857 attrs);
3859 tdev = proc.kp_eproc.e_tdev;
3860 block_input ();
3861 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3862 unblock_input ();
3863 if (ttyname)
3864 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3866 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3867 attrs);
3869 rusage = proc.kp_proc.p_ru;
3870 if (rusage)
3872 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3873 attrs);
3874 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3875 attrs);
3877 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3878 attrs);
3879 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3880 attrs);
3881 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3882 timeval_to_timespec (rusage->ru_stime));
3883 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3886 starttime = proc.kp_proc.p_starttime;
3887 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3888 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3890 now = current_timespec ();
3891 t = timespec_sub (now, timeval_to_timespec (starttime));
3892 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3894 return attrs;
3897 /* The WINDOWSNT implementation is in w32.c.
3898 The MSDOS implementation is in dosfns.c. */
3899 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3901 Lisp_Object
3902 system_process_attributes (Lisp_Object pid)
3904 return Qnil;
3907 #endif /* !defined (WINDOWSNT) */
3909 /* Wide character string collation. */
3911 #ifdef __STDC_ISO_10646__
3912 # include <wchar.h>
3913 # include <wctype.h>
3915 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3916 # include <locale.h>
3917 # endif
3918 # ifndef LC_COLLATE
3919 # define LC_COLLATE 0
3920 # endif
3921 # ifndef LC_COLLATE_MASK
3922 # define LC_COLLATE_MASK 0
3923 # endif
3924 # ifndef LC_CTYPE
3925 # define LC_CTYPE 0
3926 # endif
3927 # ifndef LC_CTYPE_MASK
3928 # define LC_CTYPE_MASK 0
3929 # endif
3931 # ifndef HAVE_NEWLOCALE
3932 # undef freelocale
3933 # undef locale_t
3934 # undef newlocale
3935 # undef wcscoll_l
3936 # undef towlower_l
3937 # define freelocale emacs_freelocale
3938 # define locale_t emacs_locale_t
3939 # define newlocale emacs_newlocale
3940 # define wcscoll_l emacs_wcscoll_l
3941 # define towlower_l emacs_towlower_l
3943 typedef char const *locale_t;
3945 static locale_t
3946 newlocale (int category_mask, char const *locale, locale_t loc)
3948 return locale;
3951 static void
3952 freelocale (locale_t loc)
3956 static char *
3957 emacs_setlocale (int category, char const *locale)
3959 # ifdef HAVE_SETLOCALE
3960 errno = 0;
3961 char *loc = setlocale (category, locale);
3962 if (loc || errno)
3963 return loc;
3964 errno = EINVAL;
3965 # else
3966 errno = ENOTSUP;
3967 # endif
3968 return 0;
3971 static int
3972 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3974 int result = 0;
3975 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3976 int err;
3978 if (! oldloc)
3979 err = errno;
3980 else
3982 USE_SAFE_ALLOCA;
3983 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3984 strcpy (oldcopy, oldloc);
3985 if (! emacs_setlocale (LC_COLLATE, loc))
3986 err = errno;
3987 else
3989 errno = 0;
3990 result = wcscoll (a, b);
3991 err = errno;
3992 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3993 err = errno;
3995 SAFE_FREE ();
3998 errno = err;
3999 return result;
4002 static wint_t
4003 towlower_l (wint_t wc, locale_t loc)
4005 wint_t result = wc;
4006 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
4008 if (oldloc)
4010 USE_SAFE_ALLOCA;
4011 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
4012 strcpy (oldcopy, oldloc);
4013 if (emacs_setlocale (LC_CTYPE, loc))
4015 result = towlower (wc);
4016 emacs_setlocale (LC_COLLATE, oldcopy);
4018 SAFE_FREE ();
4021 return result;
4023 # endif
4026 str_collate (Lisp_Object s1, Lisp_Object s2,
4027 Lisp_Object locale, Lisp_Object ignore_case)
4029 int res, err;
4030 ptrdiff_t len, i, i_byte;
4031 wchar_t *p1, *p2;
4033 USE_SAFE_ALLOCA;
4035 /* Convert byte stream to code points. */
4036 len = SCHARS (s1); i = i_byte = 0;
4037 SAFE_NALLOCA (p1, 1, len + 1);
4038 while (i < len)
4039 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
4040 *(p1+len) = 0;
4042 len = SCHARS (s2); i = i_byte = 0;
4043 SAFE_NALLOCA (p2, 1, len + 1);
4044 while (i < len)
4045 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
4046 *(p2+len) = 0;
4048 if (STRINGP (locale))
4050 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
4051 SSDATA (locale), 0);
4052 if (!loc)
4053 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4055 if (! NILP (ignore_case))
4056 for (int i = 1; i < 3; i++)
4058 wchar_t *p = (i == 1) ? p1 : p2;
4059 for (; *p; p++)
4060 *p = towlower_l (*p, loc);
4063 errno = 0;
4064 res = wcscoll_l (p1, p2, loc);
4065 err = errno;
4066 freelocale (loc);
4068 else
4070 if (! NILP (ignore_case))
4071 for (int i = 1; i < 3; i++)
4073 wchar_t *p = (i == 1) ? p1 : p2;
4074 for (; *p; p++)
4075 *p = towlower (*p);
4078 errno = 0;
4079 res = wcscoll (p1, p2);
4080 err = errno;
4082 # ifndef HAVE_NEWLOCALE
4083 if (err)
4084 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4085 # else
4086 if (err)
4087 error ("Invalid string for collation: %s", emacs_strerror (err));
4088 # endif
4090 SAFE_FREE ();
4091 return res;
4093 #endif /* __STDC_ISO_10646__ */
4095 #ifdef WINDOWSNT
4097 str_collate (Lisp_Object s1, Lisp_Object s2,
4098 Lisp_Object locale, Lisp_Object ignore_case)
4101 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4102 int res, err = errno;
4104 errno = 0;
4105 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4106 if (errno)
4107 error ("Invalid string for collation: %s", strerror (errno));
4109 errno = err;
4110 return res;
4112 #endif /* WINDOWSNT */