; * test/lisp/buff-menu-tests.el: Fix typo in the header.
[emacs.git] / src / sysdep.c
blob86d420f66c4250e0ddde4f389e8cc4d567a90d68
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2016 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <execinfo.h>
23 #include "sysstdio.h"
24 #ifdef HAVE_PWD_H
25 #include <pwd.h>
26 #include <grp.h>
27 #endif /* HAVE_PWD_H */
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
33 #include <utimens.h>
35 #include "lisp.h"
36 #include "sheap.h"
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #if defined DARWIN_OS || defined __FreeBSD__
41 # include <sys/sysctl.h>
42 #endif
44 #ifdef __FreeBSD__
45 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
46 'struct frame', so rename it. */
47 # define frame freebsd_frame
48 # include <sys/user.h>
49 # undef frame
51 # include <math.h>
52 #endif
54 #ifdef HAVE_SOCKETS
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #endif /* HAVE_SOCKETS */
59 #ifdef WINDOWSNT
60 #define read sys_read
61 #define write sys_write
62 #ifndef STDERR_FILENO
63 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
64 #endif
65 #include "w32.h"
66 #endif /* WINDOWSNT */
68 #include <sys/types.h>
69 #include <sys/stat.h>
70 #include <errno.h>
72 /* Get SI_SRPC_DOMAIN, if it is available. */
73 #ifdef HAVE_SYS_SYSTEMINFO_H
74 #include <sys/systeminfo.h>
75 #endif
77 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
78 #include "msdos.h"
79 #endif
81 #include <sys/param.h>
82 #include <sys/file.h>
83 #include <fcntl.h>
85 #include "systty.h"
86 #include "syswait.h"
88 #ifdef HAVE_SYS_UTSNAME_H
89 #include <sys/utsname.h>
90 #include <memory.h>
91 #endif /* HAVE_SYS_UTSNAME_H */
93 #include "keyboard.h"
94 #include "frame.h"
95 #include "termhooks.h"
96 #include "termchar.h"
97 #include "termopts.h"
98 #include "process.h"
99 #include "cm.h"
101 #include "gnutls.h"
102 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
103 do that during startup just to call gnutls_rnd. */
104 #if defined HAVE_GNUTLS && !defined WINDOWSNT
105 # include <gnutls/crypto.h>
106 #else
107 # define emacs_gnutls_global_init() Qnil
108 # define gnutls_rnd(level, data, len) (-1)
109 #endif
111 #ifdef WINDOWSNT
112 #include <direct.h>
113 /* In process.h which conflicts with the local copy. */
114 #define _P_WAIT 0
115 int _cdecl _spawnlp (int, const char *, const char *, ...);
116 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
117 several prototypes of functions called below. */
118 #include <sys/socket.h>
119 #endif
121 #include "syssignal.h"
122 #include "systime.h"
124 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
125 #ifndef ULLONG_MAX
126 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
127 #endif
129 /* Declare here, including term.h is problematic on some systems. */
130 extern void tputs (const char *, int, int (*)(int));
132 static const int baud_convert[] =
134 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
135 1800, 2400, 4800, 9600, 19200, 38400
138 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
139 # include <sys/personality.h>
141 /* Disable address randomization in the current process. Return true
142 if addresses were randomized but this has been disabled, false
143 otherwise. */
144 bool
145 disable_address_randomization (void)
147 int pers = personality (0xffffffff);
148 if (pers < 0)
149 return false;
150 int desired_pers = pers | ADDR_NO_RANDOMIZE;
152 /* Call 'personality' twice, to detect buggy platforms like WSL
153 where 'personality' always returns 0. */
154 return (pers != desired_pers
155 && personality (desired_pers) == pers
156 && personality (0xffffffff) == desired_pers);
158 #endif
160 /* Execute the program in FILE, with argument vector ARGV and environ
161 ENVP. Return an error number if unsuccessful. This is like execve
162 except it reenables ASLR in the executed program if necessary, and
163 on error it returns an error number rather than -1. */
165 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
167 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
168 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
169 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
170 if (change_personality)
171 personality (pers & ~ADDR_NO_RANDOMIZE);
172 #endif
174 execve (file, argv, envp);
175 int err = errno;
177 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
178 if (change_personality)
179 personality (pers);
180 #endif
182 return err;
185 /* If FD is not already open, arrange for it to be open with FLAGS. */
186 static void
187 force_open (int fd, int flags)
189 if (dup2 (fd, fd) < 0 && errno == EBADF)
191 int n = open (NULL_DEVICE, flags);
192 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
194 emacs_perror (NULL_DEVICE);
195 exit (EXIT_FAILURE);
200 /* Make sure stdin, stdout, and stderr are open to something, so that
201 their file descriptors are not hijacked by later system calls. */
202 void
203 init_standard_fds (void)
205 /* Open stdin for *writing*, and stdout and stderr for *reading*.
206 That way, any attempt to do normal I/O will result in an error,
207 just as if the files were closed, and the file descriptors will
208 not be reused by later opens. */
209 force_open (STDIN_FILENO, O_WRONLY);
210 force_open (STDOUT_FILENO, O_RDONLY);
211 force_open (STDERR_FILENO, O_RDONLY);
214 /* Return the current working directory. The result should be freed
215 with 'free'. Return NULL on errors. */
216 char *
217 emacs_get_current_dir_name (void)
219 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
220 # ifdef HYBRID_MALLOC
221 bool use_libc = bss_sbrk_did_unexec;
222 # else
223 bool use_libc = true;
224 # endif
225 if (use_libc)
226 return get_current_dir_name ();
227 # endif
229 char *buf;
230 char *pwd = getenv ("PWD");
231 struct stat dotstat, pwdstat;
232 /* If PWD is accurate, use it instead of calling getcwd. PWD is
233 sometimes a nicer name, and using it may avoid a fatal error if a
234 parent directory is searchable but not readable. */
235 if (pwd
236 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
237 && stat (pwd, &pwdstat) == 0
238 && stat (".", &dotstat) == 0
239 && dotstat.st_ino == pwdstat.st_ino
240 && dotstat.st_dev == pwdstat.st_dev
241 #ifdef MAXPATHLEN
242 && strlen (pwd) < MAXPATHLEN
243 #endif
246 buf = malloc (strlen (pwd) + 1);
247 if (!buf)
248 return NULL;
249 strcpy (buf, pwd);
251 else
253 size_t buf_size = 1024;
254 buf = malloc (buf_size);
255 if (!buf)
256 return NULL;
257 for (;;)
259 if (getcwd (buf, buf_size) == buf)
260 break;
261 if (errno != ERANGE)
263 int tmp_errno = errno;
264 free (buf);
265 errno = tmp_errno;
266 return NULL;
268 buf_size *= 2;
269 buf = realloc (buf, buf_size);
270 if (!buf)
271 return NULL;
274 return buf;
278 /* Discard pending input on all input descriptors. */
280 void
281 discard_tty_input (void)
283 #ifndef WINDOWSNT
284 struct emacs_tty buf;
286 if (noninteractive)
287 return;
289 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
290 while (dos_keyread () != -1)
292 #else /* not MSDOS */
294 struct tty_display_info *tty;
295 for (tty = tty_list; tty; tty = tty->next)
297 if (tty->input) /* Is the device suspended? */
299 emacs_get_tty (fileno (tty->input), &buf);
300 emacs_set_tty (fileno (tty->input), &buf, 0);
304 #endif /* not MSDOS */
305 #endif /* not WINDOWSNT */
309 #ifdef SIGTSTP
311 /* Arrange for character C to be read as the next input from
312 the terminal.
313 XXX What if we have multiple ttys?
316 void
317 stuff_char (char c)
319 if (! (FRAMEP (selected_frame)
320 && FRAME_LIVE_P (XFRAME (selected_frame))
321 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
322 return;
324 /* Should perhaps error if in batch mode */
325 #ifdef TIOCSTI
326 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
327 #else /* no TIOCSTI */
328 error ("Cannot stuff terminal input characters in this version of Unix");
329 #endif /* no TIOCSTI */
332 #endif /* SIGTSTP */
334 void
335 init_baud_rate (int fd)
337 int emacs_ospeed;
339 if (noninteractive)
340 emacs_ospeed = 0;
341 else
343 #ifdef DOS_NT
344 emacs_ospeed = 15;
345 #else /* not DOS_NT */
346 struct termios sg;
348 sg.c_cflag = B9600;
349 tcgetattr (fd, &sg);
350 emacs_ospeed = cfgetospeed (&sg);
351 #endif /* not DOS_NT */
354 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
355 ? baud_convert[emacs_ospeed] : 9600);
356 if (baud_rate == 0)
357 baud_rate = 1200;
362 #ifndef MSDOS
364 /* Wait for the subprocess with process id CHILD to terminate or change status.
365 CHILD must be a child process that has not been reaped.
366 If STATUS is non-null, store the waitpid-style exit status into *STATUS
367 and tell wait_reading_process_output that it needs to look around.
368 Use waitpid-style OPTIONS when waiting.
369 If INTERRUPTIBLE, this function is interruptible by a signal.
371 Return CHILD if successful, 0 if no status is available;
372 the latter is possible only when options & NOHANG. */
373 static pid_t
374 get_child_status (pid_t child, int *status, int options, bool interruptible)
376 pid_t pid;
378 /* Invoke waitpid only with a known process ID; do not invoke
379 waitpid with a nonpositive argument. Otherwise, Emacs might
380 reap an unwanted process by mistake. For example, invoking
381 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
382 so that another thread running glib won't find them. */
383 eassert (child > 0);
385 while ((pid = waitpid (child, status, options)) < 0)
387 /* Check that CHILD is a child process that has not been reaped,
388 and that STATUS and OPTIONS are valid. Otherwise abort,
389 as continuing after this internal error could cause Emacs to
390 become confused and kill innocent-victim processes. */
391 if (errno != EINTR)
392 emacs_abort ();
394 /* Note: the MS-Windows emulation of waitpid calls QUIT
395 internally. */
396 if (interruptible)
397 QUIT;
400 /* If successful and status is requested, tell wait_reading_process_output
401 that it needs to wake up and look around. */
402 if (pid && status && input_available_clear_time)
403 *input_available_clear_time = make_timespec (0, 0);
405 return pid;
408 /* Wait for the subprocess with process id CHILD to terminate.
409 CHILD must be a child process that has not been reaped.
410 If STATUS is non-null, store the waitpid-style exit status into *STATUS
411 and tell wait_reading_process_output that it needs to look around.
412 If INTERRUPTIBLE, this function is interruptible by a signal. */
413 void
414 wait_for_termination (pid_t child, int *status, bool interruptible)
416 get_child_status (child, status, 0, interruptible);
419 /* Report whether the subprocess with process id CHILD has changed status.
420 Termination counts as a change of status.
421 CHILD must be a child process that has not been reaped.
422 If STATUS is non-null, store the waitpid-style exit status into *STATUS
423 and tell wait_reading_process_output that it needs to look around.
424 Use waitpid-style OPTIONS to check status, but do not wait.
426 Return CHILD if successful, 0 if no status is available because
427 the process's state has not changed. */
428 pid_t
429 child_status_changed (pid_t child, int *status, int options)
431 return get_child_status (child, status, WNOHANG | options, 0);
435 /* Set up the terminal at the other end of a pseudo-terminal that
436 we will be controlling an inferior through.
437 It should not echo or do line-editing, since that is done
438 in Emacs. No padding needed for insertion into an Emacs buffer. */
440 void
441 child_setup_tty (int out)
443 #ifndef WINDOWSNT
444 struct emacs_tty s;
446 emacs_get_tty (out, &s);
447 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
448 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
449 #ifdef NLDLY
450 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
451 Some versions of GNU Hurd do not have FFDLY? */
452 #ifdef FFDLY
453 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
454 /* No output delays */
455 #else
456 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
457 /* No output delays */
458 #endif
459 #endif
460 s.main.c_lflag &= ~ECHO; /* Disable echo */
461 s.main.c_lflag |= ISIG; /* Enable signals */
462 #ifdef IUCLC
463 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
464 #endif
465 #ifdef ISTRIP
466 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
467 #endif
468 #ifdef OLCUC
469 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
470 #endif
471 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
472 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
473 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
474 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
476 #ifdef HPUX
477 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
478 #endif /* HPUX */
480 #ifdef SIGNALS_VIA_CHARACTERS
481 /* the QUIT and INTR character are used in process_send_signal
482 so set them here to something useful. */
483 if (s.main.c_cc[VQUIT] == CDISABLE)
484 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
485 if (s.main.c_cc[VINTR] == CDISABLE)
486 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
487 #endif /* not SIGNALS_VIA_CHARACTERS */
489 #ifdef AIX
490 /* Also, PTY overloads NUL and BREAK.
491 don't ignore break, but don't signal either, so it looks like NUL. */
492 s.main.c_iflag &= ~IGNBRK;
493 s.main.c_iflag &= ~BRKINT;
494 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
495 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
496 would force it to 0377. That looks like duplicated code. */
497 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
498 #endif /* AIX */
500 /* We originally enabled ICANON (and set VEOF to 04), and then had
501 process.c send additional EOF chars to flush the output when faced
502 with long lines, but this leads to weird effects when the
503 subprocess has disabled ICANON and ends up seeing those spurious
504 extra EOFs. So we don't send EOFs any more in
505 process.c:send_process. First we tried to disable ICANON by
506 default, so if a subsprocess sets up ICANON, it's his problem (or
507 the Elisp package that talks to it) to deal with lines that are
508 too long. But this disables some features, such as the ability
509 to send EOF signals. So we re-enabled ICANON but there is no
510 more "send eof to flush" going on (which is wrong and unportable
511 in itself). The correct way to handle too much output is to
512 buffer what could not be written and then write it again when
513 select returns ok for writing. This has it own set of
514 problems. Write is now asynchronous, is that a problem? How much
515 do we buffer, and what do we do when that limit is reached? */
517 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
518 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
519 #if 0 /* These settings only apply to non-ICANON mode. */
520 s.main.c_cc[VMIN] = 1;
521 s.main.c_cc[VTIME] = 0;
522 #endif
524 emacs_set_tty (out, &s, 0);
525 #endif /* not WINDOWSNT */
527 #endif /* not MSDOS */
530 /* Record a signal code and the action for it. */
531 struct save_signal
533 int code;
534 struct sigaction action;
537 static void save_signal_handlers (struct save_signal *);
538 static void restore_signal_handlers (struct save_signal *);
540 /* Suspend the Emacs process; give terminal to its superior. */
542 void
543 sys_suspend (void)
545 #ifndef DOS_NT
546 kill (0, SIGTSTP);
547 #else
548 /* On a system where suspending is not implemented,
549 instead fork a subshell and let it talk directly to the terminal
550 while we wait. */
551 sys_subshell ();
553 #endif
556 /* Fork a subshell. */
558 void
559 sys_subshell (void)
561 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
562 #ifdef MSDOS
563 int st;
564 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
565 #else
566 char oldwd[MAX_UTF8_PATH];
567 #endif /* MSDOS */
568 #else /* !DOS_NT */
569 int status;
570 #endif
571 pid_t pid;
572 struct save_signal saved_handlers[5];
573 char *str = SSDATA (encode_current_directory ());
575 #ifdef DOS_NT
576 pid = 0;
577 #else
579 char *volatile str_volatile = str;
580 pid = vfork ();
581 str = str_volatile;
583 #endif
585 if (pid < 0)
586 error ("Can't spawn subshell");
588 saved_handlers[0].code = SIGINT;
589 saved_handlers[1].code = SIGQUIT;
590 saved_handlers[2].code = SIGTERM;
591 #ifdef USABLE_SIGIO
592 saved_handlers[3].code = SIGIO;
593 saved_handlers[4].code = 0;
594 #else
595 saved_handlers[3].code = 0;
596 #endif
598 #ifdef DOS_NT
599 save_signal_handlers (saved_handlers);
600 #endif
602 if (pid == 0)
604 const char *sh = 0;
606 #ifdef DOS_NT /* MW, Aug 1993 */
607 getcwd (oldwd, sizeof oldwd);
608 if (sh == 0)
609 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
610 #endif
611 if (sh == 0)
612 sh = egetenv ("SHELL");
613 if (sh == 0)
614 sh = "sh";
616 /* Use our buffer's default directory for the subshell. */
617 if (chdir (str) != 0)
619 #ifndef DOS_NT
620 emacs_perror (str);
621 _exit (EXIT_CANCELED);
622 #endif
625 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
627 char *epwd = getenv ("PWD");
628 char old_pwd[MAXPATHLEN+1+4];
630 /* If PWD is set, pass it with corrected value. */
631 if (epwd)
633 strcpy (old_pwd, epwd);
634 setenv ("PWD", str, 1);
636 st = system (sh);
637 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
638 if (epwd)
639 putenv (old_pwd); /* restore previous value */
641 #else /* not MSDOS */
642 #ifdef WINDOWSNT
643 /* Waits for process completion */
644 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
645 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
646 if (pid == -1)
647 write (1, "Can't execute subshell", 22);
648 #else /* not WINDOWSNT */
649 execlp (sh, sh, (char *) 0);
650 emacs_perror (sh);
651 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
652 #endif /* not WINDOWSNT */
653 #endif /* not MSDOS */
656 /* Do this now if we did not do it before. */
657 #ifndef MSDOS
658 save_signal_handlers (saved_handlers);
659 #endif
661 #ifndef DOS_NT
662 wait_for_termination (pid, &status, 0);
663 #endif
664 restore_signal_handlers (saved_handlers);
667 static void
668 save_signal_handlers (struct save_signal *saved_handlers)
670 while (saved_handlers->code)
672 struct sigaction action;
673 emacs_sigaction_init (&action, SIG_IGN);
674 sigaction (saved_handlers->code, &action, &saved_handlers->action);
675 saved_handlers++;
679 static void
680 restore_signal_handlers (struct save_signal *saved_handlers)
682 while (saved_handlers->code)
684 sigaction (saved_handlers->code, &saved_handlers->action, 0);
685 saved_handlers++;
689 #ifdef USABLE_SIGIO
690 static int old_fcntl_flags[FD_SETSIZE];
691 #endif
693 void
694 init_sigio (int fd)
696 #ifdef USABLE_SIGIO
697 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
698 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
699 interrupts_deferred = 0;
700 #endif
703 #ifndef DOS_NT
704 static void
705 reset_sigio (int fd)
707 #ifdef USABLE_SIGIO
708 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
709 #endif
711 #endif
713 void
714 request_sigio (void)
716 #ifdef USABLE_SIGIO
717 sigset_t unblocked;
719 if (noninteractive)
720 return;
722 sigemptyset (&unblocked);
723 # ifdef SIGWINCH
724 sigaddset (&unblocked, SIGWINCH);
725 # endif
726 sigaddset (&unblocked, SIGIO);
727 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
729 interrupts_deferred = 0;
730 #endif
733 void
734 unrequest_sigio (void)
736 #ifdef USABLE_SIGIO
737 sigset_t blocked;
739 if (noninteractive)
740 return;
742 sigemptyset (&blocked);
743 # ifdef SIGWINCH
744 sigaddset (&blocked, SIGWINCH);
745 # endif
746 sigaddset (&blocked, SIGIO);
747 pthread_sigmask (SIG_BLOCK, &blocked, 0);
748 interrupts_deferred = 1;
749 #endif
752 #ifndef MSDOS
753 /* Block SIGCHLD. */
755 void
756 block_child_signal (sigset_t *oldset)
758 sigset_t blocked;
759 sigemptyset (&blocked);
760 sigaddset (&blocked, SIGCHLD);
761 sigaddset (&blocked, SIGINT);
762 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
765 /* Unblock SIGCHLD. */
767 void
768 unblock_child_signal (sigset_t const *oldset)
770 pthread_sigmask (SIG_SETMASK, oldset, 0);
773 /* Block SIGINT. */
774 void
775 block_interrupt_signal (sigset_t *oldset)
777 sigset_t blocked;
778 sigemptyset (&blocked);
779 sigaddset (&blocked, SIGINT);
780 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
783 /* Restore previously saved signal mask. */
784 void
785 restore_signal_mask (sigset_t const *oldset)
787 pthread_sigmask (SIG_SETMASK, oldset, 0);
790 #endif /* !MSDOS */
792 /* Saving and restoring the process group of Emacs's terminal. */
794 /* The process group of which Emacs was a member when it initially
795 started.
797 If Emacs was in its own process group (i.e. inherited_pgroup ==
798 getpid ()), then we know we're running under a shell with job
799 control (Emacs would never be run as part of a pipeline).
800 Everything is fine.
802 If Emacs was not in its own process group, then we know we're
803 running under a shell (or a caller) that doesn't know how to
804 separate itself from Emacs (like sh). Emacs must be in its own
805 process group in order to receive SIGIO correctly. In this
806 situation, we put ourselves in our own pgroup, forcibly set the
807 tty's pgroup to our pgroup, and make sure to restore and reinstate
808 the tty's pgroup just like any other terminal setting. If
809 inherited_group was not the tty's pgroup, then we'll get a
810 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
811 it goes foreground in the future, which is what should happen. */
813 static pid_t inherited_pgroup;
815 void
816 init_foreground_group (void)
818 pid_t pgrp = getpgrp ();
819 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
822 /* Block and unblock SIGTTOU. */
824 void
825 block_tty_out_signal (sigset_t *oldset)
827 #ifdef SIGTTOU
828 sigset_t blocked;
829 sigemptyset (&blocked);
830 sigaddset (&blocked, SIGTTOU);
831 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
832 #endif
835 void
836 unblock_tty_out_signal (sigset_t const *oldset)
838 #ifdef SIGTTOU
839 pthread_sigmask (SIG_SETMASK, oldset, 0);
840 #endif
843 /* Safely set a controlling terminal FD's process group to PGID.
844 If we are not in the foreground already, POSIX requires tcsetpgrp
845 to deliver a SIGTTOU signal, which would stop us. This is an
846 annoyance, so temporarily ignore the signal.
848 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
849 skip all this unless SIGTTOU is defined. */
850 static void
851 tcsetpgrp_without_stopping (int fd, pid_t pgid)
853 #ifdef SIGTTOU
854 sigset_t oldset;
855 block_input ();
856 block_tty_out_signal (&oldset);
857 tcsetpgrp (fd, pgid);
858 unblock_tty_out_signal (&oldset);
859 unblock_input ();
860 #endif
863 /* Split off the foreground process group to Emacs alone. When we are
864 in the foreground, but not started in our own process group,
865 redirect the tty device handle FD to point to our own process
866 group. FD must be the file descriptor of the controlling tty. */
867 static void
868 narrow_foreground_group (int fd)
870 if (inherited_pgroup && setpgid (0, 0) == 0)
871 tcsetpgrp_without_stopping (fd, getpid ());
874 /* Set the tty to our original foreground group. */
875 static void
876 widen_foreground_group (int fd)
878 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
879 tcsetpgrp_without_stopping (fd, inherited_pgroup);
882 /* Getting and setting emacs_tty structures. */
884 /* Set *TC to the parameters associated with the terminal FD,
885 or clear it if the parameters are not available.
886 Return 0 on success, -1 on failure. */
888 emacs_get_tty (int fd, struct emacs_tty *settings)
890 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
891 memset (&settings->main, 0, sizeof (settings->main));
892 #ifdef DOS_NT
893 #ifdef WINDOWSNT
894 HANDLE h = (HANDLE)_get_osfhandle (fd);
895 DWORD console_mode;
897 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
899 settings->main = console_mode;
900 return 0;
902 #endif /* WINDOWSNT */
903 return -1;
904 #else /* !DOS_NT */
905 /* We have those nifty POSIX tcmumbleattr functions. */
906 return tcgetattr (fd, &settings->main);
907 #endif
911 /* Set the parameters of the tty on FD according to the contents of
912 *SETTINGS. If FLUSHP, discard input.
913 Return 0 if all went well, and -1 (setting errno) if anything failed. */
916 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
918 /* Set the primary parameters - baud rate, character size, etcetera. */
919 #ifdef DOS_NT
920 #ifdef WINDOWSNT
921 HANDLE h = (HANDLE)_get_osfhandle (fd);
923 if (h && h != INVALID_HANDLE_VALUE)
925 DWORD new_mode;
927 /* Assume the handle is open for input. */
928 if (flushp)
929 FlushConsoleInputBuffer (h);
930 new_mode = settings->main;
931 SetConsoleMode (h, new_mode);
933 #endif /* WINDOWSNT */
934 #else /* !DOS_NT */
935 int i;
936 /* We have those nifty POSIX tcmumbleattr functions.
937 William J. Smith <wjs@wiis.wang.com> writes:
938 "POSIX 1003.1 defines tcsetattr to return success if it was
939 able to perform any of the requested actions, even if some
940 of the requested actions could not be performed.
941 We must read settings back to ensure tty setup properly.
942 AIX requires this to keep tty from hanging occasionally." */
943 /* This make sure that we don't loop indefinitely in here. */
944 for (i = 0 ; i < 10 ; i++)
945 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
947 if (errno == EINTR)
948 continue;
949 else
950 return -1;
952 else
954 struct termios new;
956 memset (&new, 0, sizeof (new));
957 /* Get the current settings, and see if they're what we asked for. */
958 tcgetattr (fd, &new);
959 /* We cannot use memcmp on the whole structure here because under
960 * aix386 the termios structure has some reserved field that may
961 * not be filled in.
963 if ( new.c_iflag == settings->main.c_iflag
964 && new.c_oflag == settings->main.c_oflag
965 && new.c_cflag == settings->main.c_cflag
966 && new.c_lflag == settings->main.c_lflag
967 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
968 break;
969 else
970 continue;
972 #endif
974 /* We have survived the tempest. */
975 return 0;
980 #ifdef F_SETOWN
981 static int old_fcntl_owner[FD_SETSIZE];
982 #endif /* F_SETOWN */
984 /* This may also be defined in stdio,
985 but if so, this does no harm,
986 and using the same name avoids wasting the other one's space. */
988 #if defined (USG)
989 unsigned char _sobuf[BUFSIZ+8];
990 #else
991 char _sobuf[BUFSIZ];
992 #endif
994 /* Initialize the terminal mode on all tty devices that are currently
995 open. */
997 void
998 init_all_sys_modes (void)
1000 struct tty_display_info *tty;
1001 for (tty = tty_list; tty; tty = tty->next)
1002 init_sys_modes (tty);
1005 /* Initialize the terminal mode on the given tty device. */
1007 void
1008 init_sys_modes (struct tty_display_info *tty_out)
1010 struct emacs_tty tty;
1011 #ifndef DOS_NT
1012 Lisp_Object terminal;
1013 #endif
1015 Vtty_erase_char = Qnil;
1017 if (noninteractive)
1018 return;
1020 if (!tty_out->output)
1021 return; /* The tty is suspended. */
1023 narrow_foreground_group (fileno (tty_out->input));
1025 if (! tty_out->old_tty)
1026 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1028 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1030 tty = *tty_out->old_tty;
1032 #if !defined (DOS_NT)
1033 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1035 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1036 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1037 #ifdef INLCR /* I'm just being cautious,
1038 since I can't check how widespread INLCR is--rms. */
1039 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1040 #endif
1041 #ifdef ISTRIP
1042 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1043 #endif
1044 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1045 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1046 #ifdef IEXTEN
1047 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1048 #endif
1049 tty.main.c_lflag |= ISIG; /* Enable signals */
1050 if (tty_out->flow_control)
1052 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1053 #ifdef IXANY
1054 tty.main.c_iflag &= ~IXANY;
1055 #endif /* IXANY */
1057 else
1058 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1059 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1060 on output */
1061 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1062 #ifdef CS8
1063 if (tty_out->meta_key)
1065 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1066 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1068 #endif
1070 XSETTERMINAL(terminal, tty_out->terminal);
1071 if (!NILP (Fcontrolling_tty_p (terminal)))
1073 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1074 /* Set up C-g for both SIGQUIT and SIGINT.
1075 We don't know which we will get, but we handle both alike
1076 so which one it really gives us does not matter. */
1077 tty.main.c_cc[VQUIT] = quit_char;
1079 else
1081 /* We normally don't get interrupt or quit signals from tty
1082 devices other than our controlling terminal; therefore,
1083 we must handle C-g as normal input. Unfortunately, this
1084 means that the interrupt and quit feature must be
1085 disabled on secondary ttys, or we would not even see the
1086 keypress.
1088 Note that even though emacsclient could have special code
1089 to pass SIGINT to Emacs, we should _not_ enable
1090 interrupt/quit keys for emacsclient frames. This means
1091 that we can't break out of loops in C code from a
1092 secondary tty frame, but we can always decide what
1093 display the C-g came from, which is more important from a
1094 usability point of view. (Consider the case when two
1095 people work together using the same Emacs instance.) */
1096 tty.main.c_cc[VINTR] = CDISABLE;
1097 tty.main.c_cc[VQUIT] = CDISABLE;
1099 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1100 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1101 #ifdef VSWTCH
1102 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1103 of C-z */
1104 #endif /* VSWTCH */
1106 #ifdef VSUSP
1107 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1108 #endif /* VSUSP */
1109 #ifdef V_DSUSP
1110 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1111 #endif /* V_DSUSP */
1112 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1113 tty.main.c_cc[VDSUSP] = CDISABLE;
1114 #endif /* VDSUSP */
1115 #ifdef VLNEXT
1116 tty.main.c_cc[VLNEXT] = CDISABLE;
1117 #endif /* VLNEXT */
1118 #ifdef VREPRINT
1119 tty.main.c_cc[VREPRINT] = CDISABLE;
1120 #endif /* VREPRINT */
1121 #ifdef VWERASE
1122 tty.main.c_cc[VWERASE] = CDISABLE;
1123 #endif /* VWERASE */
1124 #ifdef VDISCARD
1125 tty.main.c_cc[VDISCARD] = CDISABLE;
1126 #endif /* VDISCARD */
1128 if (tty_out->flow_control)
1130 #ifdef VSTART
1131 tty.main.c_cc[VSTART] = '\021';
1132 #endif /* VSTART */
1133 #ifdef VSTOP
1134 tty.main.c_cc[VSTOP] = '\023';
1135 #endif /* VSTOP */
1137 else
1139 #ifdef VSTART
1140 tty.main.c_cc[VSTART] = CDISABLE;
1141 #endif /* VSTART */
1142 #ifdef VSTOP
1143 tty.main.c_cc[VSTOP] = CDISABLE;
1144 #endif /* VSTOP */
1147 #ifdef AIX
1148 tty.main.c_cc[VSTRT] = CDISABLE;
1149 tty.main.c_cc[VSTOP] = CDISABLE;
1150 tty.main.c_cc[VSUSP] = CDISABLE;
1151 tty.main.c_cc[VDSUSP] = CDISABLE;
1152 if (tty_out->flow_control)
1154 #ifdef VSTART
1155 tty.main.c_cc[VSTART] = '\021';
1156 #endif /* VSTART */
1157 #ifdef VSTOP
1158 tty.main.c_cc[VSTOP] = '\023';
1159 #endif /* VSTOP */
1161 /* Also, PTY overloads NUL and BREAK.
1162 don't ignore break, but don't signal either, so it looks like NUL.
1163 This really serves a purpose only if running in an XTERM window
1164 or via TELNET or the like, but does no harm elsewhere. */
1165 tty.main.c_iflag &= ~IGNBRK;
1166 tty.main.c_iflag &= ~BRKINT;
1167 #endif
1168 #endif /* not DOS_NT */
1170 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1171 if (!tty_out->term_initted)
1172 internal_terminal_init ();
1173 dos_ttraw (tty_out);
1174 #endif
1176 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1178 /* This code added to insure that, if flow-control is not to be used,
1179 we have an unlocked terminal at the start. */
1181 #ifdef TCXONC
1182 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1183 #endif
1184 #ifdef TIOCSTART
1185 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1186 #endif
1188 #if !defined (DOS_NT)
1189 #ifdef TCOON
1190 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1191 #endif
1192 #endif
1194 #ifdef F_GETOWN
1195 if (interrupt_input)
1197 old_fcntl_owner[fileno (tty_out->input)] =
1198 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1199 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1200 init_sigio (fileno (tty_out->input));
1201 #ifdef HAVE_GPM
1202 if (gpm_tty == tty_out)
1204 /* Arrange for mouse events to give us SIGIO signals. */
1205 fcntl (gpm_fd, F_SETOWN, getpid ());
1206 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1207 init_sigio (gpm_fd);
1209 #endif /* HAVE_GPM */
1211 #endif /* F_GETOWN */
1213 #ifdef _IOFBF
1214 /* This symbol is defined on recent USG systems.
1215 Someone says without this call USG won't really buffer the file
1216 even with a call to setbuf. */
1217 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1218 #else
1219 setbuf (tty_out->output, (char *) _sobuf);
1220 #endif
1222 if (tty_out->terminal->set_terminal_modes_hook)
1223 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1225 if (!tty_out->term_initted)
1227 Lisp_Object tail, frame;
1228 FOR_EACH_FRAME (tail, frame)
1230 /* XXX This needs to be revised. */
1231 if (FRAME_TERMCAP_P (XFRAME (frame))
1232 && FRAME_TTY (XFRAME (frame)) == tty_out)
1233 init_frame_faces (XFRAME (frame));
1237 if (tty_out->term_initted && no_redraw_on_reenter)
1239 /* We used to call "direct_output_forward_char(0)" here,
1240 but it's not clear why, since it may not do anything anyway. */
1242 else
1244 Lisp_Object tail, frame;
1245 frame_garbaged = 1;
1246 FOR_EACH_FRAME (tail, frame)
1248 if ((FRAME_TERMCAP_P (XFRAME (frame))
1249 || FRAME_MSDOS_P (XFRAME (frame)))
1250 && FRAME_TTY (XFRAME (frame)) == tty_out)
1251 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1255 tty_out->term_initted = 1;
1258 /* Return true if safe to use tabs in output.
1259 At the time this is called, init_sys_modes has not been done yet. */
1261 bool
1262 tabs_safe_p (int fd)
1264 struct emacs_tty etty;
1266 emacs_get_tty (fd, &etty);
1267 #ifndef DOS_NT
1268 #ifdef TABDLY
1269 return ((etty.main.c_oflag & TABDLY) != TAB3);
1270 #else /* not TABDLY */
1271 return 1;
1272 #endif /* not TABDLY */
1273 #else /* DOS_NT */
1274 return 0;
1275 #endif /* DOS_NT */
1278 /* Discard echoing. */
1280 void
1281 suppress_echo_on_tty (int fd)
1283 struct emacs_tty etty;
1285 emacs_get_tty (fd, &etty);
1286 #ifdef DOS_NT
1287 /* Set raw input mode. */
1288 etty.main = 0;
1289 #else
1290 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1291 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1292 #endif /* ! WINDOWSNT */
1293 emacs_set_tty (fd, &etty, 0);
1296 /* Get terminal size from system.
1297 Store number of lines into *HEIGHTP and width into *WIDTHP.
1298 We store 0 if there's no valid information. */
1300 void
1301 get_tty_size (int fd, int *widthp, int *heightp)
1303 #if defined TIOCGWINSZ
1305 /* BSD-style. */
1306 struct winsize size;
1308 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1309 *widthp = *heightp = 0;
1310 else
1312 *widthp = size.ws_col;
1313 *heightp = size.ws_row;
1316 #elif defined TIOCGSIZE
1318 /* SunOS - style. */
1319 struct ttysize size;
1321 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1322 *widthp = *heightp = 0;
1323 else
1325 *widthp = size.ts_cols;
1326 *heightp = size.ts_lines;
1329 #elif defined WINDOWSNT
1331 CONSOLE_SCREEN_BUFFER_INFO info;
1332 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1334 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1335 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1337 else
1338 *widthp = *heightp = 0;
1340 #elif defined MSDOS
1342 *widthp = ScreenCols ();
1343 *heightp = ScreenRows ();
1345 #else /* system doesn't know size */
1347 *widthp = 0;
1348 *heightp = 0;
1350 #endif
1353 /* Set the logical window size associated with descriptor FD
1354 to HEIGHT and WIDTH. This is used mainly with ptys.
1355 Return a negative value on failure. */
1358 set_window_size (int fd, int height, int width)
1360 #ifdef TIOCSWINSZ
1362 /* BSD-style. */
1363 struct winsize size;
1364 size.ws_row = height;
1365 size.ws_col = width;
1367 return ioctl (fd, TIOCSWINSZ, &size);
1369 #else
1370 #ifdef TIOCSSIZE
1372 /* SunOS - style. */
1373 struct ttysize size;
1374 size.ts_lines = height;
1375 size.ts_cols = width;
1377 return ioctl (fd, TIOCGSIZE, &size);
1378 #else
1379 return -1;
1380 #endif /* not SunOS-style */
1381 #endif /* not BSD-style */
1386 /* Prepare all terminal devices for exiting Emacs. */
1388 void
1389 reset_all_sys_modes (void)
1391 struct tty_display_info *tty;
1392 for (tty = tty_list; tty; tty = tty->next)
1393 reset_sys_modes (tty);
1396 /* Prepare the terminal for closing it; move the cursor to the
1397 bottom of the frame, turn off interrupt-driven I/O, etc. */
1399 void
1400 reset_sys_modes (struct tty_display_info *tty_out)
1402 if (noninteractive)
1404 fflush (stdout);
1405 return;
1407 if (!tty_out->term_initted)
1408 return;
1410 if (!tty_out->output)
1411 return; /* The tty is suspended. */
1413 /* Go to and clear the last line of the terminal. */
1415 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1417 /* Code adapted from tty_clear_end_of_line. */
1418 if (tty_out->TS_clr_line)
1420 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1422 else
1423 { /* have to do it the hard way */
1424 int i;
1425 tty_turn_off_insert (tty_out);
1427 for (i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1429 fputc (' ', tty_out->output);
1433 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1434 fflush (tty_out->output);
1436 if (tty_out->terminal->reset_terminal_modes_hook)
1437 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1439 /* Avoid possible loss of output when changing terminal modes. */
1440 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1441 continue;
1443 #ifndef DOS_NT
1444 #ifdef F_SETOWN
1445 if (interrupt_input)
1447 reset_sigio (fileno (tty_out->input));
1448 fcntl (fileno (tty_out->input), F_SETOWN,
1449 old_fcntl_owner[fileno (tty_out->input)]);
1451 #endif /* F_SETOWN */
1452 fcntl (fileno (tty_out->input), F_SETFL,
1453 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1454 #endif
1456 if (tty_out->old_tty)
1457 while (emacs_set_tty (fileno (tty_out->input),
1458 tty_out->old_tty, 0) < 0 && errno == EINTR)
1461 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1462 dos_ttcooked ();
1463 #endif
1465 widen_foreground_group (fileno (tty_out->input));
1468 #ifdef HAVE_PTYS
1470 /* Set up the proper status flags for use of a pty. */
1472 void
1473 setup_pty (int fd)
1475 /* I'm told that TOICREMOTE does not mean control chars
1476 "can't be sent" but rather that they don't have
1477 input-editing or signaling effects.
1478 That should be good, because we have other ways
1479 to do those things in Emacs.
1480 However, telnet mode seems not to work on 4.2.
1481 So TIOCREMOTE is turned off now. */
1483 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1484 will hang. In particular, the "timeout" feature (which
1485 causes a read to return if there is no data available)
1486 does this. Also it is known that telnet mode will hang
1487 in such a way that Emacs must be stopped (perhaps this
1488 is the same problem).
1490 If TIOCREMOTE is turned off, then there is a bug in
1491 hp-ux which sometimes loses data. Apparently the
1492 code which blocks the master process when the internal
1493 buffer fills up does not work. Other than this,
1494 though, everything else seems to work fine.
1496 Since the latter lossage is more benign, we may as well
1497 lose that way. -- cph */
1498 #ifdef FIONBIO
1499 #if defined (UNIX98_PTYS)
1501 int on = 1;
1502 ioctl (fd, FIONBIO, &on);
1504 #endif
1505 #endif
1507 #endif /* HAVE_PTYS */
1509 void
1510 init_system_name (void)
1512 if (!build_details)
1514 /* Set system-name to nil so that the build is deterministic. */
1515 Vsystem_name = Qnil;
1516 return;
1518 char *hostname_alloc = NULL;
1519 char *hostname;
1520 #ifndef HAVE_GETHOSTNAME
1521 struct utsname uts;
1522 uname (&uts);
1523 hostname = uts.nodename;
1524 #else /* HAVE_GETHOSTNAME */
1525 char hostname_buf[256];
1526 ptrdiff_t hostname_size = sizeof hostname_buf;
1527 hostname = hostname_buf;
1529 /* Try to get the host name; if the buffer is too short, try
1530 again. Apparently, the only indication gethostname gives of
1531 whether the buffer was large enough is the presence or absence
1532 of a '\0' in the string. Eech. */
1533 for (;;)
1535 gethostname (hostname, hostname_size - 1);
1536 hostname[hostname_size - 1] = '\0';
1538 /* Was the buffer large enough for the '\0'? */
1539 if (strlen (hostname) < hostname_size - 1)
1540 break;
1542 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1543 min (PTRDIFF_MAX, SIZE_MAX), 1);
1545 #endif /* HAVE_GETHOSTNAME */
1546 char *p;
1547 for (p = hostname; *p; p++)
1548 if (*p == ' ' || *p == '\t')
1549 *p = '-';
1550 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1551 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1552 Vsystem_name = build_string (hostname);
1553 xfree (hostname_alloc);
1556 sigset_t empty_mask;
1558 static struct sigaction process_fatal_action;
1560 static int
1561 emacs_sigaction_flags (void)
1563 #ifdef SA_RESTART
1564 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1565 'select') to reset their timeout on some platforms (e.g.,
1566 HP-UX 11), which is not what we want. Also, when Emacs is
1567 interactive, we don't want SA_RESTART because we need to poll
1568 for pending input so we need long-running syscalls to be interrupted
1569 after a signal that sets pending_signals.
1571 Non-interactive keyboard input goes through stdio, where we
1572 always want restartable system calls. */
1573 if (noninteractive)
1574 return SA_RESTART;
1575 #endif
1576 return 0;
1579 /* Store into *ACTION a signal action suitable for Emacs, with handler
1580 HANDLER. */
1581 void
1582 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1584 sigemptyset (&action->sa_mask);
1586 /* When handling a signal, block nonfatal system signals that are caught
1587 by Emacs. This makes race conditions less likely. */
1588 sigaddset (&action->sa_mask, SIGALRM);
1589 #ifdef SIGCHLD
1590 sigaddset (&action->sa_mask, SIGCHLD);
1591 #endif
1592 #ifdef SIGDANGER
1593 sigaddset (&action->sa_mask, SIGDANGER);
1594 #endif
1595 #ifdef PROFILER_CPU_SUPPORT
1596 sigaddset (&action->sa_mask, SIGPROF);
1597 #endif
1598 #ifdef SIGWINCH
1599 sigaddset (&action->sa_mask, SIGWINCH);
1600 #endif
1601 if (! noninteractive)
1603 sigaddset (&action->sa_mask, SIGINT);
1604 sigaddset (&action->sa_mask, SIGQUIT);
1605 #ifdef USABLE_SIGIO
1606 sigaddset (&action->sa_mask, SIGIO);
1607 #endif
1610 action->sa_handler = handler;
1611 action->sa_flags = emacs_sigaction_flags ();
1614 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1615 static pthread_t main_thread;
1616 #endif
1618 /* SIG has arrived at the current process. Deliver it to the main
1619 thread, which should handle it with HANDLER.
1621 If we are on the main thread, handle the signal SIG with HANDLER.
1622 Otherwise, redirect the signal to the main thread, blocking it from
1623 this thread. POSIX says any thread can receive a signal that is
1624 associated with a process, process group, or asynchronous event.
1625 On GNU/Linux that is not true, but for other systems (FreeBSD at
1626 least) it is. */
1627 void
1628 deliver_process_signal (int sig, signal_handler_t handler)
1630 /* Preserve errno, to avoid race conditions with signal handlers that
1631 might change errno. Races can occur even in single-threaded hosts. */
1632 int old_errno = errno;
1634 bool on_main_thread = true;
1635 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1636 if (! pthread_equal (pthread_self (), main_thread))
1638 sigset_t blocked;
1639 sigemptyset (&blocked);
1640 sigaddset (&blocked, sig);
1641 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1642 pthread_kill (main_thread, sig);
1643 on_main_thread = false;
1645 #endif
1646 if (on_main_thread)
1647 handler (sig);
1649 errno = old_errno;
1652 /* Static location to save a fatal backtrace in a thread.
1653 FIXME: If two subsidiary threads fail simultaneously, the resulting
1654 backtrace may be garbage. */
1655 enum { BACKTRACE_LIMIT_MAX = 500 };
1656 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1657 static int thread_backtrace_npointers;
1659 /* SIG has arrived at the current thread.
1660 If we are on the main thread, handle the signal SIG with HANDLER.
1661 Otherwise, this is a fatal error in the handling thread. */
1662 static void
1663 deliver_thread_signal (int sig, signal_handler_t handler)
1665 int old_errno = errno;
1667 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1668 if (! pthread_equal (pthread_self (), main_thread))
1670 thread_backtrace_npointers
1671 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1672 sigaction (sig, &process_fatal_action, 0);
1673 pthread_kill (main_thread, sig);
1675 /* Avoid further damage while the main thread is exiting. */
1676 while (1)
1677 sigsuspend (&empty_mask);
1679 #endif
1681 handler (sig);
1682 errno = old_errno;
1685 #if !HAVE_DECL_SYS_SIGLIST
1686 # undef sys_siglist
1687 # ifdef _sys_siglist
1688 # define sys_siglist _sys_siglist
1689 # elif HAVE_DECL___SYS_SIGLIST
1690 # define sys_siglist __sys_siglist
1691 # else
1692 # define sys_siglist my_sys_siglist
1693 static char const *sys_siglist[NSIG];
1694 # endif
1695 #endif
1697 #ifdef _sys_nsig
1698 # define sys_siglist_entries _sys_nsig
1699 #else
1700 # define sys_siglist_entries NSIG
1701 #endif
1703 /* Handle bus errors, invalid instruction, etc. */
1704 static void
1705 handle_fatal_signal (int sig)
1707 terminate_due_to_signal (sig, 40);
1710 static void
1711 deliver_fatal_signal (int sig)
1713 deliver_process_signal (sig, handle_fatal_signal);
1716 static void
1717 deliver_fatal_thread_signal (int sig)
1719 deliver_thread_signal (sig, handle_fatal_signal);
1722 static _Noreturn void
1723 handle_arith_signal (int sig)
1725 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1726 xsignal0 (Qarith_error);
1729 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1731 /* Alternate stack used by SIGSEGV handler below. */
1733 static unsigned char sigsegv_stack[SIGSTKSZ];
1736 /* Return true if SIGINFO indicates a stack overflow. */
1738 static bool
1739 stack_overflow (siginfo_t *siginfo)
1741 if (!attempt_stack_overflow_recovery)
1742 return false;
1744 /* In theory, a more-accurate heuristic can be obtained by using
1745 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1746 and pthread_attr_getguardsize to find the location and size of the
1747 guard area. In practice, though, these functions are so hard to
1748 use reliably that they're not worth bothering with. E.g., see:
1749 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1750 Other operating systems also have problems, e.g., Solaris's
1751 stack_violation function is tailor-made for this problem, but it
1752 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1754 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1755 candidate here. */
1757 if (!siginfo)
1758 return false;
1760 /* The faulting address. */
1761 char *addr = siginfo->si_addr;
1762 if (!addr)
1763 return false;
1765 /* The known top and bottom of the stack. The actual stack may
1766 extend a bit beyond these boundaries. */
1767 char *bot = stack_bottom;
1768 char *top = near_C_stack_top ();
1770 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1771 of the known stack divided by the size of the guard area past the
1772 end of the stack top. The heuristic is that a bad address is
1773 considered to be a stack overflow if it occurs within
1774 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1775 stack. This heuristic is not exactly correct but it's good
1776 enough in practice. */
1777 enum { LG_STACK_HEURISTIC = 8 };
1779 if (bot < top)
1780 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1781 else
1782 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1786 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1788 static void
1789 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1791 /* Hard GC error may lead to stack overflow caused by
1792 too nested calls to mark_object. No way to survive. */
1793 bool fatal = gc_in_progress;
1795 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1796 if (!fatal && !pthread_equal (pthread_self (), main_thread))
1797 fatal = true;
1798 #endif
1800 if (!fatal && stack_overflow (siginfo))
1801 siglongjmp (return_to_command_loop, 1);
1803 /* Otherwise we can't do anything with this. */
1804 deliver_fatal_thread_signal (sig);
1807 /* Return true if we have successfully set up SIGSEGV handler on alternate
1808 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1810 static bool
1811 init_sigsegv (void)
1813 struct sigaction sa;
1814 stack_t ss;
1816 ss.ss_sp = sigsegv_stack;
1817 ss.ss_size = sizeof (sigsegv_stack);
1818 ss.ss_flags = 0;
1819 if (sigaltstack (&ss, NULL) < 0)
1820 return 0;
1822 sigfillset (&sa.sa_mask);
1823 sa.sa_sigaction = handle_sigsegv;
1824 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1825 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1828 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1830 static bool
1831 init_sigsegv (void)
1833 return 0;
1836 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1838 static void
1839 deliver_arith_signal (int sig)
1841 deliver_thread_signal (sig, handle_arith_signal);
1844 #ifdef SIGDANGER
1846 /* Handler for SIGDANGER. */
1847 static void
1848 handle_danger_signal (int sig)
1850 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1852 /* It might be unsafe to call do_auto_save now. */
1853 force_auto_save_soon ();
1856 static void
1857 deliver_danger_signal (int sig)
1859 deliver_process_signal (sig, handle_danger_signal);
1861 #endif
1863 /* Treat SIG as a terminating signal, unless it is already ignored and
1864 we are in --batch mode. Among other things, this makes nohup work. */
1865 static void
1866 maybe_fatal_sig (int sig)
1868 bool catch_sig = !noninteractive;
1869 if (!catch_sig)
1871 struct sigaction old_action;
1872 sigaction (sig, 0, &old_action);
1873 catch_sig = old_action.sa_handler != SIG_IGN;
1875 if (catch_sig)
1876 sigaction (sig, &process_fatal_action, 0);
1879 void
1880 init_signals (bool dumping)
1882 struct sigaction thread_fatal_action;
1883 struct sigaction action;
1885 sigemptyset (&empty_mask);
1887 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1888 main_thread = pthread_self ();
1889 #endif
1891 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1892 if (! initialized)
1894 sys_siglist[SIGABRT] = "Aborted";
1895 # ifdef SIGAIO
1896 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1897 # endif
1898 sys_siglist[SIGALRM] = "Alarm clock";
1899 # ifdef SIGBUS
1900 sys_siglist[SIGBUS] = "Bus error";
1901 # endif
1902 # ifdef SIGCHLD
1903 sys_siglist[SIGCHLD] = "Child status changed";
1904 # endif
1905 # ifdef SIGCONT
1906 sys_siglist[SIGCONT] = "Continued";
1907 # endif
1908 # ifdef SIGDANGER
1909 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1910 # endif
1911 # ifdef SIGDGNOTIFY
1912 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1913 # endif
1914 # ifdef SIGEMT
1915 sys_siglist[SIGEMT] = "Emulation trap";
1916 # endif
1917 sys_siglist[SIGFPE] = "Arithmetic exception";
1918 # ifdef SIGFREEZE
1919 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1920 # endif
1921 # ifdef SIGGRANT
1922 sys_siglist[SIGGRANT] = "Monitor mode granted";
1923 # endif
1924 sys_siglist[SIGHUP] = "Hangup";
1925 sys_siglist[SIGILL] = "Illegal instruction";
1926 sys_siglist[SIGINT] = "Interrupt";
1927 # ifdef SIGIO
1928 sys_siglist[SIGIO] = "I/O possible";
1929 # endif
1930 # ifdef SIGIOINT
1931 sys_siglist[SIGIOINT] = "I/O intervention required";
1932 # endif
1933 # ifdef SIGIOT
1934 sys_siglist[SIGIOT] = "IOT trap";
1935 # endif
1936 sys_siglist[SIGKILL] = "Killed";
1937 # ifdef SIGLOST
1938 sys_siglist[SIGLOST] = "Resource lost";
1939 # endif
1940 # ifdef SIGLWP
1941 sys_siglist[SIGLWP] = "SIGLWP";
1942 # endif
1943 # ifdef SIGMSG
1944 sys_siglist[SIGMSG] = "Monitor mode data available";
1945 # endif
1946 # ifdef SIGPHONE
1947 sys_siglist[SIGWIND] = "SIGPHONE";
1948 # endif
1949 sys_siglist[SIGPIPE] = "Broken pipe";
1950 # ifdef SIGPOLL
1951 sys_siglist[SIGPOLL] = "Pollable event occurred";
1952 # endif
1953 # ifdef SIGPROF
1954 sys_siglist[SIGPROF] = "Profiling timer expired";
1955 # endif
1956 # ifdef SIGPTY
1957 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1958 # endif
1959 # ifdef SIGPWR
1960 sys_siglist[SIGPWR] = "Power-fail restart";
1961 # endif
1962 sys_siglist[SIGQUIT] = "Quit";
1963 # ifdef SIGRETRACT
1964 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1965 # endif
1966 # ifdef SIGSAK
1967 sys_siglist[SIGSAK] = "Secure attention";
1968 # endif
1969 sys_siglist[SIGSEGV] = "Segmentation violation";
1970 # ifdef SIGSOUND
1971 sys_siglist[SIGSOUND] = "Sound completed";
1972 # endif
1973 # ifdef SIGSTOP
1974 sys_siglist[SIGSTOP] = "Stopped (signal)";
1975 # endif
1976 # ifdef SIGSTP
1977 sys_siglist[SIGSTP] = "Stopped (user)";
1978 # endif
1979 # ifdef SIGSYS
1980 sys_siglist[SIGSYS] = "Bad argument to system call";
1981 # endif
1982 sys_siglist[SIGTERM] = "Terminated";
1983 # ifdef SIGTHAW
1984 sys_siglist[SIGTHAW] = "SIGTHAW";
1985 # endif
1986 # ifdef SIGTRAP
1987 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1988 # endif
1989 # ifdef SIGTSTP
1990 sys_siglist[SIGTSTP] = "Stopped (user)";
1991 # endif
1992 # ifdef SIGTTIN
1993 sys_siglist[SIGTTIN] = "Stopped (tty input)";
1994 # endif
1995 # ifdef SIGTTOU
1996 sys_siglist[SIGTTOU] = "Stopped (tty output)";
1997 # endif
1998 # ifdef SIGURG
1999 sys_siglist[SIGURG] = "Urgent I/O condition";
2000 # endif
2001 # ifdef SIGUSR1
2002 sys_siglist[SIGUSR1] = "User defined signal 1";
2003 # endif
2004 # ifdef SIGUSR2
2005 sys_siglist[SIGUSR2] = "User defined signal 2";
2006 # endif
2007 # ifdef SIGVTALRM
2008 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2009 # endif
2010 # ifdef SIGWAITING
2011 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2012 # endif
2013 # ifdef SIGWINCH
2014 sys_siglist[SIGWINCH] = "Window size changed";
2015 # endif
2016 # ifdef SIGWIND
2017 sys_siglist[SIGWIND] = "SIGWIND";
2018 # endif
2019 # ifdef SIGXCPU
2020 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2021 # endif
2022 # ifdef SIGXFSZ
2023 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2024 # endif
2026 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2028 /* Don't alter signal handlers if dumping. On some machines,
2029 changing signal handlers sets static data that would make signals
2030 fail to work right when the dumped Emacs is run. */
2031 if (dumping)
2032 return;
2034 sigfillset (&process_fatal_action.sa_mask);
2035 process_fatal_action.sa_handler = deliver_fatal_signal;
2036 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2038 sigfillset (&thread_fatal_action.sa_mask);
2039 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2040 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2042 /* SIGINT may need special treatment on MS-Windows. See
2043 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2044 Please update the doc of kill-emacs, kill-emacs-hook, and
2045 NEWS if you change this. */
2047 maybe_fatal_sig (SIGHUP);
2048 maybe_fatal_sig (SIGINT);
2049 maybe_fatal_sig (SIGTERM);
2051 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2052 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2053 to behave more like typical batch applications do. */
2054 if (! noninteractive)
2055 signal (SIGPIPE, SIG_IGN);
2057 sigaction (SIGQUIT, &process_fatal_action, 0);
2058 sigaction (SIGILL, &thread_fatal_action, 0);
2059 sigaction (SIGTRAP, &thread_fatal_action, 0);
2061 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2062 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2063 interpreter's floating point operations, so treat SIGFPE as an
2064 arith-error if it arises in the main thread. */
2065 if (IEEE_FLOATING_POINT)
2066 sigaction (SIGFPE, &thread_fatal_action, 0);
2067 else
2069 emacs_sigaction_init (&action, deliver_arith_signal);
2070 sigaction (SIGFPE, &action, 0);
2073 #ifdef SIGUSR1
2074 add_user_signal (SIGUSR1, "sigusr1");
2075 #endif
2076 #ifdef SIGUSR2
2077 add_user_signal (SIGUSR2, "sigusr2");
2078 #endif
2079 sigaction (SIGABRT, &thread_fatal_action, 0);
2080 #ifdef SIGPRE
2081 sigaction (SIGPRE, &thread_fatal_action, 0);
2082 #endif
2083 #ifdef SIGORE
2084 sigaction (SIGORE, &thread_fatal_action, 0);
2085 #endif
2086 #ifdef SIGUME
2087 sigaction (SIGUME, &thread_fatal_action, 0);
2088 #endif
2089 #ifdef SIGDLK
2090 sigaction (SIGDLK, &process_fatal_action, 0);
2091 #endif
2092 #ifdef SIGCPULIM
2093 sigaction (SIGCPULIM, &process_fatal_action, 0);
2094 #endif
2095 #ifdef SIGIOT
2096 sigaction (SIGIOT, &thread_fatal_action, 0);
2097 #endif
2098 #ifdef SIGEMT
2099 sigaction (SIGEMT, &thread_fatal_action, 0);
2100 #endif
2101 #ifdef SIGBUS
2102 sigaction (SIGBUS, &thread_fatal_action, 0);
2103 #endif
2104 if (!init_sigsegv ())
2105 sigaction (SIGSEGV, &thread_fatal_action, 0);
2106 #ifdef SIGSYS
2107 sigaction (SIGSYS, &thread_fatal_action, 0);
2108 #endif
2109 sigaction (SIGTERM, &process_fatal_action, 0);
2110 #ifdef SIGPROF
2111 signal (SIGPROF, SIG_IGN);
2112 #endif
2113 #ifdef SIGVTALRM
2114 sigaction (SIGVTALRM, &process_fatal_action, 0);
2115 #endif
2116 #ifdef SIGXCPU
2117 sigaction (SIGXCPU, &process_fatal_action, 0);
2118 #endif
2119 #ifdef SIGXFSZ
2120 sigaction (SIGXFSZ, &process_fatal_action, 0);
2121 #endif
2123 #ifdef SIGDANGER
2124 /* This just means available memory is getting low. */
2125 emacs_sigaction_init (&action, deliver_danger_signal);
2126 sigaction (SIGDANGER, &action, 0);
2127 #endif
2129 /* AIX-specific signals. */
2130 #ifdef SIGGRANT
2131 sigaction (SIGGRANT, &process_fatal_action, 0);
2132 #endif
2133 #ifdef SIGMIGRATE
2134 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2135 #endif
2136 #ifdef SIGMSG
2137 sigaction (SIGMSG, &process_fatal_action, 0);
2138 #endif
2139 #ifdef SIGRETRACT
2140 sigaction (SIGRETRACT, &process_fatal_action, 0);
2141 #endif
2142 #ifdef SIGSAK
2143 sigaction (SIGSAK, &process_fatal_action, 0);
2144 #endif
2145 #ifdef SIGSOUND
2146 sigaction (SIGSOUND, &process_fatal_action, 0);
2147 #endif
2148 #ifdef SIGTALRM
2149 sigaction (SIGTALRM, &thread_fatal_action, 0);
2150 #endif
2153 #ifndef HAVE_RANDOM
2154 #ifdef random
2155 #define HAVE_RANDOM
2156 #endif
2157 #endif
2159 /* Figure out how many bits the system's random number generator uses.
2160 `random' and `lrand48' are assumed to return 31 usable bits.
2161 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2162 so we'll shift it and treat it like the 15-bit USG `rand'. */
2164 #ifndef RAND_BITS
2165 # ifdef HAVE_RANDOM
2166 # define RAND_BITS 31
2167 # else /* !HAVE_RANDOM */
2168 # ifdef HAVE_LRAND48
2169 # define RAND_BITS 31
2170 # define random lrand48
2171 # else /* !HAVE_LRAND48 */
2172 # define RAND_BITS 15
2173 # if RAND_MAX == 32767
2174 # define random rand
2175 # else /* RAND_MAX != 32767 */
2176 # if RAND_MAX == 2147483647
2177 # define random() (rand () >> 16)
2178 # else /* RAND_MAX != 2147483647 */
2179 # ifdef USG
2180 # define random rand
2181 # else
2182 # define random() (rand () >> 16)
2183 # endif /* !USG */
2184 # endif /* RAND_MAX != 2147483647 */
2185 # endif /* RAND_MAX != 32767 */
2186 # endif /* !HAVE_LRAND48 */
2187 # endif /* !HAVE_RANDOM */
2188 #endif /* !RAND_BITS */
2190 #ifdef HAVE_RANDOM
2191 typedef unsigned int random_seed;
2192 static void set_random_seed (random_seed arg) { srandom (arg); }
2193 #elif defined HAVE_LRAND48
2194 /* Although srand48 uses a long seed, this is unsigned long to avoid
2195 undefined behavior on signed integer overflow in init_random. */
2196 typedef unsigned long int random_seed;
2197 static void set_random_seed (random_seed arg) { srand48 (arg); }
2198 #else
2199 typedef unsigned int random_seed;
2200 static void set_random_seed (random_seed arg) { srand (arg); }
2201 #endif
2203 void
2204 seed_random (void *seed, ptrdiff_t seed_size)
2206 random_seed arg = 0;
2207 unsigned char *argp = (unsigned char *) &arg;
2208 unsigned char *seedp = seed;
2209 for (ptrdiff_t i = 0; i < seed_size; i++)
2210 argp[i % sizeof arg] ^= seedp[i];
2211 set_random_seed (arg);
2214 void
2215 init_random (void)
2217 random_seed v;
2218 bool success = false;
2220 /* First, try seeding the PRNG from the operating system's entropy
2221 source. This approach is both fast and secure. */
2222 #ifdef WINDOWSNT
2223 success = w32_init_random (&v, sizeof v) == 0;
2224 #else
2225 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2226 if (0 <= fd)
2228 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2229 close (fd);
2231 #endif
2233 /* If that didn't work, try using GnuTLS, which is secure, but on
2234 some systems, can be somewhat slow. */
2235 if (!success)
2236 success = EQ (emacs_gnutls_global_init (), Qt)
2237 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2239 /* If _that_ didn't work, just use the current time value and PID.
2240 It's at least better than XKCD 221. */
2241 if (!success)
2243 struct timespec t = current_timespec ();
2244 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2247 set_random_seed (v);
2251 * Return a nonnegative random integer out of whatever we've got.
2252 * It contains enough bits to make a random (signed) Emacs fixnum.
2253 * This suffices even for a 64-bit architecture with a 15-bit rand.
2255 EMACS_INT
2256 get_random (void)
2258 EMACS_UINT val = 0;
2259 int i;
2260 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2261 val = (random () ^ (val << RAND_BITS)
2262 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2263 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2264 return val & INTMASK;
2267 #ifndef HAVE_SNPRINTF
2268 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2270 snprintf (char *buf, size_t bufsize, char const *format, ...)
2272 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2273 ptrdiff_t nbytes = size - 1;
2274 va_list ap;
2276 if (size)
2278 va_start (ap, format);
2279 nbytes = doprnt (buf, size, format, 0, ap);
2280 va_end (ap);
2283 if (nbytes == size - 1)
2285 /* Calculate the length of the string that would have been created
2286 had the buffer been large enough. */
2287 char stackbuf[4000];
2288 char *b = stackbuf;
2289 ptrdiff_t bsize = sizeof stackbuf;
2290 va_start (ap, format);
2291 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2292 va_end (ap);
2293 if (b != stackbuf)
2294 xfree (b);
2297 if (INT_MAX < nbytes)
2299 #ifdef EOVERFLOW
2300 errno = EOVERFLOW;
2301 #else
2302 errno = EDOM;
2303 #endif
2304 return -1;
2306 return nbytes;
2308 #endif
2310 /* If a backtrace is available, output the top lines of it to stderr.
2311 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2312 This function may be called from a signal handler, so it should
2313 not invoke async-unsafe functions like malloc.
2315 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2316 but do not output anything. This avoids some problems that can
2317 otherwise occur if the malloc arena is corrupted before 'backtrace'
2318 is called, since 'backtrace' may call malloc if the tables are not
2319 initialized.
2321 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2322 fatal error has occurred in some other thread; generate a thread
2323 backtrace instead, ignoring BACKTRACE_LIMIT. */
2324 void
2325 emacs_backtrace (int backtrace_limit)
2327 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2328 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2329 void *buffer;
2330 int npointers;
2332 if (thread_backtrace_npointers)
2334 buffer = thread_backtrace_buffer;
2335 npointers = thread_backtrace_npointers;
2337 else
2339 buffer = main_backtrace_buffer;
2341 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2342 if (bounded_limit < 0)
2344 backtrace (buffer, 1);
2345 return;
2348 npointers = backtrace (buffer, bounded_limit + 1);
2351 if (npointers)
2353 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2354 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2355 if (bounded_limit < npointers)
2356 emacs_write (STDERR_FILENO, "...\n", 4);
2360 #ifndef HAVE_NTGUI
2361 void
2362 emacs_abort (void)
2364 terminate_due_to_signal (SIGABRT, 40);
2366 #endif
2368 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2369 Use binary I/O on systems that care about text vs binary I/O.
2370 Arrange for subprograms to not inherit the file descriptor.
2371 Prefer a method that is multithread-safe, if available.
2372 Do not fail merely because the open was interrupted by a signal.
2373 Allow the user to quit. */
2376 emacs_open (const char *file, int oflags, int mode)
2378 int fd;
2379 if (! (oflags & O_TEXT))
2380 oflags |= O_BINARY;
2381 oflags |= O_CLOEXEC;
2382 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2383 QUIT;
2384 if (! O_CLOEXEC && 0 <= fd)
2385 fcntl (fd, F_SETFD, FD_CLOEXEC);
2386 return fd;
2389 /* Open FILE as a stream for Emacs use, with mode MODE.
2390 Act like emacs_open with respect to threads, signals, and quits. */
2392 FILE *
2393 emacs_fopen (char const *file, char const *mode)
2395 int fd, omode, oflags;
2396 int bflag = 0;
2397 char const *m = mode;
2399 switch (*m++)
2401 case 'r': omode = O_RDONLY; oflags = 0; break;
2402 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2403 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2404 default: emacs_abort ();
2407 while (*m)
2408 switch (*m++)
2410 case '+': omode = O_RDWR; break;
2411 case 't': bflag = O_TEXT; break;
2412 default: /* Ignore. */ break;
2415 fd = emacs_open (file, omode | oflags | bflag, 0666);
2416 return fd < 0 ? 0 : fdopen (fd, mode);
2419 /* Create a pipe for Emacs use. */
2422 emacs_pipe (int fd[2])
2424 #ifdef MSDOS
2425 return pipe (fd);
2426 #else /* !MSDOS */
2427 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2428 if (! O_CLOEXEC && result == 0)
2430 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2431 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2433 return result;
2434 #endif /* !MSDOS */
2437 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2438 For the background behind this mess, please see Austin Group defect 529
2439 <http://austingroupbugs.net/view.php?id=529>. */
2441 #ifndef POSIX_CLOSE_RESTART
2442 # define POSIX_CLOSE_RESTART 1
2443 static int
2444 posix_close (int fd, int flag)
2446 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2447 eassert (flag == POSIX_CLOSE_RESTART);
2449 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2450 on a system that does not define POSIX_CLOSE_RESTART.
2452 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2453 closed, and retrying the close could inadvertently close a file
2454 descriptor allocated by some other thread. In other systems
2455 (e.g., HP/UX) FD is not closed. And in still other systems
2456 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2457 multithreaded program there can be no way to tell.
2459 So, in this case, pretend that the close succeeded. This works
2460 well on systems like GNU/Linux that close FD. Although it may
2461 leak a file descriptor on other systems, the leak is unlikely and
2462 it's better to leak than to close a random victim. */
2463 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2465 #endif
2467 /* Close FD, retrying if interrupted. If successful, return 0;
2468 otherwise, return -1 and set errno to a non-EINTR value. Consider
2469 an EINPROGRESS error to be successful, as that's merely a signal
2470 arriving. FD is always closed when this function returns, even
2471 when it returns -1.
2473 Do not call this function if FD is nonnegative and might already be closed,
2474 as that might close an innocent victim opened by some other thread. */
2477 emacs_close (int fd)
2479 while (1)
2481 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2482 if (r == 0)
2483 return r;
2484 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2486 eassert (errno != EBADF || fd < 0);
2487 return errno == EINPROGRESS ? 0 : r;
2492 /* Maximum number of bytes to read or write in a single system call.
2493 This works around a serious bug in Linux kernels before 2.6.16; see
2494 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2495 It's likely to work around similar bugs in other operating systems, so do it
2496 on all platforms. Round INT_MAX down to a page size, with the conservative
2497 assumption that page sizes are at most 2**18 bytes (any kernel with a
2498 page size larger than that shouldn't have the bug). */
2499 #ifndef MAX_RW_COUNT
2500 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2501 #endif
2503 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2504 Return the number of bytes read, which might be less than NBYTE.
2505 On error, set errno and return -1. */
2506 ptrdiff_t
2507 emacs_read (int fildes, void *buf, ptrdiff_t nbyte)
2509 ssize_t rtnval;
2511 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2512 passes a size that large to emacs_read. */
2514 while ((rtnval = read (fildes, buf, nbyte)) == -1
2515 && (errno == EINTR))
2516 QUIT;
2517 return (rtnval);
2520 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2521 or if a partial write occurs. If interrupted, process pending
2522 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2523 errno if this is less than NBYTE. */
2524 static ptrdiff_t
2525 emacs_full_write (int fildes, char const *buf, ptrdiff_t nbyte,
2526 bool process_signals)
2528 ptrdiff_t bytes_written = 0;
2530 while (nbyte > 0)
2532 ssize_t n = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
2534 if (n < 0)
2536 if (errno == EINTR)
2538 /* I originally used `QUIT' but that might cause files to
2539 be truncated if you hit C-g in the middle of it. --Stef */
2540 if (process_signals && pending_signals)
2541 process_pending_signals ();
2542 continue;
2544 else
2545 break;
2548 buf += n;
2549 nbyte -= n;
2550 bytes_written += n;
2553 return bytes_written;
2556 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2557 interrupted or if a partial write occurs. Return the number of
2558 bytes written, setting errno if this is less than NBYTE. */
2559 ptrdiff_t
2560 emacs_write (int fildes, void const *buf, ptrdiff_t nbyte)
2562 return emacs_full_write (fildes, buf, nbyte, 0);
2565 /* Like emacs_write, but also process pending signals if interrupted. */
2566 ptrdiff_t
2567 emacs_write_sig (int fildes, void const *buf, ptrdiff_t nbyte)
2569 return emacs_full_write (fildes, buf, nbyte, 1);
2572 /* Write a diagnostic to standard error that contains MESSAGE and a
2573 string derived from errno. Preserve errno. Do not buffer stderr.
2574 Do not process pending signals if interrupted. */
2575 void
2576 emacs_perror (char const *message)
2578 int err = errno;
2579 char const *error_string = emacs_strerror (err);
2580 char const *command = (initial_argv && initial_argv[0]
2581 ? initial_argv[0] : "emacs");
2582 /* Write it out all at once, if it's short; this is less likely to
2583 be interleaved with other output. */
2584 char buf[BUFSIZ];
2585 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2586 command, message, error_string);
2587 if (0 <= nbytes && nbytes < BUFSIZ)
2588 emacs_write (STDERR_FILENO, buf, nbytes);
2589 else
2591 emacs_write (STDERR_FILENO, command, strlen (command));
2592 emacs_write (STDERR_FILENO, ": ", 2);
2593 emacs_write (STDERR_FILENO, message, strlen (message));
2594 emacs_write (STDERR_FILENO, ": ", 2);
2595 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2596 emacs_write (STDERR_FILENO, "\n", 1);
2598 errno = err;
2601 /* Return a struct timeval that is roughly equivalent to T.
2602 Use the least timeval not less than T.
2603 Return an extremal value if the result would overflow. */
2604 struct timeval
2605 make_timeval (struct timespec t)
2607 struct timeval tv;
2608 tv.tv_sec = t.tv_sec;
2609 tv.tv_usec = t.tv_nsec / 1000;
2611 if (t.tv_nsec % 1000 != 0)
2613 if (tv.tv_usec < 999999)
2614 tv.tv_usec++;
2615 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2617 tv.tv_sec++;
2618 tv.tv_usec = 0;
2622 return tv;
2625 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2626 ATIME and MTIME, respectively.
2627 FD must be either negative -- in which case it is ignored --
2628 or a file descriptor that is open on FILE.
2629 If FD is nonnegative, then FILE can be NULL. */
2631 set_file_times (int fd, const char *filename,
2632 struct timespec atime, struct timespec mtime)
2634 struct timespec timespec[2];
2635 timespec[0] = atime;
2636 timespec[1] = mtime;
2637 return fdutimens (fd, filename, timespec);
2640 /* Like strsignal, except async-signal-safe, and this function typically
2641 returns a string in the C locale rather than the current locale. */
2642 char const *
2643 safe_strsignal (int code)
2645 char const *signame = 0;
2647 if (0 <= code && code < sys_siglist_entries)
2648 signame = sys_siglist[code];
2649 if (! signame)
2650 signame = "Unknown signal";
2652 return signame;
2655 #ifndef DOS_NT
2656 /* For make-serial-process */
2658 serial_open (Lisp_Object port)
2660 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2661 if (fd < 0)
2662 report_file_error ("Opening serial port", port);
2663 #ifdef TIOCEXCL
2664 ioctl (fd, TIOCEXCL, (char *) 0);
2665 #endif
2667 return fd;
2670 #if !defined (HAVE_CFMAKERAW)
2671 /* Workaround for targets which are missing cfmakeraw. */
2672 /* Pasted from man page. */
2673 static void
2674 cfmakeraw (struct termios *termios_p)
2676 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2677 termios_p->c_oflag &= ~OPOST;
2678 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2679 termios_p->c_cflag &= ~(CSIZE|PARENB);
2680 termios_p->c_cflag |= CS8;
2682 #endif /* !defined (HAVE_CFMAKERAW */
2684 #if !defined (HAVE_CFSETSPEED)
2685 /* Workaround for targets which are missing cfsetspeed. */
2686 static int
2687 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2689 return (cfsetispeed (termios_p, vitesse)
2690 + cfsetospeed (termios_p, vitesse));
2692 #endif
2694 /* For serial-process-configure */
2695 void
2696 serial_configure (struct Lisp_Process *p,
2697 Lisp_Object contact)
2699 Lisp_Object childp2 = Qnil;
2700 Lisp_Object tem = Qnil;
2701 struct termios attr;
2702 int err;
2703 char summary[4] = "???"; /* This usually becomes "8N1". */
2705 childp2 = Fcopy_sequence (p->childp);
2707 /* Read port attributes and prepare default configuration. */
2708 err = tcgetattr (p->outfd, &attr);
2709 if (err != 0)
2710 report_file_error ("Failed tcgetattr", Qnil);
2711 cfmakeraw (&attr);
2712 #if defined (CLOCAL)
2713 attr.c_cflag |= CLOCAL;
2714 #endif
2715 #if defined (CREAD)
2716 attr.c_cflag |= CREAD;
2717 #endif
2719 /* Configure speed. */
2720 if (!NILP (Fplist_member (contact, QCspeed)))
2721 tem = Fplist_get (contact, QCspeed);
2722 else
2723 tem = Fplist_get (p->childp, QCspeed);
2724 CHECK_NUMBER (tem);
2725 err = cfsetspeed (&attr, XINT (tem));
2726 if (err != 0)
2727 report_file_error ("Failed cfsetspeed", tem);
2728 childp2 = Fplist_put (childp2, QCspeed, tem);
2730 /* Configure bytesize. */
2731 if (!NILP (Fplist_member (contact, QCbytesize)))
2732 tem = Fplist_get (contact, QCbytesize);
2733 else
2734 tem = Fplist_get (p->childp, QCbytesize);
2735 if (NILP (tem))
2736 tem = make_number (8);
2737 CHECK_NUMBER (tem);
2738 if (XINT (tem) != 7 && XINT (tem) != 8)
2739 error (":bytesize must be nil (8), 7, or 8");
2740 summary[0] = XINT (tem) + '0';
2741 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2742 attr.c_cflag &= ~CSIZE;
2743 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2744 #else
2745 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2746 if (XINT (tem) != 8)
2747 error ("Bytesize cannot be changed");
2748 #endif
2749 childp2 = Fplist_put (childp2, QCbytesize, tem);
2751 /* Configure parity. */
2752 if (!NILP (Fplist_member (contact, QCparity)))
2753 tem = Fplist_get (contact, QCparity);
2754 else
2755 tem = Fplist_get (p->childp, QCparity);
2756 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2757 error (":parity must be nil (no parity), `even', or `odd'");
2758 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2759 attr.c_cflag &= ~(PARENB | PARODD);
2760 attr.c_iflag &= ~(IGNPAR | INPCK);
2761 if (NILP (tem))
2763 summary[1] = 'N';
2765 else if (EQ (tem, Qeven))
2767 summary[1] = 'E';
2768 attr.c_cflag |= PARENB;
2769 attr.c_iflag |= (IGNPAR | INPCK);
2771 else if (EQ (tem, Qodd))
2773 summary[1] = 'O';
2774 attr.c_cflag |= (PARENB | PARODD);
2775 attr.c_iflag |= (IGNPAR | INPCK);
2777 #else
2778 /* Don't error on no parity, which should be set by cfmakeraw. */
2779 if (!NILP (tem))
2780 error ("Parity cannot be configured");
2781 #endif
2782 childp2 = Fplist_put (childp2, QCparity, tem);
2784 /* Configure stopbits. */
2785 if (!NILP (Fplist_member (contact, QCstopbits)))
2786 tem = Fplist_get (contact, QCstopbits);
2787 else
2788 tem = Fplist_get (p->childp, QCstopbits);
2789 if (NILP (tem))
2790 tem = make_number (1);
2791 CHECK_NUMBER (tem);
2792 if (XINT (tem) != 1 && XINT (tem) != 2)
2793 error (":stopbits must be nil (1 stopbit), 1, or 2");
2794 summary[2] = XINT (tem) + '0';
2795 #if defined (CSTOPB)
2796 attr.c_cflag &= ~CSTOPB;
2797 if (XINT (tem) == 2)
2798 attr.c_cflag |= CSTOPB;
2799 #else
2800 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2801 if (XINT (tem) != 1)
2802 error ("Stopbits cannot be configured");
2803 #endif
2804 childp2 = Fplist_put (childp2, QCstopbits, tem);
2806 /* Configure flowcontrol. */
2807 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2808 tem = Fplist_get (contact, QCflowcontrol);
2809 else
2810 tem = Fplist_get (p->childp, QCflowcontrol);
2811 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2812 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2813 #if defined (CRTSCTS)
2814 attr.c_cflag &= ~CRTSCTS;
2815 #endif
2816 #if defined (CNEW_RTSCTS)
2817 attr.c_cflag &= ~CNEW_RTSCTS;
2818 #endif
2819 #if defined (IXON) && defined (IXOFF)
2820 attr.c_iflag &= ~(IXON | IXOFF);
2821 #endif
2822 if (NILP (tem))
2824 /* Already configured. */
2826 else if (EQ (tem, Qhw))
2828 #if defined (CRTSCTS)
2829 attr.c_cflag |= CRTSCTS;
2830 #elif defined (CNEW_RTSCTS)
2831 attr.c_cflag |= CNEW_RTSCTS;
2832 #else
2833 error ("Hardware flowcontrol (RTS/CTS) not supported");
2834 #endif
2836 else if (EQ (tem, Qsw))
2838 #if defined (IXON) && defined (IXOFF)
2839 attr.c_iflag |= (IXON | IXOFF);
2840 #else
2841 error ("Software flowcontrol (XON/XOFF) not supported");
2842 #endif
2844 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2846 /* Activate configuration. */
2847 err = tcsetattr (p->outfd, TCSANOW, &attr);
2848 if (err != 0)
2849 report_file_error ("Failed tcsetattr", Qnil);
2851 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2852 pset_childp (p, childp2);
2854 #endif /* not DOS_NT */
2856 /* System depended enumeration of and access to system processes a-la ps(1). */
2858 #ifdef HAVE_PROCFS
2860 /* Process enumeration and access via /proc. */
2862 Lisp_Object
2863 list_system_processes (void)
2865 Lisp_Object procdir, match, proclist, next;
2866 Lisp_Object tail;
2868 /* For every process on the system, there's a directory in the
2869 "/proc" pseudo-directory whose name is the numeric ID of that
2870 process. */
2871 procdir = build_string ("/proc");
2872 match = build_string ("[0-9]+");
2873 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2875 /* `proclist' gives process IDs as strings. Destructively convert
2876 each string into a number. */
2877 for (tail = proclist; CONSP (tail); tail = next)
2879 next = XCDR (tail);
2880 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2883 /* directory_files_internal returns the files in reverse order; undo
2884 that. */
2885 proclist = Fnreverse (proclist);
2886 return proclist;
2889 #elif defined DARWIN_OS || defined __FreeBSD__
2891 Lisp_Object
2892 list_system_processes (void)
2894 #ifdef DARWIN_OS
2895 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2896 #else
2897 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2898 #endif
2899 size_t len;
2900 struct kinfo_proc *procs;
2901 size_t i;
2903 Lisp_Object proclist = Qnil;
2905 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2906 return proclist;
2908 procs = xmalloc (len);
2909 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2911 xfree (procs);
2912 return proclist;
2915 len /= sizeof (struct kinfo_proc);
2916 for (i = 0; i < len; i++)
2918 #ifdef DARWIN_OS
2919 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2920 #else
2921 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2922 #endif
2925 xfree (procs);
2927 return proclist;
2930 /* The WINDOWSNT implementation is in w32.c.
2931 The MSDOS implementation is in dosfns.c. */
2932 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2934 Lisp_Object
2935 list_system_processes (void)
2937 return Qnil;
2940 #endif /* !defined (WINDOWSNT) */
2942 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2943 static struct timespec
2944 time_from_jiffies (unsigned long long tval, long hz)
2946 unsigned long long s = tval / hz;
2947 unsigned long long frac = tval % hz;
2948 int ns;
2950 if (TYPE_MAXIMUM (time_t) < s)
2951 time_overflow ();
2952 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2953 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2954 ns = frac * TIMESPEC_RESOLUTION / hz;
2955 else
2957 /* This is reachable only in the unlikely case that HZ * HZ
2958 exceeds ULLONG_MAX. It calculates an approximation that is
2959 guaranteed to be in range. */
2960 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
2961 + (hz % TIMESPEC_RESOLUTION != 0));
2962 ns = frac / hz_per_ns;
2965 return make_timespec (s, ns);
2968 static Lisp_Object
2969 ltime_from_jiffies (unsigned long long tval, long hz)
2971 struct timespec t = time_from_jiffies (tval, hz);
2972 return make_lisp_time (t);
2975 static struct timespec
2976 get_up_time (void)
2978 FILE *fup;
2979 struct timespec up = make_timespec (0, 0);
2981 block_input ();
2982 fup = emacs_fopen ("/proc/uptime", "r");
2984 if (fup)
2986 unsigned long long upsec, upfrac, idlesec, idlefrac;
2987 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
2989 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
2990 &upsec, &upfrac_start, &upfrac, &upfrac_end,
2991 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
2992 == 4)
2994 if (TYPE_MAXIMUM (time_t) < upsec)
2996 upsec = TYPE_MAXIMUM (time_t);
2997 upfrac = TIMESPEC_RESOLUTION - 1;
2999 else
3001 int upfraclen = upfrac_end - upfrac_start;
3002 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3003 upfrac *= 10;
3004 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3005 upfrac /= 10;
3006 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3008 up = make_timespec (upsec, upfrac);
3010 fclose (fup);
3012 unblock_input ();
3014 return up;
3017 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3018 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3020 static Lisp_Object
3021 procfs_ttyname (int rdev)
3023 FILE *fdev;
3024 char name[PATH_MAX];
3026 block_input ();
3027 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3028 name[0] = 0;
3030 if (fdev)
3032 unsigned major;
3033 unsigned long minor_beg, minor_end;
3034 char minor[25]; /* 2 32-bit numbers + dash */
3035 char *endp;
3037 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
3039 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3040 && major == MAJOR (rdev))
3042 minor_beg = strtoul (minor, &endp, 0);
3043 if (*endp == '\0')
3044 minor_end = minor_beg;
3045 else if (*endp == '-')
3046 minor_end = strtoul (endp + 1, &endp, 0);
3047 else
3048 continue;
3050 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3052 sprintf (name + strlen (name), "%u", MINOR (rdev));
3053 break;
3057 fclose (fdev);
3059 unblock_input ();
3060 return build_string (name);
3063 static uintmax_t
3064 procfs_get_total_memory (void)
3066 FILE *fmem;
3067 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3068 int c;
3070 block_input ();
3071 fmem = emacs_fopen ("/proc/meminfo", "r");
3073 if (fmem)
3075 uintmax_t entry_value;
3076 bool done;
3079 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3081 case 1:
3082 retval = entry_value;
3083 done = 1;
3084 break;
3086 case 0:
3087 while ((c = getc (fmem)) != EOF && c != '\n')
3088 continue;
3089 done = c == EOF;
3090 break;
3092 default:
3093 done = 1;
3094 break;
3096 while (!done);
3098 fclose (fmem);
3100 unblock_input ();
3101 return retval;
3104 Lisp_Object
3105 system_process_attributes (Lisp_Object pid)
3107 char procfn[PATH_MAX], fn[PATH_MAX];
3108 struct stat st;
3109 struct passwd *pw;
3110 struct group *gr;
3111 long clocks_per_sec;
3112 char *procfn_end;
3113 char procbuf[1025], *p, *q;
3114 int fd;
3115 ssize_t nread;
3116 static char const default_cmd[] = "???";
3117 const char *cmd = default_cmd;
3118 int cmdsize = sizeof default_cmd - 1;
3119 char *cmdline = NULL;
3120 ptrdiff_t cmdline_size;
3121 char c;
3122 printmax_t proc_id;
3123 int ppid, pgrp, sess, tty, tpgid, thcount;
3124 uid_t uid;
3125 gid_t gid;
3126 unsigned long long u_time, s_time, cutime, cstime, start;
3127 long priority, niceness, rss;
3128 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3129 struct timespec tnow, tstart, tboot, telapsed, us_time;
3130 double pcpu, pmem;
3131 Lisp_Object attrs = Qnil;
3132 Lisp_Object decoded_cmd;
3133 ptrdiff_t count;
3135 CHECK_NUMBER_OR_FLOAT (pid);
3136 CONS_TO_INTEGER (pid, pid_t, proc_id);
3137 sprintf (procfn, "/proc/%"pMd, proc_id);
3138 if (stat (procfn, &st) < 0)
3139 return attrs;
3141 /* euid egid */
3142 uid = st.st_uid;
3143 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3144 block_input ();
3145 pw = getpwuid (uid);
3146 unblock_input ();
3147 if (pw)
3148 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3150 gid = st.st_gid;
3151 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3152 block_input ();
3153 gr = getgrgid (gid);
3154 unblock_input ();
3155 if (gr)
3156 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3158 count = SPECPDL_INDEX ();
3159 strcpy (fn, procfn);
3160 procfn_end = fn + strlen (fn);
3161 strcpy (procfn_end, "/stat");
3162 fd = emacs_open (fn, O_RDONLY, 0);
3163 if (fd < 0)
3164 nread = 0;
3165 else
3167 record_unwind_protect_int (close_file_unwind, fd);
3168 nread = emacs_read (fd, procbuf, sizeof procbuf - 1);
3170 if (0 < nread)
3172 procbuf[nread] = '\0';
3173 p = procbuf;
3175 p = strchr (p, '(');
3176 if (p != NULL)
3178 q = strrchr (p + 1, ')');
3179 /* comm */
3180 if (q != NULL)
3182 cmd = p + 1;
3183 cmdsize = q - cmd;
3186 else
3187 q = NULL;
3188 /* Command name is encoded in locale-coding-system; decode it. */
3189 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3190 decoded_cmd = code_convert_string_norecord (cmd_str,
3191 Vlocale_coding_system, 0);
3192 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3194 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3195 utime stime cutime cstime priority nice thcount . start vsize rss */
3196 if (q
3197 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3198 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3199 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3200 &minflt, &cminflt, &majflt, &cmajflt,
3201 &u_time, &s_time, &cutime, &cstime,
3202 &priority, &niceness, &thcount, &start, &vsize, &rss)
3203 == 20))
3205 char state_str[2];
3206 state_str[0] = c;
3207 state_str[1] = '\0';
3208 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3209 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3210 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3211 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3212 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3213 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3214 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3215 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3216 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3217 attrs);
3218 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3219 attrs);
3220 clocks_per_sec = sysconf (_SC_CLK_TCK);
3221 if (clocks_per_sec < 0)
3222 clocks_per_sec = 100;
3223 attrs = Fcons (Fcons (Qutime,
3224 ltime_from_jiffies (u_time, clocks_per_sec)),
3225 attrs);
3226 attrs = Fcons (Fcons (Qstime,
3227 ltime_from_jiffies (s_time, clocks_per_sec)),
3228 attrs);
3229 attrs = Fcons (Fcons (Qtime,
3230 ltime_from_jiffies (s_time + u_time,
3231 clocks_per_sec)),
3232 attrs);
3233 attrs = Fcons (Fcons (Qcutime,
3234 ltime_from_jiffies (cutime, clocks_per_sec)),
3235 attrs);
3236 attrs = Fcons (Fcons (Qcstime,
3237 ltime_from_jiffies (cstime, clocks_per_sec)),
3238 attrs);
3239 attrs = Fcons (Fcons (Qctime,
3240 ltime_from_jiffies (cstime + cutime,
3241 clocks_per_sec)),
3242 attrs);
3243 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3244 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3245 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3246 attrs);
3247 tnow = current_timespec ();
3248 telapsed = get_up_time ();
3249 tboot = timespec_sub (tnow, telapsed);
3250 tstart = time_from_jiffies (start, clocks_per_sec);
3251 tstart = timespec_add (tboot, tstart);
3252 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3253 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3254 attrs);
3255 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3256 telapsed = timespec_sub (tnow, tstart);
3257 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3258 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3259 pcpu = timespectod (us_time) / timespectod (telapsed);
3260 if (pcpu > 1.0)
3261 pcpu = 1.0;
3262 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3263 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3264 if (pmem > 100)
3265 pmem = 100;
3266 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3269 unbind_to (count, Qnil);
3271 /* args */
3272 strcpy (procfn_end, "/cmdline");
3273 fd = emacs_open (fn, O_RDONLY, 0);
3274 if (fd >= 0)
3276 ptrdiff_t readsize, nread_incr;
3277 record_unwind_protect_int (close_file_unwind, fd);
3278 record_unwind_protect_nothing ();
3279 nread = cmdline_size = 0;
3283 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3284 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3286 /* Leave room even if every byte needs escaping below. */
3287 readsize = (cmdline_size >> 1) - nread;
3289 nread_incr = emacs_read (fd, cmdline + nread, readsize);
3290 nread += max (0, nread_incr);
3292 while (nread_incr == readsize);
3294 if (nread)
3296 /* We don't want trailing null characters. */
3297 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3298 continue;
3300 /* Escape-quote whitespace and backslashes. */
3301 q = cmdline + cmdline_size;
3302 while (cmdline < p)
3304 char c = *--p;
3305 *--q = c ? c : ' ';
3306 if (c_isspace (c) || c == '\\')
3307 *--q = '\\';
3310 nread = cmdline + cmdline_size - q;
3313 if (!nread)
3315 nread = cmdsize + 2;
3316 cmdline_size = nread + 1;
3317 q = cmdline = xrealloc (cmdline, cmdline_size);
3318 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3319 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3321 /* Command line is encoded in locale-coding-system; decode it. */
3322 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3323 decoded_cmd = code_convert_string_norecord (cmd_str,
3324 Vlocale_coding_system, 0);
3325 unbind_to (count, Qnil);
3326 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3329 return attrs;
3332 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3334 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3335 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3336 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3337 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3338 #undef _FILE_OFFSET_BITS
3339 #else
3340 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3341 #endif
3343 #include <procfs.h>
3345 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3346 #define _FILE_OFFSET_BITS 64
3347 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3348 #endif
3349 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3351 Lisp_Object
3352 system_process_attributes (Lisp_Object pid)
3354 char procfn[PATH_MAX], fn[PATH_MAX];
3355 struct stat st;
3356 struct passwd *pw;
3357 struct group *gr;
3358 char *procfn_end;
3359 struct psinfo pinfo;
3360 int fd;
3361 ssize_t nread;
3362 printmax_t proc_id;
3363 uid_t uid;
3364 gid_t gid;
3365 Lisp_Object attrs = Qnil;
3366 Lisp_Object decoded_cmd;
3367 ptrdiff_t count;
3369 CHECK_NUMBER_OR_FLOAT (pid);
3370 CONS_TO_INTEGER (pid, pid_t, proc_id);
3371 sprintf (procfn, "/proc/%"pMd, proc_id);
3372 if (stat (procfn, &st) < 0)
3373 return attrs;
3375 /* euid egid */
3376 uid = st.st_uid;
3377 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3378 block_input ();
3379 pw = getpwuid (uid);
3380 unblock_input ();
3381 if (pw)
3382 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3384 gid = st.st_gid;
3385 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3386 block_input ();
3387 gr = getgrgid (gid);
3388 unblock_input ();
3389 if (gr)
3390 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3392 count = SPECPDL_INDEX ();
3393 strcpy (fn, procfn);
3394 procfn_end = fn + strlen (fn);
3395 strcpy (procfn_end, "/psinfo");
3396 fd = emacs_open (fn, O_RDONLY, 0);
3397 if (fd < 0)
3398 nread = 0;
3399 else
3401 record_unwind_protect_int (close_file_unwind, fd);
3402 nread = emacs_read (fd, &pinfo, sizeof pinfo);
3405 if (nread == sizeof pinfo)
3407 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3408 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3409 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3412 char state_str[2];
3413 state_str[0] = pinfo.pr_lwp.pr_sname;
3414 state_str[1] = '\0';
3415 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3418 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3419 need to get a string from it. */
3421 /* FIXME: missing: Qtpgid */
3423 /* FIXME: missing:
3424 Qminflt
3425 Qmajflt
3426 Qcminflt
3427 Qcmajflt
3429 Qutime
3430 Qcutime
3431 Qstime
3432 Qcstime
3433 Are they available? */
3435 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3436 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3437 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3438 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3439 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3440 attrs);
3442 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3443 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3444 attrs);
3445 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3446 attrs);
3448 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3449 range 0 .. 2**15, representing 0.0 .. 1.0. */
3450 attrs = Fcons (Fcons (Qpcpu,
3451 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3452 attrs);
3453 attrs = Fcons (Fcons (Qpmem,
3454 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3455 attrs);
3457 AUTO_STRING (fname, pinfo.pr_fname);
3458 decoded_cmd = code_convert_string_norecord (fname,
3459 Vlocale_coding_system, 0);
3460 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3461 AUTO_STRING (psargs, pinfo.pr_psargs);
3462 decoded_cmd = code_convert_string_norecord (psargs,
3463 Vlocale_coding_system, 0);
3464 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3466 unbind_to (count, Qnil);
3467 return attrs;
3470 #elif defined __FreeBSD__
3472 static struct timespec
3473 timeval_to_timespec (struct timeval t)
3475 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3478 static Lisp_Object
3479 make_lisp_timeval (struct timeval t)
3481 return make_lisp_time (timeval_to_timespec (t));
3484 Lisp_Object
3485 system_process_attributes (Lisp_Object pid)
3487 int proc_id;
3488 int pagesize = getpagesize ();
3489 unsigned long npages;
3490 int fscale;
3491 struct passwd *pw;
3492 struct group *gr;
3493 char *ttyname;
3494 size_t len;
3495 char args[MAXPATHLEN];
3496 struct timespec t, now;
3498 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3499 struct kinfo_proc proc;
3500 size_t proclen = sizeof proc;
3502 Lisp_Object attrs = Qnil;
3503 Lisp_Object decoded_comm;
3505 CHECK_NUMBER_OR_FLOAT (pid);
3506 CONS_TO_INTEGER (pid, int, proc_id);
3507 mib[3] = proc_id;
3509 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3510 return attrs;
3512 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3514 block_input ();
3515 pw = getpwuid (proc.ki_uid);
3516 unblock_input ();
3517 if (pw)
3518 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3520 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3522 block_input ();
3523 gr = getgrgid (proc.ki_svgid);
3524 unblock_input ();
3525 if (gr)
3526 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3528 AUTO_STRING (comm, proc.ki_comm);
3529 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3531 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3533 char state[2] = {'\0', '\0'};
3534 switch (proc.ki_stat)
3536 case SRUN:
3537 state[0] = 'R';
3538 break;
3540 case SSLEEP:
3541 state[0] = 'S';
3542 break;
3544 case SLOCK:
3545 state[0] = 'D';
3546 break;
3548 case SZOMB:
3549 state[0] = 'Z';
3550 break;
3552 case SSTOP:
3553 state[0] = 'T';
3554 break;
3556 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3559 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3560 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3561 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3563 block_input ();
3564 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3565 unblock_input ();
3566 if (ttyname)
3567 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3569 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3570 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3571 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3572 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3573 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3575 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3576 attrs);
3577 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3578 attrs);
3579 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3580 timeval_to_timespec (proc.ki_rusage.ru_stime));
3581 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3583 attrs = Fcons (Fcons (Qcutime,
3584 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3585 attrs);
3586 attrs = Fcons (Fcons (Qcstime,
3587 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3588 attrs);
3589 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3590 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3591 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3593 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3594 attrs);
3595 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3596 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3597 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3598 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3599 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3600 attrs);
3602 now = current_timespec ();
3603 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3604 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3606 len = sizeof fscale;
3607 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3609 double pcpu;
3610 fixpt_t ccpu;
3611 len = sizeof ccpu;
3612 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3614 pcpu = (100.0 * proc.ki_pctcpu / fscale
3615 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3616 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3620 len = sizeof npages;
3621 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3623 double pmem = (proc.ki_flag & P_INMEM
3624 ? 100.0 * proc.ki_rssize / npages
3625 : 0);
3626 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3629 mib[2] = KERN_PROC_ARGS;
3630 len = MAXPATHLEN;
3631 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3633 int i;
3634 for (i = 0; i < len; i++)
3636 if (! args[i] && i < len - 1)
3637 args[i] = ' ';
3640 AUTO_STRING (comm, args);
3641 decoded_comm = code_convert_string_norecord (comm,
3642 Vlocale_coding_system, 0);
3644 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3647 return attrs;
3650 #elif defined DARWIN_OS
3652 static struct timespec
3653 timeval_to_timespec (struct timeval t)
3655 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3658 static Lisp_Object
3659 make_lisp_timeval (struct timeval t)
3661 return make_lisp_time (timeval_to_timespec (t));
3664 Lisp_Object
3665 system_process_attributes (Lisp_Object pid)
3667 int proc_id;
3668 int pagesize = getpagesize ();
3669 unsigned long npages;
3670 int fscale;
3671 struct passwd *pw;
3672 struct group *gr;
3673 char *ttyname;
3674 size_t len;
3675 char args[MAXPATHLEN];
3676 struct timeval starttime;
3677 struct timespec t, now;
3678 struct rusage *rusage;
3679 dev_t tdev;
3680 uid_t uid;
3681 gid_t gid;
3683 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3684 struct kinfo_proc proc;
3685 size_t proclen = sizeof proc;
3687 Lisp_Object attrs = Qnil;
3688 Lisp_Object decoded_comm;
3690 CHECK_NUMBER_OR_FLOAT (pid);
3691 CONS_TO_INTEGER (pid, int, proc_id);
3692 mib[3] = proc_id;
3694 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3695 return attrs;
3697 uid = proc.kp_eproc.e_ucred.cr_uid;
3698 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3700 block_input ();
3701 pw = getpwuid (uid);
3702 unblock_input ();
3703 if (pw)
3704 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3706 gid = proc.kp_eproc.e_pcred.p_svgid;
3707 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3709 block_input ();
3710 gr = getgrgid (gid);
3711 unblock_input ();
3712 if (gr)
3713 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3715 decoded_comm = (code_convert_string_norecord
3716 (build_unibyte_string (proc.kp_proc.p_comm),
3717 Vlocale_coding_system, 0));
3719 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3721 char state[2] = {'\0', '\0'};
3722 switch (proc.kp_proc.p_stat)
3724 case SRUN:
3725 state[0] = 'R';
3726 break;
3728 case SSLEEP:
3729 state[0] = 'S';
3730 break;
3732 case SZOMB:
3733 state[0] = 'Z';
3734 break;
3736 case SSTOP:
3737 state[0] = 'T';
3738 break;
3740 case SIDL:
3741 state[0] = 'I';
3742 break;
3744 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3747 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3748 attrs);
3749 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3750 attrs);
3752 tdev = proc.kp_eproc.e_tdev;
3753 block_input ();
3754 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3755 unblock_input ();
3756 if (ttyname)
3757 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3759 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3760 attrs);
3762 rusage = proc.kp_proc.p_ru;
3763 if (rusage)
3765 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3766 attrs);
3767 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3768 attrs);
3770 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3771 attrs);
3772 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3773 attrs);
3774 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3775 timeval_to_timespec (rusage->ru_stime));
3776 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3779 starttime = proc.kp_proc.p_starttime;
3780 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3781 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3783 now = current_timespec ();
3784 t = timespec_sub (now, timeval_to_timespec (starttime));
3785 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3787 return attrs;
3790 /* The WINDOWSNT implementation is in w32.c.
3791 The MSDOS implementation is in dosfns.c. */
3792 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3794 Lisp_Object
3795 system_process_attributes (Lisp_Object pid)
3797 return Qnil;
3800 #endif /* !defined (WINDOWSNT) */
3802 /* Wide character string collation. */
3804 #ifdef __STDC_ISO_10646__
3805 # include <wchar.h>
3806 # include <wctype.h>
3808 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3809 # include <locale.h>
3810 # endif
3811 # ifndef LC_COLLATE
3812 # define LC_COLLATE 0
3813 # endif
3814 # ifndef LC_COLLATE_MASK
3815 # define LC_COLLATE_MASK 0
3816 # endif
3817 # ifndef LC_CTYPE
3818 # define LC_CTYPE 0
3819 # endif
3820 # ifndef LC_CTYPE_MASK
3821 # define LC_CTYPE_MASK 0
3822 # endif
3824 # ifndef HAVE_NEWLOCALE
3825 # undef freelocale
3826 # undef locale_t
3827 # undef newlocale
3828 # undef wcscoll_l
3829 # undef towlower_l
3830 # define freelocale emacs_freelocale
3831 # define locale_t emacs_locale_t
3832 # define newlocale emacs_newlocale
3833 # define wcscoll_l emacs_wcscoll_l
3834 # define towlower_l emacs_towlower_l
3836 typedef char const *locale_t;
3838 static locale_t
3839 newlocale (int category_mask, char const *locale, locale_t loc)
3841 return locale;
3844 static void
3845 freelocale (locale_t loc)
3849 static char *
3850 emacs_setlocale (int category, char const *locale)
3852 # ifdef HAVE_SETLOCALE
3853 errno = 0;
3854 char *loc = setlocale (category, locale);
3855 if (loc || errno)
3856 return loc;
3857 errno = EINVAL;
3858 # else
3859 errno = ENOTSUP;
3860 # endif
3861 return 0;
3864 static int
3865 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3867 int result = 0;
3868 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3869 int err;
3871 if (! oldloc)
3872 err = errno;
3873 else
3875 USE_SAFE_ALLOCA;
3876 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3877 strcpy (oldcopy, oldloc);
3878 if (! emacs_setlocale (LC_COLLATE, loc))
3879 err = errno;
3880 else
3882 errno = 0;
3883 result = wcscoll (a, b);
3884 err = errno;
3885 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3886 err = errno;
3888 SAFE_FREE ();
3891 errno = err;
3892 return result;
3895 static wint_t
3896 towlower_l (wint_t wc, locale_t loc)
3898 wint_t result = wc;
3899 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3901 if (oldloc)
3903 USE_SAFE_ALLOCA;
3904 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3905 strcpy (oldcopy, oldloc);
3906 if (emacs_setlocale (LC_CTYPE, loc))
3908 result = towlower (wc);
3909 emacs_setlocale (LC_COLLATE, oldcopy);
3911 SAFE_FREE ();
3914 return result;
3916 # endif
3919 str_collate (Lisp_Object s1, Lisp_Object s2,
3920 Lisp_Object locale, Lisp_Object ignore_case)
3922 int res, err;
3923 ptrdiff_t len, i, i_byte;
3924 wchar_t *p1, *p2;
3926 USE_SAFE_ALLOCA;
3928 /* Convert byte stream to code points. */
3929 len = SCHARS (s1); i = i_byte = 0;
3930 SAFE_NALLOCA (p1, 1, len + 1);
3931 while (i < len)
3932 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3933 *(p1+len) = 0;
3935 len = SCHARS (s2); i = i_byte = 0;
3936 SAFE_NALLOCA (p2, 1, len + 1);
3937 while (i < len)
3938 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3939 *(p2+len) = 0;
3941 if (STRINGP (locale))
3943 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3944 SSDATA (locale), 0);
3945 if (!loc)
3946 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
3948 if (! NILP (ignore_case))
3949 for (int i = 1; i < 3; i++)
3951 wchar_t *p = (i == 1) ? p1 : p2;
3952 for (; *p; p++)
3953 *p = towlower_l (*p, loc);
3956 errno = 0;
3957 res = wcscoll_l (p1, p2, loc);
3958 err = errno;
3959 freelocale (loc);
3961 else
3963 if (! NILP (ignore_case))
3964 for (int i = 1; i < 3; i++)
3966 wchar_t *p = (i == 1) ? p1 : p2;
3967 for (; *p; p++)
3968 *p = towlower (*p);
3971 errno = 0;
3972 res = wcscoll (p1, p2);
3973 err = errno;
3975 # ifndef HAVE_NEWLOCALE
3976 if (err)
3977 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
3978 # else
3979 if (err)
3980 error ("Invalid string for collation: %s", emacs_strerror (err));
3981 # endif
3983 SAFE_FREE ();
3984 return res;
3986 #endif /* __STDC_ISO_10646__ */
3988 #ifdef WINDOWSNT
3990 str_collate (Lisp_Object s1, Lisp_Object s2,
3991 Lisp_Object locale, Lisp_Object ignore_case)
3994 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
3995 int res, err = errno;
3997 errno = 0;
3998 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
3999 if (errno)
4000 error ("Invalid string for collation: %s", strerror (errno));
4002 errno = err;
4003 return res;
4005 #endif /* WINDOWSNT */