1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2017 Free Software
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
27 #endif /* HAVE_PWD_H */
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #ifdef HAVE_LINUX_FS_H
41 # include <linux/fs.h>
42 # include <sys/syscall.h>
45 #if defined DARWIN_OS || defined __FreeBSD__
46 # include <sys/sysctl.h>
50 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
51 'struct frame', so rename it. */
52 # define frame freebsd_frame
53 # include <sys/user.h>
60 #include <sys/socket.h>
62 #endif /* HAVE_SOCKETS */
66 #define write sys_write
68 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
71 #endif /* WINDOWSNT */
73 #include <sys/types.h>
77 /* Get SI_SRPC_DOMAIN, if it is available. */
78 #ifdef HAVE_SYS_SYSTEMINFO_H
79 #include <sys/systeminfo.h>
82 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
86 #include <sys/param.h>
93 #ifdef HAVE_SYS_UTSNAME_H
94 #include <sys/utsname.h>
96 #endif /* HAVE_SYS_UTSNAME_H */
100 #include "termhooks.h"
101 #include "termchar.h"
102 #include "termopts.h"
107 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
108 do that during startup just to call gnutls_rnd. */
109 #if defined HAVE_GNUTLS && !defined WINDOWSNT
110 # include <gnutls/crypto.h>
112 # define emacs_gnutls_global_init() Qnil
113 # define gnutls_rnd(level, data, len) (-1)
118 /* In process.h which conflicts with the local copy. */
120 int _cdecl
_spawnlp (int, const char *, const char *, ...);
121 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
122 several prototypes of functions called below. */
123 #include <sys/socket.h>
126 #include "syssignal.h"
129 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
131 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
134 /* Declare here, including term.h is problematic on some systems. */
135 extern void tputs (const char *, int, int (*)(int));
137 static const int baud_convert
[] =
139 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
140 1800, 2400, 4800, 9600, 19200, 38400
143 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
144 # include <sys/personality.h>
146 /* Disable address randomization in the current process. Return true
147 if addresses were randomized but this has been disabled, false
150 disable_address_randomization (void)
152 int pers
= personality (0xffffffff);
155 int desired_pers
= pers
| ADDR_NO_RANDOMIZE
;
157 /* Call 'personality' twice, to detect buggy platforms like WSL
158 where 'personality' always returns 0. */
159 return (pers
!= desired_pers
160 && personality (desired_pers
) == pers
161 && personality (0xffffffff) == desired_pers
);
165 /* Execute the program in FILE, with argument vector ARGV and environ
166 ENVP. Return an error number if unsuccessful. This is like execve
167 except it reenables ASLR in the executed program if necessary, and
168 on error it returns an error number rather than -1. */
170 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
172 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
173 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
174 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
175 if (change_personality
)
176 personality (pers
& ~ADDR_NO_RANDOMIZE
);
179 execve (file
, argv
, envp
);
182 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
183 if (change_personality
)
190 /* If FD is not already open, arrange for it to be open with FLAGS. */
192 force_open (int fd
, int flags
)
194 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
196 int n
= open (NULL_DEVICE
, flags
);
197 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
199 emacs_perror (NULL_DEVICE
);
205 /* Make sure stdin, stdout, and stderr are open to something, so that
206 their file descriptors are not hijacked by later system calls. */
208 init_standard_fds (void)
210 /* Open stdin for *writing*, and stdout and stderr for *reading*.
211 That way, any attempt to do normal I/O will result in an error,
212 just as if the files were closed, and the file descriptors will
213 not be reused by later opens. */
214 force_open (STDIN_FILENO
, O_WRONLY
);
215 force_open (STDOUT_FILENO
, O_RDONLY
);
216 force_open (STDERR_FILENO
, O_RDONLY
);
219 /* Return the current working directory. The result should be freed
220 with 'free'. Return NULL on errors. */
222 emacs_get_current_dir_name (void)
224 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
225 # ifdef HYBRID_MALLOC
226 bool use_libc
= bss_sbrk_did_unexec
;
228 bool use_libc
= true;
231 return get_current_dir_name ();
235 char *pwd
= getenv ("PWD");
236 struct stat dotstat
, pwdstat
;
237 /* If PWD is accurate, use it instead of calling getcwd. PWD is
238 sometimes a nicer name, and using it may avoid a fatal error if a
239 parent directory is searchable but not readable. */
241 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
242 && stat (pwd
, &pwdstat
) == 0
243 && stat (".", &dotstat
) == 0
244 && dotstat
.st_ino
== pwdstat
.st_ino
245 && dotstat
.st_dev
== pwdstat
.st_dev
247 && strlen (pwd
) < MAXPATHLEN
251 buf
= malloc (strlen (pwd
) + 1);
258 size_t buf_size
= 1024;
259 buf
= malloc (buf_size
);
264 if (getcwd (buf
, buf_size
) == buf
)
268 int tmp_errno
= errno
;
274 buf
= realloc (buf
, buf_size
);
283 /* Discard pending input on all input descriptors. */
286 discard_tty_input (void)
289 struct emacs_tty buf
;
294 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
295 while (dos_keyread () != -1)
297 #else /* not MSDOS */
299 struct tty_display_info
*tty
;
300 for (tty
= tty_list
; tty
; tty
= tty
->next
)
302 if (tty
->input
) /* Is the device suspended? */
304 emacs_get_tty (fileno (tty
->input
), &buf
);
305 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
309 #endif /* not MSDOS */
310 #endif /* not WINDOWSNT */
316 /* Arrange for character C to be read as the next input from
318 XXX What if we have multiple ttys?
324 if (! (FRAMEP (selected_frame
)
325 && FRAME_LIVE_P (XFRAME (selected_frame
))
326 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
329 /* Should perhaps error if in batch mode */
331 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
332 #else /* no TIOCSTI */
333 error ("Cannot stuff terminal input characters in this version of Unix");
334 #endif /* no TIOCSTI */
340 init_baud_rate (int fd
)
350 #else /* not DOS_NT */
355 emacs_ospeed
= cfgetospeed (&sg
);
356 #endif /* not DOS_NT */
359 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
360 ? baud_convert
[emacs_ospeed
] : 9600);
369 /* Wait for the subprocess with process id CHILD to terminate or change status.
370 CHILD must be a child process that has not been reaped.
371 If STATUS is non-null, store the waitpid-style exit status into *STATUS
372 and tell wait_reading_process_output that it needs to look around.
373 Use waitpid-style OPTIONS when waiting.
374 If INTERRUPTIBLE, this function is interruptible by a signal.
376 Return CHILD if successful, 0 if no status is available, and a
377 negative value (setting errno) if waitpid is buggy. */
379 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
383 /* Invoke waitpid only with a known process ID; do not invoke
384 waitpid with a nonpositive argument. Otherwise, Emacs might
385 reap an unwanted process by mistake. For example, invoking
386 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
387 so that another thread running glib won't find them. */
392 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
397 pid
= waitpid (child
, status
, options
);
402 /* Most likely, waitpid is buggy and the operating system
403 lost track of the child somehow. Return -1 and let the
404 caller try to figure things out. Possibly the bug could
405 cause Emacs to kill the wrong process. Oh well. */
410 /* If successful and status is requested, tell wait_reading_process_output
411 that it needs to wake up and look around. */
412 if (pid
&& status
&& input_available_clear_time
)
413 *input_available_clear_time
= make_timespec (0, 0);
418 /* Wait for the subprocess with process id CHILD to terminate.
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 If INTERRUPTIBLE, this function is interruptible by a signal.
423 Return true if successful, false (setting errno) if CHILD cannot be
424 waited for because waitpid is buggy. */
426 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
428 return 0 <= get_child_status (child
, status
, 0, interruptible
);
431 /* Report whether the subprocess with process id CHILD has changed status.
432 Termination counts as a change of status.
433 CHILD must be a child process that has not been reaped.
434 If STATUS is non-null, store the waitpid-style exit status into *STATUS
435 and tell wait_reading_process_output that it needs to look around.
436 Use waitpid-style OPTIONS to check status, but do not wait.
438 Return CHILD if successful, 0 if no status is available because
439 the process's state has not changed. */
441 child_status_changed (pid_t child
, int *status
, int options
)
443 return get_child_status (child
, status
, WNOHANG
| options
, 0);
447 /* Set up the terminal at the other end of a pseudo-terminal that
448 we will be controlling an inferior through.
449 It should not echo or do line-editing, since that is done
450 in Emacs. No padding needed for insertion into an Emacs buffer. */
453 child_setup_tty (int out
)
458 emacs_get_tty (out
, &s
);
459 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
460 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
462 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
463 Some versions of GNU Hurd do not have FFDLY? */
465 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
466 /* No output delays */
468 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
469 /* No output delays */
472 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
473 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
475 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
478 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
481 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
483 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
484 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
485 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
486 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
489 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
492 #ifdef SIGNALS_VIA_CHARACTERS
493 /* the QUIT and INTR character are used in process_send_signal
494 so set them here to something useful. */
495 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
496 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
497 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
498 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
499 #endif /* not SIGNALS_VIA_CHARACTERS */
502 /* Also, PTY overloads NUL and BREAK.
503 don't ignore break, but don't signal either, so it looks like NUL. */
504 s
.main
.c_iflag
&= ~IGNBRK
;
505 s
.main
.c_iflag
&= ~BRKINT
;
506 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
507 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
508 would force it to 0377. That looks like duplicated code. */
509 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
512 /* We originally enabled ICANON (and set VEOF to 04), and then had
513 process.c send additional EOF chars to flush the output when faced
514 with long lines, but this leads to weird effects when the
515 subprocess has disabled ICANON and ends up seeing those spurious
516 extra EOFs. So we don't send EOFs any more in
517 process.c:send_process. First we tried to disable ICANON by
518 default, so if a subsprocess sets up ICANON, it's his problem (or
519 the Elisp package that talks to it) to deal with lines that are
520 too long. But this disables some features, such as the ability
521 to send EOF signals. So we re-enabled ICANON but there is no
522 more "send eof to flush" going on (which is wrong and unportable
523 in itself). The correct way to handle too much output is to
524 buffer what could not be written and then write it again when
525 select returns ok for writing. This has it own set of
526 problems. Write is now asynchronous, is that a problem? How much
527 do we buffer, and what do we do when that limit is reached? */
529 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
530 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
531 #if 0 /* These settings only apply to non-ICANON mode. */
532 s
.main
.c_cc
[VMIN
] = 1;
533 s
.main
.c_cc
[VTIME
] = 0;
536 emacs_set_tty (out
, &s
, 0);
537 #endif /* not WINDOWSNT */
539 #endif /* not MSDOS */
542 /* Record a signal code and the action for it. */
546 struct sigaction action
;
549 static void save_signal_handlers (struct save_signal
*);
550 static void restore_signal_handlers (struct save_signal
*);
552 /* Suspend the Emacs process; give terminal to its superior. */
560 /* On a system where suspending is not implemented,
561 instead fork a subshell and let it talk directly to the terminal
568 /* Fork a subshell. */
573 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
576 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
578 char oldwd
[MAX_UTF8_PATH
];
584 struct save_signal saved_handlers
[5];
585 char *str
= SSDATA (encode_current_directory ());
591 char *volatile str_volatile
= str
;
598 error ("Can't spawn subshell");
600 saved_handlers
[0].code
= SIGINT
;
601 saved_handlers
[1].code
= SIGQUIT
;
602 saved_handlers
[2].code
= SIGTERM
;
604 saved_handlers
[3].code
= SIGIO
;
605 saved_handlers
[4].code
= 0;
607 saved_handlers
[3].code
= 0;
611 save_signal_handlers (saved_handlers
);
618 #ifdef DOS_NT /* MW, Aug 1993 */
619 getcwd (oldwd
, sizeof oldwd
);
621 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
624 sh
= egetenv ("SHELL");
628 /* Use our buffer's default directory for the subshell. */
629 if (chdir (str
) != 0)
633 _exit (EXIT_CANCELED
);
637 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
639 char *epwd
= getenv ("PWD");
640 char old_pwd
[MAXPATHLEN
+1+4];
642 /* If PWD is set, pass it with corrected value. */
645 strcpy (old_pwd
, epwd
);
646 setenv ("PWD", str
, 1);
649 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
651 putenv (old_pwd
); /* restore previous value */
653 #else /* not MSDOS */
655 /* Waits for process completion */
656 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
657 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
659 write (1, "Can't execute subshell", 22);
660 #else /* not WINDOWSNT */
661 execlp (sh
, sh
, (char *) 0);
663 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
664 #endif /* not WINDOWSNT */
665 #endif /* not MSDOS */
668 /* Do this now if we did not do it before. */
670 save_signal_handlers (saved_handlers
);
674 wait_for_termination (pid
, &status
, 0);
676 restore_signal_handlers (saved_handlers
);
680 save_signal_handlers (struct save_signal
*saved_handlers
)
682 while (saved_handlers
->code
)
684 struct sigaction action
;
685 emacs_sigaction_init (&action
, SIG_IGN
);
686 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
692 restore_signal_handlers (struct save_signal
*saved_handlers
)
694 while (saved_handlers
->code
)
696 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
702 static int old_fcntl_flags
[FD_SETSIZE
];
709 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
710 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
711 interrupts_deferred
= 0;
720 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
734 sigemptyset (&unblocked
);
736 sigaddset (&unblocked
, SIGWINCH
);
738 sigaddset (&unblocked
, SIGIO
);
739 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
741 interrupts_deferred
= 0;
746 unrequest_sigio (void)
754 sigemptyset (&blocked
);
756 sigaddset (&blocked
, SIGWINCH
);
758 sigaddset (&blocked
, SIGIO
);
759 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
760 interrupts_deferred
= 1;
768 block_child_signal (sigset_t
*oldset
)
771 sigemptyset (&blocked
);
772 sigaddset (&blocked
, SIGCHLD
);
773 sigaddset (&blocked
, SIGINT
);
774 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
777 /* Unblock SIGCHLD. */
780 unblock_child_signal (sigset_t
const *oldset
)
782 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
787 block_interrupt_signal (sigset_t
*oldset
)
790 sigemptyset (&blocked
);
791 sigaddset (&blocked
, SIGINT
);
792 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
795 /* Restore previously saved signal mask. */
797 restore_signal_mask (sigset_t
const *oldset
)
799 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
804 /* Saving and restoring the process group of Emacs's terminal. */
806 /* The process group of which Emacs was a member when it initially
809 If Emacs was in its own process group (i.e. inherited_pgroup ==
810 getpid ()), then we know we're running under a shell with job
811 control (Emacs would never be run as part of a pipeline).
814 If Emacs was not in its own process group, then we know we're
815 running under a shell (or a caller) that doesn't know how to
816 separate itself from Emacs (like sh). Emacs must be in its own
817 process group in order to receive SIGIO correctly. In this
818 situation, we put ourselves in our own pgroup, forcibly set the
819 tty's pgroup to our pgroup, and make sure to restore and reinstate
820 the tty's pgroup just like any other terminal setting. If
821 inherited_group was not the tty's pgroup, then we'll get a
822 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
823 it goes foreground in the future, which is what should happen. */
825 static pid_t inherited_pgroup
;
828 init_foreground_group (void)
830 pid_t pgrp
= getpgrp ();
831 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
834 /* Block and unblock SIGTTOU. */
837 block_tty_out_signal (sigset_t
*oldset
)
841 sigemptyset (&blocked
);
842 sigaddset (&blocked
, SIGTTOU
);
843 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
848 unblock_tty_out_signal (sigset_t
const *oldset
)
851 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
855 /* Safely set a controlling terminal FD's process group to PGID.
856 If we are not in the foreground already, POSIX requires tcsetpgrp
857 to deliver a SIGTTOU signal, which would stop us. This is an
858 annoyance, so temporarily ignore the signal.
860 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
861 skip all this unless SIGTTOU is defined. */
863 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
868 block_tty_out_signal (&oldset
);
869 tcsetpgrp (fd
, pgid
);
870 unblock_tty_out_signal (&oldset
);
875 /* Split off the foreground process group to Emacs alone. When we are
876 in the foreground, but not started in our own process group,
877 redirect the tty device handle FD to point to our own process
878 group. FD must be the file descriptor of the controlling tty. */
880 narrow_foreground_group (int fd
)
882 if (inherited_pgroup
&& setpgid (0, 0) == 0)
883 tcsetpgrp_without_stopping (fd
, getpid ());
886 /* Set the tty to our original foreground group. */
888 widen_foreground_group (int fd
)
890 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
891 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
894 /* Getting and setting emacs_tty structures. */
896 /* Set *TC to the parameters associated with the terminal FD,
897 or clear it if the parameters are not available.
898 Return 0 on success, -1 on failure. */
900 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
902 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
903 memset (&settings
->main
, 0, sizeof (settings
->main
));
906 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
909 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
911 settings
->main
= console_mode
;
914 #endif /* WINDOWSNT */
917 /* We have those nifty POSIX tcmumbleattr functions. */
918 return tcgetattr (fd
, &settings
->main
);
923 /* Set the parameters of the tty on FD according to the contents of
924 *SETTINGS. If FLUSHP, discard input.
925 Return 0 if all went well, and -1 (setting errno) if anything failed. */
928 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
930 /* Set the primary parameters - baud rate, character size, etcetera. */
933 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
935 if (h
&& h
!= INVALID_HANDLE_VALUE
)
939 /* Assume the handle is open for input. */
941 FlushConsoleInputBuffer (h
);
942 new_mode
= settings
->main
;
943 SetConsoleMode (h
, new_mode
);
945 #endif /* WINDOWSNT */
948 /* We have those nifty POSIX tcmumbleattr functions.
949 William J. Smith <wjs@wiis.wang.com> writes:
950 "POSIX 1003.1 defines tcsetattr to return success if it was
951 able to perform any of the requested actions, even if some
952 of the requested actions could not be performed.
953 We must read settings back to ensure tty setup properly.
954 AIX requires this to keep tty from hanging occasionally." */
955 /* This make sure that we don't loop indefinitely in here. */
956 for (i
= 0 ; i
< 10 ; i
++)
957 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
968 memset (&new, 0, sizeof (new));
969 /* Get the current settings, and see if they're what we asked for. */
970 tcgetattr (fd
, &new);
971 /* We cannot use memcmp on the whole structure here because under
972 * aix386 the termios structure has some reserved field that may
975 if ( new.c_iflag
== settings
->main
.c_iflag
976 && new.c_oflag
== settings
->main
.c_oflag
977 && new.c_cflag
== settings
->main
.c_cflag
978 && new.c_lflag
== settings
->main
.c_lflag
979 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
986 /* We have survived the tempest. */
993 static int old_fcntl_owner
[FD_SETSIZE
];
994 #endif /* F_SETOWN */
996 /* This may also be defined in stdio,
997 but if so, this does no harm,
998 and using the same name avoids wasting the other one's space. */
1001 unsigned char _sobuf
[BUFSIZ
+8];
1003 char _sobuf
[BUFSIZ
];
1006 /* Initialize the terminal mode on all tty devices that are currently
1010 init_all_sys_modes (void)
1012 struct tty_display_info
*tty
;
1013 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1014 init_sys_modes (tty
);
1017 /* Initialize the terminal mode on the given tty device. */
1020 init_sys_modes (struct tty_display_info
*tty_out
)
1022 struct emacs_tty tty
;
1024 Lisp_Object terminal
;
1027 Vtty_erase_char
= Qnil
;
1032 if (!tty_out
->output
)
1033 return; /* The tty is suspended. */
1035 narrow_foreground_group (fileno (tty_out
->input
));
1037 if (! tty_out
->old_tty
)
1038 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1040 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1042 tty
= *tty_out
->old_tty
;
1044 #if !defined (DOS_NT)
1045 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1047 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1048 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1049 #ifdef INLCR /* I'm just being cautious,
1050 since I can't check how widespread INLCR is--rms. */
1051 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1054 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1056 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1057 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1059 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1061 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1062 if (tty_out
->flow_control
)
1064 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1066 tty
.main
.c_iflag
&= ~IXANY
;
1070 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1071 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1073 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1075 if (tty_out
->meta_key
)
1077 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1078 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1082 XSETTERMINAL(terminal
, tty_out
->terminal
);
1083 if (!NILP (Fcontrolling_tty_p (terminal
)))
1085 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1086 /* Set up C-g for both SIGQUIT and SIGINT.
1087 We don't know which we will get, but we handle both alike
1088 so which one it really gives us does not matter. */
1089 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1093 /* We normally don't get interrupt or quit signals from tty
1094 devices other than our controlling terminal; therefore,
1095 we must handle C-g as normal input. Unfortunately, this
1096 means that the interrupt and quit feature must be
1097 disabled on secondary ttys, or we would not even see the
1100 Note that even though emacsclient could have special code
1101 to pass SIGINT to Emacs, we should _not_ enable
1102 interrupt/quit keys for emacsclient frames. This means
1103 that we can't break out of loops in C code from a
1104 secondary tty frame, but we can always decide what
1105 display the C-g came from, which is more important from a
1106 usability point of view. (Consider the case when two
1107 people work together using the same Emacs instance.) */
1108 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1109 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1111 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1112 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1114 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1119 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1122 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1123 #endif /* V_DSUSP */
1124 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1125 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1128 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1131 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1132 #endif /* VREPRINT */
1134 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1135 #endif /* VWERASE */
1137 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1138 #endif /* VDISCARD */
1140 if (tty_out
->flow_control
)
1143 tty
.main
.c_cc
[VSTART
] = '\021';
1146 tty
.main
.c_cc
[VSTOP
] = '\023';
1152 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1155 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1160 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1161 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1162 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1163 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1164 if (tty_out
->flow_control
)
1167 tty
.main
.c_cc
[VSTART
] = '\021';
1170 tty
.main
.c_cc
[VSTOP
] = '\023';
1173 /* Also, PTY overloads NUL and BREAK.
1174 don't ignore break, but don't signal either, so it looks like NUL.
1175 This really serves a purpose only if running in an XTERM window
1176 or via TELNET or the like, but does no harm elsewhere. */
1177 tty
.main
.c_iflag
&= ~IGNBRK
;
1178 tty
.main
.c_iflag
&= ~BRKINT
;
1180 #endif /* not DOS_NT */
1182 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1183 if (!tty_out
->term_initted
)
1184 internal_terminal_init ();
1185 dos_ttraw (tty_out
);
1188 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1190 /* This code added to insure that, if flow-control is not to be used,
1191 we have an unlocked terminal at the start. */
1194 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1197 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1200 #if !defined (DOS_NT)
1202 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1207 if (interrupt_input
)
1209 old_fcntl_owner
[fileno (tty_out
->input
)] =
1210 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1211 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1212 init_sigio (fileno (tty_out
->input
));
1214 if (gpm_tty
== tty_out
)
1216 /* Arrange for mouse events to give us SIGIO signals. */
1217 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1218 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1219 init_sigio (gpm_fd
);
1221 #endif /* HAVE_GPM */
1223 #endif /* F_GETOWN */
1226 /* This symbol is defined on recent USG systems.
1227 Someone says without this call USG won't really buffer the file
1228 even with a call to setbuf. */
1229 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1231 setbuf (tty_out
->output
, (char *) _sobuf
);
1234 if (tty_out
->terminal
->set_terminal_modes_hook
)
1235 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1237 if (!tty_out
->term_initted
)
1239 Lisp_Object tail
, frame
;
1240 FOR_EACH_FRAME (tail
, frame
)
1242 /* XXX This needs to be revised. */
1243 if (FRAME_TERMCAP_P (XFRAME (frame
))
1244 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1245 init_frame_faces (XFRAME (frame
));
1249 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1251 /* We used to call "direct_output_forward_char(0)" here,
1252 but it's not clear why, since it may not do anything anyway. */
1256 Lisp_Object tail
, frame
;
1258 FOR_EACH_FRAME (tail
, frame
)
1260 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1261 || FRAME_MSDOS_P (XFRAME (frame
)))
1262 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1263 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1267 tty_out
->term_initted
= 1;
1270 /* Return true if safe to use tabs in output.
1271 At the time this is called, init_sys_modes has not been done yet. */
1274 tabs_safe_p (int fd
)
1276 struct emacs_tty etty
;
1278 emacs_get_tty (fd
, &etty
);
1281 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1282 #else /* not TABDLY */
1284 #endif /* not TABDLY */
1290 /* Discard echoing. */
1293 suppress_echo_on_tty (int fd
)
1295 struct emacs_tty etty
;
1297 emacs_get_tty (fd
, &etty
);
1299 /* Set raw input mode. */
1302 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1303 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1304 #endif /* ! WINDOWSNT */
1305 emacs_set_tty (fd
, &etty
, 0);
1308 /* Get terminal size from system.
1309 Store number of lines into *HEIGHTP and width into *WIDTHP.
1310 We store 0 if there's no valid information. */
1313 get_tty_size (int fd
, int *widthp
, int *heightp
)
1315 #if defined TIOCGWINSZ
1318 struct winsize size
;
1320 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1321 *widthp
= *heightp
= 0;
1324 *widthp
= size
.ws_col
;
1325 *heightp
= size
.ws_row
;
1328 #elif defined TIOCGSIZE
1330 /* SunOS - style. */
1331 struct ttysize size
;
1333 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1334 *widthp
= *heightp
= 0;
1337 *widthp
= size
.ts_cols
;
1338 *heightp
= size
.ts_lines
;
1341 #elif defined WINDOWSNT
1343 CONSOLE_SCREEN_BUFFER_INFO info
;
1344 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1346 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1347 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1350 *widthp
= *heightp
= 0;
1354 *widthp
= ScreenCols ();
1355 *heightp
= ScreenRows ();
1357 #else /* system doesn't know size */
1365 /* Set the logical window size associated with descriptor FD
1366 to HEIGHT and WIDTH. This is used mainly with ptys.
1367 Return a negative value on failure. */
1370 set_window_size (int fd
, int height
, int width
)
1375 struct winsize size
;
1376 size
.ws_row
= height
;
1377 size
.ws_col
= width
;
1379 return ioctl (fd
, TIOCSWINSZ
, &size
);
1384 /* SunOS - style. */
1385 struct ttysize size
;
1386 size
.ts_lines
= height
;
1387 size
.ts_cols
= width
;
1389 return ioctl (fd
, TIOCGSIZE
, &size
);
1392 #endif /* not SunOS-style */
1393 #endif /* not BSD-style */
1398 /* Prepare all terminal devices for exiting Emacs. */
1401 reset_all_sys_modes (void)
1403 struct tty_display_info
*tty
;
1404 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1405 reset_sys_modes (tty
);
1408 /* Prepare the terminal for closing it; move the cursor to the
1409 bottom of the frame, turn off interrupt-driven I/O, etc. */
1412 reset_sys_modes (struct tty_display_info
*tty_out
)
1416 fflush_unlocked (stdout
);
1419 if (!tty_out
->term_initted
)
1422 if (!tty_out
->output
)
1423 return; /* The tty is suspended. */
1425 /* Go to and clear the last line of the terminal. */
1427 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1429 /* Code adapted from tty_clear_end_of_line. */
1430 if (tty_out
->TS_clr_line
)
1432 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1435 { /* have to do it the hard way */
1436 tty_turn_off_insert (tty_out
);
1438 for (int i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1439 fputc_unlocked (' ', tty_out
->output
);
1442 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1443 fflush_unlocked (tty_out
->output
);
1445 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1446 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1448 /* Avoid possible loss of output when changing terminal modes. */
1449 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1454 if (interrupt_input
)
1456 reset_sigio (fileno (tty_out
->input
));
1457 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1458 old_fcntl_owner
[fileno (tty_out
->input
)]);
1460 #endif /* F_SETOWN */
1461 fcntl (fileno (tty_out
->input
), F_SETFL
,
1462 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1465 if (tty_out
->old_tty
)
1466 while (emacs_set_tty (fileno (tty_out
->input
),
1467 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1470 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1474 widen_foreground_group (fileno (tty_out
->input
));
1479 /* Set up the proper status flags for use of a pty. */
1484 /* I'm told that TOICREMOTE does not mean control chars
1485 "can't be sent" but rather that they don't have
1486 input-editing or signaling effects.
1487 That should be good, because we have other ways
1488 to do those things in Emacs.
1489 However, telnet mode seems not to work on 4.2.
1490 So TIOCREMOTE is turned off now. */
1492 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1493 will hang. In particular, the "timeout" feature (which
1494 causes a read to return if there is no data available)
1495 does this. Also it is known that telnet mode will hang
1496 in such a way that Emacs must be stopped (perhaps this
1497 is the same problem).
1499 If TIOCREMOTE is turned off, then there is a bug in
1500 hp-ux which sometimes loses data. Apparently the
1501 code which blocks the master process when the internal
1502 buffer fills up does not work. Other than this,
1503 though, everything else seems to work fine.
1505 Since the latter lossage is more benign, we may as well
1506 lose that way. -- cph */
1508 #if defined (UNIX98_PTYS)
1511 ioctl (fd
, FIONBIO
, &on
);
1516 #endif /* HAVE_PTYS */
1519 init_system_name (void)
1523 /* Set system-name to nil so that the build is deterministic. */
1524 Vsystem_name
= Qnil
;
1527 char *hostname_alloc
= NULL
;
1529 #ifndef HAVE_GETHOSTNAME
1532 hostname
= uts
.nodename
;
1533 #else /* HAVE_GETHOSTNAME */
1534 char hostname_buf
[256];
1535 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1536 hostname
= hostname_buf
;
1538 /* Try to get the host name; if the buffer is too short, try
1539 again. Apparently, the only indication gethostname gives of
1540 whether the buffer was large enough is the presence or absence
1541 of a '\0' in the string. Eech. */
1544 gethostname (hostname
, hostname_size
- 1);
1545 hostname
[hostname_size
- 1] = '\0';
1547 /* Was the buffer large enough for the '\0'? */
1548 if (strlen (hostname
) < hostname_size
- 1)
1551 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1552 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1554 #endif /* HAVE_GETHOSTNAME */
1556 for (p
= hostname
; *p
; p
++)
1557 if (*p
== ' ' || *p
== '\t')
1559 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1560 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1561 Vsystem_name
= build_string (hostname
);
1562 xfree (hostname_alloc
);
1565 sigset_t empty_mask
;
1567 static struct sigaction process_fatal_action
;
1570 emacs_sigaction_flags (void)
1573 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1574 'select') to reset their timeout on some platforms (e.g.,
1575 HP-UX 11), which is not what we want. Also, when Emacs is
1576 interactive, we don't want SA_RESTART because we need to poll
1577 for pending input so we need long-running syscalls to be interrupted
1578 after a signal that sets pending_signals.
1580 Non-interactive keyboard input goes through stdio, where we
1581 always want restartable system calls. */
1588 /* Store into *ACTION a signal action suitable for Emacs, with handler
1591 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1593 sigemptyset (&action
->sa_mask
);
1595 /* When handling a signal, block nonfatal system signals that are caught
1596 by Emacs. This makes race conditions less likely. */
1597 sigaddset (&action
->sa_mask
, SIGALRM
);
1599 sigaddset (&action
->sa_mask
, SIGCHLD
);
1602 sigaddset (&action
->sa_mask
, SIGDANGER
);
1604 #ifdef PROFILER_CPU_SUPPORT
1605 sigaddset (&action
->sa_mask
, SIGPROF
);
1608 sigaddset (&action
->sa_mask
, SIGWINCH
);
1610 if (! noninteractive
)
1612 sigaddset (&action
->sa_mask
, SIGINT
);
1613 sigaddset (&action
->sa_mask
, SIGQUIT
);
1615 sigaddset (&action
->sa_mask
, SIGIO
);
1619 action
->sa_handler
= handler
;
1620 action
->sa_flags
= emacs_sigaction_flags ();
1623 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1624 pthread_t main_thread_id
;
1627 /* SIG has arrived at the current process. Deliver it to the main
1628 thread, which should handle it with HANDLER. (Delivering the
1629 signal to some other thread might not work if the other thread is
1632 If we are on the main thread, handle the signal SIG with HANDLER.
1633 Otherwise, redirect the signal to the main thread, blocking it from
1634 this thread. POSIX says any thread can receive a signal that is
1635 associated with a process, process group, or asynchronous event.
1636 On GNU/Linux the main thread typically gets a process signal unless
1637 it's blocked, but other systems (FreeBSD at least) can deliver the
1638 signal to other threads. */
1640 deliver_process_signal (int sig
, signal_handler_t handler
)
1642 /* Preserve errno, to avoid race conditions with signal handlers that
1643 might change errno. Races can occur even in single-threaded hosts. */
1644 int old_errno
= errno
;
1646 bool on_main_thread
= true;
1647 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1648 if (! pthread_equal (pthread_self (), main_thread_id
))
1651 sigemptyset (&blocked
);
1652 sigaddset (&blocked
, sig
);
1653 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1654 pthread_kill (main_thread_id
, sig
);
1655 on_main_thread
= false;
1664 /* Static location to save a fatal backtrace in a thread.
1665 FIXME: If two subsidiary threads fail simultaneously, the resulting
1666 backtrace may be garbage. */
1667 enum { BACKTRACE_LIMIT_MAX
= 500 };
1668 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1669 static int thread_backtrace_npointers
;
1671 /* SIG has arrived at the current thread.
1672 If we are on the main thread, handle the signal SIG with HANDLER.
1673 Otherwise, this is a fatal error in the handling thread. */
1675 deliver_thread_signal (int sig
, signal_handler_t handler
)
1677 int old_errno
= errno
;
1679 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1680 if (! pthread_equal (pthread_self (), main_thread_id
))
1682 thread_backtrace_npointers
1683 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1684 sigaction (sig
, &process_fatal_action
, 0);
1685 pthread_kill (main_thread_id
, sig
);
1687 /* Avoid further damage while the main thread is exiting. */
1689 sigsuspend (&empty_mask
);
1697 #if !HAVE_DECL_SYS_SIGLIST
1699 # ifdef _sys_siglist
1700 # define sys_siglist _sys_siglist
1701 # elif HAVE_DECL___SYS_SIGLIST
1702 # define sys_siglist __sys_siglist
1704 # define sys_siglist my_sys_siglist
1705 static char const *sys_siglist
[NSIG
];
1710 # define sys_siglist_entries _sys_nsig
1712 # define sys_siglist_entries NSIG
1715 /* Handle bus errors, invalid instruction, etc. */
1717 handle_fatal_signal (int sig
)
1719 terminate_due_to_signal (sig
, 40);
1723 deliver_fatal_signal (int sig
)
1725 deliver_process_signal (sig
, handle_fatal_signal
);
1729 deliver_fatal_thread_signal (int sig
)
1731 deliver_thread_signal (sig
, handle_fatal_signal
);
1734 static _Noreturn
void
1735 handle_arith_signal (int sig
)
1737 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1738 xsignal0 (Qarith_error
);
1741 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1743 /* Alternate stack used by SIGSEGV handler below. */
1745 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1748 /* Return true if SIGINFO indicates a stack overflow. */
1751 stack_overflow (siginfo_t
*siginfo
)
1753 if (!attempt_stack_overflow_recovery
)
1756 /* In theory, a more-accurate heuristic can be obtained by using
1757 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1758 and pthread_attr_getguardsize to find the location and size of the
1759 guard area. In practice, though, these functions are so hard to
1760 use reliably that they're not worth bothering with. E.g., see:
1761 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1762 Other operating systems also have problems, e.g., Solaris's
1763 stack_violation function is tailor-made for this problem, but it
1764 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1766 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1772 /* The faulting address. */
1773 char *addr
= siginfo
->si_addr
;
1777 /* The known top and bottom of the stack. The actual stack may
1778 extend a bit beyond these boundaries. */
1779 char *bot
= stack_bottom
;
1780 char *top
= current_thread
->stack_top
;
1782 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1783 of the known stack divided by the size of the guard area past the
1784 end of the stack top. The heuristic is that a bad address is
1785 considered to be a stack overflow if it occurs within
1786 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1787 stack. This heuristic is not exactly correct but it's good
1788 enough in practice. */
1789 enum { LG_STACK_HEURISTIC
= 8 };
1792 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1794 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1798 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1801 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1803 /* Hard GC error may lead to stack overflow caused by
1804 too nested calls to mark_object. No way to survive. */
1805 bool fatal
= gc_in_progress
;
1807 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1808 if (!fatal
&& !pthread_equal (pthread_self (), main_thread_id
))
1812 if (!fatal
&& stack_overflow (siginfo
))
1813 siglongjmp (return_to_command_loop
, 1);
1815 /* Otherwise we can't do anything with this. */
1816 deliver_fatal_thread_signal (sig
);
1819 /* Return true if we have successfully set up SIGSEGV handler on alternate
1820 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1825 struct sigaction sa
;
1828 ss
.ss_sp
= sigsegv_stack
;
1829 ss
.ss_size
= sizeof (sigsegv_stack
);
1831 if (sigaltstack (&ss
, NULL
) < 0)
1834 sigfillset (&sa
.sa_mask
);
1835 sa
.sa_sigaction
= handle_sigsegv
;
1836 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1837 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1840 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1848 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1851 deliver_arith_signal (int sig
)
1853 deliver_thread_signal (sig
, handle_arith_signal
);
1858 /* Handler for SIGDANGER. */
1860 handle_danger_signal (int sig
)
1862 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1864 /* It might be unsafe to call do_auto_save now. */
1865 force_auto_save_soon ();
1869 deliver_danger_signal (int sig
)
1871 deliver_process_signal (sig
, handle_danger_signal
);
1875 /* Treat SIG as a terminating signal, unless it is already ignored and
1876 we are in --batch mode. Among other things, this makes nohup work. */
1878 maybe_fatal_sig (int sig
)
1880 bool catch_sig
= !noninteractive
;
1883 struct sigaction old_action
;
1884 sigaction (sig
, 0, &old_action
);
1885 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1888 sigaction (sig
, &process_fatal_action
, 0);
1892 init_signals (bool dumping
)
1894 struct sigaction thread_fatal_action
;
1895 struct sigaction action
;
1897 sigemptyset (&empty_mask
);
1899 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1900 main_thread_id
= pthread_self ();
1903 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1906 sys_siglist
[SIGABRT
] = "Aborted";
1908 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1910 sys_siglist
[SIGALRM
] = "Alarm clock";
1912 sys_siglist
[SIGBUS
] = "Bus error";
1915 sys_siglist
[SIGCHLD
] = "Child status changed";
1918 sys_siglist
[SIGCONT
] = "Continued";
1921 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1924 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1927 sys_siglist
[SIGEMT
] = "Emulation trap";
1929 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1931 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1934 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1936 sys_siglist
[SIGHUP
] = "Hangup";
1937 sys_siglist
[SIGILL
] = "Illegal instruction";
1938 sys_siglist
[SIGINT
] = "Interrupt";
1940 sys_siglist
[SIGIO
] = "I/O possible";
1943 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1946 sys_siglist
[SIGIOT
] = "IOT trap";
1948 sys_siglist
[SIGKILL
] = "Killed";
1950 sys_siglist
[SIGLOST
] = "Resource lost";
1953 sys_siglist
[SIGLWP
] = "SIGLWP";
1956 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1959 sys_siglist
[SIGWIND
] = "SIGPHONE";
1961 sys_siglist
[SIGPIPE
] = "Broken pipe";
1963 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1966 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1969 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1972 sys_siglist
[SIGPWR
] = "Power-fail restart";
1974 sys_siglist
[SIGQUIT
] = "Quit";
1976 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1979 sys_siglist
[SIGSAK
] = "Secure attention";
1981 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1983 sys_siglist
[SIGSOUND
] = "Sound completed";
1986 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1989 sys_siglist
[SIGSTP
] = "Stopped (user)";
1992 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1994 sys_siglist
[SIGTERM
] = "Terminated";
1996 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1999 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
2002 sys_siglist
[SIGTSTP
] = "Stopped (user)";
2005 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
2008 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
2011 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2014 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2017 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2020 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2023 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2026 sys_siglist
[SIGWINCH
] = "Window size changed";
2029 sys_siglist
[SIGWIND
] = "SIGWIND";
2032 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2035 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2038 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2040 /* Don't alter signal handlers if dumping. On some machines,
2041 changing signal handlers sets static data that would make signals
2042 fail to work right when the dumped Emacs is run. */
2046 sigfillset (&process_fatal_action
.sa_mask
);
2047 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2048 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2050 sigfillset (&thread_fatal_action
.sa_mask
);
2051 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2052 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2054 /* SIGINT may need special treatment on MS-Windows. See
2055 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2056 Please update the doc of kill-emacs, kill-emacs-hook, and
2057 NEWS if you change this. */
2059 maybe_fatal_sig (SIGHUP
);
2060 maybe_fatal_sig (SIGINT
);
2061 maybe_fatal_sig (SIGTERM
);
2063 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2064 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2065 to behave more like typical batch applications do. */
2066 if (! noninteractive
)
2067 signal (SIGPIPE
, SIG_IGN
);
2069 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2070 sigaction (SIGILL
, &thread_fatal_action
, 0);
2071 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2073 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2074 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2075 interpreter's floating point operations, so treat SIGFPE as an
2076 arith-error if it arises in the main thread. */
2077 if (IEEE_FLOATING_POINT
)
2078 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2081 emacs_sigaction_init (&action
, deliver_arith_signal
);
2082 sigaction (SIGFPE
, &action
, 0);
2086 add_user_signal (SIGUSR1
, "sigusr1");
2089 add_user_signal (SIGUSR2
, "sigusr2");
2091 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2093 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2096 sigaction (SIGORE
, &thread_fatal_action
, 0);
2099 sigaction (SIGUME
, &thread_fatal_action
, 0);
2102 sigaction (SIGDLK
, &process_fatal_action
, 0);
2105 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2108 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2111 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2114 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2116 if (!init_sigsegv ())
2117 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2119 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2121 sigaction (SIGTERM
, &process_fatal_action
, 0);
2123 signal (SIGPROF
, SIG_IGN
);
2126 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2129 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2132 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2136 /* This just means available memory is getting low. */
2137 emacs_sigaction_init (&action
, deliver_danger_signal
);
2138 sigaction (SIGDANGER
, &action
, 0);
2141 /* AIX-specific signals. */
2143 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2146 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2149 sigaction (SIGMSG
, &process_fatal_action
, 0);
2152 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2155 sigaction (SIGSAK
, &process_fatal_action
, 0);
2158 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2161 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2171 /* Figure out how many bits the system's random number generator uses.
2172 `random' and `lrand48' are assumed to return 31 usable bits.
2173 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2174 so we'll shift it and treat it like the 15-bit USG `rand'. */
2178 # define RAND_BITS 31
2179 # else /* !HAVE_RANDOM */
2180 # ifdef HAVE_LRAND48
2181 # define RAND_BITS 31
2182 # define random lrand48
2183 # else /* !HAVE_LRAND48 */
2184 # define RAND_BITS 15
2185 # if RAND_MAX == 32767
2186 # define random rand
2187 # else /* RAND_MAX != 32767 */
2188 # if RAND_MAX == 2147483647
2189 # define random() (rand () >> 16)
2190 # else /* RAND_MAX != 2147483647 */
2192 # define random rand
2194 # define random() (rand () >> 16)
2196 # endif /* RAND_MAX != 2147483647 */
2197 # endif /* RAND_MAX != 32767 */
2198 # endif /* !HAVE_LRAND48 */
2199 # endif /* !HAVE_RANDOM */
2200 #endif /* !RAND_BITS */
2203 typedef unsigned int random_seed
;
2204 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2205 #elif defined HAVE_LRAND48
2206 /* Although srand48 uses a long seed, this is unsigned long to avoid
2207 undefined behavior on signed integer overflow in init_random. */
2208 typedef unsigned long int random_seed
;
2209 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2211 typedef unsigned int random_seed
;
2212 static void set_random_seed (random_seed arg
) { srand (arg
); }
2216 seed_random (void *seed
, ptrdiff_t seed_size
)
2218 random_seed arg
= 0;
2219 unsigned char *argp
= (unsigned char *) &arg
;
2220 unsigned char *seedp
= seed
;
2221 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2222 argp
[i
% sizeof arg
] ^= seedp
[i
];
2223 set_random_seed (arg
);
2230 bool success
= false;
2232 /* First, try seeding the PRNG from the operating system's entropy
2233 source. This approach is both fast and secure. */
2235 success
= w32_init_random (&v
, sizeof v
) == 0;
2237 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2240 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2245 /* If that didn't work, try using GnuTLS, which is secure, but on
2246 some systems, can be somewhat slow. */
2248 success
= EQ (emacs_gnutls_global_init (), Qt
)
2249 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2251 /* If _that_ didn't work, just use the current time value and PID.
2252 It's at least better than XKCD 221. */
2255 struct timespec t
= current_timespec ();
2256 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2259 set_random_seed (v
);
2263 * Return a nonnegative random integer out of whatever we've got.
2264 * It contains enough bits to make a random (signed) Emacs fixnum.
2265 * This suffices even for a 64-bit architecture with a 15-bit rand.
2272 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2273 val
= (random () ^ (val
<< RAND_BITS
)
2274 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2275 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2276 return val
& INTMASK
;
2279 #ifndef HAVE_SNPRINTF
2280 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2282 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2284 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2285 ptrdiff_t nbytes
= size
- 1;
2290 va_start (ap
, format
);
2291 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2295 if (nbytes
== size
- 1)
2297 /* Calculate the length of the string that would have been created
2298 had the buffer been large enough. */
2299 char stackbuf
[4000];
2301 ptrdiff_t bsize
= sizeof stackbuf
;
2302 va_start (ap
, format
);
2303 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2309 if (INT_MAX
< nbytes
)
2322 /* If a backtrace is available, output the top lines of it to stderr.
2323 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2324 This function may be called from a signal handler, so it should
2325 not invoke async-unsafe functions like malloc.
2327 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2328 but do not output anything. This avoids some problems that can
2329 otherwise occur if the malloc arena is corrupted before 'backtrace'
2330 is called, since 'backtrace' may call malloc if the tables are not
2333 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2334 fatal error has occurred in some other thread; generate a thread
2335 backtrace instead, ignoring BACKTRACE_LIMIT. */
2337 emacs_backtrace (int backtrace_limit
)
2339 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2340 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2344 if (thread_backtrace_npointers
)
2346 buffer
= thread_backtrace_buffer
;
2347 npointers
= thread_backtrace_npointers
;
2351 buffer
= main_backtrace_buffer
;
2353 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2354 if (bounded_limit
< 0)
2356 backtrace (buffer
, 1);
2360 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2365 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2366 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2367 if (bounded_limit
< npointers
)
2368 emacs_write (STDERR_FILENO
, "...\n", 4);
2376 terminate_due_to_signal (SIGABRT
, 40);
2380 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2381 Use binary I/O on systems that care about text vs binary I/O.
2382 Arrange for subprograms to not inherit the file descriptor.
2383 Prefer a method that is multithread-safe, if available.
2384 Do not fail merely because the open was interrupted by a signal.
2385 Allow the user to quit. */
2388 emacs_open (const char *file
, int oflags
, int mode
)
2391 if (! (oflags
& O_TEXT
))
2393 oflags
|= O_CLOEXEC
;
2394 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2396 if (! O_CLOEXEC
&& 0 <= fd
)
2397 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2401 /* Open FILE as a stream for Emacs use, with mode MODE.
2402 Act like emacs_open with respect to threads, signals, and quits. */
2405 emacs_fopen (char const *file
, char const *mode
)
2407 int fd
, omode
, oflags
;
2409 char const *m
= mode
;
2413 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2414 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2415 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2416 default: emacs_abort ();
2422 case '+': omode
= O_RDWR
; break;
2423 case 't': bflag
= O_TEXT
; break;
2424 default: /* Ignore. */ break;
2427 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2428 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2431 /* Create a pipe for Emacs use. */
2434 emacs_pipe (int fd
[2])
2439 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2440 if (! O_CLOEXEC
&& result
== 0)
2442 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2443 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2449 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2450 For the background behind this mess, please see Austin Group defect 529
2451 <http://austingroupbugs.net/view.php?id=529>. */
2453 #ifndef POSIX_CLOSE_RESTART
2454 # define POSIX_CLOSE_RESTART 1
2456 posix_close (int fd
, int flag
)
2458 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2459 eassert (flag
== POSIX_CLOSE_RESTART
);
2461 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2462 on a system that does not define POSIX_CLOSE_RESTART.
2464 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2465 closed, and retrying the close could inadvertently close a file
2466 descriptor allocated by some other thread. In other systems
2467 (e.g., HP/UX) FD is not closed. And in still other systems
2468 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2469 multithreaded program there can be no way to tell.
2471 So, in this case, pretend that the close succeeded. This works
2472 well on systems like GNU/Linux that close FD. Although it may
2473 leak a file descriptor on other systems, the leak is unlikely and
2474 it's better to leak than to close a random victim. */
2475 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2479 /* Close FD, retrying if interrupted. If successful, return 0;
2480 otherwise, return -1 and set errno to a non-EINTR value. Consider
2481 an EINPROGRESS error to be successful, as that's merely a signal
2482 arriving. FD is always closed when this function returns, even
2485 Do not call this function if FD is nonnegative and might already be closed,
2486 as that might close an innocent victim opened by some other thread. */
2489 emacs_close (int fd
)
2493 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2496 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2498 eassert (errno
!= EBADF
|| fd
< 0);
2499 return errno
== EINPROGRESS
? 0 : r
;
2504 /* Maximum number of bytes to read or write in a single system call.
2505 This works around a serious bug in Linux kernels before 2.6.16; see
2506 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2507 It's likely to work around similar bugs in other operating systems, so do it
2508 on all platforms. Round INT_MAX down to a page size, with the conservative
2509 assumption that page sizes are at most 2**18 bytes (any kernel with a
2510 page size larger than that shouldn't have the bug). */
2511 #ifndef MAX_RW_COUNT
2512 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2515 /* Read from FD to a buffer BUF with size NBYTE.
2516 If interrupted, process any quits and pending signals immediately
2517 if INTERRUPTIBLE, and then retry the read unless quitting.
2518 Return the number of bytes read, which might be less than NBYTE.
2519 On error, set errno to a value other than EINTR, and return -1. */
2521 emacs_intr_read (int fd
, void *buf
, ptrdiff_t nbyte
, bool interruptible
)
2525 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2526 passes a size that large to emacs_read. */
2531 result
= read (fd
, buf
, nbyte
);
2533 while (result
< 0 && errno
== EINTR
);
2538 /* Read from FD to a buffer BUF with size NBYTE.
2539 If interrupted, retry the read. Return the number of bytes read,
2540 which might be less than NBYTE. On error, set errno to a value
2541 other than EINTR, and return -1. */
2543 emacs_read (int fd
, void *buf
, ptrdiff_t nbyte
)
2545 return emacs_intr_read (fd
, buf
, nbyte
, false);
2548 /* Like emacs_read, but also process quits and pending signals. */
2550 emacs_read_quit (int fd
, void *buf
, ptrdiff_t nbyte
)
2552 return emacs_intr_read (fd
, buf
, nbyte
, true);
2555 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2556 interrupted or if a partial write occurs. Process any quits
2557 immediately if INTERRUPTIBLE is positive, and process any pending
2558 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2559 of bytes written; if this is less than NBYTE, set errno to a value
2560 other than EINTR. */
2562 emacs_full_write (int fd
, char const *buf
, ptrdiff_t nbyte
,
2565 ptrdiff_t bytes_written
= 0;
2569 ssize_t n
= write (fd
, buf
, min (nbyte
, MAX_RW_COUNT
));
2578 if (0 < interruptible
)
2580 if (pending_signals
)
2581 process_pending_signals ();
2592 return bytes_written
;
2595 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2596 interrupted or if a partial write occurs. Do not process quits or
2597 pending signals. Return the number of bytes written, setting errno
2598 if this is less than NBYTE. */
2600 emacs_write (int fd
, void const *buf
, ptrdiff_t nbyte
)
2602 return emacs_full_write (fd
, buf
, nbyte
, 0);
2605 /* Like emacs_write, but also process pending signals. */
2607 emacs_write_sig (int fd
, void const *buf
, ptrdiff_t nbyte
)
2609 return emacs_full_write (fd
, buf
, nbyte
, -1);
2612 /* Like emacs_write, but also process quits and pending signals. */
2614 emacs_write_quit (int fd
, void const *buf
, ptrdiff_t nbyte
)
2616 return emacs_full_write (fd
, buf
, nbyte
, 1);
2619 /* Write a diagnostic to standard error that contains MESSAGE and a
2620 string derived from errno. Preserve errno. Do not buffer stderr.
2621 Do not process quits or pending signals if interrupted. */
2623 emacs_perror (char const *message
)
2626 char const *error_string
= emacs_strerror (err
);
2627 char const *command
= (initial_argv
&& initial_argv
[0]
2628 ? initial_argv
[0] : "emacs");
2629 /* Write it out all at once, if it's short; this is less likely to
2630 be interleaved with other output. */
2632 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2633 command
, message
, error_string
);
2634 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2635 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2638 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2639 emacs_write (STDERR_FILENO
, ": ", 2);
2640 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2641 emacs_write (STDERR_FILENO
, ": ", 2);
2642 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2643 emacs_write (STDERR_FILENO
, "\n", 1);
2648 /* Return a struct timeval that is roughly equivalent to T.
2649 Use the least timeval not less than T.
2650 Return an extremal value if the result would overflow. */
2652 make_timeval (struct timespec t
)
2655 tv
.tv_sec
= t
.tv_sec
;
2656 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2658 if (t
.tv_nsec
% 1000 != 0)
2660 if (tv
.tv_usec
< 999999)
2662 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2672 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2673 ATIME and MTIME, respectively.
2674 FD must be either negative -- in which case it is ignored --
2675 or a file descriptor that is open on FILE.
2676 If FD is nonnegative, then FILE can be NULL. */
2678 set_file_times (int fd
, const char *filename
,
2679 struct timespec atime
, struct timespec mtime
)
2681 struct timespec timespec
[2];
2682 timespec
[0] = atime
;
2683 timespec
[1] = mtime
;
2684 return fdutimens (fd
, filename
, timespec
);
2687 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2688 This is like renameat except that it fails if DST already exists,
2689 or if this operation is not supported atomically. Return 0 if
2690 successful, -1 (setting errno) otherwise. */
2692 renameat_noreplace (int srcfd
, char const *src
, int dstfd
, char const *dst
)
2694 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2695 return syscall (SYS_renameat2
, srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2702 /* Like strsignal, except async-signal-safe, and this function typically
2703 returns a string in the C locale rather than the current locale. */
2705 safe_strsignal (int code
)
2707 char const *signame
= 0;
2709 if (0 <= code
&& code
< sys_siglist_entries
)
2710 signame
= sys_siglist
[code
];
2712 signame
= "Unknown signal";
2718 /* For make-serial-process */
2720 serial_open (Lisp_Object port
)
2722 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2724 report_file_error ("Opening serial port", port
);
2726 ioctl (fd
, TIOCEXCL
, (char *) 0);
2732 #if !defined (HAVE_CFMAKERAW)
2733 /* Workaround for targets which are missing cfmakeraw. */
2734 /* Pasted from man page. */
2736 cfmakeraw (struct termios
*termios_p
)
2738 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2739 termios_p
->c_oflag
&= ~OPOST
;
2740 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2741 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2742 termios_p
->c_cflag
|= CS8
;
2744 #endif /* !defined (HAVE_CFMAKERAW */
2746 #if !defined (HAVE_CFSETSPEED)
2747 /* Workaround for targets which are missing cfsetspeed. */
2749 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2751 return (cfsetispeed (termios_p
, vitesse
)
2752 + cfsetospeed (termios_p
, vitesse
));
2756 /* For serial-process-configure */
2758 serial_configure (struct Lisp_Process
*p
,
2759 Lisp_Object contact
)
2761 Lisp_Object childp2
= Qnil
;
2762 Lisp_Object tem
= Qnil
;
2763 struct termios attr
;
2765 char summary
[4] = "???"; /* This usually becomes "8N1". */
2767 childp2
= Fcopy_sequence (p
->childp
);
2769 /* Read port attributes and prepare default configuration. */
2770 err
= tcgetattr (p
->outfd
, &attr
);
2772 report_file_error ("Failed tcgetattr", Qnil
);
2774 #if defined (CLOCAL)
2775 attr
.c_cflag
|= CLOCAL
;
2778 attr
.c_cflag
|= CREAD
;
2781 /* Configure speed. */
2782 if (!NILP (Fplist_member (contact
, QCspeed
)))
2783 tem
= Fplist_get (contact
, QCspeed
);
2785 tem
= Fplist_get (p
->childp
, QCspeed
);
2787 err
= cfsetspeed (&attr
, XINT (tem
));
2789 report_file_error ("Failed cfsetspeed", tem
);
2790 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2792 /* Configure bytesize. */
2793 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2794 tem
= Fplist_get (contact
, QCbytesize
);
2796 tem
= Fplist_get (p
->childp
, QCbytesize
);
2798 tem
= make_number (8);
2800 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2801 error (":bytesize must be nil (8), 7, or 8");
2802 summary
[0] = XINT (tem
) + '0';
2803 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2804 attr
.c_cflag
&= ~CSIZE
;
2805 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2807 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2808 if (XINT (tem
) != 8)
2809 error ("Bytesize cannot be changed");
2811 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2813 /* Configure parity. */
2814 if (!NILP (Fplist_member (contact
, QCparity
)))
2815 tem
= Fplist_get (contact
, QCparity
);
2817 tem
= Fplist_get (p
->childp
, QCparity
);
2818 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2819 error (":parity must be nil (no parity), `even', or `odd'");
2820 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2821 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2822 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2827 else if (EQ (tem
, Qeven
))
2830 attr
.c_cflag
|= PARENB
;
2831 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2833 else if (EQ (tem
, Qodd
))
2836 attr
.c_cflag
|= (PARENB
| PARODD
);
2837 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2840 /* Don't error on no parity, which should be set by cfmakeraw. */
2842 error ("Parity cannot be configured");
2844 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2846 /* Configure stopbits. */
2847 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2848 tem
= Fplist_get (contact
, QCstopbits
);
2850 tem
= Fplist_get (p
->childp
, QCstopbits
);
2852 tem
= make_number (1);
2854 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2855 error (":stopbits must be nil (1 stopbit), 1, or 2");
2856 summary
[2] = XINT (tem
) + '0';
2857 #if defined (CSTOPB)
2858 attr
.c_cflag
&= ~CSTOPB
;
2859 if (XINT (tem
) == 2)
2860 attr
.c_cflag
|= CSTOPB
;
2862 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2863 if (XINT (tem
) != 1)
2864 error ("Stopbits cannot be configured");
2866 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2868 /* Configure flowcontrol. */
2869 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2870 tem
= Fplist_get (contact
, QCflowcontrol
);
2872 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2873 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2874 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2875 #if defined (CRTSCTS)
2876 attr
.c_cflag
&= ~CRTSCTS
;
2878 #if defined (CNEW_RTSCTS)
2879 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2881 #if defined (IXON) && defined (IXOFF)
2882 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2886 /* Already configured. */
2888 else if (EQ (tem
, Qhw
))
2890 #if defined (CRTSCTS)
2891 attr
.c_cflag
|= CRTSCTS
;
2892 #elif defined (CNEW_RTSCTS)
2893 attr
.c_cflag
|= CNEW_RTSCTS
;
2895 error ("Hardware flowcontrol (RTS/CTS) not supported");
2898 else if (EQ (tem
, Qsw
))
2900 #if defined (IXON) && defined (IXOFF)
2901 attr
.c_iflag
|= (IXON
| IXOFF
);
2903 error ("Software flowcontrol (XON/XOFF) not supported");
2906 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2908 /* Activate configuration. */
2909 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2911 report_file_error ("Failed tcsetattr", Qnil
);
2913 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2914 pset_childp (p
, childp2
);
2916 #endif /* not DOS_NT */
2918 /* System depended enumeration of and access to system processes a-la ps(1). */
2922 /* Process enumeration and access via /proc. */
2925 list_system_processes (void)
2927 Lisp_Object procdir
, match
, proclist
, next
;
2930 /* For every process on the system, there's a directory in the
2931 "/proc" pseudo-directory whose name is the numeric ID of that
2933 procdir
= build_string ("/proc");
2934 match
= build_string ("[0-9]+");
2935 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2937 /* `proclist' gives process IDs as strings. Destructively convert
2938 each string into a number. */
2939 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2942 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2945 /* directory_files_internal returns the files in reverse order; undo
2947 proclist
= Fnreverse (proclist
);
2951 #elif defined DARWIN_OS || defined __FreeBSD__
2954 list_system_processes (void)
2957 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2959 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2962 struct kinfo_proc
*procs
;
2965 Lisp_Object proclist
= Qnil
;
2967 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2970 procs
= xmalloc (len
);
2971 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2977 len
/= sizeof (struct kinfo_proc
);
2978 for (i
= 0; i
< len
; i
++)
2981 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2983 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2992 /* The WINDOWSNT implementation is in w32.c.
2993 The MSDOS implementation is in dosfns.c. */
2994 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2997 list_system_processes (void)
3002 #endif /* !defined (WINDOWSNT) */
3004 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3005 static struct timespec
3006 time_from_jiffies (unsigned long long tval
, long hz
)
3008 unsigned long long s
= tval
/ hz
;
3009 unsigned long long frac
= tval
% hz
;
3012 if (TYPE_MAXIMUM (time_t) < s
)
3014 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
3015 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
3016 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
3019 /* This is reachable only in the unlikely case that HZ * HZ
3020 exceeds ULLONG_MAX. It calculates an approximation that is
3021 guaranteed to be in range. */
3022 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
3023 + (hz
% TIMESPEC_RESOLUTION
!= 0));
3024 ns
= frac
/ hz_per_ns
;
3027 return make_timespec (s
, ns
);
3031 ltime_from_jiffies (unsigned long long tval
, long hz
)
3033 struct timespec t
= time_from_jiffies (tval
, hz
);
3034 return make_lisp_time (t
);
3037 static struct timespec
3041 struct timespec up
= make_timespec (0, 0);
3044 fup
= emacs_fopen ("/proc/uptime", "r");
3048 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
3049 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
3051 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
3052 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
3053 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
3056 if (TYPE_MAXIMUM (time_t) < upsec
)
3058 upsec
= TYPE_MAXIMUM (time_t);
3059 upfrac
= TIMESPEC_RESOLUTION
- 1;
3063 int upfraclen
= upfrac_end
- upfrac_start
;
3064 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3066 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3068 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3070 up
= make_timespec (upsec
, upfrac
);
3079 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3080 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3083 procfs_ttyname (int rdev
)
3086 char name
[PATH_MAX
];
3089 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3095 unsigned long minor_beg
, minor_end
;
3096 char minor
[25]; /* 2 32-bit numbers + dash */
3099 for (; !feof_unlocked (fdev
) && !ferror_unlocked (fdev
); name
[0] = 0)
3101 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3102 && major
== MAJOR (rdev
))
3104 minor_beg
= strtoul (minor
, &endp
, 0);
3106 minor_end
= minor_beg
;
3107 else if (*endp
== '-')
3108 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3112 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3114 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3122 return build_string (name
);
3126 procfs_get_total_memory (void)
3129 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3133 fmem
= emacs_fopen ("/proc/meminfo", "r");
3137 uintmax_t entry_value
;
3141 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3144 retval
= entry_value
;
3149 while ((c
= getc_unlocked (fmem
)) != EOF
&& c
!= '\n')
3167 system_process_attributes (Lisp_Object pid
)
3169 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3173 long clocks_per_sec
;
3175 char procbuf
[1025], *p
, *q
;
3178 static char const default_cmd
[] = "???";
3179 const char *cmd
= default_cmd
;
3180 int cmdsize
= sizeof default_cmd
- 1;
3181 char *cmdline
= NULL
;
3182 ptrdiff_t cmdline_size
;
3185 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3188 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3189 long priority
, niceness
, rss
;
3190 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3191 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3193 Lisp_Object attrs
= Qnil
;
3194 Lisp_Object decoded_cmd
;
3197 CHECK_NUMBER_OR_FLOAT (pid
);
3198 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3199 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3200 if (stat (procfn
, &st
) < 0)
3205 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3207 pw
= getpwuid (uid
);
3210 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3213 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3215 gr
= getgrgid (gid
);
3218 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3220 count
= SPECPDL_INDEX ();
3221 strcpy (fn
, procfn
);
3222 procfn_end
= fn
+ strlen (fn
);
3223 strcpy (procfn_end
, "/stat");
3224 fd
= emacs_open (fn
, O_RDONLY
, 0);
3229 record_unwind_protect_int (close_file_unwind
, fd
);
3230 nread
= emacs_read_quit (fd
, procbuf
, sizeof procbuf
- 1);
3234 procbuf
[nread
] = '\0';
3237 p
= strchr (p
, '(');
3240 q
= strrchr (p
+ 1, ')');
3250 /* Command name is encoded in locale-coding-system; decode it. */
3251 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3252 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3253 Vlocale_coding_system
, 0);
3254 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3256 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3257 utime stime cutime cstime priority nice thcount . start vsize rss */
3259 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3260 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3261 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3262 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3263 &u_time
, &s_time
, &cutime
, &cstime
,
3264 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3269 state_str
[1] = '\0';
3270 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3271 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3272 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3273 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3274 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3275 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3276 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3277 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3278 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3280 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3282 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3283 if (clocks_per_sec
< 0)
3284 clocks_per_sec
= 100;
3285 attrs
= Fcons (Fcons (Qutime
,
3286 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3288 attrs
= Fcons (Fcons (Qstime
,
3289 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3291 attrs
= Fcons (Fcons (Qtime
,
3292 ltime_from_jiffies (s_time
+ u_time
,
3295 attrs
= Fcons (Fcons (Qcutime
,
3296 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3298 attrs
= Fcons (Fcons (Qcstime
,
3299 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3301 attrs
= Fcons (Fcons (Qctime
,
3302 ltime_from_jiffies (cstime
+ cutime
,
3305 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3306 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3307 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3309 tnow
= current_timespec ();
3310 telapsed
= get_up_time ();
3311 tboot
= timespec_sub (tnow
, telapsed
);
3312 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3313 tstart
= timespec_add (tboot
, tstart
);
3314 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3315 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3317 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3318 telapsed
= timespec_sub (tnow
, tstart
);
3319 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3320 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3321 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3324 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3325 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3328 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3331 unbind_to (count
, Qnil
);
3334 strcpy (procfn_end
, "/cmdline");
3335 fd
= emacs_open (fn
, O_RDONLY
, 0);
3338 ptrdiff_t readsize
, nread_incr
;
3339 record_unwind_protect_int (close_file_unwind
, fd
);
3340 record_unwind_protect_nothing ();
3341 nread
= cmdline_size
= 0;
3345 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3346 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3348 /* Leave room even if every byte needs escaping below. */
3349 readsize
= (cmdline_size
>> 1) - nread
;
3351 nread_incr
= emacs_read_quit (fd
, cmdline
+ nread
, readsize
);
3352 nread
+= max (0, nread_incr
);
3354 while (nread_incr
== readsize
);
3358 /* We don't want trailing null characters. */
3359 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3362 /* Escape-quote whitespace and backslashes. */
3363 q
= cmdline
+ cmdline_size
;
3368 if (c_isspace (c
) || c
== '\\')
3372 nread
= cmdline
+ cmdline_size
- q
;
3377 nread
= cmdsize
+ 2;
3378 cmdline_size
= nread
+ 1;
3379 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3380 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3381 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3383 /* Command line is encoded in locale-coding-system; decode it. */
3384 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3385 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3386 Vlocale_coding_system
, 0);
3387 unbind_to (count
, Qnil
);
3388 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3394 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3396 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3397 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3398 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3399 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3400 #undef _FILE_OFFSET_BITS
3402 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3407 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3408 #define _FILE_OFFSET_BITS 64
3409 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3411 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3414 system_process_attributes (Lisp_Object pid
)
3416 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3421 struct psinfo pinfo
;
3427 Lisp_Object attrs
= Qnil
;
3428 Lisp_Object decoded_cmd
;
3431 CHECK_NUMBER_OR_FLOAT (pid
);
3432 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3433 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3434 if (stat (procfn
, &st
) < 0)
3439 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3441 pw
= getpwuid (uid
);
3444 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3447 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3449 gr
= getgrgid (gid
);
3452 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3454 count
= SPECPDL_INDEX ();
3455 strcpy (fn
, procfn
);
3456 procfn_end
= fn
+ strlen (fn
);
3457 strcpy (procfn_end
, "/psinfo");
3458 fd
= emacs_open (fn
, O_RDONLY
, 0);
3463 record_unwind_protect_int (close_file_unwind
, fd
);
3464 nread
= emacs_read_quit (fd
, &pinfo
, sizeof pinfo
);
3467 if (nread
== sizeof pinfo
)
3469 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3470 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3471 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3475 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3476 state_str
[1] = '\0';
3477 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3480 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3481 need to get a string from it. */
3483 /* FIXME: missing: Qtpgid */
3495 Are they available? */
3497 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3498 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3499 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3500 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3501 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3504 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3505 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3507 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3510 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3511 range 0 .. 2**15, representing 0.0 .. 1.0. */
3512 attrs
= Fcons (Fcons (Qpcpu
,
3513 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3515 attrs
= Fcons (Fcons (Qpmem
,
3516 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3519 AUTO_STRING (fname
, pinfo
.pr_fname
);
3520 decoded_cmd
= code_convert_string_norecord (fname
,
3521 Vlocale_coding_system
, 0);
3522 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3523 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3524 decoded_cmd
= code_convert_string_norecord (psargs
,
3525 Vlocale_coding_system
, 0);
3526 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3528 unbind_to (count
, Qnil
);
3532 #elif defined __FreeBSD__
3534 static struct timespec
3535 timeval_to_timespec (struct timeval t
)
3537 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3541 make_lisp_timeval (struct timeval t
)
3543 return make_lisp_time (timeval_to_timespec (t
));
3547 system_process_attributes (Lisp_Object pid
)
3550 int pagesize
= getpagesize ();
3551 unsigned long npages
;
3557 char args
[MAXPATHLEN
];
3558 struct timespec t
, now
;
3560 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3561 struct kinfo_proc proc
;
3562 size_t proclen
= sizeof proc
;
3564 Lisp_Object attrs
= Qnil
;
3565 Lisp_Object decoded_comm
;
3567 CHECK_NUMBER_OR_FLOAT (pid
);
3568 CONS_TO_INTEGER (pid
, int, proc_id
);
3571 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3574 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3577 pw
= getpwuid (proc
.ki_uid
);
3580 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3582 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3585 gr
= getgrgid (proc
.ki_svgid
);
3588 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3590 AUTO_STRING (comm
, proc
.ki_comm
);
3591 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3593 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3595 char state
[2] = {'\0', '\0'};
3596 switch (proc
.ki_stat
)
3618 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3621 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3622 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3623 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3626 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3629 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3631 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3632 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3633 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3634 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3635 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3637 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3639 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3641 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3642 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3643 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3645 attrs
= Fcons (Fcons (Qcutime
,
3646 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3648 attrs
= Fcons (Fcons (Qcstime
,
3649 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3651 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3652 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3653 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3655 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3657 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3658 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3659 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3660 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3661 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3664 now
= current_timespec ();
3665 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3666 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3668 len
= sizeof fscale
;
3669 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3674 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3676 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3677 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3678 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3682 len
= sizeof npages
;
3683 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3685 double pmem
= (proc
.ki_flag
& P_INMEM
3686 ? 100.0 * proc
.ki_rssize
/ npages
3688 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3691 mib
[2] = KERN_PROC_ARGS
;
3693 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3696 for (i
= 0; i
< len
; i
++)
3698 if (! args
[i
] && i
< len
- 1)
3702 AUTO_STRING (comm
, args
);
3703 decoded_comm
= code_convert_string_norecord (comm
,
3704 Vlocale_coding_system
, 0);
3706 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3712 #elif defined DARWIN_OS
3714 static struct timespec
3715 timeval_to_timespec (struct timeval t
)
3717 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3721 make_lisp_timeval (struct timeval t
)
3723 return make_lisp_time (timeval_to_timespec (t
));
3727 system_process_attributes (Lisp_Object pid
)
3733 struct timeval starttime
;
3734 struct timespec t
, now
;
3735 struct rusage
*rusage
;
3740 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3741 struct kinfo_proc proc
;
3742 size_t proclen
= sizeof proc
;
3744 Lisp_Object attrs
= Qnil
;
3745 Lisp_Object decoded_comm
;
3747 CHECK_NUMBER_OR_FLOAT (pid
);
3748 CONS_TO_INTEGER (pid
, int, proc_id
);
3751 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3754 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3755 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3758 pw
= getpwuid (uid
);
3761 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3763 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3764 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3767 gr
= getgrgid (gid
);
3770 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3772 decoded_comm
= (code_convert_string_norecord
3773 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3774 Vlocale_coding_system
, 0));
3776 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3778 char state
[2] = {'\0', '\0'};
3779 switch (proc
.kp_proc
.p_stat
)
3801 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3804 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3806 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3809 tdev
= proc
.kp_eproc
.e_tdev
;
3811 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3814 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3816 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3819 rusage
= proc
.kp_proc
.p_ru
;
3822 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3824 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3827 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3829 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3831 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3832 timeval_to_timespec (rusage
->ru_stime
));
3833 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3836 starttime
= proc
.kp_proc
.p_starttime
;
3837 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3838 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3840 now
= current_timespec ();
3841 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3842 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3847 /* The WINDOWSNT implementation is in w32.c.
3848 The MSDOS implementation is in dosfns.c. */
3849 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3852 system_process_attributes (Lisp_Object pid
)
3857 #endif /* !defined (WINDOWSNT) */
3859 /* Wide character string collation. */
3861 #ifdef __STDC_ISO_10646__
3863 # include <wctype.h>
3865 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3866 # include <locale.h>
3869 # define LC_COLLATE 0
3871 # ifndef LC_COLLATE_MASK
3872 # define LC_COLLATE_MASK 0
3877 # ifndef LC_CTYPE_MASK
3878 # define LC_CTYPE_MASK 0
3881 # ifndef HAVE_NEWLOCALE
3887 # define freelocale emacs_freelocale
3888 # define locale_t emacs_locale_t
3889 # define newlocale emacs_newlocale
3890 # define wcscoll_l emacs_wcscoll_l
3891 # define towlower_l emacs_towlower_l
3893 typedef char const *locale_t
;
3896 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3902 freelocale (locale_t loc
)
3907 emacs_setlocale (int category
, char const *locale
)
3909 # ifdef HAVE_SETLOCALE
3911 char *loc
= setlocale (category
, locale
);
3922 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3925 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3933 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3934 strcpy (oldcopy
, oldloc
);
3935 if (! emacs_setlocale (LC_COLLATE
, loc
))
3940 result
= wcscoll (a
, b
);
3942 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3953 towlower_l (wint_t wc
, locale_t loc
)
3956 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3961 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3962 strcpy (oldcopy
, oldloc
);
3963 if (emacs_setlocale (LC_CTYPE
, loc
))
3965 result
= towlower (wc
);
3966 emacs_setlocale (LC_COLLATE
, oldcopy
);
3976 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3977 Lisp_Object locale
, Lisp_Object ignore_case
)
3980 ptrdiff_t len
, i
, i_byte
;
3985 /* Convert byte stream to code points. */
3986 len
= SCHARS (s1
); i
= i_byte
= 0;
3987 SAFE_NALLOCA (p1
, 1, len
+ 1);
3989 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3992 len
= SCHARS (s2
); i
= i_byte
= 0;
3993 SAFE_NALLOCA (p2
, 1, len
+ 1);
3995 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3998 if (STRINGP (locale
))
4000 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
4001 SSDATA (locale
), 0);
4003 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
4005 if (! NILP (ignore_case
))
4006 for (int i
= 1; i
< 3; i
++)
4008 wchar_t *p
= (i
== 1) ? p1
: p2
;
4010 *p
= towlower_l (*p
, loc
);
4014 res
= wcscoll_l (p1
, p2
, loc
);
4020 if (! NILP (ignore_case
))
4021 for (int i
= 1; i
< 3; i
++)
4023 wchar_t *p
= (i
== 1) ? p1
: p2
;
4029 res
= wcscoll (p1
, p2
);
4032 # ifndef HAVE_NEWLOCALE
4034 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
4037 error ("Invalid string for collation: %s", emacs_strerror (err
));
4043 #endif /* __STDC_ISO_10646__ */
4047 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4048 Lisp_Object locale
, Lisp_Object ignore_case
)
4051 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
4052 int res
, err
= errno
;
4055 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4057 error ("Invalid string for collation: %s", strerror (errno
));
4062 #endif /* WINDOWSNT */