1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2016 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 static pthread_t main_thread
;
1618 /* SIG has arrived at the current process. Deliver it to the main
1619 thread, which should handle it with HANDLER.
1621 If we are on the main thread, handle the signal SIG with HANDLER.
1622 Otherwise, redirect the signal to the main thread, blocking it from
1623 this thread. POSIX says any thread can receive a signal that is
1624 associated with a process, process group, or asynchronous event.
1625 On GNU/Linux that is not true, but for other systems (FreeBSD at
1628 deliver_process_signal (int sig
, signal_handler_t handler
)
1630 /* Preserve errno, to avoid race conditions with signal handlers that
1631 might change errno. Races can occur even in single-threaded hosts. */
1632 int old_errno
= errno
;
1634 bool on_main_thread
= true;
1635 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1636 if (! pthread_equal (pthread_self (), main_thread
))
1639 sigemptyset (&blocked
);
1640 sigaddset (&blocked
, sig
);
1641 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1642 pthread_kill (main_thread
, sig
);
1643 on_main_thread
= false;
1652 /* Static location to save a fatal backtrace in a thread.
1653 FIXME: If two subsidiary threads fail simultaneously, the resulting
1654 backtrace may be garbage. */
1655 enum { BACKTRACE_LIMIT_MAX
= 500 };
1656 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1657 static int thread_backtrace_npointers
;
1659 /* SIG has arrived at the current thread.
1660 If we are on the main thread, handle the signal SIG with HANDLER.
1661 Otherwise, this is a fatal error in the handling thread. */
1663 deliver_thread_signal (int sig
, signal_handler_t handler
)
1665 int old_errno
= errno
;
1667 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1668 if (! pthread_equal (pthread_self (), main_thread
))
1670 thread_backtrace_npointers
1671 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1672 sigaction (sig
, &process_fatal_action
, 0);
1673 pthread_kill (main_thread
, sig
);
1675 /* Avoid further damage while the main thread is exiting. */
1677 sigsuspend (&empty_mask
);
1685 #if !HAVE_DECL_SYS_SIGLIST
1687 # ifdef _sys_siglist
1688 # define sys_siglist _sys_siglist
1689 # elif HAVE_DECL___SYS_SIGLIST
1690 # define sys_siglist __sys_siglist
1692 # define sys_siglist my_sys_siglist
1693 static char const *sys_siglist
[NSIG
];
1698 # define sys_siglist_entries _sys_nsig
1700 # define sys_siglist_entries NSIG
1703 /* Handle bus errors, invalid instruction, etc. */
1705 handle_fatal_signal (int sig
)
1707 terminate_due_to_signal (sig
, 40);
1711 deliver_fatal_signal (int sig
)
1713 deliver_process_signal (sig
, handle_fatal_signal
);
1717 deliver_fatal_thread_signal (int sig
)
1719 deliver_thread_signal (sig
, handle_fatal_signal
);
1722 static _Noreturn
void
1723 handle_arith_signal (int sig
)
1725 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1726 xsignal0 (Qarith_error
);
1729 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1731 /* Alternate stack used by SIGSEGV handler below. */
1733 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1736 /* Return true if SIGINFO indicates a stack overflow. */
1739 stack_overflow (siginfo_t
*siginfo
)
1741 if (!attempt_stack_overflow_recovery
)
1744 /* In theory, a more-accurate heuristic can be obtained by using
1745 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1746 and pthread_attr_getguardsize to find the location and size of the
1747 guard area. In practice, though, these functions are so hard to
1748 use reliably that they're not worth bothering with. E.g., see:
1749 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1750 Other operating systems also have problems, e.g., Solaris's
1751 stack_violation function is tailor-made for this problem, but it
1752 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1754 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1760 /* The faulting address. */
1761 char *addr
= siginfo
->si_addr
;
1765 /* The known top and bottom of the stack. The actual stack may
1766 extend a bit beyond these boundaries. */
1767 char *bot
= stack_bottom
;
1768 char *top
= near_C_stack_top ();
1770 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1771 of the known stack divided by the size of the guard area past the
1772 end of the stack top. The heuristic is that a bad address is
1773 considered to be a stack overflow if it occurs within
1774 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1775 stack. This heuristic is not exactly correct but it's good
1776 enough in practice. */
1777 enum { LG_STACK_HEURISTIC
= 8 };
1780 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1782 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1786 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1789 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1791 /* Hard GC error may lead to stack overflow caused by
1792 too nested calls to mark_object. No way to survive. */
1793 bool fatal
= gc_in_progress
;
1795 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1796 if (!fatal
&& !pthread_equal (pthread_self (), main_thread
))
1800 if (!fatal
&& stack_overflow (siginfo
))
1801 siglongjmp (return_to_command_loop
, 1);
1803 /* Otherwise we can't do anything with this. */
1804 deliver_fatal_thread_signal (sig
);
1807 /* Return true if we have successfully set up SIGSEGV handler on alternate
1808 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1813 struct sigaction sa
;
1816 ss
.ss_sp
= sigsegv_stack
;
1817 ss
.ss_size
= sizeof (sigsegv_stack
);
1819 if (sigaltstack (&ss
, NULL
) < 0)
1822 sigfillset (&sa
.sa_mask
);
1823 sa
.sa_sigaction
= handle_sigsegv
;
1824 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1825 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1828 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1836 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1839 deliver_arith_signal (int sig
)
1841 deliver_thread_signal (sig
, handle_arith_signal
);
1846 /* Handler for SIGDANGER. */
1848 handle_danger_signal (int sig
)
1850 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1852 /* It might be unsafe to call do_auto_save now. */
1853 force_auto_save_soon ();
1857 deliver_danger_signal (int sig
)
1859 deliver_process_signal (sig
, handle_danger_signal
);
1863 /* Treat SIG as a terminating signal, unless it is already ignored and
1864 we are in --batch mode. Among other things, this makes nohup work. */
1866 maybe_fatal_sig (int sig
)
1868 bool catch_sig
= !noninteractive
;
1871 struct sigaction old_action
;
1872 sigaction (sig
, 0, &old_action
);
1873 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1876 sigaction (sig
, &process_fatal_action
, 0);
1880 init_signals (bool dumping
)
1882 struct sigaction thread_fatal_action
;
1883 struct sigaction action
;
1885 sigemptyset (&empty_mask
);
1887 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1888 main_thread
= pthread_self ();
1891 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1894 sys_siglist
[SIGABRT
] = "Aborted";
1896 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1898 sys_siglist
[SIGALRM
] = "Alarm clock";
1900 sys_siglist
[SIGBUS
] = "Bus error";
1903 sys_siglist
[SIGCHLD
] = "Child status changed";
1906 sys_siglist
[SIGCONT
] = "Continued";
1909 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1912 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1915 sys_siglist
[SIGEMT
] = "Emulation trap";
1917 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1919 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1922 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1924 sys_siglist
[SIGHUP
] = "Hangup";
1925 sys_siglist
[SIGILL
] = "Illegal instruction";
1926 sys_siglist
[SIGINT
] = "Interrupt";
1928 sys_siglist
[SIGIO
] = "I/O possible";
1931 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1934 sys_siglist
[SIGIOT
] = "IOT trap";
1936 sys_siglist
[SIGKILL
] = "Killed";
1938 sys_siglist
[SIGLOST
] = "Resource lost";
1941 sys_siglist
[SIGLWP
] = "SIGLWP";
1944 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1947 sys_siglist
[SIGWIND
] = "SIGPHONE";
1949 sys_siglist
[SIGPIPE
] = "Broken pipe";
1951 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1954 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1957 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1960 sys_siglist
[SIGPWR
] = "Power-fail restart";
1962 sys_siglist
[SIGQUIT
] = "Quit";
1964 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1967 sys_siglist
[SIGSAK
] = "Secure attention";
1969 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1971 sys_siglist
[SIGSOUND
] = "Sound completed";
1974 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1977 sys_siglist
[SIGSTP
] = "Stopped (user)";
1980 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1982 sys_siglist
[SIGTERM
] = "Terminated";
1984 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1987 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1990 sys_siglist
[SIGTSTP
] = "Stopped (user)";
1993 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
1996 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
1999 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2002 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2005 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2008 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2011 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2014 sys_siglist
[SIGWINCH
] = "Window size changed";
2017 sys_siglist
[SIGWIND
] = "SIGWIND";
2020 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2023 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2026 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2028 /* Don't alter signal handlers if dumping. On some machines,
2029 changing signal handlers sets static data that would make signals
2030 fail to work right when the dumped Emacs is run. */
2034 sigfillset (&process_fatal_action
.sa_mask
);
2035 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2036 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2038 sigfillset (&thread_fatal_action
.sa_mask
);
2039 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2040 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2042 /* SIGINT may need special treatment on MS-Windows. See
2043 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2044 Please update the doc of kill-emacs, kill-emacs-hook, and
2045 NEWS if you change this. */
2047 maybe_fatal_sig (SIGHUP
);
2048 maybe_fatal_sig (SIGINT
);
2049 maybe_fatal_sig (SIGTERM
);
2051 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2052 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2053 to behave more like typical batch applications do. */
2054 if (! noninteractive
)
2055 signal (SIGPIPE
, SIG_IGN
);
2057 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2058 sigaction (SIGILL
, &thread_fatal_action
, 0);
2059 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2061 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2062 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2063 interpreter's floating point operations, so treat SIGFPE as an
2064 arith-error if it arises in the main thread. */
2065 if (IEEE_FLOATING_POINT
)
2066 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2069 emacs_sigaction_init (&action
, deliver_arith_signal
);
2070 sigaction (SIGFPE
, &action
, 0);
2074 add_user_signal (SIGUSR1
, "sigusr1");
2077 add_user_signal (SIGUSR2
, "sigusr2");
2079 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2081 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2084 sigaction (SIGORE
, &thread_fatal_action
, 0);
2087 sigaction (SIGUME
, &thread_fatal_action
, 0);
2090 sigaction (SIGDLK
, &process_fatal_action
, 0);
2093 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2096 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2099 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2102 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2104 if (!init_sigsegv ())
2105 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2107 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2109 sigaction (SIGTERM
, &process_fatal_action
, 0);
2111 signal (SIGPROF
, SIG_IGN
);
2114 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2117 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2120 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2124 /* This just means available memory is getting low. */
2125 emacs_sigaction_init (&action
, deliver_danger_signal
);
2126 sigaction (SIGDANGER
, &action
, 0);
2129 /* AIX-specific signals. */
2131 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2134 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2137 sigaction (SIGMSG
, &process_fatal_action
, 0);
2140 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2143 sigaction (SIGSAK
, &process_fatal_action
, 0);
2146 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2149 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2159 /* Figure out how many bits the system's random number generator uses.
2160 `random' and `lrand48' are assumed to return 31 usable bits.
2161 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2162 so we'll shift it and treat it like the 15-bit USG `rand'. */
2166 # define RAND_BITS 31
2167 # else /* !HAVE_RANDOM */
2168 # ifdef HAVE_LRAND48
2169 # define RAND_BITS 31
2170 # define random lrand48
2171 # else /* !HAVE_LRAND48 */
2172 # define RAND_BITS 15
2173 # if RAND_MAX == 32767
2174 # define random rand
2175 # else /* RAND_MAX != 32767 */
2176 # if RAND_MAX == 2147483647
2177 # define random() (rand () >> 16)
2178 # else /* RAND_MAX != 2147483647 */
2180 # define random rand
2182 # define random() (rand () >> 16)
2184 # endif /* RAND_MAX != 2147483647 */
2185 # endif /* RAND_MAX != 32767 */
2186 # endif /* !HAVE_LRAND48 */
2187 # endif /* !HAVE_RANDOM */
2188 #endif /* !RAND_BITS */
2191 typedef unsigned int random_seed
;
2192 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2193 #elif defined HAVE_LRAND48
2194 /* Although srand48 uses a long seed, this is unsigned long to avoid
2195 undefined behavior on signed integer overflow in init_random. */
2196 typedef unsigned long int random_seed
;
2197 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2199 typedef unsigned int random_seed
;
2200 static void set_random_seed (random_seed arg
) { srand (arg
); }
2204 seed_random (void *seed
, ptrdiff_t seed_size
)
2206 random_seed arg
= 0;
2207 unsigned char *argp
= (unsigned char *) &arg
;
2208 unsigned char *seedp
= seed
;
2209 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2210 argp
[i
% sizeof arg
] ^= seedp
[i
];
2211 set_random_seed (arg
);
2218 bool success
= false;
2220 /* First, try seeding the PRNG from the operating system's entropy
2221 source. This approach is both fast and secure. */
2223 success
= w32_init_random (&v
, sizeof v
) == 0;
2225 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2228 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2233 /* If that didn't work, try using GnuTLS, which is secure, but on
2234 some systems, can be somewhat slow. */
2236 success
= EQ (emacs_gnutls_global_init (), Qt
)
2237 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2239 /* If _that_ didn't work, just use the current time value and PID.
2240 It's at least better than XKCD 221. */
2243 struct timespec t
= current_timespec ();
2244 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2247 set_random_seed (v
);
2251 * Return a nonnegative random integer out of whatever we've got.
2252 * It contains enough bits to make a random (signed) Emacs fixnum.
2253 * This suffices even for a 64-bit architecture with a 15-bit rand.
2260 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2261 val
= (random () ^ (val
<< RAND_BITS
)
2262 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2263 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2264 return val
& INTMASK
;
2267 #ifndef HAVE_SNPRINTF
2268 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2270 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2272 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2273 ptrdiff_t nbytes
= size
- 1;
2278 va_start (ap
, format
);
2279 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2283 if (nbytes
== size
- 1)
2285 /* Calculate the length of the string that would have been created
2286 had the buffer been large enough. */
2287 char stackbuf
[4000];
2289 ptrdiff_t bsize
= sizeof stackbuf
;
2290 va_start (ap
, format
);
2291 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2297 if (INT_MAX
< nbytes
)
2310 /* If a backtrace is available, output the top lines of it to stderr.
2311 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2312 This function may be called from a signal handler, so it should
2313 not invoke async-unsafe functions like malloc.
2315 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2316 but do not output anything. This avoids some problems that can
2317 otherwise occur if the malloc arena is corrupted before 'backtrace'
2318 is called, since 'backtrace' may call malloc if the tables are not
2321 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2322 fatal error has occurred in some other thread; generate a thread
2323 backtrace instead, ignoring BACKTRACE_LIMIT. */
2325 emacs_backtrace (int backtrace_limit
)
2327 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2328 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2332 if (thread_backtrace_npointers
)
2334 buffer
= thread_backtrace_buffer
;
2335 npointers
= thread_backtrace_npointers
;
2339 buffer
= main_backtrace_buffer
;
2341 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2342 if (bounded_limit
< 0)
2344 backtrace (buffer
, 1);
2348 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2353 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2354 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2355 if (bounded_limit
< npointers
)
2356 emacs_write (STDERR_FILENO
, "...\n", 4);
2364 terminate_due_to_signal (SIGABRT
, 40);
2368 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2369 Use binary I/O on systems that care about text vs binary I/O.
2370 Arrange for subprograms to not inherit the file descriptor.
2371 Prefer a method that is multithread-safe, if available.
2372 Do not fail merely because the open was interrupted by a signal.
2373 Allow the user to quit. */
2376 emacs_open (const char *file
, int oflags
, int mode
)
2379 if (! (oflags
& O_TEXT
))
2381 oflags
|= O_CLOEXEC
;
2382 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2384 if (! O_CLOEXEC
&& 0 <= fd
)
2385 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2389 /* Open FILE as a stream for Emacs use, with mode MODE.
2390 Act like emacs_open with respect to threads, signals, and quits. */
2393 emacs_fopen (char const *file
, char const *mode
)
2395 int fd
, omode
, oflags
;
2397 char const *m
= mode
;
2401 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2402 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2403 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2404 default: emacs_abort ();
2410 case '+': omode
= O_RDWR
; break;
2411 case 't': bflag
= O_TEXT
; break;
2412 default: /* Ignore. */ break;
2415 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2416 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2419 /* Create a pipe for Emacs use. */
2422 emacs_pipe (int fd
[2])
2427 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2428 if (! O_CLOEXEC
&& result
== 0)
2430 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2431 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2437 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2438 For the background behind this mess, please see Austin Group defect 529
2439 <http://austingroupbugs.net/view.php?id=529>. */
2441 #ifndef POSIX_CLOSE_RESTART
2442 # define POSIX_CLOSE_RESTART 1
2444 posix_close (int fd
, int flag
)
2446 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2447 eassert (flag
== POSIX_CLOSE_RESTART
);
2449 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2450 on a system that does not define POSIX_CLOSE_RESTART.
2452 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2453 closed, and retrying the close could inadvertently close a file
2454 descriptor allocated by some other thread. In other systems
2455 (e.g., HP/UX) FD is not closed. And in still other systems
2456 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2457 multithreaded program there can be no way to tell.
2459 So, in this case, pretend that the close succeeded. This works
2460 well on systems like GNU/Linux that close FD. Although it may
2461 leak a file descriptor on other systems, the leak is unlikely and
2462 it's better to leak than to close a random victim. */
2463 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2467 /* Close FD, retrying if interrupted. If successful, return 0;
2468 otherwise, return -1 and set errno to a non-EINTR value. Consider
2469 an EINPROGRESS error to be successful, as that's merely a signal
2470 arriving. FD is always closed when this function returns, even
2473 Do not call this function if FD is nonnegative and might already be closed,
2474 as that might close an innocent victim opened by some other thread. */
2477 emacs_close (int fd
)
2481 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2484 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2486 eassert (errno
!= EBADF
|| fd
< 0);
2487 return errno
== EINPROGRESS
? 0 : r
;
2492 /* Maximum number of bytes to read or write in a single system call.
2493 This works around a serious bug in Linux kernels before 2.6.16; see
2494 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2495 It's likely to work around similar bugs in other operating systems, so do it
2496 on all platforms. Round INT_MAX down to a page size, with the conservative
2497 assumption that page sizes are at most 2**18 bytes (any kernel with a
2498 page size larger than that shouldn't have the bug). */
2499 #ifndef MAX_RW_COUNT
2500 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2503 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2504 Return the number of bytes read, which might be less than NBYTE.
2505 On error, set errno and return -1. */
2507 emacs_read (int fildes
, void *buf
, ptrdiff_t nbyte
)
2511 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2512 passes a size that large to emacs_read. */
2514 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
2515 && (errno
== EINTR
))
2520 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2521 or if a partial write occurs. If interrupted, process pending
2522 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2523 errno if this is less than NBYTE. */
2525 emacs_full_write (int fildes
, char const *buf
, ptrdiff_t nbyte
,
2526 bool process_signals
)
2528 ptrdiff_t bytes_written
= 0;
2532 ssize_t n
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
2538 /* I originally used `QUIT' but that might cause files to
2539 be truncated if you hit C-g in the middle of it. --Stef */
2540 if (process_signals
&& pending_signals
)
2541 process_pending_signals ();
2553 return bytes_written
;
2556 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2557 interrupted or if a partial write occurs. Return the number of
2558 bytes written, setting errno if this is less than NBYTE. */
2560 emacs_write (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2562 return emacs_full_write (fildes
, buf
, nbyte
, 0);
2565 /* Like emacs_write, but also process pending signals if interrupted. */
2567 emacs_write_sig (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2569 return emacs_full_write (fildes
, buf
, nbyte
, 1);
2572 /* Write a diagnostic to standard error that contains MESSAGE and a
2573 string derived from errno. Preserve errno. Do not buffer stderr.
2574 Do not process pending signals if interrupted. */
2576 emacs_perror (char const *message
)
2579 char const *error_string
= emacs_strerror (err
);
2580 char const *command
= (initial_argv
&& initial_argv
[0]
2581 ? initial_argv
[0] : "emacs");
2582 /* Write it out all at once, if it's short; this is less likely to
2583 be interleaved with other output. */
2585 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2586 command
, message
, error_string
);
2587 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2588 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2591 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2592 emacs_write (STDERR_FILENO
, ": ", 2);
2593 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2594 emacs_write (STDERR_FILENO
, ": ", 2);
2595 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2596 emacs_write (STDERR_FILENO
, "\n", 1);
2601 /* Return a struct timeval that is roughly equivalent to T.
2602 Use the least timeval not less than T.
2603 Return an extremal value if the result would overflow. */
2605 make_timeval (struct timespec t
)
2608 tv
.tv_sec
= t
.tv_sec
;
2609 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2611 if (t
.tv_nsec
% 1000 != 0)
2613 if (tv
.tv_usec
< 999999)
2615 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2625 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2626 ATIME and MTIME, respectively.
2627 FD must be either negative -- in which case it is ignored --
2628 or a file descriptor that is open on FILE.
2629 If FD is nonnegative, then FILE can be NULL. */
2631 set_file_times (int fd
, const char *filename
,
2632 struct timespec atime
, struct timespec mtime
)
2634 struct timespec timespec
[2];
2635 timespec
[0] = atime
;
2636 timespec
[1] = mtime
;
2637 return fdutimens (fd
, filename
, timespec
);
2640 /* Like strsignal, except async-signal-safe, and this function typically
2641 returns a string in the C locale rather than the current locale. */
2643 safe_strsignal (int code
)
2645 char const *signame
= 0;
2647 if (0 <= code
&& code
< sys_siglist_entries
)
2648 signame
= sys_siglist
[code
];
2650 signame
= "Unknown signal";
2656 /* For make-serial-process */
2658 serial_open (Lisp_Object port
)
2660 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2662 report_file_error ("Opening serial port", port
);
2664 ioctl (fd
, TIOCEXCL
, (char *) 0);
2670 #if !defined (HAVE_CFMAKERAW)
2671 /* Workaround for targets which are missing cfmakeraw. */
2672 /* Pasted from man page. */
2674 cfmakeraw (struct termios
*termios_p
)
2676 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2677 termios_p
->c_oflag
&= ~OPOST
;
2678 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2679 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2680 termios_p
->c_cflag
|= CS8
;
2682 #endif /* !defined (HAVE_CFMAKERAW */
2684 #if !defined (HAVE_CFSETSPEED)
2685 /* Workaround for targets which are missing cfsetspeed. */
2687 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2689 return (cfsetispeed (termios_p
, vitesse
)
2690 + cfsetospeed (termios_p
, vitesse
));
2694 /* For serial-process-configure */
2696 serial_configure (struct Lisp_Process
*p
,
2697 Lisp_Object contact
)
2699 Lisp_Object childp2
= Qnil
;
2700 Lisp_Object tem
= Qnil
;
2701 struct termios attr
;
2703 char summary
[4] = "???"; /* This usually becomes "8N1". */
2705 childp2
= Fcopy_sequence (p
->childp
);
2707 /* Read port attributes and prepare default configuration. */
2708 err
= tcgetattr (p
->outfd
, &attr
);
2710 report_file_error ("Failed tcgetattr", Qnil
);
2712 #if defined (CLOCAL)
2713 attr
.c_cflag
|= CLOCAL
;
2716 attr
.c_cflag
|= CREAD
;
2719 /* Configure speed. */
2720 if (!NILP (Fplist_member (contact
, QCspeed
)))
2721 tem
= Fplist_get (contact
, QCspeed
);
2723 tem
= Fplist_get (p
->childp
, QCspeed
);
2725 err
= cfsetspeed (&attr
, XINT (tem
));
2727 report_file_error ("Failed cfsetspeed", tem
);
2728 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2730 /* Configure bytesize. */
2731 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2732 tem
= Fplist_get (contact
, QCbytesize
);
2734 tem
= Fplist_get (p
->childp
, QCbytesize
);
2736 tem
= make_number (8);
2738 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2739 error (":bytesize must be nil (8), 7, or 8");
2740 summary
[0] = XINT (tem
) + '0';
2741 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2742 attr
.c_cflag
&= ~CSIZE
;
2743 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2745 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2746 if (XINT (tem
) != 8)
2747 error ("Bytesize cannot be changed");
2749 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2751 /* Configure parity. */
2752 if (!NILP (Fplist_member (contact
, QCparity
)))
2753 tem
= Fplist_get (contact
, QCparity
);
2755 tem
= Fplist_get (p
->childp
, QCparity
);
2756 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2757 error (":parity must be nil (no parity), `even', or `odd'");
2758 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2759 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2760 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2765 else if (EQ (tem
, Qeven
))
2768 attr
.c_cflag
|= PARENB
;
2769 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2771 else if (EQ (tem
, Qodd
))
2774 attr
.c_cflag
|= (PARENB
| PARODD
);
2775 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2778 /* Don't error on no parity, which should be set by cfmakeraw. */
2780 error ("Parity cannot be configured");
2782 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2784 /* Configure stopbits. */
2785 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2786 tem
= Fplist_get (contact
, QCstopbits
);
2788 tem
= Fplist_get (p
->childp
, QCstopbits
);
2790 tem
= make_number (1);
2792 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2793 error (":stopbits must be nil (1 stopbit), 1, or 2");
2794 summary
[2] = XINT (tem
) + '0';
2795 #if defined (CSTOPB)
2796 attr
.c_cflag
&= ~CSTOPB
;
2797 if (XINT (tem
) == 2)
2798 attr
.c_cflag
|= CSTOPB
;
2800 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2801 if (XINT (tem
) != 1)
2802 error ("Stopbits cannot be configured");
2804 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2806 /* Configure flowcontrol. */
2807 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2808 tem
= Fplist_get (contact
, QCflowcontrol
);
2810 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2811 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2812 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2813 #if defined (CRTSCTS)
2814 attr
.c_cflag
&= ~CRTSCTS
;
2816 #if defined (CNEW_RTSCTS)
2817 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2819 #if defined (IXON) && defined (IXOFF)
2820 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2824 /* Already configured. */
2826 else if (EQ (tem
, Qhw
))
2828 #if defined (CRTSCTS)
2829 attr
.c_cflag
|= CRTSCTS
;
2830 #elif defined (CNEW_RTSCTS)
2831 attr
.c_cflag
|= CNEW_RTSCTS
;
2833 error ("Hardware flowcontrol (RTS/CTS) not supported");
2836 else if (EQ (tem
, Qsw
))
2838 #if defined (IXON) && defined (IXOFF)
2839 attr
.c_iflag
|= (IXON
| IXOFF
);
2841 error ("Software flowcontrol (XON/XOFF) not supported");
2844 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2846 /* Activate configuration. */
2847 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2849 report_file_error ("Failed tcsetattr", Qnil
);
2851 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2852 pset_childp (p
, childp2
);
2854 #endif /* not DOS_NT */
2856 /* System depended enumeration of and access to system processes a-la ps(1). */
2860 /* Process enumeration and access via /proc. */
2863 list_system_processes (void)
2865 Lisp_Object procdir
, match
, proclist
, next
;
2868 /* For every process on the system, there's a directory in the
2869 "/proc" pseudo-directory whose name is the numeric ID of that
2871 procdir
= build_string ("/proc");
2872 match
= build_string ("[0-9]+");
2873 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2875 /* `proclist' gives process IDs as strings. Destructively convert
2876 each string into a number. */
2877 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2880 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2883 /* directory_files_internal returns the files in reverse order; undo
2885 proclist
= Fnreverse (proclist
);
2889 #elif defined DARWIN_OS || defined __FreeBSD__
2892 list_system_processes (void)
2895 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2897 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2900 struct kinfo_proc
*procs
;
2903 Lisp_Object proclist
= Qnil
;
2905 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2908 procs
= xmalloc (len
);
2909 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2915 len
/= sizeof (struct kinfo_proc
);
2916 for (i
= 0; i
< len
; i
++)
2919 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2921 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2930 /* The WINDOWSNT implementation is in w32.c.
2931 The MSDOS implementation is in dosfns.c. */
2932 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2935 list_system_processes (void)
2940 #endif /* !defined (WINDOWSNT) */
2942 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2943 static struct timespec
2944 time_from_jiffies (unsigned long long tval
, long hz
)
2946 unsigned long long s
= tval
/ hz
;
2947 unsigned long long frac
= tval
% hz
;
2950 if (TYPE_MAXIMUM (time_t) < s
)
2952 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2953 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2954 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2957 /* This is reachable only in the unlikely case that HZ * HZ
2958 exceeds ULLONG_MAX. It calculates an approximation that is
2959 guaranteed to be in range. */
2960 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
2961 + (hz
% TIMESPEC_RESOLUTION
!= 0));
2962 ns
= frac
/ hz_per_ns
;
2965 return make_timespec (s
, ns
);
2969 ltime_from_jiffies (unsigned long long tval
, long hz
)
2971 struct timespec t
= time_from_jiffies (tval
, hz
);
2972 return make_lisp_time (t
);
2975 static struct timespec
2979 struct timespec up
= make_timespec (0, 0);
2982 fup
= emacs_fopen ("/proc/uptime", "r");
2986 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
2987 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
2989 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
2990 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
2991 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
2994 if (TYPE_MAXIMUM (time_t) < upsec
)
2996 upsec
= TYPE_MAXIMUM (time_t);
2997 upfrac
= TIMESPEC_RESOLUTION
- 1;
3001 int upfraclen
= upfrac_end
- upfrac_start
;
3002 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3004 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3006 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3008 up
= make_timespec (upsec
, upfrac
);
3017 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3018 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3021 procfs_ttyname (int rdev
)
3024 char name
[PATH_MAX
];
3027 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3033 unsigned long minor_beg
, minor_end
;
3034 char minor
[25]; /* 2 32-bit numbers + dash */
3037 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3039 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3040 && major
== MAJOR (rdev
))
3042 minor_beg
= strtoul (minor
, &endp
, 0);
3044 minor_end
= minor_beg
;
3045 else if (*endp
== '-')
3046 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3050 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3052 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3060 return build_string (name
);
3064 procfs_get_total_memory (void)
3067 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3071 fmem
= emacs_fopen ("/proc/meminfo", "r");
3075 uintmax_t entry_value
;
3079 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3082 retval
= entry_value
;
3087 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3105 system_process_attributes (Lisp_Object pid
)
3107 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3111 long clocks_per_sec
;
3113 char procbuf
[1025], *p
, *q
;
3116 static char const default_cmd
[] = "???";
3117 const char *cmd
= default_cmd
;
3118 int cmdsize
= sizeof default_cmd
- 1;
3119 char *cmdline
= NULL
;
3120 ptrdiff_t cmdline_size
;
3123 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3126 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3127 long priority
, niceness
, rss
;
3128 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3129 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3131 Lisp_Object attrs
= Qnil
;
3132 Lisp_Object decoded_cmd
;
3135 CHECK_NUMBER_OR_FLOAT (pid
);
3136 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3137 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3138 if (stat (procfn
, &st
) < 0)
3143 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3145 pw
= getpwuid (uid
);
3148 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3151 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3153 gr
= getgrgid (gid
);
3156 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3158 count
= SPECPDL_INDEX ();
3159 strcpy (fn
, procfn
);
3160 procfn_end
= fn
+ strlen (fn
);
3161 strcpy (procfn_end
, "/stat");
3162 fd
= emacs_open (fn
, O_RDONLY
, 0);
3167 record_unwind_protect_int (close_file_unwind
, fd
);
3168 nread
= emacs_read (fd
, procbuf
, sizeof procbuf
- 1);
3172 procbuf
[nread
] = '\0';
3175 p
= strchr (p
, '(');
3178 q
= strrchr (p
+ 1, ')');
3188 /* Command name is encoded in locale-coding-system; decode it. */
3189 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3190 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3191 Vlocale_coding_system
, 0);
3192 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3194 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3195 utime stime cutime cstime priority nice thcount . start vsize rss */
3197 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3198 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3199 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3200 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3201 &u_time
, &s_time
, &cutime
, &cstime
,
3202 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3207 state_str
[1] = '\0';
3208 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3209 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3210 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3211 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3212 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3213 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3214 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3215 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3216 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3218 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3220 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3221 if (clocks_per_sec
< 0)
3222 clocks_per_sec
= 100;
3223 attrs
= Fcons (Fcons (Qutime
,
3224 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3226 attrs
= Fcons (Fcons (Qstime
,
3227 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3229 attrs
= Fcons (Fcons (Qtime
,
3230 ltime_from_jiffies (s_time
+ u_time
,
3233 attrs
= Fcons (Fcons (Qcutime
,
3234 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3236 attrs
= Fcons (Fcons (Qcstime
,
3237 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3239 attrs
= Fcons (Fcons (Qctime
,
3240 ltime_from_jiffies (cstime
+ cutime
,
3243 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3244 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3245 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3247 tnow
= current_timespec ();
3248 telapsed
= get_up_time ();
3249 tboot
= timespec_sub (tnow
, telapsed
);
3250 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3251 tstart
= timespec_add (tboot
, tstart
);
3252 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3253 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3255 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3256 telapsed
= timespec_sub (tnow
, tstart
);
3257 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3258 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3259 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3262 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3263 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3266 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3269 unbind_to (count
, Qnil
);
3272 strcpy (procfn_end
, "/cmdline");
3273 fd
= emacs_open (fn
, O_RDONLY
, 0);
3276 ptrdiff_t readsize
, nread_incr
;
3277 record_unwind_protect_int (close_file_unwind
, fd
);
3278 record_unwind_protect_nothing ();
3279 nread
= cmdline_size
= 0;
3283 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3284 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3286 /* Leave room even if every byte needs escaping below. */
3287 readsize
= (cmdline_size
>> 1) - nread
;
3289 nread_incr
= emacs_read (fd
, cmdline
+ nread
, readsize
);
3290 nread
+= max (0, nread_incr
);
3292 while (nread_incr
== readsize
);
3296 /* We don't want trailing null characters. */
3297 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3300 /* Escape-quote whitespace and backslashes. */
3301 q
= cmdline
+ cmdline_size
;
3306 if (c_isspace (c
) || c
== '\\')
3310 nread
= cmdline
+ cmdline_size
- q
;
3315 nread
= cmdsize
+ 2;
3316 cmdline_size
= nread
+ 1;
3317 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3318 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3319 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3321 /* Command line is encoded in locale-coding-system; decode it. */
3322 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3323 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3324 Vlocale_coding_system
, 0);
3325 unbind_to (count
, Qnil
);
3326 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3332 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3334 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3335 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3336 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3337 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3338 #undef _FILE_OFFSET_BITS
3340 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3345 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3346 #define _FILE_OFFSET_BITS 64
3347 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3349 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3352 system_process_attributes (Lisp_Object pid
)
3354 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3359 struct psinfo pinfo
;
3365 Lisp_Object attrs
= Qnil
;
3366 Lisp_Object decoded_cmd
;
3369 CHECK_NUMBER_OR_FLOAT (pid
);
3370 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3371 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3372 if (stat (procfn
, &st
) < 0)
3377 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3379 pw
= getpwuid (uid
);
3382 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3385 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3387 gr
= getgrgid (gid
);
3390 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3392 count
= SPECPDL_INDEX ();
3393 strcpy (fn
, procfn
);
3394 procfn_end
= fn
+ strlen (fn
);
3395 strcpy (procfn_end
, "/psinfo");
3396 fd
= emacs_open (fn
, O_RDONLY
, 0);
3401 record_unwind_protect_int (close_file_unwind
, fd
);
3402 nread
= emacs_read (fd
, &pinfo
, sizeof pinfo
);
3405 if (nread
== sizeof pinfo
)
3407 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3408 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3409 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3413 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3414 state_str
[1] = '\0';
3415 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3418 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3419 need to get a string from it. */
3421 /* FIXME: missing: Qtpgid */
3433 Are they available? */
3435 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3436 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3437 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3438 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3439 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3442 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3443 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3445 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3448 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3449 range 0 .. 2**15, representing 0.0 .. 1.0. */
3450 attrs
= Fcons (Fcons (Qpcpu
,
3451 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3453 attrs
= Fcons (Fcons (Qpmem
,
3454 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3457 AUTO_STRING (fname
, pinfo
.pr_fname
);
3458 decoded_cmd
= code_convert_string_norecord (fname
,
3459 Vlocale_coding_system
, 0);
3460 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3461 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3462 decoded_cmd
= code_convert_string_norecord (psargs
,
3463 Vlocale_coding_system
, 0);
3464 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3466 unbind_to (count
, Qnil
);
3470 #elif defined __FreeBSD__
3472 static struct timespec
3473 timeval_to_timespec (struct timeval t
)
3475 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3479 make_lisp_timeval (struct timeval t
)
3481 return make_lisp_time (timeval_to_timespec (t
));
3485 system_process_attributes (Lisp_Object pid
)
3488 int pagesize
= getpagesize ();
3489 unsigned long npages
;
3495 char args
[MAXPATHLEN
];
3496 struct timespec t
, now
;
3498 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3499 struct kinfo_proc proc
;
3500 size_t proclen
= sizeof proc
;
3502 Lisp_Object attrs
= Qnil
;
3503 Lisp_Object decoded_comm
;
3505 CHECK_NUMBER_OR_FLOAT (pid
);
3506 CONS_TO_INTEGER (pid
, int, proc_id
);
3509 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3512 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3515 pw
= getpwuid (proc
.ki_uid
);
3518 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3520 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3523 gr
= getgrgid (proc
.ki_svgid
);
3526 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3528 AUTO_STRING (comm
, proc
.ki_comm
);
3529 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3531 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3533 char state
[2] = {'\0', '\0'};
3534 switch (proc
.ki_stat
)
3556 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3559 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3560 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3561 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3564 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3567 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3569 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3570 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3571 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3572 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3573 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3575 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3577 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3579 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3580 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3581 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3583 attrs
= Fcons (Fcons (Qcutime
,
3584 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3586 attrs
= Fcons (Fcons (Qcstime
,
3587 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3589 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3590 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3591 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3593 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3595 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3596 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3597 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3598 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3599 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3602 now
= current_timespec ();
3603 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3604 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3606 len
= sizeof fscale
;
3607 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3612 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3614 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3615 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3616 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3620 len
= sizeof npages
;
3621 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3623 double pmem
= (proc
.ki_flag
& P_INMEM
3624 ? 100.0 * proc
.ki_rssize
/ npages
3626 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3629 mib
[2] = KERN_PROC_ARGS
;
3631 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3634 for (i
= 0; i
< len
; i
++)
3636 if (! args
[i
] && i
< len
- 1)
3640 AUTO_STRING (comm
, args
);
3641 decoded_comm
= code_convert_string_norecord (comm
,
3642 Vlocale_coding_system
, 0);
3644 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3650 #elif defined DARWIN_OS
3652 static struct timespec
3653 timeval_to_timespec (struct timeval t
)
3655 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3659 make_lisp_timeval (struct timeval t
)
3661 return make_lisp_time (timeval_to_timespec (t
));
3665 system_process_attributes (Lisp_Object pid
)
3668 int pagesize
= getpagesize ();
3669 unsigned long npages
;
3675 char args
[MAXPATHLEN
];
3676 struct timeval starttime
;
3677 struct timespec t
, now
;
3678 struct rusage
*rusage
;
3683 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3684 struct kinfo_proc proc
;
3685 size_t proclen
= sizeof proc
;
3687 Lisp_Object attrs
= Qnil
;
3688 Lisp_Object decoded_comm
;
3690 CHECK_NUMBER_OR_FLOAT (pid
);
3691 CONS_TO_INTEGER (pid
, int, proc_id
);
3694 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3697 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3698 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3701 pw
= getpwuid (uid
);
3704 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3706 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3707 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3710 gr
= getgrgid (gid
);
3713 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3715 decoded_comm
= (code_convert_string_norecord
3716 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3717 Vlocale_coding_system
, 0));
3719 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3721 char state
[2] = {'\0', '\0'};
3722 switch (proc
.kp_proc
.p_stat
)
3744 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3747 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3749 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3752 tdev
= proc
.kp_eproc
.e_tdev
;
3754 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3757 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3759 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3762 rusage
= proc
.kp_proc
.p_ru
;
3765 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3767 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3770 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3772 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3774 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3775 timeval_to_timespec (rusage
->ru_stime
));
3776 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3779 starttime
= proc
.kp_proc
.p_starttime
;
3780 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3781 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3783 now
= current_timespec ();
3784 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3785 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3790 /* The WINDOWSNT implementation is in w32.c.
3791 The MSDOS implementation is in dosfns.c. */
3792 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3795 system_process_attributes (Lisp_Object pid
)
3800 #endif /* !defined (WINDOWSNT) */
3802 /* Wide character string collation. */
3804 #ifdef __STDC_ISO_10646__
3806 # include <wctype.h>
3808 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3809 # include <locale.h>
3812 # define LC_COLLATE 0
3814 # ifndef LC_COLLATE_MASK
3815 # define LC_COLLATE_MASK 0
3820 # ifndef LC_CTYPE_MASK
3821 # define LC_CTYPE_MASK 0
3824 # ifndef HAVE_NEWLOCALE
3830 # define freelocale emacs_freelocale
3831 # define locale_t emacs_locale_t
3832 # define newlocale emacs_newlocale
3833 # define wcscoll_l emacs_wcscoll_l
3834 # define towlower_l emacs_towlower_l
3836 typedef char const *locale_t
;
3839 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3845 freelocale (locale_t loc
)
3850 emacs_setlocale (int category
, char const *locale
)
3852 # ifdef HAVE_SETLOCALE
3854 char *loc
= setlocale (category
, locale
);
3865 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3868 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3876 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3877 strcpy (oldcopy
, oldloc
);
3878 if (! emacs_setlocale (LC_COLLATE
, loc
))
3883 result
= wcscoll (a
, b
);
3885 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3896 towlower_l (wint_t wc
, locale_t loc
)
3899 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3904 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3905 strcpy (oldcopy
, oldloc
);
3906 if (emacs_setlocale (LC_CTYPE
, loc
))
3908 result
= towlower (wc
);
3909 emacs_setlocale (LC_COLLATE
, oldcopy
);
3919 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3920 Lisp_Object locale
, Lisp_Object ignore_case
)
3923 ptrdiff_t len
, i
, i_byte
;
3928 /* Convert byte stream to code points. */
3929 len
= SCHARS (s1
); i
= i_byte
= 0;
3930 SAFE_NALLOCA (p1
, 1, len
+ 1);
3932 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3935 len
= SCHARS (s2
); i
= i_byte
= 0;
3936 SAFE_NALLOCA (p2
, 1, len
+ 1);
3938 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3941 if (STRINGP (locale
))
3943 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3944 SSDATA (locale
), 0);
3946 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3948 if (! NILP (ignore_case
))
3949 for (int i
= 1; i
< 3; i
++)
3951 wchar_t *p
= (i
== 1) ? p1
: p2
;
3953 *p
= towlower_l (*p
, loc
);
3957 res
= wcscoll_l (p1
, p2
, loc
);
3963 if (! NILP (ignore_case
))
3964 for (int i
= 1; i
< 3; i
++)
3966 wchar_t *p
= (i
== 1) ? p1
: p2
;
3972 res
= wcscoll (p1
, p2
);
3975 # ifndef HAVE_NEWLOCALE
3977 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
3980 error ("Invalid string for collation: %s", emacs_strerror (err
));
3986 #endif /* __STDC_ISO_10646__ */
3990 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3991 Lisp_Object locale
, Lisp_Object ignore_case
)
3994 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
3995 int res
, err
= errno
;
3998 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4000 error ("Invalid string for collation: %s", strerror (errno
));
4005 #endif /* WINDOWSNT */