Prefer HTTPS to HTTP for gnu.org
[emacs.git] / src / sysdep.c
blob26d381f5796ab31c37a9bee4da3e56ecb413ab82
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2017 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <execinfo.h>
23 #include "sysstdio.h"
24 #ifdef HAVE_PWD_H
25 #include <pwd.h>
26 #include <grp.h>
27 #endif /* HAVE_PWD_H */
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
33 #include <utimens.h>
35 #include "lisp.h"
36 #include "sheap.h"
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #ifdef HAVE_LINUX_FS_H
41 # include <linux/fs.h>
42 # include <sys/syscall.h>
43 #endif
45 #ifdef CYGWIN
46 # include <cygwin/fs.h>
47 #endif
49 #if defined DARWIN_OS || defined __FreeBSD__
50 # include <sys/sysctl.h>
51 #endif
53 #ifdef __FreeBSD__
54 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
55 'struct frame', so rename it. */
56 # define frame freebsd_frame
57 # include <sys/user.h>
58 # undef frame
60 # include <math.h>
61 #endif
63 #ifdef HAVE_SOCKETS
64 #include <sys/socket.h>
65 #include <netdb.h>
66 #endif /* HAVE_SOCKETS */
68 #ifdef WINDOWSNT
69 #define read sys_read
70 #define write sys_write
71 #ifndef STDERR_FILENO
72 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
73 #endif
74 #include "w32.h"
75 #endif /* WINDOWSNT */
77 #include <sys/types.h>
78 #include <sys/stat.h>
79 #include <errno.h>
81 /* Get SI_SRPC_DOMAIN, if it is available. */
82 #ifdef HAVE_SYS_SYSTEMINFO_H
83 #include <sys/systeminfo.h>
84 #endif
86 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
87 #include "msdos.h"
88 #endif
90 #include <sys/param.h>
91 #include <sys/file.h>
92 #include <fcntl.h>
94 #include "systty.h"
95 #include "syswait.h"
97 #ifdef HAVE_SYS_UTSNAME_H
98 #include <sys/utsname.h>
99 #include <memory.h>
100 #endif /* HAVE_SYS_UTSNAME_H */
102 #include "keyboard.h"
103 #include "frame.h"
104 #include "termhooks.h"
105 #include "termchar.h"
106 #include "termopts.h"
107 #include "process.h"
108 #include "cm.h"
110 #include "gnutls.h"
111 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
112 do that during startup just to call gnutls_rnd. */
113 #if defined HAVE_GNUTLS && !defined WINDOWSNT
114 # include <gnutls/crypto.h>
115 #else
116 # define emacs_gnutls_global_init() Qnil
117 # define gnutls_rnd(level, data, len) (-1)
118 #endif
120 #ifdef WINDOWSNT
121 #include <direct.h>
122 /* In process.h which conflicts with the local copy. */
123 #define _P_WAIT 0
124 int _cdecl _spawnlp (int, const char *, const char *, ...);
125 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
126 several prototypes of functions called below. */
127 #include <sys/socket.h>
128 #endif
130 #include "syssignal.h"
131 #include "systime.h"
133 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
134 #ifndef ULLONG_MAX
135 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
136 #endif
138 /* Declare here, including term.h is problematic on some systems. */
139 extern void tputs (const char *, int, int (*)(int));
141 static const int baud_convert[] =
143 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
144 1800, 2400, 4800, 9600, 19200, 38400
147 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
148 # include <sys/personality.h>
150 /* Disable address randomization in the current process. Return true
151 if addresses were randomized but this has been disabled, false
152 otherwise. */
153 bool
154 disable_address_randomization (void)
156 int pers = personality (0xffffffff);
157 if (pers < 0)
158 return false;
159 int desired_pers = pers | ADDR_NO_RANDOMIZE;
161 /* Call 'personality' twice, to detect buggy platforms like WSL
162 where 'personality' always returns 0. */
163 return (pers != desired_pers
164 && personality (desired_pers) == pers
165 && personality (0xffffffff) == desired_pers);
167 #endif
169 /* Execute the program in FILE, with argument vector ARGV and environ
170 ENVP. Return an error number if unsuccessful. This is like execve
171 except it reenables ASLR in the executed program if necessary, and
172 on error it returns an error number rather than -1. */
174 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
176 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
177 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
178 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
179 if (change_personality)
180 personality (pers & ~ADDR_NO_RANDOMIZE);
181 #endif
183 execve (file, argv, envp);
184 int err = errno;
186 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
187 if (change_personality)
188 personality (pers);
189 #endif
191 return err;
194 /* If FD is not already open, arrange for it to be open with FLAGS. */
195 static void
196 force_open (int fd, int flags)
198 if (dup2 (fd, fd) < 0 && errno == EBADF)
200 int n = open (NULL_DEVICE, flags);
201 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
203 emacs_perror (NULL_DEVICE);
204 exit (EXIT_FAILURE);
209 /* Make sure stdin, stdout, and stderr are open to something, so that
210 their file descriptors are not hijacked by later system calls. */
211 void
212 init_standard_fds (void)
214 /* Open stdin for *writing*, and stdout and stderr for *reading*.
215 That way, any attempt to do normal I/O will result in an error,
216 just as if the files were closed, and the file descriptors will
217 not be reused by later opens. */
218 force_open (STDIN_FILENO, O_WRONLY);
219 force_open (STDOUT_FILENO, O_RDONLY);
220 force_open (STDERR_FILENO, O_RDONLY);
223 /* Return the current working directory. The result should be freed
224 with 'free'. Return NULL on errors. */
225 char *
226 emacs_get_current_dir_name (void)
228 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
229 # ifdef HYBRID_MALLOC
230 bool use_libc = bss_sbrk_did_unexec;
231 # else
232 bool use_libc = true;
233 # endif
234 if (use_libc)
235 return get_current_dir_name ();
236 # endif
238 char *buf;
239 char *pwd = getenv ("PWD");
240 struct stat dotstat, pwdstat;
241 /* If PWD is accurate, use it instead of calling getcwd. PWD is
242 sometimes a nicer name, and using it may avoid a fatal error if a
243 parent directory is searchable but not readable. */
244 if (pwd
245 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
246 && stat (pwd, &pwdstat) == 0
247 && stat (".", &dotstat) == 0
248 && dotstat.st_ino == pwdstat.st_ino
249 && dotstat.st_dev == pwdstat.st_dev
250 #ifdef MAXPATHLEN
251 && strlen (pwd) < MAXPATHLEN
252 #endif
255 buf = malloc (strlen (pwd) + 1);
256 if (!buf)
257 return NULL;
258 strcpy (buf, pwd);
260 else
262 size_t buf_size = 1024;
263 buf = malloc (buf_size);
264 if (!buf)
265 return NULL;
266 for (;;)
268 if (getcwd (buf, buf_size) == buf)
269 break;
270 if (errno != ERANGE)
272 int tmp_errno = errno;
273 free (buf);
274 errno = tmp_errno;
275 return NULL;
277 buf_size *= 2;
278 buf = realloc (buf, buf_size);
279 if (!buf)
280 return NULL;
283 return buf;
287 /* Discard pending input on all input descriptors. */
289 void
290 discard_tty_input (void)
292 #ifndef WINDOWSNT
293 struct emacs_tty buf;
295 if (noninteractive)
296 return;
298 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
299 while (dos_keyread () != -1)
301 #else /* not MSDOS */
303 struct tty_display_info *tty;
304 for (tty = tty_list; tty; tty = tty->next)
306 if (tty->input) /* Is the device suspended? */
308 emacs_get_tty (fileno (tty->input), &buf);
309 emacs_set_tty (fileno (tty->input), &buf, 0);
313 #endif /* not MSDOS */
314 #endif /* not WINDOWSNT */
318 #ifdef SIGTSTP
320 /* Arrange for character C to be read as the next input from
321 the terminal.
322 XXX What if we have multiple ttys?
325 void
326 stuff_char (char c)
328 if (! (FRAMEP (selected_frame)
329 && FRAME_LIVE_P (XFRAME (selected_frame))
330 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
331 return;
333 /* Should perhaps error if in batch mode */
334 #ifdef TIOCSTI
335 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
336 #else /* no TIOCSTI */
337 error ("Cannot stuff terminal input characters in this version of Unix");
338 #endif /* no TIOCSTI */
341 #endif /* SIGTSTP */
343 void
344 init_baud_rate (int fd)
346 int emacs_ospeed;
348 if (noninteractive)
349 emacs_ospeed = 0;
350 else
352 #ifdef DOS_NT
353 emacs_ospeed = 15;
354 #else /* not DOS_NT */
355 struct termios sg;
357 sg.c_cflag = B9600;
358 tcgetattr (fd, &sg);
359 emacs_ospeed = cfgetospeed (&sg);
360 #endif /* not DOS_NT */
363 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
364 ? baud_convert[emacs_ospeed] : 9600);
365 if (baud_rate == 0)
366 baud_rate = 1200;
371 #ifndef MSDOS
373 /* Wait for the subprocess with process id CHILD to terminate or change status.
374 CHILD must be a child process that has not been reaped.
375 If STATUS is non-null, store the waitpid-style exit status into *STATUS
376 and tell wait_reading_process_output that it needs to look around.
377 Use waitpid-style OPTIONS when waiting.
378 If INTERRUPTIBLE, this function is interruptible by a signal.
380 Return CHILD if successful, 0 if no status is available, and a
381 negative value (setting errno) if waitpid is buggy. */
382 static pid_t
383 get_child_status (pid_t child, int *status, int options, bool interruptible)
385 pid_t pid;
387 /* Invoke waitpid only with a known process ID; do not invoke
388 waitpid with a nonpositive argument. Otherwise, Emacs might
389 reap an unwanted process by mistake. For example, invoking
390 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
391 so that another thread running glib won't find them. */
392 eassert (child > 0);
394 while (true)
396 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
397 internally. */
398 if (interruptible)
399 maybe_quit ();
401 pid = waitpid (child, status, options);
402 if (0 <= pid)
403 break;
404 if (errno != EINTR)
406 /* Most likely, waitpid is buggy and the operating system
407 lost track of the child somehow. Return -1 and let the
408 caller try to figure things out. Possibly the bug could
409 cause Emacs to kill the wrong process. Oh well. */
410 return pid;
414 /* If successful and status is requested, tell wait_reading_process_output
415 that it needs to wake up and look around. */
416 if (pid && status && input_available_clear_time)
417 *input_available_clear_time = make_timespec (0, 0);
419 return pid;
422 /* Wait for the subprocess with process id CHILD to terminate.
423 CHILD must be a child process that has not been reaped.
424 If STATUS is non-null, store the waitpid-style exit status into *STATUS
425 and tell wait_reading_process_output that it needs to look around.
426 If INTERRUPTIBLE, this function is interruptible by a signal.
427 Return true if successful, false (setting errno) if CHILD cannot be
428 waited for because waitpid is buggy. */
429 bool
430 wait_for_termination (pid_t child, int *status, bool interruptible)
432 return 0 <= get_child_status (child, status, 0, interruptible);
435 /* Report whether the subprocess with process id CHILD has changed status.
436 Termination counts as a change of status.
437 CHILD must be a child process that has not been reaped.
438 If STATUS is non-null, store the waitpid-style exit status into *STATUS
439 and tell wait_reading_process_output that it needs to look around.
440 Use waitpid-style OPTIONS to check status, but do not wait.
442 Return CHILD if successful, 0 if no status is available because
443 the process's state has not changed. */
444 pid_t
445 child_status_changed (pid_t child, int *status, int options)
447 return get_child_status (child, status, WNOHANG | options, 0);
451 /* Set up the terminal at the other end of a pseudo-terminal that
452 we will be controlling an inferior through.
453 It should not echo or do line-editing, since that is done
454 in Emacs. No padding needed for insertion into an Emacs buffer. */
456 void
457 child_setup_tty (int out)
459 #ifndef WINDOWSNT
460 struct emacs_tty s;
462 emacs_get_tty (out, &s);
463 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
464 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
465 #ifdef NLDLY
466 /* https://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
467 Some versions of GNU Hurd do not have FFDLY? */
468 #ifdef FFDLY
469 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
470 /* No output delays */
471 #else
472 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
473 /* No output delays */
474 #endif
475 #endif
476 s.main.c_lflag &= ~ECHO; /* Disable echo */
477 s.main.c_lflag |= ISIG; /* Enable signals */
478 #ifdef IUCLC
479 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
480 #endif
481 #ifdef ISTRIP
482 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
483 #endif
484 #ifdef OLCUC
485 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
486 #endif
487 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
488 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
489 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
490 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
492 #ifdef HPUX
493 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
494 #endif /* HPUX */
496 #ifdef SIGNALS_VIA_CHARACTERS
497 /* the QUIT and INTR character are used in process_send_signal
498 so set them here to something useful. */
499 if (s.main.c_cc[VQUIT] == CDISABLE)
500 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
501 if (s.main.c_cc[VINTR] == CDISABLE)
502 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
503 #endif /* not SIGNALS_VIA_CHARACTERS */
505 #ifdef AIX
506 /* Also, PTY overloads NUL and BREAK.
507 don't ignore break, but don't signal either, so it looks like NUL. */
508 s.main.c_iflag &= ~IGNBRK;
509 s.main.c_iflag &= ~BRKINT;
510 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
511 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
512 would force it to 0377. That looks like duplicated code. */
513 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
514 #endif /* AIX */
516 /* We originally enabled ICANON (and set VEOF to 04), and then had
517 process.c send additional EOF chars to flush the output when faced
518 with long lines, but this leads to weird effects when the
519 subprocess has disabled ICANON and ends up seeing those spurious
520 extra EOFs. So we don't send EOFs any more in
521 process.c:send_process. First we tried to disable ICANON by
522 default, so if a subsprocess sets up ICANON, it's his problem (or
523 the Elisp package that talks to it) to deal with lines that are
524 too long. But this disables some features, such as the ability
525 to send EOF signals. So we re-enabled ICANON but there is no
526 more "send eof to flush" going on (which is wrong and unportable
527 in itself). The correct way to handle too much output is to
528 buffer what could not be written and then write it again when
529 select returns ok for writing. This has it own set of
530 problems. Write is now asynchronous, is that a problem? How much
531 do we buffer, and what do we do when that limit is reached? */
533 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
534 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
535 #if 0 /* These settings only apply to non-ICANON mode. */
536 s.main.c_cc[VMIN] = 1;
537 s.main.c_cc[VTIME] = 0;
538 #endif
540 emacs_set_tty (out, &s, 0);
541 #endif /* not WINDOWSNT */
543 #endif /* not MSDOS */
546 /* Record a signal code and the action for it. */
547 struct save_signal
549 int code;
550 struct sigaction action;
553 static void save_signal_handlers (struct save_signal *);
554 static void restore_signal_handlers (struct save_signal *);
556 /* Suspend the Emacs process; give terminal to its superior. */
558 void
559 sys_suspend (void)
561 #ifndef DOS_NT
562 kill (0, SIGTSTP);
563 #else
564 /* On a system where suspending is not implemented,
565 instead fork a subshell and let it talk directly to the terminal
566 while we wait. */
567 sys_subshell ();
569 #endif
572 /* Fork a subshell. */
574 void
575 sys_subshell (void)
577 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
578 #ifdef MSDOS
579 int st;
580 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
581 #else
582 char oldwd[MAX_UTF8_PATH];
583 #endif /* MSDOS */
584 #else /* !DOS_NT */
585 int status;
586 #endif
587 pid_t pid;
588 struct save_signal saved_handlers[5];
589 char *str = SSDATA (encode_current_directory ());
591 #ifdef DOS_NT
592 pid = 0;
593 #else
595 char *volatile str_volatile = str;
596 pid = vfork ();
597 str = str_volatile;
599 #endif
601 if (pid < 0)
602 error ("Can't spawn subshell");
604 saved_handlers[0].code = SIGINT;
605 saved_handlers[1].code = SIGQUIT;
606 saved_handlers[2].code = SIGTERM;
607 #ifdef USABLE_SIGIO
608 saved_handlers[3].code = SIGIO;
609 saved_handlers[4].code = 0;
610 #else
611 saved_handlers[3].code = 0;
612 #endif
614 #ifdef DOS_NT
615 save_signal_handlers (saved_handlers);
616 #endif
618 if (pid == 0)
620 const char *sh = 0;
622 #ifdef DOS_NT /* MW, Aug 1993 */
623 getcwd (oldwd, sizeof oldwd);
624 if (sh == 0)
625 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
626 #endif
627 if (sh == 0)
628 sh = egetenv ("SHELL");
629 if (sh == 0)
630 sh = "sh";
632 /* Use our buffer's default directory for the subshell. */
633 if (chdir (str) != 0)
635 #ifndef DOS_NT
636 emacs_perror (str);
637 _exit (EXIT_CANCELED);
638 #endif
641 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
643 char *epwd = getenv ("PWD");
644 char old_pwd[MAXPATHLEN+1+4];
646 /* If PWD is set, pass it with corrected value. */
647 if (epwd)
649 strcpy (old_pwd, epwd);
650 setenv ("PWD", str, 1);
652 st = system (sh);
653 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
654 if (epwd)
655 putenv (old_pwd); /* restore previous value */
657 #else /* not MSDOS */
658 #ifdef WINDOWSNT
659 /* Waits for process completion */
660 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
661 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
662 if (pid == -1)
663 write (1, "Can't execute subshell", 22);
664 #else /* not WINDOWSNT */
665 execlp (sh, sh, (char *) 0);
666 emacs_perror (sh);
667 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
668 #endif /* not WINDOWSNT */
669 #endif /* not MSDOS */
672 /* Do this now if we did not do it before. */
673 #ifndef MSDOS
674 save_signal_handlers (saved_handlers);
675 #endif
677 #ifndef DOS_NT
678 wait_for_termination (pid, &status, 0);
679 #endif
680 restore_signal_handlers (saved_handlers);
683 static void
684 save_signal_handlers (struct save_signal *saved_handlers)
686 while (saved_handlers->code)
688 struct sigaction action;
689 emacs_sigaction_init (&action, SIG_IGN);
690 sigaction (saved_handlers->code, &action, &saved_handlers->action);
691 saved_handlers++;
695 static void
696 restore_signal_handlers (struct save_signal *saved_handlers)
698 while (saved_handlers->code)
700 sigaction (saved_handlers->code, &saved_handlers->action, 0);
701 saved_handlers++;
705 #ifdef USABLE_SIGIO
706 static int old_fcntl_flags[FD_SETSIZE];
707 #endif
709 void
710 init_sigio (int fd)
712 #ifdef USABLE_SIGIO
713 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
714 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
715 interrupts_deferred = 0;
716 #endif
719 #ifndef DOS_NT
720 static void
721 reset_sigio (int fd)
723 #ifdef USABLE_SIGIO
724 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
725 #endif
727 #endif
729 void
730 request_sigio (void)
732 #ifdef USABLE_SIGIO
733 sigset_t unblocked;
735 if (noninteractive)
736 return;
738 sigemptyset (&unblocked);
739 # ifdef SIGWINCH
740 sigaddset (&unblocked, SIGWINCH);
741 # endif
742 sigaddset (&unblocked, SIGIO);
743 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
745 interrupts_deferred = 0;
746 #endif
749 void
750 unrequest_sigio (void)
752 #ifdef USABLE_SIGIO
753 sigset_t blocked;
755 if (noninteractive)
756 return;
758 sigemptyset (&blocked);
759 # ifdef SIGWINCH
760 sigaddset (&blocked, SIGWINCH);
761 # endif
762 sigaddset (&blocked, SIGIO);
763 pthread_sigmask (SIG_BLOCK, &blocked, 0);
764 interrupts_deferred = 1;
765 #endif
768 #ifndef MSDOS
769 /* Block SIGCHLD. */
771 void
772 block_child_signal (sigset_t *oldset)
774 sigset_t blocked;
775 sigemptyset (&blocked);
776 sigaddset (&blocked, SIGCHLD);
777 sigaddset (&blocked, SIGINT);
778 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
781 /* Unblock SIGCHLD. */
783 void
784 unblock_child_signal (sigset_t const *oldset)
786 pthread_sigmask (SIG_SETMASK, oldset, 0);
789 /* Block SIGINT. */
790 void
791 block_interrupt_signal (sigset_t *oldset)
793 sigset_t blocked;
794 sigemptyset (&blocked);
795 sigaddset (&blocked, SIGINT);
796 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
799 /* Restore previously saved signal mask. */
800 void
801 restore_signal_mask (sigset_t const *oldset)
803 pthread_sigmask (SIG_SETMASK, oldset, 0);
806 #endif /* !MSDOS */
808 /* Saving and restoring the process group of Emacs's terminal. */
810 /* The process group of which Emacs was a member when it initially
811 started.
813 If Emacs was in its own process group (i.e. inherited_pgroup ==
814 getpid ()), then we know we're running under a shell with job
815 control (Emacs would never be run as part of a pipeline).
816 Everything is fine.
818 If Emacs was not in its own process group, then we know we're
819 running under a shell (or a caller) that doesn't know how to
820 separate itself from Emacs (like sh). Emacs must be in its own
821 process group in order to receive SIGIO correctly. In this
822 situation, we put ourselves in our own pgroup, forcibly set the
823 tty's pgroup to our pgroup, and make sure to restore and reinstate
824 the tty's pgroup just like any other terminal setting. If
825 inherited_group was not the tty's pgroup, then we'll get a
826 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
827 it goes foreground in the future, which is what should happen. */
829 static pid_t inherited_pgroup;
831 void
832 init_foreground_group (void)
834 pid_t pgrp = getpgrp ();
835 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
838 /* Block and unblock SIGTTOU. */
840 void
841 block_tty_out_signal (sigset_t *oldset)
843 #ifdef SIGTTOU
844 sigset_t blocked;
845 sigemptyset (&blocked);
846 sigaddset (&blocked, SIGTTOU);
847 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
848 #endif
851 void
852 unblock_tty_out_signal (sigset_t const *oldset)
854 #ifdef SIGTTOU
855 pthread_sigmask (SIG_SETMASK, oldset, 0);
856 #endif
859 /* Safely set a controlling terminal FD's process group to PGID.
860 If we are not in the foreground already, POSIX requires tcsetpgrp
861 to deliver a SIGTTOU signal, which would stop us. This is an
862 annoyance, so temporarily ignore the signal.
864 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
865 skip all this unless SIGTTOU is defined. */
866 static void
867 tcsetpgrp_without_stopping (int fd, pid_t pgid)
869 #ifdef SIGTTOU
870 sigset_t oldset;
871 block_input ();
872 block_tty_out_signal (&oldset);
873 tcsetpgrp (fd, pgid);
874 unblock_tty_out_signal (&oldset);
875 unblock_input ();
876 #endif
879 /* Split off the foreground process group to Emacs alone. When we are
880 in the foreground, but not started in our own process group,
881 redirect the tty device handle FD to point to our own process
882 group. FD must be the file descriptor of the controlling tty. */
883 static void
884 narrow_foreground_group (int fd)
886 if (inherited_pgroup && setpgid (0, 0) == 0)
887 tcsetpgrp_without_stopping (fd, getpid ());
890 /* Set the tty to our original foreground group. */
891 static void
892 widen_foreground_group (int fd)
894 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
895 tcsetpgrp_without_stopping (fd, inherited_pgroup);
898 /* Getting and setting emacs_tty structures. */
900 /* Set *TC to the parameters associated with the terminal FD,
901 or clear it if the parameters are not available.
902 Return 0 on success, -1 on failure. */
904 emacs_get_tty (int fd, struct emacs_tty *settings)
906 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
907 memset (&settings->main, 0, sizeof (settings->main));
908 #ifdef DOS_NT
909 #ifdef WINDOWSNT
910 HANDLE h = (HANDLE)_get_osfhandle (fd);
911 DWORD console_mode;
913 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
915 settings->main = console_mode;
916 return 0;
918 #endif /* WINDOWSNT */
919 return -1;
920 #else /* !DOS_NT */
921 /* We have those nifty POSIX tcmumbleattr functions. */
922 return tcgetattr (fd, &settings->main);
923 #endif
927 /* Set the parameters of the tty on FD according to the contents of
928 *SETTINGS. If FLUSHP, discard input.
929 Return 0 if all went well, and -1 (setting errno) if anything failed. */
932 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
934 /* Set the primary parameters - baud rate, character size, etcetera. */
935 #ifdef DOS_NT
936 #ifdef WINDOWSNT
937 HANDLE h = (HANDLE)_get_osfhandle (fd);
939 if (h && h != INVALID_HANDLE_VALUE)
941 DWORD new_mode;
943 /* Assume the handle is open for input. */
944 if (flushp)
945 FlushConsoleInputBuffer (h);
946 new_mode = settings->main;
947 SetConsoleMode (h, new_mode);
949 #endif /* WINDOWSNT */
950 #else /* !DOS_NT */
951 int i;
952 /* We have those nifty POSIX tcmumbleattr functions.
953 William J. Smith <wjs@wiis.wang.com> writes:
954 "POSIX 1003.1 defines tcsetattr to return success if it was
955 able to perform any of the requested actions, even if some
956 of the requested actions could not be performed.
957 We must read settings back to ensure tty setup properly.
958 AIX requires this to keep tty from hanging occasionally." */
959 /* This make sure that we don't loop indefinitely in here. */
960 for (i = 0 ; i < 10 ; i++)
961 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
963 if (errno == EINTR)
964 continue;
965 else
966 return -1;
968 else
970 struct termios new;
972 memset (&new, 0, sizeof (new));
973 /* Get the current settings, and see if they're what we asked for. */
974 tcgetattr (fd, &new);
975 /* We cannot use memcmp on the whole structure here because under
976 * aix386 the termios structure has some reserved field that may
977 * not be filled in.
979 if ( new.c_iflag == settings->main.c_iflag
980 && new.c_oflag == settings->main.c_oflag
981 && new.c_cflag == settings->main.c_cflag
982 && new.c_lflag == settings->main.c_lflag
983 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
984 break;
985 else
986 continue;
988 #endif
990 /* We have survived the tempest. */
991 return 0;
996 #ifdef F_SETOWN
997 static int old_fcntl_owner[FD_SETSIZE];
998 #endif /* F_SETOWN */
1000 /* This may also be defined in stdio,
1001 but if so, this does no harm,
1002 and using the same name avoids wasting the other one's space. */
1004 #if defined (USG)
1005 unsigned char _sobuf[BUFSIZ+8];
1006 #else
1007 char _sobuf[BUFSIZ];
1008 #endif
1010 /* Initialize the terminal mode on all tty devices that are currently
1011 open. */
1013 void
1014 init_all_sys_modes (void)
1016 struct tty_display_info *tty;
1017 for (tty = tty_list; tty; tty = tty->next)
1018 init_sys_modes (tty);
1021 /* Initialize the terminal mode on the given tty device. */
1023 void
1024 init_sys_modes (struct tty_display_info *tty_out)
1026 struct emacs_tty tty;
1027 #ifndef DOS_NT
1028 Lisp_Object terminal;
1029 #endif
1031 Vtty_erase_char = Qnil;
1033 if (noninteractive)
1034 return;
1036 if (!tty_out->output)
1037 return; /* The tty is suspended. */
1039 narrow_foreground_group (fileno (tty_out->input));
1041 if (! tty_out->old_tty)
1042 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1044 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1046 tty = *tty_out->old_tty;
1048 #if !defined (DOS_NT)
1049 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1051 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1052 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1053 #ifdef INLCR /* I'm just being cautious,
1054 since I can't check how widespread INLCR is--rms. */
1055 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1056 #endif
1057 #ifdef ISTRIP
1058 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1059 #endif
1060 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1061 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1062 #ifdef IEXTEN
1063 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1064 #endif
1065 tty.main.c_lflag |= ISIG; /* Enable signals */
1066 if (tty_out->flow_control)
1068 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1069 #ifdef IXANY
1070 tty.main.c_iflag &= ~IXANY;
1071 #endif /* IXANY */
1073 else
1074 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1075 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1076 on output */
1077 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1078 #ifdef CS8
1079 if (tty_out->meta_key)
1081 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1082 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1084 #endif
1086 XSETTERMINAL(terminal, tty_out->terminal);
1087 if (!NILP (Fcontrolling_tty_p (terminal)))
1089 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1090 /* Set up C-g for both SIGQUIT and SIGINT.
1091 We don't know which we will get, but we handle both alike
1092 so which one it really gives us does not matter. */
1093 tty.main.c_cc[VQUIT] = quit_char;
1095 else
1097 /* We normally don't get interrupt or quit signals from tty
1098 devices other than our controlling terminal; therefore,
1099 we must handle C-g as normal input. Unfortunately, this
1100 means that the interrupt and quit feature must be
1101 disabled on secondary ttys, or we would not even see the
1102 keypress.
1104 Note that even though emacsclient could have special code
1105 to pass SIGINT to Emacs, we should _not_ enable
1106 interrupt/quit keys for emacsclient frames. This means
1107 that we can't break out of loops in C code from a
1108 secondary tty frame, but we can always decide what
1109 display the C-g came from, which is more important from a
1110 usability point of view. (Consider the case when two
1111 people work together using the same Emacs instance.) */
1112 tty.main.c_cc[VINTR] = CDISABLE;
1113 tty.main.c_cc[VQUIT] = CDISABLE;
1115 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1116 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1117 #ifdef VSWTCH
1118 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1119 of C-z */
1120 #endif /* VSWTCH */
1122 #ifdef VSUSP
1123 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1124 #endif /* VSUSP */
1125 #ifdef V_DSUSP
1126 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1127 #endif /* V_DSUSP */
1128 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1129 tty.main.c_cc[VDSUSP] = CDISABLE;
1130 #endif /* VDSUSP */
1131 #ifdef VLNEXT
1132 tty.main.c_cc[VLNEXT] = CDISABLE;
1133 #endif /* VLNEXT */
1134 #ifdef VREPRINT
1135 tty.main.c_cc[VREPRINT] = CDISABLE;
1136 #endif /* VREPRINT */
1137 #ifdef VWERASE
1138 tty.main.c_cc[VWERASE] = CDISABLE;
1139 #endif /* VWERASE */
1140 #ifdef VDISCARD
1141 tty.main.c_cc[VDISCARD] = CDISABLE;
1142 #endif /* VDISCARD */
1144 if (tty_out->flow_control)
1146 #ifdef VSTART
1147 tty.main.c_cc[VSTART] = '\021';
1148 #endif /* VSTART */
1149 #ifdef VSTOP
1150 tty.main.c_cc[VSTOP] = '\023';
1151 #endif /* VSTOP */
1153 else
1155 #ifdef VSTART
1156 tty.main.c_cc[VSTART] = CDISABLE;
1157 #endif /* VSTART */
1158 #ifdef VSTOP
1159 tty.main.c_cc[VSTOP] = CDISABLE;
1160 #endif /* VSTOP */
1163 #ifdef AIX
1164 tty.main.c_cc[VSTRT] = CDISABLE;
1165 tty.main.c_cc[VSTOP] = CDISABLE;
1166 tty.main.c_cc[VSUSP] = CDISABLE;
1167 tty.main.c_cc[VDSUSP] = CDISABLE;
1168 if (tty_out->flow_control)
1170 #ifdef VSTART
1171 tty.main.c_cc[VSTART] = '\021';
1172 #endif /* VSTART */
1173 #ifdef VSTOP
1174 tty.main.c_cc[VSTOP] = '\023';
1175 #endif /* VSTOP */
1177 /* Also, PTY overloads NUL and BREAK.
1178 don't ignore break, but don't signal either, so it looks like NUL.
1179 This really serves a purpose only if running in an XTERM window
1180 or via TELNET or the like, but does no harm elsewhere. */
1181 tty.main.c_iflag &= ~IGNBRK;
1182 tty.main.c_iflag &= ~BRKINT;
1183 #endif
1184 #endif /* not DOS_NT */
1186 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1187 if (!tty_out->term_initted)
1188 internal_terminal_init ();
1189 dos_ttraw (tty_out);
1190 #endif
1192 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1194 /* This code added to insure that, if flow-control is not to be used,
1195 we have an unlocked terminal at the start. */
1197 #ifdef TCXONC
1198 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1199 #endif
1200 #ifdef TIOCSTART
1201 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1202 #endif
1204 #if !defined (DOS_NT)
1205 #ifdef TCOON
1206 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1207 #endif
1208 #endif
1210 #ifdef F_GETOWN
1211 if (interrupt_input)
1213 old_fcntl_owner[fileno (tty_out->input)] =
1214 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1215 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1216 init_sigio (fileno (tty_out->input));
1217 #ifdef HAVE_GPM
1218 if (gpm_tty == tty_out)
1220 /* Arrange for mouse events to give us SIGIO signals. */
1221 fcntl (gpm_fd, F_SETOWN, getpid ());
1222 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1223 init_sigio (gpm_fd);
1225 #endif /* HAVE_GPM */
1227 #endif /* F_GETOWN */
1229 #ifdef _IOFBF
1230 /* This symbol is defined on recent USG systems.
1231 Someone says without this call USG won't really buffer the file
1232 even with a call to setbuf. */
1233 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1234 #else
1235 setbuf (tty_out->output, (char *) _sobuf);
1236 #endif
1238 if (tty_out->terminal->set_terminal_modes_hook)
1239 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1241 if (!tty_out->term_initted)
1243 Lisp_Object tail, frame;
1244 FOR_EACH_FRAME (tail, frame)
1246 /* XXX This needs to be revised. */
1247 if (FRAME_TERMCAP_P (XFRAME (frame))
1248 && FRAME_TTY (XFRAME (frame)) == tty_out)
1249 init_frame_faces (XFRAME (frame));
1253 if (tty_out->term_initted && no_redraw_on_reenter)
1255 /* We used to call "direct_output_forward_char(0)" here,
1256 but it's not clear why, since it may not do anything anyway. */
1258 else
1260 Lisp_Object tail, frame;
1261 frame_garbaged = 1;
1262 FOR_EACH_FRAME (tail, frame)
1264 if ((FRAME_TERMCAP_P (XFRAME (frame))
1265 || FRAME_MSDOS_P (XFRAME (frame)))
1266 && FRAME_TTY (XFRAME (frame)) == tty_out)
1267 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1271 tty_out->term_initted = 1;
1274 /* Return true if safe to use tabs in output.
1275 At the time this is called, init_sys_modes has not been done yet. */
1277 bool
1278 tabs_safe_p (int fd)
1280 struct emacs_tty etty;
1282 emacs_get_tty (fd, &etty);
1283 #ifndef DOS_NT
1284 #ifdef TABDLY
1285 return ((etty.main.c_oflag & TABDLY) != TAB3);
1286 #else /* not TABDLY */
1287 return 1;
1288 #endif /* not TABDLY */
1289 #else /* DOS_NT */
1290 return 0;
1291 #endif /* DOS_NT */
1294 /* Discard echoing. */
1296 void
1297 suppress_echo_on_tty (int fd)
1299 struct emacs_tty etty;
1301 emacs_get_tty (fd, &etty);
1302 #ifdef DOS_NT
1303 /* Set raw input mode. */
1304 etty.main = 0;
1305 #else
1306 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1307 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1308 #endif /* ! WINDOWSNT */
1309 emacs_set_tty (fd, &etty, 0);
1312 /* Get terminal size from system.
1313 Store number of lines into *HEIGHTP and width into *WIDTHP.
1314 We store 0 if there's no valid information. */
1316 void
1317 get_tty_size (int fd, int *widthp, int *heightp)
1319 #if defined TIOCGWINSZ
1321 /* BSD-style. */
1322 struct winsize size;
1324 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1325 *widthp = *heightp = 0;
1326 else
1328 *widthp = size.ws_col;
1329 *heightp = size.ws_row;
1332 #elif defined TIOCGSIZE
1334 /* SunOS - style. */
1335 struct ttysize size;
1337 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1338 *widthp = *heightp = 0;
1339 else
1341 *widthp = size.ts_cols;
1342 *heightp = size.ts_lines;
1345 #elif defined WINDOWSNT
1347 CONSOLE_SCREEN_BUFFER_INFO info;
1348 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1350 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1351 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1353 else
1354 *widthp = *heightp = 0;
1356 #elif defined MSDOS
1358 *widthp = ScreenCols ();
1359 *heightp = ScreenRows ();
1361 #else /* system doesn't know size */
1363 *widthp = 0;
1364 *heightp = 0;
1366 #endif
1369 /* Set the logical window size associated with descriptor FD
1370 to HEIGHT and WIDTH. This is used mainly with ptys.
1371 Return a negative value on failure. */
1374 set_window_size (int fd, int height, int width)
1376 #ifdef TIOCSWINSZ
1378 /* BSD-style. */
1379 struct winsize size;
1380 size.ws_row = height;
1381 size.ws_col = width;
1383 return ioctl (fd, TIOCSWINSZ, &size);
1385 #else
1386 #ifdef TIOCSSIZE
1388 /* SunOS - style. */
1389 struct ttysize size;
1390 size.ts_lines = height;
1391 size.ts_cols = width;
1393 return ioctl (fd, TIOCGSIZE, &size);
1394 #else
1395 return -1;
1396 #endif /* not SunOS-style */
1397 #endif /* not BSD-style */
1402 /* Prepare all terminal devices for exiting Emacs. */
1404 void
1405 reset_all_sys_modes (void)
1407 struct tty_display_info *tty;
1408 for (tty = tty_list; tty; tty = tty->next)
1409 reset_sys_modes (tty);
1412 /* Prepare the terminal for closing it; move the cursor to the
1413 bottom of the frame, turn off interrupt-driven I/O, etc. */
1415 void
1416 reset_sys_modes (struct tty_display_info *tty_out)
1418 if (noninteractive)
1420 fflush_unlocked (stdout);
1421 return;
1423 if (!tty_out->term_initted)
1424 return;
1426 if (!tty_out->output)
1427 return; /* The tty is suspended. */
1429 /* Go to and clear the last line of the terminal. */
1431 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1433 /* Code adapted from tty_clear_end_of_line. */
1434 if (tty_out->TS_clr_line)
1436 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1438 else
1439 { /* have to do it the hard way */
1440 tty_turn_off_insert (tty_out);
1442 for (int i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1443 fputc_unlocked (' ', tty_out->output);
1446 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1447 fflush_unlocked (tty_out->output);
1449 if (tty_out->terminal->reset_terminal_modes_hook)
1450 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1452 /* Avoid possible loss of output when changing terminal modes. */
1453 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1454 continue;
1456 #ifndef DOS_NT
1457 #ifdef F_SETOWN
1458 if (interrupt_input)
1460 reset_sigio (fileno (tty_out->input));
1461 fcntl (fileno (tty_out->input), F_SETOWN,
1462 old_fcntl_owner[fileno (tty_out->input)]);
1464 #endif /* F_SETOWN */
1465 fcntl (fileno (tty_out->input), F_SETFL,
1466 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1467 #endif
1469 if (tty_out->old_tty)
1470 while (emacs_set_tty (fileno (tty_out->input),
1471 tty_out->old_tty, 0) < 0 && errno == EINTR)
1474 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1475 dos_ttcooked ();
1476 #endif
1478 widen_foreground_group (fileno (tty_out->input));
1481 #ifdef HAVE_PTYS
1483 /* Set up the proper status flags for use of a pty. */
1485 void
1486 setup_pty (int fd)
1488 /* I'm told that TOICREMOTE does not mean control chars
1489 "can't be sent" but rather that they don't have
1490 input-editing or signaling effects.
1491 That should be good, because we have other ways
1492 to do those things in Emacs.
1493 However, telnet mode seems not to work on 4.2.
1494 So TIOCREMOTE is turned off now. */
1496 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1497 will hang. In particular, the "timeout" feature (which
1498 causes a read to return if there is no data available)
1499 does this. Also it is known that telnet mode will hang
1500 in such a way that Emacs must be stopped (perhaps this
1501 is the same problem).
1503 If TIOCREMOTE is turned off, then there is a bug in
1504 hp-ux which sometimes loses data. Apparently the
1505 code which blocks the master process when the internal
1506 buffer fills up does not work. Other than this,
1507 though, everything else seems to work fine.
1509 Since the latter lossage is more benign, we may as well
1510 lose that way. -- cph */
1511 #ifdef FIONBIO
1512 #if defined (UNIX98_PTYS)
1514 int on = 1;
1515 ioctl (fd, FIONBIO, &on);
1517 #endif
1518 #endif
1520 #endif /* HAVE_PTYS */
1522 void
1523 init_system_name (void)
1525 if (!build_details)
1527 /* Set system-name to nil so that the build is deterministic. */
1528 Vsystem_name = Qnil;
1529 return;
1531 char *hostname_alloc = NULL;
1532 char *hostname;
1533 #ifndef HAVE_GETHOSTNAME
1534 struct utsname uts;
1535 uname (&uts);
1536 hostname = uts.nodename;
1537 #else /* HAVE_GETHOSTNAME */
1538 char hostname_buf[256];
1539 ptrdiff_t hostname_size = sizeof hostname_buf;
1540 hostname = hostname_buf;
1542 /* Try to get the host name; if the buffer is too short, try
1543 again. Apparently, the only indication gethostname gives of
1544 whether the buffer was large enough is the presence or absence
1545 of a '\0' in the string. Eech. */
1546 for (;;)
1548 gethostname (hostname, hostname_size - 1);
1549 hostname[hostname_size - 1] = '\0';
1551 /* Was the buffer large enough for the '\0'? */
1552 if (strlen (hostname) < hostname_size - 1)
1553 break;
1555 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1556 min (PTRDIFF_MAX, SIZE_MAX), 1);
1558 #endif /* HAVE_GETHOSTNAME */
1559 char *p;
1560 for (p = hostname; *p; p++)
1561 if (*p == ' ' || *p == '\t')
1562 *p = '-';
1563 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1564 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1565 Vsystem_name = build_string (hostname);
1566 xfree (hostname_alloc);
1569 sigset_t empty_mask;
1571 static struct sigaction process_fatal_action;
1573 static int
1574 emacs_sigaction_flags (void)
1576 #ifdef SA_RESTART
1577 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1578 'select') to reset their timeout on some platforms (e.g.,
1579 HP-UX 11), which is not what we want. Also, when Emacs is
1580 interactive, we don't want SA_RESTART because we need to poll
1581 for pending input so we need long-running syscalls to be interrupted
1582 after a signal that sets pending_signals.
1584 Non-interactive keyboard input goes through stdio, where we
1585 always want restartable system calls. */
1586 if (noninteractive)
1587 return SA_RESTART;
1588 #endif
1589 return 0;
1592 /* Store into *ACTION a signal action suitable for Emacs, with handler
1593 HANDLER. */
1594 void
1595 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1597 sigemptyset (&action->sa_mask);
1599 /* When handling a signal, block nonfatal system signals that are caught
1600 by Emacs. This makes race conditions less likely. */
1601 sigaddset (&action->sa_mask, SIGALRM);
1602 #ifdef SIGCHLD
1603 sigaddset (&action->sa_mask, SIGCHLD);
1604 #endif
1605 #ifdef SIGDANGER
1606 sigaddset (&action->sa_mask, SIGDANGER);
1607 #endif
1608 #ifdef PROFILER_CPU_SUPPORT
1609 sigaddset (&action->sa_mask, SIGPROF);
1610 #endif
1611 #ifdef SIGWINCH
1612 sigaddset (&action->sa_mask, SIGWINCH);
1613 #endif
1614 if (! noninteractive)
1616 sigaddset (&action->sa_mask, SIGINT);
1617 sigaddset (&action->sa_mask, SIGQUIT);
1618 #ifdef USABLE_SIGIO
1619 sigaddset (&action->sa_mask, SIGIO);
1620 #endif
1623 action->sa_handler = handler;
1624 action->sa_flags = emacs_sigaction_flags ();
1627 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1628 pthread_t main_thread_id;
1629 #endif
1631 /* SIG has arrived at the current process. Deliver it to the main
1632 thread, which should handle it with HANDLER. (Delivering the
1633 signal to some other thread might not work if the other thread is
1634 about to exit.)
1636 If we are on the main thread, handle the signal SIG with HANDLER.
1637 Otherwise, redirect the signal to the main thread, blocking it from
1638 this thread. POSIX says any thread can receive a signal that is
1639 associated with a process, process group, or asynchronous event.
1640 On GNU/Linux the main thread typically gets a process signal unless
1641 it's blocked, but other systems (FreeBSD at least) can deliver the
1642 signal to other threads. */
1643 void
1644 deliver_process_signal (int sig, signal_handler_t handler)
1646 /* Preserve errno, to avoid race conditions with signal handlers that
1647 might change errno. Races can occur even in single-threaded hosts. */
1648 int old_errno = errno;
1650 bool on_main_thread = true;
1651 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1652 if (! pthread_equal (pthread_self (), main_thread_id))
1654 sigset_t blocked;
1655 sigemptyset (&blocked);
1656 sigaddset (&blocked, sig);
1657 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1658 pthread_kill (main_thread_id, sig);
1659 on_main_thread = false;
1661 #endif
1662 if (on_main_thread)
1663 handler (sig);
1665 errno = old_errno;
1668 /* Static location to save a fatal backtrace in a thread.
1669 FIXME: If two subsidiary threads fail simultaneously, the resulting
1670 backtrace may be garbage. */
1671 enum { BACKTRACE_LIMIT_MAX = 500 };
1672 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1673 static int thread_backtrace_npointers;
1675 /* SIG has arrived at the current thread.
1676 If we are on the main thread, handle the signal SIG with HANDLER.
1677 Otherwise, this is a fatal error in the handling thread. */
1678 static void
1679 deliver_thread_signal (int sig, signal_handler_t handler)
1681 int old_errno = errno;
1683 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1684 if (! pthread_equal (pthread_self (), main_thread_id))
1686 thread_backtrace_npointers
1687 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1688 sigaction (sig, &process_fatal_action, 0);
1689 pthread_kill (main_thread_id, sig);
1691 /* Avoid further damage while the main thread is exiting. */
1692 while (1)
1693 sigsuspend (&empty_mask);
1695 #endif
1697 handler (sig);
1698 errno = old_errno;
1701 #if !HAVE_DECL_SYS_SIGLIST
1702 # undef sys_siglist
1703 # ifdef _sys_siglist
1704 # define sys_siglist _sys_siglist
1705 # elif HAVE_DECL___SYS_SIGLIST
1706 # define sys_siglist __sys_siglist
1707 # else
1708 # define sys_siglist my_sys_siglist
1709 static char const *sys_siglist[NSIG];
1710 # endif
1711 #endif
1713 #ifdef _sys_nsig
1714 # define sys_siglist_entries _sys_nsig
1715 #else
1716 # define sys_siglist_entries NSIG
1717 #endif
1719 /* Handle bus errors, invalid instruction, etc. */
1720 static void
1721 handle_fatal_signal (int sig)
1723 terminate_due_to_signal (sig, 40);
1726 static void
1727 deliver_fatal_signal (int sig)
1729 deliver_process_signal (sig, handle_fatal_signal);
1732 static void
1733 deliver_fatal_thread_signal (int sig)
1735 deliver_thread_signal (sig, handle_fatal_signal);
1738 static _Noreturn void
1739 handle_arith_signal (int sig)
1741 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1742 xsignal0 (Qarith_error);
1745 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1747 /* Alternate stack used by SIGSEGV handler below. */
1749 static unsigned char sigsegv_stack[SIGSTKSZ];
1752 /* Return true if SIGINFO indicates a stack overflow. */
1754 static bool
1755 stack_overflow (siginfo_t *siginfo)
1757 if (!attempt_stack_overflow_recovery)
1758 return false;
1760 /* In theory, a more-accurate heuristic can be obtained by using
1761 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1762 and pthread_attr_getguardsize to find the location and size of the
1763 guard area. In practice, though, these functions are so hard to
1764 use reliably that they're not worth bothering with. E.g., see:
1765 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1766 Other operating systems also have problems, e.g., Solaris's
1767 stack_violation function is tailor-made for this problem, but it
1768 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1770 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1771 candidate here. */
1773 if (!siginfo)
1774 return false;
1776 /* The faulting address. */
1777 char *addr = siginfo->si_addr;
1778 if (!addr)
1779 return false;
1781 /* The known top and bottom of the stack. The actual stack may
1782 extend a bit beyond these boundaries. */
1783 char *bot = stack_bottom;
1784 char *top = current_thread->stack_top;
1786 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1787 of the known stack divided by the size of the guard area past the
1788 end of the stack top. The heuristic is that a bad address is
1789 considered to be a stack overflow if it occurs within
1790 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1791 stack. This heuristic is not exactly correct but it's good
1792 enough in practice. */
1793 enum { LG_STACK_HEURISTIC = 8 };
1795 if (bot < top)
1796 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1797 else
1798 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1802 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1804 static void
1805 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1807 /* Hard GC error may lead to stack overflow caused by
1808 too nested calls to mark_object. No way to survive. */
1809 bool fatal = gc_in_progress;
1811 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1812 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1813 fatal = true;
1814 #endif
1816 if (!fatal && stack_overflow (siginfo))
1817 siglongjmp (return_to_command_loop, 1);
1819 /* Otherwise we can't do anything with this. */
1820 deliver_fatal_thread_signal (sig);
1823 /* Return true if we have successfully set up SIGSEGV handler on alternate
1824 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1826 static bool
1827 init_sigsegv (void)
1829 struct sigaction sa;
1830 stack_t ss;
1832 ss.ss_sp = sigsegv_stack;
1833 ss.ss_size = sizeof (sigsegv_stack);
1834 ss.ss_flags = 0;
1835 if (sigaltstack (&ss, NULL) < 0)
1836 return 0;
1838 sigfillset (&sa.sa_mask);
1839 sa.sa_sigaction = handle_sigsegv;
1840 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1841 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1844 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1846 static bool
1847 init_sigsegv (void)
1849 return 0;
1852 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1854 static void
1855 deliver_arith_signal (int sig)
1857 deliver_thread_signal (sig, handle_arith_signal);
1860 #ifdef SIGDANGER
1862 /* Handler for SIGDANGER. */
1863 static void
1864 handle_danger_signal (int sig)
1866 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1868 /* It might be unsafe to call do_auto_save now. */
1869 force_auto_save_soon ();
1872 static void
1873 deliver_danger_signal (int sig)
1875 deliver_process_signal (sig, handle_danger_signal);
1877 #endif
1879 /* Treat SIG as a terminating signal, unless it is already ignored and
1880 we are in --batch mode. Among other things, this makes nohup work. */
1881 static void
1882 maybe_fatal_sig (int sig)
1884 bool catch_sig = !noninteractive;
1885 if (!catch_sig)
1887 struct sigaction old_action;
1888 sigaction (sig, 0, &old_action);
1889 catch_sig = old_action.sa_handler != SIG_IGN;
1891 if (catch_sig)
1892 sigaction (sig, &process_fatal_action, 0);
1895 void
1896 init_signals (bool dumping)
1898 struct sigaction thread_fatal_action;
1899 struct sigaction action;
1901 sigemptyset (&empty_mask);
1903 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1904 main_thread_id = pthread_self ();
1905 #endif
1907 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1908 if (! initialized)
1910 sys_siglist[SIGABRT] = "Aborted";
1911 # ifdef SIGAIO
1912 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1913 # endif
1914 sys_siglist[SIGALRM] = "Alarm clock";
1915 # ifdef SIGBUS
1916 sys_siglist[SIGBUS] = "Bus error";
1917 # endif
1918 # ifdef SIGCHLD
1919 sys_siglist[SIGCHLD] = "Child status changed";
1920 # endif
1921 # ifdef SIGCONT
1922 sys_siglist[SIGCONT] = "Continued";
1923 # endif
1924 # ifdef SIGDANGER
1925 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1926 # endif
1927 # ifdef SIGDGNOTIFY
1928 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1929 # endif
1930 # ifdef SIGEMT
1931 sys_siglist[SIGEMT] = "Emulation trap";
1932 # endif
1933 sys_siglist[SIGFPE] = "Arithmetic exception";
1934 # ifdef SIGFREEZE
1935 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1936 # endif
1937 # ifdef SIGGRANT
1938 sys_siglist[SIGGRANT] = "Monitor mode granted";
1939 # endif
1940 sys_siglist[SIGHUP] = "Hangup";
1941 sys_siglist[SIGILL] = "Illegal instruction";
1942 sys_siglist[SIGINT] = "Interrupt";
1943 # ifdef SIGIO
1944 sys_siglist[SIGIO] = "I/O possible";
1945 # endif
1946 # ifdef SIGIOINT
1947 sys_siglist[SIGIOINT] = "I/O intervention required";
1948 # endif
1949 # ifdef SIGIOT
1950 sys_siglist[SIGIOT] = "IOT trap";
1951 # endif
1952 sys_siglist[SIGKILL] = "Killed";
1953 # ifdef SIGLOST
1954 sys_siglist[SIGLOST] = "Resource lost";
1955 # endif
1956 # ifdef SIGLWP
1957 sys_siglist[SIGLWP] = "SIGLWP";
1958 # endif
1959 # ifdef SIGMSG
1960 sys_siglist[SIGMSG] = "Monitor mode data available";
1961 # endif
1962 # ifdef SIGPHONE
1963 sys_siglist[SIGWIND] = "SIGPHONE";
1964 # endif
1965 sys_siglist[SIGPIPE] = "Broken pipe";
1966 # ifdef SIGPOLL
1967 sys_siglist[SIGPOLL] = "Pollable event occurred";
1968 # endif
1969 # ifdef SIGPROF
1970 sys_siglist[SIGPROF] = "Profiling timer expired";
1971 # endif
1972 # ifdef SIGPTY
1973 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1974 # endif
1975 # ifdef SIGPWR
1976 sys_siglist[SIGPWR] = "Power-fail restart";
1977 # endif
1978 sys_siglist[SIGQUIT] = "Quit";
1979 # ifdef SIGRETRACT
1980 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1981 # endif
1982 # ifdef SIGSAK
1983 sys_siglist[SIGSAK] = "Secure attention";
1984 # endif
1985 sys_siglist[SIGSEGV] = "Segmentation violation";
1986 # ifdef SIGSOUND
1987 sys_siglist[SIGSOUND] = "Sound completed";
1988 # endif
1989 # ifdef SIGSTOP
1990 sys_siglist[SIGSTOP] = "Stopped (signal)";
1991 # endif
1992 # ifdef SIGSTP
1993 sys_siglist[SIGSTP] = "Stopped (user)";
1994 # endif
1995 # ifdef SIGSYS
1996 sys_siglist[SIGSYS] = "Bad argument to system call";
1997 # endif
1998 sys_siglist[SIGTERM] = "Terminated";
1999 # ifdef SIGTHAW
2000 sys_siglist[SIGTHAW] = "SIGTHAW";
2001 # endif
2002 # ifdef SIGTRAP
2003 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2004 # endif
2005 # ifdef SIGTSTP
2006 sys_siglist[SIGTSTP] = "Stopped (user)";
2007 # endif
2008 # ifdef SIGTTIN
2009 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2010 # endif
2011 # ifdef SIGTTOU
2012 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2013 # endif
2014 # ifdef SIGURG
2015 sys_siglist[SIGURG] = "Urgent I/O condition";
2016 # endif
2017 # ifdef SIGUSR1
2018 sys_siglist[SIGUSR1] = "User defined signal 1";
2019 # endif
2020 # ifdef SIGUSR2
2021 sys_siglist[SIGUSR2] = "User defined signal 2";
2022 # endif
2023 # ifdef SIGVTALRM
2024 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2025 # endif
2026 # ifdef SIGWAITING
2027 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2028 # endif
2029 # ifdef SIGWINCH
2030 sys_siglist[SIGWINCH] = "Window size changed";
2031 # endif
2032 # ifdef SIGWIND
2033 sys_siglist[SIGWIND] = "SIGWIND";
2034 # endif
2035 # ifdef SIGXCPU
2036 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2037 # endif
2038 # ifdef SIGXFSZ
2039 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2040 # endif
2042 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2044 /* Don't alter signal handlers if dumping. On some machines,
2045 changing signal handlers sets static data that would make signals
2046 fail to work right when the dumped Emacs is run. */
2047 if (dumping)
2048 return;
2050 sigfillset (&process_fatal_action.sa_mask);
2051 process_fatal_action.sa_handler = deliver_fatal_signal;
2052 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2054 sigfillset (&thread_fatal_action.sa_mask);
2055 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2056 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2058 /* SIGINT may need special treatment on MS-Windows. See
2059 https://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2060 Please update the doc of kill-emacs, kill-emacs-hook, and
2061 NEWS if you change this. */
2063 maybe_fatal_sig (SIGHUP);
2064 maybe_fatal_sig (SIGINT);
2065 maybe_fatal_sig (SIGTERM);
2067 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2068 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2069 to behave more like typical batch applications do. */
2070 if (! noninteractive)
2071 signal (SIGPIPE, SIG_IGN);
2073 sigaction (SIGQUIT, &process_fatal_action, 0);
2074 sigaction (SIGILL, &thread_fatal_action, 0);
2075 sigaction (SIGTRAP, &thread_fatal_action, 0);
2077 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2078 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2079 interpreter's floating point operations, so treat SIGFPE as an
2080 arith-error if it arises in the main thread. */
2081 if (IEEE_FLOATING_POINT)
2082 sigaction (SIGFPE, &thread_fatal_action, 0);
2083 else
2085 emacs_sigaction_init (&action, deliver_arith_signal);
2086 sigaction (SIGFPE, &action, 0);
2089 #ifdef SIGUSR1
2090 add_user_signal (SIGUSR1, "sigusr1");
2091 #endif
2092 #ifdef SIGUSR2
2093 add_user_signal (SIGUSR2, "sigusr2");
2094 #endif
2095 sigaction (SIGABRT, &thread_fatal_action, 0);
2096 #ifdef SIGPRE
2097 sigaction (SIGPRE, &thread_fatal_action, 0);
2098 #endif
2099 #ifdef SIGORE
2100 sigaction (SIGORE, &thread_fatal_action, 0);
2101 #endif
2102 #ifdef SIGUME
2103 sigaction (SIGUME, &thread_fatal_action, 0);
2104 #endif
2105 #ifdef SIGDLK
2106 sigaction (SIGDLK, &process_fatal_action, 0);
2107 #endif
2108 #ifdef SIGCPULIM
2109 sigaction (SIGCPULIM, &process_fatal_action, 0);
2110 #endif
2111 #ifdef SIGIOT
2112 sigaction (SIGIOT, &thread_fatal_action, 0);
2113 #endif
2114 #ifdef SIGEMT
2115 sigaction (SIGEMT, &thread_fatal_action, 0);
2116 #endif
2117 #ifdef SIGBUS
2118 sigaction (SIGBUS, &thread_fatal_action, 0);
2119 #endif
2120 if (!init_sigsegv ())
2121 sigaction (SIGSEGV, &thread_fatal_action, 0);
2122 #ifdef SIGSYS
2123 sigaction (SIGSYS, &thread_fatal_action, 0);
2124 #endif
2125 sigaction (SIGTERM, &process_fatal_action, 0);
2126 #ifdef SIGPROF
2127 signal (SIGPROF, SIG_IGN);
2128 #endif
2129 #ifdef SIGVTALRM
2130 sigaction (SIGVTALRM, &process_fatal_action, 0);
2131 #endif
2132 #ifdef SIGXCPU
2133 sigaction (SIGXCPU, &process_fatal_action, 0);
2134 #endif
2135 #ifdef SIGXFSZ
2136 sigaction (SIGXFSZ, &process_fatal_action, 0);
2137 #endif
2139 #ifdef SIGDANGER
2140 /* This just means available memory is getting low. */
2141 emacs_sigaction_init (&action, deliver_danger_signal);
2142 sigaction (SIGDANGER, &action, 0);
2143 #endif
2145 /* AIX-specific signals. */
2146 #ifdef SIGGRANT
2147 sigaction (SIGGRANT, &process_fatal_action, 0);
2148 #endif
2149 #ifdef SIGMIGRATE
2150 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2151 #endif
2152 #ifdef SIGMSG
2153 sigaction (SIGMSG, &process_fatal_action, 0);
2154 #endif
2155 #ifdef SIGRETRACT
2156 sigaction (SIGRETRACT, &process_fatal_action, 0);
2157 #endif
2158 #ifdef SIGSAK
2159 sigaction (SIGSAK, &process_fatal_action, 0);
2160 #endif
2161 #ifdef SIGSOUND
2162 sigaction (SIGSOUND, &process_fatal_action, 0);
2163 #endif
2164 #ifdef SIGTALRM
2165 sigaction (SIGTALRM, &thread_fatal_action, 0);
2166 #endif
2169 #ifndef HAVE_RANDOM
2170 #ifdef random
2171 #define HAVE_RANDOM
2172 #endif
2173 #endif
2175 /* Figure out how many bits the system's random number generator uses.
2176 `random' and `lrand48' are assumed to return 31 usable bits.
2177 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2178 so we'll shift it and treat it like the 15-bit USG `rand'. */
2180 #ifndef RAND_BITS
2181 # ifdef HAVE_RANDOM
2182 # define RAND_BITS 31
2183 # else /* !HAVE_RANDOM */
2184 # ifdef HAVE_LRAND48
2185 # define RAND_BITS 31
2186 # define random lrand48
2187 # else /* !HAVE_LRAND48 */
2188 # define RAND_BITS 15
2189 # if RAND_MAX == 32767
2190 # define random rand
2191 # else /* RAND_MAX != 32767 */
2192 # if RAND_MAX == 2147483647
2193 # define random() (rand () >> 16)
2194 # else /* RAND_MAX != 2147483647 */
2195 # ifdef USG
2196 # define random rand
2197 # else
2198 # define random() (rand () >> 16)
2199 # endif /* !USG */
2200 # endif /* RAND_MAX != 2147483647 */
2201 # endif /* RAND_MAX != 32767 */
2202 # endif /* !HAVE_LRAND48 */
2203 # endif /* !HAVE_RANDOM */
2204 #endif /* !RAND_BITS */
2206 #ifdef HAVE_RANDOM
2207 typedef unsigned int random_seed;
2208 static void set_random_seed (random_seed arg) { srandom (arg); }
2209 #elif defined HAVE_LRAND48
2210 /* Although srand48 uses a long seed, this is unsigned long to avoid
2211 undefined behavior on signed integer overflow in init_random. */
2212 typedef unsigned long int random_seed;
2213 static void set_random_seed (random_seed arg) { srand48 (arg); }
2214 #else
2215 typedef unsigned int random_seed;
2216 static void set_random_seed (random_seed arg) { srand (arg); }
2217 #endif
2219 void
2220 seed_random (void *seed, ptrdiff_t seed_size)
2222 random_seed arg = 0;
2223 unsigned char *argp = (unsigned char *) &arg;
2224 unsigned char *seedp = seed;
2225 for (ptrdiff_t i = 0; i < seed_size; i++)
2226 argp[i % sizeof arg] ^= seedp[i];
2227 set_random_seed (arg);
2230 void
2231 init_random (void)
2233 random_seed v;
2234 bool success = false;
2236 /* First, try seeding the PRNG from the operating system's entropy
2237 source. This approach is both fast and secure. */
2238 #ifdef WINDOWSNT
2239 success = w32_init_random (&v, sizeof v) == 0;
2240 #else
2241 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2242 if (0 <= fd)
2244 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2245 close (fd);
2247 #endif
2249 /* If that didn't work, try using GnuTLS, which is secure, but on
2250 some systems, can be somewhat slow. */
2251 if (!success)
2252 success = EQ (emacs_gnutls_global_init (), Qt)
2253 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2255 /* If _that_ didn't work, just use the current time value and PID.
2256 It's at least better than XKCD 221. */
2257 if (!success)
2259 struct timespec t = current_timespec ();
2260 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2263 set_random_seed (v);
2267 * Return a nonnegative random integer out of whatever we've got.
2268 * It contains enough bits to make a random (signed) Emacs fixnum.
2269 * This suffices even for a 64-bit architecture with a 15-bit rand.
2271 EMACS_INT
2272 get_random (void)
2274 EMACS_UINT val = 0;
2275 int i;
2276 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2277 val = (random () ^ (val << RAND_BITS)
2278 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2279 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2280 return val & INTMASK;
2283 #ifndef HAVE_SNPRINTF
2284 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2286 snprintf (char *buf, size_t bufsize, char const *format, ...)
2288 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2289 ptrdiff_t nbytes = size - 1;
2290 va_list ap;
2292 if (size)
2294 va_start (ap, format);
2295 nbytes = doprnt (buf, size, format, 0, ap);
2296 va_end (ap);
2299 if (nbytes == size - 1)
2301 /* Calculate the length of the string that would have been created
2302 had the buffer been large enough. */
2303 char stackbuf[4000];
2304 char *b = stackbuf;
2305 ptrdiff_t bsize = sizeof stackbuf;
2306 va_start (ap, format);
2307 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2308 va_end (ap);
2309 if (b != stackbuf)
2310 xfree (b);
2313 if (INT_MAX < nbytes)
2315 #ifdef EOVERFLOW
2316 errno = EOVERFLOW;
2317 #else
2318 errno = EDOM;
2319 #endif
2320 return -1;
2322 return nbytes;
2324 #endif
2326 /* If a backtrace is available, output the top lines of it to stderr.
2327 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2328 This function may be called from a signal handler, so it should
2329 not invoke async-unsafe functions like malloc.
2331 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2332 but do not output anything. This avoids some problems that can
2333 otherwise occur if the malloc arena is corrupted before 'backtrace'
2334 is called, since 'backtrace' may call malloc if the tables are not
2335 initialized.
2337 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2338 fatal error has occurred in some other thread; generate a thread
2339 backtrace instead, ignoring BACKTRACE_LIMIT. */
2340 void
2341 emacs_backtrace (int backtrace_limit)
2343 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2344 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2345 void *buffer;
2346 int npointers;
2348 if (thread_backtrace_npointers)
2350 buffer = thread_backtrace_buffer;
2351 npointers = thread_backtrace_npointers;
2353 else
2355 buffer = main_backtrace_buffer;
2357 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2358 if (bounded_limit < 0)
2360 backtrace (buffer, 1);
2361 return;
2364 npointers = backtrace (buffer, bounded_limit + 1);
2367 if (npointers)
2369 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2370 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2371 if (bounded_limit < npointers)
2372 emacs_write (STDERR_FILENO, "...\n", 4);
2376 #ifndef HAVE_NTGUI
2377 void
2378 emacs_abort (void)
2380 terminate_due_to_signal (SIGABRT, 40);
2382 #endif
2384 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2385 Use binary I/O on systems that care about text vs binary I/O.
2386 Arrange for subprograms to not inherit the file descriptor.
2387 Prefer a method that is multithread-safe, if available.
2388 Do not fail merely because the open was interrupted by a signal.
2389 Allow the user to quit. */
2392 emacs_open (const char *file, int oflags, int mode)
2394 int fd;
2395 if (! (oflags & O_TEXT))
2396 oflags |= O_BINARY;
2397 oflags |= O_CLOEXEC;
2398 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2399 maybe_quit ();
2400 return fd;
2403 /* Open FILE as a stream for Emacs use, with mode MODE.
2404 Act like emacs_open with respect to threads, signals, and quits. */
2406 FILE *
2407 emacs_fopen (char const *file, char const *mode)
2409 int fd, omode, oflags;
2410 int bflag = 0;
2411 char const *m = mode;
2413 switch (*m++)
2415 case 'r': omode = O_RDONLY; oflags = 0; break;
2416 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2417 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2418 default: emacs_abort ();
2421 while (*m)
2422 switch (*m++)
2424 case '+': omode = O_RDWR; break;
2425 case 't': bflag = O_TEXT; break;
2426 default: /* Ignore. */ break;
2429 fd = emacs_open (file, omode | oflags | bflag, 0666);
2430 return fd < 0 ? 0 : fdopen (fd, mode);
2433 /* Create a pipe for Emacs use. */
2436 emacs_pipe (int fd[2])
2438 #ifdef MSDOS
2439 return pipe (fd);
2440 #else /* !MSDOS */
2441 return pipe2 (fd, O_BINARY | O_CLOEXEC);
2442 #endif /* !MSDOS */
2445 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2446 For the background behind this mess, please see Austin Group defect 529
2447 <http://austingroupbugs.net/view.php?id=529>. */
2449 #ifndef POSIX_CLOSE_RESTART
2450 # define POSIX_CLOSE_RESTART 1
2451 static int
2452 posix_close (int fd, int flag)
2454 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2455 eassert (flag == POSIX_CLOSE_RESTART);
2457 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2458 on a system that does not define POSIX_CLOSE_RESTART.
2460 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2461 closed, and retrying the close could inadvertently close a file
2462 descriptor allocated by some other thread. In other systems
2463 (e.g., HP/UX) FD is not closed. And in still other systems
2464 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2465 multithreaded program there can be no way to tell.
2467 So, in this case, pretend that the close succeeded. This works
2468 well on systems like GNU/Linux that close FD. Although it may
2469 leak a file descriptor on other systems, the leak is unlikely and
2470 it's better to leak than to close a random victim. */
2471 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2473 #endif
2475 /* Close FD, retrying if interrupted. If successful, return 0;
2476 otherwise, return -1 and set errno to a non-EINTR value. Consider
2477 an EINPROGRESS error to be successful, as that's merely a signal
2478 arriving. FD is always closed when this function returns, even
2479 when it returns -1.
2481 Do not call this function if FD is nonnegative and might already be closed,
2482 as that might close an innocent victim opened by some other thread. */
2485 emacs_close (int fd)
2487 while (1)
2489 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2490 if (r == 0)
2491 return r;
2492 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2494 eassert (errno != EBADF || fd < 0);
2495 return errno == EINPROGRESS ? 0 : r;
2500 /* Maximum number of bytes to read or write in a single system call.
2501 This works around a serious bug in Linux kernels before 2.6.16; see
2502 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2503 It's likely to work around similar bugs in other operating systems, so do it
2504 on all platforms. Round INT_MAX down to a page size, with the conservative
2505 assumption that page sizes are at most 2**18 bytes (any kernel with a
2506 page size larger than that shouldn't have the bug). */
2507 #ifndef MAX_RW_COUNT
2508 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2509 #endif
2511 /* Read from FD to a buffer BUF with size NBYTE.
2512 If interrupted, process any quits and pending signals immediately
2513 if INTERRUPTIBLE, and then retry the read unless quitting.
2514 Return the number of bytes read, which might be less than NBYTE.
2515 On error, set errno to a value other than EINTR, and return -1. */
2516 static ptrdiff_t
2517 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2519 ssize_t result;
2521 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2522 passes a size that large to emacs_read. */
2525 if (interruptible)
2526 maybe_quit ();
2527 result = read (fd, buf, nbyte);
2529 while (result < 0 && errno == EINTR);
2531 return result;
2534 /* Read from FD to a buffer BUF with size NBYTE.
2535 If interrupted, retry the read. Return the number of bytes read,
2536 which might be less than NBYTE. On error, set errno to a value
2537 other than EINTR, and return -1. */
2538 ptrdiff_t
2539 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2541 return emacs_intr_read (fd, buf, nbyte, false);
2544 /* Like emacs_read, but also process quits and pending signals. */
2545 ptrdiff_t
2546 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2548 return emacs_intr_read (fd, buf, nbyte, true);
2551 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2552 interrupted or if a partial write occurs. Process any quits
2553 immediately if INTERRUPTIBLE is positive, and process any pending
2554 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2555 of bytes written; if this is less than NBYTE, set errno to a value
2556 other than EINTR. */
2557 static ptrdiff_t
2558 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2559 int interruptible)
2561 ptrdiff_t bytes_written = 0;
2563 while (nbyte > 0)
2565 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2567 if (n < 0)
2569 if (errno != EINTR)
2570 break;
2572 if (interruptible)
2574 if (0 < interruptible)
2575 maybe_quit ();
2576 if (pending_signals)
2577 process_pending_signals ();
2580 else
2582 buf += n;
2583 nbyte -= n;
2584 bytes_written += n;
2588 return bytes_written;
2591 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2592 interrupted or if a partial write occurs. Do not process quits or
2593 pending signals. Return the number of bytes written, setting errno
2594 if this is less than NBYTE. */
2595 ptrdiff_t
2596 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2598 return emacs_full_write (fd, buf, nbyte, 0);
2601 /* Like emacs_write, but also process pending signals. */
2602 ptrdiff_t
2603 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2605 return emacs_full_write (fd, buf, nbyte, -1);
2608 /* Like emacs_write, but also process quits and pending signals. */
2609 ptrdiff_t
2610 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2612 return emacs_full_write (fd, buf, nbyte, 1);
2615 /* Write a diagnostic to standard error that contains MESSAGE and a
2616 string derived from errno. Preserve errno. Do not buffer stderr.
2617 Do not process quits or pending signals if interrupted. */
2618 void
2619 emacs_perror (char const *message)
2621 int err = errno;
2622 char const *error_string = emacs_strerror (err);
2623 char const *command = (initial_argv && initial_argv[0]
2624 ? initial_argv[0] : "emacs");
2625 /* Write it out all at once, if it's short; this is less likely to
2626 be interleaved with other output. */
2627 char buf[BUFSIZ];
2628 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2629 command, message, error_string);
2630 if (0 <= nbytes && nbytes < BUFSIZ)
2631 emacs_write (STDERR_FILENO, buf, nbytes);
2632 else
2634 emacs_write (STDERR_FILENO, command, strlen (command));
2635 emacs_write (STDERR_FILENO, ": ", 2);
2636 emacs_write (STDERR_FILENO, message, strlen (message));
2637 emacs_write (STDERR_FILENO, ": ", 2);
2638 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2639 emacs_write (STDERR_FILENO, "\n", 1);
2641 errno = err;
2644 /* Return a struct timeval that is roughly equivalent to T.
2645 Use the least timeval not less than T.
2646 Return an extremal value if the result would overflow. */
2647 struct timeval
2648 make_timeval (struct timespec t)
2650 struct timeval tv;
2651 tv.tv_sec = t.tv_sec;
2652 tv.tv_usec = t.tv_nsec / 1000;
2654 if (t.tv_nsec % 1000 != 0)
2656 if (tv.tv_usec < 999999)
2657 tv.tv_usec++;
2658 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2660 tv.tv_sec++;
2661 tv.tv_usec = 0;
2665 return tv;
2668 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2669 ATIME and MTIME, respectively.
2670 FD must be either negative -- in which case it is ignored --
2671 or a file descriptor that is open on FILE.
2672 If FD is nonnegative, then FILE can be NULL. */
2674 set_file_times (int fd, const char *filename,
2675 struct timespec atime, struct timespec mtime)
2677 struct timespec timespec[2];
2678 timespec[0] = atime;
2679 timespec[1] = mtime;
2680 return fdutimens (fd, filename, timespec);
2683 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2684 This is like renameat except that it fails if DST already exists,
2685 or if this operation is not supported atomically. Return 0 if
2686 successful, -1 (setting errno) otherwise. */
2688 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2690 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2691 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2692 #elif defined CYGWIN && defined RENAME_NOREPLACE
2693 return renameat2 (srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2694 #elif defined RENAME_EXCL
2695 return renameatx_np (srcfd, src, dstfd, dst, RENAME_EXCL);
2696 #else
2697 # ifdef WINDOWSNT
2698 if (srcfd == AT_FDCWD && dstfd == AT_FDCWD)
2699 return sys_rename_replace (src, dst, 0);
2700 # endif
2701 errno = ENOSYS;
2702 return -1;
2703 #endif
2706 /* Like strsignal, except async-signal-safe, and this function typically
2707 returns a string in the C locale rather than the current locale. */
2708 char const *
2709 safe_strsignal (int code)
2711 char const *signame = 0;
2713 if (0 <= code && code < sys_siglist_entries)
2714 signame = sys_siglist[code];
2715 if (! signame)
2716 signame = "Unknown signal";
2718 return signame;
2721 #ifndef DOS_NT
2722 /* For make-serial-process */
2724 serial_open (Lisp_Object port)
2726 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2727 if (fd < 0)
2728 report_file_error ("Opening serial port", port);
2729 #ifdef TIOCEXCL
2730 ioctl (fd, TIOCEXCL, (char *) 0);
2731 #endif
2733 return fd;
2736 #if !defined (HAVE_CFMAKERAW)
2737 /* Workaround for targets which are missing cfmakeraw. */
2738 /* Pasted from man page. */
2739 static void
2740 cfmakeraw (struct termios *termios_p)
2742 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2743 termios_p->c_oflag &= ~OPOST;
2744 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2745 termios_p->c_cflag &= ~(CSIZE|PARENB);
2746 termios_p->c_cflag |= CS8;
2748 #endif /* !defined (HAVE_CFMAKERAW */
2750 #if !defined (HAVE_CFSETSPEED)
2751 /* Workaround for targets which are missing cfsetspeed. */
2752 static int
2753 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2755 return (cfsetispeed (termios_p, vitesse)
2756 + cfsetospeed (termios_p, vitesse));
2758 #endif
2760 /* For serial-process-configure */
2761 void
2762 serial_configure (struct Lisp_Process *p,
2763 Lisp_Object contact)
2765 Lisp_Object childp2 = Qnil;
2766 Lisp_Object tem = Qnil;
2767 struct termios attr;
2768 int err;
2769 char summary[4] = "???"; /* This usually becomes "8N1". */
2771 childp2 = Fcopy_sequence (p->childp);
2773 /* Read port attributes and prepare default configuration. */
2774 err = tcgetattr (p->outfd, &attr);
2775 if (err != 0)
2776 report_file_error ("Failed tcgetattr", Qnil);
2777 cfmakeraw (&attr);
2778 #if defined (CLOCAL)
2779 attr.c_cflag |= CLOCAL;
2780 #endif
2781 #if defined (CREAD)
2782 attr.c_cflag |= CREAD;
2783 #endif
2785 /* Configure speed. */
2786 if (!NILP (Fplist_member (contact, QCspeed)))
2787 tem = Fplist_get (contact, QCspeed);
2788 else
2789 tem = Fplist_get (p->childp, QCspeed);
2790 CHECK_NUMBER (tem);
2791 err = cfsetspeed (&attr, XINT (tem));
2792 if (err != 0)
2793 report_file_error ("Failed cfsetspeed", tem);
2794 childp2 = Fplist_put (childp2, QCspeed, tem);
2796 /* Configure bytesize. */
2797 if (!NILP (Fplist_member (contact, QCbytesize)))
2798 tem = Fplist_get (contact, QCbytesize);
2799 else
2800 tem = Fplist_get (p->childp, QCbytesize);
2801 if (NILP (tem))
2802 tem = make_number (8);
2803 CHECK_NUMBER (tem);
2804 if (XINT (tem) != 7 && XINT (tem) != 8)
2805 error (":bytesize must be nil (8), 7, or 8");
2806 summary[0] = XINT (tem) + '0';
2807 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2808 attr.c_cflag &= ~CSIZE;
2809 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2810 #else
2811 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2812 if (XINT (tem) != 8)
2813 error ("Bytesize cannot be changed");
2814 #endif
2815 childp2 = Fplist_put (childp2, QCbytesize, tem);
2817 /* Configure parity. */
2818 if (!NILP (Fplist_member (contact, QCparity)))
2819 tem = Fplist_get (contact, QCparity);
2820 else
2821 tem = Fplist_get (p->childp, QCparity);
2822 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2823 error (":parity must be nil (no parity), `even', or `odd'");
2824 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2825 attr.c_cflag &= ~(PARENB | PARODD);
2826 attr.c_iflag &= ~(IGNPAR | INPCK);
2827 if (NILP (tem))
2829 summary[1] = 'N';
2831 else if (EQ (tem, Qeven))
2833 summary[1] = 'E';
2834 attr.c_cflag |= PARENB;
2835 attr.c_iflag |= (IGNPAR | INPCK);
2837 else if (EQ (tem, Qodd))
2839 summary[1] = 'O';
2840 attr.c_cflag |= (PARENB | PARODD);
2841 attr.c_iflag |= (IGNPAR | INPCK);
2843 #else
2844 /* Don't error on no parity, which should be set by cfmakeraw. */
2845 if (!NILP (tem))
2846 error ("Parity cannot be configured");
2847 #endif
2848 childp2 = Fplist_put (childp2, QCparity, tem);
2850 /* Configure stopbits. */
2851 if (!NILP (Fplist_member (contact, QCstopbits)))
2852 tem = Fplist_get (contact, QCstopbits);
2853 else
2854 tem = Fplist_get (p->childp, QCstopbits);
2855 if (NILP (tem))
2856 tem = make_number (1);
2857 CHECK_NUMBER (tem);
2858 if (XINT (tem) != 1 && XINT (tem) != 2)
2859 error (":stopbits must be nil (1 stopbit), 1, or 2");
2860 summary[2] = XINT (tem) + '0';
2861 #if defined (CSTOPB)
2862 attr.c_cflag &= ~CSTOPB;
2863 if (XINT (tem) == 2)
2864 attr.c_cflag |= CSTOPB;
2865 #else
2866 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2867 if (XINT (tem) != 1)
2868 error ("Stopbits cannot be configured");
2869 #endif
2870 childp2 = Fplist_put (childp2, QCstopbits, tem);
2872 /* Configure flowcontrol. */
2873 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2874 tem = Fplist_get (contact, QCflowcontrol);
2875 else
2876 tem = Fplist_get (p->childp, QCflowcontrol);
2877 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2878 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2879 #if defined (CRTSCTS)
2880 attr.c_cflag &= ~CRTSCTS;
2881 #endif
2882 #if defined (CNEW_RTSCTS)
2883 attr.c_cflag &= ~CNEW_RTSCTS;
2884 #endif
2885 #if defined (IXON) && defined (IXOFF)
2886 attr.c_iflag &= ~(IXON | IXOFF);
2887 #endif
2888 if (NILP (tem))
2890 /* Already configured. */
2892 else if (EQ (tem, Qhw))
2894 #if defined (CRTSCTS)
2895 attr.c_cflag |= CRTSCTS;
2896 #elif defined (CNEW_RTSCTS)
2897 attr.c_cflag |= CNEW_RTSCTS;
2898 #else
2899 error ("Hardware flowcontrol (RTS/CTS) not supported");
2900 #endif
2902 else if (EQ (tem, Qsw))
2904 #if defined (IXON) && defined (IXOFF)
2905 attr.c_iflag |= (IXON | IXOFF);
2906 #else
2907 error ("Software flowcontrol (XON/XOFF) not supported");
2908 #endif
2910 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2912 /* Activate configuration. */
2913 err = tcsetattr (p->outfd, TCSANOW, &attr);
2914 if (err != 0)
2915 report_file_error ("Failed tcsetattr", Qnil);
2917 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2918 pset_childp (p, childp2);
2920 #endif /* not DOS_NT */
2922 /* System depended enumeration of and access to system processes a-la ps(1). */
2924 #ifdef HAVE_PROCFS
2926 /* Process enumeration and access via /proc. */
2928 Lisp_Object
2929 list_system_processes (void)
2931 Lisp_Object procdir, match, proclist, next;
2932 Lisp_Object tail;
2934 /* For every process on the system, there's a directory in the
2935 "/proc" pseudo-directory whose name is the numeric ID of that
2936 process. */
2937 procdir = build_string ("/proc");
2938 match = build_string ("[0-9]+");
2939 proclist = directory_files_internal (procdir, Qnil, match, Qt, false, Qnil);
2941 /* `proclist' gives process IDs as strings. Destructively convert
2942 each string into a number. */
2943 for (tail = proclist; CONSP (tail); tail = next)
2945 next = XCDR (tail);
2946 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2949 /* directory_files_internal returns the files in reverse order; undo
2950 that. */
2951 proclist = Fnreverse (proclist);
2952 return proclist;
2955 #elif defined DARWIN_OS || defined __FreeBSD__
2957 Lisp_Object
2958 list_system_processes (void)
2960 #ifdef DARWIN_OS
2961 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2962 #else
2963 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2964 #endif
2965 size_t len;
2966 struct kinfo_proc *procs;
2967 size_t i;
2969 Lisp_Object proclist = Qnil;
2971 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2972 return proclist;
2974 procs = xmalloc (len);
2975 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2977 xfree (procs);
2978 return proclist;
2981 len /= sizeof (struct kinfo_proc);
2982 for (i = 0; i < len; i++)
2984 #ifdef DARWIN_OS
2985 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2986 #else
2987 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2988 #endif
2991 xfree (procs);
2993 return proclist;
2996 /* The WINDOWSNT implementation is in w32.c.
2997 The MSDOS implementation is in dosfns.c. */
2998 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3000 Lisp_Object
3001 list_system_processes (void)
3003 return Qnil;
3006 #endif /* !defined (WINDOWSNT) */
3008 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3009 static struct timespec
3010 time_from_jiffies (unsigned long long tval, long hz)
3012 unsigned long long s = tval / hz;
3013 unsigned long long frac = tval % hz;
3014 int ns;
3016 if (TYPE_MAXIMUM (time_t) < s)
3017 time_overflow ();
3018 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
3019 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
3020 ns = frac * TIMESPEC_RESOLUTION / hz;
3021 else
3023 /* This is reachable only in the unlikely case that HZ * HZ
3024 exceeds ULLONG_MAX. It calculates an approximation that is
3025 guaranteed to be in range. */
3026 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
3027 + (hz % TIMESPEC_RESOLUTION != 0));
3028 ns = frac / hz_per_ns;
3031 return make_timespec (s, ns);
3034 static Lisp_Object
3035 ltime_from_jiffies (unsigned long long tval, long hz)
3037 struct timespec t = time_from_jiffies (tval, hz);
3038 return make_lisp_time (t);
3041 static struct timespec
3042 get_up_time (void)
3044 FILE *fup;
3045 struct timespec up = make_timespec (0, 0);
3047 block_input ();
3048 fup = emacs_fopen ("/proc/uptime", "r");
3050 if (fup)
3052 unsigned long long upsec, upfrac, idlesec, idlefrac;
3053 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
3055 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
3056 &upsec, &upfrac_start, &upfrac, &upfrac_end,
3057 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
3058 == 4)
3060 if (TYPE_MAXIMUM (time_t) < upsec)
3062 upsec = TYPE_MAXIMUM (time_t);
3063 upfrac = TIMESPEC_RESOLUTION - 1;
3065 else
3067 int upfraclen = upfrac_end - upfrac_start;
3068 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
3069 upfrac *= 10;
3070 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
3071 upfrac /= 10;
3072 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
3074 up = make_timespec (upsec, upfrac);
3076 fclose (fup);
3078 unblock_input ();
3080 return up;
3083 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3084 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3086 static Lisp_Object
3087 procfs_ttyname (int rdev)
3089 FILE *fdev;
3090 char name[PATH_MAX];
3092 block_input ();
3093 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3094 name[0] = 0;
3096 if (fdev)
3098 unsigned major;
3099 unsigned long minor_beg, minor_end;
3100 char minor[25]; /* 2 32-bit numbers + dash */
3101 char *endp;
3103 for (; !feof_unlocked (fdev) && !ferror_unlocked (fdev); name[0] = 0)
3105 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3106 && major == MAJOR (rdev))
3108 minor_beg = strtoul (minor, &endp, 0);
3109 if (*endp == '\0')
3110 minor_end = minor_beg;
3111 else if (*endp == '-')
3112 minor_end = strtoul (endp + 1, &endp, 0);
3113 else
3114 continue;
3116 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3118 sprintf (name + strlen (name), "%u", MINOR (rdev));
3119 break;
3123 fclose (fdev);
3125 unblock_input ();
3126 return build_string (name);
3129 static uintmax_t
3130 procfs_get_total_memory (void)
3132 FILE *fmem;
3133 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3134 int c;
3136 block_input ();
3137 fmem = emacs_fopen ("/proc/meminfo", "r");
3139 if (fmem)
3141 uintmax_t entry_value;
3142 bool done;
3145 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3147 case 1:
3148 retval = entry_value;
3149 done = 1;
3150 break;
3152 case 0:
3153 while ((c = getc_unlocked (fmem)) != EOF && c != '\n')
3154 continue;
3155 done = c == EOF;
3156 break;
3158 default:
3159 done = 1;
3160 break;
3162 while (!done);
3164 fclose (fmem);
3166 unblock_input ();
3167 return retval;
3170 Lisp_Object
3171 system_process_attributes (Lisp_Object pid)
3173 char procfn[PATH_MAX], fn[PATH_MAX];
3174 struct stat st;
3175 struct passwd *pw;
3176 struct group *gr;
3177 long clocks_per_sec;
3178 char *procfn_end;
3179 char procbuf[1025], *p, *q;
3180 int fd;
3181 ssize_t nread;
3182 static char const default_cmd[] = "???";
3183 const char *cmd = default_cmd;
3184 int cmdsize = sizeof default_cmd - 1;
3185 char *cmdline = NULL;
3186 ptrdiff_t cmdline_size;
3187 char c;
3188 printmax_t proc_id;
3189 int ppid, pgrp, sess, tty, tpgid, thcount;
3190 uid_t uid;
3191 gid_t gid;
3192 unsigned long long u_time, s_time, cutime, cstime, start;
3193 long priority, niceness, rss;
3194 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3195 struct timespec tnow, tstart, tboot, telapsed, us_time;
3196 double pcpu, pmem;
3197 Lisp_Object attrs = Qnil;
3198 Lisp_Object decoded_cmd;
3199 ptrdiff_t count;
3201 CHECK_NUMBER_OR_FLOAT (pid);
3202 CONS_TO_INTEGER (pid, pid_t, proc_id);
3203 sprintf (procfn, "/proc/%"pMd, proc_id);
3204 if (stat (procfn, &st) < 0)
3205 return attrs;
3207 /* euid egid */
3208 uid = st.st_uid;
3209 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3210 block_input ();
3211 pw = getpwuid (uid);
3212 unblock_input ();
3213 if (pw)
3214 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3216 gid = st.st_gid;
3217 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3218 block_input ();
3219 gr = getgrgid (gid);
3220 unblock_input ();
3221 if (gr)
3222 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3224 count = SPECPDL_INDEX ();
3225 strcpy (fn, procfn);
3226 procfn_end = fn + strlen (fn);
3227 strcpy (procfn_end, "/stat");
3228 fd = emacs_open (fn, O_RDONLY, 0);
3229 if (fd < 0)
3230 nread = 0;
3231 else
3233 record_unwind_protect_int (close_file_unwind, fd);
3234 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3236 if (0 < nread)
3238 procbuf[nread] = '\0';
3239 p = procbuf;
3241 p = strchr (p, '(');
3242 if (p != NULL)
3244 q = strrchr (p + 1, ')');
3245 /* comm */
3246 if (q != NULL)
3248 cmd = p + 1;
3249 cmdsize = q - cmd;
3252 else
3253 q = NULL;
3254 /* Command name is encoded in locale-coding-system; decode it. */
3255 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3256 decoded_cmd = code_convert_string_norecord (cmd_str,
3257 Vlocale_coding_system, 0);
3258 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3260 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3261 utime stime cutime cstime priority nice thcount . start vsize rss */
3262 if (q
3263 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3264 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3265 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3266 &minflt, &cminflt, &majflt, &cmajflt,
3267 &u_time, &s_time, &cutime, &cstime,
3268 &priority, &niceness, &thcount, &start, &vsize, &rss)
3269 == 20))
3271 char state_str[2];
3272 state_str[0] = c;
3273 state_str[1] = '\0';
3274 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3275 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3276 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3277 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3278 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3279 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3280 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3281 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3282 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3283 attrs);
3284 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3285 attrs);
3286 clocks_per_sec = sysconf (_SC_CLK_TCK);
3287 if (clocks_per_sec < 0)
3288 clocks_per_sec = 100;
3289 attrs = Fcons (Fcons (Qutime,
3290 ltime_from_jiffies (u_time, clocks_per_sec)),
3291 attrs);
3292 attrs = Fcons (Fcons (Qstime,
3293 ltime_from_jiffies (s_time, clocks_per_sec)),
3294 attrs);
3295 attrs = Fcons (Fcons (Qtime,
3296 ltime_from_jiffies (s_time + u_time,
3297 clocks_per_sec)),
3298 attrs);
3299 attrs = Fcons (Fcons (Qcutime,
3300 ltime_from_jiffies (cutime, clocks_per_sec)),
3301 attrs);
3302 attrs = Fcons (Fcons (Qcstime,
3303 ltime_from_jiffies (cstime, clocks_per_sec)),
3304 attrs);
3305 attrs = Fcons (Fcons (Qctime,
3306 ltime_from_jiffies (cstime + cutime,
3307 clocks_per_sec)),
3308 attrs);
3309 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3310 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3311 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3312 attrs);
3313 tnow = current_timespec ();
3314 telapsed = get_up_time ();
3315 tboot = timespec_sub (tnow, telapsed);
3316 tstart = time_from_jiffies (start, clocks_per_sec);
3317 tstart = timespec_add (tboot, tstart);
3318 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3319 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3320 attrs);
3321 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3322 telapsed = timespec_sub (tnow, tstart);
3323 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3324 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3325 pcpu = timespectod (us_time) / timespectod (telapsed);
3326 if (pcpu > 1.0)
3327 pcpu = 1.0;
3328 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3329 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3330 if (pmem > 100)
3331 pmem = 100;
3332 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3335 unbind_to (count, Qnil);
3337 /* args */
3338 strcpy (procfn_end, "/cmdline");
3339 fd = emacs_open (fn, O_RDONLY, 0);
3340 if (fd >= 0)
3342 ptrdiff_t readsize, nread_incr;
3343 record_unwind_protect_int (close_file_unwind, fd);
3344 record_unwind_protect_nothing ();
3345 nread = cmdline_size = 0;
3349 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3350 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3352 /* Leave room even if every byte needs escaping below. */
3353 readsize = (cmdline_size >> 1) - nread;
3355 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3356 nread += max (0, nread_incr);
3358 while (nread_incr == readsize);
3360 if (nread)
3362 /* We don't want trailing null characters. */
3363 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3364 continue;
3366 /* Escape-quote whitespace and backslashes. */
3367 q = cmdline + cmdline_size;
3368 while (cmdline < p)
3370 char c = *--p;
3371 *--q = c ? c : ' ';
3372 if (c_isspace (c) || c == '\\')
3373 *--q = '\\';
3376 nread = cmdline + cmdline_size - q;
3379 if (!nread)
3381 nread = cmdsize + 2;
3382 cmdline_size = nread + 1;
3383 q = cmdline = xrealloc (cmdline, cmdline_size);
3384 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3385 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3387 /* Command line is encoded in locale-coding-system; decode it. */
3388 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3389 decoded_cmd = code_convert_string_norecord (cmd_str,
3390 Vlocale_coding_system, 0);
3391 unbind_to (count, Qnil);
3392 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3395 return attrs;
3398 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3400 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3401 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3402 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3403 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3404 #undef _FILE_OFFSET_BITS
3405 #else
3406 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3407 #endif
3409 #include <procfs.h>
3411 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3412 #define _FILE_OFFSET_BITS 64
3413 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3414 #endif
3415 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3417 Lisp_Object
3418 system_process_attributes (Lisp_Object pid)
3420 char procfn[PATH_MAX], fn[PATH_MAX];
3421 struct stat st;
3422 struct passwd *pw;
3423 struct group *gr;
3424 char *procfn_end;
3425 struct psinfo pinfo;
3426 int fd;
3427 ssize_t nread;
3428 printmax_t proc_id;
3429 uid_t uid;
3430 gid_t gid;
3431 Lisp_Object attrs = Qnil;
3432 Lisp_Object decoded_cmd;
3433 ptrdiff_t count;
3435 CHECK_NUMBER_OR_FLOAT (pid);
3436 CONS_TO_INTEGER (pid, pid_t, proc_id);
3437 sprintf (procfn, "/proc/%"pMd, proc_id);
3438 if (stat (procfn, &st) < 0)
3439 return attrs;
3441 /* euid egid */
3442 uid = st.st_uid;
3443 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3444 block_input ();
3445 pw = getpwuid (uid);
3446 unblock_input ();
3447 if (pw)
3448 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3450 gid = st.st_gid;
3451 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3452 block_input ();
3453 gr = getgrgid (gid);
3454 unblock_input ();
3455 if (gr)
3456 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3458 count = SPECPDL_INDEX ();
3459 strcpy (fn, procfn);
3460 procfn_end = fn + strlen (fn);
3461 strcpy (procfn_end, "/psinfo");
3462 fd = emacs_open (fn, O_RDONLY, 0);
3463 if (fd < 0)
3464 nread = 0;
3465 else
3467 record_unwind_protect_int (close_file_unwind, fd);
3468 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3471 if (nread == sizeof pinfo)
3473 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3474 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3475 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3478 char state_str[2];
3479 state_str[0] = pinfo.pr_lwp.pr_sname;
3480 state_str[1] = '\0';
3481 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3484 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3485 need to get a string from it. */
3487 /* FIXME: missing: Qtpgid */
3489 /* FIXME: missing:
3490 Qminflt
3491 Qmajflt
3492 Qcminflt
3493 Qcmajflt
3495 Qutime
3496 Qcutime
3497 Qstime
3498 Qcstime
3499 Are they available? */
3501 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3502 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3503 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3504 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3505 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3506 attrs);
3508 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3509 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3510 attrs);
3511 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3512 attrs);
3514 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3515 range 0 .. 2**15, representing 0.0 .. 1.0. */
3516 attrs = Fcons (Fcons (Qpcpu,
3517 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3518 attrs);
3519 attrs = Fcons (Fcons (Qpmem,
3520 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3521 attrs);
3523 AUTO_STRING (fname, pinfo.pr_fname);
3524 decoded_cmd = code_convert_string_norecord (fname,
3525 Vlocale_coding_system, 0);
3526 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3527 AUTO_STRING (psargs, pinfo.pr_psargs);
3528 decoded_cmd = code_convert_string_norecord (psargs,
3529 Vlocale_coding_system, 0);
3530 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3532 unbind_to (count, Qnil);
3533 return attrs;
3536 #elif defined __FreeBSD__
3538 static struct timespec
3539 timeval_to_timespec (struct timeval t)
3541 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3544 static Lisp_Object
3545 make_lisp_timeval (struct timeval t)
3547 return make_lisp_time (timeval_to_timespec (t));
3550 Lisp_Object
3551 system_process_attributes (Lisp_Object pid)
3553 int proc_id;
3554 int pagesize = getpagesize ();
3555 unsigned long npages;
3556 int fscale;
3557 struct passwd *pw;
3558 struct group *gr;
3559 char *ttyname;
3560 size_t len;
3561 char args[MAXPATHLEN];
3562 struct timespec t, now;
3564 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3565 struct kinfo_proc proc;
3566 size_t proclen = sizeof proc;
3568 Lisp_Object attrs = Qnil;
3569 Lisp_Object decoded_comm;
3571 CHECK_NUMBER_OR_FLOAT (pid);
3572 CONS_TO_INTEGER (pid, int, proc_id);
3573 mib[3] = proc_id;
3575 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3576 return attrs;
3578 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3580 block_input ();
3581 pw = getpwuid (proc.ki_uid);
3582 unblock_input ();
3583 if (pw)
3584 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3586 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3588 block_input ();
3589 gr = getgrgid (proc.ki_svgid);
3590 unblock_input ();
3591 if (gr)
3592 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3594 AUTO_STRING (comm, proc.ki_comm);
3595 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3597 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3599 char state[2] = {'\0', '\0'};
3600 switch (proc.ki_stat)
3602 case SRUN:
3603 state[0] = 'R';
3604 break;
3606 case SSLEEP:
3607 state[0] = 'S';
3608 break;
3610 case SLOCK:
3611 state[0] = 'D';
3612 break;
3614 case SZOMB:
3615 state[0] = 'Z';
3616 break;
3618 case SSTOP:
3619 state[0] = 'T';
3620 break;
3622 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3625 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3626 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3627 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3629 block_input ();
3630 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3631 unblock_input ();
3632 if (ttyname)
3633 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3635 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3636 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3637 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3638 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3639 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3641 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3642 attrs);
3643 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3644 attrs);
3645 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3646 timeval_to_timespec (proc.ki_rusage.ru_stime));
3647 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3649 attrs = Fcons (Fcons (Qcutime,
3650 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3651 attrs);
3652 attrs = Fcons (Fcons (Qcstime,
3653 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3654 attrs);
3655 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3656 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3657 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3659 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3660 attrs);
3661 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3662 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3663 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3664 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3665 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3666 attrs);
3668 now = current_timespec ();
3669 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3670 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3672 len = sizeof fscale;
3673 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3675 double pcpu;
3676 fixpt_t ccpu;
3677 len = sizeof ccpu;
3678 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3680 pcpu = (100.0 * proc.ki_pctcpu / fscale
3681 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3682 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3686 len = sizeof npages;
3687 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3689 double pmem = (proc.ki_flag & P_INMEM
3690 ? 100.0 * proc.ki_rssize / npages
3691 : 0);
3692 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3695 mib[2] = KERN_PROC_ARGS;
3696 len = MAXPATHLEN;
3697 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3699 int i;
3700 for (i = 0; i < len; i++)
3702 if (! args[i] && i < len - 1)
3703 args[i] = ' ';
3706 AUTO_STRING (comm, args);
3707 decoded_comm = code_convert_string_norecord (comm,
3708 Vlocale_coding_system, 0);
3710 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3713 return attrs;
3716 #elif defined DARWIN_OS
3718 static struct timespec
3719 timeval_to_timespec (struct timeval t)
3721 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3724 static Lisp_Object
3725 make_lisp_timeval (struct timeval t)
3727 return make_lisp_time (timeval_to_timespec (t));
3730 Lisp_Object
3731 system_process_attributes (Lisp_Object pid)
3733 int proc_id;
3734 struct passwd *pw;
3735 struct group *gr;
3736 char *ttyname;
3737 struct timeval starttime;
3738 struct timespec t, now;
3739 struct rusage *rusage;
3740 dev_t tdev;
3741 uid_t uid;
3742 gid_t gid;
3744 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3745 struct kinfo_proc proc;
3746 size_t proclen = sizeof proc;
3748 Lisp_Object attrs = Qnil;
3749 Lisp_Object decoded_comm;
3751 CHECK_NUMBER_OR_FLOAT (pid);
3752 CONS_TO_INTEGER (pid, int, proc_id);
3753 mib[3] = proc_id;
3755 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3756 return attrs;
3758 uid = proc.kp_eproc.e_ucred.cr_uid;
3759 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3761 block_input ();
3762 pw = getpwuid (uid);
3763 unblock_input ();
3764 if (pw)
3765 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3767 gid = proc.kp_eproc.e_pcred.p_svgid;
3768 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3770 block_input ();
3771 gr = getgrgid (gid);
3772 unblock_input ();
3773 if (gr)
3774 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3776 decoded_comm = (code_convert_string_norecord
3777 (build_unibyte_string (proc.kp_proc.p_comm),
3778 Vlocale_coding_system, 0));
3780 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3782 char state[2] = {'\0', '\0'};
3783 switch (proc.kp_proc.p_stat)
3785 case SRUN:
3786 state[0] = 'R';
3787 break;
3789 case SSLEEP:
3790 state[0] = 'S';
3791 break;
3793 case SZOMB:
3794 state[0] = 'Z';
3795 break;
3797 case SSTOP:
3798 state[0] = 'T';
3799 break;
3801 case SIDL:
3802 state[0] = 'I';
3803 break;
3805 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3808 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3809 attrs);
3810 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3811 attrs);
3813 tdev = proc.kp_eproc.e_tdev;
3814 block_input ();
3815 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3816 unblock_input ();
3817 if (ttyname)
3818 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3820 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3821 attrs);
3823 rusage = proc.kp_proc.p_ru;
3824 if (rusage)
3826 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3827 attrs);
3828 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3829 attrs);
3831 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3832 attrs);
3833 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3834 attrs);
3835 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3836 timeval_to_timespec (rusage->ru_stime));
3837 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3840 starttime = proc.kp_proc.p_starttime;
3841 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3842 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3844 now = current_timespec ();
3845 t = timespec_sub (now, timeval_to_timespec (starttime));
3846 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3848 return attrs;
3851 /* The WINDOWSNT implementation is in w32.c.
3852 The MSDOS implementation is in dosfns.c. */
3853 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3855 Lisp_Object
3856 system_process_attributes (Lisp_Object pid)
3858 return Qnil;
3861 #endif /* !defined (WINDOWSNT) */
3863 /* Wide character string collation. */
3865 #ifdef __STDC_ISO_10646__
3866 # include <wchar.h>
3867 # include <wctype.h>
3869 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3870 # include <locale.h>
3871 # endif
3872 # ifndef LC_COLLATE
3873 # define LC_COLLATE 0
3874 # endif
3875 # ifndef LC_COLLATE_MASK
3876 # define LC_COLLATE_MASK 0
3877 # endif
3878 # ifndef LC_CTYPE
3879 # define LC_CTYPE 0
3880 # endif
3881 # ifndef LC_CTYPE_MASK
3882 # define LC_CTYPE_MASK 0
3883 # endif
3885 # ifndef HAVE_NEWLOCALE
3886 # undef freelocale
3887 # undef locale_t
3888 # undef newlocale
3889 # undef wcscoll_l
3890 # undef towlower_l
3891 # define freelocale emacs_freelocale
3892 # define locale_t emacs_locale_t
3893 # define newlocale emacs_newlocale
3894 # define wcscoll_l emacs_wcscoll_l
3895 # define towlower_l emacs_towlower_l
3897 typedef char const *locale_t;
3899 static locale_t
3900 newlocale (int category_mask, char const *locale, locale_t loc)
3902 return locale;
3905 static void
3906 freelocale (locale_t loc)
3910 static char *
3911 emacs_setlocale (int category, char const *locale)
3913 # ifdef HAVE_SETLOCALE
3914 errno = 0;
3915 char *loc = setlocale (category, locale);
3916 if (loc || errno)
3917 return loc;
3918 errno = EINVAL;
3919 # else
3920 errno = ENOTSUP;
3921 # endif
3922 return 0;
3925 static int
3926 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3928 int result = 0;
3929 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3930 int err;
3932 if (! oldloc)
3933 err = errno;
3934 else
3936 USE_SAFE_ALLOCA;
3937 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3938 strcpy (oldcopy, oldloc);
3939 if (! emacs_setlocale (LC_COLLATE, loc))
3940 err = errno;
3941 else
3943 errno = 0;
3944 result = wcscoll (a, b);
3945 err = errno;
3946 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3947 err = errno;
3949 SAFE_FREE ();
3952 errno = err;
3953 return result;
3956 static wint_t
3957 towlower_l (wint_t wc, locale_t loc)
3959 wint_t result = wc;
3960 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3962 if (oldloc)
3964 USE_SAFE_ALLOCA;
3965 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3966 strcpy (oldcopy, oldloc);
3967 if (emacs_setlocale (LC_CTYPE, loc))
3969 result = towlower (wc);
3970 emacs_setlocale (LC_COLLATE, oldcopy);
3972 SAFE_FREE ();
3975 return result;
3977 # endif
3980 str_collate (Lisp_Object s1, Lisp_Object s2,
3981 Lisp_Object locale, Lisp_Object ignore_case)
3983 int res, err;
3984 ptrdiff_t len, i, i_byte;
3985 wchar_t *p1, *p2;
3987 USE_SAFE_ALLOCA;
3989 /* Convert byte stream to code points. */
3990 len = SCHARS (s1); i = i_byte = 0;
3991 SAFE_NALLOCA (p1, 1, len + 1);
3992 while (i < len)
3993 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3994 *(p1+len) = 0;
3996 len = SCHARS (s2); i = i_byte = 0;
3997 SAFE_NALLOCA (p2, 1, len + 1);
3998 while (i < len)
3999 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
4000 *(p2+len) = 0;
4002 if (STRINGP (locale))
4004 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
4005 SSDATA (locale), 0);
4006 if (!loc)
4007 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4009 if (! NILP (ignore_case))
4010 for (int i = 1; i < 3; i++)
4012 wchar_t *p = (i == 1) ? p1 : p2;
4013 for (; *p; p++)
4014 *p = towlower_l (*p, loc);
4017 errno = 0;
4018 res = wcscoll_l (p1, p2, loc);
4019 err = errno;
4020 freelocale (loc);
4022 else
4024 if (! NILP (ignore_case))
4025 for (int i = 1; i < 3; i++)
4027 wchar_t *p = (i == 1) ? p1 : p2;
4028 for (; *p; p++)
4029 *p = towlower (*p);
4032 errno = 0;
4033 res = wcscoll (p1, p2);
4034 err = errno;
4036 # ifndef HAVE_NEWLOCALE
4037 if (err)
4038 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4039 # else
4040 if (err)
4041 error ("Invalid string for collation: %s", emacs_strerror (err));
4042 # endif
4044 SAFE_FREE ();
4045 return res;
4047 #endif /* __STDC_ISO_10646__ */
4049 #ifdef WINDOWSNT
4051 str_collate (Lisp_Object s1, Lisp_Object s2,
4052 Lisp_Object locale, Lisp_Object ignore_case)
4055 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4056 int res, err = errno;
4058 errno = 0;
4059 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4060 if (errno)
4061 error ("Invalid string for collation: %s", strerror (errno));
4063 errno = err;
4064 return res;
4066 #endif /* WINDOWSNT */