; Typo fixes, mostly repeated words
[emacs.git] / src / sysdep.c
blobdd0062b6f04f243926b6bbf5cc7ef8261ed5e2d4
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2017 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <execinfo.h>
23 #include "sysstdio.h"
24 #ifdef HAVE_PWD_H
25 #include <pwd.h>
26 #include <grp.h>
27 #endif /* HAVE_PWD_H */
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
33 #include <utimens.h>
35 #include "lisp.h"
36 #include "sheap.h"
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #ifdef HAVE_LINUX_FS_H
41 # include <linux/fs.h>
42 # include <sys/syscall.h>
43 #endif
45 #ifdef CYGWIN
46 # include <cygwin/fs.h>
47 #endif
49 #if defined DARWIN_OS || defined __FreeBSD__
50 # include <sys/sysctl.h>
51 #endif
53 #ifdef __FreeBSD__
54 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
55 'struct frame', so rename it. */
56 # define frame freebsd_frame
57 # include <sys/user.h>
58 # undef frame
60 # include <math.h>
61 #endif
63 #ifdef HAVE_SOCKETS
64 #include <sys/socket.h>
65 #include <netdb.h>
66 #endif /* HAVE_SOCKETS */
68 #ifdef WINDOWSNT
69 #define read sys_read
70 #define write sys_write
71 #ifndef STDERR_FILENO
72 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
73 #endif
74 #include "w32.h"
75 #endif /* WINDOWSNT */
77 #include <sys/types.h>
78 #include <sys/stat.h>
79 #include <errno.h>
81 /* Get SI_SRPC_DOMAIN, if it is available. */
82 #ifdef HAVE_SYS_SYSTEMINFO_H
83 #include <sys/systeminfo.h>
84 #endif
86 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
87 #include "msdos.h"
88 #endif
90 #include <sys/param.h>
91 #include <sys/file.h>
92 #include <fcntl.h>
94 #include "systty.h"
95 #include "syswait.h"
97 #ifdef HAVE_SYS_UTSNAME_H
98 #include <sys/utsname.h>
99 #include <memory.h>
100 #endif /* HAVE_SYS_UTSNAME_H */
102 #include "keyboard.h"
103 #include "frame.h"
104 #include "termhooks.h"
105 #include "termchar.h"
106 #include "termopts.h"
107 #include "process.h"
108 #include "cm.h"
110 #include "gnutls.h"
111 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
112 do that during startup just to call gnutls_rnd. */
113 #if defined HAVE_GNUTLS && !defined WINDOWSNT
114 # include <gnutls/crypto.h>
115 #else
116 # define emacs_gnutls_global_init() Qnil
117 # define gnutls_rnd(level, data, len) (-1)
118 #endif
120 #ifdef WINDOWSNT
121 #include <direct.h>
122 /* In process.h which conflicts with the local copy. */
123 #define _P_WAIT 0
124 int _cdecl _spawnlp (int, const char *, const char *, ...);
125 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
126 several prototypes of functions called below. */
127 #include <sys/socket.h>
128 #endif
130 #include "syssignal.h"
131 #include "systime.h"
133 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
134 #ifndef ULLONG_MAX
135 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
136 #endif
138 /* Declare here, including term.h is problematic on some systems. */
139 extern void tputs (const char *, int, int (*)(int));
141 static const int baud_convert[] =
143 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
144 1800, 2400, 4800, 9600, 19200, 38400
147 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
148 # include <sys/personality.h>
150 /* Disable address randomization in the current process. Return true
151 if addresses were randomized but this has been disabled, false
152 otherwise. */
153 bool
154 disable_address_randomization (void)
156 int pers = personality (0xffffffff);
157 if (pers < 0)
158 return false;
159 int desired_pers = pers | ADDR_NO_RANDOMIZE;
161 /* Call 'personality' twice, to detect buggy platforms like WSL
162 where 'personality' always returns 0. */
163 return (pers != desired_pers
164 && personality (desired_pers) == pers
165 && personality (0xffffffff) == desired_pers);
167 #endif
169 /* Execute the program in FILE, with argument vector ARGV and environ
170 ENVP. Return an error number if unsuccessful. This is like execve
171 except it reenables ASLR in the executed program if necessary, and
172 on error it returns an error number rather than -1. */
174 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
176 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
177 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
178 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
179 if (change_personality)
180 personality (pers & ~ADDR_NO_RANDOMIZE);
181 #endif
183 execve (file, argv, envp);
184 int err = errno;
186 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
187 if (change_personality)
188 personality (pers);
189 #endif
191 return err;
194 /* If FD is not already open, arrange for it to be open with FLAGS. */
195 static void
196 force_open (int fd, int flags)
198 if (dup2 (fd, fd) < 0 && errno == EBADF)
200 int n = open (NULL_DEVICE, flags);
201 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
203 emacs_perror (NULL_DEVICE);
204 exit (EXIT_FAILURE);
209 /* Make sure stdin, stdout, and stderr are open to something, so that
210 their file descriptors are not hijacked by later system calls. */
211 void
212 init_standard_fds (void)
214 /* Open stdin for *writing*, and stdout and stderr for *reading*.
215 That way, any attempt to do normal I/O will result in an error,
216 just as if the files were closed, and the file descriptors will
217 not be reused by later opens. */
218 force_open (STDIN_FILENO, O_WRONLY);
219 force_open (STDOUT_FILENO, O_RDONLY);
220 force_open (STDERR_FILENO, O_RDONLY);
223 /* Return the current working directory. The result should be freed
224 with 'free'. Return NULL (setting errno) on errors. If the
225 current directory is unreachable, return either NULL or a string
226 beginning with '('. */
228 static char *
229 get_current_dir_name_or_unreachable (void)
231 /* Use malloc, not xmalloc, since this function can be called before
232 the xmalloc exception machinery is available. */
234 char *pwd;
236 /* The maximum size of a directory name, including the terminating null.
237 Leave room so that the caller can append a trailing slash. */
238 ptrdiff_t dirsize_max = min (PTRDIFF_MAX, SIZE_MAX) - 1;
240 /* The maximum size of a buffer for a file name, including the
241 terminating null. This is bounded by MAXPATHLEN, if available. */
242 ptrdiff_t bufsize_max = dirsize_max;
243 #ifdef MAXPATHLEN
244 bufsize_max = min (bufsize_max, MAXPATHLEN);
245 #endif
247 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
248 # ifdef HYBRID_MALLOC
249 bool use_libc = bss_sbrk_did_unexec;
250 # else
251 bool use_libc = true;
252 # endif
253 if (use_libc)
255 /* For an unreachable directory, this returns a string that starts
256 with "(unreachable)"; see Bug#27871. */
257 pwd = get_current_dir_name ();
258 if (pwd)
260 if (strlen (pwd) < dirsize_max)
261 return pwd;
262 free (pwd);
263 errno = ERANGE;
265 return NULL;
267 # endif
269 size_t pwdlen;
270 struct stat dotstat, pwdstat;
271 pwd = getenv ("PWD");
273 /* If PWD is accurate, use it instead of calling getcwd. PWD is
274 sometimes a nicer name, and using it may avoid a fatal error if a
275 parent directory is searchable but not readable. */
276 if (pwd
277 && (pwdlen = strlen (pwd)) < bufsize_max
278 && IS_DIRECTORY_SEP (pwd[pwdlen && IS_DEVICE_SEP (pwd[1]) ? 2 : 0])
279 && stat (pwd, &pwdstat) == 0
280 && stat (".", &dotstat) == 0
281 && dotstat.st_ino == pwdstat.st_ino
282 && dotstat.st_dev == pwdstat.st_dev)
284 char *buf = malloc (pwdlen + 1);
285 if (!buf)
286 return NULL;
287 return memcpy (buf, pwd, pwdlen + 1);
289 else
291 ptrdiff_t buf_size = min (bufsize_max, 1024);
292 char *buf = malloc (buf_size);
293 if (!buf)
294 return NULL;
295 for (;;)
297 if (getcwd (buf, buf_size) == buf)
298 return buf;
299 int getcwd_errno = errno;
300 if (getcwd_errno != ERANGE || buf_size == bufsize_max)
302 free (buf);
303 errno = getcwd_errno;
304 return NULL;
306 buf_size = buf_size <= bufsize_max / 2 ? 2 * buf_size : bufsize_max;
307 buf = realloc (buf, buf_size);
308 if (!buf)
309 return NULL;
314 /* Return the current working directory. The result should be freed
315 with 'free'. Return NULL (setting errno) on errors; an unreachable
316 directory (e.g., its name starts with '(') counts as an error. */
318 char *
319 emacs_get_current_dir_name (void)
321 char *dir = get_current_dir_name_or_unreachable ();
322 if (dir && *dir == '(')
324 free (dir);
325 errno = ENOENT;
326 return NULL;
328 return dir;
332 /* Discard pending input on all input descriptors. */
334 void
335 discard_tty_input (void)
337 #ifndef WINDOWSNT
338 struct emacs_tty buf;
340 if (noninteractive)
341 return;
343 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
344 while (dos_keyread () != -1)
346 #else /* not MSDOS */
348 struct tty_display_info *tty;
349 for (tty = tty_list; tty; tty = tty->next)
351 if (tty->input) /* Is the device suspended? */
353 emacs_get_tty (fileno (tty->input), &buf);
354 emacs_set_tty (fileno (tty->input), &buf, 0);
358 #endif /* not MSDOS */
359 #endif /* not WINDOWSNT */
363 #ifdef SIGTSTP
365 /* Arrange for character C to be read as the next input from
366 the terminal.
367 XXX What if we have multiple ttys?
370 void
371 stuff_char (char c)
373 if (! (FRAMEP (selected_frame)
374 && FRAME_LIVE_P (XFRAME (selected_frame))
375 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
376 return;
378 /* Should perhaps error if in batch mode */
379 #ifdef TIOCSTI
380 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
381 #else /* no TIOCSTI */
382 error ("Cannot stuff terminal input characters in this version of Unix");
383 #endif /* no TIOCSTI */
386 #endif /* SIGTSTP */
388 void
389 init_baud_rate (int fd)
391 int emacs_ospeed;
393 if (noninteractive)
394 emacs_ospeed = 0;
395 else
397 #ifdef DOS_NT
398 emacs_ospeed = 15;
399 #else /* not DOS_NT */
400 struct termios sg;
402 sg.c_cflag = B9600;
403 tcgetattr (fd, &sg);
404 emacs_ospeed = cfgetospeed (&sg);
405 #endif /* not DOS_NT */
408 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
409 ? baud_convert[emacs_ospeed] : 9600);
410 if (baud_rate == 0)
411 baud_rate = 1200;
416 #ifndef MSDOS
418 /* Wait for the subprocess with process id CHILD to terminate or change status.
419 CHILD must be a child process that has not been reaped.
420 If STATUS is non-null, store the waitpid-style exit status into *STATUS
421 and tell wait_reading_process_output that it needs to look around.
422 Use waitpid-style OPTIONS when waiting.
423 If INTERRUPTIBLE, this function is interruptible by a signal.
425 Return CHILD if successful, 0 if no status is available, and a
426 negative value (setting errno) if waitpid is buggy. */
427 static pid_t
428 get_child_status (pid_t child, int *status, int options, bool interruptible)
430 pid_t pid;
432 /* Invoke waitpid only with a known process ID; do not invoke
433 waitpid with a nonpositive argument. Otherwise, Emacs might
434 reap an unwanted process by mistake. For example, invoking
435 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
436 so that another thread running glib won't find them. */
437 eassert (child > 0);
439 while (true)
441 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
442 internally. */
443 if (interruptible)
444 maybe_quit ();
446 pid = waitpid (child, status, options);
447 if (0 <= pid)
448 break;
449 if (errno != EINTR)
451 /* Most likely, waitpid is buggy and the operating system
452 lost track of the child somehow. Return -1 and let the
453 caller try to figure things out. Possibly the bug could
454 cause Emacs to kill the wrong process. Oh well. */
455 return pid;
459 /* If successful and status is requested, tell wait_reading_process_output
460 that it needs to wake up and look around. */
461 if (pid && status && input_available_clear_time)
462 *input_available_clear_time = make_timespec (0, 0);
464 return pid;
467 /* Wait for the subprocess with process id CHILD to terminate.
468 CHILD must be a child process that has not been reaped.
469 If STATUS is non-null, store the waitpid-style exit status into *STATUS
470 and tell wait_reading_process_output that it needs to look around.
471 If INTERRUPTIBLE, this function is interruptible by a signal.
472 Return true if successful, false (setting errno) if CHILD cannot be
473 waited for because waitpid is buggy. */
474 bool
475 wait_for_termination (pid_t child, int *status, bool interruptible)
477 return 0 <= get_child_status (child, status, 0, interruptible);
480 /* Report whether the subprocess with process id CHILD has changed status.
481 Termination counts as a change of status.
482 CHILD must be a child process that has not been reaped.
483 If STATUS is non-null, store the waitpid-style exit status into *STATUS
484 and tell wait_reading_process_output that it needs to look around.
485 Use waitpid-style OPTIONS to check status, but do not wait.
487 Return CHILD if successful, 0 if no status is available because
488 the process's state has not changed. */
489 pid_t
490 child_status_changed (pid_t child, int *status, int options)
492 return get_child_status (child, status, WNOHANG | options, 0);
496 /* Set up the terminal at the other end of a pseudo-terminal that
497 we will be controlling an inferior through.
498 It should not echo or do line-editing, since that is done
499 in Emacs. No padding needed for insertion into an Emacs buffer. */
501 void
502 child_setup_tty (int out)
504 #ifndef WINDOWSNT
505 struct emacs_tty s;
507 emacs_get_tty (out, &s);
508 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
509 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
510 #ifdef NLDLY
511 /* https://lists.gnu.org/archive/html/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 /* Block SIGINT. */
835 void
836 block_interrupt_signal (sigset_t *oldset)
838 sigset_t blocked;
839 sigemptyset (&blocked);
840 sigaddset (&blocked, SIGINT);
841 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
844 /* Restore previously saved signal mask. */
845 void
846 restore_signal_mask (sigset_t const *oldset)
848 pthread_sigmask (SIG_SETMASK, oldset, 0);
851 #endif /* !MSDOS */
853 /* Saving and restoring the process group of Emacs's terminal. */
855 /* The process group of which Emacs was a member when it initially
856 started.
858 If Emacs was in its own process group (i.e. inherited_pgroup ==
859 getpid ()), then we know we're running under a shell with job
860 control (Emacs would never be run as part of a pipeline).
861 Everything is fine.
863 If Emacs was not in its own process group, then we know we're
864 running under a shell (or a caller) that doesn't know how to
865 separate itself from Emacs (like sh). Emacs must be in its own
866 process group in order to receive SIGIO correctly. In this
867 situation, we put ourselves in our own pgroup, forcibly set the
868 tty's pgroup to our pgroup, and make sure to restore and reinstate
869 the tty's pgroup just like any other terminal setting. If
870 inherited_group was not the tty's pgroup, then we'll get a
871 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
872 it goes foreground in the future, which is what should happen. */
874 static pid_t inherited_pgroup;
876 void
877 init_foreground_group (void)
879 pid_t pgrp = getpgrp ();
880 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
883 /* Block and unblock SIGTTOU. */
885 void
886 block_tty_out_signal (sigset_t *oldset)
888 #ifdef SIGTTOU
889 sigset_t blocked;
890 sigemptyset (&blocked);
891 sigaddset (&blocked, SIGTTOU);
892 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
893 #endif
896 void
897 unblock_tty_out_signal (sigset_t const *oldset)
899 #ifdef SIGTTOU
900 pthread_sigmask (SIG_SETMASK, oldset, 0);
901 #endif
904 /* Safely set a controlling terminal FD's process group to PGID.
905 If we are not in the foreground already, POSIX requires tcsetpgrp
906 to deliver a SIGTTOU signal, which would stop us. This is an
907 annoyance, so temporarily ignore the signal.
909 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
910 skip all this unless SIGTTOU is defined. */
911 static void
912 tcsetpgrp_without_stopping (int fd, pid_t pgid)
914 #ifdef SIGTTOU
915 sigset_t oldset;
916 block_input ();
917 block_tty_out_signal (&oldset);
918 tcsetpgrp (fd, pgid);
919 unblock_tty_out_signal (&oldset);
920 unblock_input ();
921 #endif
924 /* Split off the foreground process group to Emacs alone. When we are
925 in the foreground, but not started in our own process group,
926 redirect the tty device handle FD to point to our own process
927 group. FD must be the file descriptor of the controlling tty. */
928 static void
929 narrow_foreground_group (int fd)
931 if (inherited_pgroup && setpgid (0, 0) == 0)
932 tcsetpgrp_without_stopping (fd, getpid ());
935 /* Set the tty to our original foreground group. */
936 static void
937 widen_foreground_group (int fd)
939 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
940 tcsetpgrp_without_stopping (fd, inherited_pgroup);
943 /* Getting and setting emacs_tty structures. */
945 /* Set *TC to the parameters associated with the terminal FD,
946 or clear it if the parameters are not available.
947 Return 0 on success, -1 on failure. */
949 emacs_get_tty (int fd, struct emacs_tty *settings)
951 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
952 memset (&settings->main, 0, sizeof (settings->main));
953 #ifdef DOS_NT
954 #ifdef WINDOWSNT
955 HANDLE h = (HANDLE)_get_osfhandle (fd);
956 DWORD console_mode;
958 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
960 settings->main = console_mode;
961 return 0;
963 #endif /* WINDOWSNT */
964 return -1;
965 #else /* !DOS_NT */
966 /* We have those nifty POSIX tcmumbleattr functions. */
967 return tcgetattr (fd, &settings->main);
968 #endif
972 /* Set the parameters of the tty on FD according to the contents of
973 *SETTINGS. If FLUSHP, discard input.
974 Return 0 if all went well, and -1 (setting errno) if anything failed. */
977 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
979 /* Set the primary parameters - baud rate, character size, etcetera. */
980 #ifdef DOS_NT
981 #ifdef WINDOWSNT
982 HANDLE h = (HANDLE)_get_osfhandle (fd);
984 if (h && h != INVALID_HANDLE_VALUE)
986 DWORD new_mode;
988 /* Assume the handle is open for input. */
989 if (flushp)
990 FlushConsoleInputBuffer (h);
991 new_mode = settings->main;
992 SetConsoleMode (h, new_mode);
994 #endif /* WINDOWSNT */
995 #else /* !DOS_NT */
996 int i;
997 /* We have those nifty POSIX tcmumbleattr functions.
998 William J. Smith <wjs@wiis.wang.com> writes:
999 "POSIX 1003.1 defines tcsetattr to return success if it was
1000 able to perform any of the requested actions, even if some
1001 of the requested actions could not be performed.
1002 We must read settings back to ensure tty setup properly.
1003 AIX requires this to keep tty from hanging occasionally." */
1004 /* This make sure that we don't loop indefinitely in here. */
1005 for (i = 0 ; i < 10 ; i++)
1006 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
1008 if (errno == EINTR)
1009 continue;
1010 else
1011 return -1;
1013 else
1015 struct termios new;
1017 memset (&new, 0, sizeof (new));
1018 /* Get the current settings, and see if they're what we asked for. */
1019 tcgetattr (fd, &new);
1020 /* We cannot use memcmp on the whole structure here because under
1021 * aix386 the termios structure has some reserved field that may
1022 * not be filled in.
1024 if ( new.c_iflag == settings->main.c_iflag
1025 && new.c_oflag == settings->main.c_oflag
1026 && new.c_cflag == settings->main.c_cflag
1027 && new.c_lflag == settings->main.c_lflag
1028 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
1029 break;
1030 else
1031 continue;
1033 #endif
1035 /* We have survived the tempest. */
1036 return 0;
1041 #ifdef F_SETOWN
1042 static int old_fcntl_owner[FD_SETSIZE];
1043 #endif /* F_SETOWN */
1045 /* This may also be defined in stdio,
1046 but if so, this does no harm,
1047 and using the same name avoids wasting the other one's space. */
1049 #if defined (USG)
1050 unsigned char _sobuf[BUFSIZ+8];
1051 #else
1052 char _sobuf[BUFSIZ];
1053 #endif
1055 /* Initialize the terminal mode on all tty devices that are currently
1056 open. */
1058 void
1059 init_all_sys_modes (void)
1061 struct tty_display_info *tty;
1062 for (tty = tty_list; tty; tty = tty->next)
1063 init_sys_modes (tty);
1066 /* Initialize the terminal mode on the given tty device. */
1068 void
1069 init_sys_modes (struct tty_display_info *tty_out)
1071 struct emacs_tty tty;
1072 #ifndef DOS_NT
1073 Lisp_Object terminal;
1074 #endif
1076 Vtty_erase_char = Qnil;
1078 if (noninteractive)
1079 return;
1081 if (!tty_out->output)
1082 return; /* The tty is suspended. */
1084 narrow_foreground_group (fileno (tty_out->input));
1086 if (! tty_out->old_tty)
1087 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1089 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1091 tty = *tty_out->old_tty;
1093 #if !defined (DOS_NT)
1094 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1096 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1097 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1098 #ifdef INLCR /* I'm just being cautious,
1099 since I can't check how widespread INLCR is--rms. */
1100 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1101 #endif
1102 #ifdef ISTRIP
1103 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1104 #endif
1105 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1106 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1107 #ifdef IEXTEN
1108 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1109 #endif
1110 tty.main.c_lflag |= ISIG; /* Enable signals */
1111 if (tty_out->flow_control)
1113 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1114 #ifdef IXANY
1115 tty.main.c_iflag &= ~IXANY;
1116 #endif /* IXANY */
1118 else
1119 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1120 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1121 on output */
1122 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1123 #ifdef CS8
1124 if (tty_out->meta_key)
1126 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1127 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1129 #endif
1131 XSETTERMINAL(terminal, tty_out->terminal);
1132 if (!NILP (Fcontrolling_tty_p (terminal)))
1134 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1135 /* Set up C-g for both SIGQUIT and SIGINT.
1136 We don't know which we will get, but we handle both alike
1137 so which one it really gives us does not matter. */
1138 tty.main.c_cc[VQUIT] = quit_char;
1140 else
1142 /* We normally don't get interrupt or quit signals from tty
1143 devices other than our controlling terminal; therefore,
1144 we must handle C-g as normal input. Unfortunately, this
1145 means that the interrupt and quit feature must be
1146 disabled on secondary ttys, or we would not even see the
1147 keypress.
1149 Note that even though emacsclient could have special code
1150 to pass SIGINT to Emacs, we should _not_ enable
1151 interrupt/quit keys for emacsclient frames. This means
1152 that we can't break out of loops in C code from a
1153 secondary tty frame, but we can always decide what
1154 display the C-g came from, which is more important from a
1155 usability point of view. (Consider the case when two
1156 people work together using the same Emacs instance.) */
1157 tty.main.c_cc[VINTR] = CDISABLE;
1158 tty.main.c_cc[VQUIT] = CDISABLE;
1160 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1161 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1162 #ifdef VSWTCH
1163 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1164 of C-z */
1165 #endif /* VSWTCH */
1167 #ifdef VSUSP
1168 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1169 #endif /* VSUSP */
1170 #ifdef V_DSUSP
1171 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1172 #endif /* V_DSUSP */
1173 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1174 tty.main.c_cc[VDSUSP] = CDISABLE;
1175 #endif /* VDSUSP */
1176 #ifdef VLNEXT
1177 tty.main.c_cc[VLNEXT] = CDISABLE;
1178 #endif /* VLNEXT */
1179 #ifdef VREPRINT
1180 tty.main.c_cc[VREPRINT] = CDISABLE;
1181 #endif /* VREPRINT */
1182 #ifdef VWERASE
1183 tty.main.c_cc[VWERASE] = CDISABLE;
1184 #endif /* VWERASE */
1185 #ifdef VDISCARD
1186 tty.main.c_cc[VDISCARD] = CDISABLE;
1187 #endif /* VDISCARD */
1189 if (tty_out->flow_control)
1191 #ifdef VSTART
1192 tty.main.c_cc[VSTART] = '\021';
1193 #endif /* VSTART */
1194 #ifdef VSTOP
1195 tty.main.c_cc[VSTOP] = '\023';
1196 #endif /* VSTOP */
1198 else
1200 #ifdef VSTART
1201 tty.main.c_cc[VSTART] = CDISABLE;
1202 #endif /* VSTART */
1203 #ifdef VSTOP
1204 tty.main.c_cc[VSTOP] = CDISABLE;
1205 #endif /* VSTOP */
1208 #ifdef AIX
1209 tty.main.c_cc[VSTRT] = CDISABLE;
1210 tty.main.c_cc[VSTOP] = CDISABLE;
1211 tty.main.c_cc[VSUSP] = CDISABLE;
1212 tty.main.c_cc[VDSUSP] = CDISABLE;
1213 if (tty_out->flow_control)
1215 #ifdef VSTART
1216 tty.main.c_cc[VSTART] = '\021';
1217 #endif /* VSTART */
1218 #ifdef VSTOP
1219 tty.main.c_cc[VSTOP] = '\023';
1220 #endif /* VSTOP */
1222 /* Also, PTY overloads NUL and BREAK.
1223 don't ignore break, but don't signal either, so it looks like NUL.
1224 This really serves a purpose only if running in an XTERM window
1225 or via TELNET or the like, but does no harm elsewhere. */
1226 tty.main.c_iflag &= ~IGNBRK;
1227 tty.main.c_iflag &= ~BRKINT;
1228 #endif
1229 #endif /* not DOS_NT */
1231 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1232 if (!tty_out->term_initted)
1233 internal_terminal_init ();
1234 dos_ttraw (tty_out);
1235 #endif
1237 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1239 /* This code added to insure that, if flow-control is not to be used,
1240 we have an unlocked terminal at the start. */
1242 #ifdef TCXONC
1243 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1244 #endif
1245 #ifdef TIOCSTART
1246 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1247 #endif
1249 #if !defined (DOS_NT)
1250 #ifdef TCOON
1251 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1252 #endif
1253 #endif
1255 #ifdef F_GETOWN
1256 if (interrupt_input)
1258 old_fcntl_owner[fileno (tty_out->input)] =
1259 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1260 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1261 init_sigio (fileno (tty_out->input));
1262 #ifdef HAVE_GPM
1263 if (gpm_tty == tty_out)
1265 /* Arrange for mouse events to give us SIGIO signals. */
1266 fcntl (gpm_fd, F_SETOWN, getpid ());
1267 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1268 init_sigio (gpm_fd);
1270 #endif /* HAVE_GPM */
1272 #endif /* F_GETOWN */
1274 #ifdef _IOFBF
1275 /* This symbol is defined on recent USG systems.
1276 Someone says without this call USG won't really buffer the file
1277 even with a call to setbuf. */
1278 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1279 #else
1280 setbuf (tty_out->output, (char *) _sobuf);
1281 #endif
1283 if (tty_out->terminal->set_terminal_modes_hook)
1284 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1286 if (!tty_out->term_initted)
1288 Lisp_Object tail, frame;
1289 FOR_EACH_FRAME (tail, frame)
1291 /* XXX This needs to be revised. */
1292 if (FRAME_TERMCAP_P (XFRAME (frame))
1293 && FRAME_TTY (XFRAME (frame)) == tty_out)
1294 init_frame_faces (XFRAME (frame));
1298 if (tty_out->term_initted && no_redraw_on_reenter)
1300 /* We used to call "direct_output_forward_char(0)" here,
1301 but it's not clear why, since it may not do anything anyway. */
1303 else
1305 Lisp_Object tail, frame;
1306 frame_garbaged = 1;
1307 FOR_EACH_FRAME (tail, frame)
1309 if ((FRAME_TERMCAP_P (XFRAME (frame))
1310 || FRAME_MSDOS_P (XFRAME (frame)))
1311 && FRAME_TTY (XFRAME (frame)) == tty_out)
1312 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1316 tty_out->term_initted = 1;
1319 /* Return true if safe to use tabs in output.
1320 At the time this is called, init_sys_modes has not been done yet. */
1322 bool
1323 tabs_safe_p (int fd)
1325 struct emacs_tty etty;
1327 emacs_get_tty (fd, &etty);
1328 #ifndef DOS_NT
1329 #ifdef TABDLY
1330 return ((etty.main.c_oflag & TABDLY) != TAB3);
1331 #else /* not TABDLY */
1332 return 1;
1333 #endif /* not TABDLY */
1334 #else /* DOS_NT */
1335 return 0;
1336 #endif /* DOS_NT */
1339 /* Discard echoing. */
1341 void
1342 suppress_echo_on_tty (int fd)
1344 struct emacs_tty etty;
1346 emacs_get_tty (fd, &etty);
1347 #ifdef DOS_NT
1348 /* Set raw input mode. */
1349 etty.main = 0;
1350 #else
1351 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1352 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1353 #endif /* ! WINDOWSNT */
1354 emacs_set_tty (fd, &etty, 0);
1357 /* Get terminal size from system.
1358 Store number of lines into *HEIGHTP and width into *WIDTHP.
1359 We store 0 if there's no valid information. */
1361 void
1362 get_tty_size (int fd, int *widthp, int *heightp)
1364 #if defined TIOCGWINSZ
1366 /* BSD-style. */
1367 struct winsize size;
1369 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1370 *widthp = *heightp = 0;
1371 else
1373 *widthp = size.ws_col;
1374 *heightp = size.ws_row;
1377 #elif defined TIOCGSIZE
1379 /* SunOS - style. */
1380 struct ttysize size;
1382 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1383 *widthp = *heightp = 0;
1384 else
1386 *widthp = size.ts_cols;
1387 *heightp = size.ts_lines;
1390 #elif defined WINDOWSNT
1392 CONSOLE_SCREEN_BUFFER_INFO info;
1393 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1395 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1396 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1398 else
1399 *widthp = *heightp = 0;
1401 #elif defined MSDOS
1403 *widthp = ScreenCols ();
1404 *heightp = ScreenRows ();
1406 #else /* system doesn't know size */
1408 *widthp = 0;
1409 *heightp = 0;
1411 #endif
1414 /* Set the logical window size associated with descriptor FD
1415 to HEIGHT and WIDTH. This is used mainly with ptys.
1416 Return a negative value on failure. */
1419 set_window_size (int fd, int height, int width)
1421 #ifdef TIOCSWINSZ
1423 /* BSD-style. */
1424 struct winsize size;
1425 size.ws_row = height;
1426 size.ws_col = width;
1428 return ioctl (fd, TIOCSWINSZ, &size);
1430 #else
1431 #ifdef TIOCSSIZE
1433 /* SunOS - style. */
1434 struct ttysize size;
1435 size.ts_lines = height;
1436 size.ts_cols = width;
1438 return ioctl (fd, TIOCGSIZE, &size);
1439 #else
1440 return -1;
1441 #endif /* not SunOS-style */
1442 #endif /* not BSD-style */
1447 /* Prepare all terminal devices for exiting Emacs. */
1449 void
1450 reset_all_sys_modes (void)
1452 struct tty_display_info *tty;
1453 for (tty = tty_list; tty; tty = tty->next)
1454 reset_sys_modes (tty);
1457 /* Prepare the terminal for closing it; move the cursor to the
1458 bottom of the frame, turn off interrupt-driven I/O, etc. */
1460 void
1461 reset_sys_modes (struct tty_display_info *tty_out)
1463 if (noninteractive)
1465 fflush_unlocked (stdout);
1466 return;
1468 if (!tty_out->term_initted)
1469 return;
1471 if (!tty_out->output)
1472 return; /* The tty is suspended. */
1474 /* Go to and clear the last line of the terminal. */
1476 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1478 /* Code adapted from tty_clear_end_of_line. */
1479 if (tty_out->TS_clr_line)
1481 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1483 else
1484 { /* have to do it the hard way */
1485 tty_turn_off_insert (tty_out);
1487 for (int i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1488 fputc_unlocked (' ', tty_out->output);
1491 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1492 fflush_unlocked (tty_out->output);
1494 if (tty_out->terminal->reset_terminal_modes_hook)
1495 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1497 /* Avoid possible loss of output when changing terminal modes. */
1498 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1499 continue;
1501 #ifndef DOS_NT
1502 #ifdef F_SETOWN
1503 if (interrupt_input)
1505 reset_sigio (fileno (tty_out->input));
1506 fcntl (fileno (tty_out->input), F_SETOWN,
1507 old_fcntl_owner[fileno (tty_out->input)]);
1509 #endif /* F_SETOWN */
1510 fcntl (fileno (tty_out->input), F_SETFL,
1511 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1512 #endif
1514 if (tty_out->old_tty)
1515 while (emacs_set_tty (fileno (tty_out->input),
1516 tty_out->old_tty, 0) < 0 && errno == EINTR)
1519 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1520 dos_ttcooked ();
1521 #endif
1523 widen_foreground_group (fileno (tty_out->input));
1526 #ifdef HAVE_PTYS
1528 /* Set up the proper status flags for use of a pty. */
1530 void
1531 setup_pty (int fd)
1533 /* I'm told that TOICREMOTE does not mean control chars
1534 "can't be sent" but rather that they don't have
1535 input-editing or signaling effects.
1536 That should be good, because we have other ways
1537 to do those things in Emacs.
1538 However, telnet mode seems not to work on 4.2.
1539 So TIOCREMOTE is turned off now. */
1541 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1542 will hang. In particular, the "timeout" feature (which
1543 causes a read to return if there is no data available)
1544 does this. Also it is known that telnet mode will hang
1545 in such a way that Emacs must be stopped (perhaps this
1546 is the same problem).
1548 If TIOCREMOTE is turned off, then there is a bug in
1549 hp-ux which sometimes loses data. Apparently the
1550 code which blocks the master process when the internal
1551 buffer fills up does not work. Other than this,
1552 though, everything else seems to work fine.
1554 Since the latter lossage is more benign, we may as well
1555 lose that way. -- cph */
1556 #ifdef FIONBIO
1557 #if defined (UNIX98_PTYS)
1559 int on = 1;
1560 ioctl (fd, FIONBIO, &on);
1562 #endif
1563 #endif
1565 #endif /* HAVE_PTYS */
1567 void
1568 init_system_name (void)
1570 if (!build_details)
1572 /* Set system-name to nil so that the build is deterministic. */
1573 Vsystem_name = Qnil;
1574 return;
1576 char *hostname_alloc = NULL;
1577 char *hostname;
1578 #ifndef HAVE_GETHOSTNAME
1579 struct utsname uts;
1580 uname (&uts);
1581 hostname = uts.nodename;
1582 #else /* HAVE_GETHOSTNAME */
1583 char hostname_buf[256];
1584 ptrdiff_t hostname_size = sizeof hostname_buf;
1585 hostname = hostname_buf;
1587 /* Try to get the host name; if the buffer is too short, try
1588 again. Apparently, the only indication gethostname gives of
1589 whether the buffer was large enough is the presence or absence
1590 of a '\0' in the string. Eech. */
1591 for (;;)
1593 gethostname (hostname, hostname_size - 1);
1594 hostname[hostname_size - 1] = '\0';
1596 /* Was the buffer large enough for the '\0'? */
1597 if (strlen (hostname) < hostname_size - 1)
1598 break;
1600 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1601 min (PTRDIFF_MAX, SIZE_MAX), 1);
1603 #endif /* HAVE_GETHOSTNAME */
1604 char *p;
1605 for (p = hostname; *p; p++)
1606 if (*p == ' ' || *p == '\t')
1607 *p = '-';
1608 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1609 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1610 Vsystem_name = build_string (hostname);
1611 xfree (hostname_alloc);
1614 sigset_t empty_mask;
1616 static struct sigaction process_fatal_action;
1618 static int
1619 emacs_sigaction_flags (void)
1621 #ifdef SA_RESTART
1622 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1623 'select') to reset their timeout on some platforms (e.g.,
1624 HP-UX 11), which is not what we want. Also, when Emacs is
1625 interactive, we don't want SA_RESTART because we need to poll
1626 for pending input so we need long-running syscalls to be interrupted
1627 after a signal that sets pending_signals.
1629 Non-interactive keyboard input goes through stdio, where we
1630 always want restartable system calls. */
1631 if (noninteractive)
1632 return SA_RESTART;
1633 #endif
1634 return 0;
1637 /* Store into *ACTION a signal action suitable for Emacs, with handler
1638 HANDLER. */
1639 void
1640 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1642 sigemptyset (&action->sa_mask);
1644 /* When handling a signal, block nonfatal system signals that are caught
1645 by Emacs. This makes race conditions less likely. */
1646 sigaddset (&action->sa_mask, SIGALRM);
1647 #ifdef SIGCHLD
1648 sigaddset (&action->sa_mask, SIGCHLD);
1649 #endif
1650 #ifdef SIGDANGER
1651 sigaddset (&action->sa_mask, SIGDANGER);
1652 #endif
1653 #ifdef PROFILER_CPU_SUPPORT
1654 sigaddset (&action->sa_mask, SIGPROF);
1655 #endif
1656 #ifdef SIGWINCH
1657 sigaddset (&action->sa_mask, SIGWINCH);
1658 #endif
1659 if (! noninteractive)
1661 sigaddset (&action->sa_mask, SIGINT);
1662 sigaddset (&action->sa_mask, SIGQUIT);
1663 #ifdef USABLE_SIGIO
1664 sigaddset (&action->sa_mask, SIGIO);
1665 #endif
1668 action->sa_handler = handler;
1669 action->sa_flags = emacs_sigaction_flags ();
1672 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1673 pthread_t main_thread_id;
1674 #endif
1676 /* SIG has arrived at the current process. Deliver it to the main
1677 thread, which should handle it with HANDLER. (Delivering the
1678 signal to some other thread might not work if the other thread is
1679 about to exit.)
1681 If we are on the main thread, handle the signal SIG with HANDLER.
1682 Otherwise, redirect the signal to the main thread, blocking it from
1683 this thread. POSIX says any thread can receive a signal that is
1684 associated with a process, process group, or asynchronous event.
1685 On GNU/Linux the main thread typically gets a process signal unless
1686 it's blocked, but other systems (FreeBSD at least) can deliver the
1687 signal to other threads. */
1688 void
1689 deliver_process_signal (int sig, signal_handler_t handler)
1691 /* Preserve errno, to avoid race conditions with signal handlers that
1692 might change errno. Races can occur even in single-threaded hosts. */
1693 int old_errno = errno;
1695 bool on_main_thread = true;
1696 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1697 if (! pthread_equal (pthread_self (), main_thread_id))
1699 sigset_t blocked;
1700 sigemptyset (&blocked);
1701 sigaddset (&blocked, sig);
1702 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1703 pthread_kill (main_thread_id, sig);
1704 on_main_thread = false;
1706 #endif
1707 if (on_main_thread)
1708 handler (sig);
1710 errno = old_errno;
1713 /* Static location to save a fatal backtrace in a thread.
1714 FIXME: If two subsidiary threads fail simultaneously, the resulting
1715 backtrace may be garbage. */
1716 enum { BACKTRACE_LIMIT_MAX = 500 };
1717 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1718 static int thread_backtrace_npointers;
1720 /* SIG has arrived at the current thread.
1721 If we are on the main thread, handle the signal SIG with HANDLER.
1722 Otherwise, this is a fatal error in the handling thread. */
1723 static void
1724 deliver_thread_signal (int sig, signal_handler_t handler)
1726 int old_errno = errno;
1728 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1729 if (! pthread_equal (pthread_self (), main_thread_id))
1731 thread_backtrace_npointers
1732 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1733 sigaction (sig, &process_fatal_action, 0);
1734 pthread_kill (main_thread_id, sig);
1736 /* Avoid further damage while the main thread is exiting. */
1737 while (1)
1738 sigsuspend (&empty_mask);
1740 #endif
1742 handler (sig);
1743 errno = old_errno;
1746 #if !HAVE_DECL_SYS_SIGLIST
1747 # undef sys_siglist
1748 # ifdef _sys_siglist
1749 # define sys_siglist _sys_siglist
1750 # elif HAVE_DECL___SYS_SIGLIST
1751 # define sys_siglist __sys_siglist
1752 # else
1753 # define sys_siglist my_sys_siglist
1754 static char const *sys_siglist[NSIG];
1755 # endif
1756 #endif
1758 #ifdef _sys_nsig
1759 # define sys_siglist_entries _sys_nsig
1760 #else
1761 # define sys_siglist_entries NSIG
1762 #endif
1764 /* Handle bus errors, invalid instruction, etc. */
1765 static void
1766 handle_fatal_signal (int sig)
1768 terminate_due_to_signal (sig, 40);
1771 static void
1772 deliver_fatal_signal (int sig)
1774 deliver_process_signal (sig, handle_fatal_signal);
1777 static void
1778 deliver_fatal_thread_signal (int sig)
1780 deliver_thread_signal (sig, handle_fatal_signal);
1783 static _Noreturn void
1784 handle_arith_signal (int sig)
1786 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1787 xsignal0 (Qarith_error);
1790 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1792 /* Alternate stack used by SIGSEGV handler below. */
1794 static unsigned char sigsegv_stack[SIGSTKSZ];
1797 /* Return true if SIGINFO indicates a stack overflow. */
1799 static bool
1800 stack_overflow (siginfo_t *siginfo)
1802 if (!attempt_stack_overflow_recovery)
1803 return false;
1805 /* In theory, a more-accurate heuristic can be obtained by using
1806 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1807 and pthread_attr_getguardsize to find the location and size of the
1808 guard area. In practice, though, these functions are so hard to
1809 use reliably that they're not worth bothering with. E.g., see:
1810 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1811 Other operating systems also have problems, e.g., Solaris's
1812 stack_violation function is tailor-made for this problem, but it
1813 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1815 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1816 candidate here. */
1818 if (!siginfo)
1819 return false;
1821 /* The faulting address. */
1822 char *addr = siginfo->si_addr;
1823 if (!addr)
1824 return false;
1826 /* The known top and bottom of the stack. The actual stack may
1827 extend a bit beyond these boundaries. */
1828 char *bot = stack_bottom;
1829 char *top = current_thread->stack_top;
1831 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1832 of the known stack divided by the size of the guard area past the
1833 end of the stack top. The heuristic is that a bad address is
1834 considered to be a stack overflow if it occurs within
1835 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1836 stack. This heuristic is not exactly correct but it's good
1837 enough in practice. */
1838 enum { LG_STACK_HEURISTIC = 8 };
1840 if (bot < top)
1841 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1842 else
1843 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1847 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1849 static void
1850 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1852 /* Hard GC error may lead to stack overflow caused by
1853 too nested calls to mark_object. No way to survive. */
1854 bool fatal = gc_in_progress;
1856 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1857 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1858 fatal = true;
1859 #endif
1861 if (!fatal && stack_overflow (siginfo))
1862 siglongjmp (return_to_command_loop, 1);
1864 /* Otherwise we can't do anything with this. */
1865 deliver_fatal_thread_signal (sig);
1868 /* Return true if we have successfully set up SIGSEGV handler on alternate
1869 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1871 static bool
1872 init_sigsegv (void)
1874 struct sigaction sa;
1875 stack_t ss;
1877 ss.ss_sp = sigsegv_stack;
1878 ss.ss_size = sizeof (sigsegv_stack);
1879 ss.ss_flags = 0;
1880 if (sigaltstack (&ss, NULL) < 0)
1881 return 0;
1883 sigfillset (&sa.sa_mask);
1884 sa.sa_sigaction = handle_sigsegv;
1885 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1886 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1889 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1891 static bool
1892 init_sigsegv (void)
1894 return 0;
1897 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1899 static void
1900 deliver_arith_signal (int sig)
1902 deliver_thread_signal (sig, handle_arith_signal);
1905 #ifdef SIGDANGER
1907 /* Handler for SIGDANGER. */
1908 static void
1909 handle_danger_signal (int sig)
1911 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1913 /* It might be unsafe to call do_auto_save now. */
1914 force_auto_save_soon ();
1917 static void
1918 deliver_danger_signal (int sig)
1920 deliver_process_signal (sig, handle_danger_signal);
1922 #endif
1924 /* Treat SIG as a terminating signal, unless it is already ignored and
1925 we are in --batch mode. Among other things, this makes nohup work. */
1926 static void
1927 maybe_fatal_sig (int sig)
1929 bool catch_sig = !noninteractive;
1930 if (!catch_sig)
1932 struct sigaction old_action;
1933 sigaction (sig, 0, &old_action);
1934 catch_sig = old_action.sa_handler != SIG_IGN;
1936 if (catch_sig)
1937 sigaction (sig, &process_fatal_action, 0);
1940 void
1941 init_signals (bool dumping)
1943 struct sigaction thread_fatal_action;
1944 struct sigaction action;
1946 sigemptyset (&empty_mask);
1948 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1949 main_thread_id = pthread_self ();
1950 #endif
1952 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1953 if (! initialized)
1955 sys_siglist[SIGABRT] = "Aborted";
1956 # ifdef SIGAIO
1957 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1958 # endif
1959 sys_siglist[SIGALRM] = "Alarm clock";
1960 # ifdef SIGBUS
1961 sys_siglist[SIGBUS] = "Bus error";
1962 # endif
1963 # ifdef SIGCHLD
1964 sys_siglist[SIGCHLD] = "Child status changed";
1965 # endif
1966 # ifdef SIGCONT
1967 sys_siglist[SIGCONT] = "Continued";
1968 # endif
1969 # ifdef SIGDANGER
1970 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1971 # endif
1972 # ifdef SIGDGNOTIFY
1973 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1974 # endif
1975 # ifdef SIGEMT
1976 sys_siglist[SIGEMT] = "Emulation trap";
1977 # endif
1978 sys_siglist[SIGFPE] = "Arithmetic exception";
1979 # ifdef SIGFREEZE
1980 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1981 # endif
1982 # ifdef SIGGRANT
1983 sys_siglist[SIGGRANT] = "Monitor mode granted";
1984 # endif
1985 sys_siglist[SIGHUP] = "Hangup";
1986 sys_siglist[SIGILL] = "Illegal instruction";
1987 sys_siglist[SIGINT] = "Interrupt";
1988 # ifdef SIGIO
1989 sys_siglist[SIGIO] = "I/O possible";
1990 # endif
1991 # ifdef SIGIOINT
1992 sys_siglist[SIGIOINT] = "I/O intervention required";
1993 # endif
1994 # ifdef SIGIOT
1995 sys_siglist[SIGIOT] = "IOT trap";
1996 # endif
1997 sys_siglist[SIGKILL] = "Killed";
1998 # ifdef SIGLOST
1999 sys_siglist[SIGLOST] = "Resource lost";
2000 # endif
2001 # ifdef SIGLWP
2002 sys_siglist[SIGLWP] = "SIGLWP";
2003 # endif
2004 # ifdef SIGMSG
2005 sys_siglist[SIGMSG] = "Monitor mode data available";
2006 # endif
2007 # ifdef SIGPHONE
2008 sys_siglist[SIGWIND] = "SIGPHONE";
2009 # endif
2010 sys_siglist[SIGPIPE] = "Broken pipe";
2011 # ifdef SIGPOLL
2012 sys_siglist[SIGPOLL] = "Pollable event occurred";
2013 # endif
2014 # ifdef SIGPROF
2015 sys_siglist[SIGPROF] = "Profiling timer expired";
2016 # endif
2017 # ifdef SIGPTY
2018 sys_siglist[SIGPTY] = "PTY I/O interrupt";
2019 # endif
2020 # ifdef SIGPWR
2021 sys_siglist[SIGPWR] = "Power-fail restart";
2022 # endif
2023 sys_siglist[SIGQUIT] = "Quit";
2024 # ifdef SIGRETRACT
2025 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
2026 # endif
2027 # ifdef SIGSAK
2028 sys_siglist[SIGSAK] = "Secure attention";
2029 # endif
2030 sys_siglist[SIGSEGV] = "Segmentation violation";
2031 # ifdef SIGSOUND
2032 sys_siglist[SIGSOUND] = "Sound completed";
2033 # endif
2034 # ifdef SIGSTOP
2035 sys_siglist[SIGSTOP] = "Stopped (signal)";
2036 # endif
2037 # ifdef SIGSTP
2038 sys_siglist[SIGSTP] = "Stopped (user)";
2039 # endif
2040 # ifdef SIGSYS
2041 sys_siglist[SIGSYS] = "Bad argument to system call";
2042 # endif
2043 sys_siglist[SIGTERM] = "Terminated";
2044 # ifdef SIGTHAW
2045 sys_siglist[SIGTHAW] = "SIGTHAW";
2046 # endif
2047 # ifdef SIGTRAP
2048 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2049 # endif
2050 # ifdef SIGTSTP
2051 sys_siglist[SIGTSTP] = "Stopped (user)";
2052 # endif
2053 # ifdef SIGTTIN
2054 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2055 # endif
2056 # ifdef SIGTTOU
2057 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2058 # endif
2059 # ifdef SIGURG
2060 sys_siglist[SIGURG] = "Urgent I/O condition";
2061 # endif
2062 # ifdef SIGUSR1
2063 sys_siglist[SIGUSR1] = "User defined signal 1";
2064 # endif
2065 # ifdef SIGUSR2
2066 sys_siglist[SIGUSR2] = "User defined signal 2";
2067 # endif
2068 # ifdef SIGVTALRM
2069 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2070 # endif
2071 # ifdef SIGWAITING
2072 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2073 # endif
2074 # ifdef SIGWINCH
2075 sys_siglist[SIGWINCH] = "Window size changed";
2076 # endif
2077 # ifdef SIGWIND
2078 sys_siglist[SIGWIND] = "SIGWIND";
2079 # endif
2080 # ifdef SIGXCPU
2081 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2082 # endif
2083 # ifdef SIGXFSZ
2084 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2085 # endif
2087 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2089 /* Don't alter signal handlers if dumping. On some machines,
2090 changing signal handlers sets static data that would make signals
2091 fail to work right when the dumped Emacs is run. */
2092 if (dumping)
2093 return;
2095 sigfillset (&process_fatal_action.sa_mask);
2096 process_fatal_action.sa_handler = deliver_fatal_signal;
2097 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2099 sigfillset (&thread_fatal_action.sa_mask);
2100 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2101 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2103 /* SIGINT may need special treatment on MS-Windows. See
2104 https://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2105 Please update the doc of kill-emacs, kill-emacs-hook, and
2106 NEWS if you change this. */
2108 maybe_fatal_sig (SIGHUP);
2109 maybe_fatal_sig (SIGINT);
2110 maybe_fatal_sig (SIGTERM);
2112 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2113 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2114 to behave more like typical batch applications do. */
2115 if (! noninteractive)
2116 signal (SIGPIPE, SIG_IGN);
2118 sigaction (SIGQUIT, &process_fatal_action, 0);
2119 sigaction (SIGILL, &thread_fatal_action, 0);
2120 sigaction (SIGTRAP, &thread_fatal_action, 0);
2122 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2123 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2124 interpreter's floating point operations, so treat SIGFPE as an
2125 arith-error if it arises in the main thread. */
2126 if (IEEE_FLOATING_POINT)
2127 sigaction (SIGFPE, &thread_fatal_action, 0);
2128 else
2130 emacs_sigaction_init (&action, deliver_arith_signal);
2131 sigaction (SIGFPE, &action, 0);
2134 #ifdef SIGUSR1
2135 add_user_signal (SIGUSR1, "sigusr1");
2136 #endif
2137 #ifdef SIGUSR2
2138 add_user_signal (SIGUSR2, "sigusr2");
2139 #endif
2140 sigaction (SIGABRT, &thread_fatal_action, 0);
2141 #ifdef SIGPRE
2142 sigaction (SIGPRE, &thread_fatal_action, 0);
2143 #endif
2144 #ifdef SIGORE
2145 sigaction (SIGORE, &thread_fatal_action, 0);
2146 #endif
2147 #ifdef SIGUME
2148 sigaction (SIGUME, &thread_fatal_action, 0);
2149 #endif
2150 #ifdef SIGDLK
2151 sigaction (SIGDLK, &process_fatal_action, 0);
2152 #endif
2153 #ifdef SIGCPULIM
2154 sigaction (SIGCPULIM, &process_fatal_action, 0);
2155 #endif
2156 #ifdef SIGIOT
2157 sigaction (SIGIOT, &thread_fatal_action, 0);
2158 #endif
2159 #ifdef SIGEMT
2160 sigaction (SIGEMT, &thread_fatal_action, 0);
2161 #endif
2162 #ifdef SIGBUS
2163 sigaction (SIGBUS, &thread_fatal_action, 0);
2164 #endif
2165 if (!init_sigsegv ())
2166 sigaction (SIGSEGV, &thread_fatal_action, 0);
2167 #ifdef SIGSYS
2168 sigaction (SIGSYS, &thread_fatal_action, 0);
2169 #endif
2170 sigaction (SIGTERM, &process_fatal_action, 0);
2171 #ifdef SIGPROF
2172 signal (SIGPROF, SIG_IGN);
2173 #endif
2174 #ifdef SIGVTALRM
2175 sigaction (SIGVTALRM, &process_fatal_action, 0);
2176 #endif
2177 #ifdef SIGXCPU
2178 sigaction (SIGXCPU, &process_fatal_action, 0);
2179 #endif
2180 #ifdef SIGXFSZ
2181 sigaction (SIGXFSZ, &process_fatal_action, 0);
2182 #endif
2184 #ifdef SIGDANGER
2185 /* This just means available memory is getting low. */
2186 emacs_sigaction_init (&action, deliver_danger_signal);
2187 sigaction (SIGDANGER, &action, 0);
2188 #endif
2190 /* AIX-specific signals. */
2191 #ifdef SIGGRANT
2192 sigaction (SIGGRANT, &process_fatal_action, 0);
2193 #endif
2194 #ifdef SIGMIGRATE
2195 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2196 #endif
2197 #ifdef SIGMSG
2198 sigaction (SIGMSG, &process_fatal_action, 0);
2199 #endif
2200 #ifdef SIGRETRACT
2201 sigaction (SIGRETRACT, &process_fatal_action, 0);
2202 #endif
2203 #ifdef SIGSAK
2204 sigaction (SIGSAK, &process_fatal_action, 0);
2205 #endif
2206 #ifdef SIGSOUND
2207 sigaction (SIGSOUND, &process_fatal_action, 0);
2208 #endif
2209 #ifdef SIGTALRM
2210 sigaction (SIGTALRM, &thread_fatal_action, 0);
2211 #endif
2214 #ifndef HAVE_RANDOM
2215 #ifdef random
2216 #define HAVE_RANDOM
2217 #endif
2218 #endif
2220 /* Figure out how many bits the system's random number generator uses.
2221 `random' and `lrand48' are assumed to return 31 usable bits.
2222 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2223 so we'll shift it and treat it like the 15-bit USG `rand'. */
2225 #ifndef RAND_BITS
2226 # ifdef HAVE_RANDOM
2227 # define RAND_BITS 31
2228 # else /* !HAVE_RANDOM */
2229 # ifdef HAVE_LRAND48
2230 # define RAND_BITS 31
2231 # define random lrand48
2232 # else /* !HAVE_LRAND48 */
2233 # define RAND_BITS 15
2234 # if RAND_MAX == 32767
2235 # define random rand
2236 # else /* RAND_MAX != 32767 */
2237 # if RAND_MAX == 2147483647
2238 # define random() (rand () >> 16)
2239 # else /* RAND_MAX != 2147483647 */
2240 # ifdef USG
2241 # define random rand
2242 # else
2243 # define random() (rand () >> 16)
2244 # endif /* !USG */
2245 # endif /* RAND_MAX != 2147483647 */
2246 # endif /* RAND_MAX != 32767 */
2247 # endif /* !HAVE_LRAND48 */
2248 # endif /* !HAVE_RANDOM */
2249 #endif /* !RAND_BITS */
2251 #ifdef HAVE_RANDOM
2252 typedef unsigned int random_seed;
2253 static void set_random_seed (random_seed arg) { srandom (arg); }
2254 #elif defined HAVE_LRAND48
2255 /* Although srand48 uses a long seed, this is unsigned long to avoid
2256 undefined behavior on signed integer overflow in init_random. */
2257 typedef unsigned long int random_seed;
2258 static void set_random_seed (random_seed arg) { srand48 (arg); }
2259 #else
2260 typedef unsigned int random_seed;
2261 static void set_random_seed (random_seed arg) { srand (arg); }
2262 #endif
2264 void
2265 seed_random (void *seed, ptrdiff_t seed_size)
2267 random_seed arg = 0;
2268 unsigned char *argp = (unsigned char *) &arg;
2269 unsigned char *seedp = seed;
2270 for (ptrdiff_t i = 0; i < seed_size; i++)
2271 argp[i % sizeof arg] ^= seedp[i];
2272 set_random_seed (arg);
2275 void
2276 init_random (void)
2278 random_seed v;
2279 bool success = false;
2281 /* First, try seeding the PRNG from the operating system's entropy
2282 source. This approach is both fast and secure. */
2283 #ifdef WINDOWSNT
2284 success = w32_init_random (&v, sizeof v) == 0;
2285 #else
2286 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2287 if (0 <= fd)
2289 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2290 close (fd);
2292 #endif
2294 /* If that didn't work, try using GnuTLS, which is secure, but on
2295 some systems, can be somewhat slow. */
2296 if (!success)
2297 success = EQ (emacs_gnutls_global_init (), Qt)
2298 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2300 /* If _that_ didn't work, just use the current time value and PID.
2301 It's at least better than XKCD 221. */
2302 if (!success)
2304 struct timespec t = current_timespec ();
2305 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2308 set_random_seed (v);
2312 * Return a nonnegative random integer out of whatever we've got.
2313 * It contains enough bits to make a random (signed) Emacs fixnum.
2314 * This suffices even for a 64-bit architecture with a 15-bit rand.
2316 EMACS_INT
2317 get_random (void)
2319 EMACS_UINT val = 0;
2320 int i;
2321 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2322 val = (random () ^ (val << RAND_BITS)
2323 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2324 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2325 return val & INTMASK;
2328 #ifndef HAVE_SNPRINTF
2329 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2331 snprintf (char *buf, size_t bufsize, char const *format, ...)
2333 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2334 ptrdiff_t nbytes = size - 1;
2335 va_list ap;
2337 if (size)
2339 va_start (ap, format);
2340 nbytes = doprnt (buf, size, format, 0, ap);
2341 va_end (ap);
2344 if (nbytes == size - 1)
2346 /* Calculate the length of the string that would have been created
2347 had the buffer been large enough. */
2348 char stackbuf[4000];
2349 char *b = stackbuf;
2350 ptrdiff_t bsize = sizeof stackbuf;
2351 va_start (ap, format);
2352 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2353 va_end (ap);
2354 if (b != stackbuf)
2355 xfree (b);
2358 if (INT_MAX < nbytes)
2360 #ifdef EOVERFLOW
2361 errno = EOVERFLOW;
2362 #else
2363 errno = EDOM;
2364 #endif
2365 return -1;
2367 return nbytes;
2369 #endif
2371 /* If a backtrace is available, output the top lines of it to stderr.
2372 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2373 This function may be called from a signal handler, so it should
2374 not invoke async-unsafe functions like malloc.
2376 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2377 but do not output anything. This avoids some problems that can
2378 otherwise occur if the malloc arena is corrupted before 'backtrace'
2379 is called, since 'backtrace' may call malloc if the tables are not
2380 initialized.
2382 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2383 fatal error has occurred in some other thread; generate a thread
2384 backtrace instead, ignoring BACKTRACE_LIMIT. */
2385 void
2386 emacs_backtrace (int backtrace_limit)
2388 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2389 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2390 void *buffer;
2391 int npointers;
2393 if (thread_backtrace_npointers)
2395 buffer = thread_backtrace_buffer;
2396 npointers = thread_backtrace_npointers;
2398 else
2400 buffer = main_backtrace_buffer;
2402 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2403 if (bounded_limit < 0)
2405 backtrace (buffer, 1);
2406 return;
2409 npointers = backtrace (buffer, bounded_limit + 1);
2412 if (npointers)
2414 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2415 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2416 if (bounded_limit < npointers)
2417 emacs_write (STDERR_FILENO, "...\n", 4);
2421 #ifndef HAVE_NTGUI
2422 void
2423 emacs_abort (void)
2425 terminate_due_to_signal (SIGABRT, 40);
2427 #endif
2429 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2430 Use binary I/O on systems that care about text vs binary I/O.
2431 Arrange for subprograms to not inherit the file descriptor.
2432 Prefer a method that is multithread-safe, if available.
2433 Do not fail merely because the open was interrupted by a signal.
2434 Allow the user to quit. */
2437 emacs_open (const char *file, int oflags, int mode)
2439 int fd;
2440 if (! (oflags & O_TEXT))
2441 oflags |= O_BINARY;
2442 oflags |= O_CLOEXEC;
2443 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2444 maybe_quit ();
2445 return fd;
2448 /* Open FILE as a stream for Emacs use, with mode MODE.
2449 Act like emacs_open with respect to threads, signals, and quits. */
2451 FILE *
2452 emacs_fopen (char const *file, char const *mode)
2454 int fd, omode, oflags;
2455 int bflag = 0;
2456 char const *m = mode;
2458 switch (*m++)
2460 case 'r': omode = O_RDONLY; oflags = 0; break;
2461 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2462 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2463 default: emacs_abort ();
2466 while (*m)
2467 switch (*m++)
2469 case '+': omode = O_RDWR; break;
2470 case 't': bflag = O_TEXT; break;
2471 default: /* Ignore. */ break;
2474 fd = emacs_open (file, omode | oflags | bflag, 0666);
2475 return fd < 0 ? 0 : fdopen (fd, mode);
2478 /* Create a pipe for Emacs use. */
2481 emacs_pipe (int fd[2])
2483 #ifdef MSDOS
2484 return pipe (fd);
2485 #else /* !MSDOS */
2486 return pipe2 (fd, O_BINARY | O_CLOEXEC);
2487 #endif /* !MSDOS */
2490 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2491 For the background behind this mess, please see Austin Group defect 529
2492 <http://austingroupbugs.net/view.php?id=529>. */
2494 #ifndef POSIX_CLOSE_RESTART
2495 # define POSIX_CLOSE_RESTART 1
2496 static int
2497 posix_close (int fd, int flag)
2499 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2500 eassert (flag == POSIX_CLOSE_RESTART);
2502 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2503 on a system that does not define POSIX_CLOSE_RESTART.
2505 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2506 closed, and retrying the close could inadvertently close a file
2507 descriptor allocated by some other thread. In other systems
2508 (e.g., HP/UX) FD is not closed. And in still other systems
2509 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2510 multithreaded program there can be no way to tell.
2512 So, in this case, pretend that the close succeeded. This works
2513 well on systems like GNU/Linux that close FD. Although it may
2514 leak a file descriptor on other systems, the leak is unlikely and
2515 it's better to leak than to close a random victim. */
2516 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2518 #endif
2520 /* Close FD, retrying if interrupted. If successful, return 0;
2521 otherwise, return -1 and set errno to a non-EINTR value. Consider
2522 an EINPROGRESS error to be successful, as that's merely a signal
2523 arriving. FD is always closed when this function returns, even
2524 when it returns -1.
2526 Do not call this function if FD is nonnegative and might already be closed,
2527 as that might close an innocent victim opened by some other thread. */
2530 emacs_close (int fd)
2532 while (1)
2534 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2535 if (r == 0)
2536 return r;
2537 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2539 eassert (errno != EBADF || fd < 0);
2540 return errno == EINPROGRESS ? 0 : r;
2545 /* Maximum number of bytes to read or write in a single system call.
2546 This works around a serious bug in Linux kernels before 2.6.16; see
2547 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2548 It's likely to work around similar bugs in other operating systems, so do it
2549 on all platforms. Round INT_MAX down to a page size, with the conservative
2550 assumption that page sizes are at most 2**18 bytes (any kernel with a
2551 page size larger than that shouldn't have the bug). */
2552 #ifndef MAX_RW_COUNT
2553 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2554 #endif
2556 /* Read from FD to a buffer BUF with size NBYTE.
2557 If interrupted, process any quits and pending signals immediately
2558 if INTERRUPTIBLE, and then retry the read unless quitting.
2559 Return the number of bytes read, which might be less than NBYTE.
2560 On error, set errno to a value other than EINTR, and return -1. */
2561 static ptrdiff_t
2562 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2564 ssize_t result;
2566 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2567 passes a size that large to emacs_read. */
2570 if (interruptible)
2571 maybe_quit ();
2572 result = read (fd, buf, nbyte);
2574 while (result < 0 && errno == EINTR);
2576 return result;
2579 /* Read from FD to a buffer BUF with size NBYTE.
2580 If interrupted, retry the read. Return the number of bytes read,
2581 which might be less than NBYTE. On error, set errno to a value
2582 other than EINTR, and return -1. */
2583 ptrdiff_t
2584 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2586 return emacs_intr_read (fd, buf, nbyte, false);
2589 /* Like emacs_read, but also process quits and pending signals. */
2590 ptrdiff_t
2591 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2593 return emacs_intr_read (fd, buf, nbyte, true);
2596 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2597 interrupted or if a partial write occurs. Process any quits
2598 immediately if INTERRUPTIBLE is positive, and process any pending
2599 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2600 of bytes written; if this is less than NBYTE, set errno to a value
2601 other than EINTR. */
2602 static ptrdiff_t
2603 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2604 int interruptible)
2606 ptrdiff_t bytes_written = 0;
2608 while (nbyte > 0)
2610 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2612 if (n < 0)
2614 if (errno != EINTR)
2615 break;
2617 if (interruptible)
2619 if (0 < interruptible)
2620 maybe_quit ();
2621 if (pending_signals)
2622 process_pending_signals ();
2625 else
2627 buf += n;
2628 nbyte -= n;
2629 bytes_written += n;
2633 return bytes_written;
2636 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2637 interrupted or if a partial write occurs. Do not process quits or
2638 pending signals. Return the number of bytes written, setting errno
2639 if this is less than NBYTE. */
2640 ptrdiff_t
2641 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2643 return emacs_full_write (fd, buf, nbyte, 0);
2646 /* Like emacs_write, but also process pending signals. */
2647 ptrdiff_t
2648 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2650 return emacs_full_write (fd, buf, nbyte, -1);
2653 /* Like emacs_write, but also process quits and pending signals. */
2654 ptrdiff_t
2655 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2657 return emacs_full_write (fd, buf, nbyte, 1);
2660 /* Write a diagnostic to standard error that contains MESSAGE and a
2661 string derived from errno. Preserve errno. Do not buffer stderr.
2662 Do not process quits or pending signals if interrupted. */
2663 void
2664 emacs_perror (char const *message)
2666 int err = errno;
2667 char const *error_string = emacs_strerror (err);
2668 char const *command = (initial_argv && initial_argv[0]
2669 ? initial_argv[0] : "emacs");
2670 /* Write it out all at once, if it's short; this is less likely to
2671 be interleaved with other output. */
2672 char buf[BUFSIZ];
2673 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2674 command, message, error_string);
2675 if (0 <= nbytes && nbytes < BUFSIZ)
2676 emacs_write (STDERR_FILENO, buf, nbytes);
2677 else
2679 emacs_write (STDERR_FILENO, command, strlen (command));
2680 emacs_write (STDERR_FILENO, ": ", 2);
2681 emacs_write (STDERR_FILENO, message, strlen (message));
2682 emacs_write (STDERR_FILENO, ": ", 2);
2683 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2684 emacs_write (STDERR_FILENO, "\n", 1);
2686 errno = err;
2689 /* Return a struct timeval that is roughly equivalent to T.
2690 Use the least timeval not less than T.
2691 Return an extremal value if the result would overflow. */
2692 struct timeval
2693 make_timeval (struct timespec t)
2695 struct timeval tv;
2696 tv.tv_sec = t.tv_sec;
2697 tv.tv_usec = t.tv_nsec / 1000;
2699 if (t.tv_nsec % 1000 != 0)
2701 if (tv.tv_usec < 999999)
2702 tv.tv_usec++;
2703 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2705 tv.tv_sec++;
2706 tv.tv_usec = 0;
2710 return tv;
2713 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2714 ATIME and MTIME, respectively.
2715 FD must be either negative -- in which case it is ignored --
2716 or a file descriptor that is open on FILE.
2717 If FD is nonnegative, then FILE can be NULL. */
2719 set_file_times (int fd, const char *filename,
2720 struct timespec atime, struct timespec mtime)
2722 struct timespec timespec[2];
2723 timespec[0] = atime;
2724 timespec[1] = mtime;
2725 return fdutimens (fd, filename, timespec);
2728 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2729 This is like renameat except that it fails if DST already exists,
2730 or if this operation is not supported atomically. Return 0 if
2731 successful, -1 (setting errno) otherwise. */
2733 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2735 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2736 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2737 #elif defined CYGWIN && defined RENAME_NOREPLACE
2738 return renameat2 (srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2739 #elif defined RENAME_EXCL
2740 return renameatx_np (srcfd, src, dstfd, dst, RENAME_EXCL);
2741 #else
2742 # ifdef WINDOWSNT
2743 if (srcfd == AT_FDCWD && dstfd == AT_FDCWD)
2744 return sys_rename_replace (src, dst, 0);
2745 # endif
2746 errno = ENOSYS;
2747 return -1;
2748 #endif
2751 /* Like strsignal, except async-signal-safe, and this function typically
2752 returns a string in the C locale rather than the current locale. */
2753 char const *
2754 safe_strsignal (int code)
2756 char const *signame = 0;
2758 if (0 <= code && code < sys_siglist_entries)
2759 signame = sys_siglist[code];
2760 if (! signame)
2761 signame = "Unknown signal";
2763 return signame;
2766 #ifndef DOS_NT
2767 /* For make-serial-process */
2769 serial_open (Lisp_Object port)
2771 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2772 if (fd < 0)
2773 report_file_error ("Opening serial port", port);
2774 #ifdef TIOCEXCL
2775 ioctl (fd, TIOCEXCL, (char *) 0);
2776 #endif
2778 return fd;
2781 #if !defined (HAVE_CFMAKERAW)
2782 /* Workaround for targets which are missing cfmakeraw. */
2783 /* Pasted from man page. */
2784 static void
2785 cfmakeraw (struct termios *termios_p)
2787 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2788 termios_p->c_oflag &= ~OPOST;
2789 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2790 termios_p->c_cflag &= ~(CSIZE|PARENB);
2791 termios_p->c_cflag |= CS8;
2793 #endif /* !defined (HAVE_CFMAKERAW */
2795 #if !defined (HAVE_CFSETSPEED)
2796 /* Workaround for targets which are missing cfsetspeed. */
2797 static int
2798 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2800 return (cfsetispeed (termios_p, vitesse)
2801 + cfsetospeed (termios_p, vitesse));
2803 #endif
2805 /* For serial-process-configure */
2806 void
2807 serial_configure (struct Lisp_Process *p,
2808 Lisp_Object contact)
2810 Lisp_Object childp2 = Qnil;
2811 Lisp_Object tem = Qnil;
2812 struct termios attr;
2813 int err;
2814 char summary[4] = "???"; /* This usually becomes "8N1". */
2816 childp2 = Fcopy_sequence (p->childp);
2818 /* Read port attributes and prepare default configuration. */
2819 err = tcgetattr (p->outfd, &attr);
2820 if (err != 0)
2821 report_file_error ("Failed tcgetattr", Qnil);
2822 cfmakeraw (&attr);
2823 #if defined (CLOCAL)
2824 attr.c_cflag |= CLOCAL;
2825 #endif
2826 #if defined (CREAD)
2827 attr.c_cflag |= CREAD;
2828 #endif
2830 /* Configure speed. */
2831 if (!NILP (Fplist_member (contact, QCspeed)))
2832 tem = Fplist_get (contact, QCspeed);
2833 else
2834 tem = Fplist_get (p->childp, QCspeed);
2835 CHECK_NUMBER (tem);
2836 err = cfsetspeed (&attr, XINT (tem));
2837 if (err != 0)
2838 report_file_error ("Failed cfsetspeed", tem);
2839 childp2 = Fplist_put (childp2, QCspeed, tem);
2841 /* Configure bytesize. */
2842 if (!NILP (Fplist_member (contact, QCbytesize)))
2843 tem = Fplist_get (contact, QCbytesize);
2844 else
2845 tem = Fplist_get (p->childp, QCbytesize);
2846 if (NILP (tem))
2847 tem = make_number (8);
2848 CHECK_NUMBER (tem);
2849 if (XINT (tem) != 7 && XINT (tem) != 8)
2850 error (":bytesize must be nil (8), 7, or 8");
2851 summary[0] = XINT (tem) + '0';
2852 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2853 attr.c_cflag &= ~CSIZE;
2854 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2855 #else
2856 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2857 if (XINT (tem) != 8)
2858 error ("Bytesize cannot be changed");
2859 #endif
2860 childp2 = Fplist_put (childp2, QCbytesize, tem);
2862 /* Configure parity. */
2863 if (!NILP (Fplist_member (contact, QCparity)))
2864 tem = Fplist_get (contact, QCparity);
2865 else
2866 tem = Fplist_get (p->childp, QCparity);
2867 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2868 error (":parity must be nil (no parity), `even', or `odd'");
2869 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2870 attr.c_cflag &= ~(PARENB | PARODD);
2871 attr.c_iflag &= ~(IGNPAR | INPCK);
2872 if (NILP (tem))
2874 summary[1] = 'N';
2876 else if (EQ (tem, Qeven))
2878 summary[1] = 'E';
2879 attr.c_cflag |= PARENB;
2880 attr.c_iflag |= (IGNPAR | INPCK);
2882 else if (EQ (tem, Qodd))
2884 summary[1] = 'O';
2885 attr.c_cflag |= (PARENB | PARODD);
2886 attr.c_iflag |= (IGNPAR | INPCK);
2888 #else
2889 /* Don't error on no parity, which should be set by cfmakeraw. */
2890 if (!NILP (tem))
2891 error ("Parity cannot be configured");
2892 #endif
2893 childp2 = Fplist_put (childp2, QCparity, tem);
2895 /* Configure stopbits. */
2896 if (!NILP (Fplist_member (contact, QCstopbits)))
2897 tem = Fplist_get (contact, QCstopbits);
2898 else
2899 tem = Fplist_get (p->childp, QCstopbits);
2900 if (NILP (tem))
2901 tem = make_number (1);
2902 CHECK_NUMBER (tem);
2903 if (XINT (tem) != 1 && XINT (tem) != 2)
2904 error (":stopbits must be nil (1 stopbit), 1, or 2");
2905 summary[2] = XINT (tem) + '0';
2906 #if defined (CSTOPB)
2907 attr.c_cflag &= ~CSTOPB;
2908 if (XINT (tem) == 2)
2909 attr.c_cflag |= CSTOPB;
2910 #else
2911 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2912 if (XINT (tem) != 1)
2913 error ("Stopbits cannot be configured");
2914 #endif
2915 childp2 = Fplist_put (childp2, QCstopbits, tem);
2917 /* Configure flowcontrol. */
2918 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2919 tem = Fplist_get (contact, QCflowcontrol);
2920 else
2921 tem = Fplist_get (p->childp, QCflowcontrol);
2922 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2923 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2924 #if defined (CRTSCTS)
2925 attr.c_cflag &= ~CRTSCTS;
2926 #endif
2927 #if defined (CNEW_RTSCTS)
2928 attr.c_cflag &= ~CNEW_RTSCTS;
2929 #endif
2930 #if defined (IXON) && defined (IXOFF)
2931 attr.c_iflag &= ~(IXON | IXOFF);
2932 #endif
2933 if (NILP (tem))
2935 /* Already configured. */
2937 else if (EQ (tem, Qhw))
2939 #if defined (CRTSCTS)
2940 attr.c_cflag |= CRTSCTS;
2941 #elif defined (CNEW_RTSCTS)
2942 attr.c_cflag |= CNEW_RTSCTS;
2943 #else
2944 error ("Hardware flowcontrol (RTS/CTS) not supported");
2945 #endif
2947 else if (EQ (tem, Qsw))
2949 #if defined (IXON) && defined (IXOFF)
2950 attr.c_iflag |= (IXON | IXOFF);
2951 #else
2952 error ("Software flowcontrol (XON/XOFF) not supported");
2953 #endif
2955 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2957 /* Activate configuration. */
2958 err = tcsetattr (p->outfd, TCSANOW, &attr);
2959 if (err != 0)
2960 report_file_error ("Failed tcsetattr", Qnil);
2962 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2963 pset_childp (p, childp2);
2965 #endif /* not DOS_NT */
2967 /* System depended enumeration of and access to system processes a-la ps(1). */
2969 #ifdef HAVE_PROCFS
2971 /* Process enumeration and access via /proc. */
2973 Lisp_Object
2974 list_system_processes (void)
2976 Lisp_Object procdir, match, proclist, next;
2977 Lisp_Object tail;
2979 /* For every process on the system, there's a directory in the
2980 "/proc" pseudo-directory whose name is the numeric ID of that
2981 process. */
2982 procdir = build_string ("/proc");
2983 match = build_string ("[0-9]+");
2984 proclist = directory_files_internal (procdir, Qnil, match, Qt, false, Qnil);
2986 /* `proclist' gives process IDs as strings. Destructively convert
2987 each string into a number. */
2988 for (tail = proclist; CONSP (tail); tail = next)
2990 next = XCDR (tail);
2991 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2994 /* directory_files_internal returns the files in reverse order; undo
2995 that. */
2996 proclist = Fnreverse (proclist);
2997 return proclist;
3000 #elif defined DARWIN_OS || defined __FreeBSD__
3002 Lisp_Object
3003 list_system_processes (void)
3005 #ifdef DARWIN_OS
3006 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
3007 #else
3008 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
3009 #endif
3010 size_t len;
3011 struct kinfo_proc *procs;
3012 size_t i;
3014 Lisp_Object proclist = Qnil;
3016 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
3017 return proclist;
3019 procs = xmalloc (len);
3020 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
3022 xfree (procs);
3023 return proclist;
3026 len /= sizeof (struct kinfo_proc);
3027 for (i = 0; i < len; i++)
3029 #ifdef DARWIN_OS
3030 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
3031 #else
3032 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
3033 #endif
3036 xfree (procs);
3038 return proclist;
3041 /* The WINDOWSNT implementation is in w32.c.
3042 The MSDOS implementation is in dosfns.c. */
3043 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3045 Lisp_Object
3046 list_system_processes (void)
3048 return Qnil;
3051 #endif /* !defined (WINDOWSNT) */
3053 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3054 static struct timespec
3055 time_from_jiffies (unsigned long long tval, long hz)
3057 unsigned long long s = tval / hz;
3058 unsigned long long frac = tval % hz;
3059 int ns;
3061 if (TYPE_MAXIMUM (time_t) < s)
3062 time_overflow ();
3063 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
3064 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
3065 ns = frac * TIMESPEC_RESOLUTION / hz;
3066 else
3068 /* This is reachable only in the unlikely case that HZ * HZ
3069 exceeds ULLONG_MAX. It calculates an approximation that is
3070 guaranteed to be in range. */
3071 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3072 + (hz % TIMESPEC_RESOLUTION != 0));
3073 ns = frac / hz_per_ns;
3076 return make_timespec (s, ns);
3079 static Lisp_Object
3080 ltime_from_jiffies (unsigned long long tval, long hz)
3082 struct timespec t = time_from_jiffies (tval, hz);
3083 return make_lisp_time (t);
3086 static struct timespec
3087 get_up_time (void)
3089 FILE *fup;
3090 struct timespec up = make_timespec (0, 0);
3092 block_input ();
3093 fup = emacs_fopen ("/proc/uptime", "r");
3095 if (fup)
3097 unsigned long long upsec, upfrac, idlesec, idlefrac;
3098 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3100 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3101 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3102 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3103 == 4)
3105 if (TYPE_MAXIMUM (time_t) < upsec)
3107 upsec = TYPE_MAXIMUM (time_t);
3108 upfrac = TIMESPEC_RESOLUTION - 1;
3110 else
3112 int upfraclen = upfrac_end - upfrac_start;
3113 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3114 upfrac *= 10;
3115 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3116 upfrac /= 10;
3117 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3119 up = make_timespec (upsec, upfrac);
3121 fclose (fup);
3123 unblock_input ();
3125 return up;
3128 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3129 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3131 static Lisp_Object
3132 procfs_ttyname (int rdev)
3134 FILE *fdev;
3135 char name[PATH_MAX];
3137 block_input ();
3138 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3139 name[0] = 0;
3141 if (fdev)
3143 unsigned major;
3144 unsigned long minor_beg, minor_end;
3145 char minor[25]; /* 2 32-bit numbers + dash */
3146 char *endp;
3148 for (; !feof_unlocked (fdev) && !ferror_unlocked (fdev); name[0] = 0)
3150 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3151 && major == MAJOR (rdev))
3153 minor_beg = strtoul (minor, &endp, 0);
3154 if (*endp == '\0')
3155 minor_end = minor_beg;
3156 else if (*endp == '-')
3157 minor_end = strtoul (endp + 1, &endp, 0);
3158 else
3159 continue;
3161 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3163 sprintf (name + strlen (name), "%u", MINOR (rdev));
3164 break;
3168 fclose (fdev);
3170 unblock_input ();
3171 return build_string (name);
3174 static uintmax_t
3175 procfs_get_total_memory (void)
3177 FILE *fmem;
3178 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3179 int c;
3181 block_input ();
3182 fmem = emacs_fopen ("/proc/meminfo", "r");
3184 if (fmem)
3186 uintmax_t entry_value;
3187 bool done;
3190 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3192 case 1:
3193 retval = entry_value;
3194 done = 1;
3195 break;
3197 case 0:
3198 while ((c = getc_unlocked (fmem)) != EOF && c != '\n')
3199 continue;
3200 done = c == EOF;
3201 break;
3203 default:
3204 done = 1;
3205 break;
3207 while (!done);
3209 fclose (fmem);
3211 unblock_input ();
3212 return retval;
3215 Lisp_Object
3216 system_process_attributes (Lisp_Object pid)
3218 char procfn[PATH_MAX], fn[PATH_MAX];
3219 struct stat st;
3220 struct passwd *pw;
3221 struct group *gr;
3222 long clocks_per_sec;
3223 char *procfn_end;
3224 char procbuf[1025], *p, *q;
3225 int fd;
3226 ssize_t nread;
3227 static char const default_cmd[] = "???";
3228 const char *cmd = default_cmd;
3229 int cmdsize = sizeof default_cmd - 1;
3230 char *cmdline = NULL;
3231 ptrdiff_t cmdline_size;
3232 char c;
3233 printmax_t proc_id;
3234 int ppid, pgrp, sess, tty, tpgid, thcount;
3235 uid_t uid;
3236 gid_t gid;
3237 unsigned long long u_time, s_time, cutime, cstime, start;
3238 long priority, niceness, rss;
3239 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3240 struct timespec tnow, tstart, tboot, telapsed, us_time;
3241 double pcpu, pmem;
3242 Lisp_Object attrs = Qnil;
3243 Lisp_Object decoded_cmd;
3244 ptrdiff_t count;
3246 CHECK_NUMBER_OR_FLOAT (pid);
3247 CONS_TO_INTEGER (pid, pid_t, proc_id);
3248 sprintf (procfn, "/proc/%"pMd, proc_id);
3249 if (stat (procfn, &st) < 0)
3250 return attrs;
3252 /* euid egid */
3253 uid = st.st_uid;
3254 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3255 block_input ();
3256 pw = getpwuid (uid);
3257 unblock_input ();
3258 if (pw)
3259 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3261 gid = st.st_gid;
3262 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3263 block_input ();
3264 gr = getgrgid (gid);
3265 unblock_input ();
3266 if (gr)
3267 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3269 count = SPECPDL_INDEX ();
3270 strcpy (fn, procfn);
3271 procfn_end = fn + strlen (fn);
3272 strcpy (procfn_end, "/stat");
3273 fd = emacs_open (fn, O_RDONLY, 0);
3274 if (fd < 0)
3275 nread = 0;
3276 else
3278 record_unwind_protect_int (close_file_unwind, fd);
3279 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3281 if (0 < nread)
3283 procbuf[nread] = '\0';
3284 p = procbuf;
3286 p = strchr (p, '(');
3287 if (p != NULL)
3289 q = strrchr (p + 1, ')');
3290 /* comm */
3291 if (q != NULL)
3293 cmd = p + 1;
3294 cmdsize = q - cmd;
3297 else
3298 q = NULL;
3299 /* Command name is encoded in locale-coding-system; decode it. */
3300 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3301 decoded_cmd = code_convert_string_norecord (cmd_str,
3302 Vlocale_coding_system, 0);
3303 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3305 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3306 utime stime cutime cstime priority nice thcount . start vsize rss */
3307 if (q
3308 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3309 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3310 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3311 &minflt, &cminflt, &majflt, &cmajflt,
3312 &u_time, &s_time, &cutime, &cstime,
3313 &priority, &niceness, &thcount, &start, &vsize, &rss)
3314 == 20))
3316 char state_str[2];
3317 state_str[0] = c;
3318 state_str[1] = '\0';
3319 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3320 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3321 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3322 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3323 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3324 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3325 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3326 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3327 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3328 attrs);
3329 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3330 attrs);
3331 clocks_per_sec = sysconf (_SC_CLK_TCK);
3332 if (clocks_per_sec < 0)
3333 clocks_per_sec = 100;
3334 attrs = Fcons (Fcons (Qutime,
3335 ltime_from_jiffies (u_time, clocks_per_sec)),
3336 attrs);
3337 attrs = Fcons (Fcons (Qstime,
3338 ltime_from_jiffies (s_time, clocks_per_sec)),
3339 attrs);
3340 attrs = Fcons (Fcons (Qtime,
3341 ltime_from_jiffies (s_time + u_time,
3342 clocks_per_sec)),
3343 attrs);
3344 attrs = Fcons (Fcons (Qcutime,
3345 ltime_from_jiffies (cutime, clocks_per_sec)),
3346 attrs);
3347 attrs = Fcons (Fcons (Qcstime,
3348 ltime_from_jiffies (cstime, clocks_per_sec)),
3349 attrs);
3350 attrs = Fcons (Fcons (Qctime,
3351 ltime_from_jiffies (cstime + cutime,
3352 clocks_per_sec)),
3353 attrs);
3354 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3355 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3356 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3357 attrs);
3358 tnow = current_timespec ();
3359 telapsed = get_up_time ();
3360 tboot = timespec_sub (tnow, telapsed);
3361 tstart = time_from_jiffies (start, clocks_per_sec);
3362 tstart = timespec_add (tboot, tstart);
3363 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3364 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3365 attrs);
3366 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3367 telapsed = timespec_sub (tnow, tstart);
3368 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3369 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3370 pcpu = timespectod (us_time) / timespectod (telapsed);
3371 if (pcpu > 1.0)
3372 pcpu = 1.0;
3373 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3374 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3375 if (pmem > 100)
3376 pmem = 100;
3377 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3380 unbind_to (count, Qnil);
3382 /* args */
3383 strcpy (procfn_end, "/cmdline");
3384 fd = emacs_open (fn, O_RDONLY, 0);
3385 if (fd >= 0)
3387 ptrdiff_t readsize, nread_incr;
3388 record_unwind_protect_int (close_file_unwind, fd);
3389 record_unwind_protect_nothing ();
3390 nread = cmdline_size = 0;
3394 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3395 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3397 /* Leave room even if every byte needs escaping below. */
3398 readsize = (cmdline_size >> 1) - nread;
3400 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3401 nread += max (0, nread_incr);
3403 while (nread_incr == readsize);
3405 if (nread)
3407 /* We don't want trailing null characters. */
3408 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3409 continue;
3411 /* Escape-quote whitespace and backslashes. */
3412 q = cmdline + cmdline_size;
3413 while (cmdline < p)
3415 char c = *--p;
3416 *--q = c ? c : ' ';
3417 if (c_isspace (c) || c == '\\')
3418 *--q = '\\';
3421 nread = cmdline + cmdline_size - q;
3424 if (!nread)
3426 nread = cmdsize + 2;
3427 cmdline_size = nread + 1;
3428 q = cmdline = xrealloc (cmdline, cmdline_size);
3429 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3430 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3432 /* Command line is encoded in locale-coding-system; decode it. */
3433 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3434 decoded_cmd = code_convert_string_norecord (cmd_str,
3435 Vlocale_coding_system, 0);
3436 unbind_to (count, Qnil);
3437 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3440 return attrs;
3443 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3445 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3446 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3447 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3448 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3449 #undef _FILE_OFFSET_BITS
3450 #else
3451 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3452 #endif
3454 #include <procfs.h>
3456 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3457 #define _FILE_OFFSET_BITS 64
3458 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3459 #endif
3460 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3462 Lisp_Object
3463 system_process_attributes (Lisp_Object pid)
3465 char procfn[PATH_MAX], fn[PATH_MAX];
3466 struct stat st;
3467 struct passwd *pw;
3468 struct group *gr;
3469 char *procfn_end;
3470 struct psinfo pinfo;
3471 int fd;
3472 ssize_t nread;
3473 printmax_t proc_id;
3474 uid_t uid;
3475 gid_t gid;
3476 Lisp_Object attrs = Qnil;
3477 Lisp_Object decoded_cmd;
3478 ptrdiff_t count;
3480 CHECK_NUMBER_OR_FLOAT (pid);
3481 CONS_TO_INTEGER (pid, pid_t, proc_id);
3482 sprintf (procfn, "/proc/%"pMd, proc_id);
3483 if (stat (procfn, &st) < 0)
3484 return attrs;
3486 /* euid egid */
3487 uid = st.st_uid;
3488 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3489 block_input ();
3490 pw = getpwuid (uid);
3491 unblock_input ();
3492 if (pw)
3493 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3495 gid = st.st_gid;
3496 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3497 block_input ();
3498 gr = getgrgid (gid);
3499 unblock_input ();
3500 if (gr)
3501 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3503 count = SPECPDL_INDEX ();
3504 strcpy (fn, procfn);
3505 procfn_end = fn + strlen (fn);
3506 strcpy (procfn_end, "/psinfo");
3507 fd = emacs_open (fn, O_RDONLY, 0);
3508 if (fd < 0)
3509 nread = 0;
3510 else
3512 record_unwind_protect_int (close_file_unwind, fd);
3513 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3516 if (nread == sizeof pinfo)
3518 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3519 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3520 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3523 char state_str[2];
3524 state_str[0] = pinfo.pr_lwp.pr_sname;
3525 state_str[1] = '\0';
3526 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3529 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3530 need to get a string from it. */
3532 /* FIXME: missing: Qtpgid */
3534 /* FIXME: missing:
3535 Qminflt
3536 Qmajflt
3537 Qcminflt
3538 Qcmajflt
3540 Qutime
3541 Qcutime
3542 Qstime
3543 Qcstime
3544 Are they available? */
3546 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3547 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3548 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3549 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3550 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3551 attrs);
3553 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3554 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3555 attrs);
3556 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3557 attrs);
3559 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3560 range 0 .. 2**15, representing 0.0 .. 1.0. */
3561 attrs = Fcons (Fcons (Qpcpu,
3562 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3563 attrs);
3564 attrs = Fcons (Fcons (Qpmem,
3565 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3566 attrs);
3568 AUTO_STRING (fname, pinfo.pr_fname);
3569 decoded_cmd = code_convert_string_norecord (fname,
3570 Vlocale_coding_system, 0);
3571 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3572 AUTO_STRING (psargs, pinfo.pr_psargs);
3573 decoded_cmd = code_convert_string_norecord (psargs,
3574 Vlocale_coding_system, 0);
3575 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3577 unbind_to (count, Qnil);
3578 return attrs;
3581 #elif defined __FreeBSD__
3583 static struct timespec
3584 timeval_to_timespec (struct timeval t)
3586 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3589 static Lisp_Object
3590 make_lisp_timeval (struct timeval t)
3592 return make_lisp_time (timeval_to_timespec (t));
3595 Lisp_Object
3596 system_process_attributes (Lisp_Object pid)
3598 int proc_id;
3599 int pagesize = getpagesize ();
3600 unsigned long npages;
3601 int fscale;
3602 struct passwd *pw;
3603 struct group *gr;
3604 char *ttyname;
3605 size_t len;
3606 char args[MAXPATHLEN];
3607 struct timespec t, now;
3609 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3610 struct kinfo_proc proc;
3611 size_t proclen = sizeof proc;
3613 Lisp_Object attrs = Qnil;
3614 Lisp_Object decoded_comm;
3616 CHECK_NUMBER_OR_FLOAT (pid);
3617 CONS_TO_INTEGER (pid, int, proc_id);
3618 mib[3] = proc_id;
3620 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3621 return attrs;
3623 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3625 block_input ();
3626 pw = getpwuid (proc.ki_uid);
3627 unblock_input ();
3628 if (pw)
3629 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3631 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3633 block_input ();
3634 gr = getgrgid (proc.ki_svgid);
3635 unblock_input ();
3636 if (gr)
3637 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3639 AUTO_STRING (comm, proc.ki_comm);
3640 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3642 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3644 char state[2] = {'\0', '\0'};
3645 switch (proc.ki_stat)
3647 case SRUN:
3648 state[0] = 'R';
3649 break;
3651 case SSLEEP:
3652 state[0] = 'S';
3653 break;
3655 case SLOCK:
3656 state[0] = 'D';
3657 break;
3659 case SZOMB:
3660 state[0] = 'Z';
3661 break;
3663 case SSTOP:
3664 state[0] = 'T';
3665 break;
3667 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3670 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3671 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3672 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3674 block_input ();
3675 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3676 unblock_input ();
3677 if (ttyname)
3678 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3680 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3681 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3682 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3683 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3684 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3686 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3687 attrs);
3688 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3689 attrs);
3690 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3691 timeval_to_timespec (proc.ki_rusage.ru_stime));
3692 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3694 attrs = Fcons (Fcons (Qcutime,
3695 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3696 attrs);
3697 attrs = Fcons (Fcons (Qcstime,
3698 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3699 attrs);
3700 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3701 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3702 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3704 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3705 attrs);
3706 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3707 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3708 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3709 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3710 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3711 attrs);
3713 now = current_timespec ();
3714 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3715 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3717 len = sizeof fscale;
3718 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3720 double pcpu;
3721 fixpt_t ccpu;
3722 len = sizeof ccpu;
3723 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3725 pcpu = (100.0 * proc.ki_pctcpu / fscale
3726 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3727 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3731 len = sizeof npages;
3732 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3734 double pmem = (proc.ki_flag & P_INMEM
3735 ? 100.0 * proc.ki_rssize / npages
3736 : 0);
3737 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3740 mib[2] = KERN_PROC_ARGS;
3741 len = MAXPATHLEN;
3742 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3744 int i;
3745 for (i = 0; i < len; i++)
3747 if (! args[i] && i < len - 1)
3748 args[i] = ' ';
3751 AUTO_STRING (comm, args);
3752 decoded_comm = code_convert_string_norecord (comm,
3753 Vlocale_coding_system, 0);
3755 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3758 return attrs;
3761 #elif defined DARWIN_OS
3763 static struct timespec
3764 timeval_to_timespec (struct timeval t)
3766 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3769 static Lisp_Object
3770 make_lisp_timeval (struct timeval t)
3772 return make_lisp_time (timeval_to_timespec (t));
3775 Lisp_Object
3776 system_process_attributes (Lisp_Object pid)
3778 int proc_id;
3779 struct passwd *pw;
3780 struct group *gr;
3781 char *ttyname;
3782 struct timeval starttime;
3783 struct timespec t, now;
3784 struct rusage *rusage;
3785 dev_t tdev;
3786 uid_t uid;
3787 gid_t gid;
3789 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3790 struct kinfo_proc proc;
3791 size_t proclen = sizeof proc;
3793 Lisp_Object attrs = Qnil;
3794 Lisp_Object decoded_comm;
3796 CHECK_NUMBER_OR_FLOAT (pid);
3797 CONS_TO_INTEGER (pid, int, proc_id);
3798 mib[3] = proc_id;
3800 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3801 return attrs;
3803 uid = proc.kp_eproc.e_ucred.cr_uid;
3804 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3806 block_input ();
3807 pw = getpwuid (uid);
3808 unblock_input ();
3809 if (pw)
3810 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3812 gid = proc.kp_eproc.e_pcred.p_svgid;
3813 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3815 block_input ();
3816 gr = getgrgid (gid);
3817 unblock_input ();
3818 if (gr)
3819 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3821 decoded_comm = (code_convert_string_norecord
3822 (build_unibyte_string (proc.kp_proc.p_comm),
3823 Vlocale_coding_system, 0));
3825 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3827 char state[2] = {'\0', '\0'};
3828 switch (proc.kp_proc.p_stat)
3830 case SRUN:
3831 state[0] = 'R';
3832 break;
3834 case SSLEEP:
3835 state[0] = 'S';
3836 break;
3838 case SZOMB:
3839 state[0] = 'Z';
3840 break;
3842 case SSTOP:
3843 state[0] = 'T';
3844 break;
3846 case SIDL:
3847 state[0] = 'I';
3848 break;
3850 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3853 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3854 attrs);
3855 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3856 attrs);
3858 tdev = proc.kp_eproc.e_tdev;
3859 block_input ();
3860 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3861 unblock_input ();
3862 if (ttyname)
3863 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3865 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3866 attrs);
3868 rusage = proc.kp_proc.p_ru;
3869 if (rusage)
3871 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3872 attrs);
3873 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3874 attrs);
3876 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3877 attrs);
3878 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3879 attrs);
3880 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3881 timeval_to_timespec (rusage->ru_stime));
3882 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3885 starttime = proc.kp_proc.p_starttime;
3886 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3887 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3889 now = current_timespec ();
3890 t = timespec_sub (now, timeval_to_timespec (starttime));
3891 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3893 return attrs;
3896 /* The WINDOWSNT implementation is in w32.c.
3897 The MSDOS implementation is in dosfns.c. */
3898 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3900 Lisp_Object
3901 system_process_attributes (Lisp_Object pid)
3903 return Qnil;
3906 #endif /* !defined (WINDOWSNT) */
3908 /* Wide character string collation. */
3910 #ifdef __STDC_ISO_10646__
3911 # include <wchar.h>
3912 # include <wctype.h>
3914 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3915 # include <locale.h>
3916 # endif
3917 # ifndef LC_COLLATE
3918 # define LC_COLLATE 0
3919 # endif
3920 # ifndef LC_COLLATE_MASK
3921 # define LC_COLLATE_MASK 0
3922 # endif
3923 # ifndef LC_CTYPE
3924 # define LC_CTYPE 0
3925 # endif
3926 # ifndef LC_CTYPE_MASK
3927 # define LC_CTYPE_MASK 0
3928 # endif
3930 # ifndef HAVE_NEWLOCALE
3931 # undef freelocale
3932 # undef locale_t
3933 # undef newlocale
3934 # undef wcscoll_l
3935 # undef towlower_l
3936 # define freelocale emacs_freelocale
3937 # define locale_t emacs_locale_t
3938 # define newlocale emacs_newlocale
3939 # define wcscoll_l emacs_wcscoll_l
3940 # define towlower_l emacs_towlower_l
3942 typedef char const *locale_t;
3944 static locale_t
3945 newlocale (int category_mask, char const *locale, locale_t loc)
3947 return locale;
3950 static void
3951 freelocale (locale_t loc)
3955 static char *
3956 emacs_setlocale (int category, char const *locale)
3958 # ifdef HAVE_SETLOCALE
3959 errno = 0;
3960 char *loc = setlocale (category, locale);
3961 if (loc || errno)
3962 return loc;
3963 errno = EINVAL;
3964 # else
3965 errno = ENOTSUP;
3966 # endif
3967 return 0;
3970 static int
3971 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3973 int result = 0;
3974 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3975 int err;
3977 if (! oldloc)
3978 err = errno;
3979 else
3981 USE_SAFE_ALLOCA;
3982 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3983 strcpy (oldcopy, oldloc);
3984 if (! emacs_setlocale (LC_COLLATE, loc))
3985 err = errno;
3986 else
3988 errno = 0;
3989 result = wcscoll (a, b);
3990 err = errno;
3991 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3992 err = errno;
3994 SAFE_FREE ();
3997 errno = err;
3998 return result;
4001 static wint_t
4002 towlower_l (wint_t wc, locale_t loc)
4004 wint_t result = wc;
4005 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
4007 if (oldloc)
4009 USE_SAFE_ALLOCA;
4010 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
4011 strcpy (oldcopy, oldloc);
4012 if (emacs_setlocale (LC_CTYPE, loc))
4014 result = towlower (wc);
4015 emacs_setlocale (LC_COLLATE, oldcopy);
4017 SAFE_FREE ();
4020 return result;
4022 # endif
4025 str_collate (Lisp_Object s1, Lisp_Object s2,
4026 Lisp_Object locale, Lisp_Object ignore_case)
4028 int res, err;
4029 ptrdiff_t len, i, i_byte;
4030 wchar_t *p1, *p2;
4032 USE_SAFE_ALLOCA;
4034 /* Convert byte stream to code points. */
4035 len = SCHARS (s1); i = i_byte = 0;
4036 SAFE_NALLOCA (p1, 1, len + 1);
4037 while (i < len)
4038 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
4039 *(p1+len) = 0;
4041 len = SCHARS (s2); i = i_byte = 0;
4042 SAFE_NALLOCA (p2, 1, len + 1);
4043 while (i < len)
4044 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
4045 *(p2+len) = 0;
4047 if (STRINGP (locale))
4049 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
4050 SSDATA (locale), 0);
4051 if (!loc)
4052 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4054 if (! NILP (ignore_case))
4055 for (int i = 1; i < 3; i++)
4057 wchar_t *p = (i == 1) ? p1 : p2;
4058 for (; *p; p++)
4059 *p = towlower_l (*p, loc);
4062 errno = 0;
4063 res = wcscoll_l (p1, p2, loc);
4064 err = errno;
4065 freelocale (loc);
4067 else
4069 if (! NILP (ignore_case))
4070 for (int i = 1; i < 3; i++)
4072 wchar_t *p = (i == 1) ? p1 : p2;
4073 for (; *p; p++)
4074 *p = towlower (*p);
4077 errno = 0;
4078 res = wcscoll (p1, p2);
4079 err = errno;
4081 # ifndef HAVE_NEWLOCALE
4082 if (err)
4083 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4084 # else
4085 if (err)
4086 error ("Invalid string for collation: %s", emacs_strerror (err));
4087 # endif
4089 SAFE_FREE ();
4090 return res;
4092 #endif /* __STDC_ISO_10646__ */
4094 #ifdef WINDOWSNT
4096 str_collate (Lisp_Object s1, Lisp_Object s2,
4097 Lisp_Object locale, Lisp_Object ignore_case)
4100 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4101 int res, err = errno;
4103 errno = 0;
4104 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4105 if (errno)
4106 error ("Invalid string for collation: %s", strerror (errno));
4108 errno = err;
4109 return res;
4111 #endif /* WINDOWSNT */