1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2018 Free Software
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
27 #endif /* HAVE_PWD_H */
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #ifdef HAVE_LINUX_FS_H
41 # include <linux/fs.h>
42 # include <sys/syscall.h>
46 # include <cygwin/fs.h>
49 #if defined DARWIN_OS || defined __FreeBSD__
50 # include <sys/sysctl.h>
54 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
55 'struct frame', so rename it. */
56 # define frame freebsd_frame
57 # include <sys/user.h>
64 #include <sys/socket.h>
66 #endif /* HAVE_SOCKETS */
70 #define write sys_write
72 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
75 #endif /* WINDOWSNT */
77 #include <sys/types.h>
81 /* Get SI_SRPC_DOMAIN, if it is available. */
82 #ifdef HAVE_SYS_SYSTEMINFO_H
83 #include <sys/systeminfo.h>
86 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
90 #include <sys/param.h>
97 #ifdef HAVE_SYS_UTSNAME_H
98 #include <sys/utsname.h>
100 #endif /* HAVE_SYS_UTSNAME_H */
102 #include "keyboard.h"
104 #include "termhooks.h"
105 #include "termchar.h"
106 #include "termopts.h"
111 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
112 do that during startup just to call gnutls_rnd. */
113 #if defined HAVE_GNUTLS && !defined WINDOWSNT
114 # include <gnutls/crypto.h>
116 # define emacs_gnutls_global_init() Qnil
117 # define gnutls_rnd(level, data, len) (-1)
122 /* In process.h which conflicts with the local copy. */
124 int _cdecl
_spawnlp (int, const char *, const char *, ...);
125 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
126 several prototypes of functions called below. */
127 #include <sys/socket.h>
130 #include "syssignal.h"
133 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
135 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
138 /* Declare here, including term.h is problematic on some systems. */
139 extern void tputs (const char *, int, int (*)(int));
141 static const int baud_convert
[] =
143 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
144 1800, 2400, 4800, 9600, 19200, 38400
147 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
148 # include <sys/personality.h>
150 /* Disable address randomization in the current process. Return true
151 if addresses were randomized but this has been disabled, false
154 disable_address_randomization (void)
156 int pers
= personality (0xffffffff);
159 int desired_pers
= pers
| ADDR_NO_RANDOMIZE
;
161 /* Call 'personality' twice, to detect buggy platforms like WSL
162 where 'personality' always returns 0. */
163 return (pers
!= desired_pers
164 && personality (desired_pers
) == pers
165 && personality (0xffffffff) == desired_pers
);
169 /* Execute the program in FILE, with argument vector ARGV and environ
170 ENVP. Return an error number if unsuccessful. This is like execve
171 except it reenables ASLR in the executed program if necessary, and
172 on error it returns an error number rather than -1. */
174 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
176 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
177 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
178 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
179 if (change_personality
)
180 personality (pers
& ~ADDR_NO_RANDOMIZE
);
183 execve (file
, argv
, envp
);
186 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
187 if (change_personality
)
194 /* If FD is not already open, arrange for it to be open with FLAGS. */
196 force_open (int fd
, int flags
)
198 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
200 int n
= open (NULL_DEVICE
, flags
);
201 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
203 emacs_perror (NULL_DEVICE
);
209 /* Make sure stdin, stdout, and stderr are open to something, so that
210 their file descriptors are not hijacked by later system calls. */
212 init_standard_fds (void)
214 /* Open stdin for *writing*, and stdout and stderr for *reading*.
215 That way, any attempt to do normal I/O will result in an error,
216 just as if the files were closed, and the file descriptors will
217 not be reused by later opens. */
218 force_open (STDIN_FILENO
, O_WRONLY
);
219 force_open (STDOUT_FILENO
, O_RDONLY
);
220 force_open (STDERR_FILENO
, O_RDONLY
);
223 /* Return the current working directory. The result should be freed
224 with 'free'. Return NULL (setting errno) on errors. If the
225 current directory is unreachable, return either NULL or a string
226 beginning with '('. */
229 get_current_dir_name_or_unreachable (void)
231 /* Use malloc, not xmalloc, since this function can be called before
232 the xmalloc exception machinery is available. */
236 /* The maximum size of a directory name, including the terminating null.
237 Leave room so that the caller can append a trailing slash. */
238 ptrdiff_t dirsize_max
= min (PTRDIFF_MAX
, SIZE_MAX
) - 1;
240 /* The maximum size of a buffer for a file name, including the
241 terminating null. This is bounded by MAXPATHLEN, if available. */
242 ptrdiff_t bufsize_max
= dirsize_max
;
244 bufsize_max
= min (bufsize_max
, MAXPATHLEN
);
247 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
248 # ifdef HYBRID_MALLOC
249 bool use_libc
= bss_sbrk_did_unexec
;
251 bool use_libc
= true;
255 /* For an unreachable directory, this returns a string that starts
256 with "(unreachable)"; see Bug#27871. */
257 pwd
= get_current_dir_name ();
260 if (strlen (pwd
) < dirsize_max
)
270 struct stat dotstat
, pwdstat
;
271 pwd
= getenv ("PWD");
273 /* If PWD is accurate, use it instead of calling getcwd. PWD is
274 sometimes a nicer name, and using it may avoid a fatal error if a
275 parent directory is searchable but not readable. */
277 && (pwdlen
= strlen (pwd
)) < bufsize_max
278 && IS_DIRECTORY_SEP (pwd
[pwdlen
&& IS_DEVICE_SEP (pwd
[1]) ? 2 : 0])
279 && stat (pwd
, &pwdstat
) == 0
280 && stat (".", &dotstat
) == 0
281 && dotstat
.st_ino
== pwdstat
.st_ino
282 && dotstat
.st_dev
== pwdstat
.st_dev
)
284 char *buf
= malloc (pwdlen
+ 1);
287 return memcpy (buf
, pwd
, pwdlen
+ 1);
291 ptrdiff_t buf_size
= min (bufsize_max
, 1024);
292 char *buf
= malloc (buf_size
);
297 if (getcwd (buf
, buf_size
) == buf
)
299 int getcwd_errno
= errno
;
300 if (getcwd_errno
!= ERANGE
|| buf_size
== bufsize_max
)
303 errno
= getcwd_errno
;
306 buf_size
= buf_size
<= bufsize_max
/ 2 ? 2 * buf_size
: bufsize_max
;
307 buf
= realloc (buf
, buf_size
);
314 /* Return the current working directory. The result should be freed
315 with 'free'. Return NULL (setting errno) on errors; an unreachable
316 directory (e.g., its name starts with '(') counts as an error. */
319 emacs_get_current_dir_name (void)
321 char *dir
= get_current_dir_name_or_unreachable ();
322 if (dir
&& *dir
== '(')
332 /* Discard pending input on all input descriptors. */
335 discard_tty_input (void)
338 struct emacs_tty buf
;
343 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
344 while (dos_keyread () != -1)
346 #else /* not MSDOS */
348 struct tty_display_info
*tty
;
349 for (tty
= tty_list
; tty
; tty
= tty
->next
)
351 if (tty
->input
) /* Is the device suspended? */
353 emacs_get_tty (fileno (tty
->input
), &buf
);
354 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
358 #endif /* not MSDOS */
359 #endif /* not WINDOWSNT */
365 /* Arrange for character C to be read as the next input from
367 XXX What if we have multiple ttys?
373 if (! (FRAMEP (selected_frame
)
374 && FRAME_LIVE_P (XFRAME (selected_frame
))
375 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
378 /* Should perhaps error if in batch mode */
380 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
381 #else /* no TIOCSTI */
382 error ("Cannot stuff terminal input characters in this version of Unix");
383 #endif /* no TIOCSTI */
389 init_baud_rate (int fd
)
399 #else /* not DOS_NT */
404 emacs_ospeed
= cfgetospeed (&sg
);
405 #endif /* not DOS_NT */
408 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
409 ? baud_convert
[emacs_ospeed
] : 9600);
418 /* Wait for the subprocess with process id CHILD to terminate or change status.
419 CHILD must be a child process that has not been reaped.
420 If STATUS is non-null, store the waitpid-style exit status into *STATUS
421 and tell wait_reading_process_output that it needs to look around.
422 Use waitpid-style OPTIONS when waiting.
423 If INTERRUPTIBLE, this function is interruptible by a signal.
425 Return CHILD if successful, 0 if no status is available, and a
426 negative value (setting errno) if waitpid is buggy. */
428 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
432 /* Invoke waitpid only with a known process ID; do not invoke
433 waitpid with a nonpositive argument. Otherwise, Emacs might
434 reap an unwanted process by mistake. For example, invoking
435 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
436 so that another thread running glib won't find them. */
441 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
446 pid
= waitpid (child
, status
, options
);
451 /* Most likely, waitpid is buggy and the operating system
452 lost track of the child somehow. Return -1 and let the
453 caller try to figure things out. Possibly the bug could
454 cause Emacs to kill the wrong process. Oh well. */
459 /* If successful and status is requested, tell wait_reading_process_output
460 that it needs to wake up and look around. */
461 if (pid
&& status
&& input_available_clear_time
)
462 *input_available_clear_time
= make_timespec (0, 0);
467 /* Wait for the subprocess with process id CHILD to terminate.
468 CHILD must be a child process that has not been reaped.
469 If STATUS is non-null, store the waitpid-style exit status into *STATUS
470 and tell wait_reading_process_output that it needs to look around.
471 If INTERRUPTIBLE, this function is interruptible by a signal.
472 Return true if successful, false (setting errno) if CHILD cannot be
473 waited for because waitpid is buggy. */
475 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
477 return 0 <= get_child_status (child
, status
, 0, interruptible
);
480 /* Report whether the subprocess with process id CHILD has changed status.
481 Termination counts as a change of status.
482 CHILD must be a child process that has not been reaped.
483 If STATUS is non-null, store the waitpid-style exit status into *STATUS
484 and tell wait_reading_process_output that it needs to look around.
485 Use waitpid-style OPTIONS to check status, but do not wait.
487 Return CHILD if successful, 0 if no status is available because
488 the process's state has not changed. */
490 child_status_changed (pid_t child
, int *status
, int options
)
492 return get_child_status (child
, status
, WNOHANG
| options
, 0);
496 /* Set up the terminal at the other end of a pseudo-terminal that
497 we will be controlling an inferior through.
498 It should not echo or do line-editing, since that is done
499 in Emacs. No padding needed for insertion into an Emacs buffer. */
502 child_setup_tty (int out
)
507 emacs_get_tty (out
, &s
);
508 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
509 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
511 /* https://lists.gnu.org/r/emacs-devel/2008-05/msg00406.html
512 Some versions of GNU Hurd do not have FFDLY? */
514 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
515 /* No output delays */
517 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
518 /* No output delays */
521 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
522 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
524 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
527 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
530 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
532 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
533 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
534 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
535 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
538 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
541 #ifdef SIGNALS_VIA_CHARACTERS
542 /* the QUIT and INTR character are used in process_send_signal
543 so set them here to something useful. */
544 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
545 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
546 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
547 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
548 #endif /* not SIGNALS_VIA_CHARACTERS */
551 /* Also, PTY overloads NUL and BREAK.
552 don't ignore break, but don't signal either, so it looks like NUL. */
553 s
.main
.c_iflag
&= ~IGNBRK
;
554 s
.main
.c_iflag
&= ~BRKINT
;
555 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
556 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
557 would force it to 0377. That looks like duplicated code. */
558 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
561 /* We originally enabled ICANON (and set VEOF to 04), and then had
562 process.c send additional EOF chars to flush the output when faced
563 with long lines, but this leads to weird effects when the
564 subprocess has disabled ICANON and ends up seeing those spurious
565 extra EOFs. So we don't send EOFs any more in
566 process.c:send_process. First we tried to disable ICANON by
567 default, so if a subsprocess sets up ICANON, it's his problem (or
568 the Elisp package that talks to it) to deal with lines that are
569 too long. But this disables some features, such as the ability
570 to send EOF signals. So we re-enabled ICANON but there is no
571 more "send eof to flush" going on (which is wrong and unportable
572 in itself). The correct way to handle too much output is to
573 buffer what could not be written and then write it again when
574 select returns ok for writing. This has it own set of
575 problems. Write is now asynchronous, is that a problem? How much
576 do we buffer, and what do we do when that limit is reached? */
578 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
579 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
580 #if 0 /* These settings only apply to non-ICANON mode. */
581 s
.main
.c_cc
[VMIN
] = 1;
582 s
.main
.c_cc
[VTIME
] = 0;
585 emacs_set_tty (out
, &s
, 0);
586 #endif /* not WINDOWSNT */
588 #endif /* not MSDOS */
591 /* Record a signal code and the action for it. */
595 struct sigaction action
;
598 static void save_signal_handlers (struct save_signal
*);
599 static void restore_signal_handlers (struct save_signal
*);
601 /* Suspend the Emacs process; give terminal to its superior. */
609 /* On a system where suspending is not implemented,
610 instead fork a subshell and let it talk directly to the terminal
617 /* Fork a subshell. */
622 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
625 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
627 char oldwd
[MAX_UTF8_PATH
];
633 struct save_signal saved_handlers
[5];
634 char *str
= SSDATA (encode_current_directory ());
640 char *volatile str_volatile
= str
;
647 error ("Can't spawn subshell");
649 saved_handlers
[0].code
= SIGINT
;
650 saved_handlers
[1].code
= SIGQUIT
;
651 saved_handlers
[2].code
= SIGTERM
;
653 saved_handlers
[3].code
= SIGIO
;
654 saved_handlers
[4].code
= 0;
656 saved_handlers
[3].code
= 0;
660 save_signal_handlers (saved_handlers
);
667 #ifdef DOS_NT /* MW, Aug 1993 */
668 getcwd (oldwd
, sizeof oldwd
);
670 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
673 sh
= egetenv ("SHELL");
677 /* Use our buffer's default directory for the subshell. */
678 if (chdir (str
) != 0)
682 _exit (EXIT_CANCELED
);
686 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
688 char *epwd
= getenv ("PWD");
689 char old_pwd
[MAXPATHLEN
+1+4];
691 /* If PWD is set, pass it with corrected value. */
694 strcpy (old_pwd
, epwd
);
695 setenv ("PWD", str
, 1);
698 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
700 putenv (old_pwd
); /* restore previous value */
702 #else /* not MSDOS */
704 /* Waits for process completion */
705 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
706 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
708 write (1, "Can't execute subshell", 22);
709 #else /* not WINDOWSNT */
710 execlp (sh
, sh
, (char *) 0);
712 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
713 #endif /* not WINDOWSNT */
714 #endif /* not MSDOS */
717 /* Do this now if we did not do it before. */
719 save_signal_handlers (saved_handlers
);
723 wait_for_termination (pid
, &status
, 0);
725 restore_signal_handlers (saved_handlers
);
729 save_signal_handlers (struct save_signal
*saved_handlers
)
731 while (saved_handlers
->code
)
733 struct sigaction action
;
734 emacs_sigaction_init (&action
, SIG_IGN
);
735 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
741 restore_signal_handlers (struct save_signal
*saved_handlers
)
743 while (saved_handlers
->code
)
745 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
751 static int old_fcntl_flags
[FD_SETSIZE
];
758 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
759 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
760 interrupts_deferred
= 0;
769 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
783 sigemptyset (&unblocked
);
785 sigaddset (&unblocked
, SIGWINCH
);
787 sigaddset (&unblocked
, SIGIO
);
788 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
790 interrupts_deferred
= 0;
795 unrequest_sigio (void)
803 sigemptyset (&blocked
);
805 sigaddset (&blocked
, SIGWINCH
);
807 sigaddset (&blocked
, SIGIO
);
808 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
809 interrupts_deferred
= 1;
817 block_child_signal (sigset_t
*oldset
)
820 sigemptyset (&blocked
);
821 sigaddset (&blocked
, SIGCHLD
);
822 sigaddset (&blocked
, SIGINT
);
823 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
826 /* Unblock SIGCHLD. */
829 unblock_child_signal (sigset_t
const *oldset
)
831 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
838 block_interrupt_signal (sigset_t
*oldset
)
841 sigemptyset (&blocked
);
842 sigaddset (&blocked
, SIGINT
);
843 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
846 /* Restore previously saved signal mask. */
848 restore_signal_mask (sigset_t
const *oldset
)
850 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
854 /* Saving and restoring the process group of Emacs's terminal. */
856 /* The process group of which Emacs was a member when it initially
859 If Emacs was in its own process group (i.e. inherited_pgroup ==
860 getpid ()), then we know we're running under a shell with job
861 control (Emacs would never be run as part of a pipeline).
864 If Emacs was not in its own process group, then we know we're
865 running under a shell (or a caller) that doesn't know how to
866 separate itself from Emacs (like sh). Emacs must be in its own
867 process group in order to receive SIGIO correctly. In this
868 situation, we put ourselves in our own pgroup, forcibly set the
869 tty's pgroup to our pgroup, and make sure to restore and reinstate
870 the tty's pgroup just like any other terminal setting. If
871 inherited_group was not the tty's pgroup, then we'll get a
872 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
873 it goes foreground in the future, which is what should happen. */
875 static pid_t inherited_pgroup
;
878 init_foreground_group (void)
880 pid_t pgrp
= getpgrp ();
881 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
884 /* Block and unblock SIGTTOU. */
887 block_tty_out_signal (sigset_t
*oldset
)
891 sigemptyset (&blocked
);
892 sigaddset (&blocked
, SIGTTOU
);
893 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
898 unblock_tty_out_signal (sigset_t
const *oldset
)
901 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
905 /* Safely set a controlling terminal FD's process group to PGID.
906 If we are not in the foreground already, POSIX requires tcsetpgrp
907 to deliver a SIGTTOU signal, which would stop us. This is an
908 annoyance, so temporarily ignore the signal.
910 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
911 skip all this unless SIGTTOU is defined. */
913 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
918 block_tty_out_signal (&oldset
);
919 tcsetpgrp (fd
, pgid
);
920 unblock_tty_out_signal (&oldset
);
925 /* Split off the foreground process group to Emacs alone. When we are
926 in the foreground, but not started in our own process group,
927 redirect the tty device handle FD to point to our own process
928 group. FD must be the file descriptor of the controlling tty. */
930 narrow_foreground_group (int fd
)
932 if (inherited_pgroup
&& setpgid (0, 0) == 0)
933 tcsetpgrp_without_stopping (fd
, getpid ());
936 /* Set the tty to our original foreground group. */
938 widen_foreground_group (int fd
)
940 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
941 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
944 /* Getting and setting emacs_tty structures. */
946 /* Set *TC to the parameters associated with the terminal FD,
947 or clear it if the parameters are not available.
948 Return 0 on success, -1 on failure. */
950 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
952 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
953 memset (&settings
->main
, 0, sizeof (settings
->main
));
956 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
959 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
961 settings
->main
= console_mode
;
964 #endif /* WINDOWSNT */
967 /* We have those nifty POSIX tcmumbleattr functions. */
968 return tcgetattr (fd
, &settings
->main
);
973 /* Set the parameters of the tty on FD according to the contents of
974 *SETTINGS. If FLUSHP, discard input.
975 Return 0 if all went well, and -1 (setting errno) if anything failed. */
978 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
980 /* Set the primary parameters - baud rate, character size, etcetera. */
983 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
985 if (h
&& h
!= INVALID_HANDLE_VALUE
)
989 /* Assume the handle is open for input. */
991 FlushConsoleInputBuffer (h
);
992 new_mode
= settings
->main
;
993 SetConsoleMode (h
, new_mode
);
995 #endif /* WINDOWSNT */
998 /* We have those nifty POSIX tcmumbleattr functions.
999 William J. Smith <wjs@wiis.wang.com> writes:
1000 "POSIX 1003.1 defines tcsetattr to return success if it was
1001 able to perform any of the requested actions, even if some
1002 of the requested actions could not be performed.
1003 We must read settings back to ensure tty setup properly.
1004 AIX requires this to keep tty from hanging occasionally." */
1005 /* This make sure that we don't loop indefinitely in here. */
1006 for (i
= 0 ; i
< 10 ; i
++)
1007 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
1018 memset (&new, 0, sizeof (new));
1019 /* Get the current settings, and see if they're what we asked for. */
1020 tcgetattr (fd
, &new);
1021 /* We cannot use memcmp on the whole structure here because under
1022 * aix386 the termios structure has some reserved field that may
1025 if ( new.c_iflag
== settings
->main
.c_iflag
1026 && new.c_oflag
== settings
->main
.c_oflag
1027 && new.c_cflag
== settings
->main
.c_cflag
1028 && new.c_lflag
== settings
->main
.c_lflag
1029 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
1036 /* We have survived the tempest. */
1043 static int old_fcntl_owner
[FD_SETSIZE
];
1044 #endif /* F_SETOWN */
1046 /* This may also be defined in stdio,
1047 but if so, this does no harm,
1048 and using the same name avoids wasting the other one's space. */
1051 unsigned char _sobuf
[BUFSIZ
+8];
1053 char _sobuf
[BUFSIZ
];
1056 /* Initialize the terminal mode on all tty devices that are currently
1060 init_all_sys_modes (void)
1062 struct tty_display_info
*tty
;
1063 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1064 init_sys_modes (tty
);
1067 /* Initialize the terminal mode on the given tty device. */
1070 init_sys_modes (struct tty_display_info
*tty_out
)
1072 struct emacs_tty tty
;
1074 Lisp_Object terminal
;
1077 Vtty_erase_char
= Qnil
;
1082 if (!tty_out
->output
)
1083 return; /* The tty is suspended. */
1085 narrow_foreground_group (fileno (tty_out
->input
));
1087 if (! tty_out
->old_tty
)
1088 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1090 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1092 tty
= *tty_out
->old_tty
;
1094 #if !defined (DOS_NT)
1095 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1097 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1098 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1099 #ifdef INLCR /* I'm just being cautious,
1100 since I can't check how widespread INLCR is--rms. */
1101 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1104 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1106 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1107 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1109 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1111 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1112 if (tty_out
->flow_control
)
1114 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1116 tty
.main
.c_iflag
&= ~IXANY
;
1120 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1121 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1123 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1125 if (tty_out
->meta_key
)
1127 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1128 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1132 XSETTERMINAL(terminal
, tty_out
->terminal
);
1133 if (!NILP (Fcontrolling_tty_p (terminal
)))
1135 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1136 /* Set up C-g for both SIGQUIT and SIGINT.
1137 We don't know which we will get, but we handle both alike
1138 so which one it really gives us does not matter. */
1139 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1143 /* We normally don't get interrupt or quit signals from tty
1144 devices other than our controlling terminal; therefore,
1145 we must handle C-g as normal input. Unfortunately, this
1146 means that the interrupt and quit feature must be
1147 disabled on secondary ttys, or we would not even see the
1150 Note that even though emacsclient could have special code
1151 to pass SIGINT to Emacs, we should _not_ enable
1152 interrupt/quit keys for emacsclient frames. This means
1153 that we can't break out of loops in C code from a
1154 secondary tty frame, but we can always decide what
1155 display the C-g came from, which is more important from a
1156 usability point of view. (Consider the case when two
1157 people work together using the same Emacs instance.) */
1158 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1159 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1161 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1162 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1164 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1169 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1172 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1173 #endif /* V_DSUSP */
1174 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1175 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1178 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1181 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1182 #endif /* VREPRINT */
1184 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1185 #endif /* VWERASE */
1187 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1188 #endif /* VDISCARD */
1190 if (tty_out
->flow_control
)
1193 tty
.main
.c_cc
[VSTART
] = '\021';
1196 tty
.main
.c_cc
[VSTOP
] = '\023';
1202 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1205 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1210 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1211 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1212 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1213 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1214 if (tty_out
->flow_control
)
1217 tty
.main
.c_cc
[VSTART
] = '\021';
1220 tty
.main
.c_cc
[VSTOP
] = '\023';
1223 /* Also, PTY overloads NUL and BREAK.
1224 don't ignore break, but don't signal either, so it looks like NUL.
1225 This really serves a purpose only if running in an XTERM window
1226 or via TELNET or the like, but does no harm elsewhere. */
1227 tty
.main
.c_iflag
&= ~IGNBRK
;
1228 tty
.main
.c_iflag
&= ~BRKINT
;
1230 #endif /* not DOS_NT */
1232 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1233 if (!tty_out
->term_initted
)
1234 internal_terminal_init ();
1235 dos_ttraw (tty_out
);
1238 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1240 /* This code added to insure that, if flow-control is not to be used,
1241 we have an unlocked terminal at the start. */
1244 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1247 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1250 #if !defined (DOS_NT)
1252 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1257 if (interrupt_input
)
1259 old_fcntl_owner
[fileno (tty_out
->input
)] =
1260 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1261 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1262 init_sigio (fileno (tty_out
->input
));
1264 if (gpm_tty
== tty_out
)
1266 /* Arrange for mouse events to give us SIGIO signals. */
1267 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1268 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1269 init_sigio (gpm_fd
);
1271 #endif /* HAVE_GPM */
1273 #endif /* F_GETOWN */
1276 /* This symbol is defined on recent USG systems.
1277 Someone says without this call USG won't really buffer the file
1278 even with a call to setbuf. */
1279 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1281 setbuf (tty_out
->output
, (char *) _sobuf
);
1284 if (tty_out
->terminal
->set_terminal_modes_hook
)
1285 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1287 if (!tty_out
->term_initted
)
1289 Lisp_Object tail
, frame
;
1290 FOR_EACH_FRAME (tail
, frame
)
1292 /* XXX This needs to be revised. */
1293 if (FRAME_TERMCAP_P (XFRAME (frame
))
1294 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1295 init_frame_faces (XFRAME (frame
));
1299 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1301 /* We used to call "direct_output_forward_char(0)" here,
1302 but it's not clear why, since it may not do anything anyway. */
1306 Lisp_Object tail
, frame
;
1308 FOR_EACH_FRAME (tail
, frame
)
1310 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1311 || FRAME_MSDOS_P (XFRAME (frame
)))
1312 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1313 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1317 tty_out
->term_initted
= 1;
1320 /* Return true if safe to use tabs in output.
1321 At the time this is called, init_sys_modes has not been done yet. */
1324 tabs_safe_p (int fd
)
1326 struct emacs_tty etty
;
1328 emacs_get_tty (fd
, &etty
);
1331 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1332 #else /* not TABDLY */
1334 #endif /* not TABDLY */
1340 /* Discard echoing. */
1343 suppress_echo_on_tty (int fd
)
1345 struct emacs_tty etty
;
1347 emacs_get_tty (fd
, &etty
);
1349 /* Set raw input mode. */
1352 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1353 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1354 #endif /* ! WINDOWSNT */
1355 emacs_set_tty (fd
, &etty
, 0);
1358 /* Get terminal size from system.
1359 Store number of lines into *HEIGHTP and width into *WIDTHP.
1360 We store 0 if there's no valid information. */
1363 get_tty_size (int fd
, int *widthp
, int *heightp
)
1365 #if defined TIOCGWINSZ
1368 struct winsize size
;
1370 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1371 *widthp
= *heightp
= 0;
1374 *widthp
= size
.ws_col
;
1375 *heightp
= size
.ws_row
;
1378 #elif defined TIOCGSIZE
1380 /* SunOS - style. */
1381 struct ttysize size
;
1383 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1384 *widthp
= *heightp
= 0;
1387 *widthp
= size
.ts_cols
;
1388 *heightp
= size
.ts_lines
;
1391 #elif defined WINDOWSNT
1393 CONSOLE_SCREEN_BUFFER_INFO info
;
1394 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1396 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1397 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1400 *widthp
= *heightp
= 0;
1404 *widthp
= ScreenCols ();
1405 *heightp
= ScreenRows ();
1407 #else /* system doesn't know size */
1415 /* Set the logical window size associated with descriptor FD
1416 to HEIGHT and WIDTH. This is used mainly with ptys.
1417 Return a negative value on failure. */
1420 set_window_size (int fd
, int height
, int width
)
1425 struct winsize size
;
1426 size
.ws_row
= height
;
1427 size
.ws_col
= width
;
1429 return ioctl (fd
, TIOCSWINSZ
, &size
);
1434 /* SunOS - style. */
1435 struct ttysize size
;
1436 size
.ts_lines
= height
;
1437 size
.ts_cols
= width
;
1439 return ioctl (fd
, TIOCGSIZE
, &size
);
1442 #endif /* not SunOS-style */
1443 #endif /* not BSD-style */
1448 /* Prepare all terminal devices for exiting Emacs. */
1451 reset_all_sys_modes (void)
1453 struct tty_display_info
*tty
;
1454 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1455 reset_sys_modes (tty
);
1458 /* Prepare the terminal for closing it; move the cursor to the
1459 bottom of the frame, turn off interrupt-driven I/O, etc. */
1462 reset_sys_modes (struct tty_display_info
*tty_out
)
1466 fflush_unlocked (stdout
);
1469 if (!tty_out
->term_initted
)
1472 if (!tty_out
->output
)
1473 return; /* The tty is suspended. */
1475 /* Go to and clear the last line of the terminal. */
1477 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1479 /* Code adapted from tty_clear_end_of_line. */
1480 if (tty_out
->TS_clr_line
)
1482 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1485 { /* have to do it the hard way */
1486 tty_turn_off_insert (tty_out
);
1488 for (int i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1489 fputc_unlocked (' ', tty_out
->output
);
1492 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1493 fflush_unlocked (tty_out
->output
);
1495 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1496 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1498 /* Avoid possible loss of output when changing terminal modes. */
1499 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1504 if (interrupt_input
)
1506 reset_sigio (fileno (tty_out
->input
));
1507 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1508 old_fcntl_owner
[fileno (tty_out
->input
)]);
1510 #endif /* F_SETOWN */
1511 fcntl (fileno (tty_out
->input
), F_SETFL
,
1512 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1515 if (tty_out
->old_tty
)
1516 while (emacs_set_tty (fileno (tty_out
->input
),
1517 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1520 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1524 widen_foreground_group (fileno (tty_out
->input
));
1529 /* Set up the proper status flags for use of a pty. */
1534 /* I'm told that TOICREMOTE does not mean control chars
1535 "can't be sent" but rather that they don't have
1536 input-editing or signaling effects.
1537 That should be good, because we have other ways
1538 to do those things in Emacs.
1539 However, telnet mode seems not to work on 4.2.
1540 So TIOCREMOTE is turned off now. */
1542 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1543 will hang. In particular, the "timeout" feature (which
1544 causes a read to return if there is no data available)
1545 does this. Also it is known that telnet mode will hang
1546 in such a way that Emacs must be stopped (perhaps this
1547 is the same problem).
1549 If TIOCREMOTE is turned off, then there is a bug in
1550 hp-ux which sometimes loses data. Apparently the
1551 code which blocks the master process when the internal
1552 buffer fills up does not work. Other than this,
1553 though, everything else seems to work fine.
1555 Since the latter lossage is more benign, we may as well
1556 lose that way. -- cph */
1558 #if defined (UNIX98_PTYS)
1561 ioctl (fd
, FIONBIO
, &on
);
1566 #endif /* HAVE_PTYS */
1569 init_system_name (void)
1573 /* Set system-name to nil so that the build is deterministic. */
1574 Vsystem_name
= Qnil
;
1577 char *hostname_alloc
= NULL
;
1579 #ifndef HAVE_GETHOSTNAME
1582 hostname
= uts
.nodename
;
1583 #else /* HAVE_GETHOSTNAME */
1584 char hostname_buf
[256];
1585 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1586 hostname
= hostname_buf
;
1588 /* Try to get the host name; if the buffer is too short, try
1589 again. Apparently, the only indication gethostname gives of
1590 whether the buffer was large enough is the presence or absence
1591 of a '\0' in the string. Eech. */
1594 gethostname (hostname
, hostname_size
- 1);
1595 hostname
[hostname_size
- 1] = '\0';
1597 /* Was the buffer large enough for the '\0'? */
1598 if (strlen (hostname
) < hostname_size
- 1)
1601 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1602 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1604 #endif /* HAVE_GETHOSTNAME */
1606 for (p
= hostname
; *p
; p
++)
1607 if (*p
== ' ' || *p
== '\t')
1609 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1610 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1611 Vsystem_name
= build_string (hostname
);
1612 xfree (hostname_alloc
);
1615 sigset_t empty_mask
;
1617 static struct sigaction process_fatal_action
;
1620 emacs_sigaction_flags (void)
1623 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1624 'select') to reset their timeout on some platforms (e.g.,
1625 HP-UX 11), which is not what we want. Also, when Emacs is
1626 interactive, we don't want SA_RESTART because we need to poll
1627 for pending input so we need long-running syscalls to be interrupted
1628 after a signal that sets pending_signals.
1630 Non-interactive keyboard input goes through stdio, where we
1631 always want restartable system calls. */
1638 /* Store into *ACTION a signal action suitable for Emacs, with handler
1641 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1643 sigemptyset (&action
->sa_mask
);
1645 /* When handling a signal, block nonfatal system signals that are caught
1646 by Emacs. This makes race conditions less likely. */
1647 sigaddset (&action
->sa_mask
, SIGALRM
);
1649 sigaddset (&action
->sa_mask
, SIGCHLD
);
1652 sigaddset (&action
->sa_mask
, SIGDANGER
);
1654 #ifdef PROFILER_CPU_SUPPORT
1655 sigaddset (&action
->sa_mask
, SIGPROF
);
1658 sigaddset (&action
->sa_mask
, SIGWINCH
);
1660 if (! noninteractive
)
1662 sigaddset (&action
->sa_mask
, SIGINT
);
1663 sigaddset (&action
->sa_mask
, SIGQUIT
);
1665 sigaddset (&action
->sa_mask
, SIGIO
);
1669 action
->sa_handler
= handler
;
1670 action
->sa_flags
= emacs_sigaction_flags ();
1673 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1674 pthread_t main_thread_id
;
1677 /* SIG has arrived at the current process. Deliver it to the main
1678 thread, which should handle it with HANDLER. (Delivering the
1679 signal to some other thread might not work if the other thread is
1682 If we are on the main thread, handle the signal SIG with HANDLER.
1683 Otherwise, redirect the signal to the main thread, blocking it from
1684 this thread. POSIX says any thread can receive a signal that is
1685 associated with a process, process group, or asynchronous event.
1686 On GNU/Linux the main thread typically gets a process signal unless
1687 it's blocked, but other systems (FreeBSD at least) can deliver the
1688 signal to other threads. */
1690 deliver_process_signal (int sig
, signal_handler_t handler
)
1692 /* Preserve errno, to avoid race conditions with signal handlers that
1693 might change errno. Races can occur even in single-threaded hosts. */
1694 int old_errno
= errno
;
1696 bool on_main_thread
= true;
1697 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1698 if (! pthread_equal (pthread_self (), main_thread_id
))
1701 sigemptyset (&blocked
);
1702 sigaddset (&blocked
, sig
);
1703 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1704 pthread_kill (main_thread_id
, sig
);
1705 on_main_thread
= false;
1714 /* Static location to save a fatal backtrace in a thread.
1715 FIXME: If two subsidiary threads fail simultaneously, the resulting
1716 backtrace may be garbage. */
1717 enum { BACKTRACE_LIMIT_MAX
= 500 };
1718 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1719 static int thread_backtrace_npointers
;
1721 /* SIG has arrived at the current thread.
1722 If we are on the main thread, handle the signal SIG with HANDLER.
1723 Otherwise, this is a fatal error in the handling thread. */
1725 deliver_thread_signal (int sig
, signal_handler_t handler
)
1727 int old_errno
= errno
;
1729 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1730 if (! pthread_equal (pthread_self (), main_thread_id
))
1732 thread_backtrace_npointers
1733 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1734 sigaction (sig
, &process_fatal_action
, 0);
1735 pthread_kill (main_thread_id
, sig
);
1737 /* Avoid further damage while the main thread is exiting. */
1739 sigsuspend (&empty_mask
);
1747 #if !HAVE_DECL_SYS_SIGLIST
1749 # ifdef _sys_siglist
1750 # define sys_siglist _sys_siglist
1751 # elif HAVE_DECL___SYS_SIGLIST
1752 # define sys_siglist __sys_siglist
1754 # define sys_siglist my_sys_siglist
1755 static char const *sys_siglist
[NSIG
];
1760 # define sys_siglist_entries _sys_nsig
1762 # define sys_siglist_entries NSIG
1765 /* Handle bus errors, invalid instruction, etc. */
1767 handle_fatal_signal (int sig
)
1769 terminate_due_to_signal (sig
, 40);
1773 deliver_fatal_signal (int sig
)
1775 deliver_process_signal (sig
, handle_fatal_signal
);
1779 deliver_fatal_thread_signal (int sig
)
1781 deliver_thread_signal (sig
, handle_fatal_signal
);
1784 static _Noreturn
void
1785 handle_arith_signal (int sig
)
1787 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1788 xsignal0 (Qarith_error
);
1791 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1793 /* Alternate stack used by SIGSEGV handler below. */
1795 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1798 /* Return true if SIGINFO indicates a stack overflow. */
1801 stack_overflow (siginfo_t
*siginfo
)
1803 if (!attempt_stack_overflow_recovery
)
1806 /* In theory, a more-accurate heuristic can be obtained by using
1807 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1808 and pthread_attr_getguardsize to find the location and size of the
1809 guard area. In practice, though, these functions are so hard to
1810 use reliably that they're not worth bothering with. E.g., see:
1811 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1812 Other operating systems also have problems, e.g., Solaris's
1813 stack_violation function is tailor-made for this problem, but it
1814 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1816 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1822 /* The faulting address. */
1823 char *addr
= siginfo
->si_addr
;
1827 /* The known top and bottom of the stack. The actual stack may
1828 extend a bit beyond these boundaries. */
1829 char *bot
= stack_bottom
;
1830 char *top
= current_thread
->stack_top
;
1832 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1833 of the known stack divided by the size of the guard area past the
1834 end of the stack top. The heuristic is that a bad address is
1835 considered to be a stack overflow if it occurs within
1836 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1837 stack. This heuristic is not exactly correct but it's good
1838 enough in practice. */
1839 enum { LG_STACK_HEURISTIC
= 8 };
1842 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1844 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1848 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1851 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1853 /* Hard GC error may lead to stack overflow caused by
1854 too nested calls to mark_object. No way to survive. */
1855 bool fatal
= gc_in_progress
;
1857 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1858 if (!fatal
&& !pthread_equal (pthread_self (), main_thread_id
))
1862 if (!fatal
&& stack_overflow (siginfo
))
1863 siglongjmp (return_to_command_loop
, 1);
1865 /* Otherwise we can't do anything with this. */
1866 deliver_fatal_thread_signal (sig
);
1869 /* Return true if we have successfully set up SIGSEGV handler on alternate
1870 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1875 struct sigaction sa
;
1878 ss
.ss_sp
= sigsegv_stack
;
1879 ss
.ss_size
= sizeof (sigsegv_stack
);
1881 if (sigaltstack (&ss
, NULL
) < 0)
1884 sigfillset (&sa
.sa_mask
);
1885 sa
.sa_sigaction
= handle_sigsegv
;
1886 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1887 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1890 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1898 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1901 deliver_arith_signal (int sig
)
1903 deliver_thread_signal (sig
, handle_arith_signal
);
1908 /* Handler for SIGDANGER. */
1910 handle_danger_signal (int sig
)
1912 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1914 /* It might be unsafe to call do_auto_save now. */
1915 force_auto_save_soon ();
1919 deliver_danger_signal (int sig
)
1921 deliver_process_signal (sig
, handle_danger_signal
);
1925 /* Treat SIG as a terminating signal, unless it is already ignored and
1926 we are in --batch mode. Among other things, this makes nohup work. */
1928 maybe_fatal_sig (int sig
)
1930 bool catch_sig
= !noninteractive
;
1933 struct sigaction old_action
;
1934 sigaction (sig
, 0, &old_action
);
1935 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1938 sigaction (sig
, &process_fatal_action
, 0);
1942 init_signals (bool dumping
)
1944 struct sigaction thread_fatal_action
;
1945 struct sigaction action
;
1947 sigemptyset (&empty_mask
);
1949 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1950 main_thread_id
= pthread_self ();
1953 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1956 sys_siglist
[SIGABRT
] = "Aborted";
1958 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1960 sys_siglist
[SIGALRM
] = "Alarm clock";
1962 sys_siglist
[SIGBUS
] = "Bus error";
1965 sys_siglist
[SIGCHLD
] = "Child status changed";
1968 sys_siglist
[SIGCONT
] = "Continued";
1971 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1974 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1977 sys_siglist
[SIGEMT
] = "Emulation trap";
1979 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1981 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1984 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1986 sys_siglist
[SIGHUP
] = "Hangup";
1987 sys_siglist
[SIGILL
] = "Illegal instruction";
1988 sys_siglist
[SIGINT
] = "Interrupt";
1990 sys_siglist
[SIGIO
] = "I/O possible";
1993 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1996 sys_siglist
[SIGIOT
] = "IOT trap";
1998 sys_siglist
[SIGKILL
] = "Killed";
2000 sys_siglist
[SIGLOST
] = "Resource lost";
2003 sys_siglist
[SIGLWP
] = "SIGLWP";
2006 sys_siglist
[SIGMSG
] = "Monitor mode data available";
2009 sys_siglist
[SIGWIND
] = "SIGPHONE";
2011 sys_siglist
[SIGPIPE
] = "Broken pipe";
2013 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
2016 sys_siglist
[SIGPROF
] = "Profiling timer expired";
2019 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
2022 sys_siglist
[SIGPWR
] = "Power-fail restart";
2024 sys_siglist
[SIGQUIT
] = "Quit";
2026 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
2029 sys_siglist
[SIGSAK
] = "Secure attention";
2031 sys_siglist
[SIGSEGV
] = "Segmentation violation";
2033 sys_siglist
[SIGSOUND
] = "Sound completed";
2036 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
2039 sys_siglist
[SIGSTP
] = "Stopped (user)";
2042 sys_siglist
[SIGSYS
] = "Bad argument to system call";
2044 sys_siglist
[SIGTERM
] = "Terminated";
2046 sys_siglist
[SIGTHAW
] = "SIGTHAW";
2049 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
2052 sys_siglist
[SIGTSTP
] = "Stopped (user)";
2055 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
2058 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
2061 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2064 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2067 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2070 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2073 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2076 sys_siglist
[SIGWINCH
] = "Window size changed";
2079 sys_siglist
[SIGWIND
] = "SIGWIND";
2082 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2085 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2088 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2090 /* Don't alter signal handlers if dumping. On some machines,
2091 changing signal handlers sets static data that would make signals
2092 fail to work right when the dumped Emacs is run. */
2096 sigfillset (&process_fatal_action
.sa_mask
);
2097 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2098 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2100 sigfillset (&thread_fatal_action
.sa_mask
);
2101 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2102 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2104 /* SIGINT may need special treatment on MS-Windows. See
2105 https://lists.gnu.org/r/emacs-devel/2010-09/msg01062.html
2106 Please update the doc of kill-emacs, kill-emacs-hook, and
2107 NEWS if you change this. */
2109 maybe_fatal_sig (SIGHUP
);
2110 maybe_fatal_sig (SIGINT
);
2111 maybe_fatal_sig (SIGTERM
);
2113 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2114 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2115 to behave more like typical batch applications do. */
2116 if (! noninteractive
)
2117 signal (SIGPIPE
, SIG_IGN
);
2119 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2120 sigaction (SIGILL
, &thread_fatal_action
, 0);
2121 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2123 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2124 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2125 interpreter's floating point operations, so treat SIGFPE as an
2126 arith-error if it arises in the main thread. */
2127 if (IEEE_FLOATING_POINT
)
2128 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2131 emacs_sigaction_init (&action
, deliver_arith_signal
);
2132 sigaction (SIGFPE
, &action
, 0);
2136 add_user_signal (SIGUSR1
, "sigusr1");
2139 add_user_signal (SIGUSR2
, "sigusr2");
2141 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2143 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2146 sigaction (SIGORE
, &thread_fatal_action
, 0);
2149 sigaction (SIGUME
, &thread_fatal_action
, 0);
2152 sigaction (SIGDLK
, &process_fatal_action
, 0);
2155 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2158 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2161 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2164 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2166 if (!init_sigsegv ())
2167 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2169 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2171 sigaction (SIGTERM
, &process_fatal_action
, 0);
2173 signal (SIGPROF
, SIG_IGN
);
2176 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2179 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2182 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2186 /* This just means available memory is getting low. */
2187 emacs_sigaction_init (&action
, deliver_danger_signal
);
2188 sigaction (SIGDANGER
, &action
, 0);
2191 /* AIX-specific signals. */
2193 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2196 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2199 sigaction (SIGMSG
, &process_fatal_action
, 0);
2202 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2205 sigaction (SIGSAK
, &process_fatal_action
, 0);
2208 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2211 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2221 /* Figure out how many bits the system's random number generator uses.
2222 `random' and `lrand48' are assumed to return 31 usable bits.
2223 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2224 so we'll shift it and treat it like the 15-bit USG `rand'. */
2228 # define RAND_BITS 31
2229 # else /* !HAVE_RANDOM */
2230 # ifdef HAVE_LRAND48
2231 # define RAND_BITS 31
2232 # define random lrand48
2233 # else /* !HAVE_LRAND48 */
2234 # define RAND_BITS 15
2235 # if RAND_MAX == 32767
2236 # define random rand
2237 # else /* RAND_MAX != 32767 */
2238 # if RAND_MAX == 2147483647
2239 # define random() (rand () >> 16)
2240 # else /* RAND_MAX != 2147483647 */
2242 # define random rand
2244 # define random() (rand () >> 16)
2246 # endif /* RAND_MAX != 2147483647 */
2247 # endif /* RAND_MAX != 32767 */
2248 # endif /* !HAVE_LRAND48 */
2249 # endif /* !HAVE_RANDOM */
2250 #endif /* !RAND_BITS */
2253 typedef unsigned int random_seed
;
2254 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2255 #elif defined HAVE_LRAND48
2256 /* Although srand48 uses a long seed, this is unsigned long to avoid
2257 undefined behavior on signed integer overflow in init_random. */
2258 typedef unsigned long int random_seed
;
2259 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2261 typedef unsigned int random_seed
;
2262 static void set_random_seed (random_seed arg
) { srand (arg
); }
2266 seed_random (void *seed
, ptrdiff_t seed_size
)
2268 random_seed arg
= 0;
2269 unsigned char *argp
= (unsigned char *) &arg
;
2270 unsigned char *seedp
= seed
;
2271 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2272 argp
[i
% sizeof arg
] ^= seedp
[i
];
2273 set_random_seed (arg
);
2280 bool success
= false;
2282 /* First, try seeding the PRNG from the operating system's entropy
2283 source. This approach is both fast and secure. */
2285 success
= w32_init_random (&v
, sizeof v
) == 0;
2287 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2290 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2295 /* If that didn't work, try using GnuTLS, which is secure, but on
2296 some systems, can be somewhat slow. */
2298 success
= EQ (emacs_gnutls_global_init (), Qt
)
2299 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2301 /* If _that_ didn't work, just use the current time value and PID.
2302 It's at least better than XKCD 221. */
2305 struct timespec t
= current_timespec ();
2306 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2309 set_random_seed (v
);
2313 * Return a nonnegative random integer out of whatever we've got.
2314 * It contains enough bits to make a random (signed) Emacs fixnum.
2315 * This suffices even for a 64-bit architecture with a 15-bit rand.
2322 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2323 val
= (random () ^ (val
<< RAND_BITS
)
2324 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2325 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2326 return val
& INTMASK
;
2329 #ifndef HAVE_SNPRINTF
2330 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2332 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2334 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2335 ptrdiff_t nbytes
= size
- 1;
2340 va_start (ap
, format
);
2341 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2345 if (nbytes
== size
- 1)
2347 /* Calculate the length of the string that would have been created
2348 had the buffer been large enough. */
2349 char stackbuf
[4000];
2351 ptrdiff_t bsize
= sizeof stackbuf
;
2352 va_start (ap
, format
);
2353 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2359 if (INT_MAX
< nbytes
)
2372 /* If a backtrace is available, output the top lines of it to stderr.
2373 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2374 This function may be called from a signal handler, so it should
2375 not invoke async-unsafe functions like malloc.
2377 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2378 but do not output anything. This avoids some problems that can
2379 otherwise occur if the malloc arena is corrupted before 'backtrace'
2380 is called, since 'backtrace' may call malloc if the tables are not
2383 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2384 fatal error has occurred in some other thread; generate a thread
2385 backtrace instead, ignoring BACKTRACE_LIMIT. */
2387 emacs_backtrace (int backtrace_limit
)
2389 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2390 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2394 if (thread_backtrace_npointers
)
2396 buffer
= thread_backtrace_buffer
;
2397 npointers
= thread_backtrace_npointers
;
2401 buffer
= main_backtrace_buffer
;
2403 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2404 if (bounded_limit
< 0)
2406 backtrace (buffer
, 1);
2410 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2415 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2416 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2417 if (bounded_limit
< npointers
)
2418 emacs_write (STDERR_FILENO
, "...\n", 4);
2426 terminate_due_to_signal (SIGABRT
, 40);
2430 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2431 Use binary I/O on systems that care about text vs binary I/O.
2432 Arrange for subprograms to not inherit the file descriptor.
2433 Prefer a method that is multithread-safe, if available.
2434 Do not fail merely because the open was interrupted by a signal.
2435 Allow the user to quit. */
2438 emacs_open (const char *file
, int oflags
, int mode
)
2441 if (! (oflags
& O_TEXT
))
2443 oflags
|= O_CLOEXEC
;
2444 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2449 /* Open FILE as a stream for Emacs use, with mode MODE.
2450 Act like emacs_open with respect to threads, signals, and quits. */
2453 emacs_fopen (char const *file
, char const *mode
)
2455 int fd
, omode
, oflags
;
2457 char const *m
= mode
;
2461 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2462 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2463 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2464 default: emacs_abort ();
2470 case '+': omode
= O_RDWR
; break;
2471 case 't': bflag
= O_TEXT
; break;
2472 default: /* Ignore. */ break;
2475 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2476 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2479 /* Create a pipe for Emacs use. */
2482 emacs_pipe (int fd
[2])
2487 return pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2491 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2492 For the background behind this mess, please see Austin Group defect 529
2493 <http://austingroupbugs.net/view.php?id=529>. */
2495 #ifndef POSIX_CLOSE_RESTART
2496 # define POSIX_CLOSE_RESTART 1
2498 posix_close (int fd
, int flag
)
2500 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2501 eassert (flag
== POSIX_CLOSE_RESTART
);
2503 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2504 on a system that does not define POSIX_CLOSE_RESTART.
2506 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2507 closed, and retrying the close could inadvertently close a file
2508 descriptor allocated by some other thread. In other systems
2509 (e.g., HP/UX) FD is not closed. And in still other systems
2510 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2511 multithreaded program there can be no way to tell.
2513 So, in this case, pretend that the close succeeded. This works
2514 well on systems like GNU/Linux that close FD. Although it may
2515 leak a file descriptor on other systems, the leak is unlikely and
2516 it's better to leak than to close a random victim. */
2517 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2521 /* Close FD, retrying if interrupted. If successful, return 0;
2522 otherwise, return -1 and set errno to a non-EINTR value. Consider
2523 an EINPROGRESS error to be successful, as that's merely a signal
2524 arriving. FD is always closed when this function returns, even
2527 Do not call this function if FD is nonnegative and might already be closed,
2528 as that might close an innocent victim opened by some other thread. */
2531 emacs_close (int fd
)
2535 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2538 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2540 eassert (errno
!= EBADF
|| fd
< 0);
2541 return errno
== EINPROGRESS
? 0 : r
;
2546 /* Maximum number of bytes to read or write in a single system call.
2547 This works around a serious bug in Linux kernels before 2.6.16; see
2548 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2549 It's likely to work around similar bugs in other operating systems, so do it
2550 on all platforms. Round INT_MAX down to a page size, with the conservative
2551 assumption that page sizes are at most 2**18 bytes (any kernel with a
2552 page size larger than that shouldn't have the bug). */
2553 #ifndef MAX_RW_COUNT
2554 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2557 /* Read from FD to a buffer BUF with size NBYTE.
2558 If interrupted, process any quits and pending signals immediately
2559 if INTERRUPTIBLE, and then retry the read unless quitting.
2560 Return the number of bytes read, which might be less than NBYTE.
2561 On error, set errno to a value other than EINTR, and return -1. */
2563 emacs_intr_read (int fd
, void *buf
, ptrdiff_t nbyte
, bool interruptible
)
2567 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2568 passes a size that large to emacs_read. */
2573 result
= read (fd
, buf
, nbyte
);
2575 while (result
< 0 && errno
== EINTR
);
2580 /* Read from FD to a buffer BUF with size NBYTE.
2581 If interrupted, retry the read. Return the number of bytes read,
2582 which might be less than NBYTE. On error, set errno to a value
2583 other than EINTR, and return -1. */
2585 emacs_read (int fd
, void *buf
, ptrdiff_t nbyte
)
2587 return emacs_intr_read (fd
, buf
, nbyte
, false);
2590 /* Like emacs_read, but also process quits and pending signals. */
2592 emacs_read_quit (int fd
, void *buf
, ptrdiff_t nbyte
)
2594 return emacs_intr_read (fd
, buf
, nbyte
, true);
2597 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2598 interrupted or if a partial write occurs. Process any quits
2599 immediately if INTERRUPTIBLE is positive, and process any pending
2600 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2601 of bytes written; if this is less than NBYTE, set errno to a value
2602 other than EINTR. */
2604 emacs_full_write (int fd
, char const *buf
, ptrdiff_t nbyte
,
2607 ptrdiff_t bytes_written
= 0;
2611 ssize_t n
= write (fd
, buf
, min (nbyte
, MAX_RW_COUNT
));
2620 if (0 < interruptible
)
2622 if (pending_signals
)
2623 process_pending_signals ();
2634 return bytes_written
;
2637 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2638 interrupted or if a partial write occurs. Do not process quits or
2639 pending signals. Return the number of bytes written, setting errno
2640 if this is less than NBYTE. */
2642 emacs_write (int fd
, void const *buf
, ptrdiff_t nbyte
)
2644 return emacs_full_write (fd
, buf
, nbyte
, 0);
2647 /* Like emacs_write, but also process pending signals. */
2649 emacs_write_sig (int fd
, void const *buf
, ptrdiff_t nbyte
)
2651 return emacs_full_write (fd
, buf
, nbyte
, -1);
2654 /* Like emacs_write, but also process quits and pending signals. */
2656 emacs_write_quit (int fd
, void const *buf
, ptrdiff_t nbyte
)
2658 return emacs_full_write (fd
, buf
, nbyte
, 1);
2661 /* Write a diagnostic to standard error that contains MESSAGE and a
2662 string derived from errno. Preserve errno. Do not buffer stderr.
2663 Do not process quits or pending signals if interrupted. */
2665 emacs_perror (char const *message
)
2668 char const *error_string
= emacs_strerror (err
);
2669 char const *command
= (initial_argv
&& initial_argv
[0]
2670 ? initial_argv
[0] : "emacs");
2671 /* Write it out all at once, if it's short; this is less likely to
2672 be interleaved with other output. */
2674 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2675 command
, message
, error_string
);
2676 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2677 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2680 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2681 emacs_write (STDERR_FILENO
, ": ", 2);
2682 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2683 emacs_write (STDERR_FILENO
, ": ", 2);
2684 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2685 emacs_write (STDERR_FILENO
, "\n", 1);
2690 /* Return a struct timeval that is roughly equivalent to T.
2691 Use the least timeval not less than T.
2692 Return an extremal value if the result would overflow. */
2694 make_timeval (struct timespec t
)
2697 tv
.tv_sec
= t
.tv_sec
;
2698 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2700 if (t
.tv_nsec
% 1000 != 0)
2702 if (tv
.tv_usec
< 999999)
2704 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2714 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2715 ATIME and MTIME, respectively.
2716 FD must be either negative -- in which case it is ignored --
2717 or a file descriptor that is open on FILE.
2718 If FD is nonnegative, then FILE can be NULL. */
2720 set_file_times (int fd
, const char *filename
,
2721 struct timespec atime
, struct timespec mtime
)
2723 struct timespec timespec
[2];
2724 timespec
[0] = atime
;
2725 timespec
[1] = mtime
;
2726 return fdutimens (fd
, filename
, timespec
);
2729 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2730 This is like renameat except that it fails if DST already exists,
2731 or if this operation is not supported atomically. Return 0 if
2732 successful, -1 (setting errno) otherwise. */
2734 renameat_noreplace (int srcfd
, char const *src
, int dstfd
, char const *dst
)
2736 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2737 return syscall (SYS_renameat2
, srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2738 #elif defined CYGWIN && defined RENAME_NOREPLACE
2739 return renameat2 (srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2740 #elif defined RENAME_EXCL
2741 return renameatx_np (srcfd
, src
, dstfd
, dst
, RENAME_EXCL
);
2744 if (srcfd
== AT_FDCWD
&& dstfd
== AT_FDCWD
)
2745 return sys_rename_replace (src
, dst
, 0);
2752 /* Like strsignal, except async-signal-safe, and this function typically
2753 returns a string in the C locale rather than the current locale. */
2755 safe_strsignal (int code
)
2757 char const *signame
= 0;
2759 if (0 <= code
&& code
< sys_siglist_entries
)
2760 signame
= sys_siglist
[code
];
2762 signame
= "Unknown signal";
2768 /* For make-serial-process */
2770 serial_open (Lisp_Object port
)
2772 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2774 report_file_error ("Opening serial port", port
);
2776 ioctl (fd
, TIOCEXCL
, (char *) 0);
2782 #if !defined (HAVE_CFMAKERAW)
2783 /* Workaround for targets which are missing cfmakeraw. */
2784 /* Pasted from man page. */
2786 cfmakeraw (struct termios
*termios_p
)
2788 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2789 termios_p
->c_oflag
&= ~OPOST
;
2790 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2791 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2792 termios_p
->c_cflag
|= CS8
;
2794 #endif /* !defined (HAVE_CFMAKERAW */
2796 #if !defined (HAVE_CFSETSPEED)
2797 /* Workaround for targets which are missing cfsetspeed. */
2799 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2801 return (cfsetispeed (termios_p
, vitesse
)
2802 + cfsetospeed (termios_p
, vitesse
));
2806 /* For serial-process-configure */
2808 serial_configure (struct Lisp_Process
*p
,
2809 Lisp_Object contact
)
2811 Lisp_Object childp2
= Qnil
;
2812 Lisp_Object tem
= Qnil
;
2813 struct termios attr
;
2815 char summary
[4] = "???"; /* This usually becomes "8N1". */
2817 childp2
= Fcopy_sequence (p
->childp
);
2819 /* Read port attributes and prepare default configuration. */
2820 err
= tcgetattr (p
->outfd
, &attr
);
2822 report_file_error ("Failed tcgetattr", Qnil
);
2824 #if defined (CLOCAL)
2825 attr
.c_cflag
|= CLOCAL
;
2828 attr
.c_cflag
|= CREAD
;
2831 /* Configure speed. */
2832 if (!NILP (Fplist_member (contact
, QCspeed
)))
2833 tem
= Fplist_get (contact
, QCspeed
);
2835 tem
= Fplist_get (p
->childp
, QCspeed
);
2837 err
= cfsetspeed (&attr
, XINT (tem
));
2839 report_file_error ("Failed cfsetspeed", tem
);
2840 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2842 /* Configure bytesize. */
2843 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2844 tem
= Fplist_get (contact
, QCbytesize
);
2846 tem
= Fplist_get (p
->childp
, QCbytesize
);
2848 tem
= make_number (8);
2850 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2851 error (":bytesize must be nil (8), 7, or 8");
2852 summary
[0] = XINT (tem
) + '0';
2853 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2854 attr
.c_cflag
&= ~CSIZE
;
2855 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2857 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2858 if (XINT (tem
) != 8)
2859 error ("Bytesize cannot be changed");
2861 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2863 /* Configure parity. */
2864 if (!NILP (Fplist_member (contact
, QCparity
)))
2865 tem
= Fplist_get (contact
, QCparity
);
2867 tem
= Fplist_get (p
->childp
, QCparity
);
2868 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2869 error (":parity must be nil (no parity), `even', or `odd'");
2870 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2871 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2872 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2877 else if (EQ (tem
, Qeven
))
2880 attr
.c_cflag
|= PARENB
;
2881 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2883 else if (EQ (tem
, Qodd
))
2886 attr
.c_cflag
|= (PARENB
| PARODD
);
2887 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2890 /* Don't error on no parity, which should be set by cfmakeraw. */
2892 error ("Parity cannot be configured");
2894 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2896 /* Configure stopbits. */
2897 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2898 tem
= Fplist_get (contact
, QCstopbits
);
2900 tem
= Fplist_get (p
->childp
, QCstopbits
);
2902 tem
= make_number (1);
2904 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2905 error (":stopbits must be nil (1 stopbit), 1, or 2");
2906 summary
[2] = XINT (tem
) + '0';
2907 #if defined (CSTOPB)
2908 attr
.c_cflag
&= ~CSTOPB
;
2909 if (XINT (tem
) == 2)
2910 attr
.c_cflag
|= CSTOPB
;
2912 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2913 if (XINT (tem
) != 1)
2914 error ("Stopbits cannot be configured");
2916 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2918 /* Configure flowcontrol. */
2919 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2920 tem
= Fplist_get (contact
, QCflowcontrol
);
2922 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2923 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2924 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2925 #if defined (CRTSCTS)
2926 attr
.c_cflag
&= ~CRTSCTS
;
2928 #if defined (CNEW_RTSCTS)
2929 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2931 #if defined (IXON) && defined (IXOFF)
2932 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2936 /* Already configured. */
2938 else if (EQ (tem
, Qhw
))
2940 #if defined (CRTSCTS)
2941 attr
.c_cflag
|= CRTSCTS
;
2942 #elif defined (CNEW_RTSCTS)
2943 attr
.c_cflag
|= CNEW_RTSCTS
;
2945 error ("Hardware flowcontrol (RTS/CTS) not supported");
2948 else if (EQ (tem
, Qsw
))
2950 #if defined (IXON) && defined (IXOFF)
2951 attr
.c_iflag
|= (IXON
| IXOFF
);
2953 error ("Software flowcontrol (XON/XOFF) not supported");
2956 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2958 /* Activate configuration. */
2959 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2961 report_file_error ("Failed tcsetattr", Qnil
);
2963 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2964 pset_childp (p
, childp2
);
2966 #endif /* not DOS_NT */
2968 /* System depended enumeration of and access to system processes a-la ps(1). */
2972 /* Process enumeration and access via /proc. */
2975 list_system_processes (void)
2977 Lisp_Object procdir
, match
, proclist
, next
;
2980 /* For every process on the system, there's a directory in the
2981 "/proc" pseudo-directory whose name is the numeric ID of that
2983 procdir
= build_string ("/proc");
2984 match
= build_string ("[0-9]+");
2985 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, false, Qnil
);
2987 /* `proclist' gives process IDs as strings. Destructively convert
2988 each string into a number. */
2989 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2992 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2995 /* directory_files_internal returns the files in reverse order; undo
2997 proclist
= Fnreverse (proclist
);
3001 #elif defined DARWIN_OS || defined __FreeBSD__
3004 list_system_processes (void)
3007 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
3009 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
3012 struct kinfo_proc
*procs
;
3015 Lisp_Object proclist
= Qnil
;
3017 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
3020 procs
= xmalloc (len
);
3021 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
3027 len
/= sizeof (struct kinfo_proc
);
3028 for (i
= 0; i
< len
; i
++)
3031 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
3033 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
3042 /* The WINDOWSNT implementation is in w32.c.
3043 The MSDOS implementation is in dosfns.c. */
3044 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3047 list_system_processes (void)
3052 #endif /* !defined (WINDOWSNT) */
3054 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3055 static struct timespec
3056 time_from_jiffies (unsigned long long tval
, long hz
)
3058 unsigned long long s
= tval
/ hz
;
3059 unsigned long long frac
= tval
% hz
;
3062 if (TYPE_MAXIMUM (time_t) < s
)
3064 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
3065 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
3066 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
3069 /* This is reachable only in the unlikely case that HZ * HZ
3070 exceeds ULLONG_MAX. It calculates an approximation that is
3071 guaranteed to be in range. */
3072 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
3073 + (hz
% TIMESPEC_RESOLUTION
!= 0));
3074 ns
= frac
/ hz_per_ns
;
3077 return make_timespec (s
, ns
);
3081 ltime_from_jiffies (unsigned long long tval
, long hz
)
3083 struct timespec t
= time_from_jiffies (tval
, hz
);
3084 return make_lisp_time (t
);
3087 static struct timespec
3091 struct timespec up
= make_timespec (0, 0);
3094 fup
= emacs_fopen ("/proc/uptime", "r");
3098 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
3099 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
3101 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
3102 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
3103 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
3106 if (TYPE_MAXIMUM (time_t) < upsec
)
3108 upsec
= TYPE_MAXIMUM (time_t);
3109 upfrac
= TIMESPEC_RESOLUTION
- 1;
3113 int upfraclen
= upfrac_end
- upfrac_start
;
3114 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3116 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3118 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3120 up
= make_timespec (upsec
, upfrac
);
3129 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3130 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3133 procfs_ttyname (int rdev
)
3136 char name
[PATH_MAX
];
3139 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3145 unsigned long minor_beg
, minor_end
;
3146 char minor
[25]; /* 2 32-bit numbers + dash */
3149 for (; !feof_unlocked (fdev
) && !ferror_unlocked (fdev
); name
[0] = 0)
3151 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3152 && major
== MAJOR (rdev
))
3154 minor_beg
= strtoul (minor
, &endp
, 0);
3156 minor_end
= minor_beg
;
3157 else if (*endp
== '-')
3158 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3162 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3164 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3172 return build_string (name
);
3176 procfs_get_total_memory (void)
3179 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3183 fmem
= emacs_fopen ("/proc/meminfo", "r");
3187 uintmax_t entry_value
;
3191 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3194 retval
= entry_value
;
3199 while ((c
= getc_unlocked (fmem
)) != EOF
&& c
!= '\n')
3217 system_process_attributes (Lisp_Object pid
)
3219 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3223 long clocks_per_sec
;
3225 char procbuf
[1025], *p
, *q
;
3228 static char const default_cmd
[] = "???";
3229 const char *cmd
= default_cmd
;
3230 int cmdsize
= sizeof default_cmd
- 1;
3231 char *cmdline
= NULL
;
3232 ptrdiff_t cmdline_size
;
3235 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3238 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3239 long priority
, niceness
, rss
;
3240 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3241 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3243 Lisp_Object attrs
= Qnil
;
3244 Lisp_Object decoded_cmd
;
3247 CHECK_NUMBER_OR_FLOAT (pid
);
3248 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3249 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3250 if (stat (procfn
, &st
) < 0)
3255 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3257 pw
= getpwuid (uid
);
3260 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3263 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3265 gr
= getgrgid (gid
);
3268 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3270 count
= SPECPDL_INDEX ();
3271 strcpy (fn
, procfn
);
3272 procfn_end
= fn
+ strlen (fn
);
3273 strcpy (procfn_end
, "/stat");
3274 fd
= emacs_open (fn
, O_RDONLY
, 0);
3279 record_unwind_protect_int (close_file_unwind
, fd
);
3280 nread
= emacs_read_quit (fd
, procbuf
, sizeof procbuf
- 1);
3284 procbuf
[nread
] = '\0';
3287 p
= strchr (p
, '(');
3290 q
= strrchr (p
+ 1, ')');
3300 /* Command name is encoded in locale-coding-system; decode it. */
3301 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3302 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3303 Vlocale_coding_system
, 0);
3304 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3306 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3307 utime stime cutime cstime priority nice thcount . start vsize rss */
3309 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3310 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3311 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3312 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3313 &u_time
, &s_time
, &cutime
, &cstime
,
3314 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3319 state_str
[1] = '\0';
3320 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3321 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3322 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3323 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3324 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3325 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3326 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3327 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3328 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3330 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3332 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3333 if (clocks_per_sec
< 0)
3334 clocks_per_sec
= 100;
3335 attrs
= Fcons (Fcons (Qutime
,
3336 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3338 attrs
= Fcons (Fcons (Qstime
,
3339 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3341 attrs
= Fcons (Fcons (Qtime
,
3342 ltime_from_jiffies (s_time
+ u_time
,
3345 attrs
= Fcons (Fcons (Qcutime
,
3346 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3348 attrs
= Fcons (Fcons (Qcstime
,
3349 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3351 attrs
= Fcons (Fcons (Qctime
,
3352 ltime_from_jiffies (cstime
+ cutime
,
3355 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3356 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3357 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3359 tnow
= current_timespec ();
3360 telapsed
= get_up_time ();
3361 tboot
= timespec_sub (tnow
, telapsed
);
3362 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3363 tstart
= timespec_add (tboot
, tstart
);
3364 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3365 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3367 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3368 telapsed
= timespec_sub (tnow
, tstart
);
3369 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3370 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3371 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3374 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3375 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3378 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3381 unbind_to (count
, Qnil
);
3384 strcpy (procfn_end
, "/cmdline");
3385 fd
= emacs_open (fn
, O_RDONLY
, 0);
3388 ptrdiff_t readsize
, nread_incr
;
3389 record_unwind_protect_int (close_file_unwind
, fd
);
3390 record_unwind_protect_nothing ();
3391 nread
= cmdline_size
= 0;
3395 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3396 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3398 /* Leave room even if every byte needs escaping below. */
3399 readsize
= (cmdline_size
>> 1) - nread
;
3401 nread_incr
= emacs_read_quit (fd
, cmdline
+ nread
, readsize
);
3402 nread
+= max (0, nread_incr
);
3404 while (nread_incr
== readsize
);
3408 /* We don't want trailing null characters. */
3409 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3412 /* Escape-quote whitespace and backslashes. */
3413 q
= cmdline
+ cmdline_size
;
3418 if (c_isspace (c
) || c
== '\\')
3422 nread
= cmdline
+ cmdline_size
- q
;
3427 nread
= cmdsize
+ 2;
3428 cmdline_size
= nread
+ 1;
3429 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3430 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3431 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3433 /* Command line is encoded in locale-coding-system; decode it. */
3434 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3435 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3436 Vlocale_coding_system
, 0);
3437 unbind_to (count
, Qnil
);
3438 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3444 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3446 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3447 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3448 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3449 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3450 #undef _FILE_OFFSET_BITS
3452 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3457 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3458 #define _FILE_OFFSET_BITS 64
3459 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3461 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3464 system_process_attributes (Lisp_Object pid
)
3466 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3471 struct psinfo pinfo
;
3477 Lisp_Object attrs
= Qnil
;
3478 Lisp_Object decoded_cmd
;
3481 CHECK_NUMBER_OR_FLOAT (pid
);
3482 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3483 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3484 if (stat (procfn
, &st
) < 0)
3489 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3491 pw
= getpwuid (uid
);
3494 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3497 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3499 gr
= getgrgid (gid
);
3502 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3504 count
= SPECPDL_INDEX ();
3505 strcpy (fn
, procfn
);
3506 procfn_end
= fn
+ strlen (fn
);
3507 strcpy (procfn_end
, "/psinfo");
3508 fd
= emacs_open (fn
, O_RDONLY
, 0);
3513 record_unwind_protect_int (close_file_unwind
, fd
);
3514 nread
= emacs_read_quit (fd
, &pinfo
, sizeof pinfo
);
3517 if (nread
== sizeof pinfo
)
3519 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3520 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3521 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3525 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3526 state_str
[1] = '\0';
3527 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3530 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3531 need to get a string from it. */
3533 /* FIXME: missing: Qtpgid */
3545 Are they available? */
3547 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3548 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3549 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3550 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3551 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3554 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3555 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3557 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3560 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3561 range 0 .. 2**15, representing 0.0 .. 1.0. */
3562 attrs
= Fcons (Fcons (Qpcpu
,
3563 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3565 attrs
= Fcons (Fcons (Qpmem
,
3566 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3569 AUTO_STRING (fname
, pinfo
.pr_fname
);
3570 decoded_cmd
= code_convert_string_norecord (fname
,
3571 Vlocale_coding_system
, 0);
3572 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3573 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3574 decoded_cmd
= code_convert_string_norecord (psargs
,
3575 Vlocale_coding_system
, 0);
3576 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3578 unbind_to (count
, Qnil
);
3582 #elif defined __FreeBSD__
3584 static struct timespec
3585 timeval_to_timespec (struct timeval t
)
3587 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3591 make_lisp_timeval (struct timeval t
)
3593 return make_lisp_time (timeval_to_timespec (t
));
3597 system_process_attributes (Lisp_Object pid
)
3600 int pagesize
= getpagesize ();
3601 unsigned long npages
;
3607 char args
[MAXPATHLEN
];
3608 struct timespec t
, now
;
3610 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3611 struct kinfo_proc proc
;
3612 size_t proclen
= sizeof proc
;
3614 Lisp_Object attrs
= Qnil
;
3615 Lisp_Object decoded_comm
;
3617 CHECK_NUMBER_OR_FLOAT (pid
);
3618 CONS_TO_INTEGER (pid
, int, proc_id
);
3621 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3624 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3627 pw
= getpwuid (proc
.ki_uid
);
3630 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3632 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3635 gr
= getgrgid (proc
.ki_svgid
);
3638 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3640 AUTO_STRING (comm
, proc
.ki_comm
);
3641 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3643 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3645 char state
[2] = {'\0', '\0'};
3646 switch (proc
.ki_stat
)
3668 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3671 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3672 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3673 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3676 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3679 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3681 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3682 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3683 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3684 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3685 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3687 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3689 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3691 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3692 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3693 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3695 attrs
= Fcons (Fcons (Qcutime
,
3696 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3698 attrs
= Fcons (Fcons (Qcstime
,
3699 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3701 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3702 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3703 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3705 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3707 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3708 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3709 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3710 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3711 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3714 now
= current_timespec ();
3715 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3716 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3718 len
= sizeof fscale
;
3719 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3724 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3726 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3727 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3728 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3732 len
= sizeof npages
;
3733 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3735 double pmem
= (proc
.ki_flag
& P_INMEM
3736 ? 100.0 * proc
.ki_rssize
/ npages
3738 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3741 mib
[2] = KERN_PROC_ARGS
;
3743 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3746 for (i
= 0; i
< len
; i
++)
3748 if (! args
[i
] && i
< len
- 1)
3752 AUTO_STRING (comm
, args
);
3753 decoded_comm
= code_convert_string_norecord (comm
,
3754 Vlocale_coding_system
, 0);
3756 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3762 #elif defined DARWIN_OS
3764 static struct timespec
3765 timeval_to_timespec (struct timeval t
)
3767 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3771 make_lisp_timeval (struct timeval t
)
3773 return make_lisp_time (timeval_to_timespec (t
));
3777 system_process_attributes (Lisp_Object pid
)
3783 struct timeval starttime
;
3784 struct timespec t
, now
;
3785 struct rusage
*rusage
;
3790 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3791 struct kinfo_proc proc
;
3792 size_t proclen
= sizeof proc
;
3794 Lisp_Object attrs
= Qnil
;
3795 Lisp_Object decoded_comm
;
3797 CHECK_NUMBER_OR_FLOAT (pid
);
3798 CONS_TO_INTEGER (pid
, int, proc_id
);
3801 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3804 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3805 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3808 pw
= getpwuid (uid
);
3811 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3813 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3814 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3817 gr
= getgrgid (gid
);
3820 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3822 decoded_comm
= (code_convert_string_norecord
3823 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3824 Vlocale_coding_system
, 0));
3826 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3828 char state
[2] = {'\0', '\0'};
3829 switch (proc
.kp_proc
.p_stat
)
3851 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3854 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3856 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3859 tdev
= proc
.kp_eproc
.e_tdev
;
3861 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3864 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3866 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3869 rusage
= proc
.kp_proc
.p_ru
;
3872 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3874 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3877 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3879 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3881 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3882 timeval_to_timespec (rusage
->ru_stime
));
3883 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3886 starttime
= proc
.kp_proc
.p_starttime
;
3887 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3888 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3890 now
= current_timespec ();
3891 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3892 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3897 /* The WINDOWSNT implementation is in w32.c.
3898 The MSDOS implementation is in dosfns.c. */
3899 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3902 system_process_attributes (Lisp_Object pid
)
3907 #endif /* !defined (WINDOWSNT) */
3909 /* Wide character string collation. */
3911 #ifdef __STDC_ISO_10646__
3913 # include <wctype.h>
3915 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3916 # include <locale.h>
3919 # define LC_COLLATE 0
3921 # ifndef LC_COLLATE_MASK
3922 # define LC_COLLATE_MASK 0
3927 # ifndef LC_CTYPE_MASK
3928 # define LC_CTYPE_MASK 0
3931 # ifndef HAVE_NEWLOCALE
3937 # define freelocale emacs_freelocale
3938 # define locale_t emacs_locale_t
3939 # define newlocale emacs_newlocale
3940 # define wcscoll_l emacs_wcscoll_l
3941 # define towlower_l emacs_towlower_l
3943 typedef char const *locale_t
;
3946 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3952 freelocale (locale_t loc
)
3957 emacs_setlocale (int category
, char const *locale
)
3959 # ifdef HAVE_SETLOCALE
3961 char *loc
= setlocale (category
, locale
);
3972 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3975 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3983 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3984 strcpy (oldcopy
, oldloc
);
3985 if (! emacs_setlocale (LC_COLLATE
, loc
))
3990 result
= wcscoll (a
, b
);
3992 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
4003 towlower_l (wint_t wc
, locale_t loc
)
4006 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
4011 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
4012 strcpy (oldcopy
, oldloc
);
4013 if (emacs_setlocale (LC_CTYPE
, loc
))
4015 result
= towlower (wc
);
4016 emacs_setlocale (LC_COLLATE
, oldcopy
);
4026 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4027 Lisp_Object locale
, Lisp_Object ignore_case
)
4030 ptrdiff_t len
, i
, i_byte
;
4035 /* Convert byte stream to code points. */
4036 len
= SCHARS (s1
); i
= i_byte
= 0;
4037 SAFE_NALLOCA (p1
, 1, len
+ 1);
4039 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
4042 len
= SCHARS (s2
); i
= i_byte
= 0;
4043 SAFE_NALLOCA (p2
, 1, len
+ 1);
4045 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
4048 if (STRINGP (locale
))
4050 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
4051 SSDATA (locale
), 0);
4053 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
4055 if (! NILP (ignore_case
))
4056 for (int i
= 1; i
< 3; i
++)
4058 wchar_t *p
= (i
== 1) ? p1
: p2
;
4060 *p
= towlower_l (*p
, loc
);
4064 res
= wcscoll_l (p1
, p2
, loc
);
4070 if (! NILP (ignore_case
))
4071 for (int i
= 1; i
< 3; i
++)
4073 wchar_t *p
= (i
== 1) ? p1
: p2
;
4079 res
= wcscoll (p1
, p2
);
4082 # ifndef HAVE_NEWLOCALE
4084 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
4087 error ("Invalid string for collation: %s", emacs_strerror (err
));
4093 #endif /* __STDC_ISO_10646__ */
4097 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4098 Lisp_Object locale
, Lisp_Object ignore_case
)
4101 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
4102 int res
, err
= errno
;
4105 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4107 error ("Invalid string for collation: %s", strerror (errno
));
4112 #endif /* WINDOWSNT */