Be more conservative in link time optimization doc
[emacs.git] / src / sysdep.c
blobb66a7453172eff684f27322f220a0e4871284d9e
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 #ifdef HAVE_LINUX_FS_H
41 # include <linux/fs.h>
42 # include <sys/syscall.h>
43 #endif
45 #if defined DARWIN_OS || defined __FreeBSD__
46 # include <sys/sysctl.h>
47 #endif
49 #ifdef __FreeBSD__
50 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
51 'struct frame', so rename it. */
52 # define frame freebsd_frame
53 # include <sys/user.h>
54 # undef frame
56 # include <math.h>
57 #endif
59 #ifdef HAVE_SOCKETS
60 #include <sys/socket.h>
61 #include <netdb.h>
62 #endif /* HAVE_SOCKETS */
64 #ifdef WINDOWSNT
65 #define read sys_read
66 #define write sys_write
67 #ifndef STDERR_FILENO
68 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
69 #endif
70 #include "w32.h"
71 #endif /* WINDOWSNT */
73 #include <sys/types.h>
74 #include <sys/stat.h>
75 #include <errno.h>
77 /* Get SI_SRPC_DOMAIN, if it is available. */
78 #ifdef HAVE_SYS_SYSTEMINFO_H
79 #include <sys/systeminfo.h>
80 #endif
82 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
83 #include "msdos.h"
84 #endif
86 #include <sys/param.h>
87 #include <sys/file.h>
88 #include <fcntl.h>
90 #include "systty.h"
91 #include "syswait.h"
93 #ifdef HAVE_SYS_UTSNAME_H
94 #include <sys/utsname.h>
95 #include <memory.h>
96 #endif /* HAVE_SYS_UTSNAME_H */
98 #include "keyboard.h"
99 #include "frame.h"
100 #include "termhooks.h"
101 #include "termchar.h"
102 #include "termopts.h"
103 #include "process.h"
104 #include "cm.h"
106 #include "gnutls.h"
107 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
108 do that during startup just to call gnutls_rnd. */
109 #if defined HAVE_GNUTLS && !defined WINDOWSNT
110 # include <gnutls/crypto.h>
111 #else
112 # define emacs_gnutls_global_init() Qnil
113 # define gnutls_rnd(level, data, len) (-1)
114 #endif
116 #ifdef WINDOWSNT
117 #include <direct.h>
118 /* In process.h which conflicts with the local copy. */
119 #define _P_WAIT 0
120 int _cdecl _spawnlp (int, const char *, const char *, ...);
121 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
122 several prototypes of functions called below. */
123 #include <sys/socket.h>
124 #endif
126 #include "syssignal.h"
127 #include "systime.h"
129 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
130 #ifndef ULLONG_MAX
131 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
132 #endif
134 /* Declare here, including term.h is problematic on some systems. */
135 extern void tputs (const char *, int, int (*)(int));
137 static const int baud_convert[] =
139 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
140 1800, 2400, 4800, 9600, 19200, 38400
143 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
144 # include <sys/personality.h>
146 /* Disable address randomization in the current process. Return true
147 if addresses were randomized but this has been disabled, false
148 otherwise. */
149 bool
150 disable_address_randomization (void)
152 int pers = personality (0xffffffff);
153 if (pers < 0)
154 return false;
155 int desired_pers = pers | ADDR_NO_RANDOMIZE;
157 /* Call 'personality' twice, to detect buggy platforms like WSL
158 where 'personality' always returns 0. */
159 return (pers != desired_pers
160 && personality (desired_pers) == pers
161 && personality (0xffffffff) == desired_pers);
163 #endif
165 /* Execute the program in FILE, with argument vector ARGV and environ
166 ENVP. Return an error number if unsuccessful. This is like execve
167 except it reenables ASLR in the executed program if necessary, and
168 on error it returns an error number rather than -1. */
170 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
172 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
173 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
174 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
175 if (change_personality)
176 personality (pers & ~ADDR_NO_RANDOMIZE);
177 #endif
179 execve (file, argv, envp);
180 int err = errno;
182 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
183 if (change_personality)
184 personality (pers);
185 #endif
187 return err;
190 /* If FD is not already open, arrange for it to be open with FLAGS. */
191 static void
192 force_open (int fd, int flags)
194 if (dup2 (fd, fd) < 0 && errno == EBADF)
196 int n = open (NULL_DEVICE, flags);
197 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
199 emacs_perror (NULL_DEVICE);
200 exit (EXIT_FAILURE);
205 /* Make sure stdin, stdout, and stderr are open to something, so that
206 their file descriptors are not hijacked by later system calls. */
207 void
208 init_standard_fds (void)
210 /* Open stdin for *writing*, and stdout and stderr for *reading*.
211 That way, any attempt to do normal I/O will result in an error,
212 just as if the files were closed, and the file descriptors will
213 not be reused by later opens. */
214 force_open (STDIN_FILENO, O_WRONLY);
215 force_open (STDOUT_FILENO, O_RDONLY);
216 force_open (STDERR_FILENO, O_RDONLY);
219 /* Return the current working directory. The result should be freed
220 with 'free'. Return NULL on errors. */
221 char *
222 emacs_get_current_dir_name (void)
224 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
225 # ifdef HYBRID_MALLOC
226 bool use_libc = bss_sbrk_did_unexec;
227 # else
228 bool use_libc = true;
229 # endif
230 if (use_libc)
231 return get_current_dir_name ();
232 # endif
234 char *buf;
235 char *pwd = getenv ("PWD");
236 struct stat dotstat, pwdstat;
237 /* If PWD is accurate, use it instead of calling getcwd. PWD is
238 sometimes a nicer name, and using it may avoid a fatal error if a
239 parent directory is searchable but not readable. */
240 if (pwd
241 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
242 && stat (pwd, &pwdstat) == 0
243 && stat (".", &dotstat) == 0
244 && dotstat.st_ino == pwdstat.st_ino
245 && dotstat.st_dev == pwdstat.st_dev
246 #ifdef MAXPATHLEN
247 && strlen (pwd) < MAXPATHLEN
248 #endif
251 buf = malloc (strlen (pwd) + 1);
252 if (!buf)
253 return NULL;
254 strcpy (buf, pwd);
256 else
258 size_t buf_size = 1024;
259 buf = malloc (buf_size);
260 if (!buf)
261 return NULL;
262 for (;;)
264 if (getcwd (buf, buf_size) == buf)
265 break;
266 if (errno != ERANGE)
268 int tmp_errno = errno;
269 free (buf);
270 errno = tmp_errno;
271 return NULL;
273 buf_size *= 2;
274 buf = realloc (buf, buf_size);
275 if (!buf)
276 return NULL;
279 return buf;
283 /* Discard pending input on all input descriptors. */
285 void
286 discard_tty_input (void)
288 #ifndef WINDOWSNT
289 struct emacs_tty buf;
291 if (noninteractive)
292 return;
294 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
295 while (dos_keyread () != -1)
297 #else /* not MSDOS */
299 struct tty_display_info *tty;
300 for (tty = tty_list; tty; tty = tty->next)
302 if (tty->input) /* Is the device suspended? */
304 emacs_get_tty (fileno (tty->input), &buf);
305 emacs_set_tty (fileno (tty->input), &buf, 0);
309 #endif /* not MSDOS */
310 #endif /* not WINDOWSNT */
314 #ifdef SIGTSTP
316 /* Arrange for character C to be read as the next input from
317 the terminal.
318 XXX What if we have multiple ttys?
321 void
322 stuff_char (char c)
324 if (! (FRAMEP (selected_frame)
325 && FRAME_LIVE_P (XFRAME (selected_frame))
326 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
327 return;
329 /* Should perhaps error if in batch mode */
330 #ifdef TIOCSTI
331 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
332 #else /* no TIOCSTI */
333 error ("Cannot stuff terminal input characters in this version of Unix");
334 #endif /* no TIOCSTI */
337 #endif /* SIGTSTP */
339 void
340 init_baud_rate (int fd)
342 int emacs_ospeed;
344 if (noninteractive)
345 emacs_ospeed = 0;
346 else
348 #ifdef DOS_NT
349 emacs_ospeed = 15;
350 #else /* not DOS_NT */
351 struct termios sg;
353 sg.c_cflag = B9600;
354 tcgetattr (fd, &sg);
355 emacs_ospeed = cfgetospeed (&sg);
356 #endif /* not DOS_NT */
359 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
360 ? baud_convert[emacs_ospeed] : 9600);
361 if (baud_rate == 0)
362 baud_rate = 1200;
367 #ifndef MSDOS
369 /* Wait for the subprocess with process id CHILD to terminate or change status.
370 CHILD must be a child process that has not been reaped.
371 If STATUS is non-null, store the waitpid-style exit status into *STATUS
372 and tell wait_reading_process_output that it needs to look around.
373 Use waitpid-style OPTIONS when waiting.
374 If INTERRUPTIBLE, this function is interruptible by a signal.
376 Return CHILD if successful, 0 if no status is available, and a
377 negative value (setting errno) if waitpid is buggy. */
378 static pid_t
379 get_child_status (pid_t child, int *status, int options, bool interruptible)
381 pid_t pid;
383 /* Invoke waitpid only with a known process ID; do not invoke
384 waitpid with a nonpositive argument. Otherwise, Emacs might
385 reap an unwanted process by mistake. For example, invoking
386 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
387 so that another thread running glib won't find them. */
388 eassert (child > 0);
390 while (true)
392 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
393 internally. */
394 if (interruptible)
395 maybe_quit ();
397 pid = waitpid (child, status, options);
398 if (0 <= pid)
399 break;
400 if (errno != EINTR)
402 /* Most likely, waitpid is buggy and the operating system
403 lost track of the child somehow. Return -1 and let the
404 caller try to figure things out. Possibly the bug could
405 cause Emacs to kill the wrong process. Oh well. */
406 return pid;
410 /* If successful and status is requested, tell wait_reading_process_output
411 that it needs to wake up and look around. */
412 if (pid && status && input_available_clear_time)
413 *input_available_clear_time = make_timespec (0, 0);
415 return pid;
418 /* Wait for the subprocess with process id CHILD to terminate.
419 CHILD must be a child process that has not been reaped.
420 If STATUS is non-null, store the waitpid-style exit status into *STATUS
421 and tell wait_reading_process_output that it needs to look around.
422 If INTERRUPTIBLE, this function is interruptible by a signal.
423 Return true if successful, false (setting errno) if CHILD cannot be
424 waited for because waitpid is buggy. */
425 bool
426 wait_for_termination (pid_t child, int *status, bool interruptible)
428 return 0 <= get_child_status (child, status, 0, interruptible);
431 /* Report whether the subprocess with process id CHILD has changed status.
432 Termination counts as a change of status.
433 CHILD must be a child process that has not been reaped.
434 If STATUS is non-null, store the waitpid-style exit status into *STATUS
435 and tell wait_reading_process_output that it needs to look around.
436 Use waitpid-style OPTIONS to check status, but do not wait.
438 Return CHILD if successful, 0 if no status is available because
439 the process's state has not changed. */
440 pid_t
441 child_status_changed (pid_t child, int *status, int options)
443 return get_child_status (child, status, WNOHANG | options, 0);
447 /* Set up the terminal at the other end of a pseudo-terminal that
448 we will be controlling an inferior through.
449 It should not echo or do line-editing, since that is done
450 in Emacs. No padding needed for insertion into an Emacs buffer. */
452 void
453 child_setup_tty (int out)
455 #ifndef WINDOWSNT
456 struct emacs_tty s;
458 emacs_get_tty (out, &s);
459 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
460 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
461 #ifdef NLDLY
462 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
463 Some versions of GNU Hurd do not have FFDLY? */
464 #ifdef FFDLY
465 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
466 /* No output delays */
467 #else
468 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
469 /* No output delays */
470 #endif
471 #endif
472 s.main.c_lflag &= ~ECHO; /* Disable echo */
473 s.main.c_lflag |= ISIG; /* Enable signals */
474 #ifdef IUCLC
475 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
476 #endif
477 #ifdef ISTRIP
478 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
479 #endif
480 #ifdef OLCUC
481 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
482 #endif
483 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
484 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
485 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
486 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
488 #ifdef HPUX
489 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
490 #endif /* HPUX */
492 #ifdef SIGNALS_VIA_CHARACTERS
493 /* the QUIT and INTR character are used in process_send_signal
494 so set them here to something useful. */
495 if (s.main.c_cc[VQUIT] == CDISABLE)
496 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
497 if (s.main.c_cc[VINTR] == CDISABLE)
498 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
499 #endif /* not SIGNALS_VIA_CHARACTERS */
501 #ifdef AIX
502 /* Also, PTY overloads NUL and BREAK.
503 don't ignore break, but don't signal either, so it looks like NUL. */
504 s.main.c_iflag &= ~IGNBRK;
505 s.main.c_iflag &= ~BRKINT;
506 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
507 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
508 would force it to 0377. That looks like duplicated code. */
509 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
510 #endif /* AIX */
512 /* We originally enabled ICANON (and set VEOF to 04), and then had
513 process.c send additional EOF chars to flush the output when faced
514 with long lines, but this leads to weird effects when the
515 subprocess has disabled ICANON and ends up seeing those spurious
516 extra EOFs. So we don't send EOFs any more in
517 process.c:send_process. First we tried to disable ICANON by
518 default, so if a subsprocess sets up ICANON, it's his problem (or
519 the Elisp package that talks to it) to deal with lines that are
520 too long. But this disables some features, such as the ability
521 to send EOF signals. So we re-enabled ICANON but there is no
522 more "send eof to flush" going on (which is wrong and unportable
523 in itself). The correct way to handle too much output is to
524 buffer what could not be written and then write it again when
525 select returns ok for writing. This has it own set of
526 problems. Write is now asynchronous, is that a problem? How much
527 do we buffer, and what do we do when that limit is reached? */
529 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
530 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
531 #if 0 /* These settings only apply to non-ICANON mode. */
532 s.main.c_cc[VMIN] = 1;
533 s.main.c_cc[VTIME] = 0;
534 #endif
536 emacs_set_tty (out, &s, 0);
537 #endif /* not WINDOWSNT */
539 #endif /* not MSDOS */
542 /* Record a signal code and the action for it. */
543 struct save_signal
545 int code;
546 struct sigaction action;
549 static void save_signal_handlers (struct save_signal *);
550 static void restore_signal_handlers (struct save_signal *);
552 /* Suspend the Emacs process; give terminal to its superior. */
554 void
555 sys_suspend (void)
557 #ifndef DOS_NT
558 kill (0, SIGTSTP);
559 #else
560 /* On a system where suspending is not implemented,
561 instead fork a subshell and let it talk directly to the terminal
562 while we wait. */
563 sys_subshell ();
565 #endif
568 /* Fork a subshell. */
570 void
571 sys_subshell (void)
573 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
574 #ifdef MSDOS
575 int st;
576 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
577 #else
578 char oldwd[MAX_UTF8_PATH];
579 #endif /* MSDOS */
580 #else /* !DOS_NT */
581 int status;
582 #endif
583 pid_t pid;
584 struct save_signal saved_handlers[5];
585 char *str = SSDATA (encode_current_directory ());
587 #ifdef DOS_NT
588 pid = 0;
589 #else
591 char *volatile str_volatile = str;
592 pid = vfork ();
593 str = str_volatile;
595 #endif
597 if (pid < 0)
598 error ("Can't spawn subshell");
600 saved_handlers[0].code = SIGINT;
601 saved_handlers[1].code = SIGQUIT;
602 saved_handlers[2].code = SIGTERM;
603 #ifdef USABLE_SIGIO
604 saved_handlers[3].code = SIGIO;
605 saved_handlers[4].code = 0;
606 #else
607 saved_handlers[3].code = 0;
608 #endif
610 #ifdef DOS_NT
611 save_signal_handlers (saved_handlers);
612 #endif
614 if (pid == 0)
616 const char *sh = 0;
618 #ifdef DOS_NT /* MW, Aug 1993 */
619 getcwd (oldwd, sizeof oldwd);
620 if (sh == 0)
621 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
622 #endif
623 if (sh == 0)
624 sh = egetenv ("SHELL");
625 if (sh == 0)
626 sh = "sh";
628 /* Use our buffer's default directory for the subshell. */
629 if (chdir (str) != 0)
631 #ifndef DOS_NT
632 emacs_perror (str);
633 _exit (EXIT_CANCELED);
634 #endif
637 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
639 char *epwd = getenv ("PWD");
640 char old_pwd[MAXPATHLEN+1+4];
642 /* If PWD is set, pass it with corrected value. */
643 if (epwd)
645 strcpy (old_pwd, epwd);
646 setenv ("PWD", str, 1);
648 st = system (sh);
649 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
650 if (epwd)
651 putenv (old_pwd); /* restore previous value */
653 #else /* not MSDOS */
654 #ifdef WINDOWSNT
655 /* Waits for process completion */
656 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
657 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
658 if (pid == -1)
659 write (1, "Can't execute subshell", 22);
660 #else /* not WINDOWSNT */
661 execlp (sh, sh, (char *) 0);
662 emacs_perror (sh);
663 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
664 #endif /* not WINDOWSNT */
665 #endif /* not MSDOS */
668 /* Do this now if we did not do it before. */
669 #ifndef MSDOS
670 save_signal_handlers (saved_handlers);
671 #endif
673 #ifndef DOS_NT
674 wait_for_termination (pid, &status, 0);
675 #endif
676 restore_signal_handlers (saved_handlers);
679 static void
680 save_signal_handlers (struct save_signal *saved_handlers)
682 while (saved_handlers->code)
684 struct sigaction action;
685 emacs_sigaction_init (&action, SIG_IGN);
686 sigaction (saved_handlers->code, &action, &saved_handlers->action);
687 saved_handlers++;
691 static void
692 restore_signal_handlers (struct save_signal *saved_handlers)
694 while (saved_handlers->code)
696 sigaction (saved_handlers->code, &saved_handlers->action, 0);
697 saved_handlers++;
701 #ifdef USABLE_SIGIO
702 static int old_fcntl_flags[FD_SETSIZE];
703 #endif
705 void
706 init_sigio (int fd)
708 #ifdef USABLE_SIGIO
709 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
710 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
711 interrupts_deferred = 0;
712 #endif
715 #ifndef DOS_NT
716 static void
717 reset_sigio (int fd)
719 #ifdef USABLE_SIGIO
720 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
721 #endif
723 #endif
725 void
726 request_sigio (void)
728 #ifdef USABLE_SIGIO
729 sigset_t unblocked;
731 if (noninteractive)
732 return;
734 sigemptyset (&unblocked);
735 # ifdef SIGWINCH
736 sigaddset (&unblocked, SIGWINCH);
737 # endif
738 sigaddset (&unblocked, SIGIO);
739 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
741 interrupts_deferred = 0;
742 #endif
745 void
746 unrequest_sigio (void)
748 #ifdef USABLE_SIGIO
749 sigset_t blocked;
751 if (noninteractive)
752 return;
754 sigemptyset (&blocked);
755 # ifdef SIGWINCH
756 sigaddset (&blocked, SIGWINCH);
757 # endif
758 sigaddset (&blocked, SIGIO);
759 pthread_sigmask (SIG_BLOCK, &blocked, 0);
760 interrupts_deferred = 1;
761 #endif
764 #ifndef MSDOS
765 /* Block SIGCHLD. */
767 void
768 block_child_signal (sigset_t *oldset)
770 sigset_t blocked;
771 sigemptyset (&blocked);
772 sigaddset (&blocked, SIGCHLD);
773 sigaddset (&blocked, SIGINT);
774 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
777 /* Unblock SIGCHLD. */
779 void
780 unblock_child_signal (sigset_t const *oldset)
782 pthread_sigmask (SIG_SETMASK, oldset, 0);
785 /* Block SIGINT. */
786 void
787 block_interrupt_signal (sigset_t *oldset)
789 sigset_t blocked;
790 sigemptyset (&blocked);
791 sigaddset (&blocked, SIGINT);
792 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
795 /* Restore previously saved signal mask. */
796 void
797 restore_signal_mask (sigset_t const *oldset)
799 pthread_sigmask (SIG_SETMASK, oldset, 0);
802 #endif /* !MSDOS */
804 /* Saving and restoring the process group of Emacs's terminal. */
806 /* The process group of which Emacs was a member when it initially
807 started.
809 If Emacs was in its own process group (i.e. inherited_pgroup ==
810 getpid ()), then we know we're running under a shell with job
811 control (Emacs would never be run as part of a pipeline).
812 Everything is fine.
814 If Emacs was not in its own process group, then we know we're
815 running under a shell (or a caller) that doesn't know how to
816 separate itself from Emacs (like sh). Emacs must be in its own
817 process group in order to receive SIGIO correctly. In this
818 situation, we put ourselves in our own pgroup, forcibly set the
819 tty's pgroup to our pgroup, and make sure to restore and reinstate
820 the tty's pgroup just like any other terminal setting. If
821 inherited_group was not the tty's pgroup, then we'll get a
822 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
823 it goes foreground in the future, which is what should happen. */
825 static pid_t inherited_pgroup;
827 void
828 init_foreground_group (void)
830 pid_t pgrp = getpgrp ();
831 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
834 /* Block and unblock SIGTTOU. */
836 void
837 block_tty_out_signal (sigset_t *oldset)
839 #ifdef SIGTTOU
840 sigset_t blocked;
841 sigemptyset (&blocked);
842 sigaddset (&blocked, SIGTTOU);
843 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
844 #endif
847 void
848 unblock_tty_out_signal (sigset_t const *oldset)
850 #ifdef SIGTTOU
851 pthread_sigmask (SIG_SETMASK, oldset, 0);
852 #endif
855 /* Safely set a controlling terminal FD's process group to PGID.
856 If we are not in the foreground already, POSIX requires tcsetpgrp
857 to deliver a SIGTTOU signal, which would stop us. This is an
858 annoyance, so temporarily ignore the signal.
860 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
861 skip all this unless SIGTTOU is defined. */
862 static void
863 tcsetpgrp_without_stopping (int fd, pid_t pgid)
865 #ifdef SIGTTOU
866 sigset_t oldset;
867 block_input ();
868 block_tty_out_signal (&oldset);
869 tcsetpgrp (fd, pgid);
870 unblock_tty_out_signal (&oldset);
871 unblock_input ();
872 #endif
875 /* Split off the foreground process group to Emacs alone. When we are
876 in the foreground, but not started in our own process group,
877 redirect the tty device handle FD to point to our own process
878 group. FD must be the file descriptor of the controlling tty. */
879 static void
880 narrow_foreground_group (int fd)
882 if (inherited_pgroup && setpgid (0, 0) == 0)
883 tcsetpgrp_without_stopping (fd, getpid ());
886 /* Set the tty to our original foreground group. */
887 static void
888 widen_foreground_group (int fd)
890 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
891 tcsetpgrp_without_stopping (fd, inherited_pgroup);
894 /* Getting and setting emacs_tty structures. */
896 /* Set *TC to the parameters associated with the terminal FD,
897 or clear it if the parameters are not available.
898 Return 0 on success, -1 on failure. */
900 emacs_get_tty (int fd, struct emacs_tty *settings)
902 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
903 memset (&settings->main, 0, sizeof (settings->main));
904 #ifdef DOS_NT
905 #ifdef WINDOWSNT
906 HANDLE h = (HANDLE)_get_osfhandle (fd);
907 DWORD console_mode;
909 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
911 settings->main = console_mode;
912 return 0;
914 #endif /* WINDOWSNT */
915 return -1;
916 #else /* !DOS_NT */
917 /* We have those nifty POSIX tcmumbleattr functions. */
918 return tcgetattr (fd, &settings->main);
919 #endif
923 /* Set the parameters of the tty on FD according to the contents of
924 *SETTINGS. If FLUSHP, discard input.
925 Return 0 if all went well, and -1 (setting errno) if anything failed. */
928 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
930 /* Set the primary parameters - baud rate, character size, etcetera. */
931 #ifdef DOS_NT
932 #ifdef WINDOWSNT
933 HANDLE h = (HANDLE)_get_osfhandle (fd);
935 if (h && h != INVALID_HANDLE_VALUE)
937 DWORD new_mode;
939 /* Assume the handle is open for input. */
940 if (flushp)
941 FlushConsoleInputBuffer (h);
942 new_mode = settings->main;
943 SetConsoleMode (h, new_mode);
945 #endif /* WINDOWSNT */
946 #else /* !DOS_NT */
947 int i;
948 /* We have those nifty POSIX tcmumbleattr functions.
949 William J. Smith <wjs@wiis.wang.com> writes:
950 "POSIX 1003.1 defines tcsetattr to return success if it was
951 able to perform any of the requested actions, even if some
952 of the requested actions could not be performed.
953 We must read settings back to ensure tty setup properly.
954 AIX requires this to keep tty from hanging occasionally." */
955 /* This make sure that we don't loop indefinitely in here. */
956 for (i = 0 ; i < 10 ; i++)
957 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
959 if (errno == EINTR)
960 continue;
961 else
962 return -1;
964 else
966 struct termios new;
968 memset (&new, 0, sizeof (new));
969 /* Get the current settings, and see if they're what we asked for. */
970 tcgetattr (fd, &new);
971 /* We cannot use memcmp on the whole structure here because under
972 * aix386 the termios structure has some reserved field that may
973 * not be filled in.
975 if ( new.c_iflag == settings->main.c_iflag
976 && new.c_oflag == settings->main.c_oflag
977 && new.c_cflag == settings->main.c_cflag
978 && new.c_lflag == settings->main.c_lflag
979 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
980 break;
981 else
982 continue;
984 #endif
986 /* We have survived the tempest. */
987 return 0;
992 #ifdef F_SETOWN
993 static int old_fcntl_owner[FD_SETSIZE];
994 #endif /* F_SETOWN */
996 /* This may also be defined in stdio,
997 but if so, this does no harm,
998 and using the same name avoids wasting the other one's space. */
1000 #if defined (USG)
1001 unsigned char _sobuf[BUFSIZ+8];
1002 #else
1003 char _sobuf[BUFSIZ];
1004 #endif
1006 /* Initialize the terminal mode on all tty devices that are currently
1007 open. */
1009 void
1010 init_all_sys_modes (void)
1012 struct tty_display_info *tty;
1013 for (tty = tty_list; tty; tty = tty->next)
1014 init_sys_modes (tty);
1017 /* Initialize the terminal mode on the given tty device. */
1019 void
1020 init_sys_modes (struct tty_display_info *tty_out)
1022 struct emacs_tty tty;
1023 #ifndef DOS_NT
1024 Lisp_Object terminal;
1025 #endif
1027 Vtty_erase_char = Qnil;
1029 if (noninteractive)
1030 return;
1032 if (!tty_out->output)
1033 return; /* The tty is suspended. */
1035 narrow_foreground_group (fileno (tty_out->input));
1037 if (! tty_out->old_tty)
1038 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1040 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1042 tty = *tty_out->old_tty;
1044 #if !defined (DOS_NT)
1045 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1047 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1048 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1049 #ifdef INLCR /* I'm just being cautious,
1050 since I can't check how widespread INLCR is--rms. */
1051 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1052 #endif
1053 #ifdef ISTRIP
1054 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1055 #endif
1056 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1057 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1058 #ifdef IEXTEN
1059 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1060 #endif
1061 tty.main.c_lflag |= ISIG; /* Enable signals */
1062 if (tty_out->flow_control)
1064 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1065 #ifdef IXANY
1066 tty.main.c_iflag &= ~IXANY;
1067 #endif /* IXANY */
1069 else
1070 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1071 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1072 on output */
1073 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1074 #ifdef CS8
1075 if (tty_out->meta_key)
1077 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1078 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1080 #endif
1082 XSETTERMINAL(terminal, tty_out->terminal);
1083 if (!NILP (Fcontrolling_tty_p (terminal)))
1085 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1086 /* Set up C-g for both SIGQUIT and SIGINT.
1087 We don't know which we will get, but we handle both alike
1088 so which one it really gives us does not matter. */
1089 tty.main.c_cc[VQUIT] = quit_char;
1091 else
1093 /* We normally don't get interrupt or quit signals from tty
1094 devices other than our controlling terminal; therefore,
1095 we must handle C-g as normal input. Unfortunately, this
1096 means that the interrupt and quit feature must be
1097 disabled on secondary ttys, or we would not even see the
1098 keypress.
1100 Note that even though emacsclient could have special code
1101 to pass SIGINT to Emacs, we should _not_ enable
1102 interrupt/quit keys for emacsclient frames. This means
1103 that we can't break out of loops in C code from a
1104 secondary tty frame, but we can always decide what
1105 display the C-g came from, which is more important from a
1106 usability point of view. (Consider the case when two
1107 people work together using the same Emacs instance.) */
1108 tty.main.c_cc[VINTR] = CDISABLE;
1109 tty.main.c_cc[VQUIT] = CDISABLE;
1111 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1112 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1113 #ifdef VSWTCH
1114 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1115 of C-z */
1116 #endif /* VSWTCH */
1118 #ifdef VSUSP
1119 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1120 #endif /* VSUSP */
1121 #ifdef V_DSUSP
1122 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1123 #endif /* V_DSUSP */
1124 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1125 tty.main.c_cc[VDSUSP] = CDISABLE;
1126 #endif /* VDSUSP */
1127 #ifdef VLNEXT
1128 tty.main.c_cc[VLNEXT] = CDISABLE;
1129 #endif /* VLNEXT */
1130 #ifdef VREPRINT
1131 tty.main.c_cc[VREPRINT] = CDISABLE;
1132 #endif /* VREPRINT */
1133 #ifdef VWERASE
1134 tty.main.c_cc[VWERASE] = CDISABLE;
1135 #endif /* VWERASE */
1136 #ifdef VDISCARD
1137 tty.main.c_cc[VDISCARD] = CDISABLE;
1138 #endif /* VDISCARD */
1140 if (tty_out->flow_control)
1142 #ifdef VSTART
1143 tty.main.c_cc[VSTART] = '\021';
1144 #endif /* VSTART */
1145 #ifdef VSTOP
1146 tty.main.c_cc[VSTOP] = '\023';
1147 #endif /* VSTOP */
1149 else
1151 #ifdef VSTART
1152 tty.main.c_cc[VSTART] = CDISABLE;
1153 #endif /* VSTART */
1154 #ifdef VSTOP
1155 tty.main.c_cc[VSTOP] = CDISABLE;
1156 #endif /* VSTOP */
1159 #ifdef AIX
1160 tty.main.c_cc[VSTRT] = CDISABLE;
1161 tty.main.c_cc[VSTOP] = CDISABLE;
1162 tty.main.c_cc[VSUSP] = CDISABLE;
1163 tty.main.c_cc[VDSUSP] = CDISABLE;
1164 if (tty_out->flow_control)
1166 #ifdef VSTART
1167 tty.main.c_cc[VSTART] = '\021';
1168 #endif /* VSTART */
1169 #ifdef VSTOP
1170 tty.main.c_cc[VSTOP] = '\023';
1171 #endif /* VSTOP */
1173 /* Also, PTY overloads NUL and BREAK.
1174 don't ignore break, but don't signal either, so it looks like NUL.
1175 This really serves a purpose only if running in an XTERM window
1176 or via TELNET or the like, but does no harm elsewhere. */
1177 tty.main.c_iflag &= ~IGNBRK;
1178 tty.main.c_iflag &= ~BRKINT;
1179 #endif
1180 #endif /* not DOS_NT */
1182 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1183 if (!tty_out->term_initted)
1184 internal_terminal_init ();
1185 dos_ttraw (tty_out);
1186 #endif
1188 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1190 /* This code added to insure that, if flow-control is not to be used,
1191 we have an unlocked terminal at the start. */
1193 #ifdef TCXONC
1194 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1195 #endif
1196 #ifdef TIOCSTART
1197 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1198 #endif
1200 #if !defined (DOS_NT)
1201 #ifdef TCOON
1202 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1203 #endif
1204 #endif
1206 #ifdef F_GETOWN
1207 if (interrupt_input)
1209 old_fcntl_owner[fileno (tty_out->input)] =
1210 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1211 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1212 init_sigio (fileno (tty_out->input));
1213 #ifdef HAVE_GPM
1214 if (gpm_tty == tty_out)
1216 /* Arrange for mouse events to give us SIGIO signals. */
1217 fcntl (gpm_fd, F_SETOWN, getpid ());
1218 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1219 init_sigio (gpm_fd);
1221 #endif /* HAVE_GPM */
1223 #endif /* F_GETOWN */
1225 #ifdef _IOFBF
1226 /* This symbol is defined on recent USG systems.
1227 Someone says without this call USG won't really buffer the file
1228 even with a call to setbuf. */
1229 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1230 #else
1231 setbuf (tty_out->output, (char *) _sobuf);
1232 #endif
1234 if (tty_out->terminal->set_terminal_modes_hook)
1235 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1237 if (!tty_out->term_initted)
1239 Lisp_Object tail, frame;
1240 FOR_EACH_FRAME (tail, frame)
1242 /* XXX This needs to be revised. */
1243 if (FRAME_TERMCAP_P (XFRAME (frame))
1244 && FRAME_TTY (XFRAME (frame)) == tty_out)
1245 init_frame_faces (XFRAME (frame));
1249 if (tty_out->term_initted && no_redraw_on_reenter)
1251 /* We used to call "direct_output_forward_char(0)" here,
1252 but it's not clear why, since it may not do anything anyway. */
1254 else
1256 Lisp_Object tail, frame;
1257 frame_garbaged = 1;
1258 FOR_EACH_FRAME (tail, frame)
1260 if ((FRAME_TERMCAP_P (XFRAME (frame))
1261 || FRAME_MSDOS_P (XFRAME (frame)))
1262 && FRAME_TTY (XFRAME (frame)) == tty_out)
1263 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1267 tty_out->term_initted = 1;
1270 /* Return true if safe to use tabs in output.
1271 At the time this is called, init_sys_modes has not been done yet. */
1273 bool
1274 tabs_safe_p (int fd)
1276 struct emacs_tty etty;
1278 emacs_get_tty (fd, &etty);
1279 #ifndef DOS_NT
1280 #ifdef TABDLY
1281 return ((etty.main.c_oflag & TABDLY) != TAB3);
1282 #else /* not TABDLY */
1283 return 1;
1284 #endif /* not TABDLY */
1285 #else /* DOS_NT */
1286 return 0;
1287 #endif /* DOS_NT */
1290 /* Discard echoing. */
1292 void
1293 suppress_echo_on_tty (int fd)
1295 struct emacs_tty etty;
1297 emacs_get_tty (fd, &etty);
1298 #ifdef DOS_NT
1299 /* Set raw input mode. */
1300 etty.main = 0;
1301 #else
1302 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1303 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1304 #endif /* ! WINDOWSNT */
1305 emacs_set_tty (fd, &etty, 0);
1308 /* Get terminal size from system.
1309 Store number of lines into *HEIGHTP and width into *WIDTHP.
1310 We store 0 if there's no valid information. */
1312 void
1313 get_tty_size (int fd, int *widthp, int *heightp)
1315 #if defined TIOCGWINSZ
1317 /* BSD-style. */
1318 struct winsize size;
1320 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1321 *widthp = *heightp = 0;
1322 else
1324 *widthp = size.ws_col;
1325 *heightp = size.ws_row;
1328 #elif defined TIOCGSIZE
1330 /* SunOS - style. */
1331 struct ttysize size;
1333 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1334 *widthp = *heightp = 0;
1335 else
1337 *widthp = size.ts_cols;
1338 *heightp = size.ts_lines;
1341 #elif defined WINDOWSNT
1343 CONSOLE_SCREEN_BUFFER_INFO info;
1344 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1346 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1347 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1349 else
1350 *widthp = *heightp = 0;
1352 #elif defined MSDOS
1354 *widthp = ScreenCols ();
1355 *heightp = ScreenRows ();
1357 #else /* system doesn't know size */
1359 *widthp = 0;
1360 *heightp = 0;
1362 #endif
1365 /* Set the logical window size associated with descriptor FD
1366 to HEIGHT and WIDTH. This is used mainly with ptys.
1367 Return a negative value on failure. */
1370 set_window_size (int fd, int height, int width)
1372 #ifdef TIOCSWINSZ
1374 /* BSD-style. */
1375 struct winsize size;
1376 size.ws_row = height;
1377 size.ws_col = width;
1379 return ioctl (fd, TIOCSWINSZ, &size);
1381 #else
1382 #ifdef TIOCSSIZE
1384 /* SunOS - style. */
1385 struct ttysize size;
1386 size.ts_lines = height;
1387 size.ts_cols = width;
1389 return ioctl (fd, TIOCGSIZE, &size);
1390 #else
1391 return -1;
1392 #endif /* not SunOS-style */
1393 #endif /* not BSD-style */
1398 /* Prepare all terminal devices for exiting Emacs. */
1400 void
1401 reset_all_sys_modes (void)
1403 struct tty_display_info *tty;
1404 for (tty = tty_list; tty; tty = tty->next)
1405 reset_sys_modes (tty);
1408 /* Prepare the terminal for closing it; move the cursor to the
1409 bottom of the frame, turn off interrupt-driven I/O, etc. */
1411 void
1412 reset_sys_modes (struct tty_display_info *tty_out)
1414 if (noninteractive)
1416 fflush_unlocked (stdout);
1417 return;
1419 if (!tty_out->term_initted)
1420 return;
1422 if (!tty_out->output)
1423 return; /* The tty is suspended. */
1425 /* Go to and clear the last line of the terminal. */
1427 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1429 /* Code adapted from tty_clear_end_of_line. */
1430 if (tty_out->TS_clr_line)
1432 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1434 else
1435 { /* have to do it the hard way */
1436 tty_turn_off_insert (tty_out);
1438 for (int i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1439 fputc_unlocked (' ', tty_out->output);
1442 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1443 fflush_unlocked (tty_out->output);
1445 if (tty_out->terminal->reset_terminal_modes_hook)
1446 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1448 /* Avoid possible loss of output when changing terminal modes. */
1449 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1450 continue;
1452 #ifndef DOS_NT
1453 #ifdef F_SETOWN
1454 if (interrupt_input)
1456 reset_sigio (fileno (tty_out->input));
1457 fcntl (fileno (tty_out->input), F_SETOWN,
1458 old_fcntl_owner[fileno (tty_out->input)]);
1460 #endif /* F_SETOWN */
1461 fcntl (fileno (tty_out->input), F_SETFL,
1462 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1463 #endif
1465 if (tty_out->old_tty)
1466 while (emacs_set_tty (fileno (tty_out->input),
1467 tty_out->old_tty, 0) < 0 && errno == EINTR)
1470 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1471 dos_ttcooked ();
1472 #endif
1474 widen_foreground_group (fileno (tty_out->input));
1477 #ifdef HAVE_PTYS
1479 /* Set up the proper status flags for use of a pty. */
1481 void
1482 setup_pty (int fd)
1484 /* I'm told that TOICREMOTE does not mean control chars
1485 "can't be sent" but rather that they don't have
1486 input-editing or signaling effects.
1487 That should be good, because we have other ways
1488 to do those things in Emacs.
1489 However, telnet mode seems not to work on 4.2.
1490 So TIOCREMOTE is turned off now. */
1492 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1493 will hang. In particular, the "timeout" feature (which
1494 causes a read to return if there is no data available)
1495 does this. Also it is known that telnet mode will hang
1496 in such a way that Emacs must be stopped (perhaps this
1497 is the same problem).
1499 If TIOCREMOTE is turned off, then there is a bug in
1500 hp-ux which sometimes loses data. Apparently the
1501 code which blocks the master process when the internal
1502 buffer fills up does not work. Other than this,
1503 though, everything else seems to work fine.
1505 Since the latter lossage is more benign, we may as well
1506 lose that way. -- cph */
1507 #ifdef FIONBIO
1508 #if defined (UNIX98_PTYS)
1510 int on = 1;
1511 ioctl (fd, FIONBIO, &on);
1513 #endif
1514 #endif
1516 #endif /* HAVE_PTYS */
1518 void
1519 init_system_name (void)
1521 if (!build_details)
1523 /* Set system-name to nil so that the build is deterministic. */
1524 Vsystem_name = Qnil;
1525 return;
1527 char *hostname_alloc = NULL;
1528 char *hostname;
1529 #ifndef HAVE_GETHOSTNAME
1530 struct utsname uts;
1531 uname (&uts);
1532 hostname = uts.nodename;
1533 #else /* HAVE_GETHOSTNAME */
1534 char hostname_buf[256];
1535 ptrdiff_t hostname_size = sizeof hostname_buf;
1536 hostname = hostname_buf;
1538 /* Try to get the host name; if the buffer is too short, try
1539 again. Apparently, the only indication gethostname gives of
1540 whether the buffer was large enough is the presence or absence
1541 of a '\0' in the string. Eech. */
1542 for (;;)
1544 gethostname (hostname, hostname_size - 1);
1545 hostname[hostname_size - 1] = '\0';
1547 /* Was the buffer large enough for the '\0'? */
1548 if (strlen (hostname) < hostname_size - 1)
1549 break;
1551 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1552 min (PTRDIFF_MAX, SIZE_MAX), 1);
1554 #endif /* HAVE_GETHOSTNAME */
1555 char *p;
1556 for (p = hostname; *p; p++)
1557 if (*p == ' ' || *p == '\t')
1558 *p = '-';
1559 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1560 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1561 Vsystem_name = build_string (hostname);
1562 xfree (hostname_alloc);
1565 sigset_t empty_mask;
1567 static struct sigaction process_fatal_action;
1569 static int
1570 emacs_sigaction_flags (void)
1572 #ifdef SA_RESTART
1573 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1574 'select') to reset their timeout on some platforms (e.g.,
1575 HP-UX 11), which is not what we want. Also, when Emacs is
1576 interactive, we don't want SA_RESTART because we need to poll
1577 for pending input so we need long-running syscalls to be interrupted
1578 after a signal that sets pending_signals.
1580 Non-interactive keyboard input goes through stdio, where we
1581 always want restartable system calls. */
1582 if (noninteractive)
1583 return SA_RESTART;
1584 #endif
1585 return 0;
1588 /* Store into *ACTION a signal action suitable for Emacs, with handler
1589 HANDLER. */
1590 void
1591 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1593 sigemptyset (&action->sa_mask);
1595 /* When handling a signal, block nonfatal system signals that are caught
1596 by Emacs. This makes race conditions less likely. */
1597 sigaddset (&action->sa_mask, SIGALRM);
1598 #ifdef SIGCHLD
1599 sigaddset (&action->sa_mask, SIGCHLD);
1600 #endif
1601 #ifdef SIGDANGER
1602 sigaddset (&action->sa_mask, SIGDANGER);
1603 #endif
1604 #ifdef PROFILER_CPU_SUPPORT
1605 sigaddset (&action->sa_mask, SIGPROF);
1606 #endif
1607 #ifdef SIGWINCH
1608 sigaddset (&action->sa_mask, SIGWINCH);
1609 #endif
1610 if (! noninteractive)
1612 sigaddset (&action->sa_mask, SIGINT);
1613 sigaddset (&action->sa_mask, SIGQUIT);
1614 #ifdef USABLE_SIGIO
1615 sigaddset (&action->sa_mask, SIGIO);
1616 #endif
1619 action->sa_handler = handler;
1620 action->sa_flags = emacs_sigaction_flags ();
1623 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1624 pthread_t main_thread_id;
1625 #endif
1627 /* SIG has arrived at the current process. Deliver it to the main
1628 thread, which should handle it with HANDLER. (Delivering the
1629 signal to some other thread might not work if the other thread is
1630 about to exit.)
1632 If we are on the main thread, handle the signal SIG with HANDLER.
1633 Otherwise, redirect the signal to the main thread, blocking it from
1634 this thread. POSIX says any thread can receive a signal that is
1635 associated with a process, process group, or asynchronous event.
1636 On GNU/Linux the main thread typically gets a process signal unless
1637 it's blocked, but other systems (FreeBSD at least) can deliver the
1638 signal to other threads. */
1639 void
1640 deliver_process_signal (int sig, signal_handler_t handler)
1642 /* Preserve errno, to avoid race conditions with signal handlers that
1643 might change errno. Races can occur even in single-threaded hosts. */
1644 int old_errno = errno;
1646 bool on_main_thread = true;
1647 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1648 if (! pthread_equal (pthread_self (), main_thread_id))
1650 sigset_t blocked;
1651 sigemptyset (&blocked);
1652 sigaddset (&blocked, sig);
1653 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1654 pthread_kill (main_thread_id, sig);
1655 on_main_thread = false;
1657 #endif
1658 if (on_main_thread)
1659 handler (sig);
1661 errno = old_errno;
1664 /* Static location to save a fatal backtrace in a thread.
1665 FIXME: If two subsidiary threads fail simultaneously, the resulting
1666 backtrace may be garbage. */
1667 enum { BACKTRACE_LIMIT_MAX = 500 };
1668 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1669 static int thread_backtrace_npointers;
1671 /* SIG has arrived at the current thread.
1672 If we are on the main thread, handle the signal SIG with HANDLER.
1673 Otherwise, this is a fatal error in the handling thread. */
1674 static void
1675 deliver_thread_signal (int sig, signal_handler_t handler)
1677 int old_errno = errno;
1679 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1680 if (! pthread_equal (pthread_self (), main_thread_id))
1682 thread_backtrace_npointers
1683 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1684 sigaction (sig, &process_fatal_action, 0);
1685 pthread_kill (main_thread_id, sig);
1687 /* Avoid further damage while the main thread is exiting. */
1688 while (1)
1689 sigsuspend (&empty_mask);
1691 #endif
1693 handler (sig);
1694 errno = old_errno;
1697 #if !HAVE_DECL_SYS_SIGLIST
1698 # undef sys_siglist
1699 # ifdef _sys_siglist
1700 # define sys_siglist _sys_siglist
1701 # elif HAVE_DECL___SYS_SIGLIST
1702 # define sys_siglist __sys_siglist
1703 # else
1704 # define sys_siglist my_sys_siglist
1705 static char const *sys_siglist[NSIG];
1706 # endif
1707 #endif
1709 #ifdef _sys_nsig
1710 # define sys_siglist_entries _sys_nsig
1711 #else
1712 # define sys_siglist_entries NSIG
1713 #endif
1715 /* Handle bus errors, invalid instruction, etc. */
1716 static void
1717 handle_fatal_signal (int sig)
1719 terminate_due_to_signal (sig, 40);
1722 static void
1723 deliver_fatal_signal (int sig)
1725 deliver_process_signal (sig, handle_fatal_signal);
1728 static void
1729 deliver_fatal_thread_signal (int sig)
1731 deliver_thread_signal (sig, handle_fatal_signal);
1734 static _Noreturn void
1735 handle_arith_signal (int sig)
1737 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1738 xsignal0 (Qarith_error);
1741 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1743 /* Alternate stack used by SIGSEGV handler below. */
1745 static unsigned char sigsegv_stack[SIGSTKSZ];
1748 /* Return true if SIGINFO indicates a stack overflow. */
1750 static bool
1751 stack_overflow (siginfo_t *siginfo)
1753 if (!attempt_stack_overflow_recovery)
1754 return false;
1756 /* In theory, a more-accurate heuristic can be obtained by using
1757 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1758 and pthread_attr_getguardsize to find the location and size of the
1759 guard area. In practice, though, these functions are so hard to
1760 use reliably that they're not worth bothering with. E.g., see:
1761 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1762 Other operating systems also have problems, e.g., Solaris's
1763 stack_violation function is tailor-made for this problem, but it
1764 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1766 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1767 candidate here. */
1769 if (!siginfo)
1770 return false;
1772 /* The faulting address. */
1773 char *addr = siginfo->si_addr;
1774 if (!addr)
1775 return false;
1777 /* The known top and bottom of the stack. The actual stack may
1778 extend a bit beyond these boundaries. */
1779 char *bot = stack_bottom;
1780 char *top = current_thread->stack_top;
1782 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1783 of the known stack divided by the size of the guard area past the
1784 end of the stack top. The heuristic is that a bad address is
1785 considered to be a stack overflow if it occurs within
1786 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1787 stack. This heuristic is not exactly correct but it's good
1788 enough in practice. */
1789 enum { LG_STACK_HEURISTIC = 8 };
1791 if (bot < top)
1792 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1793 else
1794 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1798 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1800 static void
1801 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1803 /* Hard GC error may lead to stack overflow caused by
1804 too nested calls to mark_object. No way to survive. */
1805 bool fatal = gc_in_progress;
1807 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1808 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1809 fatal = true;
1810 #endif
1812 if (!fatal && stack_overflow (siginfo))
1813 siglongjmp (return_to_command_loop, 1);
1815 /* Otherwise we can't do anything with this. */
1816 deliver_fatal_thread_signal (sig);
1819 /* Return true if we have successfully set up SIGSEGV handler on alternate
1820 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1822 static bool
1823 init_sigsegv (void)
1825 struct sigaction sa;
1826 stack_t ss;
1828 ss.ss_sp = sigsegv_stack;
1829 ss.ss_size = sizeof (sigsegv_stack);
1830 ss.ss_flags = 0;
1831 if (sigaltstack (&ss, NULL) < 0)
1832 return 0;
1834 sigfillset (&sa.sa_mask);
1835 sa.sa_sigaction = handle_sigsegv;
1836 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1837 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1840 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1842 static bool
1843 init_sigsegv (void)
1845 return 0;
1848 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1850 static void
1851 deliver_arith_signal (int sig)
1853 deliver_thread_signal (sig, handle_arith_signal);
1856 #ifdef SIGDANGER
1858 /* Handler for SIGDANGER. */
1859 static void
1860 handle_danger_signal (int sig)
1862 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1864 /* It might be unsafe to call do_auto_save now. */
1865 force_auto_save_soon ();
1868 static void
1869 deliver_danger_signal (int sig)
1871 deliver_process_signal (sig, handle_danger_signal);
1873 #endif
1875 /* Treat SIG as a terminating signal, unless it is already ignored and
1876 we are in --batch mode. Among other things, this makes nohup work. */
1877 static void
1878 maybe_fatal_sig (int sig)
1880 bool catch_sig = !noninteractive;
1881 if (!catch_sig)
1883 struct sigaction old_action;
1884 sigaction (sig, 0, &old_action);
1885 catch_sig = old_action.sa_handler != SIG_IGN;
1887 if (catch_sig)
1888 sigaction (sig, &process_fatal_action, 0);
1891 void
1892 init_signals (bool dumping)
1894 struct sigaction thread_fatal_action;
1895 struct sigaction action;
1897 sigemptyset (&empty_mask);
1899 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1900 main_thread_id = pthread_self ();
1901 #endif
1903 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1904 if (! initialized)
1906 sys_siglist[SIGABRT] = "Aborted";
1907 # ifdef SIGAIO
1908 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1909 # endif
1910 sys_siglist[SIGALRM] = "Alarm clock";
1911 # ifdef SIGBUS
1912 sys_siglist[SIGBUS] = "Bus error";
1913 # endif
1914 # ifdef SIGCHLD
1915 sys_siglist[SIGCHLD] = "Child status changed";
1916 # endif
1917 # ifdef SIGCONT
1918 sys_siglist[SIGCONT] = "Continued";
1919 # endif
1920 # ifdef SIGDANGER
1921 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1922 # endif
1923 # ifdef SIGDGNOTIFY
1924 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1925 # endif
1926 # ifdef SIGEMT
1927 sys_siglist[SIGEMT] = "Emulation trap";
1928 # endif
1929 sys_siglist[SIGFPE] = "Arithmetic exception";
1930 # ifdef SIGFREEZE
1931 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1932 # endif
1933 # ifdef SIGGRANT
1934 sys_siglist[SIGGRANT] = "Monitor mode granted";
1935 # endif
1936 sys_siglist[SIGHUP] = "Hangup";
1937 sys_siglist[SIGILL] = "Illegal instruction";
1938 sys_siglist[SIGINT] = "Interrupt";
1939 # ifdef SIGIO
1940 sys_siglist[SIGIO] = "I/O possible";
1941 # endif
1942 # ifdef SIGIOINT
1943 sys_siglist[SIGIOINT] = "I/O intervention required";
1944 # endif
1945 # ifdef SIGIOT
1946 sys_siglist[SIGIOT] = "IOT trap";
1947 # endif
1948 sys_siglist[SIGKILL] = "Killed";
1949 # ifdef SIGLOST
1950 sys_siglist[SIGLOST] = "Resource lost";
1951 # endif
1952 # ifdef SIGLWP
1953 sys_siglist[SIGLWP] = "SIGLWP";
1954 # endif
1955 # ifdef SIGMSG
1956 sys_siglist[SIGMSG] = "Monitor mode data available";
1957 # endif
1958 # ifdef SIGPHONE
1959 sys_siglist[SIGWIND] = "SIGPHONE";
1960 # endif
1961 sys_siglist[SIGPIPE] = "Broken pipe";
1962 # ifdef SIGPOLL
1963 sys_siglist[SIGPOLL] = "Pollable event occurred";
1964 # endif
1965 # ifdef SIGPROF
1966 sys_siglist[SIGPROF] = "Profiling timer expired";
1967 # endif
1968 # ifdef SIGPTY
1969 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1970 # endif
1971 # ifdef SIGPWR
1972 sys_siglist[SIGPWR] = "Power-fail restart";
1973 # endif
1974 sys_siglist[SIGQUIT] = "Quit";
1975 # ifdef SIGRETRACT
1976 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1977 # endif
1978 # ifdef SIGSAK
1979 sys_siglist[SIGSAK] = "Secure attention";
1980 # endif
1981 sys_siglist[SIGSEGV] = "Segmentation violation";
1982 # ifdef SIGSOUND
1983 sys_siglist[SIGSOUND] = "Sound completed";
1984 # endif
1985 # ifdef SIGSTOP
1986 sys_siglist[SIGSTOP] = "Stopped (signal)";
1987 # endif
1988 # ifdef SIGSTP
1989 sys_siglist[SIGSTP] = "Stopped (user)";
1990 # endif
1991 # ifdef SIGSYS
1992 sys_siglist[SIGSYS] = "Bad argument to system call";
1993 # endif
1994 sys_siglist[SIGTERM] = "Terminated";
1995 # ifdef SIGTHAW
1996 sys_siglist[SIGTHAW] = "SIGTHAW";
1997 # endif
1998 # ifdef SIGTRAP
1999 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2000 # endif
2001 # ifdef SIGTSTP
2002 sys_siglist[SIGTSTP] = "Stopped (user)";
2003 # endif
2004 # ifdef SIGTTIN
2005 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2006 # endif
2007 # ifdef SIGTTOU
2008 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2009 # endif
2010 # ifdef SIGURG
2011 sys_siglist[SIGURG] = "Urgent I/O condition";
2012 # endif
2013 # ifdef SIGUSR1
2014 sys_siglist[SIGUSR1] = "User defined signal 1";
2015 # endif
2016 # ifdef SIGUSR2
2017 sys_siglist[SIGUSR2] = "User defined signal 2";
2018 # endif
2019 # ifdef SIGVTALRM
2020 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2021 # endif
2022 # ifdef SIGWAITING
2023 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2024 # endif
2025 # ifdef SIGWINCH
2026 sys_siglist[SIGWINCH] = "Window size changed";
2027 # endif
2028 # ifdef SIGWIND
2029 sys_siglist[SIGWIND] = "SIGWIND";
2030 # endif
2031 # ifdef SIGXCPU
2032 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2033 # endif
2034 # ifdef SIGXFSZ
2035 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2036 # endif
2038 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2040 /* Don't alter signal handlers if dumping. On some machines,
2041 changing signal handlers sets static data that would make signals
2042 fail to work right when the dumped Emacs is run. */
2043 if (dumping)
2044 return;
2046 sigfillset (&process_fatal_action.sa_mask);
2047 process_fatal_action.sa_handler = deliver_fatal_signal;
2048 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2050 sigfillset (&thread_fatal_action.sa_mask);
2051 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2052 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2054 /* SIGINT may need special treatment on MS-Windows. See
2055 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2056 Please update the doc of kill-emacs, kill-emacs-hook, and
2057 NEWS if you change this. */
2059 maybe_fatal_sig (SIGHUP);
2060 maybe_fatal_sig (SIGINT);
2061 maybe_fatal_sig (SIGTERM);
2063 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2064 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2065 to behave more like typical batch applications do. */
2066 if (! noninteractive)
2067 signal (SIGPIPE, SIG_IGN);
2069 sigaction (SIGQUIT, &process_fatal_action, 0);
2070 sigaction (SIGILL, &thread_fatal_action, 0);
2071 sigaction (SIGTRAP, &thread_fatal_action, 0);
2073 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2074 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2075 interpreter's floating point operations, so treat SIGFPE as an
2076 arith-error if it arises in the main thread. */
2077 if (IEEE_FLOATING_POINT)
2078 sigaction (SIGFPE, &thread_fatal_action, 0);
2079 else
2081 emacs_sigaction_init (&action, deliver_arith_signal);
2082 sigaction (SIGFPE, &action, 0);
2085 #ifdef SIGUSR1
2086 add_user_signal (SIGUSR1, "sigusr1");
2087 #endif
2088 #ifdef SIGUSR2
2089 add_user_signal (SIGUSR2, "sigusr2");
2090 #endif
2091 sigaction (SIGABRT, &thread_fatal_action, 0);
2092 #ifdef SIGPRE
2093 sigaction (SIGPRE, &thread_fatal_action, 0);
2094 #endif
2095 #ifdef SIGORE
2096 sigaction (SIGORE, &thread_fatal_action, 0);
2097 #endif
2098 #ifdef SIGUME
2099 sigaction (SIGUME, &thread_fatal_action, 0);
2100 #endif
2101 #ifdef SIGDLK
2102 sigaction (SIGDLK, &process_fatal_action, 0);
2103 #endif
2104 #ifdef SIGCPULIM
2105 sigaction (SIGCPULIM, &process_fatal_action, 0);
2106 #endif
2107 #ifdef SIGIOT
2108 sigaction (SIGIOT, &thread_fatal_action, 0);
2109 #endif
2110 #ifdef SIGEMT
2111 sigaction (SIGEMT, &thread_fatal_action, 0);
2112 #endif
2113 #ifdef SIGBUS
2114 sigaction (SIGBUS, &thread_fatal_action, 0);
2115 #endif
2116 if (!init_sigsegv ())
2117 sigaction (SIGSEGV, &thread_fatal_action, 0);
2118 #ifdef SIGSYS
2119 sigaction (SIGSYS, &thread_fatal_action, 0);
2120 #endif
2121 sigaction (SIGTERM, &process_fatal_action, 0);
2122 #ifdef SIGPROF
2123 signal (SIGPROF, SIG_IGN);
2124 #endif
2125 #ifdef SIGVTALRM
2126 sigaction (SIGVTALRM, &process_fatal_action, 0);
2127 #endif
2128 #ifdef SIGXCPU
2129 sigaction (SIGXCPU, &process_fatal_action, 0);
2130 #endif
2131 #ifdef SIGXFSZ
2132 sigaction (SIGXFSZ, &process_fatal_action, 0);
2133 #endif
2135 #ifdef SIGDANGER
2136 /* This just means available memory is getting low. */
2137 emacs_sigaction_init (&action, deliver_danger_signal);
2138 sigaction (SIGDANGER, &action, 0);
2139 #endif
2141 /* AIX-specific signals. */
2142 #ifdef SIGGRANT
2143 sigaction (SIGGRANT, &process_fatal_action, 0);
2144 #endif
2145 #ifdef SIGMIGRATE
2146 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2147 #endif
2148 #ifdef SIGMSG
2149 sigaction (SIGMSG, &process_fatal_action, 0);
2150 #endif
2151 #ifdef SIGRETRACT
2152 sigaction (SIGRETRACT, &process_fatal_action, 0);
2153 #endif
2154 #ifdef SIGSAK
2155 sigaction (SIGSAK, &process_fatal_action, 0);
2156 #endif
2157 #ifdef SIGSOUND
2158 sigaction (SIGSOUND, &process_fatal_action, 0);
2159 #endif
2160 #ifdef SIGTALRM
2161 sigaction (SIGTALRM, &thread_fatal_action, 0);
2162 #endif
2165 #ifndef HAVE_RANDOM
2166 #ifdef random
2167 #define HAVE_RANDOM
2168 #endif
2169 #endif
2171 /* Figure out how many bits the system's random number generator uses.
2172 `random' and `lrand48' are assumed to return 31 usable bits.
2173 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2174 so we'll shift it and treat it like the 15-bit USG `rand'. */
2176 #ifndef RAND_BITS
2177 # ifdef HAVE_RANDOM
2178 # define RAND_BITS 31
2179 # else /* !HAVE_RANDOM */
2180 # ifdef HAVE_LRAND48
2181 # define RAND_BITS 31
2182 # define random lrand48
2183 # else /* !HAVE_LRAND48 */
2184 # define RAND_BITS 15
2185 # if RAND_MAX == 32767
2186 # define random rand
2187 # else /* RAND_MAX != 32767 */
2188 # if RAND_MAX == 2147483647
2189 # define random() (rand () >> 16)
2190 # else /* RAND_MAX != 2147483647 */
2191 # ifdef USG
2192 # define random rand
2193 # else
2194 # define random() (rand () >> 16)
2195 # endif /* !USG */
2196 # endif /* RAND_MAX != 2147483647 */
2197 # endif /* RAND_MAX != 32767 */
2198 # endif /* !HAVE_LRAND48 */
2199 # endif /* !HAVE_RANDOM */
2200 #endif /* !RAND_BITS */
2202 #ifdef HAVE_RANDOM
2203 typedef unsigned int random_seed;
2204 static void set_random_seed (random_seed arg) { srandom (arg); }
2205 #elif defined HAVE_LRAND48
2206 /* Although srand48 uses a long seed, this is unsigned long to avoid
2207 undefined behavior on signed integer overflow in init_random. */
2208 typedef unsigned long int random_seed;
2209 static void set_random_seed (random_seed arg) { srand48 (arg); }
2210 #else
2211 typedef unsigned int random_seed;
2212 static void set_random_seed (random_seed arg) { srand (arg); }
2213 #endif
2215 void
2216 seed_random (void *seed, ptrdiff_t seed_size)
2218 random_seed arg = 0;
2219 unsigned char *argp = (unsigned char *) &arg;
2220 unsigned char *seedp = seed;
2221 for (ptrdiff_t i = 0; i < seed_size; i++)
2222 argp[i % sizeof arg] ^= seedp[i];
2223 set_random_seed (arg);
2226 void
2227 init_random (void)
2229 random_seed v;
2230 bool success = false;
2232 /* First, try seeding the PRNG from the operating system's entropy
2233 source. This approach is both fast and secure. */
2234 #ifdef WINDOWSNT
2235 success = w32_init_random (&v, sizeof v) == 0;
2236 #else
2237 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2238 if (0 <= fd)
2240 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2241 close (fd);
2243 #endif
2245 /* If that didn't work, try using GnuTLS, which is secure, but on
2246 some systems, can be somewhat slow. */
2247 if (!success)
2248 success = EQ (emacs_gnutls_global_init (), Qt)
2249 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2251 /* If _that_ didn't work, just use the current time value and PID.
2252 It's at least better than XKCD 221. */
2253 if (!success)
2255 struct timespec t = current_timespec ();
2256 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2259 set_random_seed (v);
2263 * Return a nonnegative random integer out of whatever we've got.
2264 * It contains enough bits to make a random (signed) Emacs fixnum.
2265 * This suffices even for a 64-bit architecture with a 15-bit rand.
2267 EMACS_INT
2268 get_random (void)
2270 EMACS_UINT val = 0;
2271 int i;
2272 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2273 val = (random () ^ (val << RAND_BITS)
2274 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2275 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2276 return val & INTMASK;
2279 #ifndef HAVE_SNPRINTF
2280 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2282 snprintf (char *buf, size_t bufsize, char const *format, ...)
2284 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2285 ptrdiff_t nbytes = size - 1;
2286 va_list ap;
2288 if (size)
2290 va_start (ap, format);
2291 nbytes = doprnt (buf, size, format, 0, ap);
2292 va_end (ap);
2295 if (nbytes == size - 1)
2297 /* Calculate the length of the string that would have been created
2298 had the buffer been large enough. */
2299 char stackbuf[4000];
2300 char *b = stackbuf;
2301 ptrdiff_t bsize = sizeof stackbuf;
2302 va_start (ap, format);
2303 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2304 va_end (ap);
2305 if (b != stackbuf)
2306 xfree (b);
2309 if (INT_MAX < nbytes)
2311 #ifdef EOVERFLOW
2312 errno = EOVERFLOW;
2313 #else
2314 errno = EDOM;
2315 #endif
2316 return -1;
2318 return nbytes;
2320 #endif
2322 /* If a backtrace is available, output the top lines of it to stderr.
2323 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2324 This function may be called from a signal handler, so it should
2325 not invoke async-unsafe functions like malloc.
2327 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2328 but do not output anything. This avoids some problems that can
2329 otherwise occur if the malloc arena is corrupted before 'backtrace'
2330 is called, since 'backtrace' may call malloc if the tables are not
2331 initialized.
2333 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2334 fatal error has occurred in some other thread; generate a thread
2335 backtrace instead, ignoring BACKTRACE_LIMIT. */
2336 void
2337 emacs_backtrace (int backtrace_limit)
2339 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2340 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2341 void *buffer;
2342 int npointers;
2344 if (thread_backtrace_npointers)
2346 buffer = thread_backtrace_buffer;
2347 npointers = thread_backtrace_npointers;
2349 else
2351 buffer = main_backtrace_buffer;
2353 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2354 if (bounded_limit < 0)
2356 backtrace (buffer, 1);
2357 return;
2360 npointers = backtrace (buffer, bounded_limit + 1);
2363 if (npointers)
2365 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2366 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2367 if (bounded_limit < npointers)
2368 emacs_write (STDERR_FILENO, "...\n", 4);
2372 #ifndef HAVE_NTGUI
2373 void
2374 emacs_abort (void)
2376 terminate_due_to_signal (SIGABRT, 40);
2378 #endif
2380 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2381 Use binary I/O on systems that care about text vs binary I/O.
2382 Arrange for subprograms to not inherit the file descriptor.
2383 Prefer a method that is multithread-safe, if available.
2384 Do not fail merely because the open was interrupted by a signal.
2385 Allow the user to quit. */
2388 emacs_open (const char *file, int oflags, int mode)
2390 int fd;
2391 if (! (oflags & O_TEXT))
2392 oflags |= O_BINARY;
2393 oflags |= O_CLOEXEC;
2394 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2395 maybe_quit ();
2396 return fd;
2399 /* Open FILE as a stream for Emacs use, with mode MODE.
2400 Act like emacs_open with respect to threads, signals, and quits. */
2402 FILE *
2403 emacs_fopen (char const *file, char const *mode)
2405 int fd, omode, oflags;
2406 int bflag = 0;
2407 char const *m = mode;
2409 switch (*m++)
2411 case 'r': omode = O_RDONLY; oflags = 0; break;
2412 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2413 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2414 default: emacs_abort ();
2417 while (*m)
2418 switch (*m++)
2420 case '+': omode = O_RDWR; break;
2421 case 't': bflag = O_TEXT; break;
2422 default: /* Ignore. */ break;
2425 fd = emacs_open (file, omode | oflags | bflag, 0666);
2426 return fd < 0 ? 0 : fdopen (fd, mode);
2429 /* Create a pipe for Emacs use. */
2432 emacs_pipe (int fd[2])
2434 #ifdef MSDOS
2435 return pipe (fd);
2436 #else /* !MSDOS */
2437 return pipe2 (fd, O_BINARY | O_CLOEXEC);
2438 #endif /* !MSDOS */
2441 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2442 For the background behind this mess, please see Austin Group defect 529
2443 <http://austingroupbugs.net/view.php?id=529>. */
2445 #ifndef POSIX_CLOSE_RESTART
2446 # define POSIX_CLOSE_RESTART 1
2447 static int
2448 posix_close (int fd, int flag)
2450 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2451 eassert (flag == POSIX_CLOSE_RESTART);
2453 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2454 on a system that does not define POSIX_CLOSE_RESTART.
2456 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2457 closed, and retrying the close could inadvertently close a file
2458 descriptor allocated by some other thread. In other systems
2459 (e.g., HP/UX) FD is not closed. And in still other systems
2460 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2461 multithreaded program there can be no way to tell.
2463 So, in this case, pretend that the close succeeded. This works
2464 well on systems like GNU/Linux that close FD. Although it may
2465 leak a file descriptor on other systems, the leak is unlikely and
2466 it's better to leak than to close a random victim. */
2467 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2469 #endif
2471 /* Close FD, retrying if interrupted. If successful, return 0;
2472 otherwise, return -1 and set errno to a non-EINTR value. Consider
2473 an EINPROGRESS error to be successful, as that's merely a signal
2474 arriving. FD is always closed when this function returns, even
2475 when it returns -1.
2477 Do not call this function if FD is nonnegative and might already be closed,
2478 as that might close an innocent victim opened by some other thread. */
2481 emacs_close (int fd)
2483 while (1)
2485 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2486 if (r == 0)
2487 return r;
2488 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2490 eassert (errno != EBADF || fd < 0);
2491 return errno == EINPROGRESS ? 0 : r;
2496 /* Maximum number of bytes to read or write in a single system call.
2497 This works around a serious bug in Linux kernels before 2.6.16; see
2498 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2499 It's likely to work around similar bugs in other operating systems, so do it
2500 on all platforms. Round INT_MAX down to a page size, with the conservative
2501 assumption that page sizes are at most 2**18 bytes (any kernel with a
2502 page size larger than that shouldn't have the bug). */
2503 #ifndef MAX_RW_COUNT
2504 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2505 #endif
2507 /* Read from FD to a buffer BUF with size NBYTE.
2508 If interrupted, process any quits and pending signals immediately
2509 if INTERRUPTIBLE, and then retry the read unless quitting.
2510 Return the number of bytes read, which might be less than NBYTE.
2511 On error, set errno to a value other than EINTR, and return -1. */
2512 static ptrdiff_t
2513 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2515 ssize_t result;
2517 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2518 passes a size that large to emacs_read. */
2521 if (interruptible)
2522 maybe_quit ();
2523 result = read (fd, buf, nbyte);
2525 while (result < 0 && errno == EINTR);
2527 return result;
2530 /* Read from FD to a buffer BUF with size NBYTE.
2531 If interrupted, retry the read. Return the number of bytes read,
2532 which might be less than NBYTE. On error, set errno to a value
2533 other than EINTR, and return -1. */
2534 ptrdiff_t
2535 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2537 return emacs_intr_read (fd, buf, nbyte, false);
2540 /* Like emacs_read, but also process quits and pending signals. */
2541 ptrdiff_t
2542 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2544 return emacs_intr_read (fd, buf, nbyte, true);
2547 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2548 interrupted or if a partial write occurs. Process any quits
2549 immediately if INTERRUPTIBLE is positive, and process any pending
2550 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2551 of bytes written; if this is less than NBYTE, set errno to a value
2552 other than EINTR. */
2553 static ptrdiff_t
2554 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2555 int interruptible)
2557 ptrdiff_t bytes_written = 0;
2559 while (nbyte > 0)
2561 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2563 if (n < 0)
2565 if (errno != EINTR)
2566 break;
2568 if (interruptible)
2570 if (0 < interruptible)
2571 maybe_quit ();
2572 if (pending_signals)
2573 process_pending_signals ();
2576 else
2578 buf += n;
2579 nbyte -= n;
2580 bytes_written += n;
2584 return bytes_written;
2587 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2588 interrupted or if a partial write occurs. Do not process quits or
2589 pending signals. Return the number of bytes written, setting errno
2590 if this is less than NBYTE. */
2591 ptrdiff_t
2592 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2594 return emacs_full_write (fd, buf, nbyte, 0);
2597 /* Like emacs_write, but also process pending signals. */
2598 ptrdiff_t
2599 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2601 return emacs_full_write (fd, buf, nbyte, -1);
2604 /* Like emacs_write, but also process quits and pending signals. */
2605 ptrdiff_t
2606 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2608 return emacs_full_write (fd, buf, nbyte, 1);
2611 /* Write a diagnostic to standard error that contains MESSAGE and a
2612 string derived from errno. Preserve errno. Do not buffer stderr.
2613 Do not process quits or pending signals if interrupted. */
2614 void
2615 emacs_perror (char const *message)
2617 int err = errno;
2618 char const *error_string = emacs_strerror (err);
2619 char const *command = (initial_argv && initial_argv[0]
2620 ? initial_argv[0] : "emacs");
2621 /* Write it out all at once, if it's short; this is less likely to
2622 be interleaved with other output. */
2623 char buf[BUFSIZ];
2624 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2625 command, message, error_string);
2626 if (0 <= nbytes && nbytes < BUFSIZ)
2627 emacs_write (STDERR_FILENO, buf, nbytes);
2628 else
2630 emacs_write (STDERR_FILENO, command, strlen (command));
2631 emacs_write (STDERR_FILENO, ": ", 2);
2632 emacs_write (STDERR_FILENO, message, strlen (message));
2633 emacs_write (STDERR_FILENO, ": ", 2);
2634 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2635 emacs_write (STDERR_FILENO, "\n", 1);
2637 errno = err;
2640 /* Return a struct timeval that is roughly equivalent to T.
2641 Use the least timeval not less than T.
2642 Return an extremal value if the result would overflow. */
2643 struct timeval
2644 make_timeval (struct timespec t)
2646 struct timeval tv;
2647 tv.tv_sec = t.tv_sec;
2648 tv.tv_usec = t.tv_nsec / 1000;
2650 if (t.tv_nsec % 1000 != 0)
2652 if (tv.tv_usec < 999999)
2653 tv.tv_usec++;
2654 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2656 tv.tv_sec++;
2657 tv.tv_usec = 0;
2661 return tv;
2664 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2665 ATIME and MTIME, respectively.
2666 FD must be either negative -- in which case it is ignored --
2667 or a file descriptor that is open on FILE.
2668 If FD is nonnegative, then FILE can be NULL. */
2670 set_file_times (int fd, const char *filename,
2671 struct timespec atime, struct timespec mtime)
2673 struct timespec timespec[2];
2674 timespec[0] = atime;
2675 timespec[1] = mtime;
2676 return fdutimens (fd, filename, timespec);
2679 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2680 This is like renameat except that it fails if DST already exists,
2681 or if this operation is not supported atomically. Return 0 if
2682 successful, -1 (setting errno) otherwise. */
2684 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2686 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2687 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2688 #elif defined RENAME_EXCL
2689 return renameatx_np (srcfd, src, dstfd, dst, RENAME_EXCL);
2690 #else
2691 # ifdef WINDOWSNT
2692 if (srcfd == AT_FDCWD && dstfd == AT_FDCWD)
2693 return sys_rename_replace (src, dst, 0);
2694 # endif
2695 errno = ENOSYS;
2696 return -1;
2697 #endif
2700 /* Like strsignal, except async-signal-safe, and this function typically
2701 returns a string in the C locale rather than the current locale. */
2702 char const *
2703 safe_strsignal (int code)
2705 char const *signame = 0;
2707 if (0 <= code && code < sys_siglist_entries)
2708 signame = sys_siglist[code];
2709 if (! signame)
2710 signame = "Unknown signal";
2712 return signame;
2715 #ifndef DOS_NT
2716 /* For make-serial-process */
2718 serial_open (Lisp_Object port)
2720 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2721 if (fd < 0)
2722 report_file_error ("Opening serial port", port);
2723 #ifdef TIOCEXCL
2724 ioctl (fd, TIOCEXCL, (char *) 0);
2725 #endif
2727 return fd;
2730 #if !defined (HAVE_CFMAKERAW)
2731 /* Workaround for targets which are missing cfmakeraw. */
2732 /* Pasted from man page. */
2733 static void
2734 cfmakeraw (struct termios *termios_p)
2736 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2737 termios_p->c_oflag &= ~OPOST;
2738 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2739 termios_p->c_cflag &= ~(CSIZE|PARENB);
2740 termios_p->c_cflag |= CS8;
2742 #endif /* !defined (HAVE_CFMAKERAW */
2744 #if !defined (HAVE_CFSETSPEED)
2745 /* Workaround for targets which are missing cfsetspeed. */
2746 static int
2747 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2749 return (cfsetispeed (termios_p, vitesse)
2750 + cfsetospeed (termios_p, vitesse));
2752 #endif
2754 /* For serial-process-configure */
2755 void
2756 serial_configure (struct Lisp_Process *p,
2757 Lisp_Object contact)
2759 Lisp_Object childp2 = Qnil;
2760 Lisp_Object tem = Qnil;
2761 struct termios attr;
2762 int err;
2763 char summary[4] = "???"; /* This usually becomes "8N1". */
2765 childp2 = Fcopy_sequence (p->childp);
2767 /* Read port attributes and prepare default configuration. */
2768 err = tcgetattr (p->outfd, &attr);
2769 if (err != 0)
2770 report_file_error ("Failed tcgetattr", Qnil);
2771 cfmakeraw (&attr);
2772 #if defined (CLOCAL)
2773 attr.c_cflag |= CLOCAL;
2774 #endif
2775 #if defined (CREAD)
2776 attr.c_cflag |= CREAD;
2777 #endif
2779 /* Configure speed. */
2780 if (!NILP (Fplist_member (contact, QCspeed)))
2781 tem = Fplist_get (contact, QCspeed);
2782 else
2783 tem = Fplist_get (p->childp, QCspeed);
2784 CHECK_NUMBER (tem);
2785 err = cfsetspeed (&attr, XINT (tem));
2786 if (err != 0)
2787 report_file_error ("Failed cfsetspeed", tem);
2788 childp2 = Fplist_put (childp2, QCspeed, tem);
2790 /* Configure bytesize. */
2791 if (!NILP (Fplist_member (contact, QCbytesize)))
2792 tem = Fplist_get (contact, QCbytesize);
2793 else
2794 tem = Fplist_get (p->childp, QCbytesize);
2795 if (NILP (tem))
2796 tem = make_number (8);
2797 CHECK_NUMBER (tem);
2798 if (XINT (tem) != 7 && XINT (tem) != 8)
2799 error (":bytesize must be nil (8), 7, or 8");
2800 summary[0] = XINT (tem) + '0';
2801 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2802 attr.c_cflag &= ~CSIZE;
2803 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2804 #else
2805 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2806 if (XINT (tem) != 8)
2807 error ("Bytesize cannot be changed");
2808 #endif
2809 childp2 = Fplist_put (childp2, QCbytesize, tem);
2811 /* Configure parity. */
2812 if (!NILP (Fplist_member (contact, QCparity)))
2813 tem = Fplist_get (contact, QCparity);
2814 else
2815 tem = Fplist_get (p->childp, QCparity);
2816 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2817 error (":parity must be nil (no parity), `even', or `odd'");
2818 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2819 attr.c_cflag &= ~(PARENB | PARODD);
2820 attr.c_iflag &= ~(IGNPAR | INPCK);
2821 if (NILP (tem))
2823 summary[1] = 'N';
2825 else if (EQ (tem, Qeven))
2827 summary[1] = 'E';
2828 attr.c_cflag |= PARENB;
2829 attr.c_iflag |= (IGNPAR | INPCK);
2831 else if (EQ (tem, Qodd))
2833 summary[1] = 'O';
2834 attr.c_cflag |= (PARENB | PARODD);
2835 attr.c_iflag |= (IGNPAR | INPCK);
2837 #else
2838 /* Don't error on no parity, which should be set by cfmakeraw. */
2839 if (!NILP (tem))
2840 error ("Parity cannot be configured");
2841 #endif
2842 childp2 = Fplist_put (childp2, QCparity, tem);
2844 /* Configure stopbits. */
2845 if (!NILP (Fplist_member (contact, QCstopbits)))
2846 tem = Fplist_get (contact, QCstopbits);
2847 else
2848 tem = Fplist_get (p->childp, QCstopbits);
2849 if (NILP (tem))
2850 tem = make_number (1);
2851 CHECK_NUMBER (tem);
2852 if (XINT (tem) != 1 && XINT (tem) != 2)
2853 error (":stopbits must be nil (1 stopbit), 1, or 2");
2854 summary[2] = XINT (tem) + '0';
2855 #if defined (CSTOPB)
2856 attr.c_cflag &= ~CSTOPB;
2857 if (XINT (tem) == 2)
2858 attr.c_cflag |= CSTOPB;
2859 #else
2860 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2861 if (XINT (tem) != 1)
2862 error ("Stopbits cannot be configured");
2863 #endif
2864 childp2 = Fplist_put (childp2, QCstopbits, tem);
2866 /* Configure flowcontrol. */
2867 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2868 tem = Fplist_get (contact, QCflowcontrol);
2869 else
2870 tem = Fplist_get (p->childp, QCflowcontrol);
2871 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2872 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2873 #if defined (CRTSCTS)
2874 attr.c_cflag &= ~CRTSCTS;
2875 #endif
2876 #if defined (CNEW_RTSCTS)
2877 attr.c_cflag &= ~CNEW_RTSCTS;
2878 #endif
2879 #if defined (IXON) && defined (IXOFF)
2880 attr.c_iflag &= ~(IXON | IXOFF);
2881 #endif
2882 if (NILP (tem))
2884 /* Already configured. */
2886 else if (EQ (tem, Qhw))
2888 #if defined (CRTSCTS)
2889 attr.c_cflag |= CRTSCTS;
2890 #elif defined (CNEW_RTSCTS)
2891 attr.c_cflag |= CNEW_RTSCTS;
2892 #else
2893 error ("Hardware flowcontrol (RTS/CTS) not supported");
2894 #endif
2896 else if (EQ (tem, Qsw))
2898 #if defined (IXON) && defined (IXOFF)
2899 attr.c_iflag |= (IXON | IXOFF);
2900 #else
2901 error ("Software flowcontrol (XON/XOFF) not supported");
2902 #endif
2904 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2906 /* Activate configuration. */
2907 err = tcsetattr (p->outfd, TCSANOW, &attr);
2908 if (err != 0)
2909 report_file_error ("Failed tcsetattr", Qnil);
2911 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2912 pset_childp (p, childp2);
2914 #endif /* not DOS_NT */
2916 /* System depended enumeration of and access to system processes a-la ps(1). */
2918 #ifdef HAVE_PROCFS
2920 /* Process enumeration and access via /proc. */
2922 Lisp_Object
2923 list_system_processes (void)
2925 Lisp_Object procdir, match, proclist, next;
2926 Lisp_Object tail;
2928 /* For every process on the system, there's a directory in the
2929 "/proc" pseudo-directory whose name is the numeric ID of that
2930 process. */
2931 procdir = build_string ("/proc");
2932 match = build_string ("[0-9]+");
2933 proclist = directory_files_internal (procdir, Qnil, match, Qt, false, Qnil);
2935 /* `proclist' gives process IDs as strings. Destructively convert
2936 each string into a number. */
2937 for (tail = proclist; CONSP (tail); tail = next)
2939 next = XCDR (tail);
2940 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2943 /* directory_files_internal returns the files in reverse order; undo
2944 that. */
2945 proclist = Fnreverse (proclist);
2946 return proclist;
2949 #elif defined DARWIN_OS || defined __FreeBSD__
2951 Lisp_Object
2952 list_system_processes (void)
2954 #ifdef DARWIN_OS
2955 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2956 #else
2957 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2958 #endif
2959 size_t len;
2960 struct kinfo_proc *procs;
2961 size_t i;
2963 Lisp_Object proclist = Qnil;
2965 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2966 return proclist;
2968 procs = xmalloc (len);
2969 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2971 xfree (procs);
2972 return proclist;
2975 len /= sizeof (struct kinfo_proc);
2976 for (i = 0; i < len; i++)
2978 #ifdef DARWIN_OS
2979 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2980 #else
2981 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2982 #endif
2985 xfree (procs);
2987 return proclist;
2990 /* The WINDOWSNT implementation is in w32.c.
2991 The MSDOS implementation is in dosfns.c. */
2992 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2994 Lisp_Object
2995 list_system_processes (void)
2997 return Qnil;
3000 #endif /* !defined (WINDOWSNT) */
3002 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3003 static struct timespec
3004 time_from_jiffies (unsigned long long tval, long hz)
3006 unsigned long long s = tval / hz;
3007 unsigned long long frac = tval % hz;
3008 int ns;
3010 if (TYPE_MAXIMUM (time_t) < s)
3011 time_overflow ();
3012 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
3013 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
3014 ns = frac * TIMESPEC_RESOLUTION / hz;
3015 else
3017 /* This is reachable only in the unlikely case that HZ * HZ
3018 exceeds ULLONG_MAX. It calculates an approximation that is
3019 guaranteed to be in range. */
3020 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3021 + (hz % TIMESPEC_RESOLUTION != 0));
3022 ns = frac / hz_per_ns;
3025 return make_timespec (s, ns);
3028 static Lisp_Object
3029 ltime_from_jiffies (unsigned long long tval, long hz)
3031 struct timespec t = time_from_jiffies (tval, hz);
3032 return make_lisp_time (t);
3035 static struct timespec
3036 get_up_time (void)
3038 FILE *fup;
3039 struct timespec up = make_timespec (0, 0);
3041 block_input ();
3042 fup = emacs_fopen ("/proc/uptime", "r");
3044 if (fup)
3046 unsigned long long upsec, upfrac, idlesec, idlefrac;
3047 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3049 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3050 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3051 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3052 == 4)
3054 if (TYPE_MAXIMUM (time_t) < upsec)
3056 upsec = TYPE_MAXIMUM (time_t);
3057 upfrac = TIMESPEC_RESOLUTION - 1;
3059 else
3061 int upfraclen = upfrac_end - upfrac_start;
3062 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3063 upfrac *= 10;
3064 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3065 upfrac /= 10;
3066 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3068 up = make_timespec (upsec, upfrac);
3070 fclose (fup);
3072 unblock_input ();
3074 return up;
3077 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3078 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3080 static Lisp_Object
3081 procfs_ttyname (int rdev)
3083 FILE *fdev;
3084 char name[PATH_MAX];
3086 block_input ();
3087 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3088 name[0] = 0;
3090 if (fdev)
3092 unsigned major;
3093 unsigned long minor_beg, minor_end;
3094 char minor[25]; /* 2 32-bit numbers + dash */
3095 char *endp;
3097 for (; !feof_unlocked (fdev) && !ferror_unlocked (fdev); name[0] = 0)
3099 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3100 && major == MAJOR (rdev))
3102 minor_beg = strtoul (minor, &endp, 0);
3103 if (*endp == '\0')
3104 minor_end = minor_beg;
3105 else if (*endp == '-')
3106 minor_end = strtoul (endp + 1, &endp, 0);
3107 else
3108 continue;
3110 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3112 sprintf (name + strlen (name), "%u", MINOR (rdev));
3113 break;
3117 fclose (fdev);
3119 unblock_input ();
3120 return build_string (name);
3123 static uintmax_t
3124 procfs_get_total_memory (void)
3126 FILE *fmem;
3127 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3128 int c;
3130 block_input ();
3131 fmem = emacs_fopen ("/proc/meminfo", "r");
3133 if (fmem)
3135 uintmax_t entry_value;
3136 bool done;
3139 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3141 case 1:
3142 retval = entry_value;
3143 done = 1;
3144 break;
3146 case 0:
3147 while ((c = getc_unlocked (fmem)) != EOF && c != '\n')
3148 continue;
3149 done = c == EOF;
3150 break;
3152 default:
3153 done = 1;
3154 break;
3156 while (!done);
3158 fclose (fmem);
3160 unblock_input ();
3161 return retval;
3164 Lisp_Object
3165 system_process_attributes (Lisp_Object pid)
3167 char procfn[PATH_MAX], fn[PATH_MAX];
3168 struct stat st;
3169 struct passwd *pw;
3170 struct group *gr;
3171 long clocks_per_sec;
3172 char *procfn_end;
3173 char procbuf[1025], *p, *q;
3174 int fd;
3175 ssize_t nread;
3176 static char const default_cmd[] = "???";
3177 const char *cmd = default_cmd;
3178 int cmdsize = sizeof default_cmd - 1;
3179 char *cmdline = NULL;
3180 ptrdiff_t cmdline_size;
3181 char c;
3182 printmax_t proc_id;
3183 int ppid, pgrp, sess, tty, tpgid, thcount;
3184 uid_t uid;
3185 gid_t gid;
3186 unsigned long long u_time, s_time, cutime, cstime, start;
3187 long priority, niceness, rss;
3188 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3189 struct timespec tnow, tstart, tboot, telapsed, us_time;
3190 double pcpu, pmem;
3191 Lisp_Object attrs = Qnil;
3192 Lisp_Object decoded_cmd;
3193 ptrdiff_t count;
3195 CHECK_NUMBER_OR_FLOAT (pid);
3196 CONS_TO_INTEGER (pid, pid_t, proc_id);
3197 sprintf (procfn, "/proc/%"pMd, proc_id);
3198 if (stat (procfn, &st) < 0)
3199 return attrs;
3201 /* euid egid */
3202 uid = st.st_uid;
3203 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3204 block_input ();
3205 pw = getpwuid (uid);
3206 unblock_input ();
3207 if (pw)
3208 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3210 gid = st.st_gid;
3211 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3212 block_input ();
3213 gr = getgrgid (gid);
3214 unblock_input ();
3215 if (gr)
3216 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3218 count = SPECPDL_INDEX ();
3219 strcpy (fn, procfn);
3220 procfn_end = fn + strlen (fn);
3221 strcpy (procfn_end, "/stat");
3222 fd = emacs_open (fn, O_RDONLY, 0);
3223 if (fd < 0)
3224 nread = 0;
3225 else
3227 record_unwind_protect_int (close_file_unwind, fd);
3228 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3230 if (0 < nread)
3232 procbuf[nread] = '\0';
3233 p = procbuf;
3235 p = strchr (p, '(');
3236 if (p != NULL)
3238 q = strrchr (p + 1, ')');
3239 /* comm */
3240 if (q != NULL)
3242 cmd = p + 1;
3243 cmdsize = q - cmd;
3246 else
3247 q = NULL;
3248 /* Command name is encoded in locale-coding-system; decode it. */
3249 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3250 decoded_cmd = code_convert_string_norecord (cmd_str,
3251 Vlocale_coding_system, 0);
3252 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3254 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3255 utime stime cutime cstime priority nice thcount . start vsize rss */
3256 if (q
3257 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3258 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3259 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3260 &minflt, &cminflt, &majflt, &cmajflt,
3261 &u_time, &s_time, &cutime, &cstime,
3262 &priority, &niceness, &thcount, &start, &vsize, &rss)
3263 == 20))
3265 char state_str[2];
3266 state_str[0] = c;
3267 state_str[1] = '\0';
3268 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3269 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3270 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3271 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3272 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3273 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3274 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3275 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3276 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3277 attrs);
3278 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3279 attrs);
3280 clocks_per_sec = sysconf (_SC_CLK_TCK);
3281 if (clocks_per_sec < 0)
3282 clocks_per_sec = 100;
3283 attrs = Fcons (Fcons (Qutime,
3284 ltime_from_jiffies (u_time, clocks_per_sec)),
3285 attrs);
3286 attrs = Fcons (Fcons (Qstime,
3287 ltime_from_jiffies (s_time, clocks_per_sec)),
3288 attrs);
3289 attrs = Fcons (Fcons (Qtime,
3290 ltime_from_jiffies (s_time + u_time,
3291 clocks_per_sec)),
3292 attrs);
3293 attrs = Fcons (Fcons (Qcutime,
3294 ltime_from_jiffies (cutime, clocks_per_sec)),
3295 attrs);
3296 attrs = Fcons (Fcons (Qcstime,
3297 ltime_from_jiffies (cstime, clocks_per_sec)),
3298 attrs);
3299 attrs = Fcons (Fcons (Qctime,
3300 ltime_from_jiffies (cstime + cutime,
3301 clocks_per_sec)),
3302 attrs);
3303 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3304 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3305 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3306 attrs);
3307 tnow = current_timespec ();
3308 telapsed = get_up_time ();
3309 tboot = timespec_sub (tnow, telapsed);
3310 tstart = time_from_jiffies (start, clocks_per_sec);
3311 tstart = timespec_add (tboot, tstart);
3312 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3313 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3314 attrs);
3315 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3316 telapsed = timespec_sub (tnow, tstart);
3317 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3318 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3319 pcpu = timespectod (us_time) / timespectod (telapsed);
3320 if (pcpu > 1.0)
3321 pcpu = 1.0;
3322 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3323 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3324 if (pmem > 100)
3325 pmem = 100;
3326 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3329 unbind_to (count, Qnil);
3331 /* args */
3332 strcpy (procfn_end, "/cmdline");
3333 fd = emacs_open (fn, O_RDONLY, 0);
3334 if (fd >= 0)
3336 ptrdiff_t readsize, nread_incr;
3337 record_unwind_protect_int (close_file_unwind, fd);
3338 record_unwind_protect_nothing ();
3339 nread = cmdline_size = 0;
3343 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3344 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3346 /* Leave room even if every byte needs escaping below. */
3347 readsize = (cmdline_size >> 1) - nread;
3349 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3350 nread += max (0, nread_incr);
3352 while (nread_incr == readsize);
3354 if (nread)
3356 /* We don't want trailing null characters. */
3357 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3358 continue;
3360 /* Escape-quote whitespace and backslashes. */
3361 q = cmdline + cmdline_size;
3362 while (cmdline < p)
3364 char c = *--p;
3365 *--q = c ? c : ' ';
3366 if (c_isspace (c) || c == '\\')
3367 *--q = '\\';
3370 nread = cmdline + cmdline_size - q;
3373 if (!nread)
3375 nread = cmdsize + 2;
3376 cmdline_size = nread + 1;
3377 q = cmdline = xrealloc (cmdline, cmdline_size);
3378 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3379 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3381 /* Command line is encoded in locale-coding-system; decode it. */
3382 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3383 decoded_cmd = code_convert_string_norecord (cmd_str,
3384 Vlocale_coding_system, 0);
3385 unbind_to (count, Qnil);
3386 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3389 return attrs;
3392 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3394 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3395 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3396 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3397 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3398 #undef _FILE_OFFSET_BITS
3399 #else
3400 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3401 #endif
3403 #include <procfs.h>
3405 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3406 #define _FILE_OFFSET_BITS 64
3407 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3408 #endif
3409 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3411 Lisp_Object
3412 system_process_attributes (Lisp_Object pid)
3414 char procfn[PATH_MAX], fn[PATH_MAX];
3415 struct stat st;
3416 struct passwd *pw;
3417 struct group *gr;
3418 char *procfn_end;
3419 struct psinfo pinfo;
3420 int fd;
3421 ssize_t nread;
3422 printmax_t proc_id;
3423 uid_t uid;
3424 gid_t gid;
3425 Lisp_Object attrs = Qnil;
3426 Lisp_Object decoded_cmd;
3427 ptrdiff_t count;
3429 CHECK_NUMBER_OR_FLOAT (pid);
3430 CONS_TO_INTEGER (pid, pid_t, proc_id);
3431 sprintf (procfn, "/proc/%"pMd, proc_id);
3432 if (stat (procfn, &st) < 0)
3433 return attrs;
3435 /* euid egid */
3436 uid = st.st_uid;
3437 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3438 block_input ();
3439 pw = getpwuid (uid);
3440 unblock_input ();
3441 if (pw)
3442 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3444 gid = st.st_gid;
3445 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3446 block_input ();
3447 gr = getgrgid (gid);
3448 unblock_input ();
3449 if (gr)
3450 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3452 count = SPECPDL_INDEX ();
3453 strcpy (fn, procfn);
3454 procfn_end = fn + strlen (fn);
3455 strcpy (procfn_end, "/psinfo");
3456 fd = emacs_open (fn, O_RDONLY, 0);
3457 if (fd < 0)
3458 nread = 0;
3459 else
3461 record_unwind_protect_int (close_file_unwind, fd);
3462 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3465 if (nread == sizeof pinfo)
3467 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3468 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3469 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3472 char state_str[2];
3473 state_str[0] = pinfo.pr_lwp.pr_sname;
3474 state_str[1] = '\0';
3475 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3478 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3479 need to get a string from it. */
3481 /* FIXME: missing: Qtpgid */
3483 /* FIXME: missing:
3484 Qminflt
3485 Qmajflt
3486 Qcminflt
3487 Qcmajflt
3489 Qutime
3490 Qcutime
3491 Qstime
3492 Qcstime
3493 Are they available? */
3495 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3496 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3497 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3498 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3499 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3500 attrs);
3502 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3503 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3504 attrs);
3505 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3506 attrs);
3508 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3509 range 0 .. 2**15, representing 0.0 .. 1.0. */
3510 attrs = Fcons (Fcons (Qpcpu,
3511 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3512 attrs);
3513 attrs = Fcons (Fcons (Qpmem,
3514 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3515 attrs);
3517 AUTO_STRING (fname, pinfo.pr_fname);
3518 decoded_cmd = code_convert_string_norecord (fname,
3519 Vlocale_coding_system, 0);
3520 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3521 AUTO_STRING (psargs, pinfo.pr_psargs);
3522 decoded_cmd = code_convert_string_norecord (psargs,
3523 Vlocale_coding_system, 0);
3524 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3526 unbind_to (count, Qnil);
3527 return attrs;
3530 #elif defined __FreeBSD__
3532 static struct timespec
3533 timeval_to_timespec (struct timeval t)
3535 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3538 static Lisp_Object
3539 make_lisp_timeval (struct timeval t)
3541 return make_lisp_time (timeval_to_timespec (t));
3544 Lisp_Object
3545 system_process_attributes (Lisp_Object pid)
3547 int proc_id;
3548 int pagesize = getpagesize ();
3549 unsigned long npages;
3550 int fscale;
3551 struct passwd *pw;
3552 struct group *gr;
3553 char *ttyname;
3554 size_t len;
3555 char args[MAXPATHLEN];
3556 struct timespec t, now;
3558 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3559 struct kinfo_proc proc;
3560 size_t proclen = sizeof proc;
3562 Lisp_Object attrs = Qnil;
3563 Lisp_Object decoded_comm;
3565 CHECK_NUMBER_OR_FLOAT (pid);
3566 CONS_TO_INTEGER (pid, int, proc_id);
3567 mib[3] = proc_id;
3569 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3570 return attrs;
3572 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3574 block_input ();
3575 pw = getpwuid (proc.ki_uid);
3576 unblock_input ();
3577 if (pw)
3578 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3580 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3582 block_input ();
3583 gr = getgrgid (proc.ki_svgid);
3584 unblock_input ();
3585 if (gr)
3586 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3588 AUTO_STRING (comm, proc.ki_comm);
3589 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3591 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3593 char state[2] = {'\0', '\0'};
3594 switch (proc.ki_stat)
3596 case SRUN:
3597 state[0] = 'R';
3598 break;
3600 case SSLEEP:
3601 state[0] = 'S';
3602 break;
3604 case SLOCK:
3605 state[0] = 'D';
3606 break;
3608 case SZOMB:
3609 state[0] = 'Z';
3610 break;
3612 case SSTOP:
3613 state[0] = 'T';
3614 break;
3616 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3619 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3620 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3621 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3623 block_input ();
3624 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3625 unblock_input ();
3626 if (ttyname)
3627 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3629 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3630 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3631 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3632 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3633 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3635 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3636 attrs);
3637 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3638 attrs);
3639 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3640 timeval_to_timespec (proc.ki_rusage.ru_stime));
3641 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3643 attrs = Fcons (Fcons (Qcutime,
3644 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3645 attrs);
3646 attrs = Fcons (Fcons (Qcstime,
3647 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3648 attrs);
3649 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3650 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3651 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3653 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3654 attrs);
3655 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3656 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3657 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3658 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3659 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3660 attrs);
3662 now = current_timespec ();
3663 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3664 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3666 len = sizeof fscale;
3667 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3669 double pcpu;
3670 fixpt_t ccpu;
3671 len = sizeof ccpu;
3672 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3674 pcpu = (100.0 * proc.ki_pctcpu / fscale
3675 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3676 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3680 len = sizeof npages;
3681 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3683 double pmem = (proc.ki_flag & P_INMEM
3684 ? 100.0 * proc.ki_rssize / npages
3685 : 0);
3686 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3689 mib[2] = KERN_PROC_ARGS;
3690 len = MAXPATHLEN;
3691 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3693 int i;
3694 for (i = 0; i < len; i++)
3696 if (! args[i] && i < len - 1)
3697 args[i] = ' ';
3700 AUTO_STRING (comm, args);
3701 decoded_comm = code_convert_string_norecord (comm,
3702 Vlocale_coding_system, 0);
3704 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3707 return attrs;
3710 #elif defined DARWIN_OS
3712 static struct timespec
3713 timeval_to_timespec (struct timeval t)
3715 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3718 static Lisp_Object
3719 make_lisp_timeval (struct timeval t)
3721 return make_lisp_time (timeval_to_timespec (t));
3724 Lisp_Object
3725 system_process_attributes (Lisp_Object pid)
3727 int proc_id;
3728 struct passwd *pw;
3729 struct group *gr;
3730 char *ttyname;
3731 struct timeval starttime;
3732 struct timespec t, now;
3733 struct rusage *rusage;
3734 dev_t tdev;
3735 uid_t uid;
3736 gid_t gid;
3738 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3739 struct kinfo_proc proc;
3740 size_t proclen = sizeof proc;
3742 Lisp_Object attrs = Qnil;
3743 Lisp_Object decoded_comm;
3745 CHECK_NUMBER_OR_FLOAT (pid);
3746 CONS_TO_INTEGER (pid, int, proc_id);
3747 mib[3] = proc_id;
3749 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3750 return attrs;
3752 uid = proc.kp_eproc.e_ucred.cr_uid;
3753 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3755 block_input ();
3756 pw = getpwuid (uid);
3757 unblock_input ();
3758 if (pw)
3759 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3761 gid = proc.kp_eproc.e_pcred.p_svgid;
3762 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3764 block_input ();
3765 gr = getgrgid (gid);
3766 unblock_input ();
3767 if (gr)
3768 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3770 decoded_comm = (code_convert_string_norecord
3771 (build_unibyte_string (proc.kp_proc.p_comm),
3772 Vlocale_coding_system, 0));
3774 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3776 char state[2] = {'\0', '\0'};
3777 switch (proc.kp_proc.p_stat)
3779 case SRUN:
3780 state[0] = 'R';
3781 break;
3783 case SSLEEP:
3784 state[0] = 'S';
3785 break;
3787 case SZOMB:
3788 state[0] = 'Z';
3789 break;
3791 case SSTOP:
3792 state[0] = 'T';
3793 break;
3795 case SIDL:
3796 state[0] = 'I';
3797 break;
3799 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3802 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3803 attrs);
3804 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3805 attrs);
3807 tdev = proc.kp_eproc.e_tdev;
3808 block_input ();
3809 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3810 unblock_input ();
3811 if (ttyname)
3812 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3814 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3815 attrs);
3817 rusage = proc.kp_proc.p_ru;
3818 if (rusage)
3820 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3821 attrs);
3822 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3823 attrs);
3825 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3826 attrs);
3827 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3828 attrs);
3829 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3830 timeval_to_timespec (rusage->ru_stime));
3831 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3834 starttime = proc.kp_proc.p_starttime;
3835 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3836 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3838 now = current_timespec ();
3839 t = timespec_sub (now, timeval_to_timespec (starttime));
3840 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3842 return attrs;
3845 /* The WINDOWSNT implementation is in w32.c.
3846 The MSDOS implementation is in dosfns.c. */
3847 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3849 Lisp_Object
3850 system_process_attributes (Lisp_Object pid)
3852 return Qnil;
3855 #endif /* !defined (WINDOWSNT) */
3857 /* Wide character string collation. */
3859 #ifdef __STDC_ISO_10646__
3860 # include <wchar.h>
3861 # include <wctype.h>
3863 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3864 # include <locale.h>
3865 # endif
3866 # ifndef LC_COLLATE
3867 # define LC_COLLATE 0
3868 # endif
3869 # ifndef LC_COLLATE_MASK
3870 # define LC_COLLATE_MASK 0
3871 # endif
3872 # ifndef LC_CTYPE
3873 # define LC_CTYPE 0
3874 # endif
3875 # ifndef LC_CTYPE_MASK
3876 # define LC_CTYPE_MASK 0
3877 # endif
3879 # ifndef HAVE_NEWLOCALE
3880 # undef freelocale
3881 # undef locale_t
3882 # undef newlocale
3883 # undef wcscoll_l
3884 # undef towlower_l
3885 # define freelocale emacs_freelocale
3886 # define locale_t emacs_locale_t
3887 # define newlocale emacs_newlocale
3888 # define wcscoll_l emacs_wcscoll_l
3889 # define towlower_l emacs_towlower_l
3891 typedef char const *locale_t;
3893 static locale_t
3894 newlocale (int category_mask, char const *locale, locale_t loc)
3896 return locale;
3899 static void
3900 freelocale (locale_t loc)
3904 static char *
3905 emacs_setlocale (int category, char const *locale)
3907 # ifdef HAVE_SETLOCALE
3908 errno = 0;
3909 char *loc = setlocale (category, locale);
3910 if (loc || errno)
3911 return loc;
3912 errno = EINVAL;
3913 # else
3914 errno = ENOTSUP;
3915 # endif
3916 return 0;
3919 static int
3920 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3922 int result = 0;
3923 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3924 int err;
3926 if (! oldloc)
3927 err = errno;
3928 else
3930 USE_SAFE_ALLOCA;
3931 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3932 strcpy (oldcopy, oldloc);
3933 if (! emacs_setlocale (LC_COLLATE, loc))
3934 err = errno;
3935 else
3937 errno = 0;
3938 result = wcscoll (a, b);
3939 err = errno;
3940 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3941 err = errno;
3943 SAFE_FREE ();
3946 errno = err;
3947 return result;
3950 static wint_t
3951 towlower_l (wint_t wc, locale_t loc)
3953 wint_t result = wc;
3954 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3956 if (oldloc)
3958 USE_SAFE_ALLOCA;
3959 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3960 strcpy (oldcopy, oldloc);
3961 if (emacs_setlocale (LC_CTYPE, loc))
3963 result = towlower (wc);
3964 emacs_setlocale (LC_COLLATE, oldcopy);
3966 SAFE_FREE ();
3969 return result;
3971 # endif
3974 str_collate (Lisp_Object s1, Lisp_Object s2,
3975 Lisp_Object locale, Lisp_Object ignore_case)
3977 int res, err;
3978 ptrdiff_t len, i, i_byte;
3979 wchar_t *p1, *p2;
3981 USE_SAFE_ALLOCA;
3983 /* Convert byte stream to code points. */
3984 len = SCHARS (s1); i = i_byte = 0;
3985 SAFE_NALLOCA (p1, 1, len + 1);
3986 while (i < len)
3987 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3988 *(p1+len) = 0;
3990 len = SCHARS (s2); i = i_byte = 0;
3991 SAFE_NALLOCA (p2, 1, len + 1);
3992 while (i < len)
3993 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3994 *(p2+len) = 0;
3996 if (STRINGP (locale))
3998 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3999 SSDATA (locale), 0);
4000 if (!loc)
4001 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4003 if (! NILP (ignore_case))
4004 for (int i = 1; i < 3; i++)
4006 wchar_t *p = (i == 1) ? p1 : p2;
4007 for (; *p; p++)
4008 *p = towlower_l (*p, loc);
4011 errno = 0;
4012 res = wcscoll_l (p1, p2, loc);
4013 err = errno;
4014 freelocale (loc);
4016 else
4018 if (! NILP (ignore_case))
4019 for (int i = 1; i < 3; i++)
4021 wchar_t *p = (i == 1) ? p1 : p2;
4022 for (; *p; p++)
4023 *p = towlower (*p);
4026 errno = 0;
4027 res = wcscoll (p1, p2);
4028 err = errno;
4030 # ifndef HAVE_NEWLOCALE
4031 if (err)
4032 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4033 # else
4034 if (err)
4035 error ("Invalid string for collation: %s", emacs_strerror (err));
4036 # endif
4038 SAFE_FREE ();
4039 return res;
4041 #endif /* __STDC_ISO_10646__ */
4043 #ifdef WINDOWSNT
4045 str_collate (Lisp_Object s1, Lisp_Object s2,
4046 Lisp_Object locale, Lisp_Object ignore_case)
4049 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4050 int res, err = errno;
4052 errno = 0;
4053 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4054 if (errno)
4055 error ("Invalid string for collation: %s", strerror (errno));
4057 errno = err;
4058 return res;
4060 #endif /* WINDOWSNT */