Guard terminal parameter in XTerm mouse mode
[emacs.git] / src / sysdep.c
blob892e97626bd92fe9eb8653882df9b2fdc1f77aa3
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 WINDOWSNT
55 #define read sys_read
56 #define write sys_write
57 #ifndef STDERR_FILENO
58 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
59 #endif
60 #include <windows.h>
61 #endif /* not WINDOWSNT */
63 #include <sys/types.h>
64 #include <sys/stat.h>
65 #include <errno.h>
67 /* Get SI_SRPC_DOMAIN, if it is available. */
68 #ifdef HAVE_SYS_SYSTEMINFO_H
69 #include <sys/systeminfo.h>
70 #endif
72 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
73 #include "msdos.h"
74 #endif
76 #include <sys/param.h>
77 #include <sys/file.h>
78 #include <fcntl.h>
80 #include "systty.h"
81 #include "syswait.h"
83 #ifdef HAVE_SYS_UTSNAME_H
84 #include <sys/utsname.h>
85 #include <memory.h>
86 #endif /* HAVE_SYS_UTSNAME_H */
88 #include "keyboard.h"
89 #include "frame.h"
90 #include "termhooks.h"
91 #include "termchar.h"
92 #include "termopts.h"
93 #include "process.h"
94 #include "cm.h"
96 #include "gnutls.h"
97 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
98 do that during startup just to call gnutls_rnd. */
99 #if defined HAVE_GNUTLS && !defined WINDOWSNT
100 # include <gnutls/crypto.h>
101 #else
102 # define emacs_gnutls_global_init() Qnil
103 # define gnutls_rnd(level, data, len) (-1)
104 #endif
106 #ifdef WINDOWSNT
107 #include <direct.h>
108 /* In process.h which conflicts with the local copy. */
109 #define _P_WAIT 0
110 int _cdecl _spawnlp (int, const char *, const char *, ...);
111 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
112 several prototypes of functions called below. */
113 #include <sys/socket.h>
114 #endif
116 #include "syssignal.h"
117 #include "systime.h"
119 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
120 #ifndef ULLONG_MAX
121 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
122 #endif
124 /* Declare here, including term.h is problematic on some systems. */
125 extern void tputs (const char *, int, int (*)(int));
127 static const int baud_convert[] =
129 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
130 1800, 2400, 4800, 9600, 19200, 38400
133 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
134 # include <sys/personality.h>
136 /* Disable address randomization in the current process. Return true
137 if addresses were randomized but this has been disabled, false
138 otherwise. */
139 bool
140 disable_address_randomization (void)
142 bool disabled = false;
143 int pers = personality (0xffffffff);
144 disabled = (! (pers & ADDR_NO_RANDOMIZE)
145 && 0 <= personality (pers | ADDR_NO_RANDOMIZE));
146 return disabled;
148 #endif
150 /* Execute the program in FILE, with argument vector ARGV and environ
151 ENVP. Return an error number if unsuccessful. This is like execve
152 except it reenables ASLR in the executed program if necessary, and
153 on error it returns an error number rather than -1. */
155 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
157 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
158 int pers = getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
159 bool change_personality = 0 <= pers && pers & ADDR_NO_RANDOMIZE;
160 if (change_personality)
161 personality (pers & ~ADDR_NO_RANDOMIZE);
162 #endif
164 execve (file, argv, envp);
165 int err = errno;
167 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
168 if (change_personality)
169 personality (pers);
170 #endif
172 return err;
175 /* If FD is not already open, arrange for it to be open with FLAGS. */
176 static void
177 force_open (int fd, int flags)
179 if (dup2 (fd, fd) < 0 && errno == EBADF)
181 int n = open (NULL_DEVICE, flags);
182 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
184 emacs_perror (NULL_DEVICE);
185 exit (EXIT_FAILURE);
190 /* Make sure stdin, stdout, and stderr are open to something, so that
191 their file descriptors are not hijacked by later system calls. */
192 void
193 init_standard_fds (void)
195 /* Open stdin for *writing*, and stdout and stderr for *reading*.
196 That way, any attempt to do normal I/O will result in an error,
197 just as if the files were closed, and the file descriptors will
198 not be reused by later opens. */
199 force_open (STDIN_FILENO, O_WRONLY);
200 force_open (STDOUT_FILENO, O_RDONLY);
201 force_open (STDERR_FILENO, O_RDONLY);
204 /* Return the current working directory. The result should be freed
205 with 'free'. Return NULL on errors. */
206 char *
207 emacs_get_current_dir_name (void)
209 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
210 # ifdef HYBRID_MALLOC
211 bool use_libc = bss_sbrk_did_unexec;
212 # else
213 bool use_libc = true;
214 # endif
215 if (use_libc)
216 return get_current_dir_name ();
217 # endif
219 char *buf;
220 char *pwd = getenv ("PWD");
221 struct stat dotstat, pwdstat;
222 /* If PWD is accurate, use it instead of calling getcwd. PWD is
223 sometimes a nicer name, and using it may avoid a fatal error if a
224 parent directory is searchable but not readable. */
225 if (pwd
226 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
227 && stat (pwd, &pwdstat) == 0
228 && stat (".", &dotstat) == 0
229 && dotstat.st_ino == pwdstat.st_ino
230 && dotstat.st_dev == pwdstat.st_dev
231 #ifdef MAXPATHLEN
232 && strlen (pwd) < MAXPATHLEN
233 #endif
236 buf = malloc (strlen (pwd) + 1);
237 if (!buf)
238 return NULL;
239 strcpy (buf, pwd);
241 else
243 size_t buf_size = 1024;
244 buf = malloc (buf_size);
245 if (!buf)
246 return NULL;
247 for (;;)
249 if (getcwd (buf, buf_size) == buf)
250 break;
251 if (errno != ERANGE)
253 int tmp_errno = errno;
254 free (buf);
255 errno = tmp_errno;
256 return NULL;
258 buf_size *= 2;
259 buf = realloc (buf, buf_size);
260 if (!buf)
261 return NULL;
264 return buf;
268 /* Discard pending input on all input descriptors. */
270 void
271 discard_tty_input (void)
273 #ifndef WINDOWSNT
274 struct emacs_tty buf;
276 if (noninteractive)
277 return;
279 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
280 while (dos_keyread () != -1)
282 #else /* not MSDOS */
284 struct tty_display_info *tty;
285 for (tty = tty_list; tty; tty = tty->next)
287 if (tty->input) /* Is the device suspended? */
289 emacs_get_tty (fileno (tty->input), &buf);
290 emacs_set_tty (fileno (tty->input), &buf, 0);
294 #endif /* not MSDOS */
295 #endif /* not WINDOWSNT */
299 #ifdef SIGTSTP
301 /* Arrange for character C to be read as the next input from
302 the terminal.
303 XXX What if we have multiple ttys?
306 void
307 stuff_char (char c)
309 if (! (FRAMEP (selected_frame)
310 && FRAME_LIVE_P (XFRAME (selected_frame))
311 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
312 return;
314 /* Should perhaps error if in batch mode */
315 #ifdef TIOCSTI
316 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
317 #else /* no TIOCSTI */
318 error ("Cannot stuff terminal input characters in this version of Unix");
319 #endif /* no TIOCSTI */
322 #endif /* SIGTSTP */
324 void
325 init_baud_rate (int fd)
327 int emacs_ospeed;
329 if (noninteractive)
330 emacs_ospeed = 0;
331 else
333 #ifdef DOS_NT
334 emacs_ospeed = 15;
335 #else /* not DOS_NT */
336 struct termios sg;
338 sg.c_cflag = B9600;
339 tcgetattr (fd, &sg);
340 emacs_ospeed = cfgetospeed (&sg);
341 #endif /* not DOS_NT */
344 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
345 ? baud_convert[emacs_ospeed] : 9600);
346 if (baud_rate == 0)
347 baud_rate = 1200;
352 #ifndef MSDOS
354 /* Wait for the subprocess with process id CHILD to terminate or change status.
355 CHILD must be a child process that has not been reaped.
356 If STATUS is non-null, store the waitpid-style exit status into *STATUS
357 and tell wait_reading_process_output that it needs to look around.
358 Use waitpid-style OPTIONS when waiting.
359 If INTERRUPTIBLE, this function is interruptible by a signal.
361 Return CHILD if successful, 0 if no status is available;
362 the latter is possible only when options & NOHANG. */
363 static pid_t
364 get_child_status (pid_t child, int *status, int options, bool interruptible)
366 pid_t pid;
368 /* Invoke waitpid only with a known process ID; do not invoke
369 waitpid with a nonpositive argument. Otherwise, Emacs might
370 reap an unwanted process by mistake. For example, invoking
371 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
372 so that another thread running glib won't find them. */
373 eassert (child > 0);
375 while ((pid = waitpid (child, status, options)) < 0)
377 /* Check that CHILD is a child process that has not been reaped,
378 and that STATUS and OPTIONS are valid. Otherwise abort,
379 as continuing after this internal error could cause Emacs to
380 become confused and kill innocent-victim processes. */
381 if (errno != EINTR)
382 emacs_abort ();
384 /* Note: the MS-Windows emulation of waitpid calls QUIT
385 internally. */
386 if (interruptible)
387 QUIT;
390 /* If successful and status is requested, tell wait_reading_process_output
391 that it needs to wake up and look around. */
392 if (pid && status && input_available_clear_time)
393 *input_available_clear_time = make_timespec (0, 0);
395 return pid;
398 /* Wait for the subprocess with process id CHILD to terminate.
399 CHILD must be a child process that has not been reaped.
400 If STATUS is non-null, store the waitpid-style exit status into *STATUS
401 and tell wait_reading_process_output that it needs to look around.
402 If INTERRUPTIBLE, this function is interruptible by a signal. */
403 void
404 wait_for_termination (pid_t child, int *status, bool interruptible)
406 get_child_status (child, status, 0, interruptible);
409 /* Report whether the subprocess with process id CHILD has changed status.
410 Termination counts as a change of status.
411 CHILD must be a child process that has not been reaped.
412 If STATUS is non-null, store the waitpid-style exit status into *STATUS
413 and tell wait_reading_process_output that it needs to look around.
414 Use waitpid-style OPTIONS to check status, but do not wait.
416 Return CHILD if successful, 0 if no status is available because
417 the process's state has not changed. */
418 pid_t
419 child_status_changed (pid_t child, int *status, int options)
421 return get_child_status (child, status, WNOHANG | options, 0);
425 /* Set up the terminal at the other end of a pseudo-terminal that
426 we will be controlling an inferior through.
427 It should not echo or do line-editing, since that is done
428 in Emacs. No padding needed for insertion into an Emacs buffer. */
430 void
431 child_setup_tty (int out)
433 #ifndef WINDOWSNT
434 struct emacs_tty s;
436 emacs_get_tty (out, &s);
437 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
438 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
439 #ifdef NLDLY
440 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
441 Some versions of GNU Hurd do not have FFDLY? */
442 #ifdef FFDLY
443 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
444 /* No output delays */
445 #else
446 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
447 /* No output delays */
448 #endif
449 #endif
450 s.main.c_lflag &= ~ECHO; /* Disable echo */
451 s.main.c_lflag |= ISIG; /* Enable signals */
452 #ifdef IUCLC
453 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
454 #endif
455 #ifdef ISTRIP
456 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
457 #endif
458 #ifdef OLCUC
459 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
460 #endif
461 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
462 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
463 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
464 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
466 #ifdef HPUX
467 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
468 #endif /* HPUX */
470 #ifdef SIGNALS_VIA_CHARACTERS
471 /* the QUIT and INTR character are used in process_send_signal
472 so set them here to something useful. */
473 if (s.main.c_cc[VQUIT] == CDISABLE)
474 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
475 if (s.main.c_cc[VINTR] == CDISABLE)
476 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
477 #endif /* not SIGNALS_VIA_CHARACTERS */
479 #ifdef AIX
480 /* Also, PTY overloads NUL and BREAK.
481 don't ignore break, but don't signal either, so it looks like NUL. */
482 s.main.c_iflag &= ~IGNBRK;
483 s.main.c_iflag &= ~BRKINT;
484 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
485 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
486 would force it to 0377. That looks like duplicated code. */
487 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
488 #endif /* AIX */
490 /* We originally enabled ICANON (and set VEOF to 04), and then had
491 process.c send additional EOF chars to flush the output when faced
492 with long lines, but this leads to weird effects when the
493 subprocess has disabled ICANON and ends up seeing those spurious
494 extra EOFs. So we don't send EOFs any more in
495 process.c:send_process. First we tried to disable ICANON by
496 default, so if a subsprocess sets up ICANON, it's his problem (or
497 the Elisp package that talks to it) to deal with lines that are
498 too long. But this disables some features, such as the ability
499 to send EOF signals. So we re-enabled ICANON but there is no
500 more "send eof to flush" going on (which is wrong and unportable
501 in itself). The correct way to handle too much output is to
502 buffer what could not be written and then write it again when
503 select returns ok for writing. This has it own set of
504 problems. Write is now asynchronous, is that a problem? How much
505 do we buffer, and what do we do when that limit is reached? */
507 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
508 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
509 #if 0 /* These settings only apply to non-ICANON mode. */
510 s.main.c_cc[VMIN] = 1;
511 s.main.c_cc[VTIME] = 0;
512 #endif
514 emacs_set_tty (out, &s, 0);
515 #endif /* not WINDOWSNT */
517 #endif /* not MSDOS */
520 /* Record a signal code and the action for it. */
521 struct save_signal
523 int code;
524 struct sigaction action;
527 static void save_signal_handlers (struct save_signal *);
528 static void restore_signal_handlers (struct save_signal *);
530 /* Suspend the Emacs process; give terminal to its superior. */
532 void
533 sys_suspend (void)
535 #ifndef DOS_NT
536 kill (0, SIGTSTP);
537 #else
538 /* On a system where suspending is not implemented,
539 instead fork a subshell and let it talk directly to the terminal
540 while we wait. */
541 sys_subshell ();
543 #endif
546 /* Fork a subshell. */
548 void
549 sys_subshell (void)
551 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
552 #ifdef MSDOS
553 int st;
554 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
555 #else
556 char oldwd[MAX_UTF8_PATH];
557 #endif /* MSDOS */
558 #else /* !DOS_NT */
559 int status;
560 #endif
561 pid_t pid;
562 struct save_signal saved_handlers[5];
563 char *str = SSDATA (encode_current_directory ());
565 #ifdef DOS_NT
566 pid = 0;
567 #else
569 char *volatile str_volatile = str;
570 pid = vfork ();
571 str = str_volatile;
573 #endif
575 if (pid < 0)
576 error ("Can't spawn subshell");
578 saved_handlers[0].code = SIGINT;
579 saved_handlers[1].code = SIGQUIT;
580 saved_handlers[2].code = SIGTERM;
581 #ifdef USABLE_SIGIO
582 saved_handlers[3].code = SIGIO;
583 saved_handlers[4].code = 0;
584 #else
585 saved_handlers[3].code = 0;
586 #endif
588 #ifdef DOS_NT
589 save_signal_handlers (saved_handlers);
590 #endif
592 if (pid == 0)
594 const char *sh = 0;
596 #ifdef DOS_NT /* MW, Aug 1993 */
597 getcwd (oldwd, sizeof oldwd);
598 if (sh == 0)
599 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
600 #endif
601 if (sh == 0)
602 sh = egetenv ("SHELL");
603 if (sh == 0)
604 sh = "sh";
606 /* Use our buffer's default directory for the subshell. */
607 if (chdir (str) != 0)
609 #ifndef DOS_NT
610 emacs_perror (str);
611 _exit (EXIT_CANCELED);
612 #endif
615 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
617 char *epwd = getenv ("PWD");
618 char old_pwd[MAXPATHLEN+1+4];
620 /* If PWD is set, pass it with corrected value. */
621 if (epwd)
623 strcpy (old_pwd, epwd);
624 setenv ("PWD", str, 1);
626 st = system (sh);
627 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
628 if (epwd)
629 putenv (old_pwd); /* restore previous value */
631 #else /* not MSDOS */
632 #ifdef WINDOWSNT
633 /* Waits for process completion */
634 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
635 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
636 if (pid == -1)
637 write (1, "Can't execute subshell", 22);
638 #else /* not WINDOWSNT */
639 execlp (sh, sh, (char *) 0);
640 emacs_perror (sh);
641 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
642 #endif /* not WINDOWSNT */
643 #endif /* not MSDOS */
646 /* Do this now if we did not do it before. */
647 #ifndef MSDOS
648 save_signal_handlers (saved_handlers);
649 #endif
651 #ifndef DOS_NT
652 wait_for_termination (pid, &status, 0);
653 #endif
654 restore_signal_handlers (saved_handlers);
657 static void
658 save_signal_handlers (struct save_signal *saved_handlers)
660 while (saved_handlers->code)
662 struct sigaction action;
663 emacs_sigaction_init (&action, SIG_IGN);
664 sigaction (saved_handlers->code, &action, &saved_handlers->action);
665 saved_handlers++;
669 static void
670 restore_signal_handlers (struct save_signal *saved_handlers)
672 while (saved_handlers->code)
674 sigaction (saved_handlers->code, &saved_handlers->action, 0);
675 saved_handlers++;
679 #ifdef USABLE_SIGIO
680 static int old_fcntl_flags[FD_SETSIZE];
681 #endif
683 void
684 init_sigio (int fd)
686 #ifdef USABLE_SIGIO
687 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
688 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
689 interrupts_deferred = 0;
690 #endif
693 #ifndef DOS_NT
694 static void
695 reset_sigio (int fd)
697 #ifdef USABLE_SIGIO
698 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
699 #endif
701 #endif
703 void
704 request_sigio (void)
706 #ifdef USABLE_SIGIO
707 sigset_t unblocked;
709 if (noninteractive)
710 return;
712 sigemptyset (&unblocked);
713 # ifdef SIGWINCH
714 sigaddset (&unblocked, SIGWINCH);
715 # endif
716 sigaddset (&unblocked, SIGIO);
717 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
719 interrupts_deferred = 0;
720 #endif
723 void
724 unrequest_sigio (void)
726 #ifdef USABLE_SIGIO
727 sigset_t blocked;
729 if (noninteractive)
730 return;
732 sigemptyset (&blocked);
733 # ifdef SIGWINCH
734 sigaddset (&blocked, SIGWINCH);
735 # endif
736 sigaddset (&blocked, SIGIO);
737 pthread_sigmask (SIG_BLOCK, &blocked, 0);
738 interrupts_deferred = 1;
739 #endif
742 #ifndef MSDOS
743 /* Block SIGCHLD. */
745 void
746 block_child_signal (sigset_t *oldset)
748 sigset_t blocked;
749 sigemptyset (&blocked);
750 sigaddset (&blocked, SIGCHLD);
751 sigaddset (&blocked, SIGINT);
752 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
755 /* Unblock SIGCHLD. */
757 void
758 unblock_child_signal (sigset_t const *oldset)
760 pthread_sigmask (SIG_SETMASK, oldset, 0);
763 #endif /* !MSDOS */
765 /* Saving and restoring the process group of Emacs's terminal. */
767 /* The process group of which Emacs was a member when it initially
768 started.
770 If Emacs was in its own process group (i.e. inherited_pgroup ==
771 getpid ()), then we know we're running under a shell with job
772 control (Emacs would never be run as part of a pipeline).
773 Everything is fine.
775 If Emacs was not in its own process group, then we know we're
776 running under a shell (or a caller) that doesn't know how to
777 separate itself from Emacs (like sh). Emacs must be in its own
778 process group in order to receive SIGIO correctly. In this
779 situation, we put ourselves in our own pgroup, forcibly set the
780 tty's pgroup to our pgroup, and make sure to restore and reinstate
781 the tty's pgroup just like any other terminal setting. If
782 inherited_group was not the tty's pgroup, then we'll get a
783 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
784 it goes foreground in the future, which is what should happen. */
786 static pid_t inherited_pgroup;
788 void
789 init_foreground_group (void)
791 pid_t pgrp = getpgrp ();
792 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
795 /* Block and unblock SIGTTOU. */
797 void
798 block_tty_out_signal (sigset_t *oldset)
800 #ifdef SIGTTOU
801 sigset_t blocked;
802 sigemptyset (&blocked);
803 sigaddset (&blocked, SIGTTOU);
804 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
805 #endif
808 void
809 unblock_tty_out_signal (sigset_t const *oldset)
811 #ifdef SIGTTOU
812 pthread_sigmask (SIG_SETMASK, oldset, 0);
813 #endif
816 /* Safely set a controlling terminal FD's process group to PGID.
817 If we are not in the foreground already, POSIX requires tcsetpgrp
818 to deliver a SIGTTOU signal, which would stop us. This is an
819 annoyance, so temporarily ignore the signal.
821 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
822 skip all this unless SIGTTOU is defined. */
823 static void
824 tcsetpgrp_without_stopping (int fd, pid_t pgid)
826 #ifdef SIGTTOU
827 sigset_t oldset;
828 block_input ();
829 block_tty_out_signal (&oldset);
830 tcsetpgrp (fd, pgid);
831 unblock_tty_out_signal (&oldset);
832 unblock_input ();
833 #endif
836 /* Split off the foreground process group to Emacs alone. When we are
837 in the foreground, but not started in our own process group,
838 redirect the tty device handle FD to point to our own process
839 group. FD must be the file descriptor of the controlling tty. */
840 static void
841 narrow_foreground_group (int fd)
843 if (inherited_pgroup && setpgid (0, 0) == 0)
844 tcsetpgrp_without_stopping (fd, getpid ());
847 /* Set the tty to our original foreground group. */
848 static void
849 widen_foreground_group (int fd)
851 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
852 tcsetpgrp_without_stopping (fd, inherited_pgroup);
855 /* Getting and setting emacs_tty structures. */
857 /* Set *TC to the parameters associated with the terminal FD,
858 or clear it if the parameters are not available.
859 Return 0 on success, -1 on failure. */
861 emacs_get_tty (int fd, struct emacs_tty *settings)
863 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
864 memset (&settings->main, 0, sizeof (settings->main));
865 #ifdef DOS_NT
866 #ifdef WINDOWSNT
867 HANDLE h = (HANDLE)_get_osfhandle (fd);
868 DWORD console_mode;
870 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
872 settings->main = console_mode;
873 return 0;
875 #endif /* WINDOWSNT */
876 return -1;
877 #else /* !DOS_NT */
878 /* We have those nifty POSIX tcmumbleattr functions. */
879 return tcgetattr (fd, &settings->main);
880 #endif
884 /* Set the parameters of the tty on FD according to the contents of
885 *SETTINGS. If FLUSHP, discard input.
886 Return 0 if all went well, and -1 (setting errno) if anything failed. */
889 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
891 /* Set the primary parameters - baud rate, character size, etcetera. */
892 #ifdef DOS_NT
893 #ifdef WINDOWSNT
894 HANDLE h = (HANDLE)_get_osfhandle (fd);
896 if (h && h != INVALID_HANDLE_VALUE)
898 DWORD new_mode;
900 /* Assume the handle is open for input. */
901 if (flushp)
902 FlushConsoleInputBuffer (h);
903 new_mode = settings->main;
904 SetConsoleMode (h, new_mode);
906 #endif /* WINDOWSNT */
907 #else /* !DOS_NT */
908 int i;
909 /* We have those nifty POSIX tcmumbleattr functions.
910 William J. Smith <wjs@wiis.wang.com> writes:
911 "POSIX 1003.1 defines tcsetattr to return success if it was
912 able to perform any of the requested actions, even if some
913 of the requested actions could not be performed.
914 We must read settings back to ensure tty setup properly.
915 AIX requires this to keep tty from hanging occasionally." */
916 /* This make sure that we don't loop indefinitely in here. */
917 for (i = 0 ; i < 10 ; i++)
918 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
920 if (errno == EINTR)
921 continue;
922 else
923 return -1;
925 else
927 struct termios new;
929 memset (&new, 0, sizeof (new));
930 /* Get the current settings, and see if they're what we asked for. */
931 tcgetattr (fd, &new);
932 /* We cannot use memcmp on the whole structure here because under
933 * aix386 the termios structure has some reserved field that may
934 * not be filled in.
936 if ( new.c_iflag == settings->main.c_iflag
937 && new.c_oflag == settings->main.c_oflag
938 && new.c_cflag == settings->main.c_cflag
939 && new.c_lflag == settings->main.c_lflag
940 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
941 break;
942 else
943 continue;
945 #endif
947 /* We have survived the tempest. */
948 return 0;
953 #ifdef F_SETOWN
954 static int old_fcntl_owner[FD_SETSIZE];
955 #endif /* F_SETOWN */
957 /* This may also be defined in stdio,
958 but if so, this does no harm,
959 and using the same name avoids wasting the other one's space. */
961 #if defined (USG)
962 unsigned char _sobuf[BUFSIZ+8];
963 #else
964 char _sobuf[BUFSIZ];
965 #endif
967 /* Initialize the terminal mode on all tty devices that are currently
968 open. */
970 void
971 init_all_sys_modes (void)
973 struct tty_display_info *tty;
974 for (tty = tty_list; tty; tty = tty->next)
975 init_sys_modes (tty);
978 /* Initialize the terminal mode on the given tty device. */
980 void
981 init_sys_modes (struct tty_display_info *tty_out)
983 struct emacs_tty tty;
984 #ifndef DOS_NT
985 Lisp_Object terminal;
986 #endif
988 Vtty_erase_char = Qnil;
990 if (noninteractive)
991 return;
993 if (!tty_out->output)
994 return; /* The tty is suspended. */
996 narrow_foreground_group (fileno (tty_out->input));
998 if (! tty_out->old_tty)
999 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1001 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1003 tty = *tty_out->old_tty;
1005 #if !defined (DOS_NT)
1006 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1008 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1009 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1010 #ifdef INLCR /* I'm just being cautious,
1011 since I can't check how widespread INLCR is--rms. */
1012 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1013 #endif
1014 #ifdef ISTRIP
1015 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1016 #endif
1017 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1018 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1019 #ifdef IEXTEN
1020 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1021 #endif
1022 tty.main.c_lflag |= ISIG; /* Enable signals */
1023 if (tty_out->flow_control)
1025 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1026 #ifdef IXANY
1027 tty.main.c_iflag &= ~IXANY;
1028 #endif /* IXANY */
1030 else
1031 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1032 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1033 on output */
1034 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1035 #ifdef CS8
1036 if (tty_out->meta_key)
1038 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1039 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1041 #endif
1043 XSETTERMINAL(terminal, tty_out->terminal);
1044 if (!NILP (Fcontrolling_tty_p (terminal)))
1046 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1047 /* Set up C-g for both SIGQUIT and SIGINT.
1048 We don't know which we will get, but we handle both alike
1049 so which one it really gives us does not matter. */
1050 tty.main.c_cc[VQUIT] = quit_char;
1052 else
1054 /* We normally don't get interrupt or quit signals from tty
1055 devices other than our controlling terminal; therefore,
1056 we must handle C-g as normal input. Unfortunately, this
1057 means that the interrupt and quit feature must be
1058 disabled on secondary ttys, or we would not even see the
1059 keypress.
1061 Note that even though emacsclient could have special code
1062 to pass SIGINT to Emacs, we should _not_ enable
1063 interrupt/quit keys for emacsclient frames. This means
1064 that we can't break out of loops in C code from a
1065 secondary tty frame, but we can always decide what
1066 display the C-g came from, which is more important from a
1067 usability point of view. (Consider the case when two
1068 people work together using the same Emacs instance.) */
1069 tty.main.c_cc[VINTR] = CDISABLE;
1070 tty.main.c_cc[VQUIT] = CDISABLE;
1072 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1073 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1074 #ifdef VSWTCH
1075 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1076 of C-z */
1077 #endif /* VSWTCH */
1079 #ifdef VSUSP
1080 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1081 #endif /* VSUSP */
1082 #ifdef V_DSUSP
1083 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1084 #endif /* V_DSUSP */
1085 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1086 tty.main.c_cc[VDSUSP] = CDISABLE;
1087 #endif /* VDSUSP */
1088 #ifdef VLNEXT
1089 tty.main.c_cc[VLNEXT] = CDISABLE;
1090 #endif /* VLNEXT */
1091 #ifdef VREPRINT
1092 tty.main.c_cc[VREPRINT] = CDISABLE;
1093 #endif /* VREPRINT */
1094 #ifdef VWERASE
1095 tty.main.c_cc[VWERASE] = CDISABLE;
1096 #endif /* VWERASE */
1097 #ifdef VDISCARD
1098 tty.main.c_cc[VDISCARD] = CDISABLE;
1099 #endif /* VDISCARD */
1101 if (tty_out->flow_control)
1103 #ifdef VSTART
1104 tty.main.c_cc[VSTART] = '\021';
1105 #endif /* VSTART */
1106 #ifdef VSTOP
1107 tty.main.c_cc[VSTOP] = '\023';
1108 #endif /* VSTOP */
1110 else
1112 #ifdef VSTART
1113 tty.main.c_cc[VSTART] = CDISABLE;
1114 #endif /* VSTART */
1115 #ifdef VSTOP
1116 tty.main.c_cc[VSTOP] = CDISABLE;
1117 #endif /* VSTOP */
1120 #ifdef AIX
1121 tty.main.c_cc[VSTRT] = CDISABLE;
1122 tty.main.c_cc[VSTOP] = CDISABLE;
1123 tty.main.c_cc[VSUSP] = CDISABLE;
1124 tty.main.c_cc[VDSUSP] = CDISABLE;
1125 if (tty_out->flow_control)
1127 #ifdef VSTART
1128 tty.main.c_cc[VSTART] = '\021';
1129 #endif /* VSTART */
1130 #ifdef VSTOP
1131 tty.main.c_cc[VSTOP] = '\023';
1132 #endif /* VSTOP */
1134 /* Also, PTY overloads NUL and BREAK.
1135 don't ignore break, but don't signal either, so it looks like NUL.
1136 This really serves a purpose only if running in an XTERM window
1137 or via TELNET or the like, but does no harm elsewhere. */
1138 tty.main.c_iflag &= ~IGNBRK;
1139 tty.main.c_iflag &= ~BRKINT;
1140 #endif
1141 #endif /* not DOS_NT */
1143 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1144 if (!tty_out->term_initted)
1145 internal_terminal_init ();
1146 dos_ttraw (tty_out);
1147 #endif
1149 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1151 /* This code added to insure that, if flow-control is not to be used,
1152 we have an unlocked terminal at the start. */
1154 #ifdef TCXONC
1155 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1156 #endif
1157 #ifdef TIOCSTART
1158 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1159 #endif
1161 #if !defined (DOS_NT)
1162 #ifdef TCOON
1163 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1164 #endif
1165 #endif
1167 #ifdef F_GETOWN
1168 if (interrupt_input)
1170 old_fcntl_owner[fileno (tty_out->input)] =
1171 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1172 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1173 init_sigio (fileno (tty_out->input));
1174 #ifdef HAVE_GPM
1175 if (gpm_tty == tty_out)
1177 /* Arrange for mouse events to give us SIGIO signals. */
1178 fcntl (gpm_fd, F_SETOWN, getpid ());
1179 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1180 init_sigio (gpm_fd);
1182 #endif /* HAVE_GPM */
1184 #endif /* F_GETOWN */
1186 #ifdef _IOFBF
1187 /* This symbol is defined on recent USG systems.
1188 Someone says without this call USG won't really buffer the file
1189 even with a call to setbuf. */
1190 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1191 #else
1192 setbuf (tty_out->output, (char *) _sobuf);
1193 #endif
1195 if (tty_out->terminal->set_terminal_modes_hook)
1196 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1198 if (!tty_out->term_initted)
1200 Lisp_Object tail, frame;
1201 FOR_EACH_FRAME (tail, frame)
1203 /* XXX This needs to be revised. */
1204 if (FRAME_TERMCAP_P (XFRAME (frame))
1205 && FRAME_TTY (XFRAME (frame)) == tty_out)
1206 init_frame_faces (XFRAME (frame));
1210 if (tty_out->term_initted && no_redraw_on_reenter)
1212 /* We used to call "direct_output_forward_char(0)" here,
1213 but it's not clear why, since it may not do anything anyway. */
1215 else
1217 Lisp_Object tail, frame;
1218 frame_garbaged = 1;
1219 FOR_EACH_FRAME (tail, frame)
1221 if ((FRAME_TERMCAP_P (XFRAME (frame))
1222 || FRAME_MSDOS_P (XFRAME (frame)))
1223 && FRAME_TTY (XFRAME (frame)) == tty_out)
1224 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1228 tty_out->term_initted = 1;
1231 /* Return true if safe to use tabs in output.
1232 At the time this is called, init_sys_modes has not been done yet. */
1234 bool
1235 tabs_safe_p (int fd)
1237 struct emacs_tty etty;
1239 emacs_get_tty (fd, &etty);
1240 #ifndef DOS_NT
1241 #ifdef TABDLY
1242 return ((etty.main.c_oflag & TABDLY) != TAB3);
1243 #else /* not TABDLY */
1244 return 1;
1245 #endif /* not TABDLY */
1246 #else /* DOS_NT */
1247 return 0;
1248 #endif /* DOS_NT */
1251 /* Discard echoing. */
1253 void
1254 suppress_echo_on_tty (int fd)
1256 struct emacs_tty etty;
1258 emacs_get_tty (fd, &etty);
1259 #ifdef DOS_NT
1260 /* Set raw input mode. */
1261 etty.main = 0;
1262 #else
1263 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1264 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1265 #endif /* ! WINDOWSNT */
1266 emacs_set_tty (fd, &etty, 0);
1269 /* Get terminal size from system.
1270 Store number of lines into *HEIGHTP and width into *WIDTHP.
1271 We store 0 if there's no valid information. */
1273 void
1274 get_tty_size (int fd, int *widthp, int *heightp)
1276 #if defined TIOCGWINSZ
1278 /* BSD-style. */
1279 struct winsize size;
1281 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1282 *widthp = *heightp = 0;
1283 else
1285 *widthp = size.ws_col;
1286 *heightp = size.ws_row;
1289 #elif defined TIOCGSIZE
1291 /* SunOS - style. */
1292 struct ttysize size;
1294 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1295 *widthp = *heightp = 0;
1296 else
1298 *widthp = size.ts_cols;
1299 *heightp = size.ts_lines;
1302 #elif defined WINDOWSNT
1304 CONSOLE_SCREEN_BUFFER_INFO info;
1305 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1307 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1308 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1310 else
1311 *widthp = *heightp = 0;
1313 #elif defined MSDOS
1315 *widthp = ScreenCols ();
1316 *heightp = ScreenRows ();
1318 #else /* system doesn't know size */
1320 *widthp = 0;
1321 *heightp = 0;
1323 #endif
1326 /* Set the logical window size associated with descriptor FD
1327 to HEIGHT and WIDTH. This is used mainly with ptys.
1328 Return a negative value on failure. */
1331 set_window_size (int fd, int height, int width)
1333 #ifdef TIOCSWINSZ
1335 /* BSD-style. */
1336 struct winsize size;
1337 size.ws_row = height;
1338 size.ws_col = width;
1340 return ioctl (fd, TIOCSWINSZ, &size);
1342 #else
1343 #ifdef TIOCSSIZE
1345 /* SunOS - style. */
1346 struct ttysize size;
1347 size.ts_lines = height;
1348 size.ts_cols = width;
1350 return ioctl (fd, TIOCGSIZE, &size);
1351 #else
1352 return -1;
1353 #endif /* not SunOS-style */
1354 #endif /* not BSD-style */
1359 /* Prepare all terminal devices for exiting Emacs. */
1361 void
1362 reset_all_sys_modes (void)
1364 struct tty_display_info *tty;
1365 for (tty = tty_list; tty; tty = tty->next)
1366 reset_sys_modes (tty);
1369 /* Prepare the terminal for closing it; move the cursor to the
1370 bottom of the frame, turn off interrupt-driven I/O, etc. */
1372 void
1373 reset_sys_modes (struct tty_display_info *tty_out)
1375 if (noninteractive)
1377 fflush (stdout);
1378 return;
1380 if (!tty_out->term_initted)
1381 return;
1383 if (!tty_out->output)
1384 return; /* The tty is suspended. */
1386 /* Go to and clear the last line of the terminal. */
1388 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1390 /* Code adapted from tty_clear_end_of_line. */
1391 if (tty_out->TS_clr_line)
1393 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1395 else
1396 { /* have to do it the hard way */
1397 int i;
1398 tty_turn_off_insert (tty_out);
1400 for (i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1402 fputc (' ', tty_out->output);
1406 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1407 fflush (tty_out->output);
1409 if (tty_out->terminal->reset_terminal_modes_hook)
1410 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1412 /* Avoid possible loss of output when changing terminal modes. */
1413 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1414 continue;
1416 #ifndef DOS_NT
1417 #ifdef F_SETOWN
1418 if (interrupt_input)
1420 reset_sigio (fileno (tty_out->input));
1421 fcntl (fileno (tty_out->input), F_SETOWN,
1422 old_fcntl_owner[fileno (tty_out->input)]);
1424 #endif /* F_SETOWN */
1425 fcntl (fileno (tty_out->input), F_SETFL,
1426 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1427 #endif
1429 if (tty_out->old_tty)
1430 while (emacs_set_tty (fileno (tty_out->input),
1431 tty_out->old_tty, 0) < 0 && errno == EINTR)
1434 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1435 dos_ttcooked ();
1436 #endif
1438 widen_foreground_group (fileno (tty_out->input));
1441 #ifdef HAVE_PTYS
1443 /* Set up the proper status flags for use of a pty. */
1445 void
1446 setup_pty (int fd)
1448 /* I'm told that TOICREMOTE does not mean control chars
1449 "can't be sent" but rather that they don't have
1450 input-editing or signaling effects.
1451 That should be good, because we have other ways
1452 to do those things in Emacs.
1453 However, telnet mode seems not to work on 4.2.
1454 So TIOCREMOTE is turned off now. */
1456 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1457 will hang. In particular, the "timeout" feature (which
1458 causes a read to return if there is no data available)
1459 does this. Also it is known that telnet mode will hang
1460 in such a way that Emacs must be stopped (perhaps this
1461 is the same problem).
1463 If TIOCREMOTE is turned off, then there is a bug in
1464 hp-ux which sometimes loses data. Apparently the
1465 code which blocks the master process when the internal
1466 buffer fills up does not work. Other than this,
1467 though, everything else seems to work fine.
1469 Since the latter lossage is more benign, we may as well
1470 lose that way. -- cph */
1471 #ifdef FIONBIO
1472 #if defined (UNIX98_PTYS)
1474 int on = 1;
1475 ioctl (fd, FIONBIO, &on);
1477 #endif
1478 #endif
1480 #endif /* HAVE_PTYS */
1482 void
1483 init_system_name (void)
1485 if (!build_details)
1487 /* Set system-name to nil so that the build is deterministic. */
1488 Vsystem_name = Qnil;
1489 return;
1491 char *hostname_alloc = NULL;
1492 char *hostname;
1493 #ifndef HAVE_GETHOSTNAME
1494 struct utsname uts;
1495 uname (&uts);
1496 hostname = uts.nodename;
1497 #else /* HAVE_GETHOSTNAME */
1498 char hostname_buf[256];
1499 ptrdiff_t hostname_size = sizeof hostname_buf;
1500 hostname = hostname_buf;
1502 /* Try to get the host name; if the buffer is too short, try
1503 again. Apparently, the only indication gethostname gives of
1504 whether the buffer was large enough is the presence or absence
1505 of a '\0' in the string. Eech. */
1506 for (;;)
1508 gethostname (hostname, hostname_size - 1);
1509 hostname[hostname_size - 1] = '\0';
1511 /* Was the buffer large enough for the '\0'? */
1512 if (strlen (hostname) < hostname_size - 1)
1513 break;
1515 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1516 min (PTRDIFF_MAX, SIZE_MAX), 1);
1518 #endif /* HAVE_GETHOSTNAME */
1519 char *p;
1520 for (p = hostname; *p; p++)
1521 if (*p == ' ' || *p == '\t')
1522 *p = '-';
1523 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1524 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1525 Vsystem_name = build_string (hostname);
1526 xfree (hostname_alloc);
1529 sigset_t empty_mask;
1531 static struct sigaction process_fatal_action;
1533 static int
1534 emacs_sigaction_flags (void)
1536 #ifdef SA_RESTART
1537 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1538 'select') to reset their timeout on some platforms (e.g.,
1539 HP-UX 11), which is not what we want. Also, when Emacs is
1540 interactive, we don't want SA_RESTART because we need to poll
1541 for pending input so we need long-running syscalls to be interrupted
1542 after a signal that sets pending_signals.
1544 Non-interactive keyboard input goes through stdio, where we
1545 always want restartable system calls. */
1546 if (noninteractive)
1547 return SA_RESTART;
1548 #endif
1549 return 0;
1552 /* Store into *ACTION a signal action suitable for Emacs, with handler
1553 HANDLER. */
1554 void
1555 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1557 sigemptyset (&action->sa_mask);
1559 /* When handling a signal, block nonfatal system signals that are caught
1560 by Emacs. This makes race conditions less likely. */
1561 sigaddset (&action->sa_mask, SIGALRM);
1562 #ifdef SIGCHLD
1563 sigaddset (&action->sa_mask, SIGCHLD);
1564 #endif
1565 #ifdef SIGDANGER
1566 sigaddset (&action->sa_mask, SIGDANGER);
1567 #endif
1568 #ifdef PROFILER_CPU_SUPPORT
1569 sigaddset (&action->sa_mask, SIGPROF);
1570 #endif
1571 #ifdef SIGWINCH
1572 sigaddset (&action->sa_mask, SIGWINCH);
1573 #endif
1574 if (! noninteractive)
1576 sigaddset (&action->sa_mask, SIGINT);
1577 sigaddset (&action->sa_mask, SIGQUIT);
1578 #ifdef USABLE_SIGIO
1579 sigaddset (&action->sa_mask, SIGIO);
1580 #endif
1583 action->sa_handler = handler;
1584 action->sa_flags = emacs_sigaction_flags ();
1587 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1588 static pthread_t main_thread;
1589 #endif
1591 /* SIG has arrived at the current process. Deliver it to the main
1592 thread, which should handle it with HANDLER.
1594 If we are on the main thread, handle the signal SIG with HANDLER.
1595 Otherwise, redirect the signal to the main thread, blocking it from
1596 this thread. POSIX says any thread can receive a signal that is
1597 associated with a process, process group, or asynchronous event.
1598 On GNU/Linux that is not true, but for other systems (FreeBSD at
1599 least) it is. */
1600 void
1601 deliver_process_signal (int sig, signal_handler_t handler)
1603 /* Preserve errno, to avoid race conditions with signal handlers that
1604 might change errno. Races can occur even in single-threaded hosts. */
1605 int old_errno = errno;
1607 bool on_main_thread = true;
1608 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1609 if (! pthread_equal (pthread_self (), main_thread))
1611 sigset_t blocked;
1612 sigemptyset (&blocked);
1613 sigaddset (&blocked, sig);
1614 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1615 pthread_kill (main_thread, sig);
1616 on_main_thread = false;
1618 #endif
1619 if (on_main_thread)
1620 handler (sig);
1622 errno = old_errno;
1625 /* Static location to save a fatal backtrace in a thread.
1626 FIXME: If two subsidiary threads fail simultaneously, the resulting
1627 backtrace may be garbage. */
1628 enum { BACKTRACE_LIMIT_MAX = 500 };
1629 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1630 static int thread_backtrace_npointers;
1632 /* SIG has arrived at the current thread.
1633 If we are on the main thread, handle the signal SIG with HANDLER.
1634 Otherwise, this is a fatal error in the handling thread. */
1635 static void
1636 deliver_thread_signal (int sig, signal_handler_t handler)
1638 int old_errno = errno;
1640 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1641 if (! pthread_equal (pthread_self (), main_thread))
1643 thread_backtrace_npointers
1644 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1645 sigaction (sig, &process_fatal_action, 0);
1646 pthread_kill (main_thread, sig);
1648 /* Avoid further damage while the main thread is exiting. */
1649 while (1)
1650 sigsuspend (&empty_mask);
1652 #endif
1654 handler (sig);
1655 errno = old_errno;
1658 #if !HAVE_DECL_SYS_SIGLIST
1659 # undef sys_siglist
1660 # ifdef _sys_siglist
1661 # define sys_siglist _sys_siglist
1662 # elif HAVE_DECL___SYS_SIGLIST
1663 # define sys_siglist __sys_siglist
1664 # else
1665 # define sys_siglist my_sys_siglist
1666 static char const *sys_siglist[NSIG];
1667 # endif
1668 #endif
1670 #ifdef _sys_nsig
1671 # define sys_siglist_entries _sys_nsig
1672 #else
1673 # define sys_siglist_entries NSIG
1674 #endif
1676 /* Handle bus errors, invalid instruction, etc. */
1677 static void
1678 handle_fatal_signal (int sig)
1680 terminate_due_to_signal (sig, 40);
1683 static void
1684 deliver_fatal_signal (int sig)
1686 deliver_process_signal (sig, handle_fatal_signal);
1689 static void
1690 deliver_fatal_thread_signal (int sig)
1692 deliver_thread_signal (sig, handle_fatal_signal);
1695 static _Noreturn void
1696 handle_arith_signal (int sig)
1698 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1699 xsignal0 (Qarith_error);
1702 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1704 /* Alternate stack used by SIGSEGV handler below. */
1706 static unsigned char sigsegv_stack[SIGSTKSZ];
1709 /* Return true if SIGINFO indicates a stack overflow. */
1711 static bool
1712 stack_overflow (siginfo_t *siginfo)
1714 if (!attempt_stack_overflow_recovery)
1715 return false;
1717 /* In theory, a more-accurate heuristic can be obtained by using
1718 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1719 and pthread_attr_getguardsize to find the location and size of the
1720 guard area. In practice, though, these functions are so hard to
1721 use reliably that they're not worth bothering with. E.g., see:
1722 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1723 Other operating systems also have problems, e.g., Solaris's
1724 stack_violation function is tailor-made for this problem, but it
1725 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1727 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1728 candidate here. */
1730 if (!siginfo)
1731 return false;
1733 /* The faulting address. */
1734 char *addr = siginfo->si_addr;
1735 if (!addr)
1736 return false;
1738 /* The known top and bottom of the stack. The actual stack may
1739 extend a bit beyond these boundaries. */
1740 char *bot = stack_bottom;
1741 char *top = near_C_stack_top ();
1743 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1744 of the known stack divided by the size of the guard area past the
1745 end of the stack top. The heuristic is that a bad address is
1746 considered to be a stack overflow if it occurs within
1747 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1748 stack. This heuristic is not exactly correct but it's good
1749 enough in practice. */
1750 enum { LG_STACK_HEURISTIC = 8 };
1752 if (bot < top)
1753 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1754 else
1755 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1759 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1761 static void
1762 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1764 /* Hard GC error may lead to stack overflow caused by
1765 too nested calls to mark_object. No way to survive. */
1766 bool fatal = gc_in_progress;
1768 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1769 if (!fatal && !pthread_equal (pthread_self (), main_thread))
1770 fatal = true;
1771 #endif
1773 if (!fatal && stack_overflow (siginfo))
1774 siglongjmp (return_to_command_loop, 1);
1776 /* Otherwise we can't do anything with this. */
1777 deliver_fatal_thread_signal (sig);
1780 /* Return true if we have successfully set up SIGSEGV handler on alternate
1781 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1783 static bool
1784 init_sigsegv (void)
1786 struct sigaction sa;
1787 stack_t ss;
1789 ss.ss_sp = sigsegv_stack;
1790 ss.ss_size = sizeof (sigsegv_stack);
1791 ss.ss_flags = 0;
1792 if (sigaltstack (&ss, NULL) < 0)
1793 return 0;
1795 sigfillset (&sa.sa_mask);
1796 sa.sa_sigaction = handle_sigsegv;
1797 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1798 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1801 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1803 static bool
1804 init_sigsegv (void)
1806 return 0;
1809 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1811 static void
1812 deliver_arith_signal (int sig)
1814 deliver_thread_signal (sig, handle_arith_signal);
1817 #ifdef SIGDANGER
1819 /* Handler for SIGDANGER. */
1820 static void
1821 handle_danger_signal (int sig)
1823 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1825 /* It might be unsafe to call do_auto_save now. */
1826 force_auto_save_soon ();
1829 static void
1830 deliver_danger_signal (int sig)
1832 deliver_process_signal (sig, handle_danger_signal);
1834 #endif
1836 /* Treat SIG as a terminating signal, unless it is already ignored and
1837 we are in --batch mode. Among other things, this makes nohup work. */
1838 static void
1839 maybe_fatal_sig (int sig)
1841 bool catch_sig = !noninteractive;
1842 if (!catch_sig)
1844 struct sigaction old_action;
1845 sigaction (sig, 0, &old_action);
1846 catch_sig = old_action.sa_handler != SIG_IGN;
1848 if (catch_sig)
1849 sigaction (sig, &process_fatal_action, 0);
1852 void
1853 init_signals (bool dumping)
1855 struct sigaction thread_fatal_action;
1856 struct sigaction action;
1858 sigemptyset (&empty_mask);
1860 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1861 main_thread = pthread_self ();
1862 #endif
1864 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1865 if (! initialized)
1867 sys_siglist[SIGABRT] = "Aborted";
1868 # ifdef SIGAIO
1869 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1870 # endif
1871 sys_siglist[SIGALRM] = "Alarm clock";
1872 # ifdef SIGBUS
1873 sys_siglist[SIGBUS] = "Bus error";
1874 # endif
1875 # ifdef SIGCHLD
1876 sys_siglist[SIGCHLD] = "Child status changed";
1877 # endif
1878 # ifdef SIGCONT
1879 sys_siglist[SIGCONT] = "Continued";
1880 # endif
1881 # ifdef SIGDANGER
1882 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1883 # endif
1884 # ifdef SIGDGNOTIFY
1885 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1886 # endif
1887 # ifdef SIGEMT
1888 sys_siglist[SIGEMT] = "Emulation trap";
1889 # endif
1890 sys_siglist[SIGFPE] = "Arithmetic exception";
1891 # ifdef SIGFREEZE
1892 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1893 # endif
1894 # ifdef SIGGRANT
1895 sys_siglist[SIGGRANT] = "Monitor mode granted";
1896 # endif
1897 sys_siglist[SIGHUP] = "Hangup";
1898 sys_siglist[SIGILL] = "Illegal instruction";
1899 sys_siglist[SIGINT] = "Interrupt";
1900 # ifdef SIGIO
1901 sys_siglist[SIGIO] = "I/O possible";
1902 # endif
1903 # ifdef SIGIOINT
1904 sys_siglist[SIGIOINT] = "I/O intervention required";
1905 # endif
1906 # ifdef SIGIOT
1907 sys_siglist[SIGIOT] = "IOT trap";
1908 # endif
1909 sys_siglist[SIGKILL] = "Killed";
1910 # ifdef SIGLOST
1911 sys_siglist[SIGLOST] = "Resource lost";
1912 # endif
1913 # ifdef SIGLWP
1914 sys_siglist[SIGLWP] = "SIGLWP";
1915 # endif
1916 # ifdef SIGMSG
1917 sys_siglist[SIGMSG] = "Monitor mode data available";
1918 # endif
1919 # ifdef SIGPHONE
1920 sys_siglist[SIGWIND] = "SIGPHONE";
1921 # endif
1922 sys_siglist[SIGPIPE] = "Broken pipe";
1923 # ifdef SIGPOLL
1924 sys_siglist[SIGPOLL] = "Pollable event occurred";
1925 # endif
1926 # ifdef SIGPROF
1927 sys_siglist[SIGPROF] = "Profiling timer expired";
1928 # endif
1929 # ifdef SIGPTY
1930 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1931 # endif
1932 # ifdef SIGPWR
1933 sys_siglist[SIGPWR] = "Power-fail restart";
1934 # endif
1935 sys_siglist[SIGQUIT] = "Quit";
1936 # ifdef SIGRETRACT
1937 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1938 # endif
1939 # ifdef SIGSAK
1940 sys_siglist[SIGSAK] = "Secure attention";
1941 # endif
1942 sys_siglist[SIGSEGV] = "Segmentation violation";
1943 # ifdef SIGSOUND
1944 sys_siglist[SIGSOUND] = "Sound completed";
1945 # endif
1946 # ifdef SIGSTOP
1947 sys_siglist[SIGSTOP] = "Stopped (signal)";
1948 # endif
1949 # ifdef SIGSTP
1950 sys_siglist[SIGSTP] = "Stopped (user)";
1951 # endif
1952 # ifdef SIGSYS
1953 sys_siglist[SIGSYS] = "Bad argument to system call";
1954 # endif
1955 sys_siglist[SIGTERM] = "Terminated";
1956 # ifdef SIGTHAW
1957 sys_siglist[SIGTHAW] = "SIGTHAW";
1958 # endif
1959 # ifdef SIGTRAP
1960 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1961 # endif
1962 # ifdef SIGTSTP
1963 sys_siglist[SIGTSTP] = "Stopped (user)";
1964 # endif
1965 # ifdef SIGTTIN
1966 sys_siglist[SIGTTIN] = "Stopped (tty input)";
1967 # endif
1968 # ifdef SIGTTOU
1969 sys_siglist[SIGTTOU] = "Stopped (tty output)";
1970 # endif
1971 # ifdef SIGURG
1972 sys_siglist[SIGURG] = "Urgent I/O condition";
1973 # endif
1974 # ifdef SIGUSR1
1975 sys_siglist[SIGUSR1] = "User defined signal 1";
1976 # endif
1977 # ifdef SIGUSR2
1978 sys_siglist[SIGUSR2] = "User defined signal 2";
1979 # endif
1980 # ifdef SIGVTALRM
1981 sys_siglist[SIGVTALRM] = "Virtual timer expired";
1982 # endif
1983 # ifdef SIGWAITING
1984 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
1985 # endif
1986 # ifdef SIGWINCH
1987 sys_siglist[SIGWINCH] = "Window size changed";
1988 # endif
1989 # ifdef SIGWIND
1990 sys_siglist[SIGWIND] = "SIGWIND";
1991 # endif
1992 # ifdef SIGXCPU
1993 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
1994 # endif
1995 # ifdef SIGXFSZ
1996 sys_siglist[SIGXFSZ] = "File size limit exceeded";
1997 # endif
1999 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2001 /* Don't alter signal handlers if dumping. On some machines,
2002 changing signal handlers sets static data that would make signals
2003 fail to work right when the dumped Emacs is run. */
2004 if (dumping)
2005 return;
2007 sigfillset (&process_fatal_action.sa_mask);
2008 process_fatal_action.sa_handler = deliver_fatal_signal;
2009 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2011 sigfillset (&thread_fatal_action.sa_mask);
2012 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2013 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2015 /* SIGINT may need special treatment on MS-Windows. See
2016 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2017 Please update the doc of kill-emacs, kill-emacs-hook, and
2018 NEWS if you change this. */
2020 maybe_fatal_sig (SIGHUP);
2021 maybe_fatal_sig (SIGINT);
2022 maybe_fatal_sig (SIGTERM);
2024 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2025 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2026 to behave more like typical batch applications do. */
2027 if (! noninteractive)
2028 signal (SIGPIPE, SIG_IGN);
2030 sigaction (SIGQUIT, &process_fatal_action, 0);
2031 sigaction (SIGILL, &thread_fatal_action, 0);
2032 sigaction (SIGTRAP, &thread_fatal_action, 0);
2034 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2035 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2036 interpreter's floating point operations, so treat SIGFPE as an
2037 arith-error if it arises in the main thread. */
2038 if (IEEE_FLOATING_POINT)
2039 sigaction (SIGFPE, &thread_fatal_action, 0);
2040 else
2042 emacs_sigaction_init (&action, deliver_arith_signal);
2043 sigaction (SIGFPE, &action, 0);
2046 #ifdef SIGUSR1
2047 add_user_signal (SIGUSR1, "sigusr1");
2048 #endif
2049 #ifdef SIGUSR2
2050 add_user_signal (SIGUSR2, "sigusr2");
2051 #endif
2052 sigaction (SIGABRT, &thread_fatal_action, 0);
2053 #ifdef SIGPRE
2054 sigaction (SIGPRE, &thread_fatal_action, 0);
2055 #endif
2056 #ifdef SIGORE
2057 sigaction (SIGORE, &thread_fatal_action, 0);
2058 #endif
2059 #ifdef SIGUME
2060 sigaction (SIGUME, &thread_fatal_action, 0);
2061 #endif
2062 #ifdef SIGDLK
2063 sigaction (SIGDLK, &process_fatal_action, 0);
2064 #endif
2065 #ifdef SIGCPULIM
2066 sigaction (SIGCPULIM, &process_fatal_action, 0);
2067 #endif
2068 #ifdef SIGIOT
2069 sigaction (SIGIOT, &thread_fatal_action, 0);
2070 #endif
2071 #ifdef SIGEMT
2072 sigaction (SIGEMT, &thread_fatal_action, 0);
2073 #endif
2074 #ifdef SIGBUS
2075 sigaction (SIGBUS, &thread_fatal_action, 0);
2076 #endif
2077 if (!init_sigsegv ())
2078 sigaction (SIGSEGV, &thread_fatal_action, 0);
2079 #ifdef SIGSYS
2080 sigaction (SIGSYS, &thread_fatal_action, 0);
2081 #endif
2082 sigaction (SIGTERM, &process_fatal_action, 0);
2083 #ifdef SIGPROF
2084 signal (SIGPROF, SIG_IGN);
2085 #endif
2086 #ifdef SIGVTALRM
2087 sigaction (SIGVTALRM, &process_fatal_action, 0);
2088 #endif
2089 #ifdef SIGXCPU
2090 sigaction (SIGXCPU, &process_fatal_action, 0);
2091 #endif
2092 #ifdef SIGXFSZ
2093 sigaction (SIGXFSZ, &process_fatal_action, 0);
2094 #endif
2096 #ifdef SIGDANGER
2097 /* This just means available memory is getting low. */
2098 emacs_sigaction_init (&action, deliver_danger_signal);
2099 sigaction (SIGDANGER, &action, 0);
2100 #endif
2102 /* AIX-specific signals. */
2103 #ifdef SIGGRANT
2104 sigaction (SIGGRANT, &process_fatal_action, 0);
2105 #endif
2106 #ifdef SIGMIGRATE
2107 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2108 #endif
2109 #ifdef SIGMSG
2110 sigaction (SIGMSG, &process_fatal_action, 0);
2111 #endif
2112 #ifdef SIGRETRACT
2113 sigaction (SIGRETRACT, &process_fatal_action, 0);
2114 #endif
2115 #ifdef SIGSAK
2116 sigaction (SIGSAK, &process_fatal_action, 0);
2117 #endif
2118 #ifdef SIGSOUND
2119 sigaction (SIGSOUND, &process_fatal_action, 0);
2120 #endif
2121 #ifdef SIGTALRM
2122 sigaction (SIGTALRM, &thread_fatal_action, 0);
2123 #endif
2126 #ifndef HAVE_RANDOM
2127 #ifdef random
2128 #define HAVE_RANDOM
2129 #endif
2130 #endif
2132 /* Figure out how many bits the system's random number generator uses.
2133 `random' and `lrand48' are assumed to return 31 usable bits.
2134 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2135 so we'll shift it and treat it like the 15-bit USG `rand'. */
2137 #ifndef RAND_BITS
2138 # ifdef HAVE_RANDOM
2139 # define RAND_BITS 31
2140 # else /* !HAVE_RANDOM */
2141 # ifdef HAVE_LRAND48
2142 # define RAND_BITS 31
2143 # define random lrand48
2144 # else /* !HAVE_LRAND48 */
2145 # define RAND_BITS 15
2146 # if RAND_MAX == 32767
2147 # define random rand
2148 # else /* RAND_MAX != 32767 */
2149 # if RAND_MAX == 2147483647
2150 # define random() (rand () >> 16)
2151 # else /* RAND_MAX != 2147483647 */
2152 # ifdef USG
2153 # define random rand
2154 # else
2155 # define random() (rand () >> 16)
2156 # endif /* !USG */
2157 # endif /* RAND_MAX != 2147483647 */
2158 # endif /* RAND_MAX != 32767 */
2159 # endif /* !HAVE_LRAND48 */
2160 # endif /* !HAVE_RANDOM */
2161 #endif /* !RAND_BITS */
2163 #ifdef HAVE_RANDOM
2164 typedef unsigned int random_seed;
2165 static void set_random_seed (random_seed arg) { srandom (arg); }
2166 #elif defined HAVE_LRAND48
2167 /* Although srand48 uses a long seed, this is unsigned long to avoid
2168 undefined behavior on signed integer overflow in init_random. */
2169 typedef unsigned long int random_seed;
2170 static void set_random_seed (random_seed arg) { srand48 (arg); }
2171 #else
2172 typedef unsigned int random_seed;
2173 static void set_random_seed (random_seed arg) { srand (arg); }
2174 #endif
2176 void
2177 seed_random (void *seed, ptrdiff_t seed_size)
2179 random_seed arg = 0;
2180 unsigned char *argp = (unsigned char *) &arg;
2181 unsigned char *seedp = seed;
2182 for (ptrdiff_t i = 0; i < seed_size; i++)
2183 argp[i % sizeof arg] ^= seedp[i];
2184 set_random_seed (arg);
2187 void
2188 init_random (void)
2190 random_seed v;
2191 bool success = false;
2193 /* First, try seeding the PRNG from the operating system's entropy
2194 source. This approach is both fast and secure. */
2195 #ifdef WINDOWSNT
2196 success = w32_init_random (&v, sizeof v) == 0;
2197 #else
2198 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2199 if (0 <= fd)
2201 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2202 close (fd);
2204 #endif
2206 /* If that didn't work, try using GnuTLS, which is secure, but on
2207 some systems, can be somewhat slow. */
2208 if (!success)
2209 success = EQ (emacs_gnutls_global_init (), Qt)
2210 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2212 /* If _that_ didn't work, just use the current time value and PID.
2213 It's at least better than XKCD 221. */
2214 if (!success)
2216 struct timespec t = current_timespec ();
2217 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2220 set_random_seed (v);
2224 * Return a nonnegative random integer out of whatever we've got.
2225 * It contains enough bits to make a random (signed) Emacs fixnum.
2226 * This suffices even for a 64-bit architecture with a 15-bit rand.
2228 EMACS_INT
2229 get_random (void)
2231 EMACS_UINT val = 0;
2232 int i;
2233 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2234 val = (random () ^ (val << RAND_BITS)
2235 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2236 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2237 return val & INTMASK;
2240 #ifndef HAVE_SNPRINTF
2241 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2243 snprintf (char *buf, size_t bufsize, char const *format, ...)
2245 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2246 ptrdiff_t nbytes = size - 1;
2247 va_list ap;
2249 if (size)
2251 va_start (ap, format);
2252 nbytes = doprnt (buf, size, format, 0, ap);
2253 va_end (ap);
2256 if (nbytes == size - 1)
2258 /* Calculate the length of the string that would have been created
2259 had the buffer been large enough. */
2260 char stackbuf[4000];
2261 char *b = stackbuf;
2262 ptrdiff_t bsize = sizeof stackbuf;
2263 va_start (ap, format);
2264 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2265 va_end (ap);
2266 if (b != stackbuf)
2267 xfree (b);
2270 if (INT_MAX < nbytes)
2272 #ifdef EOVERFLOW
2273 errno = EOVERFLOW;
2274 #else
2275 errno = EDOM;
2276 #endif
2277 return -1;
2279 return nbytes;
2281 #endif
2283 /* If a backtrace is available, output the top lines of it to stderr.
2284 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2285 This function may be called from a signal handler, so it should
2286 not invoke async-unsafe functions like malloc.
2288 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2289 but do not output anything. This avoids some problems that can
2290 otherwise occur if the malloc arena is corrupted before 'backtrace'
2291 is called, since 'backtrace' may call malloc if the tables are not
2292 initialized.
2294 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2295 fatal error has occurred in some other thread; generate a thread
2296 backtrace instead, ignoring BACKTRACE_LIMIT. */
2297 void
2298 emacs_backtrace (int backtrace_limit)
2300 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2301 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2302 void *buffer;
2303 int npointers;
2305 if (thread_backtrace_npointers)
2307 buffer = thread_backtrace_buffer;
2308 npointers = thread_backtrace_npointers;
2310 else
2312 buffer = main_backtrace_buffer;
2314 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2315 if (bounded_limit < 0)
2317 backtrace (buffer, 1);
2318 return;
2321 npointers = backtrace (buffer, bounded_limit + 1);
2324 if (npointers)
2326 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2327 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2328 if (bounded_limit < npointers)
2329 emacs_write (STDERR_FILENO, "...\n", 4);
2333 #ifndef HAVE_NTGUI
2334 void
2335 emacs_abort (void)
2337 terminate_due_to_signal (SIGABRT, 40);
2339 #endif
2341 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2342 Use binary I/O on systems that care about text vs binary I/O.
2343 Arrange for subprograms to not inherit the file descriptor.
2344 Prefer a method that is multithread-safe, if available.
2345 Do not fail merely because the open was interrupted by a signal.
2346 Allow the user to quit. */
2349 emacs_open (const char *file, int oflags, int mode)
2351 int fd;
2352 if (! (oflags & O_TEXT))
2353 oflags |= O_BINARY;
2354 oflags |= O_CLOEXEC;
2355 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2356 QUIT;
2357 if (! O_CLOEXEC && 0 <= fd)
2358 fcntl (fd, F_SETFD, FD_CLOEXEC);
2359 return fd;
2362 /* Open FILE as a stream for Emacs use, with mode MODE.
2363 Act like emacs_open with respect to threads, signals, and quits. */
2365 FILE *
2366 emacs_fopen (char const *file, char const *mode)
2368 int fd, omode, oflags;
2369 int bflag = 0;
2370 char const *m = mode;
2372 switch (*m++)
2374 case 'r': omode = O_RDONLY; oflags = 0; break;
2375 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2376 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2377 default: emacs_abort ();
2380 while (*m)
2381 switch (*m++)
2383 case '+': omode = O_RDWR; break;
2384 case 't': bflag = O_TEXT; break;
2385 default: /* Ignore. */ break;
2388 fd = emacs_open (file, omode | oflags | bflag, 0666);
2389 return fd < 0 ? 0 : fdopen (fd, mode);
2392 /* Create a pipe for Emacs use. */
2395 emacs_pipe (int fd[2])
2397 #ifdef MSDOS
2398 return pipe (fd);
2399 #else /* !MSDOS */
2400 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2401 if (! O_CLOEXEC && result == 0)
2403 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2404 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2406 return result;
2407 #endif /* !MSDOS */
2410 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2411 For the background behind this mess, please see Austin Group defect 529
2412 <http://austingroupbugs.net/view.php?id=529>. */
2414 #ifndef POSIX_CLOSE_RESTART
2415 # define POSIX_CLOSE_RESTART 1
2416 static int
2417 posix_close (int fd, int flag)
2419 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2420 eassert (flag == POSIX_CLOSE_RESTART);
2422 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2423 on a system that does not define POSIX_CLOSE_RESTART.
2425 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2426 closed, and retrying the close could inadvertently close a file
2427 descriptor allocated by some other thread. In other systems
2428 (e.g., HP/UX) FD is not closed. And in still other systems
2429 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2430 multithreaded program there can be no way to tell.
2432 So, in this case, pretend that the close succeeded. This works
2433 well on systems like GNU/Linux that close FD. Although it may
2434 leak a file descriptor on other systems, the leak is unlikely and
2435 it's better to leak than to close a random victim. */
2436 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2438 #endif
2440 /* Close FD, retrying if interrupted. If successful, return 0;
2441 otherwise, return -1 and set errno to a non-EINTR value. Consider
2442 an EINPROGRESS error to be successful, as that's merely a signal
2443 arriving. FD is always closed when this function returns, even
2444 when it returns -1.
2446 Do not call this function if FD is nonnegative and might already be closed,
2447 as that might close an innocent victim opened by some other thread. */
2450 emacs_close (int fd)
2452 while (1)
2454 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2455 if (r == 0)
2456 return r;
2457 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2459 eassert (errno != EBADF || fd < 0);
2460 return errno == EINPROGRESS ? 0 : r;
2465 /* Maximum number of bytes to read or write in a single system call.
2466 This works around a serious bug in Linux kernels before 2.6.16; see
2467 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2468 It's likely to work around similar bugs in other operating systems, so do it
2469 on all platforms. Round INT_MAX down to a page size, with the conservative
2470 assumption that page sizes are at most 2**18 bytes (any kernel with a
2471 page size larger than that shouldn't have the bug). */
2472 #ifndef MAX_RW_COUNT
2473 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2474 #endif
2476 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2477 Return the number of bytes read, which might be less than NBYTE.
2478 On error, set errno and return -1. */
2479 ptrdiff_t
2480 emacs_read (int fildes, void *buf, ptrdiff_t nbyte)
2482 ssize_t rtnval;
2484 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2485 passes a size that large to emacs_read. */
2487 while ((rtnval = read (fildes, buf, nbyte)) == -1
2488 && (errno == EINTR))
2489 QUIT;
2490 return (rtnval);
2493 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2494 or if a partial write occurs. If interrupted, process pending
2495 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2496 errno if this is less than NBYTE. */
2497 static ptrdiff_t
2498 emacs_full_write (int fildes, char const *buf, ptrdiff_t nbyte,
2499 bool process_signals)
2501 ptrdiff_t bytes_written = 0;
2503 while (nbyte > 0)
2505 ssize_t n = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
2507 if (n < 0)
2509 if (errno == EINTR)
2511 /* I originally used `QUIT' but that might cause files to
2512 be truncated if you hit C-g in the middle of it. --Stef */
2513 if (process_signals && pending_signals)
2514 process_pending_signals ();
2515 continue;
2517 else
2518 break;
2521 buf += n;
2522 nbyte -= n;
2523 bytes_written += n;
2526 return bytes_written;
2529 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2530 interrupted or if a partial write occurs. Return the number of
2531 bytes written, setting errno if this is less than NBYTE. */
2532 ptrdiff_t
2533 emacs_write (int fildes, void const *buf, ptrdiff_t nbyte)
2535 return emacs_full_write (fildes, buf, nbyte, 0);
2538 /* Like emacs_write, but also process pending signals if interrupted. */
2539 ptrdiff_t
2540 emacs_write_sig (int fildes, void const *buf, ptrdiff_t nbyte)
2542 return emacs_full_write (fildes, buf, nbyte, 1);
2545 /* Write a diagnostic to standard error that contains MESSAGE and a
2546 string derived from errno. Preserve errno. Do not buffer stderr.
2547 Do not process pending signals if interrupted. */
2548 void
2549 emacs_perror (char const *message)
2551 int err = errno;
2552 char const *error_string = emacs_strerror (err);
2553 char const *command = (initial_argv && initial_argv[0]
2554 ? initial_argv[0] : "emacs");
2555 /* Write it out all at once, if it's short; this is less likely to
2556 be interleaved with other output. */
2557 char buf[BUFSIZ];
2558 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2559 command, message, error_string);
2560 if (0 <= nbytes && nbytes < BUFSIZ)
2561 emacs_write (STDERR_FILENO, buf, nbytes);
2562 else
2564 emacs_write (STDERR_FILENO, command, strlen (command));
2565 emacs_write (STDERR_FILENO, ": ", 2);
2566 emacs_write (STDERR_FILENO, message, strlen (message));
2567 emacs_write (STDERR_FILENO, ": ", 2);
2568 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2569 emacs_write (STDERR_FILENO, "\n", 1);
2571 errno = err;
2574 /* Return a struct timeval that is roughly equivalent to T.
2575 Use the least timeval not less than T.
2576 Return an extremal value if the result would overflow. */
2577 struct timeval
2578 make_timeval (struct timespec t)
2580 struct timeval tv;
2581 tv.tv_sec = t.tv_sec;
2582 tv.tv_usec = t.tv_nsec / 1000;
2584 if (t.tv_nsec % 1000 != 0)
2586 if (tv.tv_usec < 999999)
2587 tv.tv_usec++;
2588 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2590 tv.tv_sec++;
2591 tv.tv_usec = 0;
2595 return tv;
2598 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2599 ATIME and MTIME, respectively.
2600 FD must be either negative -- in which case it is ignored --
2601 or a file descriptor that is open on FILE.
2602 If FD is nonnegative, then FILE can be NULL. */
2604 set_file_times (int fd, const char *filename,
2605 struct timespec atime, struct timespec mtime)
2607 struct timespec timespec[2];
2608 timespec[0] = atime;
2609 timespec[1] = mtime;
2610 return fdutimens (fd, filename, timespec);
2613 /* Like strsignal, except async-signal-safe, and this function typically
2614 returns a string in the C locale rather than the current locale. */
2615 char const *
2616 safe_strsignal (int code)
2618 char const *signame = 0;
2620 if (0 <= code && code < sys_siglist_entries)
2621 signame = sys_siglist[code];
2622 if (! signame)
2623 signame = "Unknown signal";
2625 return signame;
2628 #ifndef DOS_NT
2629 /* For make-serial-process */
2631 serial_open (Lisp_Object port)
2633 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2634 if (fd < 0)
2635 report_file_error ("Opening serial port", port);
2636 #ifdef TIOCEXCL
2637 ioctl (fd, TIOCEXCL, (char *) 0);
2638 #endif
2640 return fd;
2643 #if !defined (HAVE_CFMAKERAW)
2644 /* Workaround for targets which are missing cfmakeraw. */
2645 /* Pasted from man page. */
2646 static void
2647 cfmakeraw (struct termios *termios_p)
2649 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2650 termios_p->c_oflag &= ~OPOST;
2651 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2652 termios_p->c_cflag &= ~(CSIZE|PARENB);
2653 termios_p->c_cflag |= CS8;
2655 #endif /* !defined (HAVE_CFMAKERAW */
2657 #if !defined (HAVE_CFSETSPEED)
2658 /* Workaround for targets which are missing cfsetspeed. */
2659 static int
2660 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2662 return (cfsetispeed (termios_p, vitesse)
2663 + cfsetospeed (termios_p, vitesse));
2665 #endif
2667 /* For serial-process-configure */
2668 void
2669 serial_configure (struct Lisp_Process *p,
2670 Lisp_Object contact)
2672 Lisp_Object childp2 = Qnil;
2673 Lisp_Object tem = Qnil;
2674 struct termios attr;
2675 int err;
2676 char summary[4] = "???"; /* This usually becomes "8N1". */
2678 childp2 = Fcopy_sequence (p->childp);
2680 /* Read port attributes and prepare default configuration. */
2681 err = tcgetattr (p->outfd, &attr);
2682 if (err != 0)
2683 report_file_error ("Failed tcgetattr", Qnil);
2684 cfmakeraw (&attr);
2685 #if defined (CLOCAL)
2686 attr.c_cflag |= CLOCAL;
2687 #endif
2688 #if defined (CREAD)
2689 attr.c_cflag |= CREAD;
2690 #endif
2692 /* Configure speed. */
2693 if (!NILP (Fplist_member (contact, QCspeed)))
2694 tem = Fplist_get (contact, QCspeed);
2695 else
2696 tem = Fplist_get (p->childp, QCspeed);
2697 CHECK_NUMBER (tem);
2698 err = cfsetspeed (&attr, XINT (tem));
2699 if (err != 0)
2700 report_file_error ("Failed cfsetspeed", tem);
2701 childp2 = Fplist_put (childp2, QCspeed, tem);
2703 /* Configure bytesize. */
2704 if (!NILP (Fplist_member (contact, QCbytesize)))
2705 tem = Fplist_get (contact, QCbytesize);
2706 else
2707 tem = Fplist_get (p->childp, QCbytesize);
2708 if (NILP (tem))
2709 tem = make_number (8);
2710 CHECK_NUMBER (tem);
2711 if (XINT (tem) != 7 && XINT (tem) != 8)
2712 error (":bytesize must be nil (8), 7, or 8");
2713 summary[0] = XINT (tem) + '0';
2714 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2715 attr.c_cflag &= ~CSIZE;
2716 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2717 #else
2718 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2719 if (XINT (tem) != 8)
2720 error ("Bytesize cannot be changed");
2721 #endif
2722 childp2 = Fplist_put (childp2, QCbytesize, tem);
2724 /* Configure parity. */
2725 if (!NILP (Fplist_member (contact, QCparity)))
2726 tem = Fplist_get (contact, QCparity);
2727 else
2728 tem = Fplist_get (p->childp, QCparity);
2729 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2730 error (":parity must be nil (no parity), `even', or `odd'");
2731 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2732 attr.c_cflag &= ~(PARENB | PARODD);
2733 attr.c_iflag &= ~(IGNPAR | INPCK);
2734 if (NILP (tem))
2736 summary[1] = 'N';
2738 else if (EQ (tem, Qeven))
2740 summary[1] = 'E';
2741 attr.c_cflag |= PARENB;
2742 attr.c_iflag |= (IGNPAR | INPCK);
2744 else if (EQ (tem, Qodd))
2746 summary[1] = 'O';
2747 attr.c_cflag |= (PARENB | PARODD);
2748 attr.c_iflag |= (IGNPAR | INPCK);
2750 #else
2751 /* Don't error on no parity, which should be set by cfmakeraw. */
2752 if (!NILP (tem))
2753 error ("Parity cannot be configured");
2754 #endif
2755 childp2 = Fplist_put (childp2, QCparity, tem);
2757 /* Configure stopbits. */
2758 if (!NILP (Fplist_member (contact, QCstopbits)))
2759 tem = Fplist_get (contact, QCstopbits);
2760 else
2761 tem = Fplist_get (p->childp, QCstopbits);
2762 if (NILP (tem))
2763 tem = make_number (1);
2764 CHECK_NUMBER (tem);
2765 if (XINT (tem) != 1 && XINT (tem) != 2)
2766 error (":stopbits must be nil (1 stopbit), 1, or 2");
2767 summary[2] = XINT (tem) + '0';
2768 #if defined (CSTOPB)
2769 attr.c_cflag &= ~CSTOPB;
2770 if (XINT (tem) == 2)
2771 attr.c_cflag |= CSTOPB;
2772 #else
2773 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2774 if (XINT (tem) != 1)
2775 error ("Stopbits cannot be configured");
2776 #endif
2777 childp2 = Fplist_put (childp2, QCstopbits, tem);
2779 /* Configure flowcontrol. */
2780 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2781 tem = Fplist_get (contact, QCflowcontrol);
2782 else
2783 tem = Fplist_get (p->childp, QCflowcontrol);
2784 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2785 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2786 #if defined (CRTSCTS)
2787 attr.c_cflag &= ~CRTSCTS;
2788 #endif
2789 #if defined (CNEW_RTSCTS)
2790 attr.c_cflag &= ~CNEW_RTSCTS;
2791 #endif
2792 #if defined (IXON) && defined (IXOFF)
2793 attr.c_iflag &= ~(IXON | IXOFF);
2794 #endif
2795 if (NILP (tem))
2797 /* Already configured. */
2799 else if (EQ (tem, Qhw))
2801 #if defined (CRTSCTS)
2802 attr.c_cflag |= CRTSCTS;
2803 #elif defined (CNEW_RTSCTS)
2804 attr.c_cflag |= CNEW_RTSCTS;
2805 #else
2806 error ("Hardware flowcontrol (RTS/CTS) not supported");
2807 #endif
2809 else if (EQ (tem, Qsw))
2811 #if defined (IXON) && defined (IXOFF)
2812 attr.c_iflag |= (IXON | IXOFF);
2813 #else
2814 error ("Software flowcontrol (XON/XOFF) not supported");
2815 #endif
2817 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2819 /* Activate configuration. */
2820 err = tcsetattr (p->outfd, TCSANOW, &attr);
2821 if (err != 0)
2822 report_file_error ("Failed tcsetattr", Qnil);
2824 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2825 pset_childp (p, childp2);
2827 #endif /* not DOS_NT */
2829 /* System depended enumeration of and access to system processes a-la ps(1). */
2831 #ifdef HAVE_PROCFS
2833 /* Process enumeration and access via /proc. */
2835 Lisp_Object
2836 list_system_processes (void)
2838 Lisp_Object procdir, match, proclist, next;
2839 Lisp_Object tail;
2841 /* For every process on the system, there's a directory in the
2842 "/proc" pseudo-directory whose name is the numeric ID of that
2843 process. */
2844 procdir = build_string ("/proc");
2845 match = build_string ("[0-9]+");
2846 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2848 /* `proclist' gives process IDs as strings. Destructively convert
2849 each string into a number. */
2850 for (tail = proclist; CONSP (tail); tail = next)
2852 next = XCDR (tail);
2853 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2856 /* directory_files_internal returns the files in reverse order; undo
2857 that. */
2858 proclist = Fnreverse (proclist);
2859 return proclist;
2862 #elif defined DARWIN_OS || defined __FreeBSD__
2864 Lisp_Object
2865 list_system_processes (void)
2867 #ifdef DARWIN_OS
2868 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2869 #else
2870 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2871 #endif
2872 size_t len;
2873 struct kinfo_proc *procs;
2874 size_t i;
2876 Lisp_Object proclist = Qnil;
2878 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2879 return proclist;
2881 procs = xmalloc (len);
2882 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2884 xfree (procs);
2885 return proclist;
2888 len /= sizeof (struct kinfo_proc);
2889 for (i = 0; i < len; i++)
2891 #ifdef DARWIN_OS
2892 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2893 #else
2894 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2895 #endif
2898 xfree (procs);
2900 return proclist;
2903 /* The WINDOWSNT implementation is in w32.c.
2904 The MSDOS implementation is in dosfns.c. */
2905 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2907 Lisp_Object
2908 list_system_processes (void)
2910 return Qnil;
2913 #endif /* !defined (WINDOWSNT) */
2915 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2916 static struct timespec
2917 time_from_jiffies (unsigned long long tval, long hz)
2919 unsigned long long s = tval / hz;
2920 unsigned long long frac = tval % hz;
2921 int ns;
2923 if (TYPE_MAXIMUM (time_t) < s)
2924 time_overflow ();
2925 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2926 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2927 ns = frac * TIMESPEC_RESOLUTION / hz;
2928 else
2930 /* This is reachable only in the unlikely case that HZ * HZ
2931 exceeds ULLONG_MAX. It calculates an approximation that is
2932 guaranteed to be in range. */
2933 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
2934 + (hz % TIMESPEC_RESOLUTION != 0));
2935 ns = frac / hz_per_ns;
2938 return make_timespec (s, ns);
2941 static Lisp_Object
2942 ltime_from_jiffies (unsigned long long tval, long hz)
2944 struct timespec t = time_from_jiffies (tval, hz);
2945 return make_lisp_time (t);
2948 static struct timespec
2949 get_up_time (void)
2951 FILE *fup;
2952 struct timespec up = make_timespec (0, 0);
2954 block_input ();
2955 fup = emacs_fopen ("/proc/uptime", "r");
2957 if (fup)
2959 unsigned long long upsec, upfrac, idlesec, idlefrac;
2960 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
2962 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
2963 &upsec, &upfrac_start, &upfrac, &upfrac_end,
2964 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
2965 == 4)
2967 if (TYPE_MAXIMUM (time_t) < upsec)
2969 upsec = TYPE_MAXIMUM (time_t);
2970 upfrac = TIMESPEC_RESOLUTION - 1;
2972 else
2974 int upfraclen = upfrac_end - upfrac_start;
2975 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
2976 upfrac *= 10;
2977 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
2978 upfrac /= 10;
2979 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
2981 up = make_timespec (upsec, upfrac);
2983 fclose (fup);
2985 unblock_input ();
2987 return up;
2990 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2991 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2993 static Lisp_Object
2994 procfs_ttyname (int rdev)
2996 FILE *fdev;
2997 char name[PATH_MAX];
2999 block_input ();
3000 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3001 name[0] = 0;
3003 if (fdev)
3005 unsigned major;
3006 unsigned long minor_beg, minor_end;
3007 char minor[25]; /* 2 32-bit numbers + dash */
3008 char *endp;
3010 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
3012 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3013 && major == MAJOR (rdev))
3015 minor_beg = strtoul (minor, &endp, 0);
3016 if (*endp == '\0')
3017 minor_end = minor_beg;
3018 else if (*endp == '-')
3019 minor_end = strtoul (endp + 1, &endp, 0);
3020 else
3021 continue;
3023 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3025 sprintf (name + strlen (name), "%u", MINOR (rdev));
3026 break;
3030 fclose (fdev);
3032 unblock_input ();
3033 return build_string (name);
3036 static uintmax_t
3037 procfs_get_total_memory (void)
3039 FILE *fmem;
3040 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3041 int c;
3043 block_input ();
3044 fmem = emacs_fopen ("/proc/meminfo", "r");
3046 if (fmem)
3048 uintmax_t entry_value;
3049 bool done;
3052 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3054 case 1:
3055 retval = entry_value;
3056 done = 1;
3057 break;
3059 case 0:
3060 while ((c = getc (fmem)) != EOF && c != '\n')
3061 continue;
3062 done = c == EOF;
3063 break;
3065 default:
3066 done = 1;
3067 break;
3069 while (!done);
3071 fclose (fmem);
3073 unblock_input ();
3074 return retval;
3077 Lisp_Object
3078 system_process_attributes (Lisp_Object pid)
3080 char procfn[PATH_MAX], fn[PATH_MAX];
3081 struct stat st;
3082 struct passwd *pw;
3083 struct group *gr;
3084 long clocks_per_sec;
3085 char *procfn_end;
3086 char procbuf[1025], *p, *q;
3087 int fd;
3088 ssize_t nread;
3089 static char const default_cmd[] = "???";
3090 const char *cmd = default_cmd;
3091 int cmdsize = sizeof default_cmd - 1;
3092 char *cmdline = NULL;
3093 ptrdiff_t cmdline_size;
3094 char c;
3095 printmax_t proc_id;
3096 int ppid, pgrp, sess, tty, tpgid, thcount;
3097 uid_t uid;
3098 gid_t gid;
3099 unsigned long long u_time, s_time, cutime, cstime, start;
3100 long priority, niceness, rss;
3101 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3102 struct timespec tnow, tstart, tboot, telapsed, us_time;
3103 double pcpu, pmem;
3104 Lisp_Object attrs = Qnil;
3105 Lisp_Object decoded_cmd;
3106 ptrdiff_t count;
3108 CHECK_NUMBER_OR_FLOAT (pid);
3109 CONS_TO_INTEGER (pid, pid_t, proc_id);
3110 sprintf (procfn, "/proc/%"pMd, proc_id);
3111 if (stat (procfn, &st) < 0)
3112 return attrs;
3114 /* euid egid */
3115 uid = st.st_uid;
3116 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3117 block_input ();
3118 pw = getpwuid (uid);
3119 unblock_input ();
3120 if (pw)
3121 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3123 gid = st.st_gid;
3124 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3125 block_input ();
3126 gr = getgrgid (gid);
3127 unblock_input ();
3128 if (gr)
3129 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3131 count = SPECPDL_INDEX ();
3132 strcpy (fn, procfn);
3133 procfn_end = fn + strlen (fn);
3134 strcpy (procfn_end, "/stat");
3135 fd = emacs_open (fn, O_RDONLY, 0);
3136 if (fd < 0)
3137 nread = 0;
3138 else
3140 record_unwind_protect_int (close_file_unwind, fd);
3141 nread = emacs_read (fd, procbuf, sizeof procbuf - 1);
3143 if (0 < nread)
3145 procbuf[nread] = '\0';
3146 p = procbuf;
3148 p = strchr (p, '(');
3149 if (p != NULL)
3151 q = strrchr (p + 1, ')');
3152 /* comm */
3153 if (q != NULL)
3155 cmd = p + 1;
3156 cmdsize = q - cmd;
3159 else
3160 q = NULL;
3161 /* Command name is encoded in locale-coding-system; decode it. */
3162 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3163 decoded_cmd = code_convert_string_norecord (cmd_str,
3164 Vlocale_coding_system, 0);
3165 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3167 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3168 utime stime cutime cstime priority nice thcount . start vsize rss */
3169 if (q
3170 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3171 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3172 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3173 &minflt, &cminflt, &majflt, &cmajflt,
3174 &u_time, &s_time, &cutime, &cstime,
3175 &priority, &niceness, &thcount, &start, &vsize, &rss)
3176 == 20))
3178 char state_str[2];
3179 state_str[0] = c;
3180 state_str[1] = '\0';
3181 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3182 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3183 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3184 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3185 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3186 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3187 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3188 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3189 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3190 attrs);
3191 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3192 attrs);
3193 clocks_per_sec = sysconf (_SC_CLK_TCK);
3194 if (clocks_per_sec < 0)
3195 clocks_per_sec = 100;
3196 attrs = Fcons (Fcons (Qutime,
3197 ltime_from_jiffies (u_time, clocks_per_sec)),
3198 attrs);
3199 attrs = Fcons (Fcons (Qstime,
3200 ltime_from_jiffies (s_time, clocks_per_sec)),
3201 attrs);
3202 attrs = Fcons (Fcons (Qtime,
3203 ltime_from_jiffies (s_time + u_time,
3204 clocks_per_sec)),
3205 attrs);
3206 attrs = Fcons (Fcons (Qcutime,
3207 ltime_from_jiffies (cutime, clocks_per_sec)),
3208 attrs);
3209 attrs = Fcons (Fcons (Qcstime,
3210 ltime_from_jiffies (cstime, clocks_per_sec)),
3211 attrs);
3212 attrs = Fcons (Fcons (Qctime,
3213 ltime_from_jiffies (cstime + cutime,
3214 clocks_per_sec)),
3215 attrs);
3216 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3217 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3218 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3219 attrs);
3220 tnow = current_timespec ();
3221 telapsed = get_up_time ();
3222 tboot = timespec_sub (tnow, telapsed);
3223 tstart = time_from_jiffies (start, clocks_per_sec);
3224 tstart = timespec_add (tboot, tstart);
3225 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3226 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3227 attrs);
3228 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3229 telapsed = timespec_sub (tnow, tstart);
3230 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3231 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3232 pcpu = timespectod (us_time) / timespectod (telapsed);
3233 if (pcpu > 1.0)
3234 pcpu = 1.0;
3235 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3236 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3237 if (pmem > 100)
3238 pmem = 100;
3239 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3242 unbind_to (count, Qnil);
3244 /* args */
3245 strcpy (procfn_end, "/cmdline");
3246 fd = emacs_open (fn, O_RDONLY, 0);
3247 if (fd >= 0)
3249 ptrdiff_t readsize, nread_incr;
3250 record_unwind_protect_int (close_file_unwind, fd);
3251 record_unwind_protect_nothing ();
3252 nread = cmdline_size = 0;
3256 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3257 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3259 /* Leave room even if every byte needs escaping below. */
3260 readsize = (cmdline_size >> 1) - nread;
3262 nread_incr = emacs_read (fd, cmdline + nread, readsize);
3263 nread += max (0, nread_incr);
3265 while (nread_incr == readsize);
3267 if (nread)
3269 /* We don't want trailing null characters. */
3270 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3271 continue;
3273 /* Escape-quote whitespace and backslashes. */
3274 q = cmdline + cmdline_size;
3275 while (cmdline < p)
3277 char c = *--p;
3278 *--q = c ? c : ' ';
3279 if (c_isspace (c) || c == '\\')
3280 *--q = '\\';
3283 nread = cmdline + cmdline_size - q;
3286 if (!nread)
3288 nread = cmdsize + 2;
3289 cmdline_size = nread + 1;
3290 q = cmdline = xrealloc (cmdline, cmdline_size);
3291 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3292 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3294 /* Command line is encoded in locale-coding-system; decode it. */
3295 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3296 decoded_cmd = code_convert_string_norecord (cmd_str,
3297 Vlocale_coding_system, 0);
3298 unbind_to (count, Qnil);
3299 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3302 return attrs;
3305 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3307 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3308 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3309 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3310 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3311 #undef _FILE_OFFSET_BITS
3312 #else
3313 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3314 #endif
3316 #include <procfs.h>
3318 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3319 #define _FILE_OFFSET_BITS 64
3320 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3321 #endif
3322 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3324 Lisp_Object
3325 system_process_attributes (Lisp_Object pid)
3327 char procfn[PATH_MAX], fn[PATH_MAX];
3328 struct stat st;
3329 struct passwd *pw;
3330 struct group *gr;
3331 char *procfn_end;
3332 struct psinfo pinfo;
3333 int fd;
3334 ssize_t nread;
3335 printmax_t proc_id;
3336 uid_t uid;
3337 gid_t gid;
3338 Lisp_Object attrs = Qnil;
3339 Lisp_Object decoded_cmd;
3340 ptrdiff_t count;
3342 CHECK_NUMBER_OR_FLOAT (pid);
3343 CONS_TO_INTEGER (pid, pid_t, proc_id);
3344 sprintf (procfn, "/proc/%"pMd, proc_id);
3345 if (stat (procfn, &st) < 0)
3346 return attrs;
3348 /* euid egid */
3349 uid = st.st_uid;
3350 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3351 block_input ();
3352 pw = getpwuid (uid);
3353 unblock_input ();
3354 if (pw)
3355 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3357 gid = st.st_gid;
3358 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3359 block_input ();
3360 gr = getgrgid (gid);
3361 unblock_input ();
3362 if (gr)
3363 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3365 count = SPECPDL_INDEX ();
3366 strcpy (fn, procfn);
3367 procfn_end = fn + strlen (fn);
3368 strcpy (procfn_end, "/psinfo");
3369 fd = emacs_open (fn, O_RDONLY, 0);
3370 if (fd < 0)
3371 nread = 0;
3372 else
3374 record_unwind_protect (close_file_unwind, fd);
3375 nread = emacs_read (fd, &pinfo, sizeof pinfo);
3378 if (nread == sizeof pinfo)
3380 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3381 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3382 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3385 char state_str[2];
3386 state_str[0] = pinfo.pr_lwp.pr_sname;
3387 state_str[1] = '\0';
3388 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3391 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3392 need to get a string from it. */
3394 /* FIXME: missing: Qtpgid */
3396 /* FIXME: missing:
3397 Qminflt
3398 Qmajflt
3399 Qcminflt
3400 Qcmajflt
3402 Qutime
3403 Qcutime
3404 Qstime
3405 Qcstime
3406 Are they available? */
3408 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3409 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3410 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3411 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3412 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3413 attrs);
3415 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3416 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3417 attrs);
3418 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3419 attrs);
3421 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3422 range 0 .. 2**15, representing 0.0 .. 1.0. */
3423 attrs = Fcons (Fcons (Qpcpu,
3424 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3425 attrs);
3426 attrs = Fcons (Fcons (Qpmem,
3427 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3428 attrs);
3430 AUTO_STRING (fname, pinfo.pr_fname);
3431 decoded_cmd = code_convert_string_norecord (fname,
3432 Vlocale_coding_system, 0);
3433 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3434 AUTO_STRING (psargs, pinfo.pr_psargs);
3435 decoded_cmd = code_convert_string_norecord (psargs,
3436 Vlocale_coding_system, 0);
3437 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3439 unbind_to (count, Qnil);
3440 return attrs;
3443 #elif defined __FreeBSD__
3445 static struct timespec
3446 timeval_to_timespec (struct timeval t)
3448 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3451 static Lisp_Object
3452 make_lisp_timeval (struct timeval t)
3454 return make_lisp_time (timeval_to_timespec (t));
3457 Lisp_Object
3458 system_process_attributes (Lisp_Object pid)
3460 int proc_id;
3461 int pagesize = getpagesize ();
3462 unsigned long npages;
3463 int fscale;
3464 struct passwd *pw;
3465 struct group *gr;
3466 char *ttyname;
3467 size_t len;
3468 char args[MAXPATHLEN];
3469 struct timespec t, now;
3471 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3472 struct kinfo_proc proc;
3473 size_t proclen = sizeof proc;
3475 Lisp_Object attrs = Qnil;
3476 Lisp_Object decoded_comm;
3478 CHECK_NUMBER_OR_FLOAT (pid);
3479 CONS_TO_INTEGER (pid, int, proc_id);
3480 mib[3] = proc_id;
3482 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3483 return attrs;
3485 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3487 block_input ();
3488 pw = getpwuid (proc.ki_uid);
3489 unblock_input ();
3490 if (pw)
3491 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3493 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3495 block_input ();
3496 gr = getgrgid (proc.ki_svgid);
3497 unblock_input ();
3498 if (gr)
3499 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3501 AUTO_STRING (comm, proc.ki_comm);
3502 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3504 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3506 char state[2] = {'\0', '\0'};
3507 switch (proc.ki_stat)
3509 case SRUN:
3510 state[0] = 'R';
3511 break;
3513 case SSLEEP:
3514 state[0] = 'S';
3515 break;
3517 case SLOCK:
3518 state[0] = 'D';
3519 break;
3521 case SZOMB:
3522 state[0] = 'Z';
3523 break;
3525 case SSTOP:
3526 state[0] = 'T';
3527 break;
3529 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3532 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3533 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3534 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3536 block_input ();
3537 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3538 unblock_input ();
3539 if (ttyname)
3540 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3542 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3543 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3544 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3545 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3546 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3548 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3549 attrs);
3550 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3551 attrs);
3552 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3553 timeval_to_timespec (proc.ki_rusage.ru_stime));
3554 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3556 attrs = Fcons (Fcons (Qcutime,
3557 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3558 attrs);
3559 attrs = Fcons (Fcons (Qcstime,
3560 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3561 attrs);
3562 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3563 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3564 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3566 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3567 attrs);
3568 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3569 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3570 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3571 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3572 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3573 attrs);
3575 now = current_timespec ();
3576 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3577 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3579 len = sizeof fscale;
3580 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3582 double pcpu;
3583 fixpt_t ccpu;
3584 len = sizeof ccpu;
3585 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3587 pcpu = (100.0 * proc.ki_pctcpu / fscale
3588 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3589 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3593 len = sizeof npages;
3594 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3596 double pmem = (proc.ki_flag & P_INMEM
3597 ? 100.0 * proc.ki_rssize / npages
3598 : 0);
3599 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3602 mib[2] = KERN_PROC_ARGS;
3603 len = MAXPATHLEN;
3604 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3606 int i;
3607 for (i = 0; i < len; i++)
3609 if (! args[i] && i < len - 1)
3610 args[i] = ' ';
3613 AUTO_STRING (comm, args);
3614 decoded_comm = code_convert_string_norecord (comm,
3615 Vlocale_coding_system, 0);
3617 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3620 return attrs;
3623 #elif defined DARWIN_OS
3625 static struct timespec
3626 timeval_to_timespec (struct timeval t)
3628 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3631 static Lisp_Object
3632 make_lisp_timeval (struct timeval t)
3634 return make_lisp_time (timeval_to_timespec (t));
3637 Lisp_Object
3638 system_process_attributes (Lisp_Object pid)
3640 int proc_id;
3641 int pagesize = getpagesize ();
3642 unsigned long npages;
3643 int fscale;
3644 struct passwd *pw;
3645 struct group *gr;
3646 char *ttyname;
3647 size_t len;
3648 char args[MAXPATHLEN];
3649 struct timeval starttime;
3650 struct timespec t, now;
3651 struct rusage *rusage;
3652 dev_t tdev;
3653 uid_t uid;
3654 gid_t gid;
3656 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3657 struct kinfo_proc proc;
3658 size_t proclen = sizeof proc;
3660 Lisp_Object attrs = Qnil;
3661 Lisp_Object decoded_comm;
3663 CHECK_NUMBER_OR_FLOAT (pid);
3664 CONS_TO_INTEGER (pid, int, proc_id);
3665 mib[3] = proc_id;
3667 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3668 return attrs;
3670 uid = proc.kp_eproc.e_ucred.cr_uid;
3671 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3673 block_input ();
3674 pw = getpwuid (uid);
3675 unblock_input ();
3676 if (pw)
3677 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3679 gid = proc.kp_eproc.e_pcred.p_svgid;
3680 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3682 block_input ();
3683 gr = getgrgid (gid);
3684 unblock_input ();
3685 if (gr)
3686 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3688 decoded_comm = (code_convert_string_norecord
3689 (build_unibyte_string (proc.kp_proc.p_comm),
3690 Vlocale_coding_system, 0));
3692 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3694 char state[2] = {'\0', '\0'};
3695 switch (proc.kp_proc.p_stat)
3697 case SRUN:
3698 state[0] = 'R';
3699 break;
3701 case SSLEEP:
3702 state[0] = 'S';
3703 break;
3705 case SZOMB:
3706 state[0] = 'Z';
3707 break;
3709 case SSTOP:
3710 state[0] = 'T';
3711 break;
3713 case SIDL:
3714 state[0] = 'I';
3715 break;
3717 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3720 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3721 attrs);
3722 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3723 attrs);
3725 tdev = proc.kp_eproc.e_tdev;
3726 block_input ();
3727 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3728 unblock_input ();
3729 if (ttyname)
3730 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3732 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3733 attrs);
3735 rusage = proc.kp_proc.p_ru;
3736 if (rusage)
3738 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3739 attrs);
3740 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3741 attrs);
3743 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3744 attrs);
3745 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3746 attrs);
3747 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3748 timeval_to_timespec (rusage->ru_stime));
3749 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3752 starttime = proc.kp_proc.p_starttime;
3753 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3754 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3756 now = current_timespec ();
3757 t = timespec_sub (now, timeval_to_timespec (starttime));
3758 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3760 return attrs;
3763 /* The WINDOWSNT implementation is in w32.c.
3764 The MSDOS implementation is in dosfns.c. */
3765 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3767 Lisp_Object
3768 system_process_attributes (Lisp_Object pid)
3770 return Qnil;
3773 #endif /* !defined (WINDOWSNT) */
3775 /* Wide character string collation. */
3777 #ifdef __STDC_ISO_10646__
3778 # include <wchar.h>
3779 # include <wctype.h>
3781 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3782 # include <locale.h>
3783 # endif
3784 # ifndef LC_COLLATE
3785 # define LC_COLLATE 0
3786 # endif
3787 # ifndef LC_COLLATE_MASK
3788 # define LC_COLLATE_MASK 0
3789 # endif
3790 # ifndef LC_CTYPE
3791 # define LC_CTYPE 0
3792 # endif
3793 # ifndef LC_CTYPE_MASK
3794 # define LC_CTYPE_MASK 0
3795 # endif
3797 # ifndef HAVE_NEWLOCALE
3798 # undef freelocale
3799 # undef locale_t
3800 # undef newlocale
3801 # undef wcscoll_l
3802 # undef towlower_l
3803 # define freelocale emacs_freelocale
3804 # define locale_t emacs_locale_t
3805 # define newlocale emacs_newlocale
3806 # define wcscoll_l emacs_wcscoll_l
3807 # define towlower_l emacs_towlower_l
3809 typedef char const *locale_t;
3811 static locale_t
3812 newlocale (int category_mask, char const *locale, locale_t loc)
3814 return locale;
3817 static void
3818 freelocale (locale_t loc)
3822 static char *
3823 emacs_setlocale (int category, char const *locale)
3825 # ifdef HAVE_SETLOCALE
3826 errno = 0;
3827 char *loc = setlocale (category, locale);
3828 if (loc || errno)
3829 return loc;
3830 errno = EINVAL;
3831 # else
3832 errno = ENOTSUP;
3833 # endif
3834 return 0;
3837 static int
3838 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3840 int result = 0;
3841 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3842 int err;
3844 if (! oldloc)
3845 err = errno;
3846 else
3848 USE_SAFE_ALLOCA;
3849 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3850 strcpy (oldcopy, oldloc);
3851 if (! emacs_setlocale (LC_COLLATE, loc))
3852 err = errno;
3853 else
3855 errno = 0;
3856 result = wcscoll (a, b);
3857 err = errno;
3858 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3859 err = errno;
3861 SAFE_FREE ();
3864 errno = err;
3865 return result;
3868 static wint_t
3869 towlower_l (wint_t wc, locale_t loc)
3871 wint_t result = wc;
3872 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3874 if (oldloc)
3876 USE_SAFE_ALLOCA;
3877 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3878 strcpy (oldcopy, oldloc);
3879 if (emacs_setlocale (LC_CTYPE, loc))
3881 result = towlower (wc);
3882 emacs_setlocale (LC_COLLATE, oldcopy);
3884 SAFE_FREE ();
3887 return result;
3889 # endif
3892 str_collate (Lisp_Object s1, Lisp_Object s2,
3893 Lisp_Object locale, Lisp_Object ignore_case)
3895 int res, err;
3896 ptrdiff_t len, i, i_byte;
3897 wchar_t *p1, *p2;
3899 USE_SAFE_ALLOCA;
3901 /* Convert byte stream to code points. */
3902 len = SCHARS (s1); i = i_byte = 0;
3903 SAFE_NALLOCA (p1, 1, len + 1);
3904 while (i < len)
3905 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3906 *(p1+len) = 0;
3908 len = SCHARS (s2); i = i_byte = 0;
3909 SAFE_NALLOCA (p2, 1, len + 1);
3910 while (i < len)
3911 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3912 *(p2+len) = 0;
3914 if (STRINGP (locale))
3916 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3917 SSDATA (locale), 0);
3918 if (!loc)
3919 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
3921 if (! NILP (ignore_case))
3922 for (int i = 1; i < 3; i++)
3924 wchar_t *p = (i == 1) ? p1 : p2;
3925 for (; *p; p++)
3926 *p = towlower_l (*p, loc);
3929 errno = 0;
3930 res = wcscoll_l (p1, p2, loc);
3931 err = errno;
3932 freelocale (loc);
3934 else
3936 if (! NILP (ignore_case))
3937 for (int i = 1; i < 3; i++)
3939 wchar_t *p = (i == 1) ? p1 : p2;
3940 for (; *p; p++)
3941 *p = towlower (*p);
3944 errno = 0;
3945 res = wcscoll (p1, p2);
3946 err = errno;
3948 # ifndef HAVE_NEWLOCALE
3949 if (err)
3950 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
3951 # else
3952 if (err)
3953 error ("Invalid string for collation: %s", emacs_strerror (err));
3954 # endif
3956 SAFE_FREE ();
3957 return res;
3959 #endif /* __STDC_ISO_10646__ */
3961 #ifdef WINDOWSNT
3963 str_collate (Lisp_Object s1, Lisp_Object s2,
3964 Lisp_Object locale, Lisp_Object ignore_case)
3967 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
3968 int res, err = errno;
3970 errno = 0;
3971 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
3972 if (errno)
3973 error ("Invalid string for collation: %s", strerror (errno));
3975 errno = err;
3976 return res;
3978 #endif /* WINDOWSNT */