Minimize spurious diffs from master.
[emacs.git] / src / sysdep.c
blobedc3f05ab2b4d45cd3dfaef8973b16aabecf0f8f
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2016 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <execinfo.h>
23 #include "sysstdio.h"
24 #ifdef HAVE_PWD_H
25 #include <pwd.h>
26 #include <grp.h>
27 #endif /* HAVE_PWD_H */
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
33 #include <utimens.h>
35 #include "lisp.h"
36 #include "sheap.h"
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #if defined DARWIN_OS || defined __FreeBSD__
41 # include <sys/sysctl.h>
42 #endif
44 #ifdef __FreeBSD__
45 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
46 'struct frame', so rename it. */
47 # define frame freebsd_frame
48 # include <sys/user.h>
49 # undef frame
51 # include <math.h>
52 #endif
54 #ifdef HAVE_SOCKETS
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #endif /* HAVE_SOCKETS */
59 #ifdef TRY_AGAIN
60 #ifndef HAVE_H_ERRNO
61 extern int h_errno;
62 #endif
63 #endif /* TRY_AGAIN */
65 #ifdef WINDOWSNT
66 #define read sys_read
67 #define write sys_write
68 #ifndef STDERR_FILENO
69 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
70 #endif
71 #include "w32.h"
72 #endif /* not WINDOWSNT */
74 #include <sys/types.h>
75 #include <sys/stat.h>
76 #include <errno.h>
78 /* Get SI_SRPC_DOMAIN, if it is available. */
79 #ifdef HAVE_SYS_SYSTEMINFO_H
80 #include <sys/systeminfo.h>
81 #endif
83 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
84 #include "msdos.h"
85 #endif
87 #include <sys/param.h>
88 #include <sys/file.h>
89 #include <fcntl.h>
91 #include "systty.h"
92 #include "syswait.h"
94 #ifdef HAVE_SYS_UTSNAME_H
95 #include <sys/utsname.h>
96 #include <memory.h>
97 #endif /* HAVE_SYS_UTSNAME_H */
99 #include "keyboard.h"
100 #include "frame.h"
101 #include "termhooks.h"
102 #include "termchar.h"
103 #include "termopts.h"
104 #include "process.h"
105 #include "cm.h"
107 #include "gnutls.h"
108 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
109 do that during startup just to call gnutls_rnd. */
110 #if defined HAVE_GNUTLS && !defined WINDOWSNT
111 # include <gnutls/crypto.h>
112 #else
113 # define emacs_gnutls_global_init() Qnil
114 # define gnutls_rnd(level, data, len) (-1)
115 #endif
117 #ifdef WINDOWSNT
118 #include <direct.h>
119 /* In process.h which conflicts with the local copy. */
120 #define _P_WAIT 0
121 int _cdecl _spawnlp (int, const char *, const char *, ...);
122 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
123 several prototypes of functions called below. */
124 #include <sys/socket.h>
125 #endif
127 #include "syssignal.h"
128 #include "systime.h"
130 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
131 #ifndef ULLONG_MAX
132 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
133 #endif
135 /* Declare here, including term.h is problematic on some systems. */
136 extern void tputs (const char *, int, int (*)(int));
138 static const int baud_convert[] =
140 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
141 1800, 2400, 4800, 9600, 19200, 38400
144 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
145 # include <sys/personality.h>
147 /* Disable address randomization in the current process. Return true
148 if addresses were randomized but this has been disabled, false
149 otherwise. */
150 bool
151 disable_address_randomization (void)
153 bool disabled = false;
154 int pers = personality (0xffffffff);
155 disabled = (! (pers & ADDR_NO_RANDOMIZE)
156 && 0 <= personality (pers | ADDR_NO_RANDOMIZE));
157 return disabled;
159 #endif
161 /* Execute the program in FILE, with argument vector ARGV and environ
162 ENVP. Return an error number if unsuccessful. This is like execve
163 except it reenables ASLR in the executed program if necessary, and
164 on error it returns an error number rather than -1. */
166 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
168 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
169 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
170 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
171 if (change_personality)
172 personality (pers & ~ADDR_NO_RANDOMIZE);
173 #endif
175 execve (file, argv, envp);
176 int err = errno;
178 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
179 if (change_personality)
180 personality (pers);
181 #endif
183 return err;
186 /* If FD is not already open, arrange for it to be open with FLAGS. */
187 static void
188 force_open (int fd, int flags)
190 if (dup2 (fd, fd) < 0 && errno == EBADF)
192 int n = open (NULL_DEVICE, flags);
193 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
195 emacs_perror (NULL_DEVICE);
196 exit (EXIT_FAILURE);
201 /* Make sure stdin, stdout, and stderr are open to something, so that
202 their file descriptors are not hijacked by later system calls. */
203 void
204 init_standard_fds (void)
206 /* Open stdin for *writing*, and stdout and stderr for *reading*.
207 That way, any attempt to do normal I/O will result in an error,
208 just as if the files were closed, and the file descriptors will
209 not be reused by later opens. */
210 force_open (STDIN_FILENO, O_WRONLY);
211 force_open (STDOUT_FILENO, O_RDONLY);
212 force_open (STDERR_FILENO, O_RDONLY);
215 /* Return the current working directory. The result should be freed
216 with 'free'. Return NULL on errors. */
217 char *
218 emacs_get_current_dir_name (void)
220 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
221 # ifdef HYBRID_MALLOC
222 bool use_libc = bss_sbrk_did_unexec;
223 # else
224 bool use_libc = true;
225 # endif
226 if (use_libc)
227 return get_current_dir_name ();
228 # endif
230 char *buf;
231 char *pwd = getenv ("PWD");
232 struct stat dotstat, pwdstat;
233 /* If PWD is accurate, use it instead of calling getcwd. PWD is
234 sometimes a nicer name, and using it may avoid a fatal error if a
235 parent directory is searchable but not readable. */
236 if (pwd
237 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
238 && stat (pwd, &pwdstat) == 0
239 && stat (".", &dotstat) == 0
240 && dotstat.st_ino == pwdstat.st_ino
241 && dotstat.st_dev == pwdstat.st_dev
242 #ifdef MAXPATHLEN
243 && strlen (pwd) < MAXPATHLEN
244 #endif
247 buf = malloc (strlen (pwd) + 1);
248 if (!buf)
249 return NULL;
250 strcpy (buf, pwd);
252 else
254 size_t buf_size = 1024;
255 buf = malloc (buf_size);
256 if (!buf)
257 return NULL;
258 for (;;)
260 if (getcwd (buf, buf_size) == buf)
261 break;
262 if (errno != ERANGE)
264 int tmp_errno = errno;
265 free (buf);
266 errno = tmp_errno;
267 return NULL;
269 buf_size *= 2;
270 buf = realloc (buf, buf_size);
271 if (!buf)
272 return NULL;
275 return buf;
279 /* Discard pending input on all input descriptors. */
281 void
282 discard_tty_input (void)
284 #ifndef WINDOWSNT
285 struct emacs_tty buf;
287 if (noninteractive)
288 return;
290 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
291 while (dos_keyread () != -1)
293 #else /* not MSDOS */
295 struct tty_display_info *tty;
296 for (tty = tty_list; tty; tty = tty->next)
298 if (tty->input) /* Is the device suspended? */
300 emacs_get_tty (fileno (tty->input), &buf);
301 emacs_set_tty (fileno (tty->input), &buf, 0);
305 #endif /* not MSDOS */
306 #endif /* not WINDOWSNT */
310 #ifdef SIGTSTP
312 /* Arrange for character C to be read as the next input from
313 the terminal.
314 XXX What if we have multiple ttys?
317 void
318 stuff_char (char c)
320 if (! (FRAMEP (selected_frame)
321 && FRAME_LIVE_P (XFRAME (selected_frame))
322 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
323 return;
325 /* Should perhaps error if in batch mode */
326 #ifdef TIOCSTI
327 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
328 #else /* no TIOCSTI */
329 error ("Cannot stuff terminal input characters in this version of Unix");
330 #endif /* no TIOCSTI */
333 #endif /* SIGTSTP */
335 void
336 init_baud_rate (int fd)
338 int emacs_ospeed;
340 if (noninteractive)
341 emacs_ospeed = 0;
342 else
344 #ifdef DOS_NT
345 emacs_ospeed = 15;
346 #else /* not DOS_NT */
347 struct termios sg;
349 sg.c_cflag = B9600;
350 tcgetattr (fd, &sg);
351 emacs_ospeed = cfgetospeed (&sg);
352 #endif /* not DOS_NT */
355 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
356 ? baud_convert[emacs_ospeed] : 9600);
357 if (baud_rate == 0)
358 baud_rate = 1200;
363 #ifndef MSDOS
365 /* Wait for the subprocess with process id CHILD to terminate or change status.
366 CHILD must be a child process that has not been reaped.
367 If STATUS is non-null, store the waitpid-style exit status into *STATUS
368 and tell wait_reading_process_output that it needs to look around.
369 Use waitpid-style OPTIONS when waiting.
370 If INTERRUPTIBLE, this function is interruptible by a signal.
372 Return CHILD if successful, 0 if no status is available;
373 the latter is possible only when options & NOHANG. */
374 static pid_t
375 get_child_status (pid_t child, int *status, int options, bool interruptible)
377 pid_t pid;
379 /* Invoke waitpid only with a known process ID; do not invoke
380 waitpid with a nonpositive argument. Otherwise, Emacs might
381 reap an unwanted process by mistake. For example, invoking
382 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
383 so that another thread running glib won't find them. */
384 eassert (child > 0);
386 while ((pid = waitpid (child, status, options)) < 0)
388 /* Check that CHILD is a child process that has not been reaped,
389 and that STATUS and OPTIONS are valid. Otherwise abort,
390 as continuing after this internal error could cause Emacs to
391 become confused and kill innocent-victim processes. */
392 if (errno != EINTR)
393 emacs_abort ();
395 /* Note: the MS-Windows emulation of waitpid calls QUIT
396 internally. */
397 if (interruptible)
398 QUIT;
401 /* If successful and status is requested, tell wait_reading_process_output
402 that it needs to wake up and look around. */
403 if (pid && status && input_available_clear_time)
404 *input_available_clear_time = make_timespec (0, 0);
406 return pid;
409 /* Wait for the subprocess with process id CHILD to terminate.
410 CHILD must be a child process that has not been reaped.
411 If STATUS is non-null, store the waitpid-style exit status into *STATUS
412 and tell wait_reading_process_output that it needs to look around.
413 If INTERRUPTIBLE, this function is interruptible by a signal. */
414 void
415 wait_for_termination (pid_t child, int *status, bool interruptible)
417 get_child_status (child, status, 0, interruptible);
420 /* Report whether the subprocess with process id CHILD has changed status.
421 Termination counts as a change of status.
422 CHILD must be a child process that has not been reaped.
423 If STATUS is non-null, store the waitpid-style exit status into *STATUS
424 and tell wait_reading_process_output that it needs to look around.
425 Use waitpid-style OPTIONS to check status, but do not wait.
427 Return CHILD if successful, 0 if no status is available because
428 the process's state has not changed. */
429 pid_t
430 child_status_changed (pid_t child, int *status, int options)
432 return get_child_status (child, status, WNOHANG | options, 0);
436 /* Set up the terminal at the other end of a pseudo-terminal that
437 we will be controlling an inferior through.
438 It should not echo or do line-editing, since that is done
439 in Emacs. No padding needed for insertion into an Emacs buffer. */
441 void
442 child_setup_tty (int out)
444 #ifndef WINDOWSNT
445 struct emacs_tty s;
447 emacs_get_tty (out, &s);
448 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
449 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
450 #ifdef NLDLY
451 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
452 Some versions of GNU Hurd do not have FFDLY? */
453 #ifdef FFDLY
454 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
455 /* No output delays */
456 #else
457 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
458 /* No output delays */
459 #endif
460 #endif
461 s.main.c_lflag &= ~ECHO; /* Disable echo */
462 s.main.c_lflag |= ISIG; /* Enable signals */
463 #ifdef IUCLC
464 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
465 #endif
466 #ifdef ISTRIP
467 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
468 #endif
469 #ifdef OLCUC
470 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
471 #endif
472 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
473 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
474 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
475 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
477 #ifdef HPUX
478 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
479 #endif /* HPUX */
481 #ifdef SIGNALS_VIA_CHARACTERS
482 /* the QUIT and INTR character are used in process_send_signal
483 so set them here to something useful. */
484 if (s.main.c_cc[VQUIT] == CDISABLE)
485 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
486 if (s.main.c_cc[VINTR] == CDISABLE)
487 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
488 #endif /* not SIGNALS_VIA_CHARACTERS */
490 #ifdef AIX
491 /* Also, PTY overloads NUL and BREAK.
492 don't ignore break, but don't signal either, so it looks like NUL. */
493 s.main.c_iflag &= ~IGNBRK;
494 s.main.c_iflag &= ~BRKINT;
495 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
496 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
497 would force it to 0377. That looks like duplicated code. */
498 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
499 #endif /* AIX */
501 /* We originally enabled ICANON (and set VEOF to 04), and then had
502 process.c send additional EOF chars to flush the output when faced
503 with long lines, but this leads to weird effects when the
504 subprocess has disabled ICANON and ends up seeing those spurious
505 extra EOFs. So we don't send EOFs any more in
506 process.c:send_process. First we tried to disable ICANON by
507 default, so if a subsprocess sets up ICANON, it's his problem (or
508 the Elisp package that talks to it) to deal with lines that are
509 too long. But this disables some features, such as the ability
510 to send EOF signals. So we re-enabled ICANON but there is no
511 more "send eof to flush" going on (which is wrong and unportable
512 in itself). The correct way to handle too much output is to
513 buffer what could not be written and then write it again when
514 select returns ok for writing. This has it own set of
515 problems. Write is now asynchronous, is that a problem? How much
516 do we buffer, and what do we do when that limit is reached? */
518 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
519 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
520 #if 0 /* These settings only apply to non-ICANON mode. */
521 s.main.c_cc[VMIN] = 1;
522 s.main.c_cc[VTIME] = 0;
523 #endif
525 emacs_set_tty (out, &s, 0);
526 #endif /* not WINDOWSNT */
528 #endif /* not MSDOS */
531 /* Record a signal code and the action for it. */
532 struct save_signal
534 int code;
535 struct sigaction action;
538 static void save_signal_handlers (struct save_signal *);
539 static void restore_signal_handlers (struct save_signal *);
541 /* Suspend the Emacs process; give terminal to its superior. */
543 void
544 sys_suspend (void)
546 #ifndef DOS_NT
547 kill (0, SIGTSTP);
548 #else
549 /* On a system where suspending is not implemented,
550 instead fork a subshell and let it talk directly to the terminal
551 while we wait. */
552 sys_subshell ();
554 #endif
557 /* Fork a subshell. */
559 void
560 sys_subshell (void)
562 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
563 #ifdef MSDOS
564 int st;
565 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
566 #else
567 char oldwd[MAX_UTF8_PATH];
568 #endif /* MSDOS */
569 #else /* !DOS_NT */
570 int status;
571 #endif
572 pid_t pid;
573 struct save_signal saved_handlers[5];
574 char *str = SSDATA (encode_current_directory ());
576 #ifdef DOS_NT
577 pid = 0;
578 #else
580 char *volatile str_volatile = str;
581 pid = vfork ();
582 str = str_volatile;
584 #endif
586 if (pid < 0)
587 error ("Can't spawn subshell");
589 saved_handlers[0].code = SIGINT;
590 saved_handlers[1].code = SIGQUIT;
591 saved_handlers[2].code = SIGTERM;
592 #ifdef USABLE_SIGIO
593 saved_handlers[3].code = SIGIO;
594 saved_handlers[4].code = 0;
595 #else
596 saved_handlers[3].code = 0;
597 #endif
599 #ifdef DOS_NT
600 save_signal_handlers (saved_handlers);
601 #endif
603 if (pid == 0)
605 const char *sh = 0;
607 #ifdef DOS_NT /* MW, Aug 1993 */
608 getcwd (oldwd, sizeof oldwd);
609 if (sh == 0)
610 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
611 #endif
612 if (sh == 0)
613 sh = egetenv ("SHELL");
614 if (sh == 0)
615 sh = "sh";
617 /* Use our buffer's default directory for the subshell. */
618 if (chdir (str) != 0)
620 #ifndef DOS_NT
621 emacs_perror (str);
622 _exit (EXIT_CANCELED);
623 #endif
626 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
628 char *epwd = getenv ("PWD");
629 char old_pwd[MAXPATHLEN+1+4];
631 /* If PWD is set, pass it with corrected value. */
632 if (epwd)
634 strcpy (old_pwd, epwd);
635 setenv ("PWD", str, 1);
637 st = system (sh);
638 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
639 if (epwd)
640 putenv (old_pwd); /* restore previous value */
642 #else /* not MSDOS */
643 #ifdef WINDOWSNT
644 /* Waits for process completion */
645 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
646 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
647 if (pid == -1)
648 write (1, "Can't execute subshell", 22);
649 #else /* not WINDOWSNT */
650 execlp (sh, sh, (char *) 0);
651 emacs_perror (sh);
652 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
653 #endif /* not WINDOWSNT */
654 #endif /* not MSDOS */
657 /* Do this now if we did not do it before. */
658 #ifndef MSDOS
659 save_signal_handlers (saved_handlers);
660 #endif
662 #ifndef DOS_NT
663 wait_for_termination (pid, &status, 0);
664 #endif
665 restore_signal_handlers (saved_handlers);
668 static void
669 save_signal_handlers (struct save_signal *saved_handlers)
671 while (saved_handlers->code)
673 struct sigaction action;
674 emacs_sigaction_init (&action, SIG_IGN);
675 sigaction (saved_handlers->code, &action, &saved_handlers->action);
676 saved_handlers++;
680 static void
681 restore_signal_handlers (struct save_signal *saved_handlers)
683 while (saved_handlers->code)
685 sigaction (saved_handlers->code, &saved_handlers->action, 0);
686 saved_handlers++;
690 #ifdef USABLE_SIGIO
691 static int old_fcntl_flags[FD_SETSIZE];
692 #endif
694 void
695 init_sigio (int fd)
697 #ifdef USABLE_SIGIO
698 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
699 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
700 interrupts_deferred = 0;
701 #endif
704 #ifndef DOS_NT
705 static void
706 reset_sigio (int fd)
708 #ifdef USABLE_SIGIO
709 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
710 #endif
712 #endif
714 void
715 request_sigio (void)
717 #ifdef USABLE_SIGIO
718 sigset_t unblocked;
720 if (noninteractive)
721 return;
723 sigemptyset (&unblocked);
724 # ifdef SIGWINCH
725 sigaddset (&unblocked, SIGWINCH);
726 # endif
727 sigaddset (&unblocked, SIGIO);
728 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
730 interrupts_deferred = 0;
731 #endif
734 void
735 unrequest_sigio (void)
737 #ifdef USABLE_SIGIO
738 sigset_t blocked;
740 if (noninteractive)
741 return;
743 sigemptyset (&blocked);
744 # ifdef SIGWINCH
745 sigaddset (&blocked, SIGWINCH);
746 # endif
747 sigaddset (&blocked, SIGIO);
748 pthread_sigmask (SIG_BLOCK, &blocked, 0);
749 interrupts_deferred = 1;
750 #endif
753 #ifndef MSDOS
754 /* Block SIGCHLD. */
756 void
757 block_child_signal (sigset_t *oldset)
759 sigset_t blocked;
760 sigemptyset (&blocked);
761 sigaddset (&blocked, SIGCHLD);
762 sigaddset (&blocked, SIGINT);
763 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
766 /* Unblock SIGCHLD. */
768 void
769 unblock_child_signal (sigset_t const *oldset)
771 pthread_sigmask (SIG_SETMASK, oldset, 0);
774 #endif /* !MSDOS */
776 /* Saving and restoring the process group of Emacs's terminal. */
778 /* The process group of which Emacs was a member when it initially
779 started.
781 If Emacs was in its own process group (i.e. inherited_pgroup ==
782 getpid ()), then we know we're running under a shell with job
783 control (Emacs would never be run as part of a pipeline).
784 Everything is fine.
786 If Emacs was not in its own process group, then we know we're
787 running under a shell (or a caller) that doesn't know how to
788 separate itself from Emacs (like sh). Emacs must be in its own
789 process group in order to receive SIGIO correctly. In this
790 situation, we put ourselves in our own pgroup, forcibly set the
791 tty's pgroup to our pgroup, and make sure to restore and reinstate
792 the tty's pgroup just like any other terminal setting. If
793 inherited_group was not the tty's pgroup, then we'll get a
794 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
795 it goes foreground in the future, which is what should happen. */
797 static pid_t inherited_pgroup;
799 void
800 init_foreground_group (void)
802 pid_t pgrp = getpgrp ();
803 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
806 /* Block and unblock SIGTTOU. */
808 void
809 block_tty_out_signal (sigset_t *oldset)
811 #ifdef SIGTTOU
812 sigset_t blocked;
813 sigemptyset (&blocked);
814 sigaddset (&blocked, SIGTTOU);
815 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
816 #endif
819 void
820 unblock_tty_out_signal (sigset_t const *oldset)
822 #ifdef SIGTTOU
823 pthread_sigmask (SIG_SETMASK, oldset, 0);
824 #endif
827 /* Safely set a controlling terminal FD's process group to PGID.
828 If we are not in the foreground already, POSIX requires tcsetpgrp
829 to deliver a SIGTTOU signal, which would stop us. This is an
830 annoyance, so temporarily ignore the signal.
832 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
833 skip all this unless SIGTTOU is defined. */
834 static void
835 tcsetpgrp_without_stopping (int fd, pid_t pgid)
837 #ifdef SIGTTOU
838 sigset_t oldset;
839 block_input ();
840 block_tty_out_signal (&oldset);
841 tcsetpgrp (fd, pgid);
842 unblock_tty_out_signal (&oldset);
843 unblock_input ();
844 #endif
847 /* Split off the foreground process group to Emacs alone. When we are
848 in the foreground, but not started in our own process group,
849 redirect the tty device handle FD to point to our own process
850 group. FD must be the file descriptor of the controlling tty. */
851 static void
852 narrow_foreground_group (int fd)
854 if (inherited_pgroup && setpgid (0, 0) == 0)
855 tcsetpgrp_without_stopping (fd, getpid ());
858 /* Set the tty to our original foreground group. */
859 static void
860 widen_foreground_group (int fd)
862 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
863 tcsetpgrp_without_stopping (fd, inherited_pgroup);
866 /* Getting and setting emacs_tty structures. */
868 /* Set *TC to the parameters associated with the terminal FD,
869 or clear it if the parameters are not available.
870 Return 0 on success, -1 on failure. */
872 emacs_get_tty (int fd, struct emacs_tty *settings)
874 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
875 memset (&settings->main, 0, sizeof (settings->main));
876 #ifdef DOS_NT
877 #ifdef WINDOWSNT
878 HANDLE h = (HANDLE)_get_osfhandle (fd);
879 DWORD console_mode;
881 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
883 settings->main = console_mode;
884 return 0;
886 #endif /* WINDOWSNT */
887 return -1;
888 #else /* !DOS_NT */
889 /* We have those nifty POSIX tcmumbleattr functions. */
890 return tcgetattr (fd, &settings->main);
891 #endif
895 /* Set the parameters of the tty on FD according to the contents of
896 *SETTINGS. If FLUSHP, discard input.
897 Return 0 if all went well, and -1 (setting errno) if anything failed. */
900 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
902 /* Set the primary parameters - baud rate, character size, etcetera. */
903 #ifdef DOS_NT
904 #ifdef WINDOWSNT
905 HANDLE h = (HANDLE)_get_osfhandle (fd);
907 if (h && h != INVALID_HANDLE_VALUE)
909 DWORD new_mode;
911 /* Assume the handle is open for input. */
912 if (flushp)
913 FlushConsoleInputBuffer (h);
914 new_mode = settings->main;
915 SetConsoleMode (h, new_mode);
917 #endif /* WINDOWSNT */
918 #else /* !DOS_NT */
919 int i;
920 /* We have those nifty POSIX tcmumbleattr functions.
921 William J. Smith <wjs@wiis.wang.com> writes:
922 "POSIX 1003.1 defines tcsetattr to return success if it was
923 able to perform any of the requested actions, even if some
924 of the requested actions could not be performed.
925 We must read settings back to ensure tty setup properly.
926 AIX requires this to keep tty from hanging occasionally." */
927 /* This make sure that we don't loop indefinitely in here. */
928 for (i = 0 ; i < 10 ; i++)
929 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
931 if (errno == EINTR)
932 continue;
933 else
934 return -1;
936 else
938 struct termios new;
940 memset (&new, 0, sizeof (new));
941 /* Get the current settings, and see if they're what we asked for. */
942 tcgetattr (fd, &new);
943 /* We cannot use memcmp on the whole structure here because under
944 * aix386 the termios structure has some reserved field that may
945 * not be filled in.
947 if ( new.c_iflag == settings->main.c_iflag
948 && new.c_oflag == settings->main.c_oflag
949 && new.c_cflag == settings->main.c_cflag
950 && new.c_lflag == settings->main.c_lflag
951 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
952 break;
953 else
954 continue;
956 #endif
958 /* We have survived the tempest. */
959 return 0;
964 #ifdef F_SETOWN
965 static int old_fcntl_owner[FD_SETSIZE];
966 #endif /* F_SETOWN */
968 /* This may also be defined in stdio,
969 but if so, this does no harm,
970 and using the same name avoids wasting the other one's space. */
972 #if defined (USG)
973 unsigned char _sobuf[BUFSIZ+8];
974 #else
975 char _sobuf[BUFSIZ];
976 #endif
978 /* Initialize the terminal mode on all tty devices that are currently
979 open. */
981 void
982 init_all_sys_modes (void)
984 struct tty_display_info *tty;
985 for (tty = tty_list; tty; tty = tty->next)
986 init_sys_modes (tty);
989 /* Initialize the terminal mode on the given tty device. */
991 void
992 init_sys_modes (struct tty_display_info *tty_out)
994 struct emacs_tty tty;
995 #ifndef DOS_NT
996 Lisp_Object terminal;
997 #endif
999 Vtty_erase_char = Qnil;
1001 if (noninteractive)
1002 return;
1004 if (!tty_out->output)
1005 return; /* The tty is suspended. */
1007 narrow_foreground_group (fileno (tty_out->input));
1009 if (! tty_out->old_tty)
1010 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1012 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1014 tty = *tty_out->old_tty;
1016 #if !defined (DOS_NT)
1017 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1019 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1020 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1021 #ifdef INLCR /* I'm just being cautious,
1022 since I can't check how widespread INLCR is--rms. */
1023 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1024 #endif
1025 #ifdef ISTRIP
1026 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1027 #endif
1028 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1029 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1030 #ifdef IEXTEN
1031 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1032 #endif
1033 tty.main.c_lflag |= ISIG; /* Enable signals */
1034 if (tty_out->flow_control)
1036 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1037 #ifdef IXANY
1038 tty.main.c_iflag &= ~IXANY;
1039 #endif /* IXANY */
1041 else
1042 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1043 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1044 on output */
1045 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1046 #ifdef CS8
1047 if (tty_out->meta_key)
1049 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1050 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1052 #endif
1054 XSETTERMINAL(terminal, tty_out->terminal);
1055 if (!NILP (Fcontrolling_tty_p (terminal)))
1057 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1058 /* Set up C-g for both SIGQUIT and SIGINT.
1059 We don't know which we will get, but we handle both alike
1060 so which one it really gives us does not matter. */
1061 tty.main.c_cc[VQUIT] = quit_char;
1063 else
1065 /* We normally don't get interrupt or quit signals from tty
1066 devices other than our controlling terminal; therefore,
1067 we must handle C-g as normal input. Unfortunately, this
1068 means that the interrupt and quit feature must be
1069 disabled on secondary ttys, or we would not even see the
1070 keypress.
1072 Note that even though emacsclient could have special code
1073 to pass SIGINT to Emacs, we should _not_ enable
1074 interrupt/quit keys for emacsclient frames. This means
1075 that we can't break out of loops in C code from a
1076 secondary tty frame, but we can always decide what
1077 display the C-g came from, which is more important from a
1078 usability point of view. (Consider the case when two
1079 people work together using the same Emacs instance.) */
1080 tty.main.c_cc[VINTR] = CDISABLE;
1081 tty.main.c_cc[VQUIT] = CDISABLE;
1083 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1084 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1085 #ifdef VSWTCH
1086 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1087 of C-z */
1088 #endif /* VSWTCH */
1090 #ifdef VSUSP
1091 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1092 #endif /* VSUSP */
1093 #ifdef V_DSUSP
1094 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1095 #endif /* V_DSUSP */
1096 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1097 tty.main.c_cc[VDSUSP] = CDISABLE;
1098 #endif /* VDSUSP */
1099 #ifdef VLNEXT
1100 tty.main.c_cc[VLNEXT] = CDISABLE;
1101 #endif /* VLNEXT */
1102 #ifdef VREPRINT
1103 tty.main.c_cc[VREPRINT] = CDISABLE;
1104 #endif /* VREPRINT */
1105 #ifdef VWERASE
1106 tty.main.c_cc[VWERASE] = CDISABLE;
1107 #endif /* VWERASE */
1108 #ifdef VDISCARD
1109 tty.main.c_cc[VDISCARD] = CDISABLE;
1110 #endif /* VDISCARD */
1112 if (tty_out->flow_control)
1114 #ifdef VSTART
1115 tty.main.c_cc[VSTART] = '\021';
1116 #endif /* VSTART */
1117 #ifdef VSTOP
1118 tty.main.c_cc[VSTOP] = '\023';
1119 #endif /* VSTOP */
1121 else
1123 #ifdef VSTART
1124 tty.main.c_cc[VSTART] = CDISABLE;
1125 #endif /* VSTART */
1126 #ifdef VSTOP
1127 tty.main.c_cc[VSTOP] = CDISABLE;
1128 #endif /* VSTOP */
1131 #ifdef AIX
1132 tty.main.c_cc[VSTRT] = CDISABLE;
1133 tty.main.c_cc[VSTOP] = CDISABLE;
1134 tty.main.c_cc[VSUSP] = CDISABLE;
1135 tty.main.c_cc[VDSUSP] = CDISABLE;
1136 if (tty_out->flow_control)
1138 #ifdef VSTART
1139 tty.main.c_cc[VSTART] = '\021';
1140 #endif /* VSTART */
1141 #ifdef VSTOP
1142 tty.main.c_cc[VSTOP] = '\023';
1143 #endif /* VSTOP */
1145 /* Also, PTY overloads NUL and BREAK.
1146 don't ignore break, but don't signal either, so it looks like NUL.
1147 This really serves a purpose only if running in an XTERM window
1148 or via TELNET or the like, but does no harm elsewhere. */
1149 tty.main.c_iflag &= ~IGNBRK;
1150 tty.main.c_iflag &= ~BRKINT;
1151 #endif
1152 #endif /* not DOS_NT */
1154 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1155 if (!tty_out->term_initted)
1156 internal_terminal_init ();
1157 dos_ttraw (tty_out);
1158 #endif
1160 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1162 /* This code added to insure that, if flow-control is not to be used,
1163 we have an unlocked terminal at the start. */
1165 #ifdef TCXONC
1166 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1167 #endif
1168 #ifdef TIOCSTART
1169 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1170 #endif
1172 #if !defined (DOS_NT)
1173 #ifdef TCOON
1174 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1175 #endif
1176 #endif
1178 #ifdef F_GETOWN
1179 if (interrupt_input)
1181 old_fcntl_owner[fileno (tty_out->input)] =
1182 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1183 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1184 init_sigio (fileno (tty_out->input));
1185 #ifdef HAVE_GPM
1186 if (gpm_tty == tty_out)
1188 /* Arrange for mouse events to give us SIGIO signals. */
1189 fcntl (gpm_fd, F_SETOWN, getpid ());
1190 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1191 init_sigio (gpm_fd);
1193 #endif /* HAVE_GPM */
1195 #endif /* F_GETOWN */
1197 #ifdef _IOFBF
1198 /* This symbol is defined on recent USG systems.
1199 Someone says without this call USG won't really buffer the file
1200 even with a call to setbuf. */
1201 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1202 #else
1203 setbuf (tty_out->output, (char *) _sobuf);
1204 #endif
1206 if (tty_out->terminal->set_terminal_modes_hook)
1207 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1209 if (!tty_out->term_initted)
1211 Lisp_Object tail, frame;
1212 FOR_EACH_FRAME (tail, frame)
1214 /* XXX This needs to be revised. */
1215 if (FRAME_TERMCAP_P (XFRAME (frame))
1216 && FRAME_TTY (XFRAME (frame)) == tty_out)
1217 init_frame_faces (XFRAME (frame));
1221 if (tty_out->term_initted && no_redraw_on_reenter)
1223 /* We used to call "direct_output_forward_char(0)" here,
1224 but it's not clear why, since it may not do anything anyway. */
1226 else
1228 Lisp_Object tail, frame;
1229 frame_garbaged = 1;
1230 FOR_EACH_FRAME (tail, frame)
1232 if ((FRAME_TERMCAP_P (XFRAME (frame))
1233 || FRAME_MSDOS_P (XFRAME (frame)))
1234 && FRAME_TTY (XFRAME (frame)) == tty_out)
1235 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1239 tty_out->term_initted = 1;
1242 /* Return true if safe to use tabs in output.
1243 At the time this is called, init_sys_modes has not been done yet. */
1245 bool
1246 tabs_safe_p (int fd)
1248 struct emacs_tty etty;
1250 emacs_get_tty (fd, &etty);
1251 #ifndef DOS_NT
1252 #ifdef TABDLY
1253 return ((etty.main.c_oflag & TABDLY) != TAB3);
1254 #else /* not TABDLY */
1255 return 1;
1256 #endif /* not TABDLY */
1257 #else /* DOS_NT */
1258 return 0;
1259 #endif /* DOS_NT */
1262 /* Discard echoing. */
1264 void
1265 suppress_echo_on_tty (int fd)
1267 struct emacs_tty etty;
1269 emacs_get_tty (fd, &etty);
1270 #ifdef DOS_NT
1271 /* Set raw input mode. */
1272 etty.main = 0;
1273 #else
1274 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1275 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1276 #endif /* ! WINDOWSNT */
1277 emacs_set_tty (fd, &etty, 0);
1280 /* Get terminal size from system.
1281 Store number of lines into *HEIGHTP and width into *WIDTHP.
1282 We store 0 if there's no valid information. */
1284 void
1285 get_tty_size (int fd, int *widthp, int *heightp)
1287 #if defined TIOCGWINSZ
1289 /* BSD-style. */
1290 struct winsize size;
1292 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1293 *widthp = *heightp = 0;
1294 else
1296 *widthp = size.ws_col;
1297 *heightp = size.ws_row;
1300 #elif defined TIOCGSIZE
1302 /* SunOS - style. */
1303 struct ttysize size;
1305 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1306 *widthp = *heightp = 0;
1307 else
1309 *widthp = size.ts_cols;
1310 *heightp = size.ts_lines;
1313 #elif defined WINDOWSNT
1315 CONSOLE_SCREEN_BUFFER_INFO info;
1316 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1318 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1319 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1321 else
1322 *widthp = *heightp = 0;
1324 #elif defined MSDOS
1326 *widthp = ScreenCols ();
1327 *heightp = ScreenRows ();
1329 #else /* system doesn't know size */
1331 *widthp = 0;
1332 *heightp = 0;
1334 #endif
1337 /* Set the logical window size associated with descriptor FD
1338 to HEIGHT and WIDTH. This is used mainly with ptys.
1339 Return a negative value on failure. */
1342 set_window_size (int fd, int height, int width)
1344 #ifdef TIOCSWINSZ
1346 /* BSD-style. */
1347 struct winsize size;
1348 size.ws_row = height;
1349 size.ws_col = width;
1351 return ioctl (fd, TIOCSWINSZ, &size);
1353 #else
1354 #ifdef TIOCSSIZE
1356 /* SunOS - style. */
1357 struct ttysize size;
1358 size.ts_lines = height;
1359 size.ts_cols = width;
1361 return ioctl (fd, TIOCGSIZE, &size);
1362 #else
1363 return -1;
1364 #endif /* not SunOS-style */
1365 #endif /* not BSD-style */
1370 /* Prepare all terminal devices for exiting Emacs. */
1372 void
1373 reset_all_sys_modes (void)
1375 struct tty_display_info *tty;
1376 for (tty = tty_list; tty; tty = tty->next)
1377 reset_sys_modes (tty);
1380 /* Prepare the terminal for closing it; move the cursor to the
1381 bottom of the frame, turn off interrupt-driven I/O, etc. */
1383 void
1384 reset_sys_modes (struct tty_display_info *tty_out)
1386 if (noninteractive)
1388 fflush (stdout);
1389 return;
1391 if (!tty_out->term_initted)
1392 return;
1394 if (!tty_out->output)
1395 return; /* The tty is suspended. */
1397 /* Go to and clear the last line of the terminal. */
1399 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1401 /* Code adapted from tty_clear_end_of_line. */
1402 if (tty_out->TS_clr_line)
1404 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1406 else
1407 { /* have to do it the hard way */
1408 int i;
1409 tty_turn_off_insert (tty_out);
1411 for (i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1413 fputc (' ', tty_out->output);
1417 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1418 fflush (tty_out->output);
1420 if (tty_out->terminal->reset_terminal_modes_hook)
1421 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1423 /* Avoid possible loss of output when changing terminal modes. */
1424 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1425 continue;
1427 #ifndef DOS_NT
1428 #ifdef F_SETOWN
1429 if (interrupt_input)
1431 reset_sigio (fileno (tty_out->input));
1432 fcntl (fileno (tty_out->input), F_SETOWN,
1433 old_fcntl_owner[fileno (tty_out->input)]);
1435 #endif /* F_SETOWN */
1436 fcntl (fileno (tty_out->input), F_SETFL,
1437 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1438 #endif
1440 if (tty_out->old_tty)
1441 while (emacs_set_tty (fileno (tty_out->input),
1442 tty_out->old_tty, 0) < 0 && errno == EINTR)
1445 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1446 dos_ttcooked ();
1447 #endif
1449 widen_foreground_group (fileno (tty_out->input));
1452 #ifdef HAVE_PTYS
1454 /* Set up the proper status flags for use of a pty. */
1456 void
1457 setup_pty (int fd)
1459 /* I'm told that TOICREMOTE does not mean control chars
1460 "can't be sent" but rather that they don't have
1461 input-editing or signaling effects.
1462 That should be good, because we have other ways
1463 to do those things in Emacs.
1464 However, telnet mode seems not to work on 4.2.
1465 So TIOCREMOTE is turned off now. */
1467 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1468 will hang. In particular, the "timeout" feature (which
1469 causes a read to return if there is no data available)
1470 does this. Also it is known that telnet mode will hang
1471 in such a way that Emacs must be stopped (perhaps this
1472 is the same problem).
1474 If TIOCREMOTE is turned off, then there is a bug in
1475 hp-ux which sometimes loses data. Apparently the
1476 code which blocks the master process when the internal
1477 buffer fills up does not work. Other than this,
1478 though, everything else seems to work fine.
1480 Since the latter lossage is more benign, we may as well
1481 lose that way. -- cph */
1482 #ifdef FIONBIO
1483 #if defined (UNIX98_PTYS)
1485 int on = 1;
1486 ioctl (fd, FIONBIO, &on);
1488 #endif
1489 #endif
1491 #endif /* HAVE_PTYS */
1493 void
1494 init_system_name (void)
1496 if (!build_details)
1498 /* Set system-name to nil so that the build is deterministic. */
1499 Vsystem_name = Qnil;
1500 return;
1502 char *hostname_alloc = NULL;
1503 char *hostname;
1504 #ifndef HAVE_GETHOSTNAME
1505 struct utsname uts;
1506 uname (&uts);
1507 hostname = uts.nodename;
1508 #else /* HAVE_GETHOSTNAME */
1509 char hostname_buf[256];
1510 ptrdiff_t hostname_size = sizeof hostname_buf;
1511 hostname = hostname_buf;
1513 /* Try to get the host name; if the buffer is too short, try
1514 again. Apparently, the only indication gethostname gives of
1515 whether the buffer was large enough is the presence or absence
1516 of a '\0' in the string. Eech. */
1517 for (;;)
1519 gethostname (hostname, hostname_size - 1);
1520 hostname[hostname_size - 1] = '\0';
1522 /* Was the buffer large enough for the '\0'? */
1523 if (strlen (hostname) < hostname_size - 1)
1524 break;
1526 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1527 min (PTRDIFF_MAX, SIZE_MAX), 1);
1529 #endif /* HAVE_GETHOSTNAME */
1530 char *p;
1531 for (p = hostname; *p; p++)
1532 if (*p == ' ' || *p == '\t')
1533 *p = '-';
1534 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1535 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1536 Vsystem_name = build_string (hostname);
1537 xfree (hostname_alloc);
1540 sigset_t empty_mask;
1542 static struct sigaction process_fatal_action;
1544 static int
1545 emacs_sigaction_flags (void)
1547 #ifdef SA_RESTART
1548 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1549 'select') to reset their timeout on some platforms (e.g.,
1550 HP-UX 11), which is not what we want. Also, when Emacs is
1551 interactive, we don't want SA_RESTART because we need to poll
1552 for pending input so we need long-running syscalls to be interrupted
1553 after a signal that sets pending_signals.
1555 Non-interactive keyboard input goes through stdio, where we
1556 always want restartable system calls. */
1557 if (noninteractive)
1558 return SA_RESTART;
1559 #endif
1560 return 0;
1563 /* Store into *ACTION a signal action suitable for Emacs, with handler
1564 HANDLER. */
1565 void
1566 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1568 sigemptyset (&action->sa_mask);
1570 /* When handling a signal, block nonfatal system signals that are caught
1571 by Emacs. This makes race conditions less likely. */
1572 sigaddset (&action->sa_mask, SIGALRM);
1573 #ifdef SIGCHLD
1574 sigaddset (&action->sa_mask, SIGCHLD);
1575 #endif
1576 #ifdef SIGDANGER
1577 sigaddset (&action->sa_mask, SIGDANGER);
1578 #endif
1579 #ifdef PROFILER_CPU_SUPPORT
1580 sigaddset (&action->sa_mask, SIGPROF);
1581 #endif
1582 #ifdef SIGWINCH
1583 sigaddset (&action->sa_mask, SIGWINCH);
1584 #endif
1585 if (! noninteractive)
1587 sigaddset (&action->sa_mask, SIGINT);
1588 sigaddset (&action->sa_mask, SIGQUIT);
1589 #ifdef USABLE_SIGIO
1590 sigaddset (&action->sa_mask, SIGIO);
1591 #endif
1594 action->sa_handler = handler;
1595 action->sa_flags = emacs_sigaction_flags ();
1598 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1599 static pthread_t main_thread;
1600 #endif
1602 /* SIG has arrived at the current process. Deliver it to the main
1603 thread, which should handle it with HANDLER.
1605 If we are on the main thread, handle the signal SIG with HANDLER.
1606 Otherwise, redirect the signal to the main thread, blocking it from
1607 this thread. POSIX says any thread can receive a signal that is
1608 associated with a process, process group, or asynchronous event.
1609 On GNU/Linux that is not true, but for other systems (FreeBSD at
1610 least) it is. */
1611 void
1612 deliver_process_signal (int sig, signal_handler_t handler)
1614 /* Preserve errno, to avoid race conditions with signal handlers that
1615 might change errno. Races can occur even in single-threaded hosts. */
1616 int old_errno = errno;
1618 bool on_main_thread = true;
1619 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1620 if (! pthread_equal (pthread_self (), main_thread))
1622 sigset_t blocked;
1623 sigemptyset (&blocked);
1624 sigaddset (&blocked, sig);
1625 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1626 pthread_kill (main_thread, sig);
1627 on_main_thread = false;
1629 #endif
1630 if (on_main_thread)
1631 handler (sig);
1633 errno = old_errno;
1636 /* Static location to save a fatal backtrace in a thread.
1637 FIXME: If two subsidiary threads fail simultaneously, the resulting
1638 backtrace may be garbage. */
1639 enum { BACKTRACE_LIMIT_MAX = 500 };
1640 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1641 static int thread_backtrace_npointers;
1643 /* SIG has arrived at the current thread.
1644 If we are on the main thread, handle the signal SIG with HANDLER.
1645 Otherwise, this is a fatal error in the handling thread. */
1646 static void
1647 deliver_thread_signal (int sig, signal_handler_t handler)
1649 int old_errno = errno;
1651 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1652 if (! pthread_equal (pthread_self (), main_thread))
1654 thread_backtrace_npointers
1655 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1656 sigaction (sig, &process_fatal_action, 0);
1657 pthread_kill (main_thread, sig);
1659 /* Avoid further damage while the main thread is exiting. */
1660 while (1)
1661 sigsuspend (&empty_mask);
1663 #endif
1665 handler (sig);
1666 errno = old_errno;
1669 #if !HAVE_DECL_SYS_SIGLIST
1670 # undef sys_siglist
1671 # ifdef _sys_siglist
1672 # define sys_siglist _sys_siglist
1673 # elif HAVE_DECL___SYS_SIGLIST
1674 # define sys_siglist __sys_siglist
1675 # else
1676 # define sys_siglist my_sys_siglist
1677 static char const *sys_siglist[NSIG];
1678 # endif
1679 #endif
1681 #ifdef _sys_nsig
1682 # define sys_siglist_entries _sys_nsig
1683 #else
1684 # define sys_siglist_entries NSIG
1685 #endif
1687 /* Handle bus errors, invalid instruction, etc. */
1688 static void
1689 handle_fatal_signal (int sig)
1691 terminate_due_to_signal (sig, 40);
1694 static void
1695 deliver_fatal_signal (int sig)
1697 deliver_process_signal (sig, handle_fatal_signal);
1700 static void
1701 deliver_fatal_thread_signal (int sig)
1703 deliver_thread_signal (sig, handle_fatal_signal);
1706 static _Noreturn void
1707 handle_arith_signal (int sig)
1709 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1710 xsignal0 (Qarith_error);
1713 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1715 /* Alternate stack used by SIGSEGV handler below. */
1717 static unsigned char sigsegv_stack[SIGSTKSZ];
1720 /* Return true if SIGINFO indicates a stack overflow. */
1722 static bool
1723 stack_overflow (siginfo_t *siginfo)
1725 if (!attempt_stack_overflow_recovery)
1726 return false;
1728 /* In theory, a more-accurate heuristic can be obtained by using
1729 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1730 and pthread_attr_getguardsize to find the location and size of the
1731 guard area. In practice, though, these functions are so hard to
1732 use reliably that they're not worth bothering with. E.g., see:
1733 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1734 Other operating systems also have problems, e.g., Solaris's
1735 stack_violation function is tailor-made for this problem, but it
1736 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1738 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1739 candidate here. */
1741 if (!siginfo)
1742 return false;
1744 /* The faulting address. */
1745 char *addr = siginfo->si_addr;
1746 if (!addr)
1747 return false;
1749 /* The known top and bottom of the stack. The actual stack may
1750 extend a bit beyond these boundaries. */
1751 char *bot = stack_bottom;
1752 char *top = near_C_stack_top ();
1754 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1755 of the known stack divided by the size of the guard area past the
1756 end of the stack top. The heuristic is that a bad address is
1757 considered to be a stack overflow if it occurs within
1758 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1759 stack. This heuristic is not exactly correct but it's good
1760 enough in practice. */
1761 enum { LG_STACK_HEURISTIC = 8 };
1763 if (bot < top)
1764 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1765 else
1766 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1770 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1772 static void
1773 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1775 /* Hard GC error may lead to stack overflow caused by
1776 too nested calls to mark_object. No way to survive. */
1777 bool fatal = gc_in_progress;
1779 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1780 if (!fatal && !pthread_equal (pthread_self (), main_thread))
1781 fatal = true;
1782 #endif
1784 if (!fatal && stack_overflow (siginfo))
1785 siglongjmp (return_to_command_loop, 1);
1787 /* Otherwise we can't do anything with this. */
1788 deliver_fatal_thread_signal (sig);
1791 /* Return true if we have successfully set up SIGSEGV handler on alternate
1792 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1794 static bool
1795 init_sigsegv (void)
1797 struct sigaction sa;
1798 stack_t ss;
1800 ss.ss_sp = sigsegv_stack;
1801 ss.ss_size = sizeof (sigsegv_stack);
1802 ss.ss_flags = 0;
1803 if (sigaltstack (&ss, NULL) < 0)
1804 return 0;
1806 sigfillset (&sa.sa_mask);
1807 sa.sa_sigaction = handle_sigsegv;
1808 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1809 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1812 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1814 static bool
1815 init_sigsegv (void)
1817 return 0;
1820 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1822 static void
1823 deliver_arith_signal (int sig)
1825 deliver_thread_signal (sig, handle_arith_signal);
1828 #ifdef SIGDANGER
1830 /* Handler for SIGDANGER. */
1831 static void
1832 handle_danger_signal (int sig)
1834 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1836 /* It might be unsafe to call do_auto_save now. */
1837 force_auto_save_soon ();
1840 static void
1841 deliver_danger_signal (int sig)
1843 deliver_process_signal (sig, handle_danger_signal);
1845 #endif
1847 /* Treat SIG as a terminating signal, unless it is already ignored and
1848 we are in --batch mode. Among other things, this makes nohup work. */
1849 static void
1850 maybe_fatal_sig (int sig)
1852 bool catch_sig = !noninteractive;
1853 if (!catch_sig)
1855 struct sigaction old_action;
1856 sigaction (sig, 0, &old_action);
1857 catch_sig = old_action.sa_handler != SIG_IGN;
1859 if (catch_sig)
1860 sigaction (sig, &process_fatal_action, 0);
1863 void
1864 init_signals (bool dumping)
1866 struct sigaction thread_fatal_action;
1867 struct sigaction action;
1869 sigemptyset (&empty_mask);
1871 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1872 main_thread = pthread_self ();
1873 #endif
1875 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1876 if (! initialized)
1878 sys_siglist[SIGABRT] = "Aborted";
1879 # ifdef SIGAIO
1880 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1881 # endif
1882 sys_siglist[SIGALRM] = "Alarm clock";
1883 # ifdef SIGBUS
1884 sys_siglist[SIGBUS] = "Bus error";
1885 # endif
1886 # ifdef SIGCHLD
1887 sys_siglist[SIGCHLD] = "Child status changed";
1888 # endif
1889 # ifdef SIGCONT
1890 sys_siglist[SIGCONT] = "Continued";
1891 # endif
1892 # ifdef SIGDANGER
1893 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1894 # endif
1895 # ifdef SIGDGNOTIFY
1896 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1897 # endif
1898 # ifdef SIGEMT
1899 sys_siglist[SIGEMT] = "Emulation trap";
1900 # endif
1901 sys_siglist[SIGFPE] = "Arithmetic exception";
1902 # ifdef SIGFREEZE
1903 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1904 # endif
1905 # ifdef SIGGRANT
1906 sys_siglist[SIGGRANT] = "Monitor mode granted";
1907 # endif
1908 sys_siglist[SIGHUP] = "Hangup";
1909 sys_siglist[SIGILL] = "Illegal instruction";
1910 sys_siglist[SIGINT] = "Interrupt";
1911 # ifdef SIGIO
1912 sys_siglist[SIGIO] = "I/O possible";
1913 # endif
1914 # ifdef SIGIOINT
1915 sys_siglist[SIGIOINT] = "I/O intervention required";
1916 # endif
1917 # ifdef SIGIOT
1918 sys_siglist[SIGIOT] = "IOT trap";
1919 # endif
1920 sys_siglist[SIGKILL] = "Killed";
1921 # ifdef SIGLOST
1922 sys_siglist[SIGLOST] = "Resource lost";
1923 # endif
1924 # ifdef SIGLWP
1925 sys_siglist[SIGLWP] = "SIGLWP";
1926 # endif
1927 # ifdef SIGMSG
1928 sys_siglist[SIGMSG] = "Monitor mode data available";
1929 # endif
1930 # ifdef SIGPHONE
1931 sys_siglist[SIGWIND] = "SIGPHONE";
1932 # endif
1933 sys_siglist[SIGPIPE] = "Broken pipe";
1934 # ifdef SIGPOLL
1935 sys_siglist[SIGPOLL] = "Pollable event occurred";
1936 # endif
1937 # ifdef SIGPROF
1938 sys_siglist[SIGPROF] = "Profiling timer expired";
1939 # endif
1940 # ifdef SIGPTY
1941 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1942 # endif
1943 # ifdef SIGPWR
1944 sys_siglist[SIGPWR] = "Power-fail restart";
1945 # endif
1946 sys_siglist[SIGQUIT] = "Quit";
1947 # ifdef SIGRETRACT
1948 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1949 # endif
1950 # ifdef SIGSAK
1951 sys_siglist[SIGSAK] = "Secure attention";
1952 # endif
1953 sys_siglist[SIGSEGV] = "Segmentation violation";
1954 # ifdef SIGSOUND
1955 sys_siglist[SIGSOUND] = "Sound completed";
1956 # endif
1957 # ifdef SIGSTOP
1958 sys_siglist[SIGSTOP] = "Stopped (signal)";
1959 # endif
1960 # ifdef SIGSTP
1961 sys_siglist[SIGSTP] = "Stopped (user)";
1962 # endif
1963 # ifdef SIGSYS
1964 sys_siglist[SIGSYS] = "Bad argument to system call";
1965 # endif
1966 sys_siglist[SIGTERM] = "Terminated";
1967 # ifdef SIGTHAW
1968 sys_siglist[SIGTHAW] = "SIGTHAW";
1969 # endif
1970 # ifdef SIGTRAP
1971 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1972 # endif
1973 # ifdef SIGTSTP
1974 sys_siglist[SIGTSTP] = "Stopped (user)";
1975 # endif
1976 # ifdef SIGTTIN
1977 sys_siglist[SIGTTIN] = "Stopped (tty input)";
1978 # endif
1979 # ifdef SIGTTOU
1980 sys_siglist[SIGTTOU] = "Stopped (tty output)";
1981 # endif
1982 # ifdef SIGURG
1983 sys_siglist[SIGURG] = "Urgent I/O condition";
1984 # endif
1985 # ifdef SIGUSR1
1986 sys_siglist[SIGUSR1] = "User defined signal 1";
1987 # endif
1988 # ifdef SIGUSR2
1989 sys_siglist[SIGUSR2] = "User defined signal 2";
1990 # endif
1991 # ifdef SIGVTALRM
1992 sys_siglist[SIGVTALRM] = "Virtual timer expired";
1993 # endif
1994 # ifdef SIGWAITING
1995 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
1996 # endif
1997 # ifdef SIGWINCH
1998 sys_siglist[SIGWINCH] = "Window size changed";
1999 # endif
2000 # ifdef SIGWIND
2001 sys_siglist[SIGWIND] = "SIGWIND";
2002 # endif
2003 # ifdef SIGXCPU
2004 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2005 # endif
2006 # ifdef SIGXFSZ
2007 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2008 # endif
2010 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2012 /* Don't alter signal handlers if dumping. On some machines,
2013 changing signal handlers sets static data that would make signals
2014 fail to work right when the dumped Emacs is run. */
2015 if (dumping)
2016 return;
2018 sigfillset (&process_fatal_action.sa_mask);
2019 process_fatal_action.sa_handler = deliver_fatal_signal;
2020 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2022 sigfillset (&thread_fatal_action.sa_mask);
2023 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2024 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2026 /* SIGINT may need special treatment on MS-Windows. See
2027 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2028 Please update the doc of kill-emacs, kill-emacs-hook, and
2029 NEWS if you change this. */
2031 maybe_fatal_sig (SIGHUP);
2032 maybe_fatal_sig (SIGINT);
2033 maybe_fatal_sig (SIGTERM);
2035 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2036 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2037 to behave more like typical batch applications do. */
2038 if (! noninteractive)
2039 signal (SIGPIPE, SIG_IGN);
2041 sigaction (SIGQUIT, &process_fatal_action, 0);
2042 sigaction (SIGILL, &thread_fatal_action, 0);
2043 sigaction (SIGTRAP, &thread_fatal_action, 0);
2045 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2046 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2047 interpreter's floating point operations, so treat SIGFPE as an
2048 arith-error if it arises in the main thread. */
2049 if (IEEE_FLOATING_POINT)
2050 sigaction (SIGFPE, &thread_fatal_action, 0);
2051 else
2053 emacs_sigaction_init (&action, deliver_arith_signal);
2054 sigaction (SIGFPE, &action, 0);
2057 #ifdef SIGUSR1
2058 add_user_signal (SIGUSR1, "sigusr1");
2059 #endif
2060 #ifdef SIGUSR2
2061 add_user_signal (SIGUSR2, "sigusr2");
2062 #endif
2063 sigaction (SIGABRT, &thread_fatal_action, 0);
2064 #ifdef SIGPRE
2065 sigaction (SIGPRE, &thread_fatal_action, 0);
2066 #endif
2067 #ifdef SIGORE
2068 sigaction (SIGORE, &thread_fatal_action, 0);
2069 #endif
2070 #ifdef SIGUME
2071 sigaction (SIGUME, &thread_fatal_action, 0);
2072 #endif
2073 #ifdef SIGDLK
2074 sigaction (SIGDLK, &process_fatal_action, 0);
2075 #endif
2076 #ifdef SIGCPULIM
2077 sigaction (SIGCPULIM, &process_fatal_action, 0);
2078 #endif
2079 #ifdef SIGIOT
2080 sigaction (SIGIOT, &thread_fatal_action, 0);
2081 #endif
2082 #ifdef SIGEMT
2083 sigaction (SIGEMT, &thread_fatal_action, 0);
2084 #endif
2085 #ifdef SIGBUS
2086 sigaction (SIGBUS, &thread_fatal_action, 0);
2087 #endif
2088 if (!init_sigsegv ())
2089 sigaction (SIGSEGV, &thread_fatal_action, 0);
2090 #ifdef SIGSYS
2091 sigaction (SIGSYS, &thread_fatal_action, 0);
2092 #endif
2093 sigaction (SIGTERM, &process_fatal_action, 0);
2094 #ifdef SIGPROF
2095 signal (SIGPROF, SIG_IGN);
2096 #endif
2097 #ifdef SIGVTALRM
2098 sigaction (SIGVTALRM, &process_fatal_action, 0);
2099 #endif
2100 #ifdef SIGXCPU
2101 sigaction (SIGXCPU, &process_fatal_action, 0);
2102 #endif
2103 #ifdef SIGXFSZ
2104 sigaction (SIGXFSZ, &process_fatal_action, 0);
2105 #endif
2107 #ifdef SIGDANGER
2108 /* This just means available memory is getting low. */
2109 emacs_sigaction_init (&action, deliver_danger_signal);
2110 sigaction (SIGDANGER, &action, 0);
2111 #endif
2113 /* AIX-specific signals. */
2114 #ifdef SIGGRANT
2115 sigaction (SIGGRANT, &process_fatal_action, 0);
2116 #endif
2117 #ifdef SIGMIGRATE
2118 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2119 #endif
2120 #ifdef SIGMSG
2121 sigaction (SIGMSG, &process_fatal_action, 0);
2122 #endif
2123 #ifdef SIGRETRACT
2124 sigaction (SIGRETRACT, &process_fatal_action, 0);
2125 #endif
2126 #ifdef SIGSAK
2127 sigaction (SIGSAK, &process_fatal_action, 0);
2128 #endif
2129 #ifdef SIGSOUND
2130 sigaction (SIGSOUND, &process_fatal_action, 0);
2131 #endif
2132 #ifdef SIGTALRM
2133 sigaction (SIGTALRM, &thread_fatal_action, 0);
2134 #endif
2137 #ifndef HAVE_RANDOM
2138 #ifdef random
2139 #define HAVE_RANDOM
2140 #endif
2141 #endif
2143 /* Figure out how many bits the system's random number generator uses.
2144 `random' and `lrand48' are assumed to return 31 usable bits.
2145 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2146 so we'll shift it and treat it like the 15-bit USG `rand'. */
2148 #ifndef RAND_BITS
2149 # ifdef HAVE_RANDOM
2150 # define RAND_BITS 31
2151 # else /* !HAVE_RANDOM */
2152 # ifdef HAVE_LRAND48
2153 # define RAND_BITS 31
2154 # define random lrand48
2155 # else /* !HAVE_LRAND48 */
2156 # define RAND_BITS 15
2157 # if RAND_MAX == 32767
2158 # define random rand
2159 # else /* RAND_MAX != 32767 */
2160 # if RAND_MAX == 2147483647
2161 # define random() (rand () >> 16)
2162 # else /* RAND_MAX != 2147483647 */
2163 # ifdef USG
2164 # define random rand
2165 # else
2166 # define random() (rand () >> 16)
2167 # endif /* !USG */
2168 # endif /* RAND_MAX != 2147483647 */
2169 # endif /* RAND_MAX != 32767 */
2170 # endif /* !HAVE_LRAND48 */
2171 # endif /* !HAVE_RANDOM */
2172 #endif /* !RAND_BITS */
2174 #ifdef HAVE_RANDOM
2175 typedef unsigned int random_seed;
2176 static void set_random_seed (random_seed arg) { srandom (arg); }
2177 #elif defined HAVE_LRAND48
2178 /* Although srand48 uses a long seed, this is unsigned long to avoid
2179 undefined behavior on signed integer overflow in init_random. */
2180 typedef unsigned long int random_seed;
2181 static void set_random_seed (random_seed arg) { srand48 (arg); }
2182 #else
2183 typedef unsigned int random_seed;
2184 static void set_random_seed (random_seed arg) { srand (arg); }
2185 #endif
2187 void
2188 seed_random (void *seed, ptrdiff_t seed_size)
2190 random_seed arg = 0;
2191 unsigned char *argp = (unsigned char *) &arg;
2192 unsigned char *seedp = seed;
2193 for (ptrdiff_t i = 0; i < seed_size; i++)
2194 argp[i % sizeof arg] ^= seedp[i];
2195 set_random_seed (arg);
2198 void
2199 init_random (void)
2201 random_seed v;
2202 bool success = false;
2204 /* First, try seeding the PRNG from the operating system's entropy
2205 source. This approach is both fast and secure. */
2206 #ifdef WINDOWSNT
2207 success = w32_init_random (&v, sizeof v) == 0;
2208 #else
2209 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2210 if (0 <= fd)
2212 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2213 close (fd);
2215 #endif
2217 /* If that didn't work, try using GnuTLS, which is secure, but on
2218 some systems, can be somewhat slow. */
2219 if (!success)
2220 success = EQ (emacs_gnutls_global_init (), Qt)
2221 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2223 /* If _that_ didn't work, just use the current time value and PID.
2224 It's at least better than XKCD 221. */
2225 if (!success)
2227 struct timespec t = current_timespec ();
2228 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2231 set_random_seed (v);
2235 * Return a nonnegative random integer out of whatever we've got.
2236 * It contains enough bits to make a random (signed) Emacs fixnum.
2237 * This suffices even for a 64-bit architecture with a 15-bit rand.
2239 EMACS_INT
2240 get_random (void)
2242 EMACS_UINT val = 0;
2243 int i;
2244 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2245 val = (random () ^ (val << RAND_BITS)
2246 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2247 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2248 return val & INTMASK;
2251 #ifndef HAVE_SNPRINTF
2252 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2254 snprintf (char *buf, size_t bufsize, char const *format, ...)
2256 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2257 ptrdiff_t nbytes = size - 1;
2258 va_list ap;
2260 if (size)
2262 va_start (ap, format);
2263 nbytes = doprnt (buf, size, format, 0, ap);
2264 va_end (ap);
2267 if (nbytes == size - 1)
2269 /* Calculate the length of the string that would have been created
2270 had the buffer been large enough. */
2271 char stackbuf[4000];
2272 char *b = stackbuf;
2273 ptrdiff_t bsize = sizeof stackbuf;
2274 va_start (ap, format);
2275 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2276 va_end (ap);
2277 if (b != stackbuf)
2278 xfree (b);
2281 if (INT_MAX < nbytes)
2283 #ifdef EOVERFLOW
2284 errno = EOVERFLOW;
2285 #else
2286 errno = EDOM;
2287 #endif
2288 return -1;
2290 return nbytes;
2292 #endif
2294 /* If a backtrace is available, output the top lines of it to stderr.
2295 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2296 This function may be called from a signal handler, so it should
2297 not invoke async-unsafe functions like malloc.
2299 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2300 but do not output anything. This avoids some problems that can
2301 otherwise occur if the malloc arena is corrupted before 'backtrace'
2302 is called, since 'backtrace' may call malloc if the tables are not
2303 initialized.
2305 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2306 fatal error has occurred in some other thread; generate a thread
2307 backtrace instead, ignoring BACKTRACE_LIMIT. */
2308 void
2309 emacs_backtrace (int backtrace_limit)
2311 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2312 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2313 void *buffer;
2314 int npointers;
2316 if (thread_backtrace_npointers)
2318 buffer = thread_backtrace_buffer;
2319 npointers = thread_backtrace_npointers;
2321 else
2323 buffer = main_backtrace_buffer;
2325 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2326 if (bounded_limit < 0)
2328 backtrace (buffer, 1);
2329 return;
2332 npointers = backtrace (buffer, bounded_limit + 1);
2335 if (npointers)
2337 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2338 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2339 if (bounded_limit < npointers)
2340 emacs_write (STDERR_FILENO, "...\n", 4);
2344 #ifndef HAVE_NTGUI
2345 void
2346 emacs_abort (void)
2348 terminate_due_to_signal (SIGABRT, 40);
2350 #endif
2352 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2353 Use binary I/O on systems that care about text vs binary I/O.
2354 Arrange for subprograms to not inherit the file descriptor.
2355 Prefer a method that is multithread-safe, if available.
2356 Do not fail merely because the open was interrupted by a signal.
2357 Allow the user to quit. */
2360 emacs_open (const char *file, int oflags, int mode)
2362 int fd;
2363 if (! (oflags & O_TEXT))
2364 oflags |= O_BINARY;
2365 oflags |= O_CLOEXEC;
2366 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2367 QUIT;
2368 if (! O_CLOEXEC && 0 <= fd)
2369 fcntl (fd, F_SETFD, FD_CLOEXEC);
2370 return fd;
2373 /* Open FILE as a stream for Emacs use, with mode MODE.
2374 Act like emacs_open with respect to threads, signals, and quits. */
2376 FILE *
2377 emacs_fopen (char const *file, char const *mode)
2379 int fd, omode, oflags;
2380 int bflag = 0;
2381 char const *m = mode;
2383 switch (*m++)
2385 case 'r': omode = O_RDONLY; oflags = 0; break;
2386 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2387 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2388 default: emacs_abort ();
2391 while (*m)
2392 switch (*m++)
2394 case '+': omode = O_RDWR; break;
2395 case 't': bflag = O_TEXT; break;
2396 default: /* Ignore. */ break;
2399 fd = emacs_open (file, omode | oflags | bflag, 0666);
2400 return fd < 0 ? 0 : fdopen (fd, mode);
2403 /* Create a pipe for Emacs use. */
2406 emacs_pipe (int fd[2])
2408 #ifdef MSDOS
2409 return pipe (fd);
2410 #else /* !MSDOS */
2411 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2412 if (! O_CLOEXEC && result == 0)
2414 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2415 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2417 return result;
2418 #endif /* !MSDOS */
2421 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2422 For the background behind this mess, please see Austin Group defect 529
2423 <http://austingroupbugs.net/view.php?id=529>. */
2425 #ifndef POSIX_CLOSE_RESTART
2426 # define POSIX_CLOSE_RESTART 1
2427 static int
2428 posix_close (int fd, int flag)
2430 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2431 eassert (flag == POSIX_CLOSE_RESTART);
2433 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2434 on a system that does not define POSIX_CLOSE_RESTART.
2436 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2437 closed, and retrying the close could inadvertently close a file
2438 descriptor allocated by some other thread. In other systems
2439 (e.g., HP/UX) FD is not closed. And in still other systems
2440 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2441 multithreaded program there can be no way to tell.
2443 So, in this case, pretend that the close succeeded. This works
2444 well on systems like GNU/Linux that close FD. Although it may
2445 leak a file descriptor on other systems, the leak is unlikely and
2446 it's better to leak than to close a random victim. */
2447 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2449 #endif
2451 /* Close FD, retrying if interrupted. If successful, return 0;
2452 otherwise, return -1 and set errno to a non-EINTR value. Consider
2453 an EINPROGRESS error to be successful, as that's merely a signal
2454 arriving. FD is always closed when this function returns, even
2455 when it returns -1.
2457 Do not call this function if FD is nonnegative and might already be closed,
2458 as that might close an innocent victim opened by some other thread. */
2461 emacs_close (int fd)
2463 while (1)
2465 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2466 if (r == 0)
2467 return r;
2468 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2470 eassert (errno != EBADF || fd < 0);
2471 return errno == EINPROGRESS ? 0 : r;
2476 /* Maximum number of bytes to read or write in a single system call.
2477 This works around a serious bug in Linux kernels before 2.6.16; see
2478 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2479 It's likely to work around similar bugs in other operating systems, so do it
2480 on all platforms. Round INT_MAX down to a page size, with the conservative
2481 assumption that page sizes are at most 2**18 bytes (any kernel with a
2482 page size larger than that shouldn't have the bug). */
2483 #ifndef MAX_RW_COUNT
2484 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2485 #endif
2487 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2488 Return the number of bytes read, which might be less than NBYTE.
2489 On error, set errno and return -1. */
2490 ptrdiff_t
2491 emacs_read (int fildes, void *buf, ptrdiff_t nbyte)
2493 ssize_t rtnval;
2495 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2496 passes a size that large to emacs_read. */
2498 while ((rtnval = read (fildes, buf, nbyte)) == -1
2499 && (errno == EINTR))
2500 QUIT;
2501 return (rtnval);
2504 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2505 or if a partial write occurs. If interrupted, process pending
2506 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2507 errno if this is less than NBYTE. */
2508 static ptrdiff_t
2509 emacs_full_write (int fildes, char const *buf, ptrdiff_t nbyte,
2510 bool process_signals)
2512 ptrdiff_t bytes_written = 0;
2514 while (nbyte > 0)
2516 ssize_t n = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
2518 if (n < 0)
2520 if (errno == EINTR)
2522 /* I originally used `QUIT' but that might cause files to
2523 be truncated if you hit C-g in the middle of it. --Stef */
2524 if (process_signals && pending_signals)
2525 process_pending_signals ();
2526 continue;
2528 else
2529 break;
2532 buf += n;
2533 nbyte -= n;
2534 bytes_written += n;
2537 return bytes_written;
2540 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2541 interrupted or if a partial write occurs. Return the number of
2542 bytes written, setting errno if this is less than NBYTE. */
2543 ptrdiff_t
2544 emacs_write (int fildes, void const *buf, ptrdiff_t nbyte)
2546 return emacs_full_write (fildes, buf, nbyte, 0);
2549 /* Like emacs_write, but also process pending signals if interrupted. */
2550 ptrdiff_t
2551 emacs_write_sig (int fildes, void const *buf, ptrdiff_t nbyte)
2553 return emacs_full_write (fildes, buf, nbyte, 1);
2556 /* Write a diagnostic to standard error that contains MESSAGE and a
2557 string derived from errno. Preserve errno. Do not buffer stderr.
2558 Do not process pending signals if interrupted. */
2559 void
2560 emacs_perror (char const *message)
2562 int err = errno;
2563 char const *error_string = emacs_strerror (err);
2564 char const *command = (initial_argv && initial_argv[0]
2565 ? initial_argv[0] : "emacs");
2566 /* Write it out all at once, if it's short; this is less likely to
2567 be interleaved with other output. */
2568 char buf[BUFSIZ];
2569 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2570 command, message, error_string);
2571 if (0 <= nbytes && nbytes < BUFSIZ)
2572 emacs_write (STDERR_FILENO, buf, nbytes);
2573 else
2575 emacs_write (STDERR_FILENO, command, strlen (command));
2576 emacs_write (STDERR_FILENO, ": ", 2);
2577 emacs_write (STDERR_FILENO, message, strlen (message));
2578 emacs_write (STDERR_FILENO, ": ", 2);
2579 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2580 emacs_write (STDERR_FILENO, "\n", 1);
2582 errno = err;
2585 /* Return a struct timeval that is roughly equivalent to T.
2586 Use the least timeval not less than T.
2587 Return an extremal value if the result would overflow. */
2588 struct timeval
2589 make_timeval (struct timespec t)
2591 struct timeval tv;
2592 tv.tv_sec = t.tv_sec;
2593 tv.tv_usec = t.tv_nsec / 1000;
2595 if (t.tv_nsec % 1000 != 0)
2597 if (tv.tv_usec < 999999)
2598 tv.tv_usec++;
2599 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2601 tv.tv_sec++;
2602 tv.tv_usec = 0;
2606 return tv;
2609 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2610 ATIME and MTIME, respectively.
2611 FD must be either negative -- in which case it is ignored --
2612 or a file descriptor that is open on FILE.
2613 If FD is nonnegative, then FILE can be NULL. */
2615 set_file_times (int fd, const char *filename,
2616 struct timespec atime, struct timespec mtime)
2618 struct timespec timespec[2];
2619 timespec[0] = atime;
2620 timespec[1] = mtime;
2621 return fdutimens (fd, filename, timespec);
2624 /* Like strsignal, except async-signal-safe, and this function typically
2625 returns a string in the C locale rather than the current locale. */
2626 char const *
2627 safe_strsignal (int code)
2629 char const *signame = 0;
2631 if (0 <= code && code < sys_siglist_entries)
2632 signame = sys_siglist[code];
2633 if (! signame)
2634 signame = "Unknown signal";
2636 return signame;
2639 #ifndef DOS_NT
2640 /* For make-serial-process */
2642 serial_open (Lisp_Object port)
2644 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2645 if (fd < 0)
2646 report_file_error ("Opening serial port", port);
2647 #ifdef TIOCEXCL
2648 ioctl (fd, TIOCEXCL, (char *) 0);
2649 #endif
2651 return fd;
2654 #if !defined (HAVE_CFMAKERAW)
2655 /* Workaround for targets which are missing cfmakeraw. */
2656 /* Pasted from man page. */
2657 static void
2658 cfmakeraw (struct termios *termios_p)
2660 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2661 termios_p->c_oflag &= ~OPOST;
2662 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2663 termios_p->c_cflag &= ~(CSIZE|PARENB);
2664 termios_p->c_cflag |= CS8;
2666 #endif /* !defined (HAVE_CFMAKERAW */
2668 #if !defined (HAVE_CFSETSPEED)
2669 /* Workaround for targets which are missing cfsetspeed. */
2670 static int
2671 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2673 return (cfsetispeed (termios_p, vitesse)
2674 + cfsetospeed (termios_p, vitesse));
2676 #endif
2678 /* For serial-process-configure */
2679 void
2680 serial_configure (struct Lisp_Process *p,
2681 Lisp_Object contact)
2683 Lisp_Object childp2 = Qnil;
2684 Lisp_Object tem = Qnil;
2685 struct termios attr;
2686 int err;
2687 char summary[4] = "???"; /* This usually becomes "8N1". */
2689 childp2 = Fcopy_sequence (p->childp);
2691 /* Read port attributes and prepare default configuration. */
2692 err = tcgetattr (p->outfd, &attr);
2693 if (err != 0)
2694 report_file_error ("Failed tcgetattr", Qnil);
2695 cfmakeraw (&attr);
2696 #if defined (CLOCAL)
2697 attr.c_cflag |= CLOCAL;
2698 #endif
2699 #if defined (CREAD)
2700 attr.c_cflag |= CREAD;
2701 #endif
2703 /* Configure speed. */
2704 if (!NILP (Fplist_member (contact, QCspeed)))
2705 tem = Fplist_get (contact, QCspeed);
2706 else
2707 tem = Fplist_get (p->childp, QCspeed);
2708 CHECK_NUMBER (tem);
2709 err = cfsetspeed (&attr, XINT (tem));
2710 if (err != 0)
2711 report_file_error ("Failed cfsetspeed", tem);
2712 childp2 = Fplist_put (childp2, QCspeed, tem);
2714 /* Configure bytesize. */
2715 if (!NILP (Fplist_member (contact, QCbytesize)))
2716 tem = Fplist_get (contact, QCbytesize);
2717 else
2718 tem = Fplist_get (p->childp, QCbytesize);
2719 if (NILP (tem))
2720 tem = make_number (8);
2721 CHECK_NUMBER (tem);
2722 if (XINT (tem) != 7 && XINT (tem) != 8)
2723 error (":bytesize must be nil (8), 7, or 8");
2724 summary[0] = XINT (tem) + '0';
2725 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2726 attr.c_cflag &= ~CSIZE;
2727 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2728 #else
2729 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2730 if (XINT (tem) != 8)
2731 error ("Bytesize cannot be changed");
2732 #endif
2733 childp2 = Fplist_put (childp2, QCbytesize, tem);
2735 /* Configure parity. */
2736 if (!NILP (Fplist_member (contact, QCparity)))
2737 tem = Fplist_get (contact, QCparity);
2738 else
2739 tem = Fplist_get (p->childp, QCparity);
2740 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2741 error (":parity must be nil (no parity), `even', or `odd'");
2742 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2743 attr.c_cflag &= ~(PARENB | PARODD);
2744 attr.c_iflag &= ~(IGNPAR | INPCK);
2745 if (NILP (tem))
2747 summary[1] = 'N';
2749 else if (EQ (tem, Qeven))
2751 summary[1] = 'E';
2752 attr.c_cflag |= PARENB;
2753 attr.c_iflag |= (IGNPAR | INPCK);
2755 else if (EQ (tem, Qodd))
2757 summary[1] = 'O';
2758 attr.c_cflag |= (PARENB | PARODD);
2759 attr.c_iflag |= (IGNPAR | INPCK);
2761 #else
2762 /* Don't error on no parity, which should be set by cfmakeraw. */
2763 if (!NILP (tem))
2764 error ("Parity cannot be configured");
2765 #endif
2766 childp2 = Fplist_put (childp2, QCparity, tem);
2768 /* Configure stopbits. */
2769 if (!NILP (Fplist_member (contact, QCstopbits)))
2770 tem = Fplist_get (contact, QCstopbits);
2771 else
2772 tem = Fplist_get (p->childp, QCstopbits);
2773 if (NILP (tem))
2774 tem = make_number (1);
2775 CHECK_NUMBER (tem);
2776 if (XINT (tem) != 1 && XINT (tem) != 2)
2777 error (":stopbits must be nil (1 stopbit), 1, or 2");
2778 summary[2] = XINT (tem) + '0';
2779 #if defined (CSTOPB)
2780 attr.c_cflag &= ~CSTOPB;
2781 if (XINT (tem) == 2)
2782 attr.c_cflag |= CSTOPB;
2783 #else
2784 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2785 if (XINT (tem) != 1)
2786 error ("Stopbits cannot be configured");
2787 #endif
2788 childp2 = Fplist_put (childp2, QCstopbits, tem);
2790 /* Configure flowcontrol. */
2791 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2792 tem = Fplist_get (contact, QCflowcontrol);
2793 else
2794 tem = Fplist_get (p->childp, QCflowcontrol);
2795 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2796 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2797 #if defined (CRTSCTS)
2798 attr.c_cflag &= ~CRTSCTS;
2799 #endif
2800 #if defined (CNEW_RTSCTS)
2801 attr.c_cflag &= ~CNEW_RTSCTS;
2802 #endif
2803 #if defined (IXON) && defined (IXOFF)
2804 attr.c_iflag &= ~(IXON | IXOFF);
2805 #endif
2806 if (NILP (tem))
2808 /* Already configured. */
2810 else if (EQ (tem, Qhw))
2812 #if defined (CRTSCTS)
2813 attr.c_cflag |= CRTSCTS;
2814 #elif defined (CNEW_RTSCTS)
2815 attr.c_cflag |= CNEW_RTSCTS;
2816 #else
2817 error ("Hardware flowcontrol (RTS/CTS) not supported");
2818 #endif
2820 else if (EQ (tem, Qsw))
2822 #if defined (IXON) && defined (IXOFF)
2823 attr.c_iflag |= (IXON | IXOFF);
2824 #else
2825 error ("Software flowcontrol (XON/XOFF) not supported");
2826 #endif
2828 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2830 /* Activate configuration. */
2831 err = tcsetattr (p->outfd, TCSANOW, &attr);
2832 if (err != 0)
2833 report_file_error ("Failed tcsetattr", Qnil);
2835 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2836 pset_childp (p, childp2);
2838 #endif /* not DOS_NT */
2840 /* System depended enumeration of and access to system processes a-la ps(1). */
2842 #ifdef HAVE_PROCFS
2844 /* Process enumeration and access via /proc. */
2846 Lisp_Object
2847 list_system_processes (void)
2849 Lisp_Object procdir, match, proclist, next;
2850 Lisp_Object tail;
2852 /* For every process on the system, there's a directory in the
2853 "/proc" pseudo-directory whose name is the numeric ID of that
2854 process. */
2855 procdir = build_string ("/proc");
2856 match = build_string ("[0-9]+");
2857 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2859 /* `proclist' gives process IDs as strings. Destructively convert
2860 each string into a number. */
2861 for (tail = proclist; CONSP (tail); tail = next)
2863 next = XCDR (tail);
2864 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2867 /* directory_files_internal returns the files in reverse order; undo
2868 that. */
2869 proclist = Fnreverse (proclist);
2870 return proclist;
2873 #elif defined DARWIN_OS || defined __FreeBSD__
2875 Lisp_Object
2876 list_system_processes (void)
2878 #ifdef DARWIN_OS
2879 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2880 #else
2881 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2882 #endif
2883 size_t len;
2884 struct kinfo_proc *procs;
2885 size_t i;
2887 Lisp_Object proclist = Qnil;
2889 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2890 return proclist;
2892 procs = xmalloc (len);
2893 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2895 xfree (procs);
2896 return proclist;
2899 len /= sizeof (struct kinfo_proc);
2900 for (i = 0; i < len; i++)
2902 #ifdef DARWIN_OS
2903 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2904 #else
2905 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2906 #endif
2909 xfree (procs);
2911 return proclist;
2914 /* The WINDOWSNT implementation is in w32.c.
2915 The MSDOS implementation is in dosfns.c. */
2916 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2918 Lisp_Object
2919 list_system_processes (void)
2921 return Qnil;
2924 #endif /* !defined (WINDOWSNT) */
2926 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2927 static struct timespec
2928 time_from_jiffies (unsigned long long tval, long hz)
2930 unsigned long long s = tval / hz;
2931 unsigned long long frac = tval % hz;
2932 int ns;
2934 if (TYPE_MAXIMUM (time_t) < s)
2935 time_overflow ();
2936 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2937 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2938 ns = frac * TIMESPEC_RESOLUTION / hz;
2939 else
2941 /* This is reachable only in the unlikely case that HZ * HZ
2942 exceeds ULLONG_MAX. It calculates an approximation that is
2943 guaranteed to be in range. */
2944 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
2945 + (hz % TIMESPEC_RESOLUTION != 0));
2946 ns = frac / hz_per_ns;
2949 return make_timespec (s, ns);
2952 static Lisp_Object
2953 ltime_from_jiffies (unsigned long long tval, long hz)
2955 struct timespec t = time_from_jiffies (tval, hz);
2956 return make_lisp_time (t);
2959 static struct timespec
2960 get_up_time (void)
2962 FILE *fup;
2963 struct timespec up = make_timespec (0, 0);
2965 block_input ();
2966 fup = emacs_fopen ("/proc/uptime", "r");
2968 if (fup)
2970 unsigned long long upsec, upfrac, idlesec, idlefrac;
2971 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
2973 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
2974 &upsec, &upfrac_start, &upfrac, &upfrac_end,
2975 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
2976 == 4)
2978 if (TYPE_MAXIMUM (time_t) < upsec)
2980 upsec = TYPE_MAXIMUM (time_t);
2981 upfrac = TIMESPEC_RESOLUTION - 1;
2983 else
2985 int upfraclen = upfrac_end - upfrac_start;
2986 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
2987 upfrac *= 10;
2988 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
2989 upfrac /= 10;
2990 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
2992 up = make_timespec (upsec, upfrac);
2994 fclose (fup);
2996 unblock_input ();
2998 return up;
3001 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3002 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3004 static Lisp_Object
3005 procfs_ttyname (int rdev)
3007 FILE *fdev;
3008 char name[PATH_MAX];
3010 block_input ();
3011 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3012 name[0] = 0;
3014 if (fdev)
3016 unsigned major;
3017 unsigned long minor_beg, minor_end;
3018 char minor[25]; /* 2 32-bit numbers + dash */
3019 char *endp;
3021 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
3023 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3024 && major == MAJOR (rdev))
3026 minor_beg = strtoul (minor, &endp, 0);
3027 if (*endp == '\0')
3028 minor_end = minor_beg;
3029 else if (*endp == '-')
3030 minor_end = strtoul (endp + 1, &endp, 0);
3031 else
3032 continue;
3034 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3036 sprintf (name + strlen (name), "%u", MINOR (rdev));
3037 break;
3041 fclose (fdev);
3043 unblock_input ();
3044 return build_string (name);
3047 static uintmax_t
3048 procfs_get_total_memory (void)
3050 FILE *fmem;
3051 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3052 int c;
3054 block_input ();
3055 fmem = emacs_fopen ("/proc/meminfo", "r");
3057 if (fmem)
3059 uintmax_t entry_value;
3060 bool done;
3063 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3065 case 1:
3066 retval = entry_value;
3067 done = 1;
3068 break;
3070 case 0:
3071 while ((c = getc (fmem)) != EOF && c != '\n')
3072 continue;
3073 done = c == EOF;
3074 break;
3076 default:
3077 done = 1;
3078 break;
3080 while (!done);
3082 fclose (fmem);
3084 unblock_input ();
3085 return retval;
3088 Lisp_Object
3089 system_process_attributes (Lisp_Object pid)
3091 char procfn[PATH_MAX], fn[PATH_MAX];
3092 struct stat st;
3093 struct passwd *pw;
3094 struct group *gr;
3095 long clocks_per_sec;
3096 char *procfn_end;
3097 char procbuf[1025], *p, *q;
3098 int fd;
3099 ssize_t nread;
3100 static char const default_cmd[] = "???";
3101 const char *cmd = default_cmd;
3102 int cmdsize = sizeof default_cmd - 1;
3103 char *cmdline = NULL;
3104 ptrdiff_t cmdline_size;
3105 char c;
3106 printmax_t proc_id;
3107 int ppid, pgrp, sess, tty, tpgid, thcount;
3108 uid_t uid;
3109 gid_t gid;
3110 unsigned long long u_time, s_time, cutime, cstime, start;
3111 long priority, niceness, rss;
3112 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3113 struct timespec tnow, tstart, tboot, telapsed, us_time;
3114 double pcpu, pmem;
3115 Lisp_Object attrs = Qnil;
3116 Lisp_Object decoded_cmd;
3117 ptrdiff_t count;
3119 CHECK_NUMBER_OR_FLOAT (pid);
3120 CONS_TO_INTEGER (pid, pid_t, proc_id);
3121 sprintf (procfn, "/proc/%"pMd, proc_id);
3122 if (stat (procfn, &st) < 0)
3123 return attrs;
3125 /* euid egid */
3126 uid = st.st_uid;
3127 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3128 block_input ();
3129 pw = getpwuid (uid);
3130 unblock_input ();
3131 if (pw)
3132 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3134 gid = st.st_gid;
3135 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3136 block_input ();
3137 gr = getgrgid (gid);
3138 unblock_input ();
3139 if (gr)
3140 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3142 count = SPECPDL_INDEX ();
3143 strcpy (fn, procfn);
3144 procfn_end = fn + strlen (fn);
3145 strcpy (procfn_end, "/stat");
3146 fd = emacs_open (fn, O_RDONLY, 0);
3147 if (fd < 0)
3148 nread = 0;
3149 else
3151 record_unwind_protect_int (close_file_unwind, fd);
3152 nread = emacs_read (fd, procbuf, sizeof procbuf - 1);
3154 if (0 < nread)
3156 procbuf[nread] = '\0';
3157 p = procbuf;
3159 p = strchr (p, '(');
3160 if (p != NULL)
3162 q = strrchr (p + 1, ')');
3163 /* comm */
3164 if (q != NULL)
3166 cmd = p + 1;
3167 cmdsize = q - cmd;
3170 else
3171 q = NULL;
3172 /* Command name is encoded in locale-coding-system; decode it. */
3173 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3174 decoded_cmd = code_convert_string_norecord (cmd_str,
3175 Vlocale_coding_system, 0);
3176 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3178 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3179 utime stime cutime cstime priority nice thcount . start vsize rss */
3180 if (q
3181 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3182 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3183 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3184 &minflt, &cminflt, &majflt, &cmajflt,
3185 &u_time, &s_time, &cutime, &cstime,
3186 &priority, &niceness, &thcount, &start, &vsize, &rss)
3187 == 20))
3189 char state_str[2];
3190 state_str[0] = c;
3191 state_str[1] = '\0';
3192 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3193 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3194 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3195 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3196 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3197 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3198 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3199 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3200 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3201 attrs);
3202 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3203 attrs);
3204 clocks_per_sec = sysconf (_SC_CLK_TCK);
3205 if (clocks_per_sec < 0)
3206 clocks_per_sec = 100;
3207 attrs = Fcons (Fcons (Qutime,
3208 ltime_from_jiffies (u_time, clocks_per_sec)),
3209 attrs);
3210 attrs = Fcons (Fcons (Qstime,
3211 ltime_from_jiffies (s_time, clocks_per_sec)),
3212 attrs);
3213 attrs = Fcons (Fcons (Qtime,
3214 ltime_from_jiffies (s_time + u_time,
3215 clocks_per_sec)),
3216 attrs);
3217 attrs = Fcons (Fcons (Qcutime,
3218 ltime_from_jiffies (cutime, clocks_per_sec)),
3219 attrs);
3220 attrs = Fcons (Fcons (Qcstime,
3221 ltime_from_jiffies (cstime, clocks_per_sec)),
3222 attrs);
3223 attrs = Fcons (Fcons (Qctime,
3224 ltime_from_jiffies (cstime + cutime,
3225 clocks_per_sec)),
3226 attrs);
3227 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3228 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3229 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3230 attrs);
3231 tnow = current_timespec ();
3232 telapsed = get_up_time ();
3233 tboot = timespec_sub (tnow, telapsed);
3234 tstart = time_from_jiffies (start, clocks_per_sec);
3235 tstart = timespec_add (tboot, tstart);
3236 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3237 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3238 attrs);
3239 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3240 telapsed = timespec_sub (tnow, tstart);
3241 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3242 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3243 pcpu = timespectod (us_time) / timespectod (telapsed);
3244 if (pcpu > 1.0)
3245 pcpu = 1.0;
3246 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3247 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3248 if (pmem > 100)
3249 pmem = 100;
3250 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3253 unbind_to (count, Qnil);
3255 /* args */
3256 strcpy (procfn_end, "/cmdline");
3257 fd = emacs_open (fn, O_RDONLY, 0);
3258 if (fd >= 0)
3260 ptrdiff_t readsize, nread_incr;
3261 record_unwind_protect_int (close_file_unwind, fd);
3262 record_unwind_protect_nothing ();
3263 nread = cmdline_size = 0;
3267 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3268 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3270 /* Leave room even if every byte needs escaping below. */
3271 readsize = (cmdline_size >> 1) - nread;
3273 nread_incr = emacs_read (fd, cmdline + nread, readsize);
3274 nread += max (0, nread_incr);
3276 while (nread_incr == readsize);
3278 if (nread)
3280 /* We don't want trailing null characters. */
3281 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3282 continue;
3284 /* Escape-quote whitespace and backslashes. */
3285 q = cmdline + cmdline_size;
3286 while (cmdline < p)
3288 char c = *--p;
3289 *--q = c ? c : ' ';
3290 if (c_isspace (c) || c == '\\')
3291 *--q = '\\';
3294 nread = cmdline + cmdline_size - q;
3297 if (!nread)
3299 nread = cmdsize + 2;
3300 cmdline_size = nread + 1;
3301 q = cmdline = xrealloc (cmdline, cmdline_size);
3302 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3303 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3305 /* Command line is encoded in locale-coding-system; decode it. */
3306 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3307 decoded_cmd = code_convert_string_norecord (cmd_str,
3308 Vlocale_coding_system, 0);
3309 unbind_to (count, Qnil);
3310 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3313 return attrs;
3316 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3318 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3319 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3320 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3321 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3322 #undef _FILE_OFFSET_BITS
3323 #else
3324 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3325 #endif
3327 #include <procfs.h>
3329 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3330 #define _FILE_OFFSET_BITS 64
3331 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3332 #endif
3333 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3335 Lisp_Object
3336 system_process_attributes (Lisp_Object pid)
3338 char procfn[PATH_MAX], fn[PATH_MAX];
3339 struct stat st;
3340 struct passwd *pw;
3341 struct group *gr;
3342 char *procfn_end;
3343 struct psinfo pinfo;
3344 int fd;
3345 ssize_t nread;
3346 printmax_t proc_id;
3347 uid_t uid;
3348 gid_t gid;
3349 Lisp_Object attrs = Qnil;
3350 Lisp_Object decoded_cmd;
3351 ptrdiff_t count;
3353 CHECK_NUMBER_OR_FLOAT (pid);
3354 CONS_TO_INTEGER (pid, pid_t, proc_id);
3355 sprintf (procfn, "/proc/%"pMd, proc_id);
3356 if (stat (procfn, &st) < 0)
3357 return attrs;
3359 /* euid egid */
3360 uid = st.st_uid;
3361 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3362 block_input ();
3363 pw = getpwuid (uid);
3364 unblock_input ();
3365 if (pw)
3366 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3368 gid = st.st_gid;
3369 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3370 block_input ();
3371 gr = getgrgid (gid);
3372 unblock_input ();
3373 if (gr)
3374 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3376 count = SPECPDL_INDEX ();
3377 strcpy (fn, procfn);
3378 procfn_end = fn + strlen (fn);
3379 strcpy (procfn_end, "/psinfo");
3380 fd = emacs_open (fn, O_RDONLY, 0);
3381 if (fd < 0)
3382 nread = 0;
3383 else
3385 record_unwind_protect_int (close_file_unwind, fd);
3386 nread = emacs_read (fd, &pinfo, sizeof pinfo);
3389 if (nread == sizeof pinfo)
3391 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3392 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3393 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3396 char state_str[2];
3397 state_str[0] = pinfo.pr_lwp.pr_sname;
3398 state_str[1] = '\0';
3399 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3402 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3403 need to get a string from it. */
3405 /* FIXME: missing: Qtpgid */
3407 /* FIXME: missing:
3408 Qminflt
3409 Qmajflt
3410 Qcminflt
3411 Qcmajflt
3413 Qutime
3414 Qcutime
3415 Qstime
3416 Qcstime
3417 Are they available? */
3419 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3420 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3421 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3422 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3423 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3424 attrs);
3426 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3427 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3428 attrs);
3429 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3430 attrs);
3432 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3433 range 0 .. 2**15, representing 0.0 .. 1.0. */
3434 attrs = Fcons (Fcons (Qpcpu,
3435 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3436 attrs);
3437 attrs = Fcons (Fcons (Qpmem,
3438 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3439 attrs);
3441 AUTO_STRING (fname, pinfo.pr_fname);
3442 decoded_cmd = code_convert_string_norecord (fname,
3443 Vlocale_coding_system, 0);
3444 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3445 AUTO_STRING (psargs, pinfo.pr_psargs);
3446 decoded_cmd = code_convert_string_norecord (psargs,
3447 Vlocale_coding_system, 0);
3448 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3450 unbind_to (count, Qnil);
3451 return attrs;
3454 #elif defined __FreeBSD__
3456 static struct timespec
3457 timeval_to_timespec (struct timeval t)
3459 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3462 static Lisp_Object
3463 make_lisp_timeval (struct timeval t)
3465 return make_lisp_time (timeval_to_timespec (t));
3468 Lisp_Object
3469 system_process_attributes (Lisp_Object pid)
3471 int proc_id;
3472 int pagesize = getpagesize ();
3473 unsigned long npages;
3474 int fscale;
3475 struct passwd *pw;
3476 struct group *gr;
3477 char *ttyname;
3478 size_t len;
3479 char args[MAXPATHLEN];
3480 struct timespec t, now;
3482 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3483 struct kinfo_proc proc;
3484 size_t proclen = sizeof proc;
3486 Lisp_Object attrs = Qnil;
3487 Lisp_Object decoded_comm;
3489 CHECK_NUMBER_OR_FLOAT (pid);
3490 CONS_TO_INTEGER (pid, int, proc_id);
3491 mib[3] = proc_id;
3493 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3494 return attrs;
3496 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3498 block_input ();
3499 pw = getpwuid (proc.ki_uid);
3500 unblock_input ();
3501 if (pw)
3502 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3504 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3506 block_input ();
3507 gr = getgrgid (proc.ki_svgid);
3508 unblock_input ();
3509 if (gr)
3510 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3512 AUTO_STRING (comm, proc.ki_comm);
3513 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3515 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3517 char state[2] = {'\0', '\0'};
3518 switch (proc.ki_stat)
3520 case SRUN:
3521 state[0] = 'R';
3522 break;
3524 case SSLEEP:
3525 state[0] = 'S';
3526 break;
3528 case SLOCK:
3529 state[0] = 'D';
3530 break;
3532 case SZOMB:
3533 state[0] = 'Z';
3534 break;
3536 case SSTOP:
3537 state[0] = 'T';
3538 break;
3540 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3543 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3544 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3545 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3547 block_input ();
3548 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3549 unblock_input ();
3550 if (ttyname)
3551 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3553 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3554 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3555 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3556 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3557 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3559 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3560 attrs);
3561 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3562 attrs);
3563 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3564 timeval_to_timespec (proc.ki_rusage.ru_stime));
3565 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3567 attrs = Fcons (Fcons (Qcutime,
3568 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3569 attrs);
3570 attrs = Fcons (Fcons (Qcstime,
3571 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3572 attrs);
3573 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3574 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3575 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3577 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3578 attrs);
3579 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3580 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3581 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3582 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3583 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3584 attrs);
3586 now = current_timespec ();
3587 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3588 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3590 len = sizeof fscale;
3591 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3593 double pcpu;
3594 fixpt_t ccpu;
3595 len = sizeof ccpu;
3596 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3598 pcpu = (100.0 * proc.ki_pctcpu / fscale
3599 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3600 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3604 len = sizeof npages;
3605 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3607 double pmem = (proc.ki_flag & P_INMEM
3608 ? 100.0 * proc.ki_rssize / npages
3609 : 0);
3610 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3613 mib[2] = KERN_PROC_ARGS;
3614 len = MAXPATHLEN;
3615 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3617 int i;
3618 for (i = 0; i < len; i++)
3620 if (! args[i] && i < len - 1)
3621 args[i] = ' ';
3624 AUTO_STRING (comm, args);
3625 decoded_comm = code_convert_string_norecord (comm,
3626 Vlocale_coding_system, 0);
3628 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3631 return attrs;
3634 #elif defined DARWIN_OS
3636 static struct timespec
3637 timeval_to_timespec (struct timeval t)
3639 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3642 static Lisp_Object
3643 make_lisp_timeval (struct timeval t)
3645 return make_lisp_time (timeval_to_timespec (t));
3648 Lisp_Object
3649 system_process_attributes (Lisp_Object pid)
3651 int proc_id;
3652 int pagesize = getpagesize ();
3653 unsigned long npages;
3654 int fscale;
3655 struct passwd *pw;
3656 struct group *gr;
3657 char *ttyname;
3658 size_t len;
3659 char args[MAXPATHLEN];
3660 struct timeval starttime;
3661 struct timespec t, now;
3662 struct rusage *rusage;
3663 dev_t tdev;
3664 uid_t uid;
3665 gid_t gid;
3667 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3668 struct kinfo_proc proc;
3669 size_t proclen = sizeof proc;
3671 Lisp_Object attrs = Qnil;
3672 Lisp_Object decoded_comm;
3674 CHECK_NUMBER_OR_FLOAT (pid);
3675 CONS_TO_INTEGER (pid, int, proc_id);
3676 mib[3] = proc_id;
3678 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3679 return attrs;
3681 uid = proc.kp_eproc.e_ucred.cr_uid;
3682 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3684 block_input ();
3685 pw = getpwuid (uid);
3686 unblock_input ();
3687 if (pw)
3688 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3690 gid = proc.kp_eproc.e_pcred.p_svgid;
3691 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3693 block_input ();
3694 gr = getgrgid (gid);
3695 unblock_input ();
3696 if (gr)
3697 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3699 decoded_comm = (code_convert_string_norecord
3700 (build_unibyte_string (proc.kp_proc.p_comm),
3701 Vlocale_coding_system, 0));
3703 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3705 char state[2] = {'\0', '\0'};
3706 switch (proc.kp_proc.p_stat)
3708 case SRUN:
3709 state[0] = 'R';
3710 break;
3712 case SSLEEP:
3713 state[0] = 'S';
3714 break;
3716 case SZOMB:
3717 state[0] = 'Z';
3718 break;
3720 case SSTOP:
3721 state[0] = 'T';
3722 break;
3724 case SIDL:
3725 state[0] = 'I';
3726 break;
3728 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3731 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3732 attrs);
3733 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3734 attrs);
3736 tdev = proc.kp_eproc.e_tdev;
3737 block_input ();
3738 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3739 unblock_input ();
3740 if (ttyname)
3741 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3743 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3744 attrs);
3746 rusage = proc.kp_proc.p_ru;
3747 if (rusage)
3749 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3750 attrs);
3751 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3752 attrs);
3754 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3755 attrs);
3756 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3757 attrs);
3758 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3759 timeval_to_timespec (rusage->ru_stime));
3760 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3763 starttime = proc.kp_proc.p_starttime;
3764 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3765 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3767 now = current_timespec ();
3768 t = timespec_sub (now, timeval_to_timespec (starttime));
3769 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3771 return attrs;
3774 /* The WINDOWSNT implementation is in w32.c.
3775 The MSDOS implementation is in dosfns.c. */
3776 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3778 Lisp_Object
3779 system_process_attributes (Lisp_Object pid)
3781 return Qnil;
3784 #endif /* !defined (WINDOWSNT) */
3786 /* Wide character string collation. */
3788 #ifdef __STDC_ISO_10646__
3789 # include <wchar.h>
3790 # include <wctype.h>
3792 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3793 # include <locale.h>
3794 # endif
3795 # ifndef LC_COLLATE
3796 # define LC_COLLATE 0
3797 # endif
3798 # ifndef LC_COLLATE_MASK
3799 # define LC_COLLATE_MASK 0
3800 # endif
3801 # ifndef LC_CTYPE
3802 # define LC_CTYPE 0
3803 # endif
3804 # ifndef LC_CTYPE_MASK
3805 # define LC_CTYPE_MASK 0
3806 # endif
3808 # ifndef HAVE_NEWLOCALE
3809 # undef freelocale
3810 # undef locale_t
3811 # undef newlocale
3812 # undef wcscoll_l
3813 # undef towlower_l
3814 # define freelocale emacs_freelocale
3815 # define locale_t emacs_locale_t
3816 # define newlocale emacs_newlocale
3817 # define wcscoll_l emacs_wcscoll_l
3818 # define towlower_l emacs_towlower_l
3820 typedef char const *locale_t;
3822 static locale_t
3823 newlocale (int category_mask, char const *locale, locale_t loc)
3825 return locale;
3828 static void
3829 freelocale (locale_t loc)
3833 static char *
3834 emacs_setlocale (int category, char const *locale)
3836 # ifdef HAVE_SETLOCALE
3837 errno = 0;
3838 char *loc = setlocale (category, locale);
3839 if (loc || errno)
3840 return loc;
3841 errno = EINVAL;
3842 # else
3843 errno = ENOTSUP;
3844 # endif
3845 return 0;
3848 static int
3849 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3851 int result = 0;
3852 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3853 int err;
3855 if (! oldloc)
3856 err = errno;
3857 else
3859 USE_SAFE_ALLOCA;
3860 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3861 strcpy (oldcopy, oldloc);
3862 if (! emacs_setlocale (LC_COLLATE, loc))
3863 err = errno;
3864 else
3866 errno = 0;
3867 result = wcscoll (a, b);
3868 err = errno;
3869 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3870 err = errno;
3872 SAFE_FREE ();
3875 errno = err;
3876 return result;
3879 static wint_t
3880 towlower_l (wint_t wc, locale_t loc)
3882 wint_t result = wc;
3883 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3885 if (oldloc)
3887 USE_SAFE_ALLOCA;
3888 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3889 strcpy (oldcopy, oldloc);
3890 if (emacs_setlocale (LC_CTYPE, loc))
3892 result = towlower (wc);
3893 emacs_setlocale (LC_COLLATE, oldcopy);
3895 SAFE_FREE ();
3898 return result;
3900 # endif
3903 str_collate (Lisp_Object s1, Lisp_Object s2,
3904 Lisp_Object locale, Lisp_Object ignore_case)
3906 int res, err;
3907 ptrdiff_t len, i, i_byte;
3908 wchar_t *p1, *p2;
3910 USE_SAFE_ALLOCA;
3912 /* Convert byte stream to code points. */
3913 len = SCHARS (s1); i = i_byte = 0;
3914 SAFE_NALLOCA (p1, 1, len + 1);
3915 while (i < len)
3916 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3917 *(p1+len) = 0;
3919 len = SCHARS (s2); i = i_byte = 0;
3920 SAFE_NALLOCA (p2, 1, len + 1);
3921 while (i < len)
3922 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3923 *(p2+len) = 0;
3925 if (STRINGP (locale))
3927 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3928 SSDATA (locale), 0);
3929 if (!loc)
3930 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
3932 if (! NILP (ignore_case))
3933 for (int i = 1; i < 3; i++)
3935 wchar_t *p = (i == 1) ? p1 : p2;
3936 for (; *p; p++)
3937 *p = towlower_l (*p, loc);
3940 errno = 0;
3941 res = wcscoll_l (p1, p2, loc);
3942 err = errno;
3943 freelocale (loc);
3945 else
3947 if (! NILP (ignore_case))
3948 for (int i = 1; i < 3; i++)
3950 wchar_t *p = (i == 1) ? p1 : p2;
3951 for (; *p; p++)
3952 *p = towlower (*p);
3955 errno = 0;
3956 res = wcscoll (p1, p2);
3957 err = errno;
3959 # ifndef HAVE_NEWLOCALE
3960 if (err)
3961 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
3962 # else
3963 if (err)
3964 error ("Invalid string for collation: %s", emacs_strerror (err));
3965 # endif
3967 SAFE_FREE ();
3968 return res;
3970 #endif /* __STDC_ISO_10646__ */
3972 #ifdef WINDOWSNT
3974 str_collate (Lisp_Object s1, Lisp_Object s2,
3975 Lisp_Object locale, Lisp_Object ignore_case)
3978 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
3979 int res, err = errno;
3981 errno = 0;
3982 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
3983 if (errno)
3984 error ("Invalid string for collation: %s", strerror (errno));
3986 errno = err;
3987 return res;
3989 #endif /* WINDOWSNT */