1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2019 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 <https://www.gnu.org/licenses/>. */
27 #endif /* HAVE_PWD_H */
33 #include <close-stream.h>
39 #include "sysselect.h"
40 #include "blockinput.h"
42 #ifdef HAVE_LINUX_FS_H
43 # include <linux/fs.h>
44 # include <sys/syscall.h>
48 # include <cygwin/fs.h>
51 #if defined DARWIN_OS || defined __FreeBSD__
52 # include <sys/sysctl.h>
56 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
57 'struct frame', so rename it. */
58 # define frame freebsd_frame
59 # include <sys/user.h>
66 #include <sys/socket.h>
68 #endif /* HAVE_SOCKETS */
72 #define write sys_write
74 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
77 #endif /* WINDOWSNT */
79 #include <sys/types.h>
83 /* Get SI_SRPC_DOMAIN, if it is available. */
84 #ifdef HAVE_SYS_SYSTEMINFO_H
85 #include <sys/systeminfo.h>
88 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
92 #include <sys/param.h>
96 #include "syssignal.h"
101 #ifdef HAVE_SYS_RESOURCE_H
102 # include <sys/resource.h>
105 #ifdef HAVE_SYS_UTSNAME_H
106 # include <sys/utsname.h>
110 #include "keyboard.h"
112 #include "termhooks.h"
113 #include "termchar.h"
114 #include "termopts.h"
119 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
120 do that during startup just to call gnutls_rnd. */
121 #if defined HAVE_GNUTLS && !defined WINDOWSNT
122 # include <gnutls/crypto.h>
124 # define emacs_gnutls_global_init() Qnil
125 # define gnutls_rnd(level, data, len) (-1)
130 /* In process.h which conflicts with the local copy. */
132 int _cdecl
_spawnlp (int, const char *, const char *, ...);
133 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
134 several prototypes of functions called below. */
135 # include <sys/socket.h>
138 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
140 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
143 /* Declare here, including term.h is problematic on some systems. */
144 extern void tputs (const char *, int, int (*)(int));
146 static const int baud_convert
[] =
148 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
149 1800, 2400, 4800, 9600, 19200, 38400
152 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
153 # include <sys/personality.h>
155 /* If not -1, the personality that should be restored before exec. */
156 static int exec_personality
;
158 /* Try to disable randomization if the current process needs it and
159 does not appear to have it already. */
161 maybe_disable_address_randomization (bool dumping
, int argc
, char **argv
)
163 /* Undocumented Emacs option used only by this function. */
164 static char const aslr_disabled_option
[] = "--__aslr-disabled";
166 if (argc
< 2 || strcmp (argv
[1], aslr_disabled_option
) != 0)
168 bool disable_aslr
= dumping
;
172 exec_personality
= disable_aslr
? personality (0xffffffff) : -1;
173 if (exec_personality
& ADDR_NO_RANDOMIZE
)
174 exec_personality
= -1;
175 if (exec_personality
!= -1
176 && personality (exec_personality
| ADDR_NO_RANDOMIZE
) != -1)
178 char **newargv
= malloc ((argc
+ 2) * sizeof *newargv
);
181 /* Invoke self with undocumented option. */
182 newargv
[0] = argv
[0];
183 newargv
[1] = (char *) aslr_disabled_option
;
184 memcpy (&newargv
[2], &argv
[1], argc
* sizeof *newargv
);
185 execvp (newargv
[0], newargv
);
188 /* If malloc or execvp fails, warn and then try anyway. */
195 /* Our earlier incarnation already disabled ASLR. */
197 memmove (&argv
[1], &argv
[2], argc
* sizeof *argv
);
204 /* Execute the program in FILE, with argument vector ARGV and environ
205 ENVP. Return an error number if unsuccessful. This is like execve
206 except it reenables ASLR in the executed program if necessary, and
207 on error it returns an error number rather than -1. */
209 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
211 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
212 if (exec_personality
!= -1)
213 personality (exec_personality
);
216 execve (file
, argv
, envp
);
220 /* If FD is not already open, arrange for it to be open with FLAGS. */
222 force_open (int fd
, int flags
)
224 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
226 int n
= open (NULL_DEVICE
, flags
);
227 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
229 emacs_perror (NULL_DEVICE
);
235 /* A stream that is like stderr, except line buffered. It is NULL
236 during startup, or if line buffering is not in use. */
239 /* Make sure stdin, stdout, and stderr are open to something, so that
240 their file descriptors are not hijacked by later system calls. */
242 init_standard_fds (void)
244 /* Open stdin for *writing*, and stdout and stderr for *reading*.
245 That way, any attempt to do normal I/O will result in an error,
246 just as if the files were closed, and the file descriptors will
247 not be reused by later opens. */
248 force_open (STDIN_FILENO
, O_WRONLY
);
249 force_open (STDOUT_FILENO
, O_RDONLY
);
250 force_open (STDERR_FILENO
, O_RDONLY
);
252 /* Set buferr if possible on platforms defining _PC_PIPE_BUF, as
253 they support the notion of atomic writes to pipes. */
255 buferr
= fdopen (STDERR_FILENO
, "w");
257 setvbuf (buferr
, NULL
, _IOLBF
, 0);
261 /* Return the current working directory. The result should be freed
262 with 'free'. Return NULL (setting errno) on errors. If the
263 current directory is unreachable, return either NULL or a string
264 beginning with '('. */
267 get_current_dir_name_or_unreachable (void)
269 /* Use malloc, not xmalloc, since this function can be called before
270 the xmalloc exception machinery is available. */
274 /* The maximum size of a directory name, including the terminating NUL.
275 Leave room so that the caller can append a trailing slash. */
276 ptrdiff_t dirsize_max
= min (PTRDIFF_MAX
, SIZE_MAX
) - 1;
278 /* The maximum size of a buffer for a file name, including the
279 terminating NUL. This is bounded by PATH_MAX, if available. */
280 ptrdiff_t bufsize_max
= dirsize_max
;
282 bufsize_max
= min (bufsize_max
, PATH_MAX
);
285 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
286 # ifdef HYBRID_MALLOC
287 bool use_libc
= will_dump_with_unexec_p ();
289 bool use_libc
= true;
293 /* For an unreachable directory, this returns a string that starts
294 with "(unreachable)"; see Bug#27871. */
295 pwd
= get_current_dir_name ();
298 if (strnlen (pwd
, dirsize_max
) < dirsize_max
)
308 struct stat dotstat
, pwdstat
;
309 pwd
= getenv ("PWD");
311 /* If PWD is accurate, use it instead of calling getcwd. PWD is
312 sometimes a nicer name, and using it may avoid a fatal error if a
313 parent directory is searchable but not readable. */
315 && (pwdlen
= strnlen (pwd
, bufsize_max
)) < bufsize_max
316 && IS_DIRECTORY_SEP (pwd
[pwdlen
&& IS_DEVICE_SEP (pwd
[1]) ? 2 : 0])
317 && stat (pwd
, &pwdstat
) == 0
318 && stat (".", &dotstat
) == 0
319 && dotstat
.st_ino
== pwdstat
.st_ino
320 && dotstat
.st_dev
== pwdstat
.st_dev
)
322 char *buf
= malloc (pwdlen
+ 1);
325 return memcpy (buf
, pwd
, pwdlen
+ 1);
329 ptrdiff_t buf_size
= min (bufsize_max
, 1024);
330 char *buf
= malloc (buf_size
);
335 if (getcwd (buf
, buf_size
) == buf
)
337 int getcwd_errno
= errno
;
338 if (getcwd_errno
!= ERANGE
|| buf_size
== bufsize_max
)
341 errno
= getcwd_errno
;
344 buf_size
= buf_size
<= bufsize_max
/ 2 ? 2 * buf_size
: bufsize_max
;
345 buf
= realloc (buf
, buf_size
);
352 /* Return the current working directory. The result should be freed
353 with 'free'. Return NULL (setting errno) on errors; an unreachable
354 directory (e.g., its name starts with '(') counts as an error. */
357 emacs_get_current_dir_name (void)
359 char *dir
= get_current_dir_name_or_unreachable ();
360 if (dir
&& *dir
== '(')
370 /* Discard pending input on all input descriptors. */
373 discard_tty_input (void)
376 struct emacs_tty buf
;
381 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
382 while (dos_keyread () != -1)
384 #else /* not MSDOS */
386 struct tty_display_info
*tty
;
387 for (tty
= tty_list
; tty
; tty
= tty
->next
)
389 if (tty
->input
) /* Is the device suspended? */
391 emacs_get_tty (fileno (tty
->input
), &buf
);
392 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
396 #endif /* not MSDOS */
397 #endif /* not WINDOWSNT */
403 /* Arrange for character C to be read as the next input from
405 XXX What if we have multiple ttys?
411 if (! (FRAMEP (selected_frame
)
412 && FRAME_LIVE_P (XFRAME (selected_frame
))
413 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
416 /* Should perhaps error if in batch mode */
418 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
419 #else /* no TIOCSTI */
420 error ("Cannot stuff terminal input characters in this version of Unix");
421 #endif /* no TIOCSTI */
427 init_baud_rate (int fd
)
437 #else /* not DOS_NT */
442 emacs_ospeed
= cfgetospeed (&sg
);
443 #endif /* not DOS_NT */
446 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
447 ? baud_convert
[emacs_ospeed
] : 9600);
456 /* Wait for the subprocess with process id CHILD to terminate or change status.
457 CHILD must be a child process that has not been reaped.
458 If STATUS is non-null, store the waitpid-style exit status into *STATUS
459 and tell wait_reading_process_output that it needs to look around.
460 Use waitpid-style OPTIONS when waiting.
461 If INTERRUPTIBLE, this function is interruptible by a signal.
463 Return CHILD if successful, 0 if no status is available, and a
464 negative value (setting errno) if waitpid is buggy. */
466 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
470 /* Invoke waitpid only with a known process ID; do not invoke
471 waitpid with a nonpositive argument. Otherwise, Emacs might
472 reap an unwanted process by mistake. For example, invoking
473 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
474 so that another thread running glib won't find them. */
479 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
484 pid
= waitpid (child
, status
, options
);
489 /* Most likely, waitpid is buggy and the operating system
490 lost track of the child somehow. Return -1 and let the
491 caller try to figure things out. Possibly the bug could
492 cause Emacs to kill the wrong process. Oh well. */
497 /* If successful and status is requested, tell wait_reading_process_output
498 that it needs to wake up and look around. */
499 if (pid
&& status
&& input_available_clear_time
)
500 *input_available_clear_time
= make_timespec (0, 0);
505 /* Wait for the subprocess with process id CHILD to terminate.
506 CHILD must be a child process that has not been reaped.
507 If STATUS is non-null, store the waitpid-style exit status into *STATUS
508 and tell wait_reading_process_output that it needs to look around.
509 If INTERRUPTIBLE, this function is interruptible by a signal.
510 Return true if successful, false (setting errno) if CHILD cannot be
511 waited for because waitpid is buggy. */
513 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
515 return 0 <= get_child_status (child
, status
, 0, interruptible
);
518 /* Report whether the subprocess with process id CHILD has changed status.
519 Termination counts as a change of status.
520 CHILD must be a child process that has not been reaped.
521 If STATUS is non-null, store the waitpid-style exit status into *STATUS
522 and tell wait_reading_process_output that it needs to look around.
523 Use waitpid-style OPTIONS to check status, but do not wait.
525 Return CHILD if successful, 0 if no status is available because
526 the process's state has not changed. */
528 child_status_changed (pid_t child
, int *status
, int options
)
530 return get_child_status (child
, status
, WNOHANG
| options
, 0);
534 /* Set up the terminal at the other end of a pseudo-terminal that
535 we will be controlling an inferior through.
536 It should not echo or do line-editing, since that is done
537 in Emacs. No padding needed for insertion into an Emacs buffer. */
540 child_setup_tty (int out
)
545 emacs_get_tty (out
, &s
);
546 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
547 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
549 /* https://lists.gnu.org/r/emacs-devel/2008-05/msg00406.html
550 Some versions of GNU Hurd do not have FFDLY? */
552 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
553 /* No output delays */
555 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
556 /* No output delays */
559 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
560 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
562 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
565 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
568 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
570 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
571 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
572 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
573 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
576 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
579 #ifdef SIGNALS_VIA_CHARACTERS
580 /* the QUIT and INTR character are used in process_send_signal
581 so set them here to something useful. */
582 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
583 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
584 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
585 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
586 #endif /* not SIGNALS_VIA_CHARACTERS */
589 /* Also, PTY overloads NUL and BREAK.
590 don't ignore break, but don't signal either, so it looks like NUL. */
591 s
.main
.c_iflag
&= ~IGNBRK
;
592 s
.main
.c_iflag
&= ~BRKINT
;
593 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
594 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
595 would force it to 0377. That looks like duplicated code. */
596 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
599 /* We originally enabled ICANON (and set VEOF to 04), and then had
600 process.c send additional EOF chars to flush the output when faced
601 with long lines, but this leads to weird effects when the
602 subprocess has disabled ICANON and ends up seeing those spurious
603 extra EOFs. So we don't send EOFs any more in
604 process.c:send_process. First we tried to disable ICANON by
605 default, so if a subsprocess sets up ICANON, it's his problem (or
606 the Elisp package that talks to it) to deal with lines that are
607 too long. But this disables some features, such as the ability
608 to send EOF signals. So we re-enabled ICANON but there is no
609 more "send eof to flush" going on (which is wrong and unportable
610 in itself). The correct way to handle too much output is to
611 buffer what could not be written and then write it again when
612 select returns ok for writing. This has it own set of
613 problems. Write is now asynchronous, is that a problem? How much
614 do we buffer, and what do we do when that limit is reached? */
616 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
617 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
618 #if 0 /* These settings only apply to non-ICANON mode. */
619 s
.main
.c_cc
[VMIN
] = 1;
620 s
.main
.c_cc
[VTIME
] = 0;
623 emacs_set_tty (out
, &s
, 0);
624 #endif /* not WINDOWSNT */
626 #endif /* not MSDOS */
629 /* Record a signal code and the action for it. */
633 struct sigaction action
;
636 static void save_signal_handlers (struct save_signal
*);
637 static void restore_signal_handlers (struct save_signal
*);
639 /* Suspend the Emacs process; give terminal to its superior. */
647 /* On a system where suspending is not implemented,
648 instead fork a subshell and let it talk directly to the terminal
655 /* Fork a subshell. */
660 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
663 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
665 char oldwd
[MAX_UTF8_PATH
];
671 struct save_signal saved_handlers
[5];
672 char *str
= SSDATA (encode_current_directory ());
678 char *volatile str_volatile
= str
;
685 error ("Can't spawn subshell");
687 saved_handlers
[0].code
= SIGINT
;
688 saved_handlers
[1].code
= SIGQUIT
;
689 saved_handlers
[2].code
= SIGTERM
;
691 saved_handlers
[3].code
= SIGIO
;
692 saved_handlers
[4].code
= 0;
694 saved_handlers
[3].code
= 0;
698 save_signal_handlers (saved_handlers
);
705 #ifdef DOS_NT /* MW, Aug 1993 */
706 getcwd (oldwd
, sizeof oldwd
);
708 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
711 sh
= egetenv ("SHELL");
715 /* Use our buffer's default directory for the subshell. */
716 if (chdir (str
) != 0)
720 _exit (EXIT_CANCELED
);
724 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
726 char *epwd
= getenv ("PWD");
727 char old_pwd
[MAXPATHLEN
+1+4];
729 /* If PWD is set, pass it with corrected value. */
732 strcpy (old_pwd
, epwd
);
733 setenv ("PWD", str
, 1);
736 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
738 putenv (old_pwd
); /* restore previous value */
740 #else /* not MSDOS */
742 /* Waits for process completion */
743 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
744 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
746 write (1, "Can't execute subshell", 22);
747 #else /* not WINDOWSNT */
748 execlp (sh
, sh
, (char *) 0);
750 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
751 #endif /* not WINDOWSNT */
752 #endif /* not MSDOS */
755 /* Do this now if we did not do it before. */
757 save_signal_handlers (saved_handlers
);
761 wait_for_termination (pid
, &status
, 0);
763 restore_signal_handlers (saved_handlers
);
767 save_signal_handlers (struct save_signal
*saved_handlers
)
769 while (saved_handlers
->code
)
771 struct sigaction action
;
772 emacs_sigaction_init (&action
, SIG_IGN
);
773 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
779 restore_signal_handlers (struct save_signal
*saved_handlers
)
781 while (saved_handlers
->code
)
783 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
789 static int old_fcntl_flags
[FD_SETSIZE
];
796 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
797 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
798 interrupts_deferred
= 0;
807 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
821 sigemptyset (&unblocked
);
823 sigaddset (&unblocked
, SIGWINCH
);
825 sigaddset (&unblocked
, SIGIO
);
826 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
828 interrupts_deferred
= 0;
833 unrequest_sigio (void)
841 sigemptyset (&blocked
);
843 sigaddset (&blocked
, SIGWINCH
);
845 sigaddset (&blocked
, SIGIO
);
846 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
847 interrupts_deferred
= 1;
855 block_child_signal (sigset_t
*oldset
)
858 sigemptyset (&blocked
);
859 sigaddset (&blocked
, SIGCHLD
);
860 sigaddset (&blocked
, SIGINT
);
861 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
864 /* Unblock SIGCHLD. */
867 unblock_child_signal (sigset_t
const *oldset
)
869 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
876 block_interrupt_signal (sigset_t
*oldset
)
879 sigemptyset (&blocked
);
880 sigaddset (&blocked
, SIGINT
);
881 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
884 /* Restore previously saved signal mask. */
886 restore_signal_mask (sigset_t
const *oldset
)
888 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
892 /* Saving and restoring the process group of Emacs's terminal. */
894 /* The process group of which Emacs was a member when it initially
897 If Emacs was in its own process group (i.e. inherited_pgroup ==
898 getpid ()), then we know we're running under a shell with job
899 control (Emacs would never be run as part of a pipeline).
902 If Emacs was not in its own process group, then we know we're
903 running under a shell (or a caller) that doesn't know how to
904 separate itself from Emacs (like sh). Emacs must be in its own
905 process group in order to receive SIGIO correctly. In this
906 situation, we put ourselves in our own pgroup, forcibly set the
907 tty's pgroup to our pgroup, and make sure to restore and reinstate
908 the tty's pgroup just like any other terminal setting. If
909 inherited_group was not the tty's pgroup, then we'll get a
910 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
911 it goes foreground in the future, which is what should happen. */
913 static pid_t inherited_pgroup
;
916 init_foreground_group (void)
918 pid_t pgrp
= getpgrp ();
919 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
922 /* Block and unblock SIGTTOU. */
925 block_tty_out_signal (sigset_t
*oldset
)
929 sigemptyset (&blocked
);
930 sigaddset (&blocked
, SIGTTOU
);
931 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
936 unblock_tty_out_signal (sigset_t
const *oldset
)
939 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
943 /* Safely set a controlling terminal FD's process group to PGID.
944 If we are not in the foreground already, POSIX requires tcsetpgrp
945 to deliver a SIGTTOU signal, which would stop us. This is an
946 annoyance, so temporarily ignore the signal.
948 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
949 skip all this unless SIGTTOU is defined. */
951 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
956 block_tty_out_signal (&oldset
);
957 tcsetpgrp (fd
, pgid
);
958 unblock_tty_out_signal (&oldset
);
963 /* Split off the foreground process group to Emacs alone. When we are
964 in the foreground, but not started in our own process group,
965 redirect the tty device handle FD to point to our own process
966 group. FD must be the file descriptor of the controlling tty. */
968 narrow_foreground_group (int fd
)
970 if (inherited_pgroup
&& setpgid (0, 0) == 0)
971 tcsetpgrp_without_stopping (fd
, getpid ());
974 /* Set the tty to our original foreground group. */
976 widen_foreground_group (int fd
)
978 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
979 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
982 /* Getting and setting emacs_tty structures. */
984 /* Set *TC to the parameters associated with the terminal FD,
985 or clear it if the parameters are not available.
986 Return 0 on success, -1 on failure. */
988 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
990 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
991 memset (&settings
->main
, 0, sizeof (settings
->main
));
994 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
997 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
999 settings
->main
= console_mode
;
1002 #endif /* WINDOWSNT */
1005 /* We have those nifty POSIX tcmumbleattr functions. */
1006 return tcgetattr (fd
, &settings
->main
);
1011 /* Set the parameters of the tty on FD according to the contents of
1012 *SETTINGS. If FLUSHP, discard input.
1013 Return 0 if all went well, and -1 (setting errno) if anything failed. */
1016 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
1018 /* Set the primary parameters - baud rate, character size, etcetera. */
1021 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
1023 if (h
&& h
!= INVALID_HANDLE_VALUE
)
1027 /* Assume the handle is open for input. */
1029 FlushConsoleInputBuffer (h
);
1030 new_mode
= settings
->main
;
1031 SetConsoleMode (h
, new_mode
);
1033 #endif /* WINDOWSNT */
1036 /* We have those nifty POSIX tcmumbleattr functions.
1037 William J. Smith <wjs@wiis.wang.com> writes:
1038 "POSIX 1003.1 defines tcsetattr to return success if it was
1039 able to perform any of the requested actions, even if some
1040 of the requested actions could not be performed.
1041 We must read settings back to ensure tty setup properly.
1042 AIX requires this to keep tty from hanging occasionally." */
1043 /* This make sure that we don't loop indefinitely in here. */
1044 for (i
= 0 ; i
< 10 ; i
++)
1045 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
1056 memset (&new, 0, sizeof (new));
1057 /* Get the current settings, and see if they're what we asked for. */
1058 tcgetattr (fd
, &new);
1059 /* We cannot use memcmp on the whole structure here because under
1060 * aix386 the termios structure has some reserved field that may
1063 if ( new.c_iflag
== settings
->main
.c_iflag
1064 && new.c_oflag
== settings
->main
.c_oflag
1065 && new.c_cflag
== settings
->main
.c_cflag
1066 && new.c_lflag
== settings
->main
.c_lflag
1067 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
1074 /* We have survived the tempest. */
1081 static int old_fcntl_owner
[FD_SETSIZE
];
1082 #endif /* F_SETOWN */
1084 /* Initialize the terminal mode on all tty devices that are currently
1088 init_all_sys_modes (void)
1090 struct tty_display_info
*tty
;
1091 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1092 init_sys_modes (tty
);
1095 /* Initialize the terminal mode on the given tty device. */
1098 init_sys_modes (struct tty_display_info
*tty_out
)
1100 struct emacs_tty tty
;
1102 Lisp_Object terminal
;
1105 Vtty_erase_char
= Qnil
;
1110 if (!tty_out
->output
)
1111 return; /* The tty is suspended. */
1113 narrow_foreground_group (fileno (tty_out
->input
));
1115 if (! tty_out
->old_tty
)
1116 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1118 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1120 tty
= *tty_out
->old_tty
;
1122 #if !defined (DOS_NT)
1123 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1125 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1126 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1127 #ifdef INLCR /* I'm just being cautious,
1128 since I can't check how widespread INLCR is--rms. */
1129 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1132 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1134 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1135 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1137 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1139 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1140 if (tty_out
->flow_control
)
1142 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1144 tty
.main
.c_iflag
&= ~IXANY
;
1148 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1149 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1151 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1153 if (tty_out
->meta_key
)
1155 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1156 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1160 XSETTERMINAL(terminal
, tty_out
->terminal
);
1161 if (!NILP (Fcontrolling_tty_p (terminal
)))
1163 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1164 /* Set up C-g for both SIGQUIT and SIGINT.
1165 We don't know which we will get, but we handle both alike
1166 so which one it really gives us does not matter. */
1167 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1171 /* We normally don't get interrupt or quit signals from tty
1172 devices other than our controlling terminal; therefore,
1173 we must handle C-g as normal input. Unfortunately, this
1174 means that the interrupt and quit feature must be
1175 disabled on secondary ttys, or we would not even see the
1178 Note that even though emacsclient could have special code
1179 to pass SIGINT to Emacs, we should _not_ enable
1180 interrupt/quit keys for emacsclient frames. This means
1181 that we can't break out of loops in C code from a
1182 secondary tty frame, but we can always decide what
1183 display the C-g came from, which is more important from a
1184 usability point of view. (Consider the case when two
1185 people work together using the same Emacs instance.) */
1186 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1187 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1189 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1190 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1192 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1197 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1200 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1201 #endif /* V_DSUSP */
1202 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1203 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1206 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1209 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1210 #endif /* VREPRINT */
1212 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1213 #endif /* VWERASE */
1215 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1216 #endif /* VDISCARD */
1218 if (tty_out
->flow_control
)
1221 tty
.main
.c_cc
[VSTART
] = '\021';
1224 tty
.main
.c_cc
[VSTOP
] = '\023';
1230 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1233 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1238 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1239 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1240 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1241 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1242 if (tty_out
->flow_control
)
1245 tty
.main
.c_cc
[VSTART
] = '\021';
1248 tty
.main
.c_cc
[VSTOP
] = '\023';
1251 /* Also, PTY overloads NUL and BREAK.
1252 don't ignore break, but don't signal either, so it looks like NUL.
1253 This really serves a purpose only if running in an XTERM window
1254 or via TELNET or the like, but does no harm elsewhere. */
1255 tty
.main
.c_iflag
&= ~IGNBRK
;
1256 tty
.main
.c_iflag
&= ~BRKINT
;
1258 #endif /* not DOS_NT */
1260 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1261 if (!tty_out
->term_initted
)
1262 internal_terminal_init ();
1263 dos_ttraw (tty_out
);
1266 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1268 /* This code added to insure that, if flow-control is not to be used,
1269 we have an unlocked terminal at the start. */
1272 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1275 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1278 #if !defined (DOS_NT)
1280 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1285 if (interrupt_input
)
1287 old_fcntl_owner
[fileno (tty_out
->input
)] =
1288 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1289 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1290 init_sigio (fileno (tty_out
->input
));
1292 if (gpm_tty
== tty_out
)
1294 /* Arrange for mouse events to give us SIGIO signals. */
1295 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1296 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1297 init_sigio (gpm_fd
);
1299 #endif /* HAVE_GPM */
1301 #endif /* F_GETOWN */
1303 setvbuf (tty_out
->output
, NULL
, _IOFBF
, BUFSIZ
);
1305 if (tty_out
->terminal
->set_terminal_modes_hook
)
1306 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1308 if (!tty_out
->term_initted
)
1310 Lisp_Object tail
, frame
;
1311 FOR_EACH_FRAME (tail
, frame
)
1313 /* XXX This needs to be revised. */
1314 if (FRAME_TERMCAP_P (XFRAME (frame
))
1315 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1316 init_frame_faces (XFRAME (frame
));
1320 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1322 /* We used to call "direct_output_forward_char(0)" here,
1323 but it's not clear why, since it may not do anything anyway. */
1327 Lisp_Object tail
, frame
;
1329 FOR_EACH_FRAME (tail
, frame
)
1331 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1332 || FRAME_MSDOS_P (XFRAME (frame
)))
1333 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1334 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1338 tty_out
->term_initted
= 1;
1341 /* Return true if safe to use tabs in output.
1342 At the time this is called, init_sys_modes has not been done yet. */
1345 tabs_safe_p (int fd
)
1347 struct emacs_tty etty
;
1349 emacs_get_tty (fd
, &etty
);
1352 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1353 #else /* not TABDLY */
1355 #endif /* not TABDLY */
1361 /* Discard echoing. */
1364 suppress_echo_on_tty (int fd
)
1366 struct emacs_tty etty
;
1368 emacs_get_tty (fd
, &etty
);
1370 /* Set raw input mode. */
1373 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1374 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1375 #endif /* ! WINDOWSNT */
1376 emacs_set_tty (fd
, &etty
, 0);
1379 /* Get terminal size from system.
1380 Store number of lines into *HEIGHTP and width into *WIDTHP.
1381 We store 0 if there's no valid information. */
1384 get_tty_size (int fd
, int *widthp
, int *heightp
)
1386 #if defined TIOCGWINSZ
1389 struct winsize size
;
1391 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1392 *widthp
= *heightp
= 0;
1395 *widthp
= size
.ws_col
;
1396 *heightp
= size
.ws_row
;
1399 #elif defined TIOCGSIZE
1401 /* SunOS - style. */
1402 struct ttysize size
;
1404 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1405 *widthp
= *heightp
= 0;
1408 *widthp
= size
.ts_cols
;
1409 *heightp
= size
.ts_lines
;
1412 #elif defined WINDOWSNT
1414 CONSOLE_SCREEN_BUFFER_INFO info
;
1415 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1417 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1418 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1421 *widthp
= *heightp
= 0;
1425 *widthp
= ScreenCols ();
1426 *heightp
= ScreenRows ();
1428 #else /* system doesn't know size */
1436 /* Set the logical window size associated with descriptor FD
1437 to HEIGHT and WIDTH. This is used mainly with ptys.
1438 Return a negative value on failure. */
1441 set_window_size (int fd
, int height
, int width
)
1446 struct winsize size
;
1447 size
.ws_row
= height
;
1448 size
.ws_col
= width
;
1450 return ioctl (fd
, TIOCSWINSZ
, &size
);
1455 /* SunOS - style. */
1456 struct ttysize size
;
1457 size
.ts_lines
= height
;
1458 size
.ts_cols
= width
;
1460 return ioctl (fd
, TIOCGSIZE
, &size
);
1463 #endif /* not SunOS-style */
1464 #endif /* not BSD-style */
1469 /* Prepare all terminal devices for exiting Emacs. */
1472 reset_all_sys_modes (void)
1474 struct tty_display_info
*tty
;
1475 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1476 reset_sys_modes (tty
);
1479 /* Prepare the terminal for closing it; move the cursor to the
1480 bottom of the frame, turn off interrupt-driven I/O, etc. */
1483 reset_sys_modes (struct tty_display_info
*tty_out
)
1490 if (!tty_out
->term_initted
)
1493 if (!tty_out
->output
)
1494 return; /* The tty is suspended. */
1496 /* Go to and clear the last line of the terminal. */
1498 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1500 /* Code adapted from tty_clear_end_of_line. */
1501 if (tty_out
->TS_clr_line
)
1503 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1506 { /* have to do it the hard way */
1507 tty_turn_off_insert (tty_out
);
1509 for (int i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1510 putc (' ', tty_out
->output
);
1513 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1514 fflush (tty_out
->output
);
1516 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1517 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1519 /* Avoid possible loss of output when changing terminal modes. */
1520 while (tcdrain (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1525 if (interrupt_input
)
1527 reset_sigio (fileno (tty_out
->input
));
1528 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1529 old_fcntl_owner
[fileno (tty_out
->input
)]);
1531 # endif /* F_SETOWN */
1532 fcntl (fileno (tty_out
->input
), F_SETFL
,
1533 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1536 if (tty_out
->old_tty
)
1537 while (emacs_set_tty (fileno (tty_out
->input
),
1538 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1541 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1545 widen_foreground_group (fileno (tty_out
->input
));
1550 /* Set up the proper status flags for use of a pty. */
1555 /* I'm told that TOICREMOTE does not mean control chars
1556 "can't be sent" but rather that they don't have
1557 input-editing or signaling effects.
1558 That should be good, because we have other ways
1559 to do those things in Emacs.
1560 However, telnet mode seems not to work on 4.2.
1561 So TIOCREMOTE is turned off now. */
1563 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1564 will hang. In particular, the "timeout" feature (which
1565 causes a read to return if there is no data available)
1566 does this. Also it is known that telnet mode will hang
1567 in such a way that Emacs must be stopped (perhaps this
1568 is the same problem).
1570 If TIOCREMOTE is turned off, then there is a bug in
1571 hp-ux which sometimes loses data. Apparently the
1572 code which blocks the master process when the internal
1573 buffer fills up does not work. Other than this,
1574 though, everything else seems to work fine.
1576 Since the latter lossage is more benign, we may as well
1577 lose that way. -- cph */
1579 #if defined (UNIX98_PTYS)
1582 ioctl (fd
, FIONBIO
, &on
);
1587 #endif /* HAVE_PTYS */
1590 init_system_name (void)
1594 /* Set system-name to nil so that the build is deterministic. */
1595 Vsystem_name
= Qnil
;
1598 char *hostname_alloc
= NULL
;
1600 #ifndef HAVE_GETHOSTNAME
1603 hostname
= uts
.nodename
;
1604 #else /* HAVE_GETHOSTNAME */
1605 char hostname_buf
[256];
1606 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1607 hostname
= hostname_buf
;
1609 /* Try to get the host name; if the buffer is too short, try
1610 again. Apparently, the only indication gethostname gives of
1611 whether the buffer was large enough is the presence or absence
1612 of a '\0' in the string. Eech. */
1615 gethostname (hostname
, hostname_size
- 1);
1616 hostname
[hostname_size
- 1] = '\0';
1618 /* Was the buffer large enough for the '\0'? */
1619 if (strlen (hostname
) < hostname_size
- 1)
1622 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1623 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1625 #endif /* HAVE_GETHOSTNAME */
1627 for (p
= hostname
; *p
; p
++)
1628 if (*p
== ' ' || *p
== '\t')
1630 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1631 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1632 Vsystem_name
= build_string (hostname
);
1633 xfree (hostname_alloc
);
1636 sigset_t empty_mask
;
1638 static struct sigaction process_fatal_action
;
1641 emacs_sigaction_flags (void)
1644 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1645 'select') to reset their timeout on some platforms (e.g.,
1646 HP-UX 11), which is not what we want. Also, when Emacs is
1647 interactive, we don't want SA_RESTART because we need to poll
1648 for pending input so we need long-running syscalls to be interrupted
1649 after a signal that sets pending_signals.
1651 Non-interactive keyboard input goes through stdio, where we
1652 always want restartable system calls. */
1659 /* Store into *ACTION a signal action suitable for Emacs, with handler
1662 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1664 sigemptyset (&action
->sa_mask
);
1666 /* When handling a signal, block nonfatal system signals that are caught
1667 by Emacs. This makes race conditions less likely. */
1668 sigaddset (&action
->sa_mask
, SIGALRM
);
1670 sigaddset (&action
->sa_mask
, SIGCHLD
);
1673 sigaddset (&action
->sa_mask
, SIGDANGER
);
1675 #ifdef PROFILER_CPU_SUPPORT
1676 sigaddset (&action
->sa_mask
, SIGPROF
);
1679 sigaddset (&action
->sa_mask
, SIGWINCH
);
1681 if (! noninteractive
)
1683 sigaddset (&action
->sa_mask
, SIGINT
);
1684 sigaddset (&action
->sa_mask
, SIGQUIT
);
1686 sigaddset (&action
->sa_mask
, SIGIO
);
1690 action
->sa_handler
= handler
;
1691 action
->sa_flags
= emacs_sigaction_flags ();
1694 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1695 static pthread_t main_thread_id
;
1698 /* SIG has arrived at the current process. Deliver it to the main
1699 thread, which should handle it with HANDLER. (Delivering the
1700 signal to some other thread might not work if the other thread is
1703 If we are on the main thread, handle the signal SIG with HANDLER.
1704 Otherwise, redirect the signal to the main thread, blocking it from
1705 this thread. POSIX says any thread can receive a signal that is
1706 associated with a process, process group, or asynchronous event.
1707 On GNU/Linux the main thread typically gets a process signal unless
1708 it's blocked, but other systems (FreeBSD at least) can deliver the
1709 signal to other threads. */
1711 deliver_process_signal (int sig
, signal_handler_t handler
)
1713 /* Preserve errno, to avoid race conditions with signal handlers that
1714 might change errno. Races can occur even in single-threaded hosts. */
1715 int old_errno
= errno
;
1717 bool on_main_thread
= true;
1718 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1719 if (! pthread_equal (pthread_self (), main_thread_id
))
1722 sigemptyset (&blocked
);
1723 sigaddset (&blocked
, sig
);
1724 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1725 pthread_kill (main_thread_id
, sig
);
1726 on_main_thread
= false;
1735 /* Static location to save a fatal backtrace in a thread.
1736 FIXME: If two subsidiary threads fail simultaneously, the resulting
1737 backtrace may be garbage. */
1738 enum { BACKTRACE_LIMIT_MAX
= 500 };
1739 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1740 static int thread_backtrace_npointers
;
1742 /* SIG has arrived at the current thread.
1743 If we are on the main thread, handle the signal SIG with HANDLER.
1744 Otherwise, this is a fatal error in the handling thread. */
1746 deliver_thread_signal (int sig
, signal_handler_t handler
)
1748 int old_errno
= errno
;
1750 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1751 if (! pthread_equal (pthread_self (), main_thread_id
))
1753 thread_backtrace_npointers
1754 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1755 sigaction (sig
, &process_fatal_action
, 0);
1756 pthread_kill (main_thread_id
, sig
);
1758 /* Avoid further damage while the main thread is exiting. */
1760 sigsuspend (&empty_mask
);
1768 #if !HAVE_DECL_SYS_SIGLIST
1770 # ifdef _sys_siglist
1771 # define sys_siglist _sys_siglist
1772 # elif HAVE_DECL___SYS_SIGLIST
1773 # define sys_siglist __sys_siglist
1775 # define sys_siglist my_sys_siglist
1776 static char const *sys_siglist
[NSIG
];
1781 # define sys_siglist_entries _sys_nsig
1783 # define sys_siglist_entries NSIG
1786 /* Handle bus errors, invalid instruction, etc. */
1788 handle_fatal_signal (int sig
)
1790 terminate_due_to_signal (sig
, 40);
1794 deliver_fatal_signal (int sig
)
1796 deliver_process_signal (sig
, handle_fatal_signal
);
1800 deliver_fatal_thread_signal (int sig
)
1802 deliver_thread_signal (sig
, handle_fatal_signal
);
1806 handle_arith_signal (int sig
)
1808 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1809 xsignal0 (Qarith_error
);
1812 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1814 /* Alternate stack used by SIGSEGV handler below. */
1816 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1819 /* Return true if SIGINFO indicates a stack overflow. */
1822 stack_overflow (siginfo_t
*siginfo
)
1824 if (!attempt_stack_overflow_recovery
)
1827 /* In theory, a more-accurate heuristic can be obtained by using
1828 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1829 and pthread_attr_getguardsize to find the location and size of the
1830 guard area. In practice, though, these functions are so hard to
1831 use reliably that they're not worth bothering with. E.g., see:
1832 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1833 Other operating systems also have problems, e.g., Solaris's
1834 stack_violation function is tailor-made for this problem, but it
1835 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1837 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1843 /* The faulting address. */
1844 char *addr
= siginfo
->si_addr
;
1848 /* The known top and bottom of the stack. The actual stack may
1849 extend a bit beyond these boundaries. */
1850 char const *bot
= stack_bottom
;
1851 char const *top
= current_thread
->stack_top
;
1853 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1854 of the known stack divided by the size of the guard area past the
1855 end of the stack top. The heuristic is that a bad address is
1856 considered to be a stack overflow if it occurs within
1857 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1858 stack. This heuristic is not exactly correct but it's good
1859 enough in practice. */
1860 enum { LG_STACK_HEURISTIC
= 8 };
1863 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1865 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1869 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1872 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1874 /* Hard GC error may lead to stack overflow caused by
1875 too nested calls to mark_object. No way to survive. */
1876 bool fatal
= gc_in_progress
;
1878 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1879 if (!fatal
&& !pthread_equal (pthread_self (), main_thread_id
))
1883 if (!fatal
&& stack_overflow (siginfo
))
1884 siglongjmp (return_to_command_loop
, 1);
1886 /* Otherwise we can't do anything with this. */
1887 deliver_fatal_thread_signal (sig
);
1890 /* Return true if we have successfully set up SIGSEGV handler on alternate
1891 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1896 struct sigaction sa
;
1899 ss
.ss_sp
= sigsegv_stack
;
1900 ss
.ss_size
= sizeof (sigsegv_stack
);
1902 if (sigaltstack (&ss
, NULL
) < 0)
1905 sigfillset (&sa
.sa_mask
);
1906 sa
.sa_sigaction
= handle_sigsegv
;
1907 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1908 if (sigaction (SIGSEGV
, &sa
, NULL
) < 0)
1914 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1922 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1925 deliver_arith_signal (int sig
)
1927 deliver_thread_signal (sig
, handle_arith_signal
);
1932 /* Handler for SIGDANGER. */
1934 handle_danger_signal (int sig
)
1936 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1938 /* It might be unsafe to call do_auto_save now. */
1939 force_auto_save_soon ();
1943 deliver_danger_signal (int sig
)
1945 deliver_process_signal (sig
, handle_danger_signal
);
1949 /* Treat SIG as a terminating signal, unless it is already ignored and
1950 we are in --batch mode. Among other things, this makes nohup work. */
1952 maybe_fatal_sig (int sig
)
1954 bool catch_sig
= !noninteractive
;
1957 struct sigaction old_action
;
1958 sigaction (sig
, 0, &old_action
);
1959 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1962 sigaction (sig
, &process_fatal_action
, 0);
1968 struct sigaction thread_fatal_action
;
1969 struct sigaction action
;
1971 sigemptyset (&empty_mask
);
1973 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1974 main_thread_id
= pthread_self ();
1977 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1980 sys_siglist
[SIGABRT
] = "Aborted";
1982 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1984 sys_siglist
[SIGALRM
] = "Alarm clock";
1986 sys_siglist
[SIGBUS
] = "Bus error";
1989 sys_siglist
[SIGCHLD
] = "Child status changed";
1992 sys_siglist
[SIGCONT
] = "Continued";
1995 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1998 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
2001 sys_siglist
[SIGEMT
] = "Emulation trap";
2003 sys_siglist
[SIGFPE
] = "Arithmetic exception";
2005 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
2008 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
2010 sys_siglist
[SIGHUP
] = "Hangup";
2011 sys_siglist
[SIGILL
] = "Illegal instruction";
2012 sys_siglist
[SIGINT
] = "Interrupt";
2014 sys_siglist
[SIGIO
] = "I/O possible";
2017 sys_siglist
[SIGIOINT
] = "I/O intervention required";
2020 sys_siglist
[SIGIOT
] = "IOT trap";
2022 sys_siglist
[SIGKILL
] = "Killed";
2024 sys_siglist
[SIGLOST
] = "Resource lost";
2027 sys_siglist
[SIGLWP
] = "SIGLWP";
2030 sys_siglist
[SIGMSG
] = "Monitor mode data available";
2033 sys_siglist
[SIGWIND
] = "SIGPHONE";
2035 sys_siglist
[SIGPIPE
] = "Broken pipe";
2037 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
2040 sys_siglist
[SIGPROF
] = "Profiling timer expired";
2043 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
2046 sys_siglist
[SIGPWR
] = "Power-fail restart";
2048 sys_siglist
[SIGQUIT
] = "Quit";
2050 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
2053 sys_siglist
[SIGSAK
] = "Secure attention";
2055 sys_siglist
[SIGSEGV
] = "Segmentation violation";
2057 sys_siglist
[SIGSOUND
] = "Sound completed";
2060 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
2063 sys_siglist
[SIGSTP
] = "Stopped (user)";
2066 sys_siglist
[SIGSYS
] = "Bad argument to system call";
2068 sys_siglist
[SIGTERM
] = "Terminated";
2070 sys_siglist
[SIGTHAW
] = "SIGTHAW";
2073 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
2076 sys_siglist
[SIGTSTP
] = "Stopped (user)";
2079 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
2082 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
2085 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2088 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2091 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2094 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2097 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2100 sys_siglist
[SIGWINCH
] = "Window size changed";
2103 sys_siglist
[SIGWIND
] = "SIGWIND";
2106 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2109 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2112 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2114 /* Don't alter signal handlers if dumping. On some machines,
2115 changing signal handlers sets static data that would make signals
2116 fail to work right when the dumped Emacs is run. */
2120 sigfillset (&process_fatal_action
.sa_mask
);
2121 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2122 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2124 sigfillset (&thread_fatal_action
.sa_mask
);
2125 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2126 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2128 /* SIGINT may need special treatment on MS-Windows. See
2129 https://lists.gnu.org/r/emacs-devel/2010-09/msg01062.html
2130 Please update the doc of kill-emacs, kill-emacs-hook, and
2131 NEWS if you change this. */
2133 maybe_fatal_sig (SIGHUP
);
2134 maybe_fatal_sig (SIGINT
);
2135 maybe_fatal_sig (SIGTERM
);
2137 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2138 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2139 to behave more like typical batch applications do. */
2140 if (! noninteractive
)
2141 signal (SIGPIPE
, SIG_IGN
);
2143 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2144 sigaction (SIGILL
, &thread_fatal_action
, 0);
2145 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2147 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2148 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2149 interpreter's floating point operations, so treat SIGFPE as an
2150 arith-error if it arises in the main thread. */
2151 if (IEEE_FLOATING_POINT
)
2152 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2155 emacs_sigaction_init (&action
, deliver_arith_signal
);
2156 sigaction (SIGFPE
, &action
, 0);
2160 add_user_signal (SIGUSR1
, "sigusr1");
2163 add_user_signal (SIGUSR2
, "sigusr2");
2165 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2167 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2170 sigaction (SIGORE
, &thread_fatal_action
, 0);
2173 sigaction (SIGUME
, &thread_fatal_action
, 0);
2176 sigaction (SIGDLK
, &process_fatal_action
, 0);
2179 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2182 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2185 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2188 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2190 if (!init_sigsegv ())
2191 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2193 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2195 sigaction (SIGTERM
, &process_fatal_action
, 0);
2197 signal (SIGPROF
, SIG_IGN
);
2200 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2203 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2206 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2210 /* This just means available memory is getting low. */
2211 emacs_sigaction_init (&action
, deliver_danger_signal
);
2212 sigaction (SIGDANGER
, &action
, 0);
2215 /* AIX-specific signals. */
2217 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2220 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2223 sigaction (SIGMSG
, &process_fatal_action
, 0);
2226 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2229 sigaction (SIGSAK
, &process_fatal_action
, 0);
2232 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2235 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2245 /* Figure out how many bits the system's random number generator uses.
2246 `random' and `lrand48' are assumed to return 31 usable bits.
2247 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2248 so we'll shift it and treat it like the 15-bit USG `rand'. */
2252 # define RAND_BITS 31
2253 # else /* !HAVE_RANDOM */
2254 # ifdef HAVE_LRAND48
2255 # define RAND_BITS 31
2256 # define random lrand48
2257 # else /* !HAVE_LRAND48 */
2258 # define RAND_BITS 15
2259 # if RAND_MAX == 32767
2260 # define random rand
2261 # else /* RAND_MAX != 32767 */
2262 # if RAND_MAX == 2147483647
2263 # define random() (rand () >> 16)
2264 # else /* RAND_MAX != 2147483647 */
2266 # define random rand
2268 # define random() (rand () >> 16)
2270 # endif /* RAND_MAX != 2147483647 */
2271 # endif /* RAND_MAX != 32767 */
2272 # endif /* !HAVE_LRAND48 */
2273 # endif /* !HAVE_RANDOM */
2274 #endif /* !RAND_BITS */
2277 typedef unsigned int random_seed
;
2278 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2279 #elif defined HAVE_LRAND48
2280 /* Although srand48 uses a long seed, this is unsigned long to avoid
2281 undefined behavior on signed integer overflow in init_random. */
2282 typedef unsigned long int random_seed
;
2283 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2285 typedef unsigned int random_seed
;
2286 static void set_random_seed (random_seed arg
) { srand (arg
); }
2290 seed_random (void *seed
, ptrdiff_t seed_size
)
2292 random_seed arg
= 0;
2293 unsigned char *argp
= (unsigned char *) &arg
;
2294 unsigned char *seedp
= seed
;
2295 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2296 argp
[i
% sizeof arg
] ^= seedp
[i
];
2297 set_random_seed (arg
);
2304 bool success
= false;
2306 /* First, try seeding the PRNG from the operating system's entropy
2307 source. This approach is both fast and secure. */
2309 success
= w32_init_random (&v
, sizeof v
) == 0;
2311 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2314 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2319 /* If that didn't work, try using GnuTLS, which is secure, but on
2320 some systems, can be somewhat slow. */
2322 success
= EQ (emacs_gnutls_global_init (), Qt
)
2323 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2325 /* If _that_ didn't work, just use the current time value and PID.
2326 It's at least better than XKCD 221. */
2329 struct timespec t
= current_timespec ();
2330 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2333 set_random_seed (v
);
2337 * Return a nonnegative random integer out of whatever we've got.
2338 * It contains enough bits to make a random (signed) Emacs fixnum.
2339 * This suffices even for a 64-bit architecture with a 15-bit rand.
2346 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2347 val
= (random () ^ (val
<< RAND_BITS
)
2348 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2349 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2350 return val
& INTMASK
;
2353 #ifndef HAVE_SNPRINTF
2354 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2356 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2358 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2359 ptrdiff_t nbytes
= size
- 1;
2364 va_start (ap
, format
);
2365 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2369 if (nbytes
== size
- 1)
2371 /* Calculate the length of the string that would have been created
2372 had the buffer been large enough. */
2373 char stackbuf
[4000];
2375 ptrdiff_t bsize
= sizeof stackbuf
;
2376 va_start (ap
, format
);
2377 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2383 if (INT_MAX
< nbytes
)
2396 /* If a backtrace is available, output the top lines of it to stderr.
2397 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2398 This function may be called from a signal handler, so it should
2399 not invoke async-unsafe functions like malloc.
2401 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2402 but do not output anything. This avoids some problems that can
2403 otherwise occur if the malloc arena is corrupted before 'backtrace'
2404 is called, since 'backtrace' may call malloc if the tables are not
2407 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2408 fatal error has occurred in some other thread; generate a thread
2409 backtrace instead, ignoring BACKTRACE_LIMIT. */
2411 emacs_backtrace (int backtrace_limit
)
2413 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2414 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2418 if (thread_backtrace_npointers
)
2420 buffer
= thread_backtrace_buffer
;
2421 npointers
= thread_backtrace_npointers
;
2425 buffer
= main_backtrace_buffer
;
2427 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2428 if (bounded_limit
< 0)
2430 backtrace (buffer
, 1);
2434 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2439 emacs_write (STDERR_FILENO
, "Backtrace:\n", 11);
2440 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2441 if (bounded_limit
< npointers
)
2442 emacs_write (STDERR_FILENO
, "...\n", 4);
2450 terminate_due_to_signal (SIGABRT
, 40);
2454 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2455 Use binary I/O on systems that care about text vs binary I/O.
2456 Arrange for subprograms to not inherit the file descriptor.
2457 Prefer a method that is multithread-safe, if available.
2458 Do not fail merely because the open was interrupted by a signal.
2459 Allow the user to quit. */
2462 emacs_open (const char *file
, int oflags
, int mode
)
2465 if (! (oflags
& O_TEXT
))
2467 oflags
|= O_CLOEXEC
;
2468 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2473 /* Open FILE as a stream for Emacs use, with mode MODE.
2474 Act like emacs_open with respect to threads, signals, and quits. */
2477 emacs_fopen (char const *file
, char const *mode
)
2479 int fd
, omode
, oflags
;
2481 char const *m
= mode
;
2485 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2486 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2487 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2488 default: emacs_abort ();
2494 case '+': omode
= O_RDWR
; break;
2495 case 't': bflag
= O_TEXT
; break;
2496 default: /* Ignore. */ break;
2499 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2500 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2503 /* Create a pipe for Emacs use. */
2506 emacs_pipe (int fd
[2])
2511 return pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2515 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2516 For the background behind this mess, please see Austin Group defect 529
2517 <http://austingroupbugs.net/view.php?id=529>. */
2519 #ifndef POSIX_CLOSE_RESTART
2520 # define POSIX_CLOSE_RESTART 1
2522 posix_close (int fd
, int flag
)
2524 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2525 eassert (flag
== POSIX_CLOSE_RESTART
);
2527 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2528 on a system that does not define POSIX_CLOSE_RESTART.
2530 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2531 closed, and retrying the close could inadvertently close a file
2532 descriptor allocated by some other thread. In other systems
2533 (e.g., HP/UX) FD is not closed. And in still other systems
2534 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2535 multithreaded program there can be no way to tell.
2537 So, in this case, pretend that the close succeeded. This works
2538 well on systems like GNU/Linux that close FD. Although it may
2539 leak a file descriptor on other systems, the leak is unlikely and
2540 it's better to leak than to close a random victim. */
2541 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2545 /* Close FD, retrying if interrupted. If successful, return 0;
2546 otherwise, return -1 and set errno to a non-EINTR value. Consider
2547 an EINPROGRESS error to be successful, as that's merely a signal
2548 arriving. FD is always closed when this function returns, even
2551 Do not call this function if FD is nonnegative and might already be closed,
2552 as that might close an innocent victim opened by some other thread. */
2555 emacs_close (int fd
)
2559 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2562 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2564 eassert (errno
!= EBADF
|| fd
< 0);
2565 return errno
== EINPROGRESS
? 0 : r
;
2570 /* Maximum number of bytes to read or write in a single system call.
2571 This works around a serious bug in Linux kernels before 2.6.16; see
2572 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2573 It's likely to work around similar bugs in other operating systems, so do it
2574 on all platforms. Round INT_MAX down to a page size, with the conservative
2575 assumption that page sizes are at most 2**18 bytes (any kernel with a
2576 page size larger than that shouldn't have the bug). */
2577 #ifndef MAX_RW_COUNT
2578 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2581 /* Verify that MAX_RW_COUNT fits in the relevant standard types. */
2583 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
2585 verify (MAX_RW_COUNT
<= PTRDIFF_MAX
);
2586 verify (MAX_RW_COUNT
<= SIZE_MAX
);
2587 verify (MAX_RW_COUNT
<= SSIZE_MAX
);
2590 /* Verify that Emacs read requests cannot cause trouble, even in
2591 64-bit builds. The last argument of 'read' is 'unsigned int', and
2592 the return value's type (see 'sys_read') is 'int'. */
2593 verify (MAX_RW_COUNT
<= INT_MAX
);
2594 verify (MAX_RW_COUNT
<= UINT_MAX
);
2597 /* Read from FD to a buffer BUF with size NBYTE.
2598 If interrupted, process any quits and pending signals immediately
2599 if INTERRUPTIBLE, and then retry the read unless quitting.
2600 Return the number of bytes read, which might be less than NBYTE.
2601 On error, set errno to a value other than EINTR, and return -1. */
2603 emacs_intr_read (int fd
, void *buf
, ptrdiff_t nbyte
, bool interruptible
)
2605 /* No caller should ever pass a too-large size to emacs_read. */
2606 eassert (nbyte
<= MAX_RW_COUNT
);
2614 result
= read (fd
, buf
, nbyte
);
2616 while (result
< 0 && errno
== EINTR
);
2621 /* Read from FD to a buffer BUF with size NBYTE.
2622 If interrupted, retry the read. Return the number of bytes read,
2623 which might be less than NBYTE. On error, set errno to a value
2624 other than EINTR, and return -1. */
2626 emacs_read (int fd
, void *buf
, ptrdiff_t nbyte
)
2628 return emacs_intr_read (fd
, buf
, nbyte
, false);
2631 /* Like emacs_read, but also process quits and pending signals. */
2633 emacs_read_quit (int fd
, void *buf
, ptrdiff_t nbyte
)
2635 return emacs_intr_read (fd
, buf
, nbyte
, true);
2638 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2639 interrupted or if a partial write occurs. Process any quits
2640 immediately if INTERRUPTIBLE is positive, and process any pending
2641 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2642 of bytes written; if this is less than NBYTE, set errno to a value
2643 other than EINTR. */
2645 emacs_full_write (int fd
, char const *buf
, ptrdiff_t nbyte
,
2648 ptrdiff_t bytes_written
= 0;
2652 ssize_t n
= write (fd
, buf
, min (nbyte
, MAX_RW_COUNT
));
2661 if (0 < interruptible
)
2663 if (pending_signals
)
2664 process_pending_signals ();
2675 return bytes_written
;
2678 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2679 interrupted or if a partial write occurs. Do not process quits or
2680 pending signals. Return the number of bytes written, setting errno
2681 if this is less than NBYTE. */
2683 emacs_write (int fd
, void const *buf
, ptrdiff_t nbyte
)
2685 return emacs_full_write (fd
, buf
, nbyte
, 0);
2688 /* Like emacs_write, but also process pending signals. */
2690 emacs_write_sig (int fd
, void const *buf
, ptrdiff_t nbyte
)
2692 return emacs_full_write (fd
, buf
, nbyte
, -1);
2695 /* Like emacs_write, but also process quits and pending signals. */
2697 emacs_write_quit (int fd
, void const *buf
, ptrdiff_t nbyte
)
2699 return emacs_full_write (fd
, buf
, nbyte
, 1);
2702 /* Write a diagnostic to standard error that contains MESSAGE and a
2703 string derived from errno. Preserve errno. Do not buffer stderr.
2704 Do not process quits or pending signals if interrupted. */
2706 emacs_perror (char const *message
)
2709 char const *error_string
= emacs_strerror (err
);
2710 char const *command
= (initial_argv
&& initial_argv
[0]
2711 ? initial_argv
[0] : "emacs");
2712 /* Write it out all at once, if it's short; this is less likely to
2713 be interleaved with other output. */
2714 char buf
[min (PIPE_BUF
, MAX_ALLOCA
)];
2715 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2716 command
, message
, error_string
);
2717 if (0 <= nbytes
&& nbytes
< sizeof buf
)
2718 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2721 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2722 emacs_write (STDERR_FILENO
, ": ", 2);
2723 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2724 emacs_write (STDERR_FILENO
, ": ", 2);
2725 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2726 emacs_write (STDERR_FILENO
, "\n", 1);
2731 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2732 ATIME and MTIME, respectively.
2733 FD must be either negative -- in which case it is ignored --
2734 or a file descriptor that is open on FILE.
2735 If FD is nonnegative, then FILE can be NULL. */
2737 set_file_times (int fd
, const char *filename
,
2738 struct timespec atime
, struct timespec mtime
)
2740 struct timespec timespec
[2];
2741 timespec
[0] = atime
;
2742 timespec
[1] = mtime
;
2743 return fdutimens (fd
, filename
, timespec
);
2746 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2747 This is like renameat except that it fails if DST already exists,
2748 or if this operation is not supported atomically. Return 0 if
2749 successful, -1 (setting errno) otherwise. */
2751 renameat_noreplace (int srcfd
, char const *src
, int dstfd
, char const *dst
)
2753 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2754 return syscall (SYS_renameat2
, srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2755 #elif defined CYGWIN && defined RENAME_NOREPLACE
2756 return renameat2 (srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2757 #elif defined RENAME_EXCL
2758 return renameatx_np (srcfd
, src
, dstfd
, dst
, RENAME_EXCL
);
2761 if (srcfd
== AT_FDCWD
&& dstfd
== AT_FDCWD
)
2762 return sys_rename_replace (src
, dst
, 0);
2769 /* Like strsignal, except async-signal-safe, and this function typically
2770 returns a string in the C locale rather than the current locale. */
2772 safe_strsignal (int code
)
2774 char const *signame
= 0;
2776 if (0 <= code
&& code
< sys_siglist_entries
)
2777 signame
= sys_siglist
[code
];
2779 signame
= "Unknown signal";
2784 /* Output to stderr. */
2786 /* Return the error output stream. */
2793 fflush_unlocked (stderr
);
2797 /* These functions are like fputc, vfprintf, and fwrite,
2798 except that they output to stderr and buffer better on
2799 platforms that support line buffering. This avoids interleaving
2800 output when Emacs and other processes write to stderr
2801 simultaneously, so long as the lines are short enough. When a
2802 single diagnostic is emitted via a sequence of calls of one or more
2803 of these functions, the caller should arrange for the last called
2804 function to output a newline at the end. */
2809 fputc_unlocked (c
, errstream ());
2813 verrprintf (char const *fmt
, va_list ap
)
2815 vfprintf (errstream (), fmt
, ap
);
2819 errwrite (void const *buf
, ptrdiff_t nbuf
)
2821 fwrite_unlocked (buf
, 1, nbuf
, errstream ());
2824 /* Close standard output and standard error, reporting any write
2825 errors as best we can. This is intended for use with atexit. */
2827 close_output_streams (void)
2829 if (close_stream (stdout
) != 0)
2831 emacs_perror ("Write error to standard output");
2832 _exit (EXIT_FAILURE
);
2835 /* Do not close stderr if addresses are being sanitized, as the
2836 sanitizer might report to stderr after this function is invoked. */
2837 bool err
= buferr
&& (fflush (buferr
) != 0 || ferror (buferr
));
2838 if (err
| (ADDRESS_SANITIZER
2839 ? fflush (stderr
) != 0 || ferror (stderr
)
2840 : close_stream (stderr
) != 0))
2841 _exit (EXIT_FAILURE
);
2845 /* For make-serial-process */
2847 serial_open (Lisp_Object port
)
2849 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2851 report_file_error ("Opening serial port", port
);
2853 ioctl (fd
, TIOCEXCL
, (char *) 0);
2859 #if !defined (HAVE_CFMAKERAW)
2860 /* Workaround for targets which are missing cfmakeraw. */
2861 /* Pasted from man page. */
2863 cfmakeraw (struct termios
*termios_p
)
2865 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2866 termios_p
->c_oflag
&= ~OPOST
;
2867 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2868 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2869 termios_p
->c_cflag
|= CS8
;
2871 #endif /* !defined (HAVE_CFMAKERAW */
2873 #if !defined (HAVE_CFSETSPEED)
2874 /* Workaround for targets which are missing cfsetspeed. */
2876 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2878 return (cfsetispeed (termios_p
, vitesse
)
2879 + cfsetospeed (termios_p
, vitesse
));
2883 /* For serial-process-configure */
2885 serial_configure (struct Lisp_Process
*p
,
2886 Lisp_Object contact
)
2888 Lisp_Object childp2
= Qnil
;
2889 Lisp_Object tem
= Qnil
;
2890 struct termios attr
;
2892 char summary
[4] = "???"; /* This usually becomes "8N1". */
2894 childp2
= Fcopy_sequence (p
->childp
);
2896 /* Read port attributes and prepare default configuration. */
2897 err
= tcgetattr (p
->outfd
, &attr
);
2899 report_file_error ("Failed tcgetattr", Qnil
);
2901 #if defined (CLOCAL)
2902 attr
.c_cflag
|= CLOCAL
;
2905 attr
.c_cflag
|= CREAD
;
2908 /* Configure speed. */
2909 if (!NILP (Fplist_member (contact
, QCspeed
)))
2910 tem
= Fplist_get (contact
, QCspeed
);
2912 tem
= Fplist_get (p
->childp
, QCspeed
);
2914 err
= cfsetspeed (&attr
, XFIXNUM (tem
));
2916 report_file_error ("Failed cfsetspeed", tem
);
2917 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2919 /* Configure bytesize. */
2920 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2921 tem
= Fplist_get (contact
, QCbytesize
);
2923 tem
= Fplist_get (p
->childp
, QCbytesize
);
2925 tem
= make_fixnum (8);
2927 if (XFIXNUM (tem
) != 7 && XFIXNUM (tem
) != 8)
2928 error (":bytesize must be nil (8), 7, or 8");
2929 summary
[0] = XFIXNUM (tem
) + '0';
2930 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2931 attr
.c_cflag
&= ~CSIZE
;
2932 attr
.c_cflag
|= ((XFIXNUM (tem
) == 7) ? CS7
: CS8
);
2934 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2935 if (XFIXNUM (tem
) != 8)
2936 error ("Bytesize cannot be changed");
2938 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2940 /* Configure parity. */
2941 if (!NILP (Fplist_member (contact
, QCparity
)))
2942 tem
= Fplist_get (contact
, QCparity
);
2944 tem
= Fplist_get (p
->childp
, QCparity
);
2945 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2946 error (":parity must be nil (no parity), `even', or `odd'");
2947 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2948 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2949 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2954 else if (EQ (tem
, Qeven
))
2957 attr
.c_cflag
|= PARENB
;
2958 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2960 else if (EQ (tem
, Qodd
))
2963 attr
.c_cflag
|= (PARENB
| PARODD
);
2964 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2967 /* Don't error on no parity, which should be set by cfmakeraw. */
2969 error ("Parity cannot be configured");
2971 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2973 /* Configure stopbits. */
2974 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2975 tem
= Fplist_get (contact
, QCstopbits
);
2977 tem
= Fplist_get (p
->childp
, QCstopbits
);
2979 tem
= make_fixnum (1);
2981 if (XFIXNUM (tem
) != 1 && XFIXNUM (tem
) != 2)
2982 error (":stopbits must be nil (1 stopbit), 1, or 2");
2983 summary
[2] = XFIXNUM (tem
) + '0';
2984 #if defined (CSTOPB)
2985 attr
.c_cflag
&= ~CSTOPB
;
2986 if (XFIXNUM (tem
) == 2)
2987 attr
.c_cflag
|= CSTOPB
;
2989 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2990 if (XFIXNUM (tem
) != 1)
2991 error ("Stopbits cannot be configured");
2993 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2995 /* Configure flowcontrol. */
2996 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2997 tem
= Fplist_get (contact
, QCflowcontrol
);
2999 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
3000 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
3001 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
3002 #if defined (CRTSCTS)
3003 attr
.c_cflag
&= ~CRTSCTS
;
3005 #if defined (CNEW_RTSCTS)
3006 attr
.c_cflag
&= ~CNEW_RTSCTS
;
3008 #if defined (IXON) && defined (IXOFF)
3009 attr
.c_iflag
&= ~(IXON
| IXOFF
);
3013 /* Already configured. */
3015 else if (EQ (tem
, Qhw
))
3017 #if defined (CRTSCTS)
3018 attr
.c_cflag
|= CRTSCTS
;
3019 #elif defined (CNEW_RTSCTS)
3020 attr
.c_cflag
|= CNEW_RTSCTS
;
3022 error ("Hardware flowcontrol (RTS/CTS) not supported");
3025 else if (EQ (tem
, Qsw
))
3027 #if defined (IXON) && defined (IXOFF)
3028 attr
.c_iflag
|= (IXON
| IXOFF
);
3030 error ("Software flowcontrol (XON/XOFF) not supported");
3033 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
3035 /* Activate configuration. */
3036 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
3038 report_file_error ("Failed tcsetattr", Qnil
);
3040 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
3041 pset_childp (p
, childp2
);
3043 #endif /* not DOS_NT */
3045 /* System depended enumeration of and access to system processes a-la ps(1). */
3049 /* Process enumeration and access via /proc. */
3052 list_system_processes (void)
3054 Lisp_Object procdir
, match
, proclist
, next
;
3057 /* For every process on the system, there's a directory in the
3058 "/proc" pseudo-directory whose name is the numeric ID of that
3060 procdir
= build_string ("/proc");
3061 match
= build_string ("[0-9]+");
3062 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, false, Qnil
);
3064 /* `proclist' gives process IDs as strings. Destructively convert
3065 each string into a number. */
3066 for (tail
= proclist
; CONSP (tail
); tail
= next
)
3069 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
3072 /* directory_files_internal returns the files in reverse order; undo
3074 proclist
= Fnreverse (proclist
);
3078 #elif defined DARWIN_OS || defined __FreeBSD__
3081 list_system_processes (void)
3084 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
3086 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
3089 struct kinfo_proc
*procs
;
3092 Lisp_Object proclist
= Qnil
;
3094 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0 || len
== 0)
3097 procs
= xmalloc (len
);
3098 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0 || len
== 0)
3104 len
/= sizeof (struct kinfo_proc
);
3105 for (i
= 0; i
< len
; i
++)
3108 proclist
= Fcons (INT_TO_INTEGER (procs
[i
].kp_proc
.p_pid
), proclist
);
3110 proclist
= Fcons (INT_TO_INTEGER (procs
[i
].ki_pid
), proclist
);
3119 /* The WINDOWSNT implementation is in w32.c.
3120 The MSDOS implementation is in dosfns.c. */
3121 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3124 list_system_processes (void)
3129 #endif /* !defined (WINDOWSNT) */
3132 #if defined __FreeBSD__ || defined DARWIN_OS
3134 static struct timespec
3135 timeval_to_timespec (struct timeval t
)
3137 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3140 make_lisp_timeval (struct timeval t
)
3142 return make_lisp_time (timeval_to_timespec (t
));
3147 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3148 static struct timespec
3149 time_from_jiffies (unsigned long long tval
, long hz
)
3151 unsigned long long s
= tval
/ hz
;
3152 unsigned long long frac
= tval
% hz
;
3155 if (TYPE_MAXIMUM (time_t) < s
)
3157 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_HZ
3158 || frac
<= ULLONG_MAX
/ TIMESPEC_HZ
)
3159 ns
= frac
* TIMESPEC_HZ
/ hz
;
3162 /* This is reachable only in the unlikely case that HZ * HZ
3163 exceeds ULLONG_MAX. It calculates an approximation that is
3164 guaranteed to be in range. */
3165 long hz_per_ns
= hz
/ TIMESPEC_HZ
+ (hz
% TIMESPEC_HZ
!= 0);
3166 ns
= frac
/ hz_per_ns
;
3169 return make_timespec (s
, ns
);
3173 ltime_from_jiffies (unsigned long long tval
, long hz
)
3175 struct timespec t
= time_from_jiffies (tval
, hz
);
3176 return make_lisp_time (t
);
3179 static struct timespec
3183 struct timespec up
= make_timespec (0, 0);
3186 fup
= emacs_fopen ("/proc/uptime", "r");
3190 unsigned long long upsec
, upfrac
;
3191 int upfrac_start
, upfrac_end
;
3193 if (fscanf (fup
, "%llu.%n%llu%n",
3194 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
)
3197 if (TYPE_MAXIMUM (time_t) < upsec
)
3199 upsec
= TYPE_MAXIMUM (time_t);
3200 upfrac
= TIMESPEC_HZ
- 1;
3204 int upfraclen
= upfrac_end
- upfrac_start
;
3205 for (; upfraclen
< LOG10_TIMESPEC_HZ
; upfraclen
++)
3207 for (; LOG10_TIMESPEC_HZ
< upfraclen
; upfraclen
--)
3209 upfrac
= min (upfrac
, TIMESPEC_HZ
- 1);
3211 up
= make_timespec (upsec
, upfrac
);
3220 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3221 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3224 procfs_ttyname (int rdev
)
3227 char name
[PATH_MAX
];
3230 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3236 unsigned long minor_beg
, minor_end
;
3237 char minor
[25]; /* 2 32-bit numbers + dash */
3240 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3242 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3243 && major
== MAJOR (rdev
))
3245 minor_beg
= strtoul (minor
, &endp
, 0);
3247 minor_end
= minor_beg
;
3248 else if (*endp
== '-')
3249 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3253 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3255 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3263 return build_string (name
);
3267 procfs_get_total_memory (void)
3270 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3274 fmem
= emacs_fopen ("/proc/meminfo", "r");
3278 uintmax_t entry_value
;
3282 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3285 retval
= entry_value
;
3290 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3308 system_process_attributes (Lisp_Object pid
)
3310 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3314 long clocks_per_sec
;
3316 char procbuf
[1025], *p
, *q UNINIT
;
3319 static char const default_cmd
[] = "???";
3320 const char *cmd
= default_cmd
;
3321 int cmdsize
= sizeof default_cmd
- 1;
3322 char *cmdline
= NULL
;
3323 ptrdiff_t cmdline_size
;
3326 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3329 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3330 long priority
, niceness
, rss
;
3331 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3332 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3334 Lisp_Object attrs
= Qnil
;
3335 Lisp_Object decoded_cmd
;
3339 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3340 sprintf (procfn
, "/proc/%"PRIdMAX
, proc_id
);
3341 if (stat (procfn
, &st
) < 0)
3346 attrs
= Fcons (Fcons (Qeuid
, INT_TO_INTEGER (uid
)), attrs
);
3348 pw
= getpwuid (uid
);
3351 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3354 attrs
= Fcons (Fcons (Qegid
, INT_TO_INTEGER (gid
)), attrs
);
3356 gr
= getgrgid (gid
);
3359 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3361 count
= SPECPDL_INDEX ();
3362 strcpy (fn
, procfn
);
3363 procfn_end
= fn
+ strlen (fn
);
3364 strcpy (procfn_end
, "/stat");
3365 fd
= emacs_open (fn
, O_RDONLY
, 0);
3370 record_unwind_protect_int (close_file_unwind
, fd
);
3371 nread
= emacs_read_quit (fd
, procbuf
, sizeof procbuf
- 1);
3375 procbuf
[nread
] = '\0';
3378 p
= strchr (p
, '(');
3381 q
= strrchr (p
+ 1, ')');
3391 /* Command name is encoded in locale-coding-system; decode it. */
3392 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3393 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3394 Vlocale_coding_system
, 0);
3395 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3397 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3398 utime stime cutime cstime priority nice thcount . start vsize rss */
3400 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3401 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3402 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3403 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3404 &u_time
, &s_time
, &cutime
, &cstime
,
3405 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3410 state_str
[1] = '\0';
3411 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3412 attrs
= Fcons (Fcons (Qppid
, INT_TO_INTEGER (ppid
)), attrs
);
3413 attrs
= Fcons (Fcons (Qpgrp
, INT_TO_INTEGER (pgrp
)), attrs
);
3414 attrs
= Fcons (Fcons (Qsess
, INT_TO_INTEGER (sess
)), attrs
);
3415 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3416 attrs
= Fcons (Fcons (Qtpgid
, INT_TO_INTEGER (tpgid
)), attrs
);
3417 attrs
= Fcons (Fcons (Qminflt
, INT_TO_INTEGER (minflt
)), attrs
);
3418 attrs
= Fcons (Fcons (Qmajflt
, INT_TO_INTEGER (majflt
)), attrs
);
3419 attrs
= Fcons (Fcons (Qcminflt
, INT_TO_INTEGER (cminflt
)), attrs
);
3420 attrs
= Fcons (Fcons (Qcmajflt
, INT_TO_INTEGER (cmajflt
)), attrs
);
3421 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3422 if (clocks_per_sec
< 0)
3423 clocks_per_sec
= 100;
3424 attrs
= Fcons (Fcons (Qutime
,
3425 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3427 attrs
= Fcons (Fcons (Qstime
,
3428 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3430 attrs
= Fcons (Fcons (Qtime
,
3431 ltime_from_jiffies (s_time
+ u_time
,
3434 attrs
= Fcons (Fcons (Qcutime
,
3435 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3437 attrs
= Fcons (Fcons (Qcstime
,
3438 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3440 attrs
= Fcons (Fcons (Qctime
,
3441 ltime_from_jiffies (cstime
+ cutime
,
3444 attrs
= Fcons (Fcons (Qpri
, make_fixnum (priority
)), attrs
);
3445 attrs
= Fcons (Fcons (Qnice
, make_fixnum (niceness
)), attrs
);
3446 attrs
= Fcons (Fcons (Qthcount
, INT_TO_INTEGER (thcount
)), attrs
);
3447 tnow
= current_timespec ();
3448 telapsed
= get_up_time ();
3449 tboot
= timespec_sub (tnow
, telapsed
);
3450 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3451 tstart
= timespec_add (tboot
, tstart
);
3452 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3453 attrs
= Fcons (Fcons (Qvsize
, INT_TO_INTEGER (vsize
/ 1024)), attrs
);
3454 attrs
= Fcons (Fcons (Qrss
, INT_TO_INTEGER (4 * rss
)), attrs
);
3455 telapsed
= timespec_sub (tnow
, tstart
);
3456 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3457 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3458 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3461 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3462 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3465 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3468 unbind_to (count
, Qnil
);
3471 strcpy (procfn_end
, "/cmdline");
3472 fd
= emacs_open (fn
, O_RDONLY
, 0);
3475 ptrdiff_t readsize
, nread_incr
;
3476 record_unwind_protect_int (close_file_unwind
, fd
);
3477 record_unwind_protect_nothing ();
3478 nread
= cmdline_size
= 0;
3482 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3483 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3485 /* Leave room even if every byte needs escaping below. */
3486 readsize
= (cmdline_size
>> 1) - nread
;
3488 nread_incr
= emacs_read_quit (fd
, cmdline
+ nread
, readsize
);
3489 nread
+= max (0, nread_incr
);
3491 while (nread_incr
== readsize
);
3495 /* We don't want trailing NUL characters. */
3496 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3499 /* Escape-quote whitespace and backslashes. */
3500 q
= cmdline
+ cmdline_size
;
3505 if (c_isspace (c
) || c
== '\\')
3509 nread
= cmdline
+ cmdline_size
- q
;
3514 nread
= cmdsize
+ 2;
3515 cmdline_size
= nread
+ 1;
3516 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3517 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3518 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3520 /* Command line is encoded in locale-coding-system; decode it. */
3521 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3522 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3523 Vlocale_coding_system
, 0);
3524 unbind_to (count
, Qnil
);
3525 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3531 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3533 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3534 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3535 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3536 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3537 #undef _FILE_OFFSET_BITS
3539 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3544 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3545 #define _FILE_OFFSET_BITS 64
3546 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3548 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3551 system_process_attributes (Lisp_Object pid
)
3553 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3558 struct psinfo pinfo
;
3564 Lisp_Object attrs
= Qnil
;
3565 Lisp_Object decoded_cmd
;
3569 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3570 sprintf (procfn
, "/proc/%"PRIdMAX
, proc_id
);
3571 if (stat (procfn
, &st
) < 0)
3576 attrs
= Fcons (Fcons (Qeuid
, INT_TO_INTEGER (uid
)), attrs
);
3578 pw
= getpwuid (uid
);
3581 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3584 attrs
= Fcons (Fcons (Qegid
, INT_TO_INTEGER (gid
)), attrs
);
3586 gr
= getgrgid (gid
);
3589 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3591 count
= SPECPDL_INDEX ();
3592 strcpy (fn
, procfn
);
3593 procfn_end
= fn
+ strlen (fn
);
3594 strcpy (procfn_end
, "/psinfo");
3595 fd
= emacs_open (fn
, O_RDONLY
, 0);
3600 record_unwind_protect_int (close_file_unwind
, fd
);
3601 nread
= emacs_read_quit (fd
, &pinfo
, sizeof pinfo
);
3604 if (nread
== sizeof pinfo
)
3606 attrs
= Fcons (Fcons (Qppid
, INT_TO_INTEGER (pinfo
.pr_ppid
)), attrs
);
3607 attrs
= Fcons (Fcons (Qpgrp
, INT_TO_INTEGER (pinfo
.pr_pgid
)), attrs
);
3608 attrs
= Fcons (Fcons (Qsess
, INT_TO_INTEGER (pinfo
.pr_sid
)), attrs
);
3612 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3613 state_str
[1] = '\0';
3614 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3617 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3618 need to get a string from it. */
3620 /* FIXME: missing: Qtpgid */
3632 Are they available? */
3634 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3635 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3636 attrs
= Fcons (Fcons (Qpri
, make_fixnum (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3637 attrs
= Fcons (Fcons (Qnice
, make_fixnum (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3638 attrs
= Fcons (Fcons (Qthcount
, INT_TO_INTEGER (pinfo
.pr_nlwp
)), attrs
);
3640 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3641 attrs
= Fcons (Fcons (Qvsize
, INT_TO_INTEGER (pinfo
.pr_size
)), attrs
);
3642 attrs
= Fcons (Fcons (Qrss
, INT_TO_INTEGER (pinfo
.pr_rssize
)), attrs
);
3644 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3645 range 0 .. 2**15, representing 0.0 .. 1.0. */
3646 attrs
= Fcons (Fcons (Qpcpu
,
3647 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3649 attrs
= Fcons (Fcons (Qpmem
,
3650 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3653 AUTO_STRING (fname
, pinfo
.pr_fname
);
3654 decoded_cmd
= code_convert_string_norecord (fname
,
3655 Vlocale_coding_system
, 0);
3656 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3657 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3658 decoded_cmd
= code_convert_string_norecord (psargs
,
3659 Vlocale_coding_system
, 0);
3660 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3662 return unbind_to (count
, attrs
);
3665 #elif defined __FreeBSD__
3668 system_process_attributes (Lisp_Object pid
)
3671 int pagesize
= getpagesize ();
3672 unsigned long npages
;
3678 char args
[MAXPATHLEN
];
3679 struct timespec t
, now
;
3681 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3682 struct kinfo_proc proc
;
3683 size_t proclen
= sizeof proc
;
3685 Lisp_Object attrs
= Qnil
;
3686 Lisp_Object decoded_comm
;
3689 CONS_TO_INTEGER (pid
, int, proc_id
);
3692 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0 || proclen
== 0)
3695 attrs
= Fcons (Fcons (Qeuid
, INT_TO_INTEGER (proc
.ki_uid
)), attrs
);
3698 pw
= getpwuid (proc
.ki_uid
);
3701 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3703 attrs
= Fcons (Fcons (Qegid
, INT_TO_INTEGER (proc
.ki_svgid
)), attrs
);
3706 gr
= getgrgid (proc
.ki_svgid
);
3709 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3711 AUTO_STRING (comm
, proc
.ki_comm
);
3712 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3714 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3716 char state
[2] = {'\0', '\0'};
3717 switch (proc
.ki_stat
)
3739 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3742 attrs
= Fcons (Fcons (Qppid
, INT_TO_INTEGER (proc
.ki_ppid
)), attrs
);
3743 attrs
= Fcons (Fcons (Qpgrp
, INT_TO_INTEGER (proc
.ki_pgid
)), attrs
);
3744 attrs
= Fcons (Fcons (Qsess
, INT_TO_INTEGER (proc
.ki_sid
)), attrs
);
3747 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3750 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3752 attrs
= Fcons (Fcons (Qtpgid
, INT_TO_INTEGER (proc
.ki_tpgid
)), attrs
);
3753 attrs
= Fcons (Fcons (Qminflt
, INT_TO_INTEGER (proc
.ki_rusage
.ru_minflt
)),
3755 attrs
= Fcons (Fcons (Qmajflt
, INT_TO_INTEGER (proc
.ki_rusage
.ru_majflt
)),
3757 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3758 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3760 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3762 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3764 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3765 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3766 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3768 attrs
= Fcons (Fcons (Qcutime
,
3769 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3771 attrs
= Fcons (Fcons (Qcstime
,
3772 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3774 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3775 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3776 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3778 attrs
= Fcons (Fcons (Qthcount
, INT_TO_INTEGER (proc
.ki_numthreads
)), attrs
);
3779 attrs
= Fcons (Fcons (Qpri
, make_fixnum (proc
.ki_pri
.pri_native
)), attrs
);
3780 attrs
= Fcons (Fcons (Qnice
, make_fixnum (proc
.ki_nice
)), attrs
);
3781 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3782 attrs
= Fcons (Fcons (Qvsize
, make_fixnum (proc
.ki_size
>> 10)), attrs
);
3783 attrs
= Fcons (Fcons (Qrss
, make_fixnum (proc
.ki_rssize
* pagesize
>> 10)),
3786 now
= current_timespec ();
3787 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3788 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3790 len
= sizeof fscale
;
3791 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3796 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3798 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3799 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3800 attrs
= Fcons (Fcons (Qpcpu
, INT_TO_INTEGER (pcpu
)), attrs
);
3804 len
= sizeof npages
;
3805 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3807 double pmem
= (proc
.ki_flag
& P_INMEM
3808 ? 100.0 * proc
.ki_rssize
/ npages
3810 attrs
= Fcons (Fcons (Qpmem
, INT_TO_INTEGER (pmem
)), attrs
);
3813 mib
[2] = KERN_PROC_ARGS
;
3815 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0 && len
!= 0)
3818 for (i
= 0; i
< len
; i
++)
3820 if (! args
[i
] && i
< len
- 1)
3824 AUTO_STRING (comm
, args
);
3825 decoded_comm
= code_convert_string_norecord (comm
,
3826 Vlocale_coding_system
, 0);
3828 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3834 #elif defined DARWIN_OS
3837 system_process_attributes (Lisp_Object pid
)
3843 struct timeval starttime
;
3844 struct timespec t
, now
;
3845 struct rusage
*rusage
;
3850 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3851 struct kinfo_proc proc
;
3852 size_t proclen
= sizeof proc
;
3854 Lisp_Object attrs
= Qnil
;
3855 Lisp_Object decoded_comm
;
3858 CONS_TO_INTEGER (pid
, int, proc_id
);
3861 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0 || proclen
== 0)
3864 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3865 attrs
= Fcons (Fcons (Qeuid
, INT_TO_INTEGER (uid
)), attrs
);
3868 pw
= getpwuid (uid
);
3871 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3873 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3874 attrs
= Fcons (Fcons (Qegid
, INT_TO_INTEGER (gid
)), attrs
);
3877 gr
= getgrgid (gid
);
3880 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3882 decoded_comm
= (code_convert_string_norecord
3883 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3884 Vlocale_coding_system
, 0));
3886 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3888 char state
[2] = {'\0', '\0'};
3889 switch (proc
.kp_proc
.p_stat
)
3911 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3914 attrs
= Fcons (Fcons (Qppid
, INT_TO_INTEGER (proc
.kp_eproc
.e_ppid
)), attrs
);
3915 attrs
= Fcons (Fcons (Qpgrp
, INT_TO_INTEGER (proc
.kp_eproc
.e_pgid
)), attrs
);
3917 tdev
= proc
.kp_eproc
.e_tdev
;
3919 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3922 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3924 attrs
= Fcons (Fcons (Qtpgid
, INT_TO_INTEGER (proc
.kp_eproc
.e_tpgid
)),
3927 rusage
= proc
.kp_proc
.p_ru
;
3930 attrs
= Fcons (Fcons (Qminflt
, INT_TO_INTEGER (rusage
->ru_minflt
)),
3932 attrs
= Fcons (Fcons (Qmajflt
, INT_TO_INTEGER (rusage
->ru_majflt
)),
3935 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3937 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3939 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3940 timeval_to_timespec (rusage
->ru_stime
));
3941 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3944 starttime
= proc
.kp_proc
.p_starttime
;
3945 attrs
= Fcons (Fcons (Qnice
, make_fixnum (proc
.kp_proc
.p_nice
)), attrs
);
3946 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3948 now
= current_timespec ();
3949 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3950 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3955 /* The WINDOWSNT implementation is in w32.c.
3956 The MSDOS implementation is in dosfns.c. */
3957 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3960 system_process_attributes (Lisp_Object pid
)
3965 #endif /* !defined (WINDOWSNT) */
3967 DEFUN ("get-internal-run-time", Fget_internal_run_time
, Sget_internal_run_time
,
3969 doc
: /* Return the current run time used by Emacs.
3970 The time is returned as in the style of `current-time'.
3972 On systems that can't determine the run time, `get-internal-run-time'
3973 does the same thing as `current-time'. */)
3976 #ifdef HAVE_GETRUSAGE
3977 struct rusage usage
;
3981 if (getrusage (RUSAGE_SELF
, &usage
) < 0)
3982 /* This shouldn't happen. What action is appropriate? */
3985 /* Sum up user time and system time. */
3986 secs
= usage
.ru_utime
.tv_sec
+ usage
.ru_stime
.tv_sec
;
3987 usecs
= usage
.ru_utime
.tv_usec
+ usage
.ru_stime
.tv_usec
;
3988 if (usecs
>= 1000000)
3993 return make_lisp_time (make_timespec (secs
, usecs
* 1000));
3994 #else /* ! HAVE_GETRUSAGE */
3996 return w32_get_internal_run_time ();
3997 #else /* ! WINDOWSNT */
3998 return Fcurrent_time ();
3999 #endif /* WINDOWSNT */
4000 #endif /* HAVE_GETRUSAGE */
4003 /* Wide character string collation. */
4005 #ifdef __STDC_ISO_10646__
4007 # include <wctype.h>
4009 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
4010 # include <locale.h>
4013 # define LC_COLLATE 0
4015 # ifndef LC_COLLATE_MASK
4016 # define LC_COLLATE_MASK 0
4021 # ifndef LC_CTYPE_MASK
4022 # define LC_CTYPE_MASK 0
4025 # ifndef HAVE_NEWLOCALE
4031 # define freelocale emacs_freelocale
4032 # define locale_t emacs_locale_t
4033 # define newlocale emacs_newlocale
4034 # define wcscoll_l emacs_wcscoll_l
4035 # define towlower_l emacs_towlower_l
4037 typedef char const *locale_t
;
4040 newlocale (int category_mask
, char const *locale
, locale_t loc
)
4046 freelocale (locale_t loc
)
4051 emacs_setlocale (int category
, char const *locale
)
4053 # ifdef HAVE_SETLOCALE
4055 char *loc
= setlocale (category
, locale
);
4066 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
4069 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
4077 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
4078 strcpy (oldcopy
, oldloc
);
4079 if (! emacs_setlocale (LC_COLLATE
, loc
))
4084 result
= wcscoll (a
, b
);
4086 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
4097 towlower_l (wint_t wc
, locale_t loc
)
4100 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
4105 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
4106 strcpy (oldcopy
, oldloc
);
4107 if (emacs_setlocale (LC_CTYPE
, loc
))
4109 result
= towlower (wc
);
4110 emacs_setlocale (LC_COLLATE
, oldcopy
);
4120 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4121 Lisp_Object locale
, Lisp_Object ignore_case
)
4124 ptrdiff_t len
, i
, i_byte
;
4129 /* Convert byte stream to code points. */
4130 len
= SCHARS (s1
); i
= i_byte
= 0;
4131 SAFE_NALLOCA (p1
, 1, len
+ 1);
4133 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
4136 len
= SCHARS (s2
); i
= i_byte
= 0;
4137 SAFE_NALLOCA (p2
, 1, len
+ 1);
4139 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
4142 if (STRINGP (locale
))
4144 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
4145 SSDATA (locale
), 0);
4147 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
4149 if (! NILP (ignore_case
))
4150 for (int i
= 1; i
< 3; i
++)
4152 wchar_t *p
= (i
== 1) ? p1
: p2
;
4154 *p
= towlower_l (*p
, loc
);
4158 res
= wcscoll_l (p1
, p2
, loc
);
4164 if (! NILP (ignore_case
))
4165 for (int i
= 1; i
< 3; i
++)
4167 wchar_t *p
= (i
== 1) ? p1
: p2
;
4173 res
= wcscoll (p1
, p2
);
4176 # ifndef HAVE_NEWLOCALE
4178 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
4181 error ("Invalid string for collation: %s", emacs_strerror (err
));
4187 #endif /* __STDC_ISO_10646__ */
4191 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4192 Lisp_Object locale
, Lisp_Object ignore_case
)
4195 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
4196 int res
, err
= errno
;
4199 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4201 error ("Invalid string for collation: %s", strerror (errno
));
4206 #endif /* WINDOWSNT */
4209 syms_of_sysdep (void)
4211 defsubr (&Sget_internal_run_time
);