Merge branch 'master' into comment-cache
[emacs.git] / src / sysdep.c
blob91b2a5cb9435fcbc488b82441999c3fcfcff3c8c
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 <http://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 #if defined DARWIN_OS || defined __FreeBSD__
41 # include <sys/sysctl.h>
42 #endif
44 #ifdef __FreeBSD__
45 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
46 'struct frame', so rename it. */
47 # define frame freebsd_frame
48 # include <sys/user.h>
49 # undef frame
51 # include <math.h>
52 #endif
54 #ifdef HAVE_SOCKETS
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #endif /* HAVE_SOCKETS */
59 #ifdef WINDOWSNT
60 #define read sys_read
61 #define write sys_write
62 #ifndef STDERR_FILENO
63 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
64 #endif
65 #include "w32.h"
66 #endif /* WINDOWSNT */
68 #include <sys/types.h>
69 #include <sys/stat.h>
70 #include <errno.h>
72 /* Get SI_SRPC_DOMAIN, if it is available. */
73 #ifdef HAVE_SYS_SYSTEMINFO_H
74 #include <sys/systeminfo.h>
75 #endif
77 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
78 #include "msdos.h"
79 #endif
81 #include <sys/param.h>
82 #include <sys/file.h>
83 #include <fcntl.h>
85 #include "systty.h"
86 #include "syswait.h"
88 #ifdef HAVE_SYS_UTSNAME_H
89 #include <sys/utsname.h>
90 #include <memory.h>
91 #endif /* HAVE_SYS_UTSNAME_H */
93 #include "keyboard.h"
94 #include "frame.h"
95 #include "termhooks.h"
96 #include "termchar.h"
97 #include "termopts.h"
98 #include "process.h"
99 #include "cm.h"
101 #include "gnutls.h"
102 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
103 do that during startup just to call gnutls_rnd. */
104 #if defined HAVE_GNUTLS && !defined WINDOWSNT
105 # include <gnutls/crypto.h>
106 #else
107 # define emacs_gnutls_global_init() Qnil
108 # define gnutls_rnd(level, data, len) (-1)
109 #endif
111 #ifdef WINDOWSNT
112 #include <direct.h>
113 /* In process.h which conflicts with the local copy. */
114 #define _P_WAIT 0
115 int _cdecl _spawnlp (int, const char *, const char *, ...);
116 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
117 several prototypes of functions called below. */
118 #include <sys/socket.h>
119 #endif
121 #include "syssignal.h"
122 #include "systime.h"
124 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
125 #ifndef ULLONG_MAX
126 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
127 #endif
129 /* Declare here, including term.h is problematic on some systems. */
130 extern void tputs (const char *, int, int (*)(int));
132 static const int baud_convert[] =
134 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
135 1800, 2400, 4800, 9600, 19200, 38400
138 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
139 # include <sys/personality.h>
141 /* Disable address randomization in the current process. Return true
142 if addresses were randomized but this has been disabled, false
143 otherwise. */
144 bool
145 disable_address_randomization (void)
147 int pers = personality (0xffffffff);
148 if (pers < 0)
149 return false;
150 int desired_pers = pers | ADDR_NO_RANDOMIZE;
152 /* Call 'personality' twice, to detect buggy platforms like WSL
153 where 'personality' always returns 0. */
154 return (pers != desired_pers
155 && personality (desired_pers) == pers
156 && personality (0xffffffff) == desired_pers);
158 #endif
160 /* Execute the program in FILE, with argument vector ARGV and environ
161 ENVP. Return an error number if unsuccessful. This is like execve
162 except it reenables ASLR in the executed program if necessary, and
163 on error it returns an error number rather than -1. */
165 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
167 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
168 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
169 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
170 if (change_personality)
171 personality (pers & ~ADDR_NO_RANDOMIZE);
172 #endif
174 execve (file, argv, envp);
175 int err = errno;
177 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
178 if (change_personality)
179 personality (pers);
180 #endif
182 return err;
185 /* If FD is not already open, arrange for it to be open with FLAGS. */
186 static void
187 force_open (int fd, int flags)
189 if (dup2 (fd, fd) < 0 && errno == EBADF)
191 int n = open (NULL_DEVICE, flags);
192 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
194 emacs_perror (NULL_DEVICE);
195 exit (EXIT_FAILURE);
200 /* Make sure stdin, stdout, and stderr are open to something, so that
201 their file descriptors are not hijacked by later system calls. */
202 void
203 init_standard_fds (void)
205 /* Open stdin for *writing*, and stdout and stderr for *reading*.
206 That way, any attempt to do normal I/O will result in an error,
207 just as if the files were closed, and the file descriptors will
208 not be reused by later opens. */
209 force_open (STDIN_FILENO, O_WRONLY);
210 force_open (STDOUT_FILENO, O_RDONLY);
211 force_open (STDERR_FILENO, O_RDONLY);
214 /* Return the current working directory. The result should be freed
215 with 'free'. Return NULL on errors. */
216 char *
217 emacs_get_current_dir_name (void)
219 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
220 # ifdef HYBRID_MALLOC
221 bool use_libc = bss_sbrk_did_unexec;
222 # else
223 bool use_libc = true;
224 # endif
225 if (use_libc)
226 return get_current_dir_name ();
227 # endif
229 char *buf;
230 char *pwd = getenv ("PWD");
231 struct stat dotstat, pwdstat;
232 /* If PWD is accurate, use it instead of calling getcwd. PWD is
233 sometimes a nicer name, and using it may avoid a fatal error if a
234 parent directory is searchable but not readable. */
235 if (pwd
236 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
237 && stat (pwd, &pwdstat) == 0
238 && stat (".", &dotstat) == 0
239 && dotstat.st_ino == pwdstat.st_ino
240 && dotstat.st_dev == pwdstat.st_dev
241 #ifdef MAXPATHLEN
242 && strlen (pwd) < MAXPATHLEN
243 #endif
246 buf = malloc (strlen (pwd) + 1);
247 if (!buf)
248 return NULL;
249 strcpy (buf, pwd);
251 else
253 size_t buf_size = 1024;
254 buf = malloc (buf_size);
255 if (!buf)
256 return NULL;
257 for (;;)
259 if (getcwd (buf, buf_size) == buf)
260 break;
261 if (errno != ERANGE)
263 int tmp_errno = errno;
264 free (buf);
265 errno = tmp_errno;
266 return NULL;
268 buf_size *= 2;
269 buf = realloc (buf, buf_size);
270 if (!buf)
271 return NULL;
274 return buf;
278 /* Discard pending input on all input descriptors. */
280 void
281 discard_tty_input (void)
283 #ifndef WINDOWSNT
284 struct emacs_tty buf;
286 if (noninteractive)
287 return;
289 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
290 while (dos_keyread () != -1)
292 #else /* not MSDOS */
294 struct tty_display_info *tty;
295 for (tty = tty_list; tty; tty = tty->next)
297 if (tty->input) /* Is the device suspended? */
299 emacs_get_tty (fileno (tty->input), &buf);
300 emacs_set_tty (fileno (tty->input), &buf, 0);
304 #endif /* not MSDOS */
305 #endif /* not WINDOWSNT */
309 #ifdef SIGTSTP
311 /* Arrange for character C to be read as the next input from
312 the terminal.
313 XXX What if we have multiple ttys?
316 void
317 stuff_char (char c)
319 if (! (FRAMEP (selected_frame)
320 && FRAME_LIVE_P (XFRAME (selected_frame))
321 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
322 return;
324 /* Should perhaps error if in batch mode */
325 #ifdef TIOCSTI
326 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
327 #else /* no TIOCSTI */
328 error ("Cannot stuff terminal input characters in this version of Unix");
329 #endif /* no TIOCSTI */
332 #endif /* SIGTSTP */
334 void
335 init_baud_rate (int fd)
337 int emacs_ospeed;
339 if (noninteractive)
340 emacs_ospeed = 0;
341 else
343 #ifdef DOS_NT
344 emacs_ospeed = 15;
345 #else /* not DOS_NT */
346 struct termios sg;
348 sg.c_cflag = B9600;
349 tcgetattr (fd, &sg);
350 emacs_ospeed = cfgetospeed (&sg);
351 #endif /* not DOS_NT */
354 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
355 ? baud_convert[emacs_ospeed] : 9600);
356 if (baud_rate == 0)
357 baud_rate = 1200;
362 #ifndef MSDOS
364 /* Wait for the subprocess with process id CHILD to terminate or change status.
365 CHILD must be a child process that has not been reaped.
366 If STATUS is non-null, store the waitpid-style exit status into *STATUS
367 and tell wait_reading_process_output that it needs to look around.
368 Use waitpid-style OPTIONS when waiting.
369 If INTERRUPTIBLE, this function is interruptible by a signal.
371 Return CHILD if successful, 0 if no status is available;
372 the latter is possible only when options & NOHANG. */
373 static pid_t
374 get_child_status (pid_t child, int *status, int options, bool interruptible)
376 pid_t pid;
378 /* Invoke waitpid only with a known process ID; do not invoke
379 waitpid with a nonpositive argument. Otherwise, Emacs might
380 reap an unwanted process by mistake. For example, invoking
381 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
382 so that another thread running glib won't find them. */
383 eassert (child > 0);
385 while (true)
387 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
388 internally. */
389 if (interruptible)
390 maybe_quit ();
392 pid = waitpid (child, status, options);
393 if (0 <= pid)
394 break;
396 /* Check that CHILD is a child process that has not been reaped,
397 and that STATUS and OPTIONS are valid. Otherwise abort,
398 as continuing after this internal error could cause Emacs to
399 become confused and kill innocent-victim processes. */
400 if (errno != EINTR)
401 emacs_abort ();
404 /* If successful and status is requested, tell wait_reading_process_output
405 that it needs to wake up and look around. */
406 if (pid && status && input_available_clear_time)
407 *input_available_clear_time = make_timespec (0, 0);
409 return pid;
412 /* Wait for the subprocess with process id CHILD to terminate.
413 CHILD must be a child process that has not been reaped.
414 If STATUS is non-null, store the waitpid-style exit status into *STATUS
415 and tell wait_reading_process_output that it needs to look around.
416 If INTERRUPTIBLE, this function is interruptible by a signal. */
417 void
418 wait_for_termination (pid_t child, int *status, bool interruptible)
420 get_child_status (child, status, 0, interruptible);
423 /* Report whether the subprocess with process id CHILD has changed status.
424 Termination counts as a change of status.
425 CHILD must be a child process that has not been reaped.
426 If STATUS is non-null, store the waitpid-style exit status into *STATUS
427 and tell wait_reading_process_output that it needs to look around.
428 Use waitpid-style OPTIONS to check status, but do not wait.
430 Return CHILD if successful, 0 if no status is available because
431 the process's state has not changed. */
432 pid_t
433 child_status_changed (pid_t child, int *status, int options)
435 return get_child_status (child, status, WNOHANG | options, 0);
439 /* Set up the terminal at the other end of a pseudo-terminal that
440 we will be controlling an inferior through.
441 It should not echo or do line-editing, since that is done
442 in Emacs. No padding needed for insertion into an Emacs buffer. */
444 void
445 child_setup_tty (int out)
447 #ifndef WINDOWSNT
448 struct emacs_tty s;
450 emacs_get_tty (out, &s);
451 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
452 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
453 #ifdef NLDLY
454 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
455 Some versions of GNU Hurd do not have FFDLY? */
456 #ifdef FFDLY
457 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
458 /* No output delays */
459 #else
460 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
461 /* No output delays */
462 #endif
463 #endif
464 s.main.c_lflag &= ~ECHO; /* Disable echo */
465 s.main.c_lflag |= ISIG; /* Enable signals */
466 #ifdef IUCLC
467 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
468 #endif
469 #ifdef ISTRIP
470 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
471 #endif
472 #ifdef OLCUC
473 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
474 #endif
475 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
476 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
477 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
478 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
480 #ifdef HPUX
481 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
482 #endif /* HPUX */
484 #ifdef SIGNALS_VIA_CHARACTERS
485 /* the QUIT and INTR character are used in process_send_signal
486 so set them here to something useful. */
487 if (s.main.c_cc[VQUIT] == CDISABLE)
488 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
489 if (s.main.c_cc[VINTR] == CDISABLE)
490 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
491 #endif /* not SIGNALS_VIA_CHARACTERS */
493 #ifdef AIX
494 /* Also, PTY overloads NUL and BREAK.
495 don't ignore break, but don't signal either, so it looks like NUL. */
496 s.main.c_iflag &= ~IGNBRK;
497 s.main.c_iflag &= ~BRKINT;
498 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
499 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
500 would force it to 0377. That looks like duplicated code. */
501 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
502 #endif /* AIX */
504 /* We originally enabled ICANON (and set VEOF to 04), and then had
505 process.c send additional EOF chars to flush the output when faced
506 with long lines, but this leads to weird effects when the
507 subprocess has disabled ICANON and ends up seeing those spurious
508 extra EOFs. So we don't send EOFs any more in
509 process.c:send_process. First we tried to disable ICANON by
510 default, so if a subsprocess sets up ICANON, it's his problem (or
511 the Elisp package that talks to it) to deal with lines that are
512 too long. But this disables some features, such as the ability
513 to send EOF signals. So we re-enabled ICANON but there is no
514 more "send eof to flush" going on (which is wrong and unportable
515 in itself). The correct way to handle too much output is to
516 buffer what could not be written and then write it again when
517 select returns ok for writing. This has it own set of
518 problems. Write is now asynchronous, is that a problem? How much
519 do we buffer, and what do we do when that limit is reached? */
521 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
522 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
523 #if 0 /* These settings only apply to non-ICANON mode. */
524 s.main.c_cc[VMIN] = 1;
525 s.main.c_cc[VTIME] = 0;
526 #endif
528 emacs_set_tty (out, &s, 0);
529 #endif /* not WINDOWSNT */
531 #endif /* not MSDOS */
534 /* Record a signal code and the action for it. */
535 struct save_signal
537 int code;
538 struct sigaction action;
541 static void save_signal_handlers (struct save_signal *);
542 static void restore_signal_handlers (struct save_signal *);
544 /* Suspend the Emacs process; give terminal to its superior. */
546 void
547 sys_suspend (void)
549 #ifndef DOS_NT
550 kill (0, SIGTSTP);
551 #else
552 /* On a system where suspending is not implemented,
553 instead fork a subshell and let it talk directly to the terminal
554 while we wait. */
555 sys_subshell ();
557 #endif
560 /* Fork a subshell. */
562 void
563 sys_subshell (void)
565 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
566 #ifdef MSDOS
567 int st;
568 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
569 #else
570 char oldwd[MAX_UTF8_PATH];
571 #endif /* MSDOS */
572 #else /* !DOS_NT */
573 int status;
574 #endif
575 pid_t pid;
576 struct save_signal saved_handlers[5];
577 char *str = SSDATA (encode_current_directory ());
579 #ifdef DOS_NT
580 pid = 0;
581 #else
583 char *volatile str_volatile = str;
584 pid = vfork ();
585 str = str_volatile;
587 #endif
589 if (pid < 0)
590 error ("Can't spawn subshell");
592 saved_handlers[0].code = SIGINT;
593 saved_handlers[1].code = SIGQUIT;
594 saved_handlers[2].code = SIGTERM;
595 #ifdef USABLE_SIGIO
596 saved_handlers[3].code = SIGIO;
597 saved_handlers[4].code = 0;
598 #else
599 saved_handlers[3].code = 0;
600 #endif
602 #ifdef DOS_NT
603 save_signal_handlers (saved_handlers);
604 #endif
606 if (pid == 0)
608 const char *sh = 0;
610 #ifdef DOS_NT /* MW, Aug 1993 */
611 getcwd (oldwd, sizeof oldwd);
612 if (sh == 0)
613 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
614 #endif
615 if (sh == 0)
616 sh = egetenv ("SHELL");
617 if (sh == 0)
618 sh = "sh";
620 /* Use our buffer's default directory for the subshell. */
621 if (chdir (str) != 0)
623 #ifndef DOS_NT
624 emacs_perror (str);
625 _exit (EXIT_CANCELED);
626 #endif
629 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
631 char *epwd = getenv ("PWD");
632 char old_pwd[MAXPATHLEN+1+4];
634 /* If PWD is set, pass it with corrected value. */
635 if (epwd)
637 strcpy (old_pwd, epwd);
638 setenv ("PWD", str, 1);
640 st = system (sh);
641 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
642 if (epwd)
643 putenv (old_pwd); /* restore previous value */
645 #else /* not MSDOS */
646 #ifdef WINDOWSNT
647 /* Waits for process completion */
648 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
649 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
650 if (pid == -1)
651 write (1, "Can't execute subshell", 22);
652 #else /* not WINDOWSNT */
653 execlp (sh, sh, (char *) 0);
654 emacs_perror (sh);
655 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
656 #endif /* not WINDOWSNT */
657 #endif /* not MSDOS */
660 /* Do this now if we did not do it before. */
661 #ifndef MSDOS
662 save_signal_handlers (saved_handlers);
663 #endif
665 #ifndef DOS_NT
666 wait_for_termination (pid, &status, 0);
667 #endif
668 restore_signal_handlers (saved_handlers);
671 static void
672 save_signal_handlers (struct save_signal *saved_handlers)
674 while (saved_handlers->code)
676 struct sigaction action;
677 emacs_sigaction_init (&action, SIG_IGN);
678 sigaction (saved_handlers->code, &action, &saved_handlers->action);
679 saved_handlers++;
683 static void
684 restore_signal_handlers (struct save_signal *saved_handlers)
686 while (saved_handlers->code)
688 sigaction (saved_handlers->code, &saved_handlers->action, 0);
689 saved_handlers++;
693 #ifdef USABLE_SIGIO
694 static int old_fcntl_flags[FD_SETSIZE];
695 #endif
697 void
698 init_sigio (int fd)
700 #ifdef USABLE_SIGIO
701 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
702 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
703 interrupts_deferred = 0;
704 #endif
707 #ifndef DOS_NT
708 static void
709 reset_sigio (int fd)
711 #ifdef USABLE_SIGIO
712 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
713 #endif
715 #endif
717 void
718 request_sigio (void)
720 #ifdef USABLE_SIGIO
721 sigset_t unblocked;
723 if (noninteractive)
724 return;
726 sigemptyset (&unblocked);
727 # ifdef SIGWINCH
728 sigaddset (&unblocked, SIGWINCH);
729 # endif
730 sigaddset (&unblocked, SIGIO);
731 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
733 interrupts_deferred = 0;
734 #endif
737 void
738 unrequest_sigio (void)
740 #ifdef USABLE_SIGIO
741 sigset_t blocked;
743 if (noninteractive)
744 return;
746 sigemptyset (&blocked);
747 # ifdef SIGWINCH
748 sigaddset (&blocked, SIGWINCH);
749 # endif
750 sigaddset (&blocked, SIGIO);
751 pthread_sigmask (SIG_BLOCK, &blocked, 0);
752 interrupts_deferred = 1;
753 #endif
756 #ifndef MSDOS
757 /* Block SIGCHLD. */
759 void
760 block_child_signal (sigset_t *oldset)
762 sigset_t blocked;
763 sigemptyset (&blocked);
764 sigaddset (&blocked, SIGCHLD);
765 sigaddset (&blocked, SIGINT);
766 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
769 /* Unblock SIGCHLD. */
771 void
772 unblock_child_signal (sigset_t const *oldset)
774 pthread_sigmask (SIG_SETMASK, oldset, 0);
777 /* Block SIGINT. */
778 void
779 block_interrupt_signal (sigset_t *oldset)
781 sigset_t blocked;
782 sigemptyset (&blocked);
783 sigaddset (&blocked, SIGINT);
784 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
787 /* Restore previously saved signal mask. */
788 void
789 restore_signal_mask (sigset_t const *oldset)
791 pthread_sigmask (SIG_SETMASK, oldset, 0);
794 #endif /* !MSDOS */
796 /* Saving and restoring the process group of Emacs's terminal. */
798 /* The process group of which Emacs was a member when it initially
799 started.
801 If Emacs was in its own process group (i.e. inherited_pgroup ==
802 getpid ()), then we know we're running under a shell with job
803 control (Emacs would never be run as part of a pipeline).
804 Everything is fine.
806 If Emacs was not in its own process group, then we know we're
807 running under a shell (or a caller) that doesn't know how to
808 separate itself from Emacs (like sh). Emacs must be in its own
809 process group in order to receive SIGIO correctly. In this
810 situation, we put ourselves in our own pgroup, forcibly set the
811 tty's pgroup to our pgroup, and make sure to restore and reinstate
812 the tty's pgroup just like any other terminal setting. If
813 inherited_group was not the tty's pgroup, then we'll get a
814 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
815 it goes foreground in the future, which is what should happen. */
817 static pid_t inherited_pgroup;
819 void
820 init_foreground_group (void)
822 pid_t pgrp = getpgrp ();
823 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
826 /* Block and unblock SIGTTOU. */
828 void
829 block_tty_out_signal (sigset_t *oldset)
831 #ifdef SIGTTOU
832 sigset_t blocked;
833 sigemptyset (&blocked);
834 sigaddset (&blocked, SIGTTOU);
835 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
836 #endif
839 void
840 unblock_tty_out_signal (sigset_t const *oldset)
842 #ifdef SIGTTOU
843 pthread_sigmask (SIG_SETMASK, oldset, 0);
844 #endif
847 /* Safely set a controlling terminal FD's process group to PGID.
848 If we are not in the foreground already, POSIX requires tcsetpgrp
849 to deliver a SIGTTOU signal, which would stop us. This is an
850 annoyance, so temporarily ignore the signal.
852 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
853 skip all this unless SIGTTOU is defined. */
854 static void
855 tcsetpgrp_without_stopping (int fd, pid_t pgid)
857 #ifdef SIGTTOU
858 sigset_t oldset;
859 block_input ();
860 block_tty_out_signal (&oldset);
861 tcsetpgrp (fd, pgid);
862 unblock_tty_out_signal (&oldset);
863 unblock_input ();
864 #endif
867 /* Split off the foreground process group to Emacs alone. When we are
868 in the foreground, but not started in our own process group,
869 redirect the tty device handle FD to point to our own process
870 group. FD must be the file descriptor of the controlling tty. */
871 static void
872 narrow_foreground_group (int fd)
874 if (inherited_pgroup && setpgid (0, 0) == 0)
875 tcsetpgrp_without_stopping (fd, getpid ());
878 /* Set the tty to our original foreground group. */
879 static void
880 widen_foreground_group (int fd)
882 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
883 tcsetpgrp_without_stopping (fd, inherited_pgroup);
886 /* Getting and setting emacs_tty structures. */
888 /* Set *TC to the parameters associated with the terminal FD,
889 or clear it if the parameters are not available.
890 Return 0 on success, -1 on failure. */
892 emacs_get_tty (int fd, struct emacs_tty *settings)
894 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
895 memset (&settings->main, 0, sizeof (settings->main));
896 #ifdef DOS_NT
897 #ifdef WINDOWSNT
898 HANDLE h = (HANDLE)_get_osfhandle (fd);
899 DWORD console_mode;
901 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
903 settings->main = console_mode;
904 return 0;
906 #endif /* WINDOWSNT */
907 return -1;
908 #else /* !DOS_NT */
909 /* We have those nifty POSIX tcmumbleattr functions. */
910 return tcgetattr (fd, &settings->main);
911 #endif
915 /* Set the parameters of the tty on FD according to the contents of
916 *SETTINGS. If FLUSHP, discard input.
917 Return 0 if all went well, and -1 (setting errno) if anything failed. */
920 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
922 /* Set the primary parameters - baud rate, character size, etcetera. */
923 #ifdef DOS_NT
924 #ifdef WINDOWSNT
925 HANDLE h = (HANDLE)_get_osfhandle (fd);
927 if (h && h != INVALID_HANDLE_VALUE)
929 DWORD new_mode;
931 /* Assume the handle is open for input. */
932 if (flushp)
933 FlushConsoleInputBuffer (h);
934 new_mode = settings->main;
935 SetConsoleMode (h, new_mode);
937 #endif /* WINDOWSNT */
938 #else /* !DOS_NT */
939 int i;
940 /* We have those nifty POSIX tcmumbleattr functions.
941 William J. Smith <wjs@wiis.wang.com> writes:
942 "POSIX 1003.1 defines tcsetattr to return success if it was
943 able to perform any of the requested actions, even if some
944 of the requested actions could not be performed.
945 We must read settings back to ensure tty setup properly.
946 AIX requires this to keep tty from hanging occasionally." */
947 /* This make sure that we don't loop indefinitely in here. */
948 for (i = 0 ; i < 10 ; i++)
949 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
951 if (errno == EINTR)
952 continue;
953 else
954 return -1;
956 else
958 struct termios new;
960 memset (&new, 0, sizeof (new));
961 /* Get the current settings, and see if they're what we asked for. */
962 tcgetattr (fd, &new);
963 /* We cannot use memcmp on the whole structure here because under
964 * aix386 the termios structure has some reserved field that may
965 * not be filled in.
967 if ( new.c_iflag == settings->main.c_iflag
968 && new.c_oflag == settings->main.c_oflag
969 && new.c_cflag == settings->main.c_cflag
970 && new.c_lflag == settings->main.c_lflag
971 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
972 break;
973 else
974 continue;
976 #endif
978 /* We have survived the tempest. */
979 return 0;
984 #ifdef F_SETOWN
985 static int old_fcntl_owner[FD_SETSIZE];
986 #endif /* F_SETOWN */
988 /* This may also be defined in stdio,
989 but if so, this does no harm,
990 and using the same name avoids wasting the other one's space. */
992 #if defined (USG)
993 unsigned char _sobuf[BUFSIZ+8];
994 #else
995 char _sobuf[BUFSIZ];
996 #endif
998 /* Initialize the terminal mode on all tty devices that are currently
999 open. */
1001 void
1002 init_all_sys_modes (void)
1004 struct tty_display_info *tty;
1005 for (tty = tty_list; tty; tty = tty->next)
1006 init_sys_modes (tty);
1009 /* Initialize the terminal mode on the given tty device. */
1011 void
1012 init_sys_modes (struct tty_display_info *tty_out)
1014 struct emacs_tty tty;
1015 #ifndef DOS_NT
1016 Lisp_Object terminal;
1017 #endif
1019 Vtty_erase_char = Qnil;
1021 if (noninteractive)
1022 return;
1024 if (!tty_out->output)
1025 return; /* The tty is suspended. */
1027 narrow_foreground_group (fileno (tty_out->input));
1029 if (! tty_out->old_tty)
1030 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1032 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1034 tty = *tty_out->old_tty;
1036 #if !defined (DOS_NT)
1037 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1039 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1040 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1041 #ifdef INLCR /* I'm just being cautious,
1042 since I can't check how widespread INLCR is--rms. */
1043 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1044 #endif
1045 #ifdef ISTRIP
1046 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1047 #endif
1048 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1049 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1050 #ifdef IEXTEN
1051 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1052 #endif
1053 tty.main.c_lflag |= ISIG; /* Enable signals */
1054 if (tty_out->flow_control)
1056 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1057 #ifdef IXANY
1058 tty.main.c_iflag &= ~IXANY;
1059 #endif /* IXANY */
1061 else
1062 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1063 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1064 on output */
1065 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1066 #ifdef CS8
1067 if (tty_out->meta_key)
1069 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1070 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1072 #endif
1074 XSETTERMINAL(terminal, tty_out->terminal);
1075 if (!NILP (Fcontrolling_tty_p (terminal)))
1077 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1078 /* Set up C-g for both SIGQUIT and SIGINT.
1079 We don't know which we will get, but we handle both alike
1080 so which one it really gives us does not matter. */
1081 tty.main.c_cc[VQUIT] = quit_char;
1083 else
1085 /* We normally don't get interrupt or quit signals from tty
1086 devices other than our controlling terminal; therefore,
1087 we must handle C-g as normal input. Unfortunately, this
1088 means that the interrupt and quit feature must be
1089 disabled on secondary ttys, or we would not even see the
1090 keypress.
1092 Note that even though emacsclient could have special code
1093 to pass SIGINT to Emacs, we should _not_ enable
1094 interrupt/quit keys for emacsclient frames. This means
1095 that we can't break out of loops in C code from a
1096 secondary tty frame, but we can always decide what
1097 display the C-g came from, which is more important from a
1098 usability point of view. (Consider the case when two
1099 people work together using the same Emacs instance.) */
1100 tty.main.c_cc[VINTR] = CDISABLE;
1101 tty.main.c_cc[VQUIT] = CDISABLE;
1103 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1104 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1105 #ifdef VSWTCH
1106 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1107 of C-z */
1108 #endif /* VSWTCH */
1110 #ifdef VSUSP
1111 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1112 #endif /* VSUSP */
1113 #ifdef V_DSUSP
1114 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1115 #endif /* V_DSUSP */
1116 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1117 tty.main.c_cc[VDSUSP] = CDISABLE;
1118 #endif /* VDSUSP */
1119 #ifdef VLNEXT
1120 tty.main.c_cc[VLNEXT] = CDISABLE;
1121 #endif /* VLNEXT */
1122 #ifdef VREPRINT
1123 tty.main.c_cc[VREPRINT] = CDISABLE;
1124 #endif /* VREPRINT */
1125 #ifdef VWERASE
1126 tty.main.c_cc[VWERASE] = CDISABLE;
1127 #endif /* VWERASE */
1128 #ifdef VDISCARD
1129 tty.main.c_cc[VDISCARD] = CDISABLE;
1130 #endif /* VDISCARD */
1132 if (tty_out->flow_control)
1134 #ifdef VSTART
1135 tty.main.c_cc[VSTART] = '\021';
1136 #endif /* VSTART */
1137 #ifdef VSTOP
1138 tty.main.c_cc[VSTOP] = '\023';
1139 #endif /* VSTOP */
1141 else
1143 #ifdef VSTART
1144 tty.main.c_cc[VSTART] = CDISABLE;
1145 #endif /* VSTART */
1146 #ifdef VSTOP
1147 tty.main.c_cc[VSTOP] = CDISABLE;
1148 #endif /* VSTOP */
1151 #ifdef AIX
1152 tty.main.c_cc[VSTRT] = CDISABLE;
1153 tty.main.c_cc[VSTOP] = CDISABLE;
1154 tty.main.c_cc[VSUSP] = CDISABLE;
1155 tty.main.c_cc[VDSUSP] = CDISABLE;
1156 if (tty_out->flow_control)
1158 #ifdef VSTART
1159 tty.main.c_cc[VSTART] = '\021';
1160 #endif /* VSTART */
1161 #ifdef VSTOP
1162 tty.main.c_cc[VSTOP] = '\023';
1163 #endif /* VSTOP */
1165 /* Also, PTY overloads NUL and BREAK.
1166 don't ignore break, but don't signal either, so it looks like NUL.
1167 This really serves a purpose only if running in an XTERM window
1168 or via TELNET or the like, but does no harm elsewhere. */
1169 tty.main.c_iflag &= ~IGNBRK;
1170 tty.main.c_iflag &= ~BRKINT;
1171 #endif
1172 #endif /* not DOS_NT */
1174 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1175 if (!tty_out->term_initted)
1176 internal_terminal_init ();
1177 dos_ttraw (tty_out);
1178 #endif
1180 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1182 /* This code added to insure that, if flow-control is not to be used,
1183 we have an unlocked terminal at the start. */
1185 #ifdef TCXONC
1186 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1187 #endif
1188 #ifdef TIOCSTART
1189 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1190 #endif
1192 #if !defined (DOS_NT)
1193 #ifdef TCOON
1194 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1195 #endif
1196 #endif
1198 #ifdef F_GETOWN
1199 if (interrupt_input)
1201 old_fcntl_owner[fileno (tty_out->input)] =
1202 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1203 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1204 init_sigio (fileno (tty_out->input));
1205 #ifdef HAVE_GPM
1206 if (gpm_tty == tty_out)
1208 /* Arrange for mouse events to give us SIGIO signals. */
1209 fcntl (gpm_fd, F_SETOWN, getpid ());
1210 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1211 init_sigio (gpm_fd);
1213 #endif /* HAVE_GPM */
1215 #endif /* F_GETOWN */
1217 #ifdef _IOFBF
1218 /* This symbol is defined on recent USG systems.
1219 Someone says without this call USG won't really buffer the file
1220 even with a call to setbuf. */
1221 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1222 #else
1223 setbuf (tty_out->output, (char *) _sobuf);
1224 #endif
1226 if (tty_out->terminal->set_terminal_modes_hook)
1227 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1229 if (!tty_out->term_initted)
1231 Lisp_Object tail, frame;
1232 FOR_EACH_FRAME (tail, frame)
1234 /* XXX This needs to be revised. */
1235 if (FRAME_TERMCAP_P (XFRAME (frame))
1236 && FRAME_TTY (XFRAME (frame)) == tty_out)
1237 init_frame_faces (XFRAME (frame));
1241 if (tty_out->term_initted && no_redraw_on_reenter)
1243 /* We used to call "direct_output_forward_char(0)" here,
1244 but it's not clear why, since it may not do anything anyway. */
1246 else
1248 Lisp_Object tail, frame;
1249 frame_garbaged = 1;
1250 FOR_EACH_FRAME (tail, frame)
1252 if ((FRAME_TERMCAP_P (XFRAME (frame))
1253 || FRAME_MSDOS_P (XFRAME (frame)))
1254 && FRAME_TTY (XFRAME (frame)) == tty_out)
1255 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1259 tty_out->term_initted = 1;
1262 /* Return true if safe to use tabs in output.
1263 At the time this is called, init_sys_modes has not been done yet. */
1265 bool
1266 tabs_safe_p (int fd)
1268 struct emacs_tty etty;
1270 emacs_get_tty (fd, &etty);
1271 #ifndef DOS_NT
1272 #ifdef TABDLY
1273 return ((etty.main.c_oflag & TABDLY) != TAB3);
1274 #else /* not TABDLY */
1275 return 1;
1276 #endif /* not TABDLY */
1277 #else /* DOS_NT */
1278 return 0;
1279 #endif /* DOS_NT */
1282 /* Discard echoing. */
1284 void
1285 suppress_echo_on_tty (int fd)
1287 struct emacs_tty etty;
1289 emacs_get_tty (fd, &etty);
1290 #ifdef DOS_NT
1291 /* Set raw input mode. */
1292 etty.main = 0;
1293 #else
1294 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1295 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1296 #endif /* ! WINDOWSNT */
1297 emacs_set_tty (fd, &etty, 0);
1300 /* Get terminal size from system.
1301 Store number of lines into *HEIGHTP and width into *WIDTHP.
1302 We store 0 if there's no valid information. */
1304 void
1305 get_tty_size (int fd, int *widthp, int *heightp)
1307 #if defined TIOCGWINSZ
1309 /* BSD-style. */
1310 struct winsize size;
1312 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1313 *widthp = *heightp = 0;
1314 else
1316 *widthp = size.ws_col;
1317 *heightp = size.ws_row;
1320 #elif defined TIOCGSIZE
1322 /* SunOS - style. */
1323 struct ttysize size;
1325 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1326 *widthp = *heightp = 0;
1327 else
1329 *widthp = size.ts_cols;
1330 *heightp = size.ts_lines;
1333 #elif defined WINDOWSNT
1335 CONSOLE_SCREEN_BUFFER_INFO info;
1336 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1338 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1339 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1341 else
1342 *widthp = *heightp = 0;
1344 #elif defined MSDOS
1346 *widthp = ScreenCols ();
1347 *heightp = ScreenRows ();
1349 #else /* system doesn't know size */
1351 *widthp = 0;
1352 *heightp = 0;
1354 #endif
1357 /* Set the logical window size associated with descriptor FD
1358 to HEIGHT and WIDTH. This is used mainly with ptys.
1359 Return a negative value on failure. */
1362 set_window_size (int fd, int height, int width)
1364 #ifdef TIOCSWINSZ
1366 /* BSD-style. */
1367 struct winsize size;
1368 size.ws_row = height;
1369 size.ws_col = width;
1371 return ioctl (fd, TIOCSWINSZ, &size);
1373 #else
1374 #ifdef TIOCSSIZE
1376 /* SunOS - style. */
1377 struct ttysize size;
1378 size.ts_lines = height;
1379 size.ts_cols = width;
1381 return ioctl (fd, TIOCGSIZE, &size);
1382 #else
1383 return -1;
1384 #endif /* not SunOS-style */
1385 #endif /* not BSD-style */
1390 /* Prepare all terminal devices for exiting Emacs. */
1392 void
1393 reset_all_sys_modes (void)
1395 struct tty_display_info *tty;
1396 for (tty = tty_list; tty; tty = tty->next)
1397 reset_sys_modes (tty);
1400 /* Prepare the terminal for closing it; move the cursor to the
1401 bottom of the frame, turn off interrupt-driven I/O, etc. */
1403 void
1404 reset_sys_modes (struct tty_display_info *tty_out)
1406 if (noninteractive)
1408 fflush (stdout);
1409 return;
1411 if (!tty_out->term_initted)
1412 return;
1414 if (!tty_out->output)
1415 return; /* The tty is suspended. */
1417 /* Go to and clear the last line of the terminal. */
1419 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1421 /* Code adapted from tty_clear_end_of_line. */
1422 if (tty_out->TS_clr_line)
1424 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1426 else
1427 { /* have to do it the hard way */
1428 int i;
1429 tty_turn_off_insert (tty_out);
1431 for (i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1433 fputc (' ', tty_out->output);
1437 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1438 fflush (tty_out->output);
1440 if (tty_out->terminal->reset_terminal_modes_hook)
1441 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1443 /* Avoid possible loss of output when changing terminal modes. */
1444 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1445 continue;
1447 #ifndef DOS_NT
1448 #ifdef F_SETOWN
1449 if (interrupt_input)
1451 reset_sigio (fileno (tty_out->input));
1452 fcntl (fileno (tty_out->input), F_SETOWN,
1453 old_fcntl_owner[fileno (tty_out->input)]);
1455 #endif /* F_SETOWN */
1456 fcntl (fileno (tty_out->input), F_SETFL,
1457 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1458 #endif
1460 if (tty_out->old_tty)
1461 while (emacs_set_tty (fileno (tty_out->input),
1462 tty_out->old_tty, 0) < 0 && errno == EINTR)
1465 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1466 dos_ttcooked ();
1467 #endif
1469 widen_foreground_group (fileno (tty_out->input));
1472 #ifdef HAVE_PTYS
1474 /* Set up the proper status flags for use of a pty. */
1476 void
1477 setup_pty (int fd)
1479 /* I'm told that TOICREMOTE does not mean control chars
1480 "can't be sent" but rather that they don't have
1481 input-editing or signaling effects.
1482 That should be good, because we have other ways
1483 to do those things in Emacs.
1484 However, telnet mode seems not to work on 4.2.
1485 So TIOCREMOTE is turned off now. */
1487 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1488 will hang. In particular, the "timeout" feature (which
1489 causes a read to return if there is no data available)
1490 does this. Also it is known that telnet mode will hang
1491 in such a way that Emacs must be stopped (perhaps this
1492 is the same problem).
1494 If TIOCREMOTE is turned off, then there is a bug in
1495 hp-ux which sometimes loses data. Apparently the
1496 code which blocks the master process when the internal
1497 buffer fills up does not work. Other than this,
1498 though, everything else seems to work fine.
1500 Since the latter lossage is more benign, we may as well
1501 lose that way. -- cph */
1502 #ifdef FIONBIO
1503 #if defined (UNIX98_PTYS)
1505 int on = 1;
1506 ioctl (fd, FIONBIO, &on);
1508 #endif
1509 #endif
1511 #endif /* HAVE_PTYS */
1513 void
1514 init_system_name (void)
1516 if (!build_details)
1518 /* Set system-name to nil so that the build is deterministic. */
1519 Vsystem_name = Qnil;
1520 return;
1522 char *hostname_alloc = NULL;
1523 char *hostname;
1524 #ifndef HAVE_GETHOSTNAME
1525 struct utsname uts;
1526 uname (&uts);
1527 hostname = uts.nodename;
1528 #else /* HAVE_GETHOSTNAME */
1529 char hostname_buf[256];
1530 ptrdiff_t hostname_size = sizeof hostname_buf;
1531 hostname = hostname_buf;
1533 /* Try to get the host name; if the buffer is too short, try
1534 again. Apparently, the only indication gethostname gives of
1535 whether the buffer was large enough is the presence or absence
1536 of a '\0' in the string. Eech. */
1537 for (;;)
1539 gethostname (hostname, hostname_size - 1);
1540 hostname[hostname_size - 1] = '\0';
1542 /* Was the buffer large enough for the '\0'? */
1543 if (strlen (hostname) < hostname_size - 1)
1544 break;
1546 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1547 min (PTRDIFF_MAX, SIZE_MAX), 1);
1549 #endif /* HAVE_GETHOSTNAME */
1550 char *p;
1551 for (p = hostname; *p; p++)
1552 if (*p == ' ' || *p == '\t')
1553 *p = '-';
1554 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1555 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1556 Vsystem_name = build_string (hostname);
1557 xfree (hostname_alloc);
1560 sigset_t empty_mask;
1562 static struct sigaction process_fatal_action;
1564 static int
1565 emacs_sigaction_flags (void)
1567 #ifdef SA_RESTART
1568 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1569 'select') to reset their timeout on some platforms (e.g.,
1570 HP-UX 11), which is not what we want. Also, when Emacs is
1571 interactive, we don't want SA_RESTART because we need to poll
1572 for pending input so we need long-running syscalls to be interrupted
1573 after a signal that sets pending_signals.
1575 Non-interactive keyboard input goes through stdio, where we
1576 always want restartable system calls. */
1577 if (noninteractive)
1578 return SA_RESTART;
1579 #endif
1580 return 0;
1583 /* Store into *ACTION a signal action suitable for Emacs, with handler
1584 HANDLER. */
1585 void
1586 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1588 sigemptyset (&action->sa_mask);
1590 /* When handling a signal, block nonfatal system signals that are caught
1591 by Emacs. This makes race conditions less likely. */
1592 sigaddset (&action->sa_mask, SIGALRM);
1593 #ifdef SIGCHLD
1594 sigaddset (&action->sa_mask, SIGCHLD);
1595 #endif
1596 #ifdef SIGDANGER
1597 sigaddset (&action->sa_mask, SIGDANGER);
1598 #endif
1599 #ifdef PROFILER_CPU_SUPPORT
1600 sigaddset (&action->sa_mask, SIGPROF);
1601 #endif
1602 #ifdef SIGWINCH
1603 sigaddset (&action->sa_mask, SIGWINCH);
1604 #endif
1605 if (! noninteractive)
1607 sigaddset (&action->sa_mask, SIGINT);
1608 sigaddset (&action->sa_mask, SIGQUIT);
1609 #ifdef USABLE_SIGIO
1610 sigaddset (&action->sa_mask, SIGIO);
1611 #endif
1614 action->sa_handler = handler;
1615 action->sa_flags = emacs_sigaction_flags ();
1618 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1619 pthread_t main_thread_id;
1620 #endif
1622 /* SIG has arrived at the current process. Deliver it to the main
1623 thread, which should handle it with HANDLER. (Delivering the
1624 signal to some other thread might not work if the other thread is
1625 about to exit.)
1627 If we are on the main thread, handle the signal SIG with HANDLER.
1628 Otherwise, redirect the signal to the main thread, blocking it from
1629 this thread. POSIX says any thread can receive a signal that is
1630 associated with a process, process group, or asynchronous event.
1631 On GNU/Linux the main thread typically gets a process signal unless
1632 it's blocked, but other systems (FreeBSD at least) can deliver the
1633 signal to other threads. */
1634 void
1635 deliver_process_signal (int sig, signal_handler_t handler)
1637 /* Preserve errno, to avoid race conditions with signal handlers that
1638 might change errno. Races can occur even in single-threaded hosts. */
1639 int old_errno = errno;
1641 bool on_main_thread = true;
1642 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1643 if (! pthread_equal (pthread_self (), main_thread_id))
1645 sigset_t blocked;
1646 sigemptyset (&blocked);
1647 sigaddset (&blocked, sig);
1648 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1649 pthread_kill (main_thread_id, sig);
1650 on_main_thread = false;
1652 #endif
1653 if (on_main_thread)
1654 handler (sig);
1656 errno = old_errno;
1659 /* Static location to save a fatal backtrace in a thread.
1660 FIXME: If two subsidiary threads fail simultaneously, the resulting
1661 backtrace may be garbage. */
1662 enum { BACKTRACE_LIMIT_MAX = 500 };
1663 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1664 static int thread_backtrace_npointers;
1666 /* SIG has arrived at the current thread.
1667 If we are on the main thread, handle the signal SIG with HANDLER.
1668 Otherwise, this is a fatal error in the handling thread. */
1669 static void
1670 deliver_thread_signal (int sig, signal_handler_t handler)
1672 int old_errno = errno;
1674 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1675 if (! pthread_equal (pthread_self (), main_thread_id))
1677 thread_backtrace_npointers
1678 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1679 sigaction (sig, &process_fatal_action, 0);
1680 pthread_kill (main_thread_id, sig);
1682 /* Avoid further damage while the main thread is exiting. */
1683 while (1)
1684 sigsuspend (&empty_mask);
1686 #endif
1688 handler (sig);
1689 errno = old_errno;
1692 #if !HAVE_DECL_SYS_SIGLIST
1693 # undef sys_siglist
1694 # ifdef _sys_siglist
1695 # define sys_siglist _sys_siglist
1696 # elif HAVE_DECL___SYS_SIGLIST
1697 # define sys_siglist __sys_siglist
1698 # else
1699 # define sys_siglist my_sys_siglist
1700 static char const *sys_siglist[NSIG];
1701 # endif
1702 #endif
1704 #ifdef _sys_nsig
1705 # define sys_siglist_entries _sys_nsig
1706 #else
1707 # define sys_siglist_entries NSIG
1708 #endif
1710 /* Handle bus errors, invalid instruction, etc. */
1711 static void
1712 handle_fatal_signal (int sig)
1714 terminate_due_to_signal (sig, 40);
1717 static void
1718 deliver_fatal_signal (int sig)
1720 deliver_process_signal (sig, handle_fatal_signal);
1723 static void
1724 deliver_fatal_thread_signal (int sig)
1726 deliver_thread_signal (sig, handle_fatal_signal);
1729 static _Noreturn void
1730 handle_arith_signal (int sig)
1732 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1733 xsignal0 (Qarith_error);
1736 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1738 /* Alternate stack used by SIGSEGV handler below. */
1740 static unsigned char sigsegv_stack[SIGSTKSZ];
1743 /* Return true if SIGINFO indicates a stack overflow. */
1745 static bool
1746 stack_overflow (siginfo_t *siginfo)
1748 if (!attempt_stack_overflow_recovery)
1749 return false;
1751 /* In theory, a more-accurate heuristic can be obtained by using
1752 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1753 and pthread_attr_getguardsize to find the location and size of the
1754 guard area. In practice, though, these functions are so hard to
1755 use reliably that they're not worth bothering with. E.g., see:
1756 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1757 Other operating systems also have problems, e.g., Solaris's
1758 stack_violation function is tailor-made for this problem, but it
1759 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1761 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1762 candidate here. */
1764 if (!siginfo)
1765 return false;
1767 /* The faulting address. */
1768 char *addr = siginfo->si_addr;
1769 if (!addr)
1770 return false;
1772 /* The known top and bottom of the stack. The actual stack may
1773 extend a bit beyond these boundaries. */
1774 char *bot = stack_bottom;
1775 char *top = near_C_stack_top ();
1777 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1778 of the known stack divided by the size of the guard area past the
1779 end of the stack top. The heuristic is that a bad address is
1780 considered to be a stack overflow if it occurs within
1781 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1782 stack. This heuristic is not exactly correct but it's good
1783 enough in practice. */
1784 enum { LG_STACK_HEURISTIC = 8 };
1786 if (bot < top)
1787 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1788 else
1789 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1793 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1795 static void
1796 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1798 /* Hard GC error may lead to stack overflow caused by
1799 too nested calls to mark_object. No way to survive. */
1800 bool fatal = gc_in_progress;
1802 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1803 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1804 fatal = true;
1805 #endif
1807 if (!fatal && stack_overflow (siginfo))
1808 siglongjmp (return_to_command_loop, 1);
1810 /* Otherwise we can't do anything with this. */
1811 deliver_fatal_thread_signal (sig);
1814 /* Return true if we have successfully set up SIGSEGV handler on alternate
1815 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1817 static bool
1818 init_sigsegv (void)
1820 struct sigaction sa;
1821 stack_t ss;
1823 ss.ss_sp = sigsegv_stack;
1824 ss.ss_size = sizeof (sigsegv_stack);
1825 ss.ss_flags = 0;
1826 if (sigaltstack (&ss, NULL) < 0)
1827 return 0;
1829 sigfillset (&sa.sa_mask);
1830 sa.sa_sigaction = handle_sigsegv;
1831 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1832 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1835 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1837 static bool
1838 init_sigsegv (void)
1840 return 0;
1843 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1845 static void
1846 deliver_arith_signal (int sig)
1848 deliver_thread_signal (sig, handle_arith_signal);
1851 #ifdef SIGDANGER
1853 /* Handler for SIGDANGER. */
1854 static void
1855 handle_danger_signal (int sig)
1857 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1859 /* It might be unsafe to call do_auto_save now. */
1860 force_auto_save_soon ();
1863 static void
1864 deliver_danger_signal (int sig)
1866 deliver_process_signal (sig, handle_danger_signal);
1868 #endif
1870 /* Treat SIG as a terminating signal, unless it is already ignored and
1871 we are in --batch mode. Among other things, this makes nohup work. */
1872 static void
1873 maybe_fatal_sig (int sig)
1875 bool catch_sig = !noninteractive;
1876 if (!catch_sig)
1878 struct sigaction old_action;
1879 sigaction (sig, 0, &old_action);
1880 catch_sig = old_action.sa_handler != SIG_IGN;
1882 if (catch_sig)
1883 sigaction (sig, &process_fatal_action, 0);
1886 void
1887 init_signals (bool dumping)
1889 struct sigaction thread_fatal_action;
1890 struct sigaction action;
1892 sigemptyset (&empty_mask);
1894 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1895 main_thread_id = pthread_self ();
1896 #endif
1898 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1899 if (! initialized)
1901 sys_siglist[SIGABRT] = "Aborted";
1902 # ifdef SIGAIO
1903 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1904 # endif
1905 sys_siglist[SIGALRM] = "Alarm clock";
1906 # ifdef SIGBUS
1907 sys_siglist[SIGBUS] = "Bus error";
1908 # endif
1909 # ifdef SIGCHLD
1910 sys_siglist[SIGCHLD] = "Child status changed";
1911 # endif
1912 # ifdef SIGCONT
1913 sys_siglist[SIGCONT] = "Continued";
1914 # endif
1915 # ifdef SIGDANGER
1916 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1917 # endif
1918 # ifdef SIGDGNOTIFY
1919 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1920 # endif
1921 # ifdef SIGEMT
1922 sys_siglist[SIGEMT] = "Emulation trap";
1923 # endif
1924 sys_siglist[SIGFPE] = "Arithmetic exception";
1925 # ifdef SIGFREEZE
1926 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1927 # endif
1928 # ifdef SIGGRANT
1929 sys_siglist[SIGGRANT] = "Monitor mode granted";
1930 # endif
1931 sys_siglist[SIGHUP] = "Hangup";
1932 sys_siglist[SIGILL] = "Illegal instruction";
1933 sys_siglist[SIGINT] = "Interrupt";
1934 # ifdef SIGIO
1935 sys_siglist[SIGIO] = "I/O possible";
1936 # endif
1937 # ifdef SIGIOINT
1938 sys_siglist[SIGIOINT] = "I/O intervention required";
1939 # endif
1940 # ifdef SIGIOT
1941 sys_siglist[SIGIOT] = "IOT trap";
1942 # endif
1943 sys_siglist[SIGKILL] = "Killed";
1944 # ifdef SIGLOST
1945 sys_siglist[SIGLOST] = "Resource lost";
1946 # endif
1947 # ifdef SIGLWP
1948 sys_siglist[SIGLWP] = "SIGLWP";
1949 # endif
1950 # ifdef SIGMSG
1951 sys_siglist[SIGMSG] = "Monitor mode data available";
1952 # endif
1953 # ifdef SIGPHONE
1954 sys_siglist[SIGWIND] = "SIGPHONE";
1955 # endif
1956 sys_siglist[SIGPIPE] = "Broken pipe";
1957 # ifdef SIGPOLL
1958 sys_siglist[SIGPOLL] = "Pollable event occurred";
1959 # endif
1960 # ifdef SIGPROF
1961 sys_siglist[SIGPROF] = "Profiling timer expired";
1962 # endif
1963 # ifdef SIGPTY
1964 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1965 # endif
1966 # ifdef SIGPWR
1967 sys_siglist[SIGPWR] = "Power-fail restart";
1968 # endif
1969 sys_siglist[SIGQUIT] = "Quit";
1970 # ifdef SIGRETRACT
1971 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1972 # endif
1973 # ifdef SIGSAK
1974 sys_siglist[SIGSAK] = "Secure attention";
1975 # endif
1976 sys_siglist[SIGSEGV] = "Segmentation violation";
1977 # ifdef SIGSOUND
1978 sys_siglist[SIGSOUND] = "Sound completed";
1979 # endif
1980 # ifdef SIGSTOP
1981 sys_siglist[SIGSTOP] = "Stopped (signal)";
1982 # endif
1983 # ifdef SIGSTP
1984 sys_siglist[SIGSTP] = "Stopped (user)";
1985 # endif
1986 # ifdef SIGSYS
1987 sys_siglist[SIGSYS] = "Bad argument to system call";
1988 # endif
1989 sys_siglist[SIGTERM] = "Terminated";
1990 # ifdef SIGTHAW
1991 sys_siglist[SIGTHAW] = "SIGTHAW";
1992 # endif
1993 # ifdef SIGTRAP
1994 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1995 # endif
1996 # ifdef SIGTSTP
1997 sys_siglist[SIGTSTP] = "Stopped (user)";
1998 # endif
1999 # ifdef SIGTTIN
2000 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2001 # endif
2002 # ifdef SIGTTOU
2003 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2004 # endif
2005 # ifdef SIGURG
2006 sys_siglist[SIGURG] = "Urgent I/O condition";
2007 # endif
2008 # ifdef SIGUSR1
2009 sys_siglist[SIGUSR1] = "User defined signal 1";
2010 # endif
2011 # ifdef SIGUSR2
2012 sys_siglist[SIGUSR2] = "User defined signal 2";
2013 # endif
2014 # ifdef SIGVTALRM
2015 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2016 # endif
2017 # ifdef SIGWAITING
2018 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2019 # endif
2020 # ifdef SIGWINCH
2021 sys_siglist[SIGWINCH] = "Window size changed";
2022 # endif
2023 # ifdef SIGWIND
2024 sys_siglist[SIGWIND] = "SIGWIND";
2025 # endif
2026 # ifdef SIGXCPU
2027 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2028 # endif
2029 # ifdef SIGXFSZ
2030 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2031 # endif
2033 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2035 /* Don't alter signal handlers if dumping. On some machines,
2036 changing signal handlers sets static data that would make signals
2037 fail to work right when the dumped Emacs is run. */
2038 if (dumping)
2039 return;
2041 sigfillset (&process_fatal_action.sa_mask);
2042 process_fatal_action.sa_handler = deliver_fatal_signal;
2043 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2045 sigfillset (&thread_fatal_action.sa_mask);
2046 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2047 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2049 /* SIGINT may need special treatment on MS-Windows. See
2050 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2051 Please update the doc of kill-emacs, kill-emacs-hook, and
2052 NEWS if you change this. */
2054 maybe_fatal_sig (SIGHUP);
2055 maybe_fatal_sig (SIGINT);
2056 maybe_fatal_sig (SIGTERM);
2058 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2059 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2060 to behave more like typical batch applications do. */
2061 if (! noninteractive)
2062 signal (SIGPIPE, SIG_IGN);
2064 sigaction (SIGQUIT, &process_fatal_action, 0);
2065 sigaction (SIGILL, &thread_fatal_action, 0);
2066 sigaction (SIGTRAP, &thread_fatal_action, 0);
2068 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2069 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2070 interpreter's floating point operations, so treat SIGFPE as an
2071 arith-error if it arises in the main thread. */
2072 if (IEEE_FLOATING_POINT)
2073 sigaction (SIGFPE, &thread_fatal_action, 0);
2074 else
2076 emacs_sigaction_init (&action, deliver_arith_signal);
2077 sigaction (SIGFPE, &action, 0);
2080 #ifdef SIGUSR1
2081 add_user_signal (SIGUSR1, "sigusr1");
2082 #endif
2083 #ifdef SIGUSR2
2084 add_user_signal (SIGUSR2, "sigusr2");
2085 #endif
2086 sigaction (SIGABRT, &thread_fatal_action, 0);
2087 #ifdef SIGPRE
2088 sigaction (SIGPRE, &thread_fatal_action, 0);
2089 #endif
2090 #ifdef SIGORE
2091 sigaction (SIGORE, &thread_fatal_action, 0);
2092 #endif
2093 #ifdef SIGUME
2094 sigaction (SIGUME, &thread_fatal_action, 0);
2095 #endif
2096 #ifdef SIGDLK
2097 sigaction (SIGDLK, &process_fatal_action, 0);
2098 #endif
2099 #ifdef SIGCPULIM
2100 sigaction (SIGCPULIM, &process_fatal_action, 0);
2101 #endif
2102 #ifdef SIGIOT
2103 sigaction (SIGIOT, &thread_fatal_action, 0);
2104 #endif
2105 #ifdef SIGEMT
2106 sigaction (SIGEMT, &thread_fatal_action, 0);
2107 #endif
2108 #ifdef SIGBUS
2109 sigaction (SIGBUS, &thread_fatal_action, 0);
2110 #endif
2111 if (!init_sigsegv ())
2112 sigaction (SIGSEGV, &thread_fatal_action, 0);
2113 #ifdef SIGSYS
2114 sigaction (SIGSYS, &thread_fatal_action, 0);
2115 #endif
2116 sigaction (SIGTERM, &process_fatal_action, 0);
2117 #ifdef SIGPROF
2118 signal (SIGPROF, SIG_IGN);
2119 #endif
2120 #ifdef SIGVTALRM
2121 sigaction (SIGVTALRM, &process_fatal_action, 0);
2122 #endif
2123 #ifdef SIGXCPU
2124 sigaction (SIGXCPU, &process_fatal_action, 0);
2125 #endif
2126 #ifdef SIGXFSZ
2127 sigaction (SIGXFSZ, &process_fatal_action, 0);
2128 #endif
2130 #ifdef SIGDANGER
2131 /* This just means available memory is getting low. */
2132 emacs_sigaction_init (&action, deliver_danger_signal);
2133 sigaction (SIGDANGER, &action, 0);
2134 #endif
2136 /* AIX-specific signals. */
2137 #ifdef SIGGRANT
2138 sigaction (SIGGRANT, &process_fatal_action, 0);
2139 #endif
2140 #ifdef SIGMIGRATE
2141 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2142 #endif
2143 #ifdef SIGMSG
2144 sigaction (SIGMSG, &process_fatal_action, 0);
2145 #endif
2146 #ifdef SIGRETRACT
2147 sigaction (SIGRETRACT, &process_fatal_action, 0);
2148 #endif
2149 #ifdef SIGSAK
2150 sigaction (SIGSAK, &process_fatal_action, 0);
2151 #endif
2152 #ifdef SIGSOUND
2153 sigaction (SIGSOUND, &process_fatal_action, 0);
2154 #endif
2155 #ifdef SIGTALRM
2156 sigaction (SIGTALRM, &thread_fatal_action, 0);
2157 #endif
2160 #ifndef HAVE_RANDOM
2161 #ifdef random
2162 #define HAVE_RANDOM
2163 #endif
2164 #endif
2166 /* Figure out how many bits the system's random number generator uses.
2167 `random' and `lrand48' are assumed to return 31 usable bits.
2168 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2169 so we'll shift it and treat it like the 15-bit USG `rand'. */
2171 #ifndef RAND_BITS
2172 # ifdef HAVE_RANDOM
2173 # define RAND_BITS 31
2174 # else /* !HAVE_RANDOM */
2175 # ifdef HAVE_LRAND48
2176 # define RAND_BITS 31
2177 # define random lrand48
2178 # else /* !HAVE_LRAND48 */
2179 # define RAND_BITS 15
2180 # if RAND_MAX == 32767
2181 # define random rand
2182 # else /* RAND_MAX != 32767 */
2183 # if RAND_MAX == 2147483647
2184 # define random() (rand () >> 16)
2185 # else /* RAND_MAX != 2147483647 */
2186 # ifdef USG
2187 # define random rand
2188 # else
2189 # define random() (rand () >> 16)
2190 # endif /* !USG */
2191 # endif /* RAND_MAX != 2147483647 */
2192 # endif /* RAND_MAX != 32767 */
2193 # endif /* !HAVE_LRAND48 */
2194 # endif /* !HAVE_RANDOM */
2195 #endif /* !RAND_BITS */
2197 #ifdef HAVE_RANDOM
2198 typedef unsigned int random_seed;
2199 static void set_random_seed (random_seed arg) { srandom (arg); }
2200 #elif defined HAVE_LRAND48
2201 /* Although srand48 uses a long seed, this is unsigned long to avoid
2202 undefined behavior on signed integer overflow in init_random. */
2203 typedef unsigned long int random_seed;
2204 static void set_random_seed (random_seed arg) { srand48 (arg); }
2205 #else
2206 typedef unsigned int random_seed;
2207 static void set_random_seed (random_seed arg) { srand (arg); }
2208 #endif
2210 void
2211 seed_random (void *seed, ptrdiff_t seed_size)
2213 random_seed arg = 0;
2214 unsigned char *argp = (unsigned char *) &arg;
2215 unsigned char *seedp = seed;
2216 for (ptrdiff_t i = 0; i < seed_size; i++)
2217 argp[i % sizeof arg] ^= seedp[i];
2218 set_random_seed (arg);
2221 void
2222 init_random (void)
2224 random_seed v;
2225 bool success = false;
2227 /* First, try seeding the PRNG from the operating system's entropy
2228 source. This approach is both fast and secure. */
2229 #ifdef WINDOWSNT
2230 success = w32_init_random (&v, sizeof v) == 0;
2231 #else
2232 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2233 if (0 <= fd)
2235 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2236 close (fd);
2238 #endif
2240 /* If that didn't work, try using GnuTLS, which is secure, but on
2241 some systems, can be somewhat slow. */
2242 if (!success)
2243 success = EQ (emacs_gnutls_global_init (), Qt)
2244 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2246 /* If _that_ didn't work, just use the current time value and PID.
2247 It's at least better than XKCD 221. */
2248 if (!success)
2250 struct timespec t = current_timespec ();
2251 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2254 set_random_seed (v);
2258 * Return a nonnegative random integer out of whatever we've got.
2259 * It contains enough bits to make a random (signed) Emacs fixnum.
2260 * This suffices even for a 64-bit architecture with a 15-bit rand.
2262 EMACS_INT
2263 get_random (void)
2265 EMACS_UINT val = 0;
2266 int i;
2267 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2268 val = (random () ^ (val << RAND_BITS)
2269 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2270 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2271 return val & INTMASK;
2274 #ifndef HAVE_SNPRINTF
2275 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2277 snprintf (char *buf, size_t bufsize, char const *format, ...)
2279 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2280 ptrdiff_t nbytes = size - 1;
2281 va_list ap;
2283 if (size)
2285 va_start (ap, format);
2286 nbytes = doprnt (buf, size, format, 0, ap);
2287 va_end (ap);
2290 if (nbytes == size - 1)
2292 /* Calculate the length of the string that would have been created
2293 had the buffer been large enough. */
2294 char stackbuf[4000];
2295 char *b = stackbuf;
2296 ptrdiff_t bsize = sizeof stackbuf;
2297 va_start (ap, format);
2298 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2299 va_end (ap);
2300 if (b != stackbuf)
2301 xfree (b);
2304 if (INT_MAX < nbytes)
2306 #ifdef EOVERFLOW
2307 errno = EOVERFLOW;
2308 #else
2309 errno = EDOM;
2310 #endif
2311 return -1;
2313 return nbytes;
2315 #endif
2317 /* If a backtrace is available, output the top lines of it to stderr.
2318 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2319 This function may be called from a signal handler, so it should
2320 not invoke async-unsafe functions like malloc.
2322 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2323 but do not output anything. This avoids some problems that can
2324 otherwise occur if the malloc arena is corrupted before 'backtrace'
2325 is called, since 'backtrace' may call malloc if the tables are not
2326 initialized.
2328 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2329 fatal error has occurred in some other thread; generate a thread
2330 backtrace instead, ignoring BACKTRACE_LIMIT. */
2331 void
2332 emacs_backtrace (int backtrace_limit)
2334 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2335 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2336 void *buffer;
2337 int npointers;
2339 if (thread_backtrace_npointers)
2341 buffer = thread_backtrace_buffer;
2342 npointers = thread_backtrace_npointers;
2344 else
2346 buffer = main_backtrace_buffer;
2348 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2349 if (bounded_limit < 0)
2351 backtrace (buffer, 1);
2352 return;
2355 npointers = backtrace (buffer, bounded_limit + 1);
2358 if (npointers)
2360 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2361 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2362 if (bounded_limit < npointers)
2363 emacs_write (STDERR_FILENO, "...\n", 4);
2367 #ifndef HAVE_NTGUI
2368 void
2369 emacs_abort (void)
2371 terminate_due_to_signal (SIGABRT, 40);
2373 #endif
2375 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2376 Use binary I/O on systems that care about text vs binary I/O.
2377 Arrange for subprograms to not inherit the file descriptor.
2378 Prefer a method that is multithread-safe, if available.
2379 Do not fail merely because the open was interrupted by a signal.
2380 Allow the user to quit. */
2383 emacs_open (const char *file, int oflags, int mode)
2385 int fd;
2386 if (! (oflags & O_TEXT))
2387 oflags |= O_BINARY;
2388 oflags |= O_CLOEXEC;
2389 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2390 maybe_quit ();
2391 if (! O_CLOEXEC && 0 <= fd)
2392 fcntl (fd, F_SETFD, FD_CLOEXEC);
2393 return fd;
2396 /* Open FILE as a stream for Emacs use, with mode MODE.
2397 Act like emacs_open with respect to threads, signals, and quits. */
2399 FILE *
2400 emacs_fopen (char const *file, char const *mode)
2402 int fd, omode, oflags;
2403 int bflag = 0;
2404 char const *m = mode;
2406 switch (*m++)
2408 case 'r': omode = O_RDONLY; oflags = 0; break;
2409 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2410 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2411 default: emacs_abort ();
2414 while (*m)
2415 switch (*m++)
2417 case '+': omode = O_RDWR; break;
2418 case 't': bflag = O_TEXT; break;
2419 default: /* Ignore. */ break;
2422 fd = emacs_open (file, omode | oflags | bflag, 0666);
2423 return fd < 0 ? 0 : fdopen (fd, mode);
2426 /* Create a pipe for Emacs use. */
2429 emacs_pipe (int fd[2])
2431 #ifdef MSDOS
2432 return pipe (fd);
2433 #else /* !MSDOS */
2434 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2435 if (! O_CLOEXEC && result == 0)
2437 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2438 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2440 return result;
2441 #endif /* !MSDOS */
2444 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2445 For the background behind this mess, please see Austin Group defect 529
2446 <http://austingroupbugs.net/view.php?id=529>. */
2448 #ifndef POSIX_CLOSE_RESTART
2449 # define POSIX_CLOSE_RESTART 1
2450 static int
2451 posix_close (int fd, int flag)
2453 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2454 eassert (flag == POSIX_CLOSE_RESTART);
2456 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2457 on a system that does not define POSIX_CLOSE_RESTART.
2459 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2460 closed, and retrying the close could inadvertently close a file
2461 descriptor allocated by some other thread. In other systems
2462 (e.g., HP/UX) FD is not closed. And in still other systems
2463 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2464 multithreaded program there can be no way to tell.
2466 So, in this case, pretend that the close succeeded. This works
2467 well on systems like GNU/Linux that close FD. Although it may
2468 leak a file descriptor on other systems, the leak is unlikely and
2469 it's better to leak than to close a random victim. */
2470 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2472 #endif
2474 /* Close FD, retrying if interrupted. If successful, return 0;
2475 otherwise, return -1 and set errno to a non-EINTR value. Consider
2476 an EINPROGRESS error to be successful, as that's merely a signal
2477 arriving. FD is always closed when this function returns, even
2478 when it returns -1.
2480 Do not call this function if FD is nonnegative and might already be closed,
2481 as that might close an innocent victim opened by some other thread. */
2484 emacs_close (int fd)
2486 while (1)
2488 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2489 if (r == 0)
2490 return r;
2491 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2493 eassert (errno != EBADF || fd < 0);
2494 return errno == EINPROGRESS ? 0 : r;
2499 /* Maximum number of bytes to read or write in a single system call.
2500 This works around a serious bug in Linux kernels before 2.6.16; see
2501 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2502 It's likely to work around similar bugs in other operating systems, so do it
2503 on all platforms. Round INT_MAX down to a page size, with the conservative
2504 assumption that page sizes are at most 2**18 bytes (any kernel with a
2505 page size larger than that shouldn't have the bug). */
2506 #ifndef MAX_RW_COUNT
2507 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2508 #endif
2510 /* Read from FD to a buffer BUF with size NBYTE.
2511 If interrupted, process any quits and pending signals immediately
2512 if INTERRUPTIBLE, and then retry the read unless quitting.
2513 Return the number of bytes read, which might be less than NBYTE.
2514 On error, set errno to a value other than EINTR, and return -1. */
2515 static ptrdiff_t
2516 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2518 ssize_t result;
2520 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2521 passes a size that large to emacs_read. */
2524 if (interruptible)
2525 maybe_quit ();
2526 result = read (fd, buf, nbyte);
2528 while (result < 0 && errno == EINTR);
2530 return result;
2533 /* Read from FD to a buffer BUF with size NBYTE.
2534 If interrupted, retry the read. Return the number of bytes read,
2535 which might be less than NBYTE. On error, set errno to a value
2536 other than EINTR, and return -1. */
2537 ptrdiff_t
2538 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2540 return emacs_intr_read (fd, buf, nbyte, false);
2543 /* Like emacs_read, but also process quits and pending signals. */
2544 ptrdiff_t
2545 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2547 return emacs_intr_read (fd, buf, nbyte, true);
2550 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2551 interrupted or if a partial write occurs. Process any quits
2552 immediately if INTERRUPTIBLE is positive, and process any pending
2553 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2554 of bytes written; if this is less than NBYTE, set errno to a value
2555 other than EINTR. */
2556 static ptrdiff_t
2557 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2558 int interruptible)
2560 ptrdiff_t bytes_written = 0;
2562 while (nbyte > 0)
2564 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2566 if (n < 0)
2568 if (errno != EINTR)
2569 break;
2571 if (interruptible)
2573 if (0 < interruptible)
2574 maybe_quit ();
2575 if (pending_signals)
2576 process_pending_signals ();
2579 else
2581 buf += n;
2582 nbyte -= n;
2583 bytes_written += n;
2587 return bytes_written;
2590 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2591 interrupted or if a partial write occurs. Do not process quits or
2592 pending signals. Return the number of bytes written, setting errno
2593 if this is less than NBYTE. */
2594 ptrdiff_t
2595 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2597 return emacs_full_write (fd, buf, nbyte, 0);
2600 /* Like emacs_write, but also process pending signals. */
2601 ptrdiff_t
2602 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2604 return emacs_full_write (fd, buf, nbyte, -1);
2607 /* Like emacs_write, but also process quits and pending signals. */
2608 ptrdiff_t
2609 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2611 return emacs_full_write (fd, buf, nbyte, 1);
2614 /* Write a diagnostic to standard error that contains MESSAGE and a
2615 string derived from errno. Preserve errno. Do not buffer stderr.
2616 Do not process quits or pending signals if interrupted. */
2617 void
2618 emacs_perror (char const *message)
2620 int err = errno;
2621 char const *error_string = emacs_strerror (err);
2622 char const *command = (initial_argv && initial_argv[0]
2623 ? initial_argv[0] : "emacs");
2624 /* Write it out all at once, if it's short; this is less likely to
2625 be interleaved with other output. */
2626 char buf[BUFSIZ];
2627 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2628 command, message, error_string);
2629 if (0 <= nbytes && nbytes < BUFSIZ)
2630 emacs_write (STDERR_FILENO, buf, nbytes);
2631 else
2633 emacs_write (STDERR_FILENO, command, strlen (command));
2634 emacs_write (STDERR_FILENO, ": ", 2);
2635 emacs_write (STDERR_FILENO, message, strlen (message));
2636 emacs_write (STDERR_FILENO, ": ", 2);
2637 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2638 emacs_write (STDERR_FILENO, "\n", 1);
2640 errno = err;
2643 /* Return a struct timeval that is roughly equivalent to T.
2644 Use the least timeval not less than T.
2645 Return an extremal value if the result would overflow. */
2646 struct timeval
2647 make_timeval (struct timespec t)
2649 struct timeval tv;
2650 tv.tv_sec = t.tv_sec;
2651 tv.tv_usec = t.tv_nsec / 1000;
2653 if (t.tv_nsec % 1000 != 0)
2655 if (tv.tv_usec < 999999)
2656 tv.tv_usec++;
2657 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2659 tv.tv_sec++;
2660 tv.tv_usec = 0;
2664 return tv;
2667 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2668 ATIME and MTIME, respectively.
2669 FD must be either negative -- in which case it is ignored --
2670 or a file descriptor that is open on FILE.
2671 If FD is nonnegative, then FILE can be NULL. */
2673 set_file_times (int fd, const char *filename,
2674 struct timespec atime, struct timespec mtime)
2676 struct timespec timespec[2];
2677 timespec[0] = atime;
2678 timespec[1] = mtime;
2679 return fdutimens (fd, filename, timespec);
2682 /* Like strsignal, except async-signal-safe, and this function typically
2683 returns a string in the C locale rather than the current locale. */
2684 char const *
2685 safe_strsignal (int code)
2687 char const *signame = 0;
2689 if (0 <= code && code < sys_siglist_entries)
2690 signame = sys_siglist[code];
2691 if (! signame)
2692 signame = "Unknown signal";
2694 return signame;
2697 #ifndef DOS_NT
2698 /* For make-serial-process */
2700 serial_open (Lisp_Object port)
2702 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2703 if (fd < 0)
2704 report_file_error ("Opening serial port", port);
2705 #ifdef TIOCEXCL
2706 ioctl (fd, TIOCEXCL, (char *) 0);
2707 #endif
2709 return fd;
2712 #if !defined (HAVE_CFMAKERAW)
2713 /* Workaround for targets which are missing cfmakeraw. */
2714 /* Pasted from man page. */
2715 static void
2716 cfmakeraw (struct termios *termios_p)
2718 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2719 termios_p->c_oflag &= ~OPOST;
2720 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2721 termios_p->c_cflag &= ~(CSIZE|PARENB);
2722 termios_p->c_cflag |= CS8;
2724 #endif /* !defined (HAVE_CFMAKERAW */
2726 #if !defined (HAVE_CFSETSPEED)
2727 /* Workaround for targets which are missing cfsetspeed. */
2728 static int
2729 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2731 return (cfsetispeed (termios_p, vitesse)
2732 + cfsetospeed (termios_p, vitesse));
2734 #endif
2736 /* For serial-process-configure */
2737 void
2738 serial_configure (struct Lisp_Process *p,
2739 Lisp_Object contact)
2741 Lisp_Object childp2 = Qnil;
2742 Lisp_Object tem = Qnil;
2743 struct termios attr;
2744 int err;
2745 char summary[4] = "???"; /* This usually becomes "8N1". */
2747 childp2 = Fcopy_sequence (p->childp);
2749 /* Read port attributes and prepare default configuration. */
2750 err = tcgetattr (p->outfd, &attr);
2751 if (err != 0)
2752 report_file_error ("Failed tcgetattr", Qnil);
2753 cfmakeraw (&attr);
2754 #if defined (CLOCAL)
2755 attr.c_cflag |= CLOCAL;
2756 #endif
2757 #if defined (CREAD)
2758 attr.c_cflag |= CREAD;
2759 #endif
2761 /* Configure speed. */
2762 if (!NILP (Fplist_member (contact, QCspeed)))
2763 tem = Fplist_get (contact, QCspeed);
2764 else
2765 tem = Fplist_get (p->childp, QCspeed);
2766 CHECK_NUMBER (tem);
2767 err = cfsetspeed (&attr, XINT (tem));
2768 if (err != 0)
2769 report_file_error ("Failed cfsetspeed", tem);
2770 childp2 = Fplist_put (childp2, QCspeed, tem);
2772 /* Configure bytesize. */
2773 if (!NILP (Fplist_member (contact, QCbytesize)))
2774 tem = Fplist_get (contact, QCbytesize);
2775 else
2776 tem = Fplist_get (p->childp, QCbytesize);
2777 if (NILP (tem))
2778 tem = make_number (8);
2779 CHECK_NUMBER (tem);
2780 if (XINT (tem) != 7 && XINT (tem) != 8)
2781 error (":bytesize must be nil (8), 7, or 8");
2782 summary[0] = XINT (tem) + '0';
2783 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2784 attr.c_cflag &= ~CSIZE;
2785 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2786 #else
2787 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2788 if (XINT (tem) != 8)
2789 error ("Bytesize cannot be changed");
2790 #endif
2791 childp2 = Fplist_put (childp2, QCbytesize, tem);
2793 /* Configure parity. */
2794 if (!NILP (Fplist_member (contact, QCparity)))
2795 tem = Fplist_get (contact, QCparity);
2796 else
2797 tem = Fplist_get (p->childp, QCparity);
2798 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2799 error (":parity must be nil (no parity), `even', or `odd'");
2800 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2801 attr.c_cflag &= ~(PARENB | PARODD);
2802 attr.c_iflag &= ~(IGNPAR | INPCK);
2803 if (NILP (tem))
2805 summary[1] = 'N';
2807 else if (EQ (tem, Qeven))
2809 summary[1] = 'E';
2810 attr.c_cflag |= PARENB;
2811 attr.c_iflag |= (IGNPAR | INPCK);
2813 else if (EQ (tem, Qodd))
2815 summary[1] = 'O';
2816 attr.c_cflag |= (PARENB | PARODD);
2817 attr.c_iflag |= (IGNPAR | INPCK);
2819 #else
2820 /* Don't error on no parity, which should be set by cfmakeraw. */
2821 if (!NILP (tem))
2822 error ("Parity cannot be configured");
2823 #endif
2824 childp2 = Fplist_put (childp2, QCparity, tem);
2826 /* Configure stopbits. */
2827 if (!NILP (Fplist_member (contact, QCstopbits)))
2828 tem = Fplist_get (contact, QCstopbits);
2829 else
2830 tem = Fplist_get (p->childp, QCstopbits);
2831 if (NILP (tem))
2832 tem = make_number (1);
2833 CHECK_NUMBER (tem);
2834 if (XINT (tem) != 1 && XINT (tem) != 2)
2835 error (":stopbits must be nil (1 stopbit), 1, or 2");
2836 summary[2] = XINT (tem) + '0';
2837 #if defined (CSTOPB)
2838 attr.c_cflag &= ~CSTOPB;
2839 if (XINT (tem) == 2)
2840 attr.c_cflag |= CSTOPB;
2841 #else
2842 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2843 if (XINT (tem) != 1)
2844 error ("Stopbits cannot be configured");
2845 #endif
2846 childp2 = Fplist_put (childp2, QCstopbits, tem);
2848 /* Configure flowcontrol. */
2849 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2850 tem = Fplist_get (contact, QCflowcontrol);
2851 else
2852 tem = Fplist_get (p->childp, QCflowcontrol);
2853 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2854 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2855 #if defined (CRTSCTS)
2856 attr.c_cflag &= ~CRTSCTS;
2857 #endif
2858 #if defined (CNEW_RTSCTS)
2859 attr.c_cflag &= ~CNEW_RTSCTS;
2860 #endif
2861 #if defined (IXON) && defined (IXOFF)
2862 attr.c_iflag &= ~(IXON | IXOFF);
2863 #endif
2864 if (NILP (tem))
2866 /* Already configured. */
2868 else if (EQ (tem, Qhw))
2870 #if defined (CRTSCTS)
2871 attr.c_cflag |= CRTSCTS;
2872 #elif defined (CNEW_RTSCTS)
2873 attr.c_cflag |= CNEW_RTSCTS;
2874 #else
2875 error ("Hardware flowcontrol (RTS/CTS) not supported");
2876 #endif
2878 else if (EQ (tem, Qsw))
2880 #if defined (IXON) && defined (IXOFF)
2881 attr.c_iflag |= (IXON | IXOFF);
2882 #else
2883 error ("Software flowcontrol (XON/XOFF) not supported");
2884 #endif
2886 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2888 /* Activate configuration. */
2889 err = tcsetattr (p->outfd, TCSANOW, &attr);
2890 if (err != 0)
2891 report_file_error ("Failed tcsetattr", Qnil);
2893 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2894 pset_childp (p, childp2);
2896 #endif /* not DOS_NT */
2898 /* System depended enumeration of and access to system processes a-la ps(1). */
2900 #ifdef HAVE_PROCFS
2902 /* Process enumeration and access via /proc. */
2904 Lisp_Object
2905 list_system_processes (void)
2907 Lisp_Object procdir, match, proclist, next;
2908 Lisp_Object tail;
2910 /* For every process on the system, there's a directory in the
2911 "/proc" pseudo-directory whose name is the numeric ID of that
2912 process. */
2913 procdir = build_string ("/proc");
2914 match = build_string ("[0-9]+");
2915 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2917 /* `proclist' gives process IDs as strings. Destructively convert
2918 each string into a number. */
2919 for (tail = proclist; CONSP (tail); tail = next)
2921 next = XCDR (tail);
2922 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2925 /* directory_files_internal returns the files in reverse order; undo
2926 that. */
2927 proclist = Fnreverse (proclist);
2928 return proclist;
2931 #elif defined DARWIN_OS || defined __FreeBSD__
2933 Lisp_Object
2934 list_system_processes (void)
2936 #ifdef DARWIN_OS
2937 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2938 #else
2939 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2940 #endif
2941 size_t len;
2942 struct kinfo_proc *procs;
2943 size_t i;
2945 Lisp_Object proclist = Qnil;
2947 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2948 return proclist;
2950 procs = xmalloc (len);
2951 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2953 xfree (procs);
2954 return proclist;
2957 len /= sizeof (struct kinfo_proc);
2958 for (i = 0; i < len; i++)
2960 #ifdef DARWIN_OS
2961 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2962 #else
2963 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2964 #endif
2967 xfree (procs);
2969 return proclist;
2972 /* The WINDOWSNT implementation is in w32.c.
2973 The MSDOS implementation is in dosfns.c. */
2974 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2976 Lisp_Object
2977 list_system_processes (void)
2979 return Qnil;
2982 #endif /* !defined (WINDOWSNT) */
2984 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2985 static struct timespec
2986 time_from_jiffies (unsigned long long tval, long hz)
2988 unsigned long long s = tval / hz;
2989 unsigned long long frac = tval % hz;
2990 int ns;
2992 if (TYPE_MAXIMUM (time_t) < s)
2993 time_overflow ();
2994 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2995 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2996 ns = frac * TIMESPEC_RESOLUTION / hz;
2997 else
2999 /* This is reachable only in the unlikely case that HZ * HZ
3000 exceeds ULLONG_MAX. It calculates an approximation that is
3001 guaranteed to be in range. */
3002 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3003 + (hz % TIMESPEC_RESOLUTION != 0));
3004 ns = frac / hz_per_ns;
3007 return make_timespec (s, ns);
3010 static Lisp_Object
3011 ltime_from_jiffies (unsigned long long tval, long hz)
3013 struct timespec t = time_from_jiffies (tval, hz);
3014 return make_lisp_time (t);
3017 static struct timespec
3018 get_up_time (void)
3020 FILE *fup;
3021 struct timespec up = make_timespec (0, 0);
3023 block_input ();
3024 fup = emacs_fopen ("/proc/uptime", "r");
3026 if (fup)
3028 unsigned long long upsec, upfrac, idlesec, idlefrac;
3029 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3031 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3032 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3033 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3034 == 4)
3036 if (TYPE_MAXIMUM (time_t) < upsec)
3038 upsec = TYPE_MAXIMUM (time_t);
3039 upfrac = TIMESPEC_RESOLUTION - 1;
3041 else
3043 int upfraclen = upfrac_end - upfrac_start;
3044 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3045 upfrac *= 10;
3046 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3047 upfrac /= 10;
3048 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3050 up = make_timespec (upsec, upfrac);
3052 fclose (fup);
3054 unblock_input ();
3056 return up;
3059 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3060 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3062 static Lisp_Object
3063 procfs_ttyname (int rdev)
3065 FILE *fdev;
3066 char name[PATH_MAX];
3068 block_input ();
3069 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3070 name[0] = 0;
3072 if (fdev)
3074 unsigned major;
3075 unsigned long minor_beg, minor_end;
3076 char minor[25]; /* 2 32-bit numbers + dash */
3077 char *endp;
3079 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
3081 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3082 && major == MAJOR (rdev))
3084 minor_beg = strtoul (minor, &endp, 0);
3085 if (*endp == '\0')
3086 minor_end = minor_beg;
3087 else if (*endp == '-')
3088 minor_end = strtoul (endp + 1, &endp, 0);
3089 else
3090 continue;
3092 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3094 sprintf (name + strlen (name), "%u", MINOR (rdev));
3095 break;
3099 fclose (fdev);
3101 unblock_input ();
3102 return build_string (name);
3105 static uintmax_t
3106 procfs_get_total_memory (void)
3108 FILE *fmem;
3109 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3110 int c;
3112 block_input ();
3113 fmem = emacs_fopen ("/proc/meminfo", "r");
3115 if (fmem)
3117 uintmax_t entry_value;
3118 bool done;
3121 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3123 case 1:
3124 retval = entry_value;
3125 done = 1;
3126 break;
3128 case 0:
3129 while ((c = getc (fmem)) != EOF && c != '\n')
3130 continue;
3131 done = c == EOF;
3132 break;
3134 default:
3135 done = 1;
3136 break;
3138 while (!done);
3140 fclose (fmem);
3142 unblock_input ();
3143 return retval;
3146 Lisp_Object
3147 system_process_attributes (Lisp_Object pid)
3149 char procfn[PATH_MAX], fn[PATH_MAX];
3150 struct stat st;
3151 struct passwd *pw;
3152 struct group *gr;
3153 long clocks_per_sec;
3154 char *procfn_end;
3155 char procbuf[1025], *p, *q;
3156 int fd;
3157 ssize_t nread;
3158 static char const default_cmd[] = "???";
3159 const char *cmd = default_cmd;
3160 int cmdsize = sizeof default_cmd - 1;
3161 char *cmdline = NULL;
3162 ptrdiff_t cmdline_size;
3163 char c;
3164 printmax_t proc_id;
3165 int ppid, pgrp, sess, tty, tpgid, thcount;
3166 uid_t uid;
3167 gid_t gid;
3168 unsigned long long u_time, s_time, cutime, cstime, start;
3169 long priority, niceness, rss;
3170 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3171 struct timespec tnow, tstart, tboot, telapsed, us_time;
3172 double pcpu, pmem;
3173 Lisp_Object attrs = Qnil;
3174 Lisp_Object decoded_cmd;
3175 ptrdiff_t count;
3177 CHECK_NUMBER_OR_FLOAT (pid);
3178 CONS_TO_INTEGER (pid, pid_t, proc_id);
3179 sprintf (procfn, "/proc/%"pMd, proc_id);
3180 if (stat (procfn, &st) < 0)
3181 return attrs;
3183 /* euid egid */
3184 uid = st.st_uid;
3185 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3186 block_input ();
3187 pw = getpwuid (uid);
3188 unblock_input ();
3189 if (pw)
3190 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3192 gid = st.st_gid;
3193 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3194 block_input ();
3195 gr = getgrgid (gid);
3196 unblock_input ();
3197 if (gr)
3198 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3200 count = SPECPDL_INDEX ();
3201 strcpy (fn, procfn);
3202 procfn_end = fn + strlen (fn);
3203 strcpy (procfn_end, "/stat");
3204 fd = emacs_open (fn, O_RDONLY, 0);
3205 if (fd < 0)
3206 nread = 0;
3207 else
3209 record_unwind_protect_int (close_file_unwind, fd);
3210 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3212 if (0 < nread)
3214 procbuf[nread] = '\0';
3215 p = procbuf;
3217 p = strchr (p, '(');
3218 if (p != NULL)
3220 q = strrchr (p + 1, ')');
3221 /* comm */
3222 if (q != NULL)
3224 cmd = p + 1;
3225 cmdsize = q - cmd;
3228 else
3229 q = NULL;
3230 /* Command name is encoded in locale-coding-system; decode it. */
3231 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3232 decoded_cmd = code_convert_string_norecord (cmd_str,
3233 Vlocale_coding_system, 0);
3234 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3236 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3237 utime stime cutime cstime priority nice thcount . start vsize rss */
3238 if (q
3239 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3240 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3241 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3242 &minflt, &cminflt, &majflt, &cmajflt,
3243 &u_time, &s_time, &cutime, &cstime,
3244 &priority, &niceness, &thcount, &start, &vsize, &rss)
3245 == 20))
3247 char state_str[2];
3248 state_str[0] = c;
3249 state_str[1] = '\0';
3250 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3251 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3252 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3253 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3254 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3255 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3256 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3257 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3258 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3259 attrs);
3260 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3261 attrs);
3262 clocks_per_sec = sysconf (_SC_CLK_TCK);
3263 if (clocks_per_sec < 0)
3264 clocks_per_sec = 100;
3265 attrs = Fcons (Fcons (Qutime,
3266 ltime_from_jiffies (u_time, clocks_per_sec)),
3267 attrs);
3268 attrs = Fcons (Fcons (Qstime,
3269 ltime_from_jiffies (s_time, clocks_per_sec)),
3270 attrs);
3271 attrs = Fcons (Fcons (Qtime,
3272 ltime_from_jiffies (s_time + u_time,
3273 clocks_per_sec)),
3274 attrs);
3275 attrs = Fcons (Fcons (Qcutime,
3276 ltime_from_jiffies (cutime, clocks_per_sec)),
3277 attrs);
3278 attrs = Fcons (Fcons (Qcstime,
3279 ltime_from_jiffies (cstime, clocks_per_sec)),
3280 attrs);
3281 attrs = Fcons (Fcons (Qctime,
3282 ltime_from_jiffies (cstime + cutime,
3283 clocks_per_sec)),
3284 attrs);
3285 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3286 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3287 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3288 attrs);
3289 tnow = current_timespec ();
3290 telapsed = get_up_time ();
3291 tboot = timespec_sub (tnow, telapsed);
3292 tstart = time_from_jiffies (start, clocks_per_sec);
3293 tstart = timespec_add (tboot, tstart);
3294 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3295 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3296 attrs);
3297 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3298 telapsed = timespec_sub (tnow, tstart);
3299 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3300 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3301 pcpu = timespectod (us_time) / timespectod (telapsed);
3302 if (pcpu > 1.0)
3303 pcpu = 1.0;
3304 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3305 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3306 if (pmem > 100)
3307 pmem = 100;
3308 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3311 unbind_to (count, Qnil);
3313 /* args */
3314 strcpy (procfn_end, "/cmdline");
3315 fd = emacs_open (fn, O_RDONLY, 0);
3316 if (fd >= 0)
3318 ptrdiff_t readsize, nread_incr;
3319 record_unwind_protect_int (close_file_unwind, fd);
3320 record_unwind_protect_nothing ();
3321 nread = cmdline_size = 0;
3325 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3326 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3328 /* Leave room even if every byte needs escaping below. */
3329 readsize = (cmdline_size >> 1) - nread;
3331 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3332 nread += max (0, nread_incr);
3334 while (nread_incr == readsize);
3336 if (nread)
3338 /* We don't want trailing null characters. */
3339 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3340 continue;
3342 /* Escape-quote whitespace and backslashes. */
3343 q = cmdline + cmdline_size;
3344 while (cmdline < p)
3346 char c = *--p;
3347 *--q = c ? c : ' ';
3348 if (c_isspace (c) || c == '\\')
3349 *--q = '\\';
3352 nread = cmdline + cmdline_size - q;
3355 if (!nread)
3357 nread = cmdsize + 2;
3358 cmdline_size = nread + 1;
3359 q = cmdline = xrealloc (cmdline, cmdline_size);
3360 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3361 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3363 /* Command line is encoded in locale-coding-system; decode it. */
3364 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3365 decoded_cmd = code_convert_string_norecord (cmd_str,
3366 Vlocale_coding_system, 0);
3367 unbind_to (count, Qnil);
3368 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3371 return attrs;
3374 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3376 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3377 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3378 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3379 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3380 #undef _FILE_OFFSET_BITS
3381 #else
3382 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3383 #endif
3385 #include <procfs.h>
3387 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3388 #define _FILE_OFFSET_BITS 64
3389 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3390 #endif
3391 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3393 Lisp_Object
3394 system_process_attributes (Lisp_Object pid)
3396 char procfn[PATH_MAX], fn[PATH_MAX];
3397 struct stat st;
3398 struct passwd *pw;
3399 struct group *gr;
3400 char *procfn_end;
3401 struct psinfo pinfo;
3402 int fd;
3403 ssize_t nread;
3404 printmax_t proc_id;
3405 uid_t uid;
3406 gid_t gid;
3407 Lisp_Object attrs = Qnil;
3408 Lisp_Object decoded_cmd;
3409 ptrdiff_t count;
3411 CHECK_NUMBER_OR_FLOAT (pid);
3412 CONS_TO_INTEGER (pid, pid_t, proc_id);
3413 sprintf (procfn, "/proc/%"pMd, proc_id);
3414 if (stat (procfn, &st) < 0)
3415 return attrs;
3417 /* euid egid */
3418 uid = st.st_uid;
3419 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3420 block_input ();
3421 pw = getpwuid (uid);
3422 unblock_input ();
3423 if (pw)
3424 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3426 gid = st.st_gid;
3427 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3428 block_input ();
3429 gr = getgrgid (gid);
3430 unblock_input ();
3431 if (gr)
3432 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3434 count = SPECPDL_INDEX ();
3435 strcpy (fn, procfn);
3436 procfn_end = fn + strlen (fn);
3437 strcpy (procfn_end, "/psinfo");
3438 fd = emacs_open (fn, O_RDONLY, 0);
3439 if (fd < 0)
3440 nread = 0;
3441 else
3443 record_unwind_protect_int (close_file_unwind, fd);
3444 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3447 if (nread == sizeof pinfo)
3449 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3450 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3451 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3454 char state_str[2];
3455 state_str[0] = pinfo.pr_lwp.pr_sname;
3456 state_str[1] = '\0';
3457 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3460 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3461 need to get a string from it. */
3463 /* FIXME: missing: Qtpgid */
3465 /* FIXME: missing:
3466 Qminflt
3467 Qmajflt
3468 Qcminflt
3469 Qcmajflt
3471 Qutime
3472 Qcutime
3473 Qstime
3474 Qcstime
3475 Are they available? */
3477 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3478 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3479 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3480 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3481 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3482 attrs);
3484 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3485 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3486 attrs);
3487 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3488 attrs);
3490 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3491 range 0 .. 2**15, representing 0.0 .. 1.0. */
3492 attrs = Fcons (Fcons (Qpcpu,
3493 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3494 attrs);
3495 attrs = Fcons (Fcons (Qpmem,
3496 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3497 attrs);
3499 AUTO_STRING (fname, pinfo.pr_fname);
3500 decoded_cmd = code_convert_string_norecord (fname,
3501 Vlocale_coding_system, 0);
3502 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3503 AUTO_STRING (psargs, pinfo.pr_psargs);
3504 decoded_cmd = code_convert_string_norecord (psargs,
3505 Vlocale_coding_system, 0);
3506 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3508 unbind_to (count, Qnil);
3509 return attrs;
3512 #elif defined __FreeBSD__
3514 static struct timespec
3515 timeval_to_timespec (struct timeval t)
3517 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3520 static Lisp_Object
3521 make_lisp_timeval (struct timeval t)
3523 return make_lisp_time (timeval_to_timespec (t));
3526 Lisp_Object
3527 system_process_attributes (Lisp_Object pid)
3529 int proc_id;
3530 int pagesize = getpagesize ();
3531 unsigned long npages;
3532 int fscale;
3533 struct passwd *pw;
3534 struct group *gr;
3535 char *ttyname;
3536 size_t len;
3537 char args[MAXPATHLEN];
3538 struct timespec t, now;
3540 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3541 struct kinfo_proc proc;
3542 size_t proclen = sizeof proc;
3544 Lisp_Object attrs = Qnil;
3545 Lisp_Object decoded_comm;
3547 CHECK_NUMBER_OR_FLOAT (pid);
3548 CONS_TO_INTEGER (pid, int, proc_id);
3549 mib[3] = proc_id;
3551 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3552 return attrs;
3554 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3556 block_input ();
3557 pw = getpwuid (proc.ki_uid);
3558 unblock_input ();
3559 if (pw)
3560 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3562 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3564 block_input ();
3565 gr = getgrgid (proc.ki_svgid);
3566 unblock_input ();
3567 if (gr)
3568 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3570 AUTO_STRING (comm, proc.ki_comm);
3571 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3573 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3575 char state[2] = {'\0', '\0'};
3576 switch (proc.ki_stat)
3578 case SRUN:
3579 state[0] = 'R';
3580 break;
3582 case SSLEEP:
3583 state[0] = 'S';
3584 break;
3586 case SLOCK:
3587 state[0] = 'D';
3588 break;
3590 case SZOMB:
3591 state[0] = 'Z';
3592 break;
3594 case SSTOP:
3595 state[0] = 'T';
3596 break;
3598 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3601 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3602 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3603 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3605 block_input ();
3606 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3607 unblock_input ();
3608 if (ttyname)
3609 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3611 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3612 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3613 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3614 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3615 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3617 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3618 attrs);
3619 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3620 attrs);
3621 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3622 timeval_to_timespec (proc.ki_rusage.ru_stime));
3623 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3625 attrs = Fcons (Fcons (Qcutime,
3626 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3627 attrs);
3628 attrs = Fcons (Fcons (Qcstime,
3629 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3630 attrs);
3631 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3632 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3633 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3635 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3636 attrs);
3637 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3638 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3639 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3640 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3641 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3642 attrs);
3644 now = current_timespec ();
3645 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3646 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3648 len = sizeof fscale;
3649 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3651 double pcpu;
3652 fixpt_t ccpu;
3653 len = sizeof ccpu;
3654 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3656 pcpu = (100.0 * proc.ki_pctcpu / fscale
3657 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3658 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3662 len = sizeof npages;
3663 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3665 double pmem = (proc.ki_flag & P_INMEM
3666 ? 100.0 * proc.ki_rssize / npages
3667 : 0);
3668 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3671 mib[2] = KERN_PROC_ARGS;
3672 len = MAXPATHLEN;
3673 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3675 int i;
3676 for (i = 0; i < len; i++)
3678 if (! args[i] && i < len - 1)
3679 args[i] = ' ';
3682 AUTO_STRING (comm, args);
3683 decoded_comm = code_convert_string_norecord (comm,
3684 Vlocale_coding_system, 0);
3686 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3689 return attrs;
3692 #elif defined DARWIN_OS
3694 static struct timespec
3695 timeval_to_timespec (struct timeval t)
3697 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3700 static Lisp_Object
3701 make_lisp_timeval (struct timeval t)
3703 return make_lisp_time (timeval_to_timespec (t));
3706 Lisp_Object
3707 system_process_attributes (Lisp_Object pid)
3709 int proc_id;
3710 int pagesize = getpagesize ();
3711 unsigned long npages;
3712 int fscale;
3713 struct passwd *pw;
3714 struct group *gr;
3715 char *ttyname;
3716 size_t len;
3717 char args[MAXPATHLEN];
3718 struct timeval starttime;
3719 struct timespec t, now;
3720 struct rusage *rusage;
3721 dev_t tdev;
3722 uid_t uid;
3723 gid_t gid;
3725 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3726 struct kinfo_proc proc;
3727 size_t proclen = sizeof proc;
3729 Lisp_Object attrs = Qnil;
3730 Lisp_Object decoded_comm;
3732 CHECK_NUMBER_OR_FLOAT (pid);
3733 CONS_TO_INTEGER (pid, int, proc_id);
3734 mib[3] = proc_id;
3736 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3737 return attrs;
3739 uid = proc.kp_eproc.e_ucred.cr_uid;
3740 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3742 block_input ();
3743 pw = getpwuid (uid);
3744 unblock_input ();
3745 if (pw)
3746 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3748 gid = proc.kp_eproc.e_pcred.p_svgid;
3749 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3751 block_input ();
3752 gr = getgrgid (gid);
3753 unblock_input ();
3754 if (gr)
3755 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3757 decoded_comm = (code_convert_string_norecord
3758 (build_unibyte_string (proc.kp_proc.p_comm),
3759 Vlocale_coding_system, 0));
3761 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3763 char state[2] = {'\0', '\0'};
3764 switch (proc.kp_proc.p_stat)
3766 case SRUN:
3767 state[0] = 'R';
3768 break;
3770 case SSLEEP:
3771 state[0] = 'S';
3772 break;
3774 case SZOMB:
3775 state[0] = 'Z';
3776 break;
3778 case SSTOP:
3779 state[0] = 'T';
3780 break;
3782 case SIDL:
3783 state[0] = 'I';
3784 break;
3786 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3789 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3790 attrs);
3791 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3792 attrs);
3794 tdev = proc.kp_eproc.e_tdev;
3795 block_input ();
3796 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3797 unblock_input ();
3798 if (ttyname)
3799 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3801 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3802 attrs);
3804 rusage = proc.kp_proc.p_ru;
3805 if (rusage)
3807 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3808 attrs);
3809 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3810 attrs);
3812 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3813 attrs);
3814 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3815 attrs);
3816 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3817 timeval_to_timespec (rusage->ru_stime));
3818 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3821 starttime = proc.kp_proc.p_starttime;
3822 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3823 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3825 now = current_timespec ();
3826 t = timespec_sub (now, timeval_to_timespec (starttime));
3827 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3829 return attrs;
3832 /* The WINDOWSNT implementation is in w32.c.
3833 The MSDOS implementation is in dosfns.c. */
3834 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3836 Lisp_Object
3837 system_process_attributes (Lisp_Object pid)
3839 return Qnil;
3842 #endif /* !defined (WINDOWSNT) */
3844 /* Wide character string collation. */
3846 #ifdef __STDC_ISO_10646__
3847 # include <wchar.h>
3848 # include <wctype.h>
3850 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3851 # include <locale.h>
3852 # endif
3853 # ifndef LC_COLLATE
3854 # define LC_COLLATE 0
3855 # endif
3856 # ifndef LC_COLLATE_MASK
3857 # define LC_COLLATE_MASK 0
3858 # endif
3859 # ifndef LC_CTYPE
3860 # define LC_CTYPE 0
3861 # endif
3862 # ifndef LC_CTYPE_MASK
3863 # define LC_CTYPE_MASK 0
3864 # endif
3866 # ifndef HAVE_NEWLOCALE
3867 # undef freelocale
3868 # undef locale_t
3869 # undef newlocale
3870 # undef wcscoll_l
3871 # undef towlower_l
3872 # define freelocale emacs_freelocale
3873 # define locale_t emacs_locale_t
3874 # define newlocale emacs_newlocale
3875 # define wcscoll_l emacs_wcscoll_l
3876 # define towlower_l emacs_towlower_l
3878 typedef char const *locale_t;
3880 static locale_t
3881 newlocale (int category_mask, char const *locale, locale_t loc)
3883 return locale;
3886 static void
3887 freelocale (locale_t loc)
3891 static char *
3892 emacs_setlocale (int category, char const *locale)
3894 # ifdef HAVE_SETLOCALE
3895 errno = 0;
3896 char *loc = setlocale (category, locale);
3897 if (loc || errno)
3898 return loc;
3899 errno = EINVAL;
3900 # else
3901 errno = ENOTSUP;
3902 # endif
3903 return 0;
3906 static int
3907 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3909 int result = 0;
3910 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3911 int err;
3913 if (! oldloc)
3914 err = errno;
3915 else
3917 USE_SAFE_ALLOCA;
3918 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3919 strcpy (oldcopy, oldloc);
3920 if (! emacs_setlocale (LC_COLLATE, loc))
3921 err = errno;
3922 else
3924 errno = 0;
3925 result = wcscoll (a, b);
3926 err = errno;
3927 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3928 err = errno;
3930 SAFE_FREE ();
3933 errno = err;
3934 return result;
3937 static wint_t
3938 towlower_l (wint_t wc, locale_t loc)
3940 wint_t result = wc;
3941 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3943 if (oldloc)
3945 USE_SAFE_ALLOCA;
3946 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3947 strcpy (oldcopy, oldloc);
3948 if (emacs_setlocale (LC_CTYPE, loc))
3950 result = towlower (wc);
3951 emacs_setlocale (LC_COLLATE, oldcopy);
3953 SAFE_FREE ();
3956 return result;
3958 # endif
3961 str_collate (Lisp_Object s1, Lisp_Object s2,
3962 Lisp_Object locale, Lisp_Object ignore_case)
3964 int res, err;
3965 ptrdiff_t len, i, i_byte;
3966 wchar_t *p1, *p2;
3968 USE_SAFE_ALLOCA;
3970 /* Convert byte stream to code points. */
3971 len = SCHARS (s1); i = i_byte = 0;
3972 SAFE_NALLOCA (p1, 1, len + 1);
3973 while (i < len)
3974 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3975 *(p1+len) = 0;
3977 len = SCHARS (s2); i = i_byte = 0;
3978 SAFE_NALLOCA (p2, 1, len + 1);
3979 while (i < len)
3980 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3981 *(p2+len) = 0;
3983 if (STRINGP (locale))
3985 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3986 SSDATA (locale), 0);
3987 if (!loc)
3988 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
3990 if (! NILP (ignore_case))
3991 for (int i = 1; i < 3; i++)
3993 wchar_t *p = (i == 1) ? p1 : p2;
3994 for (; *p; p++)
3995 *p = towlower_l (*p, loc);
3998 errno = 0;
3999 res = wcscoll_l (p1, p2, loc);
4000 err = errno;
4001 freelocale (loc);
4003 else
4005 if (! NILP (ignore_case))
4006 for (int i = 1; i < 3; i++)
4008 wchar_t *p = (i == 1) ? p1 : p2;
4009 for (; *p; p++)
4010 *p = towlower (*p);
4013 errno = 0;
4014 res = wcscoll (p1, p2);
4015 err = errno;
4017 # ifndef HAVE_NEWLOCALE
4018 if (err)
4019 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4020 # else
4021 if (err)
4022 error ("Invalid string for collation: %s", emacs_strerror (err));
4023 # endif
4025 SAFE_FREE ();
4026 return res;
4028 #endif /* __STDC_ISO_10646__ */
4030 #ifdef WINDOWSNT
4032 str_collate (Lisp_Object s1, Lisp_Object s2,
4033 Lisp_Object locale, Lisp_Object ignore_case)
4036 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4037 int res, err = errno;
4039 errno = 0;
4040 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4041 if (errno)
4042 error ("Invalid string for collation: %s", strerror (errno));
4044 errno = err;
4045 return res;
4047 #endif /* WINDOWSNT */