; Revert "Improve diff-mode navigation/manipulation"
[emacs.git] / src / sysdep.c
blob4316c21a1c774b0c368a0d1c1b0ce81b84319339
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 ((pid = waitpid (child, status, options)) < 0)
387 /* Check that CHILD is a child process that has not been reaped,
388 and that STATUS and OPTIONS are valid. Otherwise abort,
389 as continuing after this internal error could cause Emacs to
390 become confused and kill innocent-victim processes. */
391 if (errno != EINTR)
392 emacs_abort ();
394 /* Note: the MS-Windows emulation of waitpid calls QUIT
395 internally. */
396 if (interruptible)
397 QUIT;
400 /* If successful and status is requested, tell wait_reading_process_output
401 that it needs to wake up and look around. */
402 if (pid && status && input_available_clear_time)
403 *input_available_clear_time = make_timespec (0, 0);
405 return pid;
408 /* Wait for the subprocess with process id CHILD to terminate.
409 CHILD must be a child process that has not been reaped.
410 If STATUS is non-null, store the waitpid-style exit status into *STATUS
411 and tell wait_reading_process_output that it needs to look around.
412 If INTERRUPTIBLE, this function is interruptible by a signal. */
413 void
414 wait_for_termination (pid_t child, int *status, bool interruptible)
416 get_child_status (child, status, 0, interruptible);
419 /* Report whether the subprocess with process id CHILD has changed status.
420 Termination counts as a change of status.
421 CHILD must be a child process that has not been reaped.
422 If STATUS is non-null, store the waitpid-style exit status into *STATUS
423 and tell wait_reading_process_output that it needs to look around.
424 Use waitpid-style OPTIONS to check status, but do not wait.
426 Return CHILD if successful, 0 if no status is available because
427 the process's state has not changed. */
428 pid_t
429 child_status_changed (pid_t child, int *status, int options)
431 return get_child_status (child, status, WNOHANG | options, 0);
435 /* Set up the terminal at the other end of a pseudo-terminal that
436 we will be controlling an inferior through.
437 It should not echo or do line-editing, since that is done
438 in Emacs. No padding needed for insertion into an Emacs buffer. */
440 void
441 child_setup_tty (int out)
443 #ifndef WINDOWSNT
444 struct emacs_tty s;
446 emacs_get_tty (out, &s);
447 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
448 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
449 #ifdef NLDLY
450 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
451 Some versions of GNU Hurd do not have FFDLY? */
452 #ifdef FFDLY
453 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
454 /* No output delays */
455 #else
456 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
457 /* No output delays */
458 #endif
459 #endif
460 s.main.c_lflag &= ~ECHO; /* Disable echo */
461 s.main.c_lflag |= ISIG; /* Enable signals */
462 #ifdef IUCLC
463 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
464 #endif
465 #ifdef ISTRIP
466 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
467 #endif
468 #ifdef OLCUC
469 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
470 #endif
471 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
472 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
473 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
474 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
476 #ifdef HPUX
477 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
478 #endif /* HPUX */
480 #ifdef SIGNALS_VIA_CHARACTERS
481 /* the QUIT and INTR character are used in process_send_signal
482 so set them here to something useful. */
483 if (s.main.c_cc[VQUIT] == CDISABLE)
484 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
485 if (s.main.c_cc[VINTR] == CDISABLE)
486 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
487 #endif /* not SIGNALS_VIA_CHARACTERS */
489 #ifdef AIX
490 /* Also, PTY overloads NUL and BREAK.
491 don't ignore break, but don't signal either, so it looks like NUL. */
492 s.main.c_iflag &= ~IGNBRK;
493 s.main.c_iflag &= ~BRKINT;
494 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
495 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
496 would force it to 0377. That looks like duplicated code. */
497 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
498 #endif /* AIX */
500 /* We originally enabled ICANON (and set VEOF to 04), and then had
501 process.c send additional EOF chars to flush the output when faced
502 with long lines, but this leads to weird effects when the
503 subprocess has disabled ICANON and ends up seeing those spurious
504 extra EOFs. So we don't send EOFs any more in
505 process.c:send_process. First we tried to disable ICANON by
506 default, so if a subsprocess sets up ICANON, it's his problem (or
507 the Elisp package that talks to it) to deal with lines that are
508 too long. But this disables some features, such as the ability
509 to send EOF signals. So we re-enabled ICANON but there is no
510 more "send eof to flush" going on (which is wrong and unportable
511 in itself). The correct way to handle too much output is to
512 buffer what could not be written and then write it again when
513 select returns ok for writing. This has it own set of
514 problems. Write is now asynchronous, is that a problem? How much
515 do we buffer, and what do we do when that limit is reached? */
517 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
518 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
519 #if 0 /* These settings only apply to non-ICANON mode. */
520 s.main.c_cc[VMIN] = 1;
521 s.main.c_cc[VTIME] = 0;
522 #endif
524 emacs_set_tty (out, &s, 0);
525 #endif /* not WINDOWSNT */
527 #endif /* not MSDOS */
530 /* Record a signal code and the action for it. */
531 struct save_signal
533 int code;
534 struct sigaction action;
537 static void save_signal_handlers (struct save_signal *);
538 static void restore_signal_handlers (struct save_signal *);
540 /* Suspend the Emacs process; give terminal to its superior. */
542 void
543 sys_suspend (void)
545 #ifndef DOS_NT
546 kill (0, SIGTSTP);
547 #else
548 /* On a system where suspending is not implemented,
549 instead fork a subshell and let it talk directly to the terminal
550 while we wait. */
551 sys_subshell ();
553 #endif
556 /* Fork a subshell. */
558 void
559 sys_subshell (void)
561 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
562 #ifdef MSDOS
563 int st;
564 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
565 #else
566 char oldwd[MAX_UTF8_PATH];
567 #endif /* MSDOS */
568 #else /* !DOS_NT */
569 int status;
570 #endif
571 pid_t pid;
572 struct save_signal saved_handlers[5];
573 char *str = SSDATA (encode_current_directory ());
575 #ifdef DOS_NT
576 pid = 0;
577 #else
579 char *volatile str_volatile = str;
580 pid = vfork ();
581 str = str_volatile;
583 #endif
585 if (pid < 0)
586 error ("Can't spawn subshell");
588 saved_handlers[0].code = SIGINT;
589 saved_handlers[1].code = SIGQUIT;
590 saved_handlers[2].code = SIGTERM;
591 #ifdef USABLE_SIGIO
592 saved_handlers[3].code = SIGIO;
593 saved_handlers[4].code = 0;
594 #else
595 saved_handlers[3].code = 0;
596 #endif
598 #ifdef DOS_NT
599 save_signal_handlers (saved_handlers);
600 #endif
602 if (pid == 0)
604 const char *sh = 0;
606 #ifdef DOS_NT /* MW, Aug 1993 */
607 getcwd (oldwd, sizeof oldwd);
608 if (sh == 0)
609 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
610 #endif
611 if (sh == 0)
612 sh = egetenv ("SHELL");
613 if (sh == 0)
614 sh = "sh";
616 /* Use our buffer's default directory for the subshell. */
617 if (chdir (str) != 0)
619 #ifndef DOS_NT
620 emacs_perror (str);
621 _exit (EXIT_CANCELED);
622 #endif
625 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
627 char *epwd = getenv ("PWD");
628 char old_pwd[MAXPATHLEN+1+4];
630 /* If PWD is set, pass it with corrected value. */
631 if (epwd)
633 strcpy (old_pwd, epwd);
634 setenv ("PWD", str, 1);
636 st = system (sh);
637 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
638 if (epwd)
639 putenv (old_pwd); /* restore previous value */
641 #else /* not MSDOS */
642 #ifdef WINDOWSNT
643 /* Waits for process completion */
644 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
645 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
646 if (pid == -1)
647 write (1, "Can't execute subshell", 22);
648 #else /* not WINDOWSNT */
649 execlp (sh, sh, (char *) 0);
650 emacs_perror (sh);
651 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
652 #endif /* not WINDOWSNT */
653 #endif /* not MSDOS */
656 /* Do this now if we did not do it before. */
657 #ifndef MSDOS
658 save_signal_handlers (saved_handlers);
659 #endif
661 #ifndef DOS_NT
662 wait_for_termination (pid, &status, 0);
663 #endif
664 restore_signal_handlers (saved_handlers);
667 static void
668 save_signal_handlers (struct save_signal *saved_handlers)
670 while (saved_handlers->code)
672 struct sigaction action;
673 emacs_sigaction_init (&action, SIG_IGN);
674 sigaction (saved_handlers->code, &action, &saved_handlers->action);
675 saved_handlers++;
679 static void
680 restore_signal_handlers (struct save_signal *saved_handlers)
682 while (saved_handlers->code)
684 sigaction (saved_handlers->code, &saved_handlers->action, 0);
685 saved_handlers++;
689 #ifdef USABLE_SIGIO
690 static int old_fcntl_flags[FD_SETSIZE];
691 #endif
693 void
694 init_sigio (int fd)
696 #ifdef USABLE_SIGIO
697 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
698 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
699 interrupts_deferred = 0;
700 #endif
703 #ifndef DOS_NT
704 static void
705 reset_sigio (int fd)
707 #ifdef USABLE_SIGIO
708 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
709 #endif
711 #endif
713 void
714 request_sigio (void)
716 #ifdef USABLE_SIGIO
717 sigset_t unblocked;
719 if (noninteractive)
720 return;
722 sigemptyset (&unblocked);
723 # ifdef SIGWINCH
724 sigaddset (&unblocked, SIGWINCH);
725 # endif
726 sigaddset (&unblocked, SIGIO);
727 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
729 interrupts_deferred = 0;
730 #endif
733 void
734 unrequest_sigio (void)
736 #ifdef USABLE_SIGIO
737 sigset_t blocked;
739 if (noninteractive)
740 return;
742 sigemptyset (&blocked);
743 # ifdef SIGWINCH
744 sigaddset (&blocked, SIGWINCH);
745 # endif
746 sigaddset (&blocked, SIGIO);
747 pthread_sigmask (SIG_BLOCK, &blocked, 0);
748 interrupts_deferred = 1;
749 #endif
752 #ifndef MSDOS
753 /* Block SIGCHLD. */
755 void
756 block_child_signal (sigset_t *oldset)
758 sigset_t blocked;
759 sigemptyset (&blocked);
760 sigaddset (&blocked, SIGCHLD);
761 sigaddset (&blocked, SIGINT);
762 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
765 /* Unblock SIGCHLD. */
767 void
768 unblock_child_signal (sigset_t const *oldset)
770 pthread_sigmask (SIG_SETMASK, oldset, 0);
773 /* Block SIGINT. */
774 void
775 block_interrupt_signal (sigset_t *oldset)
777 sigset_t blocked;
778 sigemptyset (&blocked);
779 sigaddset (&blocked, SIGINT);
780 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
783 /* Restore previously saved signal mask. */
784 void
785 restore_signal_mask (sigset_t const *oldset)
787 pthread_sigmask (SIG_SETMASK, oldset, 0);
790 #endif /* !MSDOS */
792 /* Saving and restoring the process group of Emacs's terminal. */
794 /* The process group of which Emacs was a member when it initially
795 started.
797 If Emacs was in its own process group (i.e. inherited_pgroup ==
798 getpid ()), then we know we're running under a shell with job
799 control (Emacs would never be run as part of a pipeline).
800 Everything is fine.
802 If Emacs was not in its own process group, then we know we're
803 running under a shell (or a caller) that doesn't know how to
804 separate itself from Emacs (like sh). Emacs must be in its own
805 process group in order to receive SIGIO correctly. In this
806 situation, we put ourselves in our own pgroup, forcibly set the
807 tty's pgroup to our pgroup, and make sure to restore and reinstate
808 the tty's pgroup just like any other terminal setting. If
809 inherited_group was not the tty's pgroup, then we'll get a
810 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
811 it goes foreground in the future, which is what should happen. */
813 static pid_t inherited_pgroup;
815 void
816 init_foreground_group (void)
818 pid_t pgrp = getpgrp ();
819 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
822 /* Block and unblock SIGTTOU. */
824 void
825 block_tty_out_signal (sigset_t *oldset)
827 #ifdef SIGTTOU
828 sigset_t blocked;
829 sigemptyset (&blocked);
830 sigaddset (&blocked, SIGTTOU);
831 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
832 #endif
835 void
836 unblock_tty_out_signal (sigset_t const *oldset)
838 #ifdef SIGTTOU
839 pthread_sigmask (SIG_SETMASK, oldset, 0);
840 #endif
843 /* Safely set a controlling terminal FD's process group to PGID.
844 If we are not in the foreground already, POSIX requires tcsetpgrp
845 to deliver a SIGTTOU signal, which would stop us. This is an
846 annoyance, so temporarily ignore the signal.
848 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
849 skip all this unless SIGTTOU is defined. */
850 static void
851 tcsetpgrp_without_stopping (int fd, pid_t pgid)
853 #ifdef SIGTTOU
854 sigset_t oldset;
855 block_input ();
856 block_tty_out_signal (&oldset);
857 tcsetpgrp (fd, pgid);
858 unblock_tty_out_signal (&oldset);
859 unblock_input ();
860 #endif
863 /* Split off the foreground process group to Emacs alone. When we are
864 in the foreground, but not started in our own process group,
865 redirect the tty device handle FD to point to our own process
866 group. FD must be the file descriptor of the controlling tty. */
867 static void
868 narrow_foreground_group (int fd)
870 if (inherited_pgroup && setpgid (0, 0) == 0)
871 tcsetpgrp_without_stopping (fd, getpid ());
874 /* Set the tty to our original foreground group. */
875 static void
876 widen_foreground_group (int fd)
878 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
879 tcsetpgrp_without_stopping (fd, inherited_pgroup);
882 /* Getting and setting emacs_tty structures. */
884 /* Set *TC to the parameters associated with the terminal FD,
885 or clear it if the parameters are not available.
886 Return 0 on success, -1 on failure. */
888 emacs_get_tty (int fd, struct emacs_tty *settings)
890 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
891 memset (&settings->main, 0, sizeof (settings->main));
892 #ifdef DOS_NT
893 #ifdef WINDOWSNT
894 HANDLE h = (HANDLE)_get_osfhandle (fd);
895 DWORD console_mode;
897 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
899 settings->main = console_mode;
900 return 0;
902 #endif /* WINDOWSNT */
903 return -1;
904 #else /* !DOS_NT */
905 /* We have those nifty POSIX tcmumbleattr functions. */
906 return tcgetattr (fd, &settings->main);
907 #endif
911 /* Set the parameters of the tty on FD according to the contents of
912 *SETTINGS. If FLUSHP, discard input.
913 Return 0 if all went well, and -1 (setting errno) if anything failed. */
916 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
918 /* Set the primary parameters - baud rate, character size, etcetera. */
919 #ifdef DOS_NT
920 #ifdef WINDOWSNT
921 HANDLE h = (HANDLE)_get_osfhandle (fd);
923 if (h && h != INVALID_HANDLE_VALUE)
925 DWORD new_mode;
927 /* Assume the handle is open for input. */
928 if (flushp)
929 FlushConsoleInputBuffer (h);
930 new_mode = settings->main;
931 SetConsoleMode (h, new_mode);
933 #endif /* WINDOWSNT */
934 #else /* !DOS_NT */
935 int i;
936 /* We have those nifty POSIX tcmumbleattr functions.
937 William J. Smith <wjs@wiis.wang.com> writes:
938 "POSIX 1003.1 defines tcsetattr to return success if it was
939 able to perform any of the requested actions, even if some
940 of the requested actions could not be performed.
941 We must read settings back to ensure tty setup properly.
942 AIX requires this to keep tty from hanging occasionally." */
943 /* This make sure that we don't loop indefinitely in here. */
944 for (i = 0 ; i < 10 ; i++)
945 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
947 if (errno == EINTR)
948 continue;
949 else
950 return -1;
952 else
954 struct termios new;
956 memset (&new, 0, sizeof (new));
957 /* Get the current settings, and see if they're what we asked for. */
958 tcgetattr (fd, &new);
959 /* We cannot use memcmp on the whole structure here because under
960 * aix386 the termios structure has some reserved field that may
961 * not be filled in.
963 if ( new.c_iflag == settings->main.c_iflag
964 && new.c_oflag == settings->main.c_oflag
965 && new.c_cflag == settings->main.c_cflag
966 && new.c_lflag == settings->main.c_lflag
967 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
968 break;
969 else
970 continue;
972 #endif
974 /* We have survived the tempest. */
975 return 0;
980 #ifdef F_SETOWN
981 static int old_fcntl_owner[FD_SETSIZE];
982 #endif /* F_SETOWN */
984 /* This may also be defined in stdio,
985 but if so, this does no harm,
986 and using the same name avoids wasting the other one's space. */
988 #if defined (USG)
989 unsigned char _sobuf[BUFSIZ+8];
990 #else
991 char _sobuf[BUFSIZ];
992 #endif
994 /* Initialize the terminal mode on all tty devices that are currently
995 open. */
997 void
998 init_all_sys_modes (void)
1000 struct tty_display_info *tty;
1001 for (tty = tty_list; tty; tty = tty->next)
1002 init_sys_modes (tty);
1005 /* Initialize the terminal mode on the given tty device. */
1007 void
1008 init_sys_modes (struct tty_display_info *tty_out)
1010 struct emacs_tty tty;
1011 #ifndef DOS_NT
1012 Lisp_Object terminal;
1013 #endif
1015 Vtty_erase_char = Qnil;
1017 if (noninteractive)
1018 return;
1020 if (!tty_out->output)
1021 return; /* The tty is suspended. */
1023 narrow_foreground_group (fileno (tty_out->input));
1025 if (! tty_out->old_tty)
1026 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1028 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1030 tty = *tty_out->old_tty;
1032 #if !defined (DOS_NT)
1033 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1035 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1036 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1037 #ifdef INLCR /* I'm just being cautious,
1038 since I can't check how widespread INLCR is--rms. */
1039 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1040 #endif
1041 #ifdef ISTRIP
1042 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1043 #endif
1044 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1045 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1046 #ifdef IEXTEN
1047 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1048 #endif
1049 tty.main.c_lflag |= ISIG; /* Enable signals */
1050 if (tty_out->flow_control)
1052 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1053 #ifdef IXANY
1054 tty.main.c_iflag &= ~IXANY;
1055 #endif /* IXANY */
1057 else
1058 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1059 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1060 on output */
1061 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1062 #ifdef CS8
1063 if (tty_out->meta_key)
1065 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1066 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1068 #endif
1070 XSETTERMINAL(terminal, tty_out->terminal);
1071 if (!NILP (Fcontrolling_tty_p (terminal)))
1073 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1074 /* Set up C-g for both SIGQUIT and SIGINT.
1075 We don't know which we will get, but we handle both alike
1076 so which one it really gives us does not matter. */
1077 tty.main.c_cc[VQUIT] = quit_char;
1079 else
1081 /* We normally don't get interrupt or quit signals from tty
1082 devices other than our controlling terminal; therefore,
1083 we must handle C-g as normal input. Unfortunately, this
1084 means that the interrupt and quit feature must be
1085 disabled on secondary ttys, or we would not even see the
1086 keypress.
1088 Note that even though emacsclient could have special code
1089 to pass SIGINT to Emacs, we should _not_ enable
1090 interrupt/quit keys for emacsclient frames. This means
1091 that we can't break out of loops in C code from a
1092 secondary tty frame, but we can always decide what
1093 display the C-g came from, which is more important from a
1094 usability point of view. (Consider the case when two
1095 people work together using the same Emacs instance.) */
1096 tty.main.c_cc[VINTR] = CDISABLE;
1097 tty.main.c_cc[VQUIT] = CDISABLE;
1099 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1100 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1101 #ifdef VSWTCH
1102 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1103 of C-z */
1104 #endif /* VSWTCH */
1106 #ifdef VSUSP
1107 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1108 #endif /* VSUSP */
1109 #ifdef V_DSUSP
1110 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1111 #endif /* V_DSUSP */
1112 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1113 tty.main.c_cc[VDSUSP] = CDISABLE;
1114 #endif /* VDSUSP */
1115 #ifdef VLNEXT
1116 tty.main.c_cc[VLNEXT] = CDISABLE;
1117 #endif /* VLNEXT */
1118 #ifdef VREPRINT
1119 tty.main.c_cc[VREPRINT] = CDISABLE;
1120 #endif /* VREPRINT */
1121 #ifdef VWERASE
1122 tty.main.c_cc[VWERASE] = CDISABLE;
1123 #endif /* VWERASE */
1124 #ifdef VDISCARD
1125 tty.main.c_cc[VDISCARD] = CDISABLE;
1126 #endif /* VDISCARD */
1128 if (tty_out->flow_control)
1130 #ifdef VSTART
1131 tty.main.c_cc[VSTART] = '\021';
1132 #endif /* VSTART */
1133 #ifdef VSTOP
1134 tty.main.c_cc[VSTOP] = '\023';
1135 #endif /* VSTOP */
1137 else
1139 #ifdef VSTART
1140 tty.main.c_cc[VSTART] = CDISABLE;
1141 #endif /* VSTART */
1142 #ifdef VSTOP
1143 tty.main.c_cc[VSTOP] = CDISABLE;
1144 #endif /* VSTOP */
1147 #ifdef AIX
1148 tty.main.c_cc[VSTRT] = CDISABLE;
1149 tty.main.c_cc[VSTOP] = CDISABLE;
1150 tty.main.c_cc[VSUSP] = CDISABLE;
1151 tty.main.c_cc[VDSUSP] = CDISABLE;
1152 if (tty_out->flow_control)
1154 #ifdef VSTART
1155 tty.main.c_cc[VSTART] = '\021';
1156 #endif /* VSTART */
1157 #ifdef VSTOP
1158 tty.main.c_cc[VSTOP] = '\023';
1159 #endif /* VSTOP */
1161 /* Also, PTY overloads NUL and BREAK.
1162 don't ignore break, but don't signal either, so it looks like NUL.
1163 This really serves a purpose only if running in an XTERM window
1164 or via TELNET or the like, but does no harm elsewhere. */
1165 tty.main.c_iflag &= ~IGNBRK;
1166 tty.main.c_iflag &= ~BRKINT;
1167 #endif
1168 #endif /* not DOS_NT */
1170 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1171 if (!tty_out->term_initted)
1172 internal_terminal_init ();
1173 dos_ttraw (tty_out);
1174 #endif
1176 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1178 /* This code added to insure that, if flow-control is not to be used,
1179 we have an unlocked terminal at the start. */
1181 #ifdef TCXONC
1182 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1183 #endif
1184 #ifdef TIOCSTART
1185 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1186 #endif
1188 #if !defined (DOS_NT)
1189 #ifdef TCOON
1190 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1191 #endif
1192 #endif
1194 #ifdef F_GETOWN
1195 if (interrupt_input)
1197 old_fcntl_owner[fileno (tty_out->input)] =
1198 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1199 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1200 init_sigio (fileno (tty_out->input));
1201 #ifdef HAVE_GPM
1202 if (gpm_tty == tty_out)
1204 /* Arrange for mouse events to give us SIGIO signals. */
1205 fcntl (gpm_fd, F_SETOWN, getpid ());
1206 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1207 init_sigio (gpm_fd);
1209 #endif /* HAVE_GPM */
1211 #endif /* F_GETOWN */
1213 #ifdef _IOFBF
1214 /* This symbol is defined on recent USG systems.
1215 Someone says without this call USG won't really buffer the file
1216 even with a call to setbuf. */
1217 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1218 #else
1219 setbuf (tty_out->output, (char *) _sobuf);
1220 #endif
1222 if (tty_out->terminal->set_terminal_modes_hook)
1223 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1225 if (!tty_out->term_initted)
1227 Lisp_Object tail, frame;
1228 FOR_EACH_FRAME (tail, frame)
1230 /* XXX This needs to be revised. */
1231 if (FRAME_TERMCAP_P (XFRAME (frame))
1232 && FRAME_TTY (XFRAME (frame)) == tty_out)
1233 init_frame_faces (XFRAME (frame));
1237 if (tty_out->term_initted && no_redraw_on_reenter)
1239 /* We used to call "direct_output_forward_char(0)" here,
1240 but it's not clear why, since it may not do anything anyway. */
1242 else
1244 Lisp_Object tail, frame;
1245 frame_garbaged = 1;
1246 FOR_EACH_FRAME (tail, frame)
1248 if ((FRAME_TERMCAP_P (XFRAME (frame))
1249 || FRAME_MSDOS_P (XFRAME (frame)))
1250 && FRAME_TTY (XFRAME (frame)) == tty_out)
1251 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1255 tty_out->term_initted = 1;
1258 /* Return true if safe to use tabs in output.
1259 At the time this is called, init_sys_modes has not been done yet. */
1261 bool
1262 tabs_safe_p (int fd)
1264 struct emacs_tty etty;
1266 emacs_get_tty (fd, &etty);
1267 #ifndef DOS_NT
1268 #ifdef TABDLY
1269 return ((etty.main.c_oflag & TABDLY) != TAB3);
1270 #else /* not TABDLY */
1271 return 1;
1272 #endif /* not TABDLY */
1273 #else /* DOS_NT */
1274 return 0;
1275 #endif /* DOS_NT */
1278 /* Discard echoing. */
1280 void
1281 suppress_echo_on_tty (int fd)
1283 struct emacs_tty etty;
1285 emacs_get_tty (fd, &etty);
1286 #ifdef DOS_NT
1287 /* Set raw input mode. */
1288 etty.main = 0;
1289 #else
1290 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1291 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1292 #endif /* ! WINDOWSNT */
1293 emacs_set_tty (fd, &etty, 0);
1296 /* Get terminal size from system.
1297 Store number of lines into *HEIGHTP and width into *WIDTHP.
1298 We store 0 if there's no valid information. */
1300 void
1301 get_tty_size (int fd, int *widthp, int *heightp)
1303 #if defined TIOCGWINSZ
1305 /* BSD-style. */
1306 struct winsize size;
1308 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1309 *widthp = *heightp = 0;
1310 else
1312 *widthp = size.ws_col;
1313 *heightp = size.ws_row;
1316 #elif defined TIOCGSIZE
1318 /* SunOS - style. */
1319 struct ttysize size;
1321 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1322 *widthp = *heightp = 0;
1323 else
1325 *widthp = size.ts_cols;
1326 *heightp = size.ts_lines;
1329 #elif defined WINDOWSNT
1331 CONSOLE_SCREEN_BUFFER_INFO info;
1332 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1334 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1335 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1337 else
1338 *widthp = *heightp = 0;
1340 #elif defined MSDOS
1342 *widthp = ScreenCols ();
1343 *heightp = ScreenRows ();
1345 #else /* system doesn't know size */
1347 *widthp = 0;
1348 *heightp = 0;
1350 #endif
1353 /* Set the logical window size associated with descriptor FD
1354 to HEIGHT and WIDTH. This is used mainly with ptys.
1355 Return a negative value on failure. */
1358 set_window_size (int fd, int height, int width)
1360 #ifdef TIOCSWINSZ
1362 /* BSD-style. */
1363 struct winsize size;
1364 size.ws_row = height;
1365 size.ws_col = width;
1367 return ioctl (fd, TIOCSWINSZ, &size);
1369 #else
1370 #ifdef TIOCSSIZE
1372 /* SunOS - style. */
1373 struct ttysize size;
1374 size.ts_lines = height;
1375 size.ts_cols = width;
1377 return ioctl (fd, TIOCGSIZE, &size);
1378 #else
1379 return -1;
1380 #endif /* not SunOS-style */
1381 #endif /* not BSD-style */
1386 /* Prepare all terminal devices for exiting Emacs. */
1388 void
1389 reset_all_sys_modes (void)
1391 struct tty_display_info *tty;
1392 for (tty = tty_list; tty; tty = tty->next)
1393 reset_sys_modes (tty);
1396 /* Prepare the terminal for closing it; move the cursor to the
1397 bottom of the frame, turn off interrupt-driven I/O, etc. */
1399 void
1400 reset_sys_modes (struct tty_display_info *tty_out)
1402 if (noninteractive)
1404 fflush (stdout);
1405 return;
1407 if (!tty_out->term_initted)
1408 return;
1410 if (!tty_out->output)
1411 return; /* The tty is suspended. */
1413 /* Go to and clear the last line of the terminal. */
1415 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1417 /* Code adapted from tty_clear_end_of_line. */
1418 if (tty_out->TS_clr_line)
1420 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1422 else
1423 { /* have to do it the hard way */
1424 int i;
1425 tty_turn_off_insert (tty_out);
1427 for (i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1429 fputc (' ', tty_out->output);
1433 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1434 fflush (tty_out->output);
1436 if (tty_out->terminal->reset_terminal_modes_hook)
1437 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1439 /* Avoid possible loss of output when changing terminal modes. */
1440 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1441 continue;
1443 #ifndef DOS_NT
1444 #ifdef F_SETOWN
1445 if (interrupt_input)
1447 reset_sigio (fileno (tty_out->input));
1448 fcntl (fileno (tty_out->input), F_SETOWN,
1449 old_fcntl_owner[fileno (tty_out->input)]);
1451 #endif /* F_SETOWN */
1452 fcntl (fileno (tty_out->input), F_SETFL,
1453 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1454 #endif
1456 if (tty_out->old_tty)
1457 while (emacs_set_tty (fileno (tty_out->input),
1458 tty_out->old_tty, 0) < 0 && errno == EINTR)
1461 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1462 dos_ttcooked ();
1463 #endif
1465 widen_foreground_group (fileno (tty_out->input));
1468 #ifdef HAVE_PTYS
1470 /* Set up the proper status flags for use of a pty. */
1472 void
1473 setup_pty (int fd)
1475 /* I'm told that TOICREMOTE does not mean control chars
1476 "can't be sent" but rather that they don't have
1477 input-editing or signaling effects.
1478 That should be good, because we have other ways
1479 to do those things in Emacs.
1480 However, telnet mode seems not to work on 4.2.
1481 So TIOCREMOTE is turned off now. */
1483 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1484 will hang. In particular, the "timeout" feature (which
1485 causes a read to return if there is no data available)
1486 does this. Also it is known that telnet mode will hang
1487 in such a way that Emacs must be stopped (perhaps this
1488 is the same problem).
1490 If TIOCREMOTE is turned off, then there is a bug in
1491 hp-ux which sometimes loses data. Apparently the
1492 code which blocks the master process when the internal
1493 buffer fills up does not work. Other than this,
1494 though, everything else seems to work fine.
1496 Since the latter lossage is more benign, we may as well
1497 lose that way. -- cph */
1498 #ifdef FIONBIO
1499 #if defined (UNIX98_PTYS)
1501 int on = 1;
1502 ioctl (fd, FIONBIO, &on);
1504 #endif
1505 #endif
1507 #endif /* HAVE_PTYS */
1509 void
1510 init_system_name (void)
1512 if (!build_details)
1514 /* Set system-name to nil so that the build is deterministic. */
1515 Vsystem_name = Qnil;
1516 return;
1518 char *hostname_alloc = NULL;
1519 char *hostname;
1520 #ifndef HAVE_GETHOSTNAME
1521 struct utsname uts;
1522 uname (&uts);
1523 hostname = uts.nodename;
1524 #else /* HAVE_GETHOSTNAME */
1525 char hostname_buf[256];
1526 ptrdiff_t hostname_size = sizeof hostname_buf;
1527 hostname = hostname_buf;
1529 /* Try to get the host name; if the buffer is too short, try
1530 again. Apparently, the only indication gethostname gives of
1531 whether the buffer was large enough is the presence or absence
1532 of a '\0' in the string. Eech. */
1533 for (;;)
1535 gethostname (hostname, hostname_size - 1);
1536 hostname[hostname_size - 1] = '\0';
1538 /* Was the buffer large enough for the '\0'? */
1539 if (strlen (hostname) < hostname_size - 1)
1540 break;
1542 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1543 min (PTRDIFF_MAX, SIZE_MAX), 1);
1545 #endif /* HAVE_GETHOSTNAME */
1546 char *p;
1547 for (p = hostname; *p; p++)
1548 if (*p == ' ' || *p == '\t')
1549 *p = '-';
1550 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1551 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1552 Vsystem_name = build_string (hostname);
1553 xfree (hostname_alloc);
1556 sigset_t empty_mask;
1558 static struct sigaction process_fatal_action;
1560 static int
1561 emacs_sigaction_flags (void)
1563 #ifdef SA_RESTART
1564 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1565 'select') to reset their timeout on some platforms (e.g.,
1566 HP-UX 11), which is not what we want. Also, when Emacs is
1567 interactive, we don't want SA_RESTART because we need to poll
1568 for pending input so we need long-running syscalls to be interrupted
1569 after a signal that sets pending_signals.
1571 Non-interactive keyboard input goes through stdio, where we
1572 always want restartable system calls. */
1573 if (noninteractive)
1574 return SA_RESTART;
1575 #endif
1576 return 0;
1579 /* Store into *ACTION a signal action suitable for Emacs, with handler
1580 HANDLER. */
1581 void
1582 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1584 sigemptyset (&action->sa_mask);
1586 /* When handling a signal, block nonfatal system signals that are caught
1587 by Emacs. This makes race conditions less likely. */
1588 sigaddset (&action->sa_mask, SIGALRM);
1589 #ifdef SIGCHLD
1590 sigaddset (&action->sa_mask, SIGCHLD);
1591 #endif
1592 #ifdef SIGDANGER
1593 sigaddset (&action->sa_mask, SIGDANGER);
1594 #endif
1595 #ifdef PROFILER_CPU_SUPPORT
1596 sigaddset (&action->sa_mask, SIGPROF);
1597 #endif
1598 #ifdef SIGWINCH
1599 sigaddset (&action->sa_mask, SIGWINCH);
1600 #endif
1601 if (! noninteractive)
1603 sigaddset (&action->sa_mask, SIGINT);
1604 sigaddset (&action->sa_mask, SIGQUIT);
1605 #ifdef USABLE_SIGIO
1606 sigaddset (&action->sa_mask, SIGIO);
1607 #endif
1610 action->sa_handler = handler;
1611 action->sa_flags = emacs_sigaction_flags ();
1614 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1615 pthread_t main_thread_id;
1616 #endif
1618 /* SIG has arrived at the current process. Deliver it to the main
1619 thread, which should handle it with HANDLER. (Delivering the
1620 signal to some other thread might not work if the other thread is
1621 about to exit.)
1623 If we are on the main thread, handle the signal SIG with HANDLER.
1624 Otherwise, redirect the signal to the main thread, blocking it from
1625 this thread. POSIX says any thread can receive a signal that is
1626 associated with a process, process group, or asynchronous event.
1627 On GNU/Linux the main thread typically gets a process signal unless
1628 it's blocked, but other systems (FreeBSD at least) can deliver the
1629 signal to other threads. */
1630 void
1631 deliver_process_signal (int sig, signal_handler_t handler)
1633 /* Preserve errno, to avoid race conditions with signal handlers that
1634 might change errno. Races can occur even in single-threaded hosts. */
1635 int old_errno = errno;
1637 bool on_main_thread = true;
1638 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1639 if (! pthread_equal (pthread_self (), main_thread_id))
1641 sigset_t blocked;
1642 sigemptyset (&blocked);
1643 sigaddset (&blocked, sig);
1644 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1645 pthread_kill (main_thread_id, sig);
1646 on_main_thread = false;
1648 #endif
1649 if (on_main_thread)
1650 handler (sig);
1652 errno = old_errno;
1655 /* Static location to save a fatal backtrace in a thread.
1656 FIXME: If two subsidiary threads fail simultaneously, the resulting
1657 backtrace may be garbage. */
1658 enum { BACKTRACE_LIMIT_MAX = 500 };
1659 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1660 static int thread_backtrace_npointers;
1662 /* SIG has arrived at the current thread.
1663 If we are on the main thread, handle the signal SIG with HANDLER.
1664 Otherwise, this is a fatal error in the handling thread. */
1665 static void
1666 deliver_thread_signal (int sig, signal_handler_t handler)
1668 int old_errno = errno;
1670 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1671 if (! pthread_equal (pthread_self (), main_thread_id))
1673 thread_backtrace_npointers
1674 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1675 sigaction (sig, &process_fatal_action, 0);
1676 pthread_kill (main_thread_id, sig);
1678 /* Avoid further damage while the main thread is exiting. */
1679 while (1)
1680 sigsuspend (&empty_mask);
1682 #endif
1684 handler (sig);
1685 errno = old_errno;
1688 #if !HAVE_DECL_SYS_SIGLIST
1689 # undef sys_siglist
1690 # ifdef _sys_siglist
1691 # define sys_siglist _sys_siglist
1692 # elif HAVE_DECL___SYS_SIGLIST
1693 # define sys_siglist __sys_siglist
1694 # else
1695 # define sys_siglist my_sys_siglist
1696 static char const *sys_siglist[NSIG];
1697 # endif
1698 #endif
1700 #ifdef _sys_nsig
1701 # define sys_siglist_entries _sys_nsig
1702 #else
1703 # define sys_siglist_entries NSIG
1704 #endif
1706 /* Handle bus errors, invalid instruction, etc. */
1707 static void
1708 handle_fatal_signal (int sig)
1710 terminate_due_to_signal (sig, 40);
1713 static void
1714 deliver_fatal_signal (int sig)
1716 deliver_process_signal (sig, handle_fatal_signal);
1719 static void
1720 deliver_fatal_thread_signal (int sig)
1722 deliver_thread_signal (sig, handle_fatal_signal);
1725 static _Noreturn void
1726 handle_arith_signal (int sig)
1728 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1729 xsignal0 (Qarith_error);
1732 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1734 /* Alternate stack used by SIGSEGV handler below. */
1736 static unsigned char sigsegv_stack[SIGSTKSZ];
1739 /* Return true if SIGINFO indicates a stack overflow. */
1741 static bool
1742 stack_overflow (siginfo_t *siginfo)
1744 if (!attempt_stack_overflow_recovery)
1745 return false;
1747 /* In theory, a more-accurate heuristic can be obtained by using
1748 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1749 and pthread_attr_getguardsize to find the location and size of the
1750 guard area. In practice, though, these functions are so hard to
1751 use reliably that they're not worth bothering with. E.g., see:
1752 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1753 Other operating systems also have problems, e.g., Solaris's
1754 stack_violation function is tailor-made for this problem, but it
1755 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1757 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1758 candidate here. */
1760 if (!siginfo)
1761 return false;
1763 /* The faulting address. */
1764 char *addr = siginfo->si_addr;
1765 if (!addr)
1766 return false;
1768 /* The known top and bottom of the stack. The actual stack may
1769 extend a bit beyond these boundaries. */
1770 char *bot = stack_bottom;
1771 char *top = near_C_stack_top ();
1773 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1774 of the known stack divided by the size of the guard area past the
1775 end of the stack top. The heuristic is that a bad address is
1776 considered to be a stack overflow if it occurs within
1777 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1778 stack. This heuristic is not exactly correct but it's good
1779 enough in practice. */
1780 enum { LG_STACK_HEURISTIC = 8 };
1782 if (bot < top)
1783 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1784 else
1785 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1789 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1791 static void
1792 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1794 /* Hard GC error may lead to stack overflow caused by
1795 too nested calls to mark_object. No way to survive. */
1796 bool fatal = gc_in_progress;
1798 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1799 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1800 fatal = true;
1801 #endif
1803 if (!fatal && stack_overflow (siginfo))
1804 siglongjmp (return_to_command_loop, 1);
1806 /* Otherwise we can't do anything with this. */
1807 deliver_fatal_thread_signal (sig);
1810 /* Return true if we have successfully set up SIGSEGV handler on alternate
1811 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1813 static bool
1814 init_sigsegv (void)
1816 struct sigaction sa;
1817 stack_t ss;
1819 ss.ss_sp = sigsegv_stack;
1820 ss.ss_size = sizeof (sigsegv_stack);
1821 ss.ss_flags = 0;
1822 if (sigaltstack (&ss, NULL) < 0)
1823 return 0;
1825 sigfillset (&sa.sa_mask);
1826 sa.sa_sigaction = handle_sigsegv;
1827 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1828 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1831 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1833 static bool
1834 init_sigsegv (void)
1836 return 0;
1839 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1841 static void
1842 deliver_arith_signal (int sig)
1844 deliver_thread_signal (sig, handle_arith_signal);
1847 #ifdef SIGDANGER
1849 /* Handler for SIGDANGER. */
1850 static void
1851 handle_danger_signal (int sig)
1853 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1855 /* It might be unsafe to call do_auto_save now. */
1856 force_auto_save_soon ();
1859 static void
1860 deliver_danger_signal (int sig)
1862 deliver_process_signal (sig, handle_danger_signal);
1864 #endif
1866 /* Treat SIG as a terminating signal, unless it is already ignored and
1867 we are in --batch mode. Among other things, this makes nohup work. */
1868 static void
1869 maybe_fatal_sig (int sig)
1871 bool catch_sig = !noninteractive;
1872 if (!catch_sig)
1874 struct sigaction old_action;
1875 sigaction (sig, 0, &old_action);
1876 catch_sig = old_action.sa_handler != SIG_IGN;
1878 if (catch_sig)
1879 sigaction (sig, &process_fatal_action, 0);
1882 void
1883 init_signals (bool dumping)
1885 struct sigaction thread_fatal_action;
1886 struct sigaction action;
1888 sigemptyset (&empty_mask);
1890 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1891 main_thread_id = pthread_self ();
1892 #endif
1894 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1895 if (! initialized)
1897 sys_siglist[SIGABRT] = "Aborted";
1898 # ifdef SIGAIO
1899 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1900 # endif
1901 sys_siglist[SIGALRM] = "Alarm clock";
1902 # ifdef SIGBUS
1903 sys_siglist[SIGBUS] = "Bus error";
1904 # endif
1905 # ifdef SIGCHLD
1906 sys_siglist[SIGCHLD] = "Child status changed";
1907 # endif
1908 # ifdef SIGCONT
1909 sys_siglist[SIGCONT] = "Continued";
1910 # endif
1911 # ifdef SIGDANGER
1912 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1913 # endif
1914 # ifdef SIGDGNOTIFY
1915 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1916 # endif
1917 # ifdef SIGEMT
1918 sys_siglist[SIGEMT] = "Emulation trap";
1919 # endif
1920 sys_siglist[SIGFPE] = "Arithmetic exception";
1921 # ifdef SIGFREEZE
1922 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1923 # endif
1924 # ifdef SIGGRANT
1925 sys_siglist[SIGGRANT] = "Monitor mode granted";
1926 # endif
1927 sys_siglist[SIGHUP] = "Hangup";
1928 sys_siglist[SIGILL] = "Illegal instruction";
1929 sys_siglist[SIGINT] = "Interrupt";
1930 # ifdef SIGIO
1931 sys_siglist[SIGIO] = "I/O possible";
1932 # endif
1933 # ifdef SIGIOINT
1934 sys_siglist[SIGIOINT] = "I/O intervention required";
1935 # endif
1936 # ifdef SIGIOT
1937 sys_siglist[SIGIOT] = "IOT trap";
1938 # endif
1939 sys_siglist[SIGKILL] = "Killed";
1940 # ifdef SIGLOST
1941 sys_siglist[SIGLOST] = "Resource lost";
1942 # endif
1943 # ifdef SIGLWP
1944 sys_siglist[SIGLWP] = "SIGLWP";
1945 # endif
1946 # ifdef SIGMSG
1947 sys_siglist[SIGMSG] = "Monitor mode data available";
1948 # endif
1949 # ifdef SIGPHONE
1950 sys_siglist[SIGWIND] = "SIGPHONE";
1951 # endif
1952 sys_siglist[SIGPIPE] = "Broken pipe";
1953 # ifdef SIGPOLL
1954 sys_siglist[SIGPOLL] = "Pollable event occurred";
1955 # endif
1956 # ifdef SIGPROF
1957 sys_siglist[SIGPROF] = "Profiling timer expired";
1958 # endif
1959 # ifdef SIGPTY
1960 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1961 # endif
1962 # ifdef SIGPWR
1963 sys_siglist[SIGPWR] = "Power-fail restart";
1964 # endif
1965 sys_siglist[SIGQUIT] = "Quit";
1966 # ifdef SIGRETRACT
1967 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1968 # endif
1969 # ifdef SIGSAK
1970 sys_siglist[SIGSAK] = "Secure attention";
1971 # endif
1972 sys_siglist[SIGSEGV] = "Segmentation violation";
1973 # ifdef SIGSOUND
1974 sys_siglist[SIGSOUND] = "Sound completed";
1975 # endif
1976 # ifdef SIGSTOP
1977 sys_siglist[SIGSTOP] = "Stopped (signal)";
1978 # endif
1979 # ifdef SIGSTP
1980 sys_siglist[SIGSTP] = "Stopped (user)";
1981 # endif
1982 # ifdef SIGSYS
1983 sys_siglist[SIGSYS] = "Bad argument to system call";
1984 # endif
1985 sys_siglist[SIGTERM] = "Terminated";
1986 # ifdef SIGTHAW
1987 sys_siglist[SIGTHAW] = "SIGTHAW";
1988 # endif
1989 # ifdef SIGTRAP
1990 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1991 # endif
1992 # ifdef SIGTSTP
1993 sys_siglist[SIGTSTP] = "Stopped (user)";
1994 # endif
1995 # ifdef SIGTTIN
1996 sys_siglist[SIGTTIN] = "Stopped (tty input)";
1997 # endif
1998 # ifdef SIGTTOU
1999 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2000 # endif
2001 # ifdef SIGURG
2002 sys_siglist[SIGURG] = "Urgent I/O condition";
2003 # endif
2004 # ifdef SIGUSR1
2005 sys_siglist[SIGUSR1] = "User defined signal 1";
2006 # endif
2007 # ifdef SIGUSR2
2008 sys_siglist[SIGUSR2] = "User defined signal 2";
2009 # endif
2010 # ifdef SIGVTALRM
2011 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2012 # endif
2013 # ifdef SIGWAITING
2014 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2015 # endif
2016 # ifdef SIGWINCH
2017 sys_siglist[SIGWINCH] = "Window size changed";
2018 # endif
2019 # ifdef SIGWIND
2020 sys_siglist[SIGWIND] = "SIGWIND";
2021 # endif
2022 # ifdef SIGXCPU
2023 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2024 # endif
2025 # ifdef SIGXFSZ
2026 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2027 # endif
2029 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2031 /* Don't alter signal handlers if dumping. On some machines,
2032 changing signal handlers sets static data that would make signals
2033 fail to work right when the dumped Emacs is run. */
2034 if (dumping)
2035 return;
2037 sigfillset (&process_fatal_action.sa_mask);
2038 process_fatal_action.sa_handler = deliver_fatal_signal;
2039 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2041 sigfillset (&thread_fatal_action.sa_mask);
2042 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2043 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2045 /* SIGINT may need special treatment on MS-Windows. See
2046 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2047 Please update the doc of kill-emacs, kill-emacs-hook, and
2048 NEWS if you change this. */
2050 maybe_fatal_sig (SIGHUP);
2051 maybe_fatal_sig (SIGINT);
2052 maybe_fatal_sig (SIGTERM);
2054 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2055 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2056 to behave more like typical batch applications do. */
2057 if (! noninteractive)
2058 signal (SIGPIPE, SIG_IGN);
2060 sigaction (SIGQUIT, &process_fatal_action, 0);
2061 sigaction (SIGILL, &thread_fatal_action, 0);
2062 sigaction (SIGTRAP, &thread_fatal_action, 0);
2064 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2065 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2066 interpreter's floating point operations, so treat SIGFPE as an
2067 arith-error if it arises in the main thread. */
2068 if (IEEE_FLOATING_POINT)
2069 sigaction (SIGFPE, &thread_fatal_action, 0);
2070 else
2072 emacs_sigaction_init (&action, deliver_arith_signal);
2073 sigaction (SIGFPE, &action, 0);
2076 #ifdef SIGUSR1
2077 add_user_signal (SIGUSR1, "sigusr1");
2078 #endif
2079 #ifdef SIGUSR2
2080 add_user_signal (SIGUSR2, "sigusr2");
2081 #endif
2082 sigaction (SIGABRT, &thread_fatal_action, 0);
2083 #ifdef SIGPRE
2084 sigaction (SIGPRE, &thread_fatal_action, 0);
2085 #endif
2086 #ifdef SIGORE
2087 sigaction (SIGORE, &thread_fatal_action, 0);
2088 #endif
2089 #ifdef SIGUME
2090 sigaction (SIGUME, &thread_fatal_action, 0);
2091 #endif
2092 #ifdef SIGDLK
2093 sigaction (SIGDLK, &process_fatal_action, 0);
2094 #endif
2095 #ifdef SIGCPULIM
2096 sigaction (SIGCPULIM, &process_fatal_action, 0);
2097 #endif
2098 #ifdef SIGIOT
2099 sigaction (SIGIOT, &thread_fatal_action, 0);
2100 #endif
2101 #ifdef SIGEMT
2102 sigaction (SIGEMT, &thread_fatal_action, 0);
2103 #endif
2104 #ifdef SIGBUS
2105 sigaction (SIGBUS, &thread_fatal_action, 0);
2106 #endif
2107 if (!init_sigsegv ())
2108 sigaction (SIGSEGV, &thread_fatal_action, 0);
2109 #ifdef SIGSYS
2110 sigaction (SIGSYS, &thread_fatal_action, 0);
2111 #endif
2112 sigaction (SIGTERM, &process_fatal_action, 0);
2113 #ifdef SIGPROF
2114 signal (SIGPROF, SIG_IGN);
2115 #endif
2116 #ifdef SIGVTALRM
2117 sigaction (SIGVTALRM, &process_fatal_action, 0);
2118 #endif
2119 #ifdef SIGXCPU
2120 sigaction (SIGXCPU, &process_fatal_action, 0);
2121 #endif
2122 #ifdef SIGXFSZ
2123 sigaction (SIGXFSZ, &process_fatal_action, 0);
2124 #endif
2126 #ifdef SIGDANGER
2127 /* This just means available memory is getting low. */
2128 emacs_sigaction_init (&action, deliver_danger_signal);
2129 sigaction (SIGDANGER, &action, 0);
2130 #endif
2132 /* AIX-specific signals. */
2133 #ifdef SIGGRANT
2134 sigaction (SIGGRANT, &process_fatal_action, 0);
2135 #endif
2136 #ifdef SIGMIGRATE
2137 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2138 #endif
2139 #ifdef SIGMSG
2140 sigaction (SIGMSG, &process_fatal_action, 0);
2141 #endif
2142 #ifdef SIGRETRACT
2143 sigaction (SIGRETRACT, &process_fatal_action, 0);
2144 #endif
2145 #ifdef SIGSAK
2146 sigaction (SIGSAK, &process_fatal_action, 0);
2147 #endif
2148 #ifdef SIGSOUND
2149 sigaction (SIGSOUND, &process_fatal_action, 0);
2150 #endif
2151 #ifdef SIGTALRM
2152 sigaction (SIGTALRM, &thread_fatal_action, 0);
2153 #endif
2156 #ifndef HAVE_RANDOM
2157 #ifdef random
2158 #define HAVE_RANDOM
2159 #endif
2160 #endif
2162 /* Figure out how many bits the system's random number generator uses.
2163 `random' and `lrand48' are assumed to return 31 usable bits.
2164 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2165 so we'll shift it and treat it like the 15-bit USG `rand'. */
2167 #ifndef RAND_BITS
2168 # ifdef HAVE_RANDOM
2169 # define RAND_BITS 31
2170 # else /* !HAVE_RANDOM */
2171 # ifdef HAVE_LRAND48
2172 # define RAND_BITS 31
2173 # define random lrand48
2174 # else /* !HAVE_LRAND48 */
2175 # define RAND_BITS 15
2176 # if RAND_MAX == 32767
2177 # define random rand
2178 # else /* RAND_MAX != 32767 */
2179 # if RAND_MAX == 2147483647
2180 # define random() (rand () >> 16)
2181 # else /* RAND_MAX != 2147483647 */
2182 # ifdef USG
2183 # define random rand
2184 # else
2185 # define random() (rand () >> 16)
2186 # endif /* !USG */
2187 # endif /* RAND_MAX != 2147483647 */
2188 # endif /* RAND_MAX != 32767 */
2189 # endif /* !HAVE_LRAND48 */
2190 # endif /* !HAVE_RANDOM */
2191 #endif /* !RAND_BITS */
2193 #ifdef HAVE_RANDOM
2194 typedef unsigned int random_seed;
2195 static void set_random_seed (random_seed arg) { srandom (arg); }
2196 #elif defined HAVE_LRAND48
2197 /* Although srand48 uses a long seed, this is unsigned long to avoid
2198 undefined behavior on signed integer overflow in init_random. */
2199 typedef unsigned long int random_seed;
2200 static void set_random_seed (random_seed arg) { srand48 (arg); }
2201 #else
2202 typedef unsigned int random_seed;
2203 static void set_random_seed (random_seed arg) { srand (arg); }
2204 #endif
2206 void
2207 seed_random (void *seed, ptrdiff_t seed_size)
2209 random_seed arg = 0;
2210 unsigned char *argp = (unsigned char *) &arg;
2211 unsigned char *seedp = seed;
2212 for (ptrdiff_t i = 0; i < seed_size; i++)
2213 argp[i % sizeof arg] ^= seedp[i];
2214 set_random_seed (arg);
2217 void
2218 init_random (void)
2220 random_seed v;
2221 bool success = false;
2223 /* First, try seeding the PRNG from the operating system's entropy
2224 source. This approach is both fast and secure. */
2225 #ifdef WINDOWSNT
2226 success = w32_init_random (&v, sizeof v) == 0;
2227 #else
2228 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2229 if (0 <= fd)
2231 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2232 close (fd);
2234 #endif
2236 /* If that didn't work, try using GnuTLS, which is secure, but on
2237 some systems, can be somewhat slow. */
2238 if (!success)
2239 success = EQ (emacs_gnutls_global_init (), Qt)
2240 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2242 /* If _that_ didn't work, just use the current time value and PID.
2243 It's at least better than XKCD 221. */
2244 if (!success)
2246 struct timespec t = current_timespec ();
2247 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2250 set_random_seed (v);
2254 * Return a nonnegative random integer out of whatever we've got.
2255 * It contains enough bits to make a random (signed) Emacs fixnum.
2256 * This suffices even for a 64-bit architecture with a 15-bit rand.
2258 EMACS_INT
2259 get_random (void)
2261 EMACS_UINT val = 0;
2262 int i;
2263 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2264 val = (random () ^ (val << RAND_BITS)
2265 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2266 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2267 return val & INTMASK;
2270 #ifndef HAVE_SNPRINTF
2271 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2273 snprintf (char *buf, size_t bufsize, char const *format, ...)
2275 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2276 ptrdiff_t nbytes = size - 1;
2277 va_list ap;
2279 if (size)
2281 va_start (ap, format);
2282 nbytes = doprnt (buf, size, format, 0, ap);
2283 va_end (ap);
2286 if (nbytes == size - 1)
2288 /* Calculate the length of the string that would have been created
2289 had the buffer been large enough. */
2290 char stackbuf[4000];
2291 char *b = stackbuf;
2292 ptrdiff_t bsize = sizeof stackbuf;
2293 va_start (ap, format);
2294 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2295 va_end (ap);
2296 if (b != stackbuf)
2297 xfree (b);
2300 if (INT_MAX < nbytes)
2302 #ifdef EOVERFLOW
2303 errno = EOVERFLOW;
2304 #else
2305 errno = EDOM;
2306 #endif
2307 return -1;
2309 return nbytes;
2311 #endif
2313 /* If a backtrace is available, output the top lines of it to stderr.
2314 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2315 This function may be called from a signal handler, so it should
2316 not invoke async-unsafe functions like malloc.
2318 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2319 but do not output anything. This avoids some problems that can
2320 otherwise occur if the malloc arena is corrupted before 'backtrace'
2321 is called, since 'backtrace' may call malloc if the tables are not
2322 initialized.
2324 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2325 fatal error has occurred in some other thread; generate a thread
2326 backtrace instead, ignoring BACKTRACE_LIMIT. */
2327 void
2328 emacs_backtrace (int backtrace_limit)
2330 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2331 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2332 void *buffer;
2333 int npointers;
2335 if (thread_backtrace_npointers)
2337 buffer = thread_backtrace_buffer;
2338 npointers = thread_backtrace_npointers;
2340 else
2342 buffer = main_backtrace_buffer;
2344 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2345 if (bounded_limit < 0)
2347 backtrace (buffer, 1);
2348 return;
2351 npointers = backtrace (buffer, bounded_limit + 1);
2354 if (npointers)
2356 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2357 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2358 if (bounded_limit < npointers)
2359 emacs_write (STDERR_FILENO, "...\n", 4);
2363 #ifndef HAVE_NTGUI
2364 void
2365 emacs_abort (void)
2367 terminate_due_to_signal (SIGABRT, 40);
2369 #endif
2371 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2372 Use binary I/O on systems that care about text vs binary I/O.
2373 Arrange for subprograms to not inherit the file descriptor.
2374 Prefer a method that is multithread-safe, if available.
2375 Do not fail merely because the open was interrupted by a signal.
2376 Allow the user to quit. */
2379 emacs_open (const char *file, int oflags, int mode)
2381 int fd;
2382 if (! (oflags & O_TEXT))
2383 oflags |= O_BINARY;
2384 oflags |= O_CLOEXEC;
2385 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2386 QUIT;
2387 if (! O_CLOEXEC && 0 <= fd)
2388 fcntl (fd, F_SETFD, FD_CLOEXEC);
2389 return fd;
2392 /* Open FILE as a stream for Emacs use, with mode MODE.
2393 Act like emacs_open with respect to threads, signals, and quits. */
2395 FILE *
2396 emacs_fopen (char const *file, char const *mode)
2398 int fd, omode, oflags;
2399 int bflag = 0;
2400 char const *m = mode;
2402 switch (*m++)
2404 case 'r': omode = O_RDONLY; oflags = 0; break;
2405 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2406 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2407 default: emacs_abort ();
2410 while (*m)
2411 switch (*m++)
2413 case '+': omode = O_RDWR; break;
2414 case 't': bflag = O_TEXT; break;
2415 default: /* Ignore. */ break;
2418 fd = emacs_open (file, omode | oflags | bflag, 0666);
2419 return fd < 0 ? 0 : fdopen (fd, mode);
2422 /* Create a pipe for Emacs use. */
2425 emacs_pipe (int fd[2])
2427 #ifdef MSDOS
2428 return pipe (fd);
2429 #else /* !MSDOS */
2430 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2431 if (! O_CLOEXEC && result == 0)
2433 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2434 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2436 return result;
2437 #endif /* !MSDOS */
2440 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2441 For the background behind this mess, please see Austin Group defect 529
2442 <http://austingroupbugs.net/view.php?id=529>. */
2444 #ifndef POSIX_CLOSE_RESTART
2445 # define POSIX_CLOSE_RESTART 1
2446 static int
2447 posix_close (int fd, int flag)
2449 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2450 eassert (flag == POSIX_CLOSE_RESTART);
2452 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2453 on a system that does not define POSIX_CLOSE_RESTART.
2455 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2456 closed, and retrying the close could inadvertently close a file
2457 descriptor allocated by some other thread. In other systems
2458 (e.g., HP/UX) FD is not closed. And in still other systems
2459 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2460 multithreaded program there can be no way to tell.
2462 So, in this case, pretend that the close succeeded. This works
2463 well on systems like GNU/Linux that close FD. Although it may
2464 leak a file descriptor on other systems, the leak is unlikely and
2465 it's better to leak than to close a random victim. */
2466 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2468 #endif
2470 /* Close FD, retrying if interrupted. If successful, return 0;
2471 otherwise, return -1 and set errno to a non-EINTR value. Consider
2472 an EINPROGRESS error to be successful, as that's merely a signal
2473 arriving. FD is always closed when this function returns, even
2474 when it returns -1.
2476 Do not call this function if FD is nonnegative and might already be closed,
2477 as that might close an innocent victim opened by some other thread. */
2480 emacs_close (int fd)
2482 while (1)
2484 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2485 if (r == 0)
2486 return r;
2487 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2489 eassert (errno != EBADF || fd < 0);
2490 return errno == EINPROGRESS ? 0 : r;
2495 /* Maximum number of bytes to read or write in a single system call.
2496 This works around a serious bug in Linux kernels before 2.6.16; see
2497 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2498 It's likely to work around similar bugs in other operating systems, so do it
2499 on all platforms. Round INT_MAX down to a page size, with the conservative
2500 assumption that page sizes are at most 2**18 bytes (any kernel with a
2501 page size larger than that shouldn't have the bug). */
2502 #ifndef MAX_RW_COUNT
2503 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2504 #endif
2506 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2507 Return the number of bytes read, which might be less than NBYTE.
2508 On error, set errno and return -1. */
2509 ptrdiff_t
2510 emacs_read (int fildes, void *buf, ptrdiff_t nbyte)
2512 ssize_t rtnval;
2514 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2515 passes a size that large to emacs_read. */
2517 while ((rtnval = read (fildes, buf, nbyte)) == -1
2518 && (errno == EINTR))
2519 QUIT;
2520 return (rtnval);
2523 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2524 or if a partial write occurs. If interrupted, process pending
2525 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2526 errno if this is less than NBYTE. */
2527 static ptrdiff_t
2528 emacs_full_write (int fildes, char const *buf, ptrdiff_t nbyte,
2529 bool process_signals)
2531 ptrdiff_t bytes_written = 0;
2533 while (nbyte > 0)
2535 ssize_t n = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
2537 if (n < 0)
2539 if (errno == EINTR)
2541 /* I originally used `QUIT' but that might cause files to
2542 be truncated if you hit C-g in the middle of it. --Stef */
2543 if (process_signals && pending_signals)
2544 process_pending_signals ();
2545 continue;
2547 else
2548 break;
2551 buf += n;
2552 nbyte -= n;
2553 bytes_written += n;
2556 return bytes_written;
2559 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2560 interrupted or if a partial write occurs. Return the number of
2561 bytes written, setting errno if this is less than NBYTE. */
2562 ptrdiff_t
2563 emacs_write (int fildes, void const *buf, ptrdiff_t nbyte)
2565 return emacs_full_write (fildes, buf, nbyte, 0);
2568 /* Like emacs_write, but also process pending signals if interrupted. */
2569 ptrdiff_t
2570 emacs_write_sig (int fildes, void const *buf, ptrdiff_t nbyte)
2572 return emacs_full_write (fildes, buf, nbyte, 1);
2575 /* Write a diagnostic to standard error that contains MESSAGE and a
2576 string derived from errno. Preserve errno. Do not buffer stderr.
2577 Do not process pending signals if interrupted. */
2578 void
2579 emacs_perror (char const *message)
2581 int err = errno;
2582 char const *error_string = emacs_strerror (err);
2583 char const *command = (initial_argv && initial_argv[0]
2584 ? initial_argv[0] : "emacs");
2585 /* Write it out all at once, if it's short; this is less likely to
2586 be interleaved with other output. */
2587 char buf[BUFSIZ];
2588 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2589 command, message, error_string);
2590 if (0 <= nbytes && nbytes < BUFSIZ)
2591 emacs_write (STDERR_FILENO, buf, nbytes);
2592 else
2594 emacs_write (STDERR_FILENO, command, strlen (command));
2595 emacs_write (STDERR_FILENO, ": ", 2);
2596 emacs_write (STDERR_FILENO, message, strlen (message));
2597 emacs_write (STDERR_FILENO, ": ", 2);
2598 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2599 emacs_write (STDERR_FILENO, "\n", 1);
2601 errno = err;
2604 /* Return a struct timeval that is roughly equivalent to T.
2605 Use the least timeval not less than T.
2606 Return an extremal value if the result would overflow. */
2607 struct timeval
2608 make_timeval (struct timespec t)
2610 struct timeval tv;
2611 tv.tv_sec = t.tv_sec;
2612 tv.tv_usec = t.tv_nsec / 1000;
2614 if (t.tv_nsec % 1000 != 0)
2616 if (tv.tv_usec < 999999)
2617 tv.tv_usec++;
2618 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2620 tv.tv_sec++;
2621 tv.tv_usec = 0;
2625 return tv;
2628 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2629 ATIME and MTIME, respectively.
2630 FD must be either negative -- in which case it is ignored --
2631 or a file descriptor that is open on FILE.
2632 If FD is nonnegative, then FILE can be NULL. */
2634 set_file_times (int fd, const char *filename,
2635 struct timespec atime, struct timespec mtime)
2637 struct timespec timespec[2];
2638 timespec[0] = atime;
2639 timespec[1] = mtime;
2640 return fdutimens (fd, filename, timespec);
2643 /* Like strsignal, except async-signal-safe, and this function typically
2644 returns a string in the C locale rather than the current locale. */
2645 char const *
2646 safe_strsignal (int code)
2648 char const *signame = 0;
2650 if (0 <= code && code < sys_siglist_entries)
2651 signame = sys_siglist[code];
2652 if (! signame)
2653 signame = "Unknown signal";
2655 return signame;
2658 #ifndef DOS_NT
2659 /* For make-serial-process */
2661 serial_open (Lisp_Object port)
2663 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2664 if (fd < 0)
2665 report_file_error ("Opening serial port", port);
2666 #ifdef TIOCEXCL
2667 ioctl (fd, TIOCEXCL, (char *) 0);
2668 #endif
2670 return fd;
2673 #if !defined (HAVE_CFMAKERAW)
2674 /* Workaround for targets which are missing cfmakeraw. */
2675 /* Pasted from man page. */
2676 static void
2677 cfmakeraw (struct termios *termios_p)
2679 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2680 termios_p->c_oflag &= ~OPOST;
2681 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2682 termios_p->c_cflag &= ~(CSIZE|PARENB);
2683 termios_p->c_cflag |= CS8;
2685 #endif /* !defined (HAVE_CFMAKERAW */
2687 #if !defined (HAVE_CFSETSPEED)
2688 /* Workaround for targets which are missing cfsetspeed. */
2689 static int
2690 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2692 return (cfsetispeed (termios_p, vitesse)
2693 + cfsetospeed (termios_p, vitesse));
2695 #endif
2697 /* For serial-process-configure */
2698 void
2699 serial_configure (struct Lisp_Process *p,
2700 Lisp_Object contact)
2702 Lisp_Object childp2 = Qnil;
2703 Lisp_Object tem = Qnil;
2704 struct termios attr;
2705 int err;
2706 char summary[4] = "???"; /* This usually becomes "8N1". */
2708 childp2 = Fcopy_sequence (p->childp);
2710 /* Read port attributes and prepare default configuration. */
2711 err = tcgetattr (p->outfd, &attr);
2712 if (err != 0)
2713 report_file_error ("Failed tcgetattr", Qnil);
2714 cfmakeraw (&attr);
2715 #if defined (CLOCAL)
2716 attr.c_cflag |= CLOCAL;
2717 #endif
2718 #if defined (CREAD)
2719 attr.c_cflag |= CREAD;
2720 #endif
2722 /* Configure speed. */
2723 if (!NILP (Fplist_member (contact, QCspeed)))
2724 tem = Fplist_get (contact, QCspeed);
2725 else
2726 tem = Fplist_get (p->childp, QCspeed);
2727 CHECK_NUMBER (tem);
2728 err = cfsetspeed (&attr, XINT (tem));
2729 if (err != 0)
2730 report_file_error ("Failed cfsetspeed", tem);
2731 childp2 = Fplist_put (childp2, QCspeed, tem);
2733 /* Configure bytesize. */
2734 if (!NILP (Fplist_member (contact, QCbytesize)))
2735 tem = Fplist_get (contact, QCbytesize);
2736 else
2737 tem = Fplist_get (p->childp, QCbytesize);
2738 if (NILP (tem))
2739 tem = make_number (8);
2740 CHECK_NUMBER (tem);
2741 if (XINT (tem) != 7 && XINT (tem) != 8)
2742 error (":bytesize must be nil (8), 7, or 8");
2743 summary[0] = XINT (tem) + '0';
2744 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2745 attr.c_cflag &= ~CSIZE;
2746 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2747 #else
2748 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2749 if (XINT (tem) != 8)
2750 error ("Bytesize cannot be changed");
2751 #endif
2752 childp2 = Fplist_put (childp2, QCbytesize, tem);
2754 /* Configure parity. */
2755 if (!NILP (Fplist_member (contact, QCparity)))
2756 tem = Fplist_get (contact, QCparity);
2757 else
2758 tem = Fplist_get (p->childp, QCparity);
2759 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2760 error (":parity must be nil (no parity), `even', or `odd'");
2761 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2762 attr.c_cflag &= ~(PARENB | PARODD);
2763 attr.c_iflag &= ~(IGNPAR | INPCK);
2764 if (NILP (tem))
2766 summary[1] = 'N';
2768 else if (EQ (tem, Qeven))
2770 summary[1] = 'E';
2771 attr.c_cflag |= PARENB;
2772 attr.c_iflag |= (IGNPAR | INPCK);
2774 else if (EQ (tem, Qodd))
2776 summary[1] = 'O';
2777 attr.c_cflag |= (PARENB | PARODD);
2778 attr.c_iflag |= (IGNPAR | INPCK);
2780 #else
2781 /* Don't error on no parity, which should be set by cfmakeraw. */
2782 if (!NILP (tem))
2783 error ("Parity cannot be configured");
2784 #endif
2785 childp2 = Fplist_put (childp2, QCparity, tem);
2787 /* Configure stopbits. */
2788 if (!NILP (Fplist_member (contact, QCstopbits)))
2789 tem = Fplist_get (contact, QCstopbits);
2790 else
2791 tem = Fplist_get (p->childp, QCstopbits);
2792 if (NILP (tem))
2793 tem = make_number (1);
2794 CHECK_NUMBER (tem);
2795 if (XINT (tem) != 1 && XINT (tem) != 2)
2796 error (":stopbits must be nil (1 stopbit), 1, or 2");
2797 summary[2] = XINT (tem) + '0';
2798 #if defined (CSTOPB)
2799 attr.c_cflag &= ~CSTOPB;
2800 if (XINT (tem) == 2)
2801 attr.c_cflag |= CSTOPB;
2802 #else
2803 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2804 if (XINT (tem) != 1)
2805 error ("Stopbits cannot be configured");
2806 #endif
2807 childp2 = Fplist_put (childp2, QCstopbits, tem);
2809 /* Configure flowcontrol. */
2810 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2811 tem = Fplist_get (contact, QCflowcontrol);
2812 else
2813 tem = Fplist_get (p->childp, QCflowcontrol);
2814 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2815 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2816 #if defined (CRTSCTS)
2817 attr.c_cflag &= ~CRTSCTS;
2818 #endif
2819 #if defined (CNEW_RTSCTS)
2820 attr.c_cflag &= ~CNEW_RTSCTS;
2821 #endif
2822 #if defined (IXON) && defined (IXOFF)
2823 attr.c_iflag &= ~(IXON | IXOFF);
2824 #endif
2825 if (NILP (tem))
2827 /* Already configured. */
2829 else if (EQ (tem, Qhw))
2831 #if defined (CRTSCTS)
2832 attr.c_cflag |= CRTSCTS;
2833 #elif defined (CNEW_RTSCTS)
2834 attr.c_cflag |= CNEW_RTSCTS;
2835 #else
2836 error ("Hardware flowcontrol (RTS/CTS) not supported");
2837 #endif
2839 else if (EQ (tem, Qsw))
2841 #if defined (IXON) && defined (IXOFF)
2842 attr.c_iflag |= (IXON | IXOFF);
2843 #else
2844 error ("Software flowcontrol (XON/XOFF) not supported");
2845 #endif
2847 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2849 /* Activate configuration. */
2850 err = tcsetattr (p->outfd, TCSANOW, &attr);
2851 if (err != 0)
2852 report_file_error ("Failed tcsetattr", Qnil);
2854 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2855 pset_childp (p, childp2);
2857 #endif /* not DOS_NT */
2859 /* System depended enumeration of and access to system processes a-la ps(1). */
2861 #ifdef HAVE_PROCFS
2863 /* Process enumeration and access via /proc. */
2865 Lisp_Object
2866 list_system_processes (void)
2868 Lisp_Object procdir, match, proclist, next;
2869 Lisp_Object tail;
2871 /* For every process on the system, there's a directory in the
2872 "/proc" pseudo-directory whose name is the numeric ID of that
2873 process. */
2874 procdir = build_string ("/proc");
2875 match = build_string ("[0-9]+");
2876 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2878 /* `proclist' gives process IDs as strings. Destructively convert
2879 each string into a number. */
2880 for (tail = proclist; CONSP (tail); tail = next)
2882 next = XCDR (tail);
2883 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2886 /* directory_files_internal returns the files in reverse order; undo
2887 that. */
2888 proclist = Fnreverse (proclist);
2889 return proclist;
2892 #elif defined DARWIN_OS || defined __FreeBSD__
2894 Lisp_Object
2895 list_system_processes (void)
2897 #ifdef DARWIN_OS
2898 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2899 #else
2900 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2901 #endif
2902 size_t len;
2903 struct kinfo_proc *procs;
2904 size_t i;
2906 Lisp_Object proclist = Qnil;
2908 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2909 return proclist;
2911 procs = xmalloc (len);
2912 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2914 xfree (procs);
2915 return proclist;
2918 len /= sizeof (struct kinfo_proc);
2919 for (i = 0; i < len; i++)
2921 #ifdef DARWIN_OS
2922 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2923 #else
2924 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2925 #endif
2928 xfree (procs);
2930 return proclist;
2933 /* The WINDOWSNT implementation is in w32.c.
2934 The MSDOS implementation is in dosfns.c. */
2935 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2937 Lisp_Object
2938 list_system_processes (void)
2940 return Qnil;
2943 #endif /* !defined (WINDOWSNT) */
2945 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2946 static struct timespec
2947 time_from_jiffies (unsigned long long tval, long hz)
2949 unsigned long long s = tval / hz;
2950 unsigned long long frac = tval % hz;
2951 int ns;
2953 if (TYPE_MAXIMUM (time_t) < s)
2954 time_overflow ();
2955 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2956 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2957 ns = frac * TIMESPEC_RESOLUTION / hz;
2958 else
2960 /* This is reachable only in the unlikely case that HZ * HZ
2961 exceeds ULLONG_MAX. It calculates an approximation that is
2962 guaranteed to be in range. */
2963 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
2964 + (hz % TIMESPEC_RESOLUTION != 0));
2965 ns = frac / hz_per_ns;
2968 return make_timespec (s, ns);
2971 static Lisp_Object
2972 ltime_from_jiffies (unsigned long long tval, long hz)
2974 struct timespec t = time_from_jiffies (tval, hz);
2975 return make_lisp_time (t);
2978 static struct timespec
2979 get_up_time (void)
2981 FILE *fup;
2982 struct timespec up = make_timespec (0, 0);
2984 block_input ();
2985 fup = emacs_fopen ("/proc/uptime", "r");
2987 if (fup)
2989 unsigned long long upsec, upfrac, idlesec, idlefrac;
2990 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
2992 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
2993 &upsec, &upfrac_start, &upfrac, &upfrac_end,
2994 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
2995 == 4)
2997 if (TYPE_MAXIMUM (time_t) < upsec)
2999 upsec = TYPE_MAXIMUM (time_t);
3000 upfrac = TIMESPEC_RESOLUTION - 1;
3002 else
3004 int upfraclen = upfrac_end - upfrac_start;
3005 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3006 upfrac *= 10;
3007 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3008 upfrac /= 10;
3009 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3011 up = make_timespec (upsec, upfrac);
3013 fclose (fup);
3015 unblock_input ();
3017 return up;
3020 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3021 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3023 static Lisp_Object
3024 procfs_ttyname (int rdev)
3026 FILE *fdev;
3027 char name[PATH_MAX];
3029 block_input ();
3030 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3031 name[0] = 0;
3033 if (fdev)
3035 unsigned major;
3036 unsigned long minor_beg, minor_end;
3037 char minor[25]; /* 2 32-bit numbers + dash */
3038 char *endp;
3040 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
3042 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3043 && major == MAJOR (rdev))
3045 minor_beg = strtoul (minor, &endp, 0);
3046 if (*endp == '\0')
3047 minor_end = minor_beg;
3048 else if (*endp == '-')
3049 minor_end = strtoul (endp + 1, &endp, 0);
3050 else
3051 continue;
3053 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3055 sprintf (name + strlen (name), "%u", MINOR (rdev));
3056 break;
3060 fclose (fdev);
3062 unblock_input ();
3063 return build_string (name);
3066 static uintmax_t
3067 procfs_get_total_memory (void)
3069 FILE *fmem;
3070 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3071 int c;
3073 block_input ();
3074 fmem = emacs_fopen ("/proc/meminfo", "r");
3076 if (fmem)
3078 uintmax_t entry_value;
3079 bool done;
3082 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3084 case 1:
3085 retval = entry_value;
3086 done = 1;
3087 break;
3089 case 0:
3090 while ((c = getc (fmem)) != EOF && c != '\n')
3091 continue;
3092 done = c == EOF;
3093 break;
3095 default:
3096 done = 1;
3097 break;
3099 while (!done);
3101 fclose (fmem);
3103 unblock_input ();
3104 return retval;
3107 Lisp_Object
3108 system_process_attributes (Lisp_Object pid)
3110 char procfn[PATH_MAX], fn[PATH_MAX];
3111 struct stat st;
3112 struct passwd *pw;
3113 struct group *gr;
3114 long clocks_per_sec;
3115 char *procfn_end;
3116 char procbuf[1025], *p, *q;
3117 int fd;
3118 ssize_t nread;
3119 static char const default_cmd[] = "???";
3120 const char *cmd = default_cmd;
3121 int cmdsize = sizeof default_cmd - 1;
3122 char *cmdline = NULL;
3123 ptrdiff_t cmdline_size;
3124 char c;
3125 printmax_t proc_id;
3126 int ppid, pgrp, sess, tty, tpgid, thcount;
3127 uid_t uid;
3128 gid_t gid;
3129 unsigned long long u_time, s_time, cutime, cstime, start;
3130 long priority, niceness, rss;
3131 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3132 struct timespec tnow, tstart, tboot, telapsed, us_time;
3133 double pcpu, pmem;
3134 Lisp_Object attrs = Qnil;
3135 Lisp_Object decoded_cmd;
3136 ptrdiff_t count;
3138 CHECK_NUMBER_OR_FLOAT (pid);
3139 CONS_TO_INTEGER (pid, pid_t, proc_id);
3140 sprintf (procfn, "/proc/%"pMd, proc_id);
3141 if (stat (procfn, &st) < 0)
3142 return attrs;
3144 /* euid egid */
3145 uid = st.st_uid;
3146 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3147 block_input ();
3148 pw = getpwuid (uid);
3149 unblock_input ();
3150 if (pw)
3151 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3153 gid = st.st_gid;
3154 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3155 block_input ();
3156 gr = getgrgid (gid);
3157 unblock_input ();
3158 if (gr)
3159 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3161 count = SPECPDL_INDEX ();
3162 strcpy (fn, procfn);
3163 procfn_end = fn + strlen (fn);
3164 strcpy (procfn_end, "/stat");
3165 fd = emacs_open (fn, O_RDONLY, 0);
3166 if (fd < 0)
3167 nread = 0;
3168 else
3170 record_unwind_protect_int (close_file_unwind, fd);
3171 nread = emacs_read (fd, procbuf, sizeof procbuf - 1);
3173 if (0 < nread)
3175 procbuf[nread] = '\0';
3176 p = procbuf;
3178 p = strchr (p, '(');
3179 if (p != NULL)
3181 q = strrchr (p + 1, ')');
3182 /* comm */
3183 if (q != NULL)
3185 cmd = p + 1;
3186 cmdsize = q - cmd;
3189 else
3190 q = NULL;
3191 /* Command name is encoded in locale-coding-system; decode it. */
3192 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3193 decoded_cmd = code_convert_string_norecord (cmd_str,
3194 Vlocale_coding_system, 0);
3195 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3197 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3198 utime stime cutime cstime priority nice thcount . start vsize rss */
3199 if (q
3200 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3201 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3202 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3203 &minflt, &cminflt, &majflt, &cmajflt,
3204 &u_time, &s_time, &cutime, &cstime,
3205 &priority, &niceness, &thcount, &start, &vsize, &rss)
3206 == 20))
3208 char state_str[2];
3209 state_str[0] = c;
3210 state_str[1] = '\0';
3211 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3212 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3213 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3214 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3215 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3216 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3217 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3218 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3219 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3220 attrs);
3221 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3222 attrs);
3223 clocks_per_sec = sysconf (_SC_CLK_TCK);
3224 if (clocks_per_sec < 0)
3225 clocks_per_sec = 100;
3226 attrs = Fcons (Fcons (Qutime,
3227 ltime_from_jiffies (u_time, clocks_per_sec)),
3228 attrs);
3229 attrs = Fcons (Fcons (Qstime,
3230 ltime_from_jiffies (s_time, clocks_per_sec)),
3231 attrs);
3232 attrs = Fcons (Fcons (Qtime,
3233 ltime_from_jiffies (s_time + u_time,
3234 clocks_per_sec)),
3235 attrs);
3236 attrs = Fcons (Fcons (Qcutime,
3237 ltime_from_jiffies (cutime, clocks_per_sec)),
3238 attrs);
3239 attrs = Fcons (Fcons (Qcstime,
3240 ltime_from_jiffies (cstime, clocks_per_sec)),
3241 attrs);
3242 attrs = Fcons (Fcons (Qctime,
3243 ltime_from_jiffies (cstime + cutime,
3244 clocks_per_sec)),
3245 attrs);
3246 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3247 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3248 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3249 attrs);
3250 tnow = current_timespec ();
3251 telapsed = get_up_time ();
3252 tboot = timespec_sub (tnow, telapsed);
3253 tstart = time_from_jiffies (start, clocks_per_sec);
3254 tstart = timespec_add (tboot, tstart);
3255 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3256 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3257 attrs);
3258 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3259 telapsed = timespec_sub (tnow, tstart);
3260 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3261 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3262 pcpu = timespectod (us_time) / timespectod (telapsed);
3263 if (pcpu > 1.0)
3264 pcpu = 1.0;
3265 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3266 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3267 if (pmem > 100)
3268 pmem = 100;
3269 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3272 unbind_to (count, Qnil);
3274 /* args */
3275 strcpy (procfn_end, "/cmdline");
3276 fd = emacs_open (fn, O_RDONLY, 0);
3277 if (fd >= 0)
3279 ptrdiff_t readsize, nread_incr;
3280 record_unwind_protect_int (close_file_unwind, fd);
3281 record_unwind_protect_nothing ();
3282 nread = cmdline_size = 0;
3286 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3287 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3289 /* Leave room even if every byte needs escaping below. */
3290 readsize = (cmdline_size >> 1) - nread;
3292 nread_incr = emacs_read (fd, cmdline + nread, readsize);
3293 nread += max (0, nread_incr);
3295 while (nread_incr == readsize);
3297 if (nread)
3299 /* We don't want trailing null characters. */
3300 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3301 continue;
3303 /* Escape-quote whitespace and backslashes. */
3304 q = cmdline + cmdline_size;
3305 while (cmdline < p)
3307 char c = *--p;
3308 *--q = c ? c : ' ';
3309 if (c_isspace (c) || c == '\\')
3310 *--q = '\\';
3313 nread = cmdline + cmdline_size - q;
3316 if (!nread)
3318 nread = cmdsize + 2;
3319 cmdline_size = nread + 1;
3320 q = cmdline = xrealloc (cmdline, cmdline_size);
3321 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3322 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3324 /* Command line is encoded in locale-coding-system; decode it. */
3325 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3326 decoded_cmd = code_convert_string_norecord (cmd_str,
3327 Vlocale_coding_system, 0);
3328 unbind_to (count, Qnil);
3329 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3332 return attrs;
3335 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3337 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3338 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3339 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3340 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3341 #undef _FILE_OFFSET_BITS
3342 #else
3343 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3344 #endif
3346 #include <procfs.h>
3348 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3349 #define _FILE_OFFSET_BITS 64
3350 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3351 #endif
3352 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3354 Lisp_Object
3355 system_process_attributes (Lisp_Object pid)
3357 char procfn[PATH_MAX], fn[PATH_MAX];
3358 struct stat st;
3359 struct passwd *pw;
3360 struct group *gr;
3361 char *procfn_end;
3362 struct psinfo pinfo;
3363 int fd;
3364 ssize_t nread;
3365 printmax_t proc_id;
3366 uid_t uid;
3367 gid_t gid;
3368 Lisp_Object attrs = Qnil;
3369 Lisp_Object decoded_cmd;
3370 ptrdiff_t count;
3372 CHECK_NUMBER_OR_FLOAT (pid);
3373 CONS_TO_INTEGER (pid, pid_t, proc_id);
3374 sprintf (procfn, "/proc/%"pMd, proc_id);
3375 if (stat (procfn, &st) < 0)
3376 return attrs;
3378 /* euid egid */
3379 uid = st.st_uid;
3380 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3381 block_input ();
3382 pw = getpwuid (uid);
3383 unblock_input ();
3384 if (pw)
3385 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3387 gid = st.st_gid;
3388 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3389 block_input ();
3390 gr = getgrgid (gid);
3391 unblock_input ();
3392 if (gr)
3393 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3395 count = SPECPDL_INDEX ();
3396 strcpy (fn, procfn);
3397 procfn_end = fn + strlen (fn);
3398 strcpy (procfn_end, "/psinfo");
3399 fd = emacs_open (fn, O_RDONLY, 0);
3400 if (fd < 0)
3401 nread = 0;
3402 else
3404 record_unwind_protect_int (close_file_unwind, fd);
3405 nread = emacs_read (fd, &pinfo, sizeof pinfo);
3408 if (nread == sizeof pinfo)
3410 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3411 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3412 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3415 char state_str[2];
3416 state_str[0] = pinfo.pr_lwp.pr_sname;
3417 state_str[1] = '\0';
3418 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3421 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3422 need to get a string from it. */
3424 /* FIXME: missing: Qtpgid */
3426 /* FIXME: missing:
3427 Qminflt
3428 Qmajflt
3429 Qcminflt
3430 Qcmajflt
3432 Qutime
3433 Qcutime
3434 Qstime
3435 Qcstime
3436 Are they available? */
3438 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3439 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3440 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3441 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3442 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3443 attrs);
3445 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3446 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3447 attrs);
3448 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3449 attrs);
3451 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3452 range 0 .. 2**15, representing 0.0 .. 1.0. */
3453 attrs = Fcons (Fcons (Qpcpu,
3454 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3455 attrs);
3456 attrs = Fcons (Fcons (Qpmem,
3457 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3458 attrs);
3460 AUTO_STRING (fname, pinfo.pr_fname);
3461 decoded_cmd = code_convert_string_norecord (fname,
3462 Vlocale_coding_system, 0);
3463 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3464 AUTO_STRING (psargs, pinfo.pr_psargs);
3465 decoded_cmd = code_convert_string_norecord (psargs,
3466 Vlocale_coding_system, 0);
3467 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3469 unbind_to (count, Qnil);
3470 return attrs;
3473 #elif defined __FreeBSD__
3475 static struct timespec
3476 timeval_to_timespec (struct timeval t)
3478 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3481 static Lisp_Object
3482 make_lisp_timeval (struct timeval t)
3484 return make_lisp_time (timeval_to_timespec (t));
3487 Lisp_Object
3488 system_process_attributes (Lisp_Object pid)
3490 int proc_id;
3491 int pagesize = getpagesize ();
3492 unsigned long npages;
3493 int fscale;
3494 struct passwd *pw;
3495 struct group *gr;
3496 char *ttyname;
3497 size_t len;
3498 char args[MAXPATHLEN];
3499 struct timespec t, now;
3501 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3502 struct kinfo_proc proc;
3503 size_t proclen = sizeof proc;
3505 Lisp_Object attrs = Qnil;
3506 Lisp_Object decoded_comm;
3508 CHECK_NUMBER_OR_FLOAT (pid);
3509 CONS_TO_INTEGER (pid, int, proc_id);
3510 mib[3] = proc_id;
3512 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3513 return attrs;
3515 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3517 block_input ();
3518 pw = getpwuid (proc.ki_uid);
3519 unblock_input ();
3520 if (pw)
3521 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3523 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3525 block_input ();
3526 gr = getgrgid (proc.ki_svgid);
3527 unblock_input ();
3528 if (gr)
3529 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3531 AUTO_STRING (comm, proc.ki_comm);
3532 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3534 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3536 char state[2] = {'\0', '\0'};
3537 switch (proc.ki_stat)
3539 case SRUN:
3540 state[0] = 'R';
3541 break;
3543 case SSLEEP:
3544 state[0] = 'S';
3545 break;
3547 case SLOCK:
3548 state[0] = 'D';
3549 break;
3551 case SZOMB:
3552 state[0] = 'Z';
3553 break;
3555 case SSTOP:
3556 state[0] = 'T';
3557 break;
3559 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3562 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3563 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3564 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3566 block_input ();
3567 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3568 unblock_input ();
3569 if (ttyname)
3570 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3572 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3573 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3574 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3575 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3576 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3578 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3579 attrs);
3580 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3581 attrs);
3582 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3583 timeval_to_timespec (proc.ki_rusage.ru_stime));
3584 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3586 attrs = Fcons (Fcons (Qcutime,
3587 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3588 attrs);
3589 attrs = Fcons (Fcons (Qcstime,
3590 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3591 attrs);
3592 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3593 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3594 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3596 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3597 attrs);
3598 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3599 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3600 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3601 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3602 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3603 attrs);
3605 now = current_timespec ();
3606 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3607 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3609 len = sizeof fscale;
3610 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3612 double pcpu;
3613 fixpt_t ccpu;
3614 len = sizeof ccpu;
3615 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3617 pcpu = (100.0 * proc.ki_pctcpu / fscale
3618 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3619 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3623 len = sizeof npages;
3624 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3626 double pmem = (proc.ki_flag & P_INMEM
3627 ? 100.0 * proc.ki_rssize / npages
3628 : 0);
3629 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3632 mib[2] = KERN_PROC_ARGS;
3633 len = MAXPATHLEN;
3634 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3636 int i;
3637 for (i = 0; i < len; i++)
3639 if (! args[i] && i < len - 1)
3640 args[i] = ' ';
3643 AUTO_STRING (comm, args);
3644 decoded_comm = code_convert_string_norecord (comm,
3645 Vlocale_coding_system, 0);
3647 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3650 return attrs;
3653 #elif defined DARWIN_OS
3655 static struct timespec
3656 timeval_to_timespec (struct timeval t)
3658 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3661 static Lisp_Object
3662 make_lisp_timeval (struct timeval t)
3664 return make_lisp_time (timeval_to_timespec (t));
3667 Lisp_Object
3668 system_process_attributes (Lisp_Object pid)
3670 int proc_id;
3671 int pagesize = getpagesize ();
3672 unsigned long npages;
3673 int fscale;
3674 struct passwd *pw;
3675 struct group *gr;
3676 char *ttyname;
3677 size_t len;
3678 char args[MAXPATHLEN];
3679 struct timeval starttime;
3680 struct timespec t, now;
3681 struct rusage *rusage;
3682 dev_t tdev;
3683 uid_t uid;
3684 gid_t gid;
3686 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3687 struct kinfo_proc proc;
3688 size_t proclen = sizeof proc;
3690 Lisp_Object attrs = Qnil;
3691 Lisp_Object decoded_comm;
3693 CHECK_NUMBER_OR_FLOAT (pid);
3694 CONS_TO_INTEGER (pid, int, proc_id);
3695 mib[3] = proc_id;
3697 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3698 return attrs;
3700 uid = proc.kp_eproc.e_ucred.cr_uid;
3701 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3703 block_input ();
3704 pw = getpwuid (uid);
3705 unblock_input ();
3706 if (pw)
3707 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3709 gid = proc.kp_eproc.e_pcred.p_svgid;
3710 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3712 block_input ();
3713 gr = getgrgid (gid);
3714 unblock_input ();
3715 if (gr)
3716 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3718 decoded_comm = (code_convert_string_norecord
3719 (build_unibyte_string (proc.kp_proc.p_comm),
3720 Vlocale_coding_system, 0));
3722 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3724 char state[2] = {'\0', '\0'};
3725 switch (proc.kp_proc.p_stat)
3727 case SRUN:
3728 state[0] = 'R';
3729 break;
3731 case SSLEEP:
3732 state[0] = 'S';
3733 break;
3735 case SZOMB:
3736 state[0] = 'Z';
3737 break;
3739 case SSTOP:
3740 state[0] = 'T';
3741 break;
3743 case SIDL:
3744 state[0] = 'I';
3745 break;
3747 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3750 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3751 attrs);
3752 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3753 attrs);
3755 tdev = proc.kp_eproc.e_tdev;
3756 block_input ();
3757 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3758 unblock_input ();
3759 if (ttyname)
3760 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3762 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3763 attrs);
3765 rusage = proc.kp_proc.p_ru;
3766 if (rusage)
3768 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3769 attrs);
3770 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3771 attrs);
3773 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3774 attrs);
3775 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3776 attrs);
3777 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3778 timeval_to_timespec (rusage->ru_stime));
3779 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3782 starttime = proc.kp_proc.p_starttime;
3783 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3784 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3786 now = current_timespec ();
3787 t = timespec_sub (now, timeval_to_timespec (starttime));
3788 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3790 return attrs;
3793 /* The WINDOWSNT implementation is in w32.c.
3794 The MSDOS implementation is in dosfns.c. */
3795 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3797 Lisp_Object
3798 system_process_attributes (Lisp_Object pid)
3800 return Qnil;
3803 #endif /* !defined (WINDOWSNT) */
3805 /* Wide character string collation. */
3807 #ifdef __STDC_ISO_10646__
3808 # include <wchar.h>
3809 # include <wctype.h>
3811 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3812 # include <locale.h>
3813 # endif
3814 # ifndef LC_COLLATE
3815 # define LC_COLLATE 0
3816 # endif
3817 # ifndef LC_COLLATE_MASK
3818 # define LC_COLLATE_MASK 0
3819 # endif
3820 # ifndef LC_CTYPE
3821 # define LC_CTYPE 0
3822 # endif
3823 # ifndef LC_CTYPE_MASK
3824 # define LC_CTYPE_MASK 0
3825 # endif
3827 # ifndef HAVE_NEWLOCALE
3828 # undef freelocale
3829 # undef locale_t
3830 # undef newlocale
3831 # undef wcscoll_l
3832 # undef towlower_l
3833 # define freelocale emacs_freelocale
3834 # define locale_t emacs_locale_t
3835 # define newlocale emacs_newlocale
3836 # define wcscoll_l emacs_wcscoll_l
3837 # define towlower_l emacs_towlower_l
3839 typedef char const *locale_t;
3841 static locale_t
3842 newlocale (int category_mask, char const *locale, locale_t loc)
3844 return locale;
3847 static void
3848 freelocale (locale_t loc)
3852 static char *
3853 emacs_setlocale (int category, char const *locale)
3855 # ifdef HAVE_SETLOCALE
3856 errno = 0;
3857 char *loc = setlocale (category, locale);
3858 if (loc || errno)
3859 return loc;
3860 errno = EINVAL;
3861 # else
3862 errno = ENOTSUP;
3863 # endif
3864 return 0;
3867 static int
3868 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3870 int result = 0;
3871 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3872 int err;
3874 if (! oldloc)
3875 err = errno;
3876 else
3878 USE_SAFE_ALLOCA;
3879 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3880 strcpy (oldcopy, oldloc);
3881 if (! emacs_setlocale (LC_COLLATE, loc))
3882 err = errno;
3883 else
3885 errno = 0;
3886 result = wcscoll (a, b);
3887 err = errno;
3888 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3889 err = errno;
3891 SAFE_FREE ();
3894 errno = err;
3895 return result;
3898 static wint_t
3899 towlower_l (wint_t wc, locale_t loc)
3901 wint_t result = wc;
3902 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3904 if (oldloc)
3906 USE_SAFE_ALLOCA;
3907 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3908 strcpy (oldcopy, oldloc);
3909 if (emacs_setlocale (LC_CTYPE, loc))
3911 result = towlower (wc);
3912 emacs_setlocale (LC_COLLATE, oldcopy);
3914 SAFE_FREE ();
3917 return result;
3919 # endif
3922 str_collate (Lisp_Object s1, Lisp_Object s2,
3923 Lisp_Object locale, Lisp_Object ignore_case)
3925 int res, err;
3926 ptrdiff_t len, i, i_byte;
3927 wchar_t *p1, *p2;
3929 USE_SAFE_ALLOCA;
3931 /* Convert byte stream to code points. */
3932 len = SCHARS (s1); i = i_byte = 0;
3933 SAFE_NALLOCA (p1, 1, len + 1);
3934 while (i < len)
3935 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3936 *(p1+len) = 0;
3938 len = SCHARS (s2); i = i_byte = 0;
3939 SAFE_NALLOCA (p2, 1, len + 1);
3940 while (i < len)
3941 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3942 *(p2+len) = 0;
3944 if (STRINGP (locale))
3946 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3947 SSDATA (locale), 0);
3948 if (!loc)
3949 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
3951 if (! NILP (ignore_case))
3952 for (int i = 1; i < 3; i++)
3954 wchar_t *p = (i == 1) ? p1 : p2;
3955 for (; *p; p++)
3956 *p = towlower_l (*p, loc);
3959 errno = 0;
3960 res = wcscoll_l (p1, p2, loc);
3961 err = errno;
3962 freelocale (loc);
3964 else
3966 if (! NILP (ignore_case))
3967 for (int i = 1; i < 3; i++)
3969 wchar_t *p = (i == 1) ? p1 : p2;
3970 for (; *p; p++)
3971 *p = towlower (*p);
3974 errno = 0;
3975 res = wcscoll (p1, p2);
3976 err = errno;
3978 # ifndef HAVE_NEWLOCALE
3979 if (err)
3980 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
3981 # else
3982 if (err)
3983 error ("Invalid string for collation: %s", emacs_strerror (err));
3984 # endif
3986 SAFE_FREE ();
3987 return res;
3989 #endif /* __STDC_ISO_10646__ */
3991 #ifdef WINDOWSNT
3993 str_collate (Lisp_Object s1, Lisp_Object s2,
3994 Lisp_Object locale, Lisp_Object ignore_case)
3997 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
3998 int res, err = errno;
4000 errno = 0;
4001 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4002 if (errno)
4003 error ("Invalid string for collation: %s", strerror (errno));
4005 errno = err;
4006 return res;
4008 #endif /* WINDOWSNT */