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 <https://www.gnu.org/licenses/>. */
27 #endif /* HAVE_PWD_H */
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #ifdef HAVE_LINUX_FS_H
41 # include <linux/fs.h>
42 # include <sys/syscall.h>
46 # include <cygwin/fs.h>
49 #if defined DARWIN_OS || defined __FreeBSD__
50 # include <sys/sysctl.h>
54 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
55 'struct frame', so rename it. */
56 # define frame freebsd_frame
57 # include <sys/user.h>
64 #include <sys/socket.h>
66 #endif /* HAVE_SOCKETS */
70 #define write sys_write
72 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
75 #endif /* WINDOWSNT */
77 #include <sys/types.h>
81 /* Get SI_SRPC_DOMAIN, if it is available. */
82 #ifdef HAVE_SYS_SYSTEMINFO_H
83 #include <sys/systeminfo.h>
86 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
90 #include <sys/param.h>
97 #ifdef HAVE_SYS_UTSNAME_H
98 #include <sys/utsname.h>
100 #endif /* HAVE_SYS_UTSNAME_H */
102 #include "keyboard.h"
104 #include "termhooks.h"
105 #include "termchar.h"
106 #include "termopts.h"
111 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
112 do that during startup just to call gnutls_rnd. */
113 #if defined HAVE_GNUTLS && !defined WINDOWSNT
114 # include <gnutls/crypto.h>
116 # define emacs_gnutls_global_init() Qnil
117 # define gnutls_rnd(level, data, len) (-1)
122 /* In process.h which conflicts with the local copy. */
124 int _cdecl
_spawnlp (int, const char *, const char *, ...);
125 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
126 several prototypes of functions called below. */
127 #include <sys/socket.h>
130 #include "syssignal.h"
133 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
135 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
138 /* Declare here, including term.h is problematic on some systems. */
139 extern void tputs (const char *, int, int (*)(int));
141 static const int baud_convert
[] =
143 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
144 1800, 2400, 4800, 9600, 19200, 38400
147 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
148 # include <sys/personality.h>
150 /* Disable address randomization in the current process. Return true
151 if addresses were randomized but this has been disabled, false
154 disable_address_randomization (void)
156 int pers
= personality (0xffffffff);
159 int desired_pers
= pers
| ADDR_NO_RANDOMIZE
;
161 /* Call 'personality' twice, to detect buggy platforms like WSL
162 where 'personality' always returns 0. */
163 return (pers
!= desired_pers
164 && personality (desired_pers
) == pers
165 && personality (0xffffffff) == desired_pers
);
169 /* Execute the program in FILE, with argument vector ARGV and environ
170 ENVP. Return an error number if unsuccessful. This is like execve
171 except it reenables ASLR in the executed program if necessary, and
172 on error it returns an error number rather than -1. */
174 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
176 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
177 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
178 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
179 if (change_personality
)
180 personality (pers
& ~ADDR_NO_RANDOMIZE
);
183 execve (file
, argv
, envp
);
186 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
187 if (change_personality
)
194 /* If FD is not already open, arrange for it to be open with FLAGS. */
196 force_open (int fd
, int flags
)
198 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
200 int n
= open (NULL_DEVICE
, flags
);
201 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
203 emacs_perror (NULL_DEVICE
);
209 /* Make sure stdin, stdout, and stderr are open to something, so that
210 their file descriptors are not hijacked by later system calls. */
212 init_standard_fds (void)
214 /* Open stdin for *writing*, and stdout and stderr for *reading*.
215 That way, any attempt to do normal I/O will result in an error,
216 just as if the files were closed, and the file descriptors will
217 not be reused by later opens. */
218 force_open (STDIN_FILENO
, O_WRONLY
);
219 force_open (STDOUT_FILENO
, O_RDONLY
);
220 force_open (STDERR_FILENO
, O_RDONLY
);
223 /* Return the current working directory. The result should be freed
224 with 'free'. Return NULL 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;
236 /* GNU/Linux get_current_dir_name can return a string starting
237 with "(unreachable)" (Bug#27871). */
238 char *wd
= get_current_dir_name ();
239 if (wd
&& ! (IS_DIRECTORY_SEP (*wd
) || (*wd
&& IS_DEVICE_SEP (wd
[1]))))
250 char *pwd
= getenv ("PWD");
251 struct stat dotstat
, pwdstat
;
252 /* If PWD is accurate, use it instead of calling getcwd. PWD is
253 sometimes a nicer name, and using it may avoid a fatal error if a
254 parent directory is searchable but not readable. */
256 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
257 && stat (pwd
, &pwdstat
) == 0
258 && stat (".", &dotstat
) == 0
259 && dotstat
.st_ino
== pwdstat
.st_ino
260 && dotstat
.st_dev
== pwdstat
.st_dev
262 && strlen (pwd
) < MAXPATHLEN
266 buf
= malloc (strlen (pwd
) + 1);
273 size_t buf_size
= 1024;
274 buf
= malloc (buf_size
);
279 if (getcwd (buf
, buf_size
) == buf
)
283 int tmp_errno
= errno
;
289 buf
= realloc (buf
, buf_size
);
298 /* Discard pending input on all input descriptors. */
301 discard_tty_input (void)
304 struct emacs_tty buf
;
309 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
310 while (dos_keyread () != -1)
312 #else /* not MSDOS */
314 struct tty_display_info
*tty
;
315 for (tty
= tty_list
; tty
; tty
= tty
->next
)
317 if (tty
->input
) /* Is the device suspended? */
319 emacs_get_tty (fileno (tty
->input
), &buf
);
320 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
324 #endif /* not MSDOS */
325 #endif /* not WINDOWSNT */
331 /* Arrange for character C to be read as the next input from
333 XXX What if we have multiple ttys?
339 if (! (FRAMEP (selected_frame
)
340 && FRAME_LIVE_P (XFRAME (selected_frame
))
341 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
344 /* Should perhaps error if in batch mode */
346 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
347 #else /* no TIOCSTI */
348 error ("Cannot stuff terminal input characters in this version of Unix");
349 #endif /* no TIOCSTI */
355 init_baud_rate (int fd
)
365 #else /* not DOS_NT */
370 emacs_ospeed
= cfgetospeed (&sg
);
371 #endif /* not DOS_NT */
374 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
375 ? baud_convert
[emacs_ospeed
] : 9600);
384 /* Wait for the subprocess with process id CHILD to terminate or change status.
385 CHILD must be a child process that has not been reaped.
386 If STATUS is non-null, store the waitpid-style exit status into *STATUS
387 and tell wait_reading_process_output that it needs to look around.
388 Use waitpid-style OPTIONS when waiting.
389 If INTERRUPTIBLE, this function is interruptible by a signal.
391 Return CHILD if successful, 0 if no status is available, and a
392 negative value (setting errno) if waitpid is buggy. */
394 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
398 /* Invoke waitpid only with a known process ID; do not invoke
399 waitpid with a nonpositive argument. Otherwise, Emacs might
400 reap an unwanted process by mistake. For example, invoking
401 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
402 so that another thread running glib won't find them. */
407 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
412 pid
= waitpid (child
, status
, options
);
417 /* Most likely, waitpid is buggy and the operating system
418 lost track of the child somehow. Return -1 and let the
419 caller try to figure things out. Possibly the bug could
420 cause Emacs to kill the wrong process. Oh well. */
425 /* If successful and status is requested, tell wait_reading_process_output
426 that it needs to wake up and look around. */
427 if (pid
&& status
&& input_available_clear_time
)
428 *input_available_clear_time
= make_timespec (0, 0);
433 /* Wait for the subprocess with process id CHILD to terminate.
434 CHILD must be a child process that has not been reaped.
435 If STATUS is non-null, store the waitpid-style exit status into *STATUS
436 and tell wait_reading_process_output that it needs to look around.
437 If INTERRUPTIBLE, this function is interruptible by a signal.
438 Return true if successful, false (setting errno) if CHILD cannot be
439 waited for because waitpid is buggy. */
441 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
443 return 0 <= get_child_status (child
, status
, 0, interruptible
);
446 /* Report whether the subprocess with process id CHILD has changed status.
447 Termination counts as a change of status.
448 CHILD must be a child process that has not been reaped.
449 If STATUS is non-null, store the waitpid-style exit status into *STATUS
450 and tell wait_reading_process_output that it needs to look around.
451 Use waitpid-style OPTIONS to check status, but do not wait.
453 Return CHILD if successful, 0 if no status is available because
454 the process's state has not changed. */
456 child_status_changed (pid_t child
, int *status
, int options
)
458 return get_child_status (child
, status
, WNOHANG
| options
, 0);
462 /* Set up the terminal at the other end of a pseudo-terminal that
463 we will be controlling an inferior through.
464 It should not echo or do line-editing, since that is done
465 in Emacs. No padding needed for insertion into an Emacs buffer. */
468 child_setup_tty (int out
)
473 emacs_get_tty (out
, &s
);
474 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
475 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
477 /* https://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
478 Some versions of GNU Hurd do not have FFDLY? */
480 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
481 /* No output delays */
483 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
484 /* No output delays */
487 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
488 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
490 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
493 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
496 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
498 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
499 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
500 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
501 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
504 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
507 #ifdef SIGNALS_VIA_CHARACTERS
508 /* the QUIT and INTR character are used in process_send_signal
509 so set them here to something useful. */
510 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
511 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
512 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
513 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
514 #endif /* not SIGNALS_VIA_CHARACTERS */
517 /* Also, PTY overloads NUL and BREAK.
518 don't ignore break, but don't signal either, so it looks like NUL. */
519 s
.main
.c_iflag
&= ~IGNBRK
;
520 s
.main
.c_iflag
&= ~BRKINT
;
521 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
522 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
523 would force it to 0377. That looks like duplicated code. */
524 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
527 /* We originally enabled ICANON (and set VEOF to 04), and then had
528 process.c send additional EOF chars to flush the output when faced
529 with long lines, but this leads to weird effects when the
530 subprocess has disabled ICANON and ends up seeing those spurious
531 extra EOFs. So we don't send EOFs any more in
532 process.c:send_process. First we tried to disable ICANON by
533 default, so if a subsprocess sets up ICANON, it's his problem (or
534 the Elisp package that talks to it) to deal with lines that are
535 too long. But this disables some features, such as the ability
536 to send EOF signals. So we re-enabled ICANON but there is no
537 more "send eof to flush" going on (which is wrong and unportable
538 in itself). The correct way to handle too much output is to
539 buffer what could not be written and then write it again when
540 select returns ok for writing. This has it own set of
541 problems. Write is now asynchronous, is that a problem? How much
542 do we buffer, and what do we do when that limit is reached? */
544 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
545 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
546 #if 0 /* These settings only apply to non-ICANON mode. */
547 s
.main
.c_cc
[VMIN
] = 1;
548 s
.main
.c_cc
[VTIME
] = 0;
551 emacs_set_tty (out
, &s
, 0);
552 #endif /* not WINDOWSNT */
554 #endif /* not MSDOS */
557 /* Record a signal code and the action for it. */
561 struct sigaction action
;
564 static void save_signal_handlers (struct save_signal
*);
565 static void restore_signal_handlers (struct save_signal
*);
567 /* Suspend the Emacs process; give terminal to its superior. */
575 /* On a system where suspending is not implemented,
576 instead fork a subshell and let it talk directly to the terminal
583 /* Fork a subshell. */
588 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
591 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
593 char oldwd
[MAX_UTF8_PATH
];
599 struct save_signal saved_handlers
[5];
600 char *str
= SSDATA (encode_current_directory ());
606 char *volatile str_volatile
= str
;
613 error ("Can't spawn subshell");
615 saved_handlers
[0].code
= SIGINT
;
616 saved_handlers
[1].code
= SIGQUIT
;
617 saved_handlers
[2].code
= SIGTERM
;
619 saved_handlers
[3].code
= SIGIO
;
620 saved_handlers
[4].code
= 0;
622 saved_handlers
[3].code
= 0;
626 save_signal_handlers (saved_handlers
);
633 #ifdef DOS_NT /* MW, Aug 1993 */
634 getcwd (oldwd
, sizeof oldwd
);
636 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
639 sh
= egetenv ("SHELL");
643 /* Use our buffer's default directory for the subshell. */
644 if (chdir (str
) != 0)
648 _exit (EXIT_CANCELED
);
652 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
654 char *epwd
= getenv ("PWD");
655 char old_pwd
[MAXPATHLEN
+1+4];
657 /* If PWD is set, pass it with corrected value. */
660 strcpy (old_pwd
, epwd
);
661 setenv ("PWD", str
, 1);
664 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
666 putenv (old_pwd
); /* restore previous value */
668 #else /* not MSDOS */
670 /* Waits for process completion */
671 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
672 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
674 write (1, "Can't execute subshell", 22);
675 #else /* not WINDOWSNT */
676 execlp (sh
, sh
, (char *) 0);
678 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
679 #endif /* not WINDOWSNT */
680 #endif /* not MSDOS */
683 /* Do this now if we did not do it before. */
685 save_signal_handlers (saved_handlers
);
689 wait_for_termination (pid
, &status
, 0);
691 restore_signal_handlers (saved_handlers
);
695 save_signal_handlers (struct save_signal
*saved_handlers
)
697 while (saved_handlers
->code
)
699 struct sigaction action
;
700 emacs_sigaction_init (&action
, SIG_IGN
);
701 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
707 restore_signal_handlers (struct save_signal
*saved_handlers
)
709 while (saved_handlers
->code
)
711 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
717 static int old_fcntl_flags
[FD_SETSIZE
];
724 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
725 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
726 interrupts_deferred
= 0;
735 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
749 sigemptyset (&unblocked
);
751 sigaddset (&unblocked
, SIGWINCH
);
753 sigaddset (&unblocked
, SIGIO
);
754 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
756 interrupts_deferred
= 0;
761 unrequest_sigio (void)
769 sigemptyset (&blocked
);
771 sigaddset (&blocked
, SIGWINCH
);
773 sigaddset (&blocked
, SIGIO
);
774 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
775 interrupts_deferred
= 1;
783 block_child_signal (sigset_t
*oldset
)
786 sigemptyset (&blocked
);
787 sigaddset (&blocked
, SIGCHLD
);
788 sigaddset (&blocked
, SIGINT
);
789 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
792 /* Unblock SIGCHLD. */
795 unblock_child_signal (sigset_t
const *oldset
)
797 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
802 block_interrupt_signal (sigset_t
*oldset
)
805 sigemptyset (&blocked
);
806 sigaddset (&blocked
, SIGINT
);
807 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
810 /* Restore previously saved signal mask. */
812 restore_signal_mask (sigset_t
const *oldset
)
814 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
819 /* Saving and restoring the process group of Emacs's terminal. */
821 /* The process group of which Emacs was a member when it initially
824 If Emacs was in its own process group (i.e. inherited_pgroup ==
825 getpid ()), then we know we're running under a shell with job
826 control (Emacs would never be run as part of a pipeline).
829 If Emacs was not in its own process group, then we know we're
830 running under a shell (or a caller) that doesn't know how to
831 separate itself from Emacs (like sh). Emacs must be in its own
832 process group in order to receive SIGIO correctly. In this
833 situation, we put ourselves in our own pgroup, forcibly set the
834 tty's pgroup to our pgroup, and make sure to restore and reinstate
835 the tty's pgroup just like any other terminal setting. If
836 inherited_group was not the tty's pgroup, then we'll get a
837 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
838 it goes foreground in the future, which is what should happen. */
840 static pid_t inherited_pgroup
;
843 init_foreground_group (void)
845 pid_t pgrp
= getpgrp ();
846 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
849 /* Block and unblock SIGTTOU. */
852 block_tty_out_signal (sigset_t
*oldset
)
856 sigemptyset (&blocked
);
857 sigaddset (&blocked
, SIGTTOU
);
858 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
863 unblock_tty_out_signal (sigset_t
const *oldset
)
866 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
870 /* Safely set a controlling terminal FD's process group to PGID.
871 If we are not in the foreground already, POSIX requires tcsetpgrp
872 to deliver a SIGTTOU signal, which would stop us. This is an
873 annoyance, so temporarily ignore the signal.
875 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
876 skip all this unless SIGTTOU is defined. */
878 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
883 block_tty_out_signal (&oldset
);
884 tcsetpgrp (fd
, pgid
);
885 unblock_tty_out_signal (&oldset
);
890 /* Split off the foreground process group to Emacs alone. When we are
891 in the foreground, but not started in our own process group,
892 redirect the tty device handle FD to point to our own process
893 group. FD must be the file descriptor of the controlling tty. */
895 narrow_foreground_group (int fd
)
897 if (inherited_pgroup
&& setpgid (0, 0) == 0)
898 tcsetpgrp_without_stopping (fd
, getpid ());
901 /* Set the tty to our original foreground group. */
903 widen_foreground_group (int fd
)
905 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
906 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
909 /* Getting and setting emacs_tty structures. */
911 /* Set *TC to the parameters associated with the terminal FD,
912 or clear it if the parameters are not available.
913 Return 0 on success, -1 on failure. */
915 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
917 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
918 memset (&settings
->main
, 0, sizeof (settings
->main
));
921 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
924 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
926 settings
->main
= console_mode
;
929 #endif /* WINDOWSNT */
932 /* We have those nifty POSIX tcmumbleattr functions. */
933 return tcgetattr (fd
, &settings
->main
);
938 /* Set the parameters of the tty on FD according to the contents of
939 *SETTINGS. If FLUSHP, discard input.
940 Return 0 if all went well, and -1 (setting errno) if anything failed. */
943 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
945 /* Set the primary parameters - baud rate, character size, etcetera. */
948 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
950 if (h
&& h
!= INVALID_HANDLE_VALUE
)
954 /* Assume the handle is open for input. */
956 FlushConsoleInputBuffer (h
);
957 new_mode
= settings
->main
;
958 SetConsoleMode (h
, new_mode
);
960 #endif /* WINDOWSNT */
963 /* We have those nifty POSIX tcmumbleattr functions.
964 William J. Smith <wjs@wiis.wang.com> writes:
965 "POSIX 1003.1 defines tcsetattr to return success if it was
966 able to perform any of the requested actions, even if some
967 of the requested actions could not be performed.
968 We must read settings back to ensure tty setup properly.
969 AIX requires this to keep tty from hanging occasionally." */
970 /* This make sure that we don't loop indefinitely in here. */
971 for (i
= 0 ; i
< 10 ; i
++)
972 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
983 memset (&new, 0, sizeof (new));
984 /* Get the current settings, and see if they're what we asked for. */
985 tcgetattr (fd
, &new);
986 /* We cannot use memcmp on the whole structure here because under
987 * aix386 the termios structure has some reserved field that may
990 if ( new.c_iflag
== settings
->main
.c_iflag
991 && new.c_oflag
== settings
->main
.c_oflag
992 && new.c_cflag
== settings
->main
.c_cflag
993 && new.c_lflag
== settings
->main
.c_lflag
994 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
1001 /* We have survived the tempest. */
1008 static int old_fcntl_owner
[FD_SETSIZE
];
1009 #endif /* F_SETOWN */
1011 /* This may also be defined in stdio,
1012 but if so, this does no harm,
1013 and using the same name avoids wasting the other one's space. */
1016 unsigned char _sobuf
[BUFSIZ
+8];
1018 char _sobuf
[BUFSIZ
];
1021 /* Initialize the terminal mode on all tty devices that are currently
1025 init_all_sys_modes (void)
1027 struct tty_display_info
*tty
;
1028 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1029 init_sys_modes (tty
);
1032 /* Initialize the terminal mode on the given tty device. */
1035 init_sys_modes (struct tty_display_info
*tty_out
)
1037 struct emacs_tty tty
;
1039 Lisp_Object terminal
;
1042 Vtty_erase_char
= Qnil
;
1047 if (!tty_out
->output
)
1048 return; /* The tty is suspended. */
1050 narrow_foreground_group (fileno (tty_out
->input
));
1052 if (! tty_out
->old_tty
)
1053 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1055 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1057 tty
= *tty_out
->old_tty
;
1059 #if !defined (DOS_NT)
1060 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1062 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1063 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1064 #ifdef INLCR /* I'm just being cautious,
1065 since I can't check how widespread INLCR is--rms. */
1066 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1069 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1071 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1072 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1074 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1076 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1077 if (tty_out
->flow_control
)
1079 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1081 tty
.main
.c_iflag
&= ~IXANY
;
1085 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1086 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1088 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1090 if (tty_out
->meta_key
)
1092 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1093 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1097 XSETTERMINAL(terminal
, tty_out
->terminal
);
1098 if (!NILP (Fcontrolling_tty_p (terminal
)))
1100 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1101 /* Set up C-g for both SIGQUIT and SIGINT.
1102 We don't know which we will get, but we handle both alike
1103 so which one it really gives us does not matter. */
1104 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1108 /* We normally don't get interrupt or quit signals from tty
1109 devices other than our controlling terminal; therefore,
1110 we must handle C-g as normal input. Unfortunately, this
1111 means that the interrupt and quit feature must be
1112 disabled on secondary ttys, or we would not even see the
1115 Note that even though emacsclient could have special code
1116 to pass SIGINT to Emacs, we should _not_ enable
1117 interrupt/quit keys for emacsclient frames. This means
1118 that we can't break out of loops in C code from a
1119 secondary tty frame, but we can always decide what
1120 display the C-g came from, which is more important from a
1121 usability point of view. (Consider the case when two
1122 people work together using the same Emacs instance.) */
1123 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1124 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1126 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1127 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1129 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1134 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1137 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1138 #endif /* V_DSUSP */
1139 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1140 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1143 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1146 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1147 #endif /* VREPRINT */
1149 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1150 #endif /* VWERASE */
1152 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1153 #endif /* VDISCARD */
1155 if (tty_out
->flow_control
)
1158 tty
.main
.c_cc
[VSTART
] = '\021';
1161 tty
.main
.c_cc
[VSTOP
] = '\023';
1167 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1170 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1175 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1176 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1177 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1178 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1179 if (tty_out
->flow_control
)
1182 tty
.main
.c_cc
[VSTART
] = '\021';
1185 tty
.main
.c_cc
[VSTOP
] = '\023';
1188 /* Also, PTY overloads NUL and BREAK.
1189 don't ignore break, but don't signal either, so it looks like NUL.
1190 This really serves a purpose only if running in an XTERM window
1191 or via TELNET or the like, but does no harm elsewhere. */
1192 tty
.main
.c_iflag
&= ~IGNBRK
;
1193 tty
.main
.c_iflag
&= ~BRKINT
;
1195 #endif /* not DOS_NT */
1197 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1198 if (!tty_out
->term_initted
)
1199 internal_terminal_init ();
1200 dos_ttraw (tty_out
);
1203 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1205 /* This code added to insure that, if flow-control is not to be used,
1206 we have an unlocked terminal at the start. */
1209 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1212 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1215 #if !defined (DOS_NT)
1217 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1222 if (interrupt_input
)
1224 old_fcntl_owner
[fileno (tty_out
->input
)] =
1225 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1226 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1227 init_sigio (fileno (tty_out
->input
));
1229 if (gpm_tty
== tty_out
)
1231 /* Arrange for mouse events to give us SIGIO signals. */
1232 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1233 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1234 init_sigio (gpm_fd
);
1236 #endif /* HAVE_GPM */
1238 #endif /* F_GETOWN */
1241 /* This symbol is defined on recent USG systems.
1242 Someone says without this call USG won't really buffer the file
1243 even with a call to setbuf. */
1244 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1246 setbuf (tty_out
->output
, (char *) _sobuf
);
1249 if (tty_out
->terminal
->set_terminal_modes_hook
)
1250 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1252 if (!tty_out
->term_initted
)
1254 Lisp_Object tail
, frame
;
1255 FOR_EACH_FRAME (tail
, frame
)
1257 /* XXX This needs to be revised. */
1258 if (FRAME_TERMCAP_P (XFRAME (frame
))
1259 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1260 init_frame_faces (XFRAME (frame
));
1264 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1266 /* We used to call "direct_output_forward_char(0)" here,
1267 but it's not clear why, since it may not do anything anyway. */
1271 Lisp_Object tail
, frame
;
1273 FOR_EACH_FRAME (tail
, frame
)
1275 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1276 || FRAME_MSDOS_P (XFRAME (frame
)))
1277 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1278 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1282 tty_out
->term_initted
= 1;
1285 /* Return true if safe to use tabs in output.
1286 At the time this is called, init_sys_modes has not been done yet. */
1289 tabs_safe_p (int fd
)
1291 struct emacs_tty etty
;
1293 emacs_get_tty (fd
, &etty
);
1296 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1297 #else /* not TABDLY */
1299 #endif /* not TABDLY */
1305 /* Discard echoing. */
1308 suppress_echo_on_tty (int fd
)
1310 struct emacs_tty etty
;
1312 emacs_get_tty (fd
, &etty
);
1314 /* Set raw input mode. */
1317 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1318 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1319 #endif /* ! WINDOWSNT */
1320 emacs_set_tty (fd
, &etty
, 0);
1323 /* Get terminal size from system.
1324 Store number of lines into *HEIGHTP and width into *WIDTHP.
1325 We store 0 if there's no valid information. */
1328 get_tty_size (int fd
, int *widthp
, int *heightp
)
1330 #if defined TIOCGWINSZ
1333 struct winsize size
;
1335 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1336 *widthp
= *heightp
= 0;
1339 *widthp
= size
.ws_col
;
1340 *heightp
= size
.ws_row
;
1343 #elif defined TIOCGSIZE
1345 /* SunOS - style. */
1346 struct ttysize size
;
1348 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1349 *widthp
= *heightp
= 0;
1352 *widthp
= size
.ts_cols
;
1353 *heightp
= size
.ts_lines
;
1356 #elif defined WINDOWSNT
1358 CONSOLE_SCREEN_BUFFER_INFO info
;
1359 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1361 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1362 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1365 *widthp
= *heightp
= 0;
1369 *widthp
= ScreenCols ();
1370 *heightp
= ScreenRows ();
1372 #else /* system doesn't know size */
1380 /* Set the logical window size associated with descriptor FD
1381 to HEIGHT and WIDTH. This is used mainly with ptys.
1382 Return a negative value on failure. */
1385 set_window_size (int fd
, int height
, int width
)
1390 struct winsize size
;
1391 size
.ws_row
= height
;
1392 size
.ws_col
= width
;
1394 return ioctl (fd
, TIOCSWINSZ
, &size
);
1399 /* SunOS - style. */
1400 struct ttysize size
;
1401 size
.ts_lines
= height
;
1402 size
.ts_cols
= width
;
1404 return ioctl (fd
, TIOCGSIZE
, &size
);
1407 #endif /* not SunOS-style */
1408 #endif /* not BSD-style */
1413 /* Prepare all terminal devices for exiting Emacs. */
1416 reset_all_sys_modes (void)
1418 struct tty_display_info
*tty
;
1419 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1420 reset_sys_modes (tty
);
1423 /* Prepare the terminal for closing it; move the cursor to the
1424 bottom of the frame, turn off interrupt-driven I/O, etc. */
1427 reset_sys_modes (struct tty_display_info
*tty_out
)
1431 fflush_unlocked (stdout
);
1434 if (!tty_out
->term_initted
)
1437 if (!tty_out
->output
)
1438 return; /* The tty is suspended. */
1440 /* Go to and clear the last line of the terminal. */
1442 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1444 /* Code adapted from tty_clear_end_of_line. */
1445 if (tty_out
->TS_clr_line
)
1447 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1450 { /* have to do it the hard way */
1451 tty_turn_off_insert (tty_out
);
1453 for (int i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1454 fputc_unlocked (' ', tty_out
->output
);
1457 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1458 fflush_unlocked (tty_out
->output
);
1460 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1461 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1463 /* Avoid possible loss of output when changing terminal modes. */
1464 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1469 if (interrupt_input
)
1471 reset_sigio (fileno (tty_out
->input
));
1472 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1473 old_fcntl_owner
[fileno (tty_out
->input
)]);
1475 #endif /* F_SETOWN */
1476 fcntl (fileno (tty_out
->input
), F_SETFL
,
1477 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1480 if (tty_out
->old_tty
)
1481 while (emacs_set_tty (fileno (tty_out
->input
),
1482 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1485 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1489 widen_foreground_group (fileno (tty_out
->input
));
1494 /* Set up the proper status flags for use of a pty. */
1499 /* I'm told that TOICREMOTE does not mean control chars
1500 "can't be sent" but rather that they don't have
1501 input-editing or signaling effects.
1502 That should be good, because we have other ways
1503 to do those things in Emacs.
1504 However, telnet mode seems not to work on 4.2.
1505 So TIOCREMOTE is turned off now. */
1507 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1508 will hang. In particular, the "timeout" feature (which
1509 causes a read to return if there is no data available)
1510 does this. Also it is known that telnet mode will hang
1511 in such a way that Emacs must be stopped (perhaps this
1512 is the same problem).
1514 If TIOCREMOTE is turned off, then there is a bug in
1515 hp-ux which sometimes loses data. Apparently the
1516 code which blocks the master process when the internal
1517 buffer fills up does not work. Other than this,
1518 though, everything else seems to work fine.
1520 Since the latter lossage is more benign, we may as well
1521 lose that way. -- cph */
1523 #if defined (UNIX98_PTYS)
1526 ioctl (fd
, FIONBIO
, &on
);
1531 #endif /* HAVE_PTYS */
1534 init_system_name (void)
1538 /* Set system-name to nil so that the build is deterministic. */
1539 Vsystem_name
= Qnil
;
1542 char *hostname_alloc
= NULL
;
1544 #ifndef HAVE_GETHOSTNAME
1547 hostname
= uts
.nodename
;
1548 #else /* HAVE_GETHOSTNAME */
1549 char hostname_buf
[256];
1550 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1551 hostname
= hostname_buf
;
1553 /* Try to get the host name; if the buffer is too short, try
1554 again. Apparently, the only indication gethostname gives of
1555 whether the buffer was large enough is the presence or absence
1556 of a '\0' in the string. Eech. */
1559 gethostname (hostname
, hostname_size
- 1);
1560 hostname
[hostname_size
- 1] = '\0';
1562 /* Was the buffer large enough for the '\0'? */
1563 if (strlen (hostname
) < hostname_size
- 1)
1566 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1567 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1569 #endif /* HAVE_GETHOSTNAME */
1571 for (p
= hostname
; *p
; p
++)
1572 if (*p
== ' ' || *p
== '\t')
1574 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1575 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1576 Vsystem_name
= build_string (hostname
);
1577 xfree (hostname_alloc
);
1580 sigset_t empty_mask
;
1582 static struct sigaction process_fatal_action
;
1585 emacs_sigaction_flags (void)
1588 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1589 'select') to reset their timeout on some platforms (e.g.,
1590 HP-UX 11), which is not what we want. Also, when Emacs is
1591 interactive, we don't want SA_RESTART because we need to poll
1592 for pending input so we need long-running syscalls to be interrupted
1593 after a signal that sets pending_signals.
1595 Non-interactive keyboard input goes through stdio, where we
1596 always want restartable system calls. */
1603 /* Store into *ACTION a signal action suitable for Emacs, with handler
1606 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1608 sigemptyset (&action
->sa_mask
);
1610 /* When handling a signal, block nonfatal system signals that are caught
1611 by Emacs. This makes race conditions less likely. */
1612 sigaddset (&action
->sa_mask
, SIGALRM
);
1614 sigaddset (&action
->sa_mask
, SIGCHLD
);
1617 sigaddset (&action
->sa_mask
, SIGDANGER
);
1619 #ifdef PROFILER_CPU_SUPPORT
1620 sigaddset (&action
->sa_mask
, SIGPROF
);
1623 sigaddset (&action
->sa_mask
, SIGWINCH
);
1625 if (! noninteractive
)
1627 sigaddset (&action
->sa_mask
, SIGINT
);
1628 sigaddset (&action
->sa_mask
, SIGQUIT
);
1630 sigaddset (&action
->sa_mask
, SIGIO
);
1634 action
->sa_handler
= handler
;
1635 action
->sa_flags
= emacs_sigaction_flags ();
1638 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1639 pthread_t main_thread_id
;
1642 /* SIG has arrived at the current process. Deliver it to the main
1643 thread, which should handle it with HANDLER. (Delivering the
1644 signal to some other thread might not work if the other thread is
1647 If we are on the main thread, handle the signal SIG with HANDLER.
1648 Otherwise, redirect the signal to the main thread, blocking it from
1649 this thread. POSIX says any thread can receive a signal that is
1650 associated with a process, process group, or asynchronous event.
1651 On GNU/Linux the main thread typically gets a process signal unless
1652 it's blocked, but other systems (FreeBSD at least) can deliver the
1653 signal to other threads. */
1655 deliver_process_signal (int sig
, signal_handler_t handler
)
1657 /* Preserve errno, to avoid race conditions with signal handlers that
1658 might change errno. Races can occur even in single-threaded hosts. */
1659 int old_errno
= errno
;
1661 bool on_main_thread
= true;
1662 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1663 if (! pthread_equal (pthread_self (), main_thread_id
))
1666 sigemptyset (&blocked
);
1667 sigaddset (&blocked
, sig
);
1668 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1669 pthread_kill (main_thread_id
, sig
);
1670 on_main_thread
= false;
1679 /* Static location to save a fatal backtrace in a thread.
1680 FIXME: If two subsidiary threads fail simultaneously, the resulting
1681 backtrace may be garbage. */
1682 enum { BACKTRACE_LIMIT_MAX
= 500 };
1683 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1684 static int thread_backtrace_npointers
;
1686 /* SIG has arrived at the current thread.
1687 If we are on the main thread, handle the signal SIG with HANDLER.
1688 Otherwise, this is a fatal error in the handling thread. */
1690 deliver_thread_signal (int sig
, signal_handler_t handler
)
1692 int old_errno
= errno
;
1694 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1695 if (! pthread_equal (pthread_self (), main_thread_id
))
1697 thread_backtrace_npointers
1698 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1699 sigaction (sig
, &process_fatal_action
, 0);
1700 pthread_kill (main_thread_id
, sig
);
1702 /* Avoid further damage while the main thread is exiting. */
1704 sigsuspend (&empty_mask
);
1712 #if !HAVE_DECL_SYS_SIGLIST
1714 # ifdef _sys_siglist
1715 # define sys_siglist _sys_siglist
1716 # elif HAVE_DECL___SYS_SIGLIST
1717 # define sys_siglist __sys_siglist
1719 # define sys_siglist my_sys_siglist
1720 static char const *sys_siglist
[NSIG
];
1725 # define sys_siglist_entries _sys_nsig
1727 # define sys_siglist_entries NSIG
1730 /* Handle bus errors, invalid instruction, etc. */
1732 handle_fatal_signal (int sig
)
1734 terminate_due_to_signal (sig
, 40);
1738 deliver_fatal_signal (int sig
)
1740 deliver_process_signal (sig
, handle_fatal_signal
);
1744 deliver_fatal_thread_signal (int sig
)
1746 deliver_thread_signal (sig
, handle_fatal_signal
);
1749 static _Noreturn
void
1750 handle_arith_signal (int sig
)
1752 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1753 xsignal0 (Qarith_error
);
1756 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1758 /* Alternate stack used by SIGSEGV handler below. */
1760 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1763 /* Return true if SIGINFO indicates a stack overflow. */
1766 stack_overflow (siginfo_t
*siginfo
)
1768 if (!attempt_stack_overflow_recovery
)
1771 /* In theory, a more-accurate heuristic can be obtained by using
1772 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1773 and pthread_attr_getguardsize to find the location and size of the
1774 guard area. In practice, though, these functions are so hard to
1775 use reliably that they're not worth bothering with. E.g., see:
1776 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1777 Other operating systems also have problems, e.g., Solaris's
1778 stack_violation function is tailor-made for this problem, but it
1779 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1781 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1787 /* The faulting address. */
1788 char *addr
= siginfo
->si_addr
;
1792 /* The known top and bottom of the stack. The actual stack may
1793 extend a bit beyond these boundaries. */
1794 char *bot
= stack_bottom
;
1795 char *top
= current_thread
->stack_top
;
1797 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1798 of the known stack divided by the size of the guard area past the
1799 end of the stack top. The heuristic is that a bad address is
1800 considered to be a stack overflow if it occurs within
1801 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1802 stack. This heuristic is not exactly correct but it's good
1803 enough in practice. */
1804 enum { LG_STACK_HEURISTIC
= 8 };
1807 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1809 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1813 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1816 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1818 /* Hard GC error may lead to stack overflow caused by
1819 too nested calls to mark_object. No way to survive. */
1820 bool fatal
= gc_in_progress
;
1822 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1823 if (!fatal
&& !pthread_equal (pthread_self (), main_thread_id
))
1827 if (!fatal
&& stack_overflow (siginfo
))
1828 siglongjmp (return_to_command_loop
, 1);
1830 /* Otherwise we can't do anything with this. */
1831 deliver_fatal_thread_signal (sig
);
1834 /* Return true if we have successfully set up SIGSEGV handler on alternate
1835 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1840 struct sigaction sa
;
1843 ss
.ss_sp
= sigsegv_stack
;
1844 ss
.ss_size
= sizeof (sigsegv_stack
);
1846 if (sigaltstack (&ss
, NULL
) < 0)
1849 sigfillset (&sa
.sa_mask
);
1850 sa
.sa_sigaction
= handle_sigsegv
;
1851 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1852 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1855 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1863 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1866 deliver_arith_signal (int sig
)
1868 deliver_thread_signal (sig
, handle_arith_signal
);
1873 /* Handler for SIGDANGER. */
1875 handle_danger_signal (int sig
)
1877 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1879 /* It might be unsafe to call do_auto_save now. */
1880 force_auto_save_soon ();
1884 deliver_danger_signal (int sig
)
1886 deliver_process_signal (sig
, handle_danger_signal
);
1890 /* Treat SIG as a terminating signal, unless it is already ignored and
1891 we are in --batch mode. Among other things, this makes nohup work. */
1893 maybe_fatal_sig (int sig
)
1895 bool catch_sig
= !noninteractive
;
1898 struct sigaction old_action
;
1899 sigaction (sig
, 0, &old_action
);
1900 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1903 sigaction (sig
, &process_fatal_action
, 0);
1907 init_signals (bool dumping
)
1909 struct sigaction thread_fatal_action
;
1910 struct sigaction action
;
1912 sigemptyset (&empty_mask
);
1914 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1915 main_thread_id
= pthread_self ();
1918 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1921 sys_siglist
[SIGABRT
] = "Aborted";
1923 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1925 sys_siglist
[SIGALRM
] = "Alarm clock";
1927 sys_siglist
[SIGBUS
] = "Bus error";
1930 sys_siglist
[SIGCHLD
] = "Child status changed";
1933 sys_siglist
[SIGCONT
] = "Continued";
1936 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1939 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1942 sys_siglist
[SIGEMT
] = "Emulation trap";
1944 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1946 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1949 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1951 sys_siglist
[SIGHUP
] = "Hangup";
1952 sys_siglist
[SIGILL
] = "Illegal instruction";
1953 sys_siglist
[SIGINT
] = "Interrupt";
1955 sys_siglist
[SIGIO
] = "I/O possible";
1958 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1961 sys_siglist
[SIGIOT
] = "IOT trap";
1963 sys_siglist
[SIGKILL
] = "Killed";
1965 sys_siglist
[SIGLOST
] = "Resource lost";
1968 sys_siglist
[SIGLWP
] = "SIGLWP";
1971 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1974 sys_siglist
[SIGWIND
] = "SIGPHONE";
1976 sys_siglist
[SIGPIPE
] = "Broken pipe";
1978 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1981 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1984 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1987 sys_siglist
[SIGPWR
] = "Power-fail restart";
1989 sys_siglist
[SIGQUIT
] = "Quit";
1991 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1994 sys_siglist
[SIGSAK
] = "Secure attention";
1996 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1998 sys_siglist
[SIGSOUND
] = "Sound completed";
2001 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
2004 sys_siglist
[SIGSTP
] = "Stopped (user)";
2007 sys_siglist
[SIGSYS
] = "Bad argument to system call";
2009 sys_siglist
[SIGTERM
] = "Terminated";
2011 sys_siglist
[SIGTHAW
] = "SIGTHAW";
2014 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
2017 sys_siglist
[SIGTSTP
] = "Stopped (user)";
2020 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
2023 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
2026 sys_siglist
[SIGURG
] = "Urgent I/O condition";
2029 sys_siglist
[SIGUSR1
] = "User defined signal 1";
2032 sys_siglist
[SIGUSR2
] = "User defined signal 2";
2035 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
2038 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
2041 sys_siglist
[SIGWINCH
] = "Window size changed";
2044 sys_siglist
[SIGWIND
] = "SIGWIND";
2047 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2050 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2053 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2055 /* Don't alter signal handlers if dumping. On some machines,
2056 changing signal handlers sets static data that would make signals
2057 fail to work right when the dumped Emacs is run. */
2061 sigfillset (&process_fatal_action
.sa_mask
);
2062 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2063 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2065 sigfillset (&thread_fatal_action
.sa_mask
);
2066 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2067 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2069 /* SIGINT may need special treatment on MS-Windows. See
2070 https://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2071 Please update the doc of kill-emacs, kill-emacs-hook, and
2072 NEWS if you change this. */
2074 maybe_fatal_sig (SIGHUP
);
2075 maybe_fatal_sig (SIGINT
);
2076 maybe_fatal_sig (SIGTERM
);
2078 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2079 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2080 to behave more like typical batch applications do. */
2081 if (! noninteractive
)
2082 signal (SIGPIPE
, SIG_IGN
);
2084 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2085 sigaction (SIGILL
, &thread_fatal_action
, 0);
2086 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2088 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2089 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2090 interpreter's floating point operations, so treat SIGFPE as an
2091 arith-error if it arises in the main thread. */
2092 if (IEEE_FLOATING_POINT
)
2093 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2096 emacs_sigaction_init (&action
, deliver_arith_signal
);
2097 sigaction (SIGFPE
, &action
, 0);
2101 add_user_signal (SIGUSR1
, "sigusr1");
2104 add_user_signal (SIGUSR2
, "sigusr2");
2106 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2108 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2111 sigaction (SIGORE
, &thread_fatal_action
, 0);
2114 sigaction (SIGUME
, &thread_fatal_action
, 0);
2117 sigaction (SIGDLK
, &process_fatal_action
, 0);
2120 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2123 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2126 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2129 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2131 if (!init_sigsegv ())
2132 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2134 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2136 sigaction (SIGTERM
, &process_fatal_action
, 0);
2138 signal (SIGPROF
, SIG_IGN
);
2141 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2144 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2147 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2151 /* This just means available memory is getting low. */
2152 emacs_sigaction_init (&action
, deliver_danger_signal
);
2153 sigaction (SIGDANGER
, &action
, 0);
2156 /* AIX-specific signals. */
2158 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2161 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2164 sigaction (SIGMSG
, &process_fatal_action
, 0);
2167 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2170 sigaction (SIGSAK
, &process_fatal_action
, 0);
2173 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2176 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2186 /* Figure out how many bits the system's random number generator uses.
2187 `random' and `lrand48' are assumed to return 31 usable bits.
2188 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2189 so we'll shift it and treat it like the 15-bit USG `rand'. */
2193 # define RAND_BITS 31
2194 # else /* !HAVE_RANDOM */
2195 # ifdef HAVE_LRAND48
2196 # define RAND_BITS 31
2197 # define random lrand48
2198 # else /* !HAVE_LRAND48 */
2199 # define RAND_BITS 15
2200 # if RAND_MAX == 32767
2201 # define random rand
2202 # else /* RAND_MAX != 32767 */
2203 # if RAND_MAX == 2147483647
2204 # define random() (rand () >> 16)
2205 # else /* RAND_MAX != 2147483647 */
2207 # define random rand
2209 # define random() (rand () >> 16)
2211 # endif /* RAND_MAX != 2147483647 */
2212 # endif /* RAND_MAX != 32767 */
2213 # endif /* !HAVE_LRAND48 */
2214 # endif /* !HAVE_RANDOM */
2215 #endif /* !RAND_BITS */
2218 typedef unsigned int random_seed
;
2219 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2220 #elif defined HAVE_LRAND48
2221 /* Although srand48 uses a long seed, this is unsigned long to avoid
2222 undefined behavior on signed integer overflow in init_random. */
2223 typedef unsigned long int random_seed
;
2224 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2226 typedef unsigned int random_seed
;
2227 static void set_random_seed (random_seed arg
) { srand (arg
); }
2231 seed_random (void *seed
, ptrdiff_t seed_size
)
2233 random_seed arg
= 0;
2234 unsigned char *argp
= (unsigned char *) &arg
;
2235 unsigned char *seedp
= seed
;
2236 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2237 argp
[i
% sizeof arg
] ^= seedp
[i
];
2238 set_random_seed (arg
);
2245 bool success
= false;
2247 /* First, try seeding the PRNG from the operating system's entropy
2248 source. This approach is both fast and secure. */
2250 success
= w32_init_random (&v
, sizeof v
) == 0;
2252 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2255 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2260 /* If that didn't work, try using GnuTLS, which is secure, but on
2261 some systems, can be somewhat slow. */
2263 success
= EQ (emacs_gnutls_global_init (), Qt
)
2264 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2266 /* If _that_ didn't work, just use the current time value and PID.
2267 It's at least better than XKCD 221. */
2270 struct timespec t
= current_timespec ();
2271 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2274 set_random_seed (v
);
2278 * Return a nonnegative random integer out of whatever we've got.
2279 * It contains enough bits to make a random (signed) Emacs fixnum.
2280 * This suffices even for a 64-bit architecture with a 15-bit rand.
2287 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2288 val
= (random () ^ (val
<< RAND_BITS
)
2289 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2290 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2291 return val
& INTMASK
;
2294 #ifndef HAVE_SNPRINTF
2295 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2297 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2299 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2300 ptrdiff_t nbytes
= size
- 1;
2305 va_start (ap
, format
);
2306 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2310 if (nbytes
== size
- 1)
2312 /* Calculate the length of the string that would have been created
2313 had the buffer been large enough. */
2314 char stackbuf
[4000];
2316 ptrdiff_t bsize
= sizeof stackbuf
;
2317 va_start (ap
, format
);
2318 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2324 if (INT_MAX
< nbytes
)
2337 /* If a backtrace is available, output the top lines of it to stderr.
2338 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2339 This function may be called from a signal handler, so it should
2340 not invoke async-unsafe functions like malloc.
2342 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2343 but do not output anything. This avoids some problems that can
2344 otherwise occur if the malloc arena is corrupted before 'backtrace'
2345 is called, since 'backtrace' may call malloc if the tables are not
2348 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2349 fatal error has occurred in some other thread; generate a thread
2350 backtrace instead, ignoring BACKTRACE_LIMIT. */
2352 emacs_backtrace (int backtrace_limit
)
2354 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2355 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2359 if (thread_backtrace_npointers
)
2361 buffer
= thread_backtrace_buffer
;
2362 npointers
= thread_backtrace_npointers
;
2366 buffer
= main_backtrace_buffer
;
2368 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2369 if (bounded_limit
< 0)
2371 backtrace (buffer
, 1);
2375 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2380 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2381 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2382 if (bounded_limit
< npointers
)
2383 emacs_write (STDERR_FILENO
, "...\n", 4);
2391 terminate_due_to_signal (SIGABRT
, 40);
2395 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2396 Use binary I/O on systems that care about text vs binary I/O.
2397 Arrange for subprograms to not inherit the file descriptor.
2398 Prefer a method that is multithread-safe, if available.
2399 Do not fail merely because the open was interrupted by a signal.
2400 Allow the user to quit. */
2403 emacs_open (const char *file
, int oflags
, int mode
)
2406 if (! (oflags
& O_TEXT
))
2408 oflags
|= O_CLOEXEC
;
2409 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2414 /* Open FILE as a stream for Emacs use, with mode MODE.
2415 Act like emacs_open with respect to threads, signals, and quits. */
2418 emacs_fopen (char const *file
, char const *mode
)
2420 int fd
, omode
, oflags
;
2422 char const *m
= mode
;
2426 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2427 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2428 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2429 default: emacs_abort ();
2435 case '+': omode
= O_RDWR
; break;
2436 case 't': bflag
= O_TEXT
; break;
2437 default: /* Ignore. */ break;
2440 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2441 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2444 /* Create a pipe for Emacs use. */
2447 emacs_pipe (int fd
[2])
2452 return pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2456 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2457 For the background behind this mess, please see Austin Group defect 529
2458 <http://austingroupbugs.net/view.php?id=529>. */
2460 #ifndef POSIX_CLOSE_RESTART
2461 # define POSIX_CLOSE_RESTART 1
2463 posix_close (int fd
, int flag
)
2465 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2466 eassert (flag
== POSIX_CLOSE_RESTART
);
2468 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2469 on a system that does not define POSIX_CLOSE_RESTART.
2471 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2472 closed, and retrying the close could inadvertently close a file
2473 descriptor allocated by some other thread. In other systems
2474 (e.g., HP/UX) FD is not closed. And in still other systems
2475 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2476 multithreaded program there can be no way to tell.
2478 So, in this case, pretend that the close succeeded. This works
2479 well on systems like GNU/Linux that close FD. Although it may
2480 leak a file descriptor on other systems, the leak is unlikely and
2481 it's better to leak than to close a random victim. */
2482 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2486 /* Close FD, retrying if interrupted. If successful, return 0;
2487 otherwise, return -1 and set errno to a non-EINTR value. Consider
2488 an EINPROGRESS error to be successful, as that's merely a signal
2489 arriving. FD is always closed when this function returns, even
2492 Do not call this function if FD is nonnegative and might already be closed,
2493 as that might close an innocent victim opened by some other thread. */
2496 emacs_close (int fd
)
2500 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2503 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2505 eassert (errno
!= EBADF
|| fd
< 0);
2506 return errno
== EINPROGRESS
? 0 : r
;
2511 /* Maximum number of bytes to read or write in a single system call.
2512 This works around a serious bug in Linux kernels before 2.6.16; see
2513 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2514 It's likely to work around similar bugs in other operating systems, so do it
2515 on all platforms. Round INT_MAX down to a page size, with the conservative
2516 assumption that page sizes are at most 2**18 bytes (any kernel with a
2517 page size larger than that shouldn't have the bug). */
2518 #ifndef MAX_RW_COUNT
2519 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2522 /* Read from FD to a buffer BUF with size NBYTE.
2523 If interrupted, process any quits and pending signals immediately
2524 if INTERRUPTIBLE, and then retry the read unless quitting.
2525 Return the number of bytes read, which might be less than NBYTE.
2526 On error, set errno to a value other than EINTR, and return -1. */
2528 emacs_intr_read (int fd
, void *buf
, ptrdiff_t nbyte
, bool interruptible
)
2532 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2533 passes a size that large to emacs_read. */
2538 result
= read (fd
, buf
, nbyte
);
2540 while (result
< 0 && errno
== EINTR
);
2545 /* Read from FD to a buffer BUF with size NBYTE.
2546 If interrupted, retry the read. Return the number of bytes read,
2547 which might be less than NBYTE. On error, set errno to a value
2548 other than EINTR, and return -1. */
2550 emacs_read (int fd
, void *buf
, ptrdiff_t nbyte
)
2552 return emacs_intr_read (fd
, buf
, nbyte
, false);
2555 /* Like emacs_read, but also process quits and pending signals. */
2557 emacs_read_quit (int fd
, void *buf
, ptrdiff_t nbyte
)
2559 return emacs_intr_read (fd
, buf
, nbyte
, true);
2562 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2563 interrupted or if a partial write occurs. Process any quits
2564 immediately if INTERRUPTIBLE is positive, and process any pending
2565 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2566 of bytes written; if this is less than NBYTE, set errno to a value
2567 other than EINTR. */
2569 emacs_full_write (int fd
, char const *buf
, ptrdiff_t nbyte
,
2572 ptrdiff_t bytes_written
= 0;
2576 ssize_t n
= write (fd
, buf
, min (nbyte
, MAX_RW_COUNT
));
2585 if (0 < interruptible
)
2587 if (pending_signals
)
2588 process_pending_signals ();
2599 return bytes_written
;
2602 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2603 interrupted or if a partial write occurs. Do not process quits or
2604 pending signals. Return the number of bytes written, setting errno
2605 if this is less than NBYTE. */
2607 emacs_write (int fd
, void const *buf
, ptrdiff_t nbyte
)
2609 return emacs_full_write (fd
, buf
, nbyte
, 0);
2612 /* Like emacs_write, but also process pending signals. */
2614 emacs_write_sig (int fd
, void const *buf
, ptrdiff_t nbyte
)
2616 return emacs_full_write (fd
, buf
, nbyte
, -1);
2619 /* Like emacs_write, but also process quits and pending signals. */
2621 emacs_write_quit (int fd
, void const *buf
, ptrdiff_t nbyte
)
2623 return emacs_full_write (fd
, buf
, nbyte
, 1);
2626 /* Write a diagnostic to standard error that contains MESSAGE and a
2627 string derived from errno. Preserve errno. Do not buffer stderr.
2628 Do not process quits or pending signals if interrupted. */
2630 emacs_perror (char const *message
)
2633 char const *error_string
= emacs_strerror (err
);
2634 char const *command
= (initial_argv
&& initial_argv
[0]
2635 ? initial_argv
[0] : "emacs");
2636 /* Write it out all at once, if it's short; this is less likely to
2637 be interleaved with other output. */
2639 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2640 command
, message
, error_string
);
2641 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2642 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2645 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2646 emacs_write (STDERR_FILENO
, ": ", 2);
2647 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2648 emacs_write (STDERR_FILENO
, ": ", 2);
2649 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2650 emacs_write (STDERR_FILENO
, "\n", 1);
2655 /* Return a struct timeval that is roughly equivalent to T.
2656 Use the least timeval not less than T.
2657 Return an extremal value if the result would overflow. */
2659 make_timeval (struct timespec t
)
2662 tv
.tv_sec
= t
.tv_sec
;
2663 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2665 if (t
.tv_nsec
% 1000 != 0)
2667 if (tv
.tv_usec
< 999999)
2669 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2679 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2680 ATIME and MTIME, respectively.
2681 FD must be either negative -- in which case it is ignored --
2682 or a file descriptor that is open on FILE.
2683 If FD is nonnegative, then FILE can be NULL. */
2685 set_file_times (int fd
, const char *filename
,
2686 struct timespec atime
, struct timespec mtime
)
2688 struct timespec timespec
[2];
2689 timespec
[0] = atime
;
2690 timespec
[1] = mtime
;
2691 return fdutimens (fd
, filename
, timespec
);
2694 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2695 This is like renameat except that it fails if DST already exists,
2696 or if this operation is not supported atomically. Return 0 if
2697 successful, -1 (setting errno) otherwise. */
2699 renameat_noreplace (int srcfd
, char const *src
, int dstfd
, char const *dst
)
2701 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2702 return syscall (SYS_renameat2
, srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2703 #elif defined CYGWIN && defined RENAME_NOREPLACE
2704 return renameat2 (srcfd
, src
, dstfd
, dst
, RENAME_NOREPLACE
);
2705 #elif defined RENAME_EXCL
2706 return renameatx_np (srcfd
, src
, dstfd
, dst
, RENAME_EXCL
);
2709 if (srcfd
== AT_FDCWD
&& dstfd
== AT_FDCWD
)
2710 return sys_rename_replace (src
, dst
, 0);
2717 /* Like strsignal, except async-signal-safe, and this function typically
2718 returns a string in the C locale rather than the current locale. */
2720 safe_strsignal (int code
)
2722 char const *signame
= 0;
2724 if (0 <= code
&& code
< sys_siglist_entries
)
2725 signame
= sys_siglist
[code
];
2727 signame
= "Unknown signal";
2733 /* For make-serial-process */
2735 serial_open (Lisp_Object port
)
2737 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2739 report_file_error ("Opening serial port", port
);
2741 ioctl (fd
, TIOCEXCL
, (char *) 0);
2747 #if !defined (HAVE_CFMAKERAW)
2748 /* Workaround for targets which are missing cfmakeraw. */
2749 /* Pasted from man page. */
2751 cfmakeraw (struct termios
*termios_p
)
2753 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2754 termios_p
->c_oflag
&= ~OPOST
;
2755 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2756 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2757 termios_p
->c_cflag
|= CS8
;
2759 #endif /* !defined (HAVE_CFMAKERAW */
2761 #if !defined (HAVE_CFSETSPEED)
2762 /* Workaround for targets which are missing cfsetspeed. */
2764 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2766 return (cfsetispeed (termios_p
, vitesse
)
2767 + cfsetospeed (termios_p
, vitesse
));
2771 /* For serial-process-configure */
2773 serial_configure (struct Lisp_Process
*p
,
2774 Lisp_Object contact
)
2776 Lisp_Object childp2
= Qnil
;
2777 Lisp_Object tem
= Qnil
;
2778 struct termios attr
;
2780 char summary
[4] = "???"; /* This usually becomes "8N1". */
2782 childp2
= Fcopy_sequence (p
->childp
);
2784 /* Read port attributes and prepare default configuration. */
2785 err
= tcgetattr (p
->outfd
, &attr
);
2787 report_file_error ("Failed tcgetattr", Qnil
);
2789 #if defined (CLOCAL)
2790 attr
.c_cflag
|= CLOCAL
;
2793 attr
.c_cflag
|= CREAD
;
2796 /* Configure speed. */
2797 if (!NILP (Fplist_member (contact
, QCspeed
)))
2798 tem
= Fplist_get (contact
, QCspeed
);
2800 tem
= Fplist_get (p
->childp
, QCspeed
);
2802 err
= cfsetspeed (&attr
, XINT (tem
));
2804 report_file_error ("Failed cfsetspeed", tem
);
2805 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2807 /* Configure bytesize. */
2808 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2809 tem
= Fplist_get (contact
, QCbytesize
);
2811 tem
= Fplist_get (p
->childp
, QCbytesize
);
2813 tem
= make_number (8);
2815 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2816 error (":bytesize must be nil (8), 7, or 8");
2817 summary
[0] = XINT (tem
) + '0';
2818 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2819 attr
.c_cflag
&= ~CSIZE
;
2820 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2822 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2823 if (XINT (tem
) != 8)
2824 error ("Bytesize cannot be changed");
2826 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2828 /* Configure parity. */
2829 if (!NILP (Fplist_member (contact
, QCparity
)))
2830 tem
= Fplist_get (contact
, QCparity
);
2832 tem
= Fplist_get (p
->childp
, QCparity
);
2833 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2834 error (":parity must be nil (no parity), `even', or `odd'");
2835 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2836 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2837 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2842 else if (EQ (tem
, Qeven
))
2845 attr
.c_cflag
|= PARENB
;
2846 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2848 else if (EQ (tem
, Qodd
))
2851 attr
.c_cflag
|= (PARENB
| PARODD
);
2852 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2855 /* Don't error on no parity, which should be set by cfmakeraw. */
2857 error ("Parity cannot be configured");
2859 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2861 /* Configure stopbits. */
2862 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2863 tem
= Fplist_get (contact
, QCstopbits
);
2865 tem
= Fplist_get (p
->childp
, QCstopbits
);
2867 tem
= make_number (1);
2869 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2870 error (":stopbits must be nil (1 stopbit), 1, or 2");
2871 summary
[2] = XINT (tem
) + '0';
2872 #if defined (CSTOPB)
2873 attr
.c_cflag
&= ~CSTOPB
;
2874 if (XINT (tem
) == 2)
2875 attr
.c_cflag
|= CSTOPB
;
2877 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2878 if (XINT (tem
) != 1)
2879 error ("Stopbits cannot be configured");
2881 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2883 /* Configure flowcontrol. */
2884 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2885 tem
= Fplist_get (contact
, QCflowcontrol
);
2887 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2888 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2889 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2890 #if defined (CRTSCTS)
2891 attr
.c_cflag
&= ~CRTSCTS
;
2893 #if defined (CNEW_RTSCTS)
2894 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2896 #if defined (IXON) && defined (IXOFF)
2897 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2901 /* Already configured. */
2903 else if (EQ (tem
, Qhw
))
2905 #if defined (CRTSCTS)
2906 attr
.c_cflag
|= CRTSCTS
;
2907 #elif defined (CNEW_RTSCTS)
2908 attr
.c_cflag
|= CNEW_RTSCTS
;
2910 error ("Hardware flowcontrol (RTS/CTS) not supported");
2913 else if (EQ (tem
, Qsw
))
2915 #if defined (IXON) && defined (IXOFF)
2916 attr
.c_iflag
|= (IXON
| IXOFF
);
2918 error ("Software flowcontrol (XON/XOFF) not supported");
2921 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2923 /* Activate configuration. */
2924 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2926 report_file_error ("Failed tcsetattr", Qnil
);
2928 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2929 pset_childp (p
, childp2
);
2931 #endif /* not DOS_NT */
2933 /* System depended enumeration of and access to system processes a-la ps(1). */
2937 /* Process enumeration and access via /proc. */
2940 list_system_processes (void)
2942 Lisp_Object procdir
, match
, proclist
, next
;
2945 /* For every process on the system, there's a directory in the
2946 "/proc" pseudo-directory whose name is the numeric ID of that
2948 procdir
= build_string ("/proc");
2949 match
= build_string ("[0-9]+");
2950 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, false, Qnil
);
2952 /* `proclist' gives process IDs as strings. Destructively convert
2953 each string into a number. */
2954 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2957 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2960 /* directory_files_internal returns the files in reverse order; undo
2962 proclist
= Fnreverse (proclist
);
2966 #elif defined DARWIN_OS || defined __FreeBSD__
2969 list_system_processes (void)
2972 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2974 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2977 struct kinfo_proc
*procs
;
2980 Lisp_Object proclist
= Qnil
;
2982 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2985 procs
= xmalloc (len
);
2986 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2992 len
/= sizeof (struct kinfo_proc
);
2993 for (i
= 0; i
< len
; i
++)
2996 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2998 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
3007 /* The WINDOWSNT implementation is in w32.c.
3008 The MSDOS implementation is in dosfns.c. */
3009 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3012 list_system_processes (void)
3017 #endif /* !defined (WINDOWSNT) */
3019 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3020 static struct timespec
3021 time_from_jiffies (unsigned long long tval
, long hz
)
3023 unsigned long long s
= tval
/ hz
;
3024 unsigned long long frac
= tval
% hz
;
3027 if (TYPE_MAXIMUM (time_t) < s
)
3029 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
3030 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
3031 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
3034 /* This is reachable only in the unlikely case that HZ * HZ
3035 exceeds ULLONG_MAX. It calculates an approximation that is
3036 guaranteed to be in range. */
3037 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
3038 + (hz
% TIMESPEC_RESOLUTION
!= 0));
3039 ns
= frac
/ hz_per_ns
;
3042 return make_timespec (s
, ns
);
3046 ltime_from_jiffies (unsigned long long tval
, long hz
)
3048 struct timespec t
= time_from_jiffies (tval
, hz
);
3049 return make_lisp_time (t
);
3052 static struct timespec
3056 struct timespec up
= make_timespec (0, 0);
3059 fup
= emacs_fopen ("/proc/uptime", "r");
3063 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
3064 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
3066 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
3067 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
3068 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
3071 if (TYPE_MAXIMUM (time_t) < upsec
)
3073 upsec
= TYPE_MAXIMUM (time_t);
3074 upfrac
= TIMESPEC_RESOLUTION
- 1;
3078 int upfraclen
= upfrac_end
- upfrac_start
;
3079 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
3081 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
3083 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
3085 up
= make_timespec (upsec
, upfrac
);
3094 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3095 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3098 procfs_ttyname (int rdev
)
3101 char name
[PATH_MAX
];
3104 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3110 unsigned long minor_beg
, minor_end
;
3111 char minor
[25]; /* 2 32-bit numbers + dash */
3114 for (; !feof_unlocked (fdev
) && !ferror_unlocked (fdev
); name
[0] = 0)
3116 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3117 && major
== MAJOR (rdev
))
3119 minor_beg
= strtoul (minor
, &endp
, 0);
3121 minor_end
= minor_beg
;
3122 else if (*endp
== '-')
3123 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3127 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3129 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3137 return build_string (name
);
3141 procfs_get_total_memory (void)
3144 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3148 fmem
= emacs_fopen ("/proc/meminfo", "r");
3152 uintmax_t entry_value
;
3156 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3159 retval
= entry_value
;
3164 while ((c
= getc_unlocked (fmem
)) != EOF
&& c
!= '\n')
3182 system_process_attributes (Lisp_Object pid
)
3184 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3188 long clocks_per_sec
;
3190 char procbuf
[1025], *p
, *q
;
3193 static char const default_cmd
[] = "???";
3194 const char *cmd
= default_cmd
;
3195 int cmdsize
= sizeof default_cmd
- 1;
3196 char *cmdline
= NULL
;
3197 ptrdiff_t cmdline_size
;
3200 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3203 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3204 long priority
, niceness
, rss
;
3205 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3206 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3208 Lisp_Object attrs
= Qnil
;
3209 Lisp_Object decoded_cmd
;
3212 CHECK_NUMBER_OR_FLOAT (pid
);
3213 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3214 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3215 if (stat (procfn
, &st
) < 0)
3220 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3222 pw
= getpwuid (uid
);
3225 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3228 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3230 gr
= getgrgid (gid
);
3233 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3235 count
= SPECPDL_INDEX ();
3236 strcpy (fn
, procfn
);
3237 procfn_end
= fn
+ strlen (fn
);
3238 strcpy (procfn_end
, "/stat");
3239 fd
= emacs_open (fn
, O_RDONLY
, 0);
3244 record_unwind_protect_int (close_file_unwind
, fd
);
3245 nread
= emacs_read_quit (fd
, procbuf
, sizeof procbuf
- 1);
3249 procbuf
[nread
] = '\0';
3252 p
= strchr (p
, '(');
3255 q
= strrchr (p
+ 1, ')');
3265 /* Command name is encoded in locale-coding-system; decode it. */
3266 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3267 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3268 Vlocale_coding_system
, 0);
3269 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3271 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3272 utime stime cutime cstime priority nice thcount . start vsize rss */
3274 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3275 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3276 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3277 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3278 &u_time
, &s_time
, &cutime
, &cstime
,
3279 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3284 state_str
[1] = '\0';
3285 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3286 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3287 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3288 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3289 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3290 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3291 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3292 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3293 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3295 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3297 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3298 if (clocks_per_sec
< 0)
3299 clocks_per_sec
= 100;
3300 attrs
= Fcons (Fcons (Qutime
,
3301 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3303 attrs
= Fcons (Fcons (Qstime
,
3304 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3306 attrs
= Fcons (Fcons (Qtime
,
3307 ltime_from_jiffies (s_time
+ u_time
,
3310 attrs
= Fcons (Fcons (Qcutime
,
3311 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3313 attrs
= Fcons (Fcons (Qcstime
,
3314 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3316 attrs
= Fcons (Fcons (Qctime
,
3317 ltime_from_jiffies (cstime
+ cutime
,
3320 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3321 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3322 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3324 tnow
= current_timespec ();
3325 telapsed
= get_up_time ();
3326 tboot
= timespec_sub (tnow
, telapsed
);
3327 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3328 tstart
= timespec_add (tboot
, tstart
);
3329 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3330 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3332 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3333 telapsed
= timespec_sub (tnow
, tstart
);
3334 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3335 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3336 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3339 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3340 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3343 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3346 unbind_to (count
, Qnil
);
3349 strcpy (procfn_end
, "/cmdline");
3350 fd
= emacs_open (fn
, O_RDONLY
, 0);
3353 ptrdiff_t readsize
, nread_incr
;
3354 record_unwind_protect_int (close_file_unwind
, fd
);
3355 record_unwind_protect_nothing ();
3356 nread
= cmdline_size
= 0;
3360 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3361 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3363 /* Leave room even if every byte needs escaping below. */
3364 readsize
= (cmdline_size
>> 1) - nread
;
3366 nread_incr
= emacs_read_quit (fd
, cmdline
+ nread
, readsize
);
3367 nread
+= max (0, nread_incr
);
3369 while (nread_incr
== readsize
);
3373 /* We don't want trailing null characters. */
3374 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3377 /* Escape-quote whitespace and backslashes. */
3378 q
= cmdline
+ cmdline_size
;
3383 if (c_isspace (c
) || c
== '\\')
3387 nread
= cmdline
+ cmdline_size
- q
;
3392 nread
= cmdsize
+ 2;
3393 cmdline_size
= nread
+ 1;
3394 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3395 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3396 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3398 /* Command line is encoded in locale-coding-system; decode it. */
3399 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3400 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3401 Vlocale_coding_system
, 0);
3402 unbind_to (count
, Qnil
);
3403 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3409 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3411 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3412 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3413 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3414 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3415 #undef _FILE_OFFSET_BITS
3417 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3422 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3423 #define _FILE_OFFSET_BITS 64
3424 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3426 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3429 system_process_attributes (Lisp_Object pid
)
3431 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3436 struct psinfo pinfo
;
3442 Lisp_Object attrs
= Qnil
;
3443 Lisp_Object decoded_cmd
;
3446 CHECK_NUMBER_OR_FLOAT (pid
);
3447 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3448 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3449 if (stat (procfn
, &st
) < 0)
3454 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3456 pw
= getpwuid (uid
);
3459 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3462 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3464 gr
= getgrgid (gid
);
3467 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3469 count
= SPECPDL_INDEX ();
3470 strcpy (fn
, procfn
);
3471 procfn_end
= fn
+ strlen (fn
);
3472 strcpy (procfn_end
, "/psinfo");
3473 fd
= emacs_open (fn
, O_RDONLY
, 0);
3478 record_unwind_protect_int (close_file_unwind
, fd
);
3479 nread
= emacs_read_quit (fd
, &pinfo
, sizeof pinfo
);
3482 if (nread
== sizeof pinfo
)
3484 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3485 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3486 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3490 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3491 state_str
[1] = '\0';
3492 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3495 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3496 need to get a string from it. */
3498 /* FIXME: missing: Qtpgid */
3510 Are they available? */
3512 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3513 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3514 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3515 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3516 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3519 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3520 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3522 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3525 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3526 range 0 .. 2**15, representing 0.0 .. 1.0. */
3527 attrs
= Fcons (Fcons (Qpcpu
,
3528 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3530 attrs
= Fcons (Fcons (Qpmem
,
3531 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3534 AUTO_STRING (fname
, pinfo
.pr_fname
);
3535 decoded_cmd
= code_convert_string_norecord (fname
,
3536 Vlocale_coding_system
, 0);
3537 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3538 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3539 decoded_cmd
= code_convert_string_norecord (psargs
,
3540 Vlocale_coding_system
, 0);
3541 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3543 unbind_to (count
, Qnil
);
3547 #elif defined __FreeBSD__
3549 static struct timespec
3550 timeval_to_timespec (struct timeval t
)
3552 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3556 make_lisp_timeval (struct timeval t
)
3558 return make_lisp_time (timeval_to_timespec (t
));
3562 system_process_attributes (Lisp_Object pid
)
3565 int pagesize
= getpagesize ();
3566 unsigned long npages
;
3572 char args
[MAXPATHLEN
];
3573 struct timespec t
, now
;
3575 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3576 struct kinfo_proc proc
;
3577 size_t proclen
= sizeof proc
;
3579 Lisp_Object attrs
= Qnil
;
3580 Lisp_Object decoded_comm
;
3582 CHECK_NUMBER_OR_FLOAT (pid
);
3583 CONS_TO_INTEGER (pid
, int, proc_id
);
3586 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3589 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3592 pw
= getpwuid (proc
.ki_uid
);
3595 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3597 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3600 gr
= getgrgid (proc
.ki_svgid
);
3603 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3605 AUTO_STRING (comm
, proc
.ki_comm
);
3606 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3608 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3610 char state
[2] = {'\0', '\0'};
3611 switch (proc
.ki_stat
)
3633 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3636 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3637 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3638 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3641 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3644 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3646 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3647 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3648 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3649 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3650 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3652 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3654 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3656 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3657 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3658 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3660 attrs
= Fcons (Fcons (Qcutime
,
3661 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3663 attrs
= Fcons (Fcons (Qcstime
,
3664 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3666 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3667 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3668 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3670 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3672 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3673 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3674 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3675 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3676 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3679 now
= current_timespec ();
3680 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3681 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3683 len
= sizeof fscale
;
3684 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3689 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3691 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3692 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3693 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3697 len
= sizeof npages
;
3698 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3700 double pmem
= (proc
.ki_flag
& P_INMEM
3701 ? 100.0 * proc
.ki_rssize
/ npages
3703 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3706 mib
[2] = KERN_PROC_ARGS
;
3708 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3711 for (i
= 0; i
< len
; i
++)
3713 if (! args
[i
] && i
< len
- 1)
3717 AUTO_STRING (comm
, args
);
3718 decoded_comm
= code_convert_string_norecord (comm
,
3719 Vlocale_coding_system
, 0);
3721 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3727 #elif defined DARWIN_OS
3729 static struct timespec
3730 timeval_to_timespec (struct timeval t
)
3732 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3736 make_lisp_timeval (struct timeval t
)
3738 return make_lisp_time (timeval_to_timespec (t
));
3742 system_process_attributes (Lisp_Object pid
)
3748 struct timeval starttime
;
3749 struct timespec t
, now
;
3750 struct rusage
*rusage
;
3755 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3756 struct kinfo_proc proc
;
3757 size_t proclen
= sizeof proc
;
3759 Lisp_Object attrs
= Qnil
;
3760 Lisp_Object decoded_comm
;
3762 CHECK_NUMBER_OR_FLOAT (pid
);
3763 CONS_TO_INTEGER (pid
, int, proc_id
);
3766 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3769 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3770 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3773 pw
= getpwuid (uid
);
3776 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3778 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3779 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3782 gr
= getgrgid (gid
);
3785 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3787 decoded_comm
= (code_convert_string_norecord
3788 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3789 Vlocale_coding_system
, 0));
3791 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3793 char state
[2] = {'\0', '\0'};
3794 switch (proc
.kp_proc
.p_stat
)
3816 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3819 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3821 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3824 tdev
= proc
.kp_eproc
.e_tdev
;
3826 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3829 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3831 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3834 rusage
= proc
.kp_proc
.p_ru
;
3837 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3839 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3842 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3844 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3846 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3847 timeval_to_timespec (rusage
->ru_stime
));
3848 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3851 starttime
= proc
.kp_proc
.p_starttime
;
3852 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3853 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3855 now
= current_timespec ();
3856 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3857 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3862 /* The WINDOWSNT implementation is in w32.c.
3863 The MSDOS implementation is in dosfns.c. */
3864 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3867 system_process_attributes (Lisp_Object pid
)
3872 #endif /* !defined (WINDOWSNT) */
3874 /* Wide character string collation. */
3876 #ifdef __STDC_ISO_10646__
3878 # include <wctype.h>
3880 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3881 # include <locale.h>
3884 # define LC_COLLATE 0
3886 # ifndef LC_COLLATE_MASK
3887 # define LC_COLLATE_MASK 0
3892 # ifndef LC_CTYPE_MASK
3893 # define LC_CTYPE_MASK 0
3896 # ifndef HAVE_NEWLOCALE
3902 # define freelocale emacs_freelocale
3903 # define locale_t emacs_locale_t
3904 # define newlocale emacs_newlocale
3905 # define wcscoll_l emacs_wcscoll_l
3906 # define towlower_l emacs_towlower_l
3908 typedef char const *locale_t
;
3911 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3917 freelocale (locale_t loc
)
3922 emacs_setlocale (int category
, char const *locale
)
3924 # ifdef HAVE_SETLOCALE
3926 char *loc
= setlocale (category
, locale
);
3937 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3940 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3948 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3949 strcpy (oldcopy
, oldloc
);
3950 if (! emacs_setlocale (LC_COLLATE
, loc
))
3955 result
= wcscoll (a
, b
);
3957 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3968 towlower_l (wint_t wc
, locale_t loc
)
3971 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3976 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3977 strcpy (oldcopy
, oldloc
);
3978 if (emacs_setlocale (LC_CTYPE
, loc
))
3980 result
= towlower (wc
);
3981 emacs_setlocale (LC_COLLATE
, oldcopy
);
3991 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3992 Lisp_Object locale
, Lisp_Object ignore_case
)
3995 ptrdiff_t len
, i
, i_byte
;
4000 /* Convert byte stream to code points. */
4001 len
= SCHARS (s1
); i
= i_byte
= 0;
4002 SAFE_NALLOCA (p1
, 1, len
+ 1);
4004 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
4007 len
= SCHARS (s2
); i
= i_byte
= 0;
4008 SAFE_NALLOCA (p2
, 1, len
+ 1);
4010 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
4013 if (STRINGP (locale
))
4015 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
4016 SSDATA (locale
), 0);
4018 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
4020 if (! NILP (ignore_case
))
4021 for (int i
= 1; i
< 3; i
++)
4023 wchar_t *p
= (i
== 1) ? p1
: p2
;
4025 *p
= towlower_l (*p
, loc
);
4029 res
= wcscoll_l (p1
, p2
, loc
);
4035 if (! NILP (ignore_case
))
4036 for (int i
= 1; i
< 3; i
++)
4038 wchar_t *p
= (i
== 1) ? p1
: p2
;
4044 res
= wcscoll (p1
, p2
);
4047 # ifndef HAVE_NEWLOCALE
4049 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
4052 error ("Invalid string for collation: %s", emacs_strerror (err
));
4058 #endif /* __STDC_ISO_10646__ */
4062 str_collate (Lisp_Object s1
, Lisp_Object s2
,
4063 Lisp_Object locale
, Lisp_Object ignore_case
)
4066 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
4067 int res
, err
= errno
;
4070 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
4072 error ("Invalid string for collation: %s", strerror (errno
));
4077 #endif /* WINDOWSNT */