1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2017 Free Software
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/>. */
27 #endif /* HAVE_PWD_H */
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #if defined DARWIN_OS || defined __FreeBSD__
41 # include <sys/sysctl.h>
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>
55 #include <sys/socket.h>
57 #endif /* HAVE_SOCKETS */
61 #define write sys_write
63 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
66 #endif /* WINDOWSNT */
68 #include <sys/types.h>
72 /* Get SI_SRPC_DOMAIN, if it is available. */
73 #ifdef HAVE_SYS_SYSTEMINFO_H
74 #include <sys/systeminfo.h>
77 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
81 #include <sys/param.h>
88 #ifdef HAVE_SYS_UTSNAME_H
89 #include <sys/utsname.h>
91 #endif /* HAVE_SYS_UTSNAME_H */
95 #include "termhooks.h"
102 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
103 do that during startup just to call gnutls_rnd. */
104 #if defined HAVE_GNUTLS && !defined WINDOWSNT
105 # include <gnutls/crypto.h>
107 # define emacs_gnutls_global_init() Qnil
108 # define gnutls_rnd(level, data, len) (-1)
113 /* In process.h which conflicts with the local copy. */
115 int _cdecl
_spawnlp (int, const char *, const char *, ...);
116 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
117 several prototypes of functions called below. */
118 #include <sys/socket.h>
121 #include "syssignal.h"
124 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
126 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
129 /* Declare here, including term.h is problematic on some systems. */
130 extern void tputs (const char *, int, int (*)(int));
132 static const int baud_convert
[] =
134 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
135 1800, 2400, 4800, 9600, 19200, 38400
138 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
139 # include <sys/personality.h>
141 /* Disable address randomization in the current process. Return true
142 if addresses were randomized but this has been disabled, false
145 disable_address_randomization (void)
147 int pers
= personality (0xffffffff);
150 int desired_pers
= pers
| ADDR_NO_RANDOMIZE
;
152 /* Call 'personality' twice, to detect buggy platforms like WSL
153 where 'personality' always returns 0. */
154 return (pers
!= desired_pers
155 && personality (desired_pers
) == pers
156 && personality (0xffffffff) == desired_pers
);
160 /* Execute the program in FILE, with argument vector ARGV and environ
161 ENVP. Return an error number if unsuccessful. This is like execve
162 except it reenables ASLR in the executed program if necessary, and
163 on error it returns an error number rather than -1. */
165 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
167 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
168 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
169 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
170 if (change_personality
)
171 personality (pers
& ~ADDR_NO_RANDOMIZE
);
174 execve (file
, argv
, envp
);
177 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
178 if (change_personality
)
185 /* If FD is not already open, arrange for it to be open with FLAGS. */
187 force_open (int fd
, int flags
)
189 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
191 int n
= open (NULL_DEVICE
, flags
);
192 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
194 emacs_perror (NULL_DEVICE
);
200 /* Make sure stdin, stdout, and stderr are open to something, so that
201 their file descriptors are not hijacked by later system calls. */
203 init_standard_fds (void)
205 /* Open stdin for *writing*, and stdout and stderr for *reading*.
206 That way, any attempt to do normal I/O will result in an error,
207 just as if the files were closed, and the file descriptors will
208 not be reused by later opens. */
209 force_open (STDIN_FILENO
, O_WRONLY
);
210 force_open (STDOUT_FILENO
, O_RDONLY
);
211 force_open (STDERR_FILENO
, O_RDONLY
);
214 /* Return the current working directory. The result should be freed
215 with 'free'. Return NULL on errors. */
217 emacs_get_current_dir_name (void)
219 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
220 # ifdef HYBRID_MALLOC
221 bool use_libc
= bss_sbrk_did_unexec
;
223 bool use_libc
= true;
226 return get_current_dir_name ();
230 char *pwd
= getenv ("PWD");
231 struct stat dotstat
, pwdstat
;
232 /* If PWD is accurate, use it instead of calling getcwd. PWD is
233 sometimes a nicer name, and using it may avoid a fatal error if a
234 parent directory is searchable but not readable. */
236 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
237 && stat (pwd
, &pwdstat
) == 0
238 && stat (".", &dotstat
) == 0
239 && dotstat
.st_ino
== pwdstat
.st_ino
240 && dotstat
.st_dev
== pwdstat
.st_dev
242 && strlen (pwd
) < MAXPATHLEN
246 buf
= malloc (strlen (pwd
) + 1);
253 size_t buf_size
= 1024;
254 buf
= malloc (buf_size
);
259 if (getcwd (buf
, buf_size
) == buf
)
263 int tmp_errno
= errno
;
269 buf
= realloc (buf
, buf_size
);
278 /* Discard pending input on all input descriptors. */
281 discard_tty_input (void)
284 struct emacs_tty buf
;
289 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
290 while (dos_keyread () != -1)
292 #else /* not MSDOS */
294 struct tty_display_info
*tty
;
295 for (tty
= tty_list
; tty
; tty
= tty
->next
)
297 if (tty
->input
) /* Is the device suspended? */
299 emacs_get_tty (fileno (tty
->input
), &buf
);
300 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
304 #endif /* not MSDOS */
305 #endif /* not WINDOWSNT */
311 /* Arrange for character C to be read as the next input from
313 XXX What if we have multiple ttys?
319 if (! (FRAMEP (selected_frame
)
320 && FRAME_LIVE_P (XFRAME (selected_frame
))
321 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
324 /* Should perhaps error if in batch mode */
326 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
327 #else /* no TIOCSTI */
328 error ("Cannot stuff terminal input characters in this version of Unix");
329 #endif /* no TIOCSTI */
335 init_baud_rate (int fd
)
345 #else /* not DOS_NT */
350 emacs_ospeed
= cfgetospeed (&sg
);
351 #endif /* not DOS_NT */
354 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
355 ? baud_convert
[emacs_ospeed
] : 9600);
364 /* Wait for the subprocess with process id CHILD to terminate or change status.
365 CHILD must be a child process that has not been reaped.
366 If STATUS is non-null, store the waitpid-style exit status into *STATUS
367 and tell wait_reading_process_output that it needs to look around.
368 Use waitpid-style OPTIONS when waiting.
369 If INTERRUPTIBLE, this function is interruptible by a signal.
371 Return CHILD if successful, 0 if no status is available;
372 the latter is possible only when options & NOHANG. */
374 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
378 /* Invoke waitpid only with a known process ID; do not invoke
379 waitpid with a nonpositive argument. Otherwise, Emacs might
380 reap an unwanted process by mistake. For example, invoking
381 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
382 so that another thread running glib won't find them. */
385 while ((pid
= waitpid (child
, status
, options
)) < 0)
387 /* Check that CHILD is a child process that has not been reaped,
388 and that STATUS and OPTIONS are valid. Otherwise abort,
389 as continuing after this internal error could cause Emacs to
390 become confused and kill innocent-victim processes. */
394 /* Note: the MS-Windows emulation of waitpid calls QUIT
400 /* If successful and status is requested, tell wait_reading_process_output
401 that it needs to wake up and look around. */
402 if (pid
&& status
&& input_available_clear_time
)
403 *input_available_clear_time
= make_timespec (0, 0);
408 /* Wait for the subprocess with process id CHILD to terminate.
409 CHILD must be a child process that has not been reaped.
410 If STATUS is non-null, store the waitpid-style exit status into *STATUS
411 and tell wait_reading_process_output that it needs to look around.
412 If INTERRUPTIBLE, this function is interruptible by a signal. */
414 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
416 get_child_status (child
, status
, 0, interruptible
);
419 /* Report whether the subprocess with process id CHILD has changed status.
420 Termination counts as a change of status.
421 CHILD must be a child process that has not been reaped.
422 If STATUS is non-null, store the waitpid-style exit status into *STATUS
423 and tell wait_reading_process_output that it needs to look around.
424 Use waitpid-style OPTIONS to check status, but do not wait.
426 Return CHILD if successful, 0 if no status is available because
427 the process's state has not changed. */
429 child_status_changed (pid_t child
, int *status
, int options
)
431 return get_child_status (child
, status
, WNOHANG
| options
, 0);
435 /* Set up the terminal at the other end of a pseudo-terminal that
436 we will be controlling an inferior through.
437 It should not echo or do line-editing, since that is done
438 in Emacs. No padding needed for insertion into an Emacs buffer. */
441 child_setup_tty (int out
)
446 emacs_get_tty (out
, &s
);
447 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
448 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
450 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
451 Some versions of GNU Hurd do not have FFDLY? */
453 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
454 /* No output delays */
456 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
457 /* No output delays */
460 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
461 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
463 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
466 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
469 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
471 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
472 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
473 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
474 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
477 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
480 #ifdef SIGNALS_VIA_CHARACTERS
481 /* the QUIT and INTR character are used in process_send_signal
482 so set them here to something useful. */
483 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
484 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
485 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
486 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
487 #endif /* not SIGNALS_VIA_CHARACTERS */
490 /* Also, PTY overloads NUL and BREAK.
491 don't ignore break, but don't signal either, so it looks like NUL. */
492 s
.main
.c_iflag
&= ~IGNBRK
;
493 s
.main
.c_iflag
&= ~BRKINT
;
494 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
495 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
496 would force it to 0377. That looks like duplicated code. */
497 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
500 /* We originally enabled ICANON (and set VEOF to 04), and then had
501 process.c send additional EOF chars to flush the output when faced
502 with long lines, but this leads to weird effects when the
503 subprocess has disabled ICANON and ends up seeing those spurious
504 extra EOFs. So we don't send EOFs any more in
505 process.c:send_process. First we tried to disable ICANON by
506 default, so if a subsprocess sets up ICANON, it's his problem (or
507 the Elisp package that talks to it) to deal with lines that are
508 too long. But this disables some features, such as the ability
509 to send EOF signals. So we re-enabled ICANON but there is no
510 more "send eof to flush" going on (which is wrong and unportable
511 in itself). The correct way to handle too much output is to
512 buffer what could not be written and then write it again when
513 select returns ok for writing. This has it own set of
514 problems. Write is now asynchronous, is that a problem? How much
515 do we buffer, and what do we do when that limit is reached? */
517 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
518 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
519 #if 0 /* These settings only apply to non-ICANON mode. */
520 s
.main
.c_cc
[VMIN
] = 1;
521 s
.main
.c_cc
[VTIME
] = 0;
524 emacs_set_tty (out
, &s
, 0);
525 #endif /* not WINDOWSNT */
527 #endif /* not MSDOS */
530 /* Record a signal code and the action for it. */
534 struct sigaction action
;
537 static void save_signal_handlers (struct save_signal
*);
538 static void restore_signal_handlers (struct save_signal
*);
540 /* Suspend the Emacs process; give terminal to its superior. */
548 /* On a system where suspending is not implemented,
549 instead fork a subshell and let it talk directly to the terminal
556 /* Fork a subshell. */
561 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
564 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
566 char oldwd
[MAX_UTF8_PATH
];
572 struct save_signal saved_handlers
[5];
573 char *str
= SSDATA (encode_current_directory ());
579 char *volatile str_volatile
= str
;
586 error ("Can't spawn subshell");
588 saved_handlers
[0].code
= SIGINT
;
589 saved_handlers
[1].code
= SIGQUIT
;
590 saved_handlers
[2].code
= SIGTERM
;
592 saved_handlers
[3].code
= SIGIO
;
593 saved_handlers
[4].code
= 0;
595 saved_handlers
[3].code
= 0;
599 save_signal_handlers (saved_handlers
);
606 #ifdef DOS_NT /* MW, Aug 1993 */
607 getcwd (oldwd
, sizeof oldwd
);
609 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
612 sh
= egetenv ("SHELL");
616 /* Use our buffer's default directory for the subshell. */
617 if (chdir (str
) != 0)
621 _exit (EXIT_CANCELED
);
625 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
627 char *epwd
= getenv ("PWD");
628 char old_pwd
[MAXPATHLEN
+1+4];
630 /* If PWD is set, pass it with corrected value. */
633 strcpy (old_pwd
, epwd
);
634 setenv ("PWD", str
, 1);
637 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
639 putenv (old_pwd
); /* restore previous value */
641 #else /* not MSDOS */
643 /* Waits for process completion */
644 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
645 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
647 write (1, "Can't execute subshell", 22);
648 #else /* not WINDOWSNT */
649 execlp (sh
, sh
, (char *) 0);
651 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
652 #endif /* not WINDOWSNT */
653 #endif /* not MSDOS */
656 /* Do this now if we did not do it before. */
658 save_signal_handlers (saved_handlers
);
662 wait_for_termination (pid
, &status
, 0);
664 restore_signal_handlers (saved_handlers
);
668 save_signal_handlers (struct save_signal
*saved_handlers
)
670 while (saved_handlers
->code
)
672 struct sigaction action
;
673 emacs_sigaction_init (&action
, SIG_IGN
);
674 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
680 restore_signal_handlers (struct save_signal
*saved_handlers
)
682 while (saved_handlers
->code
)
684 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
690 static int old_fcntl_flags
[FD_SETSIZE
];
697 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
698 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
699 interrupts_deferred
= 0;
708 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
722 sigemptyset (&unblocked
);
724 sigaddset (&unblocked
, SIGWINCH
);
726 sigaddset (&unblocked
, SIGIO
);
727 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
729 interrupts_deferred
= 0;
734 unrequest_sigio (void)
742 sigemptyset (&blocked
);
744 sigaddset (&blocked
, SIGWINCH
);
746 sigaddset (&blocked
, SIGIO
);
747 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
748 interrupts_deferred
= 1;
756 block_child_signal (sigset_t
*oldset
)
759 sigemptyset (&blocked
);
760 sigaddset (&blocked
, SIGCHLD
);
761 sigaddset (&blocked
, SIGINT
);
762 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
765 /* Unblock SIGCHLD. */
768 unblock_child_signal (sigset_t
const *oldset
)
770 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
775 block_interrupt_signal (sigset_t
*oldset
)
778 sigemptyset (&blocked
);
779 sigaddset (&blocked
, SIGINT
);
780 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
783 /* Restore previously saved signal mask. */
785 restore_signal_mask (sigset_t
const *oldset
)
787 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
792 /* Saving and restoring the process group of Emacs's terminal. */
794 /* The process group of which Emacs was a member when it initially
797 If Emacs was in its own process group (i.e. inherited_pgroup ==
798 getpid ()), then we know we're running under a shell with job
799 control (Emacs would never be run as part of a pipeline).
802 If Emacs was not in its own process group, then we know we're
803 running under a shell (or a caller) that doesn't know how to
804 separate itself from Emacs (like sh). Emacs must be in its own
805 process group in order to receive SIGIO correctly. In this
806 situation, we put ourselves in our own pgroup, forcibly set the
807 tty's pgroup to our pgroup, and make sure to restore and reinstate
808 the tty's pgroup just like any other terminal setting. If
809 inherited_group was not the tty's pgroup, then we'll get a
810 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
811 it goes foreground in the future, which is what should happen. */
813 static pid_t inherited_pgroup
;
816 init_foreground_group (void)
818 pid_t pgrp
= getpgrp ();
819 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
822 /* Block and unblock SIGTTOU. */
825 block_tty_out_signal (sigset_t
*oldset
)
829 sigemptyset (&blocked
);
830 sigaddset (&blocked
, SIGTTOU
);
831 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
836 unblock_tty_out_signal (sigset_t
const *oldset
)
839 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
843 /* Safely set a controlling terminal FD's process group to PGID.
844 If we are not in the foreground already, POSIX requires tcsetpgrp
845 to deliver a SIGTTOU signal, which would stop us. This is an
846 annoyance, so temporarily ignore the signal.
848 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
849 skip all this unless SIGTTOU is defined. */
851 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
856 block_tty_out_signal (&oldset
);
857 tcsetpgrp (fd
, pgid
);
858 unblock_tty_out_signal (&oldset
);
863 /* Split off the foreground process group to Emacs alone. When we are
864 in the foreground, but not started in our own process group,
865 redirect the tty device handle FD to point to our own process
866 group. FD must be the file descriptor of the controlling tty. */
868 narrow_foreground_group (int fd
)
870 if (inherited_pgroup
&& setpgid (0, 0) == 0)
871 tcsetpgrp_without_stopping (fd
, getpid ());
874 /* Set the tty to our original foreground group. */
876 widen_foreground_group (int fd
)
878 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
879 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
882 /* Getting and setting emacs_tty structures. */
884 /* Set *TC to the parameters associated with the terminal FD,
885 or clear it if the parameters are not available.
886 Return 0 on success, -1 on failure. */
888 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
890 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
891 memset (&settings
->main
, 0, sizeof (settings
->main
));
894 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
897 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
899 settings
->main
= console_mode
;
902 #endif /* WINDOWSNT */
905 /* We have those nifty POSIX tcmumbleattr functions. */
906 return tcgetattr (fd
, &settings
->main
);
911 /* Set the parameters of the tty on FD according to the contents of
912 *SETTINGS. If FLUSHP, discard input.
913 Return 0 if all went well, and -1 (setting errno) if anything failed. */
916 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
918 /* Set the primary parameters - baud rate, character size, etcetera. */
921 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
923 if (h
&& h
!= INVALID_HANDLE_VALUE
)
927 /* Assume the handle is open for input. */
929 FlushConsoleInputBuffer (h
);
930 new_mode
= settings
->main
;
931 SetConsoleMode (h
, new_mode
);
933 #endif /* WINDOWSNT */
936 /* We have those nifty POSIX tcmumbleattr functions.
937 William J. Smith <wjs@wiis.wang.com> writes:
938 "POSIX 1003.1 defines tcsetattr to return success if it was
939 able to perform any of the requested actions, even if some
940 of the requested actions could not be performed.
941 We must read settings back to ensure tty setup properly.
942 AIX requires this to keep tty from hanging occasionally." */
943 /* This make sure that we don't loop indefinitely in here. */
944 for (i
= 0 ; i
< 10 ; i
++)
945 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
956 memset (&new, 0, sizeof (new));
957 /* Get the current settings, and see if they're what we asked for. */
958 tcgetattr (fd
, &new);
959 /* We cannot use memcmp on the whole structure here because under
960 * aix386 the termios structure has some reserved field that may
963 if ( new.c_iflag
== settings
->main
.c_iflag
964 && new.c_oflag
== settings
->main
.c_oflag
965 && new.c_cflag
== settings
->main
.c_cflag
966 && new.c_lflag
== settings
->main
.c_lflag
967 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
974 /* We have survived the tempest. */
981 static int old_fcntl_owner
[FD_SETSIZE
];
982 #endif /* F_SETOWN */
984 /* This may also be defined in stdio,
985 but if so, this does no harm,
986 and using the same name avoids wasting the other one's space. */
989 unsigned char _sobuf
[BUFSIZ
+8];
994 /* Initialize the terminal mode on all tty devices that are currently
998 init_all_sys_modes (void)
1000 struct tty_display_info
*tty
;
1001 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1002 init_sys_modes (tty
);
1005 /* Initialize the terminal mode on the given tty device. */
1008 init_sys_modes (struct tty_display_info
*tty_out
)
1010 struct emacs_tty tty
;
1012 Lisp_Object terminal
;
1015 Vtty_erase_char
= Qnil
;
1020 if (!tty_out
->output
)
1021 return; /* The tty is suspended. */
1023 narrow_foreground_group (fileno (tty_out
->input
));
1025 if (! tty_out
->old_tty
)
1026 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1028 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1030 tty
= *tty_out
->old_tty
;
1032 #if !defined (DOS_NT)
1033 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1035 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1036 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1037 #ifdef INLCR /* I'm just being cautious,
1038 since I can't check how widespread INLCR is--rms. */
1039 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1042 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1044 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1045 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1047 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1049 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1050 if (tty_out
->flow_control
)
1052 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1054 tty
.main
.c_iflag
&= ~IXANY
;
1058 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1059 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1061 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1063 if (tty_out
->meta_key
)
1065 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1066 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1070 XSETTERMINAL(terminal
, tty_out
->terminal
);
1071 if (!NILP (Fcontrolling_tty_p (terminal
)))
1073 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1074 /* Set up C-g for both SIGQUIT and SIGINT.
1075 We don't know which we will get, but we handle both alike
1076 so which one it really gives us does not matter. */
1077 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1081 /* We normally don't get interrupt or quit signals from tty
1082 devices other than our controlling terminal; therefore,
1083 we must handle C-g as normal input. Unfortunately, this
1084 means that the interrupt and quit feature must be
1085 disabled on secondary ttys, or we would not even see the
1088 Note that even though emacsclient could have special code
1089 to pass SIGINT to Emacs, we should _not_ enable
1090 interrupt/quit keys for emacsclient frames. This means
1091 that we can't break out of loops in C code from a
1092 secondary tty frame, but we can always decide what
1093 display the C-g came from, which is more important from a
1094 usability point of view. (Consider the case when two
1095 people work together using the same Emacs instance.) */
1096 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1097 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1099 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1100 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1102 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1107 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1110 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1111 #endif /* V_DSUSP */
1112 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1113 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1116 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1119 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1120 #endif /* VREPRINT */
1122 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1123 #endif /* VWERASE */
1125 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1126 #endif /* VDISCARD */
1128 if (tty_out
->flow_control
)
1131 tty
.main
.c_cc
[VSTART
] = '\021';
1134 tty
.main
.c_cc
[VSTOP
] = '\023';
1140 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1143 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1148 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1149 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1150 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1151 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1152 if (tty_out
->flow_control
)
1155 tty
.main
.c_cc
[VSTART
] = '\021';
1158 tty
.main
.c_cc
[VSTOP
] = '\023';
1161 /* Also, PTY overloads NUL and BREAK.
1162 don't ignore break, but don't signal either, so it looks like NUL.
1163 This really serves a purpose only if running in an XTERM window
1164 or via TELNET or the like, but does no harm elsewhere. */
1165 tty
.main
.c_iflag
&= ~IGNBRK
;
1166 tty
.main
.c_iflag
&= ~BRKINT
;
1168 #endif /* not DOS_NT */
1170 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1171 if (!tty_out
->term_initted
)
1172 internal_terminal_init ();
1173 dos_ttraw (tty_out
);
1176 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1178 /* This code added to insure that, if flow-control is not to be used,
1179 we have an unlocked terminal at the start. */
1182 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1185 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1188 #if !defined (DOS_NT)
1190 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1195 if (interrupt_input
)
1197 old_fcntl_owner
[fileno (tty_out
->input
)] =
1198 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1199 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1200 init_sigio (fileno (tty_out
->input
));
1202 if (gpm_tty
== tty_out
)
1204 /* Arrange for mouse events to give us SIGIO signals. */
1205 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1206 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1207 init_sigio (gpm_fd
);
1209 #endif /* HAVE_GPM */
1211 #endif /* F_GETOWN */
1214 /* This symbol is defined on recent USG systems.
1215 Someone says without this call USG won't really buffer the file
1216 even with a call to setbuf. */
1217 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1219 setbuf (tty_out
->output
, (char *) _sobuf
);
1222 if (tty_out
->terminal
->set_terminal_modes_hook
)
1223 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1225 if (!tty_out
->term_initted
)
1227 Lisp_Object tail
, frame
;
1228 FOR_EACH_FRAME (tail
, frame
)
1230 /* XXX This needs to be revised. */
1231 if (FRAME_TERMCAP_P (XFRAME (frame
))
1232 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1233 init_frame_faces (XFRAME (frame
));
1237 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1239 /* We used to call "direct_output_forward_char(0)" here,
1240 but it's not clear why, since it may not do anything anyway. */
1244 Lisp_Object tail
, frame
;
1246 FOR_EACH_FRAME (tail
, frame
)
1248 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1249 || FRAME_MSDOS_P (XFRAME (frame
)))
1250 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1251 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1255 tty_out
->term_initted
= 1;
1258 /* Return true if safe to use tabs in output.
1259 At the time this is called, init_sys_modes has not been done yet. */
1262 tabs_safe_p (int fd
)
1264 struct emacs_tty etty
;
1266 emacs_get_tty (fd
, &etty
);
1269 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1270 #else /* not TABDLY */
1272 #endif /* not TABDLY */
1278 /* Discard echoing. */
1281 suppress_echo_on_tty (int fd
)
1283 struct emacs_tty etty
;
1285 emacs_get_tty (fd
, &etty
);
1287 /* Set raw input mode. */
1290 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1291 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1292 #endif /* ! WINDOWSNT */
1293 emacs_set_tty (fd
, &etty
, 0);
1296 /* Get terminal size from system.
1297 Store number of lines into *HEIGHTP and width into *WIDTHP.
1298 We store 0 if there's no valid information. */
1301 get_tty_size (int fd
, int *widthp
, int *heightp
)
1303 #if defined TIOCGWINSZ
1306 struct winsize size
;
1308 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1309 *widthp
= *heightp
= 0;
1312 *widthp
= size
.ws_col
;
1313 *heightp
= size
.ws_row
;
1316 #elif defined TIOCGSIZE
1318 /* SunOS - style. */
1319 struct ttysize size
;
1321 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1322 *widthp
= *heightp
= 0;
1325 *widthp
= size
.ts_cols
;
1326 *heightp
= size
.ts_lines
;
1329 #elif defined WINDOWSNT
1331 CONSOLE_SCREEN_BUFFER_INFO info
;
1332 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1334 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1335 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1338 *widthp
= *heightp
= 0;
1342 *widthp
= ScreenCols ();
1343 *heightp
= ScreenRows ();
1345 #else /* system doesn't know size */
1353 /* Set the logical window size associated with descriptor FD
1354 to HEIGHT and WIDTH. This is used mainly with ptys.
1355 Return a negative value on failure. */
1358 set_window_size (int fd
, int height
, int width
)
1363 struct winsize size
;
1364 size
.ws_row
= height
;
1365 size
.ws_col
= width
;
1367 return ioctl (fd
, TIOCSWINSZ
, &size
);
1372 /* SunOS - style. */
1373 struct ttysize size
;
1374 size
.ts_lines
= height
;
1375 size
.ts_cols
= width
;
1377 return ioctl (fd
, TIOCGSIZE
, &size
);
1380 #endif /* not SunOS-style */
1381 #endif /* not BSD-style */
1386 /* Prepare all terminal devices for exiting Emacs. */
1389 reset_all_sys_modes (void)
1391 struct tty_display_info
*tty
;
1392 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1393 reset_sys_modes (tty
);
1396 /* Prepare the terminal for closing it; move the cursor to the
1397 bottom of the frame, turn off interrupt-driven I/O, etc. */
1400 reset_sys_modes (struct tty_display_info
*tty_out
)
1407 if (!tty_out
->term_initted
)
1410 if (!tty_out
->output
)
1411 return; /* The tty is suspended. */
1413 /* Go to and clear the last line of the terminal. */
1415 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1417 /* Code adapted from tty_clear_end_of_line. */
1418 if (tty_out
->TS_clr_line
)
1420 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1423 { /* have to do it the hard way */
1425 tty_turn_off_insert (tty_out
);
1427 for (i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1429 fputc (' ', tty_out
->output
);
1433 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1434 fflush (tty_out
->output
);
1436 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1437 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1439 /* Avoid possible loss of output when changing terminal modes. */
1440 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1445 if (interrupt_input
)
1447 reset_sigio (fileno (tty_out
->input
));
1448 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1449 old_fcntl_owner
[fileno (tty_out
->input
)]);
1451 #endif /* F_SETOWN */
1452 fcntl (fileno (tty_out
->input
), F_SETFL
,
1453 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1456 if (tty_out
->old_tty
)
1457 while (emacs_set_tty (fileno (tty_out
->input
),
1458 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1461 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1465 widen_foreground_group (fileno (tty_out
->input
));
1470 /* Set up the proper status flags for use of a pty. */
1475 /* I'm told that TOICREMOTE does not mean control chars
1476 "can't be sent" but rather that they don't have
1477 input-editing or signaling effects.
1478 That should be good, because we have other ways
1479 to do those things in Emacs.
1480 However, telnet mode seems not to work on 4.2.
1481 So TIOCREMOTE is turned off now. */
1483 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1484 will hang. In particular, the "timeout" feature (which
1485 causes a read to return if there is no data available)
1486 does this. Also it is known that telnet mode will hang
1487 in such a way that Emacs must be stopped (perhaps this
1488 is the same problem).
1490 If TIOCREMOTE is turned off, then there is a bug in
1491 hp-ux which sometimes loses data. Apparently the
1492 code which blocks the master process when the internal
1493 buffer fills up does not work. Other than this,
1494 though, everything else seems to work fine.
1496 Since the latter lossage is more benign, we may as well
1497 lose that way. -- cph */
1499 #if defined (UNIX98_PTYS)
1502 ioctl (fd
, FIONBIO
, &on
);
1507 #endif /* HAVE_PTYS */
1510 init_system_name (void)
1514 /* Set system-name to nil so that the build is deterministic. */
1515 Vsystem_name
= Qnil
;
1518 char *hostname_alloc
= NULL
;
1520 #ifndef HAVE_GETHOSTNAME
1523 hostname
= uts
.nodename
;
1524 #else /* HAVE_GETHOSTNAME */
1525 char hostname_buf
[256];
1526 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1527 hostname
= hostname_buf
;
1529 /* Try to get the host name; if the buffer is too short, try
1530 again. Apparently, the only indication gethostname gives of
1531 whether the buffer was large enough is the presence or absence
1532 of a '\0' in the string. Eech. */
1535 gethostname (hostname
, hostname_size
- 1);
1536 hostname
[hostname_size
- 1] = '\0';
1538 /* Was the buffer large enough for the '\0'? */
1539 if (strlen (hostname
) < hostname_size
- 1)
1542 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1543 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1545 #endif /* HAVE_GETHOSTNAME */
1547 for (p
= hostname
; *p
; p
++)
1548 if (*p
== ' ' || *p
== '\t')
1550 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1551 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1552 Vsystem_name
= build_string (hostname
);
1553 xfree (hostname_alloc
);
1556 sigset_t empty_mask
;
1558 static struct sigaction process_fatal_action
;
1561 emacs_sigaction_flags (void)
1564 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1565 'select') to reset their timeout on some platforms (e.g.,
1566 HP-UX 11), which is not what we want. Also, when Emacs is
1567 interactive, we don't want SA_RESTART because we need to poll
1568 for pending input so we need long-running syscalls to be interrupted
1569 after a signal that sets pending_signals.
1571 Non-interactive keyboard input goes through stdio, where we
1572 always want restartable system calls. */
1579 /* Store into *ACTION a signal action suitable for Emacs, with handler
1582 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1584 sigemptyset (&action
->sa_mask
);
1586 /* When handling a signal, block nonfatal system signals that are caught
1587 by Emacs. This makes race conditions less likely. */
1588 sigaddset (&action
->sa_mask
, SIGALRM
);
1590 sigaddset (&action
->sa_mask
, SIGCHLD
);
1593 sigaddset (&action
->sa_mask
, SIGDANGER
);
1595 #ifdef PROFILER_CPU_SUPPORT
1596 sigaddset (&action
->sa_mask
, SIGPROF
);
1599 sigaddset (&action
->sa_mask
, SIGWINCH
);
1601 if (! noninteractive
)
1603 sigaddset (&action
->sa_mask
, SIGINT
);
1604 sigaddset (&action
->sa_mask
, SIGQUIT
);
1606 sigaddset (&action
->sa_mask
, SIGIO
);
1610 action
->sa_handler
= handler
;
1611 action
->sa_flags
= emacs_sigaction_flags ();
1614 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1615 pthread_t main_thread_id
;
1618 /* SIG has arrived at the current process. Deliver it to the main
1619 thread, which should handle it with HANDLER. (Delivering the
1620 signal to some other thread might not work if the other thread is
1623 If we are on the main thread, handle the signal SIG with HANDLER.
1624 Otherwise, redirect the signal to the main thread, blocking it from
1625 this thread. POSIX says any thread can receive a signal that is
1626 associated with a process, process group, or asynchronous event.
1627 On GNU/Linux the main thread typically gets a process signal unless
1628 it's blocked, but other systems (FreeBSD at least) can deliver the
1629 signal to other threads. */
1631 deliver_process_signal (int sig
, signal_handler_t handler
)
1633 /* Preserve errno, to avoid race conditions with signal handlers that
1634 might change errno. Races can occur even in single-threaded hosts. */
1635 int old_errno
= errno
;
1637 bool on_main_thread
= true;
1638 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1639 if (! pthread_equal (pthread_self (), main_thread_id
))
1642 sigemptyset (&blocked
);
1643 sigaddset (&blocked
, sig
);
1644 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1645 pthread_kill (main_thread_id
, sig
);
1646 on_main_thread
= false;
1655 /* Static location to save a fatal backtrace in a thread.
1656 FIXME: If two subsidiary threads fail simultaneously, the resulting
1657 backtrace may be garbage. */
1658 enum { BACKTRACE_LIMIT_MAX
= 500 };
1659 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1660 static int thread_backtrace_npointers
;
1662 /* SIG has arrived at the current thread.
1663 If we are on the main thread, handle the signal SIG with HANDLER.
1664 Otherwise, this is a fatal error in the handling thread. */
1666 deliver_thread_signal (int sig
, signal_handler_t handler
)
1668 int old_errno
= errno
;
1670 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1671 if (! pthread_equal (pthread_self (), main_thread_id
))
1673 thread_backtrace_npointers
1674 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1675 sigaction (sig
, &process_fatal_action
, 0);
1676 pthread_kill (main_thread_id
, sig
);
1678 /* Avoid further damage while the main thread is exiting. */
1680 sigsuspend (&empty_mask
);
1688 #if !HAVE_DECL_SYS_SIGLIST
1690 # ifdef _sys_siglist
1691 # define sys_siglist _sys_siglist
1692 # elif HAVE_DECL___SYS_SIGLIST
1693 # define sys_siglist __sys_siglist
1695 # define sys_siglist my_sys_siglist
1696 static char const *sys_siglist
[NSIG
];
1701 # define sys_siglist_entries _sys_nsig
1703 # define sys_siglist_entries NSIG
1706 /* Handle bus errors, invalid instruction, etc. */
1708 handle_fatal_signal (int sig
)
1710 terminate_due_to_signal (sig
, 40);
1714 deliver_fatal_signal (int sig
)
1716 deliver_process_signal (sig
, handle_fatal_signal
);
1720 deliver_fatal_thread_signal (int sig
)
1722 deliver_thread_signal (sig
, handle_fatal_signal
);
1725 static _Noreturn
void
1726 handle_arith_signal (int sig
)
1728 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1729 xsignal0 (Qarith_error
);
1732 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1734 /* Alternate stack used by SIGSEGV handler below. */
1736 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1739 /* Return true if SIGINFO indicates a stack overflow. */
1742 stack_overflow (siginfo_t
*siginfo
)
1744 if (!attempt_stack_overflow_recovery
)
1747 /* In theory, a more-accurate heuristic can be obtained by using
1748 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1749 and pthread_attr_getguardsize to find the location and size of the
1750 guard area. In practice, though, these functions are so hard to
1751 use reliably that they're not worth bothering with. E.g., see:
1752 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1753 Other operating systems also have problems, e.g., Solaris's
1754 stack_violation function is tailor-made for this problem, but it
1755 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1757 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1763 /* The faulting address. */
1764 char *addr
= siginfo
->si_addr
;
1768 /* The known top and bottom of the stack. The actual stack may
1769 extend a bit beyond these boundaries. */
1770 char *bot
= stack_bottom
;
1771 char *top
= near_C_stack_top ();
1773 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1774 of the known stack divided by the size of the guard area past the
1775 end of the stack top. The heuristic is that a bad address is
1776 considered to be a stack overflow if it occurs within
1777 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1778 stack. This heuristic is not exactly correct but it's good
1779 enough in practice. */
1780 enum { LG_STACK_HEURISTIC
= 8 };
1783 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1785 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1789 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1792 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1794 /* Hard GC error may lead to stack overflow caused by
1795 too nested calls to mark_object. No way to survive. */
1796 bool fatal
= gc_in_progress
;
1798 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1799 if (!fatal
&& !pthread_equal (pthread_self (), main_thread_id
))
1803 if (!fatal
&& stack_overflow (siginfo
))
1804 siglongjmp (return_to_command_loop
, 1);
1806 /* Otherwise we can't do anything with this. */
1807 deliver_fatal_thread_signal (sig
);
1810 /* Return true if we have successfully set up SIGSEGV handler on alternate
1811 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1816 struct sigaction sa
;
1819 ss
.ss_sp
= sigsegv_stack
;
1820 ss
.ss_size
= sizeof (sigsegv_stack
);
1822 if (sigaltstack (&ss
, NULL
) < 0)
1825 sigfillset (&sa
.sa_mask
);
1826 sa
.sa_sigaction
= handle_sigsegv
;
1827 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1828 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1831 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1839 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1842 deliver_arith_signal (int sig
)
1844 deliver_thread_signal (sig
, handle_arith_signal
);
1849 /* Handler for SIGDANGER. */
1851 handle_danger_signal (int sig
)
1853 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1855 /* It might be unsafe to call do_auto_save now. */
1856 force_auto_save_soon ();
1860 deliver_danger_signal (int sig
)
1862 deliver_process_signal (sig
, handle_danger_signal
);
1866 /* Treat SIG as a terminating signal, unless it is already ignored and
1867 we are in --batch mode. Among other things, this makes nohup work. */
1869 maybe_fatal_sig (int sig
)
1871 bool catch_sig
= !noninteractive
;
1874 struct sigaction old_action
;
1875 sigaction (sig
, 0, &old_action
);
1876 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1879 sigaction (sig
, &process_fatal_action
, 0);
1883 init_signals (bool dumping
)
1885 struct sigaction thread_fatal_action
;
1886 struct sigaction action
;
1888 sigemptyset (&empty_mask
);
1890 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1891 main_thread_id
= pthread_self ();
1894 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1897 sys_siglist
[SIGABRT
] = "Aborted";
1899 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1901 sys_siglist
[SIGALRM
] = "Alarm clock";
1903 sys_siglist
[SIGBUS
] = "Bus error";
1906 sys_siglist
[SIGCHLD
] = "Child status changed";
1909 sys_siglist
[SIGCONT
] = "Continued";
1912 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1915 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1918 sys_siglist
[SIGEMT
] = "Emulation trap";
1920 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1922 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1925 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1927 sys_siglist
[SIGHUP
] = "Hangup";
1928 sys_siglist
[SIGILL
] = "Illegal instruction";
1929 sys_siglist
[SIGINT
] = "Interrupt";
1931 sys_siglist
[SIGIO
] = "I/O possible";
1934 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1937 sys_siglist
[SIGIOT
] = "IOT trap";
1939 sys_siglist
[SIGKILL
] = "Killed";
1941 sys_siglist
[SIGLOST
] = "Resource lost";
1944 sys_siglist
[SIGLWP
] = "SIGLWP";
1947 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1950 sys_siglist
[SIGWIND
] = "SIGPHONE";
1952 sys_siglist
[SIGPIPE
] = "Broken pipe";
1954 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1957 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1960 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1963 sys_siglist
[SIGPWR
] = "Power-fail restart";
1965 sys_siglist
[SIGQUIT
] = "Quit";
1967 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1970 sys_siglist
[SIGSAK
] = "Secure attention";
1972 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1974 sys_siglist
[SIGSOUND
] = "Sound completed";
1977 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1980 sys_siglist
[SIGSTP
] = "Stopped (user)";
1983 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1985 sys_siglist
[SIGTERM
] = "Terminated";
1987 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1990 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1993 sys_siglist
[SIGTSTP
] = "Stopped (user)";
1996 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
1999 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
2002 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2005 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2008 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2011 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2014 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2017 sys_siglist
[SIGWINCH
] = "Window size changed";
2020 sys_siglist
[SIGWIND
] = "SIGWIND";
2023 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2026 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2029 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2031 /* Don't alter signal handlers if dumping. On some machines,
2032 changing signal handlers sets static data that would make signals
2033 fail to work right when the dumped Emacs is run. */
2037 sigfillset (&process_fatal_action
.sa_mask
);
2038 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2039 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2041 sigfillset (&thread_fatal_action
.sa_mask
);
2042 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2043 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2045 /* SIGINT may need special treatment on MS-Windows. See
2046 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2047 Please update the doc of kill-emacs, kill-emacs-hook, and
2048 NEWS if you change this. */
2050 maybe_fatal_sig (SIGHUP
);
2051 maybe_fatal_sig (SIGINT
);
2052 maybe_fatal_sig (SIGTERM
);
2054 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2055 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2056 to behave more like typical batch applications do. */
2057 if (! noninteractive
)
2058 signal (SIGPIPE
, SIG_IGN
);
2060 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2061 sigaction (SIGILL
, &thread_fatal_action
, 0);
2062 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2064 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2065 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2066 interpreter's floating point operations, so treat SIGFPE as an
2067 arith-error if it arises in the main thread. */
2068 if (IEEE_FLOATING_POINT
)
2069 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2072 emacs_sigaction_init (&action
, deliver_arith_signal
);
2073 sigaction (SIGFPE
, &action
, 0);
2077 add_user_signal (SIGUSR1
, "sigusr1");
2080 add_user_signal (SIGUSR2
, "sigusr2");
2082 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2084 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2087 sigaction (SIGORE
, &thread_fatal_action
, 0);
2090 sigaction (SIGUME
, &thread_fatal_action
, 0);
2093 sigaction (SIGDLK
, &process_fatal_action
, 0);
2096 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2099 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2102 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2105 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2107 if (!init_sigsegv ())
2108 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2110 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2112 sigaction (SIGTERM
, &process_fatal_action
, 0);
2114 signal (SIGPROF
, SIG_IGN
);
2117 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2120 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2123 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2127 /* This just means available memory is getting low. */
2128 emacs_sigaction_init (&action
, deliver_danger_signal
);
2129 sigaction (SIGDANGER
, &action
, 0);
2132 /* AIX-specific signals. */
2134 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2137 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2140 sigaction (SIGMSG
, &process_fatal_action
, 0);
2143 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2146 sigaction (SIGSAK
, &process_fatal_action
, 0);
2149 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2152 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2162 /* Figure out how many bits the system's random number generator uses.
2163 `random' and `lrand48' are assumed to return 31 usable bits.
2164 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2165 so we'll shift it and treat it like the 15-bit USG `rand'. */
2169 # define RAND_BITS 31
2170 # else /* !HAVE_RANDOM */
2171 # ifdef HAVE_LRAND48
2172 # define RAND_BITS 31
2173 # define random lrand48
2174 # else /* !HAVE_LRAND48 */
2175 # define RAND_BITS 15
2176 # if RAND_MAX == 32767
2177 # define random rand
2178 # else /* RAND_MAX != 32767 */
2179 # if RAND_MAX == 2147483647
2180 # define random() (rand () >> 16)
2181 # else /* RAND_MAX != 2147483647 */
2183 # define random rand
2185 # define random() (rand () >> 16)
2187 # endif /* RAND_MAX != 2147483647 */
2188 # endif /* RAND_MAX != 32767 */
2189 # endif /* !HAVE_LRAND48 */
2190 # endif /* !HAVE_RANDOM */
2191 #endif /* !RAND_BITS */
2194 typedef unsigned int random_seed
;
2195 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2196 #elif defined HAVE_LRAND48
2197 /* Although srand48 uses a long seed, this is unsigned long to avoid
2198 undefined behavior on signed integer overflow in init_random. */
2199 typedef unsigned long int random_seed
;
2200 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2202 typedef unsigned int random_seed
;
2203 static void set_random_seed (random_seed arg
) { srand (arg
); }
2207 seed_random (void *seed
, ptrdiff_t seed_size
)
2209 random_seed arg
= 0;
2210 unsigned char *argp
= (unsigned char *) &arg
;
2211 unsigned char *seedp
= seed
;
2212 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2213 argp
[i
% sizeof arg
] ^= seedp
[i
];
2214 set_random_seed (arg
);
2221 bool success
= false;
2223 /* First, try seeding the PRNG from the operating system's entropy
2224 source. This approach is both fast and secure. */
2226 success
= w32_init_random (&v
, sizeof v
) == 0;
2228 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2231 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2236 /* If that didn't work, try using GnuTLS, which is secure, but on
2237 some systems, can be somewhat slow. */
2239 success
= EQ (emacs_gnutls_global_init (), Qt
)
2240 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2242 /* If _that_ didn't work, just use the current time value and PID.
2243 It's at least better than XKCD 221. */
2246 struct timespec t
= current_timespec ();
2247 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2250 set_random_seed (v
);
2254 * Return a nonnegative random integer out of whatever we've got.
2255 * It contains enough bits to make a random (signed) Emacs fixnum.
2256 * This suffices even for a 64-bit architecture with a 15-bit rand.
2263 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2264 val
= (random () ^ (val
<< RAND_BITS
)
2265 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2266 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2267 return val
& INTMASK
;
2270 #ifndef HAVE_SNPRINTF
2271 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2273 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2275 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2276 ptrdiff_t nbytes
= size
- 1;
2281 va_start (ap
, format
);
2282 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2286 if (nbytes
== size
- 1)
2288 /* Calculate the length of the string that would have been created
2289 had the buffer been large enough. */
2290 char stackbuf
[4000];
2292 ptrdiff_t bsize
= sizeof stackbuf
;
2293 va_start (ap
, format
);
2294 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2300 if (INT_MAX
< nbytes
)
2313 /* If a backtrace is available, output the top lines of it to stderr.
2314 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2315 This function may be called from a signal handler, so it should
2316 not invoke async-unsafe functions like malloc.
2318 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2319 but do not output anything. This avoids some problems that can
2320 otherwise occur if the malloc arena is corrupted before 'backtrace'
2321 is called, since 'backtrace' may call malloc if the tables are not
2324 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2325 fatal error has occurred in some other thread; generate a thread
2326 backtrace instead, ignoring BACKTRACE_LIMIT. */
2328 emacs_backtrace (int backtrace_limit
)
2330 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2331 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2335 if (thread_backtrace_npointers
)
2337 buffer
= thread_backtrace_buffer
;
2338 npointers
= thread_backtrace_npointers
;
2342 buffer
= main_backtrace_buffer
;
2344 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2345 if (bounded_limit
< 0)
2347 backtrace (buffer
, 1);
2351 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2356 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2357 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2358 if (bounded_limit
< npointers
)
2359 emacs_write (STDERR_FILENO
, "...\n", 4);
2367 terminate_due_to_signal (SIGABRT
, 40);
2371 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2372 Use binary I/O on systems that care about text vs binary I/O.
2373 Arrange for subprograms to not inherit the file descriptor.
2374 Prefer a method that is multithread-safe, if available.
2375 Do not fail merely because the open was interrupted by a signal.
2376 Allow the user to quit. */
2379 emacs_open (const char *file
, int oflags
, int mode
)
2382 if (! (oflags
& O_TEXT
))
2384 oflags
|= O_CLOEXEC
;
2385 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2387 if (! O_CLOEXEC
&& 0 <= fd
)
2388 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2392 /* Open FILE as a stream for Emacs use, with mode MODE.
2393 Act like emacs_open with respect to threads, signals, and quits. */
2396 emacs_fopen (char const *file
, char const *mode
)
2398 int fd
, omode
, oflags
;
2400 char const *m
= mode
;
2404 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2405 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2406 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2407 default: emacs_abort ();
2413 case '+': omode
= O_RDWR
; break;
2414 case 't': bflag
= O_TEXT
; break;
2415 default: /* Ignore. */ break;
2418 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2419 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2422 /* Create a pipe for Emacs use. */
2425 emacs_pipe (int fd
[2])
2430 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2431 if (! O_CLOEXEC
&& result
== 0)
2433 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2434 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2440 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2441 For the background behind this mess, please see Austin Group defect 529
2442 <http://austingroupbugs.net/view.php?id=529>. */
2444 #ifndef POSIX_CLOSE_RESTART
2445 # define POSIX_CLOSE_RESTART 1
2447 posix_close (int fd
, int flag
)
2449 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2450 eassert (flag
== POSIX_CLOSE_RESTART
);
2452 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2453 on a system that does not define POSIX_CLOSE_RESTART.
2455 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2456 closed, and retrying the close could inadvertently close a file
2457 descriptor allocated by some other thread. In other systems
2458 (e.g., HP/UX) FD is not closed. And in still other systems
2459 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2460 multithreaded program there can be no way to tell.
2462 So, in this case, pretend that the close succeeded. This works
2463 well on systems like GNU/Linux that close FD. Although it may
2464 leak a file descriptor on other systems, the leak is unlikely and
2465 it's better to leak than to close a random victim. */
2466 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2470 /* Close FD, retrying if interrupted. If successful, return 0;
2471 otherwise, return -1 and set errno to a non-EINTR value. Consider
2472 an EINPROGRESS error to be successful, as that's merely a signal
2473 arriving. FD is always closed when this function returns, even
2476 Do not call this function if FD is nonnegative and might already be closed,
2477 as that might close an innocent victim opened by some other thread. */
2480 emacs_close (int fd
)
2484 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2487 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2489 eassert (errno
!= EBADF
|| fd
< 0);
2490 return errno
== EINPROGRESS
? 0 : r
;
2495 /* Maximum number of bytes to read or write in a single system call.
2496 This works around a serious bug in Linux kernels before 2.6.16; see
2497 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2498 It's likely to work around similar bugs in other operating systems, so do it
2499 on all platforms. Round INT_MAX down to a page size, with the conservative
2500 assumption that page sizes are at most 2**18 bytes (any kernel with a
2501 page size larger than that shouldn't have the bug). */
2502 #ifndef MAX_RW_COUNT
2503 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2506 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2507 Return the number of bytes read, which might be less than NBYTE.
2508 On error, set errno and return -1. */
2510 emacs_read (int fildes
, void *buf
, ptrdiff_t nbyte
)
2514 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2515 passes a size that large to emacs_read. */
2517 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
2518 && (errno
== EINTR
))
2523 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2524 or if a partial write occurs. If interrupted, process pending
2525 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2526 errno if this is less than NBYTE. */
2528 emacs_full_write (int fildes
, char const *buf
, ptrdiff_t nbyte
,
2529 bool process_signals
)
2531 ptrdiff_t bytes_written
= 0;
2535 ssize_t n
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
2541 /* I originally used `QUIT' but that might cause files to
2542 be truncated if you hit C-g in the middle of it. --Stef */
2543 if (process_signals
&& pending_signals
)
2544 process_pending_signals ();
2556 return bytes_written
;
2559 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2560 interrupted or if a partial write occurs. Return the number of
2561 bytes written, setting errno if this is less than NBYTE. */
2563 emacs_write (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2565 return emacs_full_write (fildes
, buf
, nbyte
, 0);
2568 /* Like emacs_write, but also process pending signals if interrupted. */
2570 emacs_write_sig (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2572 return emacs_full_write (fildes
, buf
, nbyte
, 1);
2575 /* Write a diagnostic to standard error that contains MESSAGE and a
2576 string derived from errno. Preserve errno. Do not buffer stderr.
2577 Do not process pending signals if interrupted. */
2579 emacs_perror (char const *message
)
2582 char const *error_string
= emacs_strerror (err
);
2583 char const *command
= (initial_argv
&& initial_argv
[0]
2584 ? initial_argv
[0] : "emacs");
2585 /* Write it out all at once, if it's short; this is less likely to
2586 be interleaved with other output. */
2588 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2589 command
, message
, error_string
);
2590 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2591 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2594 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2595 emacs_write (STDERR_FILENO
, ": ", 2);
2596 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2597 emacs_write (STDERR_FILENO
, ": ", 2);
2598 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2599 emacs_write (STDERR_FILENO
, "\n", 1);
2604 /* Return a struct timeval that is roughly equivalent to T.
2605 Use the least timeval not less than T.
2606 Return an extremal value if the result would overflow. */
2608 make_timeval (struct timespec t
)
2611 tv
.tv_sec
= t
.tv_sec
;
2612 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2614 if (t
.tv_nsec
% 1000 != 0)
2616 if (tv
.tv_usec
< 999999)
2618 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2628 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2629 ATIME and MTIME, respectively.
2630 FD must be either negative -- in which case it is ignored --
2631 or a file descriptor that is open on FILE.
2632 If FD is nonnegative, then FILE can be NULL. */
2634 set_file_times (int fd
, const char *filename
,
2635 struct timespec atime
, struct timespec mtime
)
2637 struct timespec timespec
[2];
2638 timespec
[0] = atime
;
2639 timespec
[1] = mtime
;
2640 return fdutimens (fd
, filename
, timespec
);
2643 /* Like strsignal, except async-signal-safe, and this function typically
2644 returns a string in the C locale rather than the current locale. */
2646 safe_strsignal (int code
)
2648 char const *signame
= 0;
2650 if (0 <= code
&& code
< sys_siglist_entries
)
2651 signame
= sys_siglist
[code
];
2653 signame
= "Unknown signal";
2659 /* For make-serial-process */
2661 serial_open (Lisp_Object port
)
2663 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2665 report_file_error ("Opening serial port", port
);
2667 ioctl (fd
, TIOCEXCL
, (char *) 0);
2673 #if !defined (HAVE_CFMAKERAW)
2674 /* Workaround for targets which are missing cfmakeraw. */
2675 /* Pasted from man page. */
2677 cfmakeraw (struct termios
*termios_p
)
2679 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2680 termios_p
->c_oflag
&= ~OPOST
;
2681 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2682 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2683 termios_p
->c_cflag
|= CS8
;
2685 #endif /* !defined (HAVE_CFMAKERAW */
2687 #if !defined (HAVE_CFSETSPEED)
2688 /* Workaround for targets which are missing cfsetspeed. */
2690 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2692 return (cfsetispeed (termios_p
, vitesse
)
2693 + cfsetospeed (termios_p
, vitesse
));
2697 /* For serial-process-configure */
2699 serial_configure (struct Lisp_Process
*p
,
2700 Lisp_Object contact
)
2702 Lisp_Object childp2
= Qnil
;
2703 Lisp_Object tem
= Qnil
;
2704 struct termios attr
;
2706 char summary
[4] = "???"; /* This usually becomes "8N1". */
2708 childp2
= Fcopy_sequence (p
->childp
);
2710 /* Read port attributes and prepare default configuration. */
2711 err
= tcgetattr (p
->outfd
, &attr
);
2713 report_file_error ("Failed tcgetattr", Qnil
);
2715 #if defined (CLOCAL)
2716 attr
.c_cflag
|= CLOCAL
;
2719 attr
.c_cflag
|= CREAD
;
2722 /* Configure speed. */
2723 if (!NILP (Fplist_member (contact
, QCspeed
)))
2724 tem
= Fplist_get (contact
, QCspeed
);
2726 tem
= Fplist_get (p
->childp
, QCspeed
);
2728 err
= cfsetspeed (&attr
, XINT (tem
));
2730 report_file_error ("Failed cfsetspeed", tem
);
2731 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2733 /* Configure bytesize. */
2734 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2735 tem
= Fplist_get (contact
, QCbytesize
);
2737 tem
= Fplist_get (p
->childp
, QCbytesize
);
2739 tem
= make_number (8);
2741 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2742 error (":bytesize must be nil (8), 7, or 8");
2743 summary
[0] = XINT (tem
) + '0';
2744 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2745 attr
.c_cflag
&= ~CSIZE
;
2746 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2748 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2749 if (XINT (tem
) != 8)
2750 error ("Bytesize cannot be changed");
2752 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2754 /* Configure parity. */
2755 if (!NILP (Fplist_member (contact
, QCparity
)))
2756 tem
= Fplist_get (contact
, QCparity
);
2758 tem
= Fplist_get (p
->childp
, QCparity
);
2759 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2760 error (":parity must be nil (no parity), `even', or `odd'");
2761 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2762 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2763 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2768 else if (EQ (tem
, Qeven
))
2771 attr
.c_cflag
|= PARENB
;
2772 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2774 else if (EQ (tem
, Qodd
))
2777 attr
.c_cflag
|= (PARENB
| PARODD
);
2778 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2781 /* Don't error on no parity, which should be set by cfmakeraw. */
2783 error ("Parity cannot be configured");
2785 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2787 /* Configure stopbits. */
2788 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2789 tem
= Fplist_get (contact
, QCstopbits
);
2791 tem
= Fplist_get (p
->childp
, QCstopbits
);
2793 tem
= make_number (1);
2795 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2796 error (":stopbits must be nil (1 stopbit), 1, or 2");
2797 summary
[2] = XINT (tem
) + '0';
2798 #if defined (CSTOPB)
2799 attr
.c_cflag
&= ~CSTOPB
;
2800 if (XINT (tem
) == 2)
2801 attr
.c_cflag
|= CSTOPB
;
2803 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2804 if (XINT (tem
) != 1)
2805 error ("Stopbits cannot be configured");
2807 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2809 /* Configure flowcontrol. */
2810 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2811 tem
= Fplist_get (contact
, QCflowcontrol
);
2813 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2814 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2815 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2816 #if defined (CRTSCTS)
2817 attr
.c_cflag
&= ~CRTSCTS
;
2819 #if defined (CNEW_RTSCTS)
2820 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2822 #if defined (IXON) && defined (IXOFF)
2823 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2827 /* Already configured. */
2829 else if (EQ (tem
, Qhw
))
2831 #if defined (CRTSCTS)
2832 attr
.c_cflag
|= CRTSCTS
;
2833 #elif defined (CNEW_RTSCTS)
2834 attr
.c_cflag
|= CNEW_RTSCTS
;
2836 error ("Hardware flowcontrol (RTS/CTS) not supported");
2839 else if (EQ (tem
, Qsw
))
2841 #if defined (IXON) && defined (IXOFF)
2842 attr
.c_iflag
|= (IXON
| IXOFF
);
2844 error ("Software flowcontrol (XON/XOFF) not supported");
2847 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2849 /* Activate configuration. */
2850 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2852 report_file_error ("Failed tcsetattr", Qnil
);
2854 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2855 pset_childp (p
, childp2
);
2857 #endif /* not DOS_NT */
2859 /* System depended enumeration of and access to system processes a-la ps(1). */
2863 /* Process enumeration and access via /proc. */
2866 list_system_processes (void)
2868 Lisp_Object procdir
, match
, proclist
, next
;
2871 /* For every process on the system, there's a directory in the
2872 "/proc" pseudo-directory whose name is the numeric ID of that
2874 procdir
= build_string ("/proc");
2875 match
= build_string ("[0-9]+");
2876 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2878 /* `proclist' gives process IDs as strings. Destructively convert
2879 each string into a number. */
2880 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2883 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2886 /* directory_files_internal returns the files in reverse order; undo
2888 proclist
= Fnreverse (proclist
);
2892 #elif defined DARWIN_OS || defined __FreeBSD__
2895 list_system_processes (void)
2898 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2900 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2903 struct kinfo_proc
*procs
;
2906 Lisp_Object proclist
= Qnil
;
2908 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2911 procs
= xmalloc (len
);
2912 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2918 len
/= sizeof (struct kinfo_proc
);
2919 for (i
= 0; i
< len
; i
++)
2922 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2924 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2933 /* The WINDOWSNT implementation is in w32.c.
2934 The MSDOS implementation is in dosfns.c. */
2935 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2938 list_system_processes (void)
2943 #endif /* !defined (WINDOWSNT) */
2945 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2946 static struct timespec
2947 time_from_jiffies (unsigned long long tval
, long hz
)
2949 unsigned long long s
= tval
/ hz
;
2950 unsigned long long frac
= tval
% hz
;
2953 if (TYPE_MAXIMUM (time_t) < s
)
2955 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2956 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2957 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2960 /* This is reachable only in the unlikely case that HZ * HZ
2961 exceeds ULLONG_MAX. It calculates an approximation that is
2962 guaranteed to be in range. */
2963 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
2964 + (hz
% TIMESPEC_RESOLUTION
!= 0));
2965 ns
= frac
/ hz_per_ns
;
2968 return make_timespec (s
, ns
);
2972 ltime_from_jiffies (unsigned long long tval
, long hz
)
2974 struct timespec t
= time_from_jiffies (tval
, hz
);
2975 return make_lisp_time (t
);
2978 static struct timespec
2982 struct timespec up
= make_timespec (0, 0);
2985 fup
= emacs_fopen ("/proc/uptime", "r");
2989 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
2990 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
2992 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
2993 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
2994 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
2997 if (TYPE_MAXIMUM (time_t) < upsec
)
2999 upsec
= TYPE_MAXIMUM (time_t);
3000 upfrac
= TIMESPEC_RESOLUTION
- 1;
3004 int upfraclen
= upfrac_end
- upfrac_start
;
3005 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3007 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3009 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3011 up
= make_timespec (upsec
, upfrac
);
3020 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3021 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3024 procfs_ttyname (int rdev
)
3027 char name
[PATH_MAX
];
3030 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3036 unsigned long minor_beg
, minor_end
;
3037 char minor
[25]; /* 2 32-bit numbers + dash */
3040 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3042 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3043 && major
== MAJOR (rdev
))
3045 minor_beg
= strtoul (minor
, &endp
, 0);
3047 minor_end
= minor_beg
;
3048 else if (*endp
== '-')
3049 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3053 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3055 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3063 return build_string (name
);
3067 procfs_get_total_memory (void)
3070 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3074 fmem
= emacs_fopen ("/proc/meminfo", "r");
3078 uintmax_t entry_value
;
3082 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3085 retval
= entry_value
;
3090 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3108 system_process_attributes (Lisp_Object pid
)
3110 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3114 long clocks_per_sec
;
3116 char procbuf
[1025], *p
, *q
;
3119 static char const default_cmd
[] = "???";
3120 const char *cmd
= default_cmd
;
3121 int cmdsize
= sizeof default_cmd
- 1;
3122 char *cmdline
= NULL
;
3123 ptrdiff_t cmdline_size
;
3126 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3129 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3130 long priority
, niceness
, rss
;
3131 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3132 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3134 Lisp_Object attrs
= Qnil
;
3135 Lisp_Object decoded_cmd
;
3138 CHECK_NUMBER_OR_FLOAT (pid
);
3139 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3140 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3141 if (stat (procfn
, &st
) < 0)
3146 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3148 pw
= getpwuid (uid
);
3151 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3154 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3156 gr
= getgrgid (gid
);
3159 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3161 count
= SPECPDL_INDEX ();
3162 strcpy (fn
, procfn
);
3163 procfn_end
= fn
+ strlen (fn
);
3164 strcpy (procfn_end
, "/stat");
3165 fd
= emacs_open (fn
, O_RDONLY
, 0);
3170 record_unwind_protect_int (close_file_unwind
, fd
);
3171 nread
= emacs_read (fd
, procbuf
, sizeof procbuf
- 1);
3175 procbuf
[nread
] = '\0';
3178 p
= strchr (p
, '(');
3181 q
= strrchr (p
+ 1, ')');
3191 /* Command name is encoded in locale-coding-system; decode it. */
3192 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3193 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3194 Vlocale_coding_system
, 0);
3195 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3197 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3198 utime stime cutime cstime priority nice thcount . start vsize rss */
3200 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3201 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3202 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3203 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3204 &u_time
, &s_time
, &cutime
, &cstime
,
3205 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3210 state_str
[1] = '\0';
3211 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3212 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3213 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3214 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3215 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3216 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3217 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3218 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3219 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3221 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3223 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3224 if (clocks_per_sec
< 0)
3225 clocks_per_sec
= 100;
3226 attrs
= Fcons (Fcons (Qutime
,
3227 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3229 attrs
= Fcons (Fcons (Qstime
,
3230 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3232 attrs
= Fcons (Fcons (Qtime
,
3233 ltime_from_jiffies (s_time
+ u_time
,
3236 attrs
= Fcons (Fcons (Qcutime
,
3237 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3239 attrs
= Fcons (Fcons (Qcstime
,
3240 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3242 attrs
= Fcons (Fcons (Qctime
,
3243 ltime_from_jiffies (cstime
+ cutime
,
3246 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3247 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3248 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3250 tnow
= current_timespec ();
3251 telapsed
= get_up_time ();
3252 tboot
= timespec_sub (tnow
, telapsed
);
3253 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3254 tstart
= timespec_add (tboot
, tstart
);
3255 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3256 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3258 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3259 telapsed
= timespec_sub (tnow
, tstart
);
3260 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3261 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3262 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3265 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3266 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3269 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3272 unbind_to (count
, Qnil
);
3275 strcpy (procfn_end
, "/cmdline");
3276 fd
= emacs_open (fn
, O_RDONLY
, 0);
3279 ptrdiff_t readsize
, nread_incr
;
3280 record_unwind_protect_int (close_file_unwind
, fd
);
3281 record_unwind_protect_nothing ();
3282 nread
= cmdline_size
= 0;
3286 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3287 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3289 /* Leave room even if every byte needs escaping below. */
3290 readsize
= (cmdline_size
>> 1) - nread
;
3292 nread_incr
= emacs_read (fd
, cmdline
+ nread
, readsize
);
3293 nread
+= max (0, nread_incr
);
3295 while (nread_incr
== readsize
);
3299 /* We don't want trailing null characters. */
3300 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3303 /* Escape-quote whitespace and backslashes. */
3304 q
= cmdline
+ cmdline_size
;
3309 if (c_isspace (c
) || c
== '\\')
3313 nread
= cmdline
+ cmdline_size
- q
;
3318 nread
= cmdsize
+ 2;
3319 cmdline_size
= nread
+ 1;
3320 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3321 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3322 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3324 /* Command line is encoded in locale-coding-system; decode it. */
3325 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3326 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3327 Vlocale_coding_system
, 0);
3328 unbind_to (count
, Qnil
);
3329 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3335 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3337 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3338 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3339 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3340 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3341 #undef _FILE_OFFSET_BITS
3343 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3348 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3349 #define _FILE_OFFSET_BITS 64
3350 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3352 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3355 system_process_attributes (Lisp_Object pid
)
3357 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3362 struct psinfo pinfo
;
3368 Lisp_Object attrs
= Qnil
;
3369 Lisp_Object decoded_cmd
;
3372 CHECK_NUMBER_OR_FLOAT (pid
);
3373 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3374 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3375 if (stat (procfn
, &st
) < 0)
3380 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3382 pw
= getpwuid (uid
);
3385 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3388 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3390 gr
= getgrgid (gid
);
3393 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3395 count
= SPECPDL_INDEX ();
3396 strcpy (fn
, procfn
);
3397 procfn_end
= fn
+ strlen (fn
);
3398 strcpy (procfn_end
, "/psinfo");
3399 fd
= emacs_open (fn
, O_RDONLY
, 0);
3404 record_unwind_protect_int (close_file_unwind
, fd
);
3405 nread
= emacs_read (fd
, &pinfo
, sizeof pinfo
);
3408 if (nread
== sizeof pinfo
)
3410 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3411 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3412 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3416 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3417 state_str
[1] = '\0';
3418 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3421 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3422 need to get a string from it. */
3424 /* FIXME: missing: Qtpgid */
3436 Are they available? */
3438 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3439 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3440 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3441 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3442 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3445 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3446 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3448 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3451 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3452 range 0 .. 2**15, representing 0.0 .. 1.0. */
3453 attrs
= Fcons (Fcons (Qpcpu
,
3454 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3456 attrs
= Fcons (Fcons (Qpmem
,
3457 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3460 AUTO_STRING (fname
, pinfo
.pr_fname
);
3461 decoded_cmd
= code_convert_string_norecord (fname
,
3462 Vlocale_coding_system
, 0);
3463 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3464 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3465 decoded_cmd
= code_convert_string_norecord (psargs
,
3466 Vlocale_coding_system
, 0);
3467 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3469 unbind_to (count
, Qnil
);
3473 #elif defined __FreeBSD__
3475 static struct timespec
3476 timeval_to_timespec (struct timeval t
)
3478 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3482 make_lisp_timeval (struct timeval t
)
3484 return make_lisp_time (timeval_to_timespec (t
));
3488 system_process_attributes (Lisp_Object pid
)
3491 int pagesize
= getpagesize ();
3492 unsigned long npages
;
3498 char args
[MAXPATHLEN
];
3499 struct timespec t
, now
;
3501 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3502 struct kinfo_proc proc
;
3503 size_t proclen
= sizeof proc
;
3505 Lisp_Object attrs
= Qnil
;
3506 Lisp_Object decoded_comm
;
3508 CHECK_NUMBER_OR_FLOAT (pid
);
3509 CONS_TO_INTEGER (pid
, int, proc_id
);
3512 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3515 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3518 pw
= getpwuid (proc
.ki_uid
);
3521 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3523 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3526 gr
= getgrgid (proc
.ki_svgid
);
3529 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3531 AUTO_STRING (comm
, proc
.ki_comm
);
3532 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3534 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3536 char state
[2] = {'\0', '\0'};
3537 switch (proc
.ki_stat
)
3559 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3562 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3563 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3564 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3567 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3570 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3572 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3573 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3574 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3575 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3576 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3578 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3580 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3582 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3583 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3584 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3586 attrs
= Fcons (Fcons (Qcutime
,
3587 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3589 attrs
= Fcons (Fcons (Qcstime
,
3590 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3592 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3593 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3594 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3596 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3598 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3599 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3600 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3601 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3602 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3605 now
= current_timespec ();
3606 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3607 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3609 len
= sizeof fscale
;
3610 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3615 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3617 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3618 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3619 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3623 len
= sizeof npages
;
3624 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3626 double pmem
= (proc
.ki_flag
& P_INMEM
3627 ? 100.0 * proc
.ki_rssize
/ npages
3629 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3632 mib
[2] = KERN_PROC_ARGS
;
3634 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3637 for (i
= 0; i
< len
; i
++)
3639 if (! args
[i
] && i
< len
- 1)
3643 AUTO_STRING (comm
, args
);
3644 decoded_comm
= code_convert_string_norecord (comm
,
3645 Vlocale_coding_system
, 0);
3647 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3653 #elif defined DARWIN_OS
3655 static struct timespec
3656 timeval_to_timespec (struct timeval t
)
3658 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3662 make_lisp_timeval (struct timeval t
)
3664 return make_lisp_time (timeval_to_timespec (t
));
3668 system_process_attributes (Lisp_Object pid
)
3671 int pagesize
= getpagesize ();
3672 unsigned long npages
;
3678 char args
[MAXPATHLEN
];
3679 struct timeval starttime
;
3680 struct timespec t
, now
;
3681 struct rusage
*rusage
;
3686 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3687 struct kinfo_proc proc
;
3688 size_t proclen
= sizeof proc
;
3690 Lisp_Object attrs
= Qnil
;
3691 Lisp_Object decoded_comm
;
3693 CHECK_NUMBER_OR_FLOAT (pid
);
3694 CONS_TO_INTEGER (pid
, int, proc_id
);
3697 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3700 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3701 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3704 pw
= getpwuid (uid
);
3707 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3709 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3710 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3713 gr
= getgrgid (gid
);
3716 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3718 decoded_comm
= (code_convert_string_norecord
3719 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3720 Vlocale_coding_system
, 0));
3722 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3724 char state
[2] = {'\0', '\0'};
3725 switch (proc
.kp_proc
.p_stat
)
3747 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3750 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3752 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3755 tdev
= proc
.kp_eproc
.e_tdev
;
3757 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3760 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3762 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3765 rusage
= proc
.kp_proc
.p_ru
;
3768 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3770 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3773 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3775 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3777 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3778 timeval_to_timespec (rusage
->ru_stime
));
3779 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3782 starttime
= proc
.kp_proc
.p_starttime
;
3783 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3784 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3786 now
= current_timespec ();
3787 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3788 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3793 /* The WINDOWSNT implementation is in w32.c.
3794 The MSDOS implementation is in dosfns.c. */
3795 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3798 system_process_attributes (Lisp_Object pid
)
3803 #endif /* !defined (WINDOWSNT) */
3805 /* Wide character string collation. */
3807 #ifdef __STDC_ISO_10646__
3809 # include <wctype.h>
3811 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3812 # include <locale.h>
3815 # define LC_COLLATE 0
3817 # ifndef LC_COLLATE_MASK
3818 # define LC_COLLATE_MASK 0
3823 # ifndef LC_CTYPE_MASK
3824 # define LC_CTYPE_MASK 0
3827 # ifndef HAVE_NEWLOCALE
3833 # define freelocale emacs_freelocale
3834 # define locale_t emacs_locale_t
3835 # define newlocale emacs_newlocale
3836 # define wcscoll_l emacs_wcscoll_l
3837 # define towlower_l emacs_towlower_l
3839 typedef char const *locale_t
;
3842 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3848 freelocale (locale_t loc
)
3853 emacs_setlocale (int category
, char const *locale
)
3855 # ifdef HAVE_SETLOCALE
3857 char *loc
= setlocale (category
, locale
);
3868 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3871 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3879 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3880 strcpy (oldcopy
, oldloc
);
3881 if (! emacs_setlocale (LC_COLLATE
, loc
))
3886 result
= wcscoll (a
, b
);
3888 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3899 towlower_l (wint_t wc
, locale_t loc
)
3902 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3907 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3908 strcpy (oldcopy
, oldloc
);
3909 if (emacs_setlocale (LC_CTYPE
, loc
))
3911 result
= towlower (wc
);
3912 emacs_setlocale (LC_COLLATE
, oldcopy
);
3922 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3923 Lisp_Object locale
, Lisp_Object ignore_case
)
3926 ptrdiff_t len
, i
, i_byte
;
3931 /* Convert byte stream to code points. */
3932 len
= SCHARS (s1
); i
= i_byte
= 0;
3933 SAFE_NALLOCA (p1
, 1, len
+ 1);
3935 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3938 len
= SCHARS (s2
); i
= i_byte
= 0;
3939 SAFE_NALLOCA (p2
, 1, len
+ 1);
3941 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3944 if (STRINGP (locale
))
3946 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3947 SSDATA (locale
), 0);
3949 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3951 if (! NILP (ignore_case
))
3952 for (int i
= 1; i
< 3; i
++)
3954 wchar_t *p
= (i
== 1) ? p1
: p2
;
3956 *p
= towlower_l (*p
, loc
);
3960 res
= wcscoll_l (p1
, p2
, loc
);
3966 if (! NILP (ignore_case
))
3967 for (int i
= 1; i
< 3; i
++)
3969 wchar_t *p
= (i
== 1) ? p1
: p2
;
3975 res
= wcscoll (p1
, p2
);
3978 # ifndef HAVE_NEWLOCALE
3980 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
3983 error ("Invalid string for collation: %s", emacs_strerror (err
));
3989 #endif /* __STDC_ISO_10646__ */
3993 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3994 Lisp_Object locale
, Lisp_Object ignore_case
)
3997 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
3998 int res
, err
= errno
;
4001 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4003 error ("Invalid string for collation: %s", strerror (errno
));
4008 #endif /* WINDOWSNT */