Fix a couple of make-temp-file races
[emacs.git] / src / sysdep.c
blob9eb733221e47b8a157bb40caa0bc8a1071653873
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 if (! O_CLOEXEC && 0 <= fd)
2397 fcntl (fd, F_SETFD, FD_CLOEXEC);
2398 return fd;
2401 /* Open FILE as a stream for Emacs use, with mode MODE.
2402 Act like emacs_open with respect to threads, signals, and quits. */
2404 FILE *
2405 emacs_fopen (char const *file, char const *mode)
2407 int fd, omode, oflags;
2408 int bflag = 0;
2409 char const *m = mode;
2411 switch (*m++)
2413 case 'r': omode = O_RDONLY; oflags = 0; break;
2414 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2415 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2416 default: emacs_abort ();
2419 while (*m)
2420 switch (*m++)
2422 case '+': omode = O_RDWR; break;
2423 case 't': bflag = O_TEXT; break;
2424 default: /* Ignore. */ break;
2427 fd = emacs_open (file, omode | oflags | bflag, 0666);
2428 return fd < 0 ? 0 : fdopen (fd, mode);
2431 /* Create a pipe for Emacs use. */
2434 emacs_pipe (int fd[2])
2436 #ifdef MSDOS
2437 return pipe (fd);
2438 #else /* !MSDOS */
2439 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2440 if (! O_CLOEXEC && result == 0)
2442 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2443 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2445 return result;
2446 #endif /* !MSDOS */
2449 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2450 For the background behind this mess, please see Austin Group defect 529
2451 <http://austingroupbugs.net/view.php?id=529>. */
2453 #ifndef POSIX_CLOSE_RESTART
2454 # define POSIX_CLOSE_RESTART 1
2455 static int
2456 posix_close (int fd, int flag)
2458 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2459 eassert (flag == POSIX_CLOSE_RESTART);
2461 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2462 on a system that does not define POSIX_CLOSE_RESTART.
2464 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2465 closed, and retrying the close could inadvertently close a file
2466 descriptor allocated by some other thread. In other systems
2467 (e.g., HP/UX) FD is not closed. And in still other systems
2468 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2469 multithreaded program there can be no way to tell.
2471 So, in this case, pretend that the close succeeded. This works
2472 well on systems like GNU/Linux that close FD. Although it may
2473 leak a file descriptor on other systems, the leak is unlikely and
2474 it's better to leak than to close a random victim. */
2475 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2477 #endif
2479 /* Close FD, retrying if interrupted. If successful, return 0;
2480 otherwise, return -1 and set errno to a non-EINTR value. Consider
2481 an EINPROGRESS error to be successful, as that's merely a signal
2482 arriving. FD is always closed when this function returns, even
2483 when it returns -1.
2485 Do not call this function if FD is nonnegative and might already be closed,
2486 as that might close an innocent victim opened by some other thread. */
2489 emacs_close (int fd)
2491 while (1)
2493 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2494 if (r == 0)
2495 return r;
2496 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2498 eassert (errno != EBADF || fd < 0);
2499 return errno == EINPROGRESS ? 0 : r;
2504 /* Maximum number of bytes to read or write in a single system call.
2505 This works around a serious bug in Linux kernels before 2.6.16; see
2506 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2507 It's likely to work around similar bugs in other operating systems, so do it
2508 on all platforms. Round INT_MAX down to a page size, with the conservative
2509 assumption that page sizes are at most 2**18 bytes (any kernel with a
2510 page size larger than that shouldn't have the bug). */
2511 #ifndef MAX_RW_COUNT
2512 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2513 #endif
2515 /* Read from FD to a buffer BUF with size NBYTE.
2516 If interrupted, process any quits and pending signals immediately
2517 if INTERRUPTIBLE, and then retry the read unless quitting.
2518 Return the number of bytes read, which might be less than NBYTE.
2519 On error, set errno to a value other than EINTR, and return -1. */
2520 static ptrdiff_t
2521 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2523 ssize_t result;
2525 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2526 passes a size that large to emacs_read. */
2529 if (interruptible)
2530 maybe_quit ();
2531 result = read (fd, buf, nbyte);
2533 while (result < 0 && errno == EINTR);
2535 return result;
2538 /* Read from FD to a buffer BUF with size NBYTE.
2539 If interrupted, retry the read. Return the number of bytes read,
2540 which might be less than NBYTE. On error, set errno to a value
2541 other than EINTR, and return -1. */
2542 ptrdiff_t
2543 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2545 return emacs_intr_read (fd, buf, nbyte, false);
2548 /* Like emacs_read, but also process quits and pending signals. */
2549 ptrdiff_t
2550 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2552 return emacs_intr_read (fd, buf, nbyte, true);
2555 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2556 interrupted or if a partial write occurs. Process any quits
2557 immediately if INTERRUPTIBLE is positive, and process any pending
2558 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2559 of bytes written; if this is less than NBYTE, set errno to a value
2560 other than EINTR. */
2561 static ptrdiff_t
2562 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2563 int interruptible)
2565 ptrdiff_t bytes_written = 0;
2567 while (nbyte > 0)
2569 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2571 if (n < 0)
2573 if (errno != EINTR)
2574 break;
2576 if (interruptible)
2578 if (0 < interruptible)
2579 maybe_quit ();
2580 if (pending_signals)
2581 process_pending_signals ();
2584 else
2586 buf += n;
2587 nbyte -= n;
2588 bytes_written += n;
2592 return bytes_written;
2595 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2596 interrupted or if a partial write occurs. Do not process quits or
2597 pending signals. Return the number of bytes written, setting errno
2598 if this is less than NBYTE. */
2599 ptrdiff_t
2600 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2602 return emacs_full_write (fd, buf, nbyte, 0);
2605 /* Like emacs_write, but also process pending signals. */
2606 ptrdiff_t
2607 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2609 return emacs_full_write (fd, buf, nbyte, -1);
2612 /* Like emacs_write, but also process quits and pending signals. */
2613 ptrdiff_t
2614 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2616 return emacs_full_write (fd, buf, nbyte, 1);
2619 /* Write a diagnostic to standard error that contains MESSAGE and a
2620 string derived from errno. Preserve errno. Do not buffer stderr.
2621 Do not process quits or pending signals if interrupted. */
2622 void
2623 emacs_perror (char const *message)
2625 int err = errno;
2626 char const *error_string = emacs_strerror (err);
2627 char const *command = (initial_argv && initial_argv[0]
2628 ? initial_argv[0] : "emacs");
2629 /* Write it out all at once, if it's short; this is less likely to
2630 be interleaved with other output. */
2631 char buf[BUFSIZ];
2632 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2633 command, message, error_string);
2634 if (0 <= nbytes && nbytes < BUFSIZ)
2635 emacs_write (STDERR_FILENO, buf, nbytes);
2636 else
2638 emacs_write (STDERR_FILENO, command, strlen (command));
2639 emacs_write (STDERR_FILENO, ": ", 2);
2640 emacs_write (STDERR_FILENO, message, strlen (message));
2641 emacs_write (STDERR_FILENO, ": ", 2);
2642 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2643 emacs_write (STDERR_FILENO, "\n", 1);
2645 errno = err;
2648 /* Return a struct timeval that is roughly equivalent to T.
2649 Use the least timeval not less than T.
2650 Return an extremal value if the result would overflow. */
2651 struct timeval
2652 make_timeval (struct timespec t)
2654 struct timeval tv;
2655 tv.tv_sec = t.tv_sec;
2656 tv.tv_usec = t.tv_nsec / 1000;
2658 if (t.tv_nsec % 1000 != 0)
2660 if (tv.tv_usec < 999999)
2661 tv.tv_usec++;
2662 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2664 tv.tv_sec++;
2665 tv.tv_usec = 0;
2669 return tv;
2672 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2673 ATIME and MTIME, respectively.
2674 FD must be either negative -- in which case it is ignored --
2675 or a file descriptor that is open on FILE.
2676 If FD is nonnegative, then FILE can be NULL. */
2678 set_file_times (int fd, const char *filename,
2679 struct timespec atime, struct timespec mtime)
2681 struct timespec timespec[2];
2682 timespec[0] = atime;
2683 timespec[1] = mtime;
2684 return fdutimens (fd, filename, timespec);
2687 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2688 This is like renameat except that it fails if DST already exists,
2689 or if this operation is not supported atomically. Return 0 if
2690 successful, -1 (setting errno) otherwise. */
2692 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2694 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2695 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2696 #else
2697 errno = ENOSYS;
2698 return -1;
2699 #endif
2702 /* Like strsignal, except async-signal-safe, and this function typically
2703 returns a string in the C locale rather than the current locale. */
2704 char const *
2705 safe_strsignal (int code)
2707 char const *signame = 0;
2709 if (0 <= code && code < sys_siglist_entries)
2710 signame = sys_siglist[code];
2711 if (! signame)
2712 signame = "Unknown signal";
2714 return signame;
2717 #ifndef DOS_NT
2718 /* For make-serial-process */
2720 serial_open (Lisp_Object port)
2722 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2723 if (fd < 0)
2724 report_file_error ("Opening serial port", port);
2725 #ifdef TIOCEXCL
2726 ioctl (fd, TIOCEXCL, (char *) 0);
2727 #endif
2729 return fd;
2732 #if !defined (HAVE_CFMAKERAW)
2733 /* Workaround for targets which are missing cfmakeraw. */
2734 /* Pasted from man page. */
2735 static void
2736 cfmakeraw (struct termios *termios_p)
2738 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2739 termios_p->c_oflag &= ~OPOST;
2740 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2741 termios_p->c_cflag &= ~(CSIZE|PARENB);
2742 termios_p->c_cflag |= CS8;
2744 #endif /* !defined (HAVE_CFMAKERAW */
2746 #if !defined (HAVE_CFSETSPEED)
2747 /* Workaround for targets which are missing cfsetspeed. */
2748 static int
2749 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2751 return (cfsetispeed (termios_p, vitesse)
2752 + cfsetospeed (termios_p, vitesse));
2754 #endif
2756 /* For serial-process-configure */
2757 void
2758 serial_configure (struct Lisp_Process *p,
2759 Lisp_Object contact)
2761 Lisp_Object childp2 = Qnil;
2762 Lisp_Object tem = Qnil;
2763 struct termios attr;
2764 int err;
2765 char summary[4] = "???"; /* This usually becomes "8N1". */
2767 childp2 = Fcopy_sequence (p->childp);
2769 /* Read port attributes and prepare default configuration. */
2770 err = tcgetattr (p->outfd, &attr);
2771 if (err != 0)
2772 report_file_error ("Failed tcgetattr", Qnil);
2773 cfmakeraw (&attr);
2774 #if defined (CLOCAL)
2775 attr.c_cflag |= CLOCAL;
2776 #endif
2777 #if defined (CREAD)
2778 attr.c_cflag |= CREAD;
2779 #endif
2781 /* Configure speed. */
2782 if (!NILP (Fplist_member (contact, QCspeed)))
2783 tem = Fplist_get (contact, QCspeed);
2784 else
2785 tem = Fplist_get (p->childp, QCspeed);
2786 CHECK_NUMBER (tem);
2787 err = cfsetspeed (&attr, XINT (tem));
2788 if (err != 0)
2789 report_file_error ("Failed cfsetspeed", tem);
2790 childp2 = Fplist_put (childp2, QCspeed, tem);
2792 /* Configure bytesize. */
2793 if (!NILP (Fplist_member (contact, QCbytesize)))
2794 tem = Fplist_get (contact, QCbytesize);
2795 else
2796 tem = Fplist_get (p->childp, QCbytesize);
2797 if (NILP (tem))
2798 tem = make_number (8);
2799 CHECK_NUMBER (tem);
2800 if (XINT (tem) != 7 && XINT (tem) != 8)
2801 error (":bytesize must be nil (8), 7, or 8");
2802 summary[0] = XINT (tem) + '0';
2803 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2804 attr.c_cflag &= ~CSIZE;
2805 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2806 #else
2807 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2808 if (XINT (tem) != 8)
2809 error ("Bytesize cannot be changed");
2810 #endif
2811 childp2 = Fplist_put (childp2, QCbytesize, tem);
2813 /* Configure parity. */
2814 if (!NILP (Fplist_member (contact, QCparity)))
2815 tem = Fplist_get (contact, QCparity);
2816 else
2817 tem = Fplist_get (p->childp, QCparity);
2818 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2819 error (":parity must be nil (no parity), `even', or `odd'");
2820 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2821 attr.c_cflag &= ~(PARENB | PARODD);
2822 attr.c_iflag &= ~(IGNPAR | INPCK);
2823 if (NILP (tem))
2825 summary[1] = 'N';
2827 else if (EQ (tem, Qeven))
2829 summary[1] = 'E';
2830 attr.c_cflag |= PARENB;
2831 attr.c_iflag |= (IGNPAR | INPCK);
2833 else if (EQ (tem, Qodd))
2835 summary[1] = 'O';
2836 attr.c_cflag |= (PARENB | PARODD);
2837 attr.c_iflag |= (IGNPAR | INPCK);
2839 #else
2840 /* Don't error on no parity, which should be set by cfmakeraw. */
2841 if (!NILP (tem))
2842 error ("Parity cannot be configured");
2843 #endif
2844 childp2 = Fplist_put (childp2, QCparity, tem);
2846 /* Configure stopbits. */
2847 if (!NILP (Fplist_member (contact, QCstopbits)))
2848 tem = Fplist_get (contact, QCstopbits);
2849 else
2850 tem = Fplist_get (p->childp, QCstopbits);
2851 if (NILP (tem))
2852 tem = make_number (1);
2853 CHECK_NUMBER (tem);
2854 if (XINT (tem) != 1 && XINT (tem) != 2)
2855 error (":stopbits must be nil (1 stopbit), 1, or 2");
2856 summary[2] = XINT (tem) + '0';
2857 #if defined (CSTOPB)
2858 attr.c_cflag &= ~CSTOPB;
2859 if (XINT (tem) == 2)
2860 attr.c_cflag |= CSTOPB;
2861 #else
2862 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2863 if (XINT (tem) != 1)
2864 error ("Stopbits cannot be configured");
2865 #endif
2866 childp2 = Fplist_put (childp2, QCstopbits, tem);
2868 /* Configure flowcontrol. */
2869 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2870 tem = Fplist_get (contact, QCflowcontrol);
2871 else
2872 tem = Fplist_get (p->childp, QCflowcontrol);
2873 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2874 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2875 #if defined (CRTSCTS)
2876 attr.c_cflag &= ~CRTSCTS;
2877 #endif
2878 #if defined (CNEW_RTSCTS)
2879 attr.c_cflag &= ~CNEW_RTSCTS;
2880 #endif
2881 #if defined (IXON) && defined (IXOFF)
2882 attr.c_iflag &= ~(IXON | IXOFF);
2883 #endif
2884 if (NILP (tem))
2886 /* Already configured. */
2888 else if (EQ (tem, Qhw))
2890 #if defined (CRTSCTS)
2891 attr.c_cflag |= CRTSCTS;
2892 #elif defined (CNEW_RTSCTS)
2893 attr.c_cflag |= CNEW_RTSCTS;
2894 #else
2895 error ("Hardware flowcontrol (RTS/CTS) not supported");
2896 #endif
2898 else if (EQ (tem, Qsw))
2900 #if defined (IXON) && defined (IXOFF)
2901 attr.c_iflag |= (IXON | IXOFF);
2902 #else
2903 error ("Software flowcontrol (XON/XOFF) not supported");
2904 #endif
2906 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2908 /* Activate configuration. */
2909 err = tcsetattr (p->outfd, TCSANOW, &attr);
2910 if (err != 0)
2911 report_file_error ("Failed tcsetattr", Qnil);
2913 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2914 pset_childp (p, childp2);
2916 #endif /* not DOS_NT */
2918 /* System depended enumeration of and access to system processes a-la ps(1). */
2920 #ifdef HAVE_PROCFS
2922 /* Process enumeration and access via /proc. */
2924 Lisp_Object
2925 list_system_processes (void)
2927 Lisp_Object procdir, match, proclist, next;
2928 Lisp_Object tail;
2930 /* For every process on the system, there's a directory in the
2931 "/proc" pseudo-directory whose name is the numeric ID of that
2932 process. */
2933 procdir = build_string ("/proc");
2934 match = build_string ("[0-9]+");
2935 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2937 /* `proclist' gives process IDs as strings. Destructively convert
2938 each string into a number. */
2939 for (tail = proclist; CONSP (tail); tail = next)
2941 next = XCDR (tail);
2942 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2945 /* directory_files_internal returns the files in reverse order; undo
2946 that. */
2947 proclist = Fnreverse (proclist);
2948 return proclist;
2951 #elif defined DARWIN_OS || defined __FreeBSD__
2953 Lisp_Object
2954 list_system_processes (void)
2956 #ifdef DARWIN_OS
2957 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2958 #else
2959 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2960 #endif
2961 size_t len;
2962 struct kinfo_proc *procs;
2963 size_t i;
2965 Lisp_Object proclist = Qnil;
2967 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2968 return proclist;
2970 procs = xmalloc (len);
2971 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2973 xfree (procs);
2974 return proclist;
2977 len /= sizeof (struct kinfo_proc);
2978 for (i = 0; i < len; i++)
2980 #ifdef DARWIN_OS
2981 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2982 #else
2983 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2984 #endif
2987 xfree (procs);
2989 return proclist;
2992 /* The WINDOWSNT implementation is in w32.c.
2993 The MSDOS implementation is in dosfns.c. */
2994 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2996 Lisp_Object
2997 list_system_processes (void)
2999 return Qnil;
3002 #endif /* !defined (WINDOWSNT) */
3004 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3005 static struct timespec
3006 time_from_jiffies (unsigned long long tval, long hz)
3008 unsigned long long s = tval / hz;
3009 unsigned long long frac = tval % hz;
3010 int ns;
3012 if (TYPE_MAXIMUM (time_t) < s)
3013 time_overflow ();
3014 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
3015 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
3016 ns = frac * TIMESPEC_RESOLUTION / hz;
3017 else
3019 /* This is reachable only in the unlikely case that HZ * HZ
3020 exceeds ULLONG_MAX. It calculates an approximation that is
3021 guaranteed to be in range. */
3022 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3023 + (hz % TIMESPEC_RESOLUTION != 0));
3024 ns = frac / hz_per_ns;
3027 return make_timespec (s, ns);
3030 static Lisp_Object
3031 ltime_from_jiffies (unsigned long long tval, long hz)
3033 struct timespec t = time_from_jiffies (tval, hz);
3034 return make_lisp_time (t);
3037 static struct timespec
3038 get_up_time (void)
3040 FILE *fup;
3041 struct timespec up = make_timespec (0, 0);
3043 block_input ();
3044 fup = emacs_fopen ("/proc/uptime", "r");
3046 if (fup)
3048 unsigned long long upsec, upfrac, idlesec, idlefrac;
3049 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3051 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3052 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3053 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3054 == 4)
3056 if (TYPE_MAXIMUM (time_t) < upsec)
3058 upsec = TYPE_MAXIMUM (time_t);
3059 upfrac = TIMESPEC_RESOLUTION - 1;
3061 else
3063 int upfraclen = upfrac_end - upfrac_start;
3064 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3065 upfrac *= 10;
3066 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3067 upfrac /= 10;
3068 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3070 up = make_timespec (upsec, upfrac);
3072 fclose (fup);
3074 unblock_input ();
3076 return up;
3079 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3080 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3082 static Lisp_Object
3083 procfs_ttyname (int rdev)
3085 FILE *fdev;
3086 char name[PATH_MAX];
3088 block_input ();
3089 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3090 name[0] = 0;
3092 if (fdev)
3094 unsigned major;
3095 unsigned long minor_beg, minor_end;
3096 char minor[25]; /* 2 32-bit numbers + dash */
3097 char *endp;
3099 for (; !feof_unlocked (fdev) && !ferror_unlocked (fdev); name[0] = 0)
3101 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3102 && major == MAJOR (rdev))
3104 minor_beg = strtoul (minor, &endp, 0);
3105 if (*endp == '\0')
3106 minor_end = minor_beg;
3107 else if (*endp == '-')
3108 minor_end = strtoul (endp + 1, &endp, 0);
3109 else
3110 continue;
3112 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3114 sprintf (name + strlen (name), "%u", MINOR (rdev));
3115 break;
3119 fclose (fdev);
3121 unblock_input ();
3122 return build_string (name);
3125 static uintmax_t
3126 procfs_get_total_memory (void)
3128 FILE *fmem;
3129 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3130 int c;
3132 block_input ();
3133 fmem = emacs_fopen ("/proc/meminfo", "r");
3135 if (fmem)
3137 uintmax_t entry_value;
3138 bool done;
3141 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3143 case 1:
3144 retval = entry_value;
3145 done = 1;
3146 break;
3148 case 0:
3149 while ((c = getc_unlocked (fmem)) != EOF && c != '\n')
3150 continue;
3151 done = c == EOF;
3152 break;
3154 default:
3155 done = 1;
3156 break;
3158 while (!done);
3160 fclose (fmem);
3162 unblock_input ();
3163 return retval;
3166 Lisp_Object
3167 system_process_attributes (Lisp_Object pid)
3169 char procfn[PATH_MAX], fn[PATH_MAX];
3170 struct stat st;
3171 struct passwd *pw;
3172 struct group *gr;
3173 long clocks_per_sec;
3174 char *procfn_end;
3175 char procbuf[1025], *p, *q;
3176 int fd;
3177 ssize_t nread;
3178 static char const default_cmd[] = "???";
3179 const char *cmd = default_cmd;
3180 int cmdsize = sizeof default_cmd - 1;
3181 char *cmdline = NULL;
3182 ptrdiff_t cmdline_size;
3183 char c;
3184 printmax_t proc_id;
3185 int ppid, pgrp, sess, tty, tpgid, thcount;
3186 uid_t uid;
3187 gid_t gid;
3188 unsigned long long u_time, s_time, cutime, cstime, start;
3189 long priority, niceness, rss;
3190 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3191 struct timespec tnow, tstart, tboot, telapsed, us_time;
3192 double pcpu, pmem;
3193 Lisp_Object attrs = Qnil;
3194 Lisp_Object decoded_cmd;
3195 ptrdiff_t count;
3197 CHECK_NUMBER_OR_FLOAT (pid);
3198 CONS_TO_INTEGER (pid, pid_t, proc_id);
3199 sprintf (procfn, "/proc/%"pMd, proc_id);
3200 if (stat (procfn, &st) < 0)
3201 return attrs;
3203 /* euid egid */
3204 uid = st.st_uid;
3205 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3206 block_input ();
3207 pw = getpwuid (uid);
3208 unblock_input ();
3209 if (pw)
3210 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3212 gid = st.st_gid;
3213 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3214 block_input ();
3215 gr = getgrgid (gid);
3216 unblock_input ();
3217 if (gr)
3218 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3220 count = SPECPDL_INDEX ();
3221 strcpy (fn, procfn);
3222 procfn_end = fn + strlen (fn);
3223 strcpy (procfn_end, "/stat");
3224 fd = emacs_open (fn, O_RDONLY, 0);
3225 if (fd < 0)
3226 nread = 0;
3227 else
3229 record_unwind_protect_int (close_file_unwind, fd);
3230 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3232 if (0 < nread)
3234 procbuf[nread] = '\0';
3235 p = procbuf;
3237 p = strchr (p, '(');
3238 if (p != NULL)
3240 q = strrchr (p + 1, ')');
3241 /* comm */
3242 if (q != NULL)
3244 cmd = p + 1;
3245 cmdsize = q - cmd;
3248 else
3249 q = NULL;
3250 /* Command name is encoded in locale-coding-system; decode it. */
3251 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3252 decoded_cmd = code_convert_string_norecord (cmd_str,
3253 Vlocale_coding_system, 0);
3254 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3256 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3257 utime stime cutime cstime priority nice thcount . start vsize rss */
3258 if (q
3259 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3260 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3261 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3262 &minflt, &cminflt, &majflt, &cmajflt,
3263 &u_time, &s_time, &cutime, &cstime,
3264 &priority, &niceness, &thcount, &start, &vsize, &rss)
3265 == 20))
3267 char state_str[2];
3268 state_str[0] = c;
3269 state_str[1] = '\0';
3270 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3271 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3272 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3273 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3274 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3275 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3276 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3277 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3278 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3279 attrs);
3280 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3281 attrs);
3282 clocks_per_sec = sysconf (_SC_CLK_TCK);
3283 if (clocks_per_sec < 0)
3284 clocks_per_sec = 100;
3285 attrs = Fcons (Fcons (Qutime,
3286 ltime_from_jiffies (u_time, clocks_per_sec)),
3287 attrs);
3288 attrs = Fcons (Fcons (Qstime,
3289 ltime_from_jiffies (s_time, clocks_per_sec)),
3290 attrs);
3291 attrs = Fcons (Fcons (Qtime,
3292 ltime_from_jiffies (s_time + u_time,
3293 clocks_per_sec)),
3294 attrs);
3295 attrs = Fcons (Fcons (Qcutime,
3296 ltime_from_jiffies (cutime, clocks_per_sec)),
3297 attrs);
3298 attrs = Fcons (Fcons (Qcstime,
3299 ltime_from_jiffies (cstime, clocks_per_sec)),
3300 attrs);
3301 attrs = Fcons (Fcons (Qctime,
3302 ltime_from_jiffies (cstime + cutime,
3303 clocks_per_sec)),
3304 attrs);
3305 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3306 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3307 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3308 attrs);
3309 tnow = current_timespec ();
3310 telapsed = get_up_time ();
3311 tboot = timespec_sub (tnow, telapsed);
3312 tstart = time_from_jiffies (start, clocks_per_sec);
3313 tstart = timespec_add (tboot, tstart);
3314 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3315 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3316 attrs);
3317 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3318 telapsed = timespec_sub (tnow, tstart);
3319 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3320 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3321 pcpu = timespectod (us_time) / timespectod (telapsed);
3322 if (pcpu > 1.0)
3323 pcpu = 1.0;
3324 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3325 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3326 if (pmem > 100)
3327 pmem = 100;
3328 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3331 unbind_to (count, Qnil);
3333 /* args */
3334 strcpy (procfn_end, "/cmdline");
3335 fd = emacs_open (fn, O_RDONLY, 0);
3336 if (fd >= 0)
3338 ptrdiff_t readsize, nread_incr;
3339 record_unwind_protect_int (close_file_unwind, fd);
3340 record_unwind_protect_nothing ();
3341 nread = cmdline_size = 0;
3345 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3346 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3348 /* Leave room even if every byte needs escaping below. */
3349 readsize = (cmdline_size >> 1) - nread;
3351 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3352 nread += max (0, nread_incr);
3354 while (nread_incr == readsize);
3356 if (nread)
3358 /* We don't want trailing null characters. */
3359 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3360 continue;
3362 /* Escape-quote whitespace and backslashes. */
3363 q = cmdline + cmdline_size;
3364 while (cmdline < p)
3366 char c = *--p;
3367 *--q = c ? c : ' ';
3368 if (c_isspace (c) || c == '\\')
3369 *--q = '\\';
3372 nread = cmdline + cmdline_size - q;
3375 if (!nread)
3377 nread = cmdsize + 2;
3378 cmdline_size = nread + 1;
3379 q = cmdline = xrealloc (cmdline, cmdline_size);
3380 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3381 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3383 /* Command line is encoded in locale-coding-system; decode it. */
3384 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3385 decoded_cmd = code_convert_string_norecord (cmd_str,
3386 Vlocale_coding_system, 0);
3387 unbind_to (count, Qnil);
3388 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3391 return attrs;
3394 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3396 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3397 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3398 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3399 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3400 #undef _FILE_OFFSET_BITS
3401 #else
3402 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3403 #endif
3405 #include <procfs.h>
3407 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3408 #define _FILE_OFFSET_BITS 64
3409 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3410 #endif
3411 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3413 Lisp_Object
3414 system_process_attributes (Lisp_Object pid)
3416 char procfn[PATH_MAX], fn[PATH_MAX];
3417 struct stat st;
3418 struct passwd *pw;
3419 struct group *gr;
3420 char *procfn_end;
3421 struct psinfo pinfo;
3422 int fd;
3423 ssize_t nread;
3424 printmax_t proc_id;
3425 uid_t uid;
3426 gid_t gid;
3427 Lisp_Object attrs = Qnil;
3428 Lisp_Object decoded_cmd;
3429 ptrdiff_t count;
3431 CHECK_NUMBER_OR_FLOAT (pid);
3432 CONS_TO_INTEGER (pid, pid_t, proc_id);
3433 sprintf (procfn, "/proc/%"pMd, proc_id);
3434 if (stat (procfn, &st) < 0)
3435 return attrs;
3437 /* euid egid */
3438 uid = st.st_uid;
3439 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3440 block_input ();
3441 pw = getpwuid (uid);
3442 unblock_input ();
3443 if (pw)
3444 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3446 gid = st.st_gid;
3447 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3448 block_input ();
3449 gr = getgrgid (gid);
3450 unblock_input ();
3451 if (gr)
3452 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3454 count = SPECPDL_INDEX ();
3455 strcpy (fn, procfn);
3456 procfn_end = fn + strlen (fn);
3457 strcpy (procfn_end, "/psinfo");
3458 fd = emacs_open (fn, O_RDONLY, 0);
3459 if (fd < 0)
3460 nread = 0;
3461 else
3463 record_unwind_protect_int (close_file_unwind, fd);
3464 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3467 if (nread == sizeof pinfo)
3469 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3470 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3471 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3474 char state_str[2];
3475 state_str[0] = pinfo.pr_lwp.pr_sname;
3476 state_str[1] = '\0';
3477 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3480 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3481 need to get a string from it. */
3483 /* FIXME: missing: Qtpgid */
3485 /* FIXME: missing:
3486 Qminflt
3487 Qmajflt
3488 Qcminflt
3489 Qcmajflt
3491 Qutime
3492 Qcutime
3493 Qstime
3494 Qcstime
3495 Are they available? */
3497 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3498 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3499 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3500 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3501 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3502 attrs);
3504 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3505 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3506 attrs);
3507 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3508 attrs);
3510 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3511 range 0 .. 2**15, representing 0.0 .. 1.0. */
3512 attrs = Fcons (Fcons (Qpcpu,
3513 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3514 attrs);
3515 attrs = Fcons (Fcons (Qpmem,
3516 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3517 attrs);
3519 AUTO_STRING (fname, pinfo.pr_fname);
3520 decoded_cmd = code_convert_string_norecord (fname,
3521 Vlocale_coding_system, 0);
3522 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3523 AUTO_STRING (psargs, pinfo.pr_psargs);
3524 decoded_cmd = code_convert_string_norecord (psargs,
3525 Vlocale_coding_system, 0);
3526 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3528 unbind_to (count, Qnil);
3529 return attrs;
3532 #elif defined __FreeBSD__
3534 static struct timespec
3535 timeval_to_timespec (struct timeval t)
3537 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3540 static Lisp_Object
3541 make_lisp_timeval (struct timeval t)
3543 return make_lisp_time (timeval_to_timespec (t));
3546 Lisp_Object
3547 system_process_attributes (Lisp_Object pid)
3549 int proc_id;
3550 int pagesize = getpagesize ();
3551 unsigned long npages;
3552 int fscale;
3553 struct passwd *pw;
3554 struct group *gr;
3555 char *ttyname;
3556 size_t len;
3557 char args[MAXPATHLEN];
3558 struct timespec t, now;
3560 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3561 struct kinfo_proc proc;
3562 size_t proclen = sizeof proc;
3564 Lisp_Object attrs = Qnil;
3565 Lisp_Object decoded_comm;
3567 CHECK_NUMBER_OR_FLOAT (pid);
3568 CONS_TO_INTEGER (pid, int, proc_id);
3569 mib[3] = proc_id;
3571 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3572 return attrs;
3574 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3576 block_input ();
3577 pw = getpwuid (proc.ki_uid);
3578 unblock_input ();
3579 if (pw)
3580 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3582 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3584 block_input ();
3585 gr = getgrgid (proc.ki_svgid);
3586 unblock_input ();
3587 if (gr)
3588 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3590 AUTO_STRING (comm, proc.ki_comm);
3591 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3593 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3595 char state[2] = {'\0', '\0'};
3596 switch (proc.ki_stat)
3598 case SRUN:
3599 state[0] = 'R';
3600 break;
3602 case SSLEEP:
3603 state[0] = 'S';
3604 break;
3606 case SLOCK:
3607 state[0] = 'D';
3608 break;
3610 case SZOMB:
3611 state[0] = 'Z';
3612 break;
3614 case SSTOP:
3615 state[0] = 'T';
3616 break;
3618 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3621 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3622 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3623 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3625 block_input ();
3626 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3627 unblock_input ();
3628 if (ttyname)
3629 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3631 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3632 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3633 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3634 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3635 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3637 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3638 attrs);
3639 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3640 attrs);
3641 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3642 timeval_to_timespec (proc.ki_rusage.ru_stime));
3643 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3645 attrs = Fcons (Fcons (Qcutime,
3646 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3647 attrs);
3648 attrs = Fcons (Fcons (Qcstime,
3649 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3650 attrs);
3651 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3652 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3653 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3655 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3656 attrs);
3657 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3658 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3659 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3660 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3661 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3662 attrs);
3664 now = current_timespec ();
3665 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3666 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3668 len = sizeof fscale;
3669 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3671 double pcpu;
3672 fixpt_t ccpu;
3673 len = sizeof ccpu;
3674 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3676 pcpu = (100.0 * proc.ki_pctcpu / fscale
3677 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3678 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3682 len = sizeof npages;
3683 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3685 double pmem = (proc.ki_flag & P_INMEM
3686 ? 100.0 * proc.ki_rssize / npages
3687 : 0);
3688 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3691 mib[2] = KERN_PROC_ARGS;
3692 len = MAXPATHLEN;
3693 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3695 int i;
3696 for (i = 0; i < len; i++)
3698 if (! args[i] && i < len - 1)
3699 args[i] = ' ';
3702 AUTO_STRING (comm, args);
3703 decoded_comm = code_convert_string_norecord (comm,
3704 Vlocale_coding_system, 0);
3706 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3709 return attrs;
3712 #elif defined DARWIN_OS
3714 static struct timespec
3715 timeval_to_timespec (struct timeval t)
3717 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3720 static Lisp_Object
3721 make_lisp_timeval (struct timeval t)
3723 return make_lisp_time (timeval_to_timespec (t));
3726 Lisp_Object
3727 system_process_attributes (Lisp_Object pid)
3729 int proc_id;
3730 struct passwd *pw;
3731 struct group *gr;
3732 char *ttyname;
3733 struct timeval starttime;
3734 struct timespec t, now;
3735 struct rusage *rusage;
3736 dev_t tdev;
3737 uid_t uid;
3738 gid_t gid;
3740 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3741 struct kinfo_proc proc;
3742 size_t proclen = sizeof proc;
3744 Lisp_Object attrs = Qnil;
3745 Lisp_Object decoded_comm;
3747 CHECK_NUMBER_OR_FLOAT (pid);
3748 CONS_TO_INTEGER (pid, int, proc_id);
3749 mib[3] = proc_id;
3751 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3752 return attrs;
3754 uid = proc.kp_eproc.e_ucred.cr_uid;
3755 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3757 block_input ();
3758 pw = getpwuid (uid);
3759 unblock_input ();
3760 if (pw)
3761 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3763 gid = proc.kp_eproc.e_pcred.p_svgid;
3764 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3766 block_input ();
3767 gr = getgrgid (gid);
3768 unblock_input ();
3769 if (gr)
3770 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3772 decoded_comm = (code_convert_string_norecord
3773 (build_unibyte_string (proc.kp_proc.p_comm),
3774 Vlocale_coding_system, 0));
3776 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3778 char state[2] = {'\0', '\0'};
3779 switch (proc.kp_proc.p_stat)
3781 case SRUN:
3782 state[0] = 'R';
3783 break;
3785 case SSLEEP:
3786 state[0] = 'S';
3787 break;
3789 case SZOMB:
3790 state[0] = 'Z';
3791 break;
3793 case SSTOP:
3794 state[0] = 'T';
3795 break;
3797 case SIDL:
3798 state[0] = 'I';
3799 break;
3801 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3804 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3805 attrs);
3806 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3807 attrs);
3809 tdev = proc.kp_eproc.e_tdev;
3810 block_input ();
3811 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3812 unblock_input ();
3813 if (ttyname)
3814 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3816 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3817 attrs);
3819 rusage = proc.kp_proc.p_ru;
3820 if (rusage)
3822 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3823 attrs);
3824 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3825 attrs);
3827 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3828 attrs);
3829 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3830 attrs);
3831 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3832 timeval_to_timespec (rusage->ru_stime));
3833 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3836 starttime = proc.kp_proc.p_starttime;
3837 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3838 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3840 now = current_timespec ();
3841 t = timespec_sub (now, timeval_to_timespec (starttime));
3842 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3844 return attrs;
3847 /* The WINDOWSNT implementation is in w32.c.
3848 The MSDOS implementation is in dosfns.c. */
3849 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3851 Lisp_Object
3852 system_process_attributes (Lisp_Object pid)
3854 return Qnil;
3857 #endif /* !defined (WINDOWSNT) */
3859 /* Wide character string collation. */
3861 #ifdef __STDC_ISO_10646__
3862 # include <wchar.h>
3863 # include <wctype.h>
3865 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3866 # include <locale.h>
3867 # endif
3868 # ifndef LC_COLLATE
3869 # define LC_COLLATE 0
3870 # endif
3871 # ifndef LC_COLLATE_MASK
3872 # define LC_COLLATE_MASK 0
3873 # endif
3874 # ifndef LC_CTYPE
3875 # define LC_CTYPE 0
3876 # endif
3877 # ifndef LC_CTYPE_MASK
3878 # define LC_CTYPE_MASK 0
3879 # endif
3881 # ifndef HAVE_NEWLOCALE
3882 # undef freelocale
3883 # undef locale_t
3884 # undef newlocale
3885 # undef wcscoll_l
3886 # undef towlower_l
3887 # define freelocale emacs_freelocale
3888 # define locale_t emacs_locale_t
3889 # define newlocale emacs_newlocale
3890 # define wcscoll_l emacs_wcscoll_l
3891 # define towlower_l emacs_towlower_l
3893 typedef char const *locale_t;
3895 static locale_t
3896 newlocale (int category_mask, char const *locale, locale_t loc)
3898 return locale;
3901 static void
3902 freelocale (locale_t loc)
3906 static char *
3907 emacs_setlocale (int category, char const *locale)
3909 # ifdef HAVE_SETLOCALE
3910 errno = 0;
3911 char *loc = setlocale (category, locale);
3912 if (loc || errno)
3913 return loc;
3914 errno = EINVAL;
3915 # else
3916 errno = ENOTSUP;
3917 # endif
3918 return 0;
3921 static int
3922 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3924 int result = 0;
3925 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3926 int err;
3928 if (! oldloc)
3929 err = errno;
3930 else
3932 USE_SAFE_ALLOCA;
3933 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3934 strcpy (oldcopy, oldloc);
3935 if (! emacs_setlocale (LC_COLLATE, loc))
3936 err = errno;
3937 else
3939 errno = 0;
3940 result = wcscoll (a, b);
3941 err = errno;
3942 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3943 err = errno;
3945 SAFE_FREE ();
3948 errno = err;
3949 return result;
3952 static wint_t
3953 towlower_l (wint_t wc, locale_t loc)
3955 wint_t result = wc;
3956 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3958 if (oldloc)
3960 USE_SAFE_ALLOCA;
3961 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3962 strcpy (oldcopy, oldloc);
3963 if (emacs_setlocale (LC_CTYPE, loc))
3965 result = towlower (wc);
3966 emacs_setlocale (LC_COLLATE, oldcopy);
3968 SAFE_FREE ();
3971 return result;
3973 # endif
3976 str_collate (Lisp_Object s1, Lisp_Object s2,
3977 Lisp_Object locale, Lisp_Object ignore_case)
3979 int res, err;
3980 ptrdiff_t len, i, i_byte;
3981 wchar_t *p1, *p2;
3983 USE_SAFE_ALLOCA;
3985 /* Convert byte stream to code points. */
3986 len = SCHARS (s1); i = i_byte = 0;
3987 SAFE_NALLOCA (p1, 1, len + 1);
3988 while (i < len)
3989 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3990 *(p1+len) = 0;
3992 len = SCHARS (s2); i = i_byte = 0;
3993 SAFE_NALLOCA (p2, 1, len + 1);
3994 while (i < len)
3995 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3996 *(p2+len) = 0;
3998 if (STRINGP (locale))
4000 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
4001 SSDATA (locale), 0);
4002 if (!loc)
4003 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4005 if (! NILP (ignore_case))
4006 for (int i = 1; i < 3; i++)
4008 wchar_t *p = (i == 1) ? p1 : p2;
4009 for (; *p; p++)
4010 *p = towlower_l (*p, loc);
4013 errno = 0;
4014 res = wcscoll_l (p1, p2, loc);
4015 err = errno;
4016 freelocale (loc);
4018 else
4020 if (! NILP (ignore_case))
4021 for (int i = 1; i < 3; i++)
4023 wchar_t *p = (i == 1) ? p1 : p2;
4024 for (; *p; p++)
4025 *p = towlower (*p);
4028 errno = 0;
4029 res = wcscoll (p1, p2);
4030 err = errno;
4032 # ifndef HAVE_NEWLOCALE
4033 if (err)
4034 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4035 # else
4036 if (err)
4037 error ("Invalid string for collation: %s", emacs_strerror (err));
4038 # endif
4040 SAFE_FREE ();
4041 return res;
4043 #endif /* __STDC_ISO_10646__ */
4045 #ifdef WINDOWSNT
4047 str_collate (Lisp_Object s1, Lisp_Object s2,
4048 Lisp_Object locale, Lisp_Object ignore_case)
4051 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4052 int res, err = errno;
4054 errno = 0;
4055 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4056 if (errno)
4057 error ("Invalid string for collation: %s", strerror (errno));
4059 errno = err;
4060 return res;
4062 #endif /* WINDOWSNT */