Prevent infinite loop on entering wdired-mode
[emacs.git] / src / sysdep.c
blobf7478253a3555c4f01b892c98a01137caa7381be
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2019 Free Software
3 Foundation, Inc.
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 <https://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <execinfo.h>
23 #include "sysstdio.h"
24 #ifdef HAVE_PWD_H
25 #include <pwd.h>
26 #include <grp.h>
27 #endif /* HAVE_PWD_H */
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
33 #include <close-stream.h>
34 #include <pathmax.h>
35 #include <utimens.h>
37 #include "lisp.h"
38 #include "sheap.h"
39 #include "sysselect.h"
40 #include "blockinput.h"
42 #ifdef HAVE_LINUX_FS_H
43 # include <linux/fs.h>
44 # include <sys/syscall.h>
45 #endif
47 #ifdef CYGWIN
48 # include <cygwin/fs.h>
49 #endif
51 #if defined DARWIN_OS || defined __FreeBSD__
52 # include <sys/sysctl.h>
53 #endif
55 #ifdef __FreeBSD__
56 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
57 'struct frame', so rename it. */
58 # define frame freebsd_frame
59 # include <sys/user.h>
60 # undef frame
62 # include <math.h>
63 #endif
65 #ifdef HAVE_SOCKETS
66 #include <sys/socket.h>
67 #include <netdb.h>
68 #endif /* HAVE_SOCKETS */
70 #ifdef WINDOWSNT
71 #define read sys_read
72 #define write sys_write
73 #ifndef STDERR_FILENO
74 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
75 #endif
76 #include "w32.h"
77 #endif /* WINDOWSNT */
79 #include <sys/types.h>
80 #include <sys/stat.h>
81 #include <errno.h>
83 /* Get SI_SRPC_DOMAIN, if it is available. */
84 #ifdef HAVE_SYS_SYSTEMINFO_H
85 #include <sys/systeminfo.h>
86 #endif
88 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
89 #include "msdos.h"
90 #endif
92 #include <sys/param.h>
93 #include <sys/file.h>
94 #include <fcntl.h>
96 #include "syssignal.h"
97 #include "systime.h"
98 #include "systty.h"
99 #include "syswait.h"
101 #ifdef HAVE_SYS_RESOURCE_H
102 # include <sys/resource.h>
103 #endif
105 #ifdef HAVE_SYS_UTSNAME_H
106 # include <sys/utsname.h>
107 # include <memory.h>
108 #endif
110 #include "keyboard.h"
111 #include "frame.h"
112 #include "termhooks.h"
113 #include "termchar.h"
114 #include "termopts.h"
115 #include "process.h"
116 #include "cm.h"
118 #include "gnutls.h"
119 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
120 do that during startup just to call gnutls_rnd. */
121 #if defined HAVE_GNUTLS && !defined WINDOWSNT
122 # include <gnutls/crypto.h>
123 #else
124 # define emacs_gnutls_global_init() Qnil
125 # define gnutls_rnd(level, data, len) (-1)
126 #endif
128 #ifdef WINDOWSNT
129 # include <direct.h>
130 /* In process.h which conflicts with the local copy. */
131 # define _P_WAIT 0
132 int _cdecl _spawnlp (int, const char *, const char *, ...);
133 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
134 several prototypes of functions called below. */
135 # include <sys/socket.h>
136 #endif
138 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
139 #ifndef ULLONG_MAX
140 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
141 #endif
143 /* Declare here, including term.h is problematic on some systems. */
144 extern void tputs (const char *, int, int (*)(int));
146 static const int baud_convert[] =
148 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
149 1800, 2400, 4800, 9600, 19200, 38400
152 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
153 # include <sys/personality.h>
155 /* If not -1, the personality that should be restored before exec. */
156 static int exec_personality;
158 /* Try to disable randomization if the current process needs it and
159 does not appear to have it already. */
161 maybe_disable_address_randomization (bool dumping, int argc, char **argv)
163 /* Undocumented Emacs option used only by this function. */
164 static char const aslr_disabled_option[] = "--__aslr-disabled";
166 if (argc < 2 || strcmp (argv[1], aslr_disabled_option) != 0)
168 bool disable_aslr = dumping;
169 # ifdef __PPC64__
170 disable_aslr = true;
171 # endif
172 exec_personality = disable_aslr ? personality (0xffffffff) : -1;
173 if (exec_personality & ADDR_NO_RANDOMIZE)
174 exec_personality = -1;
175 if (exec_personality != -1
176 && personality (exec_personality | ADDR_NO_RANDOMIZE) != -1)
178 char **newargv = malloc ((argc + 2) * sizeof *newargv);
179 if (newargv)
181 /* Invoke self with undocumented option. */
182 newargv[0] = argv[0];
183 newargv[1] = (char *) aslr_disabled_option;
184 memcpy (&newargv[2], &argv[1], argc * sizeof *newargv);
185 execvp (newargv[0], newargv);
188 /* If malloc or execvp fails, warn and then try anyway. */
189 perror (argv[0]);
190 free (newargv);
193 else
195 /* Our earlier incarnation already disabled ASLR. */
196 argc--;
197 memmove (&argv[1], &argv[2], argc * sizeof *argv);
200 return argc;
202 #endif
204 /* Execute the program in FILE, with argument vector ARGV and environ
205 ENVP. Return an error number if unsuccessful. This is like execve
206 except it reenables ASLR in the executed program if necessary, and
207 on error it returns an error number rather than -1. */
209 emacs_exec_file (char const *file, char *const *argv, char *const *envp)
211 #ifdef HAVE_PERSONALITY_ADDR_NO_RANDOMIZE
212 if (exec_personality != -1)
213 personality (exec_personality);
214 #endif
216 execve (file, argv, envp);
217 return errno;
220 /* If FD is not already open, arrange for it to be open with FLAGS. */
221 static void
222 force_open (int fd, int flags)
224 if (dup2 (fd, fd) < 0 && errno == EBADF)
226 int n = open (NULL_DEVICE, flags);
227 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
229 emacs_perror (NULL_DEVICE);
230 exit (EXIT_FAILURE);
235 /* A stream that is like stderr, except line buffered. It is NULL
236 during startup, or if line buffering is not in use. */
237 static FILE *buferr;
239 /* Make sure stdin, stdout, and stderr are open to something, so that
240 their file descriptors are not hijacked by later system calls. */
241 void
242 init_standard_fds (void)
244 /* Open stdin for *writing*, and stdout and stderr for *reading*.
245 That way, any attempt to do normal I/O will result in an error,
246 just as if the files were closed, and the file descriptors will
247 not be reused by later opens. */
248 force_open (STDIN_FILENO, O_WRONLY);
249 force_open (STDOUT_FILENO, O_RDONLY);
250 force_open (STDERR_FILENO, O_RDONLY);
252 /* Set buferr if possible on platforms defining _PC_PIPE_BUF, as
253 they support the notion of atomic writes to pipes. */
254 #ifdef _PC_PIPE_BUF
255 buferr = fdopen (STDERR_FILENO, "w");
256 if (buferr)
257 setvbuf (buferr, NULL, _IOLBF, 0);
258 #endif
261 /* Return the current working directory. The result should be freed
262 with 'free'. Return NULL (setting errno) on errors. If the
263 current directory is unreachable, return either NULL or a string
264 beginning with '('. */
266 static char *
267 get_current_dir_name_or_unreachable (void)
269 /* Use malloc, not xmalloc, since this function can be called before
270 the xmalloc exception machinery is available. */
272 char *pwd;
274 /* The maximum size of a directory name, including the terminating NUL.
275 Leave room so that the caller can append a trailing slash. */
276 ptrdiff_t dirsize_max = min (PTRDIFF_MAX, SIZE_MAX) - 1;
278 /* The maximum size of a buffer for a file name, including the
279 terminating NUL. This is bounded by PATH_MAX, if available. */
280 ptrdiff_t bufsize_max = dirsize_max;
281 #ifdef PATH_MAX
282 bufsize_max = min (bufsize_max, PATH_MAX);
283 #endif
285 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
286 # ifdef HYBRID_MALLOC
287 bool use_libc = will_dump_with_unexec_p ();
288 # else
289 bool use_libc = true;
290 # endif
291 if (use_libc)
293 /* For an unreachable directory, this returns a string that starts
294 with "(unreachable)"; see Bug#27871. */
295 pwd = get_current_dir_name ();
296 if (pwd)
298 if (strnlen (pwd, dirsize_max) < dirsize_max)
299 return pwd;
300 free (pwd);
301 errno = ERANGE;
303 return NULL;
305 # endif
307 size_t pwdlen;
308 struct stat dotstat, pwdstat;
309 pwd = getenv ("PWD");
311 /* If PWD is accurate, use it instead of calling getcwd. PWD is
312 sometimes a nicer name, and using it may avoid a fatal error if a
313 parent directory is searchable but not readable. */
314 if (pwd
315 && (pwdlen = strnlen (pwd, bufsize_max)) < bufsize_max
316 && IS_DIRECTORY_SEP (pwd[pwdlen && IS_DEVICE_SEP (pwd[1]) ? 2 : 0])
317 && stat (pwd, &pwdstat) == 0
318 && stat (".", &dotstat) == 0
319 && dotstat.st_ino == pwdstat.st_ino
320 && dotstat.st_dev == pwdstat.st_dev)
322 char *buf = malloc (pwdlen + 1);
323 if (!buf)
324 return NULL;
325 return memcpy (buf, pwd, pwdlen + 1);
327 else
329 ptrdiff_t buf_size = min (bufsize_max, 1024);
330 char *buf = malloc (buf_size);
331 if (!buf)
332 return NULL;
333 for (;;)
335 if (getcwd (buf, buf_size) == buf)
336 return buf;
337 int getcwd_errno = errno;
338 if (getcwd_errno != ERANGE || buf_size == bufsize_max)
340 free (buf);
341 errno = getcwd_errno;
342 return NULL;
344 buf_size = buf_size <= bufsize_max / 2 ? 2 * buf_size : bufsize_max;
345 buf = realloc (buf, buf_size);
346 if (!buf)
347 return NULL;
352 /* Return the current working directory. The result should be freed
353 with 'free'. Return NULL (setting errno) on errors; an unreachable
354 directory (e.g., its name starts with '(') counts as an error. */
356 char *
357 emacs_get_current_dir_name (void)
359 char *dir = get_current_dir_name_or_unreachable ();
360 if (dir && *dir == '(')
362 free (dir);
363 errno = ENOENT;
364 return NULL;
366 return dir;
370 /* Discard pending input on all input descriptors. */
372 void
373 discard_tty_input (void)
375 #ifndef WINDOWSNT
376 struct emacs_tty buf;
378 if (noninteractive)
379 return;
381 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
382 while (dos_keyread () != -1)
384 #else /* not MSDOS */
386 struct tty_display_info *tty;
387 for (tty = tty_list; tty; tty = tty->next)
389 if (tty->input) /* Is the device suspended? */
391 emacs_get_tty (fileno (tty->input), &buf);
392 emacs_set_tty (fileno (tty->input), &buf, 0);
396 #endif /* not MSDOS */
397 #endif /* not WINDOWSNT */
401 #ifdef SIGTSTP
403 /* Arrange for character C to be read as the next input from
404 the terminal.
405 XXX What if we have multiple ttys?
408 void
409 stuff_char (char c)
411 if (! (FRAMEP (selected_frame)
412 && FRAME_LIVE_P (XFRAME (selected_frame))
413 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
414 return;
416 /* Should perhaps error if in batch mode */
417 #ifdef TIOCSTI
418 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
419 #else /* no TIOCSTI */
420 error ("Cannot stuff terminal input characters in this version of Unix");
421 #endif /* no TIOCSTI */
424 #endif /* SIGTSTP */
426 void
427 init_baud_rate (int fd)
429 int emacs_ospeed;
431 if (noninteractive)
432 emacs_ospeed = 0;
433 else
435 #ifdef DOS_NT
436 emacs_ospeed = 15;
437 #else /* not DOS_NT */
438 struct termios sg;
440 sg.c_cflag = B9600;
441 tcgetattr (fd, &sg);
442 emacs_ospeed = cfgetospeed (&sg);
443 #endif /* not DOS_NT */
446 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
447 ? baud_convert[emacs_ospeed] : 9600);
448 if (baud_rate == 0)
449 baud_rate = 1200;
454 #ifndef MSDOS
456 /* Wait for the subprocess with process id CHILD to terminate or change status.
457 CHILD must be a child process that has not been reaped.
458 If STATUS is non-null, store the waitpid-style exit status into *STATUS
459 and tell wait_reading_process_output that it needs to look around.
460 Use waitpid-style OPTIONS when waiting.
461 If INTERRUPTIBLE, this function is interruptible by a signal.
463 Return CHILD if successful, 0 if no status is available, and a
464 negative value (setting errno) if waitpid is buggy. */
465 static pid_t
466 get_child_status (pid_t child, int *status, int options, bool interruptible)
468 pid_t pid;
470 /* Invoke waitpid only with a known process ID; do not invoke
471 waitpid with a nonpositive argument. Otherwise, Emacs might
472 reap an unwanted process by mistake. For example, invoking
473 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
474 so that another thread running glib won't find them. */
475 eassert (child > 0);
477 while (true)
479 /* Note: the MS-Windows emulation of waitpid calls maybe_quit
480 internally. */
481 if (interruptible)
482 maybe_quit ();
484 pid = waitpid (child, status, options);
485 if (0 <= pid)
486 break;
487 if (errno != EINTR)
489 /* Most likely, waitpid is buggy and the operating system
490 lost track of the child somehow. Return -1 and let the
491 caller try to figure things out. Possibly the bug could
492 cause Emacs to kill the wrong process. Oh well. */
493 return pid;
497 /* If successful and status is requested, tell wait_reading_process_output
498 that it needs to wake up and look around. */
499 if (pid && status && input_available_clear_time)
500 *input_available_clear_time = make_timespec (0, 0);
502 return pid;
505 /* Wait for the subprocess with process id CHILD to terminate.
506 CHILD must be a child process that has not been reaped.
507 If STATUS is non-null, store the waitpid-style exit status into *STATUS
508 and tell wait_reading_process_output that it needs to look around.
509 If INTERRUPTIBLE, this function is interruptible by a signal.
510 Return true if successful, false (setting errno) if CHILD cannot be
511 waited for because waitpid is buggy. */
512 bool
513 wait_for_termination (pid_t child, int *status, bool interruptible)
515 return 0 <= get_child_status (child, status, 0, interruptible);
518 /* Report whether the subprocess with process id CHILD has changed status.
519 Termination counts as a change of status.
520 CHILD must be a child process that has not been reaped.
521 If STATUS is non-null, store the waitpid-style exit status into *STATUS
522 and tell wait_reading_process_output that it needs to look around.
523 Use waitpid-style OPTIONS to check status, but do not wait.
525 Return CHILD if successful, 0 if no status is available because
526 the process's state has not changed. */
527 pid_t
528 child_status_changed (pid_t child, int *status, int options)
530 return get_child_status (child, status, WNOHANG | options, 0);
534 /* Set up the terminal at the other end of a pseudo-terminal that
535 we will be controlling an inferior through.
536 It should not echo or do line-editing, since that is done
537 in Emacs. No padding needed for insertion into an Emacs buffer. */
539 void
540 child_setup_tty (int out)
542 #ifndef WINDOWSNT
543 struct emacs_tty s;
545 emacs_get_tty (out, &s);
546 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
547 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
548 #ifdef NLDLY
549 /* https://lists.gnu.org/r/emacs-devel/2008-05/msg00406.html
550 Some versions of GNU Hurd do not have FFDLY? */
551 #ifdef FFDLY
552 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
553 /* No output delays */
554 #else
555 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
556 /* No output delays */
557 #endif
558 #endif
559 s.main.c_lflag &= ~ECHO; /* Disable echo */
560 s.main.c_lflag |= ISIG; /* Enable signals */
561 #ifdef IUCLC
562 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
563 #endif
564 #ifdef ISTRIP
565 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
566 #endif
567 #ifdef OLCUC
568 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
569 #endif
570 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
571 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
572 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
573 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
575 #ifdef HPUX
576 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
577 #endif /* HPUX */
579 #ifdef SIGNALS_VIA_CHARACTERS
580 /* the QUIT and INTR character are used in process_send_signal
581 so set them here to something useful. */
582 if (s.main.c_cc[VQUIT] == CDISABLE)
583 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
584 if (s.main.c_cc[VINTR] == CDISABLE)
585 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
586 #endif /* not SIGNALS_VIA_CHARACTERS */
588 #ifdef AIX
589 /* Also, PTY overloads NUL and BREAK.
590 don't ignore break, but don't signal either, so it looks like NUL. */
591 s.main.c_iflag &= ~IGNBRK;
592 s.main.c_iflag &= ~BRKINT;
593 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
594 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
595 would force it to 0377. That looks like duplicated code. */
596 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
597 #endif /* AIX */
599 /* We originally enabled ICANON (and set VEOF to 04), and then had
600 process.c send additional EOF chars to flush the output when faced
601 with long lines, but this leads to weird effects when the
602 subprocess has disabled ICANON and ends up seeing those spurious
603 extra EOFs. So we don't send EOFs any more in
604 process.c:send_process. First we tried to disable ICANON by
605 default, so if a subsprocess sets up ICANON, it's his problem (or
606 the Elisp package that talks to it) to deal with lines that are
607 too long. But this disables some features, such as the ability
608 to send EOF signals. So we re-enabled ICANON but there is no
609 more "send eof to flush" going on (which is wrong and unportable
610 in itself). The correct way to handle too much output is to
611 buffer what could not be written and then write it again when
612 select returns ok for writing. This has it own set of
613 problems. Write is now asynchronous, is that a problem? How much
614 do we buffer, and what do we do when that limit is reached? */
616 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
617 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
618 #if 0 /* These settings only apply to non-ICANON mode. */
619 s.main.c_cc[VMIN] = 1;
620 s.main.c_cc[VTIME] = 0;
621 #endif
623 emacs_set_tty (out, &s, 0);
624 #endif /* not WINDOWSNT */
626 #endif /* not MSDOS */
629 /* Record a signal code and the action for it. */
630 struct save_signal
632 int code;
633 struct sigaction action;
636 static void save_signal_handlers (struct save_signal *);
637 static void restore_signal_handlers (struct save_signal *);
639 /* Suspend the Emacs process; give terminal to its superior. */
641 void
642 sys_suspend (void)
644 #ifndef DOS_NT
645 kill (0, SIGTSTP);
646 #else
647 /* On a system where suspending is not implemented,
648 instead fork a subshell and let it talk directly to the terminal
649 while we wait. */
650 sys_subshell ();
652 #endif
655 /* Fork a subshell. */
657 void
658 sys_subshell (void)
660 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
661 #ifdef MSDOS
662 int st;
663 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
664 #else
665 char oldwd[MAX_UTF8_PATH];
666 #endif /* MSDOS */
667 #else /* !DOS_NT */
668 int status;
669 #endif
670 pid_t pid;
671 struct save_signal saved_handlers[5];
672 char *str = SSDATA (encode_current_directory ());
674 #ifdef DOS_NT
675 pid = 0;
676 #else
678 char *volatile str_volatile = str;
679 pid = vfork ();
680 str = str_volatile;
682 #endif
684 if (pid < 0)
685 error ("Can't spawn subshell");
687 saved_handlers[0].code = SIGINT;
688 saved_handlers[1].code = SIGQUIT;
689 saved_handlers[2].code = SIGTERM;
690 #ifdef USABLE_SIGIO
691 saved_handlers[3].code = SIGIO;
692 saved_handlers[4].code = 0;
693 #else
694 saved_handlers[3].code = 0;
695 #endif
697 #ifdef DOS_NT
698 save_signal_handlers (saved_handlers);
699 #endif
701 if (pid == 0)
703 const char *sh = 0;
705 #ifdef DOS_NT /* MW, Aug 1993 */
706 getcwd (oldwd, sizeof oldwd);
707 if (sh == 0)
708 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
709 #endif
710 if (sh == 0)
711 sh = egetenv ("SHELL");
712 if (sh == 0)
713 sh = "sh";
715 /* Use our buffer's default directory for the subshell. */
716 if (chdir (str) != 0)
718 #ifndef DOS_NT
719 emacs_perror (str);
720 _exit (EXIT_CANCELED);
721 #endif
724 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
726 char *epwd = getenv ("PWD");
727 char old_pwd[MAXPATHLEN+1+4];
729 /* If PWD is set, pass it with corrected value. */
730 if (epwd)
732 strcpy (old_pwd, epwd);
733 setenv ("PWD", str, 1);
735 st = system (sh);
736 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
737 if (epwd)
738 putenv (old_pwd); /* restore previous value */
740 #else /* not MSDOS */
741 #ifdef WINDOWSNT
742 /* Waits for process completion */
743 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
744 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
745 if (pid == -1)
746 write (1, "Can't execute subshell", 22);
747 #else /* not WINDOWSNT */
748 execlp (sh, sh, (char *) 0);
749 emacs_perror (sh);
750 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
751 #endif /* not WINDOWSNT */
752 #endif /* not MSDOS */
755 /* Do this now if we did not do it before. */
756 #ifndef MSDOS
757 save_signal_handlers (saved_handlers);
758 #endif
760 #ifndef DOS_NT
761 wait_for_termination (pid, &status, 0);
762 #endif
763 restore_signal_handlers (saved_handlers);
766 static void
767 save_signal_handlers (struct save_signal *saved_handlers)
769 while (saved_handlers->code)
771 struct sigaction action;
772 emacs_sigaction_init (&action, SIG_IGN);
773 sigaction (saved_handlers->code, &action, &saved_handlers->action);
774 saved_handlers++;
778 static void
779 restore_signal_handlers (struct save_signal *saved_handlers)
781 while (saved_handlers->code)
783 sigaction (saved_handlers->code, &saved_handlers->action, 0);
784 saved_handlers++;
788 #ifdef USABLE_SIGIO
789 static int old_fcntl_flags[FD_SETSIZE];
790 #endif
792 void
793 init_sigio (int fd)
795 #ifdef USABLE_SIGIO
796 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
797 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
798 interrupts_deferred = 0;
799 #endif
802 #ifndef DOS_NT
803 static void
804 reset_sigio (int fd)
806 #ifdef USABLE_SIGIO
807 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
808 #endif
810 #endif
812 void
813 request_sigio (void)
815 #ifdef USABLE_SIGIO
816 sigset_t unblocked;
818 if (noninteractive)
819 return;
821 sigemptyset (&unblocked);
822 # ifdef SIGWINCH
823 sigaddset (&unblocked, SIGWINCH);
824 # endif
825 sigaddset (&unblocked, SIGIO);
826 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
828 interrupts_deferred = 0;
829 #endif
832 void
833 unrequest_sigio (void)
835 #ifdef USABLE_SIGIO
836 sigset_t blocked;
838 if (noninteractive)
839 return;
841 sigemptyset (&blocked);
842 # ifdef SIGWINCH
843 sigaddset (&blocked, SIGWINCH);
844 # endif
845 sigaddset (&blocked, SIGIO);
846 pthread_sigmask (SIG_BLOCK, &blocked, 0);
847 interrupts_deferred = 1;
848 #endif
851 #ifndef MSDOS
852 /* Block SIGCHLD. */
854 void
855 block_child_signal (sigset_t *oldset)
857 sigset_t blocked;
858 sigemptyset (&blocked);
859 sigaddset (&blocked, SIGCHLD);
860 sigaddset (&blocked, SIGINT);
861 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
864 /* Unblock SIGCHLD. */
866 void
867 unblock_child_signal (sigset_t const *oldset)
869 pthread_sigmask (SIG_SETMASK, oldset, 0);
872 #endif /* !MSDOS */
874 /* Block SIGINT. */
875 void
876 block_interrupt_signal (sigset_t *oldset)
878 sigset_t blocked;
879 sigemptyset (&blocked);
880 sigaddset (&blocked, SIGINT);
881 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
884 /* Restore previously saved signal mask. */
885 void
886 restore_signal_mask (sigset_t const *oldset)
888 pthread_sigmask (SIG_SETMASK, oldset, 0);
892 /* Saving and restoring the process group of Emacs's terminal. */
894 /* The process group of which Emacs was a member when it initially
895 started.
897 If Emacs was in its own process group (i.e. inherited_pgroup ==
898 getpid ()), then we know we're running under a shell with job
899 control (Emacs would never be run as part of a pipeline).
900 Everything is fine.
902 If Emacs was not in its own process group, then we know we're
903 running under a shell (or a caller) that doesn't know how to
904 separate itself from Emacs (like sh). Emacs must be in its own
905 process group in order to receive SIGIO correctly. In this
906 situation, we put ourselves in our own pgroup, forcibly set the
907 tty's pgroup to our pgroup, and make sure to restore and reinstate
908 the tty's pgroup just like any other terminal setting. If
909 inherited_group was not the tty's pgroup, then we'll get a
910 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
911 it goes foreground in the future, which is what should happen. */
913 static pid_t inherited_pgroup;
915 void
916 init_foreground_group (void)
918 pid_t pgrp = getpgrp ();
919 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
922 /* Block and unblock SIGTTOU. */
924 void
925 block_tty_out_signal (sigset_t *oldset)
927 #ifdef SIGTTOU
928 sigset_t blocked;
929 sigemptyset (&blocked);
930 sigaddset (&blocked, SIGTTOU);
931 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
932 #endif
935 void
936 unblock_tty_out_signal (sigset_t const *oldset)
938 #ifdef SIGTTOU
939 pthread_sigmask (SIG_SETMASK, oldset, 0);
940 #endif
943 /* Safely set a controlling terminal FD's process group to PGID.
944 If we are not in the foreground already, POSIX requires tcsetpgrp
945 to deliver a SIGTTOU signal, which would stop us. This is an
946 annoyance, so temporarily ignore the signal.
948 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
949 skip all this unless SIGTTOU is defined. */
950 static void
951 tcsetpgrp_without_stopping (int fd, pid_t pgid)
953 #ifdef SIGTTOU
954 sigset_t oldset;
955 block_input ();
956 block_tty_out_signal (&oldset);
957 tcsetpgrp (fd, pgid);
958 unblock_tty_out_signal (&oldset);
959 unblock_input ();
960 #endif
963 /* Split off the foreground process group to Emacs alone. When we are
964 in the foreground, but not started in our own process group,
965 redirect the tty device handle FD to point to our own process
966 group. FD must be the file descriptor of the controlling tty. */
967 static void
968 narrow_foreground_group (int fd)
970 if (inherited_pgroup && setpgid (0, 0) == 0)
971 tcsetpgrp_without_stopping (fd, getpid ());
974 /* Set the tty to our original foreground group. */
975 static void
976 widen_foreground_group (int fd)
978 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
979 tcsetpgrp_without_stopping (fd, inherited_pgroup);
982 /* Getting and setting emacs_tty structures. */
984 /* Set *TC to the parameters associated with the terminal FD,
985 or clear it if the parameters are not available.
986 Return 0 on success, -1 on failure. */
988 emacs_get_tty (int fd, struct emacs_tty *settings)
990 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
991 memset (&settings->main, 0, sizeof (settings->main));
992 #ifdef DOS_NT
993 #ifdef WINDOWSNT
994 HANDLE h = (HANDLE)_get_osfhandle (fd);
995 DWORD console_mode;
997 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
999 settings->main = console_mode;
1000 return 0;
1002 #endif /* WINDOWSNT */
1003 return -1;
1004 #else /* !DOS_NT */
1005 /* We have those nifty POSIX tcmumbleattr functions. */
1006 return tcgetattr (fd, &settings->main);
1007 #endif
1011 /* Set the parameters of the tty on FD according to the contents of
1012 *SETTINGS. If FLUSHP, discard input.
1013 Return 0 if all went well, and -1 (setting errno) if anything failed. */
1016 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
1018 /* Set the primary parameters - baud rate, character size, etcetera. */
1019 #ifdef DOS_NT
1020 #ifdef WINDOWSNT
1021 HANDLE h = (HANDLE)_get_osfhandle (fd);
1023 if (h && h != INVALID_HANDLE_VALUE)
1025 DWORD new_mode;
1027 /* Assume the handle is open for input. */
1028 if (flushp)
1029 FlushConsoleInputBuffer (h);
1030 new_mode = settings->main;
1031 SetConsoleMode (h, new_mode);
1033 #endif /* WINDOWSNT */
1034 #else /* !DOS_NT */
1035 int i;
1036 /* We have those nifty POSIX tcmumbleattr functions.
1037 William J. Smith <wjs@wiis.wang.com> writes:
1038 "POSIX 1003.1 defines tcsetattr to return success if it was
1039 able to perform any of the requested actions, even if some
1040 of the requested actions could not be performed.
1041 We must read settings back to ensure tty setup properly.
1042 AIX requires this to keep tty from hanging occasionally." */
1043 /* This make sure that we don't loop indefinitely in here. */
1044 for (i = 0 ; i < 10 ; i++)
1045 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
1047 if (errno == EINTR)
1048 continue;
1049 else
1050 return -1;
1052 else
1054 struct termios new;
1056 memset (&new, 0, sizeof (new));
1057 /* Get the current settings, and see if they're what we asked for. */
1058 tcgetattr (fd, &new);
1059 /* We cannot use memcmp on the whole structure here because under
1060 * aix386 the termios structure has some reserved field that may
1061 * not be filled in.
1063 if ( new.c_iflag == settings->main.c_iflag
1064 && new.c_oflag == settings->main.c_oflag
1065 && new.c_cflag == settings->main.c_cflag
1066 && new.c_lflag == settings->main.c_lflag
1067 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
1068 break;
1069 else
1070 continue;
1072 #endif
1074 /* We have survived the tempest. */
1075 return 0;
1080 #ifdef F_SETOWN
1081 static int old_fcntl_owner[FD_SETSIZE];
1082 #endif /* F_SETOWN */
1084 /* Initialize the terminal mode on all tty devices that are currently
1085 open. */
1087 void
1088 init_all_sys_modes (void)
1090 struct tty_display_info *tty;
1091 for (tty = tty_list; tty; tty = tty->next)
1092 init_sys_modes (tty);
1095 /* Initialize the terminal mode on the given tty device. */
1097 void
1098 init_sys_modes (struct tty_display_info *tty_out)
1100 struct emacs_tty tty;
1101 #ifndef DOS_NT
1102 Lisp_Object terminal;
1103 #endif
1105 Vtty_erase_char = Qnil;
1107 if (noninteractive)
1108 return;
1110 if (!tty_out->output)
1111 return; /* The tty is suspended. */
1113 narrow_foreground_group (fileno (tty_out->input));
1115 if (! tty_out->old_tty)
1116 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
1118 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
1120 tty = *tty_out->old_tty;
1122 #if !defined (DOS_NT)
1123 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1125 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1126 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1127 #ifdef INLCR /* I'm just being cautious,
1128 since I can't check how widespread INLCR is--rms. */
1129 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1130 #endif
1131 #ifdef ISTRIP
1132 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1133 #endif
1134 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1135 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1136 #ifdef IEXTEN
1137 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1138 #endif
1139 tty.main.c_lflag |= ISIG; /* Enable signals */
1140 if (tty_out->flow_control)
1142 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1143 #ifdef IXANY
1144 tty.main.c_iflag &= ~IXANY;
1145 #endif /* IXANY */
1147 else
1148 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1149 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1150 on output */
1151 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1152 #ifdef CS8
1153 if (tty_out->meta_key)
1155 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1156 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1158 #endif
1160 XSETTERMINAL(terminal, tty_out->terminal);
1161 if (!NILP (Fcontrolling_tty_p (terminal)))
1163 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1164 /* Set up C-g for both SIGQUIT and SIGINT.
1165 We don't know which we will get, but we handle both alike
1166 so which one it really gives us does not matter. */
1167 tty.main.c_cc[VQUIT] = quit_char;
1169 else
1171 /* We normally don't get interrupt or quit signals from tty
1172 devices other than our controlling terminal; therefore,
1173 we must handle C-g as normal input. Unfortunately, this
1174 means that the interrupt and quit feature must be
1175 disabled on secondary ttys, or we would not even see the
1176 keypress.
1178 Note that even though emacsclient could have special code
1179 to pass SIGINT to Emacs, we should _not_ enable
1180 interrupt/quit keys for emacsclient frames. This means
1181 that we can't break out of loops in C code from a
1182 secondary tty frame, but we can always decide what
1183 display the C-g came from, which is more important from a
1184 usability point of view. (Consider the case when two
1185 people work together using the same Emacs instance.) */
1186 tty.main.c_cc[VINTR] = CDISABLE;
1187 tty.main.c_cc[VQUIT] = CDISABLE;
1189 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1190 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1191 #ifdef VSWTCH
1192 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1193 of C-z */
1194 #endif /* VSWTCH */
1196 #ifdef VSUSP
1197 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1198 #endif /* VSUSP */
1199 #ifdef V_DSUSP
1200 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1201 #endif /* V_DSUSP */
1202 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1203 tty.main.c_cc[VDSUSP] = CDISABLE;
1204 #endif /* VDSUSP */
1205 #ifdef VLNEXT
1206 tty.main.c_cc[VLNEXT] = CDISABLE;
1207 #endif /* VLNEXT */
1208 #ifdef VREPRINT
1209 tty.main.c_cc[VREPRINT] = CDISABLE;
1210 #endif /* VREPRINT */
1211 #ifdef VWERASE
1212 tty.main.c_cc[VWERASE] = CDISABLE;
1213 #endif /* VWERASE */
1214 #ifdef VDISCARD
1215 tty.main.c_cc[VDISCARD] = CDISABLE;
1216 #endif /* VDISCARD */
1218 if (tty_out->flow_control)
1220 #ifdef VSTART
1221 tty.main.c_cc[VSTART] = '\021';
1222 #endif /* VSTART */
1223 #ifdef VSTOP
1224 tty.main.c_cc[VSTOP] = '\023';
1225 #endif /* VSTOP */
1227 else
1229 #ifdef VSTART
1230 tty.main.c_cc[VSTART] = CDISABLE;
1231 #endif /* VSTART */
1232 #ifdef VSTOP
1233 tty.main.c_cc[VSTOP] = CDISABLE;
1234 #endif /* VSTOP */
1237 #ifdef AIX
1238 tty.main.c_cc[VSTRT] = CDISABLE;
1239 tty.main.c_cc[VSTOP] = CDISABLE;
1240 tty.main.c_cc[VSUSP] = CDISABLE;
1241 tty.main.c_cc[VDSUSP] = CDISABLE;
1242 if (tty_out->flow_control)
1244 #ifdef VSTART
1245 tty.main.c_cc[VSTART] = '\021';
1246 #endif /* VSTART */
1247 #ifdef VSTOP
1248 tty.main.c_cc[VSTOP] = '\023';
1249 #endif /* VSTOP */
1251 /* Also, PTY overloads NUL and BREAK.
1252 don't ignore break, but don't signal either, so it looks like NUL.
1253 This really serves a purpose only if running in an XTERM window
1254 or via TELNET or the like, but does no harm elsewhere. */
1255 tty.main.c_iflag &= ~IGNBRK;
1256 tty.main.c_iflag &= ~BRKINT;
1257 #endif
1258 #endif /* not DOS_NT */
1260 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1261 if (!tty_out->term_initted)
1262 internal_terminal_init ();
1263 dos_ttraw (tty_out);
1264 #endif
1266 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1268 /* This code added to insure that, if flow-control is not to be used,
1269 we have an unlocked terminal at the start. */
1271 #ifdef TCXONC
1272 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1273 #endif
1274 #ifdef TIOCSTART
1275 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1276 #endif
1278 #if !defined (DOS_NT)
1279 #ifdef TCOON
1280 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1281 #endif
1282 #endif
1284 #ifdef F_GETOWN
1285 if (interrupt_input)
1287 old_fcntl_owner[fileno (tty_out->input)] =
1288 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1289 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1290 init_sigio (fileno (tty_out->input));
1291 #ifdef HAVE_GPM
1292 if (gpm_tty == tty_out)
1294 /* Arrange for mouse events to give us SIGIO signals. */
1295 fcntl (gpm_fd, F_SETOWN, getpid ());
1296 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1297 init_sigio (gpm_fd);
1299 #endif /* HAVE_GPM */
1301 #endif /* F_GETOWN */
1303 setvbuf (tty_out->output, NULL, _IOFBF, BUFSIZ);
1305 if (tty_out->terminal->set_terminal_modes_hook)
1306 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1308 if (!tty_out->term_initted)
1310 Lisp_Object tail, frame;
1311 FOR_EACH_FRAME (tail, frame)
1313 /* XXX This needs to be revised. */
1314 if (FRAME_TERMCAP_P (XFRAME (frame))
1315 && FRAME_TTY (XFRAME (frame)) == tty_out)
1316 init_frame_faces (XFRAME (frame));
1320 if (tty_out->term_initted && no_redraw_on_reenter)
1322 /* We used to call "direct_output_forward_char(0)" here,
1323 but it's not clear why, since it may not do anything anyway. */
1325 else
1327 Lisp_Object tail, frame;
1328 frame_garbaged = 1;
1329 FOR_EACH_FRAME (tail, frame)
1331 if ((FRAME_TERMCAP_P (XFRAME (frame))
1332 || FRAME_MSDOS_P (XFRAME (frame)))
1333 && FRAME_TTY (XFRAME (frame)) == tty_out)
1334 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1338 tty_out->term_initted = 1;
1341 /* Return true if safe to use tabs in output.
1342 At the time this is called, init_sys_modes has not been done yet. */
1344 bool
1345 tabs_safe_p (int fd)
1347 struct emacs_tty etty;
1349 emacs_get_tty (fd, &etty);
1350 #ifndef DOS_NT
1351 #ifdef TABDLY
1352 return ((etty.main.c_oflag & TABDLY) != TAB3);
1353 #else /* not TABDLY */
1354 return 1;
1355 #endif /* not TABDLY */
1356 #else /* DOS_NT */
1357 return 0;
1358 #endif /* DOS_NT */
1361 /* Discard echoing. */
1363 void
1364 suppress_echo_on_tty (int fd)
1366 struct emacs_tty etty;
1368 emacs_get_tty (fd, &etty);
1369 #ifdef DOS_NT
1370 /* Set raw input mode. */
1371 etty.main = 0;
1372 #else
1373 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1374 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1375 #endif /* ! WINDOWSNT */
1376 emacs_set_tty (fd, &etty, 0);
1379 /* Get terminal size from system.
1380 Store number of lines into *HEIGHTP and width into *WIDTHP.
1381 We store 0 if there's no valid information. */
1383 void
1384 get_tty_size (int fd, int *widthp, int *heightp)
1386 #if defined TIOCGWINSZ
1388 /* BSD-style. */
1389 struct winsize size;
1391 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1392 *widthp = *heightp = 0;
1393 else
1395 *widthp = size.ws_col;
1396 *heightp = size.ws_row;
1399 #elif defined TIOCGSIZE
1401 /* SunOS - style. */
1402 struct ttysize size;
1404 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1405 *widthp = *heightp = 0;
1406 else
1408 *widthp = size.ts_cols;
1409 *heightp = size.ts_lines;
1412 #elif defined WINDOWSNT
1414 CONSOLE_SCREEN_BUFFER_INFO info;
1415 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1417 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1418 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1420 else
1421 *widthp = *heightp = 0;
1423 #elif defined MSDOS
1425 *widthp = ScreenCols ();
1426 *heightp = ScreenRows ();
1428 #else /* system doesn't know size */
1430 *widthp = 0;
1431 *heightp = 0;
1433 #endif
1436 /* Set the logical window size associated with descriptor FD
1437 to HEIGHT and WIDTH. This is used mainly with ptys.
1438 Return a negative value on failure. */
1441 set_window_size (int fd, int height, int width)
1443 #ifdef TIOCSWINSZ
1445 /* BSD-style. */
1446 struct winsize size;
1447 size.ws_row = height;
1448 size.ws_col = width;
1450 return ioctl (fd, TIOCSWINSZ, &size);
1452 #else
1453 #ifdef TIOCSSIZE
1455 /* SunOS - style. */
1456 struct ttysize size;
1457 size.ts_lines = height;
1458 size.ts_cols = width;
1460 return ioctl (fd, TIOCGSIZE, &size);
1461 #else
1462 return -1;
1463 #endif /* not SunOS-style */
1464 #endif /* not BSD-style */
1469 /* Prepare all terminal devices for exiting Emacs. */
1471 void
1472 reset_all_sys_modes (void)
1474 struct tty_display_info *tty;
1475 for (tty = tty_list; tty; tty = tty->next)
1476 reset_sys_modes (tty);
1479 /* Prepare the terminal for closing it; move the cursor to the
1480 bottom of the frame, turn off interrupt-driven I/O, etc. */
1482 void
1483 reset_sys_modes (struct tty_display_info *tty_out)
1485 if (noninteractive)
1487 fflush (stdout);
1488 return;
1490 if (!tty_out->term_initted)
1491 return;
1493 if (!tty_out->output)
1494 return; /* The tty is suspended. */
1496 /* Go to and clear the last line of the terminal. */
1498 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1500 /* Code adapted from tty_clear_end_of_line. */
1501 if (tty_out->TS_clr_line)
1503 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1505 else
1506 { /* have to do it the hard way */
1507 tty_turn_off_insert (tty_out);
1509 for (int i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1510 putc (' ', tty_out->output);
1513 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1514 fflush (tty_out->output);
1516 if (tty_out->terminal->reset_terminal_modes_hook)
1517 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1519 /* Avoid possible loss of output when changing terminal modes. */
1520 while (tcdrain (fileno (tty_out->output)) != 0 && errno == EINTR)
1521 continue;
1523 #ifndef DOS_NT
1524 # ifdef F_SETOWN
1525 if (interrupt_input)
1527 reset_sigio (fileno (tty_out->input));
1528 fcntl (fileno (tty_out->input), F_SETOWN,
1529 old_fcntl_owner[fileno (tty_out->input)]);
1531 # endif /* F_SETOWN */
1532 fcntl (fileno (tty_out->input), F_SETFL,
1533 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1534 #endif
1536 if (tty_out->old_tty)
1537 while (emacs_set_tty (fileno (tty_out->input),
1538 tty_out->old_tty, 0) < 0 && errno == EINTR)
1541 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1542 dos_ttcooked ();
1543 #endif
1545 widen_foreground_group (fileno (tty_out->input));
1548 #ifdef HAVE_PTYS
1550 /* Set up the proper status flags for use of a pty. */
1552 void
1553 setup_pty (int fd)
1555 /* I'm told that TOICREMOTE does not mean control chars
1556 "can't be sent" but rather that they don't have
1557 input-editing or signaling effects.
1558 That should be good, because we have other ways
1559 to do those things in Emacs.
1560 However, telnet mode seems not to work on 4.2.
1561 So TIOCREMOTE is turned off now. */
1563 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1564 will hang. In particular, the "timeout" feature (which
1565 causes a read to return if there is no data available)
1566 does this. Also it is known that telnet mode will hang
1567 in such a way that Emacs must be stopped (perhaps this
1568 is the same problem).
1570 If TIOCREMOTE is turned off, then there is a bug in
1571 hp-ux which sometimes loses data. Apparently the
1572 code which blocks the master process when the internal
1573 buffer fills up does not work. Other than this,
1574 though, everything else seems to work fine.
1576 Since the latter lossage is more benign, we may as well
1577 lose that way. -- cph */
1578 #ifdef FIONBIO
1579 #if defined (UNIX98_PTYS)
1581 int on = 1;
1582 ioctl (fd, FIONBIO, &on);
1584 #endif
1585 #endif
1587 #endif /* HAVE_PTYS */
1589 void
1590 init_system_name (void)
1592 if (!build_details)
1594 /* Set system-name to nil so that the build is deterministic. */
1595 Vsystem_name = Qnil;
1596 return;
1598 char *hostname_alloc = NULL;
1599 char *hostname;
1600 #ifndef HAVE_GETHOSTNAME
1601 struct utsname uts;
1602 uname (&uts);
1603 hostname = uts.nodename;
1604 #else /* HAVE_GETHOSTNAME */
1605 char hostname_buf[256];
1606 ptrdiff_t hostname_size = sizeof hostname_buf;
1607 hostname = hostname_buf;
1609 /* Try to get the host name; if the buffer is too short, try
1610 again. Apparently, the only indication gethostname gives of
1611 whether the buffer was large enough is the presence or absence
1612 of a '\0' in the string. Eech. */
1613 for (;;)
1615 gethostname (hostname, hostname_size - 1);
1616 hostname[hostname_size - 1] = '\0';
1618 /* Was the buffer large enough for the '\0'? */
1619 if (strlen (hostname) < hostname_size - 1)
1620 break;
1622 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1623 min (PTRDIFF_MAX, SIZE_MAX), 1);
1625 #endif /* HAVE_GETHOSTNAME */
1626 char *p;
1627 for (p = hostname; *p; p++)
1628 if (*p == ' ' || *p == '\t')
1629 *p = '-';
1630 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1631 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1632 Vsystem_name = build_string (hostname);
1633 xfree (hostname_alloc);
1636 sigset_t empty_mask;
1638 static struct sigaction process_fatal_action;
1640 static int
1641 emacs_sigaction_flags (void)
1643 #ifdef SA_RESTART
1644 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1645 'select') to reset their timeout on some platforms (e.g.,
1646 HP-UX 11), which is not what we want. Also, when Emacs is
1647 interactive, we don't want SA_RESTART because we need to poll
1648 for pending input so we need long-running syscalls to be interrupted
1649 after a signal that sets pending_signals.
1651 Non-interactive keyboard input goes through stdio, where we
1652 always want restartable system calls. */
1653 if (noninteractive)
1654 return SA_RESTART;
1655 #endif
1656 return 0;
1659 /* Store into *ACTION a signal action suitable for Emacs, with handler
1660 HANDLER. */
1661 void
1662 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1664 sigemptyset (&action->sa_mask);
1666 /* When handling a signal, block nonfatal system signals that are caught
1667 by Emacs. This makes race conditions less likely. */
1668 sigaddset (&action->sa_mask, SIGALRM);
1669 #ifdef SIGCHLD
1670 sigaddset (&action->sa_mask, SIGCHLD);
1671 #endif
1672 #ifdef SIGDANGER
1673 sigaddset (&action->sa_mask, SIGDANGER);
1674 #endif
1675 #ifdef PROFILER_CPU_SUPPORT
1676 sigaddset (&action->sa_mask, SIGPROF);
1677 #endif
1678 #ifdef SIGWINCH
1679 sigaddset (&action->sa_mask, SIGWINCH);
1680 #endif
1681 if (! noninteractive)
1683 sigaddset (&action->sa_mask, SIGINT);
1684 sigaddset (&action->sa_mask, SIGQUIT);
1685 #ifdef USABLE_SIGIO
1686 sigaddset (&action->sa_mask, SIGIO);
1687 #endif
1690 action->sa_handler = handler;
1691 action->sa_flags = emacs_sigaction_flags ();
1694 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1695 static pthread_t main_thread_id;
1696 #endif
1698 /* SIG has arrived at the current process. Deliver it to the main
1699 thread, which should handle it with HANDLER. (Delivering the
1700 signal to some other thread might not work if the other thread is
1701 about to exit.)
1703 If we are on the main thread, handle the signal SIG with HANDLER.
1704 Otherwise, redirect the signal to the main thread, blocking it from
1705 this thread. POSIX says any thread can receive a signal that is
1706 associated with a process, process group, or asynchronous event.
1707 On GNU/Linux the main thread typically gets a process signal unless
1708 it's blocked, but other systems (FreeBSD at least) can deliver the
1709 signal to other threads. */
1710 void
1711 deliver_process_signal (int sig, signal_handler_t handler)
1713 /* Preserve errno, to avoid race conditions with signal handlers that
1714 might change errno. Races can occur even in single-threaded hosts. */
1715 int old_errno = errno;
1717 bool on_main_thread = true;
1718 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1719 if (! pthread_equal (pthread_self (), main_thread_id))
1721 sigset_t blocked;
1722 sigemptyset (&blocked);
1723 sigaddset (&blocked, sig);
1724 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1725 pthread_kill (main_thread_id, sig);
1726 on_main_thread = false;
1728 #endif
1729 if (on_main_thread)
1730 handler (sig);
1732 errno = old_errno;
1735 /* Static location to save a fatal backtrace in a thread.
1736 FIXME: If two subsidiary threads fail simultaneously, the resulting
1737 backtrace may be garbage. */
1738 enum { BACKTRACE_LIMIT_MAX = 500 };
1739 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1740 static int thread_backtrace_npointers;
1742 /* SIG has arrived at the current thread.
1743 If we are on the main thread, handle the signal SIG with HANDLER.
1744 Otherwise, this is a fatal error in the handling thread. */
1745 static void
1746 deliver_thread_signal (int sig, signal_handler_t handler)
1748 int old_errno = errno;
1750 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1751 if (! pthread_equal (pthread_self (), main_thread_id))
1753 thread_backtrace_npointers
1754 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1755 sigaction (sig, &process_fatal_action, 0);
1756 pthread_kill (main_thread_id, sig);
1758 /* Avoid further damage while the main thread is exiting. */
1759 while (1)
1760 sigsuspend (&empty_mask);
1762 #endif
1764 handler (sig);
1765 errno = old_errno;
1768 #if !HAVE_DECL_SYS_SIGLIST
1769 # undef sys_siglist
1770 # ifdef _sys_siglist
1771 # define sys_siglist _sys_siglist
1772 # elif HAVE_DECL___SYS_SIGLIST
1773 # define sys_siglist __sys_siglist
1774 # else
1775 # define sys_siglist my_sys_siglist
1776 static char const *sys_siglist[NSIG];
1777 # endif
1778 #endif
1780 #ifdef _sys_nsig
1781 # define sys_siglist_entries _sys_nsig
1782 #else
1783 # define sys_siglist_entries NSIG
1784 #endif
1786 /* Handle bus errors, invalid instruction, etc. */
1787 static void
1788 handle_fatal_signal (int sig)
1790 terminate_due_to_signal (sig, 40);
1793 static void
1794 deliver_fatal_signal (int sig)
1796 deliver_process_signal (sig, handle_fatal_signal);
1799 static void
1800 deliver_fatal_thread_signal (int sig)
1802 deliver_thread_signal (sig, handle_fatal_signal);
1805 static AVOID
1806 handle_arith_signal (int sig)
1808 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1809 xsignal0 (Qarith_error);
1812 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1814 /* Alternate stack used by SIGSEGV handler below. */
1816 static unsigned char sigsegv_stack[SIGSTKSZ];
1819 /* Return true if SIGINFO indicates a stack overflow. */
1821 static bool
1822 stack_overflow (siginfo_t *siginfo)
1824 if (!attempt_stack_overflow_recovery)
1825 return false;
1827 /* In theory, a more-accurate heuristic can be obtained by using
1828 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1829 and pthread_attr_getguardsize to find the location and size of the
1830 guard area. In practice, though, these functions are so hard to
1831 use reliably that they're not worth bothering with. E.g., see:
1832 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1833 Other operating systems also have problems, e.g., Solaris's
1834 stack_violation function is tailor-made for this problem, but it
1835 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1837 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1838 candidate here. */
1840 if (!siginfo)
1841 return false;
1843 /* The faulting address. */
1844 char *addr = siginfo->si_addr;
1845 if (!addr)
1846 return false;
1848 /* The known top and bottom of the stack. The actual stack may
1849 extend a bit beyond these boundaries. */
1850 char const *bot = stack_bottom;
1851 char const *top = current_thread->stack_top;
1853 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1854 of the known stack divided by the size of the guard area past the
1855 end of the stack top. The heuristic is that a bad address is
1856 considered to be a stack overflow if it occurs within
1857 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1858 stack. This heuristic is not exactly correct but it's good
1859 enough in practice. */
1860 enum { LG_STACK_HEURISTIC = 8 };
1862 if (bot < top)
1863 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1864 else
1865 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1869 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1871 static void
1872 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1874 /* Hard GC error may lead to stack overflow caused by
1875 too nested calls to mark_object. No way to survive. */
1876 bool fatal = gc_in_progress;
1878 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1879 if (!fatal && !pthread_equal (pthread_self (), main_thread_id))
1880 fatal = true;
1881 #endif
1883 if (!fatal && stack_overflow (siginfo))
1884 siglongjmp (return_to_command_loop, 1);
1886 /* Otherwise we can't do anything with this. */
1887 deliver_fatal_thread_signal (sig);
1890 /* Return true if we have successfully set up SIGSEGV handler on alternate
1891 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1893 static bool
1894 init_sigsegv (void)
1896 struct sigaction sa;
1897 stack_t ss;
1899 ss.ss_sp = sigsegv_stack;
1900 ss.ss_size = sizeof (sigsegv_stack);
1901 ss.ss_flags = 0;
1902 if (sigaltstack (&ss, NULL) < 0)
1903 return 0;
1905 sigfillset (&sa.sa_mask);
1906 sa.sa_sigaction = handle_sigsegv;
1907 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1908 if (sigaction (SIGSEGV, &sa, NULL) < 0)
1909 return 0;
1911 return 1;
1914 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1916 static bool
1917 init_sigsegv (void)
1919 return 0;
1922 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1924 static void
1925 deliver_arith_signal (int sig)
1927 deliver_thread_signal (sig, handle_arith_signal);
1930 #ifdef SIGDANGER
1932 /* Handler for SIGDANGER. */
1933 static void
1934 handle_danger_signal (int sig)
1936 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1938 /* It might be unsafe to call do_auto_save now. */
1939 force_auto_save_soon ();
1942 static void
1943 deliver_danger_signal (int sig)
1945 deliver_process_signal (sig, handle_danger_signal);
1947 #endif
1949 /* Treat SIG as a terminating signal, unless it is already ignored and
1950 we are in --batch mode. Among other things, this makes nohup work. */
1951 static void
1952 maybe_fatal_sig (int sig)
1954 bool catch_sig = !noninteractive;
1955 if (!catch_sig)
1957 struct sigaction old_action;
1958 sigaction (sig, 0, &old_action);
1959 catch_sig = old_action.sa_handler != SIG_IGN;
1961 if (catch_sig)
1962 sigaction (sig, &process_fatal_action, 0);
1965 void
1966 init_signals (void)
1968 struct sigaction thread_fatal_action;
1969 struct sigaction action;
1971 sigemptyset (&empty_mask);
1973 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1974 main_thread_id = pthread_self ();
1975 #endif
1977 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1978 if (! initialized)
1980 sys_siglist[SIGABRT] = "Aborted";
1981 # ifdef SIGAIO
1982 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1983 # endif
1984 sys_siglist[SIGALRM] = "Alarm clock";
1985 # ifdef SIGBUS
1986 sys_siglist[SIGBUS] = "Bus error";
1987 # endif
1988 # ifdef SIGCHLD
1989 sys_siglist[SIGCHLD] = "Child status changed";
1990 # endif
1991 # ifdef SIGCONT
1992 sys_siglist[SIGCONT] = "Continued";
1993 # endif
1994 # ifdef SIGDANGER
1995 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1996 # endif
1997 # ifdef SIGDGNOTIFY
1998 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1999 # endif
2000 # ifdef SIGEMT
2001 sys_siglist[SIGEMT] = "Emulation trap";
2002 # endif
2003 sys_siglist[SIGFPE] = "Arithmetic exception";
2004 # ifdef SIGFREEZE
2005 sys_siglist[SIGFREEZE] = "SIGFREEZE";
2006 # endif
2007 # ifdef SIGGRANT
2008 sys_siglist[SIGGRANT] = "Monitor mode granted";
2009 # endif
2010 sys_siglist[SIGHUP] = "Hangup";
2011 sys_siglist[SIGILL] = "Illegal instruction";
2012 sys_siglist[SIGINT] = "Interrupt";
2013 # ifdef SIGIO
2014 sys_siglist[SIGIO] = "I/O possible";
2015 # endif
2016 # ifdef SIGIOINT
2017 sys_siglist[SIGIOINT] = "I/O intervention required";
2018 # endif
2019 # ifdef SIGIOT
2020 sys_siglist[SIGIOT] = "IOT trap";
2021 # endif
2022 sys_siglist[SIGKILL] = "Killed";
2023 # ifdef SIGLOST
2024 sys_siglist[SIGLOST] = "Resource lost";
2025 # endif
2026 # ifdef SIGLWP
2027 sys_siglist[SIGLWP] = "SIGLWP";
2028 # endif
2029 # ifdef SIGMSG
2030 sys_siglist[SIGMSG] = "Monitor mode data available";
2031 # endif
2032 # ifdef SIGPHONE
2033 sys_siglist[SIGWIND] = "SIGPHONE";
2034 # endif
2035 sys_siglist[SIGPIPE] = "Broken pipe";
2036 # ifdef SIGPOLL
2037 sys_siglist[SIGPOLL] = "Pollable event occurred";
2038 # endif
2039 # ifdef SIGPROF
2040 sys_siglist[SIGPROF] = "Profiling timer expired";
2041 # endif
2042 # ifdef SIGPTY
2043 sys_siglist[SIGPTY] = "PTY I/O interrupt";
2044 # endif
2045 # ifdef SIGPWR
2046 sys_siglist[SIGPWR] = "Power-fail restart";
2047 # endif
2048 sys_siglist[SIGQUIT] = "Quit";
2049 # ifdef SIGRETRACT
2050 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
2051 # endif
2052 # ifdef SIGSAK
2053 sys_siglist[SIGSAK] = "Secure attention";
2054 # endif
2055 sys_siglist[SIGSEGV] = "Segmentation violation";
2056 # ifdef SIGSOUND
2057 sys_siglist[SIGSOUND] = "Sound completed";
2058 # endif
2059 # ifdef SIGSTOP
2060 sys_siglist[SIGSTOP] = "Stopped (signal)";
2061 # endif
2062 # ifdef SIGSTP
2063 sys_siglist[SIGSTP] = "Stopped (user)";
2064 # endif
2065 # ifdef SIGSYS
2066 sys_siglist[SIGSYS] = "Bad argument to system call";
2067 # endif
2068 sys_siglist[SIGTERM] = "Terminated";
2069 # ifdef SIGTHAW
2070 sys_siglist[SIGTHAW] = "SIGTHAW";
2071 # endif
2072 # ifdef SIGTRAP
2073 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2074 # endif
2075 # ifdef SIGTSTP
2076 sys_siglist[SIGTSTP] = "Stopped (user)";
2077 # endif
2078 # ifdef SIGTTIN
2079 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2080 # endif
2081 # ifdef SIGTTOU
2082 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2083 # endif
2084 # ifdef SIGURG
2085 sys_siglist[SIGURG] = "Urgent I/O condition";
2086 # endif
2087 # ifdef SIGUSR1
2088 sys_siglist[SIGUSR1] = "User defined signal 1";
2089 # endif
2090 # ifdef SIGUSR2
2091 sys_siglist[SIGUSR2] = "User defined signal 2";
2092 # endif
2093 # ifdef SIGVTALRM
2094 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2095 # endif
2096 # ifdef SIGWAITING
2097 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2098 # endif
2099 # ifdef SIGWINCH
2100 sys_siglist[SIGWINCH] = "Window size changed";
2101 # endif
2102 # ifdef SIGWIND
2103 sys_siglist[SIGWIND] = "SIGWIND";
2104 # endif
2105 # ifdef SIGXCPU
2106 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2107 # endif
2108 # ifdef SIGXFSZ
2109 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2110 # endif
2112 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
2114 /* Don't alter signal handlers if dumping. On some machines,
2115 changing signal handlers sets static data that would make signals
2116 fail to work right when the dumped Emacs is run. */
2117 if (will_dump_p ())
2118 return;
2120 sigfillset (&process_fatal_action.sa_mask);
2121 process_fatal_action.sa_handler = deliver_fatal_signal;
2122 process_fatal_action.sa_flags = emacs_sigaction_flags ();
2124 sigfillset (&thread_fatal_action.sa_mask);
2125 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
2126 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
2128 /* SIGINT may need special treatment on MS-Windows. See
2129 https://lists.gnu.org/r/emacs-devel/2010-09/msg01062.html
2130 Please update the doc of kill-emacs, kill-emacs-hook, and
2131 NEWS if you change this. */
2133 maybe_fatal_sig (SIGHUP);
2134 maybe_fatal_sig (SIGINT);
2135 maybe_fatal_sig (SIGTERM);
2137 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
2138 However, in batch mode leave SIGPIPE alone, as that causes Emacs
2139 to behave more like typical batch applications do. */
2140 if (! noninteractive)
2141 signal (SIGPIPE, SIG_IGN);
2143 sigaction (SIGQUIT, &process_fatal_action, 0);
2144 sigaction (SIGILL, &thread_fatal_action, 0);
2145 sigaction (SIGTRAP, &thread_fatal_action, 0);
2147 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
2148 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
2149 interpreter's floating point operations, so treat SIGFPE as an
2150 arith-error if it arises in the main thread. */
2151 if (IEEE_FLOATING_POINT)
2152 sigaction (SIGFPE, &thread_fatal_action, 0);
2153 else
2155 emacs_sigaction_init (&action, deliver_arith_signal);
2156 sigaction (SIGFPE, &action, 0);
2159 #ifdef SIGUSR1
2160 add_user_signal (SIGUSR1, "sigusr1");
2161 #endif
2162 #ifdef SIGUSR2
2163 add_user_signal (SIGUSR2, "sigusr2");
2164 #endif
2165 sigaction (SIGABRT, &thread_fatal_action, 0);
2166 #ifdef SIGPRE
2167 sigaction (SIGPRE, &thread_fatal_action, 0);
2168 #endif
2169 #ifdef SIGORE
2170 sigaction (SIGORE, &thread_fatal_action, 0);
2171 #endif
2172 #ifdef SIGUME
2173 sigaction (SIGUME, &thread_fatal_action, 0);
2174 #endif
2175 #ifdef SIGDLK
2176 sigaction (SIGDLK, &process_fatal_action, 0);
2177 #endif
2178 #ifdef SIGCPULIM
2179 sigaction (SIGCPULIM, &process_fatal_action, 0);
2180 #endif
2181 #ifdef SIGIOT
2182 sigaction (SIGIOT, &thread_fatal_action, 0);
2183 #endif
2184 #ifdef SIGEMT
2185 sigaction (SIGEMT, &thread_fatal_action, 0);
2186 #endif
2187 #ifdef SIGBUS
2188 sigaction (SIGBUS, &thread_fatal_action, 0);
2189 #endif
2190 if (!init_sigsegv ())
2191 sigaction (SIGSEGV, &thread_fatal_action, 0);
2192 #ifdef SIGSYS
2193 sigaction (SIGSYS, &thread_fatal_action, 0);
2194 #endif
2195 sigaction (SIGTERM, &process_fatal_action, 0);
2196 #ifdef SIGPROF
2197 signal (SIGPROF, SIG_IGN);
2198 #endif
2199 #ifdef SIGVTALRM
2200 sigaction (SIGVTALRM, &process_fatal_action, 0);
2201 #endif
2202 #ifdef SIGXCPU
2203 sigaction (SIGXCPU, &process_fatal_action, 0);
2204 #endif
2205 #ifdef SIGXFSZ
2206 sigaction (SIGXFSZ, &process_fatal_action, 0);
2207 #endif
2209 #ifdef SIGDANGER
2210 /* This just means available memory is getting low. */
2211 emacs_sigaction_init (&action, deliver_danger_signal);
2212 sigaction (SIGDANGER, &action, 0);
2213 #endif
2215 /* AIX-specific signals. */
2216 #ifdef SIGGRANT
2217 sigaction (SIGGRANT, &process_fatal_action, 0);
2218 #endif
2219 #ifdef SIGMIGRATE
2220 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2221 #endif
2222 #ifdef SIGMSG
2223 sigaction (SIGMSG, &process_fatal_action, 0);
2224 #endif
2225 #ifdef SIGRETRACT
2226 sigaction (SIGRETRACT, &process_fatal_action, 0);
2227 #endif
2228 #ifdef SIGSAK
2229 sigaction (SIGSAK, &process_fatal_action, 0);
2230 #endif
2231 #ifdef SIGSOUND
2232 sigaction (SIGSOUND, &process_fatal_action, 0);
2233 #endif
2234 #ifdef SIGTALRM
2235 sigaction (SIGTALRM, &thread_fatal_action, 0);
2236 #endif
2239 #ifndef HAVE_RANDOM
2240 #ifdef random
2241 #define HAVE_RANDOM
2242 #endif
2243 #endif
2245 /* Figure out how many bits the system's random number generator uses.
2246 `random' and `lrand48' are assumed to return 31 usable bits.
2247 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2248 so we'll shift it and treat it like the 15-bit USG `rand'. */
2250 #ifndef RAND_BITS
2251 # ifdef HAVE_RANDOM
2252 # define RAND_BITS 31
2253 # else /* !HAVE_RANDOM */
2254 # ifdef HAVE_LRAND48
2255 # define RAND_BITS 31
2256 # define random lrand48
2257 # else /* !HAVE_LRAND48 */
2258 # define RAND_BITS 15
2259 # if RAND_MAX == 32767
2260 # define random rand
2261 # else /* RAND_MAX != 32767 */
2262 # if RAND_MAX == 2147483647
2263 # define random() (rand () >> 16)
2264 # else /* RAND_MAX != 2147483647 */
2265 # ifdef USG
2266 # define random rand
2267 # else
2268 # define random() (rand () >> 16)
2269 # endif /* !USG */
2270 # endif /* RAND_MAX != 2147483647 */
2271 # endif /* RAND_MAX != 32767 */
2272 # endif /* !HAVE_LRAND48 */
2273 # endif /* !HAVE_RANDOM */
2274 #endif /* !RAND_BITS */
2276 #ifdef HAVE_RANDOM
2277 typedef unsigned int random_seed;
2278 static void set_random_seed (random_seed arg) { srandom (arg); }
2279 #elif defined HAVE_LRAND48
2280 /* Although srand48 uses a long seed, this is unsigned long to avoid
2281 undefined behavior on signed integer overflow in init_random. */
2282 typedef unsigned long int random_seed;
2283 static void set_random_seed (random_seed arg) { srand48 (arg); }
2284 #else
2285 typedef unsigned int random_seed;
2286 static void set_random_seed (random_seed arg) { srand (arg); }
2287 #endif
2289 void
2290 seed_random (void *seed, ptrdiff_t seed_size)
2292 random_seed arg = 0;
2293 unsigned char *argp = (unsigned char *) &arg;
2294 unsigned char *seedp = seed;
2295 for (ptrdiff_t i = 0; i < seed_size; i++)
2296 argp[i % sizeof arg] ^= seedp[i];
2297 set_random_seed (arg);
2300 void
2301 init_random (void)
2303 random_seed v;
2304 bool success = false;
2306 /* First, try seeding the PRNG from the operating system's entropy
2307 source. This approach is both fast and secure. */
2308 #ifdef WINDOWSNT
2309 success = w32_init_random (&v, sizeof v) == 0;
2310 #else
2311 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2312 if (0 <= fd)
2314 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2315 close (fd);
2317 #endif
2319 /* If that didn't work, try using GnuTLS, which is secure, but on
2320 some systems, can be somewhat slow. */
2321 if (!success)
2322 success = EQ (emacs_gnutls_global_init (), Qt)
2323 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0;
2325 /* If _that_ didn't work, just use the current time value and PID.
2326 It's at least better than XKCD 221. */
2327 if (!success)
2329 struct timespec t = current_timespec ();
2330 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2333 set_random_seed (v);
2337 * Return a nonnegative random integer out of whatever we've got.
2338 * It contains enough bits to make a random (signed) Emacs fixnum.
2339 * This suffices even for a 64-bit architecture with a 15-bit rand.
2341 EMACS_INT
2342 get_random (void)
2344 EMACS_UINT val = 0;
2345 int i;
2346 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2347 val = (random () ^ (val << RAND_BITS)
2348 ^ (val >> (EMACS_INT_WIDTH - RAND_BITS)));
2349 val ^= val >> (EMACS_INT_WIDTH - FIXNUM_BITS);
2350 return val & INTMASK;
2353 #ifndef HAVE_SNPRINTF
2354 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2356 snprintf (char *buf, size_t bufsize, char const *format, ...)
2358 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2359 ptrdiff_t nbytes = size - 1;
2360 va_list ap;
2362 if (size)
2364 va_start (ap, format);
2365 nbytes = doprnt (buf, size, format, 0, ap);
2366 va_end (ap);
2369 if (nbytes == size - 1)
2371 /* Calculate the length of the string that would have been created
2372 had the buffer been large enough. */
2373 char stackbuf[4000];
2374 char *b = stackbuf;
2375 ptrdiff_t bsize = sizeof stackbuf;
2376 va_start (ap, format);
2377 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2378 va_end (ap);
2379 if (b != stackbuf)
2380 xfree (b);
2383 if (INT_MAX < nbytes)
2385 #ifdef EOVERFLOW
2386 errno = EOVERFLOW;
2387 #else
2388 errno = EDOM;
2389 #endif
2390 return -1;
2392 return nbytes;
2394 #endif
2396 /* If a backtrace is available, output the top lines of it to stderr.
2397 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2398 This function may be called from a signal handler, so it should
2399 not invoke async-unsafe functions like malloc.
2401 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2402 but do not output anything. This avoids some problems that can
2403 otherwise occur if the malloc arena is corrupted before 'backtrace'
2404 is called, since 'backtrace' may call malloc if the tables are not
2405 initialized.
2407 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2408 fatal error has occurred in some other thread; generate a thread
2409 backtrace instead, ignoring BACKTRACE_LIMIT. */
2410 void
2411 emacs_backtrace (int backtrace_limit)
2413 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2414 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2415 void *buffer;
2416 int npointers;
2418 if (thread_backtrace_npointers)
2420 buffer = thread_backtrace_buffer;
2421 npointers = thread_backtrace_npointers;
2423 else
2425 buffer = main_backtrace_buffer;
2427 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2428 if (bounded_limit < 0)
2430 backtrace (buffer, 1);
2431 return;
2434 npointers = backtrace (buffer, bounded_limit + 1);
2437 if (npointers)
2439 emacs_write (STDERR_FILENO, "Backtrace:\n", 11);
2440 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2441 if (bounded_limit < npointers)
2442 emacs_write (STDERR_FILENO, "...\n", 4);
2446 #ifndef HAVE_NTGUI
2447 void
2448 emacs_abort (void)
2450 terminate_due_to_signal (SIGABRT, 40);
2452 #endif
2454 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2455 Use binary I/O on systems that care about text vs binary I/O.
2456 Arrange for subprograms to not inherit the file descriptor.
2457 Prefer a method that is multithread-safe, if available.
2458 Do not fail merely because the open was interrupted by a signal.
2459 Allow the user to quit. */
2462 emacs_open (const char *file, int oflags, int mode)
2464 int fd;
2465 if (! (oflags & O_TEXT))
2466 oflags |= O_BINARY;
2467 oflags |= O_CLOEXEC;
2468 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2469 maybe_quit ();
2470 return fd;
2473 /* Open FILE as a stream for Emacs use, with mode MODE.
2474 Act like emacs_open with respect to threads, signals, and quits. */
2476 FILE *
2477 emacs_fopen (char const *file, char const *mode)
2479 int fd, omode, oflags;
2480 int bflag = 0;
2481 char const *m = mode;
2483 switch (*m++)
2485 case 'r': omode = O_RDONLY; oflags = 0; break;
2486 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2487 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2488 default: emacs_abort ();
2491 while (*m)
2492 switch (*m++)
2494 case '+': omode = O_RDWR; break;
2495 case 't': bflag = O_TEXT; break;
2496 default: /* Ignore. */ break;
2499 fd = emacs_open (file, omode | oflags | bflag, 0666);
2500 return fd < 0 ? 0 : fdopen (fd, mode);
2503 /* Create a pipe for Emacs use. */
2506 emacs_pipe (int fd[2])
2508 #ifdef MSDOS
2509 return pipe (fd);
2510 #else /* !MSDOS */
2511 return pipe2 (fd, O_BINARY | O_CLOEXEC);
2512 #endif /* !MSDOS */
2515 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2516 For the background behind this mess, please see Austin Group defect 529
2517 <http://austingroupbugs.net/view.php?id=529>. */
2519 #ifndef POSIX_CLOSE_RESTART
2520 # define POSIX_CLOSE_RESTART 1
2521 static int
2522 posix_close (int fd, int flag)
2524 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2525 eassert (flag == POSIX_CLOSE_RESTART);
2527 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2528 on a system that does not define POSIX_CLOSE_RESTART.
2530 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2531 closed, and retrying the close could inadvertently close a file
2532 descriptor allocated by some other thread. In other systems
2533 (e.g., HP/UX) FD is not closed. And in still other systems
2534 (e.g., macOS, Solaris), maybe FD is closed, maybe not, and in a
2535 multithreaded program there can be no way to tell.
2537 So, in this case, pretend that the close succeeded. This works
2538 well on systems like GNU/Linux that close FD. Although it may
2539 leak a file descriptor on other systems, the leak is unlikely and
2540 it's better to leak than to close a random victim. */
2541 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2543 #endif
2545 /* Close FD, retrying if interrupted. If successful, return 0;
2546 otherwise, return -1 and set errno to a non-EINTR value. Consider
2547 an EINPROGRESS error to be successful, as that's merely a signal
2548 arriving. FD is always closed when this function returns, even
2549 when it returns -1.
2551 Do not call this function if FD is nonnegative and might already be closed,
2552 as that might close an innocent victim opened by some other thread. */
2555 emacs_close (int fd)
2557 while (1)
2559 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2560 if (r == 0)
2561 return r;
2562 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2564 eassert (errno != EBADF || fd < 0);
2565 return errno == EINPROGRESS ? 0 : r;
2570 /* Maximum number of bytes to read or write in a single system call.
2571 This works around a serious bug in Linux kernels before 2.6.16; see
2572 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2573 It's likely to work around similar bugs in other operating systems, so do it
2574 on all platforms. Round INT_MAX down to a page size, with the conservative
2575 assumption that page sizes are at most 2**18 bytes (any kernel with a
2576 page size larger than that shouldn't have the bug). */
2577 #ifndef MAX_RW_COUNT
2578 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2579 #endif
2581 /* Verify that MAX_RW_COUNT fits in the relevant standard types. */
2582 #ifndef SSIZE_MAX
2583 # define SSIZE_MAX TYPE_MAXIMUM (ssize_t)
2584 #endif
2585 verify (MAX_RW_COUNT <= PTRDIFF_MAX);
2586 verify (MAX_RW_COUNT <= SIZE_MAX);
2587 verify (MAX_RW_COUNT <= SSIZE_MAX);
2589 #ifdef WINDOWSNT
2590 /* Verify that Emacs read requests cannot cause trouble, even in
2591 64-bit builds. The last argument of 'read' is 'unsigned int', and
2592 the return value's type (see 'sys_read') is 'int'. */
2593 verify (MAX_RW_COUNT <= INT_MAX);
2594 verify (MAX_RW_COUNT <= UINT_MAX);
2595 #endif
2597 /* Read from FD to a buffer BUF with size NBYTE.
2598 If interrupted, process any quits and pending signals immediately
2599 if INTERRUPTIBLE, and then retry the read unless quitting.
2600 Return the number of bytes read, which might be less than NBYTE.
2601 On error, set errno to a value other than EINTR, and return -1. */
2602 static ptrdiff_t
2603 emacs_intr_read (int fd, void *buf, ptrdiff_t nbyte, bool interruptible)
2605 /* No caller should ever pass a too-large size to emacs_read. */
2606 eassert (nbyte <= MAX_RW_COUNT);
2608 ssize_t result;
2612 if (interruptible)
2613 maybe_quit ();
2614 result = read (fd, buf, nbyte);
2616 while (result < 0 && errno == EINTR);
2618 return result;
2621 /* Read from FD to a buffer BUF with size NBYTE.
2622 If interrupted, retry the read. Return the number of bytes read,
2623 which might be less than NBYTE. On error, set errno to a value
2624 other than EINTR, and return -1. */
2625 ptrdiff_t
2626 emacs_read (int fd, void *buf, ptrdiff_t nbyte)
2628 return emacs_intr_read (fd, buf, nbyte, false);
2631 /* Like emacs_read, but also process quits and pending signals. */
2632 ptrdiff_t
2633 emacs_read_quit (int fd, void *buf, ptrdiff_t nbyte)
2635 return emacs_intr_read (fd, buf, nbyte, true);
2638 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2639 interrupted or if a partial write occurs. Process any quits
2640 immediately if INTERRUPTIBLE is positive, and process any pending
2641 signals immediately if INTERRUPTIBLE is nonzero. Return the number
2642 of bytes written; if this is less than NBYTE, set errno to a value
2643 other than EINTR. */
2644 static ptrdiff_t
2645 emacs_full_write (int fd, char const *buf, ptrdiff_t nbyte,
2646 int interruptible)
2648 ptrdiff_t bytes_written = 0;
2650 while (nbyte > 0)
2652 ssize_t n = write (fd, buf, min (nbyte, MAX_RW_COUNT));
2654 if (n < 0)
2656 if (errno != EINTR)
2657 break;
2659 if (interruptible)
2661 if (0 < interruptible)
2662 maybe_quit ();
2663 if (pending_signals)
2664 process_pending_signals ();
2667 else
2669 buf += n;
2670 nbyte -= n;
2671 bytes_written += n;
2675 return bytes_written;
2678 /* Write to FD from a buffer BUF with size NBYTE, retrying if
2679 interrupted or if a partial write occurs. Do not process quits or
2680 pending signals. Return the number of bytes written, setting errno
2681 if this is less than NBYTE. */
2682 ptrdiff_t
2683 emacs_write (int fd, void const *buf, ptrdiff_t nbyte)
2685 return emacs_full_write (fd, buf, nbyte, 0);
2688 /* Like emacs_write, but also process pending signals. */
2689 ptrdiff_t
2690 emacs_write_sig (int fd, void const *buf, ptrdiff_t nbyte)
2692 return emacs_full_write (fd, buf, nbyte, -1);
2695 /* Like emacs_write, but also process quits and pending signals. */
2696 ptrdiff_t
2697 emacs_write_quit (int fd, void const *buf, ptrdiff_t nbyte)
2699 return emacs_full_write (fd, buf, nbyte, 1);
2702 /* Write a diagnostic to standard error that contains MESSAGE and a
2703 string derived from errno. Preserve errno. Do not buffer stderr.
2704 Do not process quits or pending signals if interrupted. */
2705 void
2706 emacs_perror (char const *message)
2708 int err = errno;
2709 char const *error_string = emacs_strerror (err);
2710 char const *command = (initial_argv && initial_argv[0]
2711 ? initial_argv[0] : "emacs");
2712 /* Write it out all at once, if it's short; this is less likely to
2713 be interleaved with other output. */
2714 char buf[min (PIPE_BUF, MAX_ALLOCA)];
2715 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2716 command, message, error_string);
2717 if (0 <= nbytes && nbytes < sizeof buf)
2718 emacs_write (STDERR_FILENO, buf, nbytes);
2719 else
2721 emacs_write (STDERR_FILENO, command, strlen (command));
2722 emacs_write (STDERR_FILENO, ": ", 2);
2723 emacs_write (STDERR_FILENO, message, strlen (message));
2724 emacs_write (STDERR_FILENO, ": ", 2);
2725 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2726 emacs_write (STDERR_FILENO, "\n", 1);
2728 errno = err;
2731 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2732 ATIME and MTIME, respectively.
2733 FD must be either negative -- in which case it is ignored --
2734 or a file descriptor that is open on FILE.
2735 If FD is nonnegative, then FILE can be NULL. */
2737 set_file_times (int fd, const char *filename,
2738 struct timespec atime, struct timespec mtime)
2740 struct timespec timespec[2];
2741 timespec[0] = atime;
2742 timespec[1] = mtime;
2743 return fdutimens (fd, filename, timespec);
2746 /* Rename directory SRCFD's entry SRC to directory DSTFD's entry DST.
2747 This is like renameat except that it fails if DST already exists,
2748 or if this operation is not supported atomically. Return 0 if
2749 successful, -1 (setting errno) otherwise. */
2751 renameat_noreplace (int srcfd, char const *src, int dstfd, char const *dst)
2753 #if defined SYS_renameat2 && defined RENAME_NOREPLACE
2754 return syscall (SYS_renameat2, srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2755 #elif defined CYGWIN && defined RENAME_NOREPLACE
2756 return renameat2 (srcfd, src, dstfd, dst, RENAME_NOREPLACE);
2757 #elif defined RENAME_EXCL
2758 return renameatx_np (srcfd, src, dstfd, dst, RENAME_EXCL);
2759 #else
2760 # ifdef WINDOWSNT
2761 if (srcfd == AT_FDCWD && dstfd == AT_FDCWD)
2762 return sys_rename_replace (src, dst, 0);
2763 # endif
2764 errno = ENOSYS;
2765 return -1;
2766 #endif
2769 /* Like strsignal, except async-signal-safe, and this function typically
2770 returns a string in the C locale rather than the current locale. */
2771 char const *
2772 safe_strsignal (int code)
2774 char const *signame = 0;
2776 if (0 <= code && code < sys_siglist_entries)
2777 signame = sys_siglist[code];
2778 if (! signame)
2779 signame = "Unknown signal";
2781 return signame;
2784 /* Output to stderr. */
2786 /* Return the error output stream. */
2787 static FILE *
2788 errstream (void)
2790 FILE *err = buferr;
2791 if (!err)
2792 return stderr;
2793 fflush_unlocked (stderr);
2794 return err;
2797 /* These functions are like fputc, vfprintf, and fwrite,
2798 except that they output to stderr and buffer better on
2799 platforms that support line buffering. This avoids interleaving
2800 output when Emacs and other processes write to stderr
2801 simultaneously, so long as the lines are short enough. When a
2802 single diagnostic is emitted via a sequence of calls of one or more
2803 of these functions, the caller should arrange for the last called
2804 function to output a newline at the end. */
2806 void
2807 errputc (int c)
2809 fputc_unlocked (c, errstream ());
2812 void
2813 verrprintf (char const *fmt, va_list ap)
2815 vfprintf (errstream (), fmt, ap);
2818 void
2819 errwrite (void const *buf, ptrdiff_t nbuf)
2821 fwrite_unlocked (buf, 1, nbuf, errstream ());
2824 /* Close standard output and standard error, reporting any write
2825 errors as best we can. This is intended for use with atexit. */
2826 void
2827 close_output_streams (void)
2829 if (close_stream (stdout) != 0)
2831 emacs_perror ("Write error to standard output");
2832 _exit (EXIT_FAILURE);
2835 /* Do not close stderr if addresses are being sanitized, as the
2836 sanitizer might report to stderr after this function is invoked. */
2837 bool err = buferr && (fflush (buferr) != 0 || ferror (buferr));
2838 if (err | (ADDRESS_SANITIZER
2839 ? fflush (stderr) != 0 || ferror (stderr)
2840 : close_stream (stderr) != 0))
2841 _exit (EXIT_FAILURE);
2844 #ifndef DOS_NT
2845 /* For make-serial-process */
2847 serial_open (Lisp_Object port)
2849 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2850 if (fd < 0)
2851 report_file_error ("Opening serial port", port);
2852 #ifdef TIOCEXCL
2853 ioctl (fd, TIOCEXCL, (char *) 0);
2854 #endif
2856 return fd;
2859 #if !defined (HAVE_CFMAKERAW)
2860 /* Workaround for targets which are missing cfmakeraw. */
2861 /* Pasted from man page. */
2862 static void
2863 cfmakeraw (struct termios *termios_p)
2865 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2866 termios_p->c_oflag &= ~OPOST;
2867 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2868 termios_p->c_cflag &= ~(CSIZE|PARENB);
2869 termios_p->c_cflag |= CS8;
2871 #endif /* !defined (HAVE_CFMAKERAW */
2873 #if !defined (HAVE_CFSETSPEED)
2874 /* Workaround for targets which are missing cfsetspeed. */
2875 static int
2876 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2878 return (cfsetispeed (termios_p, vitesse)
2879 + cfsetospeed (termios_p, vitesse));
2881 #endif
2883 /* For serial-process-configure */
2884 void
2885 serial_configure (struct Lisp_Process *p,
2886 Lisp_Object contact)
2888 Lisp_Object childp2 = Qnil;
2889 Lisp_Object tem = Qnil;
2890 struct termios attr;
2891 int err;
2892 char summary[4] = "???"; /* This usually becomes "8N1". */
2894 childp2 = Fcopy_sequence (p->childp);
2896 /* Read port attributes and prepare default configuration. */
2897 err = tcgetattr (p->outfd, &attr);
2898 if (err != 0)
2899 report_file_error ("Failed tcgetattr", Qnil);
2900 cfmakeraw (&attr);
2901 #if defined (CLOCAL)
2902 attr.c_cflag |= CLOCAL;
2903 #endif
2904 #if defined (CREAD)
2905 attr.c_cflag |= CREAD;
2906 #endif
2908 /* Configure speed. */
2909 if (!NILP (Fplist_member (contact, QCspeed)))
2910 tem = Fplist_get (contact, QCspeed);
2911 else
2912 tem = Fplist_get (p->childp, QCspeed);
2913 CHECK_FIXNUM (tem);
2914 err = cfsetspeed (&attr, XFIXNUM (tem));
2915 if (err != 0)
2916 report_file_error ("Failed cfsetspeed", tem);
2917 childp2 = Fplist_put (childp2, QCspeed, tem);
2919 /* Configure bytesize. */
2920 if (!NILP (Fplist_member (contact, QCbytesize)))
2921 tem = Fplist_get (contact, QCbytesize);
2922 else
2923 tem = Fplist_get (p->childp, QCbytesize);
2924 if (NILP (tem))
2925 tem = make_fixnum (8);
2926 CHECK_FIXNUM (tem);
2927 if (XFIXNUM (tem) != 7 && XFIXNUM (tem) != 8)
2928 error (":bytesize must be nil (8), 7, or 8");
2929 summary[0] = XFIXNUM (tem) + '0';
2930 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2931 attr.c_cflag &= ~CSIZE;
2932 attr.c_cflag |= ((XFIXNUM (tem) == 7) ? CS7 : CS8);
2933 #else
2934 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2935 if (XFIXNUM (tem) != 8)
2936 error ("Bytesize cannot be changed");
2937 #endif
2938 childp2 = Fplist_put (childp2, QCbytesize, tem);
2940 /* Configure parity. */
2941 if (!NILP (Fplist_member (contact, QCparity)))
2942 tem = Fplist_get (contact, QCparity);
2943 else
2944 tem = Fplist_get (p->childp, QCparity);
2945 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2946 error (":parity must be nil (no parity), `even', or `odd'");
2947 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2948 attr.c_cflag &= ~(PARENB | PARODD);
2949 attr.c_iflag &= ~(IGNPAR | INPCK);
2950 if (NILP (tem))
2952 summary[1] = 'N';
2954 else if (EQ (tem, Qeven))
2956 summary[1] = 'E';
2957 attr.c_cflag |= PARENB;
2958 attr.c_iflag |= (IGNPAR | INPCK);
2960 else if (EQ (tem, Qodd))
2962 summary[1] = 'O';
2963 attr.c_cflag |= (PARENB | PARODD);
2964 attr.c_iflag |= (IGNPAR | INPCK);
2966 #else
2967 /* Don't error on no parity, which should be set by cfmakeraw. */
2968 if (!NILP (tem))
2969 error ("Parity cannot be configured");
2970 #endif
2971 childp2 = Fplist_put (childp2, QCparity, tem);
2973 /* Configure stopbits. */
2974 if (!NILP (Fplist_member (contact, QCstopbits)))
2975 tem = Fplist_get (contact, QCstopbits);
2976 else
2977 tem = Fplist_get (p->childp, QCstopbits);
2978 if (NILP (tem))
2979 tem = make_fixnum (1);
2980 CHECK_FIXNUM (tem);
2981 if (XFIXNUM (tem) != 1 && XFIXNUM (tem) != 2)
2982 error (":stopbits must be nil (1 stopbit), 1, or 2");
2983 summary[2] = XFIXNUM (tem) + '0';
2984 #if defined (CSTOPB)
2985 attr.c_cflag &= ~CSTOPB;
2986 if (XFIXNUM (tem) == 2)
2987 attr.c_cflag |= CSTOPB;
2988 #else
2989 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2990 if (XFIXNUM (tem) != 1)
2991 error ("Stopbits cannot be configured");
2992 #endif
2993 childp2 = Fplist_put (childp2, QCstopbits, tem);
2995 /* Configure flowcontrol. */
2996 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2997 tem = Fplist_get (contact, QCflowcontrol);
2998 else
2999 tem = Fplist_get (p->childp, QCflowcontrol);
3000 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
3001 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
3002 #if defined (CRTSCTS)
3003 attr.c_cflag &= ~CRTSCTS;
3004 #endif
3005 #if defined (CNEW_RTSCTS)
3006 attr.c_cflag &= ~CNEW_RTSCTS;
3007 #endif
3008 #if defined (IXON) && defined (IXOFF)
3009 attr.c_iflag &= ~(IXON | IXOFF);
3010 #endif
3011 if (NILP (tem))
3013 /* Already configured. */
3015 else if (EQ (tem, Qhw))
3017 #if defined (CRTSCTS)
3018 attr.c_cflag |= CRTSCTS;
3019 #elif defined (CNEW_RTSCTS)
3020 attr.c_cflag |= CNEW_RTSCTS;
3021 #else
3022 error ("Hardware flowcontrol (RTS/CTS) not supported");
3023 #endif
3025 else if (EQ (tem, Qsw))
3027 #if defined (IXON) && defined (IXOFF)
3028 attr.c_iflag |= (IXON | IXOFF);
3029 #else
3030 error ("Software flowcontrol (XON/XOFF) not supported");
3031 #endif
3033 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
3035 /* Activate configuration. */
3036 err = tcsetattr (p->outfd, TCSANOW, &attr);
3037 if (err != 0)
3038 report_file_error ("Failed tcsetattr", Qnil);
3040 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
3041 pset_childp (p, childp2);
3043 #endif /* not DOS_NT */
3045 /* System depended enumeration of and access to system processes a-la ps(1). */
3047 #ifdef HAVE_PROCFS
3049 /* Process enumeration and access via /proc. */
3051 Lisp_Object
3052 list_system_processes (void)
3054 Lisp_Object procdir, match, proclist, next;
3055 Lisp_Object tail;
3057 /* For every process on the system, there's a directory in the
3058 "/proc" pseudo-directory whose name is the numeric ID of that
3059 process. */
3060 procdir = build_string ("/proc");
3061 match = build_string ("[0-9]+");
3062 proclist = directory_files_internal (procdir, Qnil, match, Qt, false, Qnil);
3064 /* `proclist' gives process IDs as strings. Destructively convert
3065 each string into a number. */
3066 for (tail = proclist; CONSP (tail); tail = next)
3068 next = XCDR (tail);
3069 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
3072 /* directory_files_internal returns the files in reverse order; undo
3073 that. */
3074 proclist = Fnreverse (proclist);
3075 return proclist;
3078 #elif defined DARWIN_OS || defined __FreeBSD__
3080 Lisp_Object
3081 list_system_processes (void)
3083 #ifdef DARWIN_OS
3084 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
3085 #else
3086 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
3087 #endif
3088 size_t len;
3089 struct kinfo_proc *procs;
3090 size_t i;
3092 Lisp_Object proclist = Qnil;
3094 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0 || len == 0)
3095 return proclist;
3097 procs = xmalloc (len);
3098 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0 || len == 0)
3100 xfree (procs);
3101 return proclist;
3104 len /= sizeof (struct kinfo_proc);
3105 for (i = 0; i < len; i++)
3107 #ifdef DARWIN_OS
3108 proclist = Fcons (INT_TO_INTEGER (procs[i].kp_proc.p_pid), proclist);
3109 #else
3110 proclist = Fcons (INT_TO_INTEGER (procs[i].ki_pid), proclist);
3111 #endif
3114 xfree (procs);
3116 return proclist;
3119 /* The WINDOWSNT implementation is in w32.c.
3120 The MSDOS implementation is in dosfns.c. */
3121 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3123 Lisp_Object
3124 list_system_processes (void)
3126 return Qnil;
3129 #endif /* !defined (WINDOWSNT) */
3132 #if defined __FreeBSD__ || defined DARWIN_OS
3134 static struct timespec
3135 timeval_to_timespec (struct timeval t)
3137 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3139 static Lisp_Object
3140 make_lisp_timeval (struct timeval t)
3142 return make_lisp_time (timeval_to_timespec (t));
3145 #endif
3147 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
3148 static struct timespec
3149 time_from_jiffies (unsigned long long tval, long hz)
3151 unsigned long long s = tval / hz;
3152 unsigned long long frac = tval % hz;
3153 int ns;
3155 if (TYPE_MAXIMUM (time_t) < s)
3156 time_overflow ();
3157 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_HZ
3158 || frac <= ULLONG_MAX / TIMESPEC_HZ)
3159 ns = frac * TIMESPEC_HZ / hz;
3160 else
3162 /* This is reachable only in the unlikely case that HZ * HZ
3163 exceeds ULLONG_MAX. It calculates an approximation that is
3164 guaranteed to be in range. */
3165 long hz_per_ns = hz / TIMESPEC_HZ + (hz % TIMESPEC_HZ != 0);
3166 ns = frac / hz_per_ns;
3169 return make_timespec (s, ns);
3172 static Lisp_Object
3173 ltime_from_jiffies (unsigned long long tval, long hz)
3175 struct timespec t = time_from_jiffies (tval, hz);
3176 return make_lisp_time (t);
3179 static struct timespec
3180 get_up_time (void)
3182 FILE *fup;
3183 struct timespec up = make_timespec (0, 0);
3185 block_input ();
3186 fup = emacs_fopen ("/proc/uptime", "r");
3188 if (fup)
3190 unsigned long long upsec, upfrac;
3191 int upfrac_start, upfrac_end;
3193 if (fscanf (fup, "%llu.%n%llu%n",
3194 &upsec, &upfrac_start, &upfrac, &upfrac_end)
3195 == 2)
3197 if (TYPE_MAXIMUM (time_t) < upsec)
3199 upsec = TYPE_MAXIMUM (time_t);
3200 upfrac = TIMESPEC_HZ - 1;
3202 else
3204 int upfraclen = upfrac_end - upfrac_start;
3205 for (; upfraclen < LOG10_TIMESPEC_HZ; upfraclen++)
3206 upfrac *= 10;
3207 for (; LOG10_TIMESPEC_HZ < upfraclen; upfraclen--)
3208 upfrac /= 10;
3209 upfrac = min (upfrac, TIMESPEC_HZ - 1);
3211 up = make_timespec (upsec, upfrac);
3213 fclose (fup);
3215 unblock_input ();
3217 return up;
3220 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3221 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3223 static Lisp_Object
3224 procfs_ttyname (int rdev)
3226 FILE *fdev;
3227 char name[PATH_MAX];
3229 block_input ();
3230 fdev = emacs_fopen ("/proc/tty/drivers", "r");
3231 name[0] = 0;
3233 if (fdev)
3235 unsigned major;
3236 unsigned long minor_beg, minor_end;
3237 char minor[25]; /* 2 32-bit numbers + dash */
3238 char *endp;
3240 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
3242 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
3243 && major == MAJOR (rdev))
3245 minor_beg = strtoul (minor, &endp, 0);
3246 if (*endp == '\0')
3247 minor_end = minor_beg;
3248 else if (*endp == '-')
3249 minor_end = strtoul (endp + 1, &endp, 0);
3250 else
3251 continue;
3253 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3255 sprintf (name + strlen (name), "%u", MINOR (rdev));
3256 break;
3260 fclose (fdev);
3262 unblock_input ();
3263 return build_string (name);
3266 static uintmax_t
3267 procfs_get_total_memory (void)
3269 FILE *fmem;
3270 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
3271 int c;
3273 block_input ();
3274 fmem = emacs_fopen ("/proc/meminfo", "r");
3276 if (fmem)
3278 uintmax_t entry_value;
3279 bool done;
3282 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3284 case 1:
3285 retval = entry_value;
3286 done = 1;
3287 break;
3289 case 0:
3290 while ((c = getc (fmem)) != EOF && c != '\n')
3291 continue;
3292 done = c == EOF;
3293 break;
3295 default:
3296 done = 1;
3297 break;
3299 while (!done);
3301 fclose (fmem);
3303 unblock_input ();
3304 return retval;
3307 Lisp_Object
3308 system_process_attributes (Lisp_Object pid)
3310 char procfn[PATH_MAX], fn[PATH_MAX];
3311 struct stat st;
3312 struct passwd *pw;
3313 struct group *gr;
3314 long clocks_per_sec;
3315 char *procfn_end;
3316 char procbuf[1025], *p, *q UNINIT;
3317 int fd;
3318 ssize_t nread;
3319 static char const default_cmd[] = "???";
3320 const char *cmd = default_cmd;
3321 int cmdsize = sizeof default_cmd - 1;
3322 char *cmdline = NULL;
3323 ptrdiff_t cmdline_size;
3324 char c;
3325 intmax_t proc_id;
3326 int ppid, pgrp, sess, tty, tpgid, thcount;
3327 uid_t uid;
3328 gid_t gid;
3329 unsigned long long u_time, s_time, cutime, cstime, start;
3330 long priority, niceness, rss;
3331 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3332 struct timespec tnow, tstart, tboot, telapsed, us_time;
3333 double pcpu, pmem;
3334 Lisp_Object attrs = Qnil;
3335 Lisp_Object decoded_cmd;
3336 ptrdiff_t count;
3338 CHECK_NUMBER (pid);
3339 CONS_TO_INTEGER (pid, pid_t, proc_id);
3340 sprintf (procfn, "/proc/%"PRIdMAX, proc_id);
3341 if (stat (procfn, &st) < 0)
3342 return attrs;
3344 /* euid egid */
3345 uid = st.st_uid;
3346 attrs = Fcons (Fcons (Qeuid, INT_TO_INTEGER (uid)), attrs);
3347 block_input ();
3348 pw = getpwuid (uid);
3349 unblock_input ();
3350 if (pw)
3351 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3353 gid = st.st_gid;
3354 attrs = Fcons (Fcons (Qegid, INT_TO_INTEGER (gid)), attrs);
3355 block_input ();
3356 gr = getgrgid (gid);
3357 unblock_input ();
3358 if (gr)
3359 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3361 count = SPECPDL_INDEX ();
3362 strcpy (fn, procfn);
3363 procfn_end = fn + strlen (fn);
3364 strcpy (procfn_end, "/stat");
3365 fd = emacs_open (fn, O_RDONLY, 0);
3366 if (fd < 0)
3367 nread = 0;
3368 else
3370 record_unwind_protect_int (close_file_unwind, fd);
3371 nread = emacs_read_quit (fd, procbuf, sizeof procbuf - 1);
3373 if (0 < nread)
3375 procbuf[nread] = '\0';
3376 p = procbuf;
3378 p = strchr (p, '(');
3379 if (p != NULL)
3381 q = strrchr (p + 1, ')');
3382 /* comm */
3383 if (q != NULL)
3385 cmd = p + 1;
3386 cmdsize = q - cmd;
3389 else
3390 q = NULL;
3391 /* Command name is encoded in locale-coding-system; decode it. */
3392 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3393 decoded_cmd = code_convert_string_norecord (cmd_str,
3394 Vlocale_coding_system, 0);
3395 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3397 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3398 utime stime cutime cstime priority nice thcount . start vsize rss */
3399 if (q
3400 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3401 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3402 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3403 &minflt, &cminflt, &majflt, &cmajflt,
3404 &u_time, &s_time, &cutime, &cstime,
3405 &priority, &niceness, &thcount, &start, &vsize, &rss)
3406 == 20))
3408 char state_str[2];
3409 state_str[0] = c;
3410 state_str[1] = '\0';
3411 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3412 attrs = Fcons (Fcons (Qppid, INT_TO_INTEGER (ppid)), attrs);
3413 attrs = Fcons (Fcons (Qpgrp, INT_TO_INTEGER (pgrp)), attrs);
3414 attrs = Fcons (Fcons (Qsess, INT_TO_INTEGER (sess)), attrs);
3415 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3416 attrs = Fcons (Fcons (Qtpgid, INT_TO_INTEGER (tpgid)), attrs);
3417 attrs = Fcons (Fcons (Qminflt, INT_TO_INTEGER (minflt)), attrs);
3418 attrs = Fcons (Fcons (Qmajflt, INT_TO_INTEGER (majflt)), attrs);
3419 attrs = Fcons (Fcons (Qcminflt, INT_TO_INTEGER (cminflt)), attrs);
3420 attrs = Fcons (Fcons (Qcmajflt, INT_TO_INTEGER (cmajflt)), attrs);
3421 clocks_per_sec = sysconf (_SC_CLK_TCK);
3422 if (clocks_per_sec < 0)
3423 clocks_per_sec = 100;
3424 attrs = Fcons (Fcons (Qutime,
3425 ltime_from_jiffies (u_time, clocks_per_sec)),
3426 attrs);
3427 attrs = Fcons (Fcons (Qstime,
3428 ltime_from_jiffies (s_time, clocks_per_sec)),
3429 attrs);
3430 attrs = Fcons (Fcons (Qtime,
3431 ltime_from_jiffies (s_time + u_time,
3432 clocks_per_sec)),
3433 attrs);
3434 attrs = Fcons (Fcons (Qcutime,
3435 ltime_from_jiffies (cutime, clocks_per_sec)),
3436 attrs);
3437 attrs = Fcons (Fcons (Qcstime,
3438 ltime_from_jiffies (cstime, clocks_per_sec)),
3439 attrs);
3440 attrs = Fcons (Fcons (Qctime,
3441 ltime_from_jiffies (cstime + cutime,
3442 clocks_per_sec)),
3443 attrs);
3444 attrs = Fcons (Fcons (Qpri, make_fixnum (priority)), attrs);
3445 attrs = Fcons (Fcons (Qnice, make_fixnum (niceness)), attrs);
3446 attrs = Fcons (Fcons (Qthcount, INT_TO_INTEGER (thcount)), attrs);
3447 tnow = current_timespec ();
3448 telapsed = get_up_time ();
3449 tboot = timespec_sub (tnow, telapsed);
3450 tstart = time_from_jiffies (start, clocks_per_sec);
3451 tstart = timespec_add (tboot, tstart);
3452 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3453 attrs = Fcons (Fcons (Qvsize, INT_TO_INTEGER (vsize / 1024)), attrs);
3454 attrs = Fcons (Fcons (Qrss, INT_TO_INTEGER (4 * rss)), attrs);
3455 telapsed = timespec_sub (tnow, tstart);
3456 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3457 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3458 pcpu = timespectod (us_time) / timespectod (telapsed);
3459 if (pcpu > 1.0)
3460 pcpu = 1.0;
3461 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3462 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3463 if (pmem > 100)
3464 pmem = 100;
3465 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3468 unbind_to (count, Qnil);
3470 /* args */
3471 strcpy (procfn_end, "/cmdline");
3472 fd = emacs_open (fn, O_RDONLY, 0);
3473 if (fd >= 0)
3475 ptrdiff_t readsize, nread_incr;
3476 record_unwind_protect_int (close_file_unwind, fd);
3477 record_unwind_protect_nothing ();
3478 nread = cmdline_size = 0;
3482 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3483 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3485 /* Leave room even if every byte needs escaping below. */
3486 readsize = (cmdline_size >> 1) - nread;
3488 nread_incr = emacs_read_quit (fd, cmdline + nread, readsize);
3489 nread += max (0, nread_incr);
3491 while (nread_incr == readsize);
3493 if (nread)
3495 /* We don't want trailing NUL characters. */
3496 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3497 continue;
3499 /* Escape-quote whitespace and backslashes. */
3500 q = cmdline + cmdline_size;
3501 while (cmdline < p)
3503 char c = *--p;
3504 *--q = c ? c : ' ';
3505 if (c_isspace (c) || c == '\\')
3506 *--q = '\\';
3509 nread = cmdline + cmdline_size - q;
3512 if (!nread)
3514 nread = cmdsize + 2;
3515 cmdline_size = nread + 1;
3516 q = cmdline = xrealloc (cmdline, cmdline_size);
3517 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3518 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3520 /* Command line is encoded in locale-coding-system; decode it. */
3521 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3522 decoded_cmd = code_convert_string_norecord (cmd_str,
3523 Vlocale_coding_system, 0);
3524 unbind_to (count, Qnil);
3525 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3528 return attrs;
3531 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3533 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3534 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3535 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3536 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3537 #undef _FILE_OFFSET_BITS
3538 #else
3539 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3540 #endif
3542 #include <procfs.h>
3544 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3545 #define _FILE_OFFSET_BITS 64
3546 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3547 #endif
3548 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3550 Lisp_Object
3551 system_process_attributes (Lisp_Object pid)
3553 char procfn[PATH_MAX], fn[PATH_MAX];
3554 struct stat st;
3555 struct passwd *pw;
3556 struct group *gr;
3557 char *procfn_end;
3558 struct psinfo pinfo;
3559 int fd;
3560 ssize_t nread;
3561 intmax_t proc_id;
3562 uid_t uid;
3563 gid_t gid;
3564 Lisp_Object attrs = Qnil;
3565 Lisp_Object decoded_cmd;
3566 ptrdiff_t count;
3568 CHECK_NUMBER (pid);
3569 CONS_TO_INTEGER (pid, pid_t, proc_id);
3570 sprintf (procfn, "/proc/%"PRIdMAX, proc_id);
3571 if (stat (procfn, &st) < 0)
3572 return attrs;
3574 /* euid egid */
3575 uid = st.st_uid;
3576 attrs = Fcons (Fcons (Qeuid, INT_TO_INTEGER (uid)), attrs);
3577 block_input ();
3578 pw = getpwuid (uid);
3579 unblock_input ();
3580 if (pw)
3581 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3583 gid = st.st_gid;
3584 attrs = Fcons (Fcons (Qegid, INT_TO_INTEGER (gid)), attrs);
3585 block_input ();
3586 gr = getgrgid (gid);
3587 unblock_input ();
3588 if (gr)
3589 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3591 count = SPECPDL_INDEX ();
3592 strcpy (fn, procfn);
3593 procfn_end = fn + strlen (fn);
3594 strcpy (procfn_end, "/psinfo");
3595 fd = emacs_open (fn, O_RDONLY, 0);
3596 if (fd < 0)
3597 nread = 0;
3598 else
3600 record_unwind_protect_int (close_file_unwind, fd);
3601 nread = emacs_read_quit (fd, &pinfo, sizeof pinfo);
3604 if (nread == sizeof pinfo)
3606 attrs = Fcons (Fcons (Qppid, INT_TO_INTEGER (pinfo.pr_ppid)), attrs);
3607 attrs = Fcons (Fcons (Qpgrp, INT_TO_INTEGER (pinfo.pr_pgid)), attrs);
3608 attrs = Fcons (Fcons (Qsess, INT_TO_INTEGER (pinfo.pr_sid)), attrs);
3611 char state_str[2];
3612 state_str[0] = pinfo.pr_lwp.pr_sname;
3613 state_str[1] = '\0';
3614 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3617 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3618 need to get a string from it. */
3620 /* FIXME: missing: Qtpgid */
3622 /* FIXME: missing:
3623 Qminflt
3624 Qmajflt
3625 Qcminflt
3626 Qcmajflt
3628 Qutime
3629 Qcutime
3630 Qstime
3631 Qcstime
3632 Are they available? */
3634 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3635 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3636 attrs = Fcons (Fcons (Qpri, make_fixnum (pinfo.pr_lwp.pr_pri)), attrs);
3637 attrs = Fcons (Fcons (Qnice, make_fixnum (pinfo.pr_lwp.pr_nice)), attrs);
3638 attrs = Fcons (Fcons (Qthcount, INT_TO_INTEGER (pinfo.pr_nlwp)), attrs);
3640 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3641 attrs = Fcons (Fcons (Qvsize, INT_TO_INTEGER (pinfo.pr_size)), attrs);
3642 attrs = Fcons (Fcons (Qrss, INT_TO_INTEGER (pinfo.pr_rssize)), attrs);
3644 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3645 range 0 .. 2**15, representing 0.0 .. 1.0. */
3646 attrs = Fcons (Fcons (Qpcpu,
3647 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3648 attrs);
3649 attrs = Fcons (Fcons (Qpmem,
3650 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3651 attrs);
3653 AUTO_STRING (fname, pinfo.pr_fname);
3654 decoded_cmd = code_convert_string_norecord (fname,
3655 Vlocale_coding_system, 0);
3656 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3657 AUTO_STRING (psargs, pinfo.pr_psargs);
3658 decoded_cmd = code_convert_string_norecord (psargs,
3659 Vlocale_coding_system, 0);
3660 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3662 return unbind_to (count, attrs);
3665 #elif defined __FreeBSD__
3667 Lisp_Object
3668 system_process_attributes (Lisp_Object pid)
3670 int proc_id;
3671 int pagesize = getpagesize ();
3672 unsigned long npages;
3673 int fscale;
3674 struct passwd *pw;
3675 struct group *gr;
3676 char *ttyname;
3677 size_t len;
3678 char args[MAXPATHLEN];
3679 struct timespec t, now;
3681 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3682 struct kinfo_proc proc;
3683 size_t proclen = sizeof proc;
3685 Lisp_Object attrs = Qnil;
3686 Lisp_Object decoded_comm;
3688 CHECK_NUMBER (pid);
3689 CONS_TO_INTEGER (pid, int, proc_id);
3690 mib[3] = proc_id;
3692 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0 || proclen == 0)
3693 return attrs;
3695 attrs = Fcons (Fcons (Qeuid, INT_TO_INTEGER (proc.ki_uid)), attrs);
3697 block_input ();
3698 pw = getpwuid (proc.ki_uid);
3699 unblock_input ();
3700 if (pw)
3701 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3703 attrs = Fcons (Fcons (Qegid, INT_TO_INTEGER (proc.ki_svgid)), attrs);
3705 block_input ();
3706 gr = getgrgid (proc.ki_svgid);
3707 unblock_input ();
3708 if (gr)
3709 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3711 AUTO_STRING (comm, proc.ki_comm);
3712 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3714 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3716 char state[2] = {'\0', '\0'};
3717 switch (proc.ki_stat)
3719 case SRUN:
3720 state[0] = 'R';
3721 break;
3723 case SSLEEP:
3724 state[0] = 'S';
3725 break;
3727 case SLOCK:
3728 state[0] = 'D';
3729 break;
3731 case SZOMB:
3732 state[0] = 'Z';
3733 break;
3735 case SSTOP:
3736 state[0] = 'T';
3737 break;
3739 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3742 attrs = Fcons (Fcons (Qppid, INT_TO_INTEGER (proc.ki_ppid)), attrs);
3743 attrs = Fcons (Fcons (Qpgrp, INT_TO_INTEGER (proc.ki_pgid)), attrs);
3744 attrs = Fcons (Fcons (Qsess, INT_TO_INTEGER (proc.ki_sid)), attrs);
3746 block_input ();
3747 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3748 unblock_input ();
3749 if (ttyname)
3750 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3752 attrs = Fcons (Fcons (Qtpgid, INT_TO_INTEGER (proc.ki_tpgid)), attrs);
3753 attrs = Fcons (Fcons (Qminflt, INT_TO_INTEGER (proc.ki_rusage.ru_minflt)),
3754 attrs);
3755 attrs = Fcons (Fcons (Qmajflt, INT_TO_INTEGER (proc.ki_rusage.ru_majflt)),
3756 attrs);
3757 attrs = Fcons (Fcons (Qcminflt, make_fixnum (proc.ki_rusage_ch.ru_minflt)), attrs);
3758 attrs = Fcons (Fcons (Qcmajflt, make_fixnum (proc.ki_rusage_ch.ru_majflt)), attrs);
3760 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3761 attrs);
3762 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3763 attrs);
3764 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3765 timeval_to_timespec (proc.ki_rusage.ru_stime));
3766 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3768 attrs = Fcons (Fcons (Qcutime,
3769 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3770 attrs);
3771 attrs = Fcons (Fcons (Qcstime,
3772 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3773 attrs);
3774 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3775 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3776 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3778 attrs = Fcons (Fcons (Qthcount, INT_TO_INTEGER (proc.ki_numthreads)), attrs);
3779 attrs = Fcons (Fcons (Qpri, make_fixnum (proc.ki_pri.pri_native)), attrs);
3780 attrs = Fcons (Fcons (Qnice, make_fixnum (proc.ki_nice)), attrs);
3781 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3782 attrs = Fcons (Fcons (Qvsize, make_fixnum (proc.ki_size >> 10)), attrs);
3783 attrs = Fcons (Fcons (Qrss, make_fixnum (proc.ki_rssize * pagesize >> 10)),
3784 attrs);
3786 now = current_timespec ();
3787 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3788 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3790 len = sizeof fscale;
3791 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3793 double pcpu;
3794 fixpt_t ccpu;
3795 len = sizeof ccpu;
3796 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3798 pcpu = (100.0 * proc.ki_pctcpu / fscale
3799 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3800 attrs = Fcons (Fcons (Qpcpu, INT_TO_INTEGER (pcpu)), attrs);
3804 len = sizeof npages;
3805 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3807 double pmem = (proc.ki_flag & P_INMEM
3808 ? 100.0 * proc.ki_rssize / npages
3809 : 0);
3810 attrs = Fcons (Fcons (Qpmem, INT_TO_INTEGER (pmem)), attrs);
3813 mib[2] = KERN_PROC_ARGS;
3814 len = MAXPATHLEN;
3815 if (sysctl (mib, 4, args, &len, NULL, 0) == 0 && len != 0)
3817 int i;
3818 for (i = 0; i < len; i++)
3820 if (! args[i] && i < len - 1)
3821 args[i] = ' ';
3824 AUTO_STRING (comm, args);
3825 decoded_comm = code_convert_string_norecord (comm,
3826 Vlocale_coding_system, 0);
3828 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3831 return attrs;
3834 #elif defined DARWIN_OS
3836 Lisp_Object
3837 system_process_attributes (Lisp_Object pid)
3839 int proc_id;
3840 struct passwd *pw;
3841 struct group *gr;
3842 char *ttyname;
3843 struct timeval starttime;
3844 struct timespec t, now;
3845 struct rusage *rusage;
3846 dev_t tdev;
3847 uid_t uid;
3848 gid_t gid;
3850 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3851 struct kinfo_proc proc;
3852 size_t proclen = sizeof proc;
3854 Lisp_Object attrs = Qnil;
3855 Lisp_Object decoded_comm;
3857 CHECK_NUMBER (pid);
3858 CONS_TO_INTEGER (pid, int, proc_id);
3859 mib[3] = proc_id;
3861 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0 || proclen == 0)
3862 return attrs;
3864 uid = proc.kp_eproc.e_ucred.cr_uid;
3865 attrs = Fcons (Fcons (Qeuid, INT_TO_INTEGER (uid)), attrs);
3867 block_input ();
3868 pw = getpwuid (uid);
3869 unblock_input ();
3870 if (pw)
3871 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3873 gid = proc.kp_eproc.e_pcred.p_svgid;
3874 attrs = Fcons (Fcons (Qegid, INT_TO_INTEGER (gid)), attrs);
3876 block_input ();
3877 gr = getgrgid (gid);
3878 unblock_input ();
3879 if (gr)
3880 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3882 decoded_comm = (code_convert_string_norecord
3883 (build_unibyte_string (proc.kp_proc.p_comm),
3884 Vlocale_coding_system, 0));
3886 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3888 char state[2] = {'\0', '\0'};
3889 switch (proc.kp_proc.p_stat)
3891 case SRUN:
3892 state[0] = 'R';
3893 break;
3895 case SSLEEP:
3896 state[0] = 'S';
3897 break;
3899 case SZOMB:
3900 state[0] = 'Z';
3901 break;
3903 case SSTOP:
3904 state[0] = 'T';
3905 break;
3907 case SIDL:
3908 state[0] = 'I';
3909 break;
3911 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3914 attrs = Fcons (Fcons (Qppid, INT_TO_INTEGER (proc.kp_eproc.e_ppid)), attrs);
3915 attrs = Fcons (Fcons (Qpgrp, INT_TO_INTEGER (proc.kp_eproc.e_pgid)), attrs);
3917 tdev = proc.kp_eproc.e_tdev;
3918 block_input ();
3919 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3920 unblock_input ();
3921 if (ttyname)
3922 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3924 attrs = Fcons (Fcons (Qtpgid, INT_TO_INTEGER (proc.kp_eproc.e_tpgid)),
3925 attrs);
3927 rusage = proc.kp_proc.p_ru;
3928 if (rusage)
3930 attrs = Fcons (Fcons (Qminflt, INT_TO_INTEGER (rusage->ru_minflt)),
3931 attrs);
3932 attrs = Fcons (Fcons (Qmajflt, INT_TO_INTEGER (rusage->ru_majflt)),
3933 attrs);
3935 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3936 attrs);
3937 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3938 attrs);
3939 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3940 timeval_to_timespec (rusage->ru_stime));
3941 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3944 starttime = proc.kp_proc.p_starttime;
3945 attrs = Fcons (Fcons (Qnice, make_fixnum (proc.kp_proc.p_nice)), attrs);
3946 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3948 now = current_timespec ();
3949 t = timespec_sub (now, timeval_to_timespec (starttime));
3950 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3952 return attrs;
3955 /* The WINDOWSNT implementation is in w32.c.
3956 The MSDOS implementation is in dosfns.c. */
3957 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3959 Lisp_Object
3960 system_process_attributes (Lisp_Object pid)
3962 return Qnil;
3965 #endif /* !defined (WINDOWSNT) */
3967 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
3968 0, 0, 0,
3969 doc: /* Return the current run time used by Emacs.
3970 The time is returned as in the style of `current-time'.
3972 On systems that can't determine the run time, `get-internal-run-time'
3973 does the same thing as `current-time'. */)
3974 (void)
3976 #ifdef HAVE_GETRUSAGE
3977 struct rusage usage;
3978 time_t secs;
3979 int usecs;
3981 if (getrusage (RUSAGE_SELF, &usage) < 0)
3982 /* This shouldn't happen. What action is appropriate? */
3983 xsignal0 (Qerror);
3985 /* Sum up user time and system time. */
3986 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
3987 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
3988 if (usecs >= 1000000)
3990 usecs -= 1000000;
3991 secs++;
3993 return make_lisp_time (make_timespec (secs, usecs * 1000));
3994 #else /* ! HAVE_GETRUSAGE */
3995 #ifdef WINDOWSNT
3996 return w32_get_internal_run_time ();
3997 #else /* ! WINDOWSNT */
3998 return Fcurrent_time ();
3999 #endif /* WINDOWSNT */
4000 #endif /* HAVE_GETRUSAGE */
4003 /* Wide character string collation. */
4005 #ifdef __STDC_ISO_10646__
4006 # include <wchar.h>
4007 # include <wctype.h>
4009 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
4010 # include <locale.h>
4011 # endif
4012 # ifndef LC_COLLATE
4013 # define LC_COLLATE 0
4014 # endif
4015 # ifndef LC_COLLATE_MASK
4016 # define LC_COLLATE_MASK 0
4017 # endif
4018 # ifndef LC_CTYPE
4019 # define LC_CTYPE 0
4020 # endif
4021 # ifndef LC_CTYPE_MASK
4022 # define LC_CTYPE_MASK 0
4023 # endif
4025 # ifndef HAVE_NEWLOCALE
4026 # undef freelocale
4027 # undef locale_t
4028 # undef newlocale
4029 # undef wcscoll_l
4030 # undef towlower_l
4031 # define freelocale emacs_freelocale
4032 # define locale_t emacs_locale_t
4033 # define newlocale emacs_newlocale
4034 # define wcscoll_l emacs_wcscoll_l
4035 # define towlower_l emacs_towlower_l
4037 typedef char const *locale_t;
4039 static locale_t
4040 newlocale (int category_mask, char const *locale, locale_t loc)
4042 return locale;
4045 static void
4046 freelocale (locale_t loc)
4050 static char *
4051 emacs_setlocale (int category, char const *locale)
4053 # ifdef HAVE_SETLOCALE
4054 errno = 0;
4055 char *loc = setlocale (category, locale);
4056 if (loc || errno)
4057 return loc;
4058 errno = EINVAL;
4059 # else
4060 errno = ENOTSUP;
4061 # endif
4062 return 0;
4065 static int
4066 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
4068 int result = 0;
4069 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
4070 int err;
4072 if (! oldloc)
4073 err = errno;
4074 else
4076 USE_SAFE_ALLOCA;
4077 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
4078 strcpy (oldcopy, oldloc);
4079 if (! emacs_setlocale (LC_COLLATE, loc))
4080 err = errno;
4081 else
4083 errno = 0;
4084 result = wcscoll (a, b);
4085 err = errno;
4086 if (! emacs_setlocale (LC_COLLATE, oldcopy))
4087 err = errno;
4089 SAFE_FREE ();
4092 errno = err;
4093 return result;
4096 static wint_t
4097 towlower_l (wint_t wc, locale_t loc)
4099 wint_t result = wc;
4100 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
4102 if (oldloc)
4104 USE_SAFE_ALLOCA;
4105 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
4106 strcpy (oldcopy, oldloc);
4107 if (emacs_setlocale (LC_CTYPE, loc))
4109 result = towlower (wc);
4110 emacs_setlocale (LC_COLLATE, oldcopy);
4112 SAFE_FREE ();
4115 return result;
4117 # endif
4120 str_collate (Lisp_Object s1, Lisp_Object s2,
4121 Lisp_Object locale, Lisp_Object ignore_case)
4123 int res, err;
4124 ptrdiff_t len, i, i_byte;
4125 wchar_t *p1, *p2;
4127 USE_SAFE_ALLOCA;
4129 /* Convert byte stream to code points. */
4130 len = SCHARS (s1); i = i_byte = 0;
4131 SAFE_NALLOCA (p1, 1, len + 1);
4132 while (i < len)
4133 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
4134 *(p1+len) = 0;
4136 len = SCHARS (s2); i = i_byte = 0;
4137 SAFE_NALLOCA (p2, 1, len + 1);
4138 while (i < len)
4139 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
4140 *(p2+len) = 0;
4142 if (STRINGP (locale))
4144 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
4145 SSDATA (locale), 0);
4146 if (!loc)
4147 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
4149 if (! NILP (ignore_case))
4150 for (int i = 1; i < 3; i++)
4152 wchar_t *p = (i == 1) ? p1 : p2;
4153 for (; *p; p++)
4154 *p = towlower_l (*p, loc);
4157 errno = 0;
4158 res = wcscoll_l (p1, p2, loc);
4159 err = errno;
4160 freelocale (loc);
4162 else
4164 if (! NILP (ignore_case))
4165 for (int i = 1; i < 3; i++)
4167 wchar_t *p = (i == 1) ? p1 : p2;
4168 for (; *p; p++)
4169 *p = towlower (*p);
4172 errno = 0;
4173 res = wcscoll (p1, p2);
4174 err = errno;
4176 # ifndef HAVE_NEWLOCALE
4177 if (err)
4178 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
4179 # else
4180 if (err)
4181 error ("Invalid string for collation: %s", emacs_strerror (err));
4182 # endif
4184 SAFE_FREE ();
4185 return res;
4187 #endif /* __STDC_ISO_10646__ */
4189 #ifdef WINDOWSNT
4191 str_collate (Lisp_Object s1, Lisp_Object s2,
4192 Lisp_Object locale, Lisp_Object ignore_case)
4195 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
4196 int res, err = errno;
4198 errno = 0;
4199 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
4200 if (errno)
4201 error ("Invalid string for collation: %s", strerror (errno));
4203 errno = err;
4204 return res;
4206 #endif /* WINDOWSNT */
4208 void
4209 syms_of_sysdep (void)
4211 defsubr (&Sget_internal_run_time);