* lisp/gnus/mm-util.el: Use lexical-binding and use cl-lib
[emacs.git] / src / sysdep.c
blobc59034ce5c30373f3049aa11700496680cccd832
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2018 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 /* Verify that MAX_RW_COUNT fits in the relevant standard types. */
2558 #ifndef SSIZE_MAX
2559 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
2560 #endif
2561 verify (MAX_RW_COUNT <= PTRDIFF_MAX);
2562 verify (MAX_RW_COUNT <= SIZE_MAX);
2563 verify (MAX_RW_COUNT <= SSIZE_MAX);
2565 #ifdef WINDOWSNT
2566 /* Verify that Emacs read requests cannot cause trouble, even in
2567 64-bit builds. The last argument of 'read' is 'unsigned int', and
2568 the return value's type (see 'sys_read') is 'int'. */
2569 verify (MAX_RW_COUNT <= INT_MAX);
2570 verify (MAX_RW_COUNT <= UINT_MAX);
2571 #endif
2573 /* Read from FD to a buffer BUF with size NBYTE.
2574 If interrupted, process any quits and pending signals immediately
2575 if INTERRUPTIBLE, and then retry the read unless quitting.
2576 Return the number of bytes read, which might be less than NBYTE.
2577 On error, set errno to a value other than EINTR, and return -1. */
2578 static ptrdiff_t
2579 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2581 /* No caller should ever pass a too-large size to emacs_read. */
2582 eassert (nbyte <= MAX_RW_COUNT);
2584 ssize_t result;
2588 if (interruptible)
2589 maybe_quit ();
2590 result = read (fd, buf, nbyte);
2592 while (result < 0 && errno == EINTR);
2594 return result;
2597 /* Read from FD to a buffer BUF with size NBYTE.
2598 If interrupted, retry the read. Return the number of bytes read,
2599 which might be less than NBYTE. On error, set errno to a value
2600 other than EINTR, and return -1. */
2601 ptrdiff_t
2602 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2604 return emacs_intr_read (fd, buf, nbyte, false);
2607 /* Like emacs_read, but also process quits and pending signals. */
2608 ptrdiff_t
2609 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2611 return emacs_intr_read (fd, buf, nbyte, true);
2614 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2615 interrupted or if a partial write occurs. Process any quits
2616 immediately if INTERRUPTIBLE is positive, and process any pending
2617 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2618 of bytes written; if this is less than NBYTE, set errno to a value
2619 other than EINTR. */
2620 static ptrdiff_t
2621 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2622 int interruptible)
2624 ptrdiff_t bytes_written = 0;
2626 while (nbyte > 0)
2628 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2630 if (n < 0)
2632 if (errno != EINTR)
2633 break;
2635 if (interruptible)
2637 if (0 < interruptible)
2638 maybe_quit ();
2639 if (pending_signals)
2640 process_pending_signals ();
2643 else
2645 buf += n;
2646 nbyte -= n;
2647 bytes_written += n;
2651 return bytes_written;
2654 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2655 interrupted or if a partial write occurs. Do not process quits or
2656 pending signals. Return the number of bytes written, setting errno
2657 if this is less than NBYTE. */
2658 ptrdiff_t
2659 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2661 return emacs_full_write (fd, buf, nbyte, 0);
2664 /* Like emacs_write, but also process pending signals. */
2665 ptrdiff_t
2666 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2668 return emacs_full_write (fd, buf, nbyte, -1);
2671 /* Like emacs_write, but also process quits and pending signals. */
2672 ptrdiff_t
2673 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2675 return emacs_full_write (fd, buf, nbyte, 1);
2678 /* Write a diagnostic to standard error that contains MESSAGE and a
2679 string derived from errno. Preserve errno. Do not buffer stderr.
2680 Do not process quits or pending signals if interrupted. */
2681 void
2682 emacs_perror (char const *message)
2684 int err = errno;
2685 char const *error_string = emacs_strerror (err);
2686 char const *command = (initial_argv && initial_argv[0]
2687 ? initial_argv[0] : "emacs");
2688 /* Write it out all at once, if it's short; this is less likely to
2689 be interleaved with other output. */
2690 char buf[BUFSIZ];
2691 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2692 command, message, error_string);
2693 if (0 <= nbytes && nbytes < BUFSIZ)
2694 emacs_write (STDERR_FILENO, buf, nbytes);
2695 else
2697 emacs_write (STDERR_FILENO, command, strlen (command));
2698 emacs_write (STDERR_FILENO, ": ", 2);
2699 emacs_write (STDERR_FILENO, message, strlen (message));
2700 emacs_write (STDERR_FILENO, ": ", 2);
2701 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2702 emacs_write (STDERR_FILENO, "\n", 1);
2704 errno = err;
2707 /* Return a struct timeval that is roughly equivalent to T.
2708 Use the least timeval not less than T.
2709 Return an extremal value if the result would overflow. */
2710 struct timeval
2711 make_timeval (struct timespec t)
2713 struct timeval tv;
2714 tv.tv_sec = t.tv_sec;
2715 tv.tv_usec = t.tv_nsec / 1000;
2717 if (t.tv_nsec % 1000 != 0)
2719 if (tv.tv_usec < 999999)
2720 tv.tv_usec++;
2721 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2723 tv.tv_sec++;
2724 tv.tv_usec = 0;
2728 return tv;
2731 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2732 ATIME and MTIME, respectively.
2733 FD must be either negative -- in which case it is ignored --
2734 or a file descriptor that is open on FILE.
2735 If FD is nonnegative, then FILE can be NULL. */
2737 set_file_times (int fd, const char *filename,
2738 struct timespec atime, struct timespec mtime)
2740 struct timespec timespec[2];
2741 timespec[0] = atime;
2742 timespec[1] = mtime;
2743 return fdutimens (fd, filename, timespec);
2746 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2747 This is like renameat except that it fails if DST already exists,
2748 or if this operation is not supported atomically. Return 0 if
2749 successful, -1 (setting errno) otherwise. */
2751 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2753 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2754 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2755 #elif defined CYGWIN && defined RENAME_NOREPLACE
2756 return renameat2 (srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2757 #elif defined RENAME_EXCL
2758 return renameatx_np (srcfd, src, dstfd, dst, RENAME_EXCL);
2759 #else
2760 # ifdef WINDOWSNT
2761 if (srcfd == AT_FDCWD && dstfd == AT_FDCWD)
2762 return sys_rename_replace (src, dst, 0);
2763 # endif
2764 errno = ENOSYS;
2765 return -1;
2766 #endif
2769 /* Like strsignal, except async-signal-safe, and this function typically
2770 returns a string in the C locale rather than the current locale. */
2771 char const *
2772 safe_strsignal (int code)
2774 char const *signame = 0;
2776 if (0 <= code && code < sys_siglist_entries)
2777 signame = sys_siglist[code];
2778 if (! signame)
2779 signame = "Unknown signal";
2781 return signame;
2784 #ifndef DOS_NT
2785 /* For make-serial-process */
2787 serial_open (Lisp_Object port)
2789 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2790 if (fd < 0)
2791 report_file_error ("Opening serial port", port);
2792 #ifdef TIOCEXCL
2793 ioctl (fd, TIOCEXCL, (char *) 0);
2794 #endif
2796 return fd;
2799 #if !defined (HAVE_CFMAKERAW)
2800 /* Workaround for targets which are missing cfmakeraw. */
2801 /* Pasted from man page. */
2802 static void
2803 cfmakeraw (struct termios *termios_p)
2805 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2806 termios_p->c_oflag &= ~OPOST;
2807 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2808 termios_p->c_cflag &= ~(CSIZE|PARENB);
2809 termios_p->c_cflag |= CS8;
2811 #endif /* !defined (HAVE_CFMAKERAW */
2813 #if !defined (HAVE_CFSETSPEED)
2814 /* Workaround for targets which are missing cfsetspeed. */
2815 static int
2816 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2818 return (cfsetispeed (termios_p, vitesse)
2819 + cfsetospeed (termios_p, vitesse));
2821 #endif
2823 /* For serial-process-configure */
2824 void
2825 serial_configure (struct Lisp_Process *p,
2826 Lisp_Object contact)
2828 Lisp_Object childp2 = Qnil;
2829 Lisp_Object tem = Qnil;
2830 struct termios attr;
2831 int err;
2832 char summary[4] = "???"; /* This usually becomes "8N1". */
2834 childp2 = Fcopy_sequence (p->childp);
2836 /* Read port attributes and prepare default configuration. */
2837 err = tcgetattr (p->outfd, &attr);
2838 if (err != 0)
2839 report_file_error ("Failed tcgetattr", Qnil);
2840 cfmakeraw (&attr);
2841 #if defined (CLOCAL)
2842 attr.c_cflag |= CLOCAL;
2843 #endif
2844 #if defined (CREAD)
2845 attr.c_cflag |= CREAD;
2846 #endif
2848 /* Configure speed. */
2849 if (!NILP (Fplist_member (contact, QCspeed)))
2850 tem = Fplist_get (contact, QCspeed);
2851 else
2852 tem = Fplist_get (p->childp, QCspeed);
2853 CHECK_NUMBER (tem);
2854 err = cfsetspeed (&attr, XINT (tem));
2855 if (err != 0)
2856 report_file_error ("Failed cfsetspeed", tem);
2857 childp2 = Fplist_put (childp2, QCspeed, tem);
2859 /* Configure bytesize. */
2860 if (!NILP (Fplist_member (contact, QCbytesize)))
2861 tem = Fplist_get (contact, QCbytesize);
2862 else
2863 tem = Fplist_get (p->childp, QCbytesize);
2864 if (NILP (tem))
2865 tem = make_number (8);
2866 CHECK_NUMBER (tem);
2867 if (XINT (tem) != 7 && XINT (tem) != 8)
2868 error (":bytesize must be nil (8), 7, or 8");
2869 summary[0] = XINT (tem) + '0';
2870 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2871 attr.c_cflag &= ~CSIZE;
2872 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2873 #else
2874 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2875 if (XINT (tem) != 8)
2876 error ("Bytesize cannot be changed");
2877 #endif
2878 childp2 = Fplist_put (childp2, QCbytesize, tem);
2880 /* Configure parity. */
2881 if (!NILP (Fplist_member (contact, QCparity)))
2882 tem = Fplist_get (contact, QCparity);
2883 else
2884 tem = Fplist_get (p->childp, QCparity);
2885 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2886 error (":parity must be nil (no parity), `even', or `odd'");
2887 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2888 attr.c_cflag &= ~(PARENB | PARODD);
2889 attr.c_iflag &= ~(IGNPAR | INPCK);
2890 if (NILP (tem))
2892 summary[1] = 'N';
2894 else if (EQ (tem, Qeven))
2896 summary[1] = 'E';
2897 attr.c_cflag |= PARENB;
2898 attr.c_iflag |= (IGNPAR | INPCK);
2900 else if (EQ (tem, Qodd))
2902 summary[1] = 'O';
2903 attr.c_cflag |= (PARENB | PARODD);
2904 attr.c_iflag |= (IGNPAR | INPCK);
2906 #else
2907 /* Don't error on no parity, which should be set by cfmakeraw. */
2908 if (!NILP (tem))
2909 error ("Parity cannot be configured");
2910 #endif
2911 childp2 = Fplist_put (childp2, QCparity, tem);
2913 /* Configure stopbits. */
2914 if (!NILP (Fplist_member (contact, QCstopbits)))
2915 tem = Fplist_get (contact, QCstopbits);
2916 else
2917 tem = Fplist_get (p->childp, QCstopbits);
2918 if (NILP (tem))
2919 tem = make_number (1);
2920 CHECK_NUMBER (tem);
2921 if (XINT (tem) != 1 && XINT (tem) != 2)
2922 error (":stopbits must be nil (1 stopbit), 1, or 2");
2923 summary[2] = XINT (tem) + '0';
2924 #if defined (CSTOPB)
2925 attr.c_cflag &= ~CSTOPB;
2926 if (XINT (tem) == 2)
2927 attr.c_cflag |= CSTOPB;
2928 #else
2929 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2930 if (XINT (tem) != 1)
2931 error ("Stopbits cannot be configured");
2932 #endif
2933 childp2 = Fplist_put (childp2, QCstopbits, tem);
2935 /* Configure flowcontrol. */
2936 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2937 tem = Fplist_get (contact, QCflowcontrol);
2938 else
2939 tem = Fplist_get (p->childp, QCflowcontrol);
2940 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2941 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2942 #if defined (CRTSCTS)
2943 attr.c_cflag &= ~CRTSCTS;
2944 #endif
2945 #if defined (CNEW_RTSCTS)
2946 attr.c_cflag &= ~CNEW_RTSCTS;
2947 #endif
2948 #if defined (IXON) && defined (IXOFF)
2949 attr.c_iflag &= ~(IXON | IXOFF);
2950 #endif
2951 if (NILP (tem))
2953 /* Already configured. */
2955 else if (EQ (tem, Qhw))
2957 #if defined (CRTSCTS)
2958 attr.c_cflag |= CRTSCTS;
2959 #elif defined (CNEW_RTSCTS)
2960 attr.c_cflag |= CNEW_RTSCTS;
2961 #else
2962 error ("Hardware flowcontrol (RTS/CTS) not supported");
2963 #endif
2965 else if (EQ (tem, Qsw))
2967 #if defined (IXON) && defined (IXOFF)
2968 attr.c_iflag |= (IXON | IXOFF);
2969 #else
2970 error ("Software flowcontrol (XON/XOFF) not supported");
2971 #endif
2973 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2975 /* Activate configuration. */
2976 err = tcsetattr (p->outfd, TCSANOW, &attr);
2977 if (err != 0)
2978 report_file_error ("Failed tcsetattr", Qnil);
2980 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2981 pset_childp (p, childp2);
2983 #endif /* not DOS_NT */
2985 /* System depended enumeration of and access to system processes a-la ps(1). */
2987 #ifdef HAVE_PROCFS
2989 /* Process enumeration and access via /proc. */
2991 Lisp_Object
2992 list_system_processes (void)
2994 Lisp_Object procdir, match, proclist, next;
2995 Lisp_Object tail;
2997 /* For every process on the system, there's a directory in the
2998 "/proc" pseudo-directory whose name is the numeric ID of that
2999 process. */
3000 procdir = build_string ("/proc");
3001 match = build_string ("[0-9]+");
3002 proclist = directory_files_internal (procdir, Qnil, match, Qt, false, Qnil);
3004 /* `proclist' gives process IDs as strings. Destructively convert
3005 each string into a number. */
3006 for (tail = proclist; CONSP (tail); tail = next)
3008 next = XCDR (tail);
3009 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
3012 /* directory_files_internal returns the files in reverse order; undo
3013 that. */
3014 proclist = Fnreverse (proclist);
3015 return proclist;
3018 #elif defined DARWIN_OS || defined __FreeBSD__
3020 Lisp_Object
3021 list_system_processes (void)
3023 #ifdef DARWIN_OS
3024 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
3025 #else
3026 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
3027 #endif
3028 size_t len;
3029 struct kinfo_proc *procs;
3030 size_t i;
3032 Lisp_Object proclist = Qnil;
3034 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
3035 return proclist;
3037 procs = xmalloc (len);
3038 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
3040 xfree (procs);
3041 return proclist;
3044 len /= sizeof (struct kinfo_proc);
3045 for (i = 0; i < len; i++)
3047 #ifdef DARWIN_OS
3048 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
3049 #else
3050 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
3051 #endif
3054 xfree (procs);
3056 return proclist;
3059 /* The WINDOWSNT implementation is in w32.c.
3060 The MSDOS implementation is in dosfns.c. */
3061 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3063 Lisp_Object
3064 list_system_processes (void)
3066 return Qnil;
3069 #endif /* !defined (WINDOWSNT) */
3071 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3072 static struct timespec
3073 time_from_jiffies (unsigned long long tval, long hz)
3075 unsigned long long s = tval / hz;
3076 unsigned long long frac = tval % hz;
3077 int ns;
3079 if (TYPE_MAXIMUM (time_t) < s)
3080 time_overflow ();
3081 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
3082 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
3083 ns = frac * TIMESPEC_RESOLUTION / hz;
3084 else
3086 /* This is reachable only in the unlikely case that HZ * HZ
3087 exceeds ULLONG_MAX. It calculates an approximation that is
3088 guaranteed to be in range. */
3089 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3090 + (hz % TIMESPEC_RESOLUTION != 0));
3091 ns = frac / hz_per_ns;
3094 return make_timespec (s, ns);
3097 static Lisp_Object
3098 ltime_from_jiffies (unsigned long long tval, long hz)
3100 struct timespec t = time_from_jiffies (tval, hz);
3101 return make_lisp_time (t);
3104 static struct timespec
3105 get_up_time (void)
3107 FILE *fup;
3108 struct timespec up = make_timespec (0, 0);
3110 block_input ();
3111 fup = emacs_fopen ("/proc/uptime", "r");
3113 if (fup)
3115 unsigned long long upsec, upfrac, idlesec, idlefrac;
3116 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3118 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3119 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3120 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3121 == 4)
3123 if (TYPE_MAXIMUM (time_t) < upsec)
3125 upsec = TYPE_MAXIMUM (time_t);
3126 upfrac = TIMESPEC_RESOLUTION - 1;
3128 else
3130 int upfraclen = upfrac_end - upfrac_start;
3131 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3132 upfrac *= 10;
3133 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3134 upfrac /= 10;
3135 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3137 up = make_timespec (upsec, upfrac);
3139 fclose (fup);
3141 unblock_input ();
3143 return up;
3146 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3147 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3149 static Lisp_Object
3150 procfs_ttyname (int rdev)
3152 FILE *fdev;
3153 char name[PATH_MAX];
3155 block_input ();
3156 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3157 name[0] = 0;
3159 if (fdev)
3161 unsigned major;
3162 unsigned long minor_beg, minor_end;
3163 char minor[25]; /* 2 32-bit numbers + dash */
3164 char *endp;
3166 for (; !feof_unlocked (fdev) && !ferror_unlocked (fdev); name[0] = 0)
3168 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3169 && major == MAJOR (rdev))
3171 minor_beg = strtoul (minor, &endp, 0);
3172 if (*endp == '\0')
3173 minor_end = minor_beg;
3174 else if (*endp == '-')
3175 minor_end = strtoul (endp + 1, &endp, 0);
3176 else
3177 continue;
3179 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3181 sprintf (name + strlen (name), "%u", MINOR (rdev));
3182 break;
3186 fclose (fdev);
3188 unblock_input ();
3189 return build_string (name);
3192 static uintmax_t
3193 procfs_get_total_memory (void)
3195 FILE *fmem;
3196 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3197 int c;
3199 block_input ();
3200 fmem = emacs_fopen ("/proc/meminfo", "r");
3202 if (fmem)
3204 uintmax_t entry_value;
3205 bool done;
3208 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3210 case 1:
3211 retval = entry_value;
3212 done = 1;
3213 break;
3215 case 0:
3216 while ((c = getc_unlocked (fmem)) != EOF && c != '\n')
3217 continue;
3218 done = c == EOF;
3219 break;
3221 default:
3222 done = 1;
3223 break;
3225 while (!done);
3227 fclose (fmem);
3229 unblock_input ();
3230 return retval;
3233 Lisp_Object
3234 system_process_attributes (Lisp_Object pid)
3236 char procfn[PATH_MAX], fn[PATH_MAX];
3237 struct stat st;
3238 struct passwd *pw;
3239 struct group *gr;
3240 long clocks_per_sec;
3241 char *procfn_end;
3242 char procbuf[1025], *p, *q;
3243 int fd;
3244 ssize_t nread;
3245 static char const default_cmd[] = "???";
3246 const char *cmd = default_cmd;
3247 int cmdsize = sizeof default_cmd - 1;
3248 char *cmdline = NULL;
3249 ptrdiff_t cmdline_size;
3250 char c;
3251 printmax_t proc_id;
3252 int ppid, pgrp, sess, tty, tpgid, thcount;
3253 uid_t uid;
3254 gid_t gid;
3255 unsigned long long u_time, s_time, cutime, cstime, start;
3256 long priority, niceness, rss;
3257 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3258 struct timespec tnow, tstart, tboot, telapsed, us_time;
3259 double pcpu, pmem;
3260 Lisp_Object attrs = Qnil;
3261 Lisp_Object decoded_cmd;
3262 ptrdiff_t count;
3264 CHECK_NUMBER_OR_FLOAT (pid);
3265 CONS_TO_INTEGER (pid, pid_t, proc_id);
3266 sprintf (procfn, "/proc/%"pMd, proc_id);
3267 if (stat (procfn, &st) < 0)
3268 return attrs;
3270 /* euid egid */
3271 uid = st.st_uid;
3272 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3273 block_input ();
3274 pw = getpwuid (uid);
3275 unblock_input ();
3276 if (pw)
3277 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3279 gid = st.st_gid;
3280 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3281 block_input ();
3282 gr = getgrgid (gid);
3283 unblock_input ();
3284 if (gr)
3285 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3287 count = SPECPDL_INDEX ();
3288 strcpy (fn, procfn);
3289 procfn_end = fn + strlen (fn);
3290 strcpy (procfn_end, "/stat");
3291 fd = emacs_open (fn, O_RDONLY, 0);
3292 if (fd < 0)
3293 nread = 0;
3294 else
3296 record_unwind_protect_int (close_file_unwind, fd);
3297 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3299 if (0 < nread)
3301 procbuf[nread] = '\0';
3302 p = procbuf;
3304 p = strchr (p, '(');
3305 if (p != NULL)
3307 q = strrchr (p + 1, ')');
3308 /* comm */
3309 if (q != NULL)
3311 cmd = p + 1;
3312 cmdsize = q - cmd;
3315 else
3316 q = NULL;
3317 /* Command name is encoded in locale-coding-system; decode it. */
3318 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3319 decoded_cmd = code_convert_string_norecord (cmd_str,
3320 Vlocale_coding_system, 0);
3321 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3323 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3324 utime stime cutime cstime priority nice thcount . start vsize rss */
3325 if (q
3326 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3327 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3328 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3329 &minflt, &cminflt, &majflt, &cmajflt,
3330 &u_time, &s_time, &cutime, &cstime,
3331 &priority, &niceness, &thcount, &start, &vsize, &rss)
3332 == 20))
3334 char state_str[2];
3335 state_str[0] = c;
3336 state_str[1] = '\0';
3337 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3338 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3339 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3340 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3341 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3342 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3343 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3344 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3345 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3346 attrs);
3347 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3348 attrs);
3349 clocks_per_sec = sysconf (_SC_CLK_TCK);
3350 if (clocks_per_sec < 0)
3351 clocks_per_sec = 100;
3352 attrs = Fcons (Fcons (Qutime,
3353 ltime_from_jiffies (u_time, clocks_per_sec)),
3354 attrs);
3355 attrs = Fcons (Fcons (Qstime,
3356 ltime_from_jiffies (s_time, clocks_per_sec)),
3357 attrs);
3358 attrs = Fcons (Fcons (Qtime,
3359 ltime_from_jiffies (s_time + u_time,
3360 clocks_per_sec)),
3361 attrs);
3362 attrs = Fcons (Fcons (Qcutime,
3363 ltime_from_jiffies (cutime, clocks_per_sec)),
3364 attrs);
3365 attrs = Fcons (Fcons (Qcstime,
3366 ltime_from_jiffies (cstime, clocks_per_sec)),
3367 attrs);
3368 attrs = Fcons (Fcons (Qctime,
3369 ltime_from_jiffies (cstime + cutime,
3370 clocks_per_sec)),
3371 attrs);
3372 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3373 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3374 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3375 attrs);
3376 tnow = current_timespec ();
3377 telapsed = get_up_time ();
3378 tboot = timespec_sub (tnow, telapsed);
3379 tstart = time_from_jiffies (start, clocks_per_sec);
3380 tstart = timespec_add (tboot, tstart);
3381 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3382 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3383 attrs);
3384 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3385 telapsed = timespec_sub (tnow, tstart);
3386 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3387 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3388 pcpu = timespectod (us_time) / timespectod (telapsed);
3389 if (pcpu > 1.0)
3390 pcpu = 1.0;
3391 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3392 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3393 if (pmem > 100)
3394 pmem = 100;
3395 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3398 unbind_to (count, Qnil);
3400 /* args */
3401 strcpy (procfn_end, "/cmdline");
3402 fd = emacs_open (fn, O_RDONLY, 0);
3403 if (fd >= 0)
3405 ptrdiff_t readsize, nread_incr;
3406 record_unwind_protect_int (close_file_unwind, fd);
3407 record_unwind_protect_nothing ();
3408 nread = cmdline_size = 0;
3412 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3413 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3415 /* Leave room even if every byte needs escaping below. */
3416 readsize = (cmdline_size >> 1) - nread;
3418 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3419 nread += max (0, nread_incr);
3421 while (nread_incr == readsize);
3423 if (nread)
3425 /* We don't want trailing null characters. */
3426 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3427 continue;
3429 /* Escape-quote whitespace and backslashes. */
3430 q = cmdline + cmdline_size;
3431 while (cmdline < p)
3433 char c = *--p;
3434 *--q = c ? c : ' ';
3435 if (c_isspace (c) || c == '\\')
3436 *--q = '\\';
3439 nread = cmdline + cmdline_size - q;
3442 if (!nread)
3444 nread = cmdsize + 2;
3445 cmdline_size = nread + 1;
3446 q = cmdline = xrealloc (cmdline, cmdline_size);
3447 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3448 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3450 /* Command line is encoded in locale-coding-system; decode it. */
3451 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3452 decoded_cmd = code_convert_string_norecord (cmd_str,
3453 Vlocale_coding_system, 0);
3454 unbind_to (count, Qnil);
3455 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3458 return attrs;
3461 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3463 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3464 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3465 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3466 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3467 #undef _FILE_OFFSET_BITS
3468 #else
3469 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3470 #endif
3472 #include <procfs.h>
3474 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3475 #define _FILE_OFFSET_BITS 64
3476 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3477 #endif
3478 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3480 Lisp_Object
3481 system_process_attributes (Lisp_Object pid)
3483 char procfn[PATH_MAX], fn[PATH_MAX];
3484 struct stat st;
3485 struct passwd *pw;
3486 struct group *gr;
3487 char *procfn_end;
3488 struct psinfo pinfo;
3489 int fd;
3490 ssize_t nread;
3491 printmax_t proc_id;
3492 uid_t uid;
3493 gid_t gid;
3494 Lisp_Object attrs = Qnil;
3495 Lisp_Object decoded_cmd;
3496 ptrdiff_t count;
3498 CHECK_NUMBER_OR_FLOAT (pid);
3499 CONS_TO_INTEGER (pid, pid_t, proc_id);
3500 sprintf (procfn, "/proc/%"pMd, proc_id);
3501 if (stat (procfn, &st) < 0)
3502 return attrs;
3504 /* euid egid */
3505 uid = st.st_uid;
3506 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3507 block_input ();
3508 pw = getpwuid (uid);
3509 unblock_input ();
3510 if (pw)
3511 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3513 gid = st.st_gid;
3514 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3515 block_input ();
3516 gr = getgrgid (gid);
3517 unblock_input ();
3518 if (gr)
3519 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3521 count = SPECPDL_INDEX ();
3522 strcpy (fn, procfn);
3523 procfn_end = fn + strlen (fn);
3524 strcpy (procfn_end, "/psinfo");
3525 fd = emacs_open (fn, O_RDONLY, 0);
3526 if (fd < 0)
3527 nread = 0;
3528 else
3530 record_unwind_protect_int (close_file_unwind, fd);
3531 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3534 if (nread == sizeof pinfo)
3536 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3537 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3538 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3541 char state_str[2];
3542 state_str[0] = pinfo.pr_lwp.pr_sname;
3543 state_str[1] = '\0';
3544 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3547 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3548 need to get a string from it. */
3550 /* FIXME: missing: Qtpgid */
3552 /* FIXME: missing:
3553 Qminflt
3554 Qmajflt
3555 Qcminflt
3556 Qcmajflt
3558 Qutime
3559 Qcutime
3560 Qstime
3561 Qcstime
3562 Are they available? */
3564 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3565 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3566 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3567 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3568 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3569 attrs);
3571 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3572 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3573 attrs);
3574 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3575 attrs);
3577 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3578 range 0 .. 2**15, representing 0.0 .. 1.0. */
3579 attrs = Fcons (Fcons (Qpcpu,
3580 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3581 attrs);
3582 attrs = Fcons (Fcons (Qpmem,
3583 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3584 attrs);
3586 AUTO_STRING (fname, pinfo.pr_fname);
3587 decoded_cmd = code_convert_string_norecord (fname,
3588 Vlocale_coding_system, 0);
3589 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3590 AUTO_STRING (psargs, pinfo.pr_psargs);
3591 decoded_cmd = code_convert_string_norecord (psargs,
3592 Vlocale_coding_system, 0);
3593 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3595 unbind_to (count, Qnil);
3596 return attrs;
3599 #elif defined __FreeBSD__
3601 static struct timespec
3602 timeval_to_timespec (struct timeval t)
3604 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3607 static Lisp_Object
3608 make_lisp_timeval (struct timeval t)
3610 return make_lisp_time (timeval_to_timespec (t));
3613 Lisp_Object
3614 system_process_attributes (Lisp_Object pid)
3616 int proc_id;
3617 int pagesize = getpagesize ();
3618 unsigned long npages;
3619 int fscale;
3620 struct passwd *pw;
3621 struct group *gr;
3622 char *ttyname;
3623 size_t len;
3624 char args[MAXPATHLEN];
3625 struct timespec t, now;
3627 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3628 struct kinfo_proc proc;
3629 size_t proclen = sizeof proc;
3631 Lisp_Object attrs = Qnil;
3632 Lisp_Object decoded_comm;
3634 CHECK_NUMBER_OR_FLOAT (pid);
3635 CONS_TO_INTEGER (pid, int, proc_id);
3636 mib[3] = proc_id;
3638 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3639 return attrs;
3641 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3643 block_input ();
3644 pw = getpwuid (proc.ki_uid);
3645 unblock_input ();
3646 if (pw)
3647 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3649 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3651 block_input ();
3652 gr = getgrgid (proc.ki_svgid);
3653 unblock_input ();
3654 if (gr)
3655 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3657 AUTO_STRING (comm, proc.ki_comm);
3658 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3660 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3662 char state[2] = {'\0', '\0'};
3663 switch (proc.ki_stat)
3665 case SRUN:
3666 state[0] = 'R';
3667 break;
3669 case SSLEEP:
3670 state[0] = 'S';
3671 break;
3673 case SLOCK:
3674 state[0] = 'D';
3675 break;
3677 case SZOMB:
3678 state[0] = 'Z';
3679 break;
3681 case SSTOP:
3682 state[0] = 'T';
3683 break;
3685 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3688 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3689 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3690 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3692 block_input ();
3693 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3694 unblock_input ();
3695 if (ttyname)
3696 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3698 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3699 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3700 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3701 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3702 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3704 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3705 attrs);
3706 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3707 attrs);
3708 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3709 timeval_to_timespec (proc.ki_rusage.ru_stime));
3710 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3712 attrs = Fcons (Fcons (Qcutime,
3713 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3714 attrs);
3715 attrs = Fcons (Fcons (Qcstime,
3716 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3717 attrs);
3718 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3719 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3720 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3722 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3723 attrs);
3724 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3725 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3726 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3727 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3728 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3729 attrs);
3731 now = current_timespec ();
3732 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3733 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3735 len = sizeof fscale;
3736 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3738 double pcpu;
3739 fixpt_t ccpu;
3740 len = sizeof ccpu;
3741 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3743 pcpu = (100.0 * proc.ki_pctcpu / fscale
3744 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3745 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3749 len = sizeof npages;
3750 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3752 double pmem = (proc.ki_flag & P_INMEM
3753 ? 100.0 * proc.ki_rssize / npages
3754 : 0);
3755 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3758 mib[2] = KERN_PROC_ARGS;
3759 len = MAXPATHLEN;
3760 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3762 int i;
3763 for (i = 0; i < len; i++)
3765 if (! args[i] && i < len - 1)
3766 args[i] = ' ';
3769 AUTO_STRING (comm, args);
3770 decoded_comm = code_convert_string_norecord (comm,
3771 Vlocale_coding_system, 0);
3773 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3776 return attrs;
3779 #elif defined DARWIN_OS
3781 static struct timespec
3782 timeval_to_timespec (struct timeval t)
3784 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3787 static Lisp_Object
3788 make_lisp_timeval (struct timeval t)
3790 return make_lisp_time (timeval_to_timespec (t));
3793 Lisp_Object
3794 system_process_attributes (Lisp_Object pid)
3796 int proc_id;
3797 struct passwd *pw;
3798 struct group *gr;
3799 char *ttyname;
3800 struct timeval starttime;
3801 struct timespec t, now;
3802 struct rusage *rusage;
3803 dev_t tdev;
3804 uid_t uid;
3805 gid_t gid;
3807 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3808 struct kinfo_proc proc;
3809 size_t proclen = sizeof proc;
3811 Lisp_Object attrs = Qnil;
3812 Lisp_Object decoded_comm;
3814 CHECK_NUMBER_OR_FLOAT (pid);
3815 CONS_TO_INTEGER (pid, int, proc_id);
3816 mib[3] = proc_id;
3818 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3819 return attrs;
3821 uid = proc.kp_eproc.e_ucred.cr_uid;
3822 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3824 block_input ();
3825 pw = getpwuid (uid);
3826 unblock_input ();
3827 if (pw)
3828 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3830 gid = proc.kp_eproc.e_pcred.p_svgid;
3831 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3833 block_input ();
3834 gr = getgrgid (gid);
3835 unblock_input ();
3836 if (gr)
3837 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3839 decoded_comm = (code_convert_string_norecord
3840 (build_unibyte_string (proc.kp_proc.p_comm),
3841 Vlocale_coding_system, 0));
3843 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3845 char state[2] = {'\0', '\0'};
3846 switch (proc.kp_proc.p_stat)
3848 case SRUN:
3849 state[0] = 'R';
3850 break;
3852 case SSLEEP:
3853 state[0] = 'S';
3854 break;
3856 case SZOMB:
3857 state[0] = 'Z';
3858 break;
3860 case SSTOP:
3861 state[0] = 'T';
3862 break;
3864 case SIDL:
3865 state[0] = 'I';
3866 break;
3868 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3871 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3872 attrs);
3873 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3874 attrs);
3876 tdev = proc.kp_eproc.e_tdev;
3877 block_input ();
3878 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3879 unblock_input ();
3880 if (ttyname)
3881 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3883 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3884 attrs);
3886 rusage = proc.kp_proc.p_ru;
3887 if (rusage)
3889 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3890 attrs);
3891 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3892 attrs);
3894 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3895 attrs);
3896 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3897 attrs);
3898 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3899 timeval_to_timespec (rusage->ru_stime));
3900 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3903 starttime = proc.kp_proc.p_starttime;
3904 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3905 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3907 now = current_timespec ();
3908 t = timespec_sub (now, timeval_to_timespec (starttime));
3909 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3911 return attrs;
3914 /* The WINDOWSNT implementation is in w32.c.
3915 The MSDOS implementation is in dosfns.c. */
3916 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3918 Lisp_Object
3919 system_process_attributes (Lisp_Object pid)
3921 return Qnil;
3924 #endif /* !defined (WINDOWSNT) */
3926 /* Wide character string collation. */
3928 #ifdef __STDC_ISO_10646__
3929 # include <wchar.h>
3930 # include <wctype.h>
3932 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3933 # include <locale.h>
3934 # endif
3935 # ifndef LC_COLLATE
3936 # define LC_COLLATE 0
3937 # endif
3938 # ifndef LC_COLLATE_MASK
3939 # define LC_COLLATE_MASK 0
3940 # endif
3941 # ifndef LC_CTYPE
3942 # define LC_CTYPE 0
3943 # endif
3944 # ifndef LC_CTYPE_MASK
3945 # define LC_CTYPE_MASK 0
3946 # endif
3948 # ifndef HAVE_NEWLOCALE
3949 # undef freelocale
3950 # undef locale_t
3951 # undef newlocale
3952 # undef wcscoll_l
3953 # undef towlower_l
3954 # define freelocale emacs_freelocale
3955 # define locale_t emacs_locale_t
3956 # define newlocale emacs_newlocale
3957 # define wcscoll_l emacs_wcscoll_l
3958 # define towlower_l emacs_towlower_l
3960 typedef char const *locale_t;
3962 static locale_t
3963 newlocale (int category_mask, char const *locale, locale_t loc)
3965 return locale;
3968 static void
3969 freelocale (locale_t loc)
3973 static char *
3974 emacs_setlocale (int category, char const *locale)
3976 # ifdef HAVE_SETLOCALE
3977 errno = 0;
3978 char *loc = setlocale (category, locale);
3979 if (loc || errno)
3980 return loc;
3981 errno = EINVAL;
3982 # else
3983 errno = ENOTSUP;
3984 # endif
3985 return 0;
3988 static int
3989 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3991 int result = 0;
3992 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3993 int err;
3995 if (! oldloc)
3996 err = errno;
3997 else
3999 USE_SAFE_ALLOCA;
4000 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
4001 strcpy (oldcopy, oldloc);
4002 if (! emacs_setlocale (LC_COLLATE, loc))
4003 err = errno;
4004 else
4006 errno = 0;
4007 result = wcscoll (a, b);
4008 err = errno;
4009 if (! emacs_setlocale (LC_COLLATE, oldcopy))
4010 err = errno;
4012 SAFE_FREE ();
4015 errno = err;
4016 return result;
4019 static wint_t
4020 towlower_l (wint_t wc, locale_t loc)
4022 wint_t result = wc;
4023 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
4025 if (oldloc)
4027 USE_SAFE_ALLOCA;
4028 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
4029 strcpy (oldcopy, oldloc);
4030 if (emacs_setlocale (LC_CTYPE, loc))
4032 result = towlower (wc);
4033 emacs_setlocale (LC_COLLATE, oldcopy);
4035 SAFE_FREE ();
4038 return result;
4040 # endif
4043 str_collate (Lisp_Object s1, Lisp_Object s2,
4044 Lisp_Object locale, Lisp_Object ignore_case)
4046 int res, err;
4047 ptrdiff_t len, i, i_byte;
4048 wchar_t *p1, *p2;
4050 USE_SAFE_ALLOCA;
4052 /* Convert byte stream to code points. */
4053 len = SCHARS (s1); i = i_byte = 0;
4054 SAFE_NALLOCA (p1, 1, len + 1);
4055 while (i < len)
4056 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
4057 *(p1+len) = 0;
4059 len = SCHARS (s2); i = i_byte = 0;
4060 SAFE_NALLOCA (p2, 1, len + 1);
4061 while (i < len)
4062 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
4063 *(p2+len) = 0;
4065 if (STRINGP (locale))
4067 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
4068 SSDATA (locale), 0);
4069 if (!loc)
4070 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4072 if (! NILP (ignore_case))
4073 for (int i = 1; i < 3; i++)
4075 wchar_t *p = (i == 1) ? p1 : p2;
4076 for (; *p; p++)
4077 *p = towlower_l (*p, loc);
4080 errno = 0;
4081 res = wcscoll_l (p1, p2, loc);
4082 err = errno;
4083 freelocale (loc);
4085 else
4087 if (! NILP (ignore_case))
4088 for (int i = 1; i < 3; i++)
4090 wchar_t *p = (i == 1) ? p1 : p2;
4091 for (; *p; p++)
4092 *p = towlower (*p);
4095 errno = 0;
4096 res = wcscoll (p1, p2);
4097 err = errno;
4099 # ifndef HAVE_NEWLOCALE
4100 if (err)
4101 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4102 # else
4103 if (err)
4104 error ("Invalid string for collation: %s", emacs_strerror (err));
4105 # endif
4107 SAFE_FREE ();
4108 return res;
4110 #endif /* __STDC_ISO_10646__ */
4112 #ifdef WINDOWSNT
4114 str_collate (Lisp_Object s1, Lisp_Object s2,
4115 Lisp_Object locale, Lisp_Object ignore_case)
4118 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4119 int res, err = errno;
4121 errno = 0;
4122 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4123 if (errno)
4124 error ("Invalid string for collation: %s", strerror (errno));
4126 errno = err;
4127 return res;
4129 #endif /* WINDOWSNT */