Merge from origin/emacs-25
[emacs.git] / src / sysdep.c
blob0121f01631c63e623b668af9bc88fd0db32812fd
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 if (! (EQ (emacs_gnutls_global_init (), Qt)
2192 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0))
2194 bool success = false;
2195 #ifndef WINDOWSNT
2196 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2197 if (0 <= fd)
2199 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2200 emacs_close (fd);
2202 #else
2203 success = w32_init_random (&v, sizeof v) == 0;
2204 #endif
2205 if (! success)
2207 /* Fall back to current time value + PID. */
2208 struct timespec t = current_timespec ();
2209 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2212 set_random_seed (v);
2216 * Return a nonnegative random integer out of whatever we've got.
2217 * It contains enough bits to make a random (signed) Emacs fixnum.
2218 * This suffices even for a 64-bit architecture with a 15-bit rand.
2220 EMACS_INT
2221 get_random (void)
2223 EMACS_UINT val = 0;
2224 int i;
2225 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2226 val = (random () ^ (val << RAND_BITS)
2227 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2228 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2229 return val & INTMASK;
2232 #ifndef HAVE_SNPRINTF
2233 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2235 snprintf (char *buf, size_t bufsize, char const *format, ...)
2237 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2238 ptrdiff_t nbytes = size - 1;
2239 va_list ap;
2241 if (size)
2243 va_start (ap, format);
2244 nbytes = doprnt (buf, size, format, 0, ap);
2245 va_end (ap);
2248 if (nbytes == size - 1)
2250 /* Calculate the length of the string that would have been created
2251 had the buffer been large enough. */
2252 char stackbuf[4000];
2253 char *b = stackbuf;
2254 ptrdiff_t bsize = sizeof stackbuf;
2255 va_start (ap, format);
2256 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2257 va_end (ap);
2258 if (b != stackbuf)
2259 xfree (b);
2262 if (INT_MAX < nbytes)
2264 #ifdef EOVERFLOW
2265 errno = EOVERFLOW;
2266 #else
2267 errno = EDOM;
2268 #endif
2269 return -1;
2271 return nbytes;
2273 #endif
2275 /* If a backtrace is available, output the top lines of it to stderr.
2276 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2277 This function may be called from a signal handler, so it should
2278 not invoke async-unsafe functions like malloc.
2280 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2281 but do not output anything. This avoids some problems that can
2282 otherwise occur if the malloc arena is corrupted before 'backtrace'
2283 is called, since 'backtrace' may call malloc if the tables are not
2284 initialized.
2286 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2287 fatal error has occurred in some other thread; generate a thread
2288 backtrace instead, ignoring BACKTRACE_LIMIT. */
2289 void
2290 emacs_backtrace (int backtrace_limit)
2292 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2293 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2294 void *buffer;
2295 int npointers;
2297 if (thread_backtrace_npointers)
2299 buffer = thread_backtrace_buffer;
2300 npointers = thread_backtrace_npointers;
2302 else
2304 buffer = main_backtrace_buffer;
2306 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2307 if (bounded_limit < 0)
2309 backtrace (buffer, 1);
2310 return;
2313 npointers = backtrace (buffer, bounded_limit + 1);
2316 if (npointers)
2318 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2319 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2320 if (bounded_limit < npointers)
2321 emacs_write (STDERR_FILENO, "...\n", 4);
2325 #ifndef HAVE_NTGUI
2326 void
2327 emacs_abort (void)
2329 terminate_due_to_signal (SIGABRT, 40);
2331 #endif
2333 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2334 Use binary I/O on systems that care about text vs binary I/O.
2335 Arrange for subprograms to not inherit the file descriptor.
2336 Prefer a method that is multithread-safe, if available.
2337 Do not fail merely because the open was interrupted by a signal.
2338 Allow the user to quit. */
2341 emacs_open (const char *file, int oflags, int mode)
2343 int fd;
2344 if (! (oflags & O_TEXT))
2345 oflags |= O_BINARY;
2346 oflags |= O_CLOEXEC;
2347 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2348 QUIT;
2349 if (! O_CLOEXEC && 0 <= fd)
2350 fcntl (fd, F_SETFD, FD_CLOEXEC);
2351 return fd;
2354 /* Open FILE as a stream for Emacs use, with mode MODE.
2355 Act like emacs_open with respect to threads, signals, and quits. */
2357 FILE *
2358 emacs_fopen (char const *file, char const *mode)
2360 int fd, omode, oflags;
2361 int bflag = 0;
2362 char const *m = mode;
2364 switch (*m++)
2366 case 'r': omode = O_RDONLY; oflags = 0; break;
2367 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2368 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2369 default: emacs_abort ();
2372 while (*m)
2373 switch (*m++)
2375 case '+': omode = O_RDWR; break;
2376 case 't': bflag = O_TEXT; break;
2377 default: /* Ignore. */ break;
2380 fd = emacs_open (file, omode | oflags | bflag, 0666);
2381 return fd < 0 ? 0 : fdopen (fd, mode);
2384 /* Create a pipe for Emacs use. */
2387 emacs_pipe (int fd[2])
2389 #ifdef MSDOS
2390 return pipe (fd);
2391 #else /* !MSDOS */
2392 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2393 if (! O_CLOEXEC && result == 0)
2395 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2396 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2398 return result;
2399 #endif /* !MSDOS */
2402 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2403 For the background behind this mess, please see Austin Group defect 529
2404 <http://austingroupbugs.net/view.php?id=529>. */
2406 #ifndef POSIX_CLOSE_RESTART
2407 # define POSIX_CLOSE_RESTART 1
2408 static int
2409 posix_close (int fd, int flag)
2411 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2412 eassert (flag == POSIX_CLOSE_RESTART);
2414 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2415 on a system that does not define POSIX_CLOSE_RESTART.
2417 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2418 closed, and retrying the close could inadvertently close a file
2419 descriptor allocated by some other thread. In other systems
2420 (e.g., HP/UX) FD is not closed. And in still other systems
2421 (e.g., OS X, Solaris), maybe FD is closed, maybe not, and in a
2422 multithreaded program there can be no way to tell.
2424 So, in this case, pretend that the close succeeded. This works
2425 well on systems like GNU/Linux that close FD. Although it may
2426 leak a file descriptor on other systems, the leak is unlikely and
2427 it's better to leak than to close a random victim. */
2428 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2430 #endif
2432 /* Close FD, retrying if interrupted. If successful, return 0;
2433 otherwise, return -1 and set errno to a non-EINTR value. Consider
2434 an EINPROGRESS error to be successful, as that's merely a signal
2435 arriving. FD is always closed when this function returns, even
2436 when it returns -1.
2438 Do not call this function if FD is nonnegative and might already be closed,
2439 as that might close an innocent victim opened by some other thread. */
2442 emacs_close (int fd)
2444 while (1)
2446 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2447 if (r == 0)
2448 return r;
2449 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2451 eassert (errno != EBADF || fd < 0);
2452 return errno == EINPROGRESS ? 0 : r;
2457 /* Maximum number of bytes to read or write in a single system call.
2458 This works around a serious bug in Linux kernels before 2.6.16; see
2459 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2460 It's likely to work around similar bugs in other operating systems, so do it
2461 on all platforms. Round INT_MAX down to a page size, with the conservative
2462 assumption that page sizes are at most 2**18 bytes (any kernel with a
2463 page size larger than that shouldn't have the bug). */
2464 #ifndef MAX_RW_COUNT
2465 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2466 #endif
2468 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2469 Return the number of bytes read, which might be less than NBYTE.
2470 On error, set errno and return -1. */
2471 ptrdiff_t
2472 emacs_read (int fildes, void *buf, ptrdiff_t nbyte)
2474 ssize_t rtnval;
2476 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2477 passes a size that large to emacs_read. */
2479 while ((rtnval = read (fildes, buf, nbyte)) == -1
2480 && (errno == EINTR))
2481 QUIT;
2482 return (rtnval);
2485 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2486 or if a partial write occurs. If interrupted, process pending
2487 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2488 errno if this is less than NBYTE. */
2489 static ptrdiff_t
2490 emacs_full_write (int fildes, char const *buf, ptrdiff_t nbyte,
2491 bool process_signals)
2493 ptrdiff_t bytes_written = 0;
2495 while (nbyte > 0)
2497 ssize_t n = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
2499 if (n < 0)
2501 if (errno == EINTR)
2503 /* I originally used `QUIT' but that might cause files to
2504 be truncated if you hit C-g in the middle of it. --Stef */
2505 if (process_signals && pending_signals)
2506 process_pending_signals ();
2507 continue;
2509 else
2510 break;
2513 buf += n;
2514 nbyte -= n;
2515 bytes_written += n;
2518 return bytes_written;
2521 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2522 interrupted or if a partial write occurs. Return the number of
2523 bytes written, setting errno if this is less than NBYTE. */
2524 ptrdiff_t
2525 emacs_write (int fildes, void const *buf, ptrdiff_t nbyte)
2527 return emacs_full_write (fildes, buf, nbyte, 0);
2530 /* Like emacs_write, but also process pending signals if interrupted. */
2531 ptrdiff_t
2532 emacs_write_sig (int fildes, void const *buf, ptrdiff_t nbyte)
2534 return emacs_full_write (fildes, buf, nbyte, 1);
2537 /* Write a diagnostic to standard error that contains MESSAGE and a
2538 string derived from errno. Preserve errno. Do not buffer stderr.
2539 Do not process pending signals if interrupted. */
2540 void
2541 emacs_perror (char const *message)
2543 int err = errno;
2544 char const *error_string = emacs_strerror (err);
2545 char const *command = (initial_argv && initial_argv[0]
2546 ? initial_argv[0] : "emacs");
2547 /* Write it out all at once, if it's short; this is less likely to
2548 be interleaved with other output. */
2549 char buf[BUFSIZ];
2550 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2551 command, message, error_string);
2552 if (0 <= nbytes && nbytes < BUFSIZ)
2553 emacs_write (STDERR_FILENO, buf, nbytes);
2554 else
2556 emacs_write (STDERR_FILENO, command, strlen (command));
2557 emacs_write (STDERR_FILENO, ": ", 2);
2558 emacs_write (STDERR_FILENO, message, strlen (message));
2559 emacs_write (STDERR_FILENO, ": ", 2);
2560 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2561 emacs_write (STDERR_FILENO, "\n", 1);
2563 errno = err;
2566 /* Return a struct timeval that is roughly equivalent to T.
2567 Use the least timeval not less than T.
2568 Return an extremal value if the result would overflow. */
2569 struct timeval
2570 make_timeval (struct timespec t)
2572 struct timeval tv;
2573 tv.tv_sec = t.tv_sec;
2574 tv.tv_usec = t.tv_nsec / 1000;
2576 if (t.tv_nsec % 1000 != 0)
2578 if (tv.tv_usec < 999999)
2579 tv.tv_usec++;
2580 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2582 tv.tv_sec++;
2583 tv.tv_usec = 0;
2587 return tv;
2590 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2591 ATIME and MTIME, respectively.
2592 FD must be either negative -- in which case it is ignored --
2593 or a file descriptor that is open on FILE.
2594 If FD is nonnegative, then FILE can be NULL. */
2596 set_file_times (int fd, const char *filename,
2597 struct timespec atime, struct timespec mtime)
2599 struct timespec timespec[2];
2600 timespec[0] = atime;
2601 timespec[1] = mtime;
2602 return fdutimens (fd, filename, timespec);
2605 /* Like strsignal, except async-signal-safe, and this function typically
2606 returns a string in the C locale rather than the current locale. */
2607 char const *
2608 safe_strsignal (int code)
2610 char const *signame = 0;
2612 if (0 <= code && code < sys_siglist_entries)
2613 signame = sys_siglist[code];
2614 if (! signame)
2615 signame = "Unknown signal";
2617 return signame;
2620 #ifndef DOS_NT
2621 /* For make-serial-process */
2623 serial_open (Lisp_Object port)
2625 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2626 if (fd < 0)
2627 report_file_error ("Opening serial port", port);
2628 #ifdef TIOCEXCL
2629 ioctl (fd, TIOCEXCL, (char *) 0);
2630 #endif
2632 return fd;
2635 #if !defined (HAVE_CFMAKERAW)
2636 /* Workaround for targets which are missing cfmakeraw. */
2637 /* Pasted from man page. */
2638 static void
2639 cfmakeraw (struct termios *termios_p)
2641 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2642 termios_p->c_oflag &= ~OPOST;
2643 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2644 termios_p->c_cflag &= ~(CSIZE|PARENB);
2645 termios_p->c_cflag |= CS8;
2647 #endif /* !defined (HAVE_CFMAKERAW */
2649 #if !defined (HAVE_CFSETSPEED)
2650 /* Workaround for targets which are missing cfsetspeed. */
2651 static int
2652 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2654 return (cfsetispeed (termios_p, vitesse)
2655 + cfsetospeed (termios_p, vitesse));
2657 #endif
2659 /* For serial-process-configure */
2660 void
2661 serial_configure (struct Lisp_Process *p,
2662 Lisp_Object contact)
2664 Lisp_Object childp2 = Qnil;
2665 Lisp_Object tem = Qnil;
2666 struct termios attr;
2667 int err;
2668 char summary[4] = "???"; /* This usually becomes "8N1". */
2670 childp2 = Fcopy_sequence (p->childp);
2672 /* Read port attributes and prepare default configuration. */
2673 err = tcgetattr (p->outfd, &attr);
2674 if (err != 0)
2675 report_file_error ("Failed tcgetattr", Qnil);
2676 cfmakeraw (&attr);
2677 #if defined (CLOCAL)
2678 attr.c_cflag |= CLOCAL;
2679 #endif
2680 #if defined (CREAD)
2681 attr.c_cflag |= CREAD;
2682 #endif
2684 /* Configure speed. */
2685 if (!NILP (Fplist_member (contact, QCspeed)))
2686 tem = Fplist_get (contact, QCspeed);
2687 else
2688 tem = Fplist_get (p->childp, QCspeed);
2689 CHECK_NUMBER (tem);
2690 err = cfsetspeed (&attr, XINT (tem));
2691 if (err != 0)
2692 report_file_error ("Failed cfsetspeed", tem);
2693 childp2 = Fplist_put (childp2, QCspeed, tem);
2695 /* Configure bytesize. */
2696 if (!NILP (Fplist_member (contact, QCbytesize)))
2697 tem = Fplist_get (contact, QCbytesize);
2698 else
2699 tem = Fplist_get (p->childp, QCbytesize);
2700 if (NILP (tem))
2701 tem = make_number (8);
2702 CHECK_NUMBER (tem);
2703 if (XINT (tem) != 7 && XINT (tem) != 8)
2704 error (":bytesize must be nil (8), 7, or 8");
2705 summary[0] = XINT (tem) + '0';
2706 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2707 attr.c_cflag &= ~CSIZE;
2708 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2709 #else
2710 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2711 if (XINT (tem) != 8)
2712 error ("Bytesize cannot be changed");
2713 #endif
2714 childp2 = Fplist_put (childp2, QCbytesize, tem);
2716 /* Configure parity. */
2717 if (!NILP (Fplist_member (contact, QCparity)))
2718 tem = Fplist_get (contact, QCparity);
2719 else
2720 tem = Fplist_get (p->childp, QCparity);
2721 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2722 error (":parity must be nil (no parity), `even', or `odd'");
2723 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2724 attr.c_cflag &= ~(PARENB | PARODD);
2725 attr.c_iflag &= ~(IGNPAR | INPCK);
2726 if (NILP (tem))
2728 summary[1] = 'N';
2730 else if (EQ (tem, Qeven))
2732 summary[1] = 'E';
2733 attr.c_cflag |= PARENB;
2734 attr.c_iflag |= (IGNPAR | INPCK);
2736 else if (EQ (tem, Qodd))
2738 summary[1] = 'O';
2739 attr.c_cflag |= (PARENB | PARODD);
2740 attr.c_iflag |= (IGNPAR | INPCK);
2742 #else
2743 /* Don't error on no parity, which should be set by cfmakeraw. */
2744 if (!NILP (tem))
2745 error ("Parity cannot be configured");
2746 #endif
2747 childp2 = Fplist_put (childp2, QCparity, tem);
2749 /* Configure stopbits. */
2750 if (!NILP (Fplist_member (contact, QCstopbits)))
2751 tem = Fplist_get (contact, QCstopbits);
2752 else
2753 tem = Fplist_get (p->childp, QCstopbits);
2754 if (NILP (tem))
2755 tem = make_number (1);
2756 CHECK_NUMBER (tem);
2757 if (XINT (tem) != 1 && XINT (tem) != 2)
2758 error (":stopbits must be nil (1 stopbit), 1, or 2");
2759 summary[2] = XINT (tem) + '0';
2760 #if defined (CSTOPB)
2761 attr.c_cflag &= ~CSTOPB;
2762 if (XINT (tem) == 2)
2763 attr.c_cflag |= CSTOPB;
2764 #else
2765 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2766 if (XINT (tem) != 1)
2767 error ("Stopbits cannot be configured");
2768 #endif
2769 childp2 = Fplist_put (childp2, QCstopbits, tem);
2771 /* Configure flowcontrol. */
2772 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2773 tem = Fplist_get (contact, QCflowcontrol);
2774 else
2775 tem = Fplist_get (p->childp, QCflowcontrol);
2776 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2777 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2778 #if defined (CRTSCTS)
2779 attr.c_cflag &= ~CRTSCTS;
2780 #endif
2781 #if defined (CNEW_RTSCTS)
2782 attr.c_cflag &= ~CNEW_RTSCTS;
2783 #endif
2784 #if defined (IXON) && defined (IXOFF)
2785 attr.c_iflag &= ~(IXON | IXOFF);
2786 #endif
2787 if (NILP (tem))
2789 /* Already configured. */
2791 else if (EQ (tem, Qhw))
2793 #if defined (CRTSCTS)
2794 attr.c_cflag |= CRTSCTS;
2795 #elif defined (CNEW_RTSCTS)
2796 attr.c_cflag |= CNEW_RTSCTS;
2797 #else
2798 error ("Hardware flowcontrol (RTS/CTS) not supported");
2799 #endif
2801 else if (EQ (tem, Qsw))
2803 #if defined (IXON) && defined (IXOFF)
2804 attr.c_iflag |= (IXON | IXOFF);
2805 #else
2806 error ("Software flowcontrol (XON/XOFF) not supported");
2807 #endif
2809 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2811 /* Activate configuration. */
2812 err = tcsetattr (p->outfd, TCSANOW, &attr);
2813 if (err != 0)
2814 report_file_error ("Failed tcsetattr", Qnil);
2816 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2817 pset_childp (p, childp2);
2819 #endif /* not DOS_NT */
2821 /* System depended enumeration of and access to system processes a-la ps(1). */
2823 #ifdef HAVE_PROCFS
2825 /* Process enumeration and access via /proc. */
2827 Lisp_Object
2828 list_system_processes (void)
2830 Lisp_Object procdir, match, proclist, next;
2831 Lisp_Object tail;
2833 /* For every process on the system, there's a directory in the
2834 "/proc" pseudo-directory whose name is the numeric ID of that
2835 process. */
2836 procdir = build_string ("/proc");
2837 match = build_string ("[0-9]+");
2838 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2840 /* `proclist' gives process IDs as strings. Destructively convert
2841 each string into a number. */
2842 for (tail = proclist; CONSP (tail); tail = next)
2844 next = XCDR (tail);
2845 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2848 /* directory_files_internal returns the files in reverse order; undo
2849 that. */
2850 proclist = Fnreverse (proclist);
2851 return proclist;
2854 #elif defined DARWIN_OS || defined __FreeBSD__
2856 Lisp_Object
2857 list_system_processes (void)
2859 #ifdef DARWIN_OS
2860 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2861 #else
2862 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2863 #endif
2864 size_t len;
2865 struct kinfo_proc *procs;
2866 size_t i;
2868 Lisp_Object proclist = Qnil;
2870 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2871 return proclist;
2873 procs = xmalloc (len);
2874 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2876 xfree (procs);
2877 return proclist;
2880 len /= sizeof (struct kinfo_proc);
2881 for (i = 0; i < len; i++)
2883 #ifdef DARWIN_OS
2884 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2885 #else
2886 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2887 #endif
2890 xfree (procs);
2892 return proclist;
2895 /* The WINDOWSNT implementation is in w32.c.
2896 The MSDOS implementation is in dosfns.c. */
2897 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2899 Lisp_Object
2900 list_system_processes (void)
2902 return Qnil;
2905 #endif /* !defined (WINDOWSNT) */
2907 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2908 static struct timespec
2909 time_from_jiffies (unsigned long long tval, long hz)
2911 unsigned long long s = tval / hz;
2912 unsigned long long frac = tval % hz;
2913 int ns;
2915 if (TYPE_MAXIMUM (time_t) < s)
2916 time_overflow ();
2917 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2918 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2919 ns = frac * TIMESPEC_RESOLUTION / hz;
2920 else
2922 /* This is reachable only in the unlikely case that HZ * HZ
2923 exceeds ULLONG_MAX. It calculates an approximation that is
2924 guaranteed to be in range. */
2925 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
2926 + (hz % TIMESPEC_RESOLUTION != 0));
2927 ns = frac / hz_per_ns;
2930 return make_timespec (s, ns);
2933 static Lisp_Object
2934 ltime_from_jiffies (unsigned long long tval, long hz)
2936 struct timespec t = time_from_jiffies (tval, hz);
2937 return make_lisp_time (t);
2940 static struct timespec
2941 get_up_time (void)
2943 FILE *fup;
2944 struct timespec up = make_timespec (0, 0);
2946 block_input ();
2947 fup = emacs_fopen ("/proc/uptime", "r");
2949 if (fup)
2951 unsigned long long upsec, upfrac, idlesec, idlefrac;
2952 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
2954 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
2955 &upsec, &upfrac_start, &upfrac, &upfrac_end,
2956 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
2957 == 4)
2959 if (TYPE_MAXIMUM (time_t) < upsec)
2961 upsec = TYPE_MAXIMUM (time_t);
2962 upfrac = TIMESPEC_RESOLUTION - 1;
2964 else
2966 int upfraclen = upfrac_end - upfrac_start;
2967 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
2968 upfrac *= 10;
2969 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
2970 upfrac /= 10;
2971 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
2973 up = make_timespec (upsec, upfrac);
2975 fclose (fup);
2977 unblock_input ();
2979 return up;
2982 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2983 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2985 static Lisp_Object
2986 procfs_ttyname (int rdev)
2988 FILE *fdev;
2989 char name[PATH_MAX];
2991 block_input ();
2992 fdev = emacs_fopen ("/proc/tty/drivers", "r");
2993 name[0] = 0;
2995 if (fdev)
2997 unsigned major;
2998 unsigned long minor_beg, minor_end;
2999 char minor[25]; /* 2 32-bit numbers + dash */
3000 char *endp;
3002 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
3004 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3005 && major == MAJOR (rdev))
3007 minor_beg = strtoul (minor, &endp, 0);
3008 if (*endp == '\0')
3009 minor_end = minor_beg;
3010 else if (*endp == '-')
3011 minor_end = strtoul (endp + 1, &endp, 0);
3012 else
3013 continue;
3015 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3017 sprintf (name + strlen (name), "%u", MINOR (rdev));
3018 break;
3022 fclose (fdev);
3024 unblock_input ();
3025 return build_string (name);
3028 static uintmax_t
3029 procfs_get_total_memory (void)
3031 FILE *fmem;
3032 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3033 int c;
3035 block_input ();
3036 fmem = emacs_fopen ("/proc/meminfo", "r");
3038 if (fmem)
3040 uintmax_t entry_value;
3041 bool done;
3044 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3046 case 1:
3047 retval = entry_value;
3048 done = 1;
3049 break;
3051 case 0:
3052 while ((c = getc (fmem)) != EOF && c != '\n')
3053 continue;
3054 done = c == EOF;
3055 break;
3057 default:
3058 done = 1;
3059 break;
3061 while (!done);
3063 fclose (fmem);
3065 unblock_input ();
3066 return retval;
3069 Lisp_Object
3070 system_process_attributes (Lisp_Object pid)
3072 char procfn[PATH_MAX], fn[PATH_MAX];
3073 struct stat st;
3074 struct passwd *pw;
3075 struct group *gr;
3076 long clocks_per_sec;
3077 char *procfn_end;
3078 char procbuf[1025], *p, *q;
3079 int fd;
3080 ssize_t nread;
3081 static char const default_cmd[] = "???";
3082 const char *cmd = default_cmd;
3083 int cmdsize = sizeof default_cmd - 1;
3084 char *cmdline = NULL;
3085 ptrdiff_t cmdline_size;
3086 char c;
3087 printmax_t proc_id;
3088 int ppid, pgrp, sess, tty, tpgid, thcount;
3089 uid_t uid;
3090 gid_t gid;
3091 unsigned long long u_time, s_time, cutime, cstime, start;
3092 long priority, niceness, rss;
3093 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3094 struct timespec tnow, tstart, tboot, telapsed, us_time;
3095 double pcpu, pmem;
3096 Lisp_Object attrs = Qnil;
3097 Lisp_Object decoded_cmd;
3098 ptrdiff_t count;
3100 CHECK_NUMBER_OR_FLOAT (pid);
3101 CONS_TO_INTEGER (pid, pid_t, proc_id);
3102 sprintf (procfn, "/proc/%"pMd, proc_id);
3103 if (stat (procfn, &st) < 0)
3104 return attrs;
3106 /* euid egid */
3107 uid = st.st_uid;
3108 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3109 block_input ();
3110 pw = getpwuid (uid);
3111 unblock_input ();
3112 if (pw)
3113 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3115 gid = st.st_gid;
3116 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3117 block_input ();
3118 gr = getgrgid (gid);
3119 unblock_input ();
3120 if (gr)
3121 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3123 count = SPECPDL_INDEX ();
3124 strcpy (fn, procfn);
3125 procfn_end = fn + strlen (fn);
3126 strcpy (procfn_end, "/stat");
3127 fd = emacs_open (fn, O_RDONLY, 0);
3128 if (fd < 0)
3129 nread = 0;
3130 else
3132 record_unwind_protect_int (close_file_unwind, fd);
3133 nread = emacs_read (fd, procbuf, sizeof procbuf - 1);
3135 if (0 < nread)
3137 procbuf[nread] = '\0';
3138 p = procbuf;
3140 p = strchr (p, '(');
3141 if (p != NULL)
3143 q = strrchr (p + 1, ')');
3144 /* comm */
3145 if (q != NULL)
3147 cmd = p + 1;
3148 cmdsize = q - cmd;
3151 else
3152 q = NULL;
3153 /* Command name is encoded in locale-coding-system; decode it. */
3154 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3155 decoded_cmd = code_convert_string_norecord (cmd_str,
3156 Vlocale_coding_system, 0);
3157 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3159 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3160 utime stime cutime cstime priority nice thcount . start vsize rss */
3161 if (q
3162 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3163 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3164 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3165 &minflt, &cminflt, &majflt, &cmajflt,
3166 &u_time, &s_time, &cutime, &cstime,
3167 &priority, &niceness, &thcount, &start, &vsize, &rss)
3168 == 20))
3170 char state_str[2];
3171 state_str[0] = c;
3172 state_str[1] = '\0';
3173 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3174 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3175 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3176 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3177 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3178 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3179 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3180 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3181 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3182 attrs);
3183 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3184 attrs);
3185 clocks_per_sec = sysconf (_SC_CLK_TCK);
3186 if (clocks_per_sec < 0)
3187 clocks_per_sec = 100;
3188 attrs = Fcons (Fcons (Qutime,
3189 ltime_from_jiffies (u_time, clocks_per_sec)),
3190 attrs);
3191 attrs = Fcons (Fcons (Qstime,
3192 ltime_from_jiffies (s_time, clocks_per_sec)),
3193 attrs);
3194 attrs = Fcons (Fcons (Qtime,
3195 ltime_from_jiffies (s_time + u_time,
3196 clocks_per_sec)),
3197 attrs);
3198 attrs = Fcons (Fcons (Qcutime,
3199 ltime_from_jiffies (cutime, clocks_per_sec)),
3200 attrs);
3201 attrs = Fcons (Fcons (Qcstime,
3202 ltime_from_jiffies (cstime, clocks_per_sec)),
3203 attrs);
3204 attrs = Fcons (Fcons (Qctime,
3205 ltime_from_jiffies (cstime + cutime,
3206 clocks_per_sec)),
3207 attrs);
3208 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3209 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3210 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3211 attrs);
3212 tnow = current_timespec ();
3213 telapsed = get_up_time ();
3214 tboot = timespec_sub (tnow, telapsed);
3215 tstart = time_from_jiffies (start, clocks_per_sec);
3216 tstart = timespec_add (tboot, tstart);
3217 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3218 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3219 attrs);
3220 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3221 telapsed = timespec_sub (tnow, tstart);
3222 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3223 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3224 pcpu = timespectod (us_time) / timespectod (telapsed);
3225 if (pcpu > 1.0)
3226 pcpu = 1.0;
3227 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3228 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3229 if (pmem > 100)
3230 pmem = 100;
3231 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3234 unbind_to (count, Qnil);
3236 /* args */
3237 strcpy (procfn_end, "/cmdline");
3238 fd = emacs_open (fn, O_RDONLY, 0);
3239 if (fd >= 0)
3241 ptrdiff_t readsize, nread_incr;
3242 record_unwind_protect_int (close_file_unwind, fd);
3243 record_unwind_protect_nothing ();
3244 nread = cmdline_size = 0;
3248 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3249 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3251 /* Leave room even if every byte needs escaping below. */
3252 readsize = (cmdline_size >> 1) - nread;
3254 nread_incr = emacs_read (fd, cmdline + nread, readsize);
3255 nread += max (0, nread_incr);
3257 while (nread_incr == readsize);
3259 if (nread)
3261 /* We don't want trailing null characters. */
3262 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3263 continue;
3265 /* Escape-quote whitespace and backslashes. */
3266 q = cmdline + cmdline_size;
3267 while (cmdline < p)
3269 char c = *--p;
3270 *--q = c ? c : ' ';
3271 if (c_isspace (c) || c == '\\')
3272 *--q = '\\';
3275 nread = cmdline + cmdline_size - q;
3278 if (!nread)
3280 nread = cmdsize + 2;
3281 cmdline_size = nread + 1;
3282 q = cmdline = xrealloc (cmdline, cmdline_size);
3283 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3284 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3286 /* Command line is encoded in locale-coding-system; decode it. */
3287 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3288 decoded_cmd = code_convert_string_norecord (cmd_str,
3289 Vlocale_coding_system, 0);
3290 unbind_to (count, Qnil);
3291 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3294 return attrs;
3297 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3299 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3300 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3301 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3302 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3303 #undef _FILE_OFFSET_BITS
3304 #else
3305 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3306 #endif
3308 #include <procfs.h>
3310 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3311 #define _FILE_OFFSET_BITS 64
3312 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3313 #endif
3314 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3316 Lisp_Object
3317 system_process_attributes (Lisp_Object pid)
3319 char procfn[PATH_MAX], fn[PATH_MAX];
3320 struct stat st;
3321 struct passwd *pw;
3322 struct group *gr;
3323 char *procfn_end;
3324 struct psinfo pinfo;
3325 int fd;
3326 ssize_t nread;
3327 printmax_t proc_id;
3328 uid_t uid;
3329 gid_t gid;
3330 Lisp_Object attrs = Qnil;
3331 Lisp_Object decoded_cmd;
3332 ptrdiff_t count;
3334 CHECK_NUMBER_OR_FLOAT (pid);
3335 CONS_TO_INTEGER (pid, pid_t, proc_id);
3336 sprintf (procfn, "/proc/%"pMd, proc_id);
3337 if (stat (procfn, &st) < 0)
3338 return attrs;
3340 /* euid egid */
3341 uid = st.st_uid;
3342 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3343 block_input ();
3344 pw = getpwuid (uid);
3345 unblock_input ();
3346 if (pw)
3347 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3349 gid = st.st_gid;
3350 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3351 block_input ();
3352 gr = getgrgid (gid);
3353 unblock_input ();
3354 if (gr)
3355 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3357 count = SPECPDL_INDEX ();
3358 strcpy (fn, procfn);
3359 procfn_end = fn + strlen (fn);
3360 strcpy (procfn_end, "/psinfo");
3361 fd = emacs_open (fn, O_RDONLY, 0);
3362 if (fd < 0)
3363 nread = 0;
3364 else
3366 record_unwind_protect (close_file_unwind, fd);
3367 nread = emacs_read (fd, &pinfo, sizeof pinfo);
3370 if (nread == sizeof pinfo)
3372 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3373 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3374 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3377 char state_str[2];
3378 state_str[0] = pinfo.pr_lwp.pr_sname;
3379 state_str[1] = '\0';
3380 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3383 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3384 need to get a string from it. */
3386 /* FIXME: missing: Qtpgid */
3388 /* FIXME: missing:
3389 Qminflt
3390 Qmajflt
3391 Qcminflt
3392 Qcmajflt
3394 Qutime
3395 Qcutime
3396 Qstime
3397 Qcstime
3398 Are they available? */
3400 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3401 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3402 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3403 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3404 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3405 attrs);
3407 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3408 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3409 attrs);
3410 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3411 attrs);
3413 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3414 range 0 .. 2**15, representing 0.0 .. 1.0. */
3415 attrs = Fcons (Fcons (Qpcpu,
3416 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3417 attrs);
3418 attrs = Fcons (Fcons (Qpmem,
3419 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3420 attrs);
3422 AUTO_STRING (fname, pinfo.pr_fname);
3423 decoded_cmd = code_convert_string_norecord (fname,
3424 Vlocale_coding_system, 0);
3425 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3426 AUTO_STRING (psargs, pinfo.pr_psargs);
3427 decoded_cmd = code_convert_string_norecord (psargs,
3428 Vlocale_coding_system, 0);
3429 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3431 unbind_to (count, Qnil);
3432 return attrs;
3435 #elif defined __FreeBSD__
3437 static struct timespec
3438 timeval_to_timespec (struct timeval t)
3440 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3443 static Lisp_Object
3444 make_lisp_timeval (struct timeval t)
3446 return make_lisp_time (timeval_to_timespec (t));
3449 Lisp_Object
3450 system_process_attributes (Lisp_Object pid)
3452 int proc_id;
3453 int pagesize = getpagesize ();
3454 unsigned long npages;
3455 int fscale;
3456 struct passwd *pw;
3457 struct group *gr;
3458 char *ttyname;
3459 size_t len;
3460 char args[MAXPATHLEN];
3461 struct timespec t, now;
3463 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3464 struct kinfo_proc proc;
3465 size_t proclen = sizeof proc;
3467 Lisp_Object attrs = Qnil;
3468 Lisp_Object decoded_comm;
3470 CHECK_NUMBER_OR_FLOAT (pid);
3471 CONS_TO_INTEGER (pid, int, proc_id);
3472 mib[3] = proc_id;
3474 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3475 return attrs;
3477 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3479 block_input ();
3480 pw = getpwuid (proc.ki_uid);
3481 unblock_input ();
3482 if (pw)
3483 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3485 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3487 block_input ();
3488 gr = getgrgid (proc.ki_svgid);
3489 unblock_input ();
3490 if (gr)
3491 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3493 AUTO_STRING (comm, proc.ki_comm);
3494 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3496 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3498 char state[2] = {'\0', '\0'};
3499 switch (proc.ki_stat)
3501 case SRUN:
3502 state[0] = 'R';
3503 break;
3505 case SSLEEP:
3506 state[0] = 'S';
3507 break;
3509 case SLOCK:
3510 state[0] = 'D';
3511 break;
3513 case SZOMB:
3514 state[0] = 'Z';
3515 break;
3517 case SSTOP:
3518 state[0] = 'T';
3519 break;
3521 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3524 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3525 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3526 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3528 block_input ();
3529 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3530 unblock_input ();
3531 if (ttyname)
3532 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3534 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3535 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3536 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3537 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3538 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3540 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3541 attrs);
3542 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3543 attrs);
3544 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3545 timeval_to_timespec (proc.ki_rusage.ru_stime));
3546 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3548 attrs = Fcons (Fcons (Qcutime,
3549 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3550 attrs);
3551 attrs = Fcons (Fcons (Qcstime,
3552 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3553 attrs);
3554 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3555 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3556 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3558 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3559 attrs);
3560 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3561 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3562 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3563 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3564 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3565 attrs);
3567 now = current_timespec ();
3568 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3569 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3571 len = sizeof fscale;
3572 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3574 double pcpu;
3575 fixpt_t ccpu;
3576 len = sizeof ccpu;
3577 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3579 pcpu = (100.0 * proc.ki_pctcpu / fscale
3580 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3581 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3585 len = sizeof npages;
3586 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3588 double pmem = (proc.ki_flag & P_INMEM
3589 ? 100.0 * proc.ki_rssize / npages
3590 : 0);
3591 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3594 mib[2] = KERN_PROC_ARGS;
3595 len = MAXPATHLEN;
3596 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3598 int i;
3599 for (i = 0; i < len; i++)
3601 if (! args[i] && i < len - 1)
3602 args[i] = ' ';
3605 AUTO_STRING (comm, args);
3606 decoded_comm = code_convert_string_norecord (comm,
3607 Vlocale_coding_system, 0);
3609 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3612 return attrs;
3615 #elif defined DARWIN_OS
3617 static struct timespec
3618 timeval_to_timespec (struct timeval t)
3620 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3623 static Lisp_Object
3624 make_lisp_timeval (struct timeval t)
3626 return make_lisp_time (timeval_to_timespec (t));
3629 Lisp_Object
3630 system_process_attributes (Lisp_Object pid)
3632 int proc_id;
3633 int pagesize = getpagesize ();
3634 unsigned long npages;
3635 int fscale;
3636 struct passwd *pw;
3637 struct group *gr;
3638 char *ttyname;
3639 size_t len;
3640 char args[MAXPATHLEN];
3641 struct timeval starttime;
3642 struct timespec t, now;
3643 struct rusage *rusage;
3644 dev_t tdev;
3645 uid_t uid;
3646 gid_t gid;
3648 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3649 struct kinfo_proc proc;
3650 size_t proclen = sizeof proc;
3652 Lisp_Object attrs = Qnil;
3653 Lisp_Object decoded_comm;
3655 CHECK_NUMBER_OR_FLOAT (pid);
3656 CONS_TO_INTEGER (pid, int, proc_id);
3657 mib[3] = proc_id;
3659 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3660 return attrs;
3662 uid = proc.kp_eproc.e_ucred.cr_uid;
3663 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3665 block_input ();
3666 pw = getpwuid (uid);
3667 unblock_input ();
3668 if (pw)
3669 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3671 gid = proc.kp_eproc.e_pcred.p_svgid;
3672 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3674 block_input ();
3675 gr = getgrgid (gid);
3676 unblock_input ();
3677 if (gr)
3678 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3680 decoded_comm = (code_convert_string_norecord
3681 (build_unibyte_string (proc.kp_proc.p_comm),
3682 Vlocale_coding_system, 0));
3684 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3686 char state[2] = {'\0', '\0'};
3687 switch (proc.kp_proc.p_stat)
3689 case SRUN:
3690 state[0] = 'R';
3691 break;
3693 case SSLEEP:
3694 state[0] = 'S';
3695 break;
3697 case SZOMB:
3698 state[0] = 'Z';
3699 break;
3701 case SSTOP:
3702 state[0] = 'T';
3703 break;
3705 case SIDL:
3706 state[0] = 'I';
3707 break;
3709 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3712 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3713 attrs);
3714 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3715 attrs);
3717 tdev = proc.kp_eproc.e_tdev;
3718 block_input ();
3719 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3720 unblock_input ();
3721 if (ttyname)
3722 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3724 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3725 attrs);
3727 rusage = proc.kp_proc.p_ru;
3728 if (rusage)
3730 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3731 attrs);
3732 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3733 attrs);
3735 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3736 attrs);
3737 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3738 attrs);
3739 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3740 timeval_to_timespec (rusage->ru_stime));
3741 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3744 starttime = proc.kp_proc.p_starttime;
3745 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3746 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3748 now = current_timespec ();
3749 t = timespec_sub (now, timeval_to_timespec (starttime));
3750 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3752 return attrs;
3755 /* The WINDOWSNT implementation is in w32.c.
3756 The MSDOS implementation is in dosfns.c. */
3757 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3759 Lisp_Object
3760 system_process_attributes (Lisp_Object pid)
3762 return Qnil;
3765 #endif /* !defined (WINDOWSNT) */
3767 /* Wide character string collation. */
3769 #ifdef __STDC_ISO_10646__
3770 # include <wchar.h>
3771 # include <wctype.h>
3773 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3774 # include <locale.h>
3775 # endif
3776 # ifndef LC_COLLATE
3777 # define LC_COLLATE 0
3778 # endif
3779 # ifndef LC_COLLATE_MASK
3780 # define LC_COLLATE_MASK 0
3781 # endif
3782 # ifndef LC_CTYPE
3783 # define LC_CTYPE 0
3784 # endif
3785 # ifndef LC_CTYPE_MASK
3786 # define LC_CTYPE_MASK 0
3787 # endif
3789 # ifndef HAVE_NEWLOCALE
3790 # undef freelocale
3791 # undef locale_t
3792 # undef newlocale
3793 # undef wcscoll_l
3794 # undef towlower_l
3795 # define freelocale emacs_freelocale
3796 # define locale_t emacs_locale_t
3797 # define newlocale emacs_newlocale
3798 # define wcscoll_l emacs_wcscoll_l
3799 # define towlower_l emacs_towlower_l
3801 typedef char const *locale_t;
3803 static locale_t
3804 newlocale (int category_mask, char const *locale, locale_t loc)
3806 return locale;
3809 static void
3810 freelocale (locale_t loc)
3814 static char *
3815 emacs_setlocale (int category, char const *locale)
3817 # ifdef HAVE_SETLOCALE
3818 errno = 0;
3819 char *loc = setlocale (category, locale);
3820 if (loc || errno)
3821 return loc;
3822 errno = EINVAL;
3823 # else
3824 errno = ENOTSUP;
3825 # endif
3826 return 0;
3829 static int
3830 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3832 int result = 0;
3833 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3834 int err;
3836 if (! oldloc)
3837 err = errno;
3838 else
3840 USE_SAFE_ALLOCA;
3841 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3842 strcpy (oldcopy, oldloc);
3843 if (! emacs_setlocale (LC_COLLATE, loc))
3844 err = errno;
3845 else
3847 errno = 0;
3848 result = wcscoll (a, b);
3849 err = errno;
3850 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3851 err = errno;
3853 SAFE_FREE ();
3856 errno = err;
3857 return result;
3860 static wint_t
3861 towlower_l (wint_t wc, locale_t loc)
3863 wint_t result = wc;
3864 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3866 if (oldloc)
3868 USE_SAFE_ALLOCA;
3869 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3870 strcpy (oldcopy, oldloc);
3871 if (emacs_setlocale (LC_CTYPE, loc))
3873 result = towlower (wc);
3874 emacs_setlocale (LC_COLLATE, oldcopy);
3876 SAFE_FREE ();
3879 return result;
3881 # endif
3884 str_collate (Lisp_Object s1, Lisp_Object s2,
3885 Lisp_Object locale, Lisp_Object ignore_case)
3887 int res, err;
3888 ptrdiff_t len, i, i_byte;
3889 wchar_t *p1, *p2;
3891 USE_SAFE_ALLOCA;
3893 /* Convert byte stream to code points. */
3894 len = SCHARS (s1); i = i_byte = 0;
3895 SAFE_NALLOCA (p1, 1, len + 1);
3896 while (i < len)
3897 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3898 *(p1+len) = 0;
3900 len = SCHARS (s2); i = i_byte = 0;
3901 SAFE_NALLOCA (p2, 1, len + 1);
3902 while (i < len)
3903 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3904 *(p2+len) = 0;
3906 if (STRINGP (locale))
3908 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3909 SSDATA (locale), 0);
3910 if (!loc)
3911 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
3913 if (! NILP (ignore_case))
3914 for (int i = 1; i < 3; i++)
3916 wchar_t *p = (i == 1) ? p1 : p2;
3917 for (; *p; p++)
3918 *p = towlower_l (*p, loc);
3921 errno = 0;
3922 res = wcscoll_l (p1, p2, loc);
3923 err = errno;
3924 freelocale (loc);
3926 else
3928 if (! NILP (ignore_case))
3929 for (int i = 1; i < 3; i++)
3931 wchar_t *p = (i == 1) ? p1 : p2;
3932 for (; *p; p++)
3933 *p = towlower (*p);
3936 errno = 0;
3937 res = wcscoll (p1, p2);
3938 err = errno;
3940 # ifndef HAVE_NEWLOCALE
3941 if (err)
3942 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
3943 # else
3944 if (err)
3945 error ("Invalid string for collation: %s", emacs_strerror (err));
3946 # endif
3948 SAFE_FREE ();
3949 return res;
3951 #endif /* __STDC_ISO_10646__ */
3953 #ifdef WINDOWSNT
3955 str_collate (Lisp_Object s1, Lisp_Object s2,
3956 Lisp_Object locale, Lisp_Object ignore_case)
3959 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
3960 int res, err = errno;
3962 errno = 0;
3963 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
3964 if (errno)
3965 error ("Invalid string for collation: %s", strerror (errno));
3967 errno = err;
3968 return res;
3970 #endif /* WINDOWSNT */