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>
46 # include <cygwin/fs.h>
49 #if defined DARWIN_OS || defined __FreeBSD__
50 # include <sys/sysctl.h>
54 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
55 'struct frame', so rename it. */
56 # define frame freebsd_frame
57 # include <sys/user.h>
64 #include <sys/socket.h>
66 #endif /* HAVE_SOCKETS */
70 #define write sys_write
72 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
75 #endif /* WINDOWSNT */
77 #include <sys/types.h>
81 /* Get SI_SRPC_DOMAIN, if it is available. */
82 #ifdef HAVE_SYS_SYSTEMINFO_H
83 #include <sys/systeminfo.h>
86 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
90 #include <sys/param.h>
97 #ifdef HAVE_SYS_UTSNAME_H
98 #include <sys/utsname.h>
100 #endif /* HAVE_SYS_UTSNAME_H */
102 #include "keyboard.h"
104 #include "termhooks.h"
105 #include "termchar.h"
106 #include "termopts.h"
111 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
112 do that during startup just to call gnutls_rnd. */
113 #if defined HAVE_GNUTLS && !defined WINDOWSNT
114 # include <gnutls/crypto.h>
116 # define emacs_gnutls_global_init() Qnil
117 # define gnutls_rnd(level, data, len) (-1)
122 /* In process.h which conflicts with the local copy. */
124 int _cdecl
_spawnlp (int, const char *, const char *, ...);
125 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
126 several prototypes of functions called below. */
127 #include <sys/socket.h>
130 #include "syssignal.h"
133 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
135 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
138 /* Declare here, including term.h is problematic on some systems. */
139 extern void tputs (const char *, int, int (*)(int));
141 static const int baud_convert
[] =
143 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
144 1800, 2400, 4800, 9600, 19200, 38400
147 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
148 # include <sys/personality.h>
150 /* Disable address randomization in the current process. Return true
151 if addresses were randomized but this has been disabled, false
154 disable_address_randomization (void)
156 int pers
= personality (0xffffffff);
159 int desired_pers
= pers
| ADDR_NO_RANDOMIZE
;
161 /* Call 'personality' twice, to detect buggy platforms like WSL
162 where 'personality' always returns 0. */
163 return (pers
!= desired_pers
164 && personality (desired_pers
) == pers
165 && personality (0xffffffff) == desired_pers
);
169 /* Execute the program in FILE, with argument vector ARGV and environ
170 ENVP. Return an error number if unsuccessful. This is like execve
171 except it reenables ASLR in the executed program if necessary, and
172 on error it returns an error number rather than -1. */
174 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
176 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
177 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
178 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
179 if (change_personality
)
180 personality (pers
& ~ADDR_NO_RANDOMIZE
);
183 execve (file
, argv
, envp
);
186 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
187 if (change_personality
)
194 /* If FD is not already open, arrange for it to be open with FLAGS. */
196 force_open (int fd
, int flags
)
198 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
200 int n
= open (NULL_DEVICE
, flags
);
201 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
203 emacs_perror (NULL_DEVICE
);
209 /* Make sure stdin, stdout, and stderr are open to something, so that
210 their file descriptors are not hijacked by later system calls. */
212 init_standard_fds (void)
214 /* Open stdin for *writing*, and stdout and stderr for *reading*.
215 That way, any attempt to do normal I/O will result in an error,
216 just as if the files were closed, and the file descriptors will
217 not be reused by later opens. */
218 force_open (STDIN_FILENO
, O_WRONLY
);
219 force_open (STDOUT_FILENO
, O_RDONLY
);
220 force_open (STDERR_FILENO
, O_RDONLY
);
223 /* Return the current working directory. The result should be freed
224 with 'free'. Return NULL on errors. */
226 emacs_get_current_dir_name (void)
228 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
229 # ifdef HYBRID_MALLOC
230 bool use_libc
= bss_sbrk_did_unexec
;
232 bool use_libc
= true;
235 return get_current_dir_name ();
239 char *pwd
= getenv ("PWD");
240 struct stat dotstat
, pwdstat
;
241 /* If PWD is accurate, use it instead of calling getcwd. PWD is
242 sometimes a nicer name, and using it may avoid a fatal error if a
243 parent directory is searchable but not readable. */
245 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
246 && stat (pwd
, &pwdstat
) == 0
247 && stat (".", &dotstat
) == 0
248 && dotstat
.st_ino
== pwdstat
.st_ino
249 && dotstat
.st_dev
== pwdstat
.st_dev
251 && strlen (pwd
) < MAXPATHLEN
255 buf
= malloc (strlen (pwd
) + 1);
262 size_t buf_size
= 1024;
263 buf
= malloc (buf_size
);
268 if (getcwd (buf
, buf_size
) == buf
)
272 int tmp_errno
= errno
;
278 buf
= realloc (buf
, buf_size
);
287 /* Discard pending input on all input descriptors. */
290 discard_tty_input (void)
293 struct emacs_tty buf
;
298 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
299 while (dos_keyread () != -1)
301 #else /* not MSDOS */
303 struct tty_display_info
*tty
;
304 for (tty
= tty_list
; tty
; tty
= tty
->next
)
306 if (tty
->input
) /* Is the device suspended? */
308 emacs_get_tty (fileno (tty
->input
), &buf
);
309 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
313 #endif /* not MSDOS */
314 #endif /* not WINDOWSNT */
320 /* Arrange for character C to be read as the next input from
322 XXX What if we have multiple ttys?
328 if (! (FRAMEP (selected_frame
)
329 && FRAME_LIVE_P (XFRAME (selected_frame
))
330 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
333 /* Should perhaps error if in batch mode */
335 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
336 #else /* no TIOCSTI */
337 error ("Cannot stuff terminal input characters in this version of Unix");
338 #endif /* no TIOCSTI */
344 init_baud_rate (int fd
)
354 #else /* not DOS_NT */
359 emacs_ospeed
= cfgetospeed (&sg
);
360 #endif /* not DOS_NT */
363 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
364 ? baud_convert
[emacs_ospeed
] : 9600);
373 /* Wait for the subprocess with process id CHILD to terminate or change status.
374 CHILD must be a child process that has not been reaped.
375 If STATUS is non-null, store the waitpid-style exit status into *STATUS
376 and tell wait_reading_process_output that it needs to look around.
377 Use waitpid-style OPTIONS when waiting.
378 If INTERRUPTIBLE, this function is interruptible by a signal.
380 Return CHILD if successful, 0 if no status is available, and a
381 negative value (setting errno) if waitpid is buggy. */
383 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
387 /* Invoke waitpid only with a known process ID; do not invoke
388 waitpid with a nonpositive argument. Otherwise, Emacs might
389 reap an unwanted process by mistake. For example, invoking
390 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
391 so that another thread running glib won't find them. */
396 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
401 pid
= waitpid (child
, status
, options
);
406 /* Most likely, waitpid is buggy and the operating system
407 lost track of the child somehow. Return -1 and let the
408 caller try to figure things out. Possibly the bug could
409 cause Emacs to kill the wrong process. Oh well. */
414 /* If successful and status is requested, tell wait_reading_process_output
415 that it needs to wake up and look around. */
416 if (pid
&& status
&& input_available_clear_time
)
417 *input_available_clear_time
= make_timespec (0, 0);
422 /* Wait for the subprocess with process id CHILD to terminate.
423 CHILD must be a child process that has not been reaped.
424 If STATUS is non-null, store the waitpid-style exit status into *STATUS
425 and tell wait_reading_process_output that it needs to look around.
426 If INTERRUPTIBLE, this function is interruptible by a signal.
427 Return true if successful, false (setting errno) if CHILD cannot be
428 waited for because waitpid is buggy. */
430 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
432 return 0 <= get_child_status (child
, status
, 0, interruptible
);
435 /* Report whether the subprocess with process id CHILD has changed status.
436 Termination counts as a change of status.
437 CHILD must be a child process that has not been reaped.
438 If STATUS is non-null, store the waitpid-style exit status into *STATUS
439 and tell wait_reading_process_output that it needs to look around.
440 Use waitpid-style OPTIONS to check status, but do not wait.
442 Return CHILD if successful, 0 if no status is available because
443 the process's state has not changed. */
445 child_status_changed (pid_t child
, int *status
, int options
)
447 return get_child_status (child
, status
, WNOHANG
| options
, 0);
451 /* Set up the terminal at the other end of a pseudo-terminal that
452 we will be controlling an inferior through.
453 It should not echo or do line-editing, since that is done
454 in Emacs. No padding needed for insertion into an Emacs buffer. */
457 child_setup_tty (int out
)
462 emacs_get_tty (out
, &s
);
463 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
464 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
466 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
467 Some versions of GNU Hurd do not have FFDLY? */
469 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
470 /* No output delays */
472 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
473 /* No output delays */
476 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
477 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
479 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
482 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
485 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
487 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
488 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
489 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
490 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
493 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
496 #ifdef SIGNALS_VIA_CHARACTERS
497 /* the QUIT and INTR character are used in process_send_signal
498 so set them here to something useful. */
499 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
500 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
501 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
502 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
503 #endif /* not SIGNALS_VIA_CHARACTERS */
506 /* Also, PTY overloads NUL and BREAK.
507 don't ignore break, but don't signal either, so it looks like NUL. */
508 s
.main
.c_iflag
&= ~IGNBRK
;
509 s
.main
.c_iflag
&= ~BRKINT
;
510 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
511 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
512 would force it to 0377. That looks like duplicated code. */
513 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
516 /* We originally enabled ICANON (and set VEOF to 04), and then had
517 process.c send additional EOF chars to flush the output when faced
518 with long lines, but this leads to weird effects when the
519 subprocess has disabled ICANON and ends up seeing those spurious
520 extra EOFs. So we don't send EOFs any more in
521 process.c:send_process. First we tried to disable ICANON by
522 default, so if a subsprocess sets up ICANON, it's his problem (or
523 the Elisp package that talks to it) to deal with lines that are
524 too long. But this disables some features, such as the ability
525 to send EOF signals. So we re-enabled ICANON but there is no
526 more "send eof to flush" going on (which is wrong and unportable
527 in itself). The correct way to handle too much output is to
528 buffer what could not be written and then write it again when
529 select returns ok for writing. This has it own set of
530 problems. Write is now asynchronous, is that a problem? How much
531 do we buffer, and what do we do when that limit is reached? */
533 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
534 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
535 #if 0 /* These settings only apply to non-ICANON mode. */
536 s
.main
.c_cc
[VMIN
] = 1;
537 s
.main
.c_cc
[VTIME
] = 0;
540 emacs_set_tty (out
, &s
, 0);
541 #endif /* not WINDOWSNT */
543 #endif /* not MSDOS */
546 /* Record a signal code and the action for it. */
550 struct sigaction action
;
553 static void save_signal_handlers (struct save_signal
*);
554 static void restore_signal_handlers (struct save_signal
*);
556 /* Suspend the Emacs process; give terminal to its superior. */
564 /* On a system where suspending is not implemented,
565 instead fork a subshell and let it talk directly to the terminal
572 /* Fork a subshell. */
577 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
580 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
582 char oldwd
[MAX_UTF8_PATH
];
588 struct save_signal saved_handlers
[5];
589 char *str
= SSDATA (encode_current_directory ());
595 char *volatile str_volatile
= str
;
602 error ("Can't spawn subshell");
604 saved_handlers
[0].code
= SIGINT
;
605 saved_handlers
[1].code
= SIGQUIT
;
606 saved_handlers
[2].code
= SIGTERM
;
608 saved_handlers
[3].code
= SIGIO
;
609 saved_handlers
[4].code
= 0;
611 saved_handlers
[3].code
= 0;
615 save_signal_handlers (saved_handlers
);
622 #ifdef DOS_NT /* MW, Aug 1993 */
623 getcwd (oldwd
, sizeof oldwd
);
625 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
628 sh
= egetenv ("SHELL");
632 /* Use our buffer's default directory for the subshell. */
633 if (chdir (str
) != 0)
637 _exit (EXIT_CANCELED
);
641 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
643 char *epwd
= getenv ("PWD");
644 char old_pwd
[MAXPATHLEN
+1+4];
646 /* If PWD is set, pass it with corrected value. */
649 strcpy (old_pwd
, epwd
);
650 setenv ("PWD", str
, 1);
653 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
655 putenv (old_pwd
); /* restore previous value */
657 #else /* not MSDOS */
659 /* Waits for process completion */
660 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
661 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
663 write (1, "Can't execute subshell", 22);
664 #else /* not WINDOWSNT */
665 execlp (sh
, sh
, (char *) 0);
667 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
668 #endif /* not WINDOWSNT */
669 #endif /* not MSDOS */
672 /* Do this now if we did not do it before. */
674 save_signal_handlers (saved_handlers
);
678 wait_for_termination (pid
, &status
, 0);
680 restore_signal_handlers (saved_handlers
);
684 save_signal_handlers (struct save_signal
*saved_handlers
)
686 while (saved_handlers
->code
)
688 struct sigaction action
;
689 emacs_sigaction_init (&action
, SIG_IGN
);
690 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
696 restore_signal_handlers (struct save_signal
*saved_handlers
)
698 while (saved_handlers
->code
)
700 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
706 static int old_fcntl_flags
[FD_SETSIZE
];
713 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
714 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
715 interrupts_deferred
= 0;
724 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
738 sigemptyset (&unblocked
);
740 sigaddset (&unblocked
, SIGWINCH
);
742 sigaddset (&unblocked
, SIGIO
);
743 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
745 interrupts_deferred
= 0;
750 unrequest_sigio (void)
758 sigemptyset (&blocked
);
760 sigaddset (&blocked
, SIGWINCH
);
762 sigaddset (&blocked
, SIGIO
);
763 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
764 interrupts_deferred
= 1;
772 block_child_signal (sigset_t
*oldset
)
775 sigemptyset (&blocked
);
776 sigaddset (&blocked
, SIGCHLD
);
777 sigaddset (&blocked
, SIGINT
);
778 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
781 /* Unblock SIGCHLD. */
784 unblock_child_signal (sigset_t
const *oldset
)
786 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
791 block_interrupt_signal (sigset_t
*oldset
)
794 sigemptyset (&blocked
);
795 sigaddset (&blocked
, SIGINT
);
796 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
799 /* Restore previously saved signal mask. */
801 restore_signal_mask (sigset_t
const *oldset
)
803 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
808 /* Saving and restoring the process group of Emacs's terminal. */
810 /* The process group of which Emacs was a member when it initially
813 If Emacs was in its own process group (i.e. inherited_pgroup ==
814 getpid ()), then we know we're running under a shell with job
815 control (Emacs would never be run as part of a pipeline).
818 If Emacs was not in its own process group, then we know we're
819 running under a shell (or a caller) that doesn't know how to
820 separate itself from Emacs (like sh). Emacs must be in its own
821 process group in order to receive SIGIO correctly. In this
822 situation, we put ourselves in our own pgroup, forcibly set the
823 tty's pgroup to our pgroup, and make sure to restore and reinstate
824 the tty's pgroup just like any other terminal setting. If
825 inherited_group was not the tty's pgroup, then we'll get a
826 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
827 it goes foreground in the future, which is what should happen. */
829 static pid_t inherited_pgroup
;
832 init_foreground_group (void)
834 pid_t pgrp
= getpgrp ();
835 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
838 /* Block and unblock SIGTTOU. */
841 block_tty_out_signal (sigset_t
*oldset
)
845 sigemptyset (&blocked
);
846 sigaddset (&blocked
, SIGTTOU
);
847 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
852 unblock_tty_out_signal (sigset_t
const *oldset
)
855 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
859 /* Safely set a controlling terminal FD's process group to PGID.
860 If we are not in the foreground already, POSIX requires tcsetpgrp
861 to deliver a SIGTTOU signal, which would stop us. This is an
862 annoyance, so temporarily ignore the signal.
864 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
865 skip all this unless SIGTTOU is defined. */
867 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
872 block_tty_out_signal (&oldset
);
873 tcsetpgrp (fd
, pgid
);
874 unblock_tty_out_signal (&oldset
);
879 /* Split off the foreground process group to Emacs alone. When we are
880 in the foreground, but not started in our own process group,
881 redirect the tty device handle FD to point to our own process
882 group. FD must be the file descriptor of the controlling tty. */
884 narrow_foreground_group (int fd
)
886 if (inherited_pgroup
&& setpgid (0, 0) == 0)
887 tcsetpgrp_without_stopping (fd
, getpid ());
890 /* Set the tty to our original foreground group. */
892 widen_foreground_group (int fd
)
894 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
895 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
898 /* Getting and setting emacs_tty structures. */
900 /* Set *TC to the parameters associated with the terminal FD,
901 or clear it if the parameters are not available.
902 Return 0 on success, -1 on failure. */
904 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
906 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
907 memset (&settings
->main
, 0, sizeof (settings
->main
));
910 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
913 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
915 settings
->main
= console_mode
;
918 #endif /* WINDOWSNT */
921 /* We have those nifty POSIX tcmumbleattr functions. */
922 return tcgetattr (fd
, &settings
->main
);
927 /* Set the parameters of the tty on FD according to the contents of
928 *SETTINGS. If FLUSHP, discard input.
929 Return 0 if all went well, and -1 (setting errno) if anything failed. */
932 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
934 /* Set the primary parameters - baud rate, character size, etcetera. */
937 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
939 if (h
&& h
!= INVALID_HANDLE_VALUE
)
943 /* Assume the handle is open for input. */
945 FlushConsoleInputBuffer (h
);
946 new_mode
= settings
->main
;
947 SetConsoleMode (h
, new_mode
);
949 #endif /* WINDOWSNT */
952 /* We have those nifty POSIX tcmumbleattr functions.
953 William J. Smith <wjs@wiis.wang.com> writes:
954 "POSIX 1003.1 defines tcsetattr to return success if it was
955 able to perform any of the requested actions, even if some
956 of the requested actions could not be performed.
957 We must read settings back to ensure tty setup properly.
958 AIX requires this to keep tty from hanging occasionally." */
959 /* This make sure that we don't loop indefinitely in here. */
960 for (i
= 0 ; i
< 10 ; i
++)
961 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
972 memset (&new, 0, sizeof (new));
973 /* Get the current settings, and see if they're what we asked for. */
974 tcgetattr (fd
, &new);
975 /* We cannot use memcmp on the whole structure here because under
976 * aix386 the termios structure has some reserved field that may
979 if ( new.c_iflag
== settings
->main
.c_iflag
980 && new.c_oflag
== settings
->main
.c_oflag
981 && new.c_cflag
== settings
->main
.c_cflag
982 && new.c_lflag
== settings
->main
.c_lflag
983 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
990 /* We have survived the tempest. */
997 static int old_fcntl_owner
[FD_SETSIZE
];
998 #endif /* F_SETOWN */
1000 /* This may also be defined in stdio,
1001 but if so, this does no harm,
1002 and using the same name avoids wasting the other one's space. */
1005 unsigned char _sobuf
[BUFSIZ
+8];
1007 char _sobuf
[BUFSIZ
];
1010 /* Initialize the terminal mode on all tty devices that are currently
1014 init_all_sys_modes (void)
1016 struct tty_display_info
*tty
;
1017 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1018 init_sys_modes (tty
);
1021 /* Initialize the terminal mode on the given tty device. */
1024 init_sys_modes (struct tty_display_info
*tty_out
)
1026 struct emacs_tty tty
;
1028 Lisp_Object terminal
;
1031 Vtty_erase_char
= Qnil
;
1036 if (!tty_out
->output
)
1037 return; /* The tty is suspended. */
1039 narrow_foreground_group (fileno (tty_out
->input
));
1041 if (! tty_out
->old_tty
)
1042 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1044 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1046 tty
= *tty_out
->old_tty
;
1048 #if !defined (DOS_NT)
1049 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1051 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1052 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1053 #ifdef INLCR /* I'm just being cautious,
1054 since I can't check how widespread INLCR is--rms. */
1055 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1058 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1060 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1061 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1063 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1065 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1066 if (tty_out
->flow_control
)
1068 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1070 tty
.main
.c_iflag
&= ~IXANY
;
1074 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1075 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1077 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1079 if (tty_out
->meta_key
)
1081 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1082 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1086 XSETTERMINAL(terminal
, tty_out
->terminal
);
1087 if (!NILP (Fcontrolling_tty_p (terminal
)))
1089 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1090 /* Set up C-g for both SIGQUIT and SIGINT.
1091 We don't know which we will get, but we handle both alike
1092 so which one it really gives us does not matter. */
1093 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1097 /* We normally don't get interrupt or quit signals from tty
1098 devices other than our controlling terminal; therefore,
1099 we must handle C-g as normal input. Unfortunately, this
1100 means that the interrupt and quit feature must be
1101 disabled on secondary ttys, or we would not even see the
1104 Note that even though emacsclient could have special code
1105 to pass SIGINT to Emacs, we should _not_ enable
1106 interrupt/quit keys for emacsclient frames. This means
1107 that we can't break out of loops in C code from a
1108 secondary tty frame, but we can always decide what
1109 display the C-g came from, which is more important from a
1110 usability point of view. (Consider the case when two
1111 people work together using the same Emacs instance.) */
1112 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1113 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1115 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1116 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1118 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1123 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1126 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1127 #endif /* V_DSUSP */
1128 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1129 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1132 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1135 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1136 #endif /* VREPRINT */
1138 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1139 #endif /* VWERASE */
1141 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1142 #endif /* VDISCARD */
1144 if (tty_out
->flow_control
)
1147 tty
.main
.c_cc
[VSTART
] = '\021';
1150 tty
.main
.c_cc
[VSTOP
] = '\023';
1156 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1159 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1164 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1165 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1166 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1167 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1168 if (tty_out
->flow_control
)
1171 tty
.main
.c_cc
[VSTART
] = '\021';
1174 tty
.main
.c_cc
[VSTOP
] = '\023';
1177 /* Also, PTY overloads NUL and BREAK.
1178 don't ignore break, but don't signal either, so it looks like NUL.
1179 This really serves a purpose only if running in an XTERM window
1180 or via TELNET or the like, but does no harm elsewhere. */
1181 tty
.main
.c_iflag
&= ~IGNBRK
;
1182 tty
.main
.c_iflag
&= ~BRKINT
;
1184 #endif /* not DOS_NT */
1186 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1187 if (!tty_out
->term_initted
)
1188 internal_terminal_init ();
1189 dos_ttraw (tty_out
);
1192 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1194 /* This code added to insure that, if flow-control is not to be used,
1195 we have an unlocked terminal at the start. */
1198 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1201 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1204 #if !defined (DOS_NT)
1206 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1211 if (interrupt_input
)
1213 old_fcntl_owner
[fileno (tty_out
->input
)] =
1214 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1215 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1216 init_sigio (fileno (tty_out
->input
));
1218 if (gpm_tty
== tty_out
)
1220 /* Arrange for mouse events to give us SIGIO signals. */
1221 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1222 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1223 init_sigio (gpm_fd
);
1225 #endif /* HAVE_GPM */
1227 #endif /* F_GETOWN */
1230 /* This symbol is defined on recent USG systems.
1231 Someone says without this call USG won't really buffer the file
1232 even with a call to setbuf. */
1233 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1235 setbuf (tty_out
->output
, (char *) _sobuf
);
1238 if (tty_out
->terminal
->set_terminal_modes_hook
)
1239 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1241 if (!tty_out
->term_initted
)
1243 Lisp_Object tail
, frame
;
1244 FOR_EACH_FRAME (tail
, frame
)
1246 /* XXX This needs to be revised. */
1247 if (FRAME_TERMCAP_P (XFRAME (frame
))
1248 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1249 init_frame_faces (XFRAME (frame
));
1253 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1255 /* We used to call "direct_output_forward_char(0)" here,
1256 but it's not clear why, since it may not do anything anyway. */
1260 Lisp_Object tail
, frame
;
1262 FOR_EACH_FRAME (tail
, frame
)
1264 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1265 || FRAME_MSDOS_P (XFRAME (frame
)))
1266 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1267 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1271 tty_out
->term_initted
= 1;
1274 /* Return true if safe to use tabs in output.
1275 At the time this is called, init_sys_modes has not been done yet. */
1278 tabs_safe_p (int fd
)
1280 struct emacs_tty etty
;
1282 emacs_get_tty (fd
, &etty
);
1285 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1286 #else /* not TABDLY */
1288 #endif /* not TABDLY */
1294 /* Discard echoing. */
1297 suppress_echo_on_tty (int fd
)
1299 struct emacs_tty etty
;
1301 emacs_get_tty (fd
, &etty
);
1303 /* Set raw input mode. */
1306 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1307 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1308 #endif /* ! WINDOWSNT */
1309 emacs_set_tty (fd
, &etty
, 0);
1312 /* Get terminal size from system.
1313 Store number of lines into *HEIGHTP and width into *WIDTHP.
1314 We store 0 if there's no valid information. */
1317 get_tty_size (int fd
, int *widthp
, int *heightp
)
1319 #if defined TIOCGWINSZ
1322 struct winsize size
;
1324 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1325 *widthp
= *heightp
= 0;
1328 *widthp
= size
.ws_col
;
1329 *heightp
= size
.ws_row
;
1332 #elif defined TIOCGSIZE
1334 /* SunOS - style. */
1335 struct ttysize size
;
1337 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1338 *widthp
= *heightp
= 0;
1341 *widthp
= size
.ts_cols
;
1342 *heightp
= size
.ts_lines
;
1345 #elif defined WINDOWSNT
1347 CONSOLE_SCREEN_BUFFER_INFO info
;
1348 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1350 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1351 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1354 *widthp
= *heightp
= 0;
1358 *widthp
= ScreenCols ();
1359 *heightp
= ScreenRows ();
1361 #else /* system doesn't know size */
1369 /* Set the logical window size associated with descriptor FD
1370 to HEIGHT and WIDTH. This is used mainly with ptys.
1371 Return a negative value on failure. */
1374 set_window_size (int fd
, int height
, int width
)
1379 struct winsize size
;
1380 size
.ws_row
= height
;
1381 size
.ws_col
= width
;
1383 return ioctl (fd
, TIOCSWINSZ
, &size
);
1388 /* SunOS - style. */
1389 struct ttysize size
;
1390 size
.ts_lines
= height
;
1391 size
.ts_cols
= width
;
1393 return ioctl (fd
, TIOCGSIZE
, &size
);
1396 #endif /* not SunOS-style */
1397 #endif /* not BSD-style */
1402 /* Prepare all terminal devices for exiting Emacs. */
1405 reset_all_sys_modes (void)
1407 struct tty_display_info
*tty
;
1408 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1409 reset_sys_modes (tty
);
1412 /* Prepare the terminal for closing it; move the cursor to the
1413 bottom of the frame, turn off interrupt-driven I/O, etc. */
1416 reset_sys_modes (struct tty_display_info
*tty_out
)
1420 fflush_unlocked (stdout
);
1423 if (!tty_out
->term_initted
)
1426 if (!tty_out
->output
)
1427 return; /* The tty is suspended. */
1429 /* Go to and clear the last line of the terminal. */
1431 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1433 /* Code adapted from tty_clear_end_of_line. */
1434 if (tty_out
->TS_clr_line
)
1436 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1439 { /* have to do it the hard way */
1440 tty_turn_off_insert (tty_out
);
1442 for (int i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1443 fputc_unlocked (' ', tty_out
->output
);
1446 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1447 fflush_unlocked (tty_out
->output
);
1449 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1450 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1452 /* Avoid possible loss of output when changing terminal modes. */
1453 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1458 if (interrupt_input
)
1460 reset_sigio (fileno (tty_out
->input
));
1461 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1462 old_fcntl_owner
[fileno (tty_out
->input
)]);
1464 #endif /* F_SETOWN */
1465 fcntl (fileno (tty_out
->input
), F_SETFL
,
1466 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1469 if (tty_out
->old_tty
)
1470 while (emacs_set_tty (fileno (tty_out
->input
),
1471 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1474 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1478 widen_foreground_group (fileno (tty_out
->input
));
1483 /* Set up the proper status flags for use of a pty. */
1488 /* I'm told that TOICREMOTE does not mean control chars
1489 "can't be sent" but rather that they don't have
1490 input-editing or signaling effects.
1491 That should be good, because we have other ways
1492 to do those things in Emacs.
1493 However, telnet mode seems not to work on 4.2.
1494 So TIOCREMOTE is turned off now. */
1496 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1497 will hang. In particular, the "timeout" feature (which
1498 causes a read to return if there is no data available)
1499 does this. Also it is known that telnet mode will hang
1500 in such a way that Emacs must be stopped (perhaps this
1501 is the same problem).
1503 If TIOCREMOTE is turned off, then there is a bug in
1504 hp-ux which sometimes loses data. Apparently the
1505 code which blocks the master process when the internal
1506 buffer fills up does not work. Other than this,
1507 though, everything else seems to work fine.
1509 Since the latter lossage is more benign, we may as well
1510 lose that way. -- cph */
1512 #if defined (UNIX98_PTYS)
1515 ioctl (fd
, FIONBIO
, &on
);
1520 #endif /* HAVE_PTYS */
1523 init_system_name (void)
1527 /* Set system-name to nil so that the build is deterministic. */
1528 Vsystem_name
= Qnil
;
1531 char *hostname_alloc
= NULL
;
1533 #ifndef HAVE_GETHOSTNAME
1536 hostname
= uts
.nodename
;
1537 #else /* HAVE_GETHOSTNAME */
1538 char hostname_buf
[256];
1539 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1540 hostname
= hostname_buf
;
1542 /* Try to get the host name; if the buffer is too short, try
1543 again. Apparently, the only indication gethostname gives of
1544 whether the buffer was large enough is the presence or absence
1545 of a '\0' in the string. Eech. */
1548 gethostname (hostname
, hostname_size
- 1);
1549 hostname
[hostname_size
- 1] = '\0';
1551 /* Was the buffer large enough for the '\0'? */
1552 if (strlen (hostname
) < hostname_size
- 1)
1555 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1556 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1558 #endif /* HAVE_GETHOSTNAME */
1560 for (p
= hostname
; *p
; p
++)
1561 if (*p
== ' ' || *p
== '\t')
1563 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1564 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1565 Vsystem_name
= build_string (hostname
);
1566 xfree (hostname_alloc
);
1569 sigset_t empty_mask
;
1571 static struct sigaction process_fatal_action
;
1574 emacs_sigaction_flags (void)
1577 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1578 'select') to reset their timeout on some platforms (e.g.,
1579 HP-UX 11), which is not what we want. Also, when Emacs is
1580 interactive, we don't want SA_RESTART because we need to poll
1581 for pending input so we need long-running syscalls to be interrupted
1582 after a signal that sets pending_signals.
1584 Non-interactive keyboard input goes through stdio, where we
1585 always want restartable system calls. */
1592 /* Store into *ACTION a signal action suitable for Emacs, with handler
1595 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1597 sigemptyset (&action
->sa_mask
);
1599 /* When handling a signal, block nonfatal system signals that are caught
1600 by Emacs. This makes race conditions less likely. */
1601 sigaddset (&action
->sa_mask
, SIGALRM
);
1603 sigaddset (&action
->sa_mask
, SIGCHLD
);
1606 sigaddset (&action
->sa_mask
, SIGDANGER
);
1608 #ifdef PROFILER_CPU_SUPPORT
1609 sigaddset (&action
->sa_mask
, SIGPROF
);
1612 sigaddset (&action
->sa_mask
, SIGWINCH
);
1614 if (! noninteractive
)
1616 sigaddset (&action
->sa_mask
, SIGINT
);
1617 sigaddset (&action
->sa_mask
, SIGQUIT
);
1619 sigaddset (&action
->sa_mask
, SIGIO
);
1623 action
->sa_handler
= handler
;
1624 action
->sa_flags
= emacs_sigaction_flags ();
1627 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1628 pthread_t main_thread_id
;
1631 /* SIG has arrived at the current process. Deliver it to the main
1632 thread, which should handle it with HANDLER. (Delivering the
1633 signal to some other thread might not work if the other thread is
1636 If we are on the main thread, handle the signal SIG with HANDLER.
1637 Otherwise, redirect the signal to the main thread, blocking it from
1638 this thread. POSIX says any thread can receive a signal that is
1639 associated with a process, process group, or asynchronous event.
1640 On GNU/Linux the main thread typically gets a process signal unless
1641 it's blocked, but other systems (FreeBSD at least) can deliver the
1642 signal to other threads. */
1644 deliver_process_signal (int sig
, signal_handler_t handler
)
1646 /* Preserve errno, to avoid race conditions with signal handlers that
1647 might change errno. Races can occur even in single-threaded hosts. */
1648 int old_errno
= errno
;
1650 bool on_main_thread
= true;
1651 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1652 if (! pthread_equal (pthread_self (), main_thread_id
))
1655 sigemptyset (&blocked
);
1656 sigaddset (&blocked
, sig
);
1657 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1658 pthread_kill (main_thread_id
, sig
);
1659 on_main_thread
= false;
1668 /* Static location to save a fatal backtrace in a thread.
1669 FIXME: If two subsidiary threads fail simultaneously, the resulting
1670 backtrace may be garbage. */
1671 enum { BACKTRACE_LIMIT_MAX
= 500 };
1672 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1673 static int thread_backtrace_npointers
;
1675 /* SIG has arrived at the current thread.
1676 If we are on the main thread, handle the signal SIG with HANDLER.
1677 Otherwise, this is a fatal error in the handling thread. */
1679 deliver_thread_signal (int sig
, signal_handler_t handler
)
1681 int old_errno
= errno
;
1683 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1684 if (! pthread_equal (pthread_self (), main_thread_id
))
1686 thread_backtrace_npointers
1687 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1688 sigaction (sig
, &process_fatal_action
, 0);
1689 pthread_kill (main_thread_id
, sig
);
1691 /* Avoid further damage while the main thread is exiting. */
1693 sigsuspend (&empty_mask
);
1701 #if !HAVE_DECL_SYS_SIGLIST
1703 # ifdef _sys_siglist
1704 # define sys_siglist _sys_siglist
1705 # elif HAVE_DECL___SYS_SIGLIST
1706 # define sys_siglist __sys_siglist
1708 # define sys_siglist my_sys_siglist
1709 static char const *sys_siglist
[NSIG
];
1714 # define sys_siglist_entries _sys_nsig
1716 # define sys_siglist_entries NSIG
1719 /* Handle bus errors, invalid instruction, etc. */
1721 handle_fatal_signal (int sig
)
1723 terminate_due_to_signal (sig
, 40);
1727 deliver_fatal_signal (int sig
)
1729 deliver_process_signal (sig
, handle_fatal_signal
);
1733 deliver_fatal_thread_signal (int sig
)
1735 deliver_thread_signal (sig
, handle_fatal_signal
);
1738 static _Noreturn
void
1739 handle_arith_signal (int sig
)
1741 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1742 xsignal0 (Qarith_error
);
1745 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1747 /* Alternate stack used by SIGSEGV handler below. */
1749 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1752 /* Return true if SIGINFO indicates a stack overflow. */
1755 stack_overflow (siginfo_t
*siginfo
)
1757 if (!attempt_stack_overflow_recovery
)
1760 /* In theory, a more-accurate heuristic can be obtained by using
1761 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1762 and pthread_attr_getguardsize to find the location and size of the
1763 guard area. In practice, though, these functions are so hard to
1764 use reliably that they're not worth bothering with. E.g., see:
1765 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1766 Other operating systems also have problems, e.g., Solaris's
1767 stack_violation function is tailor-made for this problem, but it
1768 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1770 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1776 /* The faulting address. */
1777 char *addr
= siginfo
->si_addr
;
1781 /* The known top and bottom of the stack. The actual stack may
1782 extend a bit beyond these boundaries. */
1783 char *bot
= stack_bottom
;
1784 char *top
= current_thread
->stack_top
;
1786 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1787 of the known stack divided by the size of the guard area past the
1788 end of the stack top. The heuristic is that a bad address is
1789 considered to be a stack overflow if it occurs within
1790 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1791 stack. This heuristic is not exactly correct but it's good
1792 enough in practice. */
1793 enum { LG_STACK_HEURISTIC
= 8 };
1796 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1798 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1802 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1805 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1807 /* Hard GC error may lead to stack overflow caused by
1808 too nested calls to mark_object. No way to survive. */
1809 bool fatal
= gc_in_progress
;
1811 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1812 if (!fatal
&& !pthread_equal (pthread_self (), main_thread_id
))
1816 if (!fatal
&& stack_overflow (siginfo
))
1817 siglongjmp (return_to_command_loop
, 1);
1819 /* Otherwise we can't do anything with this. */
1820 deliver_fatal_thread_signal (sig
);
1823 /* Return true if we have successfully set up SIGSEGV handler on alternate
1824 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1829 struct sigaction sa
;
1832 ss
.ss_sp
= sigsegv_stack
;
1833 ss
.ss_size
= sizeof (sigsegv_stack
);
1835 if (sigaltstack (&ss
, NULL
) < 0)
1838 sigfillset (&sa
.sa_mask
);
1839 sa
.sa_sigaction
= handle_sigsegv
;
1840 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1841 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1844 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1852 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1855 deliver_arith_signal (int sig
)
1857 deliver_thread_signal (sig
, handle_arith_signal
);
1862 /* Handler for SIGDANGER. */
1864 handle_danger_signal (int sig
)
1866 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1868 /* It might be unsafe to call do_auto_save now. */
1869 force_auto_save_soon ();
1873 deliver_danger_signal (int sig
)
1875 deliver_process_signal (sig
, handle_danger_signal
);
1879 /* Treat SIG as a terminating signal, unless it is already ignored and
1880 we are in --batch mode. Among other things, this makes nohup work. */
1882 maybe_fatal_sig (int sig
)
1884 bool catch_sig
= !noninteractive
;
1887 struct sigaction old_action
;
1888 sigaction (sig
, 0, &old_action
);
1889 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1892 sigaction (sig
, &process_fatal_action
, 0);
1896 init_signals (bool dumping
)
1898 struct sigaction thread_fatal_action
;
1899 struct sigaction action
;
1901 sigemptyset (&empty_mask
);
1903 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1904 main_thread_id
= pthread_self ();
1907 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1910 sys_siglist
[SIGABRT
] = "Aborted";
1912 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1914 sys_siglist
[SIGALRM
] = "Alarm clock";
1916 sys_siglist
[SIGBUS
] = "Bus error";
1919 sys_siglist
[SIGCHLD
] = "Child status changed";
1922 sys_siglist
[SIGCONT
] = "Continued";
1925 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1928 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1931 sys_siglist
[SIGEMT
] = "Emulation trap";
1933 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1935 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1938 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1940 sys_siglist
[SIGHUP
] = "Hangup";
1941 sys_siglist
[SIGILL
] = "Illegal instruction";
1942 sys_siglist
[SIGINT
] = "Interrupt";
1944 sys_siglist
[SIGIO
] = "I/O possible";
1947 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1950 sys_siglist
[SIGIOT
] = "IOT trap";
1952 sys_siglist
[SIGKILL
] = "Killed";
1954 sys_siglist
[SIGLOST
] = "Resource lost";
1957 sys_siglist
[SIGLWP
] = "SIGLWP";
1960 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1963 sys_siglist
[SIGWIND
] = "SIGPHONE";
1965 sys_siglist
[SIGPIPE
] = "Broken pipe";
1967 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1970 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1973 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1976 sys_siglist
[SIGPWR
] = "Power-fail restart";
1978 sys_siglist
[SIGQUIT
] = "Quit";
1980 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1983 sys_siglist
[SIGSAK
] = "Secure attention";
1985 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1987 sys_siglist
[SIGSOUND
] = "Sound completed";
1990 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1993 sys_siglist
[SIGSTP
] = "Stopped (user)";
1996 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1998 sys_siglist
[SIGTERM
] = "Terminated";
2000 sys_siglist
[SIGTHAW
] = "SIGTHAW";
2003 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
2006 sys_siglist
[SIGTSTP
] = "Stopped (user)";
2009 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
2012 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
2015 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2018 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2021 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2024 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2027 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2030 sys_siglist
[SIGWINCH
] = "Window size changed";
2033 sys_siglist
[SIGWIND
] = "SIGWIND";
2036 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2039 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2042 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2044 /* Don't alter signal handlers if dumping. On some machines,
2045 changing signal handlers sets static data that would make signals
2046 fail to work right when the dumped Emacs is run. */
2050 sigfillset (&process_fatal_action
.sa_mask
);
2051 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2052 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2054 sigfillset (&thread_fatal_action
.sa_mask
);
2055 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2056 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2058 /* SIGINT may need special treatment on MS-Windows. See
2059 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2060 Please update the doc of kill-emacs, kill-emacs-hook, and
2061 NEWS if you change this. */
2063 maybe_fatal_sig (SIGHUP
);
2064 maybe_fatal_sig (SIGINT
);
2065 maybe_fatal_sig (SIGTERM
);
2067 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2068 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2069 to behave more like typical batch applications do. */
2070 if (! noninteractive
)
2071 signal (SIGPIPE
, SIG_IGN
);
2073 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2074 sigaction (SIGILL
, &thread_fatal_action
, 0);
2075 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2077 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2078 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2079 interpreter's floating point operations, so treat SIGFPE as an
2080 arith-error if it arises in the main thread. */
2081 if (IEEE_FLOATING_POINT
)
2082 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2085 emacs_sigaction_init (&action
, deliver_arith_signal
);
2086 sigaction (SIGFPE
, &action
, 0);
2090 add_user_signal (SIGUSR1
, "sigusr1");
2093 add_user_signal (SIGUSR2
, "sigusr2");
2095 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2097 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2100 sigaction (SIGORE
, &thread_fatal_action
, 0);
2103 sigaction (SIGUME
, &thread_fatal_action
, 0);
2106 sigaction (SIGDLK
, &process_fatal_action
, 0);
2109 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2112 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2115 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2118 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2120 if (!init_sigsegv ())
2121 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2123 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2125 sigaction (SIGTERM
, &process_fatal_action
, 0);
2127 signal (SIGPROF
, SIG_IGN
);
2130 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2133 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2136 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2140 /* This just means available memory is getting low. */
2141 emacs_sigaction_init (&action
, deliver_danger_signal
);
2142 sigaction (SIGDANGER
, &action
, 0);
2145 /* AIX-specific signals. */
2147 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2150 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2153 sigaction (SIGMSG
, &process_fatal_action
, 0);
2156 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2159 sigaction (SIGSAK
, &process_fatal_action
, 0);
2162 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2165 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2175 /* Figure out how many bits the system's random number generator uses.
2176 `random' and `lrand48' are assumed to return 31 usable bits.
2177 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2178 so we'll shift it and treat it like the 15-bit USG `rand'. */
2182 # define RAND_BITS 31
2183 # else /* !HAVE_RANDOM */
2184 # ifdef HAVE_LRAND48
2185 # define RAND_BITS 31
2186 # define random lrand48
2187 # else /* !HAVE_LRAND48 */
2188 # define RAND_BITS 15
2189 # if RAND_MAX == 32767
2190 # define random rand
2191 # else /* RAND_MAX != 32767 */
2192 # if RAND_MAX == 2147483647
2193 # define random() (rand () >> 16)
2194 # else /* RAND_MAX != 2147483647 */
2196 # define random rand
2198 # define random() (rand () >> 16)
2200 # endif /* RAND_MAX != 2147483647 */
2201 # endif /* RAND_MAX != 32767 */
2202 # endif /* !HAVE_LRAND48 */
2203 # endif /* !HAVE_RANDOM */
2204 #endif /* !RAND_BITS */
2207 typedef unsigned int random_seed
;
2208 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2209 #elif defined HAVE_LRAND48
2210 /* Although srand48 uses a long seed, this is unsigned long to avoid
2211 undefined behavior on signed integer overflow in init_random. */
2212 typedef unsigned long int random_seed
;
2213 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2215 typedef unsigned int random_seed
;
2216 static void set_random_seed (random_seed arg
) { srand (arg
); }
2220 seed_random (void *seed
, ptrdiff_t seed_size
)
2222 random_seed arg
= 0;
2223 unsigned char *argp
= (unsigned char *) &arg
;
2224 unsigned char *seedp
= seed
;
2225 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2226 argp
[i
% sizeof arg
] ^= seedp
[i
];
2227 set_random_seed (arg
);
2234 bool success
= false;
2236 /* First, try seeding the PRNG from the operating system's entropy
2237 source. This approach is both fast and secure. */
2239 success
= w32_init_random (&v
, sizeof v
) == 0;
2241 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2244 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2249 /* If that didn't work, try using GnuTLS, which is secure, but on
2250 some systems, can be somewhat slow. */
2252 success
= EQ (emacs_gnutls_global_init (), Qt
)
2253 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2255 /* If _that_ didn't work, just use the current time value and PID.
2256 It's at least better than XKCD 221. */
2259 struct timespec t
= current_timespec ();
2260 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2263 set_random_seed (v
);
2267 * Return a nonnegative random integer out of whatever we've got.
2268 * It contains enough bits to make a random (signed) Emacs fixnum.
2269 * This suffices even for a 64-bit architecture with a 15-bit rand.
2276 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2277 val
= (random () ^ (val
<< RAND_BITS
)
2278 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2279 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2280 return val
& INTMASK
;
2283 #ifndef HAVE_SNPRINTF
2284 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2286 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2288 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2289 ptrdiff_t nbytes
= size
- 1;
2294 va_start (ap
, format
);
2295 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2299 if (nbytes
== size
- 1)
2301 /* Calculate the length of the string that would have been created
2302 had the buffer been large enough. */
2303 char stackbuf
[4000];
2305 ptrdiff_t bsize
= sizeof stackbuf
;
2306 va_start (ap
, format
);
2307 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2313 if (INT_MAX
< nbytes
)
2326 /* If a backtrace is available, output the top lines of it to stderr.
2327 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2328 This function may be called from a signal handler, so it should
2329 not invoke async-unsafe functions like malloc.
2331 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2332 but do not output anything. This avoids some problems that can
2333 otherwise occur if the malloc arena is corrupted before 'backtrace'
2334 is called, since 'backtrace' may call malloc if the tables are not
2337 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2338 fatal error has occurred in some other thread; generate a thread
2339 backtrace instead, ignoring BACKTRACE_LIMIT. */
2341 emacs_backtrace (int backtrace_limit
)
2343 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2344 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2348 if (thread_backtrace_npointers
)
2350 buffer
= thread_backtrace_buffer
;
2351 npointers
= thread_backtrace_npointers
;
2355 buffer
= main_backtrace_buffer
;
2357 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2358 if (bounded_limit
< 0)
2360 backtrace (buffer
, 1);
2364 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2369 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2370 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2371 if (bounded_limit
< npointers
)
2372 emacs_write (STDERR_FILENO
, "...\n", 4);
2380 terminate_due_to_signal (SIGABRT
, 40);
2384 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2385 Use binary I/O on systems that care about text vs binary I/O.
2386 Arrange for subprograms to not inherit the file descriptor.
2387 Prefer a method that is multithread-safe, if available.
2388 Do not fail merely because the open was interrupted by a signal.
2389 Allow the user to quit. */
2392 emacs_open (const char *file
, int oflags
, int mode
)
2395 if (! (oflags
& O_TEXT
))
2397 oflags
|= O_CLOEXEC
;
2398 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2403 /* Open FILE as a stream for Emacs use, with mode MODE.
2404 Act like emacs_open with respect to threads, signals, and quits. */
2407 emacs_fopen (char const *file
, char const *mode
)
2409 int fd
, omode
, oflags
;
2411 char const *m
= mode
;
2415 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2416 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2417 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2418 default: emacs_abort ();
2424 case '+': omode
= O_RDWR
; break;
2425 case 't': bflag
= O_TEXT
; break;
2426 default: /* Ignore. */ break;
2429 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2430 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2433 /* Create a pipe for Emacs use. */
2436 emacs_pipe (int fd
[2])
2441 return pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2445 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2446 For the background behind this mess, please see Austin Group defect 529
2447 <http://austingroupbugs.net/view.php?id=529>. */
2449 #ifndef POSIX_CLOSE_RESTART
2450 # define POSIX_CLOSE_RESTART 1
2452 posix_close (int fd
, int flag
)
2454 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2455 eassert (flag
== POSIX_CLOSE_RESTART
);
2457 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2458 on a system that does not define POSIX_CLOSE_RESTART.
2460 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2461 closed, and retrying the close could inadvertently close a file
2462 descriptor allocated by some other thread. In other systems
2463 (e.g., HP/UX) FD is not closed. And in still other systems
2464 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2465 multithreaded program there can be no way to tell.
2467 So, in this case, pretend that the close succeeded. This works
2468 well on systems like GNU/Linux that close FD. Although it may
2469 leak a file descriptor on other systems, the leak is unlikely and
2470 it's better to leak than to close a random victim. */
2471 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2475 /* Close FD, retrying if interrupted. If successful, return 0;
2476 otherwise, return -1 and set errno to a non-EINTR value. Consider
2477 an EINPROGRESS error to be successful, as that's merely a signal
2478 arriving. FD is always closed when this function returns, even
2481 Do not call this function if FD is nonnegative and might already be closed,
2482 as that might close an innocent victim opened by some other thread. */
2485 emacs_close (int fd
)
2489 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2492 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2494 eassert (errno
!= EBADF
|| fd
< 0);
2495 return errno
== EINPROGRESS
? 0 : r
;
2500 /* Maximum number of bytes to read or write in a single system call.
2501 This works around a serious bug in Linux kernels before 2.6.16; see
2502 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2503 It's likely to work around similar bugs in other operating systems, so do it
2504 on all platforms. Round INT_MAX down to a page size, with the conservative
2505 assumption that page sizes are at most 2**18 bytes (any kernel with a
2506 page size larger than that shouldn't have the bug). */
2507 #ifndef MAX_RW_COUNT
2508 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2511 /* Read from FD to a buffer BUF with size NBYTE.
2512 If interrupted, process any quits and pending signals immediately
2513 if INTERRUPTIBLE, and then retry the read unless quitting.
2514 Return the number of bytes read, which might be less than NBYTE.
2515 On error, set errno to a value other than EINTR, and return -1. */
2517 emacs_intr_read (int fd
, void *buf
, ptrdiff_t nbyte
, bool interruptible
)
2521 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2522 passes a size that large to emacs_read. */
2527 result
= read (fd
, buf
, nbyte
);
2529 while (result
< 0 && errno
== EINTR
);
2534 /* Read from FD to a buffer BUF with size NBYTE.
2535 If interrupted, retry the read. Return the number of bytes read,
2536 which might be less than NBYTE. On error, set errno to a value
2537 other than EINTR, and return -1. */
2539 emacs_read (int fd
, void *buf
, ptrdiff_t nbyte
)
2541 return emacs_intr_read (fd
, buf
, nbyte
, false);
2544 /* Like emacs_read, but also process quits and pending signals. */
2546 emacs_read_quit (int fd
, void *buf
, ptrdiff_t nbyte
)
2548 return emacs_intr_read (fd
, buf
, nbyte
, true);
2551 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2552 interrupted or if a partial write occurs. Process any quits
2553 immediately if INTERRUPTIBLE is positive, and process any pending
2554 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2555 of bytes written; if this is less than NBYTE, set errno to a value
2556 other than EINTR. */
2558 emacs_full_write (int fd
, char const *buf
, ptrdiff_t nbyte
,
2561 ptrdiff_t bytes_written
= 0;
2565 ssize_t n
= write (fd
, buf
, min (nbyte
, MAX_RW_COUNT
));
2574 if (0 < interruptible
)
2576 if (pending_signals
)
2577 process_pending_signals ();
2588 return bytes_written
;
2591 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2592 interrupted or if a partial write occurs. Do not process quits or
2593 pending signals. Return the number of bytes written, setting errno
2594 if this is less than NBYTE. */
2596 emacs_write (int fd
, void const *buf
, ptrdiff_t nbyte
)
2598 return emacs_full_write (fd
, buf
, nbyte
, 0);
2601 /* Like emacs_write, but also process pending signals. */
2603 emacs_write_sig (int fd
, void const *buf
, ptrdiff_t nbyte
)
2605 return emacs_full_write (fd
, buf
, nbyte
, -1);
2608 /* Like emacs_write, but also process quits and pending signals. */
2610 emacs_write_quit (int fd
, void const *buf
, ptrdiff_t nbyte
)
2612 return emacs_full_write (fd
, buf
, nbyte
, 1);
2615 /* Write a diagnostic to standard error that contains MESSAGE and a
2616 string derived from errno. Preserve errno. Do not buffer stderr.
2617 Do not process quits or pending signals if interrupted. */
2619 emacs_perror (char const *message
)
2622 char const *error_string
= emacs_strerror (err
);
2623 char const *command
= (initial_argv
&& initial_argv
[0]
2624 ? initial_argv
[0] : "emacs");
2625 /* Write it out all at once, if it's short; this is less likely to
2626 be interleaved with other output. */
2628 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2629 command
, message
, error_string
);
2630 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2631 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2634 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2635 emacs_write (STDERR_FILENO
, ": ", 2);
2636 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2637 emacs_write (STDERR_FILENO
, ": ", 2);
2638 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2639 emacs_write (STDERR_FILENO
, "\n", 1);
2644 /* Return a struct timeval that is roughly equivalent to T.
2645 Use the least timeval not less than T.
2646 Return an extremal value if the result would overflow. */
2648 make_timeval (struct timespec t
)
2651 tv
.tv_sec
= t
.tv_sec
;
2652 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2654 if (t
.tv_nsec
% 1000 != 0)
2656 if (tv
.tv_usec
< 999999)
2658 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2668 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2669 ATIME and MTIME, respectively.
2670 FD must be either negative -- in which case it is ignored --
2671 or a file descriptor that is open on FILE.
2672 If FD is nonnegative, then FILE can be NULL. */
2674 set_file_times (int fd
, const char *filename
,
2675 struct timespec atime
, struct timespec mtime
)
2677 struct timespec timespec
[2];
2678 timespec
[0] = atime
;
2679 timespec
[1] = mtime
;
2680 return fdutimens (fd
, filename
, timespec
);
2683 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2684 This is like renameat except that it fails if DST already exists,
2685 or if this operation is not supported atomically. Return 0 if
2686 successful, -1 (setting errno) otherwise. */
2688 renameat_noreplace (int srcfd
, char const *src
, int dstfd
, char const *dst
)
2690 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2691 return syscall (SYS_renameat2
, srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2692 #elif defined RENAME_NOREPLACE /* Cygwin >= 2.9.0. */
2693 return renameat2 (srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2694 #elif defined RENAME_EXCL
2695 return renameatx_np (srcfd
, src
, dstfd
, dst
, RENAME_EXCL
);
2698 if (srcfd
== AT_FDCWD
&& dstfd
== AT_FDCWD
)
2699 return sys_rename_replace (src
, dst
, 0);
2706 /* Like strsignal, except async-signal-safe, and this function typically
2707 returns a string in the C locale rather than the current locale. */
2709 safe_strsignal (int code
)
2711 char const *signame
= 0;
2713 if (0 <= code
&& code
< sys_siglist_entries
)
2714 signame
= sys_siglist
[code
];
2716 signame
= "Unknown signal";
2722 /* For make-serial-process */
2724 serial_open (Lisp_Object port
)
2726 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2728 report_file_error ("Opening serial port", port
);
2730 ioctl (fd
, TIOCEXCL
, (char *) 0);
2736 #if !defined (HAVE_CFMAKERAW)
2737 /* Workaround for targets which are missing cfmakeraw. */
2738 /* Pasted from man page. */
2740 cfmakeraw (struct termios
*termios_p
)
2742 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2743 termios_p
->c_oflag
&= ~OPOST
;
2744 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2745 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2746 termios_p
->c_cflag
|= CS8
;
2748 #endif /* !defined (HAVE_CFMAKERAW */
2750 #if !defined (HAVE_CFSETSPEED)
2751 /* Workaround for targets which are missing cfsetspeed. */
2753 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2755 return (cfsetispeed (termios_p
, vitesse
)
2756 + cfsetospeed (termios_p
, vitesse
));
2760 /* For serial-process-configure */
2762 serial_configure (struct Lisp_Process
*p
,
2763 Lisp_Object contact
)
2765 Lisp_Object childp2
= Qnil
;
2766 Lisp_Object tem
= Qnil
;
2767 struct termios attr
;
2769 char summary
[4] = "???"; /* This usually becomes "8N1". */
2771 childp2
= Fcopy_sequence (p
->childp
);
2773 /* Read port attributes and prepare default configuration. */
2774 err
= tcgetattr (p
->outfd
, &attr
);
2776 report_file_error ("Failed tcgetattr", Qnil
);
2778 #if defined (CLOCAL)
2779 attr
.c_cflag
|= CLOCAL
;
2782 attr
.c_cflag
|= CREAD
;
2785 /* Configure speed. */
2786 if (!NILP (Fplist_member (contact
, QCspeed
)))
2787 tem
= Fplist_get (contact
, QCspeed
);
2789 tem
= Fplist_get (p
->childp
, QCspeed
);
2791 err
= cfsetspeed (&attr
, XINT (tem
));
2793 report_file_error ("Failed cfsetspeed", tem
);
2794 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2796 /* Configure bytesize. */
2797 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2798 tem
= Fplist_get (contact
, QCbytesize
);
2800 tem
= Fplist_get (p
->childp
, QCbytesize
);
2802 tem
= make_number (8);
2804 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2805 error (":bytesize must be nil (8), 7, or 8");
2806 summary
[0] = XINT (tem
) + '0';
2807 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2808 attr
.c_cflag
&= ~CSIZE
;
2809 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2811 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2812 if (XINT (tem
) != 8)
2813 error ("Bytesize cannot be changed");
2815 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2817 /* Configure parity. */
2818 if (!NILP (Fplist_member (contact
, QCparity
)))
2819 tem
= Fplist_get (contact
, QCparity
);
2821 tem
= Fplist_get (p
->childp
, QCparity
);
2822 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2823 error (":parity must be nil (no parity), `even', or `odd'");
2824 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2825 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2826 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2831 else if (EQ (tem
, Qeven
))
2834 attr
.c_cflag
|= PARENB
;
2835 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2837 else if (EQ (tem
, Qodd
))
2840 attr
.c_cflag
|= (PARENB
| PARODD
);
2841 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2844 /* Don't error on no parity, which should be set by cfmakeraw. */
2846 error ("Parity cannot be configured");
2848 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2850 /* Configure stopbits. */
2851 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2852 tem
= Fplist_get (contact
, QCstopbits
);
2854 tem
= Fplist_get (p
->childp
, QCstopbits
);
2856 tem
= make_number (1);
2858 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2859 error (":stopbits must be nil (1 stopbit), 1, or 2");
2860 summary
[2] = XINT (tem
) + '0';
2861 #if defined (CSTOPB)
2862 attr
.c_cflag
&= ~CSTOPB
;
2863 if (XINT (tem
) == 2)
2864 attr
.c_cflag
|= CSTOPB
;
2866 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2867 if (XINT (tem
) != 1)
2868 error ("Stopbits cannot be configured");
2870 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2872 /* Configure flowcontrol. */
2873 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2874 tem
= Fplist_get (contact
, QCflowcontrol
);
2876 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2877 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2878 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2879 #if defined (CRTSCTS)
2880 attr
.c_cflag
&= ~CRTSCTS
;
2882 #if defined (CNEW_RTSCTS)
2883 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2885 #if defined (IXON) && defined (IXOFF)
2886 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2890 /* Already configured. */
2892 else if (EQ (tem
, Qhw
))
2894 #if defined (CRTSCTS)
2895 attr
.c_cflag
|= CRTSCTS
;
2896 #elif defined (CNEW_RTSCTS)
2897 attr
.c_cflag
|= CNEW_RTSCTS
;
2899 error ("Hardware flowcontrol (RTS/CTS) not supported");
2902 else if (EQ (tem
, Qsw
))
2904 #if defined (IXON) && defined (IXOFF)
2905 attr
.c_iflag
|= (IXON
| IXOFF
);
2907 error ("Software flowcontrol (XON/XOFF) not supported");
2910 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2912 /* Activate configuration. */
2913 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2915 report_file_error ("Failed tcsetattr", Qnil
);
2917 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2918 pset_childp (p
, childp2
);
2920 #endif /* not DOS_NT */
2922 /* System depended enumeration of and access to system processes a-la ps(1). */
2926 /* Process enumeration and access via /proc. */
2929 list_system_processes (void)
2931 Lisp_Object procdir
, match
, proclist
, next
;
2934 /* For every process on the system, there's a directory in the
2935 "/proc" pseudo-directory whose name is the numeric ID of that
2937 procdir
= build_string ("/proc");
2938 match
= build_string ("[0-9]+");
2939 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, false, Qnil
);
2941 /* `proclist' gives process IDs as strings. Destructively convert
2942 each string into a number. */
2943 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2946 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2949 /* directory_files_internal returns the files in reverse order; undo
2951 proclist
= Fnreverse (proclist
);
2955 #elif defined DARWIN_OS || defined __FreeBSD__
2958 list_system_processes (void)
2961 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2963 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2966 struct kinfo_proc
*procs
;
2969 Lisp_Object proclist
= Qnil
;
2971 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2974 procs
= xmalloc (len
);
2975 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2981 len
/= sizeof (struct kinfo_proc
);
2982 for (i
= 0; i
< len
; i
++)
2985 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2987 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2996 /* The WINDOWSNT implementation is in w32.c.
2997 The MSDOS implementation is in dosfns.c. */
2998 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3001 list_system_processes (void)
3006 #endif /* !defined (WINDOWSNT) */
3008 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3009 static struct timespec
3010 time_from_jiffies (unsigned long long tval
, long hz
)
3012 unsigned long long s
= tval
/ hz
;
3013 unsigned long long frac
= tval
% hz
;
3016 if (TYPE_MAXIMUM (time_t) < s
)
3018 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
3019 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
3020 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
3023 /* This is reachable only in the unlikely case that HZ * HZ
3024 exceeds ULLONG_MAX. It calculates an approximation that is
3025 guaranteed to be in range. */
3026 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
3027 + (hz
% TIMESPEC_RESOLUTION
!= 0));
3028 ns
= frac
/ hz_per_ns
;
3031 return make_timespec (s
, ns
);
3035 ltime_from_jiffies (unsigned long long tval
, long hz
)
3037 struct timespec t
= time_from_jiffies (tval
, hz
);
3038 return make_lisp_time (t
);
3041 static struct timespec
3045 struct timespec up
= make_timespec (0, 0);
3048 fup
= emacs_fopen ("/proc/uptime", "r");
3052 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
3053 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
3055 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
3056 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
3057 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
3060 if (TYPE_MAXIMUM (time_t) < upsec
)
3062 upsec
= TYPE_MAXIMUM (time_t);
3063 upfrac
= TIMESPEC_RESOLUTION
- 1;
3067 int upfraclen
= upfrac_end
- upfrac_start
;
3068 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3070 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3072 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3074 up
= make_timespec (upsec
, upfrac
);
3083 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3084 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3087 procfs_ttyname (int rdev
)
3090 char name
[PATH_MAX
];
3093 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3099 unsigned long minor_beg
, minor_end
;
3100 char minor
[25]; /* 2 32-bit numbers + dash */
3103 for (; !feof_unlocked (fdev
) && !ferror_unlocked (fdev
); name
[0] = 0)
3105 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3106 && major
== MAJOR (rdev
))
3108 minor_beg
= strtoul (minor
, &endp
, 0);
3110 minor_end
= minor_beg
;
3111 else if (*endp
== '-')
3112 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3116 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3118 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3126 return build_string (name
);
3130 procfs_get_total_memory (void)
3133 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3137 fmem
= emacs_fopen ("/proc/meminfo", "r");
3141 uintmax_t entry_value
;
3145 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3148 retval
= entry_value
;
3153 while ((c
= getc_unlocked (fmem
)) != EOF
&& c
!= '\n')
3171 system_process_attributes (Lisp_Object pid
)
3173 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3177 long clocks_per_sec
;
3179 char procbuf
[1025], *p
, *q
;
3182 static char const default_cmd
[] = "???";
3183 const char *cmd
= default_cmd
;
3184 int cmdsize
= sizeof default_cmd
- 1;
3185 char *cmdline
= NULL
;
3186 ptrdiff_t cmdline_size
;
3189 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3192 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3193 long priority
, niceness
, rss
;
3194 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3195 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3197 Lisp_Object attrs
= Qnil
;
3198 Lisp_Object decoded_cmd
;
3201 CHECK_NUMBER_OR_FLOAT (pid
);
3202 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3203 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3204 if (stat (procfn
, &st
) < 0)
3209 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3211 pw
= getpwuid (uid
);
3214 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3217 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3219 gr
= getgrgid (gid
);
3222 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3224 count
= SPECPDL_INDEX ();
3225 strcpy (fn
, procfn
);
3226 procfn_end
= fn
+ strlen (fn
);
3227 strcpy (procfn_end
, "/stat");
3228 fd
= emacs_open (fn
, O_RDONLY
, 0);
3233 record_unwind_protect_int (close_file_unwind
, fd
);
3234 nread
= emacs_read_quit (fd
, procbuf
, sizeof procbuf
- 1);
3238 procbuf
[nread
] = '\0';
3241 p
= strchr (p
, '(');
3244 q
= strrchr (p
+ 1, ')');
3254 /* Command name is encoded in locale-coding-system; decode it. */
3255 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3256 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3257 Vlocale_coding_system
, 0);
3258 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3260 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3261 utime stime cutime cstime priority nice thcount . start vsize rss */
3263 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3264 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3265 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3266 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3267 &u_time
, &s_time
, &cutime
, &cstime
,
3268 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3273 state_str
[1] = '\0';
3274 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3275 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3276 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3277 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3278 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3279 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3280 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3281 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3282 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3284 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3286 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3287 if (clocks_per_sec
< 0)
3288 clocks_per_sec
= 100;
3289 attrs
= Fcons (Fcons (Qutime
,
3290 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3292 attrs
= Fcons (Fcons (Qstime
,
3293 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3295 attrs
= Fcons (Fcons (Qtime
,
3296 ltime_from_jiffies (s_time
+ u_time
,
3299 attrs
= Fcons (Fcons (Qcutime
,
3300 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3302 attrs
= Fcons (Fcons (Qcstime
,
3303 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3305 attrs
= Fcons (Fcons (Qctime
,
3306 ltime_from_jiffies (cstime
+ cutime
,
3309 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3310 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3311 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3313 tnow
= current_timespec ();
3314 telapsed
= get_up_time ();
3315 tboot
= timespec_sub (tnow
, telapsed
);
3316 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3317 tstart
= timespec_add (tboot
, tstart
);
3318 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3319 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3321 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3322 telapsed
= timespec_sub (tnow
, tstart
);
3323 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3324 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3325 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3328 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3329 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3332 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3335 unbind_to (count
, Qnil
);
3338 strcpy (procfn_end
, "/cmdline");
3339 fd
= emacs_open (fn
, O_RDONLY
, 0);
3342 ptrdiff_t readsize
, nread_incr
;
3343 record_unwind_protect_int (close_file_unwind
, fd
);
3344 record_unwind_protect_nothing ();
3345 nread
= cmdline_size
= 0;
3349 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3350 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3352 /* Leave room even if every byte needs escaping below. */
3353 readsize
= (cmdline_size
>> 1) - nread
;
3355 nread_incr
= emacs_read_quit (fd
, cmdline
+ nread
, readsize
);
3356 nread
+= max (0, nread_incr
);
3358 while (nread_incr
== readsize
);
3362 /* We don't want trailing null characters. */
3363 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3366 /* Escape-quote whitespace and backslashes. */
3367 q
= cmdline
+ cmdline_size
;
3372 if (c_isspace (c
) || c
== '\\')
3376 nread
= cmdline
+ cmdline_size
- q
;
3381 nread
= cmdsize
+ 2;
3382 cmdline_size
= nread
+ 1;
3383 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3384 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3385 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3387 /* Command line is encoded in locale-coding-system; decode it. */
3388 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3389 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3390 Vlocale_coding_system
, 0);
3391 unbind_to (count
, Qnil
);
3392 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3398 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3400 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3401 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3402 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3403 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3404 #undef _FILE_OFFSET_BITS
3406 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3411 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3412 #define _FILE_OFFSET_BITS 64
3413 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3415 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3418 system_process_attributes (Lisp_Object pid
)
3420 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3425 struct psinfo pinfo
;
3431 Lisp_Object attrs
= Qnil
;
3432 Lisp_Object decoded_cmd
;
3435 CHECK_NUMBER_OR_FLOAT (pid
);
3436 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3437 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3438 if (stat (procfn
, &st
) < 0)
3443 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3445 pw
= getpwuid (uid
);
3448 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3451 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3453 gr
= getgrgid (gid
);
3456 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3458 count
= SPECPDL_INDEX ();
3459 strcpy (fn
, procfn
);
3460 procfn_end
= fn
+ strlen (fn
);
3461 strcpy (procfn_end
, "/psinfo");
3462 fd
= emacs_open (fn
, O_RDONLY
, 0);
3467 record_unwind_protect_int (close_file_unwind
, fd
);
3468 nread
= emacs_read_quit (fd
, &pinfo
, sizeof pinfo
);
3471 if (nread
== sizeof pinfo
)
3473 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3474 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3475 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3479 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3480 state_str
[1] = '\0';
3481 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3484 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3485 need to get a string from it. */
3487 /* FIXME: missing: Qtpgid */
3499 Are they available? */
3501 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3502 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3503 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3504 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3505 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3508 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3509 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3511 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3514 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3515 range 0 .. 2**15, representing 0.0 .. 1.0. */
3516 attrs
= Fcons (Fcons (Qpcpu
,
3517 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3519 attrs
= Fcons (Fcons (Qpmem
,
3520 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3523 AUTO_STRING (fname
, pinfo
.pr_fname
);
3524 decoded_cmd
= code_convert_string_norecord (fname
,
3525 Vlocale_coding_system
, 0);
3526 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3527 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3528 decoded_cmd
= code_convert_string_norecord (psargs
,
3529 Vlocale_coding_system
, 0);
3530 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3532 unbind_to (count
, Qnil
);
3536 #elif defined __FreeBSD__
3538 static struct timespec
3539 timeval_to_timespec (struct timeval t
)
3541 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3545 make_lisp_timeval (struct timeval t
)
3547 return make_lisp_time (timeval_to_timespec (t
));
3551 system_process_attributes (Lisp_Object pid
)
3554 int pagesize
= getpagesize ();
3555 unsigned long npages
;
3561 char args
[MAXPATHLEN
];
3562 struct timespec t
, now
;
3564 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3565 struct kinfo_proc proc
;
3566 size_t proclen
= sizeof proc
;
3568 Lisp_Object attrs
= Qnil
;
3569 Lisp_Object decoded_comm
;
3571 CHECK_NUMBER_OR_FLOAT (pid
);
3572 CONS_TO_INTEGER (pid
, int, proc_id
);
3575 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3578 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3581 pw
= getpwuid (proc
.ki_uid
);
3584 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3586 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3589 gr
= getgrgid (proc
.ki_svgid
);
3592 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3594 AUTO_STRING (comm
, proc
.ki_comm
);
3595 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3597 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3599 char state
[2] = {'\0', '\0'};
3600 switch (proc
.ki_stat
)
3622 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3625 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3626 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3627 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3630 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3633 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3635 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3636 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3637 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3638 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3639 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3641 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3643 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3645 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3646 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3647 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3649 attrs
= Fcons (Fcons (Qcutime
,
3650 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3652 attrs
= Fcons (Fcons (Qcstime
,
3653 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3655 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3656 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3657 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3659 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3661 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3662 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3663 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3664 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3665 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3668 now
= current_timespec ();
3669 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3670 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3672 len
= sizeof fscale
;
3673 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3678 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3680 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3681 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3682 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3686 len
= sizeof npages
;
3687 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3689 double pmem
= (proc
.ki_flag
& P_INMEM
3690 ? 100.0 * proc
.ki_rssize
/ npages
3692 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3695 mib
[2] = KERN_PROC_ARGS
;
3697 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3700 for (i
= 0; i
< len
; i
++)
3702 if (! args
[i
] && i
< len
- 1)
3706 AUTO_STRING (comm
, args
);
3707 decoded_comm
= code_convert_string_norecord (comm
,
3708 Vlocale_coding_system
, 0);
3710 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3716 #elif defined DARWIN_OS
3718 static struct timespec
3719 timeval_to_timespec (struct timeval t
)
3721 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3725 make_lisp_timeval (struct timeval t
)
3727 return make_lisp_time (timeval_to_timespec (t
));
3731 system_process_attributes (Lisp_Object pid
)
3737 struct timeval starttime
;
3738 struct timespec t
, now
;
3739 struct rusage
*rusage
;
3744 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3745 struct kinfo_proc proc
;
3746 size_t proclen
= sizeof proc
;
3748 Lisp_Object attrs
= Qnil
;
3749 Lisp_Object decoded_comm
;
3751 CHECK_NUMBER_OR_FLOAT (pid
);
3752 CONS_TO_INTEGER (pid
, int, proc_id
);
3755 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3758 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3759 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3762 pw
= getpwuid (uid
);
3765 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3767 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3768 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3771 gr
= getgrgid (gid
);
3774 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3776 decoded_comm
= (code_convert_string_norecord
3777 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3778 Vlocale_coding_system
, 0));
3780 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3782 char state
[2] = {'\0', '\0'};
3783 switch (proc
.kp_proc
.p_stat
)
3805 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3808 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3810 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3813 tdev
= proc
.kp_eproc
.e_tdev
;
3815 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3818 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3820 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3823 rusage
= proc
.kp_proc
.p_ru
;
3826 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3828 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3831 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3833 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3835 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3836 timeval_to_timespec (rusage
->ru_stime
));
3837 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3840 starttime
= proc
.kp_proc
.p_starttime
;
3841 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3842 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3844 now
= current_timespec ();
3845 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3846 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3851 /* The WINDOWSNT implementation is in w32.c.
3852 The MSDOS implementation is in dosfns.c. */
3853 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3856 system_process_attributes (Lisp_Object pid
)
3861 #endif /* !defined (WINDOWSNT) */
3863 /* Wide character string collation. */
3865 #ifdef __STDC_ISO_10646__
3867 # include <wctype.h>
3869 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3870 # include <locale.h>
3873 # define LC_COLLATE 0
3875 # ifndef LC_COLLATE_MASK
3876 # define LC_COLLATE_MASK 0
3881 # ifndef LC_CTYPE_MASK
3882 # define LC_CTYPE_MASK 0
3885 # ifndef HAVE_NEWLOCALE
3891 # define freelocale emacs_freelocale
3892 # define locale_t emacs_locale_t
3893 # define newlocale emacs_newlocale
3894 # define wcscoll_l emacs_wcscoll_l
3895 # define towlower_l emacs_towlower_l
3897 typedef char const *locale_t
;
3900 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3906 freelocale (locale_t loc
)
3911 emacs_setlocale (int category
, char const *locale
)
3913 # ifdef HAVE_SETLOCALE
3915 char *loc
= setlocale (category
, locale
);
3926 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3929 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3937 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3938 strcpy (oldcopy
, oldloc
);
3939 if (! emacs_setlocale (LC_COLLATE
, loc
))
3944 result
= wcscoll (a
, b
);
3946 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3957 towlower_l (wint_t wc
, locale_t loc
)
3960 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3965 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3966 strcpy (oldcopy
, oldloc
);
3967 if (emacs_setlocale (LC_CTYPE
, loc
))
3969 result
= towlower (wc
);
3970 emacs_setlocale (LC_COLLATE
, oldcopy
);
3980 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3981 Lisp_Object locale
, Lisp_Object ignore_case
)
3984 ptrdiff_t len
, i
, i_byte
;
3989 /* Convert byte stream to code points. */
3990 len
= SCHARS (s1
); i
= i_byte
= 0;
3991 SAFE_NALLOCA (p1
, 1, len
+ 1);
3993 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3996 len
= SCHARS (s2
); i
= i_byte
= 0;
3997 SAFE_NALLOCA (p2
, 1, len
+ 1);
3999 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
4002 if (STRINGP (locale
))
4004 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
4005 SSDATA (locale
), 0);
4007 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
4009 if (! NILP (ignore_case
))
4010 for (int i
= 1; i
< 3; i
++)
4012 wchar_t *p
= (i
== 1) ? p1
: p2
;
4014 *p
= towlower_l (*p
, loc
);
4018 res
= wcscoll_l (p1
, p2
, loc
);
4024 if (! NILP (ignore_case
))
4025 for (int i
= 1; i
< 3; i
++)
4027 wchar_t *p
= (i
== 1) ? p1
: p2
;
4033 res
= wcscoll (p1
, p2
);
4036 # ifndef HAVE_NEWLOCALE
4038 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
4041 error ("Invalid string for collation: %s", emacs_strerror (err
));
4047 #endif /* __STDC_ISO_10646__ */
4051 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4052 Lisp_Object locale
, Lisp_Object ignore_case
)
4055 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
4056 int res
, err
= errno
;
4059 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4061 error ("Invalid string for collation: %s", strerror (errno
));
4066 #endif /* WINDOWSNT */