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
)
2399 /* Open FILE as a stream for Emacs use, with mode MODE.
2400 Act like emacs_open with respect to threads, signals, and quits. */
2403 emacs_fopen (char const *file
, char const *mode
)
2405 int fd
, omode
, oflags
;
2407 char const *m
= mode
;
2411 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2412 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2413 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2414 default: emacs_abort ();
2420 case '+': omode
= O_RDWR
; break;
2421 case 't': bflag
= O_TEXT
; break;
2422 default: /* Ignore. */ break;
2425 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2426 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2429 /* Create a pipe for Emacs use. */
2432 emacs_pipe (int fd
[2])
2437 return pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2441 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2442 For the background behind this mess, please see Austin Group defect 529
2443 <http://austingroupbugs.net/view.php?id=529>. */
2445 #ifndef POSIX_CLOSE_RESTART
2446 # define POSIX_CLOSE_RESTART 1
2448 posix_close (int fd
, int flag
)
2450 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2451 eassert (flag
== POSIX_CLOSE_RESTART
);
2453 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2454 on a system that does not define POSIX_CLOSE_RESTART.
2456 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2457 closed, and retrying the close could inadvertently close a file
2458 descriptor allocated by some other thread. In other systems
2459 (e.g., HP/UX) FD is not closed. And in still other systems
2460 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2461 multithreaded program there can be no way to tell.
2463 So, in this case, pretend that the close succeeded. This works
2464 well on systems like GNU/Linux that close FD. Although it may
2465 leak a file descriptor on other systems, the leak is unlikely and
2466 it's better to leak than to close a random victim. */
2467 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2471 /* Close FD, retrying if interrupted. If successful, return 0;
2472 otherwise, return -1 and set errno to a non-EINTR value. Consider
2473 an EINPROGRESS error to be successful, as that's merely a signal
2474 arriving. FD is always closed when this function returns, even
2477 Do not call this function if FD is nonnegative and might already be closed,
2478 as that might close an innocent victim opened by some other thread. */
2481 emacs_close (int fd
)
2485 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2488 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2490 eassert (errno
!= EBADF
|| fd
< 0);
2491 return errno
== EINPROGRESS
? 0 : r
;
2496 /* Maximum number of bytes to read or write in a single system call.
2497 This works around a serious bug in Linux kernels before 2.6.16; see
2498 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2499 It's likely to work around similar bugs in other operating systems, so do it
2500 on all platforms. Round INT_MAX down to a page size, with the conservative
2501 assumption that page sizes are at most 2**18 bytes (any kernel with a
2502 page size larger than that shouldn't have the bug). */
2503 #ifndef MAX_RW_COUNT
2504 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2507 /* Read from FD to a buffer BUF with size NBYTE.
2508 If interrupted, process any quits and pending signals immediately
2509 if INTERRUPTIBLE, and then retry the read unless quitting.
2510 Return the number of bytes read, which might be less than NBYTE.
2511 On error, set errno to a value other than EINTR, and return -1. */
2513 emacs_intr_read (int fd
, void *buf
, ptrdiff_t nbyte
, bool interruptible
)
2517 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2518 passes a size that large to emacs_read. */
2523 result
= read (fd
, buf
, nbyte
);
2525 while (result
< 0 && errno
== EINTR
);
2530 /* Read from FD to a buffer BUF with size NBYTE.
2531 If interrupted, retry the read. Return the number of bytes read,
2532 which might be less than NBYTE. On error, set errno to a value
2533 other than EINTR, and return -1. */
2535 emacs_read (int fd
, void *buf
, ptrdiff_t nbyte
)
2537 return emacs_intr_read (fd
, buf
, nbyte
, false);
2540 /* Like emacs_read, but also process quits and pending signals. */
2542 emacs_read_quit (int fd
, void *buf
, ptrdiff_t nbyte
)
2544 return emacs_intr_read (fd
, buf
, nbyte
, true);
2547 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2548 interrupted or if a partial write occurs. Process any quits
2549 immediately if INTERRUPTIBLE is positive, and process any pending
2550 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2551 of bytes written; if this is less than NBYTE, set errno to a value
2552 other than EINTR. */
2554 emacs_full_write (int fd
, char const *buf
, ptrdiff_t nbyte
,
2557 ptrdiff_t bytes_written
= 0;
2561 ssize_t n
= write (fd
, buf
, min (nbyte
, MAX_RW_COUNT
));
2570 if (0 < interruptible
)
2572 if (pending_signals
)
2573 process_pending_signals ();
2584 return bytes_written
;
2587 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2588 interrupted or if a partial write occurs. Do not process quits or
2589 pending signals. Return the number of bytes written, setting errno
2590 if this is less than NBYTE. */
2592 emacs_write (int fd
, void const *buf
, ptrdiff_t nbyte
)
2594 return emacs_full_write (fd
, buf
, nbyte
, 0);
2597 /* Like emacs_write, but also process pending signals. */
2599 emacs_write_sig (int fd
, void const *buf
, ptrdiff_t nbyte
)
2601 return emacs_full_write (fd
, buf
, nbyte
, -1);
2604 /* Like emacs_write, but also process quits and pending signals. */
2606 emacs_write_quit (int fd
, void const *buf
, ptrdiff_t nbyte
)
2608 return emacs_full_write (fd
, buf
, nbyte
, 1);
2611 /* Write a diagnostic to standard error that contains MESSAGE and a
2612 string derived from errno. Preserve errno. Do not buffer stderr.
2613 Do not process quits or pending signals if interrupted. */
2615 emacs_perror (char const *message
)
2618 char const *error_string
= emacs_strerror (err
);
2619 char const *command
= (initial_argv
&& initial_argv
[0]
2620 ? initial_argv
[0] : "emacs");
2621 /* Write it out all at once, if it's short; this is less likely to
2622 be interleaved with other output. */
2624 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2625 command
, message
, error_string
);
2626 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2627 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2630 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2631 emacs_write (STDERR_FILENO
, ": ", 2);
2632 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2633 emacs_write (STDERR_FILENO
, ": ", 2);
2634 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2635 emacs_write (STDERR_FILENO
, "\n", 1);
2640 /* Return a struct timeval that is roughly equivalent to T.
2641 Use the least timeval not less than T.
2642 Return an extremal value if the result would overflow. */
2644 make_timeval (struct timespec t
)
2647 tv
.tv_sec
= t
.tv_sec
;
2648 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2650 if (t
.tv_nsec
% 1000 != 0)
2652 if (tv
.tv_usec
< 999999)
2654 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2664 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2665 ATIME and MTIME, respectively.
2666 FD must be either negative -- in which case it is ignored --
2667 or a file descriptor that is open on FILE.
2668 If FD is nonnegative, then FILE can be NULL. */
2670 set_file_times (int fd
, const char *filename
,
2671 struct timespec atime
, struct timespec mtime
)
2673 struct timespec timespec
[2];
2674 timespec
[0] = atime
;
2675 timespec
[1] = mtime
;
2676 return fdutimens (fd
, filename
, timespec
);
2679 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2680 This is like renameat except that it fails if DST already exists,
2681 or if this operation is not supported atomically. Return 0 if
2682 successful, -1 (setting errno) otherwise. */
2684 renameat_noreplace (int srcfd
, char const *src
, int dstfd
, char const *dst
)
2686 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2687 return syscall (SYS_renameat2
, srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2688 #elif defined RENAME_EXCL
2689 return renameatx_np (srcfd
, src
, dstfd
, dst
, RENAME_EXCL
);
2692 if (srcfd
== AT_FDCWD
&& dstfd
== AT_FDCWD
)
2693 return sys_rename_replace (src
, dst
, 0);
2700 /* Like strsignal, except async-signal-safe, and this function typically
2701 returns a string in the C locale rather than the current locale. */
2703 safe_strsignal (int code
)
2705 char const *signame
= 0;
2707 if (0 <= code
&& code
< sys_siglist_entries
)
2708 signame
= sys_siglist
[code
];
2710 signame
= "Unknown signal";
2716 /* For make-serial-process */
2718 serial_open (Lisp_Object port
)
2720 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2722 report_file_error ("Opening serial port", port
);
2724 ioctl (fd
, TIOCEXCL
, (char *) 0);
2730 #if !defined (HAVE_CFMAKERAW)
2731 /* Workaround for targets which are missing cfmakeraw. */
2732 /* Pasted from man page. */
2734 cfmakeraw (struct termios
*termios_p
)
2736 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2737 termios_p
->c_oflag
&= ~OPOST
;
2738 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2739 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2740 termios_p
->c_cflag
|= CS8
;
2742 #endif /* !defined (HAVE_CFMAKERAW */
2744 #if !defined (HAVE_CFSETSPEED)
2745 /* Workaround for targets which are missing cfsetspeed. */
2747 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2749 return (cfsetispeed (termios_p
, vitesse
)
2750 + cfsetospeed (termios_p
, vitesse
));
2754 /* For serial-process-configure */
2756 serial_configure (struct Lisp_Process
*p
,
2757 Lisp_Object contact
)
2759 Lisp_Object childp2
= Qnil
;
2760 Lisp_Object tem
= Qnil
;
2761 struct termios attr
;
2763 char summary
[4] = "???"; /* This usually becomes "8N1". */
2765 childp2
= Fcopy_sequence (p
->childp
);
2767 /* Read port attributes and prepare default configuration. */
2768 err
= tcgetattr (p
->outfd
, &attr
);
2770 report_file_error ("Failed tcgetattr", Qnil
);
2772 #if defined (CLOCAL)
2773 attr
.c_cflag
|= CLOCAL
;
2776 attr
.c_cflag
|= CREAD
;
2779 /* Configure speed. */
2780 if (!NILP (Fplist_member (contact
, QCspeed
)))
2781 tem
= Fplist_get (contact
, QCspeed
);
2783 tem
= Fplist_get (p
->childp
, QCspeed
);
2785 err
= cfsetspeed (&attr
, XINT (tem
));
2787 report_file_error ("Failed cfsetspeed", tem
);
2788 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2790 /* Configure bytesize. */
2791 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2792 tem
= Fplist_get (contact
, QCbytesize
);
2794 tem
= Fplist_get (p
->childp
, QCbytesize
);
2796 tem
= make_number (8);
2798 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2799 error (":bytesize must be nil (8), 7, or 8");
2800 summary
[0] = XINT (tem
) + '0';
2801 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2802 attr
.c_cflag
&= ~CSIZE
;
2803 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2805 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2806 if (XINT (tem
) != 8)
2807 error ("Bytesize cannot be changed");
2809 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2811 /* Configure parity. */
2812 if (!NILP (Fplist_member (contact
, QCparity
)))
2813 tem
= Fplist_get (contact
, QCparity
);
2815 tem
= Fplist_get (p
->childp
, QCparity
);
2816 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2817 error (":parity must be nil (no parity), `even', or `odd'");
2818 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2819 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2820 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2825 else if (EQ (tem
, Qeven
))
2828 attr
.c_cflag
|= PARENB
;
2829 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2831 else if (EQ (tem
, Qodd
))
2834 attr
.c_cflag
|= (PARENB
| PARODD
);
2835 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2838 /* Don't error on no parity, which should be set by cfmakeraw. */
2840 error ("Parity cannot be configured");
2842 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2844 /* Configure stopbits. */
2845 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2846 tem
= Fplist_get (contact
, QCstopbits
);
2848 tem
= Fplist_get (p
->childp
, QCstopbits
);
2850 tem
= make_number (1);
2852 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2853 error (":stopbits must be nil (1 stopbit), 1, or 2");
2854 summary
[2] = XINT (tem
) + '0';
2855 #if defined (CSTOPB)
2856 attr
.c_cflag
&= ~CSTOPB
;
2857 if (XINT (tem
) == 2)
2858 attr
.c_cflag
|= CSTOPB
;
2860 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2861 if (XINT (tem
) != 1)
2862 error ("Stopbits cannot be configured");
2864 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2866 /* Configure flowcontrol. */
2867 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2868 tem
= Fplist_get (contact
, QCflowcontrol
);
2870 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2871 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2872 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2873 #if defined (CRTSCTS)
2874 attr
.c_cflag
&= ~CRTSCTS
;
2876 #if defined (CNEW_RTSCTS)
2877 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2879 #if defined (IXON) && defined (IXOFF)
2880 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2884 /* Already configured. */
2886 else if (EQ (tem
, Qhw
))
2888 #if defined (CRTSCTS)
2889 attr
.c_cflag
|= CRTSCTS
;
2890 #elif defined (CNEW_RTSCTS)
2891 attr
.c_cflag
|= CNEW_RTSCTS
;
2893 error ("Hardware flowcontrol (RTS/CTS) not supported");
2896 else if (EQ (tem
, Qsw
))
2898 #if defined (IXON) && defined (IXOFF)
2899 attr
.c_iflag
|= (IXON
| IXOFF
);
2901 error ("Software flowcontrol (XON/XOFF) not supported");
2904 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2906 /* Activate configuration. */
2907 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2909 report_file_error ("Failed tcsetattr", Qnil
);
2911 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2912 pset_childp (p
, childp2
);
2914 #endif /* not DOS_NT */
2916 /* System depended enumeration of and access to system processes a-la ps(1). */
2920 /* Process enumeration and access via /proc. */
2923 list_system_processes (void)
2925 Lisp_Object procdir
, match
, proclist
, next
;
2928 /* For every process on the system, there's a directory in the
2929 "/proc" pseudo-directory whose name is the numeric ID of that
2931 procdir
= build_string ("/proc");
2932 match
= build_string ("[0-9]+");
2933 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, false, Qnil
);
2935 /* `proclist' gives process IDs as strings. Destructively convert
2936 each string into a number. */
2937 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2940 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2943 /* directory_files_internal returns the files in reverse order; undo
2945 proclist
= Fnreverse (proclist
);
2949 #elif defined DARWIN_OS || defined __FreeBSD__
2952 list_system_processes (void)
2955 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2957 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2960 struct kinfo_proc
*procs
;
2963 Lisp_Object proclist
= Qnil
;
2965 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2968 procs
= xmalloc (len
);
2969 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2975 len
/= sizeof (struct kinfo_proc
);
2976 for (i
= 0; i
< len
; i
++)
2979 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2981 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2990 /* The WINDOWSNT implementation is in w32.c.
2991 The MSDOS implementation is in dosfns.c. */
2992 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2995 list_system_processes (void)
3000 #endif /* !defined (WINDOWSNT) */
3002 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3003 static struct timespec
3004 time_from_jiffies (unsigned long long tval
, long hz
)
3006 unsigned long long s
= tval
/ hz
;
3007 unsigned long long frac
= tval
% hz
;
3010 if (TYPE_MAXIMUM (time_t) < s
)
3012 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
3013 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
3014 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
3017 /* This is reachable only in the unlikely case that HZ * HZ
3018 exceeds ULLONG_MAX. It calculates an approximation that is
3019 guaranteed to be in range. */
3020 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
3021 + (hz
% TIMESPEC_RESOLUTION
!= 0));
3022 ns
= frac
/ hz_per_ns
;
3025 return make_timespec (s
, ns
);
3029 ltime_from_jiffies (unsigned long long tval
, long hz
)
3031 struct timespec t
= time_from_jiffies (tval
, hz
);
3032 return make_lisp_time (t
);
3035 static struct timespec
3039 struct timespec up
= make_timespec (0, 0);
3042 fup
= emacs_fopen ("/proc/uptime", "r");
3046 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
3047 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
3049 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
3050 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
3051 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
3054 if (TYPE_MAXIMUM (time_t) < upsec
)
3056 upsec
= TYPE_MAXIMUM (time_t);
3057 upfrac
= TIMESPEC_RESOLUTION
- 1;
3061 int upfraclen
= upfrac_end
- upfrac_start
;
3062 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3064 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3066 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3068 up
= make_timespec (upsec
, upfrac
);
3077 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3078 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3081 procfs_ttyname (int rdev
)
3084 char name
[PATH_MAX
];
3087 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3093 unsigned long minor_beg
, minor_end
;
3094 char minor
[25]; /* 2 32-bit numbers + dash */
3097 for (; !feof_unlocked (fdev
) && !ferror_unlocked (fdev
); name
[0] = 0)
3099 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3100 && major
== MAJOR (rdev
))
3102 minor_beg
= strtoul (minor
, &endp
, 0);
3104 minor_end
= minor_beg
;
3105 else if (*endp
== '-')
3106 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3110 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3112 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3120 return build_string (name
);
3124 procfs_get_total_memory (void)
3127 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3131 fmem
= emacs_fopen ("/proc/meminfo", "r");
3135 uintmax_t entry_value
;
3139 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3142 retval
= entry_value
;
3147 while ((c
= getc_unlocked (fmem
)) != EOF
&& c
!= '\n')
3165 system_process_attributes (Lisp_Object pid
)
3167 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3171 long clocks_per_sec
;
3173 char procbuf
[1025], *p
, *q
;
3176 static char const default_cmd
[] = "???";
3177 const char *cmd
= default_cmd
;
3178 int cmdsize
= sizeof default_cmd
- 1;
3179 char *cmdline
= NULL
;
3180 ptrdiff_t cmdline_size
;
3183 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3186 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3187 long priority
, niceness
, rss
;
3188 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3189 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3191 Lisp_Object attrs
= Qnil
;
3192 Lisp_Object decoded_cmd
;
3195 CHECK_NUMBER_OR_FLOAT (pid
);
3196 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3197 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3198 if (stat (procfn
, &st
) < 0)
3203 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3205 pw
= getpwuid (uid
);
3208 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3211 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3213 gr
= getgrgid (gid
);
3216 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3218 count
= SPECPDL_INDEX ();
3219 strcpy (fn
, procfn
);
3220 procfn_end
= fn
+ strlen (fn
);
3221 strcpy (procfn_end
, "/stat");
3222 fd
= emacs_open (fn
, O_RDONLY
, 0);
3227 record_unwind_protect_int (close_file_unwind
, fd
);
3228 nread
= emacs_read_quit (fd
, procbuf
, sizeof procbuf
- 1);
3232 procbuf
[nread
] = '\0';
3235 p
= strchr (p
, '(');
3238 q
= strrchr (p
+ 1, ')');
3248 /* Command name is encoded in locale-coding-system; decode it. */
3249 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3250 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3251 Vlocale_coding_system
, 0);
3252 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3254 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3255 utime stime cutime cstime priority nice thcount . start vsize rss */
3257 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3258 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3259 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3260 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3261 &u_time
, &s_time
, &cutime
, &cstime
,
3262 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3267 state_str
[1] = '\0';
3268 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3269 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3270 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3271 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3272 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3273 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3274 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3275 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3276 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3278 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3280 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3281 if (clocks_per_sec
< 0)
3282 clocks_per_sec
= 100;
3283 attrs
= Fcons (Fcons (Qutime
,
3284 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3286 attrs
= Fcons (Fcons (Qstime
,
3287 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3289 attrs
= Fcons (Fcons (Qtime
,
3290 ltime_from_jiffies (s_time
+ u_time
,
3293 attrs
= Fcons (Fcons (Qcutime
,
3294 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3296 attrs
= Fcons (Fcons (Qcstime
,
3297 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3299 attrs
= Fcons (Fcons (Qctime
,
3300 ltime_from_jiffies (cstime
+ cutime
,
3303 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3304 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3305 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3307 tnow
= current_timespec ();
3308 telapsed
= get_up_time ();
3309 tboot
= timespec_sub (tnow
, telapsed
);
3310 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3311 tstart
= timespec_add (tboot
, tstart
);
3312 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3313 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3315 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3316 telapsed
= timespec_sub (tnow
, tstart
);
3317 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3318 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3319 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3322 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3323 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3326 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3329 unbind_to (count
, Qnil
);
3332 strcpy (procfn_end
, "/cmdline");
3333 fd
= emacs_open (fn
, O_RDONLY
, 0);
3336 ptrdiff_t readsize
, nread_incr
;
3337 record_unwind_protect_int (close_file_unwind
, fd
);
3338 record_unwind_protect_nothing ();
3339 nread
= cmdline_size
= 0;
3343 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3344 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3346 /* Leave room even if every byte needs escaping below. */
3347 readsize
= (cmdline_size
>> 1) - nread
;
3349 nread_incr
= emacs_read_quit (fd
, cmdline
+ nread
, readsize
);
3350 nread
+= max (0, nread_incr
);
3352 while (nread_incr
== readsize
);
3356 /* We don't want trailing null characters. */
3357 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3360 /* Escape-quote whitespace and backslashes. */
3361 q
= cmdline
+ cmdline_size
;
3366 if (c_isspace (c
) || c
== '\\')
3370 nread
= cmdline
+ cmdline_size
- q
;
3375 nread
= cmdsize
+ 2;
3376 cmdline_size
= nread
+ 1;
3377 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3378 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3379 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3381 /* Command line is encoded in locale-coding-system; decode it. */
3382 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3383 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3384 Vlocale_coding_system
, 0);
3385 unbind_to (count
, Qnil
);
3386 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3392 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3394 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3395 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3396 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3397 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3398 #undef _FILE_OFFSET_BITS
3400 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3405 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3406 #define _FILE_OFFSET_BITS 64
3407 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3409 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3412 system_process_attributes (Lisp_Object pid
)
3414 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3419 struct psinfo pinfo
;
3425 Lisp_Object attrs
= Qnil
;
3426 Lisp_Object decoded_cmd
;
3429 CHECK_NUMBER_OR_FLOAT (pid
);
3430 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3431 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3432 if (stat (procfn
, &st
) < 0)
3437 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3439 pw
= getpwuid (uid
);
3442 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3445 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3447 gr
= getgrgid (gid
);
3450 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3452 count
= SPECPDL_INDEX ();
3453 strcpy (fn
, procfn
);
3454 procfn_end
= fn
+ strlen (fn
);
3455 strcpy (procfn_end
, "/psinfo");
3456 fd
= emacs_open (fn
, O_RDONLY
, 0);
3461 record_unwind_protect_int (close_file_unwind
, fd
);
3462 nread
= emacs_read_quit (fd
, &pinfo
, sizeof pinfo
);
3465 if (nread
== sizeof pinfo
)
3467 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3468 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3469 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3473 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3474 state_str
[1] = '\0';
3475 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3478 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3479 need to get a string from it. */
3481 /* FIXME: missing: Qtpgid */
3493 Are they available? */
3495 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3496 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3497 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3498 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3499 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3502 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3503 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3505 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3508 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3509 range 0 .. 2**15, representing 0.0 .. 1.0. */
3510 attrs
= Fcons (Fcons (Qpcpu
,
3511 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3513 attrs
= Fcons (Fcons (Qpmem
,
3514 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3517 AUTO_STRING (fname
, pinfo
.pr_fname
);
3518 decoded_cmd
= code_convert_string_norecord (fname
,
3519 Vlocale_coding_system
, 0);
3520 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3521 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3522 decoded_cmd
= code_convert_string_norecord (psargs
,
3523 Vlocale_coding_system
, 0);
3524 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3526 unbind_to (count
, Qnil
);
3530 #elif defined __FreeBSD__
3532 static struct timespec
3533 timeval_to_timespec (struct timeval t
)
3535 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3539 make_lisp_timeval (struct timeval t
)
3541 return make_lisp_time (timeval_to_timespec (t
));
3545 system_process_attributes (Lisp_Object pid
)
3548 int pagesize
= getpagesize ();
3549 unsigned long npages
;
3555 char args
[MAXPATHLEN
];
3556 struct timespec t
, now
;
3558 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3559 struct kinfo_proc proc
;
3560 size_t proclen
= sizeof proc
;
3562 Lisp_Object attrs
= Qnil
;
3563 Lisp_Object decoded_comm
;
3565 CHECK_NUMBER_OR_FLOAT (pid
);
3566 CONS_TO_INTEGER (pid
, int, proc_id
);
3569 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3572 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3575 pw
= getpwuid (proc
.ki_uid
);
3578 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3580 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3583 gr
= getgrgid (proc
.ki_svgid
);
3586 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3588 AUTO_STRING (comm
, proc
.ki_comm
);
3589 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3591 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3593 char state
[2] = {'\0', '\0'};
3594 switch (proc
.ki_stat
)
3616 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3619 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3620 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3621 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3624 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3627 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3629 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3630 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3631 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3632 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3633 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3635 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3637 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3639 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3640 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3641 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3643 attrs
= Fcons (Fcons (Qcutime
,
3644 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3646 attrs
= Fcons (Fcons (Qcstime
,
3647 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3649 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3650 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3651 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3653 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3655 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3656 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3657 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3658 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3659 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3662 now
= current_timespec ();
3663 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3664 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3666 len
= sizeof fscale
;
3667 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3672 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3674 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3675 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3676 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3680 len
= sizeof npages
;
3681 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3683 double pmem
= (proc
.ki_flag
& P_INMEM
3684 ? 100.0 * proc
.ki_rssize
/ npages
3686 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3689 mib
[2] = KERN_PROC_ARGS
;
3691 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3694 for (i
= 0; i
< len
; i
++)
3696 if (! args
[i
] && i
< len
- 1)
3700 AUTO_STRING (comm
, args
);
3701 decoded_comm
= code_convert_string_norecord (comm
,
3702 Vlocale_coding_system
, 0);
3704 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3710 #elif defined DARWIN_OS
3712 static struct timespec
3713 timeval_to_timespec (struct timeval t
)
3715 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3719 make_lisp_timeval (struct timeval t
)
3721 return make_lisp_time (timeval_to_timespec (t
));
3725 system_process_attributes (Lisp_Object pid
)
3731 struct timeval starttime
;
3732 struct timespec t
, now
;
3733 struct rusage
*rusage
;
3738 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3739 struct kinfo_proc proc
;
3740 size_t proclen
= sizeof proc
;
3742 Lisp_Object attrs
= Qnil
;
3743 Lisp_Object decoded_comm
;
3745 CHECK_NUMBER_OR_FLOAT (pid
);
3746 CONS_TO_INTEGER (pid
, int, proc_id
);
3749 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3752 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3753 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3756 pw
= getpwuid (uid
);
3759 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3761 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3762 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3765 gr
= getgrgid (gid
);
3768 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3770 decoded_comm
= (code_convert_string_norecord
3771 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3772 Vlocale_coding_system
, 0));
3774 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3776 char state
[2] = {'\0', '\0'};
3777 switch (proc
.kp_proc
.p_stat
)
3799 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3802 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3804 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3807 tdev
= proc
.kp_eproc
.e_tdev
;
3809 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3812 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3814 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3817 rusage
= proc
.kp_proc
.p_ru
;
3820 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3822 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3825 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3827 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3829 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3830 timeval_to_timespec (rusage
->ru_stime
));
3831 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3834 starttime
= proc
.kp_proc
.p_starttime
;
3835 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3836 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3838 now
= current_timespec ();
3839 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3840 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3845 /* The WINDOWSNT implementation is in w32.c.
3846 The MSDOS implementation is in dosfns.c. */
3847 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3850 system_process_attributes (Lisp_Object pid
)
3855 #endif /* !defined (WINDOWSNT) */
3857 /* Wide character string collation. */
3859 #ifdef __STDC_ISO_10646__
3861 # include <wctype.h>
3863 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3864 # include <locale.h>
3867 # define LC_COLLATE 0
3869 # ifndef LC_COLLATE_MASK
3870 # define LC_COLLATE_MASK 0
3875 # ifndef LC_CTYPE_MASK
3876 # define LC_CTYPE_MASK 0
3879 # ifndef HAVE_NEWLOCALE
3885 # define freelocale emacs_freelocale
3886 # define locale_t emacs_locale_t
3887 # define newlocale emacs_newlocale
3888 # define wcscoll_l emacs_wcscoll_l
3889 # define towlower_l emacs_towlower_l
3891 typedef char const *locale_t
;
3894 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3900 freelocale (locale_t loc
)
3905 emacs_setlocale (int category
, char const *locale
)
3907 # ifdef HAVE_SETLOCALE
3909 char *loc
= setlocale (category
, locale
);
3920 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3923 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3931 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3932 strcpy (oldcopy
, oldloc
);
3933 if (! emacs_setlocale (LC_COLLATE
, loc
))
3938 result
= wcscoll (a
, b
);
3940 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3951 towlower_l (wint_t wc
, locale_t loc
)
3954 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3959 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3960 strcpy (oldcopy
, oldloc
);
3961 if (emacs_setlocale (LC_CTYPE
, loc
))
3963 result
= towlower (wc
);
3964 emacs_setlocale (LC_COLLATE
, oldcopy
);
3974 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3975 Lisp_Object locale
, Lisp_Object ignore_case
)
3978 ptrdiff_t len
, i
, i_byte
;
3983 /* Convert byte stream to code points. */
3984 len
= SCHARS (s1
); i
= i_byte
= 0;
3985 SAFE_NALLOCA (p1
, 1, len
+ 1);
3987 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3990 len
= SCHARS (s2
); i
= i_byte
= 0;
3991 SAFE_NALLOCA (p2
, 1, len
+ 1);
3993 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3996 if (STRINGP (locale
))
3998 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3999 SSDATA (locale
), 0);
4001 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
4003 if (! NILP (ignore_case
))
4004 for (int i
= 1; i
< 3; i
++)
4006 wchar_t *p
= (i
== 1) ? p1
: p2
;
4008 *p
= towlower_l (*p
, loc
);
4012 res
= wcscoll_l (p1
, p2
, loc
);
4018 if (! NILP (ignore_case
))
4019 for (int i
= 1; i
< 3; i
++)
4021 wchar_t *p
= (i
== 1) ? p1
: p2
;
4027 res
= wcscoll (p1
, p2
);
4030 # ifndef HAVE_NEWLOCALE
4032 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
4035 error ("Invalid string for collation: %s", emacs_strerror (err
));
4041 #endif /* __STDC_ISO_10646__ */
4045 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4046 Lisp_Object locale
, Lisp_Object ignore_case
)
4049 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
4050 int res
, err
= errno
;
4053 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4055 error ("Invalid string for collation: %s", strerror (errno
));
4060 #endif /* WINDOWSNT */