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 defined HAVE_GNUTLS && !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 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
133 # include <sys/personality.h>
135 /* Disable address randomization in the current process. Return true
136 if addresses were randomized but this has been disabled, false
139 disable_address_randomization (void)
141 bool disabled
= false;
142 int pers
= personality (0xffffffff);
143 disabled
= (! (pers
& ADDR_NO_RANDOMIZE
)
144 && 0 <= personality (pers
| ADDR_NO_RANDOMIZE
));
149 /* Execute the program in FILE, with argument vector ARGV and environ
150 ENVP. Return an error number if unsuccessful. This is like execve
151 except it reenables ASLR in the executed program if necessary, and
152 on error it returns an error number rather than -1. */
154 emacs_exec_file (char const *file
, char *const *argv
, char *const *envp
)
156 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
157 int pers
= getenv ("EMACS_HEAP_EXEC") ? personality (0xffffffff) : -1;
158 bool change_personality
= 0 <= pers
&& pers
& ADDR_NO_RANDOMIZE
;
159 if (change_personality
)
160 personality (pers
& ~ADDR_NO_RANDOMIZE
);
163 execve (file
, argv
, envp
);
166 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
167 if (change_personality
)
174 /* If FD is not already open, arrange for it to be open with FLAGS. */
176 force_open (int fd
, int flags
)
178 if (dup2 (fd
, fd
) < 0 && errno
== EBADF
)
180 int n
= open (NULL_DEVICE
, flags
);
181 if (n
< 0 || (fd
!= n
&& (dup2 (n
, fd
) < 0 || emacs_close (n
) != 0)))
183 emacs_perror (NULL_DEVICE
);
189 /* Make sure stdin, stdout, and stderr are open to something, so that
190 their file descriptors are not hijacked by later system calls. */
192 init_standard_fds (void)
194 /* Open stdin for *writing*, and stdout and stderr for *reading*.
195 That way, any attempt to do normal I/O will result in an error,
196 just as if the files were closed, and the file descriptors will
197 not be reused by later opens. */
198 force_open (STDIN_FILENO
, O_WRONLY
);
199 force_open (STDOUT_FILENO
, O_RDONLY
);
200 force_open (STDERR_FILENO
, O_RDONLY
);
203 /* Return the current working directory. The result should be freed
204 with 'free'. Return NULL on errors. */
206 emacs_get_current_dir_name (void)
208 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
209 # ifdef HYBRID_MALLOC
210 bool use_libc
= bss_sbrk_did_unexec
;
212 bool use_libc
= true;
215 return get_current_dir_name ();
219 char *pwd
= getenv ("PWD");
220 struct stat dotstat
, pwdstat
;
221 /* If PWD is accurate, use it instead of calling getcwd. PWD is
222 sometimes a nicer name, and using it may avoid a fatal error if a
223 parent directory is searchable but not readable. */
225 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
226 && stat (pwd
, &pwdstat
) == 0
227 && stat (".", &dotstat
) == 0
228 && dotstat
.st_ino
== pwdstat
.st_ino
229 && dotstat
.st_dev
== pwdstat
.st_dev
231 && strlen (pwd
) < MAXPATHLEN
235 buf
= malloc (strlen (pwd
) + 1);
242 size_t buf_size
= 1024;
243 buf
= malloc (buf_size
);
248 if (getcwd (buf
, buf_size
) == buf
)
252 int tmp_errno
= errno
;
258 buf
= realloc (buf
, buf_size
);
267 /* Discard pending input on all input descriptors. */
270 discard_tty_input (void)
273 struct emacs_tty buf
;
278 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
279 while (dos_keyread () != -1)
281 #else /* not MSDOS */
283 struct tty_display_info
*tty
;
284 for (tty
= tty_list
; tty
; tty
= tty
->next
)
286 if (tty
->input
) /* Is the device suspended? */
288 emacs_get_tty (fileno (tty
->input
), &buf
);
289 emacs_set_tty (fileno (tty
->input
), &buf
, 0);
293 #endif /* not MSDOS */
294 #endif /* not WINDOWSNT */
300 /* Arrange for character C to be read as the next input from
302 XXX What if we have multiple ttys?
308 if (! (FRAMEP (selected_frame
)
309 && FRAME_LIVE_P (XFRAME (selected_frame
))
310 && FRAME_TERMCAP_P (XFRAME (selected_frame
))))
313 /* Should perhaps error if in batch mode */
315 ioctl (fileno (CURTTY()->input
), TIOCSTI
, &c
);
316 #else /* no TIOCSTI */
317 error ("Cannot stuff terminal input characters in this version of Unix");
318 #endif /* no TIOCSTI */
324 init_baud_rate (int fd
)
334 #else /* not DOS_NT */
339 emacs_ospeed
= cfgetospeed (&sg
);
340 #endif /* not DOS_NT */
343 baud_rate
= (emacs_ospeed
< ARRAYELTS (baud_convert
)
344 ? baud_convert
[emacs_ospeed
] : 9600);
353 /* Wait for the subprocess with process id CHILD to terminate or change status.
354 CHILD must be a child process that has not been reaped.
355 If STATUS is non-null, store the waitpid-style exit status into *STATUS
356 and tell wait_reading_process_output that it needs to look around.
357 Use waitpid-style OPTIONS when waiting.
358 If INTERRUPTIBLE, this function is interruptible by a signal.
360 Return CHILD if successful, 0 if no status is available;
361 the latter is possible only when options & NOHANG. */
363 get_child_status (pid_t child
, int *status
, int options
, bool interruptible
)
367 /* Invoke waitpid only with a known process ID; do not invoke
368 waitpid with a nonpositive argument. Otherwise, Emacs might
369 reap an unwanted process by mistake. For example, invoking
370 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
371 so that another thread running glib won't find them. */
374 while ((pid
= waitpid (child
, status
, options
)) < 0)
376 /* Check that CHILD is a child process that has not been reaped,
377 and that STATUS and OPTIONS are valid. Otherwise abort,
378 as continuing after this internal error could cause Emacs to
379 become confused and kill innocent-victim processes. */
383 /* Note: the MS-Windows emulation of waitpid calls QUIT
389 /* If successful and status is requested, tell wait_reading_process_output
390 that it needs to wake up and look around. */
391 if (pid
&& status
&& input_available_clear_time
)
392 *input_available_clear_time
= make_timespec (0, 0);
397 /* Wait for the subprocess with process id CHILD to terminate.
398 CHILD must be a child process that has not been reaped.
399 If STATUS is non-null, store the waitpid-style exit status into *STATUS
400 and tell wait_reading_process_output that it needs to look around.
401 If INTERRUPTIBLE, this function is interruptible by a signal. */
403 wait_for_termination (pid_t child
, int *status
, bool interruptible
)
405 get_child_status (child
, status
, 0, interruptible
);
408 /* Report whether the subprocess with process id CHILD has changed status.
409 Termination counts as a change of status.
410 CHILD must be a child process that has not been reaped.
411 If STATUS is non-null, store the waitpid-style exit status into *STATUS
412 and tell wait_reading_process_output that it needs to look around.
413 Use waitpid-style OPTIONS to check status, but do not wait.
415 Return CHILD if successful, 0 if no status is available because
416 the process's state has not changed. */
418 child_status_changed (pid_t child
, int *status
, int options
)
420 return get_child_status (child
, status
, WNOHANG
| options
, 0);
424 /* Set up the terminal at the other end of a pseudo-terminal that
425 we will be controlling an inferior through.
426 It should not echo or do line-editing, since that is done
427 in Emacs. No padding needed for insertion into an Emacs buffer. */
430 child_setup_tty (int out
)
435 emacs_get_tty (out
, &s
);
436 s
.main
.c_oflag
|= OPOST
; /* Enable output postprocessing */
437 s
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL on output */
439 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
440 Some versions of GNU Hurd do not have FFDLY? */
442 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
443 /* No output delays */
445 s
.main
.c_oflag
&= ~(NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
);
446 /* No output delays */
449 s
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
450 s
.main
.c_lflag
|= ISIG
; /* Enable signals */
452 s
.main
.c_iflag
&= ~IUCLC
; /* Disable downcasing on input. */
455 s
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
458 s
.main
.c_oflag
&= ~OLCUC
; /* Disable upcasing on output. */
460 s
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
461 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
462 s
.main
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
463 s
.main
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
466 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
469 #ifdef SIGNALS_VIA_CHARACTERS
470 /* the QUIT and INTR character are used in process_send_signal
471 so set them here to something useful. */
472 if (s
.main
.c_cc
[VQUIT
] == CDISABLE
)
473 s
.main
.c_cc
[VQUIT
] = '\\'&037; /* Control-\ */
474 if (s
.main
.c_cc
[VINTR
] == CDISABLE
)
475 s
.main
.c_cc
[VINTR
] = 'C'&037; /* Control-C */
476 #endif /* not SIGNALS_VIA_CHARACTERS */
479 /* Also, PTY overloads NUL and BREAK.
480 don't ignore break, but don't signal either, so it looks like NUL. */
481 s
.main
.c_iflag
&= ~IGNBRK
;
482 s
.main
.c_iflag
&= ~BRKINT
;
483 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
484 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
485 would force it to 0377. That looks like duplicated code. */
486 s
.main
.c_cflag
= (s
.main
.c_cflag
& ~CBAUD
) | B9600
; /* baud rate sanity */
489 /* We originally enabled ICANON (and set VEOF to 04), and then had
490 process.c send additional EOF chars to flush the output when faced
491 with long lines, but this leads to weird effects when the
492 subprocess has disabled ICANON and ends up seeing those spurious
493 extra EOFs. So we don't send EOFs any more in
494 process.c:send_process. First we tried to disable ICANON by
495 default, so if a subsprocess sets up ICANON, it's his problem (or
496 the Elisp package that talks to it) to deal with lines that are
497 too long. But this disables some features, such as the ability
498 to send EOF signals. So we re-enabled ICANON but there is no
499 more "send eof to flush" going on (which is wrong and unportable
500 in itself). The correct way to handle too much output is to
501 buffer what could not be written and then write it again when
502 select returns ok for writing. This has it own set of
503 problems. Write is now asynchronous, is that a problem? How much
504 do we buffer, and what do we do when that limit is reached? */
506 s
.main
.c_lflag
|= ICANON
; /* Enable line editing and eof processing */
507 s
.main
.c_cc
[VEOF
] = 'D'&037; /* Control-D */
508 #if 0 /* These settings only apply to non-ICANON mode. */
509 s
.main
.c_cc
[VMIN
] = 1;
510 s
.main
.c_cc
[VTIME
] = 0;
513 emacs_set_tty (out
, &s
, 0);
514 #endif /* not WINDOWSNT */
516 #endif /* not MSDOS */
519 /* Record a signal code and the action for it. */
523 struct sigaction action
;
526 static void save_signal_handlers (struct save_signal
*);
527 static void restore_signal_handlers (struct save_signal
*);
529 /* Suspend the Emacs process; give terminal to its superior. */
537 /* On a system where suspending is not implemented,
538 instead fork a subshell and let it talk directly to the terminal
545 /* Fork a subshell. */
550 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
553 char oldwd
[MAXPATHLEN
+1]; /* Fixed length is safe on MSDOS. */
555 char oldwd
[MAX_UTF8_PATH
];
561 struct save_signal saved_handlers
[5];
562 char *str
= SSDATA (encode_current_directory ());
568 char *volatile str_volatile
= str
;
575 error ("Can't spawn subshell");
577 saved_handlers
[0].code
= SIGINT
;
578 saved_handlers
[1].code
= SIGQUIT
;
579 saved_handlers
[2].code
= SIGTERM
;
581 saved_handlers
[3].code
= SIGIO
;
582 saved_handlers
[4].code
= 0;
584 saved_handlers
[3].code
= 0;
588 save_signal_handlers (saved_handlers
);
595 #ifdef DOS_NT /* MW, Aug 1993 */
596 getcwd (oldwd
, sizeof oldwd
);
598 sh
= egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
601 sh
= egetenv ("SHELL");
605 /* Use our buffer's default directory for the subshell. */
606 if (chdir (str
) != 0)
610 _exit (EXIT_CANCELED
);
614 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
616 char *epwd
= getenv ("PWD");
617 char old_pwd
[MAXPATHLEN
+1+4];
619 /* If PWD is set, pass it with corrected value. */
622 strcpy (old_pwd
, epwd
);
623 setenv ("PWD", str
, 1);
626 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
628 putenv (old_pwd
); /* restore previous value */
630 #else /* not MSDOS */
632 /* Waits for process completion */
633 pid
= _spawnlp (_P_WAIT
, sh
, sh
, NULL
);
634 chdir (oldwd
); /* FIXME: Do the right thing on chdir failure. */
636 write (1, "Can't execute subshell", 22);
637 #else /* not WINDOWSNT */
638 execlp (sh
, sh
, (char *) 0);
640 _exit (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
641 #endif /* not WINDOWSNT */
642 #endif /* not MSDOS */
645 /* Do this now if we did not do it before. */
647 save_signal_handlers (saved_handlers
);
651 wait_for_termination (pid
, &status
, 0);
653 restore_signal_handlers (saved_handlers
);
657 save_signal_handlers (struct save_signal
*saved_handlers
)
659 while (saved_handlers
->code
)
661 struct sigaction action
;
662 emacs_sigaction_init (&action
, SIG_IGN
);
663 sigaction (saved_handlers
->code
, &action
, &saved_handlers
->action
);
669 restore_signal_handlers (struct save_signal
*saved_handlers
)
671 while (saved_handlers
->code
)
673 sigaction (saved_handlers
->code
, &saved_handlers
->action
, 0);
679 static int old_fcntl_flags
[FD_SETSIZE
];
686 old_fcntl_flags
[fd
] = fcntl (fd
, F_GETFL
, 0) & ~FASYNC
;
687 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
] | FASYNC
);
688 interrupts_deferred
= 0;
697 fcntl (fd
, F_SETFL
, old_fcntl_flags
[fd
]);
711 sigemptyset (&unblocked
);
713 sigaddset (&unblocked
, SIGWINCH
);
715 sigaddset (&unblocked
, SIGIO
);
716 pthread_sigmask (SIG_UNBLOCK
, &unblocked
, 0);
718 interrupts_deferred
= 0;
723 unrequest_sigio (void)
731 sigemptyset (&blocked
);
733 sigaddset (&blocked
, SIGWINCH
);
735 sigaddset (&blocked
, SIGIO
);
736 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
737 interrupts_deferred
= 1;
745 block_child_signal (sigset_t
*oldset
)
748 sigemptyset (&blocked
);
749 sigaddset (&blocked
, SIGCHLD
);
750 sigaddset (&blocked
, SIGINT
);
751 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
754 /* Unblock SIGCHLD. */
757 unblock_child_signal (sigset_t
const *oldset
)
759 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
764 /* Saving and restoring the process group of Emacs's terminal. */
766 /* The process group of which Emacs was a member when it initially
769 If Emacs was in its own process group (i.e. inherited_pgroup ==
770 getpid ()), then we know we're running under a shell with job
771 control (Emacs would never be run as part of a pipeline).
774 If Emacs was not in its own process group, then we know we're
775 running under a shell (or a caller) that doesn't know how to
776 separate itself from Emacs (like sh). Emacs must be in its own
777 process group in order to receive SIGIO correctly. In this
778 situation, we put ourselves in our own pgroup, forcibly set the
779 tty's pgroup to our pgroup, and make sure to restore and reinstate
780 the tty's pgroup just like any other terminal setting. If
781 inherited_group was not the tty's pgroup, then we'll get a
782 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
783 it goes foreground in the future, which is what should happen. */
785 static pid_t inherited_pgroup
;
788 init_foreground_group (void)
790 pid_t pgrp
= getpgrp ();
791 inherited_pgroup
= getpid () == pgrp
? 0 : pgrp
;
794 /* Block and unblock SIGTTOU. */
797 block_tty_out_signal (sigset_t
*oldset
)
801 sigemptyset (&blocked
);
802 sigaddset (&blocked
, SIGTTOU
);
803 pthread_sigmask (SIG_BLOCK
, &blocked
, oldset
);
808 unblock_tty_out_signal (sigset_t
const *oldset
)
811 pthread_sigmask (SIG_SETMASK
, oldset
, 0);
815 /* Safely set a controlling terminal FD's process group to PGID.
816 If we are not in the foreground already, POSIX requires tcsetpgrp
817 to deliver a SIGTTOU signal, which would stop us. This is an
818 annoyance, so temporarily ignore the signal.
820 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
821 skip all this unless SIGTTOU is defined. */
823 tcsetpgrp_without_stopping (int fd
, pid_t pgid
)
828 block_tty_out_signal (&oldset
);
829 tcsetpgrp (fd
, pgid
);
830 unblock_tty_out_signal (&oldset
);
835 /* Split off the foreground process group to Emacs alone. When we are
836 in the foreground, but not started in our own process group,
837 redirect the tty device handle FD to point to our own process
838 group. FD must be the file descriptor of the controlling tty. */
840 narrow_foreground_group (int fd
)
842 if (inherited_pgroup
&& setpgid (0, 0) == 0)
843 tcsetpgrp_without_stopping (fd
, getpid ());
846 /* Set the tty to our original foreground group. */
848 widen_foreground_group (int fd
)
850 if (inherited_pgroup
&& setpgid (0, inherited_pgroup
) == 0)
851 tcsetpgrp_without_stopping (fd
, inherited_pgroup
);
854 /* Getting and setting emacs_tty structures. */
856 /* Set *TC to the parameters associated with the terminal FD,
857 or clear it if the parameters are not available.
858 Return 0 on success, -1 on failure. */
860 emacs_get_tty (int fd
, struct emacs_tty
*settings
)
862 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
863 memset (&settings
->main
, 0, sizeof (settings
->main
));
866 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
869 if (h
&& h
!= INVALID_HANDLE_VALUE
&& GetConsoleMode (h
, &console_mode
))
871 settings
->main
= console_mode
;
874 #endif /* WINDOWSNT */
877 /* We have those nifty POSIX tcmumbleattr functions. */
878 return tcgetattr (fd
, &settings
->main
);
883 /* Set the parameters of the tty on FD according to the contents of
884 *SETTINGS. If FLUSHP, discard input.
885 Return 0 if all went well, and -1 (setting errno) if anything failed. */
888 emacs_set_tty (int fd
, struct emacs_tty
*settings
, bool flushp
)
890 /* Set the primary parameters - baud rate, character size, etcetera. */
893 HANDLE h
= (HANDLE
)_get_osfhandle (fd
);
895 if (h
&& h
!= INVALID_HANDLE_VALUE
)
899 /* Assume the handle is open for input. */
901 FlushConsoleInputBuffer (h
);
902 new_mode
= settings
->main
;
903 SetConsoleMode (h
, new_mode
);
905 #endif /* WINDOWSNT */
908 /* We have those nifty POSIX tcmumbleattr functions.
909 William J. Smith <wjs@wiis.wang.com> writes:
910 "POSIX 1003.1 defines tcsetattr to return success if it was
911 able to perform any of the requested actions, even if some
912 of the requested actions could not be performed.
913 We must read settings back to ensure tty setup properly.
914 AIX requires this to keep tty from hanging occasionally." */
915 /* This make sure that we don't loop indefinitely in here. */
916 for (i
= 0 ; i
< 10 ; i
++)
917 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, &settings
->main
) < 0)
928 memset (&new, 0, sizeof (new));
929 /* Get the current settings, and see if they're what we asked for. */
930 tcgetattr (fd
, &new);
931 /* We cannot use memcmp on the whole structure here because under
932 * aix386 the termios structure has some reserved field that may
935 if ( new.c_iflag
== settings
->main
.c_iflag
936 && new.c_oflag
== settings
->main
.c_oflag
937 && new.c_cflag
== settings
->main
.c_cflag
938 && new.c_lflag
== settings
->main
.c_lflag
939 && memcmp (new.c_cc
, settings
->main
.c_cc
, NCCS
) == 0)
946 /* We have survived the tempest. */
953 static int old_fcntl_owner
[FD_SETSIZE
];
954 #endif /* F_SETOWN */
956 /* This may also be defined in stdio,
957 but if so, this does no harm,
958 and using the same name avoids wasting the other one's space. */
961 unsigned char _sobuf
[BUFSIZ
+8];
966 /* Initialize the terminal mode on all tty devices that are currently
970 init_all_sys_modes (void)
972 struct tty_display_info
*tty
;
973 for (tty
= tty_list
; tty
; tty
= tty
->next
)
974 init_sys_modes (tty
);
977 /* Initialize the terminal mode on the given tty device. */
980 init_sys_modes (struct tty_display_info
*tty_out
)
982 struct emacs_tty tty
;
984 Lisp_Object terminal
;
987 Vtty_erase_char
= Qnil
;
992 if (!tty_out
->output
)
993 return; /* The tty is suspended. */
995 narrow_foreground_group (fileno (tty_out
->input
));
997 if (! tty_out
->old_tty
)
998 tty_out
->old_tty
= xmalloc (sizeof *tty_out
->old_tty
);
1000 emacs_get_tty (fileno (tty_out
->input
), tty_out
->old_tty
);
1002 tty
= *tty_out
->old_tty
;
1004 #if !defined (DOS_NT)
1005 XSETINT (Vtty_erase_char
, tty
.main
.c_cc
[VERASE
]);
1007 tty
.main
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
1008 tty
.main
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
1009 #ifdef INLCR /* I'm just being cautious,
1010 since I can't check how widespread INLCR is--rms. */
1011 tty
.main
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
1014 tty
.main
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
1016 tty
.main
.c_lflag
&= ~ECHO
; /* Disable echo */
1017 tty
.main
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
1019 tty
.main
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
1021 tty
.main
.c_lflag
|= ISIG
; /* Enable signals */
1022 if (tty_out
->flow_control
)
1024 tty
.main
.c_iflag
|= IXON
; /* Enable start/stop output control */
1026 tty
.main
.c_iflag
&= ~IXANY
;
1030 tty
.main
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
1031 tty
.main
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
1033 tty
.main
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
1035 if (tty_out
->meta_key
)
1037 tty
.main
.c_cflag
|= CS8
; /* allow 8th bit on input */
1038 tty
.main
.c_cflag
&= ~PARENB
;/* Don't check parity */
1042 XSETTERMINAL(terminal
, tty_out
->terminal
);
1043 if (!NILP (Fcontrolling_tty_p (terminal
)))
1045 tty
.main
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
1046 /* Set up C-g for both SIGQUIT and SIGINT.
1047 We don't know which we will get, but we handle both alike
1048 so which one it really gives us does not matter. */
1049 tty
.main
.c_cc
[VQUIT
] = quit_char
;
1053 /* We normally don't get interrupt or quit signals from tty
1054 devices other than our controlling terminal; therefore,
1055 we must handle C-g as normal input. Unfortunately, this
1056 means that the interrupt and quit feature must be
1057 disabled on secondary ttys, or we would not even see the
1060 Note that even though emacsclient could have special code
1061 to pass SIGINT to Emacs, we should _not_ enable
1062 interrupt/quit keys for emacsclient frames. This means
1063 that we can't break out of loops in C code from a
1064 secondary tty frame, but we can always decide what
1065 display the C-g came from, which is more important from a
1066 usability point of view. (Consider the case when two
1067 people work together using the same Emacs instance.) */
1068 tty
.main
.c_cc
[VINTR
] = CDISABLE
;
1069 tty
.main
.c_cc
[VQUIT
] = CDISABLE
;
1071 tty
.main
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
1072 tty
.main
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
1074 tty
.main
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use
1079 tty
.main
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off handling of C-z. */
1082 tty
.main
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off handling of C-y. */
1083 #endif /* V_DSUSP */
1084 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1085 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1088 tty
.main
.c_cc
[VLNEXT
] = CDISABLE
;
1091 tty
.main
.c_cc
[VREPRINT
] = CDISABLE
;
1092 #endif /* VREPRINT */
1094 tty
.main
.c_cc
[VWERASE
] = CDISABLE
;
1095 #endif /* VWERASE */
1097 tty
.main
.c_cc
[VDISCARD
] = CDISABLE
;
1098 #endif /* VDISCARD */
1100 if (tty_out
->flow_control
)
1103 tty
.main
.c_cc
[VSTART
] = '\021';
1106 tty
.main
.c_cc
[VSTOP
] = '\023';
1112 tty
.main
.c_cc
[VSTART
] = CDISABLE
;
1115 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1120 tty
.main
.c_cc
[VSTRT
] = CDISABLE
;
1121 tty
.main
.c_cc
[VSTOP
] = CDISABLE
;
1122 tty
.main
.c_cc
[VSUSP
] = CDISABLE
;
1123 tty
.main
.c_cc
[VDSUSP
] = CDISABLE
;
1124 if (tty_out
->flow_control
)
1127 tty
.main
.c_cc
[VSTART
] = '\021';
1130 tty
.main
.c_cc
[VSTOP
] = '\023';
1133 /* Also, PTY overloads NUL and BREAK.
1134 don't ignore break, but don't signal either, so it looks like NUL.
1135 This really serves a purpose only if running in an XTERM window
1136 or via TELNET or the like, but does no harm elsewhere. */
1137 tty
.main
.c_iflag
&= ~IGNBRK
;
1138 tty
.main
.c_iflag
&= ~BRKINT
;
1140 #endif /* not DOS_NT */
1142 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1143 if (!tty_out
->term_initted
)
1144 internal_terminal_init ();
1145 dos_ttraw (tty_out
);
1148 emacs_set_tty (fileno (tty_out
->input
), &tty
, 0);
1150 /* This code added to insure that, if flow-control is not to be used,
1151 we have an unlocked terminal at the start. */
1154 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TCXONC
, 1);
1157 if (!tty_out
->flow_control
) ioctl (fileno (tty_out
->input
), TIOCSTART
, 0);
1160 #if !defined (DOS_NT)
1162 if (!tty_out
->flow_control
) tcflow (fileno (tty_out
->input
), TCOON
);
1167 if (interrupt_input
)
1169 old_fcntl_owner
[fileno (tty_out
->input
)] =
1170 fcntl (fileno (tty_out
->input
), F_GETOWN
, 0);
1171 fcntl (fileno (tty_out
->input
), F_SETOWN
, getpid ());
1172 init_sigio (fileno (tty_out
->input
));
1174 if (gpm_tty
== tty_out
)
1176 /* Arrange for mouse events to give us SIGIO signals. */
1177 fcntl (gpm_fd
, F_SETOWN
, getpid ());
1178 fcntl (gpm_fd
, F_SETFL
, fcntl (gpm_fd
, F_GETFL
, 0) | O_NONBLOCK
);
1179 init_sigio (gpm_fd
);
1181 #endif /* HAVE_GPM */
1183 #endif /* F_GETOWN */
1186 /* This symbol is defined on recent USG systems.
1187 Someone says without this call USG won't really buffer the file
1188 even with a call to setbuf. */
1189 setvbuf (tty_out
->output
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
1191 setbuf (tty_out
->output
, (char *) _sobuf
);
1194 if (tty_out
->terminal
->set_terminal_modes_hook
)
1195 tty_out
->terminal
->set_terminal_modes_hook (tty_out
->terminal
);
1197 if (!tty_out
->term_initted
)
1199 Lisp_Object tail
, frame
;
1200 FOR_EACH_FRAME (tail
, frame
)
1202 /* XXX This needs to be revised. */
1203 if (FRAME_TERMCAP_P (XFRAME (frame
))
1204 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1205 init_frame_faces (XFRAME (frame
));
1209 if (tty_out
->term_initted
&& no_redraw_on_reenter
)
1211 /* We used to call "direct_output_forward_char(0)" here,
1212 but it's not clear why, since it may not do anything anyway. */
1216 Lisp_Object tail
, frame
;
1218 FOR_EACH_FRAME (tail
, frame
)
1220 if ((FRAME_TERMCAP_P (XFRAME (frame
))
1221 || FRAME_MSDOS_P (XFRAME (frame
)))
1222 && FRAME_TTY (XFRAME (frame
)) == tty_out
)
1223 FRAME_GARBAGED_P (XFRAME (frame
)) = 1;
1227 tty_out
->term_initted
= 1;
1230 /* Return true if safe to use tabs in output.
1231 At the time this is called, init_sys_modes has not been done yet. */
1234 tabs_safe_p (int fd
)
1236 struct emacs_tty etty
;
1238 emacs_get_tty (fd
, &etty
);
1241 return ((etty
.main
.c_oflag
& TABDLY
) != TAB3
);
1242 #else /* not TABDLY */
1244 #endif /* not TABDLY */
1250 /* Discard echoing. */
1253 suppress_echo_on_tty (int fd
)
1255 struct emacs_tty etty
;
1257 emacs_get_tty (fd
, &etty
);
1259 /* Set raw input mode. */
1262 etty
.main
.c_lflag
&= ~ICANON
; /* Disable buffering */
1263 etty
.main
.c_lflag
&= ~ECHO
; /* Disable echoing */
1264 #endif /* ! WINDOWSNT */
1265 emacs_set_tty (fd
, &etty
, 0);
1268 /* Get terminal size from system.
1269 Store number of lines into *HEIGHTP and width into *WIDTHP.
1270 We store 0 if there's no valid information. */
1273 get_tty_size (int fd
, int *widthp
, int *heightp
)
1275 #if defined TIOCGWINSZ
1278 struct winsize size
;
1280 if (ioctl (fd
, TIOCGWINSZ
, &size
) == -1)
1281 *widthp
= *heightp
= 0;
1284 *widthp
= size
.ws_col
;
1285 *heightp
= size
.ws_row
;
1288 #elif defined TIOCGSIZE
1290 /* SunOS - style. */
1291 struct ttysize size
;
1293 if (ioctl (fd
, TIOCGSIZE
, &size
) == -1)
1294 *widthp
= *heightp
= 0;
1297 *widthp
= size
.ts_cols
;
1298 *heightp
= size
.ts_lines
;
1301 #elif defined WINDOWSNT
1303 CONSOLE_SCREEN_BUFFER_INFO info
;
1304 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE
), &info
))
1306 *widthp
= info
.srWindow
.Right
- info
.srWindow
.Left
+ 1;
1307 *heightp
= info
.srWindow
.Bottom
- info
.srWindow
.Top
+ 1;
1310 *widthp
= *heightp
= 0;
1314 *widthp
= ScreenCols ();
1315 *heightp
= ScreenRows ();
1317 #else /* system doesn't know size */
1325 /* Set the logical window size associated with descriptor FD
1326 to HEIGHT and WIDTH. This is used mainly with ptys.
1327 Return a negative value on failure. */
1330 set_window_size (int fd
, int height
, int width
)
1335 struct winsize size
;
1336 size
.ws_row
= height
;
1337 size
.ws_col
= width
;
1339 return ioctl (fd
, TIOCSWINSZ
, &size
);
1344 /* SunOS - style. */
1345 struct ttysize size
;
1346 size
.ts_lines
= height
;
1347 size
.ts_cols
= width
;
1349 return ioctl (fd
, TIOCGSIZE
, &size
);
1352 #endif /* not SunOS-style */
1353 #endif /* not BSD-style */
1358 /* Prepare all terminal devices for exiting Emacs. */
1361 reset_all_sys_modes (void)
1363 struct tty_display_info
*tty
;
1364 for (tty
= tty_list
; tty
; tty
= tty
->next
)
1365 reset_sys_modes (tty
);
1368 /* Prepare the terminal for closing it; move the cursor to the
1369 bottom of the frame, turn off interrupt-driven I/O, etc. */
1372 reset_sys_modes (struct tty_display_info
*tty_out
)
1379 if (!tty_out
->term_initted
)
1382 if (!tty_out
->output
)
1383 return; /* The tty is suspended. */
1385 /* Go to and clear the last line of the terminal. */
1387 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1389 /* Code adapted from tty_clear_end_of_line. */
1390 if (tty_out
->TS_clr_line
)
1392 emacs_tputs (tty_out
, tty_out
->TS_clr_line
, 1, cmputc
);
1395 { /* have to do it the hard way */
1397 tty_turn_off_insert (tty_out
);
1399 for (i
= cursorX (tty_out
); i
< FrameCols (tty_out
) - 1; i
++)
1401 fputc (' ', tty_out
->output
);
1405 cmgoto (tty_out
, FrameRows (tty_out
) - 1, 0);
1406 fflush (tty_out
->output
);
1408 if (tty_out
->terminal
->reset_terminal_modes_hook
)
1409 tty_out
->terminal
->reset_terminal_modes_hook (tty_out
->terminal
);
1411 /* Avoid possible loss of output when changing terminal modes. */
1412 while (fdatasync (fileno (tty_out
->output
)) != 0 && errno
== EINTR
)
1417 if (interrupt_input
)
1419 reset_sigio (fileno (tty_out
->input
));
1420 fcntl (fileno (tty_out
->input
), F_SETOWN
,
1421 old_fcntl_owner
[fileno (tty_out
->input
)]);
1423 #endif /* F_SETOWN */
1424 fcntl (fileno (tty_out
->input
), F_SETFL
,
1425 fcntl (fileno (tty_out
->input
), F_GETFL
, 0) & ~O_NONBLOCK
);
1428 if (tty_out
->old_tty
)
1429 while (emacs_set_tty (fileno (tty_out
->input
),
1430 tty_out
->old_tty
, 0) < 0 && errno
== EINTR
)
1433 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1437 widen_foreground_group (fileno (tty_out
->input
));
1442 /* Set up the proper status flags for use of a pty. */
1447 /* I'm told that TOICREMOTE does not mean control chars
1448 "can't be sent" but rather that they don't have
1449 input-editing or signaling effects.
1450 That should be good, because we have other ways
1451 to do those things in Emacs.
1452 However, telnet mode seems not to work on 4.2.
1453 So TIOCREMOTE is turned off now. */
1455 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1456 will hang. In particular, the "timeout" feature (which
1457 causes a read to return if there is no data available)
1458 does this. Also it is known that telnet mode will hang
1459 in such a way that Emacs must be stopped (perhaps this
1460 is the same problem).
1462 If TIOCREMOTE is turned off, then there is a bug in
1463 hp-ux which sometimes loses data. Apparently the
1464 code which blocks the master process when the internal
1465 buffer fills up does not work. Other than this,
1466 though, everything else seems to work fine.
1468 Since the latter lossage is more benign, we may as well
1469 lose that way. -- cph */
1471 #if defined (UNIX98_PTYS)
1474 ioctl (fd
, FIONBIO
, &on
);
1479 #endif /* HAVE_PTYS */
1482 init_system_name (void)
1486 /* Set system-name to nil so that the build is deterministic. */
1487 Vsystem_name
= Qnil
;
1490 char *hostname_alloc
= NULL
;
1492 #ifndef HAVE_GETHOSTNAME
1495 hostname
= uts
.nodename
;
1496 #else /* HAVE_GETHOSTNAME */
1497 char hostname_buf
[256];
1498 ptrdiff_t hostname_size
= sizeof hostname_buf
;
1499 hostname
= hostname_buf
;
1501 /* Try to get the host name; if the buffer is too short, try
1502 again. Apparently, the only indication gethostname gives of
1503 whether the buffer was large enough is the presence or absence
1504 of a '\0' in the string. Eech. */
1507 gethostname (hostname
, hostname_size
- 1);
1508 hostname
[hostname_size
- 1] = '\0';
1510 /* Was the buffer large enough for the '\0'? */
1511 if (strlen (hostname
) < hostname_size
- 1)
1514 hostname
= hostname_alloc
= xpalloc (hostname_alloc
, &hostname_size
, 1,
1515 min (PTRDIFF_MAX
, SIZE_MAX
), 1);
1517 #endif /* HAVE_GETHOSTNAME */
1519 for (p
= hostname
; *p
; p
++)
1520 if (*p
== ' ' || *p
== '\t')
1522 if (! (STRINGP (Vsystem_name
) && SBYTES (Vsystem_name
) == p
- hostname
1523 && strcmp (SSDATA (Vsystem_name
), hostname
) == 0))
1524 Vsystem_name
= build_string (hostname
);
1525 xfree (hostname_alloc
);
1528 sigset_t empty_mask
;
1530 static struct sigaction process_fatal_action
;
1533 emacs_sigaction_flags (void)
1536 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1537 'select') to reset their timeout on some platforms (e.g.,
1538 HP-UX 11), which is not what we want. Also, when Emacs is
1539 interactive, we don't want SA_RESTART because we need to poll
1540 for pending input so we need long-running syscalls to be interrupted
1541 after a signal that sets pending_signals.
1543 Non-interactive keyboard input goes through stdio, where we
1544 always want restartable system calls. */
1551 /* Store into *ACTION a signal action suitable for Emacs, with handler
1554 emacs_sigaction_init (struct sigaction
*action
, signal_handler_t handler
)
1556 sigemptyset (&action
->sa_mask
);
1558 /* When handling a signal, block nonfatal system signals that are caught
1559 by Emacs. This makes race conditions less likely. */
1560 sigaddset (&action
->sa_mask
, SIGALRM
);
1562 sigaddset (&action
->sa_mask
, SIGCHLD
);
1565 sigaddset (&action
->sa_mask
, SIGDANGER
);
1567 #ifdef PROFILER_CPU_SUPPORT
1568 sigaddset (&action
->sa_mask
, SIGPROF
);
1571 sigaddset (&action
->sa_mask
, SIGWINCH
);
1573 if (! noninteractive
)
1575 sigaddset (&action
->sa_mask
, SIGINT
);
1576 sigaddset (&action
->sa_mask
, SIGQUIT
);
1578 sigaddset (&action
->sa_mask
, SIGIO
);
1582 action
->sa_handler
= handler
;
1583 action
->sa_flags
= emacs_sigaction_flags ();
1586 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1587 static pthread_t main_thread
;
1590 /* SIG has arrived at the current process. Deliver it to the main
1591 thread, which should handle it with HANDLER.
1593 If we are on the main thread, handle the signal SIG with HANDLER.
1594 Otherwise, redirect the signal to the main thread, blocking it from
1595 this thread. POSIX says any thread can receive a signal that is
1596 associated with a process, process group, or asynchronous event.
1597 On GNU/Linux that is not true, but for other systems (FreeBSD at
1600 deliver_process_signal (int sig
, signal_handler_t handler
)
1602 /* Preserve errno, to avoid race conditions with signal handlers that
1603 might change errno. Races can occur even in single-threaded hosts. */
1604 int old_errno
= errno
;
1606 bool on_main_thread
= true;
1607 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1608 if (! pthread_equal (pthread_self (), main_thread
))
1611 sigemptyset (&blocked
);
1612 sigaddset (&blocked
, sig
);
1613 pthread_sigmask (SIG_BLOCK
, &blocked
, 0);
1614 pthread_kill (main_thread
, sig
);
1615 on_main_thread
= false;
1624 /* Static location to save a fatal backtrace in a thread.
1625 FIXME: If two subsidiary threads fail simultaneously, the resulting
1626 backtrace may be garbage. */
1627 enum { BACKTRACE_LIMIT_MAX
= 500 };
1628 static void *thread_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
1629 static int thread_backtrace_npointers
;
1631 /* SIG has arrived at the current thread.
1632 If we are on the main thread, handle the signal SIG with HANDLER.
1633 Otherwise, this is a fatal error in the handling thread. */
1635 deliver_thread_signal (int sig
, signal_handler_t handler
)
1637 int old_errno
= errno
;
1639 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1640 if (! pthread_equal (pthread_self (), main_thread
))
1642 thread_backtrace_npointers
1643 = backtrace (thread_backtrace_buffer
, BACKTRACE_LIMIT_MAX
);
1644 sigaction (sig
, &process_fatal_action
, 0);
1645 pthread_kill (main_thread
, sig
);
1647 /* Avoid further damage while the main thread is exiting. */
1649 sigsuspend (&empty_mask
);
1657 #if !HAVE_DECL_SYS_SIGLIST
1659 # ifdef _sys_siglist
1660 # define sys_siglist _sys_siglist
1661 # elif HAVE_DECL___SYS_SIGLIST
1662 # define sys_siglist __sys_siglist
1664 # define sys_siglist my_sys_siglist
1665 static char const *sys_siglist
[NSIG
];
1670 # define sys_siglist_entries _sys_nsig
1672 # define sys_siglist_entries NSIG
1675 /* Handle bus errors, invalid instruction, etc. */
1677 handle_fatal_signal (int sig
)
1679 terminate_due_to_signal (sig
, 40);
1683 deliver_fatal_signal (int sig
)
1685 deliver_process_signal (sig
, handle_fatal_signal
);
1689 deliver_fatal_thread_signal (int sig
)
1691 deliver_thread_signal (sig
, handle_fatal_signal
);
1694 static _Noreturn
void
1695 handle_arith_signal (int sig
)
1697 pthread_sigmask (SIG_SETMASK
, &empty_mask
, 0);
1698 xsignal0 (Qarith_error
);
1701 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1703 /* Alternate stack used by SIGSEGV handler below. */
1705 static unsigned char sigsegv_stack
[SIGSTKSZ
];
1708 /* Return true if SIGINFO indicates a stack overflow. */
1711 stack_overflow (siginfo_t
*siginfo
)
1713 if (!attempt_stack_overflow_recovery
)
1716 /* In theory, a more-accurate heuristic can be obtained by using
1717 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1718 and pthread_attr_getguardsize to find the location and size of the
1719 guard area. In practice, though, these functions are so hard to
1720 use reliably that they're not worth bothering with. E.g., see:
1721 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1722 Other operating systems also have problems, e.g., Solaris's
1723 stack_violation function is tailor-made for this problem, but it
1724 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1726 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1732 /* The faulting address. */
1733 char *addr
= siginfo
->si_addr
;
1737 /* The known top and bottom of the stack. The actual stack may
1738 extend a bit beyond these boundaries. */
1739 char *bot
= stack_bottom
;
1740 char *top
= near_C_stack_top ();
1742 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1743 of the known stack divided by the size of the guard area past the
1744 end of the stack top. The heuristic is that a bad address is
1745 considered to be a stack overflow if it occurs within
1746 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1747 stack. This heuristic is not exactly correct but it's good
1748 enough in practice. */
1749 enum { LG_STACK_HEURISTIC
= 8 };
1752 return 0 <= addr
- top
&& addr
- top
< (top
- bot
) >> LG_STACK_HEURISTIC
;
1754 return 0 <= top
- addr
&& top
- addr
< (bot
- top
) >> LG_STACK_HEURISTIC
;
1758 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1761 handle_sigsegv (int sig
, siginfo_t
*siginfo
, void *arg
)
1763 /* Hard GC error may lead to stack overflow caused by
1764 too nested calls to mark_object. No way to survive. */
1765 bool fatal
= gc_in_progress
;
1767 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1768 if (!fatal
&& !pthread_equal (pthread_self (), main_thread
))
1772 if (!fatal
&& stack_overflow (siginfo
))
1773 siglongjmp (return_to_command_loop
, 1);
1775 /* Otherwise we can't do anything with this. */
1776 deliver_fatal_thread_signal (sig
);
1779 /* Return true if we have successfully set up SIGSEGV handler on alternate
1780 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1785 struct sigaction sa
;
1788 ss
.ss_sp
= sigsegv_stack
;
1789 ss
.ss_size
= sizeof (sigsegv_stack
);
1791 if (sigaltstack (&ss
, NULL
) < 0)
1794 sigfillset (&sa
.sa_mask
);
1795 sa
.sa_sigaction
= handle_sigsegv
;
1796 sa
.sa_flags
= SA_SIGINFO
| SA_ONSTACK
| emacs_sigaction_flags ();
1797 return sigaction (SIGSEGV
, &sa
, NULL
) < 0 ? 0 : 1;
1800 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1808 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1811 deliver_arith_signal (int sig
)
1813 deliver_thread_signal (sig
, handle_arith_signal
);
1818 /* Handler for SIGDANGER. */
1820 handle_danger_signal (int sig
)
1822 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1824 /* It might be unsafe to call do_auto_save now. */
1825 force_auto_save_soon ();
1829 deliver_danger_signal (int sig
)
1831 deliver_process_signal (sig
, handle_danger_signal
);
1835 /* Treat SIG as a terminating signal, unless it is already ignored and
1836 we are in --batch mode. Among other things, this makes nohup work. */
1838 maybe_fatal_sig (int sig
)
1840 bool catch_sig
= !noninteractive
;
1843 struct sigaction old_action
;
1844 sigaction (sig
, 0, &old_action
);
1845 catch_sig
= old_action
.sa_handler
!= SIG_IGN
;
1848 sigaction (sig
, &process_fatal_action
, 0);
1852 init_signals (bool dumping
)
1854 struct sigaction thread_fatal_action
;
1855 struct sigaction action
;
1857 sigemptyset (&empty_mask
);
1859 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1860 main_thread
= pthread_self ();
1863 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1866 sys_siglist
[SIGABRT
] = "Aborted";
1868 sys_siglist
[SIGAIO
] = "LAN I/O interrupt";
1870 sys_siglist
[SIGALRM
] = "Alarm clock";
1872 sys_siglist
[SIGBUS
] = "Bus error";
1875 sys_siglist
[SIGCHLD
] = "Child status changed";
1878 sys_siglist
[SIGCONT
] = "Continued";
1881 sys_siglist
[SIGDANGER
] = "Swap space dangerously low";
1884 sys_siglist
[SIGDGNOTIFY
] = "Notification message in queue";
1887 sys_siglist
[SIGEMT
] = "Emulation trap";
1889 sys_siglist
[SIGFPE
] = "Arithmetic exception";
1891 sys_siglist
[SIGFREEZE
] = "SIGFREEZE";
1894 sys_siglist
[SIGGRANT
] = "Monitor mode granted";
1896 sys_siglist
[SIGHUP
] = "Hangup";
1897 sys_siglist
[SIGILL
] = "Illegal instruction";
1898 sys_siglist
[SIGINT
] = "Interrupt";
1900 sys_siglist
[SIGIO
] = "I/O possible";
1903 sys_siglist
[SIGIOINT
] = "I/O intervention required";
1906 sys_siglist
[SIGIOT
] = "IOT trap";
1908 sys_siglist
[SIGKILL
] = "Killed";
1910 sys_siglist
[SIGLOST
] = "Resource lost";
1913 sys_siglist
[SIGLWP
] = "SIGLWP";
1916 sys_siglist
[SIGMSG
] = "Monitor mode data available";
1919 sys_siglist
[SIGWIND
] = "SIGPHONE";
1921 sys_siglist
[SIGPIPE
] = "Broken pipe";
1923 sys_siglist
[SIGPOLL
] = "Pollable event occurred";
1926 sys_siglist
[SIGPROF
] = "Profiling timer expired";
1929 sys_siglist
[SIGPTY
] = "PTY I/O interrupt";
1932 sys_siglist
[SIGPWR
] = "Power-fail restart";
1934 sys_siglist
[SIGQUIT
] = "Quit";
1936 sys_siglist
[SIGRETRACT
] = "Need to relinquish monitor mode";
1939 sys_siglist
[SIGSAK
] = "Secure attention";
1941 sys_siglist
[SIGSEGV
] = "Segmentation violation";
1943 sys_siglist
[SIGSOUND
] = "Sound completed";
1946 sys_siglist
[SIGSTOP
] = "Stopped (signal)";
1949 sys_siglist
[SIGSTP
] = "Stopped (user)";
1952 sys_siglist
[SIGSYS
] = "Bad argument to system call";
1954 sys_siglist
[SIGTERM
] = "Terminated";
1956 sys_siglist
[SIGTHAW
] = "SIGTHAW";
1959 sys_siglist
[SIGTRAP
] = "Trace/breakpoint trap";
1962 sys_siglist
[SIGTSTP
] = "Stopped (user)";
1965 sys_siglist
[SIGTTIN
] = "Stopped (tty input)";
1968 sys_siglist
[SIGTTOU
] = "Stopped (tty output)";
1971 sys_siglist
[SIGURG
] = "Urgent I/O condition";
1974 sys_siglist
[SIGUSR1
] = "User defined signal 1";
1977 sys_siglist
[SIGUSR2
] = "User defined signal 2";
1980 sys_siglist
[SIGVTALRM
] = "Virtual timer expired";
1983 sys_siglist
[SIGWAITING
] = "Process's LWPs are blocked";
1986 sys_siglist
[SIGWINCH
] = "Window size changed";
1989 sys_siglist
[SIGWIND
] = "SIGWIND";
1992 sys_siglist
[SIGXCPU
] = "CPU time limit exceeded";
1995 sys_siglist
[SIGXFSZ
] = "File size limit exceeded";
1998 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2000 /* Don't alter signal handlers if dumping. On some machines,
2001 changing signal handlers sets static data that would make signals
2002 fail to work right when the dumped Emacs is run. */
2006 sigfillset (&process_fatal_action
.sa_mask
);
2007 process_fatal_action
.sa_handler
= deliver_fatal_signal
;
2008 process_fatal_action
.sa_flags
= emacs_sigaction_flags ();
2010 sigfillset (&thread_fatal_action
.sa_mask
);
2011 thread_fatal_action
.sa_handler
= deliver_fatal_thread_signal
;
2012 thread_fatal_action
.sa_flags
= process_fatal_action
.sa_flags
;
2014 /* SIGINT may need special treatment on MS-Windows. See
2015 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
2016 Please update the doc of kill-emacs, kill-emacs-hook, and
2017 NEWS if you change this. */
2019 maybe_fatal_sig (SIGHUP
);
2020 maybe_fatal_sig (SIGINT
);
2021 maybe_fatal_sig (SIGTERM
);
2023 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2024 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2025 to behave more like typical batch applications do. */
2026 if (! noninteractive
)
2027 signal (SIGPIPE
, SIG_IGN
);
2029 sigaction (SIGQUIT
, &process_fatal_action
, 0);
2030 sigaction (SIGILL
, &thread_fatal_action
, 0);
2031 sigaction (SIGTRAP
, &thread_fatal_action
, 0);
2033 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2034 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2035 interpreter's floating point operations, so treat SIGFPE as an
2036 arith-error if it arises in the main thread. */
2037 if (IEEE_FLOATING_POINT
)
2038 sigaction (SIGFPE
, &thread_fatal_action
, 0);
2041 emacs_sigaction_init (&action
, deliver_arith_signal
);
2042 sigaction (SIGFPE
, &action
, 0);
2046 add_user_signal (SIGUSR1
, "sigusr1");
2049 add_user_signal (SIGUSR2
, "sigusr2");
2051 sigaction (SIGABRT
, &thread_fatal_action
, 0);
2053 sigaction (SIGPRE
, &thread_fatal_action
, 0);
2056 sigaction (SIGORE
, &thread_fatal_action
, 0);
2059 sigaction (SIGUME
, &thread_fatal_action
, 0);
2062 sigaction (SIGDLK
, &process_fatal_action
, 0);
2065 sigaction (SIGCPULIM
, &process_fatal_action
, 0);
2068 sigaction (SIGIOT
, &thread_fatal_action
, 0);
2071 sigaction (SIGEMT
, &thread_fatal_action
, 0);
2074 sigaction (SIGBUS
, &thread_fatal_action
, 0);
2076 if (!init_sigsegv ())
2077 sigaction (SIGSEGV
, &thread_fatal_action
, 0);
2079 sigaction (SIGSYS
, &thread_fatal_action
, 0);
2081 sigaction (SIGTERM
, &process_fatal_action
, 0);
2083 signal (SIGPROF
, SIG_IGN
);
2086 sigaction (SIGVTALRM
, &process_fatal_action
, 0);
2089 sigaction (SIGXCPU
, &process_fatal_action
, 0);
2092 sigaction (SIGXFSZ
, &process_fatal_action
, 0);
2096 /* This just means available memory is getting low. */
2097 emacs_sigaction_init (&action
, deliver_danger_signal
);
2098 sigaction (SIGDANGER
, &action
, 0);
2101 /* AIX-specific signals. */
2103 sigaction (SIGGRANT
, &process_fatal_action
, 0);
2106 sigaction (SIGMIGRATE
, &process_fatal_action
, 0);
2109 sigaction (SIGMSG
, &process_fatal_action
, 0);
2112 sigaction (SIGRETRACT
, &process_fatal_action
, 0);
2115 sigaction (SIGSAK
, &process_fatal_action
, 0);
2118 sigaction (SIGSOUND
, &process_fatal_action
, 0);
2121 sigaction (SIGTALRM
, &thread_fatal_action
, 0);
2131 /* Figure out how many bits the system's random number generator uses.
2132 `random' and `lrand48' are assumed to return 31 usable bits.
2133 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2134 so we'll shift it and treat it like the 15-bit USG `rand'. */
2138 # define RAND_BITS 31
2139 # else /* !HAVE_RANDOM */
2140 # ifdef HAVE_LRAND48
2141 # define RAND_BITS 31
2142 # define random lrand48
2143 # else /* !HAVE_LRAND48 */
2144 # define RAND_BITS 15
2145 # if RAND_MAX == 32767
2146 # define random rand
2147 # else /* RAND_MAX != 32767 */
2148 # if RAND_MAX == 2147483647
2149 # define random() (rand () >> 16)
2150 # else /* RAND_MAX != 2147483647 */
2152 # define random rand
2154 # define random() (rand () >> 16)
2156 # endif /* RAND_MAX != 2147483647 */
2157 # endif /* RAND_MAX != 32767 */
2158 # endif /* !HAVE_LRAND48 */
2159 # endif /* !HAVE_RANDOM */
2160 #endif /* !RAND_BITS */
2163 typedef unsigned int random_seed
;
2164 static void set_random_seed (random_seed arg
) { srandom (arg
); }
2165 #elif defined HAVE_LRAND48
2166 /* Although srand48 uses a long seed, this is unsigned long to avoid
2167 undefined behavior on signed integer overflow in init_random. */
2168 typedef unsigned long int random_seed
;
2169 static void set_random_seed (random_seed arg
) { srand48 (arg
); }
2171 typedef unsigned int random_seed
;
2172 static void set_random_seed (random_seed arg
) { srand (arg
); }
2176 seed_random (void *seed
, ptrdiff_t seed_size
)
2178 random_seed arg
= 0;
2179 unsigned char *argp
= (unsigned char *) &arg
;
2180 unsigned char *seedp
= seed
;
2181 for (ptrdiff_t i
= 0; i
< seed_size
; i
++)
2182 argp
[i
% sizeof arg
] ^= seedp
[i
];
2183 set_random_seed (arg
);
2190 if (! (EQ (emacs_gnutls_global_init (), Qt
)
2191 && gnutls_rnd (GNUTLS_RND_NONCE
, &v
, sizeof v
) == 0))
2193 bool success
= false;
2195 int fd
= emacs_open ("/dev/urandom", O_RDONLY
, 0);
2198 success
= emacs_read (fd
, &v
, sizeof v
) == sizeof v
;
2202 success
= w32_init_random (&v
, sizeof v
) == 0;
2206 /* Fall back to current time value + PID. */
2207 struct timespec t
= current_timespec ();
2208 v
= getpid () ^ t
.tv_sec
^ t
.tv_nsec
;
2211 set_random_seed (v
);
2215 * Return a nonnegative random integer out of whatever we've got.
2216 * It contains enough bits to make a random (signed) Emacs fixnum.
2217 * This suffices even for a 64-bit architecture with a 15-bit rand.
2224 for (i
= 0; i
< (FIXNUM_BITS
+ RAND_BITS
- 1) / RAND_BITS
; i
++)
2225 val
= (random () ^ (val
<< RAND_BITS
)
2226 ^ (val
>> (BITS_PER_EMACS_INT
- RAND_BITS
)));
2227 val
^= val
>> (BITS_PER_EMACS_INT
- FIXNUM_BITS
);
2228 return val
& INTMASK
;
2231 #ifndef HAVE_SNPRINTF
2232 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2234 snprintf (char *buf
, size_t bufsize
, char const *format
, ...)
2236 ptrdiff_t size
= min (bufsize
, PTRDIFF_MAX
);
2237 ptrdiff_t nbytes
= size
- 1;
2242 va_start (ap
, format
);
2243 nbytes
= doprnt (buf
, size
, format
, 0, ap
);
2247 if (nbytes
== size
- 1)
2249 /* Calculate the length of the string that would have been created
2250 had the buffer been large enough. */
2251 char stackbuf
[4000];
2253 ptrdiff_t bsize
= sizeof stackbuf
;
2254 va_start (ap
, format
);
2255 nbytes
= evxprintf (&b
, &bsize
, stackbuf
, -1, format
, ap
);
2261 if (INT_MAX
< nbytes
)
2274 /* If a backtrace is available, output the top lines of it to stderr.
2275 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2276 This function may be called from a signal handler, so it should
2277 not invoke async-unsafe functions like malloc.
2279 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2280 but do not output anything. This avoids some problems that can
2281 otherwise occur if the malloc arena is corrupted before 'backtrace'
2282 is called, since 'backtrace' may call malloc if the tables are not
2285 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2286 fatal error has occurred in some other thread; generate a thread
2287 backtrace instead, ignoring BACKTRACE_LIMIT. */
2289 emacs_backtrace (int backtrace_limit
)
2291 void *main_backtrace_buffer
[BACKTRACE_LIMIT_MAX
+ 1];
2292 int bounded_limit
= min (backtrace_limit
, BACKTRACE_LIMIT_MAX
);
2296 if (thread_backtrace_npointers
)
2298 buffer
= thread_backtrace_buffer
;
2299 npointers
= thread_backtrace_npointers
;
2303 buffer
= main_backtrace_buffer
;
2305 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2306 if (bounded_limit
< 0)
2308 backtrace (buffer
, 1);
2312 npointers
= backtrace (buffer
, bounded_limit
+ 1);
2317 emacs_write (STDERR_FILENO
, "\nBacktrace:\n", 12);
2318 backtrace_symbols_fd (buffer
, npointers
, STDERR_FILENO
);
2319 if (bounded_limit
< npointers
)
2320 emacs_write (STDERR_FILENO
, "...\n", 4);
2328 terminate_due_to_signal (SIGABRT
, 40);
2332 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2333 Use binary I/O on systems that care about text vs binary I/O.
2334 Arrange for subprograms to not inherit the file descriptor.
2335 Prefer a method that is multithread-safe, if available.
2336 Do not fail merely because the open was interrupted by a signal.
2337 Allow the user to quit. */
2340 emacs_open (const char *file
, int oflags
, int mode
)
2343 if (! (oflags
& O_TEXT
))
2345 oflags
|= O_CLOEXEC
;
2346 while ((fd
= open (file
, oflags
, mode
)) < 0 && errno
== EINTR
)
2348 if (! O_CLOEXEC
&& 0 <= fd
)
2349 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
2353 /* Open FILE as a stream for Emacs use, with mode MODE.
2354 Act like emacs_open with respect to threads, signals, and quits. */
2357 emacs_fopen (char const *file
, char const *mode
)
2359 int fd
, omode
, oflags
;
2361 char const *m
= mode
;
2365 case 'r': omode
= O_RDONLY
; oflags
= 0; break;
2366 case 'w': omode
= O_WRONLY
; oflags
= O_CREAT
| O_TRUNC
; break;
2367 case 'a': omode
= O_WRONLY
; oflags
= O_CREAT
| O_APPEND
; break;
2368 default: emacs_abort ();
2374 case '+': omode
= O_RDWR
; break;
2375 case 't': bflag
= O_TEXT
; break;
2376 default: /* Ignore. */ break;
2379 fd
= emacs_open (file
, omode
| oflags
| bflag
, 0666);
2380 return fd
< 0 ? 0 : fdopen (fd
, mode
);
2383 /* Create a pipe for Emacs use. */
2386 emacs_pipe (int fd
[2])
2391 int result
= pipe2 (fd
, O_BINARY
| O_CLOEXEC
);
2392 if (! O_CLOEXEC
&& result
== 0)
2394 fcntl (fd
[0], F_SETFD
, FD_CLOEXEC
);
2395 fcntl (fd
[1], F_SETFD
, FD_CLOEXEC
);
2401 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2402 For the background behind this mess, please see Austin Group defect 529
2403 <http://austingroupbugs.net/view.php?id=529>. */
2405 #ifndef POSIX_CLOSE_RESTART
2406 # define POSIX_CLOSE_RESTART 1
2408 posix_close (int fd
, int flag
)
2410 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2411 eassert (flag
== POSIX_CLOSE_RESTART
);
2413 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2414 on a system that does not define POSIX_CLOSE_RESTART.
2416 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2417 closed, and retrying the close could inadvertently close a file
2418 descriptor allocated by some other thread. In other systems
2419 (e.g., HP/UX) FD is not closed. And in still other systems
2420 (e.g., OS X, Solaris), maybe FD is closed, maybe not, and in a
2421 multithreaded program there can be no way to tell.
2423 So, in this case, pretend that the close succeeded. This works
2424 well on systems like GNU/Linux that close FD. Although it may
2425 leak a file descriptor on other systems, the leak is unlikely and
2426 it's better to leak than to close a random victim. */
2427 return close (fd
) == 0 || errno
== EINTR
? 0 : -1;
2431 /* Close FD, retrying if interrupted. If successful, return 0;
2432 otherwise, return -1 and set errno to a non-EINTR value. Consider
2433 an EINPROGRESS error to be successful, as that's merely a signal
2434 arriving. FD is always closed when this function returns, even
2437 Do not call this function if FD is nonnegative and might already be closed,
2438 as that might close an innocent victim opened by some other thread. */
2441 emacs_close (int fd
)
2445 int r
= posix_close (fd
, POSIX_CLOSE_RESTART
);
2448 if (!POSIX_CLOSE_RESTART
|| errno
!= EINTR
)
2450 eassert (errno
!= EBADF
|| fd
< 0);
2451 return errno
== EINPROGRESS
? 0 : r
;
2456 /* Maximum number of bytes to read or write in a single system call.
2457 This works around a serious bug in Linux kernels before 2.6.16; see
2458 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2459 It's likely to work around similar bugs in other operating systems, so do it
2460 on all platforms. Round INT_MAX down to a page size, with the conservative
2461 assumption that page sizes are at most 2**18 bytes (any kernel with a
2462 page size larger than that shouldn't have the bug). */
2463 #ifndef MAX_RW_COUNT
2464 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2467 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2468 Return the number of bytes read, which might be less than NBYTE.
2469 On error, set errno and return -1. */
2471 emacs_read (int fildes
, void *buf
, ptrdiff_t nbyte
)
2475 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2476 passes a size that large to emacs_read. */
2478 while ((rtnval
= read (fildes
, buf
, nbyte
)) == -1
2479 && (errno
== EINTR
))
2484 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2485 or if a partial write occurs. If interrupted, process pending
2486 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2487 errno if this is less than NBYTE. */
2489 emacs_full_write (int fildes
, char const *buf
, ptrdiff_t nbyte
,
2490 bool process_signals
)
2492 ptrdiff_t bytes_written
= 0;
2496 ssize_t n
= write (fildes
, buf
, min (nbyte
, MAX_RW_COUNT
));
2502 /* I originally used `QUIT' but that might cause files to
2503 be truncated if you hit C-g in the middle of it. --Stef */
2504 if (process_signals
&& pending_signals
)
2505 process_pending_signals ();
2517 return bytes_written
;
2520 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2521 interrupted or if a partial write occurs. Return the number of
2522 bytes written, setting errno if this is less than NBYTE. */
2524 emacs_write (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2526 return emacs_full_write (fildes
, buf
, nbyte
, 0);
2529 /* Like emacs_write, but also process pending signals if interrupted. */
2531 emacs_write_sig (int fildes
, void const *buf
, ptrdiff_t nbyte
)
2533 return emacs_full_write (fildes
, buf
, nbyte
, 1);
2536 /* Write a diagnostic to standard error that contains MESSAGE and a
2537 string derived from errno. Preserve errno. Do not buffer stderr.
2538 Do not process pending signals if interrupted. */
2540 emacs_perror (char const *message
)
2543 char const *error_string
= emacs_strerror (err
);
2544 char const *command
= (initial_argv
&& initial_argv
[0]
2545 ? initial_argv
[0] : "emacs");
2546 /* Write it out all at once, if it's short; this is less likely to
2547 be interleaved with other output. */
2549 int nbytes
= snprintf (buf
, sizeof buf
, "%s: %s: %s\n",
2550 command
, message
, error_string
);
2551 if (0 <= nbytes
&& nbytes
< BUFSIZ
)
2552 emacs_write (STDERR_FILENO
, buf
, nbytes
);
2555 emacs_write (STDERR_FILENO
, command
, strlen (command
));
2556 emacs_write (STDERR_FILENO
, ": ", 2);
2557 emacs_write (STDERR_FILENO
, message
, strlen (message
));
2558 emacs_write (STDERR_FILENO
, ": ", 2);
2559 emacs_write (STDERR_FILENO
, error_string
, strlen (error_string
));
2560 emacs_write (STDERR_FILENO
, "\n", 1);
2565 /* Return a struct timeval that is roughly equivalent to T.
2566 Use the least timeval not less than T.
2567 Return an extremal value if the result would overflow. */
2569 make_timeval (struct timespec t
)
2572 tv
.tv_sec
= t
.tv_sec
;
2573 tv
.tv_usec
= t
.tv_nsec
/ 1000;
2575 if (t
.tv_nsec
% 1000 != 0)
2577 if (tv
.tv_usec
< 999999)
2579 else if (tv
.tv_sec
< TYPE_MAXIMUM (time_t))
2589 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2590 ATIME and MTIME, respectively.
2591 FD must be either negative -- in which case it is ignored --
2592 or a file descriptor that is open on FILE.
2593 If FD is nonnegative, then FILE can be NULL. */
2595 set_file_times (int fd
, const char *filename
,
2596 struct timespec atime
, struct timespec mtime
)
2598 struct timespec timespec
[2];
2599 timespec
[0] = atime
;
2600 timespec
[1] = mtime
;
2601 return fdutimens (fd
, filename
, timespec
);
2604 /* Like strsignal, except async-signal-safe, and this function typically
2605 returns a string in the C locale rather than the current locale. */
2607 safe_strsignal (int code
)
2609 char const *signame
= 0;
2611 if (0 <= code
&& code
< sys_siglist_entries
)
2612 signame
= sys_siglist
[code
];
2614 signame
= "Unknown signal";
2620 /* For make-serial-process */
2622 serial_open (Lisp_Object port
)
2624 int fd
= emacs_open (SSDATA (port
), O_RDWR
| O_NOCTTY
| O_NONBLOCK
, 0);
2626 report_file_error ("Opening serial port", port
);
2628 ioctl (fd
, TIOCEXCL
, (char *) 0);
2634 #if !defined (HAVE_CFMAKERAW)
2635 /* Workaround for targets which are missing cfmakeraw. */
2636 /* Pasted from man page. */
2638 cfmakeraw (struct termios
*termios_p
)
2640 termios_p
->c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2641 termios_p
->c_oflag
&= ~OPOST
;
2642 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2643 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2644 termios_p
->c_cflag
|= CS8
;
2646 #endif /* !defined (HAVE_CFMAKERAW */
2648 #if !defined (HAVE_CFSETSPEED)
2649 /* Workaround for targets which are missing cfsetspeed. */
2651 cfsetspeed (struct termios
*termios_p
, speed_t vitesse
)
2653 return (cfsetispeed (termios_p
, vitesse
)
2654 + cfsetospeed (termios_p
, vitesse
));
2658 /* For serial-process-configure */
2660 serial_configure (struct Lisp_Process
*p
,
2661 Lisp_Object contact
)
2663 Lisp_Object childp2
= Qnil
;
2664 Lisp_Object tem
= Qnil
;
2665 struct termios attr
;
2667 char summary
[4] = "???"; /* This usually becomes "8N1". */
2669 childp2
= Fcopy_sequence (p
->childp
);
2671 /* Read port attributes and prepare default configuration. */
2672 err
= tcgetattr (p
->outfd
, &attr
);
2674 report_file_error ("Failed tcgetattr", Qnil
);
2676 #if defined (CLOCAL)
2677 attr
.c_cflag
|= CLOCAL
;
2680 attr
.c_cflag
|= CREAD
;
2683 /* Configure speed. */
2684 if (!NILP (Fplist_member (contact
, QCspeed
)))
2685 tem
= Fplist_get (contact
, QCspeed
);
2687 tem
= Fplist_get (p
->childp
, QCspeed
);
2689 err
= cfsetspeed (&attr
, XINT (tem
));
2691 report_file_error ("Failed cfsetspeed", tem
);
2692 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
2694 /* Configure bytesize. */
2695 if (!NILP (Fplist_member (contact
, QCbytesize
)))
2696 tem
= Fplist_get (contact
, QCbytesize
);
2698 tem
= Fplist_get (p
->childp
, QCbytesize
);
2700 tem
= make_number (8);
2702 if (XINT (tem
) != 7 && XINT (tem
) != 8)
2703 error (":bytesize must be nil (8), 7, or 8");
2704 summary
[0] = XINT (tem
) + '0';
2705 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2706 attr
.c_cflag
&= ~CSIZE
;
2707 attr
.c_cflag
|= ((XINT (tem
) == 7) ? CS7
: CS8
);
2709 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2710 if (XINT (tem
) != 8)
2711 error ("Bytesize cannot be changed");
2713 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
2715 /* Configure parity. */
2716 if (!NILP (Fplist_member (contact
, QCparity
)))
2717 tem
= Fplist_get (contact
, QCparity
);
2719 tem
= Fplist_get (p
->childp
, QCparity
);
2720 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
2721 error (":parity must be nil (no parity), `even', or `odd'");
2722 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2723 attr
.c_cflag
&= ~(PARENB
| PARODD
);
2724 attr
.c_iflag
&= ~(IGNPAR
| INPCK
);
2729 else if (EQ (tem
, Qeven
))
2732 attr
.c_cflag
|= PARENB
;
2733 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2735 else if (EQ (tem
, Qodd
))
2738 attr
.c_cflag
|= (PARENB
| PARODD
);
2739 attr
.c_iflag
|= (IGNPAR
| INPCK
);
2742 /* Don't error on no parity, which should be set by cfmakeraw. */
2744 error ("Parity cannot be configured");
2746 childp2
= Fplist_put (childp2
, QCparity
, tem
);
2748 /* Configure stopbits. */
2749 if (!NILP (Fplist_member (contact
, QCstopbits
)))
2750 tem
= Fplist_get (contact
, QCstopbits
);
2752 tem
= Fplist_get (p
->childp
, QCstopbits
);
2754 tem
= make_number (1);
2756 if (XINT (tem
) != 1 && XINT (tem
) != 2)
2757 error (":stopbits must be nil (1 stopbit), 1, or 2");
2758 summary
[2] = XINT (tem
) + '0';
2759 #if defined (CSTOPB)
2760 attr
.c_cflag
&= ~CSTOPB
;
2761 if (XINT (tem
) == 2)
2762 attr
.c_cflag
|= CSTOPB
;
2764 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2765 if (XINT (tem
) != 1)
2766 error ("Stopbits cannot be configured");
2768 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
2770 /* Configure flowcontrol. */
2771 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
2772 tem
= Fplist_get (contact
, QCflowcontrol
);
2774 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
2775 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
2776 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2777 #if defined (CRTSCTS)
2778 attr
.c_cflag
&= ~CRTSCTS
;
2780 #if defined (CNEW_RTSCTS)
2781 attr
.c_cflag
&= ~CNEW_RTSCTS
;
2783 #if defined (IXON) && defined (IXOFF)
2784 attr
.c_iflag
&= ~(IXON
| IXOFF
);
2788 /* Already configured. */
2790 else if (EQ (tem
, Qhw
))
2792 #if defined (CRTSCTS)
2793 attr
.c_cflag
|= CRTSCTS
;
2794 #elif defined (CNEW_RTSCTS)
2795 attr
.c_cflag
|= CNEW_RTSCTS
;
2797 error ("Hardware flowcontrol (RTS/CTS) not supported");
2800 else if (EQ (tem
, Qsw
))
2802 #if defined (IXON) && defined (IXOFF)
2803 attr
.c_iflag
|= (IXON
| IXOFF
);
2805 error ("Software flowcontrol (XON/XOFF) not supported");
2808 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
2810 /* Activate configuration. */
2811 err
= tcsetattr (p
->outfd
, TCSANOW
, &attr
);
2813 report_file_error ("Failed tcsetattr", Qnil
);
2815 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
2816 pset_childp (p
, childp2
);
2818 #endif /* not DOS_NT */
2820 /* System depended enumeration of and access to system processes a-la ps(1). */
2824 /* Process enumeration and access via /proc. */
2827 list_system_processes (void)
2829 Lisp_Object procdir
, match
, proclist
, next
;
2832 /* For every process on the system, there's a directory in the
2833 "/proc" pseudo-directory whose name is the numeric ID of that
2835 procdir
= build_string ("/proc");
2836 match
= build_string ("[0-9]+");
2837 proclist
= directory_files_internal (procdir
, Qnil
, match
, Qt
, 0, Qnil
);
2839 /* `proclist' gives process IDs as strings. Destructively convert
2840 each string into a number. */
2841 for (tail
= proclist
; CONSP (tail
); tail
= next
)
2844 XSETCAR (tail
, Fstring_to_number (XCAR (tail
), Qnil
));
2847 /* directory_files_internal returns the files in reverse order; undo
2849 proclist
= Fnreverse (proclist
);
2853 #elif defined DARWIN_OS || defined __FreeBSD__
2856 list_system_processes (void)
2859 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
};
2861 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PROC
};
2864 struct kinfo_proc
*procs
;
2867 Lisp_Object proclist
= Qnil
;
2869 if (sysctl (mib
, 3, NULL
, &len
, NULL
, 0) != 0)
2872 procs
= xmalloc (len
);
2873 if (sysctl (mib
, 3, procs
, &len
, NULL
, 0) != 0)
2879 len
/= sizeof (struct kinfo_proc
);
2880 for (i
= 0; i
< len
; i
++)
2883 proclist
= Fcons (make_fixnum_or_float (procs
[i
].kp_proc
.p_pid
), proclist
);
2885 proclist
= Fcons (make_fixnum_or_float (procs
[i
].ki_pid
), proclist
);
2894 /* The WINDOWSNT implementation is in w32.c.
2895 The MSDOS implementation is in dosfns.c. */
2896 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2899 list_system_processes (void)
2904 #endif /* !defined (WINDOWSNT) */
2906 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2907 static struct timespec
2908 time_from_jiffies (unsigned long long tval
, long hz
)
2910 unsigned long long s
= tval
/ hz
;
2911 unsigned long long frac
= tval
% hz
;
2914 if (TYPE_MAXIMUM (time_t) < s
)
2916 if (LONG_MAX
- 1 <= ULLONG_MAX
/ TIMESPEC_RESOLUTION
2917 || frac
<= ULLONG_MAX
/ TIMESPEC_RESOLUTION
)
2918 ns
= frac
* TIMESPEC_RESOLUTION
/ hz
;
2921 /* This is reachable only in the unlikely case that HZ * HZ
2922 exceeds ULLONG_MAX. It calculates an approximation that is
2923 guaranteed to be in range. */
2924 long hz_per_ns
= (hz
/ TIMESPEC_RESOLUTION
2925 + (hz
% TIMESPEC_RESOLUTION
!= 0));
2926 ns
= frac
/ hz_per_ns
;
2929 return make_timespec (s
, ns
);
2933 ltime_from_jiffies (unsigned long long tval
, long hz
)
2935 struct timespec t
= time_from_jiffies (tval
, hz
);
2936 return make_lisp_time (t
);
2939 static struct timespec
2943 struct timespec up
= make_timespec (0, 0);
2946 fup
= emacs_fopen ("/proc/uptime", "r");
2950 unsigned long long upsec
, upfrac
, idlesec
, idlefrac
;
2951 int upfrac_start
, upfrac_end
, idlefrac_start
, idlefrac_end
;
2953 if (fscanf (fup
, "%llu.%n%llu%n %llu.%n%llu%n",
2954 &upsec
, &upfrac_start
, &upfrac
, &upfrac_end
,
2955 &idlesec
, &idlefrac_start
, &idlefrac
, &idlefrac_end
)
2958 if (TYPE_MAXIMUM (time_t) < upsec
)
2960 upsec
= TYPE_MAXIMUM (time_t);
2961 upfrac
= TIMESPEC_RESOLUTION
- 1;
2965 int upfraclen
= upfrac_end
- upfrac_start
;
2966 for (; upfraclen
< LOG10_TIMESPEC_RESOLUTION
; upfraclen
++)
2968 for (; LOG10_TIMESPEC_RESOLUTION
< upfraclen
; upfraclen
--)
2970 upfrac
= min (upfrac
, TIMESPEC_RESOLUTION
- 1);
2972 up
= make_timespec (upsec
, upfrac
);
2981 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2982 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2985 procfs_ttyname (int rdev
)
2988 char name
[PATH_MAX
];
2991 fdev
= emacs_fopen ("/proc/tty/drivers", "r");
2997 unsigned long minor_beg
, minor_end
;
2998 char minor
[25]; /* 2 32-bit numbers + dash */
3001 for (; !feof (fdev
) && !ferror (fdev
); name
[0] = 0)
3003 if (fscanf (fdev
, "%*s %s %u %s %*s\n", name
, &major
, minor
) >= 3
3004 && major
== MAJOR (rdev
))
3006 minor_beg
= strtoul (minor
, &endp
, 0);
3008 minor_end
= minor_beg
;
3009 else if (*endp
== '-')
3010 minor_end
= strtoul (endp
+ 1, &endp
, 0);
3014 if (MINOR (rdev
) >= minor_beg
&& MINOR (rdev
) <= minor_end
)
3016 sprintf (name
+ strlen (name
), "%u", MINOR (rdev
));
3024 return build_string (name
);
3028 procfs_get_total_memory (void)
3031 uintmax_t retval
= 2 * 1024 * 1024; /* default: 2 GiB */
3035 fmem
= emacs_fopen ("/proc/meminfo", "r");
3039 uintmax_t entry_value
;
3043 switch (fscanf (fmem
, "MemTotal: %"SCNuMAX
, &entry_value
))
3046 retval
= entry_value
;
3051 while ((c
= getc (fmem
)) != EOF
&& c
!= '\n')
3069 system_process_attributes (Lisp_Object pid
)
3071 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3075 long clocks_per_sec
;
3077 char procbuf
[1025], *p
, *q
;
3080 static char const default_cmd
[] = "???";
3081 const char *cmd
= default_cmd
;
3082 int cmdsize
= sizeof default_cmd
- 1;
3083 char *cmdline
= NULL
;
3084 ptrdiff_t cmdline_size
;
3087 int ppid
, pgrp
, sess
, tty
, tpgid
, thcount
;
3090 unsigned long long u_time
, s_time
, cutime
, cstime
, start
;
3091 long priority
, niceness
, rss
;
3092 unsigned long minflt
, majflt
, cminflt
, cmajflt
, vsize
;
3093 struct timespec tnow
, tstart
, tboot
, telapsed
, us_time
;
3095 Lisp_Object attrs
= Qnil
;
3096 Lisp_Object decoded_cmd
;
3099 CHECK_NUMBER_OR_FLOAT (pid
);
3100 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3101 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3102 if (stat (procfn
, &st
) < 0)
3107 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3109 pw
= getpwuid (uid
);
3112 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3115 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3117 gr
= getgrgid (gid
);
3120 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3122 count
= SPECPDL_INDEX ();
3123 strcpy (fn
, procfn
);
3124 procfn_end
= fn
+ strlen (fn
);
3125 strcpy (procfn_end
, "/stat");
3126 fd
= emacs_open (fn
, O_RDONLY
, 0);
3131 record_unwind_protect_int (close_file_unwind
, fd
);
3132 nread
= emacs_read (fd
, procbuf
, sizeof procbuf
- 1);
3136 procbuf
[nread
] = '\0';
3139 p
= strchr (p
, '(');
3142 q
= strrchr (p
+ 1, ')');
3152 /* Command name is encoded in locale-coding-system; decode it. */
3153 AUTO_STRING_WITH_LEN (cmd_str
, cmd
, cmdsize
);
3154 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3155 Vlocale_coding_system
, 0);
3156 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3158 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3159 utime stime cutime cstime priority nice thcount . start vsize rss */
3161 && (sscanf (q
+ 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3162 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3163 &c
, &ppid
, &pgrp
, &sess
, &tty
, &tpgid
,
3164 &minflt
, &cminflt
, &majflt
, &cmajflt
,
3165 &u_time
, &s_time
, &cutime
, &cstime
,
3166 &priority
, &niceness
, &thcount
, &start
, &vsize
, &rss
)
3171 state_str
[1] = '\0';
3172 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3173 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (ppid
)), attrs
);
3174 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pgrp
)), attrs
);
3175 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (sess
)), attrs
);
3176 attrs
= Fcons (Fcons (Qttname
, procfs_ttyname (tty
)), attrs
);
3177 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (tpgid
)), attrs
);
3178 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (minflt
)), attrs
);
3179 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (majflt
)), attrs
);
3180 attrs
= Fcons (Fcons (Qcminflt
, make_fixnum_or_float (cminflt
)),
3182 attrs
= Fcons (Fcons (Qcmajflt
, make_fixnum_or_float (cmajflt
)),
3184 clocks_per_sec
= sysconf (_SC_CLK_TCK
);
3185 if (clocks_per_sec
< 0)
3186 clocks_per_sec
= 100;
3187 attrs
= Fcons (Fcons (Qutime
,
3188 ltime_from_jiffies (u_time
, clocks_per_sec
)),
3190 attrs
= Fcons (Fcons (Qstime
,
3191 ltime_from_jiffies (s_time
, clocks_per_sec
)),
3193 attrs
= Fcons (Fcons (Qtime
,
3194 ltime_from_jiffies (s_time
+ u_time
,
3197 attrs
= Fcons (Fcons (Qcutime
,
3198 ltime_from_jiffies (cutime
, clocks_per_sec
)),
3200 attrs
= Fcons (Fcons (Qcstime
,
3201 ltime_from_jiffies (cstime
, clocks_per_sec
)),
3203 attrs
= Fcons (Fcons (Qctime
,
3204 ltime_from_jiffies (cstime
+ cutime
,
3207 attrs
= Fcons (Fcons (Qpri
, make_number (priority
)), attrs
);
3208 attrs
= Fcons (Fcons (Qnice
, make_number (niceness
)), attrs
);
3209 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (thcount
)),
3211 tnow
= current_timespec ();
3212 telapsed
= get_up_time ();
3213 tboot
= timespec_sub (tnow
, telapsed
);
3214 tstart
= time_from_jiffies (start
, clocks_per_sec
);
3215 tstart
= timespec_add (tboot
, tstart
);
3216 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (tstart
)), attrs
);
3217 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (vsize
/ 1024)),
3219 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (4 * rss
)), attrs
);
3220 telapsed
= timespec_sub (tnow
, tstart
);
3221 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (telapsed
)), attrs
);
3222 us_time
= time_from_jiffies (u_time
+ s_time
, clocks_per_sec
);
3223 pcpu
= timespectod (us_time
) / timespectod (telapsed
);
3226 attrs
= Fcons (Fcons (Qpcpu
, make_float (100 * pcpu
)), attrs
);
3227 pmem
= 4.0 * 100 * rss
/ procfs_get_total_memory ();
3230 attrs
= Fcons (Fcons (Qpmem
, make_float (pmem
)), attrs
);
3233 unbind_to (count
, Qnil
);
3236 strcpy (procfn_end
, "/cmdline");
3237 fd
= emacs_open (fn
, O_RDONLY
, 0);
3240 ptrdiff_t readsize
, nread_incr
;
3241 record_unwind_protect_int (close_file_unwind
, fd
);
3242 record_unwind_protect_nothing ();
3243 nread
= cmdline_size
= 0;
3247 cmdline
= xpalloc (cmdline
, &cmdline_size
, 2, STRING_BYTES_BOUND
, 1);
3248 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3250 /* Leave room even if every byte needs escaping below. */
3251 readsize
= (cmdline_size
>> 1) - nread
;
3253 nread_incr
= emacs_read (fd
, cmdline
+ nread
, readsize
);
3254 nread
+= max (0, nread_incr
);
3256 while (nread_incr
== readsize
);
3260 /* We don't want trailing null characters. */
3261 for (p
= cmdline
+ nread
; cmdline
< p
&& !p
[-1]; p
--)
3264 /* Escape-quote whitespace and backslashes. */
3265 q
= cmdline
+ cmdline_size
;
3270 if (c_isspace (c
) || c
== '\\')
3274 nread
= cmdline
+ cmdline_size
- q
;
3279 nread
= cmdsize
+ 2;
3280 cmdline_size
= nread
+ 1;
3281 q
= cmdline
= xrealloc (cmdline
, cmdline_size
);
3282 set_unwind_protect_ptr (count
+ 1, xfree
, cmdline
);
3283 sprintf (cmdline
, "[%.*s]", cmdsize
, cmd
);
3285 /* Command line is encoded in locale-coding-system; decode it. */
3286 AUTO_STRING_WITH_LEN (cmd_str
, q
, nread
);
3287 decoded_cmd
= code_convert_string_norecord (cmd_str
,
3288 Vlocale_coding_system
, 0);
3289 unbind_to (count
, Qnil
);
3290 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3296 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3298 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3299 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3300 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3301 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3302 #undef _FILE_OFFSET_BITS
3304 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3309 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3310 #define _FILE_OFFSET_BITS 64
3311 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3313 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3316 system_process_attributes (Lisp_Object pid
)
3318 char procfn
[PATH_MAX
], fn
[PATH_MAX
];
3323 struct psinfo pinfo
;
3329 Lisp_Object attrs
= Qnil
;
3330 Lisp_Object decoded_cmd
;
3333 CHECK_NUMBER_OR_FLOAT (pid
);
3334 CONS_TO_INTEGER (pid
, pid_t
, proc_id
);
3335 sprintf (procfn
, "/proc/%"pMd
, proc_id
);
3336 if (stat (procfn
, &st
) < 0)
3341 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3343 pw
= getpwuid (uid
);
3346 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3349 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3351 gr
= getgrgid (gid
);
3354 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3356 count
= SPECPDL_INDEX ();
3357 strcpy (fn
, procfn
);
3358 procfn_end
= fn
+ strlen (fn
);
3359 strcpy (procfn_end
, "/psinfo");
3360 fd
= emacs_open (fn
, O_RDONLY
, 0);
3365 record_unwind_protect (close_file_unwind
, fd
);
3366 nread
= emacs_read (fd
, &pinfo
, sizeof pinfo
);
3369 if (nread
== sizeof pinfo
)
3371 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (pinfo
.pr_ppid
)), attrs
);
3372 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (pinfo
.pr_pgid
)), attrs
);
3373 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (pinfo
.pr_sid
)), attrs
);
3377 state_str
[0] = pinfo
.pr_lwp
.pr_sname
;
3378 state_str
[1] = '\0';
3379 attrs
= Fcons (Fcons (Qstate
, build_string (state_str
)), attrs
);
3382 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3383 need to get a string from it. */
3385 /* FIXME: missing: Qtpgid */
3397 Are they available? */
3399 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (pinfo
.pr_time
)), attrs
);
3400 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (pinfo
.pr_ctime
)), attrs
);
3401 attrs
= Fcons (Fcons (Qpri
, make_number (pinfo
.pr_lwp
.pr_pri
)), attrs
);
3402 attrs
= Fcons (Fcons (Qnice
, make_number (pinfo
.pr_lwp
.pr_nice
)), attrs
);
3403 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (pinfo
.pr_nlwp
)),
3406 attrs
= Fcons (Fcons (Qstart
, make_lisp_time (pinfo
.pr_start
)), attrs
);
3407 attrs
= Fcons (Fcons (Qvsize
, make_fixnum_or_float (pinfo
.pr_size
)),
3409 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (pinfo
.pr_rssize
)),
3412 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3413 range 0 .. 2**15, representing 0.0 .. 1.0. */
3414 attrs
= Fcons (Fcons (Qpcpu
,
3415 make_float (100.0 / 0x8000 * pinfo
.pr_pctcpu
)),
3417 attrs
= Fcons (Fcons (Qpmem
,
3418 make_float (100.0 / 0x8000 * pinfo
.pr_pctmem
)),
3421 AUTO_STRING (fname
, pinfo
.pr_fname
);
3422 decoded_cmd
= code_convert_string_norecord (fname
,
3423 Vlocale_coding_system
, 0);
3424 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
3425 AUTO_STRING (psargs
, pinfo
.pr_psargs
);
3426 decoded_cmd
= code_convert_string_norecord (psargs
,
3427 Vlocale_coding_system
, 0);
3428 attrs
= Fcons (Fcons (Qargs
, decoded_cmd
), attrs
);
3430 unbind_to (count
, Qnil
);
3434 #elif defined __FreeBSD__
3436 static struct timespec
3437 timeval_to_timespec (struct timeval t
)
3439 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3443 make_lisp_timeval (struct timeval t
)
3445 return make_lisp_time (timeval_to_timespec (t
));
3449 system_process_attributes (Lisp_Object pid
)
3452 int pagesize
= getpagesize ();
3453 unsigned long npages
;
3459 char args
[MAXPATHLEN
];
3460 struct timespec t
, now
;
3462 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3463 struct kinfo_proc proc
;
3464 size_t proclen
= sizeof proc
;
3466 Lisp_Object attrs
= Qnil
;
3467 Lisp_Object decoded_comm
;
3469 CHECK_NUMBER_OR_FLOAT (pid
);
3470 CONS_TO_INTEGER (pid
, int, proc_id
);
3473 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3476 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (proc
.ki_uid
)), attrs
);
3479 pw
= getpwuid (proc
.ki_uid
);
3482 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3484 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (proc
.ki_svgid
)), attrs
);
3487 gr
= getgrgid (proc
.ki_svgid
);
3490 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3492 AUTO_STRING (comm
, proc
.ki_comm
);
3493 decoded_comm
= code_convert_string_norecord (comm
, Vlocale_coding_system
, 0);
3495 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3497 char state
[2] = {'\0', '\0'};
3498 switch (proc
.ki_stat
)
3520 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3523 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.ki_ppid
)), attrs
);
3524 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.ki_pgid
)), attrs
);
3525 attrs
= Fcons (Fcons (Qsess
, make_fixnum_or_float (proc
.ki_sid
)), attrs
);
3528 ttyname
= proc
.ki_tdev
== NODEV
? NULL
: devname (proc
.ki_tdev
, S_IFCHR
);
3531 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3533 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.ki_tpgid
)), attrs
);
3534 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_minflt
)), attrs
);
3535 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (proc
.ki_rusage
.ru_majflt
)), attrs
);
3536 attrs
= Fcons (Fcons (Qcminflt
, make_number (proc
.ki_rusage_ch
.ru_minflt
)), attrs
);
3537 attrs
= Fcons (Fcons (Qcmajflt
, make_number (proc
.ki_rusage_ch
.ru_majflt
)), attrs
);
3539 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (proc
.ki_rusage
.ru_utime
)),
3541 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (proc
.ki_rusage
.ru_stime
)),
3543 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage
.ru_utime
),
3544 timeval_to_timespec (proc
.ki_rusage
.ru_stime
));
3545 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3547 attrs
= Fcons (Fcons (Qcutime
,
3548 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3550 attrs
= Fcons (Fcons (Qcstime
,
3551 make_lisp_timeval (proc
.ki_rusage_ch
.ru_utime
)),
3553 t
= timespec_add (timeval_to_timespec (proc
.ki_rusage_ch
.ru_utime
),
3554 timeval_to_timespec (proc
.ki_rusage_ch
.ru_stime
));
3555 attrs
= Fcons (Fcons (Qctime
, make_lisp_time (t
)), attrs
);
3557 attrs
= Fcons (Fcons (Qthcount
, make_fixnum_or_float (proc
.ki_numthreads
)),
3559 attrs
= Fcons (Fcons (Qpri
, make_number (proc
.ki_pri
.pri_native
)), attrs
);
3560 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.ki_nice
)), attrs
);
3561 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (proc
.ki_start
)), attrs
);
3562 attrs
= Fcons (Fcons (Qvsize
, make_number (proc
.ki_size
>> 10)), attrs
);
3563 attrs
= Fcons (Fcons (Qrss
, make_number (proc
.ki_rssize
* pagesize
>> 10)),
3566 now
= current_timespec ();
3567 t
= timespec_sub (now
, timeval_to_timespec (proc
.ki_start
));
3568 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3570 len
= sizeof fscale
;
3571 if (sysctlbyname ("kern.fscale", &fscale
, &len
, NULL
, 0) == 0)
3576 if (sysctlbyname ("kern.ccpu", &ccpu
, &len
, NULL
, 0) == 0)
3578 pcpu
= (100.0 * proc
.ki_pctcpu
/ fscale
3579 / (1 - exp (proc
.ki_swtime
* log ((double) ccpu
/ fscale
))));
3580 attrs
= Fcons (Fcons (Qpcpu
, make_fixnum_or_float (pcpu
)), attrs
);
3584 len
= sizeof npages
;
3585 if (sysctlbyname ("hw.availpages", &npages
, &len
, NULL
, 0) == 0)
3587 double pmem
= (proc
.ki_flag
& P_INMEM
3588 ? 100.0 * proc
.ki_rssize
/ npages
3590 attrs
= Fcons (Fcons (Qpmem
, make_fixnum_or_float (pmem
)), attrs
);
3593 mib
[2] = KERN_PROC_ARGS
;
3595 if (sysctl (mib
, 4, args
, &len
, NULL
, 0) == 0)
3598 for (i
= 0; i
< len
; i
++)
3600 if (! args
[i
] && i
< len
- 1)
3604 AUTO_STRING (comm
, args
);
3605 decoded_comm
= code_convert_string_norecord (comm
,
3606 Vlocale_coding_system
, 0);
3608 attrs
= Fcons (Fcons (Qargs
, decoded_comm
), attrs
);
3614 #elif defined DARWIN_OS
3616 static struct timespec
3617 timeval_to_timespec (struct timeval t
)
3619 return make_timespec (t
.tv_sec
, t
.tv_usec
* 1000);
3623 make_lisp_timeval (struct timeval t
)
3625 return make_lisp_time (timeval_to_timespec (t
));
3629 system_process_attributes (Lisp_Object pid
)
3632 int pagesize
= getpagesize ();
3633 unsigned long npages
;
3639 char args
[MAXPATHLEN
];
3640 struct timeval starttime
;
3641 struct timespec t
, now
;
3642 struct rusage
*rusage
;
3647 int mib
[4] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
};
3648 struct kinfo_proc proc
;
3649 size_t proclen
= sizeof proc
;
3651 Lisp_Object attrs
= Qnil
;
3652 Lisp_Object decoded_comm
;
3654 CHECK_NUMBER_OR_FLOAT (pid
);
3655 CONS_TO_INTEGER (pid
, int, proc_id
);
3658 if (sysctl (mib
, 4, &proc
, &proclen
, NULL
, 0) != 0)
3661 uid
= proc
.kp_eproc
.e_ucred
.cr_uid
;
3662 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (uid
)), attrs
);
3665 pw
= getpwuid (uid
);
3668 attrs
= Fcons (Fcons (Quser
, build_string (pw
->pw_name
)), attrs
);
3670 gid
= proc
.kp_eproc
.e_pcred
.p_svgid
;
3671 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (gid
)), attrs
);
3674 gr
= getgrgid (gid
);
3677 attrs
= Fcons (Fcons (Qgroup
, build_string (gr
->gr_name
)), attrs
);
3679 decoded_comm
= (code_convert_string_norecord
3680 (build_unibyte_string (proc
.kp_proc
.p_comm
),
3681 Vlocale_coding_system
, 0));
3683 attrs
= Fcons (Fcons (Qcomm
, decoded_comm
), attrs
);
3685 char state
[2] = {'\0', '\0'};
3686 switch (proc
.kp_proc
.p_stat
)
3708 attrs
= Fcons (Fcons (Qstate
, build_string (state
)), attrs
);
3711 attrs
= Fcons (Fcons (Qppid
, make_fixnum_or_float (proc
.kp_eproc
.e_ppid
)),
3713 attrs
= Fcons (Fcons (Qpgrp
, make_fixnum_or_float (proc
.kp_eproc
.e_pgid
)),
3716 tdev
= proc
.kp_eproc
.e_tdev
;
3718 ttyname
= tdev
== NODEV
? NULL
: devname (tdev
, S_IFCHR
);
3721 attrs
= Fcons (Fcons (Qtty
, build_string (ttyname
)), attrs
);
3723 attrs
= Fcons (Fcons (Qtpgid
, make_fixnum_or_float (proc
.kp_eproc
.e_tpgid
)),
3726 rusage
= proc
.kp_proc
.p_ru
;
3729 attrs
= Fcons (Fcons (Qminflt
, make_fixnum_or_float (rusage
->ru_minflt
)),
3731 attrs
= Fcons (Fcons (Qmajflt
, make_fixnum_or_float (rusage
->ru_majflt
)),
3734 attrs
= Fcons (Fcons (Qutime
, make_lisp_timeval (rusage
->ru_utime
)),
3736 attrs
= Fcons (Fcons (Qstime
, make_lisp_timeval (rusage
->ru_stime
)),
3738 t
= timespec_add (timeval_to_timespec (rusage
->ru_utime
),
3739 timeval_to_timespec (rusage
->ru_stime
));
3740 attrs
= Fcons (Fcons (Qtime
, make_lisp_time (t
)), attrs
);
3743 starttime
= proc
.kp_proc
.p_starttime
;
3744 attrs
= Fcons (Fcons (Qnice
, make_number (proc
.kp_proc
.p_nice
)), attrs
);
3745 attrs
= Fcons (Fcons (Qstart
, make_lisp_timeval (starttime
)), attrs
);
3747 now
= current_timespec ();
3748 t
= timespec_sub (now
, timeval_to_timespec (starttime
));
3749 attrs
= Fcons (Fcons (Qetime
, make_lisp_time (t
)), attrs
);
3754 /* The WINDOWSNT implementation is in w32.c.
3755 The MSDOS implementation is in dosfns.c. */
3756 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3759 system_process_attributes (Lisp_Object pid
)
3764 #endif /* !defined (WINDOWSNT) */
3766 /* Wide character string collation. */
3768 #ifdef __STDC_ISO_10646__
3770 # include <wctype.h>
3772 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3773 # include <locale.h>
3776 # define LC_COLLATE 0
3778 # ifndef LC_COLLATE_MASK
3779 # define LC_COLLATE_MASK 0
3784 # ifndef LC_CTYPE_MASK
3785 # define LC_CTYPE_MASK 0
3788 # ifndef HAVE_NEWLOCALE
3794 # define freelocale emacs_freelocale
3795 # define locale_t emacs_locale_t
3796 # define newlocale emacs_newlocale
3797 # define wcscoll_l emacs_wcscoll_l
3798 # define towlower_l emacs_towlower_l
3800 typedef char const *locale_t
;
3803 newlocale (int category_mask
, char const *locale
, locale_t loc
)
3809 freelocale (locale_t loc
)
3814 emacs_setlocale (int category
, char const *locale
)
3816 # ifdef HAVE_SETLOCALE
3818 char *loc
= setlocale (category
, locale
);
3829 wcscoll_l (wchar_t const *a
, wchar_t const *b
, locale_t loc
)
3832 char *oldloc
= emacs_setlocale (LC_COLLATE
, NULL
);
3840 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3841 strcpy (oldcopy
, oldloc
);
3842 if (! emacs_setlocale (LC_COLLATE
, loc
))
3847 result
= wcscoll (a
, b
);
3849 if (! emacs_setlocale (LC_COLLATE
, oldcopy
))
3860 towlower_l (wint_t wc
, locale_t loc
)
3863 char *oldloc
= emacs_setlocale (LC_CTYPE
, NULL
);
3868 char *oldcopy
= SAFE_ALLOCA (strlen (oldloc
) + 1);
3869 strcpy (oldcopy
, oldloc
);
3870 if (emacs_setlocale (LC_CTYPE
, loc
))
3872 result
= towlower (wc
);
3873 emacs_setlocale (LC_COLLATE
, oldcopy
);
3883 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3884 Lisp_Object locale
, Lisp_Object ignore_case
)
3887 ptrdiff_t len
, i
, i_byte
;
3892 /* Convert byte stream to code points. */
3893 len
= SCHARS (s1
); i
= i_byte
= 0;
3894 SAFE_NALLOCA (p1
, 1, len
+ 1);
3896 FETCH_STRING_CHAR_ADVANCE (*(p1
+i
-1), s1
, i
, i_byte
);
3899 len
= SCHARS (s2
); i
= i_byte
= 0;
3900 SAFE_NALLOCA (p2
, 1, len
+ 1);
3902 FETCH_STRING_CHAR_ADVANCE (*(p2
+i
-1), s2
, i
, i_byte
);
3905 if (STRINGP (locale
))
3907 locale_t loc
= newlocale (LC_COLLATE_MASK
| LC_CTYPE_MASK
,
3908 SSDATA (locale
), 0);
3910 error ("Invalid locale %s: %s", SSDATA (locale
), emacs_strerror (errno
));
3912 if (! NILP (ignore_case
))
3913 for (int i
= 1; i
< 3; i
++)
3915 wchar_t *p
= (i
== 1) ? p1
: p2
;
3917 *p
= towlower_l (*p
, loc
);
3921 res
= wcscoll_l (p1
, p2
, loc
);
3927 if (! NILP (ignore_case
))
3928 for (int i
= 1; i
< 3; i
++)
3930 wchar_t *p
= (i
== 1) ? p1
: p2
;
3936 res
= wcscoll (p1
, p2
);
3939 # ifndef HAVE_NEWLOCALE
3941 error ("Invalid locale or string for collation: %s", emacs_strerror (err
));
3944 error ("Invalid string for collation: %s", emacs_strerror (err
));
3950 #endif /* __STDC_ISO_10646__ */
3954 str_collate (Lisp_Object s1
, Lisp_Object s2
,
3955 Lisp_Object locale
, Lisp_Object ignore_case
)
3958 char *loc
= STRINGP (locale
) ? SSDATA (locale
) : NULL
;
3959 int res
, err
= errno
;
3962 res
= w32_compare_strings (SSDATA (s1
), SSDATA (s2
), loc
, !NILP (ignore_case
));
3964 error ("Invalid string for collation: %s", strerror (errno
));
3969 #endif /* WINDOWSNT */