1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2016 Free Software
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
27 #endif /* HAVE_PWD_H */
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #if defined DARWIN_OS || defined __FreeBSD__
41 # include <sys/sysctl.h>
45 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
46 'struct frame', so rename it. */
47 # define frame freebsd_frame
48 # include <sys/user.h>
55 #include <sys/socket.h>
57 #endif /* HAVE_SOCKETS */
63 #endif /* TRY_AGAIN */
67 #define write sys_write
69 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
72 #endif /* not WINDOWSNT */
74 #include <sys/types.h>
78 /* Get SI_SRPC_DOMAIN, if it is available. */
79 #ifdef HAVE_SYS_SYSTEMINFO_H
80 #include <sys/systeminfo.h>
83 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
87 #include <sys/param.h>
94 #ifdef HAVE_SYS_UTSNAME_H
95 #include <sys/utsname.h>
97 #endif /* HAVE_SYS_UTSNAME_H */
101 #include "termhooks.h"
102 #include "termchar.h"
103 #include "termopts.h"
108 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
109 do that during startup just to call gnutls_rnd. */
110 #if defined HAVE_GNUTLS && !defined WINDOWSNT
111 # include <gnutls/crypto.h>
113 # define emacs_gnutls_global_init() Qnil
114 # define gnutls_rnd(level, data, len) (-1)
119 /* In process.h which conflicts with the local copy. */
121 int _cdecl
_spawnlp (int, const char *, const char *, ...);
122 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
123 several prototypes of functions called below. */
124 #include <sys/socket.h>
127 #include "syssignal.h"
130 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
132 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
135 /* Declare here, including term.h is problematic on some systems. */
136 extern void tputs (const char *, int, int (*)(int));
138 static const int baud_convert
[] =
140 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
141 1800, 2400, 4800, 9600, 19200, 38400
144 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
145 # include <sys/personality.h>
147 /* Disable address randomization in the current process. Return true
148 if addresses were randomized but this has been disabled, false
151 disable_address_randomization (void)
153 bool disabled
= false;
154 int pers
= personality (0xffffffff);
155 disabled
= (! (pers
& ADDR_NO_RANDOMIZE
)
156 && 0 <= personality (pers
| ADDR_NO_RANDOMIZE
));
161 /* Execute the program in FILE, with argument vector ARGV and environ
162 ENVP. Return an error number if unsuccessful. This is like execve
163 except it reenables ASLR in the executed program if necessary, and
164 on error it returns an error number rather than -1. */
166 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
168 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
169 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
170 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
171 if (change_personality
)
172 personality (pers
& ~ADDR_NO_RANDOMIZE
);
175 execve (file
, argv
, envp
);
178 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
179 if (change_personality
)
186 /* If FD is not already open, arrange for it to be open with FLAGS. */
188 force_open (int fd
, int flags
)
190 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
192 int n
= open (NULL_DEVICE
, flags
);
193 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
195 emacs_perror (NULL_DEVICE
);
201 /* Make sure stdin, stdout, and stderr are open to something, so that
202 their file descriptors are not hijacked by later system calls. */
204 init_standard_fds (void)
206 /* Open stdin for *writing*, and stdout and stderr for *reading*.
207 That way, any attempt to do normal I/O will result in an error,
208 just as if the files were closed, and the file descriptors will
209 not be reused by later opens. */
210 force_open (STDIN_FILENO
, O_WRONLY
);
211 force_open (STDOUT_FILENO
, O_RDONLY
);
212 force_open (STDERR_FILENO
, O_RDONLY
);
215 /* Return the current working directory. The result should be freed
216 with 'free'. Return NULL on errors. */
218 emacs_get_current_dir_name (void)
220 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
221 # ifdef HYBRID_MALLOC
222 bool use_libc
= bss_sbrk_did_unexec
;
224 bool use_libc
= true;
227 return get_current_dir_name ();
231 char *pwd
= getenv ("PWD");
232 struct stat dotstat
, pwdstat
;
233 /* If PWD is accurate, use it instead of calling getcwd. PWD is
234 sometimes a nicer name, and using it may avoid a fatal error if a
235 parent directory is searchable but not readable. */
237 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
238 && stat (pwd
, &pwdstat
) == 0
239 && stat (".", &dotstat
) == 0
240 && dotstat
.st_ino
== pwdstat
.st_ino
241 && dotstat
.st_dev
== pwdstat
.st_dev
243 && strlen (pwd
) < MAXPATHLEN
247 buf
= malloc (strlen (pwd
) + 1);
254 size_t buf_size
= 1024;
255 buf
= malloc (buf_size
);
260 if (getcwd (buf
, buf_size
) == buf
)
264 int tmp_errno
= errno
;
270 buf
= realloc (buf
, buf_size
);
279 /* Discard pending input on all input descriptors. */
282 discard_tty_input (void)
285 struct emacs_tty buf
;
290 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
291 while (dos_keyread () != -1)
293 #else /* not MSDOS */
295 struct tty_display_info
*tty
;
296 for (tty
= tty_list
; tty
; tty
= tty
->next
)
298 if (tty
->input
) /* Is the device suspended? */
300 emacs_get_tty (fileno (tty
->input
), &buf
);
301 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
305 #endif /* not MSDOS */
306 #endif /* not WINDOWSNT */
312 /* Arrange for character C to be read as the next input from
314 XXX What if we have multiple ttys?
320 if (! (FRAMEP (selected_frame
)
321 && FRAME_LIVE_P (XFRAME (selected_frame
))
322 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
325 /* Should perhaps error if in batch mode */
327 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
328 #else /* no TIOCSTI */
329 error ("Cannot stuff terminal input characters in this version of Unix");
330 #endif /* no TIOCSTI */
336 init_baud_rate (int fd
)
346 #else /* not DOS_NT */
351 emacs_ospeed
= cfgetospeed (&sg
);
352 #endif /* not DOS_NT */
355 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
356 ? baud_convert
[emacs_ospeed
] : 9600);
365 /* Wait for the subprocess with process id CHILD to terminate or change status.
366 CHILD must be a child process that has not been reaped.
367 If STATUS is non-null, store the waitpid-style exit status into *STATUS
368 and tell wait_reading_process_output that it needs to look around.
369 Use waitpid-style OPTIONS when waiting.
370 If INTERRUPTIBLE, this function is interruptible by a signal.
372 Return CHILD if successful, 0 if no status is available;
373 the latter is possible only when options & NOHANG. */
375 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
379 /* Invoke waitpid only with a known process ID; do not invoke
380 waitpid with a nonpositive argument. Otherwise, Emacs might
381 reap an unwanted process by mistake. For example, invoking
382 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
383 so that another thread running glib won't find them. */
386 while ((pid
= waitpid (child
, status
, options
)) < 0)
388 /* Check that CHILD is a child process that has not been reaped,
389 and that STATUS and OPTIONS are valid. Otherwise abort,
390 as continuing after this internal error could cause Emacs to
391 become confused and kill innocent-victim processes. */
395 /* Note: the MS-Windows emulation of waitpid calls QUIT
401 /* If successful and status is requested, tell wait_reading_process_output
402 that it needs to wake up and look around. */
403 if (pid
&& status
&& input_available_clear_time
)
404 *input_available_clear_time
= make_timespec (0, 0);
409 /* Wait for the subprocess with process id CHILD to terminate.
410 CHILD must be a child process that has not been reaped.
411 If STATUS is non-null, store the waitpid-style exit status into *STATUS
412 and tell wait_reading_process_output that it needs to look around.
413 If INTERRUPTIBLE, this function is interruptible by a signal. */
415 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
417 get_child_status (child
, status
, 0, interruptible
);
420 /* Report whether the subprocess with process id CHILD has changed status.
421 Termination counts as a change of status.
422 CHILD must be a child process that has not been reaped.
423 If STATUS is non-null, store the waitpid-style exit status into *STATUS
424 and tell wait_reading_process_output that it needs to look around.
425 Use waitpid-style OPTIONS to check status, but do not wait.
427 Return CHILD if successful, 0 if no status is available because
428 the process's state has not changed. */
430 child_status_changed (pid_t child
, int *status
, int options
)
432 return get_child_status (child
, status
, WNOHANG
| options
, 0);
436 /* Set up the terminal at the other end of a pseudo-terminal that
437 we will be controlling an inferior through.
438 It should not echo or do line-editing, since that is done
439 in Emacs. No padding needed for insertion into an Emacs buffer. */
442 child_setup_tty (int out
)
447 emacs_get_tty (out
, &s
);
448 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
449 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
451 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
452 Some versions of GNU Hurd do not have FFDLY? */
454 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
455 /* No output delays */
457 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
458 /* No output delays */
461 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
462 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
464 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
467 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
470 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
472 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
473 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
474 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
475 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
478 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
481 #ifdef SIGNALS_VIA_CHARACTERS
482 /* the QUIT and INTR character are used in process_send_signal
483 so set them here to something useful. */
484 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
485 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
486 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
487 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
488 #endif /* not SIGNALS_VIA_CHARACTERS */
491 /* Also, PTY overloads NUL and BREAK.
492 don't ignore break, but don't signal either, so it looks like NUL. */
493 s
.main
.c_iflag
&= ~IGNBRK
;
494 s
.main
.c_iflag
&= ~BRKINT
;
495 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
496 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
497 would force it to 0377. That looks like duplicated code. */
498 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
501 /* We originally enabled ICANON (and set VEOF to 04), and then had
502 process.c send additional EOF chars to flush the output when faced
503 with long lines, but this leads to weird effects when the
504 subprocess has disabled ICANON and ends up seeing those spurious
505 extra EOFs. So we don't send EOFs any more in
506 process.c:send_process. First we tried to disable ICANON by
507 default, so if a subsprocess sets up ICANON, it's his problem (or
508 the Elisp package that talks to it) to deal with lines that are
509 too long. But this disables some features, such as the ability
510 to send EOF signals. So we re-enabled ICANON but there is no
511 more "send eof to flush" going on (which is wrong and unportable
512 in itself). The correct way to handle too much output is to
513 buffer what could not be written and then write it again when
514 select returns ok for writing. This has it own set of
515 problems. Write is now asynchronous, is that a problem? How much
516 do we buffer, and what do we do when that limit is reached? */
518 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
519 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
520 #if 0 /* These settings only apply to non-ICANON mode. */
521 s
.main
.c_cc
[VMIN
] = 1;
522 s
.main
.c_cc
[VTIME
] = 0;
525 emacs_set_tty (out
, &s
, 0);
526 #endif /* not WINDOWSNT */
528 #endif /* not MSDOS */
531 /* Record a signal code and the action for it. */
535 struct sigaction action
;
538 static void save_signal_handlers (struct save_signal
*);
539 static void restore_signal_handlers (struct save_signal
*);
541 /* Suspend the Emacs process; give terminal to its superior. */
549 /* On a system where suspending is not implemented,
550 instead fork a subshell and let it talk directly to the terminal
557 /* Fork a subshell. */
562 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
565 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
567 char oldwd
[MAX_UTF8_PATH
];
573 struct save_signal saved_handlers
[5];
574 char *str
= SSDATA (encode_current_directory ());
580 char *volatile str_volatile
= str
;
587 error ("Can't spawn subshell");
589 saved_handlers
[0].code
= SIGINT
;
590 saved_handlers
[1].code
= SIGQUIT
;
591 saved_handlers
[2].code
= SIGTERM
;
593 saved_handlers
[3].code
= SIGIO
;
594 saved_handlers
[4].code
= 0;
596 saved_handlers
[3].code
= 0;
600 save_signal_handlers (saved_handlers
);
607 #ifdef DOS_NT /* MW, Aug 1993 */
608 getcwd (oldwd
, sizeof oldwd
);
610 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
613 sh
= egetenv ("SHELL");
617 /* Use our buffer's default directory for the subshell. */
618 if (chdir (str
) != 0)
622 _exit (EXIT_CANCELED
);
626 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
628 char *epwd
= getenv ("PWD");
629 char old_pwd
[MAXPATHLEN
+1+4];
631 /* If PWD is set, pass it with corrected value. */
634 strcpy (old_pwd
, epwd
);
635 setenv ("PWD", str
, 1);
638 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
640 putenv (old_pwd
); /* restore previous value */
642 #else /* not MSDOS */
644 /* Waits for process completion */
645 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
646 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
648 write (1, "Can't execute subshell", 22);
649 #else /* not WINDOWSNT */
650 execlp (sh
, sh
, (char *) 0);
652 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
653 #endif /* not WINDOWSNT */
654 #endif /* not MSDOS */
657 /* Do this now if we did not do it before. */
659 save_signal_handlers (saved_handlers
);
663 wait_for_termination (pid
, &status
, 0);
665 restore_signal_handlers (saved_handlers
);
669 save_signal_handlers (struct save_signal
*saved_handlers
)
671 while (saved_handlers
->code
)
673 struct sigaction action
;
674 emacs_sigaction_init (&action
, SIG_IGN
);
675 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
681 restore_signal_handlers (struct save_signal
*saved_handlers
)
683 while (saved_handlers
->code
)
685 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
691 static int old_fcntl_flags
[FD_SETSIZE
];
698 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
699 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
700 interrupts_deferred
= 0;
709 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
723 sigemptyset (&unblocked
);
725 sigaddset (&unblocked
, SIGWINCH
);
727 sigaddset (&unblocked
, SIGIO
);
728 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
730 interrupts_deferred
= 0;
735 unrequest_sigio (void)
743 sigemptyset (&blocked
);
745 sigaddset (&blocked
, SIGWINCH
);
747 sigaddset (&blocked
, SIGIO
);
748 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
749 interrupts_deferred
= 1;
757 block_child_signal (sigset_t
*oldset
)
760 sigemptyset (&blocked
);
761 sigaddset (&blocked
, SIGCHLD
);
762 sigaddset (&blocked
, SIGINT
);
763 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
766 /* Unblock SIGCHLD. */
769 unblock_child_signal (sigset_t
const *oldset
)
771 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
776 /* Saving and restoring the process group of Emacs's terminal. */
778 /* The process group of which Emacs was a member when it initially
781 If Emacs was in its own process group (i.e. inherited_pgroup ==
782 getpid ()), then we know we're running under a shell with job
783 control (Emacs would never be run as part of a pipeline).
786 If Emacs was not in its own process group, then we know we're
787 running under a shell (or a caller) that doesn't know how to
788 separate itself from Emacs (like sh). Emacs must be in its own
789 process group in order to receive SIGIO correctly. In this
790 situation, we put ourselves in our own pgroup, forcibly set the
791 tty's pgroup to our pgroup, and make sure to restore and reinstate
792 the tty's pgroup just like any other terminal setting. If
793 inherited_group was not the tty's pgroup, then we'll get a
794 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
795 it goes foreground in the future, which is what should happen. */
797 static pid_t inherited_pgroup
;
800 init_foreground_group (void)
802 pid_t pgrp
= getpgrp ();
803 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
806 /* Block and unblock SIGTTOU. */
809 block_tty_out_signal (sigset_t
*oldset
)
813 sigemptyset (&blocked
);
814 sigaddset (&blocked
, SIGTTOU
);
815 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
820 unblock_tty_out_signal (sigset_t
const *oldset
)
823 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
827 /* Safely set a controlling terminal FD's process group to PGID.
828 If we are not in the foreground already, POSIX requires tcsetpgrp
829 to deliver a SIGTTOU signal, which would stop us. This is an
830 annoyance, so temporarily ignore the signal.
832 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
833 skip all this unless SIGTTOU is defined. */
835 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
840 block_tty_out_signal (&oldset
);
841 tcsetpgrp (fd
, pgid
);
842 unblock_tty_out_signal (&oldset
);
847 /* Split off the foreground process group to Emacs alone. When we are
848 in the foreground, but not started in our own process group,
849 redirect the tty device handle FD to point to our own process
850 group. FD must be the file descriptor of the controlling tty. */
852 narrow_foreground_group (int fd
)
854 if (inherited_pgroup
&& setpgid (0, 0) == 0)
855 tcsetpgrp_without_stopping (fd
, getpid ());
858 /* Set the tty to our original foreground group. */
860 widen_foreground_group (int fd
)
862 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
863 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
866 /* Getting and setting emacs_tty structures. */
868 /* Set *TC to the parameters associated with the terminal FD,
869 or clear it if the parameters are not available.
870 Return 0 on success, -1 on failure. */
872 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
874 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
875 memset (&settings
->main
, 0, sizeof (settings
->main
));
878 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
881 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
883 settings
->main
= console_mode
;
886 #endif /* WINDOWSNT */
889 /* We have those nifty POSIX tcmumbleattr functions. */
890 return tcgetattr (fd
, &settings
->main
);
895 /* Set the parameters of the tty on FD according to the contents of
896 *SETTINGS. If FLUSHP, discard input.
897 Return 0 if all went well, and -1 (setting errno) if anything failed. */
900 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
902 /* Set the primary parameters - baud rate, character size, etcetera. */
905 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
907 if (h
&& h
!= INVALID_HANDLE_VALUE
)
911 /* Assume the handle is open for input. */
913 FlushConsoleInputBuffer (h
);
914 new_mode
= settings
->main
;
915 SetConsoleMode (h
, new_mode
);
917 #endif /* WINDOWSNT */
920 /* We have those nifty POSIX tcmumbleattr functions.
921 William J. Smith <wjs@wiis.wang.com> writes:
922 "POSIX 1003.1 defines tcsetattr to return success if it was
923 able to perform any of the requested actions, even if some
924 of the requested actions could not be performed.
925 We must read settings back to ensure tty setup properly.
926 AIX requires this to keep tty from hanging occasionally." */
927 /* This make sure that we don't loop indefinitely in here. */
928 for (i
= 0 ; i
< 10 ; i
++)
929 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
940 memset (&new, 0, sizeof (new));
941 /* Get the current settings, and see if they're what we asked for. */
942 tcgetattr (fd
, &new);
943 /* We cannot use memcmp on the whole structure here because under
944 * aix386 the termios structure has some reserved field that may
947 if ( new.c_iflag
== settings
->main
.c_iflag
948 && new.c_oflag
== settings
->main
.c_oflag
949 && new.c_cflag
== settings
->main
.c_cflag
950 && new.c_lflag
== settings
->main
.c_lflag
951 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
958 /* We have survived the tempest. */
965 static int old_fcntl_owner
[FD_SETSIZE
];
966 #endif /* F_SETOWN */
968 /* This may also be defined in stdio,
969 but if so, this does no harm,
970 and using the same name avoids wasting the other one's space. */
973 unsigned char _sobuf
[BUFSIZ
+8];
978 /* Initialize the terminal mode on all tty devices that are currently
982 init_all_sys_modes (void)
984 struct tty_display_info
*tty
;
985 for (tty
= tty_list
; tty
; tty
= tty
->next
)
986 init_sys_modes (tty
);
989 /* Initialize the terminal mode on the given tty device. */
992 init_sys_modes (struct tty_display_info
*tty_out
)
994 struct emacs_tty tty
;
996 Lisp_Object terminal
;
999 Vtty_erase_char
= Qnil
;
1004 if (!tty_out
->output
)
1005 return; /* The tty is suspended. */
1007 narrow_foreground_group (fileno (tty_out
->input
));
1009 if (! tty_out
->old_tty
)
1010 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1012 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1014 tty
= *tty_out
->old_tty
;
1016 #if !defined (DOS_NT)
1017 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1019 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1020 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1021 #ifdef INLCR /* I'm just being cautious,
1022 since I can't check how widespread INLCR is--rms. */
1023 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1026 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1028 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1029 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1031 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1033 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1034 if (tty_out
->flow_control
)
1036 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1038 tty
.main
.c_iflag
&= ~IXANY
;
1042 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1043 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1045 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1047 if (tty_out
->meta_key
)
1049 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1050 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1054 XSETTERMINAL(terminal
, tty_out
->terminal
);
1055 if (!NILP (Fcontrolling_tty_p (terminal
)))
1057 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1058 /* Set up C-g for both SIGQUIT and SIGINT.
1059 We don't know which we will get, but we handle both alike
1060 so which one it really gives us does not matter. */
1061 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1065 /* We normally don't get interrupt or quit signals from tty
1066 devices other than our controlling terminal; therefore,
1067 we must handle C-g as normal input. Unfortunately, this
1068 means that the interrupt and quit feature must be
1069 disabled on secondary ttys, or we would not even see the
1072 Note that even though emacsclient could have special code
1073 to pass SIGINT to Emacs, we should _not_ enable
1074 interrupt/quit keys for emacsclient frames. This means
1075 that we can't break out of loops in C code from a
1076 secondary tty frame, but we can always decide what
1077 display the C-g came from, which is more important from a
1078 usability point of view. (Consider the case when two
1079 people work together using the same Emacs instance.) */
1080 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1081 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1083 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1084 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1086 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1091 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1094 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1095 #endif /* V_DSUSP */
1096 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1097 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1100 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1103 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1104 #endif /* VREPRINT */
1106 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1107 #endif /* VWERASE */
1109 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1110 #endif /* VDISCARD */
1112 if (tty_out
->flow_control
)
1115 tty
.main
.c_cc
[VSTART
] = '\021';
1118 tty
.main
.c_cc
[VSTOP
] = '\023';
1124 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1127 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1132 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1133 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1134 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1135 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1136 if (tty_out
->flow_control
)
1139 tty
.main
.c_cc
[VSTART
] = '\021';
1142 tty
.main
.c_cc
[VSTOP
] = '\023';
1145 /* Also, PTY overloads NUL and BREAK.
1146 don't ignore break, but don't signal either, so it looks like NUL.
1147 This really serves a purpose only if running in an XTERM window
1148 or via TELNET or the like, but does no harm elsewhere. */
1149 tty
.main
.c_iflag
&= ~IGNBRK
;
1150 tty
.main
.c_iflag
&= ~BRKINT
;
1152 #endif /* not DOS_NT */
1154 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1155 if (!tty_out
->term_initted
)
1156 internal_terminal_init ();
1157 dos_ttraw (tty_out
);
1160 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1162 /* This code added to insure that, if flow-control is not to be used,
1163 we have an unlocked terminal at the start. */
1166 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1169 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1172 #if !defined (DOS_NT)
1174 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1179 if (interrupt_input
)
1181 old_fcntl_owner
[fileno (tty_out
->input
)] =
1182 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1183 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1184 init_sigio (fileno (tty_out
->input
));
1186 if (gpm_tty
== tty_out
)
1188 /* Arrange for mouse events to give us SIGIO signals. */
1189 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1190 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1191 init_sigio (gpm_fd
);
1193 #endif /* HAVE_GPM */
1195 #endif /* F_GETOWN */
1198 /* This symbol is defined on recent USG systems.
1199 Someone says without this call USG won't really buffer the file
1200 even with a call to setbuf. */
1201 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1203 setbuf (tty_out
->output
, (char *) _sobuf
);
1206 if (tty_out
->terminal
->set_terminal_modes_hook
)
1207 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1209 if (!tty_out
->term_initted
)
1211 Lisp_Object tail
, frame
;
1212 FOR_EACH_FRAME (tail
, frame
)
1214 /* XXX This needs to be revised. */
1215 if (FRAME_TERMCAP_P (XFRAME (frame
))
1216 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1217 init_frame_faces (XFRAME (frame
));
1221 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1223 /* We used to call "direct_output_forward_char(0)" here,
1224 but it's not clear why, since it may not do anything anyway. */
1228 Lisp_Object tail
, frame
;
1230 FOR_EACH_FRAME (tail
, frame
)
1232 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1233 || FRAME_MSDOS_P (XFRAME (frame
)))
1234 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1235 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1239 tty_out
->term_initted
= 1;
1242 /* Return true if safe to use tabs in output.
1243 At the time this is called, init_sys_modes has not been done yet. */
1246 tabs_safe_p (int fd
)
1248 struct emacs_tty etty
;
1250 emacs_get_tty (fd
, &etty
);
1253 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1254 #else /* not TABDLY */
1256 #endif /* not TABDLY */
1262 /* Discard echoing. */
1265 suppress_echo_on_tty (int fd
)
1267 struct emacs_tty etty
;
1269 emacs_get_tty (fd
, &etty
);
1271 /* Set raw input mode. */
1274 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1275 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1276 #endif /* ! WINDOWSNT */
1277 emacs_set_tty (fd
, &etty
, 0);
1280 /* Get terminal size from system.
1281 Store number of lines into *HEIGHTP and width into *WIDTHP.
1282 We store 0 if there's no valid information. */
1285 get_tty_size (int fd
, int *widthp
, int *heightp
)
1287 #if defined TIOCGWINSZ
1290 struct winsize size
;
1292 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1293 *widthp
= *heightp
= 0;
1296 *widthp
= size
.ws_col
;
1297 *heightp
= size
.ws_row
;
1300 #elif defined TIOCGSIZE
1302 /* SunOS - style. */
1303 struct ttysize size
;
1305 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1306 *widthp
= *heightp
= 0;
1309 *widthp
= size
.ts_cols
;
1310 *heightp
= size
.ts_lines
;
1313 #elif defined WINDOWSNT
1315 CONSOLE_SCREEN_BUFFER_INFO info
;
1316 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1318 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1319 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1322 *widthp
= *heightp
= 0;
1326 *widthp
= ScreenCols ();
1327 *heightp
= ScreenRows ();
1329 #else /* system doesn't know size */
1337 /* Set the logical window size associated with descriptor FD
1338 to HEIGHT and WIDTH. This is used mainly with ptys.
1339 Return a negative value on failure. */
1342 set_window_size (int fd
, int height
, int width
)
1347 struct winsize size
;
1348 size
.ws_row
= height
;
1349 size
.ws_col
= width
;
1351 return ioctl (fd
, TIOCSWINSZ
, &size
);
1356 /* SunOS - style. */
1357 struct ttysize size
;
1358 size
.ts_lines
= height
;
1359 size
.ts_cols
= width
;
1361 return ioctl (fd
, TIOCGSIZE
, &size
);
1364 #endif /* not SunOS-style */
1365 #endif /* not BSD-style */
1370 /* Prepare all terminal devices for exiting Emacs. */
1373 reset_all_sys_modes (void)
1375 struct tty_display_info
*tty
;
1376 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1377 reset_sys_modes (tty
);
1380 /* Prepare the terminal for closing it; move the cursor to the
1381 bottom of the frame, turn off interrupt-driven I/O, etc. */
1384 reset_sys_modes (struct tty_display_info
*tty_out
)
1391 if (!tty_out
->term_initted
)
1394 if (!tty_out
->output
)
1395 return; /* The tty is suspended. */
1397 /* Go to and clear the last line of the terminal. */
1399 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1401 /* Code adapted from tty_clear_end_of_line. */
1402 if (tty_out
->TS_clr_line
)
1404 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1407 { /* have to do it the hard way */
1409 tty_turn_off_insert (tty_out
);
1411 for (i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1413 fputc (' ', tty_out
->output
);
1417 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1418 fflush (tty_out
->output
);
1420 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1421 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1423 /* Avoid possible loss of output when changing terminal modes. */
1424 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1429 if (interrupt_input
)
1431 reset_sigio (fileno (tty_out
->input
));
1432 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1433 old_fcntl_owner
[fileno (tty_out
->input
)]);
1435 #endif /* F_SETOWN */
1436 fcntl (fileno (tty_out
->input
), F_SETFL
,
1437 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1440 if (tty_out
->old_tty
)
1441 while (emacs_set_tty (fileno (tty_out
->input
),
1442 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1445 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1449 widen_foreground_group (fileno (tty_out
->input
));
1454 /* Set up the proper status flags for use of a pty. */
1459 /* I'm told that TOICREMOTE does not mean control chars
1460 "can't be sent" but rather that they don't have
1461 input-editing or signaling effects.
1462 That should be good, because we have other ways
1463 to do those things in Emacs.
1464 However, telnet mode seems not to work on 4.2.
1465 So TIOCREMOTE is turned off now. */
1467 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1468 will hang. In particular, the "timeout" feature (which
1469 causes a read to return if there is no data available)
1470 does this. Also it is known that telnet mode will hang
1471 in such a way that Emacs must be stopped (perhaps this
1472 is the same problem).
1474 If TIOCREMOTE is turned off, then there is a bug in
1475 hp-ux which sometimes loses data. Apparently the
1476 code which blocks the master process when the internal
1477 buffer fills up does not work. Other than this,
1478 though, everything else seems to work fine.
1480 Since the latter lossage is more benign, we may as well
1481 lose that way. -- cph */
1483 #if defined (UNIX98_PTYS)
1486 ioctl (fd
, FIONBIO
, &on
);
1491 #endif /* HAVE_PTYS */
1494 init_system_name (void)
1498 /* Set system-name to nil so that the build is deterministic. */
1499 Vsystem_name
= Qnil
;
1502 char *hostname_alloc
= NULL
;
1504 #ifndef HAVE_GETHOSTNAME
1507 hostname
= uts
.nodename
;
1508 #else /* HAVE_GETHOSTNAME */
1509 char hostname_buf
[256];
1510 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1511 hostname
= hostname_buf
;
1513 /* Try to get the host name; if the buffer is too short, try
1514 again. Apparently, the only indication gethostname gives of
1515 whether the buffer was large enough is the presence or absence
1516 of a '\0' in the string. Eech. */
1519 gethostname (hostname
, hostname_size
- 1);
1520 hostname
[hostname_size
- 1] = '\0';
1522 /* Was the buffer large enough for the '\0'? */
1523 if (strlen (hostname
) < hostname_size
- 1)
1526 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1527 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1529 #endif /* HAVE_GETHOSTNAME */
1531 for (p
= hostname
; *p
; p
++)
1532 if (*p
== ' ' || *p
== '\t')
1534 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1535 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1536 Vsystem_name
= build_string (hostname
);
1537 xfree (hostname_alloc
);
1540 sigset_t empty_mask
;
1542 static struct sigaction process_fatal_action
;
1545 emacs_sigaction_flags (void)
1548 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1549 'select') to reset their timeout on some platforms (e.g.,
1550 HP-UX 11), which is not what we want. Also, when Emacs is
1551 interactive, we don't want SA_RESTART because we need to poll
1552 for pending input so we need long-running syscalls to be interrupted
1553 after a signal that sets pending_signals.
1555 Non-interactive keyboard input goes through stdio, where we
1556 always want restartable system calls. */
1563 /* Store into *ACTION a signal action suitable for Emacs, with handler
1566 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1568 sigemptyset (&action
->sa_mask
);
1570 /* When handling a signal, block nonfatal system signals that are caught
1571 by Emacs. This makes race conditions less likely. */
1572 sigaddset (&action
->sa_mask
, SIGALRM
);
1574 sigaddset (&action
->sa_mask
, SIGCHLD
);
1577 sigaddset (&action
->sa_mask
, SIGDANGER
);
1579 #ifdef PROFILER_CPU_SUPPORT
1580 sigaddset (&action
->sa_mask
, SIGPROF
);
1583 sigaddset (&action
->sa_mask
, SIGWINCH
);
1585 if (! noninteractive
)
1587 sigaddset (&action
->sa_mask
, SIGINT
);
1588 sigaddset (&action
->sa_mask
, SIGQUIT
);
1590 sigaddset (&action
->sa_mask
, SIGIO
);
1594 action
->sa_handler
= handler
;
1595 action
->sa_flags
= emacs_sigaction_flags ();
1598 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1599 static pthread_t main_thread
;
1602 /* SIG has arrived at the current process. Deliver it to the main
1603 thread, which should handle it with HANDLER.
1605 If we are on the main thread, handle the signal SIG with HANDLER.
1606 Otherwise, redirect the signal to the main thread, blocking it from
1607 this thread. POSIX says any thread can receive a signal that is
1608 associated with a process, process group, or asynchronous event.
1609 On GNU/Linux that is not true, but for other systems (FreeBSD at
1612 deliver_process_signal (int sig
, signal_handler_t handler
)
1614 /* Preserve errno, to avoid race conditions with signal handlers that
1615 might change errno. Races can occur even in single-threaded hosts. */
1616 int old_errno
= errno
;
1618 bool on_main_thread
= true;
1619 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1620 if (! pthread_equal (pthread_self (), main_thread
))
1623 sigemptyset (&blocked
);
1624 sigaddset (&blocked
, sig
);
1625 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1626 pthread_kill (main_thread
, sig
);
1627 on_main_thread
= false;
1636 /* Static location to save a fatal backtrace in a thread.
1637 FIXME: If two subsidiary threads fail simultaneously, the resulting
1638 backtrace may be garbage. */
1639 enum { BACKTRACE_LIMIT_MAX
= 500 };
1640 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1641 static int thread_backtrace_npointers
;
1643 /* SIG has arrived at the current thread.
1644 If we are on the main thread, handle the signal SIG with HANDLER.
1645 Otherwise, this is a fatal error in the handling thread. */
1647 deliver_thread_signal (int sig
, signal_handler_t handler
)
1649 int old_errno
= errno
;
1651 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1652 if (! pthread_equal (pthread_self (), main_thread
))
1654 thread_backtrace_npointers
1655 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1656 sigaction (sig
, &process_fatal_action
, 0);
1657 pthread_kill (main_thread
, sig
);
1659 /* Avoid further damage while the main thread is exiting. */
1661 sigsuspend (&empty_mask
);
1669 #if !HAVE_DECL_SYS_SIGLIST
1671 # ifdef _sys_siglist
1672 # define sys_siglist _sys_siglist
1673 # elif HAVE_DECL___SYS_SIGLIST
1674 # define sys_siglist __sys_siglist
1676 # define sys_siglist my_sys_siglist
1677 static char const *sys_siglist
[NSIG
];
1682 # define sys_siglist_entries _sys_nsig
1684 # define sys_siglist_entries NSIG
1687 /* Handle bus errors, invalid instruction, etc. */
1689 handle_fatal_signal (int sig
)
1691 terminate_due_to_signal (sig
, 40);
1695 deliver_fatal_signal (int sig
)
1697 deliver_process_signal (sig
, handle_fatal_signal
);
1701 deliver_fatal_thread_signal (int sig
)
1703 deliver_thread_signal (sig
, handle_fatal_signal
);
1706 static _Noreturn
void
1707 handle_arith_signal (int sig
)
1709 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1710 xsignal0 (Qarith_error
);
1713 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1715 /* Alternate stack used by SIGSEGV handler below. */
1717 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1720 /* Return true if SIGINFO indicates a stack overflow. */
1723 stack_overflow (siginfo_t
*siginfo
)
1725 if (!attempt_stack_overflow_recovery
)
1728 /* In theory, a more-accurate heuristic can be obtained by using
1729 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1730 and pthread_attr_getguardsize to find the location and size of the
1731 guard area. In practice, though, these functions are so hard to
1732 use reliably that they're not worth bothering with. E.g., see:
1733 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1734 Other operating systems also have problems, e.g., Solaris's
1735 stack_violation function is tailor-made for this problem, but it
1736 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1738 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1744 /* The faulting address. */
1745 char *addr
= siginfo
->si_addr
;
1749 /* The known top and bottom of the stack. The actual stack may
1750 extend a bit beyond these boundaries. */
1751 char *bot
= stack_bottom
;
1752 char *top
= near_C_stack_top ();
1754 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1755 of the known stack divided by the size of the guard area past the
1756 end of the stack top. The heuristic is that a bad address is
1757 considered to be a stack overflow if it occurs within
1758 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1759 stack. This heuristic is not exactly correct but it's good
1760 enough in practice. */
1761 enum { LG_STACK_HEURISTIC
= 8 };
1764 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1766 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1770 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1773 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1775 /* Hard GC error may lead to stack overflow caused by
1776 too nested calls to mark_object. No way to survive. */
1777 bool fatal
= gc_in_progress
;
1779 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1780 if (!fatal
&& !pthread_equal (pthread_self (), main_thread
))
1784 if (!fatal
&& stack_overflow (siginfo
))
1785 siglongjmp (return_to_command_loop
, 1);
1787 /* Otherwise we can't do anything with this. */
1788 deliver_fatal_thread_signal (sig
);
1791 /* Return true if we have successfully set up SIGSEGV handler on alternate
1792 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1797 struct sigaction sa
;
1800 ss
.ss_sp
= sigsegv_stack
;
1801 ss
.ss_size
= sizeof (sigsegv_stack
);
1803 if (sigaltstack (&ss
, NULL
) < 0)
1806 sigfillset (&sa
.sa_mask
);
1807 sa
.sa_sigaction
= handle_sigsegv
;
1808 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1809 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1812 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1820 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1823 deliver_arith_signal (int sig
)
1825 deliver_thread_signal (sig
, handle_arith_signal
);
1830 /* Handler for SIGDANGER. */
1832 handle_danger_signal (int sig
)
1834 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1836 /* It might be unsafe to call do_auto_save now. */
1837 force_auto_save_soon ();
1841 deliver_danger_signal (int sig
)
1843 deliver_process_signal (sig
, handle_danger_signal
);
1847 /* Treat SIG as a terminating signal, unless it is already ignored and
1848 we are in --batch mode. Among other things, this makes nohup work. */
1850 maybe_fatal_sig (int sig
)
1852 bool catch_sig
= !noninteractive
;
1855 struct sigaction old_action
;
1856 sigaction (sig
, 0, &old_action
);
1857 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1860 sigaction (sig
, &process_fatal_action
, 0);
1864 init_signals (bool dumping
)
1866 struct sigaction thread_fatal_action
;
1867 struct sigaction action
;
1869 sigemptyset (&empty_mask
);
1871 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1872 main_thread
= pthread_self ();
1875 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1878 sys_siglist
[SIGABRT
] = "Aborted";
1880 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1882 sys_siglist
[SIGALRM
] = "Alarm clock";
1884 sys_siglist
[SIGBUS
] = "Bus error";
1887 sys_siglist
[SIGCHLD
] = "Child status changed";
1890 sys_siglist
[SIGCONT
] = "Continued";
1893 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1896 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1899 sys_siglist
[SIGEMT
] = "Emulation trap";
1901 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1903 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1906 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1908 sys_siglist
[SIGHUP
] = "Hangup";
1909 sys_siglist
[SIGILL
] = "Illegal instruction";
1910 sys_siglist
[SIGINT
] = "Interrupt";
1912 sys_siglist
[SIGIO
] = "I/O possible";
1915 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1918 sys_siglist
[SIGIOT
] = "IOT trap";
1920 sys_siglist
[SIGKILL
] = "Killed";
1922 sys_siglist
[SIGLOST
] = "Resource lost";
1925 sys_siglist
[SIGLWP
] = "SIGLWP";
1928 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1931 sys_siglist
[SIGWIND
] = "SIGPHONE";
1933 sys_siglist
[SIGPIPE
] = "Broken pipe";
1935 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1938 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1941 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1944 sys_siglist
[SIGPWR
] = "Power-fail restart";
1946 sys_siglist
[SIGQUIT
] = "Quit";
1948 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1951 sys_siglist
[SIGSAK
] = "Secure attention";
1953 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1955 sys_siglist
[SIGSOUND
] = "Sound completed";
1958 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1961 sys_siglist
[SIGSTP
] = "Stopped (user)";
1964 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1966 sys_siglist
[SIGTERM
] = "Terminated";
1968 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1971 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1974 sys_siglist
[SIGTSTP
] = "Stopped (user)";
1977 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
1980 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
1983 sys_siglist
[SIGURG
] = "Urgent I/O condition";
1986 sys_siglist
[SIGUSR1
] = "User defined signal 1";
1989 sys_siglist
[SIGUSR2
] = "User defined signal 2";
1992 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
1995 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
1998 sys_siglist
[SIGWINCH
] = "Window size changed";
2001 sys_siglist
[SIGWIND
] = "SIGWIND";
2004 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
2007 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
2010 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2012 /* Don't alter signal handlers if dumping. On some machines,
2013 changing signal handlers sets static data that would make signals
2014 fail to work right when the dumped Emacs is run. */
2018 sigfillset (&process_fatal_action
.sa_mask
);
2019 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2020 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2022 sigfillset (&thread_fatal_action
.sa_mask
);
2023 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2024 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2026 /* SIGINT may need special treatment on MS-Windows. See
2027 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2028 Please update the doc of kill-emacs, kill-emacs-hook, and
2029 NEWS if you change this. */
2031 maybe_fatal_sig (SIGHUP
);
2032 maybe_fatal_sig (SIGINT
);
2033 maybe_fatal_sig (SIGTERM
);
2035 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2036 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2037 to behave more like typical batch applications do. */
2038 if (! noninteractive
)
2039 signal (SIGPIPE
, SIG_IGN
);
2041 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2042 sigaction (SIGILL
, &thread_fatal_action
, 0);
2043 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2045 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2046 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2047 interpreter's floating point operations, so treat SIGFPE as an
2048 arith-error if it arises in the main thread. */
2049 if (IEEE_FLOATING_POINT
)
2050 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2053 emacs_sigaction_init (&action
, deliver_arith_signal
);
2054 sigaction (SIGFPE
, &action
, 0);
2058 add_user_signal (SIGUSR1
, "sigusr1");
2061 add_user_signal (SIGUSR2
, "sigusr2");
2063 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2065 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2068 sigaction (SIGORE
, &thread_fatal_action
, 0);
2071 sigaction (SIGUME
, &thread_fatal_action
, 0);
2074 sigaction (SIGDLK
, &process_fatal_action
, 0);
2077 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2080 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2083 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2086 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2088 if (!init_sigsegv ())
2089 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2091 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2093 sigaction (SIGTERM
, &process_fatal_action
, 0);
2095 signal (SIGPROF
, SIG_IGN
);
2098 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2101 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2104 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2108 /* This just means available memory is getting low. */
2109 emacs_sigaction_init (&action
, deliver_danger_signal
);
2110 sigaction (SIGDANGER
, &action
, 0);
2113 /* AIX-specific signals. */
2115 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2118 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2121 sigaction (SIGMSG
, &process_fatal_action
, 0);
2124 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2127 sigaction (SIGSAK
, &process_fatal_action
, 0);
2130 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2133 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2143 /* Figure out how many bits the system's random number generator uses.
2144 `random' and `lrand48' are assumed to return 31 usable bits.
2145 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2146 so we'll shift it and treat it like the 15-bit USG `rand'. */
2150 # define RAND_BITS 31
2151 # else /* !HAVE_RANDOM */
2152 # ifdef HAVE_LRAND48
2153 # define RAND_BITS 31
2154 # define random lrand48
2155 # else /* !HAVE_LRAND48 */
2156 # define RAND_BITS 15
2157 # if RAND_MAX == 32767
2158 # define random rand
2159 # else /* RAND_MAX != 32767 */
2160 # if RAND_MAX == 2147483647
2161 # define random() (rand () >> 16)
2162 # else /* RAND_MAX != 2147483647 */
2164 # define random rand
2166 # define random() (rand () >> 16)
2168 # endif /* RAND_MAX != 2147483647 */
2169 # endif /* RAND_MAX != 32767 */
2170 # endif /* !HAVE_LRAND48 */
2171 # endif /* !HAVE_RANDOM */
2172 #endif /* !RAND_BITS */
2175 typedef unsigned int random_seed
;
2176 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2177 #elif defined HAVE_LRAND48
2178 /* Although srand48 uses a long seed, this is unsigned long to avoid
2179 undefined behavior on signed integer overflow in init_random. */
2180 typedef unsigned long int random_seed
;
2181 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2183 typedef unsigned int random_seed
;
2184 static void set_random_seed (random_seed arg
) { srand (arg
); }
2188 seed_random (void *seed
, ptrdiff_t seed_size
)
2190 random_seed arg
= 0;
2191 unsigned char *argp
= (unsigned char *) &arg
;
2192 unsigned char *seedp
= seed
;
2193 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2194 argp
[i
% sizeof arg
] ^= seedp
[i
];
2195 set_random_seed (arg
);
2202 bool success
= false;
2204 /* First, try seeding the PRNG from the operating system's entropy
2205 source. This approach is both fast and secure. */
2207 success
= w32_init_random (&v
, sizeof v
) == 0;
2209 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2212 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2217 /* If that didn't work, try using GnuTLS, which is secure, but on
2218 some systems, can be somewhat slow. */
2220 success
= EQ (emacs_gnutls_global_init (), Qt
)
2221 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2223 /* If _that_ didn't work, just use the current time value and PID.
2224 It's at least better than XKCD 221. */
2227 struct timespec t
= current_timespec ();
2228 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2231 set_random_seed (v
);
2235 * Return a nonnegative random integer out of whatever we've got.
2236 * It contains enough bits to make a random (signed) Emacs fixnum.
2237 * This suffices even for a 64-bit architecture with a 15-bit rand.
2244 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2245 val
= (random () ^ (val
<< RAND_BITS
)
2246 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2247 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2248 return val
& INTMASK
;
2251 #ifndef HAVE_SNPRINTF
2252 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2254 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2256 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2257 ptrdiff_t nbytes
= size
- 1;
2262 va_start (ap
, format
);
2263 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2267 if (nbytes
== size
- 1)
2269 /* Calculate the length of the string that would have been created
2270 had the buffer been large enough. */
2271 char stackbuf
[4000];
2273 ptrdiff_t bsize
= sizeof stackbuf
;
2274 va_start (ap
, format
);
2275 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2281 if (INT_MAX
< nbytes
)
2294 /* If a backtrace is available, output the top lines of it to stderr.
2295 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2296 This function may be called from a signal handler, so it should
2297 not invoke async-unsafe functions like malloc.
2299 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2300 but do not output anything. This avoids some problems that can
2301 otherwise occur if the malloc arena is corrupted before 'backtrace'
2302 is called, since 'backtrace' may call malloc if the tables are not
2305 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2306 fatal error has occurred in some other thread; generate a thread
2307 backtrace instead, ignoring BACKTRACE_LIMIT. */
2309 emacs_backtrace (int backtrace_limit
)
2311 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2312 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2316 if (thread_backtrace_npointers
)
2318 buffer
= thread_backtrace_buffer
;
2319 npointers
= thread_backtrace_npointers
;
2323 buffer
= main_backtrace_buffer
;
2325 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2326 if (bounded_limit
< 0)
2328 backtrace (buffer
, 1);
2332 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2337 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2338 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2339 if (bounded_limit
< npointers
)
2340 emacs_write (STDERR_FILENO
, "...\n", 4);
2348 terminate_due_to_signal (SIGABRT
, 40);
2352 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2353 Use binary I/O on systems that care about text vs binary I/O.
2354 Arrange for subprograms to not inherit the file descriptor.
2355 Prefer a method that is multithread-safe, if available.
2356 Do not fail merely because the open was interrupted by a signal.
2357 Allow the user to quit. */
2360 emacs_open (const char *file
, int oflags
, int mode
)
2363 if (! (oflags
& O_TEXT
))
2365 oflags
|= O_CLOEXEC
;
2366 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2368 if (! O_CLOEXEC
&& 0 <= fd
)
2369 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2373 /* Open FILE as a stream for Emacs use, with mode MODE.
2374 Act like emacs_open with respect to threads, signals, and quits. */
2377 emacs_fopen (char const *file
, char const *mode
)
2379 int fd
, omode
, oflags
;
2381 char const *m
= mode
;
2385 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2386 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2387 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2388 default: emacs_abort ();
2394 case '+': omode
= O_RDWR
; break;
2395 case 't': bflag
= O_TEXT
; break;
2396 default: /* Ignore. */ break;
2399 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2400 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2403 /* Create a pipe for Emacs use. */
2406 emacs_pipe (int fd
[2])
2411 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2412 if (! O_CLOEXEC
&& result
== 0)
2414 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2415 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2421 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2422 For the background behind this mess, please see Austin Group defect 529
2423 <http://austingroupbugs.net/view.php?id=529>. */
2425 #ifndef POSIX_CLOSE_RESTART
2426 # define POSIX_CLOSE_RESTART 1
2428 posix_close (int fd
, int flag
)
2430 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2431 eassert (flag
== POSIX_CLOSE_RESTART
);
2433 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2434 on a system that does not define POSIX_CLOSE_RESTART.
2436 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2437 closed, and retrying the close could inadvertently close a file
2438 descriptor allocated by some other thread. In other systems
2439 (e.g., HP/UX) FD is not closed. And in still other systems
2440 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2441 multithreaded program there can be no way to tell.
2443 So, in this case, pretend that the close succeeded. This works
2444 well on systems like GNU/Linux that close FD. Although it may
2445 leak a file descriptor on other systems, the leak is unlikely and
2446 it's better to leak than to close a random victim. */
2447 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2451 /* Close FD, retrying if interrupted. If successful, return 0;
2452 otherwise, return -1 and set errno to a non-EINTR value. Consider
2453 an EINPROGRESS error to be successful, as that's merely a signal
2454 arriving. FD is always closed when this function returns, even
2457 Do not call this function if FD is nonnegative and might already be closed,
2458 as that might close an innocent victim opened by some other thread. */
2461 emacs_close (int fd
)
2465 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2468 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2470 eassert (errno
!= EBADF
|| fd
< 0);
2471 return errno
== EINPROGRESS
? 0 : r
;
2476 /* Maximum number of bytes to read or write in a single system call.
2477 This works around a serious bug in Linux kernels before 2.6.16; see
2478 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2479 It's likely to work around similar bugs in other operating systems, so do it
2480 on all platforms. Round INT_MAX down to a page size, with the conservative
2481 assumption that page sizes are at most 2**18 bytes (any kernel with a
2482 page size larger than that shouldn't have the bug). */
2483 #ifndef MAX_RW_COUNT
2484 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2487 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2488 Return the number of bytes read, which might be less than NBYTE.
2489 On error, set errno and return -1. */
2491 emacs_read (int fildes
, void *buf
, ptrdiff_t nbyte
)
2495 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2496 passes a size that large to emacs_read. */
2498 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
2499 && (errno
== EINTR
))
2504 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2505 or if a partial write occurs. If interrupted, process pending
2506 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2507 errno if this is less than NBYTE. */
2509 emacs_full_write (int fildes
, char const *buf
, ptrdiff_t nbyte
,
2510 bool process_signals
)
2512 ptrdiff_t bytes_written
= 0;
2516 ssize_t n
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
2522 /* I originally used `QUIT' but that might cause files to
2523 be truncated if you hit C-g in the middle of it. --Stef */
2524 if (process_signals
&& pending_signals
)
2525 process_pending_signals ();
2537 return bytes_written
;
2540 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2541 interrupted or if a partial write occurs. Return the number of
2542 bytes written, setting errno if this is less than NBYTE. */
2544 emacs_write (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2546 return emacs_full_write (fildes
, buf
, nbyte
, 0);
2549 /* Like emacs_write, but also process pending signals if interrupted. */
2551 emacs_write_sig (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2553 return emacs_full_write (fildes
, buf
, nbyte
, 1);
2556 /* Write a diagnostic to standard error that contains MESSAGE and a
2557 string derived from errno. Preserve errno. Do not buffer stderr.
2558 Do not process pending signals if interrupted. */
2560 emacs_perror (char const *message
)
2563 char const *error_string
= emacs_strerror (err
);
2564 char const *command
= (initial_argv
&& initial_argv
[0]
2565 ? initial_argv
[0] : "emacs");
2566 /* Write it out all at once, if it's short; this is less likely to
2567 be interleaved with other output. */
2569 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2570 command
, message
, error_string
);
2571 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2572 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2575 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2576 emacs_write (STDERR_FILENO
, ": ", 2);
2577 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2578 emacs_write (STDERR_FILENO
, ": ", 2);
2579 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2580 emacs_write (STDERR_FILENO
, "\n", 1);
2585 /* Return a struct timeval that is roughly equivalent to T.
2586 Use the least timeval not less than T.
2587 Return an extremal value if the result would overflow. */
2589 make_timeval (struct timespec t
)
2592 tv
.tv_sec
= t
.tv_sec
;
2593 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2595 if (t
.tv_nsec
% 1000 != 0)
2597 if (tv
.tv_usec
< 999999)
2599 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2609 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2610 ATIME and MTIME, respectively.
2611 FD must be either negative -- in which case it is ignored --
2612 or a file descriptor that is open on FILE.
2613 If FD is nonnegative, then FILE can be NULL. */
2615 set_file_times (int fd
, const char *filename
,
2616 struct timespec atime
, struct timespec mtime
)
2618 struct timespec timespec
[2];
2619 timespec
[0] = atime
;
2620 timespec
[1] = mtime
;
2621 return fdutimens (fd
, filename
, timespec
);
2624 /* Like strsignal, except async-signal-safe, and this function typically
2625 returns a string in the C locale rather than the current locale. */
2627 safe_strsignal (int code
)
2629 char const *signame
= 0;
2631 if (0 <= code
&& code
< sys_siglist_entries
)
2632 signame
= sys_siglist
[code
];
2634 signame
= "Unknown signal";
2640 /* For make-serial-process */
2642 serial_open (Lisp_Object port
)
2644 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2646 report_file_error ("Opening serial port", port
);
2648 ioctl (fd
, TIOCEXCL
, (char *) 0);
2654 #if !defined (HAVE_CFMAKERAW)
2655 /* Workaround for targets which are missing cfmakeraw. */
2656 /* Pasted from man page. */
2658 cfmakeraw (struct termios
*termios_p
)
2660 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2661 termios_p
->c_oflag
&= ~OPOST
;
2662 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2663 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2664 termios_p
->c_cflag
|= CS8
;
2666 #endif /* !defined (HAVE_CFMAKERAW */
2668 #if !defined (HAVE_CFSETSPEED)
2669 /* Workaround for targets which are missing cfsetspeed. */
2671 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2673 return (cfsetispeed (termios_p
, vitesse
)
2674 + cfsetospeed (termios_p
, vitesse
));
2678 /* For serial-process-configure */
2680 serial_configure (struct Lisp_Process
*p
,
2681 Lisp_Object contact
)
2683 Lisp_Object childp2
= Qnil
;
2684 Lisp_Object tem
= Qnil
;
2685 struct termios attr
;
2687 char summary
[4] = "???"; /* This usually becomes "8N1". */
2689 childp2
= Fcopy_sequence (p
->childp
);
2691 /* Read port attributes and prepare default configuration. */
2692 err
= tcgetattr (p
->outfd
, &attr
);
2694 report_file_error ("Failed tcgetattr", Qnil
);
2696 #if defined (CLOCAL)
2697 attr
.c_cflag
|= CLOCAL
;
2700 attr
.c_cflag
|= CREAD
;
2703 /* Configure speed. */
2704 if (!NILP (Fplist_member (contact
, QCspeed
)))
2705 tem
= Fplist_get (contact
, QCspeed
);
2707 tem
= Fplist_get (p
->childp
, QCspeed
);
2709 err
= cfsetspeed (&attr
, XINT (tem
));
2711 report_file_error ("Failed cfsetspeed", tem
);
2712 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2714 /* Configure bytesize. */
2715 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2716 tem
= Fplist_get (contact
, QCbytesize
);
2718 tem
= Fplist_get (p
->childp
, QCbytesize
);
2720 tem
= make_number (8);
2722 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2723 error (":bytesize must be nil (8), 7, or 8");
2724 summary
[0] = XINT (tem
) + '0';
2725 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2726 attr
.c_cflag
&= ~CSIZE
;
2727 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2729 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2730 if (XINT (tem
) != 8)
2731 error ("Bytesize cannot be changed");
2733 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2735 /* Configure parity. */
2736 if (!NILP (Fplist_member (contact
, QCparity
)))
2737 tem
= Fplist_get (contact
, QCparity
);
2739 tem
= Fplist_get (p
->childp
, QCparity
);
2740 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2741 error (":parity must be nil (no parity), `even', or `odd'");
2742 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2743 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2744 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2749 else if (EQ (tem
, Qeven
))
2752 attr
.c_cflag
|= PARENB
;
2753 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2755 else if (EQ (tem
, Qodd
))
2758 attr
.c_cflag
|= (PARENB
| PARODD
);
2759 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2762 /* Don't error on no parity, which should be set by cfmakeraw. */
2764 error ("Parity cannot be configured");
2766 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2768 /* Configure stopbits. */
2769 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2770 tem
= Fplist_get (contact
, QCstopbits
);
2772 tem
= Fplist_get (p
->childp
, QCstopbits
);
2774 tem
= make_number (1);
2776 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2777 error (":stopbits must be nil (1 stopbit), 1, or 2");
2778 summary
[2] = XINT (tem
) + '0';
2779 #if defined (CSTOPB)
2780 attr
.c_cflag
&= ~CSTOPB
;
2781 if (XINT (tem
) == 2)
2782 attr
.c_cflag
|= CSTOPB
;
2784 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2785 if (XINT (tem
) != 1)
2786 error ("Stopbits cannot be configured");
2788 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2790 /* Configure flowcontrol. */
2791 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2792 tem
= Fplist_get (contact
, QCflowcontrol
);
2794 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2795 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2796 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2797 #if defined (CRTSCTS)
2798 attr
.c_cflag
&= ~CRTSCTS
;
2800 #if defined (CNEW_RTSCTS)
2801 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2803 #if defined (IXON) && defined (IXOFF)
2804 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2808 /* Already configured. */
2810 else if (EQ (tem
, Qhw
))
2812 #if defined (CRTSCTS)
2813 attr
.c_cflag
|= CRTSCTS
;
2814 #elif defined (CNEW_RTSCTS)
2815 attr
.c_cflag
|= CNEW_RTSCTS
;
2817 error ("Hardware flowcontrol (RTS/CTS) not supported");
2820 else if (EQ (tem
, Qsw
))
2822 #if defined (IXON) && defined (IXOFF)
2823 attr
.c_iflag
|= (IXON
| IXOFF
);
2825 error ("Software flowcontrol (XON/XOFF) not supported");
2828 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2830 /* Activate configuration. */
2831 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2833 report_file_error ("Failed tcsetattr", Qnil
);
2835 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2836 pset_childp (p
, childp2
);
2838 #endif /* not DOS_NT */
2840 /* System depended enumeration of and access to system processes a-la ps(1). */
2844 /* Process enumeration and access via /proc. */
2847 list_system_processes (void)
2849 Lisp_Object procdir
, match
, proclist
, next
;
2852 /* For every process on the system, there's a directory in the
2853 "/proc" pseudo-directory whose name is the numeric ID of that
2855 procdir
= build_string ("/proc");
2856 match
= build_string ("[0-9]+");
2857 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2859 /* `proclist' gives process IDs as strings. Destructively convert
2860 each string into a number. */
2861 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2864 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2867 /* directory_files_internal returns the files in reverse order; undo
2869 proclist
= Fnreverse (proclist
);
2873 #elif defined DARWIN_OS || defined __FreeBSD__
2876 list_system_processes (void)
2879 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2881 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2884 struct kinfo_proc
*procs
;
2887 Lisp_Object proclist
= Qnil
;
2889 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2892 procs
= xmalloc (len
);
2893 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2899 len
/= sizeof (struct kinfo_proc
);
2900 for (i
= 0; i
< len
; i
++)
2903 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2905 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2914 /* The WINDOWSNT implementation is in w32.c.
2915 The MSDOS implementation is in dosfns.c. */
2916 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2919 list_system_processes (void)
2924 #endif /* !defined (WINDOWSNT) */
2926 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2927 static struct timespec
2928 time_from_jiffies (unsigned long long tval
, long hz
)
2930 unsigned long long s
= tval
/ hz
;
2931 unsigned long long frac
= tval
% hz
;
2934 if (TYPE_MAXIMUM (time_t) < s
)
2936 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2937 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2938 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2941 /* This is reachable only in the unlikely case that HZ * HZ
2942 exceeds ULLONG_MAX. It calculates an approximation that is
2943 guaranteed to be in range. */
2944 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
2945 + (hz
% TIMESPEC_RESOLUTION
!= 0));
2946 ns
= frac
/ hz_per_ns
;
2949 return make_timespec (s
, ns
);
2953 ltime_from_jiffies (unsigned long long tval
, long hz
)
2955 struct timespec t
= time_from_jiffies (tval
, hz
);
2956 return make_lisp_time (t
);
2959 static struct timespec
2963 struct timespec up
= make_timespec (0, 0);
2966 fup
= emacs_fopen ("/proc/uptime", "r");
2970 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
2971 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
2973 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
2974 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
2975 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
2978 if (TYPE_MAXIMUM (time_t) < upsec
)
2980 upsec
= TYPE_MAXIMUM (time_t);
2981 upfrac
= TIMESPEC_RESOLUTION
- 1;
2985 int upfraclen
= upfrac_end
- upfrac_start
;
2986 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
2988 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
2990 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
2992 up
= make_timespec (upsec
, upfrac
);
3001 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3002 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3005 procfs_ttyname (int rdev
)
3008 char name
[PATH_MAX
];
3011 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3017 unsigned long minor_beg
, minor_end
;
3018 char minor
[25]; /* 2 32-bit numbers + dash */
3021 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3023 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3024 && major
== MAJOR (rdev
))
3026 minor_beg
= strtoul (minor
, &endp
, 0);
3028 minor_end
= minor_beg
;
3029 else if (*endp
== '-')
3030 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3034 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3036 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3044 return build_string (name
);
3048 procfs_get_total_memory (void)
3051 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3055 fmem
= emacs_fopen ("/proc/meminfo", "r");
3059 uintmax_t entry_value
;
3063 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3066 retval
= entry_value
;
3071 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3089 system_process_attributes (Lisp_Object pid
)
3091 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3095 long clocks_per_sec
;
3097 char procbuf
[1025], *p
, *q
;
3100 static char const default_cmd
[] = "???";
3101 const char *cmd
= default_cmd
;
3102 int cmdsize
= sizeof default_cmd
- 1;
3103 char *cmdline
= NULL
;
3104 ptrdiff_t cmdline_size
;
3107 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3110 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3111 long priority
, niceness
, rss
;
3112 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3113 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3115 Lisp_Object attrs
= Qnil
;
3116 Lisp_Object decoded_cmd
;
3119 CHECK_NUMBER_OR_FLOAT (pid
);
3120 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3121 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3122 if (stat (procfn
, &st
) < 0)
3127 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3129 pw
= getpwuid (uid
);
3132 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3135 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3137 gr
= getgrgid (gid
);
3140 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3142 count
= SPECPDL_INDEX ();
3143 strcpy (fn
, procfn
);
3144 procfn_end
= fn
+ strlen (fn
);
3145 strcpy (procfn_end
, "/stat");
3146 fd
= emacs_open (fn
, O_RDONLY
, 0);
3151 record_unwind_protect_int (close_file_unwind
, fd
);
3152 nread
= emacs_read (fd
, procbuf
, sizeof procbuf
- 1);
3156 procbuf
[nread
] = '\0';
3159 p
= strchr (p
, '(');
3162 q
= strrchr (p
+ 1, ')');
3172 /* Command name is encoded in locale-coding-system; decode it. */
3173 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3174 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3175 Vlocale_coding_system
, 0);
3176 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3178 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3179 utime stime cutime cstime priority nice thcount . start vsize rss */
3181 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3182 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3183 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3184 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3185 &u_time
, &s_time
, &cutime
, &cstime
,
3186 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3191 state_str
[1] = '\0';
3192 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3193 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3194 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3195 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3196 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3197 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3198 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3199 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3200 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3202 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3204 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3205 if (clocks_per_sec
< 0)
3206 clocks_per_sec
= 100;
3207 attrs
= Fcons (Fcons (Qutime
,
3208 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3210 attrs
= Fcons (Fcons (Qstime
,
3211 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3213 attrs
= Fcons (Fcons (Qtime
,
3214 ltime_from_jiffies (s_time
+ u_time
,
3217 attrs
= Fcons (Fcons (Qcutime
,
3218 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3220 attrs
= Fcons (Fcons (Qcstime
,
3221 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3223 attrs
= Fcons (Fcons (Qctime
,
3224 ltime_from_jiffies (cstime
+ cutime
,
3227 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3228 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3229 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3231 tnow
= current_timespec ();
3232 telapsed
= get_up_time ();
3233 tboot
= timespec_sub (tnow
, telapsed
);
3234 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3235 tstart
= timespec_add (tboot
, tstart
);
3236 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3237 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3239 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3240 telapsed
= timespec_sub (tnow
, tstart
);
3241 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3242 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3243 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3246 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3247 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3250 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3253 unbind_to (count
, Qnil
);
3256 strcpy (procfn_end
, "/cmdline");
3257 fd
= emacs_open (fn
, O_RDONLY
, 0);
3260 ptrdiff_t readsize
, nread_incr
;
3261 record_unwind_protect_int (close_file_unwind
, fd
);
3262 record_unwind_protect_nothing ();
3263 nread
= cmdline_size
= 0;
3267 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3268 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3270 /* Leave room even if every byte needs escaping below. */
3271 readsize
= (cmdline_size
>> 1) - nread
;
3273 nread_incr
= emacs_read (fd
, cmdline
+ nread
, readsize
);
3274 nread
+= max (0, nread_incr
);
3276 while (nread_incr
== readsize
);
3280 /* We don't want trailing null characters. */
3281 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3284 /* Escape-quote whitespace and backslashes. */
3285 q
= cmdline
+ cmdline_size
;
3290 if (c_isspace (c
) || c
== '\\')
3294 nread
= cmdline
+ cmdline_size
- q
;
3299 nread
= cmdsize
+ 2;
3300 cmdline_size
= nread
+ 1;
3301 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3302 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3303 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3305 /* Command line is encoded in locale-coding-system; decode it. */
3306 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3307 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3308 Vlocale_coding_system
, 0);
3309 unbind_to (count
, Qnil
);
3310 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3316 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3318 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3319 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3320 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3321 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3322 #undef _FILE_OFFSET_BITS
3324 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3329 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3330 #define _FILE_OFFSET_BITS 64
3331 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3333 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3336 system_process_attributes (Lisp_Object pid
)
3338 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3343 struct psinfo pinfo
;
3349 Lisp_Object attrs
= Qnil
;
3350 Lisp_Object decoded_cmd
;
3353 CHECK_NUMBER_OR_FLOAT (pid
);
3354 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3355 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3356 if (stat (procfn
, &st
) < 0)
3361 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3363 pw
= getpwuid (uid
);
3366 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3369 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3371 gr
= getgrgid (gid
);
3374 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3376 count
= SPECPDL_INDEX ();
3377 strcpy (fn
, procfn
);
3378 procfn_end
= fn
+ strlen (fn
);
3379 strcpy (procfn_end
, "/psinfo");
3380 fd
= emacs_open (fn
, O_RDONLY
, 0);
3385 record_unwind_protect_int (close_file_unwind
, fd
);
3386 nread
= emacs_read (fd
, &pinfo
, sizeof pinfo
);
3389 if (nread
== sizeof pinfo
)
3391 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3392 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3393 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3397 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3398 state_str
[1] = '\0';
3399 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3402 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3403 need to get a string from it. */
3405 /* FIXME: missing: Qtpgid */
3417 Are they available? */
3419 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3420 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3421 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3422 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3423 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3426 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3427 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3429 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3432 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3433 range 0 .. 2**15, representing 0.0 .. 1.0. */
3434 attrs
= Fcons (Fcons (Qpcpu
,
3435 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3437 attrs
= Fcons (Fcons (Qpmem
,
3438 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3441 AUTO_STRING (fname
, pinfo
.pr_fname
);
3442 decoded_cmd
= code_convert_string_norecord (fname
,
3443 Vlocale_coding_system
, 0);
3444 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3445 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3446 decoded_cmd
= code_convert_string_norecord (psargs
,
3447 Vlocale_coding_system
, 0);
3448 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3450 unbind_to (count
, Qnil
);
3454 #elif defined __FreeBSD__
3456 static struct timespec
3457 timeval_to_timespec (struct timeval t
)
3459 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3463 make_lisp_timeval (struct timeval t
)
3465 return make_lisp_time (timeval_to_timespec (t
));
3469 system_process_attributes (Lisp_Object pid
)
3472 int pagesize
= getpagesize ();
3473 unsigned long npages
;
3479 char args
[MAXPATHLEN
];
3480 struct timespec t
, now
;
3482 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3483 struct kinfo_proc proc
;
3484 size_t proclen
= sizeof proc
;
3486 Lisp_Object attrs
= Qnil
;
3487 Lisp_Object decoded_comm
;
3489 CHECK_NUMBER_OR_FLOAT (pid
);
3490 CONS_TO_INTEGER (pid
, int, proc_id
);
3493 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3496 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3499 pw
= getpwuid (proc
.ki_uid
);
3502 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3504 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3507 gr
= getgrgid (proc
.ki_svgid
);
3510 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3512 AUTO_STRING (comm
, proc
.ki_comm
);
3513 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3515 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3517 char state
[2] = {'\0', '\0'};
3518 switch (proc
.ki_stat
)
3540 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3543 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3544 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3545 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3548 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3551 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3553 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3554 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3555 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3556 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3557 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3559 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3561 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3563 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3564 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3565 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3567 attrs
= Fcons (Fcons (Qcutime
,
3568 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3570 attrs
= Fcons (Fcons (Qcstime
,
3571 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3573 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3574 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3575 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3577 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3579 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3580 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3581 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3582 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3583 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3586 now
= current_timespec ();
3587 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3588 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3590 len
= sizeof fscale
;
3591 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3596 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3598 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3599 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3600 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3604 len
= sizeof npages
;
3605 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3607 double pmem
= (proc
.ki_flag
& P_INMEM
3608 ? 100.0 * proc
.ki_rssize
/ npages
3610 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3613 mib
[2] = KERN_PROC_ARGS
;
3615 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3618 for (i
= 0; i
< len
; i
++)
3620 if (! args
[i
] && i
< len
- 1)
3624 AUTO_STRING (comm
, args
);
3625 decoded_comm
= code_convert_string_norecord (comm
,
3626 Vlocale_coding_system
, 0);
3628 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3634 #elif defined DARWIN_OS
3636 static struct timespec
3637 timeval_to_timespec (struct timeval t
)
3639 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3643 make_lisp_timeval (struct timeval t
)
3645 return make_lisp_time (timeval_to_timespec (t
));
3649 system_process_attributes (Lisp_Object pid
)
3652 int pagesize
= getpagesize ();
3653 unsigned long npages
;
3659 char args
[MAXPATHLEN
];
3660 struct timeval starttime
;
3661 struct timespec t
, now
;
3662 struct rusage
*rusage
;
3667 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3668 struct kinfo_proc proc
;
3669 size_t proclen
= sizeof proc
;
3671 Lisp_Object attrs
= Qnil
;
3672 Lisp_Object decoded_comm
;
3674 CHECK_NUMBER_OR_FLOAT (pid
);
3675 CONS_TO_INTEGER (pid
, int, proc_id
);
3678 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3681 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3682 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3685 pw
= getpwuid (uid
);
3688 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3690 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3691 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3694 gr
= getgrgid (gid
);
3697 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3699 decoded_comm
= (code_convert_string_norecord
3700 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3701 Vlocale_coding_system
, 0));
3703 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3705 char state
[2] = {'\0', '\0'};
3706 switch (proc
.kp_proc
.p_stat
)
3728 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3731 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3733 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3736 tdev
= proc
.kp_eproc
.e_tdev
;
3738 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3741 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3743 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3746 rusage
= proc
.kp_proc
.p_ru
;
3749 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3751 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3754 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3756 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3758 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3759 timeval_to_timespec (rusage
->ru_stime
));
3760 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3763 starttime
= proc
.kp_proc
.p_starttime
;
3764 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3765 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3767 now
= current_timespec ();
3768 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3769 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3774 /* The WINDOWSNT implementation is in w32.c.
3775 The MSDOS implementation is in dosfns.c. */
3776 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3779 system_process_attributes (Lisp_Object pid
)
3784 #endif /* !defined (WINDOWSNT) */
3786 /* Wide character string collation. */
3788 #ifdef __STDC_ISO_10646__
3790 # include <wctype.h>
3792 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3793 # include <locale.h>
3796 # define LC_COLLATE 0
3798 # ifndef LC_COLLATE_MASK
3799 # define LC_COLLATE_MASK 0
3804 # ifndef LC_CTYPE_MASK
3805 # define LC_CTYPE_MASK 0
3808 # ifndef HAVE_NEWLOCALE
3814 # define freelocale emacs_freelocale
3815 # define locale_t emacs_locale_t
3816 # define newlocale emacs_newlocale
3817 # define wcscoll_l emacs_wcscoll_l
3818 # define towlower_l emacs_towlower_l
3820 typedef char const *locale_t
;
3823 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3829 freelocale (locale_t loc
)
3834 emacs_setlocale (int category
, char const *locale
)
3836 # ifdef HAVE_SETLOCALE
3838 char *loc
= setlocale (category
, locale
);
3849 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3852 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3860 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3861 strcpy (oldcopy
, oldloc
);
3862 if (! emacs_setlocale (LC_COLLATE
, loc
))
3867 result
= wcscoll (a
, b
);
3869 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3880 towlower_l (wint_t wc
, locale_t loc
)
3883 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3888 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3889 strcpy (oldcopy
, oldloc
);
3890 if (emacs_setlocale (LC_CTYPE
, loc
))
3892 result
= towlower (wc
);
3893 emacs_setlocale (LC_COLLATE
, oldcopy
);
3903 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3904 Lisp_Object locale
, Lisp_Object ignore_case
)
3907 ptrdiff_t len
, i
, i_byte
;
3912 /* Convert byte stream to code points. */
3913 len
= SCHARS (s1
); i
= i_byte
= 0;
3914 SAFE_NALLOCA (p1
, 1, len
+ 1);
3916 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3919 len
= SCHARS (s2
); i
= i_byte
= 0;
3920 SAFE_NALLOCA (p2
, 1, len
+ 1);
3922 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3925 if (STRINGP (locale
))
3927 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3928 SSDATA (locale
), 0);
3930 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3932 if (! NILP (ignore_case
))
3933 for (int i
= 1; i
< 3; i
++)
3935 wchar_t *p
= (i
== 1) ? p1
: p2
;
3937 *p
= towlower_l (*p
, loc
);
3941 res
= wcscoll_l (p1
, p2
, loc
);
3947 if (! NILP (ignore_case
))
3948 for (int i
= 1; i
< 3; i
++)
3950 wchar_t *p
= (i
== 1) ? p1
: p2
;
3956 res
= wcscoll (p1
, p2
);
3959 # ifndef HAVE_NEWLOCALE
3961 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
3964 error ("Invalid string for collation: %s", emacs_strerror (err
));
3970 #endif /* __STDC_ISO_10646__ */
3974 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3975 Lisp_Object locale
, Lisp_Object ignore_case
)
3978 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
3979 int res
, err
= errno
;
3982 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
3984 error ("Invalid string for collation: %s", strerror (errno
));
3989 #endif /* WINDOWSNT */