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>
56 #define write sys_write
58 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
61 #endif /* not WINDOWSNT */
63 #include <sys/types.h>
67 /* Get SI_SRPC_DOMAIN, if it is available. */
68 #ifdef HAVE_SYS_SYSTEMINFO_H
69 #include <sys/systeminfo.h>
72 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
76 #include <sys/param.h>
83 #ifdef HAVE_SYS_UTSNAME_H
84 #include <sys/utsname.h>
86 #endif /* HAVE_SYS_UTSNAME_H */
90 #include "termhooks.h"
97 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
98 do that during startup just to call gnutls_rnd. */
99 #if defined HAVE_GNUTLS && !defined WINDOWSNT
100 # include <gnutls/crypto.h>
102 # define emacs_gnutls_global_init() Qnil
103 # define gnutls_rnd(level, data, len) (-1)
108 /* In process.h which conflicts with the local copy. */
110 int _cdecl
_spawnlp (int, const char *, const char *, ...);
111 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
112 several prototypes of functions called below. */
113 #include <sys/socket.h>
116 #include "syssignal.h"
119 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
121 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
124 /* Declare here, including term.h is problematic on some systems. */
125 extern void tputs (const char *, int, int (*)(int));
127 static const int baud_convert
[] =
129 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
130 1800, 2400, 4800, 9600, 19200, 38400
133 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
134 # include <sys/personality.h>
136 /* Disable address randomization in the current process. Return true
137 if addresses were randomized but this has been disabled, false
140 disable_address_randomization (void)
142 bool disabled
= false;
143 int pers
= personality (0xffffffff);
144 disabled
= (! (pers
& ADDR_NO_RANDOMIZE
)
145 && 0 <= personality (pers
| ADDR_NO_RANDOMIZE
));
150 /* Execute the program in FILE, with argument vector ARGV and environ
151 ENVP. Return an error number if unsuccessful. This is like execve
152 except it reenables ASLR in the executed program if necessary, and
153 on error it returns an error number rather than -1. */
155 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
157 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
158 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
159 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
160 if (change_personality
)
161 personality (pers
& ~ADDR_NO_RANDOMIZE
);
164 execve (file
, argv
, envp
);
167 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
168 if (change_personality
)
175 /* If FD is not already open, arrange for it to be open with FLAGS. */
177 force_open (int fd
, int flags
)
179 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
181 int n
= open (NULL_DEVICE
, flags
);
182 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
184 emacs_perror (NULL_DEVICE
);
190 /* Make sure stdin, stdout, and stderr are open to something, so that
191 their file descriptors are not hijacked by later system calls. */
193 init_standard_fds (void)
195 /* Open stdin for *writing*, and stdout and stderr for *reading*.
196 That way, any attempt to do normal I/O will result in an error,
197 just as if the files were closed, and the file descriptors will
198 not be reused by later opens. */
199 force_open (STDIN_FILENO
, O_WRONLY
);
200 force_open (STDOUT_FILENO
, O_RDONLY
);
201 force_open (STDERR_FILENO
, O_RDONLY
);
204 /* Return the current working directory. The result should be freed
205 with 'free'. Return NULL on errors. */
207 emacs_get_current_dir_name (void)
209 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
210 # ifdef HYBRID_MALLOC
211 bool use_libc
= bss_sbrk_did_unexec
;
213 bool use_libc
= true;
216 return get_current_dir_name ();
220 char *pwd
= getenv ("PWD");
221 struct stat dotstat
, pwdstat
;
222 /* If PWD is accurate, use it instead of calling getcwd. PWD is
223 sometimes a nicer name, and using it may avoid a fatal error if a
224 parent directory is searchable but not readable. */
226 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
227 && stat (pwd
, &pwdstat
) == 0
228 && stat (".", &dotstat
) == 0
229 && dotstat
.st_ino
== pwdstat
.st_ino
230 && dotstat
.st_dev
== pwdstat
.st_dev
232 && strlen (pwd
) < MAXPATHLEN
236 buf
= malloc (strlen (pwd
) + 1);
243 size_t buf_size
= 1024;
244 buf
= malloc (buf_size
);
249 if (getcwd (buf
, buf_size
) == buf
)
253 int tmp_errno
= errno
;
259 buf
= realloc (buf
, buf_size
);
268 /* Discard pending input on all input descriptors. */
271 discard_tty_input (void)
274 struct emacs_tty buf
;
279 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
280 while (dos_keyread () != -1)
282 #else /* not MSDOS */
284 struct tty_display_info
*tty
;
285 for (tty
= tty_list
; tty
; tty
= tty
->next
)
287 if (tty
->input
) /* Is the device suspended? */
289 emacs_get_tty (fileno (tty
->input
), &buf
);
290 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
294 #endif /* not MSDOS */
295 #endif /* not WINDOWSNT */
301 /* Arrange for character C to be read as the next input from
303 XXX What if we have multiple ttys?
309 if (! (FRAMEP (selected_frame
)
310 && FRAME_LIVE_P (XFRAME (selected_frame
))
311 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
314 /* Should perhaps error if in batch mode */
316 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
317 #else /* no TIOCSTI */
318 error ("Cannot stuff terminal input characters in this version of Unix");
319 #endif /* no TIOCSTI */
325 init_baud_rate (int fd
)
335 #else /* not DOS_NT */
340 emacs_ospeed
= cfgetospeed (&sg
);
341 #endif /* not DOS_NT */
344 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
345 ? baud_convert
[emacs_ospeed
] : 9600);
354 /* Wait for the subprocess with process id CHILD to terminate or change status.
355 CHILD must be a child process that has not been reaped.
356 If STATUS is non-null, store the waitpid-style exit status into *STATUS
357 and tell wait_reading_process_output that it needs to look around.
358 Use waitpid-style OPTIONS when waiting.
359 If INTERRUPTIBLE, this function is interruptible by a signal.
361 Return CHILD if successful, 0 if no status is available;
362 the latter is possible only when options & NOHANG. */
364 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
368 /* Invoke waitpid only with a known process ID; do not invoke
369 waitpid with a nonpositive argument. Otherwise, Emacs might
370 reap an unwanted process by mistake. For example, invoking
371 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
372 so that another thread running glib won't find them. */
375 while ((pid
= waitpid (child
, status
, options
)) < 0)
377 /* Check that CHILD is a child process that has not been reaped,
378 and that STATUS and OPTIONS are valid. Otherwise abort,
379 as continuing after this internal error could cause Emacs to
380 become confused and kill innocent-victim processes. */
384 /* Note: the MS-Windows emulation of waitpid calls QUIT
390 /* If successful and status is requested, tell wait_reading_process_output
391 that it needs to wake up and look around. */
392 if (pid
&& status
&& input_available_clear_time
)
393 *input_available_clear_time
= make_timespec (0, 0);
398 /* Wait for the subprocess with process id CHILD to terminate.
399 CHILD must be a child process that has not been reaped.
400 If STATUS is non-null, store the waitpid-style exit status into *STATUS
401 and tell wait_reading_process_output that it needs to look around.
402 If INTERRUPTIBLE, this function is interruptible by a signal. */
404 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
406 get_child_status (child
, status
, 0, interruptible
);
409 /* Report whether the subprocess with process id CHILD has changed status.
410 Termination counts as a change of status.
411 CHILD must be a child process that has not been reaped.
412 If STATUS is non-null, store the waitpid-style exit status into *STATUS
413 and tell wait_reading_process_output that it needs to look around.
414 Use waitpid-style OPTIONS to check status, but do not wait.
416 Return CHILD if successful, 0 if no status is available because
417 the process's state has not changed. */
419 child_status_changed (pid_t child
, int *status
, int options
)
421 return get_child_status (child
, status
, WNOHANG
| options
, 0);
425 /* Set up the terminal at the other end of a pseudo-terminal that
426 we will be controlling an inferior through.
427 It should not echo or do line-editing, since that is done
428 in Emacs. No padding needed for insertion into an Emacs buffer. */
431 child_setup_tty (int out
)
436 emacs_get_tty (out
, &s
);
437 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
438 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
440 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
441 Some versions of GNU Hurd do not have FFDLY? */
443 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
444 /* No output delays */
446 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
447 /* No output delays */
450 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
451 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
453 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
456 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
459 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
461 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
462 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
463 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
464 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
467 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
470 #ifdef SIGNALS_VIA_CHARACTERS
471 /* the QUIT and INTR character are used in process_send_signal
472 so set them here to something useful. */
473 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
474 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
475 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
476 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
477 #endif /* not SIGNALS_VIA_CHARACTERS */
480 /* Also, PTY overloads NUL and BREAK.
481 don't ignore break, but don't signal either, so it looks like NUL. */
482 s
.main
.c_iflag
&= ~IGNBRK
;
483 s
.main
.c_iflag
&= ~BRKINT
;
484 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
485 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
486 would force it to 0377. That looks like duplicated code. */
487 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
490 /* We originally enabled ICANON (and set VEOF to 04), and then had
491 process.c send additional EOF chars to flush the output when faced
492 with long lines, but this leads to weird effects when the
493 subprocess has disabled ICANON and ends up seeing those spurious
494 extra EOFs. So we don't send EOFs any more in
495 process.c:send_process. First we tried to disable ICANON by
496 default, so if a subsprocess sets up ICANON, it's his problem (or
497 the Elisp package that talks to it) to deal with lines that are
498 too long. But this disables some features, such as the ability
499 to send EOF signals. So we re-enabled ICANON but there is no
500 more "send eof to flush" going on (which is wrong and unportable
501 in itself). The correct way to handle too much output is to
502 buffer what could not be written and then write it again when
503 select returns ok for writing. This has it own set of
504 problems. Write is now asynchronous, is that a problem? How much
505 do we buffer, and what do we do when that limit is reached? */
507 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
508 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
509 #if 0 /* These settings only apply to non-ICANON mode. */
510 s
.main
.c_cc
[VMIN
] = 1;
511 s
.main
.c_cc
[VTIME
] = 0;
514 emacs_set_tty (out
, &s
, 0);
515 #endif /* not WINDOWSNT */
517 #endif /* not MSDOS */
520 /* Record a signal code and the action for it. */
524 struct sigaction action
;
527 static void save_signal_handlers (struct save_signal
*);
528 static void restore_signal_handlers (struct save_signal
*);
530 /* Suspend the Emacs process; give terminal to its superior. */
538 /* On a system where suspending is not implemented,
539 instead fork a subshell and let it talk directly to the terminal
546 /* Fork a subshell. */
551 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
554 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
556 char oldwd
[MAX_UTF8_PATH
];
562 struct save_signal saved_handlers
[5];
563 char *str
= SSDATA (encode_current_directory ());
569 char *volatile str_volatile
= str
;
576 error ("Can't spawn subshell");
578 saved_handlers
[0].code
= SIGINT
;
579 saved_handlers
[1].code
= SIGQUIT
;
580 saved_handlers
[2].code
= SIGTERM
;
582 saved_handlers
[3].code
= SIGIO
;
583 saved_handlers
[4].code
= 0;
585 saved_handlers
[3].code
= 0;
589 save_signal_handlers (saved_handlers
);
596 #ifdef DOS_NT /* MW, Aug 1993 */
597 getcwd (oldwd
, sizeof oldwd
);
599 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
602 sh
= egetenv ("SHELL");
606 /* Use our buffer's default directory for the subshell. */
607 if (chdir (str
) != 0)
611 _exit (EXIT_CANCELED
);
615 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
617 char *epwd
= getenv ("PWD");
618 char old_pwd
[MAXPATHLEN
+1+4];
620 /* If PWD is set, pass it with corrected value. */
623 strcpy (old_pwd
, epwd
);
624 setenv ("PWD", str
, 1);
627 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
629 putenv (old_pwd
); /* restore previous value */
631 #else /* not MSDOS */
633 /* Waits for process completion */
634 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
635 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
637 write (1, "Can't execute subshell", 22);
638 #else /* not WINDOWSNT */
639 execlp (sh
, sh
, (char *) 0);
641 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
642 #endif /* not WINDOWSNT */
643 #endif /* not MSDOS */
646 /* Do this now if we did not do it before. */
648 save_signal_handlers (saved_handlers
);
652 wait_for_termination (pid
, &status
, 0);
654 restore_signal_handlers (saved_handlers
);
658 save_signal_handlers (struct save_signal
*saved_handlers
)
660 while (saved_handlers
->code
)
662 struct sigaction action
;
663 emacs_sigaction_init (&action
, SIG_IGN
);
664 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
670 restore_signal_handlers (struct save_signal
*saved_handlers
)
672 while (saved_handlers
->code
)
674 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
680 static int old_fcntl_flags
[FD_SETSIZE
];
687 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
688 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
689 interrupts_deferred
= 0;
698 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
712 sigemptyset (&unblocked
);
714 sigaddset (&unblocked
, SIGWINCH
);
716 sigaddset (&unblocked
, SIGIO
);
717 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
719 interrupts_deferred
= 0;
724 unrequest_sigio (void)
732 sigemptyset (&blocked
);
734 sigaddset (&blocked
, SIGWINCH
);
736 sigaddset (&blocked
, SIGIO
);
737 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
738 interrupts_deferred
= 1;
746 block_child_signal (sigset_t
*oldset
)
749 sigemptyset (&blocked
);
750 sigaddset (&blocked
, SIGCHLD
);
751 sigaddset (&blocked
, SIGINT
);
752 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
755 /* Unblock SIGCHLD. */
758 unblock_child_signal (sigset_t
const *oldset
)
760 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
765 /* Saving and restoring the process group of Emacs's terminal. */
767 /* The process group of which Emacs was a member when it initially
770 If Emacs was in its own process group (i.e. inherited_pgroup ==
771 getpid ()), then we know we're running under a shell with job
772 control (Emacs would never be run as part of a pipeline).
775 If Emacs was not in its own process group, then we know we're
776 running under a shell (or a caller) that doesn't know how to
777 separate itself from Emacs (like sh). Emacs must be in its own
778 process group in order to receive SIGIO correctly. In this
779 situation, we put ourselves in our own pgroup, forcibly set the
780 tty's pgroup to our pgroup, and make sure to restore and reinstate
781 the tty's pgroup just like any other terminal setting. If
782 inherited_group was not the tty's pgroup, then we'll get a
783 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
784 it goes foreground in the future, which is what should happen. */
786 static pid_t inherited_pgroup
;
789 init_foreground_group (void)
791 pid_t pgrp
= getpgrp ();
792 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
795 /* Block and unblock SIGTTOU. */
798 block_tty_out_signal (sigset_t
*oldset
)
802 sigemptyset (&blocked
);
803 sigaddset (&blocked
, SIGTTOU
);
804 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
809 unblock_tty_out_signal (sigset_t
const *oldset
)
812 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
816 /* Safely set a controlling terminal FD's process group to PGID.
817 If we are not in the foreground already, POSIX requires tcsetpgrp
818 to deliver a SIGTTOU signal, which would stop us. This is an
819 annoyance, so temporarily ignore the signal.
821 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
822 skip all this unless SIGTTOU is defined. */
824 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
829 block_tty_out_signal (&oldset
);
830 tcsetpgrp (fd
, pgid
);
831 unblock_tty_out_signal (&oldset
);
836 /* Split off the foreground process group to Emacs alone. When we are
837 in the foreground, but not started in our own process group,
838 redirect the tty device handle FD to point to our own process
839 group. FD must be the file descriptor of the controlling tty. */
841 narrow_foreground_group (int fd
)
843 if (inherited_pgroup
&& setpgid (0, 0) == 0)
844 tcsetpgrp_without_stopping (fd
, getpid ());
847 /* Set the tty to our original foreground group. */
849 widen_foreground_group (int fd
)
851 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
852 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
855 /* Getting and setting emacs_tty structures. */
857 /* Set *TC to the parameters associated with the terminal FD,
858 or clear it if the parameters are not available.
859 Return 0 on success, -1 on failure. */
861 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
863 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
864 memset (&settings
->main
, 0, sizeof (settings
->main
));
867 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
870 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
872 settings
->main
= console_mode
;
875 #endif /* WINDOWSNT */
878 /* We have those nifty POSIX tcmumbleattr functions. */
879 return tcgetattr (fd
, &settings
->main
);
884 /* Set the parameters of the tty on FD according to the contents of
885 *SETTINGS. If FLUSHP, discard input.
886 Return 0 if all went well, and -1 (setting errno) if anything failed. */
889 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
891 /* Set the primary parameters - baud rate, character size, etcetera. */
894 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
896 if (h
&& h
!= INVALID_HANDLE_VALUE
)
900 /* Assume the handle is open for input. */
902 FlushConsoleInputBuffer (h
);
903 new_mode
= settings
->main
;
904 SetConsoleMode (h
, new_mode
);
906 #endif /* WINDOWSNT */
909 /* We have those nifty POSIX tcmumbleattr functions.
910 William J. Smith <wjs@wiis.wang.com> writes:
911 "POSIX 1003.1 defines tcsetattr to return success if it was
912 able to perform any of the requested actions, even if some
913 of the requested actions could not be performed.
914 We must read settings back to ensure tty setup properly.
915 AIX requires this to keep tty from hanging occasionally." */
916 /* This make sure that we don't loop indefinitely in here. */
917 for (i
= 0 ; i
< 10 ; i
++)
918 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
929 memset (&new, 0, sizeof (new));
930 /* Get the current settings, and see if they're what we asked for. */
931 tcgetattr (fd
, &new);
932 /* We cannot use memcmp on the whole structure here because under
933 * aix386 the termios structure has some reserved field that may
936 if ( new.c_iflag
== settings
->main
.c_iflag
937 && new.c_oflag
== settings
->main
.c_oflag
938 && new.c_cflag
== settings
->main
.c_cflag
939 && new.c_lflag
== settings
->main
.c_lflag
940 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
947 /* We have survived the tempest. */
954 static int old_fcntl_owner
[FD_SETSIZE
];
955 #endif /* F_SETOWN */
957 /* This may also be defined in stdio,
958 but if so, this does no harm,
959 and using the same name avoids wasting the other one's space. */
962 unsigned char _sobuf
[BUFSIZ
+8];
967 /* Initialize the terminal mode on all tty devices that are currently
971 init_all_sys_modes (void)
973 struct tty_display_info
*tty
;
974 for (tty
= tty_list
; tty
; tty
= tty
->next
)
975 init_sys_modes (tty
);
978 /* Initialize the terminal mode on the given tty device. */
981 init_sys_modes (struct tty_display_info
*tty_out
)
983 struct emacs_tty tty
;
985 Lisp_Object terminal
;
988 Vtty_erase_char
= Qnil
;
993 if (!tty_out
->output
)
994 return; /* The tty is suspended. */
996 narrow_foreground_group (fileno (tty_out
->input
));
998 if (! tty_out
->old_tty
)
999 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1001 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1003 tty
= *tty_out
->old_tty
;
1005 #if !defined (DOS_NT)
1006 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1008 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1009 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1010 #ifdef INLCR /* I'm just being cautious,
1011 since I can't check how widespread INLCR is--rms. */
1012 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1015 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1017 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1018 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1020 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1022 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1023 if (tty_out
->flow_control
)
1025 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1027 tty
.main
.c_iflag
&= ~IXANY
;
1031 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1032 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1034 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1036 if (tty_out
->meta_key
)
1038 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1039 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1043 XSETTERMINAL(terminal
, tty_out
->terminal
);
1044 if (!NILP (Fcontrolling_tty_p (terminal
)))
1046 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1047 /* Set up C-g for both SIGQUIT and SIGINT.
1048 We don't know which we will get, but we handle both alike
1049 so which one it really gives us does not matter. */
1050 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1054 /* We normally don't get interrupt or quit signals from tty
1055 devices other than our controlling terminal; therefore,
1056 we must handle C-g as normal input. Unfortunately, this
1057 means that the interrupt and quit feature must be
1058 disabled on secondary ttys, or we would not even see the
1061 Note that even though emacsclient could have special code
1062 to pass SIGINT to Emacs, we should _not_ enable
1063 interrupt/quit keys for emacsclient frames. This means
1064 that we can't break out of loops in C code from a
1065 secondary tty frame, but we can always decide what
1066 display the C-g came from, which is more important from a
1067 usability point of view. (Consider the case when two
1068 people work together using the same Emacs instance.) */
1069 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1070 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1072 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1073 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1075 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1080 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1083 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1084 #endif /* V_DSUSP */
1085 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1086 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1089 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1092 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1093 #endif /* VREPRINT */
1095 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1096 #endif /* VWERASE */
1098 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1099 #endif /* VDISCARD */
1101 if (tty_out
->flow_control
)
1104 tty
.main
.c_cc
[VSTART
] = '\021';
1107 tty
.main
.c_cc
[VSTOP
] = '\023';
1113 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1116 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1121 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1122 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1123 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1124 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1125 if (tty_out
->flow_control
)
1128 tty
.main
.c_cc
[VSTART
] = '\021';
1131 tty
.main
.c_cc
[VSTOP
] = '\023';
1134 /* Also, PTY overloads NUL and BREAK.
1135 don't ignore break, but don't signal either, so it looks like NUL.
1136 This really serves a purpose only if running in an XTERM window
1137 or via TELNET or the like, but does no harm elsewhere. */
1138 tty
.main
.c_iflag
&= ~IGNBRK
;
1139 tty
.main
.c_iflag
&= ~BRKINT
;
1141 #endif /* not DOS_NT */
1143 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1144 if (!tty_out
->term_initted
)
1145 internal_terminal_init ();
1146 dos_ttraw (tty_out
);
1149 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1151 /* This code added to insure that, if flow-control is not to be used,
1152 we have an unlocked terminal at the start. */
1155 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1158 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1161 #if !defined (DOS_NT)
1163 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1168 if (interrupt_input
)
1170 old_fcntl_owner
[fileno (tty_out
->input
)] =
1171 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1172 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1173 init_sigio (fileno (tty_out
->input
));
1175 if (gpm_tty
== tty_out
)
1177 /* Arrange for mouse events to give us SIGIO signals. */
1178 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1179 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1180 init_sigio (gpm_fd
);
1182 #endif /* HAVE_GPM */
1184 #endif /* F_GETOWN */
1187 /* This symbol is defined on recent USG systems.
1188 Someone says without this call USG won't really buffer the file
1189 even with a call to setbuf. */
1190 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1192 setbuf (tty_out
->output
, (char *) _sobuf
);
1195 if (tty_out
->terminal
->set_terminal_modes_hook
)
1196 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1198 if (!tty_out
->term_initted
)
1200 Lisp_Object tail
, frame
;
1201 FOR_EACH_FRAME (tail
, frame
)
1203 /* XXX This needs to be revised. */
1204 if (FRAME_TERMCAP_P (XFRAME (frame
))
1205 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1206 init_frame_faces (XFRAME (frame
));
1210 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1212 /* We used to call "direct_output_forward_char(0)" here,
1213 but it's not clear why, since it may not do anything anyway. */
1217 Lisp_Object tail
, frame
;
1219 FOR_EACH_FRAME (tail
, frame
)
1221 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1222 || FRAME_MSDOS_P (XFRAME (frame
)))
1223 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1224 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1228 tty_out
->term_initted
= 1;
1231 /* Return true if safe to use tabs in output.
1232 At the time this is called, init_sys_modes has not been done yet. */
1235 tabs_safe_p (int fd
)
1237 struct emacs_tty etty
;
1239 emacs_get_tty (fd
, &etty
);
1242 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1243 #else /* not TABDLY */
1245 #endif /* not TABDLY */
1251 /* Discard echoing. */
1254 suppress_echo_on_tty (int fd
)
1256 struct emacs_tty etty
;
1258 emacs_get_tty (fd
, &etty
);
1260 /* Set raw input mode. */
1263 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1264 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1265 #endif /* ! WINDOWSNT */
1266 emacs_set_tty (fd
, &etty
, 0);
1269 /* Get terminal size from system.
1270 Store number of lines into *HEIGHTP and width into *WIDTHP.
1271 We store 0 if there's no valid information. */
1274 get_tty_size (int fd
, int *widthp
, int *heightp
)
1276 #if defined TIOCGWINSZ
1279 struct winsize size
;
1281 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1282 *widthp
= *heightp
= 0;
1285 *widthp
= size
.ws_col
;
1286 *heightp
= size
.ws_row
;
1289 #elif defined TIOCGSIZE
1291 /* SunOS - style. */
1292 struct ttysize size
;
1294 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1295 *widthp
= *heightp
= 0;
1298 *widthp
= size
.ts_cols
;
1299 *heightp
= size
.ts_lines
;
1302 #elif defined WINDOWSNT
1304 CONSOLE_SCREEN_BUFFER_INFO info
;
1305 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1307 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1308 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1311 *widthp
= *heightp
= 0;
1315 *widthp
= ScreenCols ();
1316 *heightp
= ScreenRows ();
1318 #else /* system doesn't know size */
1326 /* Set the logical window size associated with descriptor FD
1327 to HEIGHT and WIDTH. This is used mainly with ptys.
1328 Return a negative value on failure. */
1331 set_window_size (int fd
, int height
, int width
)
1336 struct winsize size
;
1337 size
.ws_row
= height
;
1338 size
.ws_col
= width
;
1340 return ioctl (fd
, TIOCSWINSZ
, &size
);
1345 /* SunOS - style. */
1346 struct ttysize size
;
1347 size
.ts_lines
= height
;
1348 size
.ts_cols
= width
;
1350 return ioctl (fd
, TIOCGSIZE
, &size
);
1353 #endif /* not SunOS-style */
1354 #endif /* not BSD-style */
1359 /* Prepare all terminal devices for exiting Emacs. */
1362 reset_all_sys_modes (void)
1364 struct tty_display_info
*tty
;
1365 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1366 reset_sys_modes (tty
);
1369 /* Prepare the terminal for closing it; move the cursor to the
1370 bottom of the frame, turn off interrupt-driven I/O, etc. */
1373 reset_sys_modes (struct tty_display_info
*tty_out
)
1380 if (!tty_out
->term_initted
)
1383 if (!tty_out
->output
)
1384 return; /* The tty is suspended. */
1386 /* Go to and clear the last line of the terminal. */
1388 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1390 /* Code adapted from tty_clear_end_of_line. */
1391 if (tty_out
->TS_clr_line
)
1393 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1396 { /* have to do it the hard way */
1398 tty_turn_off_insert (tty_out
);
1400 for (i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1402 fputc (' ', tty_out
->output
);
1406 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1407 fflush (tty_out
->output
);
1409 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1410 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1412 /* Avoid possible loss of output when changing terminal modes. */
1413 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1418 if (interrupt_input
)
1420 reset_sigio (fileno (tty_out
->input
));
1421 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1422 old_fcntl_owner
[fileno (tty_out
->input
)]);
1424 #endif /* F_SETOWN */
1425 fcntl (fileno (tty_out
->input
), F_SETFL
,
1426 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1429 if (tty_out
->old_tty
)
1430 while (emacs_set_tty (fileno (tty_out
->input
),
1431 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1434 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1438 widen_foreground_group (fileno (tty_out
->input
));
1443 /* Set up the proper status flags for use of a pty. */
1448 /* I'm told that TOICREMOTE does not mean control chars
1449 "can't be sent" but rather that they don't have
1450 input-editing or signaling effects.
1451 That should be good, because we have other ways
1452 to do those things in Emacs.
1453 However, telnet mode seems not to work on 4.2.
1454 So TIOCREMOTE is turned off now. */
1456 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1457 will hang. In particular, the "timeout" feature (which
1458 causes a read to return if there is no data available)
1459 does this. Also it is known that telnet mode will hang
1460 in such a way that Emacs must be stopped (perhaps this
1461 is the same problem).
1463 If TIOCREMOTE is turned off, then there is a bug in
1464 hp-ux which sometimes loses data. Apparently the
1465 code which blocks the master process when the internal
1466 buffer fills up does not work. Other than this,
1467 though, everything else seems to work fine.
1469 Since the latter lossage is more benign, we may as well
1470 lose that way. -- cph */
1472 #if defined (UNIX98_PTYS)
1475 ioctl (fd
, FIONBIO
, &on
);
1480 #endif /* HAVE_PTYS */
1483 init_system_name (void)
1487 /* Set system-name to nil so that the build is deterministic. */
1488 Vsystem_name
= Qnil
;
1491 char *hostname_alloc
= NULL
;
1493 #ifndef HAVE_GETHOSTNAME
1496 hostname
= uts
.nodename
;
1497 #else /* HAVE_GETHOSTNAME */
1498 char hostname_buf
[256];
1499 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1500 hostname
= hostname_buf
;
1502 /* Try to get the host name; if the buffer is too short, try
1503 again. Apparently, the only indication gethostname gives of
1504 whether the buffer was large enough is the presence or absence
1505 of a '\0' in the string. Eech. */
1508 gethostname (hostname
, hostname_size
- 1);
1509 hostname
[hostname_size
- 1] = '\0';
1511 /* Was the buffer large enough for the '\0'? */
1512 if (strlen (hostname
) < hostname_size
- 1)
1515 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1516 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1518 #endif /* HAVE_GETHOSTNAME */
1520 for (p
= hostname
; *p
; p
++)
1521 if (*p
== ' ' || *p
== '\t')
1523 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1524 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1525 Vsystem_name
= build_string (hostname
);
1526 xfree (hostname_alloc
);
1529 sigset_t empty_mask
;
1531 static struct sigaction process_fatal_action
;
1534 emacs_sigaction_flags (void)
1537 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1538 'select') to reset their timeout on some platforms (e.g.,
1539 HP-UX 11), which is not what we want. Also, when Emacs is
1540 interactive, we don't want SA_RESTART because we need to poll
1541 for pending input so we need long-running syscalls to be interrupted
1542 after a signal that sets pending_signals.
1544 Non-interactive keyboard input goes through stdio, where we
1545 always want restartable system calls. */
1552 /* Store into *ACTION a signal action suitable for Emacs, with handler
1555 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1557 sigemptyset (&action
->sa_mask
);
1559 /* When handling a signal, block nonfatal system signals that are caught
1560 by Emacs. This makes race conditions less likely. */
1561 sigaddset (&action
->sa_mask
, SIGALRM
);
1563 sigaddset (&action
->sa_mask
, SIGCHLD
);
1566 sigaddset (&action
->sa_mask
, SIGDANGER
);
1568 #ifdef PROFILER_CPU_SUPPORT
1569 sigaddset (&action
->sa_mask
, SIGPROF
);
1572 sigaddset (&action
->sa_mask
, SIGWINCH
);
1574 if (! noninteractive
)
1576 sigaddset (&action
->sa_mask
, SIGINT
);
1577 sigaddset (&action
->sa_mask
, SIGQUIT
);
1579 sigaddset (&action
->sa_mask
, SIGIO
);
1583 action
->sa_handler
= handler
;
1584 action
->sa_flags
= emacs_sigaction_flags ();
1587 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1588 static pthread_t main_thread
;
1591 /* SIG has arrived at the current process. Deliver it to the main
1592 thread, which should handle it with HANDLER.
1594 If we are on the main thread, handle the signal SIG with HANDLER.
1595 Otherwise, redirect the signal to the main thread, blocking it from
1596 this thread. POSIX says any thread can receive a signal that is
1597 associated with a process, process group, or asynchronous event.
1598 On GNU/Linux that is not true, but for other systems (FreeBSD at
1601 deliver_process_signal (int sig
, signal_handler_t handler
)
1603 /* Preserve errno, to avoid race conditions with signal handlers that
1604 might change errno. Races can occur even in single-threaded hosts. */
1605 int old_errno
= errno
;
1607 bool on_main_thread
= true;
1608 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1609 if (! pthread_equal (pthread_self (), main_thread
))
1612 sigemptyset (&blocked
);
1613 sigaddset (&blocked
, sig
);
1614 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1615 pthread_kill (main_thread
, sig
);
1616 on_main_thread
= false;
1625 /* Static location to save a fatal backtrace in a thread.
1626 FIXME: If two subsidiary threads fail simultaneously, the resulting
1627 backtrace may be garbage. */
1628 enum { BACKTRACE_LIMIT_MAX
= 500 };
1629 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1630 static int thread_backtrace_npointers
;
1632 /* SIG has arrived at the current thread.
1633 If we are on the main thread, handle the signal SIG with HANDLER.
1634 Otherwise, this is a fatal error in the handling thread. */
1636 deliver_thread_signal (int sig
, signal_handler_t handler
)
1638 int old_errno
= errno
;
1640 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1641 if (! pthread_equal (pthread_self (), main_thread
))
1643 thread_backtrace_npointers
1644 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1645 sigaction (sig
, &process_fatal_action
, 0);
1646 pthread_kill (main_thread
, sig
);
1648 /* Avoid further damage while the main thread is exiting. */
1650 sigsuspend (&empty_mask
);
1658 #if !HAVE_DECL_SYS_SIGLIST
1660 # ifdef _sys_siglist
1661 # define sys_siglist _sys_siglist
1662 # elif HAVE_DECL___SYS_SIGLIST
1663 # define sys_siglist __sys_siglist
1665 # define sys_siglist my_sys_siglist
1666 static char const *sys_siglist
[NSIG
];
1671 # define sys_siglist_entries _sys_nsig
1673 # define sys_siglist_entries NSIG
1676 /* Handle bus errors, invalid instruction, etc. */
1678 handle_fatal_signal (int sig
)
1680 terminate_due_to_signal (sig
, 40);
1684 deliver_fatal_signal (int sig
)
1686 deliver_process_signal (sig
, handle_fatal_signal
);
1690 deliver_fatal_thread_signal (int sig
)
1692 deliver_thread_signal (sig
, handle_fatal_signal
);
1695 static _Noreturn
void
1696 handle_arith_signal (int sig
)
1698 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1699 xsignal0 (Qarith_error
);
1702 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1704 /* Alternate stack used by SIGSEGV handler below. */
1706 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1709 /* Return true if SIGINFO indicates a stack overflow. */
1712 stack_overflow (siginfo_t
*siginfo
)
1714 if (!attempt_stack_overflow_recovery
)
1717 /* In theory, a more-accurate heuristic can be obtained by using
1718 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1719 and pthread_attr_getguardsize to find the location and size of the
1720 guard area. In practice, though, these functions are so hard to
1721 use reliably that they're not worth bothering with. E.g., see:
1722 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1723 Other operating systems also have problems, e.g., Solaris's
1724 stack_violation function is tailor-made for this problem, but it
1725 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1727 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1733 /* The faulting address. */
1734 char *addr
= siginfo
->si_addr
;
1738 /* The known top and bottom of the stack. The actual stack may
1739 extend a bit beyond these boundaries. */
1740 char *bot
= stack_bottom
;
1741 char *top
= near_C_stack_top ();
1743 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1744 of the known stack divided by the size of the guard area past the
1745 end of the stack top. The heuristic is that a bad address is
1746 considered to be a stack overflow if it occurs within
1747 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1748 stack. This heuristic is not exactly correct but it's good
1749 enough in practice. */
1750 enum { LG_STACK_HEURISTIC
= 8 };
1753 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1755 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1759 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1762 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1764 /* Hard GC error may lead to stack overflow caused by
1765 too nested calls to mark_object. No way to survive. */
1766 bool fatal
= gc_in_progress
;
1768 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1769 if (!fatal
&& !pthread_equal (pthread_self (), main_thread
))
1773 if (!fatal
&& stack_overflow (siginfo
))
1774 siglongjmp (return_to_command_loop
, 1);
1776 /* Otherwise we can't do anything with this. */
1777 deliver_fatal_thread_signal (sig
);
1780 /* Return true if we have successfully set up SIGSEGV handler on alternate
1781 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1786 struct sigaction sa
;
1789 ss
.ss_sp
= sigsegv_stack
;
1790 ss
.ss_size
= sizeof (sigsegv_stack
);
1792 if (sigaltstack (&ss
, NULL
) < 0)
1795 sigfillset (&sa
.sa_mask
);
1796 sa
.sa_sigaction
= handle_sigsegv
;
1797 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1798 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1801 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1809 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1812 deliver_arith_signal (int sig
)
1814 deliver_thread_signal (sig
, handle_arith_signal
);
1819 /* Handler for SIGDANGER. */
1821 handle_danger_signal (int sig
)
1823 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1825 /* It might be unsafe to call do_auto_save now. */
1826 force_auto_save_soon ();
1830 deliver_danger_signal (int sig
)
1832 deliver_process_signal (sig
, handle_danger_signal
);
1836 /* Treat SIG as a terminating signal, unless it is already ignored and
1837 we are in --batch mode. Among other things, this makes nohup work. */
1839 maybe_fatal_sig (int sig
)
1841 bool catch_sig
= !noninteractive
;
1844 struct sigaction old_action
;
1845 sigaction (sig
, 0, &old_action
);
1846 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1849 sigaction (sig
, &process_fatal_action
, 0);
1853 init_signals (bool dumping
)
1855 struct sigaction thread_fatal_action
;
1856 struct sigaction action
;
1858 sigemptyset (&empty_mask
);
1860 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1861 main_thread
= pthread_self ();
1864 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1867 sys_siglist
[SIGABRT
] = "Aborted";
1869 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1871 sys_siglist
[SIGALRM
] = "Alarm clock";
1873 sys_siglist
[SIGBUS
] = "Bus error";
1876 sys_siglist
[SIGCHLD
] = "Child status changed";
1879 sys_siglist
[SIGCONT
] = "Continued";
1882 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1885 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1888 sys_siglist
[SIGEMT
] = "Emulation trap";
1890 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1892 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1895 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1897 sys_siglist
[SIGHUP
] = "Hangup";
1898 sys_siglist
[SIGILL
] = "Illegal instruction";
1899 sys_siglist
[SIGINT
] = "Interrupt";
1901 sys_siglist
[SIGIO
] = "I/O possible";
1904 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1907 sys_siglist
[SIGIOT
] = "IOT trap";
1909 sys_siglist
[SIGKILL
] = "Killed";
1911 sys_siglist
[SIGLOST
] = "Resource lost";
1914 sys_siglist
[SIGLWP
] = "SIGLWP";
1917 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1920 sys_siglist
[SIGWIND
] = "SIGPHONE";
1922 sys_siglist
[SIGPIPE
] = "Broken pipe";
1924 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1927 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1930 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1933 sys_siglist
[SIGPWR
] = "Power-fail restart";
1935 sys_siglist
[SIGQUIT
] = "Quit";
1937 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1940 sys_siglist
[SIGSAK
] = "Secure attention";
1942 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1944 sys_siglist
[SIGSOUND
] = "Sound completed";
1947 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1950 sys_siglist
[SIGSTP
] = "Stopped (user)";
1953 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1955 sys_siglist
[SIGTERM
] = "Terminated";
1957 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1960 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1963 sys_siglist
[SIGTSTP
] = "Stopped (user)";
1966 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
1969 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
1972 sys_siglist
[SIGURG
] = "Urgent I/O condition";
1975 sys_siglist
[SIGUSR1
] = "User defined signal 1";
1978 sys_siglist
[SIGUSR2
] = "User defined signal 2";
1981 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
1984 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
1987 sys_siglist
[SIGWINCH
] = "Window size changed";
1990 sys_siglist
[SIGWIND
] = "SIGWIND";
1993 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
1996 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
1999 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2001 /* Don't alter signal handlers if dumping. On some machines,
2002 changing signal handlers sets static data that would make signals
2003 fail to work right when the dumped Emacs is run. */
2007 sigfillset (&process_fatal_action
.sa_mask
);
2008 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2009 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2011 sigfillset (&thread_fatal_action
.sa_mask
);
2012 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2013 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2015 /* SIGINT may need special treatment on MS-Windows. See
2016 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2017 Please update the doc of kill-emacs, kill-emacs-hook, and
2018 NEWS if you change this. */
2020 maybe_fatal_sig (SIGHUP
);
2021 maybe_fatal_sig (SIGINT
);
2022 maybe_fatal_sig (SIGTERM
);
2024 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2025 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2026 to behave more like typical batch applications do. */
2027 if (! noninteractive
)
2028 signal (SIGPIPE
, SIG_IGN
);
2030 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2031 sigaction (SIGILL
, &thread_fatal_action
, 0);
2032 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2034 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2035 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2036 interpreter's floating point operations, so treat SIGFPE as an
2037 arith-error if it arises in the main thread. */
2038 if (IEEE_FLOATING_POINT
)
2039 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2042 emacs_sigaction_init (&action
, deliver_arith_signal
);
2043 sigaction (SIGFPE
, &action
, 0);
2047 add_user_signal (SIGUSR1
, "sigusr1");
2050 add_user_signal (SIGUSR2
, "sigusr2");
2052 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2054 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2057 sigaction (SIGORE
, &thread_fatal_action
, 0);
2060 sigaction (SIGUME
, &thread_fatal_action
, 0);
2063 sigaction (SIGDLK
, &process_fatal_action
, 0);
2066 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2069 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2072 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2075 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2077 if (!init_sigsegv ())
2078 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2080 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2082 sigaction (SIGTERM
, &process_fatal_action
, 0);
2084 signal (SIGPROF
, SIG_IGN
);
2087 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2090 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2093 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2097 /* This just means available memory is getting low. */
2098 emacs_sigaction_init (&action
, deliver_danger_signal
);
2099 sigaction (SIGDANGER
, &action
, 0);
2102 /* AIX-specific signals. */
2104 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2107 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2110 sigaction (SIGMSG
, &process_fatal_action
, 0);
2113 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2116 sigaction (SIGSAK
, &process_fatal_action
, 0);
2119 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2122 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2132 /* Figure out how many bits the system's random number generator uses.
2133 `random' and `lrand48' are assumed to return 31 usable bits.
2134 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2135 so we'll shift it and treat it like the 15-bit USG `rand'. */
2139 # define RAND_BITS 31
2140 # else /* !HAVE_RANDOM */
2141 # ifdef HAVE_LRAND48
2142 # define RAND_BITS 31
2143 # define random lrand48
2144 # else /* !HAVE_LRAND48 */
2145 # define RAND_BITS 15
2146 # if RAND_MAX == 32767
2147 # define random rand
2148 # else /* RAND_MAX != 32767 */
2149 # if RAND_MAX == 2147483647
2150 # define random() (rand () >> 16)
2151 # else /* RAND_MAX != 2147483647 */
2153 # define random rand
2155 # define random() (rand () >> 16)
2157 # endif /* RAND_MAX != 2147483647 */
2158 # endif /* RAND_MAX != 32767 */
2159 # endif /* !HAVE_LRAND48 */
2160 # endif /* !HAVE_RANDOM */
2161 #endif /* !RAND_BITS */
2164 typedef unsigned int random_seed
;
2165 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2166 #elif defined HAVE_LRAND48
2167 /* Although srand48 uses a long seed, this is unsigned long to avoid
2168 undefined behavior on signed integer overflow in init_random. */
2169 typedef unsigned long int random_seed
;
2170 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2172 typedef unsigned int random_seed
;
2173 static void set_random_seed (random_seed arg
) { srand (arg
); }
2177 seed_random (void *seed
, ptrdiff_t seed_size
)
2179 random_seed arg
= 0;
2180 unsigned char *argp
= (unsigned char *) &arg
;
2181 unsigned char *seedp
= seed
;
2182 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2183 argp
[i
% sizeof arg
] ^= seedp
[i
];
2184 set_random_seed (arg
);
2191 if (! (EQ (emacs_gnutls_global_init (), Qt
)
2192 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0))
2194 bool success
= false;
2196 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2199 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2203 success
= w32_init_random (&v
, sizeof v
) == 0;
2207 /* Fall back to current time value + PID. */
2208 struct timespec t
= current_timespec ();
2209 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2212 set_random_seed (v
);
2216 * Return a nonnegative random integer out of whatever we've got.
2217 * It contains enough bits to make a random (signed) Emacs fixnum.
2218 * This suffices even for a 64-bit architecture with a 15-bit rand.
2225 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2226 val
= (random () ^ (val
<< RAND_BITS
)
2227 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2228 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2229 return val
& INTMASK
;
2232 #ifndef HAVE_SNPRINTF
2233 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2235 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2237 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2238 ptrdiff_t nbytes
= size
- 1;
2243 va_start (ap
, format
);
2244 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2248 if (nbytes
== size
- 1)
2250 /* Calculate the length of the string that would have been created
2251 had the buffer been large enough. */
2252 char stackbuf
[4000];
2254 ptrdiff_t bsize
= sizeof stackbuf
;
2255 va_start (ap
, format
);
2256 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2262 if (INT_MAX
< nbytes
)
2275 /* If a backtrace is available, output the top lines of it to stderr.
2276 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2277 This function may be called from a signal handler, so it should
2278 not invoke async-unsafe functions like malloc.
2280 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2281 but do not output anything. This avoids some problems that can
2282 otherwise occur if the malloc arena is corrupted before 'backtrace'
2283 is called, since 'backtrace' may call malloc if the tables are not
2286 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2287 fatal error has occurred in some other thread; generate a thread
2288 backtrace instead, ignoring BACKTRACE_LIMIT. */
2290 emacs_backtrace (int backtrace_limit
)
2292 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2293 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2297 if (thread_backtrace_npointers
)
2299 buffer
= thread_backtrace_buffer
;
2300 npointers
= thread_backtrace_npointers
;
2304 buffer
= main_backtrace_buffer
;
2306 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2307 if (bounded_limit
< 0)
2309 backtrace (buffer
, 1);
2313 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2318 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2319 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2320 if (bounded_limit
< npointers
)
2321 emacs_write (STDERR_FILENO
, "...\n", 4);
2329 terminate_due_to_signal (SIGABRT
, 40);
2333 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2334 Use binary I/O on systems that care about text vs binary I/O.
2335 Arrange for subprograms to not inherit the file descriptor.
2336 Prefer a method that is multithread-safe, if available.
2337 Do not fail merely because the open was interrupted by a signal.
2338 Allow the user to quit. */
2341 emacs_open (const char *file
, int oflags
, int mode
)
2344 if (! (oflags
& O_TEXT
))
2346 oflags
|= O_CLOEXEC
;
2347 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2349 if (! O_CLOEXEC
&& 0 <= fd
)
2350 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2354 /* Open FILE as a stream for Emacs use, with mode MODE.
2355 Act like emacs_open with respect to threads, signals, and quits. */
2358 emacs_fopen (char const *file
, char const *mode
)
2360 int fd
, omode
, oflags
;
2362 char const *m
= mode
;
2366 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2367 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2368 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2369 default: emacs_abort ();
2375 case '+': omode
= O_RDWR
; break;
2376 case 't': bflag
= O_TEXT
; break;
2377 default: /* Ignore. */ break;
2380 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2381 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2384 /* Create a pipe for Emacs use. */
2387 emacs_pipe (int fd
[2])
2392 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2393 if (! O_CLOEXEC
&& result
== 0)
2395 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2396 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2402 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2403 For the background behind this mess, please see Austin Group defect 529
2404 <http://austingroupbugs.net/view.php?id=529>. */
2406 #ifndef POSIX_CLOSE_RESTART
2407 # define POSIX_CLOSE_RESTART 1
2409 posix_close (int fd
, int flag
)
2411 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2412 eassert (flag
== POSIX_CLOSE_RESTART
);
2414 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2415 on a system that does not define POSIX_CLOSE_RESTART.
2417 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2418 closed, and retrying the close could inadvertently close a file
2419 descriptor allocated by some other thread. In other systems
2420 (e.g., HP/UX) FD is not closed. And in still other systems
2421 (e.g., OS X, Solaris), maybe FD is closed, maybe not, and in a
2422 multithreaded program there can be no way to tell.
2424 So, in this case, pretend that the close succeeded. This works
2425 well on systems like GNU/Linux that close FD. Although it may
2426 leak a file descriptor on other systems, the leak is unlikely and
2427 it's better to leak than to close a random victim. */
2428 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2432 /* Close FD, retrying if interrupted. If successful, return 0;
2433 otherwise, return -1 and set errno to a non-EINTR value. Consider
2434 an EINPROGRESS error to be successful, as that's merely a signal
2435 arriving. FD is always closed when this function returns, even
2438 Do not call this function if FD is nonnegative and might already be closed,
2439 as that might close an innocent victim opened by some other thread. */
2442 emacs_close (int fd
)
2446 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2449 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2451 eassert (errno
!= EBADF
|| fd
< 0);
2452 return errno
== EINPROGRESS
? 0 : r
;
2457 /* Maximum number of bytes to read or write in a single system call.
2458 This works around a serious bug in Linux kernels before 2.6.16; see
2459 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2460 It's likely to work around similar bugs in other operating systems, so do it
2461 on all platforms. Round INT_MAX down to a page size, with the conservative
2462 assumption that page sizes are at most 2**18 bytes (any kernel with a
2463 page size larger than that shouldn't have the bug). */
2464 #ifndef MAX_RW_COUNT
2465 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2468 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2469 Return the number of bytes read, which might be less than NBYTE.
2470 On error, set errno and return -1. */
2472 emacs_read (int fildes
, void *buf
, ptrdiff_t nbyte
)
2476 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2477 passes a size that large to emacs_read. */
2479 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
2480 && (errno
== EINTR
))
2485 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2486 or if a partial write occurs. If interrupted, process pending
2487 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2488 errno if this is less than NBYTE. */
2490 emacs_full_write (int fildes
, char const *buf
, ptrdiff_t nbyte
,
2491 bool process_signals
)
2493 ptrdiff_t bytes_written
= 0;
2497 ssize_t n
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
2503 /* I originally used `QUIT' but that might cause files to
2504 be truncated if you hit C-g in the middle of it. --Stef */
2505 if (process_signals
&& pending_signals
)
2506 process_pending_signals ();
2518 return bytes_written
;
2521 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2522 interrupted or if a partial write occurs. Return the number of
2523 bytes written, setting errno if this is less than NBYTE. */
2525 emacs_write (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2527 return emacs_full_write (fildes
, buf
, nbyte
, 0);
2530 /* Like emacs_write, but also process pending signals if interrupted. */
2532 emacs_write_sig (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2534 return emacs_full_write (fildes
, buf
, nbyte
, 1);
2537 /* Write a diagnostic to standard error that contains MESSAGE and a
2538 string derived from errno. Preserve errno. Do not buffer stderr.
2539 Do not process pending signals if interrupted. */
2541 emacs_perror (char const *message
)
2544 char const *error_string
= emacs_strerror (err
);
2545 char const *command
= (initial_argv
&& initial_argv
[0]
2546 ? initial_argv
[0] : "emacs");
2547 /* Write it out all at once, if it's short; this is less likely to
2548 be interleaved with other output. */
2550 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2551 command
, message
, error_string
);
2552 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2553 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2556 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2557 emacs_write (STDERR_FILENO
, ": ", 2);
2558 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2559 emacs_write (STDERR_FILENO
, ": ", 2);
2560 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2561 emacs_write (STDERR_FILENO
, "\n", 1);
2566 /* Return a struct timeval that is roughly equivalent to T.
2567 Use the least timeval not less than T.
2568 Return an extremal value if the result would overflow. */
2570 make_timeval (struct timespec t
)
2573 tv
.tv_sec
= t
.tv_sec
;
2574 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2576 if (t
.tv_nsec
% 1000 != 0)
2578 if (tv
.tv_usec
< 999999)
2580 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2590 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2591 ATIME and MTIME, respectively.
2592 FD must be either negative -- in which case it is ignored --
2593 or a file descriptor that is open on FILE.
2594 If FD is nonnegative, then FILE can be NULL. */
2596 set_file_times (int fd
, const char *filename
,
2597 struct timespec atime
, struct timespec mtime
)
2599 struct timespec timespec
[2];
2600 timespec
[0] = atime
;
2601 timespec
[1] = mtime
;
2602 return fdutimens (fd
, filename
, timespec
);
2605 /* Like strsignal, except async-signal-safe, and this function typically
2606 returns a string in the C locale rather than the current locale. */
2608 safe_strsignal (int code
)
2610 char const *signame
= 0;
2612 if (0 <= code
&& code
< sys_siglist_entries
)
2613 signame
= sys_siglist
[code
];
2615 signame
= "Unknown signal";
2621 /* For make-serial-process */
2623 serial_open (Lisp_Object port
)
2625 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2627 report_file_error ("Opening serial port", port
);
2629 ioctl (fd
, TIOCEXCL
, (char *) 0);
2635 #if !defined (HAVE_CFMAKERAW)
2636 /* Workaround for targets which are missing cfmakeraw. */
2637 /* Pasted from man page. */
2639 cfmakeraw (struct termios
*termios_p
)
2641 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2642 termios_p
->c_oflag
&= ~OPOST
;
2643 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2644 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2645 termios_p
->c_cflag
|= CS8
;
2647 #endif /* !defined (HAVE_CFMAKERAW */
2649 #if !defined (HAVE_CFSETSPEED)
2650 /* Workaround for targets which are missing cfsetspeed. */
2652 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2654 return (cfsetispeed (termios_p
, vitesse
)
2655 + cfsetospeed (termios_p
, vitesse
));
2659 /* For serial-process-configure */
2661 serial_configure (struct Lisp_Process
*p
,
2662 Lisp_Object contact
)
2664 Lisp_Object childp2
= Qnil
;
2665 Lisp_Object tem
= Qnil
;
2666 struct termios attr
;
2668 char summary
[4] = "???"; /* This usually becomes "8N1". */
2670 childp2
= Fcopy_sequence (p
->childp
);
2672 /* Read port attributes and prepare default configuration. */
2673 err
= tcgetattr (p
->outfd
, &attr
);
2675 report_file_error ("Failed tcgetattr", Qnil
);
2677 #if defined (CLOCAL)
2678 attr
.c_cflag
|= CLOCAL
;
2681 attr
.c_cflag
|= CREAD
;
2684 /* Configure speed. */
2685 if (!NILP (Fplist_member (contact
, QCspeed
)))
2686 tem
= Fplist_get (contact
, QCspeed
);
2688 tem
= Fplist_get (p
->childp
, QCspeed
);
2690 err
= cfsetspeed (&attr
, XINT (tem
));
2692 report_file_error ("Failed cfsetspeed", tem
);
2693 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2695 /* Configure bytesize. */
2696 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2697 tem
= Fplist_get (contact
, QCbytesize
);
2699 tem
= Fplist_get (p
->childp
, QCbytesize
);
2701 tem
= make_number (8);
2703 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2704 error (":bytesize must be nil (8), 7, or 8");
2705 summary
[0] = XINT (tem
) + '0';
2706 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2707 attr
.c_cflag
&= ~CSIZE
;
2708 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2710 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2711 if (XINT (tem
) != 8)
2712 error ("Bytesize cannot be changed");
2714 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2716 /* Configure parity. */
2717 if (!NILP (Fplist_member (contact
, QCparity
)))
2718 tem
= Fplist_get (contact
, QCparity
);
2720 tem
= Fplist_get (p
->childp
, QCparity
);
2721 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2722 error (":parity must be nil (no parity), `even', or `odd'");
2723 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2724 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2725 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2730 else if (EQ (tem
, Qeven
))
2733 attr
.c_cflag
|= PARENB
;
2734 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2736 else if (EQ (tem
, Qodd
))
2739 attr
.c_cflag
|= (PARENB
| PARODD
);
2740 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2743 /* Don't error on no parity, which should be set by cfmakeraw. */
2745 error ("Parity cannot be configured");
2747 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2749 /* Configure stopbits. */
2750 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2751 tem
= Fplist_get (contact
, QCstopbits
);
2753 tem
= Fplist_get (p
->childp
, QCstopbits
);
2755 tem
= make_number (1);
2757 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2758 error (":stopbits must be nil (1 stopbit), 1, or 2");
2759 summary
[2] = XINT (tem
) + '0';
2760 #if defined (CSTOPB)
2761 attr
.c_cflag
&= ~CSTOPB
;
2762 if (XINT (tem
) == 2)
2763 attr
.c_cflag
|= CSTOPB
;
2765 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2766 if (XINT (tem
) != 1)
2767 error ("Stopbits cannot be configured");
2769 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2771 /* Configure flowcontrol. */
2772 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2773 tem
= Fplist_get (contact
, QCflowcontrol
);
2775 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2776 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2777 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2778 #if defined (CRTSCTS)
2779 attr
.c_cflag
&= ~CRTSCTS
;
2781 #if defined (CNEW_RTSCTS)
2782 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2784 #if defined (IXON) && defined (IXOFF)
2785 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2789 /* Already configured. */
2791 else if (EQ (tem
, Qhw
))
2793 #if defined (CRTSCTS)
2794 attr
.c_cflag
|= CRTSCTS
;
2795 #elif defined (CNEW_RTSCTS)
2796 attr
.c_cflag
|= CNEW_RTSCTS
;
2798 error ("Hardware flowcontrol (RTS/CTS) not supported");
2801 else if (EQ (tem
, Qsw
))
2803 #if defined (IXON) && defined (IXOFF)
2804 attr
.c_iflag
|= (IXON
| IXOFF
);
2806 error ("Software flowcontrol (XON/XOFF) not supported");
2809 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2811 /* Activate configuration. */
2812 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2814 report_file_error ("Failed tcsetattr", Qnil
);
2816 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2817 pset_childp (p
, childp2
);
2819 #endif /* not DOS_NT */
2821 /* System depended enumeration of and access to system processes a-la ps(1). */
2825 /* Process enumeration and access via /proc. */
2828 list_system_processes (void)
2830 Lisp_Object procdir
, match
, proclist
, next
;
2833 /* For every process on the system, there's a directory in the
2834 "/proc" pseudo-directory whose name is the numeric ID of that
2836 procdir
= build_string ("/proc");
2837 match
= build_string ("[0-9]+");
2838 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2840 /* `proclist' gives process IDs as strings. Destructively convert
2841 each string into a number. */
2842 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2845 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2848 /* directory_files_internal returns the files in reverse order; undo
2850 proclist
= Fnreverse (proclist
);
2854 #elif defined DARWIN_OS || defined __FreeBSD__
2857 list_system_processes (void)
2860 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2862 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2865 struct kinfo_proc
*procs
;
2868 Lisp_Object proclist
= Qnil
;
2870 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2873 procs
= xmalloc (len
);
2874 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2880 len
/= sizeof (struct kinfo_proc
);
2881 for (i
= 0; i
< len
; i
++)
2884 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2886 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2895 /* The WINDOWSNT implementation is in w32.c.
2896 The MSDOS implementation is in dosfns.c. */
2897 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2900 list_system_processes (void)
2905 #endif /* !defined (WINDOWSNT) */
2907 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2908 static struct timespec
2909 time_from_jiffies (unsigned long long tval
, long hz
)
2911 unsigned long long s
= tval
/ hz
;
2912 unsigned long long frac
= tval
% hz
;
2915 if (TYPE_MAXIMUM (time_t) < s
)
2917 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2918 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2919 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2922 /* This is reachable only in the unlikely case that HZ * HZ
2923 exceeds ULLONG_MAX. It calculates an approximation that is
2924 guaranteed to be in range. */
2925 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
2926 + (hz
% TIMESPEC_RESOLUTION
!= 0));
2927 ns
= frac
/ hz_per_ns
;
2930 return make_timespec (s
, ns
);
2934 ltime_from_jiffies (unsigned long long tval
, long hz
)
2936 struct timespec t
= time_from_jiffies (tval
, hz
);
2937 return make_lisp_time (t
);
2940 static struct timespec
2944 struct timespec up
= make_timespec (0, 0);
2947 fup
= emacs_fopen ("/proc/uptime", "r");
2951 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
2952 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
2954 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
2955 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
2956 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
2959 if (TYPE_MAXIMUM (time_t) < upsec
)
2961 upsec
= TYPE_MAXIMUM (time_t);
2962 upfrac
= TIMESPEC_RESOLUTION
- 1;
2966 int upfraclen
= upfrac_end
- upfrac_start
;
2967 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
2969 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
2971 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
2973 up
= make_timespec (upsec
, upfrac
);
2982 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2983 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2986 procfs_ttyname (int rdev
)
2989 char name
[PATH_MAX
];
2992 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
2998 unsigned long minor_beg
, minor_end
;
2999 char minor
[25]; /* 2 32-bit numbers + dash */
3002 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3004 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3005 && major
== MAJOR (rdev
))
3007 minor_beg
= strtoul (minor
, &endp
, 0);
3009 minor_end
= minor_beg
;
3010 else if (*endp
== '-')
3011 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3015 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3017 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3025 return build_string (name
);
3029 procfs_get_total_memory (void)
3032 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3036 fmem
= emacs_fopen ("/proc/meminfo", "r");
3040 uintmax_t entry_value
;
3044 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3047 retval
= entry_value
;
3052 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3070 system_process_attributes (Lisp_Object pid
)
3072 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3076 long clocks_per_sec
;
3078 char procbuf
[1025], *p
, *q
;
3081 static char const default_cmd
[] = "???";
3082 const char *cmd
= default_cmd
;
3083 int cmdsize
= sizeof default_cmd
- 1;
3084 char *cmdline
= NULL
;
3085 ptrdiff_t cmdline_size
;
3088 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3091 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3092 long priority
, niceness
, rss
;
3093 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3094 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3096 Lisp_Object attrs
= Qnil
;
3097 Lisp_Object decoded_cmd
;
3100 CHECK_NUMBER_OR_FLOAT (pid
);
3101 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3102 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3103 if (stat (procfn
, &st
) < 0)
3108 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3110 pw
= getpwuid (uid
);
3113 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3116 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3118 gr
= getgrgid (gid
);
3121 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3123 count
= SPECPDL_INDEX ();
3124 strcpy (fn
, procfn
);
3125 procfn_end
= fn
+ strlen (fn
);
3126 strcpy (procfn_end
, "/stat");
3127 fd
= emacs_open (fn
, O_RDONLY
, 0);
3132 record_unwind_protect_int (close_file_unwind
, fd
);
3133 nread
= emacs_read (fd
, procbuf
, sizeof procbuf
- 1);
3137 procbuf
[nread
] = '\0';
3140 p
= strchr (p
, '(');
3143 q
= strrchr (p
+ 1, ')');
3153 /* Command name is encoded in locale-coding-system; decode it. */
3154 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3155 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3156 Vlocale_coding_system
, 0);
3157 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3159 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3160 utime stime cutime cstime priority nice thcount . start vsize rss */
3162 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3163 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3164 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3165 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3166 &u_time
, &s_time
, &cutime
, &cstime
,
3167 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3172 state_str
[1] = '\0';
3173 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3174 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3175 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3176 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3177 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3178 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3179 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3180 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3181 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3183 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3185 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3186 if (clocks_per_sec
< 0)
3187 clocks_per_sec
= 100;
3188 attrs
= Fcons (Fcons (Qutime
,
3189 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3191 attrs
= Fcons (Fcons (Qstime
,
3192 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3194 attrs
= Fcons (Fcons (Qtime
,
3195 ltime_from_jiffies (s_time
+ u_time
,
3198 attrs
= Fcons (Fcons (Qcutime
,
3199 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3201 attrs
= Fcons (Fcons (Qcstime
,
3202 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3204 attrs
= Fcons (Fcons (Qctime
,
3205 ltime_from_jiffies (cstime
+ cutime
,
3208 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3209 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3210 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3212 tnow
= current_timespec ();
3213 telapsed
= get_up_time ();
3214 tboot
= timespec_sub (tnow
, telapsed
);
3215 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3216 tstart
= timespec_add (tboot
, tstart
);
3217 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3218 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3220 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3221 telapsed
= timespec_sub (tnow
, tstart
);
3222 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3223 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3224 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3227 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3228 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3231 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3234 unbind_to (count
, Qnil
);
3237 strcpy (procfn_end
, "/cmdline");
3238 fd
= emacs_open (fn
, O_RDONLY
, 0);
3241 ptrdiff_t readsize
, nread_incr
;
3242 record_unwind_protect_int (close_file_unwind
, fd
);
3243 record_unwind_protect_nothing ();
3244 nread
= cmdline_size
= 0;
3248 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3249 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3251 /* Leave room even if every byte needs escaping below. */
3252 readsize
= (cmdline_size
>> 1) - nread
;
3254 nread_incr
= emacs_read (fd
, cmdline
+ nread
, readsize
);
3255 nread
+= max (0, nread_incr
);
3257 while (nread_incr
== readsize
);
3261 /* We don't want trailing null characters. */
3262 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3265 /* Escape-quote whitespace and backslashes. */
3266 q
= cmdline
+ cmdline_size
;
3271 if (c_isspace (c
) || c
== '\\')
3275 nread
= cmdline
+ cmdline_size
- q
;
3280 nread
= cmdsize
+ 2;
3281 cmdline_size
= nread
+ 1;
3282 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3283 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3284 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3286 /* Command line is encoded in locale-coding-system; decode it. */
3287 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3288 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3289 Vlocale_coding_system
, 0);
3290 unbind_to (count
, Qnil
);
3291 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3297 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3299 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3300 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3301 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3302 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3303 #undef _FILE_OFFSET_BITS
3305 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3310 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3311 #define _FILE_OFFSET_BITS 64
3312 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3314 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3317 system_process_attributes (Lisp_Object pid
)
3319 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3324 struct psinfo pinfo
;
3330 Lisp_Object attrs
= Qnil
;
3331 Lisp_Object decoded_cmd
;
3334 CHECK_NUMBER_OR_FLOAT (pid
);
3335 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3336 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3337 if (stat (procfn
, &st
) < 0)
3342 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3344 pw
= getpwuid (uid
);
3347 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3350 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3352 gr
= getgrgid (gid
);
3355 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3357 count
= SPECPDL_INDEX ();
3358 strcpy (fn
, procfn
);
3359 procfn_end
= fn
+ strlen (fn
);
3360 strcpy (procfn_end
, "/psinfo");
3361 fd
= emacs_open (fn
, O_RDONLY
, 0);
3366 record_unwind_protect (close_file_unwind
, fd
);
3367 nread
= emacs_read (fd
, &pinfo
, sizeof pinfo
);
3370 if (nread
== sizeof pinfo
)
3372 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3373 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3374 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3378 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3379 state_str
[1] = '\0';
3380 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3383 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3384 need to get a string from it. */
3386 /* FIXME: missing: Qtpgid */
3398 Are they available? */
3400 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3401 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3402 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3403 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3404 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3407 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3408 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3410 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3413 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3414 range 0 .. 2**15, representing 0.0 .. 1.0. */
3415 attrs
= Fcons (Fcons (Qpcpu
,
3416 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3418 attrs
= Fcons (Fcons (Qpmem
,
3419 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3422 AUTO_STRING (fname
, pinfo
.pr_fname
);
3423 decoded_cmd
= code_convert_string_norecord (fname
,
3424 Vlocale_coding_system
, 0);
3425 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3426 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3427 decoded_cmd
= code_convert_string_norecord (psargs
,
3428 Vlocale_coding_system
, 0);
3429 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3431 unbind_to (count
, Qnil
);
3435 #elif defined __FreeBSD__
3437 static struct timespec
3438 timeval_to_timespec (struct timeval t
)
3440 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3444 make_lisp_timeval (struct timeval t
)
3446 return make_lisp_time (timeval_to_timespec (t
));
3450 system_process_attributes (Lisp_Object pid
)
3453 int pagesize
= getpagesize ();
3454 unsigned long npages
;
3460 char args
[MAXPATHLEN
];
3461 struct timespec t
, now
;
3463 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3464 struct kinfo_proc proc
;
3465 size_t proclen
= sizeof proc
;
3467 Lisp_Object attrs
= Qnil
;
3468 Lisp_Object decoded_comm
;
3470 CHECK_NUMBER_OR_FLOAT (pid
);
3471 CONS_TO_INTEGER (pid
, int, proc_id
);
3474 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3477 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3480 pw
= getpwuid (proc
.ki_uid
);
3483 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3485 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3488 gr
= getgrgid (proc
.ki_svgid
);
3491 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3493 AUTO_STRING (comm
, proc
.ki_comm
);
3494 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3496 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3498 char state
[2] = {'\0', '\0'};
3499 switch (proc
.ki_stat
)
3521 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3524 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3525 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3526 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3529 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3532 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3534 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3535 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3536 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3537 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3538 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3540 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3542 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3544 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3545 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3546 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3548 attrs
= Fcons (Fcons (Qcutime
,
3549 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3551 attrs
= Fcons (Fcons (Qcstime
,
3552 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3554 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3555 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3556 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3558 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3560 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3561 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3562 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3563 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3564 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3567 now
= current_timespec ();
3568 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3569 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3571 len
= sizeof fscale
;
3572 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3577 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3579 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3580 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3581 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3585 len
= sizeof npages
;
3586 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3588 double pmem
= (proc
.ki_flag
& P_INMEM
3589 ? 100.0 * proc
.ki_rssize
/ npages
3591 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3594 mib
[2] = KERN_PROC_ARGS
;
3596 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3599 for (i
= 0; i
< len
; i
++)
3601 if (! args
[i
] && i
< len
- 1)
3605 AUTO_STRING (comm
, args
);
3606 decoded_comm
= code_convert_string_norecord (comm
,
3607 Vlocale_coding_system
, 0);
3609 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3615 #elif defined DARWIN_OS
3617 static struct timespec
3618 timeval_to_timespec (struct timeval t
)
3620 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3624 make_lisp_timeval (struct timeval t
)
3626 return make_lisp_time (timeval_to_timespec (t
));
3630 system_process_attributes (Lisp_Object pid
)
3633 int pagesize
= getpagesize ();
3634 unsigned long npages
;
3640 char args
[MAXPATHLEN
];
3641 struct timeval starttime
;
3642 struct timespec t
, now
;
3643 struct rusage
*rusage
;
3648 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3649 struct kinfo_proc proc
;
3650 size_t proclen
= sizeof proc
;
3652 Lisp_Object attrs
= Qnil
;
3653 Lisp_Object decoded_comm
;
3655 CHECK_NUMBER_OR_FLOAT (pid
);
3656 CONS_TO_INTEGER (pid
, int, proc_id
);
3659 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3662 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3663 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3666 pw
= getpwuid (uid
);
3669 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3671 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3672 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3675 gr
= getgrgid (gid
);
3678 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3680 decoded_comm
= (code_convert_string_norecord
3681 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3682 Vlocale_coding_system
, 0));
3684 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3686 char state
[2] = {'\0', '\0'};
3687 switch (proc
.kp_proc
.p_stat
)
3709 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3712 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3714 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3717 tdev
= proc
.kp_eproc
.e_tdev
;
3719 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3722 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3724 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3727 rusage
= proc
.kp_proc
.p_ru
;
3730 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3732 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3735 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3737 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3739 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3740 timeval_to_timespec (rusage
->ru_stime
));
3741 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3744 starttime
= proc
.kp_proc
.p_starttime
;
3745 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3746 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3748 now
= current_timespec ();
3749 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3750 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3755 /* The WINDOWSNT implementation is in w32.c.
3756 The MSDOS implementation is in dosfns.c. */
3757 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3760 system_process_attributes (Lisp_Object pid
)
3765 #endif /* !defined (WINDOWSNT) */
3767 /* Wide character string collation. */
3769 #ifdef __STDC_ISO_10646__
3771 # include <wctype.h>
3773 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3774 # include <locale.h>
3777 # define LC_COLLATE 0
3779 # ifndef LC_COLLATE_MASK
3780 # define LC_COLLATE_MASK 0
3785 # ifndef LC_CTYPE_MASK
3786 # define LC_CTYPE_MASK 0
3789 # ifndef HAVE_NEWLOCALE
3795 # define freelocale emacs_freelocale
3796 # define locale_t emacs_locale_t
3797 # define newlocale emacs_newlocale
3798 # define wcscoll_l emacs_wcscoll_l
3799 # define towlower_l emacs_towlower_l
3801 typedef char const *locale_t
;
3804 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3810 freelocale (locale_t loc
)
3815 emacs_setlocale (int category
, char const *locale
)
3817 # ifdef HAVE_SETLOCALE
3819 char *loc
= setlocale (category
, locale
);
3830 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3833 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3841 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3842 strcpy (oldcopy
, oldloc
);
3843 if (! emacs_setlocale (LC_COLLATE
, loc
))
3848 result
= wcscoll (a
, b
);
3850 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3861 towlower_l (wint_t wc
, locale_t loc
)
3864 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3869 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3870 strcpy (oldcopy
, oldloc
);
3871 if (emacs_setlocale (LC_CTYPE
, loc
))
3873 result
= towlower (wc
);
3874 emacs_setlocale (LC_COLLATE
, oldcopy
);
3884 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3885 Lisp_Object locale
, Lisp_Object ignore_case
)
3888 ptrdiff_t len
, i
, i_byte
;
3893 /* Convert byte stream to code points. */
3894 len
= SCHARS (s1
); i
= i_byte
= 0;
3895 SAFE_NALLOCA (p1
, 1, len
+ 1);
3897 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3900 len
= SCHARS (s2
); i
= i_byte
= 0;
3901 SAFE_NALLOCA (p2
, 1, len
+ 1);
3903 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3906 if (STRINGP (locale
))
3908 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3909 SSDATA (locale
), 0);
3911 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3913 if (! NILP (ignore_case
))
3914 for (int i
= 1; i
< 3; i
++)
3916 wchar_t *p
= (i
== 1) ? p1
: p2
;
3918 *p
= towlower_l (*p
, loc
);
3922 res
= wcscoll_l (p1
, p2
, loc
);
3928 if (! NILP (ignore_case
))
3929 for (int i
= 1; i
< 3; i
++)
3931 wchar_t *p
= (i
== 1) ? p1
: p2
;
3937 res
= wcscoll (p1
, p2
);
3940 # ifndef HAVE_NEWLOCALE
3942 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
3945 error ("Invalid string for collation: %s", emacs_strerror (err
));
3951 #endif /* __STDC_ISO_10646__ */
3955 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3956 Lisp_Object locale
, Lisp_Object ignore_case
)
3959 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
3960 int res
, err
= errno
;
3963 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
3965 error ("Invalid string for collation: %s", strerror (errno
));
3970 #endif /* WINDOWSNT */