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 bool success
= false;
2193 /* First, try seeding the PRNG from the operating system's entropy
2194 source. This approach is both fast and secure. */
2196 success
= w32_init_random (&v
, sizeof v
) == 0;
2198 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2201 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2206 /* If that didn't work, try using GnuTLS, which is secure, but on
2207 some systems, can be somewhat slow. */
2209 success
= EQ (emacs_gnutls_global_init (), Qt
)
2210 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0;
2212 /* If _that_ didn't work, just use the current time value and PID.
2213 It's at least better than XKCD 221. */
2216 struct timespec t
= current_timespec ();
2217 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2220 set_random_seed (v
);
2224 * Return a nonnegative random integer out of whatever we've got.
2225 * It contains enough bits to make a random (signed) Emacs fixnum.
2226 * This suffices even for a 64-bit architecture with a 15-bit rand.
2233 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2234 val
= (random () ^ (val
<< RAND_BITS
)
2235 ^ (val
>> (EMACS_INT_WIDTH
- RAND_BITS
)));
2236 val
^= val
>> (EMACS_INT_WIDTH
- FIXNUM_BITS
);
2237 return val
& INTMASK
;
2240 #ifndef HAVE_SNPRINTF
2241 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2243 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2245 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2246 ptrdiff_t nbytes
= size
- 1;
2251 va_start (ap
, format
);
2252 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2256 if (nbytes
== size
- 1)
2258 /* Calculate the length of the string that would have been created
2259 had the buffer been large enough. */
2260 char stackbuf
[4000];
2262 ptrdiff_t bsize
= sizeof stackbuf
;
2263 va_start (ap
, format
);
2264 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2270 if (INT_MAX
< nbytes
)
2283 /* If a backtrace is available, output the top lines of it to stderr.
2284 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2285 This function may be called from a signal handler, so it should
2286 not invoke async-unsafe functions like malloc.
2288 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2289 but do not output anything. This avoids some problems that can
2290 otherwise occur if the malloc arena is corrupted before 'backtrace'
2291 is called, since 'backtrace' may call malloc if the tables are not
2294 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2295 fatal error has occurred in some other thread; generate a thread
2296 backtrace instead, ignoring BACKTRACE_LIMIT. */
2298 emacs_backtrace (int backtrace_limit
)
2300 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2301 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2305 if (thread_backtrace_npointers
)
2307 buffer
= thread_backtrace_buffer
;
2308 npointers
= thread_backtrace_npointers
;
2312 buffer
= main_backtrace_buffer
;
2314 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2315 if (bounded_limit
< 0)
2317 backtrace (buffer
, 1);
2321 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2326 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2327 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2328 if (bounded_limit
< npointers
)
2329 emacs_write (STDERR_FILENO
, "...\n", 4);
2337 terminate_due_to_signal (SIGABRT
, 40);
2341 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2342 Use binary I/O on systems that care about text vs binary I/O.
2343 Arrange for subprograms to not inherit the file descriptor.
2344 Prefer a method that is multithread-safe, if available.
2345 Do not fail merely because the open was interrupted by a signal.
2346 Allow the user to quit. */
2349 emacs_open (const char *file
, int oflags
, int mode
)
2352 if (! (oflags
& O_TEXT
))
2354 oflags
|= O_CLOEXEC
;
2355 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2357 if (! O_CLOEXEC
&& 0 <= fd
)
2358 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2362 /* Open FILE as a stream for Emacs use, with mode MODE.
2363 Act like emacs_open with respect to threads, signals, and quits. */
2366 emacs_fopen (char const *file
, char const *mode
)
2368 int fd
, omode
, oflags
;
2370 char const *m
= mode
;
2374 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2375 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2376 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2377 default: emacs_abort ();
2383 case '+': omode
= O_RDWR
; break;
2384 case 't': bflag
= O_TEXT
; break;
2385 default: /* Ignore. */ break;
2388 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2389 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2392 /* Create a pipe for Emacs use. */
2395 emacs_pipe (int fd
[2])
2400 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2401 if (! O_CLOEXEC
&& result
== 0)
2403 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2404 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2410 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2411 For the background behind this mess, please see Austin Group defect 529
2412 <http://austingroupbugs.net/view.php?id=529>. */
2414 #ifndef POSIX_CLOSE_RESTART
2415 # define POSIX_CLOSE_RESTART 1
2417 posix_close (int fd
, int flag
)
2419 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2420 eassert (flag
== POSIX_CLOSE_RESTART
);
2422 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2423 on a system that does not define POSIX_CLOSE_RESTART.
2425 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2426 closed, and retrying the close could inadvertently close a file
2427 descriptor allocated by some other thread. In other systems
2428 (e.g., HP/UX) FD is not closed. And in still other systems
2429 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2430 multithreaded program there can be no way to tell.
2432 So, in this case, pretend that the close succeeded. This works
2433 well on systems like GNU/Linux that close FD. Although it may
2434 leak a file descriptor on other systems, the leak is unlikely and
2435 it's better to leak than to close a random victim. */
2436 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2440 /* Close FD, retrying if interrupted. If successful, return 0;
2441 otherwise, return -1 and set errno to a non-EINTR value. Consider
2442 an EINPROGRESS error to be successful, as that's merely a signal
2443 arriving. FD is always closed when this function returns, even
2446 Do not call this function if FD is nonnegative and might already be closed,
2447 as that might close an innocent victim opened by some other thread. */
2450 emacs_close (int fd
)
2454 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2457 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2459 eassert (errno
!= EBADF
|| fd
< 0);
2460 return errno
== EINPROGRESS
? 0 : r
;
2465 /* Maximum number of bytes to read or write in a single system call.
2466 This works around a serious bug in Linux kernels before 2.6.16; see
2467 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2468 It's likely to work around similar bugs in other operating systems, so do it
2469 on all platforms. Round INT_MAX down to a page size, with the conservative
2470 assumption that page sizes are at most 2**18 bytes (any kernel with a
2471 page size larger than that shouldn't have the bug). */
2472 #ifndef MAX_RW_COUNT
2473 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2476 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2477 Return the number of bytes read, which might be less than NBYTE.
2478 On error, set errno and return -1. */
2480 emacs_read (int fildes
, void *buf
, ptrdiff_t nbyte
)
2484 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2485 passes a size that large to emacs_read. */
2487 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
2488 && (errno
== EINTR
))
2493 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2494 or if a partial write occurs. If interrupted, process pending
2495 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2496 errno if this is less than NBYTE. */
2498 emacs_full_write (int fildes
, char const *buf
, ptrdiff_t nbyte
,
2499 bool process_signals
)
2501 ptrdiff_t bytes_written
= 0;
2505 ssize_t n
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
2511 /* I originally used `QUIT' but that might cause files to
2512 be truncated if you hit C-g in the middle of it. --Stef */
2513 if (process_signals
&& pending_signals
)
2514 process_pending_signals ();
2526 return bytes_written
;
2529 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2530 interrupted or if a partial write occurs. Return the number of
2531 bytes written, setting errno if this is less than NBYTE. */
2533 emacs_write (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2535 return emacs_full_write (fildes
, buf
, nbyte
, 0);
2538 /* Like emacs_write, but also process pending signals if interrupted. */
2540 emacs_write_sig (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2542 return emacs_full_write (fildes
, buf
, nbyte
, 1);
2545 /* Write a diagnostic to standard error that contains MESSAGE and a
2546 string derived from errno. Preserve errno. Do not buffer stderr.
2547 Do not process pending signals if interrupted. */
2549 emacs_perror (char const *message
)
2552 char const *error_string
= emacs_strerror (err
);
2553 char const *command
= (initial_argv
&& initial_argv
[0]
2554 ? initial_argv
[0] : "emacs");
2555 /* Write it out all at once, if it's short; this is less likely to
2556 be interleaved with other output. */
2558 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2559 command
, message
, error_string
);
2560 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2561 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2564 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2565 emacs_write (STDERR_FILENO
, ": ", 2);
2566 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2567 emacs_write (STDERR_FILENO
, ": ", 2);
2568 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2569 emacs_write (STDERR_FILENO
, "\n", 1);
2574 /* Return a struct timeval that is roughly equivalent to T.
2575 Use the least timeval not less than T.
2576 Return an extremal value if the result would overflow. */
2578 make_timeval (struct timespec t
)
2581 tv
.tv_sec
= t
.tv_sec
;
2582 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2584 if (t
.tv_nsec
% 1000 != 0)
2586 if (tv
.tv_usec
< 999999)
2588 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2598 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2599 ATIME and MTIME, respectively.
2600 FD must be either negative -- in which case it is ignored --
2601 or a file descriptor that is open on FILE.
2602 If FD is nonnegative, then FILE can be NULL. */
2604 set_file_times (int fd
, const char *filename
,
2605 struct timespec atime
, struct timespec mtime
)
2607 struct timespec timespec
[2];
2608 timespec
[0] = atime
;
2609 timespec
[1] = mtime
;
2610 return fdutimens (fd
, filename
, timespec
);
2613 /* Like strsignal, except async-signal-safe, and this function typically
2614 returns a string in the C locale rather than the current locale. */
2616 safe_strsignal (int code
)
2618 char const *signame
= 0;
2620 if (0 <= code
&& code
< sys_siglist_entries
)
2621 signame
= sys_siglist
[code
];
2623 signame
= "Unknown signal";
2629 /* For make-serial-process */
2631 serial_open (Lisp_Object port
)
2633 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2635 report_file_error ("Opening serial port", port
);
2637 ioctl (fd
, TIOCEXCL
, (char *) 0);
2643 #if !defined (HAVE_CFMAKERAW)
2644 /* Workaround for targets which are missing cfmakeraw. */
2645 /* Pasted from man page. */
2647 cfmakeraw (struct termios
*termios_p
)
2649 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2650 termios_p
->c_oflag
&= ~OPOST
;
2651 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2652 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2653 termios_p
->c_cflag
|= CS8
;
2655 #endif /* !defined (HAVE_CFMAKERAW */
2657 #if !defined (HAVE_CFSETSPEED)
2658 /* Workaround for targets which are missing cfsetspeed. */
2660 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2662 return (cfsetispeed (termios_p
, vitesse
)
2663 + cfsetospeed (termios_p
, vitesse
));
2667 /* For serial-process-configure */
2669 serial_configure (struct Lisp_Process
*p
,
2670 Lisp_Object contact
)
2672 Lisp_Object childp2
= Qnil
;
2673 Lisp_Object tem
= Qnil
;
2674 struct termios attr
;
2676 char summary
[4] = "???"; /* This usually becomes "8N1". */
2678 childp2
= Fcopy_sequence (p
->childp
);
2680 /* Read port attributes and prepare default configuration. */
2681 err
= tcgetattr (p
->outfd
, &attr
);
2683 report_file_error ("Failed tcgetattr", Qnil
);
2685 #if defined (CLOCAL)
2686 attr
.c_cflag
|= CLOCAL
;
2689 attr
.c_cflag
|= CREAD
;
2692 /* Configure speed. */
2693 if (!NILP (Fplist_member (contact
, QCspeed
)))
2694 tem
= Fplist_get (contact
, QCspeed
);
2696 tem
= Fplist_get (p
->childp
, QCspeed
);
2698 err
= cfsetspeed (&attr
, XINT (tem
));
2700 report_file_error ("Failed cfsetspeed", tem
);
2701 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2703 /* Configure bytesize. */
2704 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2705 tem
= Fplist_get (contact
, QCbytesize
);
2707 tem
= Fplist_get (p
->childp
, QCbytesize
);
2709 tem
= make_number (8);
2711 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2712 error (":bytesize must be nil (8), 7, or 8");
2713 summary
[0] = XINT (tem
) + '0';
2714 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2715 attr
.c_cflag
&= ~CSIZE
;
2716 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2718 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2719 if (XINT (tem
) != 8)
2720 error ("Bytesize cannot be changed");
2722 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2724 /* Configure parity. */
2725 if (!NILP (Fplist_member (contact
, QCparity
)))
2726 tem
= Fplist_get (contact
, QCparity
);
2728 tem
= Fplist_get (p
->childp
, QCparity
);
2729 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2730 error (":parity must be nil (no parity), `even', or `odd'");
2731 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2732 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2733 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2738 else if (EQ (tem
, Qeven
))
2741 attr
.c_cflag
|= PARENB
;
2742 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2744 else if (EQ (tem
, Qodd
))
2747 attr
.c_cflag
|= (PARENB
| PARODD
);
2748 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2751 /* Don't error on no parity, which should be set by cfmakeraw. */
2753 error ("Parity cannot be configured");
2755 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2757 /* Configure stopbits. */
2758 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2759 tem
= Fplist_get (contact
, QCstopbits
);
2761 tem
= Fplist_get (p
->childp
, QCstopbits
);
2763 tem
= make_number (1);
2765 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2766 error (":stopbits must be nil (1 stopbit), 1, or 2");
2767 summary
[2] = XINT (tem
) + '0';
2768 #if defined (CSTOPB)
2769 attr
.c_cflag
&= ~CSTOPB
;
2770 if (XINT (tem
) == 2)
2771 attr
.c_cflag
|= CSTOPB
;
2773 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2774 if (XINT (tem
) != 1)
2775 error ("Stopbits cannot be configured");
2777 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2779 /* Configure flowcontrol. */
2780 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2781 tem
= Fplist_get (contact
, QCflowcontrol
);
2783 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2784 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2785 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2786 #if defined (CRTSCTS)
2787 attr
.c_cflag
&= ~CRTSCTS
;
2789 #if defined (CNEW_RTSCTS)
2790 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2792 #if defined (IXON) && defined (IXOFF)
2793 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2797 /* Already configured. */
2799 else if (EQ (tem
, Qhw
))
2801 #if defined (CRTSCTS)
2802 attr
.c_cflag
|= CRTSCTS
;
2803 #elif defined (CNEW_RTSCTS)
2804 attr
.c_cflag
|= CNEW_RTSCTS
;
2806 error ("Hardware flowcontrol (RTS/CTS) not supported");
2809 else if (EQ (tem
, Qsw
))
2811 #if defined (IXON) && defined (IXOFF)
2812 attr
.c_iflag
|= (IXON
| IXOFF
);
2814 error ("Software flowcontrol (XON/XOFF) not supported");
2817 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2819 /* Activate configuration. */
2820 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2822 report_file_error ("Failed tcsetattr", Qnil
);
2824 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2825 pset_childp (p
, childp2
);
2827 #endif /* not DOS_NT */
2829 /* System depended enumeration of and access to system processes a-la ps(1). */
2833 /* Process enumeration and access via /proc. */
2836 list_system_processes (void)
2838 Lisp_Object procdir
, match
, proclist
, next
;
2841 /* For every process on the system, there's a directory in the
2842 "/proc" pseudo-directory whose name is the numeric ID of that
2844 procdir
= build_string ("/proc");
2845 match
= build_string ("[0-9]+");
2846 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2848 /* `proclist' gives process IDs as strings. Destructively convert
2849 each string into a number. */
2850 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2853 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2856 /* directory_files_internal returns the files in reverse order; undo
2858 proclist
= Fnreverse (proclist
);
2862 #elif defined DARWIN_OS || defined __FreeBSD__
2865 list_system_processes (void)
2868 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2870 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2873 struct kinfo_proc
*procs
;
2876 Lisp_Object proclist
= Qnil
;
2878 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2881 procs
= xmalloc (len
);
2882 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2888 len
/= sizeof (struct kinfo_proc
);
2889 for (i
= 0; i
< len
; i
++)
2892 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2894 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2903 /* The WINDOWSNT implementation is in w32.c.
2904 The MSDOS implementation is in dosfns.c. */
2905 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2908 list_system_processes (void)
2913 #endif /* !defined (WINDOWSNT) */
2915 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2916 static struct timespec
2917 time_from_jiffies (unsigned long long tval
, long hz
)
2919 unsigned long long s
= tval
/ hz
;
2920 unsigned long long frac
= tval
% hz
;
2923 if (TYPE_MAXIMUM (time_t) < s
)
2925 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2926 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2927 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2930 /* This is reachable only in the unlikely case that HZ * HZ
2931 exceeds ULLONG_MAX. It calculates an approximation that is
2932 guaranteed to be in range. */
2933 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
2934 + (hz
% TIMESPEC_RESOLUTION
!= 0));
2935 ns
= frac
/ hz_per_ns
;
2938 return make_timespec (s
, ns
);
2942 ltime_from_jiffies (unsigned long long tval
, long hz
)
2944 struct timespec t
= time_from_jiffies (tval
, hz
);
2945 return make_lisp_time (t
);
2948 static struct timespec
2952 struct timespec up
= make_timespec (0, 0);
2955 fup
= emacs_fopen ("/proc/uptime", "r");
2959 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
2960 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
2962 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
2963 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
2964 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
2967 if (TYPE_MAXIMUM (time_t) < upsec
)
2969 upsec
= TYPE_MAXIMUM (time_t);
2970 upfrac
= TIMESPEC_RESOLUTION
- 1;
2974 int upfraclen
= upfrac_end
- upfrac_start
;
2975 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
2977 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
2979 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
2981 up
= make_timespec (upsec
, upfrac
);
2990 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2991 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2994 procfs_ttyname (int rdev
)
2997 char name
[PATH_MAX
];
3000 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
3006 unsigned long minor_beg
, minor_end
;
3007 char minor
[25]; /* 2 32-bit numbers + dash */
3010 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3012 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3013 && major
== MAJOR (rdev
))
3015 minor_beg
= strtoul (minor
, &endp
, 0);
3017 minor_end
= minor_beg
;
3018 else if (*endp
== '-')
3019 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3023 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3025 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3033 return build_string (name
);
3037 procfs_get_total_memory (void)
3040 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3044 fmem
= emacs_fopen ("/proc/meminfo", "r");
3048 uintmax_t entry_value
;
3052 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3055 retval
= entry_value
;
3060 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3078 system_process_attributes (Lisp_Object pid
)
3080 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3084 long clocks_per_sec
;
3086 char procbuf
[1025], *p
, *q
;
3089 static char const default_cmd
[] = "???";
3090 const char *cmd
= default_cmd
;
3091 int cmdsize
= sizeof default_cmd
- 1;
3092 char *cmdline
= NULL
;
3093 ptrdiff_t cmdline_size
;
3096 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3099 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3100 long priority
, niceness
, rss
;
3101 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3102 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3104 Lisp_Object attrs
= Qnil
;
3105 Lisp_Object decoded_cmd
;
3108 CHECK_NUMBER_OR_FLOAT (pid
);
3109 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3110 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3111 if (stat (procfn
, &st
) < 0)
3116 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3118 pw
= getpwuid (uid
);
3121 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3124 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3126 gr
= getgrgid (gid
);
3129 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3131 count
= SPECPDL_INDEX ();
3132 strcpy (fn
, procfn
);
3133 procfn_end
= fn
+ strlen (fn
);
3134 strcpy (procfn_end
, "/stat");
3135 fd
= emacs_open (fn
, O_RDONLY
, 0);
3140 record_unwind_protect_int (close_file_unwind
, fd
);
3141 nread
= emacs_read (fd
, procbuf
, sizeof procbuf
- 1);
3145 procbuf
[nread
] = '\0';
3148 p
= strchr (p
, '(');
3151 q
= strrchr (p
+ 1, ')');
3161 /* Command name is encoded in locale-coding-system; decode it. */
3162 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3163 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3164 Vlocale_coding_system
, 0);
3165 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3167 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3168 utime stime cutime cstime priority nice thcount . start vsize rss */
3170 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3171 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3172 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3173 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3174 &u_time
, &s_time
, &cutime
, &cstime
,
3175 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3180 state_str
[1] = '\0';
3181 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3182 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3183 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3184 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3185 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3186 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3187 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3188 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3189 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3191 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3193 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3194 if (clocks_per_sec
< 0)
3195 clocks_per_sec
= 100;
3196 attrs
= Fcons (Fcons (Qutime
,
3197 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3199 attrs
= Fcons (Fcons (Qstime
,
3200 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3202 attrs
= Fcons (Fcons (Qtime
,
3203 ltime_from_jiffies (s_time
+ u_time
,
3206 attrs
= Fcons (Fcons (Qcutime
,
3207 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3209 attrs
= Fcons (Fcons (Qcstime
,
3210 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3212 attrs
= Fcons (Fcons (Qctime
,
3213 ltime_from_jiffies (cstime
+ cutime
,
3216 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3217 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3218 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3220 tnow
= current_timespec ();
3221 telapsed
= get_up_time ();
3222 tboot
= timespec_sub (tnow
, telapsed
);
3223 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3224 tstart
= timespec_add (tboot
, tstart
);
3225 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3226 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3228 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3229 telapsed
= timespec_sub (tnow
, tstart
);
3230 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3231 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3232 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3235 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3236 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3239 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3242 unbind_to (count
, Qnil
);
3245 strcpy (procfn_end
, "/cmdline");
3246 fd
= emacs_open (fn
, O_RDONLY
, 0);
3249 ptrdiff_t readsize
, nread_incr
;
3250 record_unwind_protect_int (close_file_unwind
, fd
);
3251 record_unwind_protect_nothing ();
3252 nread
= cmdline_size
= 0;
3256 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3257 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3259 /* Leave room even if every byte needs escaping below. */
3260 readsize
= (cmdline_size
>> 1) - nread
;
3262 nread_incr
= emacs_read (fd
, cmdline
+ nread
, readsize
);
3263 nread
+= max (0, nread_incr
);
3265 while (nread_incr
== readsize
);
3269 /* We don't want trailing null characters. */
3270 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3273 /* Escape-quote whitespace and backslashes. */
3274 q
= cmdline
+ cmdline_size
;
3279 if (c_isspace (c
) || c
== '\\')
3283 nread
= cmdline
+ cmdline_size
- q
;
3288 nread
= cmdsize
+ 2;
3289 cmdline_size
= nread
+ 1;
3290 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3291 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3292 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3294 /* Command line is encoded in locale-coding-system; decode it. */
3295 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3296 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3297 Vlocale_coding_system
, 0);
3298 unbind_to (count
, Qnil
);
3299 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3305 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3307 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3308 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3309 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3310 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3311 #undef _FILE_OFFSET_BITS
3313 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3318 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3319 #define _FILE_OFFSET_BITS 64
3320 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3322 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3325 system_process_attributes (Lisp_Object pid
)
3327 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3332 struct psinfo pinfo
;
3338 Lisp_Object attrs
= Qnil
;
3339 Lisp_Object decoded_cmd
;
3342 CHECK_NUMBER_OR_FLOAT (pid
);
3343 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3344 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3345 if (stat (procfn
, &st
) < 0)
3350 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3352 pw
= getpwuid (uid
);
3355 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3358 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3360 gr
= getgrgid (gid
);
3363 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3365 count
= SPECPDL_INDEX ();
3366 strcpy (fn
, procfn
);
3367 procfn_end
= fn
+ strlen (fn
);
3368 strcpy (procfn_end
, "/psinfo");
3369 fd
= emacs_open (fn
, O_RDONLY
, 0);
3374 record_unwind_protect (close_file_unwind
, fd
);
3375 nread
= emacs_read (fd
, &pinfo
, sizeof pinfo
);
3378 if (nread
== sizeof pinfo
)
3380 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3381 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3382 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3386 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3387 state_str
[1] = '\0';
3388 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3391 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3392 need to get a string from it. */
3394 /* FIXME: missing: Qtpgid */
3406 Are they available? */
3408 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3409 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3410 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3411 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3412 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3415 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3416 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3418 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3421 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3422 range 0 .. 2**15, representing 0.0 .. 1.0. */
3423 attrs
= Fcons (Fcons (Qpcpu
,
3424 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3426 attrs
= Fcons (Fcons (Qpmem
,
3427 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3430 AUTO_STRING (fname
, pinfo
.pr_fname
);
3431 decoded_cmd
= code_convert_string_norecord (fname
,
3432 Vlocale_coding_system
, 0);
3433 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3434 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3435 decoded_cmd
= code_convert_string_norecord (psargs
,
3436 Vlocale_coding_system
, 0);
3437 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3439 unbind_to (count
, Qnil
);
3443 #elif defined __FreeBSD__
3445 static struct timespec
3446 timeval_to_timespec (struct timeval t
)
3448 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3452 make_lisp_timeval (struct timeval t
)
3454 return make_lisp_time (timeval_to_timespec (t
));
3458 system_process_attributes (Lisp_Object pid
)
3461 int pagesize
= getpagesize ();
3462 unsigned long npages
;
3468 char args
[MAXPATHLEN
];
3469 struct timespec t
, now
;
3471 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3472 struct kinfo_proc proc
;
3473 size_t proclen
= sizeof proc
;
3475 Lisp_Object attrs
= Qnil
;
3476 Lisp_Object decoded_comm
;
3478 CHECK_NUMBER_OR_FLOAT (pid
);
3479 CONS_TO_INTEGER (pid
, int, proc_id
);
3482 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3485 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3488 pw
= getpwuid (proc
.ki_uid
);
3491 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3493 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3496 gr
= getgrgid (proc
.ki_svgid
);
3499 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3501 AUTO_STRING (comm
, proc
.ki_comm
);
3502 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3504 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3506 char state
[2] = {'\0', '\0'};
3507 switch (proc
.ki_stat
)
3529 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3532 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3533 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3534 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3537 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3540 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3542 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3543 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3544 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3545 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3546 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3548 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3550 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3552 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3553 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3554 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3556 attrs
= Fcons (Fcons (Qcutime
,
3557 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3559 attrs
= Fcons (Fcons (Qcstime
,
3560 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3562 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3563 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3564 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3566 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3568 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3569 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3570 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3571 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3572 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3575 now
= current_timespec ();
3576 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3577 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3579 len
= sizeof fscale
;
3580 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3585 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3587 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3588 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3589 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3593 len
= sizeof npages
;
3594 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3596 double pmem
= (proc
.ki_flag
& P_INMEM
3597 ? 100.0 * proc
.ki_rssize
/ npages
3599 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3602 mib
[2] = KERN_PROC_ARGS
;
3604 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3607 for (i
= 0; i
< len
; i
++)
3609 if (! args
[i
] && i
< len
- 1)
3613 AUTO_STRING (comm
, args
);
3614 decoded_comm
= code_convert_string_norecord (comm
,
3615 Vlocale_coding_system
, 0);
3617 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3623 #elif defined DARWIN_OS
3625 static struct timespec
3626 timeval_to_timespec (struct timeval t
)
3628 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3632 make_lisp_timeval (struct timeval t
)
3634 return make_lisp_time (timeval_to_timespec (t
));
3638 system_process_attributes (Lisp_Object pid
)
3641 int pagesize
= getpagesize ();
3642 unsigned long npages
;
3648 char args
[MAXPATHLEN
];
3649 struct timeval starttime
;
3650 struct timespec t
, now
;
3651 struct rusage
*rusage
;
3656 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3657 struct kinfo_proc proc
;
3658 size_t proclen
= sizeof proc
;
3660 Lisp_Object attrs
= Qnil
;
3661 Lisp_Object decoded_comm
;
3663 CHECK_NUMBER_OR_FLOAT (pid
);
3664 CONS_TO_INTEGER (pid
, int, proc_id
);
3667 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3670 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3671 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3674 pw
= getpwuid (uid
);
3677 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3679 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3680 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3683 gr
= getgrgid (gid
);
3686 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3688 decoded_comm
= (code_convert_string_norecord
3689 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3690 Vlocale_coding_system
, 0));
3692 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3694 char state
[2] = {'\0', '\0'};
3695 switch (proc
.kp_proc
.p_stat
)
3717 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3720 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3722 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3725 tdev
= proc
.kp_eproc
.e_tdev
;
3727 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3730 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3732 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3735 rusage
= proc
.kp_proc
.p_ru
;
3738 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3740 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3743 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3745 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3747 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3748 timeval_to_timespec (rusage
->ru_stime
));
3749 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3752 starttime
= proc
.kp_proc
.p_starttime
;
3753 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3754 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3756 now
= current_timespec ();
3757 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3758 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3763 /* The WINDOWSNT implementation is in w32.c.
3764 The MSDOS implementation is in dosfns.c. */
3765 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3768 system_process_attributes (Lisp_Object pid
)
3773 #endif /* !defined (WINDOWSNT) */
3775 /* Wide character string collation. */
3777 #ifdef __STDC_ISO_10646__
3779 # include <wctype.h>
3781 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3782 # include <locale.h>
3785 # define LC_COLLATE 0
3787 # ifndef LC_COLLATE_MASK
3788 # define LC_COLLATE_MASK 0
3793 # ifndef LC_CTYPE_MASK
3794 # define LC_CTYPE_MASK 0
3797 # ifndef HAVE_NEWLOCALE
3803 # define freelocale emacs_freelocale
3804 # define locale_t emacs_locale_t
3805 # define newlocale emacs_newlocale
3806 # define wcscoll_l emacs_wcscoll_l
3807 # define towlower_l emacs_towlower_l
3809 typedef char const *locale_t
;
3812 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3818 freelocale (locale_t loc
)
3823 emacs_setlocale (int category
, char const *locale
)
3825 # ifdef HAVE_SETLOCALE
3827 char *loc
= setlocale (category
, locale
);
3838 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3841 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3849 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3850 strcpy (oldcopy
, oldloc
);
3851 if (! emacs_setlocale (LC_COLLATE
, loc
))
3856 result
= wcscoll (a
, b
);
3858 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3869 towlower_l (wint_t wc
, locale_t loc
)
3872 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3877 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3878 strcpy (oldcopy
, oldloc
);
3879 if (emacs_setlocale (LC_CTYPE
, loc
))
3881 result
= towlower (wc
);
3882 emacs_setlocale (LC_COLLATE
, oldcopy
);
3892 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3893 Lisp_Object locale
, Lisp_Object ignore_case
)
3896 ptrdiff_t len
, i
, i_byte
;
3901 /* Convert byte stream to code points. */
3902 len
= SCHARS (s1
); i
= i_byte
= 0;
3903 SAFE_NALLOCA (p1
, 1, len
+ 1);
3905 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3908 len
= SCHARS (s2
); i
= i_byte
= 0;
3909 SAFE_NALLOCA (p2
, 1, len
+ 1);
3911 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3914 if (STRINGP (locale
))
3916 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3917 SSDATA (locale
), 0);
3919 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3921 if (! NILP (ignore_case
))
3922 for (int i
= 1; i
< 3; i
++)
3924 wchar_t *p
= (i
== 1) ? p1
: p2
;
3926 *p
= towlower_l (*p
, loc
);
3930 res
= wcscoll_l (p1
, p2
, loc
);
3936 if (! NILP (ignore_case
))
3937 for (int i
= 1; i
< 3; i
++)
3939 wchar_t *p
= (i
== 1) ? p1
: p2
;
3945 res
= wcscoll (p1
, p2
);
3948 # ifndef HAVE_NEWLOCALE
3950 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
3953 error ("Invalid string for collation: %s", emacs_strerror (err
));
3959 #endif /* __STDC_ISO_10646__ */
3963 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3964 Lisp_Object locale
, Lisp_Object ignore_case
)
3967 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
3968 int res
, err
= errno
;
3971 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
3973 error ("Invalid string for collation: %s", strerror (errno
));
3978 #endif /* WINDOWSNT */