Fix bug with unmounted directory on GNU/Linux
[emacs.git] / src / sysdep.c
blob8291a606bea1e21cee2274b7424a8101d5f6cd16
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 on errors. */
225 char *
226 emacs_get_current_dir_name (void)
228 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
229 # ifdef HYBRID_MALLOC
230 bool use_libc = bss_sbrk_did_unexec;
231 # else
232 bool use_libc = true;
233 # endif
234 if (use_libc)
236 /* GNU/Linux get_current_dir_name can return a string starting
237 with "(unreachable)" (Bug#27871). */
238 char *wd = get_current_dir_name ();
239 if (wd && ! (IS_DIRECTORY_SEP (*wd) || (*wd && IS_DEVICE_SEP (wd[1]))))
241 free (wd);
242 errno = ENOENT;
243 return NULL;
245 return wd;
247 # endif
249 char *buf;
250 char *pwd = getenv ("PWD");
251 struct stat dotstat, pwdstat;
252 /* If PWD is accurate, use it instead of calling getcwd. PWD is
253 sometimes a nicer name, and using it may avoid a fatal error if a
254 parent directory is searchable but not readable. */
255 if (pwd
256 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
257 && stat (pwd, &pwdstat) == 0
258 && stat (".", &dotstat) == 0
259 && dotstat.st_ino == pwdstat.st_ino
260 && dotstat.st_dev == pwdstat.st_dev
261 #ifdef MAXPATHLEN
262 && strlen (pwd) < MAXPATHLEN
263 #endif
266 buf = malloc (strlen (pwd) + 1);
267 if (!buf)
268 return NULL;
269 strcpy (buf, pwd);
271 else
273 size_t buf_size = 1024;
274 buf = malloc (buf_size);
275 if (!buf)
276 return NULL;
277 for (;;)
279 if (getcwd (buf, buf_size) == buf)
280 break;
281 if (errno != ERANGE)
283 int tmp_errno = errno;
284 free (buf);
285 errno = tmp_errno;
286 return NULL;
288 buf_size *= 2;
289 buf = realloc (buf, buf_size);
290 if (!buf)
291 return NULL;
294 return buf;
298 /* Discard pending input on all input descriptors. */
300 void
301 discard_tty_input (void)
303 #ifndef WINDOWSNT
304 struct emacs_tty buf;
306 if (noninteractive)
307 return;
309 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
310 while (dos_keyread () != -1)
312 #else /* not MSDOS */
314 struct tty_display_info *tty;
315 for (tty = tty_list; tty; tty = tty->next)
317 if (tty->input) /* Is the device suspended? */
319 emacs_get_tty (fileno (tty->input), &buf);
320 emacs_set_tty (fileno (tty->input), &buf, 0);
324 #endif /* not MSDOS */
325 #endif /* not WINDOWSNT */
329 #ifdef SIGTSTP
331 /* Arrange for character C to be read as the next input from
332 the terminal.
333 XXX What if we have multiple ttys?
336 void
337 stuff_char (char c)
339 if (! (FRAMEP (selected_frame)
340 && FRAME_LIVE_P (XFRAME (selected_frame))
341 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
342 return;
344 /* Should perhaps error if in batch mode */
345 #ifdef TIOCSTI
346 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
347 #else /* no TIOCSTI */
348 error ("Cannot stuff terminal input characters in this version of Unix");
349 #endif /* no TIOCSTI */
352 #endif /* SIGTSTP */
354 void
355 init_baud_rate (int fd)
357 int emacs_ospeed;
359 if (noninteractive)
360 emacs_ospeed = 0;
361 else
363 #ifdef DOS_NT
364 emacs_ospeed = 15;
365 #else /* not DOS_NT */
366 struct termios sg;
368 sg.c_cflag = B9600;
369 tcgetattr (fd, &sg);
370 emacs_ospeed = cfgetospeed (&sg);
371 #endif /* not DOS_NT */
374 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
375 ? baud_convert[emacs_ospeed] : 9600);
376 if (baud_rate == 0)
377 baud_rate = 1200;
382 #ifndef MSDOS
384 /* Wait for the subprocess with process id CHILD to terminate or change status.
385 CHILD must be a child process that has not been reaped.
386 If STATUS is non-null, store the waitpid-style exit status into *STATUS
387 and tell wait_reading_process_output that it needs to look around.
388 Use waitpid-style OPTIONS when waiting.
389 If INTERRUPTIBLE, this function is interruptible by a signal.
391 Return CHILD if successful, 0 if no status is available, and a
392 negative value (setting errno) if waitpid is buggy. */
393 static pid_t
394 get_child_status (pid_t child, int *status, int options, bool interruptible)
396 pid_t pid;
398 /* Invoke waitpid only with a known process ID; do not invoke
399 waitpid with a nonpositive argument. Otherwise, Emacs might
400 reap an unwanted process by mistake. For example, invoking
401 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
402 so that another thread running glib won't find them. */
403 eassert (child > 0);
405 while (true)
407 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
408 internally. */
409 if (interruptible)
410 maybe_quit ();
412 pid = waitpid (child, status, options);
413 if (0 <= pid)
414 break;
415 if (errno != EINTR)
417 /* Most likely, waitpid is buggy and the operating system
418 lost track of the child somehow. Return -1 and let the
419 caller try to figure things out. Possibly the bug could
420 cause Emacs to kill the wrong process. Oh well. */
421 return pid;
425 /* If successful and status is requested, tell wait_reading_process_output
426 that it needs to wake up and look around. */
427 if (pid && status && input_available_clear_time)
428 *input_available_clear_time = make_timespec (0, 0);
430 return pid;
433 /* Wait for the subprocess with process id CHILD to terminate.
434 CHILD must be a child process that has not been reaped.
435 If STATUS is non-null, store the waitpid-style exit status into *STATUS
436 and tell wait_reading_process_output that it needs to look around.
437 If INTERRUPTIBLE, this function is interruptible by a signal.
438 Return true if successful, false (setting errno) if CHILD cannot be
439 waited for because waitpid is buggy. */
440 bool
441 wait_for_termination (pid_t child, int *status, bool interruptible)
443 return 0 <= get_child_status (child, status, 0, interruptible);
446 /* Report whether the subprocess with process id CHILD has changed status.
447 Termination counts as a change of status.
448 CHILD must be a child process that has not been reaped.
449 If STATUS is non-null, store the waitpid-style exit status into *STATUS
450 and tell wait_reading_process_output that it needs to look around.
451 Use waitpid-style OPTIONS to check status, but do not wait.
453 Return CHILD if successful, 0 if no status is available because
454 the process's state has not changed. */
455 pid_t
456 child_status_changed (pid_t child, int *status, int options)
458 return get_child_status (child, status, WNOHANG | options, 0);
462 /* Set up the terminal at the other end of a pseudo-terminal that
463 we will be controlling an inferior through.
464 It should not echo or do line-editing, since that is done
465 in Emacs. No padding needed for insertion into an Emacs buffer. */
467 void
468 child_setup_tty (int out)
470 #ifndef WINDOWSNT
471 struct emacs_tty s;
473 emacs_get_tty (out, &s);
474 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
475 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
476 #ifdef NLDLY
477 /* https://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
478 Some versions of GNU Hurd do not have FFDLY? */
479 #ifdef FFDLY
480 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
481 /* No output delays */
482 #else
483 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
484 /* No output delays */
485 #endif
486 #endif
487 s.main.c_lflag &= ~ECHO; /* Disable echo */
488 s.main.c_lflag |= ISIG; /* Enable signals */
489 #ifdef IUCLC
490 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
491 #endif
492 #ifdef ISTRIP
493 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
494 #endif
495 #ifdef OLCUC
496 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
497 #endif
498 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
499 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
500 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
501 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
503 #ifdef HPUX
504 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
505 #endif /* HPUX */
507 #ifdef SIGNALS_VIA_CHARACTERS
508 /* the QUIT and INTR character are used in process_send_signal
509 so set them here to something useful. */
510 if (s.main.c_cc[VQUIT] == CDISABLE)
511 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
512 if (s.main.c_cc[VINTR] == CDISABLE)
513 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
514 #endif /* not SIGNALS_VIA_CHARACTERS */
516 #ifdef AIX
517 /* Also, PTY overloads NUL and BREAK.
518 don't ignore break, but don't signal either, so it looks like NUL. */
519 s.main.c_iflag &= ~IGNBRK;
520 s.main.c_iflag &= ~BRKINT;
521 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
522 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
523 would force it to 0377. That looks like duplicated code. */
524 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
525 #endif /* AIX */
527 /* We originally enabled ICANON (and set VEOF to 04), and then had
528 process.c send additional EOF chars to flush the output when faced
529 with long lines, but this leads to weird effects when the
530 subprocess has disabled ICANON and ends up seeing those spurious
531 extra EOFs. So we don't send EOFs any more in
532 process.c:send_process. First we tried to disable ICANON by
533 default, so if a subsprocess sets up ICANON, it's his problem (or
534 the Elisp package that talks to it) to deal with lines that are
535 too long. But this disables some features, such as the ability
536 to send EOF signals. So we re-enabled ICANON but there is no
537 more "send eof to flush" going on (which is wrong and unportable
538 in itself). The correct way to handle too much output is to
539 buffer what could not be written and then write it again when
540 select returns ok for writing. This has it own set of
541 problems. Write is now asynchronous, is that a problem? How much
542 do we buffer, and what do we do when that limit is reached? */
544 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
545 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
546 #if 0 /* These settings only apply to non-ICANON mode. */
547 s.main.c_cc[VMIN] = 1;
548 s.main.c_cc[VTIME] = 0;
549 #endif
551 emacs_set_tty (out, &s, 0);
552 #endif /* not WINDOWSNT */
554 #endif /* not MSDOS */
557 /* Record a signal code and the action for it. */
558 struct save_signal
560 int code;
561 struct sigaction action;
564 static void save_signal_handlers (struct save_signal *);
565 static void restore_signal_handlers (struct save_signal *);
567 /* Suspend the Emacs process; give terminal to its superior. */
569 void
570 sys_suspend (void)
572 #ifndef DOS_NT
573 kill (0, SIGTSTP);
574 #else
575 /* On a system where suspending is not implemented,
576 instead fork a subshell and let it talk directly to the terminal
577 while we wait. */
578 sys_subshell ();
580 #endif
583 /* Fork a subshell. */
585 void
586 sys_subshell (void)
588 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
589 #ifdef MSDOS
590 int st;
591 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
592 #else
593 char oldwd[MAX_UTF8_PATH];
594 #endif /* MSDOS */
595 #else /* !DOS_NT */
596 int status;
597 #endif
598 pid_t pid;
599 struct save_signal saved_handlers[5];
600 char *str = SSDATA (encode_current_directory ());
602 #ifdef DOS_NT
603 pid = 0;
604 #else
606 char *volatile str_volatile = str;
607 pid = vfork ();
608 str = str_volatile;
610 #endif
612 if (pid < 0)
613 error ("Can't spawn subshell");
615 saved_handlers[0].code = SIGINT;
616 saved_handlers[1].code = SIGQUIT;
617 saved_handlers[2].code = SIGTERM;
618 #ifdef USABLE_SIGIO
619 saved_handlers[3].code = SIGIO;
620 saved_handlers[4].code = 0;
621 #else
622 saved_handlers[3].code = 0;
623 #endif
625 #ifdef DOS_NT
626 save_signal_handlers (saved_handlers);
627 #endif
629 if (pid == 0)
631 const char *sh = 0;
633 #ifdef DOS_NT /* MW, Aug 1993 */
634 getcwd (oldwd, sizeof oldwd);
635 if (sh == 0)
636 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
637 #endif
638 if (sh == 0)
639 sh = egetenv ("SHELL");
640 if (sh == 0)
641 sh = "sh";
643 /* Use our buffer's default directory for the subshell. */
644 if (chdir (str) != 0)
646 #ifndef DOS_NT
647 emacs_perror (str);
648 _exit (EXIT_CANCELED);
649 #endif
652 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
654 char *epwd = getenv ("PWD");
655 char old_pwd[MAXPATHLEN+1+4];
657 /* If PWD is set, pass it with corrected value. */
658 if (epwd)
660 strcpy (old_pwd, epwd);
661 setenv ("PWD", str, 1);
663 st = system (sh);
664 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
665 if (epwd)
666 putenv (old_pwd); /* restore previous value */
668 #else /* not MSDOS */
669 #ifdef WINDOWSNT
670 /* Waits for process completion */
671 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
672 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
673 if (pid == -1)
674 write (1, "Can't execute subshell", 22);
675 #else /* not WINDOWSNT */
676 execlp (sh, sh, (char *) 0);
677 emacs_perror (sh);
678 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
679 #endif /* not WINDOWSNT */
680 #endif /* not MSDOS */
683 /* Do this now if we did not do it before. */
684 #ifndef MSDOS
685 save_signal_handlers (saved_handlers);
686 #endif
688 #ifndef DOS_NT
689 wait_for_termination (pid, &status, 0);
690 #endif
691 restore_signal_handlers (saved_handlers);
694 static void
695 save_signal_handlers (struct save_signal *saved_handlers)
697 while (saved_handlers->code)
699 struct sigaction action;
700 emacs_sigaction_init (&action, SIG_IGN);
701 sigaction (saved_handlers->code, &action, &saved_handlers->action);
702 saved_handlers++;
706 static void
707 restore_signal_handlers (struct save_signal *saved_handlers)
709 while (saved_handlers->code)
711 sigaction (saved_handlers->code, &saved_handlers->action, 0);
712 saved_handlers++;
716 #ifdef USABLE_SIGIO
717 static int old_fcntl_flags[FD_SETSIZE];
718 #endif
720 void
721 init_sigio (int fd)
723 #ifdef USABLE_SIGIO
724 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
725 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
726 interrupts_deferred = 0;
727 #endif
730 #ifndef DOS_NT
731 static void
732 reset_sigio (int fd)
734 #ifdef USABLE_SIGIO
735 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
736 #endif
738 #endif
740 void
741 request_sigio (void)
743 #ifdef USABLE_SIGIO
744 sigset_t unblocked;
746 if (noninteractive)
747 return;
749 sigemptyset (&unblocked);
750 # ifdef SIGWINCH
751 sigaddset (&unblocked, SIGWINCH);
752 # endif
753 sigaddset (&unblocked, SIGIO);
754 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
756 interrupts_deferred = 0;
757 #endif
760 void
761 unrequest_sigio (void)
763 #ifdef USABLE_SIGIO
764 sigset_t blocked;
766 if (noninteractive)
767 return;
769 sigemptyset (&blocked);
770 # ifdef SIGWINCH
771 sigaddset (&blocked, SIGWINCH);
772 # endif
773 sigaddset (&blocked, SIGIO);
774 pthread_sigmask (SIG_BLOCK, &blocked, 0);
775 interrupts_deferred = 1;
776 #endif
779 #ifndef MSDOS
780 /* Block SIGCHLD. */
782 void
783 block_child_signal (sigset_t *oldset)
785 sigset_t blocked;
786 sigemptyset (&blocked);
787 sigaddset (&blocked, SIGCHLD);
788 sigaddset (&blocked, SIGINT);
789 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
792 /* Unblock SIGCHLD. */
794 void
795 unblock_child_signal (sigset_t const *oldset)
797 pthread_sigmask (SIG_SETMASK, oldset, 0);
800 /* Block SIGINT. */
801 void
802 block_interrupt_signal (sigset_t *oldset)
804 sigset_t blocked;
805 sigemptyset (&blocked);
806 sigaddset (&blocked, SIGINT);
807 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
810 /* Restore previously saved signal mask. */
811 void
812 restore_signal_mask (sigset_t const *oldset)
814 pthread_sigmask (SIG_SETMASK, oldset, 0);
817 #endif /* !MSDOS */
819 /* Saving and restoring the process group of Emacs's terminal. */
821 /* The process group of which Emacs was a member when it initially
822 started.
824 If Emacs was in its own process group (i.e. inherited_pgroup ==
825 getpid ()), then we know we're running under a shell with job
826 control (Emacs would never be run as part of a pipeline).
827 Everything is fine.
829 If Emacs was not in its own process group, then we know we're
830 running under a shell (or a caller) that doesn't know how to
831 separate itself from Emacs (like sh). Emacs must be in its own
832 process group in order to receive SIGIO correctly. In this
833 situation, we put ourselves in our own pgroup, forcibly set the
834 tty's pgroup to our pgroup, and make sure to restore and reinstate
835 the tty's pgroup just like any other terminal setting. If
836 inherited_group was not the tty's pgroup, then we'll get a
837 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
838 it goes foreground in the future, which is what should happen. */
840 static pid_t inherited_pgroup;
842 void
843 init_foreground_group (void)
845 pid_t pgrp = getpgrp ();
846 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
849 /* Block and unblock SIGTTOU. */
851 void
852 block_tty_out_signal (sigset_t *oldset)
854 #ifdef SIGTTOU
855 sigset_t blocked;
856 sigemptyset (&blocked);
857 sigaddset (&blocked, SIGTTOU);
858 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
859 #endif
862 void
863 unblock_tty_out_signal (sigset_t const *oldset)
865 #ifdef SIGTTOU
866 pthread_sigmask (SIG_SETMASK, oldset, 0);
867 #endif
870 /* Safely set a controlling terminal FD's process group to PGID.
871 If we are not in the foreground already, POSIX requires tcsetpgrp
872 to deliver a SIGTTOU signal, which would stop us. This is an
873 annoyance, so temporarily ignore the signal.
875 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
876 skip all this unless SIGTTOU is defined. */
877 static void
878 tcsetpgrp_without_stopping (int fd, pid_t pgid)
880 #ifdef SIGTTOU
881 sigset_t oldset;
882 block_input ();
883 block_tty_out_signal (&oldset);
884 tcsetpgrp (fd, pgid);
885 unblock_tty_out_signal (&oldset);
886 unblock_input ();
887 #endif
890 /* Split off the foreground process group to Emacs alone. When we are
891 in the foreground, but not started in our own process group,
892 redirect the tty device handle FD to point to our own process
893 group. FD must be the file descriptor of the controlling tty. */
894 static void
895 narrow_foreground_group (int fd)
897 if (inherited_pgroup && setpgid (0, 0) == 0)
898 tcsetpgrp_without_stopping (fd, getpid ());
901 /* Set the tty to our original foreground group. */
902 static void
903 widen_foreground_group (int fd)
905 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
906 tcsetpgrp_without_stopping (fd, inherited_pgroup);
909 /* Getting and setting emacs_tty structures. */
911 /* Set *TC to the parameters associated with the terminal FD,
912 or clear it if the parameters are not available.
913 Return 0 on success, -1 on failure. */
915 emacs_get_tty (int fd, struct emacs_tty *settings)
917 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
918 memset (&settings->main, 0, sizeof (settings->main));
919 #ifdef DOS_NT
920 #ifdef WINDOWSNT
921 HANDLE h = (HANDLE)_get_osfhandle (fd);
922 DWORD console_mode;
924 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
926 settings->main = console_mode;
927 return 0;
929 #endif /* WINDOWSNT */
930 return -1;
931 #else /* !DOS_NT */
932 /* We have those nifty POSIX tcmumbleattr functions. */
933 return tcgetattr (fd, &settings->main);
934 #endif
938 /* Set the parameters of the tty on FD according to the contents of
939 *SETTINGS. If FLUSHP, discard input.
940 Return 0 if all went well, and -1 (setting errno) if anything failed. */
943 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
945 /* Set the primary parameters - baud rate, character size, etcetera. */
946 #ifdef DOS_NT
947 #ifdef WINDOWSNT
948 HANDLE h = (HANDLE)_get_osfhandle (fd);
950 if (h && h != INVALID_HANDLE_VALUE)
952 DWORD new_mode;
954 /* Assume the handle is open for input. */
955 if (flushp)
956 FlushConsoleInputBuffer (h);
957 new_mode = settings->main;
958 SetConsoleMode (h, new_mode);
960 #endif /* WINDOWSNT */
961 #else /* !DOS_NT */
962 int i;
963 /* We have those nifty POSIX tcmumbleattr functions.
964 William J. Smith <wjs@wiis.wang.com> writes:
965 "POSIX 1003.1 defines tcsetattr to return success if it was
966 able to perform any of the requested actions, even if some
967 of the requested actions could not be performed.
968 We must read settings back to ensure tty setup properly.
969 AIX requires this to keep tty from hanging occasionally." */
970 /* This make sure that we don't loop indefinitely in here. */
971 for (i = 0 ; i < 10 ; i++)
972 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
974 if (errno == EINTR)
975 continue;
976 else
977 return -1;
979 else
981 struct termios new;
983 memset (&new, 0, sizeof (new));
984 /* Get the current settings, and see if they're what we asked for. */
985 tcgetattr (fd, &new);
986 /* We cannot use memcmp on the whole structure here because under
987 * aix386 the termios structure has some reserved field that may
988 * not be filled in.
990 if ( new.c_iflag == settings->main.c_iflag
991 && new.c_oflag == settings->main.c_oflag
992 && new.c_cflag == settings->main.c_cflag
993 && new.c_lflag == settings->main.c_lflag
994 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
995 break;
996 else
997 continue;
999 #endif
1001 /* We have survived the tempest. */
1002 return 0;
1007 #ifdef F_SETOWN
1008 static int old_fcntl_owner[FD_SETSIZE];
1009 #endif /* F_SETOWN */
1011 /* This may also be defined in stdio,
1012 but if so, this does no harm,
1013 and using the same name avoids wasting the other one's space. */
1015 #if defined (USG)
1016 unsigned char _sobuf[BUFSIZ+8];
1017 #else
1018 char _sobuf[BUFSIZ];
1019 #endif
1021 /* Initialize the terminal mode on all tty devices that are currently
1022 open. */
1024 void
1025 init_all_sys_modes (void)
1027 struct tty_display_info *tty;
1028 for (tty = tty_list; tty; tty = tty->next)
1029 init_sys_modes (tty);
1032 /* Initialize the terminal mode on the given tty device. */
1034 void
1035 init_sys_modes (struct tty_display_info *tty_out)
1037 struct emacs_tty tty;
1038 #ifndef DOS_NT
1039 Lisp_Object terminal;
1040 #endif
1042 Vtty_erase_char = Qnil;
1044 if (noninteractive)
1045 return;
1047 if (!tty_out->output)
1048 return; /* The tty is suspended. */
1050 narrow_foreground_group (fileno (tty_out->input));
1052 if (! tty_out->old_tty)
1053 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1055 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1057 tty = *tty_out->old_tty;
1059 #if !defined (DOS_NT)
1060 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1062 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1063 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1064 #ifdef INLCR /* I'm just being cautious,
1065 since I can't check how widespread INLCR is--rms. */
1066 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1067 #endif
1068 #ifdef ISTRIP
1069 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1070 #endif
1071 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1072 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1073 #ifdef IEXTEN
1074 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1075 #endif
1076 tty.main.c_lflag |= ISIG; /* Enable signals */
1077 if (tty_out->flow_control)
1079 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1080 #ifdef IXANY
1081 tty.main.c_iflag &= ~IXANY;
1082 #endif /* IXANY */
1084 else
1085 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1086 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1087 on output */
1088 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1089 #ifdef CS8
1090 if (tty_out->meta_key)
1092 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1093 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1095 #endif
1097 XSETTERMINAL(terminal, tty_out->terminal);
1098 if (!NILP (Fcontrolling_tty_p (terminal)))
1100 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1101 /* Set up C-g for both SIGQUIT and SIGINT.
1102 We don't know which we will get, but we handle both alike
1103 so which one it really gives us does not matter. */
1104 tty.main.c_cc[VQUIT] = quit_char;
1106 else
1108 /* We normally don't get interrupt or quit signals from tty
1109 devices other than our controlling terminal; therefore,
1110 we must handle C-g as normal input. Unfortunately, this
1111 means that the interrupt and quit feature must be
1112 disabled on secondary ttys, or we would not even see the
1113 keypress.
1115 Note that even though emacsclient could have special code
1116 to pass SIGINT to Emacs, we should _not_ enable
1117 interrupt/quit keys for emacsclient frames. This means
1118 that we can't break out of loops in C code from a
1119 secondary tty frame, but we can always decide what
1120 display the C-g came from, which is more important from a
1121 usability point of view. (Consider the case when two
1122 people work together using the same Emacs instance.) */
1123 tty.main.c_cc[VINTR] = CDISABLE;
1124 tty.main.c_cc[VQUIT] = CDISABLE;
1126 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1127 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1128 #ifdef VSWTCH
1129 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1130 of C-z */
1131 #endif /* VSWTCH */
1133 #ifdef VSUSP
1134 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1135 #endif /* VSUSP */
1136 #ifdef V_DSUSP
1137 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1138 #endif /* V_DSUSP */
1139 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1140 tty.main.c_cc[VDSUSP] = CDISABLE;
1141 #endif /* VDSUSP */
1142 #ifdef VLNEXT
1143 tty.main.c_cc[VLNEXT] = CDISABLE;
1144 #endif /* VLNEXT */
1145 #ifdef VREPRINT
1146 tty.main.c_cc[VREPRINT] = CDISABLE;
1147 #endif /* VREPRINT */
1148 #ifdef VWERASE
1149 tty.main.c_cc[VWERASE] = CDISABLE;
1150 #endif /* VWERASE */
1151 #ifdef VDISCARD
1152 tty.main.c_cc[VDISCARD] = CDISABLE;
1153 #endif /* VDISCARD */
1155 if (tty_out->flow_control)
1157 #ifdef VSTART
1158 tty.main.c_cc[VSTART] = '\021';
1159 #endif /* VSTART */
1160 #ifdef VSTOP
1161 tty.main.c_cc[VSTOP] = '\023';
1162 #endif /* VSTOP */
1164 else
1166 #ifdef VSTART
1167 tty.main.c_cc[VSTART] = CDISABLE;
1168 #endif /* VSTART */
1169 #ifdef VSTOP
1170 tty.main.c_cc[VSTOP] = CDISABLE;
1171 #endif /* VSTOP */
1174 #ifdef AIX
1175 tty.main.c_cc[VSTRT] = CDISABLE;
1176 tty.main.c_cc[VSTOP] = CDISABLE;
1177 tty.main.c_cc[VSUSP] = CDISABLE;
1178 tty.main.c_cc[VDSUSP] = CDISABLE;
1179 if (tty_out->flow_control)
1181 #ifdef VSTART
1182 tty.main.c_cc[VSTART] = '\021';
1183 #endif /* VSTART */
1184 #ifdef VSTOP
1185 tty.main.c_cc[VSTOP] = '\023';
1186 #endif /* VSTOP */
1188 /* Also, PTY overloads NUL and BREAK.
1189 don't ignore break, but don't signal either, so it looks like NUL.
1190 This really serves a purpose only if running in an XTERM window
1191 or via TELNET or the like, but does no harm elsewhere. */
1192 tty.main.c_iflag &= ~IGNBRK;
1193 tty.main.c_iflag &= ~BRKINT;
1194 #endif
1195 #endif /* not DOS_NT */
1197 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1198 if (!tty_out->term_initted)
1199 internal_terminal_init ();
1200 dos_ttraw (tty_out);
1201 #endif
1203 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1205 /* This code added to insure that, if flow-control is not to be used,
1206 we have an unlocked terminal at the start. */
1208 #ifdef TCXONC
1209 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1210 #endif
1211 #ifdef TIOCSTART
1212 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1213 #endif
1215 #if !defined (DOS_NT)
1216 #ifdef TCOON
1217 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1218 #endif
1219 #endif
1221 #ifdef F_GETOWN
1222 if (interrupt_input)
1224 old_fcntl_owner[fileno (tty_out->input)] =
1225 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1226 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1227 init_sigio (fileno (tty_out->input));
1228 #ifdef HAVE_GPM
1229 if (gpm_tty == tty_out)
1231 /* Arrange for mouse events to give us SIGIO signals. */
1232 fcntl (gpm_fd, F_SETOWN, getpid ());
1233 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1234 init_sigio (gpm_fd);
1236 #endif /* HAVE_GPM */
1238 #endif /* F_GETOWN */
1240 #ifdef _IOFBF
1241 /* This symbol is defined on recent USG systems.
1242 Someone says without this call USG won't really buffer the file
1243 even with a call to setbuf. */
1244 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1245 #else
1246 setbuf (tty_out->output, (char *) _sobuf);
1247 #endif
1249 if (tty_out->terminal->set_terminal_modes_hook)
1250 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1252 if (!tty_out->term_initted)
1254 Lisp_Object tail, frame;
1255 FOR_EACH_FRAME (tail, frame)
1257 /* XXX This needs to be revised. */
1258 if (FRAME_TERMCAP_P (XFRAME (frame))
1259 && FRAME_TTY (XFRAME (frame)) == tty_out)
1260 init_frame_faces (XFRAME (frame));
1264 if (tty_out->term_initted && no_redraw_on_reenter)
1266 /* We used to call "direct_output_forward_char(0)" here,
1267 but it's not clear why, since it may not do anything anyway. */
1269 else
1271 Lisp_Object tail, frame;
1272 frame_garbaged = 1;
1273 FOR_EACH_FRAME (tail, frame)
1275 if ((FRAME_TERMCAP_P (XFRAME (frame))
1276 || FRAME_MSDOS_P (XFRAME (frame)))
1277 && FRAME_TTY (XFRAME (frame)) == tty_out)
1278 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1282 tty_out->term_initted = 1;
1285 /* Return true if safe to use tabs in output.
1286 At the time this is called, init_sys_modes has not been done yet. */
1288 bool
1289 tabs_safe_p (int fd)
1291 struct emacs_tty etty;
1293 emacs_get_tty (fd, &etty);
1294 #ifndef DOS_NT
1295 #ifdef TABDLY
1296 return ((etty.main.c_oflag & TABDLY) != TAB3);
1297 #else /* not TABDLY */
1298 return 1;
1299 #endif /* not TABDLY */
1300 #else /* DOS_NT */
1301 return 0;
1302 #endif /* DOS_NT */
1305 /* Discard echoing. */
1307 void
1308 suppress_echo_on_tty (int fd)
1310 struct emacs_tty etty;
1312 emacs_get_tty (fd, &etty);
1313 #ifdef DOS_NT
1314 /* Set raw input mode. */
1315 etty.main = 0;
1316 #else
1317 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1318 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1319 #endif /* ! WINDOWSNT */
1320 emacs_set_tty (fd, &etty, 0);
1323 /* Get terminal size from system.
1324 Store number of lines into *HEIGHTP and width into *WIDTHP.
1325 We store 0 if there's no valid information. */
1327 void
1328 get_tty_size (int fd, int *widthp, int *heightp)
1330 #if defined TIOCGWINSZ
1332 /* BSD-style. */
1333 struct winsize size;
1335 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1336 *widthp = *heightp = 0;
1337 else
1339 *widthp = size.ws_col;
1340 *heightp = size.ws_row;
1343 #elif defined TIOCGSIZE
1345 /* SunOS - style. */
1346 struct ttysize size;
1348 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1349 *widthp = *heightp = 0;
1350 else
1352 *widthp = size.ts_cols;
1353 *heightp = size.ts_lines;
1356 #elif defined WINDOWSNT
1358 CONSOLE_SCREEN_BUFFER_INFO info;
1359 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1361 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1362 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1364 else
1365 *widthp = *heightp = 0;
1367 #elif defined MSDOS
1369 *widthp = ScreenCols ();
1370 *heightp = ScreenRows ();
1372 #else /* system doesn't know size */
1374 *widthp = 0;
1375 *heightp = 0;
1377 #endif
1380 /* Set the logical window size associated with descriptor FD
1381 to HEIGHT and WIDTH. This is used mainly with ptys.
1382 Return a negative value on failure. */
1385 set_window_size (int fd, int height, int width)
1387 #ifdef TIOCSWINSZ
1389 /* BSD-style. */
1390 struct winsize size;
1391 size.ws_row = height;
1392 size.ws_col = width;
1394 return ioctl (fd, TIOCSWINSZ, &size);
1396 #else
1397 #ifdef TIOCSSIZE
1399 /* SunOS - style. */
1400 struct ttysize size;
1401 size.ts_lines = height;
1402 size.ts_cols = width;
1404 return ioctl (fd, TIOCGSIZE, &size);
1405 #else
1406 return -1;
1407 #endif /* not SunOS-style */
1408 #endif /* not BSD-style */
1413 /* Prepare all terminal devices for exiting Emacs. */
1415 void
1416 reset_all_sys_modes (void)
1418 struct tty_display_info *tty;
1419 for (tty = tty_list; tty; tty = tty->next)
1420 reset_sys_modes (tty);
1423 /* Prepare the terminal for closing it; move the cursor to the
1424 bottom of the frame, turn off interrupt-driven I/O, etc. */
1426 void
1427 reset_sys_modes (struct tty_display_info *tty_out)
1429 if (noninteractive)
1431 fflush_unlocked (stdout);
1432 return;
1434 if (!tty_out->term_initted)
1435 return;
1437 if (!tty_out->output)
1438 return; /* The tty is suspended. */
1440 /* Go to and clear the last line of the terminal. */
1442 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1444 /* Code adapted from tty_clear_end_of_line. */
1445 if (tty_out->TS_clr_line)
1447 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1449 else
1450 { /* have to do it the hard way */
1451 tty_turn_off_insert (tty_out);
1453 for (int i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1454 fputc_unlocked (' ', tty_out->output);
1457 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1458 fflush_unlocked (tty_out->output);
1460 if (tty_out->terminal->reset_terminal_modes_hook)
1461 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1463 /* Avoid possible loss of output when changing terminal modes. */
1464 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1465 continue;
1467 #ifndef DOS_NT
1468 #ifdef F_SETOWN
1469 if (interrupt_input)
1471 reset_sigio (fileno (tty_out->input));
1472 fcntl (fileno (tty_out->input), F_SETOWN,
1473 old_fcntl_owner[fileno (tty_out->input)]);
1475 #endif /* F_SETOWN */
1476 fcntl (fileno (tty_out->input), F_SETFL,
1477 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1478 #endif
1480 if (tty_out->old_tty)
1481 while (emacs_set_tty (fileno (tty_out->input),
1482 tty_out->old_tty, 0) < 0 && errno == EINTR)
1485 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1486 dos_ttcooked ();
1487 #endif
1489 widen_foreground_group (fileno (tty_out->input));
1492 #ifdef HAVE_PTYS
1494 /* Set up the proper status flags for use of a pty. */
1496 void
1497 setup_pty (int fd)
1499 /* I'm told that TOICREMOTE does not mean control chars
1500 "can't be sent" but rather that they don't have
1501 input-editing or signaling effects.
1502 That should be good, because we have other ways
1503 to do those things in Emacs.
1504 However, telnet mode seems not to work on 4.2.
1505 So TIOCREMOTE is turned off now. */
1507 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1508 will hang. In particular, the "timeout" feature (which
1509 causes a read to return if there is no data available)
1510 does this. Also it is known that telnet mode will hang
1511 in such a way that Emacs must be stopped (perhaps this
1512 is the same problem).
1514 If TIOCREMOTE is turned off, then there is a bug in
1515 hp-ux which sometimes loses data. Apparently the
1516 code which blocks the master process when the internal
1517 buffer fills up does not work. Other than this,
1518 though, everything else seems to work fine.
1520 Since the latter lossage is more benign, we may as well
1521 lose that way. -- cph */
1522 #ifdef FIONBIO
1523 #if defined (UNIX98_PTYS)
1525 int on = 1;
1526 ioctl (fd, FIONBIO, &on);
1528 #endif
1529 #endif
1531 #endif /* HAVE_PTYS */
1533 void
1534 init_system_name (void)
1536 if (!build_details)
1538 /* Set system-name to nil so that the build is deterministic. */
1539 Vsystem_name = Qnil;
1540 return;
1542 char *hostname_alloc = NULL;
1543 char *hostname;
1544 #ifndef HAVE_GETHOSTNAME
1545 struct utsname uts;
1546 uname (&uts);
1547 hostname = uts.nodename;
1548 #else /* HAVE_GETHOSTNAME */
1549 char hostname_buf[256];
1550 ptrdiff_t hostname_size = sizeof hostname_buf;
1551 hostname = hostname_buf;
1553 /* Try to get the host name; if the buffer is too short, try
1554 again. Apparently, the only indication gethostname gives of
1555 whether the buffer was large enough is the presence or absence
1556 of a '\0' in the string. Eech. */
1557 for (;;)
1559 gethostname (hostname, hostname_size - 1);
1560 hostname[hostname_size - 1] = '\0';
1562 /* Was the buffer large enough for the '\0'? */
1563 if (strlen (hostname) < hostname_size - 1)
1564 break;
1566 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1567 min (PTRDIFF_MAX, SIZE_MAX), 1);
1569 #endif /* HAVE_GETHOSTNAME */
1570 char *p;
1571 for (p = hostname; *p; p++)
1572 if (*p == ' ' || *p == '\t')
1573 *p = '-';
1574 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1575 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1576 Vsystem_name = build_string (hostname);
1577 xfree (hostname_alloc);
1580 sigset_t empty_mask;
1582 static struct sigaction process_fatal_action;
1584 static int
1585 emacs_sigaction_flags (void)
1587 #ifdef SA_RESTART
1588 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1589 'select') to reset their timeout on some platforms (e.g.,
1590 HP-UX 11), which is not what we want. Also, when Emacs is
1591 interactive, we don't want SA_RESTART because we need to poll
1592 for pending input so we need long-running syscalls to be interrupted
1593 after a signal that sets pending_signals.
1595 Non-interactive keyboard input goes through stdio, where we
1596 always want restartable system calls. */
1597 if (noninteractive)
1598 return SA_RESTART;
1599 #endif
1600 return 0;
1603 /* Store into *ACTION a signal action suitable for Emacs, with handler
1604 HANDLER. */
1605 void
1606 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1608 sigemptyset (&action->sa_mask);
1610 /* When handling a signal, block nonfatal system signals that are caught
1611 by Emacs. This makes race conditions less likely. */
1612 sigaddset (&action->sa_mask, SIGALRM);
1613 #ifdef SIGCHLD
1614 sigaddset (&action->sa_mask, SIGCHLD);
1615 #endif
1616 #ifdef SIGDANGER
1617 sigaddset (&action->sa_mask, SIGDANGER);
1618 #endif
1619 #ifdef PROFILER_CPU_SUPPORT
1620 sigaddset (&action->sa_mask, SIGPROF);
1621 #endif
1622 #ifdef SIGWINCH
1623 sigaddset (&action->sa_mask, SIGWINCH);
1624 #endif
1625 if (! noninteractive)
1627 sigaddset (&action->sa_mask, SIGINT);
1628 sigaddset (&action->sa_mask, SIGQUIT);
1629 #ifdef USABLE_SIGIO
1630 sigaddset (&action->sa_mask, SIGIO);
1631 #endif
1634 action->sa_handler = handler;
1635 action->sa_flags = emacs_sigaction_flags ();
1638 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1639 pthread_t main_thread_id;
1640 #endif
1642 /* SIG has arrived at the current process. Deliver it to the main
1643 thread, which should handle it with HANDLER. (Delivering the
1644 signal to some other thread might not work if the other thread is
1645 about to exit.)
1647 If we are on the main thread, handle the signal SIG with HANDLER.
1648 Otherwise, redirect the signal to the main thread, blocking it from
1649 this thread. POSIX says any thread can receive a signal that is
1650 associated with a process, process group, or asynchronous event.
1651 On GNU/Linux the main thread typically gets a process signal unless
1652 it's blocked, but other systems (FreeBSD at least) can deliver the
1653 signal to other threads. */
1654 void
1655 deliver_process_signal (int sig, signal_handler_t handler)
1657 /* Preserve errno, to avoid race conditions with signal handlers that
1658 might change errno. Races can occur even in single-threaded hosts. */
1659 int old_errno = errno;
1661 bool on_main_thread = true;
1662 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1663 if (! pthread_equal (pthread_self (), main_thread_id))
1665 sigset_t blocked;
1666 sigemptyset (&blocked);
1667 sigaddset (&blocked, sig);
1668 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1669 pthread_kill (main_thread_id, sig);
1670 on_main_thread = false;
1672 #endif
1673 if (on_main_thread)
1674 handler (sig);
1676 errno = old_errno;
1679 /* Static location to save a fatal backtrace in a thread.
1680 FIXME: If two subsidiary threads fail simultaneously, the resulting
1681 backtrace may be garbage. */
1682 enum { BACKTRACE_LIMIT_MAX = 500 };
1683 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1684 static int thread_backtrace_npointers;
1686 /* SIG has arrived at the current thread.
1687 If we are on the main thread, handle the signal SIG with HANDLER.
1688 Otherwise, this is a fatal error in the handling thread. */
1689 static void
1690 deliver_thread_signal (int sig, signal_handler_t handler)
1692 int old_errno = errno;
1694 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1695 if (! pthread_equal (pthread_self (), main_thread_id))
1697 thread_backtrace_npointers
1698 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1699 sigaction (sig, &process_fatal_action, 0);
1700 pthread_kill (main_thread_id, sig);
1702 /* Avoid further damage while the main thread is exiting. */
1703 while (1)
1704 sigsuspend (&empty_mask);
1706 #endif
1708 handler (sig);
1709 errno = old_errno;
1712 #if !HAVE_DECL_SYS_SIGLIST
1713 # undef sys_siglist
1714 # ifdef _sys_siglist
1715 # define sys_siglist _sys_siglist
1716 # elif HAVE_DECL___SYS_SIGLIST
1717 # define sys_siglist __sys_siglist
1718 # else
1719 # define sys_siglist my_sys_siglist
1720 static char const *sys_siglist[NSIG];
1721 # endif
1722 #endif
1724 #ifdef _sys_nsig
1725 # define sys_siglist_entries _sys_nsig
1726 #else
1727 # define sys_siglist_entries NSIG
1728 #endif
1730 /* Handle bus errors, invalid instruction, etc. */
1731 static void
1732 handle_fatal_signal (int sig)
1734 terminate_due_to_signal (sig, 40);
1737 static void
1738 deliver_fatal_signal (int sig)
1740 deliver_process_signal (sig, handle_fatal_signal);
1743 static void
1744 deliver_fatal_thread_signal (int sig)
1746 deliver_thread_signal (sig, handle_fatal_signal);
1749 static _Noreturn void
1750 handle_arith_signal (int sig)
1752 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1753 xsignal0 (Qarith_error);
1756 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1758 /* Alternate stack used by SIGSEGV handler below. */
1760 static unsigned char sigsegv_stack[SIGSTKSZ];
1763 /* Return true if SIGINFO indicates a stack overflow. */
1765 static bool
1766 stack_overflow (siginfo_t *siginfo)
1768 if (!attempt_stack_overflow_recovery)
1769 return false;
1771 /* In theory, a more-accurate heuristic can be obtained by using
1772 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1773 and pthread_attr_getguardsize to find the location and size of the
1774 guard area. In practice, though, these functions are so hard to
1775 use reliably that they're not worth bothering with. E.g., see:
1776 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1777 Other operating systems also have problems, e.g., Solaris's
1778 stack_violation function is tailor-made for this problem, but it
1779 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1781 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1782 candidate here. */
1784 if (!siginfo)
1785 return false;
1787 /* The faulting address. */
1788 char *addr = siginfo->si_addr;
1789 if (!addr)
1790 return false;
1792 /* The known top and bottom of the stack. The actual stack may
1793 extend a bit beyond these boundaries. */
1794 char *bot = stack_bottom;
1795 char *top = current_thread->stack_top;
1797 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1798 of the known stack divided by the size of the guard area past the
1799 end of the stack top. The heuristic is that a bad address is
1800 considered to be a stack overflow if it occurs within
1801 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1802 stack. This heuristic is not exactly correct but it's good
1803 enough in practice. */
1804 enum { LG_STACK_HEURISTIC = 8 };
1806 if (bot < top)
1807 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1808 else
1809 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1813 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1815 static void
1816 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1818 /* Hard GC error may lead to stack overflow caused by
1819 too nested calls to mark_object. No way to survive. */
1820 bool fatal = gc_in_progress;
1822 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1823 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1824 fatal = true;
1825 #endif
1827 if (!fatal && stack_overflow (siginfo))
1828 siglongjmp (return_to_command_loop, 1);
1830 /* Otherwise we can't do anything with this. */
1831 deliver_fatal_thread_signal (sig);
1834 /* Return true if we have successfully set up SIGSEGV handler on alternate
1835 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1837 static bool
1838 init_sigsegv (void)
1840 struct sigaction sa;
1841 stack_t ss;
1843 ss.ss_sp = sigsegv_stack;
1844 ss.ss_size = sizeof (sigsegv_stack);
1845 ss.ss_flags = 0;
1846 if (sigaltstack (&ss, NULL) < 0)
1847 return 0;
1849 sigfillset (&sa.sa_mask);
1850 sa.sa_sigaction = handle_sigsegv;
1851 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1852 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1855 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1857 static bool
1858 init_sigsegv (void)
1860 return 0;
1863 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1865 static void
1866 deliver_arith_signal (int sig)
1868 deliver_thread_signal (sig, handle_arith_signal);
1871 #ifdef SIGDANGER
1873 /* Handler for SIGDANGER. */
1874 static void
1875 handle_danger_signal (int sig)
1877 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1879 /* It might be unsafe to call do_auto_save now. */
1880 force_auto_save_soon ();
1883 static void
1884 deliver_danger_signal (int sig)
1886 deliver_process_signal (sig, handle_danger_signal);
1888 #endif
1890 /* Treat SIG as a terminating signal, unless it is already ignored and
1891 we are in --batch mode. Among other things, this makes nohup work. */
1892 static void
1893 maybe_fatal_sig (int sig)
1895 bool catch_sig = !noninteractive;
1896 if (!catch_sig)
1898 struct sigaction old_action;
1899 sigaction (sig, 0, &old_action);
1900 catch_sig = old_action.sa_handler != SIG_IGN;
1902 if (catch_sig)
1903 sigaction (sig, &process_fatal_action, 0);
1906 void
1907 init_signals (bool dumping)
1909 struct sigaction thread_fatal_action;
1910 struct sigaction action;
1912 sigemptyset (&empty_mask);
1914 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1915 main_thread_id = pthread_self ();
1916 #endif
1918 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1919 if (! initialized)
1921 sys_siglist[SIGABRT] = "Aborted";
1922 # ifdef SIGAIO
1923 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1924 # endif
1925 sys_siglist[SIGALRM] = "Alarm clock";
1926 # ifdef SIGBUS
1927 sys_siglist[SIGBUS] = "Bus error";
1928 # endif
1929 # ifdef SIGCHLD
1930 sys_siglist[SIGCHLD] = "Child status changed";
1931 # endif
1932 # ifdef SIGCONT
1933 sys_siglist[SIGCONT] = "Continued";
1934 # endif
1935 # ifdef SIGDANGER
1936 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1937 # endif
1938 # ifdef SIGDGNOTIFY
1939 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1940 # endif
1941 # ifdef SIGEMT
1942 sys_siglist[SIGEMT] = "Emulation trap";
1943 # endif
1944 sys_siglist[SIGFPE] = "Arithmetic exception";
1945 # ifdef SIGFREEZE
1946 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1947 # endif
1948 # ifdef SIGGRANT
1949 sys_siglist[SIGGRANT] = "Monitor mode granted";
1950 # endif
1951 sys_siglist[SIGHUP] = "Hangup";
1952 sys_siglist[SIGILL] = "Illegal instruction";
1953 sys_siglist[SIGINT] = "Interrupt";
1954 # ifdef SIGIO
1955 sys_siglist[SIGIO] = "I/O possible";
1956 # endif
1957 # ifdef SIGIOINT
1958 sys_siglist[SIGIOINT] = "I/O intervention required";
1959 # endif
1960 # ifdef SIGIOT
1961 sys_siglist[SIGIOT] = "IOT trap";
1962 # endif
1963 sys_siglist[SIGKILL] = "Killed";
1964 # ifdef SIGLOST
1965 sys_siglist[SIGLOST] = "Resource lost";
1966 # endif
1967 # ifdef SIGLWP
1968 sys_siglist[SIGLWP] = "SIGLWP";
1969 # endif
1970 # ifdef SIGMSG
1971 sys_siglist[SIGMSG] = "Monitor mode data available";
1972 # endif
1973 # ifdef SIGPHONE
1974 sys_siglist[SIGWIND] = "SIGPHONE";
1975 # endif
1976 sys_siglist[SIGPIPE] = "Broken pipe";
1977 # ifdef SIGPOLL
1978 sys_siglist[SIGPOLL] = "Pollable event occurred";
1979 # endif
1980 # ifdef SIGPROF
1981 sys_siglist[SIGPROF] = "Profiling timer expired";
1982 # endif
1983 # ifdef SIGPTY
1984 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1985 # endif
1986 # ifdef SIGPWR
1987 sys_siglist[SIGPWR] = "Power-fail restart";
1988 # endif
1989 sys_siglist[SIGQUIT] = "Quit";
1990 # ifdef SIGRETRACT
1991 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1992 # endif
1993 # ifdef SIGSAK
1994 sys_siglist[SIGSAK] = "Secure attention";
1995 # endif
1996 sys_siglist[SIGSEGV] = "Segmentation violation";
1997 # ifdef SIGSOUND
1998 sys_siglist[SIGSOUND] = "Sound completed";
1999 # endif
2000 # ifdef SIGSTOP
2001 sys_siglist[SIGSTOP] = "Stopped (signal)";
2002 # endif
2003 # ifdef SIGSTP
2004 sys_siglist[SIGSTP] = "Stopped (user)";
2005 # endif
2006 # ifdef SIGSYS
2007 sys_siglist[SIGSYS] = "Bad argument to system call";
2008 # endif
2009 sys_siglist[SIGTERM] = "Terminated";
2010 # ifdef SIGTHAW
2011 sys_siglist[SIGTHAW] = "SIGTHAW";
2012 # endif
2013 # ifdef SIGTRAP
2014 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2015 # endif
2016 # ifdef SIGTSTP
2017 sys_siglist[SIGTSTP] = "Stopped (user)";
2018 # endif
2019 # ifdef SIGTTIN
2020 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2021 # endif
2022 # ifdef SIGTTOU
2023 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2024 # endif
2025 # ifdef SIGURG
2026 sys_siglist[SIGURG] = "Urgent I/O condition";
2027 # endif
2028 # ifdef SIGUSR1
2029 sys_siglist[SIGUSR1] = "User defined signal 1";
2030 # endif
2031 # ifdef SIGUSR2
2032 sys_siglist[SIGUSR2] = "User defined signal 2";
2033 # endif
2034 # ifdef SIGVTALRM
2035 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2036 # endif
2037 # ifdef SIGWAITING
2038 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2039 # endif
2040 # ifdef SIGWINCH
2041 sys_siglist[SIGWINCH] = "Window size changed";
2042 # endif
2043 # ifdef SIGWIND
2044 sys_siglist[SIGWIND] = "SIGWIND";
2045 # endif
2046 # ifdef SIGXCPU
2047 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2048 # endif
2049 # ifdef SIGXFSZ
2050 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2051 # endif
2053 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2055 /* Don't alter signal handlers if dumping. On some machines,
2056 changing signal handlers sets static data that would make signals
2057 fail to work right when the dumped Emacs is run. */
2058 if (dumping)
2059 return;
2061 sigfillset (&process_fatal_action.sa_mask);
2062 process_fatal_action.sa_handler = deliver_fatal_signal;
2063 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2065 sigfillset (&thread_fatal_action.sa_mask);
2066 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2067 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2069 /* SIGINT may need special treatment on MS-Windows. See
2070 https://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2071 Please update the doc of kill-emacs, kill-emacs-hook, and
2072 NEWS if you change this. */
2074 maybe_fatal_sig (SIGHUP);
2075 maybe_fatal_sig (SIGINT);
2076 maybe_fatal_sig (SIGTERM);
2078 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2079 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2080 to behave more like typical batch applications do. */
2081 if (! noninteractive)
2082 signal (SIGPIPE, SIG_IGN);
2084 sigaction (SIGQUIT, &process_fatal_action, 0);
2085 sigaction (SIGILL, &thread_fatal_action, 0);
2086 sigaction (SIGTRAP, &thread_fatal_action, 0);
2088 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2089 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2090 interpreter's floating point operations, so treat SIGFPE as an
2091 arith-error if it arises in the main thread. */
2092 if (IEEE_FLOATING_POINT)
2093 sigaction (SIGFPE, &thread_fatal_action, 0);
2094 else
2096 emacs_sigaction_init (&action, deliver_arith_signal);
2097 sigaction (SIGFPE, &action, 0);
2100 #ifdef SIGUSR1
2101 add_user_signal (SIGUSR1, "sigusr1");
2102 #endif
2103 #ifdef SIGUSR2
2104 add_user_signal (SIGUSR2, "sigusr2");
2105 #endif
2106 sigaction (SIGABRT, &thread_fatal_action, 0);
2107 #ifdef SIGPRE
2108 sigaction (SIGPRE, &thread_fatal_action, 0);
2109 #endif
2110 #ifdef SIGORE
2111 sigaction (SIGORE, &thread_fatal_action, 0);
2112 #endif
2113 #ifdef SIGUME
2114 sigaction (SIGUME, &thread_fatal_action, 0);
2115 #endif
2116 #ifdef SIGDLK
2117 sigaction (SIGDLK, &process_fatal_action, 0);
2118 #endif
2119 #ifdef SIGCPULIM
2120 sigaction (SIGCPULIM, &process_fatal_action, 0);
2121 #endif
2122 #ifdef SIGIOT
2123 sigaction (SIGIOT, &thread_fatal_action, 0);
2124 #endif
2125 #ifdef SIGEMT
2126 sigaction (SIGEMT, &thread_fatal_action, 0);
2127 #endif
2128 #ifdef SIGBUS
2129 sigaction (SIGBUS, &thread_fatal_action, 0);
2130 #endif
2131 if (!init_sigsegv ())
2132 sigaction (SIGSEGV, &thread_fatal_action, 0);
2133 #ifdef SIGSYS
2134 sigaction (SIGSYS, &thread_fatal_action, 0);
2135 #endif
2136 sigaction (SIGTERM, &process_fatal_action, 0);
2137 #ifdef SIGPROF
2138 signal (SIGPROF, SIG_IGN);
2139 #endif
2140 #ifdef SIGVTALRM
2141 sigaction (SIGVTALRM, &process_fatal_action, 0);
2142 #endif
2143 #ifdef SIGXCPU
2144 sigaction (SIGXCPU, &process_fatal_action, 0);
2145 #endif
2146 #ifdef SIGXFSZ
2147 sigaction (SIGXFSZ, &process_fatal_action, 0);
2148 #endif
2150 #ifdef SIGDANGER
2151 /* This just means available memory is getting low. */
2152 emacs_sigaction_init (&action, deliver_danger_signal);
2153 sigaction (SIGDANGER, &action, 0);
2154 #endif
2156 /* AIX-specific signals. */
2157 #ifdef SIGGRANT
2158 sigaction (SIGGRANT, &process_fatal_action, 0);
2159 #endif
2160 #ifdef SIGMIGRATE
2161 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2162 #endif
2163 #ifdef SIGMSG
2164 sigaction (SIGMSG, &process_fatal_action, 0);
2165 #endif
2166 #ifdef SIGRETRACT
2167 sigaction (SIGRETRACT, &process_fatal_action, 0);
2168 #endif
2169 #ifdef SIGSAK
2170 sigaction (SIGSAK, &process_fatal_action, 0);
2171 #endif
2172 #ifdef SIGSOUND
2173 sigaction (SIGSOUND, &process_fatal_action, 0);
2174 #endif
2175 #ifdef SIGTALRM
2176 sigaction (SIGTALRM, &thread_fatal_action, 0);
2177 #endif
2180 #ifndef HAVE_RANDOM
2181 #ifdef random
2182 #define HAVE_RANDOM
2183 #endif
2184 #endif
2186 /* Figure out how many bits the system's random number generator uses.
2187 `random' and `lrand48' are assumed to return 31 usable bits.
2188 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2189 so we'll shift it and treat it like the 15-bit USG `rand'. */
2191 #ifndef RAND_BITS
2192 # ifdef HAVE_RANDOM
2193 # define RAND_BITS 31
2194 # else /* !HAVE_RANDOM */
2195 # ifdef HAVE_LRAND48
2196 # define RAND_BITS 31
2197 # define random lrand48
2198 # else /* !HAVE_LRAND48 */
2199 # define RAND_BITS 15
2200 # if RAND_MAX == 32767
2201 # define random rand
2202 # else /* RAND_MAX != 32767 */
2203 # if RAND_MAX == 2147483647
2204 # define random() (rand () >> 16)
2205 # else /* RAND_MAX != 2147483647 */
2206 # ifdef USG
2207 # define random rand
2208 # else
2209 # define random() (rand () >> 16)
2210 # endif /* !USG */
2211 # endif /* RAND_MAX != 2147483647 */
2212 # endif /* RAND_MAX != 32767 */
2213 # endif /* !HAVE_LRAND48 */
2214 # endif /* !HAVE_RANDOM */
2215 #endif /* !RAND_BITS */
2217 #ifdef HAVE_RANDOM
2218 typedef unsigned int random_seed;
2219 static void set_random_seed (random_seed arg) { srandom (arg); }
2220 #elif defined HAVE_LRAND48
2221 /* Although srand48 uses a long seed, this is unsigned long to avoid
2222 undefined behavior on signed integer overflow in init_random. */
2223 typedef unsigned long int random_seed;
2224 static void set_random_seed (random_seed arg) { srand48 (arg); }
2225 #else
2226 typedef unsigned int random_seed;
2227 static void set_random_seed (random_seed arg) { srand (arg); }
2228 #endif
2230 void
2231 seed_random (void *seed, ptrdiff_t seed_size)
2233 random_seed arg = 0;
2234 unsigned char *argp = (unsigned char *) &arg;
2235 unsigned char *seedp = seed;
2236 for (ptrdiff_t i = 0; i < seed_size; i++)
2237 argp[i % sizeof arg] ^= seedp[i];
2238 set_random_seed (arg);
2241 void
2242 init_random (void)
2244 random_seed v;
2245 bool success = false;
2247 /* First, try seeding the PRNG from the operating system's entropy
2248 source. This approach is both fast and secure. */
2249 #ifdef WINDOWSNT
2250 success = w32_init_random (&v, sizeof v) == 0;
2251 #else
2252 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2253 if (0 <= fd)
2255 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2256 close (fd);
2258 #endif
2260 /* If that didn't work, try using GnuTLS, which is secure, but on
2261 some systems, can be somewhat slow. */
2262 if (!success)
2263 success = EQ (emacs_gnutls_global_init (), Qt)
2264 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2266 /* If _that_ didn't work, just use the current time value and PID.
2267 It's at least better than XKCD 221. */
2268 if (!success)
2270 struct timespec t = current_timespec ();
2271 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2274 set_random_seed (v);
2278 * Return a nonnegative random integer out of whatever we've got.
2279 * It contains enough bits to make a random (signed) Emacs fixnum.
2280 * This suffices even for a 64-bit architecture with a 15-bit rand.
2282 EMACS_INT
2283 get_random (void)
2285 EMACS_UINT val = 0;
2286 int i;
2287 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2288 val = (random () ^ (val << RAND_BITS)
2289 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2290 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2291 return val & INTMASK;
2294 #ifndef HAVE_SNPRINTF
2295 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2297 snprintf (char *buf, size_t bufsize, char const *format, ...)
2299 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2300 ptrdiff_t nbytes = size - 1;
2301 va_list ap;
2303 if (size)
2305 va_start (ap, format);
2306 nbytes = doprnt (buf, size, format, 0, ap);
2307 va_end (ap);
2310 if (nbytes == size - 1)
2312 /* Calculate the length of the string that would have been created
2313 had the buffer been large enough. */
2314 char stackbuf[4000];
2315 char *b = stackbuf;
2316 ptrdiff_t bsize = sizeof stackbuf;
2317 va_start (ap, format);
2318 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2319 va_end (ap);
2320 if (b != stackbuf)
2321 xfree (b);
2324 if (INT_MAX < nbytes)
2326 #ifdef EOVERFLOW
2327 errno = EOVERFLOW;
2328 #else
2329 errno = EDOM;
2330 #endif
2331 return -1;
2333 return nbytes;
2335 #endif
2337 /* If a backtrace is available, output the top lines of it to stderr.
2338 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2339 This function may be called from a signal handler, so it should
2340 not invoke async-unsafe functions like malloc.
2342 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2343 but do not output anything. This avoids some problems that can
2344 otherwise occur if the malloc arena is corrupted before 'backtrace'
2345 is called, since 'backtrace' may call malloc if the tables are not
2346 initialized.
2348 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2349 fatal error has occurred in some other thread; generate a thread
2350 backtrace instead, ignoring BACKTRACE_LIMIT. */
2351 void
2352 emacs_backtrace (int backtrace_limit)
2354 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2355 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2356 void *buffer;
2357 int npointers;
2359 if (thread_backtrace_npointers)
2361 buffer = thread_backtrace_buffer;
2362 npointers = thread_backtrace_npointers;
2364 else
2366 buffer = main_backtrace_buffer;
2368 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2369 if (bounded_limit < 0)
2371 backtrace (buffer, 1);
2372 return;
2375 npointers = backtrace (buffer, bounded_limit + 1);
2378 if (npointers)
2380 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2381 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2382 if (bounded_limit < npointers)
2383 emacs_write (STDERR_FILENO, "...\n", 4);
2387 #ifndef HAVE_NTGUI
2388 void
2389 emacs_abort (void)
2391 terminate_due_to_signal (SIGABRT, 40);
2393 #endif
2395 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2396 Use binary I/O on systems that care about text vs binary I/O.
2397 Arrange for subprograms to not inherit the file descriptor.
2398 Prefer a method that is multithread-safe, if available.
2399 Do not fail merely because the open was interrupted by a signal.
2400 Allow the user to quit. */
2403 emacs_open (const char *file, int oflags, int mode)
2405 int fd;
2406 if (! (oflags & O_TEXT))
2407 oflags |= O_BINARY;
2408 oflags |= O_CLOEXEC;
2409 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2410 maybe_quit ();
2411 return fd;
2414 /* Open FILE as a stream for Emacs use, with mode MODE.
2415 Act like emacs_open with respect to threads, signals, and quits. */
2417 FILE *
2418 emacs_fopen (char const *file, char const *mode)
2420 int fd, omode, oflags;
2421 int bflag = 0;
2422 char const *m = mode;
2424 switch (*m++)
2426 case 'r': omode = O_RDONLY; oflags = 0; break;
2427 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2428 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2429 default: emacs_abort ();
2432 while (*m)
2433 switch (*m++)
2435 case '+': omode = O_RDWR; break;
2436 case 't': bflag = O_TEXT; break;
2437 default: /* Ignore. */ break;
2440 fd = emacs_open (file, omode | oflags | bflag, 0666);
2441 return fd < 0 ? 0 : fdopen (fd, mode);
2444 /* Create a pipe for Emacs use. */
2447 emacs_pipe (int fd[2])
2449 #ifdef MSDOS
2450 return pipe (fd);
2451 #else /* !MSDOS */
2452 return pipe2 (fd, O_BINARY | O_CLOEXEC);
2453 #endif /* !MSDOS */
2456 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2457 For the background behind this mess, please see Austin Group defect 529
2458 <http://austingroupbugs.net/view.php?id=529>. */
2460 #ifndef POSIX_CLOSE_RESTART
2461 # define POSIX_CLOSE_RESTART 1
2462 static int
2463 posix_close (int fd, int flag)
2465 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2466 eassert (flag == POSIX_CLOSE_RESTART);
2468 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2469 on a system that does not define POSIX_CLOSE_RESTART.
2471 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2472 closed, and retrying the close could inadvertently close a file
2473 descriptor allocated by some other thread. In other systems
2474 (e.g., HP/UX) FD is not closed. And in still other systems
2475 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2476 multithreaded program there can be no way to tell.
2478 So, in this case, pretend that the close succeeded. This works
2479 well on systems like GNU/Linux that close FD. Although it may
2480 leak a file descriptor on other systems, the leak is unlikely and
2481 it's better to leak than to close a random victim. */
2482 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2484 #endif
2486 /* Close FD, retrying if interrupted. If successful, return 0;
2487 otherwise, return -1 and set errno to a non-EINTR value. Consider
2488 an EINPROGRESS error to be successful, as that's merely a signal
2489 arriving. FD is always closed when this function returns, even
2490 when it returns -1.
2492 Do not call this function if FD is nonnegative and might already be closed,
2493 as that might close an innocent victim opened by some other thread. */
2496 emacs_close (int fd)
2498 while (1)
2500 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2501 if (r == 0)
2502 return r;
2503 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2505 eassert (errno != EBADF || fd < 0);
2506 return errno == EINPROGRESS ? 0 : r;
2511 /* Maximum number of bytes to read or write in a single system call.
2512 This works around a serious bug in Linux kernels before 2.6.16; see
2513 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2514 It's likely to work around similar bugs in other operating systems, so do it
2515 on all platforms. Round INT_MAX down to a page size, with the conservative
2516 assumption that page sizes are at most 2**18 bytes (any kernel with a
2517 page size larger than that shouldn't have the bug). */
2518 #ifndef MAX_RW_COUNT
2519 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2520 #endif
2522 /* Read from FD to a buffer BUF with size NBYTE.
2523 If interrupted, process any quits and pending signals immediately
2524 if INTERRUPTIBLE, and then retry the read unless quitting.
2525 Return the number of bytes read, which might be less than NBYTE.
2526 On error, set errno to a value other than EINTR, and return -1. */
2527 static ptrdiff_t
2528 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2530 ssize_t result;
2532 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2533 passes a size that large to emacs_read. */
2536 if (interruptible)
2537 maybe_quit ();
2538 result = read (fd, buf, nbyte);
2540 while (result < 0 && errno == EINTR);
2542 return result;
2545 /* Read from FD to a buffer BUF with size NBYTE.
2546 If interrupted, retry the read. Return the number of bytes read,
2547 which might be less than NBYTE. On error, set errno to a value
2548 other than EINTR, and return -1. */
2549 ptrdiff_t
2550 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2552 return emacs_intr_read (fd, buf, nbyte, false);
2555 /* Like emacs_read, but also process quits and pending signals. */
2556 ptrdiff_t
2557 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2559 return emacs_intr_read (fd, buf, nbyte, true);
2562 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2563 interrupted or if a partial write occurs. Process any quits
2564 immediately if INTERRUPTIBLE is positive, and process any pending
2565 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2566 of bytes written; if this is less than NBYTE, set errno to a value
2567 other than EINTR. */
2568 static ptrdiff_t
2569 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2570 int interruptible)
2572 ptrdiff_t bytes_written = 0;
2574 while (nbyte > 0)
2576 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2578 if (n < 0)
2580 if (errno != EINTR)
2581 break;
2583 if (interruptible)
2585 if (0 < interruptible)
2586 maybe_quit ();
2587 if (pending_signals)
2588 process_pending_signals ();
2591 else
2593 buf += n;
2594 nbyte -= n;
2595 bytes_written += n;
2599 return bytes_written;
2602 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2603 interrupted or if a partial write occurs. Do not process quits or
2604 pending signals. Return the number of bytes written, setting errno
2605 if this is less than NBYTE. */
2606 ptrdiff_t
2607 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2609 return emacs_full_write (fd, buf, nbyte, 0);
2612 /* Like emacs_write, but also process pending signals. */
2613 ptrdiff_t
2614 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2616 return emacs_full_write (fd, buf, nbyte, -1);
2619 /* Like emacs_write, but also process quits and pending signals. */
2620 ptrdiff_t
2621 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2623 return emacs_full_write (fd, buf, nbyte, 1);
2626 /* Write a diagnostic to standard error that contains MESSAGE and a
2627 string derived from errno. Preserve errno. Do not buffer stderr.
2628 Do not process quits or pending signals if interrupted. */
2629 void
2630 emacs_perror (char const *message)
2632 int err = errno;
2633 char const *error_string = emacs_strerror (err);
2634 char const *command = (initial_argv && initial_argv[0]
2635 ? initial_argv[0] : "emacs");
2636 /* Write it out all at once, if it's short; this is less likely to
2637 be interleaved with other output. */
2638 char buf[BUFSIZ];
2639 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2640 command, message, error_string);
2641 if (0 <= nbytes && nbytes < BUFSIZ)
2642 emacs_write (STDERR_FILENO, buf, nbytes);
2643 else
2645 emacs_write (STDERR_FILENO, command, strlen (command));
2646 emacs_write (STDERR_FILENO, ": ", 2);
2647 emacs_write (STDERR_FILENO, message, strlen (message));
2648 emacs_write (STDERR_FILENO, ": ", 2);
2649 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2650 emacs_write (STDERR_FILENO, "\n", 1);
2652 errno = err;
2655 /* Return a struct timeval that is roughly equivalent to T.
2656 Use the least timeval not less than T.
2657 Return an extremal value if the result would overflow. */
2658 struct timeval
2659 make_timeval (struct timespec t)
2661 struct timeval tv;
2662 tv.tv_sec = t.tv_sec;
2663 tv.tv_usec = t.tv_nsec / 1000;
2665 if (t.tv_nsec % 1000 != 0)
2667 if (tv.tv_usec < 999999)
2668 tv.tv_usec++;
2669 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2671 tv.tv_sec++;
2672 tv.tv_usec = 0;
2676 return tv;
2679 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2680 ATIME and MTIME, respectively.
2681 FD must be either negative -- in which case it is ignored --
2682 or a file descriptor that is open on FILE.
2683 If FD is nonnegative, then FILE can be NULL. */
2685 set_file_times (int fd, const char *filename,
2686 struct timespec atime, struct timespec mtime)
2688 struct timespec timespec[2];
2689 timespec[0] = atime;
2690 timespec[1] = mtime;
2691 return fdutimens (fd, filename, timespec);
2694 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2695 This is like renameat except that it fails if DST already exists,
2696 or if this operation is not supported atomically. Return 0 if
2697 successful, -1 (setting errno) otherwise. */
2699 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2701 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2702 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2703 #elif defined CYGWIN && defined RENAME_NOREPLACE
2704 return renameat2 (srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2705 #elif defined RENAME_EXCL
2706 return renameatx_np (srcfd, src, dstfd, dst, RENAME_EXCL);
2707 #else
2708 # ifdef WINDOWSNT
2709 if (srcfd == AT_FDCWD && dstfd == AT_FDCWD)
2710 return sys_rename_replace (src, dst, 0);
2711 # endif
2712 errno = ENOSYS;
2713 return -1;
2714 #endif
2717 /* Like strsignal, except async-signal-safe, and this function typically
2718 returns a string in the C locale rather than the current locale. */
2719 char const *
2720 safe_strsignal (int code)
2722 char const *signame = 0;
2724 if (0 <= code && code < sys_siglist_entries)
2725 signame = sys_siglist[code];
2726 if (! signame)
2727 signame = "Unknown signal";
2729 return signame;
2732 #ifndef DOS_NT
2733 /* For make-serial-process */
2735 serial_open (Lisp_Object port)
2737 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2738 if (fd < 0)
2739 report_file_error ("Opening serial port", port);
2740 #ifdef TIOCEXCL
2741 ioctl (fd, TIOCEXCL, (char *) 0);
2742 #endif
2744 return fd;
2747 #if !defined (HAVE_CFMAKERAW)
2748 /* Workaround for targets which are missing cfmakeraw. */
2749 /* Pasted from man page. */
2750 static void
2751 cfmakeraw (struct termios *termios_p)
2753 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2754 termios_p->c_oflag &= ~OPOST;
2755 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2756 termios_p->c_cflag &= ~(CSIZE|PARENB);
2757 termios_p->c_cflag |= CS8;
2759 #endif /* !defined (HAVE_CFMAKERAW */
2761 #if !defined (HAVE_CFSETSPEED)
2762 /* Workaround for targets which are missing cfsetspeed. */
2763 static int
2764 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2766 return (cfsetispeed (termios_p, vitesse)
2767 + cfsetospeed (termios_p, vitesse));
2769 #endif
2771 /* For serial-process-configure */
2772 void
2773 serial_configure (struct Lisp_Process *p,
2774 Lisp_Object contact)
2776 Lisp_Object childp2 = Qnil;
2777 Lisp_Object tem = Qnil;
2778 struct termios attr;
2779 int err;
2780 char summary[4] = "???"; /* This usually becomes "8N1". */
2782 childp2 = Fcopy_sequence (p->childp);
2784 /* Read port attributes and prepare default configuration. */
2785 err = tcgetattr (p->outfd, &attr);
2786 if (err != 0)
2787 report_file_error ("Failed tcgetattr", Qnil);
2788 cfmakeraw (&attr);
2789 #if defined (CLOCAL)
2790 attr.c_cflag |= CLOCAL;
2791 #endif
2792 #if defined (CREAD)
2793 attr.c_cflag |= CREAD;
2794 #endif
2796 /* Configure speed. */
2797 if (!NILP (Fplist_member (contact, QCspeed)))
2798 tem = Fplist_get (contact, QCspeed);
2799 else
2800 tem = Fplist_get (p->childp, QCspeed);
2801 CHECK_NUMBER (tem);
2802 err = cfsetspeed (&attr, XINT (tem));
2803 if (err != 0)
2804 report_file_error ("Failed cfsetspeed", tem);
2805 childp2 = Fplist_put (childp2, QCspeed, tem);
2807 /* Configure bytesize. */
2808 if (!NILP (Fplist_member (contact, QCbytesize)))
2809 tem = Fplist_get (contact, QCbytesize);
2810 else
2811 tem = Fplist_get (p->childp, QCbytesize);
2812 if (NILP (tem))
2813 tem = make_number (8);
2814 CHECK_NUMBER (tem);
2815 if (XINT (tem) != 7 && XINT (tem) != 8)
2816 error (":bytesize must be nil (8), 7, or 8");
2817 summary[0] = XINT (tem) + '0';
2818 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2819 attr.c_cflag &= ~CSIZE;
2820 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2821 #else
2822 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2823 if (XINT (tem) != 8)
2824 error ("Bytesize cannot be changed");
2825 #endif
2826 childp2 = Fplist_put (childp2, QCbytesize, tem);
2828 /* Configure parity. */
2829 if (!NILP (Fplist_member (contact, QCparity)))
2830 tem = Fplist_get (contact, QCparity);
2831 else
2832 tem = Fplist_get (p->childp, QCparity);
2833 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2834 error (":parity must be nil (no parity), `even', or `odd'");
2835 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2836 attr.c_cflag &= ~(PARENB | PARODD);
2837 attr.c_iflag &= ~(IGNPAR | INPCK);
2838 if (NILP (tem))
2840 summary[1] = 'N';
2842 else if (EQ (tem, Qeven))
2844 summary[1] = 'E';
2845 attr.c_cflag |= PARENB;
2846 attr.c_iflag |= (IGNPAR | INPCK);
2848 else if (EQ (tem, Qodd))
2850 summary[1] = 'O';
2851 attr.c_cflag |= (PARENB | PARODD);
2852 attr.c_iflag |= (IGNPAR | INPCK);
2854 #else
2855 /* Don't error on no parity, which should be set by cfmakeraw. */
2856 if (!NILP (tem))
2857 error ("Parity cannot be configured");
2858 #endif
2859 childp2 = Fplist_put (childp2, QCparity, tem);
2861 /* Configure stopbits. */
2862 if (!NILP (Fplist_member (contact, QCstopbits)))
2863 tem = Fplist_get (contact, QCstopbits);
2864 else
2865 tem = Fplist_get (p->childp, QCstopbits);
2866 if (NILP (tem))
2867 tem = make_number (1);
2868 CHECK_NUMBER (tem);
2869 if (XINT (tem) != 1 && XINT (tem) != 2)
2870 error (":stopbits must be nil (1 stopbit), 1, or 2");
2871 summary[2] = XINT (tem) + '0';
2872 #if defined (CSTOPB)
2873 attr.c_cflag &= ~CSTOPB;
2874 if (XINT (tem) == 2)
2875 attr.c_cflag |= CSTOPB;
2876 #else
2877 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2878 if (XINT (tem) != 1)
2879 error ("Stopbits cannot be configured");
2880 #endif
2881 childp2 = Fplist_put (childp2, QCstopbits, tem);
2883 /* Configure flowcontrol. */
2884 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2885 tem = Fplist_get (contact, QCflowcontrol);
2886 else
2887 tem = Fplist_get (p->childp, QCflowcontrol);
2888 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2889 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2890 #if defined (CRTSCTS)
2891 attr.c_cflag &= ~CRTSCTS;
2892 #endif
2893 #if defined (CNEW_RTSCTS)
2894 attr.c_cflag &= ~CNEW_RTSCTS;
2895 #endif
2896 #if defined (IXON) && defined (IXOFF)
2897 attr.c_iflag &= ~(IXON | IXOFF);
2898 #endif
2899 if (NILP (tem))
2901 /* Already configured. */
2903 else if (EQ (tem, Qhw))
2905 #if defined (CRTSCTS)
2906 attr.c_cflag |= CRTSCTS;
2907 #elif defined (CNEW_RTSCTS)
2908 attr.c_cflag |= CNEW_RTSCTS;
2909 #else
2910 error ("Hardware flowcontrol (RTS/CTS) not supported");
2911 #endif
2913 else if (EQ (tem, Qsw))
2915 #if defined (IXON) && defined (IXOFF)
2916 attr.c_iflag |= (IXON | IXOFF);
2917 #else
2918 error ("Software flowcontrol (XON/XOFF) not supported");
2919 #endif
2921 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2923 /* Activate configuration. */
2924 err = tcsetattr (p->outfd, TCSANOW, &attr);
2925 if (err != 0)
2926 report_file_error ("Failed tcsetattr", Qnil);
2928 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2929 pset_childp (p, childp2);
2931 #endif /* not DOS_NT */
2933 /* System depended enumeration of and access to system processes a-la ps(1). */
2935 #ifdef HAVE_PROCFS
2937 /* Process enumeration and access via /proc. */
2939 Lisp_Object
2940 list_system_processes (void)
2942 Lisp_Object procdir, match, proclist, next;
2943 Lisp_Object tail;
2945 /* For every process on the system, there's a directory in the
2946 "/proc" pseudo-directory whose name is the numeric ID of that
2947 process. */
2948 procdir = build_string ("/proc");
2949 match = build_string ("[0-9]+");
2950 proclist = directory_files_internal (procdir, Qnil, match, Qt, false, Qnil);
2952 /* `proclist' gives process IDs as strings. Destructively convert
2953 each string into a number. */
2954 for (tail = proclist; CONSP (tail); tail = next)
2956 next = XCDR (tail);
2957 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2960 /* directory_files_internal returns the files in reverse order; undo
2961 that. */
2962 proclist = Fnreverse (proclist);
2963 return proclist;
2966 #elif defined DARWIN_OS || defined __FreeBSD__
2968 Lisp_Object
2969 list_system_processes (void)
2971 #ifdef DARWIN_OS
2972 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2973 #else
2974 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2975 #endif
2976 size_t len;
2977 struct kinfo_proc *procs;
2978 size_t i;
2980 Lisp_Object proclist = Qnil;
2982 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2983 return proclist;
2985 procs = xmalloc (len);
2986 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2988 xfree (procs);
2989 return proclist;
2992 len /= sizeof (struct kinfo_proc);
2993 for (i = 0; i < len; i++)
2995 #ifdef DARWIN_OS
2996 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2997 #else
2998 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2999 #endif
3002 xfree (procs);
3004 return proclist;
3007 /* The WINDOWSNT implementation is in w32.c.
3008 The MSDOS implementation is in dosfns.c. */
3009 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3011 Lisp_Object
3012 list_system_processes (void)
3014 return Qnil;
3017 #endif /* !defined (WINDOWSNT) */
3019 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3020 static struct timespec
3021 time_from_jiffies (unsigned long long tval, long hz)
3023 unsigned long long s = tval / hz;
3024 unsigned long long frac = tval % hz;
3025 int ns;
3027 if (TYPE_MAXIMUM (time_t) < s)
3028 time_overflow ();
3029 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
3030 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
3031 ns = frac * TIMESPEC_RESOLUTION / hz;
3032 else
3034 /* This is reachable only in the unlikely case that HZ * HZ
3035 exceeds ULLONG_MAX. It calculates an approximation that is
3036 guaranteed to be in range. */
3037 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3038 + (hz % TIMESPEC_RESOLUTION != 0));
3039 ns = frac / hz_per_ns;
3042 return make_timespec (s, ns);
3045 static Lisp_Object
3046 ltime_from_jiffies (unsigned long long tval, long hz)
3048 struct timespec t = time_from_jiffies (tval, hz);
3049 return make_lisp_time (t);
3052 static struct timespec
3053 get_up_time (void)
3055 FILE *fup;
3056 struct timespec up = make_timespec (0, 0);
3058 block_input ();
3059 fup = emacs_fopen ("/proc/uptime", "r");
3061 if (fup)
3063 unsigned long long upsec, upfrac, idlesec, idlefrac;
3064 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3066 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3067 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3068 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3069 == 4)
3071 if (TYPE_MAXIMUM (time_t) < upsec)
3073 upsec = TYPE_MAXIMUM (time_t);
3074 upfrac = TIMESPEC_RESOLUTION - 1;
3076 else
3078 int upfraclen = upfrac_end - upfrac_start;
3079 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3080 upfrac *= 10;
3081 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3082 upfrac /= 10;
3083 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3085 up = make_timespec (upsec, upfrac);
3087 fclose (fup);
3089 unblock_input ();
3091 return up;
3094 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3095 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3097 static Lisp_Object
3098 procfs_ttyname (int rdev)
3100 FILE *fdev;
3101 char name[PATH_MAX];
3103 block_input ();
3104 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3105 name[0] = 0;
3107 if (fdev)
3109 unsigned major;
3110 unsigned long minor_beg, minor_end;
3111 char minor[25]; /* 2 32-bit numbers + dash */
3112 char *endp;
3114 for (; !feof_unlocked (fdev) && !ferror_unlocked (fdev); name[0] = 0)
3116 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3117 && major == MAJOR (rdev))
3119 minor_beg = strtoul (minor, &endp, 0);
3120 if (*endp == '\0')
3121 minor_end = minor_beg;
3122 else if (*endp == '-')
3123 minor_end = strtoul (endp + 1, &endp, 0);
3124 else
3125 continue;
3127 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3129 sprintf (name + strlen (name), "%u", MINOR (rdev));
3130 break;
3134 fclose (fdev);
3136 unblock_input ();
3137 return build_string (name);
3140 static uintmax_t
3141 procfs_get_total_memory (void)
3143 FILE *fmem;
3144 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3145 int c;
3147 block_input ();
3148 fmem = emacs_fopen ("/proc/meminfo", "r");
3150 if (fmem)
3152 uintmax_t entry_value;
3153 bool done;
3156 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3158 case 1:
3159 retval = entry_value;
3160 done = 1;
3161 break;
3163 case 0:
3164 while ((c = getc_unlocked (fmem)) != EOF && c != '\n')
3165 continue;
3166 done = c == EOF;
3167 break;
3169 default:
3170 done = 1;
3171 break;
3173 while (!done);
3175 fclose (fmem);
3177 unblock_input ();
3178 return retval;
3181 Lisp_Object
3182 system_process_attributes (Lisp_Object pid)
3184 char procfn[PATH_MAX], fn[PATH_MAX];
3185 struct stat st;
3186 struct passwd *pw;
3187 struct group *gr;
3188 long clocks_per_sec;
3189 char *procfn_end;
3190 char procbuf[1025], *p, *q;
3191 int fd;
3192 ssize_t nread;
3193 static char const default_cmd[] = "???";
3194 const char *cmd = default_cmd;
3195 int cmdsize = sizeof default_cmd - 1;
3196 char *cmdline = NULL;
3197 ptrdiff_t cmdline_size;
3198 char c;
3199 printmax_t proc_id;
3200 int ppid, pgrp, sess, tty, tpgid, thcount;
3201 uid_t uid;
3202 gid_t gid;
3203 unsigned long long u_time, s_time, cutime, cstime, start;
3204 long priority, niceness, rss;
3205 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3206 struct timespec tnow, tstart, tboot, telapsed, us_time;
3207 double pcpu, pmem;
3208 Lisp_Object attrs = Qnil;
3209 Lisp_Object decoded_cmd;
3210 ptrdiff_t count;
3212 CHECK_NUMBER_OR_FLOAT (pid);
3213 CONS_TO_INTEGER (pid, pid_t, proc_id);
3214 sprintf (procfn, "/proc/%"pMd, proc_id);
3215 if (stat (procfn, &st) < 0)
3216 return attrs;
3218 /* euid egid */
3219 uid = st.st_uid;
3220 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3221 block_input ();
3222 pw = getpwuid (uid);
3223 unblock_input ();
3224 if (pw)
3225 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3227 gid = st.st_gid;
3228 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3229 block_input ();
3230 gr = getgrgid (gid);
3231 unblock_input ();
3232 if (gr)
3233 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3235 count = SPECPDL_INDEX ();
3236 strcpy (fn, procfn);
3237 procfn_end = fn + strlen (fn);
3238 strcpy (procfn_end, "/stat");
3239 fd = emacs_open (fn, O_RDONLY, 0);
3240 if (fd < 0)
3241 nread = 0;
3242 else
3244 record_unwind_protect_int (close_file_unwind, fd);
3245 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3247 if (0 < nread)
3249 procbuf[nread] = '\0';
3250 p = procbuf;
3252 p = strchr (p, '(');
3253 if (p != NULL)
3255 q = strrchr (p + 1, ')');
3256 /* comm */
3257 if (q != NULL)
3259 cmd = p + 1;
3260 cmdsize = q - cmd;
3263 else
3264 q = NULL;
3265 /* Command name is encoded in locale-coding-system; decode it. */
3266 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3267 decoded_cmd = code_convert_string_norecord (cmd_str,
3268 Vlocale_coding_system, 0);
3269 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3271 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3272 utime stime cutime cstime priority nice thcount . start vsize rss */
3273 if (q
3274 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3275 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3276 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3277 &minflt, &cminflt, &majflt, &cmajflt,
3278 &u_time, &s_time, &cutime, &cstime,
3279 &priority, &niceness, &thcount, &start, &vsize, &rss)
3280 == 20))
3282 char state_str[2];
3283 state_str[0] = c;
3284 state_str[1] = '\0';
3285 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3286 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3287 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3288 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3289 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3290 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3291 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3292 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3293 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3294 attrs);
3295 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3296 attrs);
3297 clocks_per_sec = sysconf (_SC_CLK_TCK);
3298 if (clocks_per_sec < 0)
3299 clocks_per_sec = 100;
3300 attrs = Fcons (Fcons (Qutime,
3301 ltime_from_jiffies (u_time, clocks_per_sec)),
3302 attrs);
3303 attrs = Fcons (Fcons (Qstime,
3304 ltime_from_jiffies (s_time, clocks_per_sec)),
3305 attrs);
3306 attrs = Fcons (Fcons (Qtime,
3307 ltime_from_jiffies (s_time + u_time,
3308 clocks_per_sec)),
3309 attrs);
3310 attrs = Fcons (Fcons (Qcutime,
3311 ltime_from_jiffies (cutime, clocks_per_sec)),
3312 attrs);
3313 attrs = Fcons (Fcons (Qcstime,
3314 ltime_from_jiffies (cstime, clocks_per_sec)),
3315 attrs);
3316 attrs = Fcons (Fcons (Qctime,
3317 ltime_from_jiffies (cstime + cutime,
3318 clocks_per_sec)),
3319 attrs);
3320 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3321 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3322 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3323 attrs);
3324 tnow = current_timespec ();
3325 telapsed = get_up_time ();
3326 tboot = timespec_sub (tnow, telapsed);
3327 tstart = time_from_jiffies (start, clocks_per_sec);
3328 tstart = timespec_add (tboot, tstart);
3329 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3330 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3331 attrs);
3332 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3333 telapsed = timespec_sub (tnow, tstart);
3334 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3335 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3336 pcpu = timespectod (us_time) / timespectod (telapsed);
3337 if (pcpu > 1.0)
3338 pcpu = 1.0;
3339 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3340 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3341 if (pmem > 100)
3342 pmem = 100;
3343 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3346 unbind_to (count, Qnil);
3348 /* args */
3349 strcpy (procfn_end, "/cmdline");
3350 fd = emacs_open (fn, O_RDONLY, 0);
3351 if (fd >= 0)
3353 ptrdiff_t readsize, nread_incr;
3354 record_unwind_protect_int (close_file_unwind, fd);
3355 record_unwind_protect_nothing ();
3356 nread = cmdline_size = 0;
3360 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3361 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3363 /* Leave room even if every byte needs escaping below. */
3364 readsize = (cmdline_size >> 1) - nread;
3366 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3367 nread += max (0, nread_incr);
3369 while (nread_incr == readsize);
3371 if (nread)
3373 /* We don't want trailing null characters. */
3374 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3375 continue;
3377 /* Escape-quote whitespace and backslashes. */
3378 q = cmdline + cmdline_size;
3379 while (cmdline < p)
3381 char c = *--p;
3382 *--q = c ? c : ' ';
3383 if (c_isspace (c) || c == '\\')
3384 *--q = '\\';
3387 nread = cmdline + cmdline_size - q;
3390 if (!nread)
3392 nread = cmdsize + 2;
3393 cmdline_size = nread + 1;
3394 q = cmdline = xrealloc (cmdline, cmdline_size);
3395 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3396 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3398 /* Command line is encoded in locale-coding-system; decode it. */
3399 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3400 decoded_cmd = code_convert_string_norecord (cmd_str,
3401 Vlocale_coding_system, 0);
3402 unbind_to (count, Qnil);
3403 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3406 return attrs;
3409 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3411 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3412 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3413 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3414 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3415 #undef _FILE_OFFSET_BITS
3416 #else
3417 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3418 #endif
3420 #include <procfs.h>
3422 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3423 #define _FILE_OFFSET_BITS 64
3424 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3425 #endif
3426 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3428 Lisp_Object
3429 system_process_attributes (Lisp_Object pid)
3431 char procfn[PATH_MAX], fn[PATH_MAX];
3432 struct stat st;
3433 struct passwd *pw;
3434 struct group *gr;
3435 char *procfn_end;
3436 struct psinfo pinfo;
3437 int fd;
3438 ssize_t nread;
3439 printmax_t proc_id;
3440 uid_t uid;
3441 gid_t gid;
3442 Lisp_Object attrs = Qnil;
3443 Lisp_Object decoded_cmd;
3444 ptrdiff_t count;
3446 CHECK_NUMBER_OR_FLOAT (pid);
3447 CONS_TO_INTEGER (pid, pid_t, proc_id);
3448 sprintf (procfn, "/proc/%"pMd, proc_id);
3449 if (stat (procfn, &st) < 0)
3450 return attrs;
3452 /* euid egid */
3453 uid = st.st_uid;
3454 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3455 block_input ();
3456 pw = getpwuid (uid);
3457 unblock_input ();
3458 if (pw)
3459 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3461 gid = st.st_gid;
3462 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3463 block_input ();
3464 gr = getgrgid (gid);
3465 unblock_input ();
3466 if (gr)
3467 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3469 count = SPECPDL_INDEX ();
3470 strcpy (fn, procfn);
3471 procfn_end = fn + strlen (fn);
3472 strcpy (procfn_end, "/psinfo");
3473 fd = emacs_open (fn, O_RDONLY, 0);
3474 if (fd < 0)
3475 nread = 0;
3476 else
3478 record_unwind_protect_int (close_file_unwind, fd);
3479 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3482 if (nread == sizeof pinfo)
3484 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3485 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3486 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3489 char state_str[2];
3490 state_str[0] = pinfo.pr_lwp.pr_sname;
3491 state_str[1] = '\0';
3492 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3495 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3496 need to get a string from it. */
3498 /* FIXME: missing: Qtpgid */
3500 /* FIXME: missing:
3501 Qminflt
3502 Qmajflt
3503 Qcminflt
3504 Qcmajflt
3506 Qutime
3507 Qcutime
3508 Qstime
3509 Qcstime
3510 Are they available? */
3512 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3513 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3514 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3515 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3516 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3517 attrs);
3519 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3520 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3521 attrs);
3522 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3523 attrs);
3525 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3526 range 0 .. 2**15, representing 0.0 .. 1.0. */
3527 attrs = Fcons (Fcons (Qpcpu,
3528 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3529 attrs);
3530 attrs = Fcons (Fcons (Qpmem,
3531 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3532 attrs);
3534 AUTO_STRING (fname, pinfo.pr_fname);
3535 decoded_cmd = code_convert_string_norecord (fname,
3536 Vlocale_coding_system, 0);
3537 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3538 AUTO_STRING (psargs, pinfo.pr_psargs);
3539 decoded_cmd = code_convert_string_norecord (psargs,
3540 Vlocale_coding_system, 0);
3541 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3543 unbind_to (count, Qnil);
3544 return attrs;
3547 #elif defined __FreeBSD__
3549 static struct timespec
3550 timeval_to_timespec (struct timeval t)
3552 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3555 static Lisp_Object
3556 make_lisp_timeval (struct timeval t)
3558 return make_lisp_time (timeval_to_timespec (t));
3561 Lisp_Object
3562 system_process_attributes (Lisp_Object pid)
3564 int proc_id;
3565 int pagesize = getpagesize ();
3566 unsigned long npages;
3567 int fscale;
3568 struct passwd *pw;
3569 struct group *gr;
3570 char *ttyname;
3571 size_t len;
3572 char args[MAXPATHLEN];
3573 struct timespec t, now;
3575 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3576 struct kinfo_proc proc;
3577 size_t proclen = sizeof proc;
3579 Lisp_Object attrs = Qnil;
3580 Lisp_Object decoded_comm;
3582 CHECK_NUMBER_OR_FLOAT (pid);
3583 CONS_TO_INTEGER (pid, int, proc_id);
3584 mib[3] = proc_id;
3586 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3587 return attrs;
3589 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3591 block_input ();
3592 pw = getpwuid (proc.ki_uid);
3593 unblock_input ();
3594 if (pw)
3595 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3597 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3599 block_input ();
3600 gr = getgrgid (proc.ki_svgid);
3601 unblock_input ();
3602 if (gr)
3603 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3605 AUTO_STRING (comm, proc.ki_comm);
3606 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3608 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3610 char state[2] = {'\0', '\0'};
3611 switch (proc.ki_stat)
3613 case SRUN:
3614 state[0] = 'R';
3615 break;
3617 case SSLEEP:
3618 state[0] = 'S';
3619 break;
3621 case SLOCK:
3622 state[0] = 'D';
3623 break;
3625 case SZOMB:
3626 state[0] = 'Z';
3627 break;
3629 case SSTOP:
3630 state[0] = 'T';
3631 break;
3633 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3636 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3637 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3638 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3640 block_input ();
3641 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3642 unblock_input ();
3643 if (ttyname)
3644 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3646 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3647 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3648 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3649 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3650 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3652 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3653 attrs);
3654 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3655 attrs);
3656 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3657 timeval_to_timespec (proc.ki_rusage.ru_stime));
3658 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3660 attrs = Fcons (Fcons (Qcutime,
3661 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3662 attrs);
3663 attrs = Fcons (Fcons (Qcstime,
3664 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3665 attrs);
3666 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3667 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3668 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3670 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3671 attrs);
3672 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3673 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3674 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3675 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3676 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3677 attrs);
3679 now = current_timespec ();
3680 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3681 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3683 len = sizeof fscale;
3684 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3686 double pcpu;
3687 fixpt_t ccpu;
3688 len = sizeof ccpu;
3689 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3691 pcpu = (100.0 * proc.ki_pctcpu / fscale
3692 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3693 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3697 len = sizeof npages;
3698 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3700 double pmem = (proc.ki_flag & P_INMEM
3701 ? 100.0 * proc.ki_rssize / npages
3702 : 0);
3703 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3706 mib[2] = KERN_PROC_ARGS;
3707 len = MAXPATHLEN;
3708 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3710 int i;
3711 for (i = 0; i < len; i++)
3713 if (! args[i] && i < len - 1)
3714 args[i] = ' ';
3717 AUTO_STRING (comm, args);
3718 decoded_comm = code_convert_string_norecord (comm,
3719 Vlocale_coding_system, 0);
3721 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3724 return attrs;
3727 #elif defined DARWIN_OS
3729 static struct timespec
3730 timeval_to_timespec (struct timeval t)
3732 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3735 static Lisp_Object
3736 make_lisp_timeval (struct timeval t)
3738 return make_lisp_time (timeval_to_timespec (t));
3741 Lisp_Object
3742 system_process_attributes (Lisp_Object pid)
3744 int proc_id;
3745 struct passwd *pw;
3746 struct group *gr;
3747 char *ttyname;
3748 struct timeval starttime;
3749 struct timespec t, now;
3750 struct rusage *rusage;
3751 dev_t tdev;
3752 uid_t uid;
3753 gid_t gid;
3755 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3756 struct kinfo_proc proc;
3757 size_t proclen = sizeof proc;
3759 Lisp_Object attrs = Qnil;
3760 Lisp_Object decoded_comm;
3762 CHECK_NUMBER_OR_FLOAT (pid);
3763 CONS_TO_INTEGER (pid, int, proc_id);
3764 mib[3] = proc_id;
3766 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3767 return attrs;
3769 uid = proc.kp_eproc.e_ucred.cr_uid;
3770 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3772 block_input ();
3773 pw = getpwuid (uid);
3774 unblock_input ();
3775 if (pw)
3776 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3778 gid = proc.kp_eproc.e_pcred.p_svgid;
3779 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3781 block_input ();
3782 gr = getgrgid (gid);
3783 unblock_input ();
3784 if (gr)
3785 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3787 decoded_comm = (code_convert_string_norecord
3788 (build_unibyte_string (proc.kp_proc.p_comm),
3789 Vlocale_coding_system, 0));
3791 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3793 char state[2] = {'\0', '\0'};
3794 switch (proc.kp_proc.p_stat)
3796 case SRUN:
3797 state[0] = 'R';
3798 break;
3800 case SSLEEP:
3801 state[0] = 'S';
3802 break;
3804 case SZOMB:
3805 state[0] = 'Z';
3806 break;
3808 case SSTOP:
3809 state[0] = 'T';
3810 break;
3812 case SIDL:
3813 state[0] = 'I';
3814 break;
3816 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3819 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3820 attrs);
3821 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3822 attrs);
3824 tdev = proc.kp_eproc.e_tdev;
3825 block_input ();
3826 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3827 unblock_input ();
3828 if (ttyname)
3829 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3831 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3832 attrs);
3834 rusage = proc.kp_proc.p_ru;
3835 if (rusage)
3837 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3838 attrs);
3839 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3840 attrs);
3842 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3843 attrs);
3844 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3845 attrs);
3846 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3847 timeval_to_timespec (rusage->ru_stime));
3848 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3851 starttime = proc.kp_proc.p_starttime;
3852 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3853 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3855 now = current_timespec ();
3856 t = timespec_sub (now, timeval_to_timespec (starttime));
3857 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3859 return attrs;
3862 /* The WINDOWSNT implementation is in w32.c.
3863 The MSDOS implementation is in dosfns.c. */
3864 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3866 Lisp_Object
3867 system_process_attributes (Lisp_Object pid)
3869 return Qnil;
3872 #endif /* !defined (WINDOWSNT) */
3874 /* Wide character string collation. */
3876 #ifdef __STDC_ISO_10646__
3877 # include <wchar.h>
3878 # include <wctype.h>
3880 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3881 # include <locale.h>
3882 # endif
3883 # ifndef LC_COLLATE
3884 # define LC_COLLATE 0
3885 # endif
3886 # ifndef LC_COLLATE_MASK
3887 # define LC_COLLATE_MASK 0
3888 # endif
3889 # ifndef LC_CTYPE
3890 # define LC_CTYPE 0
3891 # endif
3892 # ifndef LC_CTYPE_MASK
3893 # define LC_CTYPE_MASK 0
3894 # endif
3896 # ifndef HAVE_NEWLOCALE
3897 # undef freelocale
3898 # undef locale_t
3899 # undef newlocale
3900 # undef wcscoll_l
3901 # undef towlower_l
3902 # define freelocale emacs_freelocale
3903 # define locale_t emacs_locale_t
3904 # define newlocale emacs_newlocale
3905 # define wcscoll_l emacs_wcscoll_l
3906 # define towlower_l emacs_towlower_l
3908 typedef char const *locale_t;
3910 static locale_t
3911 newlocale (int category_mask, char const *locale, locale_t loc)
3913 return locale;
3916 static void
3917 freelocale (locale_t loc)
3921 static char *
3922 emacs_setlocale (int category, char const *locale)
3924 # ifdef HAVE_SETLOCALE
3925 errno = 0;
3926 char *loc = setlocale (category, locale);
3927 if (loc || errno)
3928 return loc;
3929 errno = EINVAL;
3930 # else
3931 errno = ENOTSUP;
3932 # endif
3933 return 0;
3936 static int
3937 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3939 int result = 0;
3940 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3941 int err;
3943 if (! oldloc)
3944 err = errno;
3945 else
3947 USE_SAFE_ALLOCA;
3948 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3949 strcpy (oldcopy, oldloc);
3950 if (! emacs_setlocale (LC_COLLATE, loc))
3951 err = errno;
3952 else
3954 errno = 0;
3955 result = wcscoll (a, b);
3956 err = errno;
3957 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3958 err = errno;
3960 SAFE_FREE ();
3963 errno = err;
3964 return result;
3967 static wint_t
3968 towlower_l (wint_t wc, locale_t loc)
3970 wint_t result = wc;
3971 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3973 if (oldloc)
3975 USE_SAFE_ALLOCA;
3976 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3977 strcpy (oldcopy, oldloc);
3978 if (emacs_setlocale (LC_CTYPE, loc))
3980 result = towlower (wc);
3981 emacs_setlocale (LC_COLLATE, oldcopy);
3983 SAFE_FREE ();
3986 return result;
3988 # endif
3991 str_collate (Lisp_Object s1, Lisp_Object s2,
3992 Lisp_Object locale, Lisp_Object ignore_case)
3994 int res, err;
3995 ptrdiff_t len, i, i_byte;
3996 wchar_t *p1, *p2;
3998 USE_SAFE_ALLOCA;
4000 /* Convert byte stream to code points. */
4001 len = SCHARS (s1); i = i_byte = 0;
4002 SAFE_NALLOCA (p1, 1, len + 1);
4003 while (i < len)
4004 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
4005 *(p1+len) = 0;
4007 len = SCHARS (s2); i = i_byte = 0;
4008 SAFE_NALLOCA (p2, 1, len + 1);
4009 while (i < len)
4010 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
4011 *(p2+len) = 0;
4013 if (STRINGP (locale))
4015 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
4016 SSDATA (locale), 0);
4017 if (!loc)
4018 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4020 if (! NILP (ignore_case))
4021 for (int i = 1; i < 3; i++)
4023 wchar_t *p = (i == 1) ? p1 : p2;
4024 for (; *p; p++)
4025 *p = towlower_l (*p, loc);
4028 errno = 0;
4029 res = wcscoll_l (p1, p2, loc);
4030 err = errno;
4031 freelocale (loc);
4033 else
4035 if (! NILP (ignore_case))
4036 for (int i = 1; i < 3; i++)
4038 wchar_t *p = (i == 1) ? p1 : p2;
4039 for (; *p; p++)
4040 *p = towlower (*p);
4043 errno = 0;
4044 res = wcscoll (p1, p2);
4045 err = errno;
4047 # ifndef HAVE_NEWLOCALE
4048 if (err)
4049 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4050 # else
4051 if (err)
4052 error ("Invalid string for collation: %s", emacs_strerror (err));
4053 # endif
4055 SAFE_FREE ();
4056 return res;
4058 #endif /* __STDC_ISO_10646__ */
4060 #ifdef WINDOWSNT
4062 str_collate (Lisp_Object s1, Lisp_Object s2,
4063 Lisp_Object locale, Lisp_Object ignore_case)
4066 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4067 int res, err = errno;
4069 errno = 0;
4070 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4071 if (errno)
4072 error ("Invalid string for collation: %s", strerror (errno));
4074 errno = err;
4075 return res;
4077 #endif /* WINDOWSNT */