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 */
36 #include "sysselect.h"
37 #include "blockinput.h"
39 #if defined DARWIN_OS || defined __FreeBSD__
40 # include <sys/sysctl.h>
44 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
45 'struct frame', so rename it. */
46 # define frame freebsd_frame
47 # include <sys/user.h>
55 #define write sys_write
57 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
60 #endif /* not WINDOWSNT */
62 #include <sys/types.h>
66 /* Get SI_SRPC_DOMAIN, if it is available. */
67 #ifdef HAVE_SYS_SYSTEMINFO_H
68 #include <sys/systeminfo.h>
71 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
75 #include <sys/param.h>
82 #ifdef HAVE_SYS_UTSNAME_H
83 #include <sys/utsname.h>
85 #endif /* HAVE_SYS_UTSNAME_H */
89 #include "termhooks.h"
96 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
97 do that during startup just to call gnutls_rnd. */
98 #if 0x020c00 <= GNUTLS_VERSION_NUMBER && !defined WINDOWSNT
99 # include <gnutls/crypto.h>
101 # define emacs_gnutls_global_init() Qnil
102 # define gnutls_rnd(level, data, len) (-1)
107 /* In process.h which conflicts with the local copy. */
109 int _cdecl
_spawnlp (int, const char *, const char *, ...);
110 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
111 several prototypes of functions called below. */
112 #include <sys/socket.h>
115 #include "syssignal.h"
118 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
120 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
123 /* Declare here, including term.h is problematic on some systems. */
124 extern void tputs (const char *, int, int (*)(int));
126 static const int baud_convert
[] =
128 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
129 1800, 2400, 4800, 9600, 19200, 38400
132 /* If FD is not already open, arrange for it to be open with FLAGS. */
134 force_open (int fd
, int flags
)
136 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
138 int n
= open (NULL_DEVICE
, flags
);
139 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
141 emacs_perror (NULL_DEVICE
);
147 /* Make sure stdin, stdout, and stderr are open to something, so that
148 their file descriptors are not hijacked by later system calls. */
150 init_standard_fds (void)
152 /* Open stdin for *writing*, and stdout and stderr for *reading*.
153 That way, any attempt to do normal I/O will result in an error,
154 just as if the files were closed, and the file descriptors will
155 not be reused by later opens. */
156 force_open (STDIN_FILENO
, O_WRONLY
);
157 force_open (STDOUT_FILENO
, O_RDONLY
);
158 force_open (STDERR_FILENO
, O_RDONLY
);
161 /* Return the current working directory. The result should be freed
162 with 'free'. Return NULL on errors. */
164 emacs_get_current_dir_name (void)
166 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
167 # ifdef HYBRID_MALLOC
168 bool use_libc
= bss_sbrk_did_unexec
;
170 bool use_libc
= true;
173 return get_current_dir_name ();
177 char *pwd
= getenv ("PWD");
178 struct stat dotstat
, pwdstat
;
179 /* If PWD is accurate, use it instead of calling getcwd. PWD is
180 sometimes a nicer name, and using it may avoid a fatal error if a
181 parent directory is searchable but not readable. */
183 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
184 && stat (pwd
, &pwdstat
) == 0
185 && stat (".", &dotstat
) == 0
186 && dotstat
.st_ino
== pwdstat
.st_ino
187 && dotstat
.st_dev
== pwdstat
.st_dev
189 && strlen (pwd
) < MAXPATHLEN
193 buf
= malloc (strlen (pwd
) + 1);
200 size_t buf_size
= 1024;
201 buf
= malloc (buf_size
);
206 if (getcwd (buf
, buf_size
) == buf
)
210 int tmp_errno
= errno
;
216 buf
= realloc (buf
, buf_size
);
225 /* Discard pending input on all input descriptors. */
228 discard_tty_input (void)
231 struct emacs_tty buf
;
236 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
237 while (dos_keyread () != -1)
239 #else /* not MSDOS */
241 struct tty_display_info
*tty
;
242 for (tty
= tty_list
; tty
; tty
= tty
->next
)
244 if (tty
->input
) /* Is the device suspended? */
246 emacs_get_tty (fileno (tty
->input
), &buf
);
247 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
251 #endif /* not MSDOS */
252 #endif /* not WINDOWSNT */
258 /* Arrange for character C to be read as the next input from
260 XXX What if we have multiple ttys?
266 if (! (FRAMEP (selected_frame
)
267 && FRAME_LIVE_P (XFRAME (selected_frame
))
268 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
271 /* Should perhaps error if in batch mode */
273 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
274 #else /* no TIOCSTI */
275 error ("Cannot stuff terminal input characters in this version of Unix");
276 #endif /* no TIOCSTI */
282 init_baud_rate (int fd
)
292 #else /* not DOS_NT */
297 emacs_ospeed
= cfgetospeed (&sg
);
298 #endif /* not DOS_NT */
301 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
302 ? baud_convert
[emacs_ospeed
] : 9600);
311 /* Wait for the subprocess with process id CHILD to terminate or change status.
312 CHILD must be a child process that has not been reaped.
313 If STATUS is non-null, store the waitpid-style exit status into *STATUS
314 and tell wait_reading_process_output that it needs to look around.
315 Use waitpid-style OPTIONS when waiting.
316 If INTERRUPTIBLE, this function is interruptible by a signal.
318 Return CHILD if successful, 0 if no status is available;
319 the latter is possible only when options & NOHANG. */
321 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
325 /* Invoke waitpid only with a known process ID; do not invoke
326 waitpid with a nonpositive argument. Otherwise, Emacs might
327 reap an unwanted process by mistake. For example, invoking
328 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
329 so that another thread running glib won't find them. */
332 while ((pid
= waitpid (child
, status
, options
)) < 0)
334 /* Check that CHILD is a child process that has not been reaped,
335 and that STATUS and OPTIONS are valid. Otherwise abort,
336 as continuing after this internal error could cause Emacs to
337 become confused and kill innocent-victim processes. */
341 /* Note: the MS-Windows emulation of waitpid calls QUIT
347 /* If successful and status is requested, tell wait_reading_process_output
348 that it needs to wake up and look around. */
349 if (pid
&& status
&& input_available_clear_time
)
350 *input_available_clear_time
= make_timespec (0, 0);
355 /* Wait for the subprocess with process id CHILD to terminate.
356 CHILD must be a child process that has not been reaped.
357 If STATUS is non-null, store the waitpid-style exit status into *STATUS
358 and tell wait_reading_process_output that it needs to look around.
359 If INTERRUPTIBLE, this function is interruptible by a signal. */
361 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
363 get_child_status (child
, status
, 0, interruptible
);
366 /* Report whether the subprocess with process id CHILD has changed status.
367 Termination counts as a change of status.
368 CHILD must be a child process that has not been reaped.
369 If STATUS is non-null, store the waitpid-style exit status into *STATUS
370 and tell wait_reading_process_output that it needs to look around.
371 Use waitpid-style OPTIONS to check status, but do not wait.
373 Return CHILD if successful, 0 if no status is available because
374 the process's state has not changed. */
376 child_status_changed (pid_t child
, int *status
, int options
)
378 return get_child_status (child
, status
, WNOHANG
| options
, 0);
382 /* Set up the terminal at the other end of a pseudo-terminal that
383 we will be controlling an inferior through.
384 It should not echo or do line-editing, since that is done
385 in Emacs. No padding needed for insertion into an Emacs buffer. */
388 child_setup_tty (int out
)
393 emacs_get_tty (out
, &s
);
394 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
395 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
397 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
398 Some versions of GNU Hurd do not have FFDLY? */
400 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
401 /* No output delays */
403 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
404 /* No output delays */
407 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
408 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
410 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
413 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
416 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
418 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
419 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
420 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
421 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
424 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
427 #ifdef SIGNALS_VIA_CHARACTERS
428 /* the QUIT and INTR character are used in process_send_signal
429 so set them here to something useful. */
430 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
431 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
432 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
433 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
434 #endif /* not SIGNALS_VIA_CHARACTERS */
437 /* Also, PTY overloads NUL and BREAK.
438 don't ignore break, but don't signal either, so it looks like NUL. */
439 s
.main
.c_iflag
&= ~IGNBRK
;
440 s
.main
.c_iflag
&= ~BRKINT
;
441 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
442 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
443 would force it to 0377. That looks like duplicated code. */
444 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
447 /* We originally enabled ICANON (and set VEOF to 04), and then had
448 process.c send additional EOF chars to flush the output when faced
449 with long lines, but this leads to weird effects when the
450 subprocess has disabled ICANON and ends up seeing those spurious
451 extra EOFs. So we don't send EOFs any more in
452 process.c:send_process. First we tried to disable ICANON by
453 default, so if a subsprocess sets up ICANON, it's his problem (or
454 the Elisp package that talks to it) to deal with lines that are
455 too long. But this disables some features, such as the ability
456 to send EOF signals. So we re-enabled ICANON but there is no
457 more "send eof to flush" going on (which is wrong and unportable
458 in itself). The correct way to handle too much output is to
459 buffer what could not be written and then write it again when
460 select returns ok for writing. This has it own set of
461 problems. Write is now asynchronous, is that a problem? How much
462 do we buffer, and what do we do when that limit is reached? */
464 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
465 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
466 #if 0 /* These settings only apply to non-ICANON mode. */
467 s
.main
.c_cc
[VMIN
] = 1;
468 s
.main
.c_cc
[VTIME
] = 0;
471 emacs_set_tty (out
, &s
, 0);
472 #endif /* not WINDOWSNT */
474 #endif /* not MSDOS */
477 /* Record a signal code and the action for it. */
481 struct sigaction action
;
484 static void save_signal_handlers (struct save_signal
*);
485 static void restore_signal_handlers (struct save_signal
*);
487 /* Suspend the Emacs process; give terminal to its superior. */
495 /* On a system where suspending is not implemented,
496 instead fork a subshell and let it talk directly to the terminal
503 /* Fork a subshell. */
508 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
511 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
513 char oldwd
[MAX_UTF8_PATH
];
519 struct save_signal saved_handlers
[5];
520 char *str
= SSDATA (encode_current_directory ());
526 char *volatile str_volatile
= str
;
533 error ("Can't spawn subshell");
535 saved_handlers
[0].code
= SIGINT
;
536 saved_handlers
[1].code
= SIGQUIT
;
537 saved_handlers
[2].code
= SIGTERM
;
539 saved_handlers
[3].code
= SIGIO
;
540 saved_handlers
[4].code
= 0;
542 saved_handlers
[3].code
= 0;
546 save_signal_handlers (saved_handlers
);
553 #ifdef DOS_NT /* MW, Aug 1993 */
554 getcwd (oldwd
, sizeof oldwd
);
556 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
559 sh
= egetenv ("SHELL");
563 /* Use our buffer's default directory for the subshell. */
564 if (chdir (str
) != 0)
568 _exit (EXIT_CANCELED
);
572 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
574 char *epwd
= getenv ("PWD");
575 char old_pwd
[MAXPATHLEN
+1+4];
577 /* If PWD is set, pass it with corrected value. */
580 strcpy (old_pwd
, epwd
);
581 setenv ("PWD", str
, 1);
584 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
586 putenv (old_pwd
); /* restore previous value */
588 #else /* not MSDOS */
590 /* Waits for process completion */
591 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
592 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
594 write (1, "Can't execute subshell", 22);
595 #else /* not WINDOWSNT */
596 execlp (sh
, sh
, (char *) 0);
598 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
599 #endif /* not WINDOWSNT */
600 #endif /* not MSDOS */
603 /* Do this now if we did not do it before. */
605 save_signal_handlers (saved_handlers
);
609 wait_for_termination (pid
, &status
, 0);
611 restore_signal_handlers (saved_handlers
);
615 save_signal_handlers (struct save_signal
*saved_handlers
)
617 while (saved_handlers
->code
)
619 struct sigaction action
;
620 emacs_sigaction_init (&action
, SIG_IGN
);
621 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
627 restore_signal_handlers (struct save_signal
*saved_handlers
)
629 while (saved_handlers
->code
)
631 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
637 static int old_fcntl_flags
[FD_SETSIZE
];
644 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
645 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
646 interrupts_deferred
= 0;
655 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
669 sigemptyset (&unblocked
);
671 sigaddset (&unblocked
, SIGWINCH
);
673 sigaddset (&unblocked
, SIGIO
);
674 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
676 interrupts_deferred
= 0;
681 unrequest_sigio (void)
689 sigemptyset (&blocked
);
691 sigaddset (&blocked
, SIGWINCH
);
693 sigaddset (&blocked
, SIGIO
);
694 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
695 interrupts_deferred
= 1;
703 block_child_signal (sigset_t
*oldset
)
706 sigemptyset (&blocked
);
707 sigaddset (&blocked
, SIGCHLD
);
708 sigaddset (&blocked
, SIGINT
);
709 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
712 /* Unblock SIGCHLD. */
715 unblock_child_signal (sigset_t
const *oldset
)
717 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
722 /* Saving and restoring the process group of Emacs's terminal. */
724 /* The process group of which Emacs was a member when it initially
727 If Emacs was in its own process group (i.e. inherited_pgroup ==
728 getpid ()), then we know we're running under a shell with job
729 control (Emacs would never be run as part of a pipeline).
732 If Emacs was not in its own process group, then we know we're
733 running under a shell (or a caller) that doesn't know how to
734 separate itself from Emacs (like sh). Emacs must be in its own
735 process group in order to receive SIGIO correctly. In this
736 situation, we put ourselves in our own pgroup, forcibly set the
737 tty's pgroup to our pgroup, and make sure to restore and reinstate
738 the tty's pgroup just like any other terminal setting. If
739 inherited_group was not the tty's pgroup, then we'll get a
740 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
741 it goes foreground in the future, which is what should happen. */
743 static pid_t inherited_pgroup
;
746 init_foreground_group (void)
748 pid_t pgrp
= getpgrp ();
749 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
752 /* Block and unblock SIGTTOU. */
755 block_tty_out_signal (sigset_t
*oldset
)
759 sigemptyset (&blocked
);
760 sigaddset (&blocked
, SIGTTOU
);
761 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
766 unblock_tty_out_signal (sigset_t
const *oldset
)
769 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
773 /* Safely set a controlling terminal FD's process group to PGID.
774 If we are not in the foreground already, POSIX requires tcsetpgrp
775 to deliver a SIGTTOU signal, which would stop us. This is an
776 annoyance, so temporarily ignore the signal.
778 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
779 skip all this unless SIGTTOU is defined. */
781 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
786 block_tty_out_signal (&oldset
);
787 tcsetpgrp (fd
, pgid
);
788 unblock_tty_out_signal (&oldset
);
793 /* Split off the foreground process group to Emacs alone. When we are
794 in the foreground, but not started in our own process group,
795 redirect the tty device handle FD to point to our own process
796 group. FD must be the file descriptor of the controlling tty. */
798 narrow_foreground_group (int fd
)
800 if (inherited_pgroup
&& setpgid (0, 0) == 0)
801 tcsetpgrp_without_stopping (fd
, getpid ());
804 /* Set the tty to our original foreground group. */
806 widen_foreground_group (int fd
)
808 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
809 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
812 /* Getting and setting emacs_tty structures. */
814 /* Set *TC to the parameters associated with the terminal FD,
815 or clear it if the parameters are not available.
816 Return 0 on success, -1 on failure. */
818 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
820 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
821 memset (&settings
->main
, 0, sizeof (settings
->main
));
824 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
827 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
829 settings
->main
= console_mode
;
832 #endif /* WINDOWSNT */
835 /* We have those nifty POSIX tcmumbleattr functions. */
836 return tcgetattr (fd
, &settings
->main
);
841 /* Set the parameters of the tty on FD according to the contents of
842 *SETTINGS. If FLUSHP, discard input.
843 Return 0 if all went well, and -1 (setting errno) if anything failed. */
846 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
848 /* Set the primary parameters - baud rate, character size, etcetera. */
851 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
853 if (h
&& h
!= INVALID_HANDLE_VALUE
)
857 /* Assume the handle is open for input. */
859 FlushConsoleInputBuffer (h
);
860 new_mode
= settings
->main
;
861 SetConsoleMode (h
, new_mode
);
863 #endif /* WINDOWSNT */
866 /* We have those nifty POSIX tcmumbleattr functions.
867 William J. Smith <wjs@wiis.wang.com> writes:
868 "POSIX 1003.1 defines tcsetattr to return success if it was
869 able to perform any of the requested actions, even if some
870 of the requested actions could not be performed.
871 We must read settings back to ensure tty setup properly.
872 AIX requires this to keep tty from hanging occasionally." */
873 /* This make sure that we don't loop indefinitely in here. */
874 for (i
= 0 ; i
< 10 ; i
++)
875 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
886 memset (&new, 0, sizeof (new));
887 /* Get the current settings, and see if they're what we asked for. */
888 tcgetattr (fd
, &new);
889 /* We cannot use memcmp on the whole structure here because under
890 * aix386 the termios structure has some reserved field that may
893 if ( new.c_iflag
== settings
->main
.c_iflag
894 && new.c_oflag
== settings
->main
.c_oflag
895 && new.c_cflag
== settings
->main
.c_cflag
896 && new.c_lflag
== settings
->main
.c_lflag
897 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
904 /* We have survived the tempest. */
911 static int old_fcntl_owner
[FD_SETSIZE
];
912 #endif /* F_SETOWN */
914 /* This may also be defined in stdio,
915 but if so, this does no harm,
916 and using the same name avoids wasting the other one's space. */
919 unsigned char _sobuf
[BUFSIZ
+8];
924 /* Initialize the terminal mode on all tty devices that are currently
928 init_all_sys_modes (void)
930 struct tty_display_info
*tty
;
931 for (tty
= tty_list
; tty
; tty
= tty
->next
)
932 init_sys_modes (tty
);
935 /* Initialize the terminal mode on the given tty device. */
938 init_sys_modes (struct tty_display_info
*tty_out
)
940 struct emacs_tty tty
;
942 Lisp_Object terminal
;
945 Vtty_erase_char
= Qnil
;
950 if (!tty_out
->output
)
951 return; /* The tty is suspended. */
953 narrow_foreground_group (fileno (tty_out
->input
));
955 if (! tty_out
->old_tty
)
956 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
958 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
960 tty
= *tty_out
->old_tty
;
962 #if !defined (DOS_NT)
963 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
965 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
966 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
967 #ifdef INLCR /* I'm just being cautious,
968 since I can't check how widespread INLCR is--rms. */
969 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
972 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
974 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
975 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
977 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
979 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
980 if (tty_out
->flow_control
)
982 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
984 tty
.main
.c_iflag
&= ~IXANY
;
988 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
989 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
991 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
993 if (tty_out
->meta_key
)
995 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
996 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1000 XSETTERMINAL(terminal
, tty_out
->terminal
);
1001 if (!NILP (Fcontrolling_tty_p (terminal
)))
1003 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1004 /* Set up C-g for both SIGQUIT and SIGINT.
1005 We don't know which we will get, but we handle both alike
1006 so which one it really gives us does not matter. */
1007 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1011 /* We normally don't get interrupt or quit signals from tty
1012 devices other than our controlling terminal; therefore,
1013 we must handle C-g as normal input. Unfortunately, this
1014 means that the interrupt and quit feature must be
1015 disabled on secondary ttys, or we would not even see the
1018 Note that even though emacsclient could have special code
1019 to pass SIGINT to Emacs, we should _not_ enable
1020 interrupt/quit keys for emacsclient frames. This means
1021 that we can't break out of loops in C code from a
1022 secondary tty frame, but we can always decide what
1023 display the C-g came from, which is more important from a
1024 usability point of view. (Consider the case when two
1025 people work together using the same Emacs instance.) */
1026 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1027 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1029 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1030 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1032 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1037 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1040 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1041 #endif /* V_DSUSP */
1042 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1043 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1046 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1049 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1050 #endif /* VREPRINT */
1052 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1053 #endif /* VWERASE */
1055 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1056 #endif /* VDISCARD */
1058 if (tty_out
->flow_control
)
1061 tty
.main
.c_cc
[VSTART
] = '\021';
1064 tty
.main
.c_cc
[VSTOP
] = '\023';
1070 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1073 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1078 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1079 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1080 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1081 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1082 if (tty_out
->flow_control
)
1085 tty
.main
.c_cc
[VSTART
] = '\021';
1088 tty
.main
.c_cc
[VSTOP
] = '\023';
1091 /* Also, PTY overloads NUL and BREAK.
1092 don't ignore break, but don't signal either, so it looks like NUL.
1093 This really serves a purpose only if running in an XTERM window
1094 or via TELNET or the like, but does no harm elsewhere. */
1095 tty
.main
.c_iflag
&= ~IGNBRK
;
1096 tty
.main
.c_iflag
&= ~BRKINT
;
1098 #endif /* not DOS_NT */
1100 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1101 if (!tty_out
->term_initted
)
1102 internal_terminal_init ();
1103 dos_ttraw (tty_out
);
1106 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1108 /* This code added to insure that, if flow-control is not to be used,
1109 we have an unlocked terminal at the start. */
1112 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1115 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1118 #if !defined (DOS_NT)
1120 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1125 if (interrupt_input
)
1127 old_fcntl_owner
[fileno (tty_out
->input
)] =
1128 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1129 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1130 init_sigio (fileno (tty_out
->input
));
1132 if (gpm_tty
== tty_out
)
1134 /* Arrange for mouse events to give us SIGIO signals. */
1135 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1136 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1137 init_sigio (gpm_fd
);
1139 #endif /* HAVE_GPM */
1141 #endif /* F_GETOWN */
1144 /* This symbol is defined on recent USG systems.
1145 Someone says without this call USG won't really buffer the file
1146 even with a call to setbuf. */
1147 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1149 setbuf (tty_out
->output
, (char *) _sobuf
);
1152 if (tty_out
->terminal
->set_terminal_modes_hook
)
1153 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1155 if (!tty_out
->term_initted
)
1157 Lisp_Object tail
, frame
;
1158 FOR_EACH_FRAME (tail
, frame
)
1160 /* XXX This needs to be revised. */
1161 if (FRAME_TERMCAP_P (XFRAME (frame
))
1162 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1163 init_frame_faces (XFRAME (frame
));
1167 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1169 /* We used to call "direct_output_forward_char(0)" here,
1170 but it's not clear why, since it may not do anything anyway. */
1174 Lisp_Object tail
, frame
;
1176 FOR_EACH_FRAME (tail
, frame
)
1178 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1179 || FRAME_MSDOS_P (XFRAME (frame
)))
1180 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1181 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1185 tty_out
->term_initted
= 1;
1188 /* Return true if safe to use tabs in output.
1189 At the time this is called, init_sys_modes has not been done yet. */
1192 tabs_safe_p (int fd
)
1194 struct emacs_tty etty
;
1196 emacs_get_tty (fd
, &etty
);
1199 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1200 #else /* not TABDLY */
1202 #endif /* not TABDLY */
1208 /* Discard echoing. */
1211 suppress_echo_on_tty (int fd
)
1213 struct emacs_tty etty
;
1215 emacs_get_tty (fd
, &etty
);
1217 /* Set raw input mode. */
1220 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1221 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1222 #endif /* ! WINDOWSNT */
1223 emacs_set_tty (fd
, &etty
, 0);
1226 /* Get terminal size from system.
1227 Store number of lines into *HEIGHTP and width into *WIDTHP.
1228 We store 0 if there's no valid information. */
1231 get_tty_size (int fd
, int *widthp
, int *heightp
)
1233 #if defined TIOCGWINSZ
1236 struct winsize size
;
1238 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1239 *widthp
= *heightp
= 0;
1242 *widthp
= size
.ws_col
;
1243 *heightp
= size
.ws_row
;
1246 #elif defined TIOCGSIZE
1248 /* SunOS - style. */
1249 struct ttysize size
;
1251 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1252 *widthp
= *heightp
= 0;
1255 *widthp
= size
.ts_cols
;
1256 *heightp
= size
.ts_lines
;
1259 #elif defined WINDOWSNT
1261 CONSOLE_SCREEN_BUFFER_INFO info
;
1262 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1264 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1265 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1268 *widthp
= *heightp
= 0;
1272 *widthp
= ScreenCols ();
1273 *heightp
= ScreenRows ();
1275 #else /* system doesn't know size */
1283 /* Set the logical window size associated with descriptor FD
1284 to HEIGHT and WIDTH. This is used mainly with ptys.
1285 Return a negative value on failure. */
1288 set_window_size (int fd
, int height
, int width
)
1293 struct winsize size
;
1294 size
.ws_row
= height
;
1295 size
.ws_col
= width
;
1297 return ioctl (fd
, TIOCSWINSZ
, &size
);
1302 /* SunOS - style. */
1303 struct ttysize size
;
1304 size
.ts_lines
= height
;
1305 size
.ts_cols
= width
;
1307 return ioctl (fd
, TIOCGSIZE
, &size
);
1310 #endif /* not SunOS-style */
1311 #endif /* not BSD-style */
1316 /* Prepare all terminal devices for exiting Emacs. */
1319 reset_all_sys_modes (void)
1321 struct tty_display_info
*tty
;
1322 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1323 reset_sys_modes (tty
);
1326 /* Prepare the terminal for closing it; move the cursor to the
1327 bottom of the frame, turn off interrupt-driven I/O, etc. */
1330 reset_sys_modes (struct tty_display_info
*tty_out
)
1337 if (!tty_out
->term_initted
)
1340 if (!tty_out
->output
)
1341 return; /* The tty is suspended. */
1343 /* Go to and clear the last line of the terminal. */
1345 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1347 /* Code adapted from tty_clear_end_of_line. */
1348 if (tty_out
->TS_clr_line
)
1350 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1353 { /* have to do it the hard way */
1355 tty_turn_off_insert (tty_out
);
1357 for (i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1359 fputc (' ', tty_out
->output
);
1363 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1364 fflush (tty_out
->output
);
1366 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1367 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1369 /* Avoid possible loss of output when changing terminal modes. */
1370 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1375 if (interrupt_input
)
1377 reset_sigio (fileno (tty_out
->input
));
1378 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1379 old_fcntl_owner
[fileno (tty_out
->input
)]);
1381 #endif /* F_SETOWN */
1382 fcntl (fileno (tty_out
->input
), F_SETFL
,
1383 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1386 if (tty_out
->old_tty
)
1387 while (emacs_set_tty (fileno (tty_out
->input
),
1388 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1391 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1395 widen_foreground_group (fileno (tty_out
->input
));
1400 /* Set up the proper status flags for use of a pty. */
1405 /* I'm told that TOICREMOTE does not mean control chars
1406 "can't be sent" but rather that they don't have
1407 input-editing or signaling effects.
1408 That should be good, because we have other ways
1409 to do those things in Emacs.
1410 However, telnet mode seems not to work on 4.2.
1411 So TIOCREMOTE is turned off now. */
1413 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1414 will hang. In particular, the "timeout" feature (which
1415 causes a read to return if there is no data available)
1416 does this. Also it is known that telnet mode will hang
1417 in such a way that Emacs must be stopped (perhaps this
1418 is the same problem).
1420 If TIOCREMOTE is turned off, then there is a bug in
1421 hp-ux which sometimes loses data. Apparently the
1422 code which blocks the master process when the internal
1423 buffer fills up does not work. Other than this,
1424 though, everything else seems to work fine.
1426 Since the latter lossage is more benign, we may as well
1427 lose that way. -- cph */
1429 #if defined (UNIX98_PTYS)
1432 ioctl (fd
, FIONBIO
, &on
);
1437 #endif /* HAVE_PTYS */
1440 init_system_name (void)
1444 /* Set system-name to nil so that the build is deterministic. */
1445 Vsystem_name
= Qnil
;
1448 char *hostname_alloc
= NULL
;
1450 #ifndef HAVE_GETHOSTNAME
1453 hostname
= uts
.nodename
;
1454 #else /* HAVE_GETHOSTNAME */
1455 char hostname_buf
[256];
1456 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1457 hostname
= hostname_buf
;
1459 /* Try to get the host name; if the buffer is too short, try
1460 again. Apparently, the only indication gethostname gives of
1461 whether the buffer was large enough is the presence or absence
1462 of a '\0' in the string. Eech. */
1465 gethostname (hostname
, hostname_size
- 1);
1466 hostname
[hostname_size
- 1] = '\0';
1468 /* Was the buffer large enough for the '\0'? */
1469 if (strlen (hostname
) < hostname_size
- 1)
1472 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1473 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1475 #endif /* HAVE_GETHOSTNAME */
1477 for (p
= hostname
; *p
; p
++)
1478 if (*p
== ' ' || *p
== '\t')
1480 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1481 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1482 Vsystem_name
= build_string (hostname
);
1483 xfree (hostname_alloc
);
1486 sigset_t empty_mask
;
1488 static struct sigaction process_fatal_action
;
1491 emacs_sigaction_flags (void)
1494 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1495 'select') to reset their timeout on some platforms (e.g.,
1496 HP-UX 11), which is not what we want. Also, when Emacs is
1497 interactive, we don't want SA_RESTART because we need to poll
1498 for pending input so we need long-running syscalls to be interrupted
1499 after a signal that sets pending_signals.
1501 Non-interactive keyboard input goes through stdio, where we
1502 always want restartable system calls. */
1509 /* Store into *ACTION a signal action suitable for Emacs, with handler
1512 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1514 sigemptyset (&action
->sa_mask
);
1516 /* When handling a signal, block nonfatal system signals that are caught
1517 by Emacs. This makes race conditions less likely. */
1518 sigaddset (&action
->sa_mask
, SIGALRM
);
1520 sigaddset (&action
->sa_mask
, SIGCHLD
);
1523 sigaddset (&action
->sa_mask
, SIGDANGER
);
1525 #ifdef PROFILER_CPU_SUPPORT
1526 sigaddset (&action
->sa_mask
, SIGPROF
);
1529 sigaddset (&action
->sa_mask
, SIGWINCH
);
1531 if (! noninteractive
)
1533 sigaddset (&action
->sa_mask
, SIGINT
);
1534 sigaddset (&action
->sa_mask
, SIGQUIT
);
1536 sigaddset (&action
->sa_mask
, SIGIO
);
1540 action
->sa_handler
= handler
;
1541 action
->sa_flags
= emacs_sigaction_flags ();
1544 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1545 static pthread_t main_thread
;
1548 /* SIG has arrived at the current process. Deliver it to the main
1549 thread, which should handle it with HANDLER.
1551 If we are on the main thread, handle the signal SIG with HANDLER.
1552 Otherwise, redirect the signal to the main thread, blocking it from
1553 this thread. POSIX says any thread can receive a signal that is
1554 associated with a process, process group, or asynchronous event.
1555 On GNU/Linux that is not true, but for other systems (FreeBSD at
1558 deliver_process_signal (int sig
, signal_handler_t handler
)
1560 /* Preserve errno, to avoid race conditions with signal handlers that
1561 might change errno. Races can occur even in single-threaded hosts. */
1562 int old_errno
= errno
;
1564 bool on_main_thread
= true;
1565 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1566 if (! pthread_equal (pthread_self (), main_thread
))
1569 sigemptyset (&blocked
);
1570 sigaddset (&blocked
, sig
);
1571 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1572 pthread_kill (main_thread
, sig
);
1573 on_main_thread
= false;
1582 /* Static location to save a fatal backtrace in a thread.
1583 FIXME: If two subsidiary threads fail simultaneously, the resulting
1584 backtrace may be garbage. */
1585 enum { BACKTRACE_LIMIT_MAX
= 500 };
1586 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1587 static int thread_backtrace_npointers
;
1589 /* SIG has arrived at the current thread.
1590 If we are on the main thread, handle the signal SIG with HANDLER.
1591 Otherwise, this is a fatal error in the handling thread. */
1593 deliver_thread_signal (int sig
, signal_handler_t handler
)
1595 int old_errno
= errno
;
1597 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1598 if (! pthread_equal (pthread_self (), main_thread
))
1600 thread_backtrace_npointers
1601 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1602 sigaction (sig
, &process_fatal_action
, 0);
1603 pthread_kill (main_thread
, sig
);
1605 /* Avoid further damage while the main thread is exiting. */
1607 sigsuspend (&empty_mask
);
1615 #if !HAVE_DECL_SYS_SIGLIST
1617 # ifdef _sys_siglist
1618 # define sys_siglist _sys_siglist
1619 # elif HAVE_DECL___SYS_SIGLIST
1620 # define sys_siglist __sys_siglist
1622 # define sys_siglist my_sys_siglist
1623 static char const *sys_siglist
[NSIG
];
1628 # define sys_siglist_entries _sys_nsig
1630 # define sys_siglist_entries NSIG
1633 /* Handle bus errors, invalid instruction, etc. */
1635 handle_fatal_signal (int sig
)
1637 terminate_due_to_signal (sig
, 40);
1641 deliver_fatal_signal (int sig
)
1643 deliver_process_signal (sig
, handle_fatal_signal
);
1647 deliver_fatal_thread_signal (int sig
)
1649 deliver_thread_signal (sig
, handle_fatal_signal
);
1652 static _Noreturn
void
1653 handle_arith_signal (int sig
)
1655 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1656 xsignal0 (Qarith_error
);
1659 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1661 /* Alternate stack used by SIGSEGV handler below. */
1663 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1666 /* Return true if SIGINFO indicates a stack overflow. */
1669 stack_overflow (siginfo_t
*siginfo
)
1671 if (!attempt_stack_overflow_recovery
)
1674 /* In theory, a more-accurate heuristic can be obtained by using
1675 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1676 and pthread_attr_getguardsize to find the location and size of the
1677 guard area. In practice, though, these functions are so hard to
1678 use reliably that they're not worth bothering with. E.g., see:
1679 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1680 Other operating systems also have problems, e.g., Solaris's
1681 stack_violation function is tailor-made for this problem, but it
1682 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1684 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1690 /* The faulting address. */
1691 char *addr
= siginfo
->si_addr
;
1695 /* The known top and bottom of the stack. The actual stack may
1696 extend a bit beyond these boundaries. */
1697 char *bot
= stack_bottom
;
1698 char *top
= near_C_stack_top ();
1700 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1701 of the known stack divided by the size of the guard area past the
1702 end of the stack top. The heuristic is that a bad address is
1703 considered to be a stack overflow if it occurs within
1704 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1705 stack. This heuristic is not exactly correct but it's good
1706 enough in practice. */
1707 enum { LG_STACK_HEURISTIC
= 8 };
1710 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1712 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1716 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1719 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1721 /* Hard GC error may lead to stack overflow caused by
1722 too nested calls to mark_object. No way to survive. */
1723 bool fatal
= gc_in_progress
;
1725 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1726 if (!fatal
&& !pthread_equal (pthread_self (), main_thread
))
1730 if (!fatal
&& stack_overflow (siginfo
))
1731 siglongjmp (return_to_command_loop
, 1);
1733 /* Otherwise we can't do anything with this. */
1734 deliver_fatal_thread_signal (sig
);
1737 /* Return true if we have successfully set up SIGSEGV handler on alternate
1738 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1743 struct sigaction sa
;
1746 ss
.ss_sp
= sigsegv_stack
;
1747 ss
.ss_size
= sizeof (sigsegv_stack
);
1749 if (sigaltstack (&ss
, NULL
) < 0)
1752 sigfillset (&sa
.sa_mask
);
1753 sa
.sa_sigaction
= handle_sigsegv
;
1754 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1755 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1758 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1766 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1769 deliver_arith_signal (int sig
)
1771 deliver_thread_signal (sig
, handle_arith_signal
);
1776 /* Handler for SIGDANGER. */
1778 handle_danger_signal (int sig
)
1780 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1782 /* It might be unsafe to call do_auto_save now. */
1783 force_auto_save_soon ();
1787 deliver_danger_signal (int sig
)
1789 deliver_process_signal (sig
, handle_danger_signal
);
1793 /* Treat SIG as a terminating signal, unless it is already ignored and
1794 we are in --batch mode. Among other things, this makes nohup work. */
1796 maybe_fatal_sig (int sig
)
1798 bool catch_sig
= !noninteractive
;
1801 struct sigaction old_action
;
1802 sigaction (sig
, 0, &old_action
);
1803 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1806 sigaction (sig
, &process_fatal_action
, 0);
1810 init_signals (bool dumping
)
1812 struct sigaction thread_fatal_action
;
1813 struct sigaction action
;
1815 sigemptyset (&empty_mask
);
1817 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1818 main_thread
= pthread_self ();
1821 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1824 sys_siglist
[SIGABRT
] = "Aborted";
1826 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1828 sys_siglist
[SIGALRM
] = "Alarm clock";
1830 sys_siglist
[SIGBUS
] = "Bus error";
1833 sys_siglist
[SIGCHLD
] = "Child status changed";
1836 sys_siglist
[SIGCONT
] = "Continued";
1839 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1842 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1845 sys_siglist
[SIGEMT
] = "Emulation trap";
1847 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1849 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1852 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1854 sys_siglist
[SIGHUP
] = "Hangup";
1855 sys_siglist
[SIGILL
] = "Illegal instruction";
1856 sys_siglist
[SIGINT
] = "Interrupt";
1858 sys_siglist
[SIGIO
] = "I/O possible";
1861 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1864 sys_siglist
[SIGIOT
] = "IOT trap";
1866 sys_siglist
[SIGKILL
] = "Killed";
1868 sys_siglist
[SIGLOST
] = "Resource lost";
1871 sys_siglist
[SIGLWP
] = "SIGLWP";
1874 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1877 sys_siglist
[SIGWIND
] = "SIGPHONE";
1879 sys_siglist
[SIGPIPE
] = "Broken pipe";
1881 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1884 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1887 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1890 sys_siglist
[SIGPWR
] = "Power-fail restart";
1892 sys_siglist
[SIGQUIT
] = "Quit";
1894 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1897 sys_siglist
[SIGSAK
] = "Secure attention";
1899 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1901 sys_siglist
[SIGSOUND
] = "Sound completed";
1904 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1907 sys_siglist
[SIGSTP
] = "Stopped (user)";
1910 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1912 sys_siglist
[SIGTERM
] = "Terminated";
1914 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1917 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1920 sys_siglist
[SIGTSTP
] = "Stopped (user)";
1923 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
1926 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
1929 sys_siglist
[SIGURG
] = "Urgent I/O condition";
1932 sys_siglist
[SIGUSR1
] = "User defined signal 1";
1935 sys_siglist
[SIGUSR2
] = "User defined signal 2";
1938 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
1941 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
1944 sys_siglist
[SIGWINCH
] = "Window size changed";
1947 sys_siglist
[SIGWIND
] = "SIGWIND";
1950 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
1953 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
1956 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
1958 /* Don't alter signal handlers if dumping. On some machines,
1959 changing signal handlers sets static data that would make signals
1960 fail to work right when the dumped Emacs is run. */
1964 sigfillset (&process_fatal_action
.sa_mask
);
1965 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
1966 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
1968 sigfillset (&thread_fatal_action
.sa_mask
);
1969 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
1970 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
1972 /* SIGINT may need special treatment on MS-Windows. See
1973 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
1974 Please update the doc of kill-emacs, kill-emacs-hook, and
1975 NEWS if you change this. */
1977 maybe_fatal_sig (SIGHUP
);
1978 maybe_fatal_sig (SIGINT
);
1979 maybe_fatal_sig (SIGTERM
);
1981 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
1982 However, in batch mode leave SIGPIPE alone, as that causes Emacs
1983 to behave more like typical batch applications do. */
1984 if (! noninteractive
)
1985 signal (SIGPIPE
, SIG_IGN
);
1987 sigaction (SIGQUIT
, &process_fatal_action
, 0);
1988 sigaction (SIGILL
, &thread_fatal_action
, 0);
1989 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
1991 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
1992 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
1993 interpreter's floating point operations, so treat SIGFPE as an
1994 arith-error if it arises in the main thread. */
1995 if (IEEE_FLOATING_POINT
)
1996 sigaction (SIGFPE
, &thread_fatal_action
, 0);
1999 emacs_sigaction_init (&action
, deliver_arith_signal
);
2000 sigaction (SIGFPE
, &action
, 0);
2004 add_user_signal (SIGUSR1
, "sigusr1");
2007 add_user_signal (SIGUSR2
, "sigusr2");
2009 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2011 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2014 sigaction (SIGORE
, &thread_fatal_action
, 0);
2017 sigaction (SIGUME
, &thread_fatal_action
, 0);
2020 sigaction (SIGDLK
, &process_fatal_action
, 0);
2023 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2026 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2029 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2032 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2034 if (!init_sigsegv ())
2035 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2037 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2039 sigaction (SIGTERM
, &process_fatal_action
, 0);
2041 signal (SIGPROF
, SIG_IGN
);
2044 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2047 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2050 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2054 /* This just means available memory is getting low. */
2055 emacs_sigaction_init (&action
, deliver_danger_signal
);
2056 sigaction (SIGDANGER
, &action
, 0);
2059 /* AIX-specific signals. */
2061 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2064 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2067 sigaction (SIGMSG
, &process_fatal_action
, 0);
2070 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2073 sigaction (SIGSAK
, &process_fatal_action
, 0);
2076 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2079 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2089 /* Figure out how many bits the system's random number generator uses.
2090 `random' and `lrand48' are assumed to return 31 usable bits.
2091 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2092 so we'll shift it and treat it like the 15-bit USG `rand'. */
2096 # define RAND_BITS 31
2097 # else /* !HAVE_RANDOM */
2098 # ifdef HAVE_LRAND48
2099 # define RAND_BITS 31
2100 # define random lrand48
2101 # else /* !HAVE_LRAND48 */
2102 # define RAND_BITS 15
2103 # if RAND_MAX == 32767
2104 # define random rand
2105 # else /* RAND_MAX != 32767 */
2106 # if RAND_MAX == 2147483647
2107 # define random() (rand () >> 16)
2108 # else /* RAND_MAX != 2147483647 */
2110 # define random rand
2112 # define random() (rand () >> 16)
2114 # endif /* RAND_MAX != 2147483647 */
2115 # endif /* RAND_MAX != 32767 */
2116 # endif /* !HAVE_LRAND48 */
2117 # endif /* !HAVE_RANDOM */
2118 #endif /* !RAND_BITS */
2121 typedef unsigned int random_seed
;
2122 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2123 #elif defined HAVE_LRAND48
2124 /* Although srand48 uses a long seed, this is unsigned long to avoid
2125 undefined behavior on signed integer overflow in init_random. */
2126 typedef unsigned long int random_seed
;
2127 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2129 typedef unsigned int random_seed
;
2130 static void set_random_seed (random_seed arg
) { srand (arg
); }
2134 seed_random (void *seed
, ptrdiff_t seed_size
)
2136 random_seed arg
= 0;
2137 unsigned char *argp
= (unsigned char *) &arg
;
2138 unsigned char *seedp
= seed
;
2139 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2140 argp
[i
% sizeof arg
] ^= seedp
[i
];
2141 set_random_seed (arg
);
2148 if (! (EQ (emacs_gnutls_global_init (), Qt
)
2149 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0))
2151 bool success
= false;
2153 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2156 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2160 success
= w32_init_random (&v
, sizeof v
) == 0;
2164 /* Fall back to current time value + PID. */
2165 struct timespec t
= current_timespec ();
2166 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2169 set_random_seed (v
);
2173 * Return a nonnegative random integer out of whatever we've got.
2174 * It contains enough bits to make a random (signed) Emacs fixnum.
2175 * This suffices even for a 64-bit architecture with a 15-bit rand.
2182 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2183 val
= (random () ^ (val
<< RAND_BITS
)
2184 ^ (val
>> (BITS_PER_EMACS_INT
- RAND_BITS
)));
2185 val
^= val
>> (BITS_PER_EMACS_INT
- FIXNUM_BITS
);
2186 return val
& INTMASK
;
2189 #ifndef HAVE_SNPRINTF
2190 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2192 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2194 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2195 ptrdiff_t nbytes
= size
- 1;
2200 va_start (ap
, format
);
2201 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2205 if (nbytes
== size
- 1)
2207 /* Calculate the length of the string that would have been created
2208 had the buffer been large enough. */
2209 char stackbuf
[4000];
2211 ptrdiff_t bsize
= sizeof stackbuf
;
2212 va_start (ap
, format
);
2213 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2219 if (INT_MAX
< nbytes
)
2232 /* If a backtrace is available, output the top lines of it to stderr.
2233 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2234 This function may be called from a signal handler, so it should
2235 not invoke async-unsafe functions like malloc.
2237 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2238 but do not output anything. This avoids some problems that can
2239 otherwise occur if the malloc arena is corrupted before 'backtrace'
2240 is called, since 'backtrace' may call malloc if the tables are not
2243 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2244 fatal error has occurred in some other thread; generate a thread
2245 backtrace instead, ignoring BACKTRACE_LIMIT. */
2247 emacs_backtrace (int backtrace_limit
)
2249 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2250 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2254 if (thread_backtrace_npointers
)
2256 buffer
= thread_backtrace_buffer
;
2257 npointers
= thread_backtrace_npointers
;
2261 buffer
= main_backtrace_buffer
;
2263 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2264 if (bounded_limit
< 0)
2266 backtrace (buffer
, 1);
2270 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2275 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2276 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2277 if (bounded_limit
< npointers
)
2278 emacs_write (STDERR_FILENO
, "...\n", 4);
2286 terminate_due_to_signal (SIGABRT
, 40);
2290 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2291 Use binary I/O on systems that care about text vs binary I/O.
2292 Arrange for subprograms to not inherit the file descriptor.
2293 Prefer a method that is multithread-safe, if available.
2294 Do not fail merely because the open was interrupted by a signal.
2295 Allow the user to quit. */
2298 emacs_open (const char *file
, int oflags
, int mode
)
2301 if (! (oflags
& O_TEXT
))
2303 oflags
|= O_CLOEXEC
;
2304 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2306 if (! O_CLOEXEC
&& 0 <= fd
)
2307 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2311 /* Open FILE as a stream for Emacs use, with mode MODE.
2312 Act like emacs_open with respect to threads, signals, and quits. */
2315 emacs_fopen (char const *file
, char const *mode
)
2317 int fd
, omode
, oflags
;
2319 char const *m
= mode
;
2323 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2324 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2325 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2326 default: emacs_abort ();
2332 case '+': omode
= O_RDWR
; break;
2333 case 't': bflag
= O_TEXT
; break;
2334 default: /* Ignore. */ break;
2337 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2338 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2341 /* Create a pipe for Emacs use. */
2344 emacs_pipe (int fd
[2])
2349 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2350 if (! O_CLOEXEC
&& result
== 0)
2352 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2353 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2359 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2360 For the background behind this mess, please see Austin Group defect 529
2361 <http://austingroupbugs.net/view.php?id=529>. */
2363 #ifndef POSIX_CLOSE_RESTART
2364 # define POSIX_CLOSE_RESTART 1
2366 posix_close (int fd
, int flag
)
2368 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2369 eassert (flag
== POSIX_CLOSE_RESTART
);
2371 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2372 on a system that does not define POSIX_CLOSE_RESTART.
2374 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2375 closed, and retrying the close could inadvertently close a file
2376 descriptor allocated by some other thread. In other systems
2377 (e.g., HP/UX) FD is not closed. And in still other systems
2378 (e.g., OS X, Solaris), maybe FD is closed, maybe not, and in a
2379 multithreaded program there can be no way to tell.
2381 So, in this case, pretend that the close succeeded. This works
2382 well on systems like GNU/Linux that close FD. Although it may
2383 leak a file descriptor on other systems, the leak is unlikely and
2384 it's better to leak than to close a random victim. */
2385 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2389 /* Close FD, retrying if interrupted. If successful, return 0;
2390 otherwise, return -1 and set errno to a non-EINTR value. Consider
2391 an EINPROGRESS error to be successful, as that's merely a signal
2392 arriving. FD is always closed when this function returns, even
2395 Do not call this function if FD is nonnegative and might already be closed,
2396 as that might close an innocent victim opened by some other thread. */
2399 emacs_close (int fd
)
2403 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2406 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2408 eassert (errno
!= EBADF
|| fd
< 0);
2409 return errno
== EINPROGRESS
? 0 : r
;
2414 /* Maximum number of bytes to read or write in a single system call.
2415 This works around a serious bug in Linux kernels before 2.6.16; see
2416 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2417 It's likely to work around similar bugs in other operating systems, so do it
2418 on all platforms. Round INT_MAX down to a page size, with the conservative
2419 assumption that page sizes are at most 2**18 bytes (any kernel with a
2420 page size larger than that shouldn't have the bug). */
2421 #ifndef MAX_RW_COUNT
2422 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2425 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2426 Return the number of bytes read, which might be less than NBYTE.
2427 On error, set errno and return -1. */
2429 emacs_read (int fildes
, void *buf
, ptrdiff_t nbyte
)
2433 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2434 passes a size that large to emacs_read. */
2436 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
2437 && (errno
== EINTR
))
2442 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2443 or if a partial write occurs. If interrupted, process pending
2444 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2445 errno if this is less than NBYTE. */
2447 emacs_full_write (int fildes
, char const *buf
, ptrdiff_t nbyte
,
2448 bool process_signals
)
2450 ptrdiff_t bytes_written
= 0;
2454 ssize_t n
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
2460 /* I originally used `QUIT' but that might cause files to
2461 be truncated if you hit C-g in the middle of it. --Stef */
2462 if (process_signals
&& pending_signals
)
2463 process_pending_signals ();
2475 return bytes_written
;
2478 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2479 interrupted or if a partial write occurs. Return the number of
2480 bytes written, setting errno if this is less than NBYTE. */
2482 emacs_write (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2484 return emacs_full_write (fildes
, buf
, nbyte
, 0);
2487 /* Like emacs_write, but also process pending signals if interrupted. */
2489 emacs_write_sig (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2491 return emacs_full_write (fildes
, buf
, nbyte
, 1);
2494 /* Write a diagnostic to standard error that contains MESSAGE and a
2495 string derived from errno. Preserve errno. Do not buffer stderr.
2496 Do not process pending signals if interrupted. */
2498 emacs_perror (char const *message
)
2501 char const *error_string
= emacs_strerror (err
);
2502 char const *command
= (initial_argv
&& initial_argv
[0]
2503 ? initial_argv
[0] : "emacs");
2504 /* Write it out all at once, if it's short; this is less likely to
2505 be interleaved with other output. */
2507 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2508 command
, message
, error_string
);
2509 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2510 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2513 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2514 emacs_write (STDERR_FILENO
, ": ", 2);
2515 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2516 emacs_write (STDERR_FILENO
, ": ", 2);
2517 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2518 emacs_write (STDERR_FILENO
, "\n", 1);
2523 /* Return a struct timeval that is roughly equivalent to T.
2524 Use the least timeval not less than T.
2525 Return an extremal value if the result would overflow. */
2527 make_timeval (struct timespec t
)
2530 tv
.tv_sec
= t
.tv_sec
;
2531 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2533 if (t
.tv_nsec
% 1000 != 0)
2535 if (tv
.tv_usec
< 999999)
2537 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2547 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2548 ATIME and MTIME, respectively.
2549 FD must be either negative -- in which case it is ignored --
2550 or a file descriptor that is open on FILE.
2551 If FD is nonnegative, then FILE can be NULL. */
2553 set_file_times (int fd
, const char *filename
,
2554 struct timespec atime
, struct timespec mtime
)
2556 struct timespec timespec
[2];
2557 timespec
[0] = atime
;
2558 timespec
[1] = mtime
;
2559 return fdutimens (fd
, filename
, timespec
);
2562 /* Like strsignal, except async-signal-safe, and this function typically
2563 returns a string in the C locale rather than the current locale. */
2565 safe_strsignal (int code
)
2567 char const *signame
= 0;
2569 if (0 <= code
&& code
< sys_siglist_entries
)
2570 signame
= sys_siglist
[code
];
2572 signame
= "Unknown signal";
2578 /* For make-serial-process */
2580 serial_open (Lisp_Object port
)
2582 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2584 report_file_error ("Opening serial port", port
);
2586 ioctl (fd
, TIOCEXCL
, (char *) 0);
2592 #if !defined (HAVE_CFMAKERAW)
2593 /* Workaround for targets which are missing cfmakeraw. */
2594 /* Pasted from man page. */
2596 cfmakeraw (struct termios
*termios_p
)
2598 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2599 termios_p
->c_oflag
&= ~OPOST
;
2600 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2601 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2602 termios_p
->c_cflag
|= CS8
;
2604 #endif /* !defined (HAVE_CFMAKERAW */
2606 #if !defined (HAVE_CFSETSPEED)
2607 /* Workaround for targets which are missing cfsetspeed. */
2609 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2611 return (cfsetispeed (termios_p
, vitesse
)
2612 + cfsetospeed (termios_p
, vitesse
));
2616 /* For serial-process-configure */
2618 serial_configure (struct Lisp_Process
*p
,
2619 Lisp_Object contact
)
2621 Lisp_Object childp2
= Qnil
;
2622 Lisp_Object tem
= Qnil
;
2623 struct termios attr
;
2625 char summary
[4] = "???"; /* This usually becomes "8N1". */
2627 childp2
= Fcopy_sequence (p
->childp
);
2629 /* Read port attributes and prepare default configuration. */
2630 err
= tcgetattr (p
->outfd
, &attr
);
2632 report_file_error ("Failed tcgetattr", Qnil
);
2634 #if defined (CLOCAL)
2635 attr
.c_cflag
|= CLOCAL
;
2638 attr
.c_cflag
|= CREAD
;
2641 /* Configure speed. */
2642 if (!NILP (Fplist_member (contact
, QCspeed
)))
2643 tem
= Fplist_get (contact
, QCspeed
);
2645 tem
= Fplist_get (p
->childp
, QCspeed
);
2647 err
= cfsetspeed (&attr
, XINT (tem
));
2649 report_file_error ("Failed cfsetspeed", tem
);
2650 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2652 /* Configure bytesize. */
2653 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2654 tem
= Fplist_get (contact
, QCbytesize
);
2656 tem
= Fplist_get (p
->childp
, QCbytesize
);
2658 tem
= make_number (8);
2660 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2661 error (":bytesize must be nil (8), 7, or 8");
2662 summary
[0] = XINT (tem
) + '0';
2663 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2664 attr
.c_cflag
&= ~CSIZE
;
2665 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2667 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2668 if (XINT (tem
) != 8)
2669 error ("Bytesize cannot be changed");
2671 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2673 /* Configure parity. */
2674 if (!NILP (Fplist_member (contact
, QCparity
)))
2675 tem
= Fplist_get (contact
, QCparity
);
2677 tem
= Fplist_get (p
->childp
, QCparity
);
2678 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2679 error (":parity must be nil (no parity), `even', or `odd'");
2680 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2681 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2682 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2687 else if (EQ (tem
, Qeven
))
2690 attr
.c_cflag
|= PARENB
;
2691 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2693 else if (EQ (tem
, Qodd
))
2696 attr
.c_cflag
|= (PARENB
| PARODD
);
2697 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2700 /* Don't error on no parity, which should be set by cfmakeraw. */
2702 error ("Parity cannot be configured");
2704 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2706 /* Configure stopbits. */
2707 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2708 tem
= Fplist_get (contact
, QCstopbits
);
2710 tem
= Fplist_get (p
->childp
, QCstopbits
);
2712 tem
= make_number (1);
2714 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2715 error (":stopbits must be nil (1 stopbit), 1, or 2");
2716 summary
[2] = XINT (tem
) + '0';
2717 #if defined (CSTOPB)
2718 attr
.c_cflag
&= ~CSTOPB
;
2719 if (XINT (tem
) == 2)
2720 attr
.c_cflag
|= CSTOPB
;
2722 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2723 if (XINT (tem
) != 1)
2724 error ("Stopbits cannot be configured");
2726 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2728 /* Configure flowcontrol. */
2729 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2730 tem
= Fplist_get (contact
, QCflowcontrol
);
2732 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2733 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2734 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2735 #if defined (CRTSCTS)
2736 attr
.c_cflag
&= ~CRTSCTS
;
2738 #if defined (CNEW_RTSCTS)
2739 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2741 #if defined (IXON) && defined (IXOFF)
2742 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2746 /* Already configured. */
2748 else if (EQ (tem
, Qhw
))
2750 #if defined (CRTSCTS)
2751 attr
.c_cflag
|= CRTSCTS
;
2752 #elif defined (CNEW_RTSCTS)
2753 attr
.c_cflag
|= CNEW_RTSCTS
;
2755 error ("Hardware flowcontrol (RTS/CTS) not supported");
2758 else if (EQ (tem
, Qsw
))
2760 #if defined (IXON) && defined (IXOFF)
2761 attr
.c_iflag
|= (IXON
| IXOFF
);
2763 error ("Software flowcontrol (XON/XOFF) not supported");
2766 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2768 /* Activate configuration. */
2769 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2771 report_file_error ("Failed tcsetattr", Qnil
);
2773 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2774 pset_childp (p
, childp2
);
2776 #endif /* not DOS_NT */
2778 /* System depended enumeration of and access to system processes a-la ps(1). */
2782 /* Process enumeration and access via /proc. */
2785 list_system_processes (void)
2787 Lisp_Object procdir
, match
, proclist
, next
;
2790 /* For every process on the system, there's a directory in the
2791 "/proc" pseudo-directory whose name is the numeric ID of that
2793 procdir
= build_string ("/proc");
2794 match
= build_string ("[0-9]+");
2795 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2797 /* `proclist' gives process IDs as strings. Destructively convert
2798 each string into a number. */
2799 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2802 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2805 /* directory_files_internal returns the files in reverse order; undo
2807 proclist
= Fnreverse (proclist
);
2811 #elif defined DARWIN_OS || defined __FreeBSD__
2814 list_system_processes (void)
2817 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2819 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2822 struct kinfo_proc
*procs
;
2825 Lisp_Object proclist
= Qnil
;
2827 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2830 procs
= xmalloc (len
);
2831 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2837 len
/= sizeof (struct kinfo_proc
);
2838 for (i
= 0; i
< len
; i
++)
2841 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2843 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2852 /* The WINDOWSNT implementation is in w32.c.
2853 The MSDOS implementation is in dosfns.c. */
2854 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2857 list_system_processes (void)
2862 #endif /* !defined (WINDOWSNT) */
2864 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2865 static struct timespec
2866 time_from_jiffies (unsigned long long tval
, long hz
)
2868 unsigned long long s
= tval
/ hz
;
2869 unsigned long long frac
= tval
% hz
;
2872 if (TYPE_MAXIMUM (time_t) < s
)
2874 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2875 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2876 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2879 /* This is reachable only in the unlikely case that HZ * HZ
2880 exceeds ULLONG_MAX. It calculates an approximation that is
2881 guaranteed to be in range. */
2882 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
2883 + (hz
% TIMESPEC_RESOLUTION
!= 0));
2884 ns
= frac
/ hz_per_ns
;
2887 return make_timespec (s
, ns
);
2891 ltime_from_jiffies (unsigned long long tval
, long hz
)
2893 struct timespec t
= time_from_jiffies (tval
, hz
);
2894 return make_lisp_time (t
);
2897 static struct timespec
2901 struct timespec up
= make_timespec (0, 0);
2904 fup
= emacs_fopen ("/proc/uptime", "r");
2908 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
2909 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
2911 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
2912 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
2913 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
2916 if (TYPE_MAXIMUM (time_t) < upsec
)
2918 upsec
= TYPE_MAXIMUM (time_t);
2919 upfrac
= TIMESPEC_RESOLUTION
- 1;
2923 int upfraclen
= upfrac_end
- upfrac_start
;
2924 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
2926 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
2928 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
2930 up
= make_timespec (upsec
, upfrac
);
2939 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2940 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2943 procfs_ttyname (int rdev
)
2946 char name
[PATH_MAX
];
2949 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
2955 unsigned long minor_beg
, minor_end
;
2956 char minor
[25]; /* 2 32-bit numbers + dash */
2959 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
2961 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
2962 && major
== MAJOR (rdev
))
2964 minor_beg
= strtoul (minor
, &endp
, 0);
2966 minor_end
= minor_beg
;
2967 else if (*endp
== '-')
2968 minor_end
= strtoul (endp
+ 1, &endp
, 0);
2972 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
2974 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
2982 return build_string (name
);
2986 procfs_get_total_memory (void)
2989 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
2993 fmem
= emacs_fopen ("/proc/meminfo", "r");
2997 uintmax_t entry_value
;
3001 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3004 retval
= entry_value
;
3009 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3027 system_process_attributes (Lisp_Object pid
)
3029 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3033 long clocks_per_sec
;
3035 char procbuf
[1025], *p
, *q
;
3038 static char const default_cmd
[] = "???";
3039 const char *cmd
= default_cmd
;
3040 int cmdsize
= sizeof default_cmd
- 1;
3041 char *cmdline
= NULL
;
3042 ptrdiff_t cmdline_size
;
3045 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3048 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3049 long priority
, niceness
, rss
;
3050 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3051 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3053 Lisp_Object attrs
= Qnil
;
3054 Lisp_Object decoded_cmd
;
3057 CHECK_NUMBER_OR_FLOAT (pid
);
3058 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3059 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3060 if (stat (procfn
, &st
) < 0)
3065 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3067 pw
= getpwuid (uid
);
3070 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3073 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3075 gr
= getgrgid (gid
);
3078 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3080 count
= SPECPDL_INDEX ();
3081 strcpy (fn
, procfn
);
3082 procfn_end
= fn
+ strlen (fn
);
3083 strcpy (procfn_end
, "/stat");
3084 fd
= emacs_open (fn
, O_RDONLY
, 0);
3089 record_unwind_protect_int (close_file_unwind
, fd
);
3090 nread
= emacs_read (fd
, procbuf
, sizeof procbuf
- 1);
3094 procbuf
[nread
] = '\0';
3097 p
= strchr (p
, '(');
3100 q
= strrchr (p
+ 1, ')');
3110 /* Command name is encoded in locale-coding-system; decode it. */
3111 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3112 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3113 Vlocale_coding_system
, 0);
3114 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3116 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3117 utime stime cutime cstime priority nice thcount . start vsize rss */
3119 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3120 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3121 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3122 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3123 &u_time
, &s_time
, &cutime
, &cstime
,
3124 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3129 state_str
[1] = '\0';
3130 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3131 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3132 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3133 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3134 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3135 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3136 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3137 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3138 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3140 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3142 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3143 if (clocks_per_sec
< 0)
3144 clocks_per_sec
= 100;
3145 attrs
= Fcons (Fcons (Qutime
,
3146 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3148 attrs
= Fcons (Fcons (Qstime
,
3149 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3151 attrs
= Fcons (Fcons (Qtime
,
3152 ltime_from_jiffies (s_time
+ u_time
,
3155 attrs
= Fcons (Fcons (Qcutime
,
3156 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3158 attrs
= Fcons (Fcons (Qcstime
,
3159 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3161 attrs
= Fcons (Fcons (Qctime
,
3162 ltime_from_jiffies (cstime
+ cutime
,
3165 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3166 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3167 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3169 tnow
= current_timespec ();
3170 telapsed
= get_up_time ();
3171 tboot
= timespec_sub (tnow
, telapsed
);
3172 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3173 tstart
= timespec_add (tboot
, tstart
);
3174 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3175 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3177 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3178 telapsed
= timespec_sub (tnow
, tstart
);
3179 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3180 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3181 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3184 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3185 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3188 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3191 unbind_to (count
, Qnil
);
3194 strcpy (procfn_end
, "/cmdline");
3195 fd
= emacs_open (fn
, O_RDONLY
, 0);
3198 ptrdiff_t readsize
, nread_incr
;
3199 record_unwind_protect_int (close_file_unwind
, fd
);
3200 record_unwind_protect_nothing ();
3201 nread
= cmdline_size
= 0;
3205 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3206 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3208 /* Leave room even if every byte needs escaping below. */
3209 readsize
= (cmdline_size
>> 1) - nread
;
3211 nread_incr
= emacs_read (fd
, cmdline
+ nread
, readsize
);
3212 nread
+= max (0, nread_incr
);
3214 while (nread_incr
== readsize
);
3218 /* We don't want trailing null characters. */
3219 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3222 /* Escape-quote whitespace and backslashes. */
3223 q
= cmdline
+ cmdline_size
;
3228 if (c_isspace (c
) || c
== '\\')
3232 nread
= cmdline
+ cmdline_size
- q
;
3237 nread
= cmdsize
+ 2;
3238 cmdline_size
= nread
+ 1;
3239 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3240 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3241 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3243 /* Command line is encoded in locale-coding-system; decode it. */
3244 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3245 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3246 Vlocale_coding_system
, 0);
3247 unbind_to (count
, Qnil
);
3248 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3254 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3256 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3257 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3258 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3259 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3260 #undef _FILE_OFFSET_BITS
3262 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3267 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3268 #define _FILE_OFFSET_BITS 64
3269 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3271 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3274 system_process_attributes (Lisp_Object pid
)
3276 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3281 struct psinfo pinfo
;
3287 Lisp_Object attrs
= Qnil
;
3288 Lisp_Object decoded_cmd
;
3291 CHECK_NUMBER_OR_FLOAT (pid
);
3292 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3293 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3294 if (stat (procfn
, &st
) < 0)
3299 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3301 pw
= getpwuid (uid
);
3304 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3307 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3309 gr
= getgrgid (gid
);
3312 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3314 count
= SPECPDL_INDEX ();
3315 strcpy (fn
, procfn
);
3316 procfn_end
= fn
+ strlen (fn
);
3317 strcpy (procfn_end
, "/psinfo");
3318 fd
= emacs_open (fn
, O_RDONLY
, 0);
3323 record_unwind_protect (close_file_unwind
, fd
);
3324 nread
= emacs_read (fd
, &pinfo
, sizeof pinfo
);
3327 if (nread
== sizeof pinfo
)
3329 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3330 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3331 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3335 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3336 state_str
[1] = '\0';
3337 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3340 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3341 need to get a string from it. */
3343 /* FIXME: missing: Qtpgid */
3355 Are they available? */
3357 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3358 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3359 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3360 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3361 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3364 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3365 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3367 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3370 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3371 range 0 .. 2**15, representing 0.0 .. 1.0. */
3372 attrs
= Fcons (Fcons (Qpcpu
,
3373 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3375 attrs
= Fcons (Fcons (Qpmem
,
3376 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3379 AUTO_STRING (fname
, pinfo
.pr_fname
);
3380 decoded_cmd
= code_convert_string_norecord (fname
,
3381 Vlocale_coding_system
, 0);
3382 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3383 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3384 decoded_cmd
= code_convert_string_norecord (psargs
,
3385 Vlocale_coding_system
, 0);
3386 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3388 unbind_to (count
, Qnil
);
3392 #elif defined __FreeBSD__
3394 static struct timespec
3395 timeval_to_timespec (struct timeval t
)
3397 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3401 make_lisp_timeval (struct timeval t
)
3403 return make_lisp_time (timeval_to_timespec (t
));
3407 system_process_attributes (Lisp_Object pid
)
3410 int pagesize
= getpagesize ();
3411 unsigned long npages
;
3417 char args
[MAXPATHLEN
];
3418 struct timespec t
, now
;
3420 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3421 struct kinfo_proc proc
;
3422 size_t proclen
= sizeof proc
;
3424 Lisp_Object attrs
= Qnil
;
3425 Lisp_Object decoded_comm
;
3427 CHECK_NUMBER_OR_FLOAT (pid
);
3428 CONS_TO_INTEGER (pid
, int, proc_id
);
3431 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3434 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3437 pw
= getpwuid (proc
.ki_uid
);
3440 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3442 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3445 gr
= getgrgid (proc
.ki_svgid
);
3448 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3450 AUTO_STRING (comm
, proc
.ki_comm
);
3451 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3453 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3455 char state
[2] = {'\0', '\0'};
3456 switch (proc
.ki_stat
)
3478 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3481 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3482 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3483 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3486 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3489 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3491 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3492 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3493 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3494 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3495 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3497 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3499 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3501 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3502 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3503 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3505 attrs
= Fcons (Fcons (Qcutime
,
3506 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3508 attrs
= Fcons (Fcons (Qcstime
,
3509 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3511 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3512 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3513 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3515 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3517 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3518 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3519 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3520 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3521 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3524 now
= current_timespec ();
3525 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3526 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3528 len
= sizeof fscale
;
3529 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3534 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3536 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3537 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3538 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3542 len
= sizeof npages
;
3543 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3545 double pmem
= (proc
.ki_flag
& P_INMEM
3546 ? 100.0 * proc
.ki_rssize
/ npages
3548 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3551 mib
[2] = KERN_PROC_ARGS
;
3553 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3556 for (i
= 0; i
< len
; i
++)
3558 if (! args
[i
] && i
< len
- 1)
3562 AUTO_STRING (comm
, args
);
3563 decoded_comm
= code_convert_string_norecord (comm
,
3564 Vlocale_coding_system
, 0);
3566 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3572 #elif defined DARWIN_OS
3574 static struct timespec
3575 timeval_to_timespec (struct timeval t
)
3577 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3581 make_lisp_timeval (struct timeval t
)
3583 return make_lisp_time (timeval_to_timespec (t
));
3587 system_process_attributes (Lisp_Object pid
)
3590 int pagesize
= getpagesize ();
3591 unsigned long npages
;
3597 char args
[MAXPATHLEN
];
3598 struct timeval starttime
;
3599 struct timespec t
, now
;
3600 struct rusage
*rusage
;
3605 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3606 struct kinfo_proc proc
;
3607 size_t proclen
= sizeof proc
;
3609 Lisp_Object attrs
= Qnil
;
3610 Lisp_Object decoded_comm
;
3612 CHECK_NUMBER_OR_FLOAT (pid
);
3613 CONS_TO_INTEGER (pid
, int, proc_id
);
3616 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3619 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3620 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3623 pw
= getpwuid (uid
);
3626 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3628 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3629 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3632 gr
= getgrgid (gid
);
3635 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3637 decoded_comm
= (code_convert_string_norecord
3638 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3639 Vlocale_coding_system
, 0));
3641 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3643 char state
[2] = {'\0', '\0'};
3644 switch (proc
.kp_proc
.p_stat
)
3666 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3669 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3671 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3674 tdev
= proc
.kp_eproc
.e_tdev
;
3676 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3679 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3681 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3684 rusage
= proc
.kp_proc
.p_ru
;
3687 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3689 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3692 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3694 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3696 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3697 timeval_to_timespec (rusage
->ru_stime
));
3698 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3701 starttime
= proc
.kp_proc
.p_starttime
;
3702 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3703 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3705 now
= current_timespec ();
3706 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3707 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3712 /* The WINDOWSNT implementation is in w32.c.
3713 The MSDOS implementation is in dosfns.c. */
3714 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3717 system_process_attributes (Lisp_Object pid
)
3722 #endif /* !defined (WINDOWSNT) */
3724 /* Wide character string collation. */
3726 #ifdef __STDC_ISO_10646__
3728 # include <wctype.h>
3730 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3731 # include <locale.h>
3734 # define LC_COLLATE 0
3736 # ifndef LC_COLLATE_MASK
3737 # define LC_COLLATE_MASK 0
3742 # ifndef LC_CTYPE_MASK
3743 # define LC_CTYPE_MASK 0
3746 # ifndef HAVE_NEWLOCALE
3752 # define freelocale emacs_freelocale
3753 # define locale_t emacs_locale_t
3754 # define newlocale emacs_newlocale
3755 # define wcscoll_l emacs_wcscoll_l
3756 # define towlower_l emacs_towlower_l
3758 typedef char const *locale_t
;
3761 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3767 freelocale (locale_t loc
)
3772 emacs_setlocale (int category
, char const *locale
)
3774 # ifdef HAVE_SETLOCALE
3776 char *loc
= setlocale (category
, locale
);
3787 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3790 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3798 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3799 strcpy (oldcopy
, oldloc
);
3800 if (! emacs_setlocale (LC_COLLATE
, loc
))
3805 result
= wcscoll (a
, b
);
3807 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3818 towlower_l (wint_t wc
, locale_t loc
)
3821 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3826 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3827 strcpy (oldcopy
, oldloc
);
3828 if (emacs_setlocale (LC_CTYPE
, loc
))
3830 result
= towlower (wc
);
3831 emacs_setlocale (LC_COLLATE
, oldcopy
);
3841 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3842 Lisp_Object locale
, Lisp_Object ignore_case
)
3845 ptrdiff_t len
, i
, i_byte
;
3850 /* Convert byte stream to code points. */
3851 len
= SCHARS (s1
); i
= i_byte
= 0;
3852 SAFE_NALLOCA (p1
, 1, len
+ 1);
3854 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3857 len
= SCHARS (s2
); i
= i_byte
= 0;
3858 SAFE_NALLOCA (p2
, 1, len
+ 1);
3860 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3863 if (STRINGP (locale
))
3865 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3866 SSDATA (locale
), 0);
3868 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3870 if (! NILP (ignore_case
))
3871 for (int i
= 1; i
< 3; i
++)
3873 wchar_t *p
= (i
== 1) ? p1
: p2
;
3875 *p
= towlower_l (*p
, loc
);
3879 res
= wcscoll_l (p1
, p2
, loc
);
3885 if (! NILP (ignore_case
))
3886 for (int i
= 1; i
< 3; i
++)
3888 wchar_t *p
= (i
== 1) ? p1
: p2
;
3894 res
= wcscoll (p1
, p2
);
3897 # ifndef HAVE_NEWLOCALE
3899 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
3902 error ("Invalid string for collation: %s", emacs_strerror (err
));
3908 #endif /* __STDC_ISO_10646__ */
3912 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3913 Lisp_Object locale
, Lisp_Object ignore_case
)
3916 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
3917 int res
, err
= errno
;
3920 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
3922 error ("Invalid string for collation: %s", strerror (errno
));
3927 #endif /* WINDOWSNT */