1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2017 Free Software
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
27 #endif /* HAVE_PWD_H */
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #if defined DARWIN_OS || defined __FreeBSD__
41 # include <sys/sysctl.h>
45 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
46 'struct frame', so rename it. */
47 # define frame freebsd_frame
48 # include <sys/user.h>
55 #include <sys/socket.h>
57 #endif /* HAVE_SOCKETS */
61 #define write sys_write
63 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
66 #endif /* WINDOWSNT */
68 #include <sys/types.h>
72 /* Get SI_SRPC_DOMAIN, if it is available. */
73 #ifdef HAVE_SYS_SYSTEMINFO_H
74 #include <sys/systeminfo.h>
77 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
81 #include <sys/param.h>
88 #ifdef HAVE_SYS_UTSNAME_H
89 #include <sys/utsname.h>
91 #endif /* HAVE_SYS_UTSNAME_H */
95 #include "termhooks.h"
102 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
103 do that during startup just to call gnutls_rnd. */
104 #if defined HAVE_GNUTLS && !defined WINDOWSNT
105 # include <gnutls/crypto.h>
107 # define emacs_gnutls_global_init() Qnil
108 # define gnutls_rnd(level, data, len) (-1)
113 /* In process.h which conflicts with the local copy. */
115 int _cdecl
_spawnlp (int, const char *, const char *, ...);
116 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
117 several prototypes of functions called below. */
118 #include <sys/socket.h>
121 #include "syssignal.h"
124 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
126 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
129 /* Declare here, including term.h is problematic on some systems. */
130 extern void tputs (const char *, int, int (*)(int));
132 static const int baud_convert
[] =
134 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
135 1800, 2400, 4800, 9600, 19200, 38400
138 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
139 # include <sys/personality.h>
141 /* Disable address randomization in the current process. Return true
142 if addresses were randomized but this has been disabled, false
145 disable_address_randomization (void)
147 int pers
= personality (0xffffffff);
150 int desired_pers
= pers
| ADDR_NO_RANDOMIZE
;
152 /* Call 'personality' twice, to detect buggy platforms like WSL
153 where 'personality' always returns 0. */
154 return (pers
!= desired_pers
155 && personality (desired_pers
) == pers
156 && personality (0xffffffff) == desired_pers
);
160 /* Execute the program in FILE, with argument vector ARGV and environ
161 ENVP. Return an error number if unsuccessful. This is like execve
162 except it reenables ASLR in the executed program if necessary, and
163 on error it returns an error number rather than -1. */
165 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
167 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
168 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
169 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
170 if (change_personality
)
171 personality (pers
& ~ADDR_NO_RANDOMIZE
);
174 execve (file
, argv
, envp
);
177 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
178 if (change_personality
)
185 /* If FD is not already open, arrange for it to be open with FLAGS. */
187 force_open (int fd
, int flags
)
189 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
191 int n
= open (NULL_DEVICE
, flags
);
192 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
194 emacs_perror (NULL_DEVICE
);
200 /* Make sure stdin, stdout, and stderr are open to something, so that
201 their file descriptors are not hijacked by later system calls. */
203 init_standard_fds (void)
205 /* Open stdin for *writing*, and stdout and stderr for *reading*.
206 That way, any attempt to do normal I/O will result in an error,
207 just as if the files were closed, and the file descriptors will
208 not be reused by later opens. */
209 force_open (STDIN_FILENO
, O_WRONLY
);
210 force_open (STDOUT_FILENO
, O_RDONLY
);
211 force_open (STDERR_FILENO
, O_RDONLY
);
214 /* Return the current working directory. The result should be freed
215 with 'free'. Return NULL on errors. */
217 emacs_get_current_dir_name (void)
219 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
220 # ifdef HYBRID_MALLOC
221 bool use_libc
= bss_sbrk_did_unexec
;
223 bool use_libc
= true;
226 return get_current_dir_name ();
230 char *pwd
= getenv ("PWD");
231 struct stat dotstat
, pwdstat
;
232 /* If PWD is accurate, use it instead of calling getcwd. PWD is
233 sometimes a nicer name, and using it may avoid a fatal error if a
234 parent directory is searchable but not readable. */
236 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
237 && stat (pwd
, &pwdstat
) == 0
238 && stat (".", &dotstat
) == 0
239 && dotstat
.st_ino
== pwdstat
.st_ino
240 && dotstat
.st_dev
== pwdstat
.st_dev
242 && strlen (pwd
) < MAXPATHLEN
246 buf
= malloc (strlen (pwd
) + 1);
253 size_t buf_size
= 1024;
254 buf
= malloc (buf_size
);
259 if (getcwd (buf
, buf_size
) == buf
)
263 int tmp_errno
= errno
;
269 buf
= realloc (buf
, buf_size
);
278 /* Discard pending input on all input descriptors. */
281 discard_tty_input (void)
284 struct emacs_tty buf
;
289 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
290 while (dos_keyread () != -1)
292 #else /* not MSDOS */
294 struct tty_display_info
*tty
;
295 for (tty
= tty_list
; tty
; tty
= tty
->next
)
297 if (tty
->input
) /* Is the device suspended? */
299 emacs_get_tty (fileno (tty
->input
), &buf
);
300 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
304 #endif /* not MSDOS */
305 #endif /* not WINDOWSNT */
311 /* Arrange for character C to be read as the next input from
313 XXX What if we have multiple ttys?
319 if (! (FRAMEP (selected_frame
)
320 && FRAME_LIVE_P (XFRAME (selected_frame
))
321 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
324 /* Should perhaps error if in batch mode */
326 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
327 #else /* no TIOCSTI */
328 error ("Cannot stuff terminal input characters in this version of Unix");
329 #endif /* no TIOCSTI */
335 init_baud_rate (int fd
)
345 #else /* not DOS_NT */
350 emacs_ospeed
= cfgetospeed (&sg
);
351 #endif /* not DOS_NT */
354 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
355 ? baud_convert
[emacs_ospeed
] : 9600);
364 /* Wait for the subprocess with process id CHILD to terminate or change status.
365 CHILD must be a child process that has not been reaped.
366 If STATUS is non-null, store the waitpid-style exit status into *STATUS
367 and tell wait_reading_process_output that it needs to look around.
368 Use waitpid-style OPTIONS when waiting.
369 If INTERRUPTIBLE, this function is interruptible by a signal.
371 Return CHILD if successful, 0 if no status is available;
372 the latter is possible only when options & NOHANG. */
374 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
378 /* Invoke waitpid only with a known process ID; do not invoke
379 waitpid with a nonpositive argument. Otherwise, Emacs might
380 reap an unwanted process by mistake. For example, invoking
381 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
382 so that another thread running glib won't find them. */
387 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
392 pid
= waitpid (child
, status
, options
);
396 /* Check that CHILD is a child process that has not been reaped,
397 and that STATUS and OPTIONS are valid. Otherwise abort,
398 as continuing after this internal error could cause Emacs to
399 become confused and kill innocent-victim processes. */
404 /* If successful and status is requested, tell wait_reading_process_output
405 that it needs to wake up and look around. */
406 if (pid
&& status
&& input_available_clear_time
)
407 *input_available_clear_time
= make_timespec (0, 0);
412 /* Wait for the subprocess with process id CHILD to terminate.
413 CHILD must be a child process that has not been reaped.
414 If STATUS is non-null, store the waitpid-style exit status into *STATUS
415 and tell wait_reading_process_output that it needs to look around.
416 If INTERRUPTIBLE, this function is interruptible by a signal. */
418 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
420 get_child_status (child
, status
, 0, interruptible
);
423 /* Report whether the subprocess with process id CHILD has changed status.
424 Termination counts as a change of status.
425 CHILD must be a child process that has not been reaped.
426 If STATUS is non-null, store the waitpid-style exit status into *STATUS
427 and tell wait_reading_process_output that it needs to look around.
428 Use waitpid-style OPTIONS to check status, but do not wait.
430 Return CHILD if successful, 0 if no status is available because
431 the process's state has not changed. */
433 child_status_changed (pid_t child
, int *status
, int options
)
435 return get_child_status (child
, status
, WNOHANG
| options
, 0);
439 /* Set up the terminal at the other end of a pseudo-terminal that
440 we will be controlling an inferior through.
441 It should not echo or do line-editing, since that is done
442 in Emacs. No padding needed for insertion into an Emacs buffer. */
445 child_setup_tty (int out
)
450 emacs_get_tty (out
, &s
);
451 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
452 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
454 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
455 Some versions of GNU Hurd do not have FFDLY? */
457 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
458 /* No output delays */
460 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
461 /* No output delays */
464 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
465 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
467 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
470 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
473 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
475 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
476 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
477 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
478 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
481 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
484 #ifdef SIGNALS_VIA_CHARACTERS
485 /* the QUIT and INTR character are used in process_send_signal
486 so set them here to something useful. */
487 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
488 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
489 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
490 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
491 #endif /* not SIGNALS_VIA_CHARACTERS */
494 /* Also, PTY overloads NUL and BREAK.
495 don't ignore break, but don't signal either, so it looks like NUL. */
496 s
.main
.c_iflag
&= ~IGNBRK
;
497 s
.main
.c_iflag
&= ~BRKINT
;
498 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
499 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
500 would force it to 0377. That looks like duplicated code. */
501 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
504 /* We originally enabled ICANON (and set VEOF to 04), and then had
505 process.c send additional EOF chars to flush the output when faced
506 with long lines, but this leads to weird effects when the
507 subprocess has disabled ICANON and ends up seeing those spurious
508 extra EOFs. So we don't send EOFs any more in
509 process.c:send_process. First we tried to disable ICANON by
510 default, so if a subsprocess sets up ICANON, it's his problem (or
511 the Elisp package that talks to it) to deal with lines that are
512 too long. But this disables some features, such as the ability
513 to send EOF signals. So we re-enabled ICANON but there is no
514 more "send eof to flush" going on (which is wrong and unportable
515 in itself). The correct way to handle too much output is to
516 buffer what could not be written and then write it again when
517 select returns ok for writing. This has it own set of
518 problems. Write is now asynchronous, is that a problem? How much
519 do we buffer, and what do we do when that limit is reached? */
521 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
522 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
523 #if 0 /* These settings only apply to non-ICANON mode. */
524 s
.main
.c_cc
[VMIN
] = 1;
525 s
.main
.c_cc
[VTIME
] = 0;
528 emacs_set_tty (out
, &s
, 0);
529 #endif /* not WINDOWSNT */
531 #endif /* not MSDOS */
534 /* Record a signal code and the action for it. */
538 struct sigaction action
;
541 static void save_signal_handlers (struct save_signal
*);
542 static void restore_signal_handlers (struct save_signal
*);
544 /* Suspend the Emacs process; give terminal to its superior. */
552 /* On a system where suspending is not implemented,
553 instead fork a subshell and let it talk directly to the terminal
560 /* Fork a subshell. */
565 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
568 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
570 char oldwd
[MAX_UTF8_PATH
];
576 struct save_signal saved_handlers
[5];
577 char *str
= SSDATA (encode_current_directory ());
583 char *volatile str_volatile
= str
;
590 error ("Can't spawn subshell");
592 saved_handlers
[0].code
= SIGINT
;
593 saved_handlers
[1].code
= SIGQUIT
;
594 saved_handlers
[2].code
= SIGTERM
;
596 saved_handlers
[3].code
= SIGIO
;
597 saved_handlers
[4].code
= 0;
599 saved_handlers
[3].code
= 0;
603 save_signal_handlers (saved_handlers
);
610 #ifdef DOS_NT /* MW, Aug 1993 */
611 getcwd (oldwd
, sizeof oldwd
);
613 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
616 sh
= egetenv ("SHELL");
620 /* Use our buffer's default directory for the subshell. */
621 if (chdir (str
) != 0)
625 _exit (EXIT_CANCELED
);
629 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
631 char *epwd
= getenv ("PWD");
632 char old_pwd
[MAXPATHLEN
+1+4];
634 /* If PWD is set, pass it with corrected value. */
637 strcpy (old_pwd
, epwd
);
638 setenv ("PWD", str
, 1);
641 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
643 putenv (old_pwd
); /* restore previous value */
645 #else /* not MSDOS */
647 /* Waits for process completion */
648 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
649 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
651 write (1, "Can't execute subshell", 22);
652 #else /* not WINDOWSNT */
653 execlp (sh
, sh
, (char *) 0);
655 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
656 #endif /* not WINDOWSNT */
657 #endif /* not MSDOS */
660 /* Do this now if we did not do it before. */
662 save_signal_handlers (saved_handlers
);
666 wait_for_termination (pid
, &status
, 0);
668 restore_signal_handlers (saved_handlers
);
672 save_signal_handlers (struct save_signal
*saved_handlers
)
674 while (saved_handlers
->code
)
676 struct sigaction action
;
677 emacs_sigaction_init (&action
, SIG_IGN
);
678 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
684 restore_signal_handlers (struct save_signal
*saved_handlers
)
686 while (saved_handlers
->code
)
688 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
694 static int old_fcntl_flags
[FD_SETSIZE
];
701 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
702 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
703 interrupts_deferred
= 0;
712 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
726 sigemptyset (&unblocked
);
728 sigaddset (&unblocked
, SIGWINCH
);
730 sigaddset (&unblocked
, SIGIO
);
731 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
733 interrupts_deferred
= 0;
738 unrequest_sigio (void)
746 sigemptyset (&blocked
);
748 sigaddset (&blocked
, SIGWINCH
);
750 sigaddset (&blocked
, SIGIO
);
751 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
752 interrupts_deferred
= 1;
760 block_child_signal (sigset_t
*oldset
)
763 sigemptyset (&blocked
);
764 sigaddset (&blocked
, SIGCHLD
);
765 sigaddset (&blocked
, SIGINT
);
766 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
769 /* Unblock SIGCHLD. */
772 unblock_child_signal (sigset_t
const *oldset
)
774 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
779 block_interrupt_signal (sigset_t
*oldset
)
782 sigemptyset (&blocked
);
783 sigaddset (&blocked
, SIGINT
);
784 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
787 /* Restore previously saved signal mask. */
789 restore_signal_mask (sigset_t
const *oldset
)
791 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
796 /* Saving and restoring the process group of Emacs's terminal. */
798 /* The process group of which Emacs was a member when it initially
801 If Emacs was in its own process group (i.e. inherited_pgroup ==
802 getpid ()), then we know we're running under a shell with job
803 control (Emacs would never be run as part of a pipeline).
806 If Emacs was not in its own process group, then we know we're
807 running under a shell (or a caller) that doesn't know how to
808 separate itself from Emacs (like sh). Emacs must be in its own
809 process group in order to receive SIGIO correctly. In this
810 situation, we put ourselves in our own pgroup, forcibly set the
811 tty's pgroup to our pgroup, and make sure to restore and reinstate
812 the tty's pgroup just like any other terminal setting. If
813 inherited_group was not the tty's pgroup, then we'll get a
814 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
815 it goes foreground in the future, which is what should happen. */
817 static pid_t inherited_pgroup
;
820 init_foreground_group (void)
822 pid_t pgrp
= getpgrp ();
823 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
826 /* Block and unblock SIGTTOU. */
829 block_tty_out_signal (sigset_t
*oldset
)
833 sigemptyset (&blocked
);
834 sigaddset (&blocked
, SIGTTOU
);
835 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
840 unblock_tty_out_signal (sigset_t
const *oldset
)
843 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
847 /* Safely set a controlling terminal FD's process group to PGID.
848 If we are not in the foreground already, POSIX requires tcsetpgrp
849 to deliver a SIGTTOU signal, which would stop us. This is an
850 annoyance, so temporarily ignore the signal.
852 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
853 skip all this unless SIGTTOU is defined. */
855 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
860 block_tty_out_signal (&oldset
);
861 tcsetpgrp (fd
, pgid
);
862 unblock_tty_out_signal (&oldset
);
867 /* Split off the foreground process group to Emacs alone. When we are
868 in the foreground, but not started in our own process group,
869 redirect the tty device handle FD to point to our own process
870 group. FD must be the file descriptor of the controlling tty. */
872 narrow_foreground_group (int fd
)
874 if (inherited_pgroup
&& setpgid (0, 0) == 0)
875 tcsetpgrp_without_stopping (fd
, getpid ());
878 /* Set the tty to our original foreground group. */
880 widen_foreground_group (int fd
)
882 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
883 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
886 /* Getting and setting emacs_tty structures. */
888 /* Set *TC to the parameters associated with the terminal FD,
889 or clear it if the parameters are not available.
890 Return 0 on success, -1 on failure. */
892 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
894 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
895 memset (&settings
->main
, 0, sizeof (settings
->main
));
898 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
901 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
903 settings
->main
= console_mode
;
906 #endif /* WINDOWSNT */
909 /* We have those nifty POSIX tcmumbleattr functions. */
910 return tcgetattr (fd
, &settings
->main
);
915 /* Set the parameters of the tty on FD according to the contents of
916 *SETTINGS. If FLUSHP, discard input.
917 Return 0 if all went well, and -1 (setting errno) if anything failed. */
920 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
922 /* Set the primary parameters - baud rate, character size, etcetera. */
925 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
927 if (h
&& h
!= INVALID_HANDLE_VALUE
)
931 /* Assume the handle is open for input. */
933 FlushConsoleInputBuffer (h
);
934 new_mode
= settings
->main
;
935 SetConsoleMode (h
, new_mode
);
937 #endif /* WINDOWSNT */
940 /* We have those nifty POSIX tcmumbleattr functions.
941 William J. Smith <wjs@wiis.wang.com> writes:
942 "POSIX 1003.1 defines tcsetattr to return success if it was
943 able to perform any of the requested actions, even if some
944 of the requested actions could not be performed.
945 We must read settings back to ensure tty setup properly.
946 AIX requires this to keep tty from hanging occasionally." */
947 /* This make sure that we don't loop indefinitely in here. */
948 for (i
= 0 ; i
< 10 ; i
++)
949 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
960 memset (&new, 0, sizeof (new));
961 /* Get the current settings, and see if they're what we asked for. */
962 tcgetattr (fd
, &new);
963 /* We cannot use memcmp on the whole structure here because under
964 * aix386 the termios structure has some reserved field that may
967 if ( new.c_iflag
== settings
->main
.c_iflag
968 && new.c_oflag
== settings
->main
.c_oflag
969 && new.c_cflag
== settings
->main
.c_cflag
970 && new.c_lflag
== settings
->main
.c_lflag
971 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
978 /* We have survived the tempest. */
985 static int old_fcntl_owner
[FD_SETSIZE
];
986 #endif /* F_SETOWN */
988 /* This may also be defined in stdio,
989 but if so, this does no harm,
990 and using the same name avoids wasting the other one's space. */
993 unsigned char _sobuf
[BUFSIZ
+8];
998 /* Initialize the terminal mode on all tty devices that are currently
1002 init_all_sys_modes (void)
1004 struct tty_display_info
*tty
;
1005 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1006 init_sys_modes (tty
);
1009 /* Initialize the terminal mode on the given tty device. */
1012 init_sys_modes (struct tty_display_info
*tty_out
)
1014 struct emacs_tty tty
;
1016 Lisp_Object terminal
;
1019 Vtty_erase_char
= Qnil
;
1024 if (!tty_out
->output
)
1025 return; /* The tty is suspended. */
1027 narrow_foreground_group (fileno (tty_out
->input
));
1029 if (! tty_out
->old_tty
)
1030 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1032 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1034 tty
= *tty_out
->old_tty
;
1036 #if !defined (DOS_NT)
1037 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1039 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1040 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1041 #ifdef INLCR /* I'm just being cautious,
1042 since I can't check how widespread INLCR is--rms. */
1043 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1046 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1048 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1049 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1051 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1053 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1054 if (tty_out
->flow_control
)
1056 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1058 tty
.main
.c_iflag
&= ~IXANY
;
1062 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1063 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1065 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1067 if (tty_out
->meta_key
)
1069 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1070 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1074 XSETTERMINAL(terminal
, tty_out
->terminal
);
1075 if (!NILP (Fcontrolling_tty_p (terminal
)))
1077 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1078 /* Set up C-g for both SIGQUIT and SIGINT.
1079 We don't know which we will get, but we handle both alike
1080 so which one it really gives us does not matter. */
1081 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1085 /* We normally don't get interrupt or quit signals from tty
1086 devices other than our controlling terminal; therefore,
1087 we must handle C-g as normal input. Unfortunately, this
1088 means that the interrupt and quit feature must be
1089 disabled on secondary ttys, or we would not even see the
1092 Note that even though emacsclient could have special code
1093 to pass SIGINT to Emacs, we should _not_ enable
1094 interrupt/quit keys for emacsclient frames. This means
1095 that we can't break out of loops in C code from a
1096 secondary tty frame, but we can always decide what
1097 display the C-g came from, which is more important from a
1098 usability point of view. (Consider the case when two
1099 people work together using the same Emacs instance.) */
1100 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1101 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1103 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1104 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1106 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1111 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1114 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1115 #endif /* V_DSUSP */
1116 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1117 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1120 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1123 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1124 #endif /* VREPRINT */
1126 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1127 #endif /* VWERASE */
1129 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1130 #endif /* VDISCARD */
1132 if (tty_out
->flow_control
)
1135 tty
.main
.c_cc
[VSTART
] = '\021';
1138 tty
.main
.c_cc
[VSTOP
] = '\023';
1144 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1147 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1152 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1153 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1154 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1155 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1156 if (tty_out
->flow_control
)
1159 tty
.main
.c_cc
[VSTART
] = '\021';
1162 tty
.main
.c_cc
[VSTOP
] = '\023';
1165 /* Also, PTY overloads NUL and BREAK.
1166 don't ignore break, but don't signal either, so it looks like NUL.
1167 This really serves a purpose only if running in an XTERM window
1168 or via TELNET or the like, but does no harm elsewhere. */
1169 tty
.main
.c_iflag
&= ~IGNBRK
;
1170 tty
.main
.c_iflag
&= ~BRKINT
;
1172 #endif /* not DOS_NT */
1174 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1175 if (!tty_out
->term_initted
)
1176 internal_terminal_init ();
1177 dos_ttraw (tty_out
);
1180 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1182 /* This code added to insure that, if flow-control is not to be used,
1183 we have an unlocked terminal at the start. */
1186 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1189 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1192 #if !defined (DOS_NT)
1194 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1199 if (interrupt_input
)
1201 old_fcntl_owner
[fileno (tty_out
->input
)] =
1202 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1203 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1204 init_sigio (fileno (tty_out
->input
));
1206 if (gpm_tty
== tty_out
)
1208 /* Arrange for mouse events to give us SIGIO signals. */
1209 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1210 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1211 init_sigio (gpm_fd
);
1213 #endif /* HAVE_GPM */
1215 #endif /* F_GETOWN */
1218 /* This symbol is defined on recent USG systems.
1219 Someone says without this call USG won't really buffer the file
1220 even with a call to setbuf. */
1221 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1223 setbuf (tty_out
->output
, (char *) _sobuf
);
1226 if (tty_out
->terminal
->set_terminal_modes_hook
)
1227 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1229 if (!tty_out
->term_initted
)
1231 Lisp_Object tail
, frame
;
1232 FOR_EACH_FRAME (tail
, frame
)
1234 /* XXX This needs to be revised. */
1235 if (FRAME_TERMCAP_P (XFRAME (frame
))
1236 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1237 init_frame_faces (XFRAME (frame
));
1241 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1243 /* We used to call "direct_output_forward_char(0)" here,
1244 but it's not clear why, since it may not do anything anyway. */
1248 Lisp_Object tail
, frame
;
1250 FOR_EACH_FRAME (tail
, frame
)
1252 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1253 || FRAME_MSDOS_P (XFRAME (frame
)))
1254 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1255 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1259 tty_out
->term_initted
= 1;
1262 /* Return true if safe to use tabs in output.
1263 At the time this is called, init_sys_modes has not been done yet. */
1266 tabs_safe_p (int fd
)
1268 struct emacs_tty etty
;
1270 emacs_get_tty (fd
, &etty
);
1273 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1274 #else /* not TABDLY */
1276 #endif /* not TABDLY */
1282 /* Discard echoing. */
1285 suppress_echo_on_tty (int fd
)
1287 struct emacs_tty etty
;
1289 emacs_get_tty (fd
, &etty
);
1291 /* Set raw input mode. */
1294 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1295 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1296 #endif /* ! WINDOWSNT */
1297 emacs_set_tty (fd
, &etty
, 0);
1300 /* Get terminal size from system.
1301 Store number of lines into *HEIGHTP and width into *WIDTHP.
1302 We store 0 if there's no valid information. */
1305 get_tty_size (int fd
, int *widthp
, int *heightp
)
1307 #if defined TIOCGWINSZ
1310 struct winsize size
;
1312 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1313 *widthp
= *heightp
= 0;
1316 *widthp
= size
.ws_col
;
1317 *heightp
= size
.ws_row
;
1320 #elif defined TIOCGSIZE
1322 /* SunOS - style. */
1323 struct ttysize size
;
1325 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1326 *widthp
= *heightp
= 0;
1329 *widthp
= size
.ts_cols
;
1330 *heightp
= size
.ts_lines
;
1333 #elif defined WINDOWSNT
1335 CONSOLE_SCREEN_BUFFER_INFO info
;
1336 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1338 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1339 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1342 *widthp
= *heightp
= 0;
1346 *widthp
= ScreenCols ();
1347 *heightp
= ScreenRows ();
1349 #else /* system doesn't know size */
1357 /* Set the logical window size associated with descriptor FD
1358 to HEIGHT and WIDTH. This is used mainly with ptys.
1359 Return a negative value on failure. */
1362 set_window_size (int fd
, int height
, int width
)
1367 struct winsize size
;
1368 size
.ws_row
= height
;
1369 size
.ws_col
= width
;
1371 return ioctl (fd
, TIOCSWINSZ
, &size
);
1376 /* SunOS - style. */
1377 struct ttysize size
;
1378 size
.ts_lines
= height
;
1379 size
.ts_cols
= width
;
1381 return ioctl (fd
, TIOCGSIZE
, &size
);
1384 #endif /* not SunOS-style */
1385 #endif /* not BSD-style */
1390 /* Prepare all terminal devices for exiting Emacs. */
1393 reset_all_sys_modes (void)
1395 struct tty_display_info
*tty
;
1396 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1397 reset_sys_modes (tty
);
1400 /* Prepare the terminal for closing it; move the cursor to the
1401 bottom of the frame, turn off interrupt-driven I/O, etc. */
1404 reset_sys_modes (struct tty_display_info
*tty_out
)
1411 if (!tty_out
->term_initted
)
1414 if (!tty_out
->output
)
1415 return; /* The tty is suspended. */
1417 /* Go to and clear the last line of the terminal. */
1419 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1421 /* Code adapted from tty_clear_end_of_line. */
1422 if (tty_out
->TS_clr_line
)
1424 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1427 { /* have to do it the hard way */
1429 tty_turn_off_insert (tty_out
);
1431 for (i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1433 fputc (' ', tty_out
->output
);
1437 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1438 fflush (tty_out
->output
);
1440 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1441 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1443 /* Avoid possible loss of output when changing terminal modes. */
1444 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1449 if (interrupt_input
)
1451 reset_sigio (fileno (tty_out
->input
));
1452 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1453 old_fcntl_owner
[fileno (tty_out
->input
)]);
1455 #endif /* F_SETOWN */
1456 fcntl (fileno (tty_out
->input
), F_SETFL
,
1457 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1460 if (tty_out
->old_tty
)
1461 while (emacs_set_tty (fileno (tty_out
->input
),
1462 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1465 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1469 widen_foreground_group (fileno (tty_out
->input
));
1474 /* Set up the proper status flags for use of a pty. */
1479 /* I'm told that TOICREMOTE does not mean control chars
1480 "can't be sent" but rather that they don't have
1481 input-editing or signaling effects.
1482 That should be good, because we have other ways
1483 to do those things in Emacs.
1484 However, telnet mode seems not to work on 4.2.
1485 So TIOCREMOTE is turned off now. */
1487 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1488 will hang. In particular, the "timeout" feature (which
1489 causes a read to return if there is no data available)
1490 does this. Also it is known that telnet mode will hang
1491 in such a way that Emacs must be stopped (perhaps this
1492 is the same problem).
1494 If TIOCREMOTE is turned off, then there is a bug in
1495 hp-ux which sometimes loses data. Apparently the
1496 code which blocks the master process when the internal
1497 buffer fills up does not work. Other than this,
1498 though, everything else seems to work fine.
1500 Since the latter lossage is more benign, we may as well
1501 lose that way. -- cph */
1503 #if defined (UNIX98_PTYS)
1506 ioctl (fd
, FIONBIO
, &on
);
1511 #endif /* HAVE_PTYS */
1514 init_system_name (void)
1518 /* Set system-name to nil so that the build is deterministic. */
1519 Vsystem_name
= Qnil
;
1522 char *hostname_alloc
= NULL
;
1524 #ifndef HAVE_GETHOSTNAME
1527 hostname
= uts
.nodename
;
1528 #else /* HAVE_GETHOSTNAME */
1529 char hostname_buf
[256];
1530 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1531 hostname
= hostname_buf
;
1533 /* Try to get the host name; if the buffer is too short, try
1534 again. Apparently, the only indication gethostname gives of
1535 whether the buffer was large enough is the presence or absence
1536 of a '\0' in the string. Eech. */
1539 gethostname (hostname
, hostname_size
- 1);
1540 hostname
[hostname_size
- 1] = '\0';
1542 /* Was the buffer large enough for the '\0'? */
1543 if (strlen (hostname
) < hostname_size
- 1)
1546 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1547 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1549 #endif /* HAVE_GETHOSTNAME */
1551 for (p
= hostname
; *p
; p
++)
1552 if (*p
== ' ' || *p
== '\t')
1554 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1555 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1556 Vsystem_name
= build_string (hostname
);
1557 xfree (hostname_alloc
);
1560 sigset_t empty_mask
;
1562 static struct sigaction process_fatal_action
;
1565 emacs_sigaction_flags (void)
1568 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1569 'select') to reset their timeout on some platforms (e.g.,
1570 HP-UX 11), which is not what we want. Also, when Emacs is
1571 interactive, we don't want SA_RESTART because we need to poll
1572 for pending input so we need long-running syscalls to be interrupted
1573 after a signal that sets pending_signals.
1575 Non-interactive keyboard input goes through stdio, where we
1576 always want restartable system calls. */
1583 /* Store into *ACTION a signal action suitable for Emacs, with handler
1586 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1588 sigemptyset (&action
->sa_mask
);
1590 /* When handling a signal, block nonfatal system signals that are caught
1591 by Emacs. This makes race conditions less likely. */
1592 sigaddset (&action
->sa_mask
, SIGALRM
);
1594 sigaddset (&action
->sa_mask
, SIGCHLD
);
1597 sigaddset (&action
->sa_mask
, SIGDANGER
);
1599 #ifdef PROFILER_CPU_SUPPORT
1600 sigaddset (&action
->sa_mask
, SIGPROF
);
1603 sigaddset (&action
->sa_mask
, SIGWINCH
);
1605 if (! noninteractive
)
1607 sigaddset (&action
->sa_mask
, SIGINT
);
1608 sigaddset (&action
->sa_mask
, SIGQUIT
);
1610 sigaddset (&action
->sa_mask
, SIGIO
);
1614 action
->sa_handler
= handler
;
1615 action
->sa_flags
= emacs_sigaction_flags ();
1618 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1619 pthread_t main_thread_id
;
1622 /* SIG has arrived at the current process. Deliver it to the main
1623 thread, which should handle it with HANDLER. (Delivering the
1624 signal to some other thread might not work if the other thread is
1627 If we are on the main thread, handle the signal SIG with HANDLER.
1628 Otherwise, redirect the signal to the main thread, blocking it from
1629 this thread. POSIX says any thread can receive a signal that is
1630 associated with a process, process group, or asynchronous event.
1631 On GNU/Linux the main thread typically gets a process signal unless
1632 it's blocked, but other systems (FreeBSD at least) can deliver the
1633 signal to other threads. */
1635 deliver_process_signal (int sig
, signal_handler_t handler
)
1637 /* Preserve errno, to avoid race conditions with signal handlers that
1638 might change errno. Races can occur even in single-threaded hosts. */
1639 int old_errno
= errno
;
1641 bool on_main_thread
= true;
1642 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1643 if (! pthread_equal (pthread_self (), main_thread_id
))
1646 sigemptyset (&blocked
);
1647 sigaddset (&blocked
, sig
);
1648 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1649 pthread_kill (main_thread_id
, sig
);
1650 on_main_thread
= false;
1659 /* Static location to save a fatal backtrace in a thread.
1660 FIXME: If two subsidiary threads fail simultaneously, the resulting
1661 backtrace may be garbage. */
1662 enum { BACKTRACE_LIMIT_MAX
= 500 };
1663 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1664 static int thread_backtrace_npointers
;
1666 /* SIG has arrived at the current thread.
1667 If we are on the main thread, handle the signal SIG with HANDLER.
1668 Otherwise, this is a fatal error in the handling thread. */
1670 deliver_thread_signal (int sig
, signal_handler_t handler
)
1672 int old_errno
= errno
;
1674 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1675 if (! pthread_equal (pthread_self (), main_thread_id
))
1677 thread_backtrace_npointers
1678 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1679 sigaction (sig
, &process_fatal_action
, 0);
1680 pthread_kill (main_thread_id
, sig
);
1682 /* Avoid further damage while the main thread is exiting. */
1684 sigsuspend (&empty_mask
);
1692 #if !HAVE_DECL_SYS_SIGLIST
1694 # ifdef _sys_siglist
1695 # define sys_siglist _sys_siglist
1696 # elif HAVE_DECL___SYS_SIGLIST
1697 # define sys_siglist __sys_siglist
1699 # define sys_siglist my_sys_siglist
1700 static char const *sys_siglist
[NSIG
];
1705 # define sys_siglist_entries _sys_nsig
1707 # define sys_siglist_entries NSIG
1710 /* Handle bus errors, invalid instruction, etc. */
1712 handle_fatal_signal (int sig
)
1714 terminate_due_to_signal (sig
, 40);
1718 deliver_fatal_signal (int sig
)
1720 deliver_process_signal (sig
, handle_fatal_signal
);
1724 deliver_fatal_thread_signal (int sig
)
1726 deliver_thread_signal (sig
, handle_fatal_signal
);
1729 static _Noreturn
void
1730 handle_arith_signal (int sig
)
1732 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1733 xsignal0 (Qarith_error
);
1736 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1738 /* Alternate stack used by SIGSEGV handler below. */
1740 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1743 /* Return true if SIGINFO indicates a stack overflow. */
1746 stack_overflow (siginfo_t
*siginfo
)
1748 if (!attempt_stack_overflow_recovery
)
1751 /* In theory, a more-accurate heuristic can be obtained by using
1752 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1753 and pthread_attr_getguardsize to find the location and size of the
1754 guard area. In practice, though, these functions are so hard to
1755 use reliably that they're not worth bothering with. E.g., see:
1756 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1757 Other operating systems also have problems, e.g., Solaris's
1758 stack_violation function is tailor-made for this problem, but it
1759 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1761 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1767 /* The faulting address. */
1768 char *addr
= siginfo
->si_addr
;
1772 /* The known top and bottom of the stack. The actual stack may
1773 extend a bit beyond these boundaries. */
1774 char *bot
= stack_bottom
;
1775 char *top
= near_C_stack_top ();
1777 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1778 of the known stack divided by the size of the guard area past the
1779 end of the stack top. The heuristic is that a bad address is
1780 considered to be a stack overflow if it occurs within
1781 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1782 stack. This heuristic is not exactly correct but it's good
1783 enough in practice. */
1784 enum { LG_STACK_HEURISTIC
= 8 };
1787 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1789 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1793 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1796 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1798 /* Hard GC error may lead to stack overflow caused by
1799 too nested calls to mark_object. No way to survive. */
1800 bool fatal
= gc_in_progress
;
1802 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1803 if (!fatal
&& !pthread_equal (pthread_self (), main_thread_id
))
1807 if (!fatal
&& stack_overflow (siginfo
))
1808 siglongjmp (return_to_command_loop
, 1);
1810 /* Otherwise we can't do anything with this. */
1811 deliver_fatal_thread_signal (sig
);
1814 /* Return true if we have successfully set up SIGSEGV handler on alternate
1815 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1820 struct sigaction sa
;
1823 ss
.ss_sp
= sigsegv_stack
;
1824 ss
.ss_size
= sizeof (sigsegv_stack
);
1826 if (sigaltstack (&ss
, NULL
) < 0)
1829 sigfillset (&sa
.sa_mask
);
1830 sa
.sa_sigaction
= handle_sigsegv
;
1831 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1832 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1835 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1843 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1846 deliver_arith_signal (int sig
)
1848 deliver_thread_signal (sig
, handle_arith_signal
);
1853 /* Handler for SIGDANGER. */
1855 handle_danger_signal (int sig
)
1857 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1859 /* It might be unsafe to call do_auto_save now. */
1860 force_auto_save_soon ();
1864 deliver_danger_signal (int sig
)
1866 deliver_process_signal (sig
, handle_danger_signal
);
1870 /* Treat SIG as a terminating signal, unless it is already ignored and
1871 we are in --batch mode. Among other things, this makes nohup work. */
1873 maybe_fatal_sig (int sig
)
1875 bool catch_sig
= !noninteractive
;
1878 struct sigaction old_action
;
1879 sigaction (sig
, 0, &old_action
);
1880 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1883 sigaction (sig
, &process_fatal_action
, 0);
1887 init_signals (bool dumping
)
1889 struct sigaction thread_fatal_action
;
1890 struct sigaction action
;
1892 sigemptyset (&empty_mask
);
1894 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1895 main_thread_id
= pthread_self ();
1898 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1901 sys_siglist
[SIGABRT
] = "Aborted";
1903 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1905 sys_siglist
[SIGALRM
] = "Alarm clock";
1907 sys_siglist
[SIGBUS
] = "Bus error";
1910 sys_siglist
[SIGCHLD
] = "Child status changed";
1913 sys_siglist
[SIGCONT
] = "Continued";
1916 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1919 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1922 sys_siglist
[SIGEMT
] = "Emulation trap";
1924 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1926 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1929 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1931 sys_siglist
[SIGHUP
] = "Hangup";
1932 sys_siglist
[SIGILL
] = "Illegal instruction";
1933 sys_siglist
[SIGINT
] = "Interrupt";
1935 sys_siglist
[SIGIO
] = "I/O possible";
1938 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1941 sys_siglist
[SIGIOT
] = "IOT trap";
1943 sys_siglist
[SIGKILL
] = "Killed";
1945 sys_siglist
[SIGLOST
] = "Resource lost";
1948 sys_siglist
[SIGLWP
] = "SIGLWP";
1951 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1954 sys_siglist
[SIGWIND
] = "SIGPHONE";
1956 sys_siglist
[SIGPIPE
] = "Broken pipe";
1958 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1961 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1964 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1967 sys_siglist
[SIGPWR
] = "Power-fail restart";
1969 sys_siglist
[SIGQUIT
] = "Quit";
1971 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1974 sys_siglist
[SIGSAK
] = "Secure attention";
1976 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1978 sys_siglist
[SIGSOUND
] = "Sound completed";
1981 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1984 sys_siglist
[SIGSTP
] = "Stopped (user)";
1987 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1989 sys_siglist
[SIGTERM
] = "Terminated";
1991 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1994 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1997 sys_siglist
[SIGTSTP
] = "Stopped (user)";
2000 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
2003 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
2006 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2009 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2012 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2015 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2018 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2021 sys_siglist
[SIGWINCH
] = "Window size changed";
2024 sys_siglist
[SIGWIND
] = "SIGWIND";
2027 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2030 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2033 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2035 /* Don't alter signal handlers if dumping. On some machines,
2036 changing signal handlers sets static data that would make signals
2037 fail to work right when the dumped Emacs is run. */
2041 sigfillset (&process_fatal_action
.sa_mask
);
2042 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2043 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2045 sigfillset (&thread_fatal_action
.sa_mask
);
2046 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2047 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2049 /* SIGINT may need special treatment on MS-Windows. See
2050 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2051 Please update the doc of kill-emacs, kill-emacs-hook, and
2052 NEWS if you change this. */
2054 maybe_fatal_sig (SIGHUP
);
2055 maybe_fatal_sig (SIGINT
);
2056 maybe_fatal_sig (SIGTERM
);
2058 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2059 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2060 to behave more like typical batch applications do. */
2061 if (! noninteractive
)
2062 signal (SIGPIPE
, SIG_IGN
);
2064 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2065 sigaction (SIGILL
, &thread_fatal_action
, 0);
2066 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2068 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2069 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2070 interpreter's floating point operations, so treat SIGFPE as an
2071 arith-error if it arises in the main thread. */
2072 if (IEEE_FLOATING_POINT
)
2073 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2076 emacs_sigaction_init (&action
, deliver_arith_signal
);
2077 sigaction (SIGFPE
, &action
, 0);
2081 add_user_signal (SIGUSR1
, "sigusr1");
2084 add_user_signal (SIGUSR2
, "sigusr2");
2086 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2088 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2091 sigaction (SIGORE
, &thread_fatal_action
, 0);
2094 sigaction (SIGUME
, &thread_fatal_action
, 0);
2097 sigaction (SIGDLK
, &process_fatal_action
, 0);
2100 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2103 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2106 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2109 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2111 if (!init_sigsegv ())
2112 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2114 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2116 sigaction (SIGTERM
, &process_fatal_action
, 0);
2118 signal (SIGPROF
, SIG_IGN
);
2121 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2124 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2127 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2131 /* This just means available memory is getting low. */
2132 emacs_sigaction_init (&action
, deliver_danger_signal
);
2133 sigaction (SIGDANGER
, &action
, 0);
2136 /* AIX-specific signals. */
2138 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2141 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2144 sigaction (SIGMSG
, &process_fatal_action
, 0);
2147 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2150 sigaction (SIGSAK
, &process_fatal_action
, 0);
2153 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2156 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2166 /* Figure out how many bits the system's random number generator uses.
2167 `random' and `lrand48' are assumed to return 31 usable bits.
2168 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2169 so we'll shift it and treat it like the 15-bit USG `rand'. */
2173 # define RAND_BITS 31
2174 # else /* !HAVE_RANDOM */
2175 # ifdef HAVE_LRAND48
2176 # define RAND_BITS 31
2177 # define random lrand48
2178 # else /* !HAVE_LRAND48 */
2179 # define RAND_BITS 15
2180 # if RAND_MAX == 32767
2181 # define random rand
2182 # else /* RAND_MAX != 32767 */
2183 # if RAND_MAX == 2147483647
2184 # define random() (rand () >> 16)
2185 # else /* RAND_MAX != 2147483647 */
2187 # define random rand
2189 # define random() (rand () >> 16)
2191 # endif /* RAND_MAX != 2147483647 */
2192 # endif /* RAND_MAX != 32767 */
2193 # endif /* !HAVE_LRAND48 */
2194 # endif /* !HAVE_RANDOM */
2195 #endif /* !RAND_BITS */
2198 typedef unsigned int random_seed
;
2199 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2200 #elif defined HAVE_LRAND48
2201 /* Although srand48 uses a long seed, this is unsigned long to avoid
2202 undefined behavior on signed integer overflow in init_random. */
2203 typedef unsigned long int random_seed
;
2204 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2206 typedef unsigned int random_seed
;
2207 static void set_random_seed (random_seed arg
) { srand (arg
); }
2211 seed_random (void *seed
, ptrdiff_t seed_size
)
2213 random_seed arg
= 0;
2214 unsigned char *argp
= (unsigned char *) &arg
;
2215 unsigned char *seedp
= seed
;
2216 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2217 argp
[i
% sizeof arg
] ^= seedp
[i
];
2218 set_random_seed (arg
);
2225 bool success
= false;
2227 /* First, try seeding the PRNG from the operating system's entropy
2228 source. This approach is both fast and secure. */
2230 success
= w32_init_random (&v
, sizeof v
) == 0;
2232 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2235 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2240 /* If that didn't work, try using GnuTLS, which is secure, but on
2241 some systems, can be somewhat slow. */
2243 success
= EQ (emacs_gnutls_global_init (), Qt
)
2244 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2246 /* If _that_ didn't work, just use the current time value and PID.
2247 It's at least better than XKCD 221. */
2250 struct timespec t
= current_timespec ();
2251 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2254 set_random_seed (v
);
2258 * Return a nonnegative random integer out of whatever we've got.
2259 * It contains enough bits to make a random (signed) Emacs fixnum.
2260 * This suffices even for a 64-bit architecture with a 15-bit rand.
2267 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2268 val
= (random () ^ (val
<< RAND_BITS
)
2269 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2270 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2271 return val
& INTMASK
;
2274 #ifndef HAVE_SNPRINTF
2275 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2277 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2279 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2280 ptrdiff_t nbytes
= size
- 1;
2285 va_start (ap
, format
);
2286 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2290 if (nbytes
== size
- 1)
2292 /* Calculate the length of the string that would have been created
2293 had the buffer been large enough. */
2294 char stackbuf
[4000];
2296 ptrdiff_t bsize
= sizeof stackbuf
;
2297 va_start (ap
, format
);
2298 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2304 if (INT_MAX
< nbytes
)
2317 /* If a backtrace is available, output the top lines of it to stderr.
2318 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2319 This function may be called from a signal handler, so it should
2320 not invoke async-unsafe functions like malloc.
2322 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2323 but do not output anything. This avoids some problems that can
2324 otherwise occur if the malloc arena is corrupted before 'backtrace'
2325 is called, since 'backtrace' may call malloc if the tables are not
2328 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2329 fatal error has occurred in some other thread; generate a thread
2330 backtrace instead, ignoring BACKTRACE_LIMIT. */
2332 emacs_backtrace (int backtrace_limit
)
2334 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2335 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2339 if (thread_backtrace_npointers
)
2341 buffer
= thread_backtrace_buffer
;
2342 npointers
= thread_backtrace_npointers
;
2346 buffer
= main_backtrace_buffer
;
2348 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2349 if (bounded_limit
< 0)
2351 backtrace (buffer
, 1);
2355 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2360 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2361 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2362 if (bounded_limit
< npointers
)
2363 emacs_write (STDERR_FILENO
, "...\n", 4);
2371 terminate_due_to_signal (SIGABRT
, 40);
2375 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2376 Use binary I/O on systems that care about text vs binary I/O.
2377 Arrange for subprograms to not inherit the file descriptor.
2378 Prefer a method that is multithread-safe, if available.
2379 Do not fail merely because the open was interrupted by a signal.
2380 Allow the user to quit. */
2383 emacs_open (const char *file
, int oflags
, int mode
)
2386 if (! (oflags
& O_TEXT
))
2388 oflags
|= O_CLOEXEC
;
2389 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2391 if (! O_CLOEXEC
&& 0 <= fd
)
2392 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2396 /* Open FILE as a stream for Emacs use, with mode MODE.
2397 Act like emacs_open with respect to threads, signals, and quits. */
2400 emacs_fopen (char const *file
, char const *mode
)
2402 int fd
, omode
, oflags
;
2404 char const *m
= mode
;
2408 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2409 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2410 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2411 default: emacs_abort ();
2417 case '+': omode
= O_RDWR
; break;
2418 case 't': bflag
= O_TEXT
; break;
2419 default: /* Ignore. */ break;
2422 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2423 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2426 /* Create a pipe for Emacs use. */
2429 emacs_pipe (int fd
[2])
2434 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2435 if (! O_CLOEXEC
&& result
== 0)
2437 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2438 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2444 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2445 For the background behind this mess, please see Austin Group defect 529
2446 <http://austingroupbugs.net/view.php?id=529>. */
2448 #ifndef POSIX_CLOSE_RESTART
2449 # define POSIX_CLOSE_RESTART 1
2451 posix_close (int fd
, int flag
)
2453 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2454 eassert (flag
== POSIX_CLOSE_RESTART
);
2456 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2457 on a system that does not define POSIX_CLOSE_RESTART.
2459 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2460 closed, and retrying the close could inadvertently close a file
2461 descriptor allocated by some other thread. In other systems
2462 (e.g., HP/UX) FD is not closed. And in still other systems
2463 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2464 multithreaded program there can be no way to tell.
2466 So, in this case, pretend that the close succeeded. This works
2467 well on systems like GNU/Linux that close FD. Although it may
2468 leak a file descriptor on other systems, the leak is unlikely and
2469 it's better to leak than to close a random victim. */
2470 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2474 /* Close FD, retrying if interrupted. If successful, return 0;
2475 otherwise, return -1 and set errno to a non-EINTR value. Consider
2476 an EINPROGRESS error to be successful, as that's merely a signal
2477 arriving. FD is always closed when this function returns, even
2480 Do not call this function if FD is nonnegative and might already be closed,
2481 as that might close an innocent victim opened by some other thread. */
2484 emacs_close (int fd
)
2488 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2491 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2493 eassert (errno
!= EBADF
|| fd
< 0);
2494 return errno
== EINPROGRESS
? 0 : r
;
2499 /* Maximum number of bytes to read or write in a single system call.
2500 This works around a serious bug in Linux kernels before 2.6.16; see
2501 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2502 It's likely to work around similar bugs in other operating systems, so do it
2503 on all platforms. Round INT_MAX down to a page size, with the conservative
2504 assumption that page sizes are at most 2**18 bytes (any kernel with a
2505 page size larger than that shouldn't have the bug). */
2506 #ifndef MAX_RW_COUNT
2507 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2510 /* Read from FD to a buffer BUF with size NBYTE.
2511 If interrupted, process any quits and pending signals immediately
2512 if INTERRUPTIBLE, and then retry the read unless quitting.
2513 Return the number of bytes read, which might be less than NBYTE.
2514 On error, set errno to a value other than EINTR, and return -1. */
2516 emacs_intr_read (int fd
, void *buf
, ptrdiff_t nbyte
, bool interruptible
)
2520 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2521 passes a size that large to emacs_read. */
2526 result
= read (fd
, buf
, nbyte
);
2528 while (result
< 0 && errno
== EINTR
);
2533 /* Read from FD to a buffer BUF with size NBYTE.
2534 If interrupted, retry the read. Return the number of bytes read,
2535 which might be less than NBYTE. On error, set errno to a value
2536 other than EINTR, and return -1. */
2538 emacs_read (int fd
, void *buf
, ptrdiff_t nbyte
)
2540 return emacs_intr_read (fd
, buf
, nbyte
, false);
2543 /* Like emacs_read, but also process quits and pending signals. */
2545 emacs_read_quit (int fd
, void *buf
, ptrdiff_t nbyte
)
2547 return emacs_intr_read (fd
, buf
, nbyte
, true);
2550 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2551 interrupted or if a partial write occurs. Process any quits
2552 immediately if INTERRUPTIBLE is positive, and process any pending
2553 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2554 of bytes written; if this is less than NBYTE, set errno to a value
2555 other than EINTR. */
2557 emacs_full_write (int fd
, char const *buf
, ptrdiff_t nbyte
,
2560 ptrdiff_t bytes_written
= 0;
2564 ssize_t n
= write (fd
, buf
, min (nbyte
, MAX_RW_COUNT
));
2573 if (0 < interruptible
)
2575 if (pending_signals
)
2576 process_pending_signals ();
2587 return bytes_written
;
2590 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2591 interrupted or if a partial write occurs. Do not process quits or
2592 pending signals. Return the number of bytes written, setting errno
2593 if this is less than NBYTE. */
2595 emacs_write (int fd
, void const *buf
, ptrdiff_t nbyte
)
2597 return emacs_full_write (fd
, buf
, nbyte
, 0);
2600 /* Like emacs_write, but also process pending signals. */
2602 emacs_write_sig (int fd
, void const *buf
, ptrdiff_t nbyte
)
2604 return emacs_full_write (fd
, buf
, nbyte
, -1);
2607 /* Like emacs_write, but also process quits and pending signals. */
2609 emacs_write_quit (int fd
, void const *buf
, ptrdiff_t nbyte
)
2611 return emacs_full_write (fd
, buf
, nbyte
, 1);
2614 /* Write a diagnostic to standard error that contains MESSAGE and a
2615 string derived from errno. Preserve errno. Do not buffer stderr.
2616 Do not process quits or pending signals if interrupted. */
2618 emacs_perror (char const *message
)
2621 char const *error_string
= emacs_strerror (err
);
2622 char const *command
= (initial_argv
&& initial_argv
[0]
2623 ? initial_argv
[0] : "emacs");
2624 /* Write it out all at once, if it's short; this is less likely to
2625 be interleaved with other output. */
2627 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2628 command
, message
, error_string
);
2629 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2630 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2633 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2634 emacs_write (STDERR_FILENO
, ": ", 2);
2635 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2636 emacs_write (STDERR_FILENO
, ": ", 2);
2637 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2638 emacs_write (STDERR_FILENO
, "\n", 1);
2643 /* Return a struct timeval that is roughly equivalent to T.
2644 Use the least timeval not less than T.
2645 Return an extremal value if the result would overflow. */
2647 make_timeval (struct timespec t
)
2650 tv
.tv_sec
= t
.tv_sec
;
2651 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2653 if (t
.tv_nsec
% 1000 != 0)
2655 if (tv
.tv_usec
< 999999)
2657 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2667 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2668 ATIME and MTIME, respectively.
2669 FD must be either negative -- in which case it is ignored --
2670 or a file descriptor that is open on FILE.
2671 If FD is nonnegative, then FILE can be NULL. */
2673 set_file_times (int fd
, const char *filename
,
2674 struct timespec atime
, struct timespec mtime
)
2676 struct timespec timespec
[2];
2677 timespec
[0] = atime
;
2678 timespec
[1] = mtime
;
2679 return fdutimens (fd
, filename
, timespec
);
2682 /* Like strsignal, except async-signal-safe, and this function typically
2683 returns a string in the C locale rather than the current locale. */
2685 safe_strsignal (int code
)
2687 char const *signame
= 0;
2689 if (0 <= code
&& code
< sys_siglist_entries
)
2690 signame
= sys_siglist
[code
];
2692 signame
= "Unknown signal";
2698 /* For make-serial-process */
2700 serial_open (Lisp_Object port
)
2702 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2704 report_file_error ("Opening serial port", port
);
2706 ioctl (fd
, TIOCEXCL
, (char *) 0);
2712 #if !defined (HAVE_CFMAKERAW)
2713 /* Workaround for targets which are missing cfmakeraw. */
2714 /* Pasted from man page. */
2716 cfmakeraw (struct termios
*termios_p
)
2718 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2719 termios_p
->c_oflag
&= ~OPOST
;
2720 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2721 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2722 termios_p
->c_cflag
|= CS8
;
2724 #endif /* !defined (HAVE_CFMAKERAW */
2726 #if !defined (HAVE_CFSETSPEED)
2727 /* Workaround for targets which are missing cfsetspeed. */
2729 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2731 return (cfsetispeed (termios_p
, vitesse
)
2732 + cfsetospeed (termios_p
, vitesse
));
2736 /* For serial-process-configure */
2738 serial_configure (struct Lisp_Process
*p
,
2739 Lisp_Object contact
)
2741 Lisp_Object childp2
= Qnil
;
2742 Lisp_Object tem
= Qnil
;
2743 struct termios attr
;
2745 char summary
[4] = "???"; /* This usually becomes "8N1". */
2747 childp2
= Fcopy_sequence (p
->childp
);
2749 /* Read port attributes and prepare default configuration. */
2750 err
= tcgetattr (p
->outfd
, &attr
);
2752 report_file_error ("Failed tcgetattr", Qnil
);
2754 #if defined (CLOCAL)
2755 attr
.c_cflag
|= CLOCAL
;
2758 attr
.c_cflag
|= CREAD
;
2761 /* Configure speed. */
2762 if (!NILP (Fplist_member (contact
, QCspeed
)))
2763 tem
= Fplist_get (contact
, QCspeed
);
2765 tem
= Fplist_get (p
->childp
, QCspeed
);
2767 err
= cfsetspeed (&attr
, XINT (tem
));
2769 report_file_error ("Failed cfsetspeed", tem
);
2770 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2772 /* Configure bytesize. */
2773 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2774 tem
= Fplist_get (contact
, QCbytesize
);
2776 tem
= Fplist_get (p
->childp
, QCbytesize
);
2778 tem
= make_number (8);
2780 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2781 error (":bytesize must be nil (8), 7, or 8");
2782 summary
[0] = XINT (tem
) + '0';
2783 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2784 attr
.c_cflag
&= ~CSIZE
;
2785 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2787 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2788 if (XINT (tem
) != 8)
2789 error ("Bytesize cannot be changed");
2791 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2793 /* Configure parity. */
2794 if (!NILP (Fplist_member (contact
, QCparity
)))
2795 tem
= Fplist_get (contact
, QCparity
);
2797 tem
= Fplist_get (p
->childp
, QCparity
);
2798 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2799 error (":parity must be nil (no parity), `even', or `odd'");
2800 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2801 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2802 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2807 else if (EQ (tem
, Qeven
))
2810 attr
.c_cflag
|= PARENB
;
2811 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2813 else if (EQ (tem
, Qodd
))
2816 attr
.c_cflag
|= (PARENB
| PARODD
);
2817 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2820 /* Don't error on no parity, which should be set by cfmakeraw. */
2822 error ("Parity cannot be configured");
2824 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2826 /* Configure stopbits. */
2827 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2828 tem
= Fplist_get (contact
, QCstopbits
);
2830 tem
= Fplist_get (p
->childp
, QCstopbits
);
2832 tem
= make_number (1);
2834 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2835 error (":stopbits must be nil (1 stopbit), 1, or 2");
2836 summary
[2] = XINT (tem
) + '0';
2837 #if defined (CSTOPB)
2838 attr
.c_cflag
&= ~CSTOPB
;
2839 if (XINT (tem
) == 2)
2840 attr
.c_cflag
|= CSTOPB
;
2842 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2843 if (XINT (tem
) != 1)
2844 error ("Stopbits cannot be configured");
2846 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2848 /* Configure flowcontrol. */
2849 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2850 tem
= Fplist_get (contact
, QCflowcontrol
);
2852 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2853 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2854 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2855 #if defined (CRTSCTS)
2856 attr
.c_cflag
&= ~CRTSCTS
;
2858 #if defined (CNEW_RTSCTS)
2859 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2861 #if defined (IXON) && defined (IXOFF)
2862 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2866 /* Already configured. */
2868 else if (EQ (tem
, Qhw
))
2870 #if defined (CRTSCTS)
2871 attr
.c_cflag
|= CRTSCTS
;
2872 #elif defined (CNEW_RTSCTS)
2873 attr
.c_cflag
|= CNEW_RTSCTS
;
2875 error ("Hardware flowcontrol (RTS/CTS) not supported");
2878 else if (EQ (tem
, Qsw
))
2880 #if defined (IXON) && defined (IXOFF)
2881 attr
.c_iflag
|= (IXON
| IXOFF
);
2883 error ("Software flowcontrol (XON/XOFF) not supported");
2886 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2888 /* Activate configuration. */
2889 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2891 report_file_error ("Failed tcsetattr", Qnil
);
2893 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2894 pset_childp (p
, childp2
);
2896 #endif /* not DOS_NT */
2898 /* System depended enumeration of and access to system processes a-la ps(1). */
2902 /* Process enumeration and access via /proc. */
2905 list_system_processes (void)
2907 Lisp_Object procdir
, match
, proclist
, next
;
2910 /* For every process on the system, there's a directory in the
2911 "/proc" pseudo-directory whose name is the numeric ID of that
2913 procdir
= build_string ("/proc");
2914 match
= build_string ("[0-9]+");
2915 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2917 /* `proclist' gives process IDs as strings. Destructively convert
2918 each string into a number. */
2919 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2922 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2925 /* directory_files_internal returns the files in reverse order; undo
2927 proclist
= Fnreverse (proclist
);
2931 #elif defined DARWIN_OS || defined __FreeBSD__
2934 list_system_processes (void)
2937 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2939 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2942 struct kinfo_proc
*procs
;
2945 Lisp_Object proclist
= Qnil
;
2947 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2950 procs
= xmalloc (len
);
2951 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2957 len
/= sizeof (struct kinfo_proc
);
2958 for (i
= 0; i
< len
; i
++)
2961 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2963 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2972 /* The WINDOWSNT implementation is in w32.c.
2973 The MSDOS implementation is in dosfns.c. */
2974 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2977 list_system_processes (void)
2982 #endif /* !defined (WINDOWSNT) */
2984 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2985 static struct timespec
2986 time_from_jiffies (unsigned long long tval
, long hz
)
2988 unsigned long long s
= tval
/ hz
;
2989 unsigned long long frac
= tval
% hz
;
2992 if (TYPE_MAXIMUM (time_t) < s
)
2994 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2995 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2996 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2999 /* This is reachable only in the unlikely case that HZ * HZ
3000 exceeds ULLONG_MAX. It calculates an approximation that is
3001 guaranteed to be in range. */
3002 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
3003 + (hz
% TIMESPEC_RESOLUTION
!= 0));
3004 ns
= frac
/ hz_per_ns
;
3007 return make_timespec (s
, ns
);
3011 ltime_from_jiffies (unsigned long long tval
, long hz
)
3013 struct timespec t
= time_from_jiffies (tval
, hz
);
3014 return make_lisp_time (t
);
3017 static struct timespec
3021 struct timespec up
= make_timespec (0, 0);
3024 fup
= emacs_fopen ("/proc/uptime", "r");
3028 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
3029 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
3031 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
3032 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
3033 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
3036 if (TYPE_MAXIMUM (time_t) < upsec
)
3038 upsec
= TYPE_MAXIMUM (time_t);
3039 upfrac
= TIMESPEC_RESOLUTION
- 1;
3043 int upfraclen
= upfrac_end
- upfrac_start
;
3044 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3046 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3048 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3050 up
= make_timespec (upsec
, upfrac
);
3059 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3060 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3063 procfs_ttyname (int rdev
)
3066 char name
[PATH_MAX
];
3069 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3075 unsigned long minor_beg
, minor_end
;
3076 char minor
[25]; /* 2 32-bit numbers + dash */
3079 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3081 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3082 && major
== MAJOR (rdev
))
3084 minor_beg
= strtoul (minor
, &endp
, 0);
3086 minor_end
= minor_beg
;
3087 else if (*endp
== '-')
3088 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3092 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3094 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3102 return build_string (name
);
3106 procfs_get_total_memory (void)
3109 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3113 fmem
= emacs_fopen ("/proc/meminfo", "r");
3117 uintmax_t entry_value
;
3121 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3124 retval
= entry_value
;
3129 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3147 system_process_attributes (Lisp_Object pid
)
3149 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3153 long clocks_per_sec
;
3155 char procbuf
[1025], *p
, *q
;
3158 static char const default_cmd
[] = "???";
3159 const char *cmd
= default_cmd
;
3160 int cmdsize
= sizeof default_cmd
- 1;
3161 char *cmdline
= NULL
;
3162 ptrdiff_t cmdline_size
;
3165 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3168 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3169 long priority
, niceness
, rss
;
3170 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3171 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3173 Lisp_Object attrs
= Qnil
;
3174 Lisp_Object decoded_cmd
;
3177 CHECK_NUMBER_OR_FLOAT (pid
);
3178 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3179 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3180 if (stat (procfn
, &st
) < 0)
3185 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3187 pw
= getpwuid (uid
);
3190 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3193 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3195 gr
= getgrgid (gid
);
3198 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3200 count
= SPECPDL_INDEX ();
3201 strcpy (fn
, procfn
);
3202 procfn_end
= fn
+ strlen (fn
);
3203 strcpy (procfn_end
, "/stat");
3204 fd
= emacs_open (fn
, O_RDONLY
, 0);
3209 record_unwind_protect_int (close_file_unwind
, fd
);
3210 nread
= emacs_read_quit (fd
, procbuf
, sizeof procbuf
- 1);
3214 procbuf
[nread
] = '\0';
3217 p
= strchr (p
, '(');
3220 q
= strrchr (p
+ 1, ')');
3230 /* Command name is encoded in locale-coding-system; decode it. */
3231 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3232 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3233 Vlocale_coding_system
, 0);
3234 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3236 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3237 utime stime cutime cstime priority nice thcount . start vsize rss */
3239 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3240 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3241 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3242 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3243 &u_time
, &s_time
, &cutime
, &cstime
,
3244 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3249 state_str
[1] = '\0';
3250 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3251 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3252 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3253 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3254 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3255 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3256 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3257 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3258 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3260 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3262 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3263 if (clocks_per_sec
< 0)
3264 clocks_per_sec
= 100;
3265 attrs
= Fcons (Fcons (Qutime
,
3266 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3268 attrs
= Fcons (Fcons (Qstime
,
3269 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3271 attrs
= Fcons (Fcons (Qtime
,
3272 ltime_from_jiffies (s_time
+ u_time
,
3275 attrs
= Fcons (Fcons (Qcutime
,
3276 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3278 attrs
= Fcons (Fcons (Qcstime
,
3279 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3281 attrs
= Fcons (Fcons (Qctime
,
3282 ltime_from_jiffies (cstime
+ cutime
,
3285 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3286 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3287 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3289 tnow
= current_timespec ();
3290 telapsed
= get_up_time ();
3291 tboot
= timespec_sub (tnow
, telapsed
);
3292 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3293 tstart
= timespec_add (tboot
, tstart
);
3294 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3295 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3297 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3298 telapsed
= timespec_sub (tnow
, tstart
);
3299 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3300 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3301 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3304 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3305 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3308 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3311 unbind_to (count
, Qnil
);
3314 strcpy (procfn_end
, "/cmdline");
3315 fd
= emacs_open (fn
, O_RDONLY
, 0);
3318 ptrdiff_t readsize
, nread_incr
;
3319 record_unwind_protect_int (close_file_unwind
, fd
);
3320 record_unwind_protect_nothing ();
3321 nread
= cmdline_size
= 0;
3325 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3326 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3328 /* Leave room even if every byte needs escaping below. */
3329 readsize
= (cmdline_size
>> 1) - nread
;
3331 nread_incr
= emacs_read_quit (fd
, cmdline
+ nread
, readsize
);
3332 nread
+= max (0, nread_incr
);
3334 while (nread_incr
== readsize
);
3338 /* We don't want trailing null characters. */
3339 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3342 /* Escape-quote whitespace and backslashes. */
3343 q
= cmdline
+ cmdline_size
;
3348 if (c_isspace (c
) || c
== '\\')
3352 nread
= cmdline
+ cmdline_size
- q
;
3357 nread
= cmdsize
+ 2;
3358 cmdline_size
= nread
+ 1;
3359 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3360 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3361 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3363 /* Command line is encoded in locale-coding-system; decode it. */
3364 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3365 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3366 Vlocale_coding_system
, 0);
3367 unbind_to (count
, Qnil
);
3368 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3374 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3376 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3377 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3378 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3379 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3380 #undef _FILE_OFFSET_BITS
3382 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3387 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3388 #define _FILE_OFFSET_BITS 64
3389 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3391 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3394 system_process_attributes (Lisp_Object pid
)
3396 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3401 struct psinfo pinfo
;
3407 Lisp_Object attrs
= Qnil
;
3408 Lisp_Object decoded_cmd
;
3411 CHECK_NUMBER_OR_FLOAT (pid
);
3412 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3413 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3414 if (stat (procfn
, &st
) < 0)
3419 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3421 pw
= getpwuid (uid
);
3424 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3427 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3429 gr
= getgrgid (gid
);
3432 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3434 count
= SPECPDL_INDEX ();
3435 strcpy (fn
, procfn
);
3436 procfn_end
= fn
+ strlen (fn
);
3437 strcpy (procfn_end
, "/psinfo");
3438 fd
= emacs_open (fn
, O_RDONLY
, 0);
3443 record_unwind_protect_int (close_file_unwind
, fd
);
3444 nread
= emacs_read_quit (fd
, &pinfo
, sizeof pinfo
);
3447 if (nread
== sizeof pinfo
)
3449 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3450 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3451 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3455 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3456 state_str
[1] = '\0';
3457 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3460 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3461 need to get a string from it. */
3463 /* FIXME: missing: Qtpgid */
3475 Are they available? */
3477 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3478 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3479 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3480 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3481 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3484 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3485 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3487 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3490 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3491 range 0 .. 2**15, representing 0.0 .. 1.0. */
3492 attrs
= Fcons (Fcons (Qpcpu
,
3493 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3495 attrs
= Fcons (Fcons (Qpmem
,
3496 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3499 AUTO_STRING (fname
, pinfo
.pr_fname
);
3500 decoded_cmd
= code_convert_string_norecord (fname
,
3501 Vlocale_coding_system
, 0);
3502 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3503 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3504 decoded_cmd
= code_convert_string_norecord (psargs
,
3505 Vlocale_coding_system
, 0);
3506 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3508 unbind_to (count
, Qnil
);
3512 #elif defined __FreeBSD__
3514 static struct timespec
3515 timeval_to_timespec (struct timeval t
)
3517 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3521 make_lisp_timeval (struct timeval t
)
3523 return make_lisp_time (timeval_to_timespec (t
));
3527 system_process_attributes (Lisp_Object pid
)
3530 int pagesize
= getpagesize ();
3531 unsigned long npages
;
3537 char args
[MAXPATHLEN
];
3538 struct timespec t
, now
;
3540 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3541 struct kinfo_proc proc
;
3542 size_t proclen
= sizeof proc
;
3544 Lisp_Object attrs
= Qnil
;
3545 Lisp_Object decoded_comm
;
3547 CHECK_NUMBER_OR_FLOAT (pid
);
3548 CONS_TO_INTEGER (pid
, int, proc_id
);
3551 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3554 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3557 pw
= getpwuid (proc
.ki_uid
);
3560 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3562 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3565 gr
= getgrgid (proc
.ki_svgid
);
3568 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3570 AUTO_STRING (comm
, proc
.ki_comm
);
3571 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3573 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3575 char state
[2] = {'\0', '\0'};
3576 switch (proc
.ki_stat
)
3598 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3601 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3602 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3603 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3606 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3609 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3611 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3612 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3613 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3614 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3615 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3617 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3619 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3621 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3622 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3623 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3625 attrs
= Fcons (Fcons (Qcutime
,
3626 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3628 attrs
= Fcons (Fcons (Qcstime
,
3629 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3631 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3632 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3633 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3635 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3637 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3638 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3639 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3640 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3641 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3644 now
= current_timespec ();
3645 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3646 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3648 len
= sizeof fscale
;
3649 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3654 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3656 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3657 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3658 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3662 len
= sizeof npages
;
3663 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3665 double pmem
= (proc
.ki_flag
& P_INMEM
3666 ? 100.0 * proc
.ki_rssize
/ npages
3668 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3671 mib
[2] = KERN_PROC_ARGS
;
3673 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3676 for (i
= 0; i
< len
; i
++)
3678 if (! args
[i
] && i
< len
- 1)
3682 AUTO_STRING (comm
, args
);
3683 decoded_comm
= code_convert_string_norecord (comm
,
3684 Vlocale_coding_system
, 0);
3686 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3692 #elif defined DARWIN_OS
3694 static struct timespec
3695 timeval_to_timespec (struct timeval t
)
3697 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3701 make_lisp_timeval (struct timeval t
)
3703 return make_lisp_time (timeval_to_timespec (t
));
3707 system_process_attributes (Lisp_Object pid
)
3710 int pagesize
= getpagesize ();
3711 unsigned long npages
;
3717 char args
[MAXPATHLEN
];
3718 struct timeval starttime
;
3719 struct timespec t
, now
;
3720 struct rusage
*rusage
;
3725 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3726 struct kinfo_proc proc
;
3727 size_t proclen
= sizeof proc
;
3729 Lisp_Object attrs
= Qnil
;
3730 Lisp_Object decoded_comm
;
3732 CHECK_NUMBER_OR_FLOAT (pid
);
3733 CONS_TO_INTEGER (pid
, int, proc_id
);
3736 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3739 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3740 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3743 pw
= getpwuid (uid
);
3746 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3748 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3749 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3752 gr
= getgrgid (gid
);
3755 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3757 decoded_comm
= (code_convert_string_norecord
3758 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3759 Vlocale_coding_system
, 0));
3761 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3763 char state
[2] = {'\0', '\0'};
3764 switch (proc
.kp_proc
.p_stat
)
3786 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3789 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3791 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3794 tdev
= proc
.kp_eproc
.e_tdev
;
3796 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3799 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3801 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3804 rusage
= proc
.kp_proc
.p_ru
;
3807 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3809 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3812 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3814 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3816 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3817 timeval_to_timespec (rusage
->ru_stime
));
3818 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3821 starttime
= proc
.kp_proc
.p_starttime
;
3822 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3823 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3825 now
= current_timespec ();
3826 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3827 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3832 /* The WINDOWSNT implementation is in w32.c.
3833 The MSDOS implementation is in dosfns.c. */
3834 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3837 system_process_attributes (Lisp_Object pid
)
3842 #endif /* !defined (WINDOWSNT) */
3844 /* Wide character string collation. */
3846 #ifdef __STDC_ISO_10646__
3848 # include <wctype.h>
3850 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3851 # include <locale.h>
3854 # define LC_COLLATE 0
3856 # ifndef LC_COLLATE_MASK
3857 # define LC_COLLATE_MASK 0
3862 # ifndef LC_CTYPE_MASK
3863 # define LC_CTYPE_MASK 0
3866 # ifndef HAVE_NEWLOCALE
3872 # define freelocale emacs_freelocale
3873 # define locale_t emacs_locale_t
3874 # define newlocale emacs_newlocale
3875 # define wcscoll_l emacs_wcscoll_l
3876 # define towlower_l emacs_towlower_l
3878 typedef char const *locale_t
;
3881 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3887 freelocale (locale_t loc
)
3892 emacs_setlocale (int category
, char const *locale
)
3894 # ifdef HAVE_SETLOCALE
3896 char *loc
= setlocale (category
, locale
);
3907 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3910 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3918 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3919 strcpy (oldcopy
, oldloc
);
3920 if (! emacs_setlocale (LC_COLLATE
, loc
))
3925 result
= wcscoll (a
, b
);
3927 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3938 towlower_l (wint_t wc
, locale_t loc
)
3941 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3946 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3947 strcpy (oldcopy
, oldloc
);
3948 if (emacs_setlocale (LC_CTYPE
, loc
))
3950 result
= towlower (wc
);
3951 emacs_setlocale (LC_COLLATE
, oldcopy
);
3961 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3962 Lisp_Object locale
, Lisp_Object ignore_case
)
3965 ptrdiff_t len
, i
, i_byte
;
3970 /* Convert byte stream to code points. */
3971 len
= SCHARS (s1
); i
= i_byte
= 0;
3972 SAFE_NALLOCA (p1
, 1, len
+ 1);
3974 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3977 len
= SCHARS (s2
); i
= i_byte
= 0;
3978 SAFE_NALLOCA (p2
, 1, len
+ 1);
3980 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3983 if (STRINGP (locale
))
3985 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3986 SSDATA (locale
), 0);
3988 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3990 if (! NILP (ignore_case
))
3991 for (int i
= 1; i
< 3; i
++)
3993 wchar_t *p
= (i
== 1) ? p1
: p2
;
3995 *p
= towlower_l (*p
, loc
);
3999 res
= wcscoll_l (p1
, p2
, loc
);
4005 if (! NILP (ignore_case
))
4006 for (int i
= 1; i
< 3; i
++)
4008 wchar_t *p
= (i
== 1) ? p1
: p2
;
4014 res
= wcscoll (p1
, p2
);
4017 # ifndef HAVE_NEWLOCALE
4019 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
4022 error ("Invalid string for collation: %s", emacs_strerror (err
));
4028 #endif /* __STDC_ISO_10646__ */
4032 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4033 Lisp_Object locale
, Lisp_Object ignore_case
)
4036 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
4037 int res
, err
= errno
;
4040 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4042 error ("Invalid string for collation: %s", strerror (errno
));
4047 #endif /* WINDOWSNT */