]> code.delx.au - gnu-emacs/blob - src/sysdep.c
; Merge from origin/emacs-25
[gnu-emacs] / src / sysdep.c
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2016 Free Software
3 Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include <config.h>
21
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 <unistd.h>
30
31 #include <c-ctype.h>
32 #include <utimens.h>
33
34 #include "lisp.h"
35 #include "sheap.h"
36 #include "sysselect.h"
37 #include "blockinput.h"
38
39 #if defined DARWIN_OS || defined __FreeBSD__
40 # include <sys/sysctl.h>
41 #endif
42
43 #ifdef __FreeBSD__
44 /* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
45 'struct frame', so rename it. */
46 # define frame freebsd_frame
47 # include <sys/user.h>
48 # undef frame
49
50 # include <math.h>
51 #endif
52
53 #ifdef WINDOWSNT
54 #define read sys_read
55 #define write sys_write
56 #ifndef STDERR_FILENO
57 #define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
58 #endif
59 #include <windows.h>
60 #endif /* not WINDOWSNT */
61
62 #include <sys/types.h>
63 #include <sys/stat.h>
64 #include <errno.h>
65
66 /* Get SI_SRPC_DOMAIN, if it is available. */
67 #ifdef HAVE_SYS_SYSTEMINFO_H
68 #include <sys/systeminfo.h>
69 #endif
70
71 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
72 #include "msdos.h"
73 #endif
74
75 #include <sys/param.h>
76 #include <sys/file.h>
77 #include <fcntl.h>
78
79 #include "systty.h"
80 #include "syswait.h"
81
82 #ifdef HAVE_SYS_UTSNAME_H
83 #include <sys/utsname.h>
84 #include <memory.h>
85 #endif /* HAVE_SYS_UTSNAME_H */
86
87 #include "keyboard.h"
88 #include "frame.h"
89 #include "termhooks.h"
90 #include "termchar.h"
91 #include "termopts.h"
92 #include "process.h"
93 #include "cm.h"
94
95 #include "gnutls.h"
96 /* MS-Windows loads GnuTLS at run time, if available; we don't want to
97 do that during startup just to call gnutls_rnd. */
98 #if 0x020c00 <= GNUTLS_VERSION_NUMBER && !defined WINDOWSNT
99 # include <gnutls/crypto.h>
100 #else
101 # define emacs_gnutls_global_init() Qnil
102 # define gnutls_rnd(level, data, len) (-1)
103 #endif
104
105 #ifdef WINDOWSNT
106 #include <direct.h>
107 /* In process.h which conflicts with the local copy. */
108 #define _P_WAIT 0
109 int _cdecl _spawnlp (int, const char *, const char *, ...);
110 /* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
111 several prototypes of functions called below. */
112 #include <sys/socket.h>
113 #endif
114
115 #include "syssignal.h"
116 #include "systime.h"
117
118 /* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781. */
119 #ifndef ULLONG_MAX
120 #define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
121 #endif
122
123 /* Declare here, including term.h is problematic on some systems. */
124 extern void tputs (const char *, int, int (*)(int));
125
126 static const int baud_convert[] =
127 {
128 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
129 1800, 2400, 4800, 9600, 19200, 38400
130 };
131
132 /* If FD is not already open, arrange for it to be open with FLAGS. */
133 static void
134 force_open (int fd, int flags)
135 {
136 if (dup2 (fd, fd) < 0 && errno == EBADF)
137 {
138 int n = open (NULL_DEVICE, flags);
139 if (n < 0 || (fd != n && (dup2 (n, fd) < 0 || emacs_close (n) != 0)))
140 {
141 emacs_perror (NULL_DEVICE);
142 exit (EXIT_FAILURE);
143 }
144 }
145 }
146
147 /* Make sure stdin, stdout, and stderr are open to something, so that
148 their file descriptors are not hijacked by later system calls. */
149 void
150 init_standard_fds (void)
151 {
152 /* Open stdin for *writing*, and stdout and stderr for *reading*.
153 That way, any attempt to do normal I/O will result in an error,
154 just as if the files were closed, and the file descriptors will
155 not be reused by later opens. */
156 force_open (STDIN_FILENO, O_WRONLY);
157 force_open (STDOUT_FILENO, O_RDONLY);
158 force_open (STDERR_FILENO, O_RDONLY);
159 }
160
161 /* Return the current working directory. The result should be freed
162 with 'free'. Return NULL on errors. */
163 char *
164 emacs_get_current_dir_name (void)
165 {
166 # if HAVE_GET_CURRENT_DIR_NAME && !BROKEN_GET_CURRENT_DIR_NAME
167 # ifdef HYBRID_MALLOC
168 bool use_libc = bss_sbrk_did_unexec;
169 # else
170 bool use_libc = true;
171 # endif
172 if (use_libc)
173 return get_current_dir_name ();
174 # endif
175
176 char *buf;
177 char *pwd = getenv ("PWD");
178 struct stat dotstat, pwdstat;
179 /* If PWD is accurate, use it instead of calling getcwd. PWD is
180 sometimes a nicer name, and using it may avoid a fatal error if a
181 parent directory is searchable but not readable. */
182 if (pwd
183 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
184 && stat (pwd, &pwdstat) == 0
185 && stat (".", &dotstat) == 0
186 && dotstat.st_ino == pwdstat.st_ino
187 && dotstat.st_dev == pwdstat.st_dev
188 #ifdef MAXPATHLEN
189 && strlen (pwd) < MAXPATHLEN
190 #endif
191 )
192 {
193 buf = malloc (strlen (pwd) + 1);
194 if (!buf)
195 return NULL;
196 strcpy (buf, pwd);
197 }
198 else
199 {
200 size_t buf_size = 1024;
201 buf = malloc (buf_size);
202 if (!buf)
203 return NULL;
204 for (;;)
205 {
206 if (getcwd (buf, buf_size) == buf)
207 break;
208 if (errno != ERANGE)
209 {
210 int tmp_errno = errno;
211 free (buf);
212 errno = tmp_errno;
213 return NULL;
214 }
215 buf_size *= 2;
216 buf = realloc (buf, buf_size);
217 if (!buf)
218 return NULL;
219 }
220 }
221 return buf;
222 }
223
224 \f
225 /* Discard pending input on all input descriptors. */
226
227 void
228 discard_tty_input (void)
229 {
230 #ifndef WINDOWSNT
231 struct emacs_tty buf;
232
233 if (noninteractive)
234 return;
235
236 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
237 while (dos_keyread () != -1)
238 ;
239 #else /* not MSDOS */
240 {
241 struct tty_display_info *tty;
242 for (tty = tty_list; tty; tty = tty->next)
243 {
244 if (tty->input) /* Is the device suspended? */
245 {
246 emacs_get_tty (fileno (tty->input), &buf);
247 emacs_set_tty (fileno (tty->input), &buf, 0);
248 }
249 }
250 }
251 #endif /* not MSDOS */
252 #endif /* not WINDOWSNT */
253 }
254
255 \f
256 #ifdef SIGTSTP
257
258 /* Arrange for character C to be read as the next input from
259 the terminal.
260 XXX What if we have multiple ttys?
261 */
262
263 void
264 stuff_char (char c)
265 {
266 if (! (FRAMEP (selected_frame)
267 && FRAME_LIVE_P (XFRAME (selected_frame))
268 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
269 return;
270
271 /* Should perhaps error if in batch mode */
272 #ifdef TIOCSTI
273 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
274 #else /* no TIOCSTI */
275 error ("Cannot stuff terminal input characters in this version of Unix");
276 #endif /* no TIOCSTI */
277 }
278
279 #endif /* SIGTSTP */
280 \f
281 void
282 init_baud_rate (int fd)
283 {
284 int emacs_ospeed;
285
286 if (noninteractive)
287 emacs_ospeed = 0;
288 else
289 {
290 #ifdef DOS_NT
291 emacs_ospeed = 15;
292 #else /* not DOS_NT */
293 struct termios sg;
294
295 sg.c_cflag = B9600;
296 tcgetattr (fd, &sg);
297 emacs_ospeed = cfgetospeed (&sg);
298 #endif /* not DOS_NT */
299 }
300
301 baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
302 ? baud_convert[emacs_ospeed] : 9600);
303 if (baud_rate == 0)
304 baud_rate = 1200;
305 }
306
307 \f
308
309 #ifndef MSDOS
310
311 /* Wait for the subprocess with process id CHILD to terminate or change status.
312 CHILD must be a child process that has not been reaped.
313 If STATUS is non-null, store the waitpid-style exit status into *STATUS
314 and tell wait_reading_process_output that it needs to look around.
315 Use waitpid-style OPTIONS when waiting.
316 If INTERRUPTIBLE, this function is interruptible by a signal.
317
318 Return CHILD if successful, 0 if no status is available;
319 the latter is possible only when options & NOHANG. */
320 static pid_t
321 get_child_status (pid_t child, int *status, int options, bool interruptible)
322 {
323 pid_t pid;
324
325 /* Invoke waitpid only with a known process ID; do not invoke
326 waitpid with a nonpositive argument. Otherwise, Emacs might
327 reap an unwanted process by mistake. For example, invoking
328 waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
329 so that another thread running glib won't find them. */
330 eassert (child > 0);
331
332 while ((pid = waitpid (child, status, options)) < 0)
333 {
334 /* Check that CHILD is a child process that has not been reaped,
335 and that STATUS and OPTIONS are valid. Otherwise abort,
336 as continuing after this internal error could cause Emacs to
337 become confused and kill innocent-victim processes. */
338 if (errno != EINTR)
339 emacs_abort ();
340
341 /* Note: the MS-Windows emulation of waitpid calls QUIT
342 internally. */
343 if (interruptible)
344 QUIT;
345 }
346
347 /* If successful and status is requested, tell wait_reading_process_output
348 that it needs to wake up and look around. */
349 if (pid && status && input_available_clear_time)
350 *input_available_clear_time = make_timespec (0, 0);
351
352 return pid;
353 }
354
355 /* Wait for the subprocess with process id CHILD to terminate.
356 CHILD must be a child process that has not been reaped.
357 If STATUS is non-null, store the waitpid-style exit status into *STATUS
358 and tell wait_reading_process_output that it needs to look around.
359 If INTERRUPTIBLE, this function is interruptible by a signal. */
360 void
361 wait_for_termination (pid_t child, int *status, bool interruptible)
362 {
363 get_child_status (child, status, 0, interruptible);
364 }
365
366 /* Report whether the subprocess with process id CHILD has changed status.
367 Termination counts as a change of status.
368 CHILD must be a child process that has not been reaped.
369 If STATUS is non-null, store the waitpid-style exit status into *STATUS
370 and tell wait_reading_process_output that it needs to look around.
371 Use waitpid-style OPTIONS to check status, but do not wait.
372
373 Return CHILD if successful, 0 if no status is available because
374 the process's state has not changed. */
375 pid_t
376 child_status_changed (pid_t child, int *status, int options)
377 {
378 return get_child_status (child, status, WNOHANG | options, 0);
379 }
380
381 \f
382 /* Set up the terminal at the other end of a pseudo-terminal that
383 we will be controlling an inferior through.
384 It should not echo or do line-editing, since that is done
385 in Emacs. No padding needed for insertion into an Emacs buffer. */
386
387 void
388 child_setup_tty (int out)
389 {
390 #ifndef WINDOWSNT
391 struct emacs_tty s;
392
393 emacs_get_tty (out, &s);
394 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
395 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
396 #ifdef NLDLY
397 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
398 Some versions of GNU Hurd do not have FFDLY? */
399 #ifdef FFDLY
400 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
401 /* No output delays */
402 #else
403 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
404 /* No output delays */
405 #endif
406 #endif
407 s.main.c_lflag &= ~ECHO; /* Disable echo */
408 s.main.c_lflag |= ISIG; /* Enable signals */
409 #ifdef IUCLC
410 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
411 #endif
412 #ifdef ISTRIP
413 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
414 #endif
415 #ifdef OLCUC
416 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
417 #endif
418 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
419 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
420 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
421 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
422
423 #ifdef HPUX
424 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
425 #endif /* HPUX */
426
427 #ifdef SIGNALS_VIA_CHARACTERS
428 /* the QUIT and INTR character are used in process_send_signal
429 so set them here to something useful. */
430 if (s.main.c_cc[VQUIT] == CDISABLE)
431 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
432 if (s.main.c_cc[VINTR] == CDISABLE)
433 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
434 #endif /* not SIGNALS_VIA_CHARACTERS */
435
436 #ifdef AIX
437 /* Also, PTY overloads NUL and BREAK.
438 don't ignore break, but don't signal either, so it looks like NUL. */
439 s.main.c_iflag &= ~IGNBRK;
440 s.main.c_iflag &= ~BRKINT;
441 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
442 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
443 would force it to 0377. That looks like duplicated code. */
444 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
445 #endif /* AIX */
446
447 /* We originally enabled ICANON (and set VEOF to 04), and then had
448 process.c send additional EOF chars to flush the output when faced
449 with long lines, but this leads to weird effects when the
450 subprocess has disabled ICANON and ends up seeing those spurious
451 extra EOFs. So we don't send EOFs any more in
452 process.c:send_process. First we tried to disable ICANON by
453 default, so if a subsprocess sets up ICANON, it's his problem (or
454 the Elisp package that talks to it) to deal with lines that are
455 too long. But this disables some features, such as the ability
456 to send EOF signals. So we re-enabled ICANON but there is no
457 more "send eof to flush" going on (which is wrong and unportable
458 in itself). The correct way to handle too much output is to
459 buffer what could not be written and then write it again when
460 select returns ok for writing. This has it own set of
461 problems. Write is now asynchronous, is that a problem? How much
462 do we buffer, and what do we do when that limit is reached? */
463
464 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
465 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
466 #if 0 /* These settings only apply to non-ICANON mode. */
467 s.main.c_cc[VMIN] = 1;
468 s.main.c_cc[VTIME] = 0;
469 #endif
470
471 emacs_set_tty (out, &s, 0);
472 #endif /* not WINDOWSNT */
473 }
474 #endif /* not MSDOS */
475
476 \f
477 /* Record a signal code and the action for it. */
478 struct save_signal
479 {
480 int code;
481 struct sigaction action;
482 };
483
484 static void save_signal_handlers (struct save_signal *);
485 static void restore_signal_handlers (struct save_signal *);
486
487 /* Suspend the Emacs process; give terminal to its superior. */
488
489 void
490 sys_suspend (void)
491 {
492 #ifndef DOS_NT
493 kill (0, SIGTSTP);
494 #else
495 /* On a system where suspending is not implemented,
496 instead fork a subshell and let it talk directly to the terminal
497 while we wait. */
498 sys_subshell ();
499
500 #endif
501 }
502
503 /* Fork a subshell. */
504
505 void
506 sys_subshell (void)
507 {
508 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
509 #ifdef MSDOS
510 int st;
511 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
512 #else
513 char oldwd[MAX_UTF8_PATH];
514 #endif /* MSDOS */
515 #else /* !DOS_NT */
516 int status;
517 #endif
518 pid_t pid;
519 struct save_signal saved_handlers[5];
520 char *str = SSDATA (encode_current_directory ());
521
522 #ifdef DOS_NT
523 pid = 0;
524 #else
525 {
526 char *volatile str_volatile = str;
527 pid = vfork ();
528 str = str_volatile;
529 }
530 #endif
531
532 if (pid < 0)
533 error ("Can't spawn subshell");
534
535 saved_handlers[0].code = SIGINT;
536 saved_handlers[1].code = SIGQUIT;
537 saved_handlers[2].code = SIGTERM;
538 #ifdef USABLE_SIGIO
539 saved_handlers[3].code = SIGIO;
540 saved_handlers[4].code = 0;
541 #else
542 saved_handlers[3].code = 0;
543 #endif
544
545 #ifdef DOS_NT
546 save_signal_handlers (saved_handlers);
547 #endif
548
549 if (pid == 0)
550 {
551 const char *sh = 0;
552
553 #ifdef DOS_NT /* MW, Aug 1993 */
554 getcwd (oldwd, sizeof oldwd);
555 if (sh == 0)
556 sh = egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
557 #endif
558 if (sh == 0)
559 sh = egetenv ("SHELL");
560 if (sh == 0)
561 sh = "sh";
562
563 /* Use our buffer's default directory for the subshell. */
564 if (chdir (str) != 0)
565 {
566 #ifndef DOS_NT
567 emacs_perror (str);
568 _exit (EXIT_CANCELED);
569 #endif
570 }
571
572 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
573 {
574 char *epwd = getenv ("PWD");
575 char old_pwd[MAXPATHLEN+1+4];
576
577 /* If PWD is set, pass it with corrected value. */
578 if (epwd)
579 {
580 strcpy (old_pwd, epwd);
581 setenv ("PWD", str, 1);
582 }
583 st = system (sh);
584 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
585 if (epwd)
586 putenv (old_pwd); /* restore previous value */
587 }
588 #else /* not MSDOS */
589 #ifdef WINDOWSNT
590 /* Waits for process completion */
591 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
592 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
593 if (pid == -1)
594 write (1, "Can't execute subshell", 22);
595 #else /* not WINDOWSNT */
596 execlp (sh, sh, (char *) 0);
597 emacs_perror (sh);
598 _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
599 #endif /* not WINDOWSNT */
600 #endif /* not MSDOS */
601 }
602
603 /* Do this now if we did not do it before. */
604 #ifndef MSDOS
605 save_signal_handlers (saved_handlers);
606 #endif
607
608 #ifndef DOS_NT
609 wait_for_termination (pid, &status, 0);
610 #endif
611 restore_signal_handlers (saved_handlers);
612 }
613
614 static void
615 save_signal_handlers (struct save_signal *saved_handlers)
616 {
617 while (saved_handlers->code)
618 {
619 struct sigaction action;
620 emacs_sigaction_init (&action, SIG_IGN);
621 sigaction (saved_handlers->code, &action, &saved_handlers->action);
622 saved_handlers++;
623 }
624 }
625
626 static void
627 restore_signal_handlers (struct save_signal *saved_handlers)
628 {
629 while (saved_handlers->code)
630 {
631 sigaction (saved_handlers->code, &saved_handlers->action, 0);
632 saved_handlers++;
633 }
634 }
635 \f
636 #ifdef USABLE_SIGIO
637 static int old_fcntl_flags[FD_SETSIZE];
638 #endif
639
640 void
641 init_sigio (int fd)
642 {
643 #ifdef USABLE_SIGIO
644 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
645 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
646 interrupts_deferred = 0;
647 #endif
648 }
649
650 #ifndef DOS_NT
651 static void
652 reset_sigio (int fd)
653 {
654 #ifdef USABLE_SIGIO
655 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
656 #endif
657 }
658 #endif
659
660 void
661 request_sigio (void)
662 {
663 #ifdef USABLE_SIGIO
664 sigset_t unblocked;
665
666 if (noninteractive)
667 return;
668
669 sigemptyset (&unblocked);
670 # ifdef SIGWINCH
671 sigaddset (&unblocked, SIGWINCH);
672 # endif
673 sigaddset (&unblocked, SIGIO);
674 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
675
676 interrupts_deferred = 0;
677 #endif
678 }
679
680 void
681 unrequest_sigio (void)
682 {
683 #ifdef USABLE_SIGIO
684 sigset_t blocked;
685
686 if (noninteractive)
687 return;
688
689 sigemptyset (&blocked);
690 # ifdef SIGWINCH
691 sigaddset (&blocked, SIGWINCH);
692 # endif
693 sigaddset (&blocked, SIGIO);
694 pthread_sigmask (SIG_BLOCK, &blocked, 0);
695 interrupts_deferred = 1;
696 #endif
697 }
698 \f
699 #ifndef MSDOS
700 /* Block SIGCHLD. */
701
702 void
703 block_child_signal (sigset_t *oldset)
704 {
705 sigset_t blocked;
706 sigemptyset (&blocked);
707 sigaddset (&blocked, SIGCHLD);
708 sigaddset (&blocked, SIGINT);
709 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
710 }
711
712 /* Unblock SIGCHLD. */
713
714 void
715 unblock_child_signal (sigset_t const *oldset)
716 {
717 pthread_sigmask (SIG_SETMASK, oldset, 0);
718 }
719
720 #endif /* !MSDOS */
721 \f
722 /* Saving and restoring the process group of Emacs's terminal. */
723
724 /* The process group of which Emacs was a member when it initially
725 started.
726
727 If Emacs was in its own process group (i.e. inherited_pgroup ==
728 getpid ()), then we know we're running under a shell with job
729 control (Emacs would never be run as part of a pipeline).
730 Everything is fine.
731
732 If Emacs was not in its own process group, then we know we're
733 running under a shell (or a caller) that doesn't know how to
734 separate itself from Emacs (like sh). Emacs must be in its own
735 process group in order to receive SIGIO correctly. In this
736 situation, we put ourselves in our own pgroup, forcibly set the
737 tty's pgroup to our pgroup, and make sure to restore and reinstate
738 the tty's pgroup just like any other terminal setting. If
739 inherited_group was not the tty's pgroup, then we'll get a
740 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
741 it goes foreground in the future, which is what should happen. */
742
743 static pid_t inherited_pgroup;
744
745 void
746 init_foreground_group (void)
747 {
748 pid_t pgrp = getpgrp ();
749 inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
750 }
751
752 /* Block and unblock SIGTTOU. */
753
754 void
755 block_tty_out_signal (sigset_t *oldset)
756 {
757 #ifdef SIGTTOU
758 sigset_t blocked;
759 sigemptyset (&blocked);
760 sigaddset (&blocked, SIGTTOU);
761 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
762 #endif
763 }
764
765 void
766 unblock_tty_out_signal (sigset_t const *oldset)
767 {
768 #ifdef SIGTTOU
769 pthread_sigmask (SIG_SETMASK, oldset, 0);
770 #endif
771 }
772
773 /* Safely set a controlling terminal FD's process group to PGID.
774 If we are not in the foreground already, POSIX requires tcsetpgrp
775 to deliver a SIGTTOU signal, which would stop us. This is an
776 annoyance, so temporarily ignore the signal.
777
778 In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
779 skip all this unless SIGTTOU is defined. */
780 static void
781 tcsetpgrp_without_stopping (int fd, pid_t pgid)
782 {
783 #ifdef SIGTTOU
784 sigset_t oldset;
785 block_input ();
786 block_tty_out_signal (&oldset);
787 tcsetpgrp (fd, pgid);
788 unblock_tty_out_signal (&oldset);
789 unblock_input ();
790 #endif
791 }
792
793 /* Split off the foreground process group to Emacs alone. When we are
794 in the foreground, but not started in our own process group,
795 redirect the tty device handle FD to point to our own process
796 group. FD must be the file descriptor of the controlling tty. */
797 static void
798 narrow_foreground_group (int fd)
799 {
800 if (inherited_pgroup && setpgid (0, 0) == 0)
801 tcsetpgrp_without_stopping (fd, getpid ());
802 }
803
804 /* Set the tty to our original foreground group. */
805 static void
806 widen_foreground_group (int fd)
807 {
808 if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
809 tcsetpgrp_without_stopping (fd, inherited_pgroup);
810 }
811 \f
812 /* Getting and setting emacs_tty structures. */
813
814 /* Set *TC to the parameters associated with the terminal FD,
815 or clear it if the parameters are not available.
816 Return 0 on success, -1 on failure. */
817 int
818 emacs_get_tty (int fd, struct emacs_tty *settings)
819 {
820 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
821 memset (&settings->main, 0, sizeof (settings->main));
822 #ifdef DOS_NT
823 #ifdef WINDOWSNT
824 HANDLE h = (HANDLE)_get_osfhandle (fd);
825 DWORD console_mode;
826
827 if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
828 {
829 settings->main = console_mode;
830 return 0;
831 }
832 #endif /* WINDOWSNT */
833 return -1;
834 #else /* !DOS_NT */
835 /* We have those nifty POSIX tcmumbleattr functions. */
836 return tcgetattr (fd, &settings->main);
837 #endif
838 }
839
840
841 /* Set the parameters of the tty on FD according to the contents of
842 *SETTINGS. If FLUSHP, discard input.
843 Return 0 if all went well, and -1 (setting errno) if anything failed. */
844
845 int
846 emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
847 {
848 /* Set the primary parameters - baud rate, character size, etcetera. */
849 #ifdef DOS_NT
850 #ifdef WINDOWSNT
851 HANDLE h = (HANDLE)_get_osfhandle (fd);
852
853 if (h && h != INVALID_HANDLE_VALUE)
854 {
855 DWORD new_mode;
856
857 /* Assume the handle is open for input. */
858 if (flushp)
859 FlushConsoleInputBuffer (h);
860 new_mode = settings->main;
861 SetConsoleMode (h, new_mode);
862 }
863 #endif /* WINDOWSNT */
864 #else /* !DOS_NT */
865 int i;
866 /* We have those nifty POSIX tcmumbleattr functions.
867 William J. Smith <wjs@wiis.wang.com> writes:
868 "POSIX 1003.1 defines tcsetattr to return success if it was
869 able to perform any of the requested actions, even if some
870 of the requested actions could not be performed.
871 We must read settings back to ensure tty setup properly.
872 AIX requires this to keep tty from hanging occasionally." */
873 /* This make sure that we don't loop indefinitely in here. */
874 for (i = 0 ; i < 10 ; i++)
875 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
876 {
877 if (errno == EINTR)
878 continue;
879 else
880 return -1;
881 }
882 else
883 {
884 struct termios new;
885
886 memset (&new, 0, sizeof (new));
887 /* Get the current settings, and see if they're what we asked for. */
888 tcgetattr (fd, &new);
889 /* We cannot use memcmp on the whole structure here because under
890 * aix386 the termios structure has some reserved field that may
891 * not be filled in.
892 */
893 if ( new.c_iflag == settings->main.c_iflag
894 && new.c_oflag == settings->main.c_oflag
895 && new.c_cflag == settings->main.c_cflag
896 && new.c_lflag == settings->main.c_lflag
897 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
898 break;
899 else
900 continue;
901 }
902 #endif
903
904 /* We have survived the tempest. */
905 return 0;
906 }
907
908 \f
909
910 #ifdef F_SETOWN
911 static int old_fcntl_owner[FD_SETSIZE];
912 #endif /* F_SETOWN */
913
914 /* This may also be defined in stdio,
915 but if so, this does no harm,
916 and using the same name avoids wasting the other one's space. */
917
918 #if defined (USG)
919 unsigned char _sobuf[BUFSIZ+8];
920 #else
921 char _sobuf[BUFSIZ];
922 #endif
923
924 /* Initialize the terminal mode on all tty devices that are currently
925 open. */
926
927 void
928 init_all_sys_modes (void)
929 {
930 struct tty_display_info *tty;
931 for (tty = tty_list; tty; tty = tty->next)
932 init_sys_modes (tty);
933 }
934
935 /* Initialize the terminal mode on the given tty device. */
936
937 void
938 init_sys_modes (struct tty_display_info *tty_out)
939 {
940 struct emacs_tty tty;
941 #ifndef DOS_NT
942 Lisp_Object terminal;
943 #endif
944
945 Vtty_erase_char = Qnil;
946
947 if (noninteractive)
948 return;
949
950 if (!tty_out->output)
951 return; /* The tty is suspended. */
952
953 narrow_foreground_group (fileno (tty_out->input));
954
955 if (! tty_out->old_tty)
956 tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
957
958 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
959
960 tty = *tty_out->old_tty;
961
962 #if !defined (DOS_NT)
963 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
964
965 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
966 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
967 #ifdef INLCR /* I'm just being cautious,
968 since I can't check how widespread INLCR is--rms. */
969 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
970 #endif
971 #ifdef ISTRIP
972 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
973 #endif
974 tty.main.c_lflag &= ~ECHO; /* Disable echo */
975 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
976 #ifdef IEXTEN
977 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
978 #endif
979 tty.main.c_lflag |= ISIG; /* Enable signals */
980 if (tty_out->flow_control)
981 {
982 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
983 #ifdef IXANY
984 tty.main.c_iflag &= ~IXANY;
985 #endif /* IXANY */
986 }
987 else
988 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
989 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
990 on output */
991 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
992 #ifdef CS8
993 if (tty_out->meta_key)
994 {
995 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
996 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
997 }
998 #endif
999
1000 XSETTERMINAL(terminal, tty_out->terminal);
1001 if (!NILP (Fcontrolling_tty_p (terminal)))
1002 {
1003 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1004 /* Set up C-g for both SIGQUIT and SIGINT.
1005 We don't know which we will get, but we handle both alike
1006 so which one it really gives us does not matter. */
1007 tty.main.c_cc[VQUIT] = quit_char;
1008 }
1009 else
1010 {
1011 /* We normally don't get interrupt or quit signals from tty
1012 devices other than our controlling terminal; therefore,
1013 we must handle C-g as normal input. Unfortunately, this
1014 means that the interrupt and quit feature must be
1015 disabled on secondary ttys, or we would not even see the
1016 keypress.
1017
1018 Note that even though emacsclient could have special code
1019 to pass SIGINT to Emacs, we should _not_ enable
1020 interrupt/quit keys for emacsclient frames. This means
1021 that we can't break out of loops in C code from a
1022 secondary tty frame, but we can always decide what
1023 display the C-g came from, which is more important from a
1024 usability point of view. (Consider the case when two
1025 people work together using the same Emacs instance.) */
1026 tty.main.c_cc[VINTR] = CDISABLE;
1027 tty.main.c_cc[VQUIT] = CDISABLE;
1028 }
1029 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1030 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1031 #ifdef VSWTCH
1032 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1033 of C-z */
1034 #endif /* VSWTCH */
1035
1036 #ifdef VSUSP
1037 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
1038 #endif /* VSUSP */
1039 #ifdef V_DSUSP
1040 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
1041 #endif /* V_DSUSP */
1042 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1043 tty.main.c_cc[VDSUSP] = CDISABLE;
1044 #endif /* VDSUSP */
1045 #ifdef VLNEXT
1046 tty.main.c_cc[VLNEXT] = CDISABLE;
1047 #endif /* VLNEXT */
1048 #ifdef VREPRINT
1049 tty.main.c_cc[VREPRINT] = CDISABLE;
1050 #endif /* VREPRINT */
1051 #ifdef VWERASE
1052 tty.main.c_cc[VWERASE] = CDISABLE;
1053 #endif /* VWERASE */
1054 #ifdef VDISCARD
1055 tty.main.c_cc[VDISCARD] = CDISABLE;
1056 #endif /* VDISCARD */
1057
1058 if (tty_out->flow_control)
1059 {
1060 #ifdef VSTART
1061 tty.main.c_cc[VSTART] = '\021';
1062 #endif /* VSTART */
1063 #ifdef VSTOP
1064 tty.main.c_cc[VSTOP] = '\023';
1065 #endif /* VSTOP */
1066 }
1067 else
1068 {
1069 #ifdef VSTART
1070 tty.main.c_cc[VSTART] = CDISABLE;
1071 #endif /* VSTART */
1072 #ifdef VSTOP
1073 tty.main.c_cc[VSTOP] = CDISABLE;
1074 #endif /* VSTOP */
1075 }
1076
1077 #ifdef AIX
1078 tty.main.c_cc[VSTRT] = CDISABLE;
1079 tty.main.c_cc[VSTOP] = CDISABLE;
1080 tty.main.c_cc[VSUSP] = CDISABLE;
1081 tty.main.c_cc[VDSUSP] = CDISABLE;
1082 if (tty_out->flow_control)
1083 {
1084 #ifdef VSTART
1085 tty.main.c_cc[VSTART] = '\021';
1086 #endif /* VSTART */
1087 #ifdef VSTOP
1088 tty.main.c_cc[VSTOP] = '\023';
1089 #endif /* VSTOP */
1090 }
1091 /* Also, PTY overloads NUL and BREAK.
1092 don't ignore break, but don't signal either, so it looks like NUL.
1093 This really serves a purpose only if running in an XTERM window
1094 or via TELNET or the like, but does no harm elsewhere. */
1095 tty.main.c_iflag &= ~IGNBRK;
1096 tty.main.c_iflag &= ~BRKINT;
1097 #endif
1098 #endif /* not DOS_NT */
1099
1100 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1101 if (!tty_out->term_initted)
1102 internal_terminal_init ();
1103 dos_ttraw (tty_out);
1104 #endif
1105
1106 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1107
1108 /* This code added to insure that, if flow-control is not to be used,
1109 we have an unlocked terminal at the start. */
1110
1111 #ifdef TCXONC
1112 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1113 #endif
1114 #ifdef TIOCSTART
1115 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1116 #endif
1117
1118 #if !defined (DOS_NT)
1119 #ifdef TCOON
1120 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1121 #endif
1122 #endif
1123
1124 #ifdef F_GETOWN
1125 if (interrupt_input)
1126 {
1127 old_fcntl_owner[fileno (tty_out->input)] =
1128 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1129 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1130 init_sigio (fileno (tty_out->input));
1131 #ifdef HAVE_GPM
1132 if (gpm_tty == tty_out)
1133 {
1134 /* Arrange for mouse events to give us SIGIO signals. */
1135 fcntl (gpm_fd, F_SETOWN, getpid ());
1136 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1137 init_sigio (gpm_fd);
1138 }
1139 #endif /* HAVE_GPM */
1140 }
1141 #endif /* F_GETOWN */
1142
1143 #ifdef _IOFBF
1144 /* This symbol is defined on recent USG systems.
1145 Someone says without this call USG won't really buffer the file
1146 even with a call to setbuf. */
1147 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1148 #else
1149 setbuf (tty_out->output, (char *) _sobuf);
1150 #endif
1151
1152 if (tty_out->terminal->set_terminal_modes_hook)
1153 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1154
1155 if (!tty_out->term_initted)
1156 {
1157 Lisp_Object tail, frame;
1158 FOR_EACH_FRAME (tail, frame)
1159 {
1160 /* XXX This needs to be revised. */
1161 if (FRAME_TERMCAP_P (XFRAME (frame))
1162 && FRAME_TTY (XFRAME (frame)) == tty_out)
1163 init_frame_faces (XFRAME (frame));
1164 }
1165 }
1166
1167 if (tty_out->term_initted && no_redraw_on_reenter)
1168 {
1169 /* We used to call "direct_output_forward_char(0)" here,
1170 but it's not clear why, since it may not do anything anyway. */
1171 }
1172 else
1173 {
1174 Lisp_Object tail, frame;
1175 frame_garbaged = 1;
1176 FOR_EACH_FRAME (tail, frame)
1177 {
1178 if ((FRAME_TERMCAP_P (XFRAME (frame))
1179 || FRAME_MSDOS_P (XFRAME (frame)))
1180 && FRAME_TTY (XFRAME (frame)) == tty_out)
1181 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1182 }
1183 }
1184
1185 tty_out->term_initted = 1;
1186 }
1187
1188 /* Return true if safe to use tabs in output.
1189 At the time this is called, init_sys_modes has not been done yet. */
1190
1191 bool
1192 tabs_safe_p (int fd)
1193 {
1194 struct emacs_tty etty;
1195
1196 emacs_get_tty (fd, &etty);
1197 #ifndef DOS_NT
1198 #ifdef TABDLY
1199 return ((etty.main.c_oflag & TABDLY) != TAB3);
1200 #else /* not TABDLY */
1201 return 1;
1202 #endif /* not TABDLY */
1203 #else /* DOS_NT */
1204 return 0;
1205 #endif /* DOS_NT */
1206 }
1207
1208 /* Discard echoing. */
1209
1210 void
1211 suppress_echo_on_tty (int fd)
1212 {
1213 struct emacs_tty etty;
1214
1215 emacs_get_tty (fd, &etty);
1216 #ifdef DOS_NT
1217 /* Set raw input mode. */
1218 etty.main = 0;
1219 #else
1220 etty.main.c_lflag &= ~ICANON; /* Disable buffering */
1221 etty.main.c_lflag &= ~ECHO; /* Disable echoing */
1222 #endif /* ! WINDOWSNT */
1223 emacs_set_tty (fd, &etty, 0);
1224 }
1225 \f
1226 /* Get terminal size from system.
1227 Store number of lines into *HEIGHTP and width into *WIDTHP.
1228 We store 0 if there's no valid information. */
1229
1230 void
1231 get_tty_size (int fd, int *widthp, int *heightp)
1232 {
1233 #if defined TIOCGWINSZ
1234
1235 /* BSD-style. */
1236 struct winsize size;
1237
1238 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1239 *widthp = *heightp = 0;
1240 else
1241 {
1242 *widthp = size.ws_col;
1243 *heightp = size.ws_row;
1244 }
1245
1246 #elif defined TIOCGSIZE
1247
1248 /* SunOS - style. */
1249 struct ttysize size;
1250
1251 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1252 *widthp = *heightp = 0;
1253 else
1254 {
1255 *widthp = size.ts_cols;
1256 *heightp = size.ts_lines;
1257 }
1258
1259 #elif defined WINDOWSNT
1260
1261 CONSOLE_SCREEN_BUFFER_INFO info;
1262 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1263 {
1264 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1265 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1266 }
1267 else
1268 *widthp = *heightp = 0;
1269
1270 #elif defined MSDOS
1271
1272 *widthp = ScreenCols ();
1273 *heightp = ScreenRows ();
1274
1275 #else /* system doesn't know size */
1276
1277 *widthp = 0;
1278 *heightp = 0;
1279
1280 #endif
1281 }
1282
1283 /* Set the logical window size associated with descriptor FD
1284 to HEIGHT and WIDTH. This is used mainly with ptys.
1285 Return a negative value on failure. */
1286
1287 int
1288 set_window_size (int fd, int height, int width)
1289 {
1290 #ifdef TIOCSWINSZ
1291
1292 /* BSD-style. */
1293 struct winsize size;
1294 size.ws_row = height;
1295 size.ws_col = width;
1296
1297 return ioctl (fd, TIOCSWINSZ, &size);
1298
1299 #else
1300 #ifdef TIOCSSIZE
1301
1302 /* SunOS - style. */
1303 struct ttysize size;
1304 size.ts_lines = height;
1305 size.ts_cols = width;
1306
1307 return ioctl (fd, TIOCGSIZE, &size);
1308 #else
1309 return -1;
1310 #endif /* not SunOS-style */
1311 #endif /* not BSD-style */
1312 }
1313
1314 \f
1315
1316 /* Prepare all terminal devices for exiting Emacs. */
1317
1318 void
1319 reset_all_sys_modes (void)
1320 {
1321 struct tty_display_info *tty;
1322 for (tty = tty_list; tty; tty = tty->next)
1323 reset_sys_modes (tty);
1324 }
1325
1326 /* Prepare the terminal for closing it; move the cursor to the
1327 bottom of the frame, turn off interrupt-driven I/O, etc. */
1328
1329 void
1330 reset_sys_modes (struct tty_display_info *tty_out)
1331 {
1332 if (noninteractive)
1333 {
1334 fflush (stdout);
1335 return;
1336 }
1337 if (!tty_out->term_initted)
1338 return;
1339
1340 if (!tty_out->output)
1341 return; /* The tty is suspended. */
1342
1343 /* Go to and clear the last line of the terminal. */
1344
1345 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1346
1347 /* Code adapted from tty_clear_end_of_line. */
1348 if (tty_out->TS_clr_line)
1349 {
1350 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1351 }
1352 else
1353 { /* have to do it the hard way */
1354 int i;
1355 tty_turn_off_insert (tty_out);
1356
1357 for (i = cursorX (tty_out); i < FrameCols (tty_out) - 1; i++)
1358 {
1359 fputc (' ', tty_out->output);
1360 }
1361 }
1362
1363 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1364 fflush (tty_out->output);
1365
1366 if (tty_out->terminal->reset_terminal_modes_hook)
1367 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1368
1369 /* Avoid possible loss of output when changing terminal modes. */
1370 while (fdatasync (fileno (tty_out->output)) != 0 && errno == EINTR)
1371 continue;
1372
1373 #ifndef DOS_NT
1374 #ifdef F_SETOWN
1375 if (interrupt_input)
1376 {
1377 reset_sigio (fileno (tty_out->input));
1378 fcntl (fileno (tty_out->input), F_SETOWN,
1379 old_fcntl_owner[fileno (tty_out->input)]);
1380 }
1381 #endif /* F_SETOWN */
1382 fcntl (fileno (tty_out->input), F_SETFL,
1383 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NONBLOCK);
1384 #endif
1385
1386 if (tty_out->old_tty)
1387 while (emacs_set_tty (fileno (tty_out->input),
1388 tty_out->old_tty, 0) < 0 && errno == EINTR)
1389 ;
1390
1391 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1392 dos_ttcooked ();
1393 #endif
1394
1395 widen_foreground_group (fileno (tty_out->input));
1396 }
1397 \f
1398 #ifdef HAVE_PTYS
1399
1400 /* Set up the proper status flags for use of a pty. */
1401
1402 void
1403 setup_pty (int fd)
1404 {
1405 /* I'm told that TOICREMOTE does not mean control chars
1406 "can't be sent" but rather that they don't have
1407 input-editing or signaling effects.
1408 That should be good, because we have other ways
1409 to do those things in Emacs.
1410 However, telnet mode seems not to work on 4.2.
1411 So TIOCREMOTE is turned off now. */
1412
1413 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1414 will hang. In particular, the "timeout" feature (which
1415 causes a read to return if there is no data available)
1416 does this. Also it is known that telnet mode will hang
1417 in such a way that Emacs must be stopped (perhaps this
1418 is the same problem).
1419
1420 If TIOCREMOTE is turned off, then there is a bug in
1421 hp-ux which sometimes loses data. Apparently the
1422 code which blocks the master process when the internal
1423 buffer fills up does not work. Other than this,
1424 though, everything else seems to work fine.
1425
1426 Since the latter lossage is more benign, we may as well
1427 lose that way. -- cph */
1428 #ifdef FIONBIO
1429 #if defined (UNIX98_PTYS)
1430 {
1431 int on = 1;
1432 ioctl (fd, FIONBIO, &on);
1433 }
1434 #endif
1435 #endif
1436 }
1437 #endif /* HAVE_PTYS */
1438 \f
1439 void
1440 init_system_name (void)
1441 {
1442 if (!build_details)
1443 {
1444 /* Set system-name to nil so that the build is deterministic. */
1445 Vsystem_name = Qnil;
1446 return;
1447 }
1448 char *hostname_alloc = NULL;
1449 char *hostname;
1450 #ifndef HAVE_GETHOSTNAME
1451 struct utsname uts;
1452 uname (&uts);
1453 hostname = uts.nodename;
1454 #else /* HAVE_GETHOSTNAME */
1455 char hostname_buf[256];
1456 ptrdiff_t hostname_size = sizeof hostname_buf;
1457 hostname = hostname_buf;
1458
1459 /* Try to get the host name; if the buffer is too short, try
1460 again. Apparently, the only indication gethostname gives of
1461 whether the buffer was large enough is the presence or absence
1462 of a '\0' in the string. Eech. */
1463 for (;;)
1464 {
1465 gethostname (hostname, hostname_size - 1);
1466 hostname[hostname_size - 1] = '\0';
1467
1468 /* Was the buffer large enough for the '\0'? */
1469 if (strlen (hostname) < hostname_size - 1)
1470 break;
1471
1472 hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
1473 min (PTRDIFF_MAX, SIZE_MAX), 1);
1474 }
1475 #endif /* HAVE_GETHOSTNAME */
1476 char *p;
1477 for (p = hostname; *p; p++)
1478 if (*p == ' ' || *p == '\t')
1479 *p = '-';
1480 if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
1481 && strcmp (SSDATA (Vsystem_name), hostname) == 0))
1482 Vsystem_name = build_string (hostname);
1483 xfree (hostname_alloc);
1484 }
1485 \f
1486 sigset_t empty_mask;
1487
1488 static struct sigaction process_fatal_action;
1489
1490 static int
1491 emacs_sigaction_flags (void)
1492 {
1493 #ifdef SA_RESTART
1494 /* SA_RESTART causes interruptible functions with timeouts (e.g.,
1495 'select') to reset their timeout on some platforms (e.g.,
1496 HP-UX 11), which is not what we want. Also, when Emacs is
1497 interactive, we don't want SA_RESTART because we need to poll
1498 for pending input so we need long-running syscalls to be interrupted
1499 after a signal that sets pending_signals.
1500
1501 Non-interactive keyboard input goes through stdio, where we
1502 always want restartable system calls. */
1503 if (noninteractive)
1504 return SA_RESTART;
1505 #endif
1506 return 0;
1507 }
1508
1509 /* Store into *ACTION a signal action suitable for Emacs, with handler
1510 HANDLER. */
1511 void
1512 emacs_sigaction_init (struct sigaction *action, signal_handler_t handler)
1513 {
1514 sigemptyset (&action->sa_mask);
1515
1516 /* When handling a signal, block nonfatal system signals that are caught
1517 by Emacs. This makes race conditions less likely. */
1518 sigaddset (&action->sa_mask, SIGALRM);
1519 #ifdef SIGCHLD
1520 sigaddset (&action->sa_mask, SIGCHLD);
1521 #endif
1522 #ifdef SIGDANGER
1523 sigaddset (&action->sa_mask, SIGDANGER);
1524 #endif
1525 #ifdef PROFILER_CPU_SUPPORT
1526 sigaddset (&action->sa_mask, SIGPROF);
1527 #endif
1528 #ifdef SIGWINCH
1529 sigaddset (&action->sa_mask, SIGWINCH);
1530 #endif
1531 if (! noninteractive)
1532 {
1533 sigaddset (&action->sa_mask, SIGINT);
1534 sigaddset (&action->sa_mask, SIGQUIT);
1535 #ifdef USABLE_SIGIO
1536 sigaddset (&action->sa_mask, SIGIO);
1537 #endif
1538 }
1539
1540 action->sa_handler = handler;
1541 action->sa_flags = emacs_sigaction_flags ();
1542 }
1543
1544 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1545 static pthread_t main_thread;
1546 #endif
1547
1548 /* SIG has arrived at the current process. Deliver it to the main
1549 thread, which should handle it with HANDLER.
1550
1551 If we are on the main thread, handle the signal SIG with HANDLER.
1552 Otherwise, redirect the signal to the main thread, blocking it from
1553 this thread. POSIX says any thread can receive a signal that is
1554 associated with a process, process group, or asynchronous event.
1555 On GNU/Linux that is not true, but for other systems (FreeBSD at
1556 least) it is. */
1557 void
1558 deliver_process_signal (int sig, signal_handler_t handler)
1559 {
1560 /* Preserve errno, to avoid race conditions with signal handlers that
1561 might change errno. Races can occur even in single-threaded hosts. */
1562 int old_errno = errno;
1563
1564 bool on_main_thread = true;
1565 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1566 if (! pthread_equal (pthread_self (), main_thread))
1567 {
1568 sigset_t blocked;
1569 sigemptyset (&blocked);
1570 sigaddset (&blocked, sig);
1571 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1572 pthread_kill (main_thread, sig);
1573 on_main_thread = false;
1574 }
1575 #endif
1576 if (on_main_thread)
1577 handler (sig);
1578
1579 errno = old_errno;
1580 }
1581
1582 /* Static location to save a fatal backtrace in a thread.
1583 FIXME: If two subsidiary threads fail simultaneously, the resulting
1584 backtrace may be garbage. */
1585 enum { BACKTRACE_LIMIT_MAX = 500 };
1586 static void *thread_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
1587 static int thread_backtrace_npointers;
1588
1589 /* SIG has arrived at the current thread.
1590 If we are on the main thread, handle the signal SIG with HANDLER.
1591 Otherwise, this is a fatal error in the handling thread. */
1592 static void
1593 deliver_thread_signal (int sig, signal_handler_t handler)
1594 {
1595 int old_errno = errno;
1596
1597 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1598 if (! pthread_equal (pthread_self (), main_thread))
1599 {
1600 thread_backtrace_npointers
1601 = backtrace (thread_backtrace_buffer, BACKTRACE_LIMIT_MAX);
1602 sigaction (sig, &process_fatal_action, 0);
1603 pthread_kill (main_thread, sig);
1604
1605 /* Avoid further damage while the main thread is exiting. */
1606 while (1)
1607 sigsuspend (&empty_mask);
1608 }
1609 #endif
1610
1611 handler (sig);
1612 errno = old_errno;
1613 }
1614 \f
1615 #if !HAVE_DECL_SYS_SIGLIST
1616 # undef sys_siglist
1617 # ifdef _sys_siglist
1618 # define sys_siglist _sys_siglist
1619 # elif HAVE_DECL___SYS_SIGLIST
1620 # define sys_siglist __sys_siglist
1621 # else
1622 # define sys_siglist my_sys_siglist
1623 static char const *sys_siglist[NSIG];
1624 # endif
1625 #endif
1626
1627 #ifdef _sys_nsig
1628 # define sys_siglist_entries _sys_nsig
1629 #else
1630 # define sys_siglist_entries NSIG
1631 #endif
1632
1633 /* Handle bus errors, invalid instruction, etc. */
1634 static void
1635 handle_fatal_signal (int sig)
1636 {
1637 terminate_due_to_signal (sig, 40);
1638 }
1639
1640 static void
1641 deliver_fatal_signal (int sig)
1642 {
1643 deliver_process_signal (sig, handle_fatal_signal);
1644 }
1645
1646 static void
1647 deliver_fatal_thread_signal (int sig)
1648 {
1649 deliver_thread_signal (sig, handle_fatal_signal);
1650 }
1651
1652 static _Noreturn void
1653 handle_arith_signal (int sig)
1654 {
1655 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1656 xsignal0 (Qarith_error);
1657 }
1658
1659 #if defined HAVE_STACK_OVERFLOW_HANDLING && !defined WINDOWSNT
1660
1661 /* Alternate stack used by SIGSEGV handler below. */
1662
1663 static unsigned char sigsegv_stack[SIGSTKSZ];
1664
1665
1666 /* Return true if SIGINFO indicates a stack overflow. */
1667
1668 static bool
1669 stack_overflow (siginfo_t *siginfo)
1670 {
1671 if (!attempt_stack_overflow_recovery)
1672 return false;
1673
1674 /* In theory, a more-accurate heuristic can be obtained by using
1675 GNU/Linux pthread_getattr_np along with POSIX pthread_attr_getstack
1676 and pthread_attr_getguardsize to find the location and size of the
1677 guard area. In practice, though, these functions are so hard to
1678 use reliably that they're not worth bothering with. E.g., see:
1679 https://sourceware.org/bugzilla/show_bug.cgi?id=16291
1680 Other operating systems also have problems, e.g., Solaris's
1681 stack_violation function is tailor-made for this problem, but it
1682 doesn't work on Solaris 11.2 x86-64 with a 32-bit executable.
1683
1684 GNU libsigsegv is overkill for Emacs; otherwise it might be a
1685 candidate here. */
1686
1687 if (!siginfo)
1688 return false;
1689
1690 /* The faulting address. */
1691 char *addr = siginfo->si_addr;
1692 if (!addr)
1693 return false;
1694
1695 /* The known top and bottom of the stack. The actual stack may
1696 extend a bit beyond these boundaries. */
1697 char *bot = stack_bottom;
1698 char *top = near_C_stack_top ();
1699
1700 /* Log base 2 of the stack heuristic ratio. This ratio is the size
1701 of the known stack divided by the size of the guard area past the
1702 end of the stack top. The heuristic is that a bad address is
1703 considered to be a stack overflow if it occurs within
1704 stacksize>>LG_STACK_HEURISTIC bytes above the top of the known
1705 stack. This heuristic is not exactly correct but it's good
1706 enough in practice. */
1707 enum { LG_STACK_HEURISTIC = 8 };
1708
1709 if (bot < top)
1710 return 0 <= addr - top && addr - top < (top - bot) >> LG_STACK_HEURISTIC;
1711 else
1712 return 0 <= top - addr && top - addr < (bot - top) >> LG_STACK_HEURISTIC;
1713 }
1714
1715
1716 /* Attempt to recover from SIGSEGV caused by C stack overflow. */
1717
1718 static void
1719 handle_sigsegv (int sig, siginfo_t *siginfo, void *arg)
1720 {
1721 /* Hard GC error may lead to stack overflow caused by
1722 too nested calls to mark_object. No way to survive. */
1723 bool fatal = gc_in_progress;
1724
1725 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1726 if (!fatal && !pthread_equal (pthread_self (), main_thread))
1727 fatal = true;
1728 #endif
1729
1730 if (!fatal && stack_overflow (siginfo))
1731 siglongjmp (return_to_command_loop, 1);
1732
1733 /* Otherwise we can't do anything with this. */
1734 deliver_fatal_thread_signal (sig);
1735 }
1736
1737 /* Return true if we have successfully set up SIGSEGV handler on alternate
1738 stack. Otherwise we just treat SIGSEGV among the rest of fatal signals. */
1739
1740 static bool
1741 init_sigsegv (void)
1742 {
1743 struct sigaction sa;
1744 stack_t ss;
1745
1746 ss.ss_sp = sigsegv_stack;
1747 ss.ss_size = sizeof (sigsegv_stack);
1748 ss.ss_flags = 0;
1749 if (sigaltstack (&ss, NULL) < 0)
1750 return 0;
1751
1752 sigfillset (&sa.sa_mask);
1753 sa.sa_sigaction = handle_sigsegv;
1754 sa.sa_flags = SA_SIGINFO | SA_ONSTACK | emacs_sigaction_flags ();
1755 return sigaction (SIGSEGV, &sa, NULL) < 0 ? 0 : 1;
1756 }
1757
1758 #else /* not HAVE_STACK_OVERFLOW_HANDLING or WINDOWSNT */
1759
1760 static bool
1761 init_sigsegv (void)
1762 {
1763 return 0;
1764 }
1765
1766 #endif /* HAVE_STACK_OVERFLOW_HANDLING && !WINDOWSNT */
1767
1768 static void
1769 deliver_arith_signal (int sig)
1770 {
1771 deliver_thread_signal (sig, handle_arith_signal);
1772 }
1773
1774 #ifdef SIGDANGER
1775
1776 /* Handler for SIGDANGER. */
1777 static void
1778 handle_danger_signal (int sig)
1779 {
1780 malloc_warning ("Operating system warns that virtual memory is running low.\n");
1781
1782 /* It might be unsafe to call do_auto_save now. */
1783 force_auto_save_soon ();
1784 }
1785
1786 static void
1787 deliver_danger_signal (int sig)
1788 {
1789 deliver_process_signal (sig, handle_danger_signal);
1790 }
1791 #endif
1792
1793 /* Treat SIG as a terminating signal, unless it is already ignored and
1794 we are in --batch mode. Among other things, this makes nohup work. */
1795 static void
1796 maybe_fatal_sig (int sig)
1797 {
1798 bool catch_sig = !noninteractive;
1799 if (!catch_sig)
1800 {
1801 struct sigaction old_action;
1802 sigaction (sig, 0, &old_action);
1803 catch_sig = old_action.sa_handler != SIG_IGN;
1804 }
1805 if (catch_sig)
1806 sigaction (sig, &process_fatal_action, 0);
1807 }
1808
1809 void
1810 init_signals (bool dumping)
1811 {
1812 struct sigaction thread_fatal_action;
1813 struct sigaction action;
1814
1815 sigemptyset (&empty_mask);
1816
1817 #ifdef FORWARD_SIGNAL_TO_MAIN_THREAD
1818 main_thread = pthread_self ();
1819 #endif
1820
1821 #if !HAVE_DECL_SYS_SIGLIST && !defined _sys_siglist
1822 if (! initialized)
1823 {
1824 sys_siglist[SIGABRT] = "Aborted";
1825 # ifdef SIGAIO
1826 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1827 # endif
1828 sys_siglist[SIGALRM] = "Alarm clock";
1829 # ifdef SIGBUS
1830 sys_siglist[SIGBUS] = "Bus error";
1831 # endif
1832 # ifdef SIGCHLD
1833 sys_siglist[SIGCHLD] = "Child status changed";
1834 # endif
1835 # ifdef SIGCONT
1836 sys_siglist[SIGCONT] = "Continued";
1837 # endif
1838 # ifdef SIGDANGER
1839 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1840 # endif
1841 # ifdef SIGDGNOTIFY
1842 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1843 # endif
1844 # ifdef SIGEMT
1845 sys_siglist[SIGEMT] = "Emulation trap";
1846 # endif
1847 sys_siglist[SIGFPE] = "Arithmetic exception";
1848 # ifdef SIGFREEZE
1849 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1850 # endif
1851 # ifdef SIGGRANT
1852 sys_siglist[SIGGRANT] = "Monitor mode granted";
1853 # endif
1854 sys_siglist[SIGHUP] = "Hangup";
1855 sys_siglist[SIGILL] = "Illegal instruction";
1856 sys_siglist[SIGINT] = "Interrupt";
1857 # ifdef SIGIO
1858 sys_siglist[SIGIO] = "I/O possible";
1859 # endif
1860 # ifdef SIGIOINT
1861 sys_siglist[SIGIOINT] = "I/O intervention required";
1862 # endif
1863 # ifdef SIGIOT
1864 sys_siglist[SIGIOT] = "IOT trap";
1865 # endif
1866 sys_siglist[SIGKILL] = "Killed";
1867 # ifdef SIGLOST
1868 sys_siglist[SIGLOST] = "Resource lost";
1869 # endif
1870 # ifdef SIGLWP
1871 sys_siglist[SIGLWP] = "SIGLWP";
1872 # endif
1873 # ifdef SIGMSG
1874 sys_siglist[SIGMSG] = "Monitor mode data available";
1875 # endif
1876 # ifdef SIGPHONE
1877 sys_siglist[SIGWIND] = "SIGPHONE";
1878 # endif
1879 sys_siglist[SIGPIPE] = "Broken pipe";
1880 # ifdef SIGPOLL
1881 sys_siglist[SIGPOLL] = "Pollable event occurred";
1882 # endif
1883 # ifdef SIGPROF
1884 sys_siglist[SIGPROF] = "Profiling timer expired";
1885 # endif
1886 # ifdef SIGPTY
1887 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1888 # endif
1889 # ifdef SIGPWR
1890 sys_siglist[SIGPWR] = "Power-fail restart";
1891 # endif
1892 sys_siglist[SIGQUIT] = "Quit";
1893 # ifdef SIGRETRACT
1894 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1895 # endif
1896 # ifdef SIGSAK
1897 sys_siglist[SIGSAK] = "Secure attention";
1898 # endif
1899 sys_siglist[SIGSEGV] = "Segmentation violation";
1900 # ifdef SIGSOUND
1901 sys_siglist[SIGSOUND] = "Sound completed";
1902 # endif
1903 # ifdef SIGSTOP
1904 sys_siglist[SIGSTOP] = "Stopped (signal)";
1905 # endif
1906 # ifdef SIGSTP
1907 sys_siglist[SIGSTP] = "Stopped (user)";
1908 # endif
1909 # ifdef SIGSYS
1910 sys_siglist[SIGSYS] = "Bad argument to system call";
1911 # endif
1912 sys_siglist[SIGTERM] = "Terminated";
1913 # ifdef SIGTHAW
1914 sys_siglist[SIGTHAW] = "SIGTHAW";
1915 # endif
1916 # ifdef SIGTRAP
1917 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1918 # endif
1919 # ifdef SIGTSTP
1920 sys_siglist[SIGTSTP] = "Stopped (user)";
1921 # endif
1922 # ifdef SIGTTIN
1923 sys_siglist[SIGTTIN] = "Stopped (tty input)";
1924 # endif
1925 # ifdef SIGTTOU
1926 sys_siglist[SIGTTOU] = "Stopped (tty output)";
1927 # endif
1928 # ifdef SIGURG
1929 sys_siglist[SIGURG] = "Urgent I/O condition";
1930 # endif
1931 # ifdef SIGUSR1
1932 sys_siglist[SIGUSR1] = "User defined signal 1";
1933 # endif
1934 # ifdef SIGUSR2
1935 sys_siglist[SIGUSR2] = "User defined signal 2";
1936 # endif
1937 # ifdef SIGVTALRM
1938 sys_siglist[SIGVTALRM] = "Virtual timer expired";
1939 # endif
1940 # ifdef SIGWAITING
1941 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
1942 # endif
1943 # ifdef SIGWINCH
1944 sys_siglist[SIGWINCH] = "Window size changed";
1945 # endif
1946 # ifdef SIGWIND
1947 sys_siglist[SIGWIND] = "SIGWIND";
1948 # endif
1949 # ifdef SIGXCPU
1950 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
1951 # endif
1952 # ifdef SIGXFSZ
1953 sys_siglist[SIGXFSZ] = "File size limit exceeded";
1954 # endif
1955 }
1956 #endif /* !HAVE_DECL_SYS_SIGLIST && !_sys_siglist */
1957
1958 /* Don't alter signal handlers if dumping. On some machines,
1959 changing signal handlers sets static data that would make signals
1960 fail to work right when the dumped Emacs is run. */
1961 if (dumping)
1962 return;
1963
1964 sigfillset (&process_fatal_action.sa_mask);
1965 process_fatal_action.sa_handler = deliver_fatal_signal;
1966 process_fatal_action.sa_flags = emacs_sigaction_flags ();
1967
1968 sigfillset (&thread_fatal_action.sa_mask);
1969 thread_fatal_action.sa_handler = deliver_fatal_thread_signal;
1970 thread_fatal_action.sa_flags = process_fatal_action.sa_flags;
1971
1972 /* SIGINT may need special treatment on MS-Windows. See
1973 http://lists.gnu.org/archive/html/emacs-devel/2010-09/msg01062.html
1974 Please update the doc of kill-emacs, kill-emacs-hook, and
1975 NEWS if you change this. */
1976
1977 maybe_fatal_sig (SIGHUP);
1978 maybe_fatal_sig (SIGINT);
1979 maybe_fatal_sig (SIGTERM);
1980
1981 /* Emacs checks for write errors, so it can safely ignore SIGPIPE.
1982 However, in batch mode leave SIGPIPE alone, as that causes Emacs
1983 to behave more like typical batch applications do. */
1984 if (! noninteractive)
1985 signal (SIGPIPE, SIG_IGN);
1986
1987 sigaction (SIGQUIT, &process_fatal_action, 0);
1988 sigaction (SIGILL, &thread_fatal_action, 0);
1989 sigaction (SIGTRAP, &thread_fatal_action, 0);
1990
1991 /* Typically SIGFPE is thread-specific and is fatal, like SIGILL.
1992 But on a non-IEEE host SIGFPE can come from a trap in the Lisp
1993 interpreter's floating point operations, so treat SIGFPE as an
1994 arith-error if it arises in the main thread. */
1995 if (IEEE_FLOATING_POINT)
1996 sigaction (SIGFPE, &thread_fatal_action, 0);
1997 else
1998 {
1999 emacs_sigaction_init (&action, deliver_arith_signal);
2000 sigaction (SIGFPE, &action, 0);
2001 }
2002
2003 #ifdef SIGUSR1
2004 add_user_signal (SIGUSR1, "sigusr1");
2005 #endif
2006 #ifdef SIGUSR2
2007 add_user_signal (SIGUSR2, "sigusr2");
2008 #endif
2009 sigaction (SIGABRT, &thread_fatal_action, 0);
2010 #ifdef SIGPRE
2011 sigaction (SIGPRE, &thread_fatal_action, 0);
2012 #endif
2013 #ifdef SIGORE
2014 sigaction (SIGORE, &thread_fatal_action, 0);
2015 #endif
2016 #ifdef SIGUME
2017 sigaction (SIGUME, &thread_fatal_action, 0);
2018 #endif
2019 #ifdef SIGDLK
2020 sigaction (SIGDLK, &process_fatal_action, 0);
2021 #endif
2022 #ifdef SIGCPULIM
2023 sigaction (SIGCPULIM, &process_fatal_action, 0);
2024 #endif
2025 #ifdef SIGIOT
2026 sigaction (SIGIOT, &thread_fatal_action, 0);
2027 #endif
2028 #ifdef SIGEMT
2029 sigaction (SIGEMT, &thread_fatal_action, 0);
2030 #endif
2031 #ifdef SIGBUS
2032 sigaction (SIGBUS, &thread_fatal_action, 0);
2033 #endif
2034 if (!init_sigsegv ())
2035 sigaction (SIGSEGV, &thread_fatal_action, 0);
2036 #ifdef SIGSYS
2037 sigaction (SIGSYS, &thread_fatal_action, 0);
2038 #endif
2039 sigaction (SIGTERM, &process_fatal_action, 0);
2040 #ifdef SIGPROF
2041 signal (SIGPROF, SIG_IGN);
2042 #endif
2043 #ifdef SIGVTALRM
2044 sigaction (SIGVTALRM, &process_fatal_action, 0);
2045 #endif
2046 #ifdef SIGXCPU
2047 sigaction (SIGXCPU, &process_fatal_action, 0);
2048 #endif
2049 #ifdef SIGXFSZ
2050 sigaction (SIGXFSZ, &process_fatal_action, 0);
2051 #endif
2052
2053 #ifdef SIGDANGER
2054 /* This just means available memory is getting low. */
2055 emacs_sigaction_init (&action, deliver_danger_signal);
2056 sigaction (SIGDANGER, &action, 0);
2057 #endif
2058
2059 /* AIX-specific signals. */
2060 #ifdef SIGGRANT
2061 sigaction (SIGGRANT, &process_fatal_action, 0);
2062 #endif
2063 #ifdef SIGMIGRATE
2064 sigaction (SIGMIGRATE, &process_fatal_action, 0);
2065 #endif
2066 #ifdef SIGMSG
2067 sigaction (SIGMSG, &process_fatal_action, 0);
2068 #endif
2069 #ifdef SIGRETRACT
2070 sigaction (SIGRETRACT, &process_fatal_action, 0);
2071 #endif
2072 #ifdef SIGSAK
2073 sigaction (SIGSAK, &process_fatal_action, 0);
2074 #endif
2075 #ifdef SIGSOUND
2076 sigaction (SIGSOUND, &process_fatal_action, 0);
2077 #endif
2078 #ifdef SIGTALRM
2079 sigaction (SIGTALRM, &thread_fatal_action, 0);
2080 #endif
2081 }
2082 \f
2083 #ifndef HAVE_RANDOM
2084 #ifdef random
2085 #define HAVE_RANDOM
2086 #endif
2087 #endif
2088
2089 /* Figure out how many bits the system's random number generator uses.
2090 `random' and `lrand48' are assumed to return 31 usable bits.
2091 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2092 so we'll shift it and treat it like the 15-bit USG `rand'. */
2093
2094 #ifndef RAND_BITS
2095 # ifdef HAVE_RANDOM
2096 # define RAND_BITS 31
2097 # else /* !HAVE_RANDOM */
2098 # ifdef HAVE_LRAND48
2099 # define RAND_BITS 31
2100 # define random lrand48
2101 # else /* !HAVE_LRAND48 */
2102 # define RAND_BITS 15
2103 # if RAND_MAX == 32767
2104 # define random rand
2105 # else /* RAND_MAX != 32767 */
2106 # if RAND_MAX == 2147483647
2107 # define random() (rand () >> 16)
2108 # else /* RAND_MAX != 2147483647 */
2109 # ifdef USG
2110 # define random rand
2111 # else
2112 # define random() (rand () >> 16)
2113 # endif /* !USG */
2114 # endif /* RAND_MAX != 2147483647 */
2115 # endif /* RAND_MAX != 32767 */
2116 # endif /* !HAVE_LRAND48 */
2117 # endif /* !HAVE_RANDOM */
2118 #endif /* !RAND_BITS */
2119
2120 #ifdef HAVE_RANDOM
2121 typedef unsigned int random_seed;
2122 static void set_random_seed (random_seed arg) { srandom (arg); }
2123 #elif defined HAVE_LRAND48
2124 /* Although srand48 uses a long seed, this is unsigned long to avoid
2125 undefined behavior on signed integer overflow in init_random. */
2126 typedef unsigned long int random_seed;
2127 static void set_random_seed (random_seed arg) { srand48 (arg); }
2128 #else
2129 typedef unsigned int random_seed;
2130 static void set_random_seed (random_seed arg) { srand (arg); }
2131 #endif
2132
2133 void
2134 seed_random (void *seed, ptrdiff_t seed_size)
2135 {
2136 random_seed arg = 0;
2137 unsigned char *argp = (unsigned char *) &arg;
2138 unsigned char *seedp = seed;
2139 for (ptrdiff_t i = 0; i < seed_size; i++)
2140 argp[i % sizeof arg] ^= seedp[i];
2141 set_random_seed (arg);
2142 }
2143
2144 void
2145 init_random (void)
2146 {
2147 random_seed v;
2148 if (! (EQ (emacs_gnutls_global_init (), Qt)
2149 && gnutls_rnd (GNUTLS_RND_NONCE, &v, sizeof v) == 0))
2150 {
2151 bool success = false;
2152 #ifndef WINDOWSNT
2153 int fd = emacs_open ("/dev/urandom", O_RDONLY, 0);
2154 if (0 <= fd)
2155 {
2156 success = emacs_read (fd, &v, sizeof v) == sizeof v;
2157 emacs_close (fd);
2158 }
2159 #else
2160 success = w32_init_random (&v, sizeof v) == 0;
2161 #endif
2162 if (! success)
2163 {
2164 /* Fall back to current time value + PID. */
2165 struct timespec t = current_timespec ();
2166 v = getpid () ^ t.tv_sec ^ t.tv_nsec;
2167 }
2168 }
2169 set_random_seed (v);
2170 }
2171
2172 /*
2173 * Return a nonnegative random integer out of whatever we've got.
2174 * It contains enough bits to make a random (signed) Emacs fixnum.
2175 * This suffices even for a 64-bit architecture with a 15-bit rand.
2176 */
2177 EMACS_INT
2178 get_random (void)
2179 {
2180 EMACS_UINT val = 0;
2181 int i;
2182 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
2183 val = (random () ^ (val << RAND_BITS)
2184 ^ (val >> (BITS_PER_EMACS_INT - RAND_BITS)));
2185 val ^= val >> (BITS_PER_EMACS_INT - FIXNUM_BITS);
2186 return val & INTMASK;
2187 }
2188
2189 #ifndef HAVE_SNPRINTF
2190 /* Approximate snprintf as best we can on ancient hosts that lack it. */
2191 int
2192 snprintf (char *buf, size_t bufsize, char const *format, ...)
2193 {
2194 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
2195 ptrdiff_t nbytes = size - 1;
2196 va_list ap;
2197
2198 if (size)
2199 {
2200 va_start (ap, format);
2201 nbytes = doprnt (buf, size, format, 0, ap);
2202 va_end (ap);
2203 }
2204
2205 if (nbytes == size - 1)
2206 {
2207 /* Calculate the length of the string that would have been created
2208 had the buffer been large enough. */
2209 char stackbuf[4000];
2210 char *b = stackbuf;
2211 ptrdiff_t bsize = sizeof stackbuf;
2212 va_start (ap, format);
2213 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
2214 va_end (ap);
2215 if (b != stackbuf)
2216 xfree (b);
2217 }
2218
2219 if (INT_MAX < nbytes)
2220 {
2221 #ifdef EOVERFLOW
2222 errno = EOVERFLOW;
2223 #else
2224 errno = EDOM;
2225 #endif
2226 return -1;
2227 }
2228 return nbytes;
2229 }
2230 #endif
2231 \f
2232 /* If a backtrace is available, output the top lines of it to stderr.
2233 Do not output more than BACKTRACE_LIMIT or BACKTRACE_LIMIT_MAX lines.
2234 This function may be called from a signal handler, so it should
2235 not invoke async-unsafe functions like malloc.
2236
2237 If BACKTRACE_LIMIT is -1, initialize tables that 'backtrace' uses
2238 but do not output anything. This avoids some problems that can
2239 otherwise occur if the malloc arena is corrupted before 'backtrace'
2240 is called, since 'backtrace' may call malloc if the tables are not
2241 initialized.
2242
2243 If the static variable THREAD_BACKTRACE_NPOINTERS is nonzero, a
2244 fatal error has occurred in some other thread; generate a thread
2245 backtrace instead, ignoring BACKTRACE_LIMIT. */
2246 void
2247 emacs_backtrace (int backtrace_limit)
2248 {
2249 void *main_backtrace_buffer[BACKTRACE_LIMIT_MAX + 1];
2250 int bounded_limit = min (backtrace_limit, BACKTRACE_LIMIT_MAX);
2251 void *buffer;
2252 int npointers;
2253
2254 if (thread_backtrace_npointers)
2255 {
2256 buffer = thread_backtrace_buffer;
2257 npointers = thread_backtrace_npointers;
2258 }
2259 else
2260 {
2261 buffer = main_backtrace_buffer;
2262
2263 /* Work around 'backtrace' bug; see Bug#19959 and glibc bug#18084. */
2264 if (bounded_limit < 0)
2265 {
2266 backtrace (buffer, 1);
2267 return;
2268 }
2269
2270 npointers = backtrace (buffer, bounded_limit + 1);
2271 }
2272
2273 if (npointers)
2274 {
2275 emacs_write (STDERR_FILENO, "\nBacktrace:\n", 12);
2276 backtrace_symbols_fd (buffer, npointers, STDERR_FILENO);
2277 if (bounded_limit < npointers)
2278 emacs_write (STDERR_FILENO, "...\n", 4);
2279 }
2280 }
2281 \f
2282 #ifndef HAVE_NTGUI
2283 void
2284 emacs_abort (void)
2285 {
2286 terminate_due_to_signal (SIGABRT, 40);
2287 }
2288 #endif
2289
2290 /* Open FILE for Emacs use, using open flags OFLAG and mode MODE.
2291 Use binary I/O on systems that care about text vs binary I/O.
2292 Arrange for subprograms to not inherit the file descriptor.
2293 Prefer a method that is multithread-safe, if available.
2294 Do not fail merely because the open was interrupted by a signal.
2295 Allow the user to quit. */
2296
2297 int
2298 emacs_open (const char *file, int oflags, int mode)
2299 {
2300 int fd;
2301 if (! (oflags & O_TEXT))
2302 oflags |= O_BINARY;
2303 oflags |= O_CLOEXEC;
2304 while ((fd = open (file, oflags, mode)) < 0 && errno == EINTR)
2305 QUIT;
2306 if (! O_CLOEXEC && 0 <= fd)
2307 fcntl (fd, F_SETFD, FD_CLOEXEC);
2308 return fd;
2309 }
2310
2311 /* Open FILE as a stream for Emacs use, with mode MODE.
2312 Act like emacs_open with respect to threads, signals, and quits. */
2313
2314 FILE *
2315 emacs_fopen (char const *file, char const *mode)
2316 {
2317 int fd, omode, oflags;
2318 int bflag = 0;
2319 char const *m = mode;
2320
2321 switch (*m++)
2322 {
2323 case 'r': omode = O_RDONLY; oflags = 0; break;
2324 case 'w': omode = O_WRONLY; oflags = O_CREAT | O_TRUNC; break;
2325 case 'a': omode = O_WRONLY; oflags = O_CREAT | O_APPEND; break;
2326 default: emacs_abort ();
2327 }
2328
2329 while (*m)
2330 switch (*m++)
2331 {
2332 case '+': omode = O_RDWR; break;
2333 case 't': bflag = O_TEXT; break;
2334 default: /* Ignore. */ break;
2335 }
2336
2337 fd = emacs_open (file, omode | oflags | bflag, 0666);
2338 return fd < 0 ? 0 : fdopen (fd, mode);
2339 }
2340
2341 /* Create a pipe for Emacs use. */
2342
2343 int
2344 emacs_pipe (int fd[2])
2345 {
2346 #ifdef MSDOS
2347 return pipe (fd);
2348 #else /* !MSDOS */
2349 int result = pipe2 (fd, O_BINARY | O_CLOEXEC);
2350 if (! O_CLOEXEC && result == 0)
2351 {
2352 fcntl (fd[0], F_SETFD, FD_CLOEXEC);
2353 fcntl (fd[1], F_SETFD, FD_CLOEXEC);
2354 }
2355 return result;
2356 #endif /* !MSDOS */
2357 }
2358
2359 /* Approximate posix_close and POSIX_CLOSE_RESTART well enough for Emacs.
2360 For the background behind this mess, please see Austin Group defect 529
2361 <http://austingroupbugs.net/view.php?id=529>. */
2362
2363 #ifndef POSIX_CLOSE_RESTART
2364 # define POSIX_CLOSE_RESTART 1
2365 static int
2366 posix_close (int fd, int flag)
2367 {
2368 /* Only the POSIX_CLOSE_RESTART case is emulated. */
2369 eassert (flag == POSIX_CLOSE_RESTART);
2370
2371 /* Things are tricky if close (fd) returns -1 with errno == EINTR
2372 on a system that does not define POSIX_CLOSE_RESTART.
2373
2374 In this case, in some systems (e.g., GNU/Linux, AIX) FD is
2375 closed, and retrying the close could inadvertently close a file
2376 descriptor allocated by some other thread. In other systems
2377 (e.g., HP/UX) FD is not closed. And in still other systems
2378 (e.g., OS X, Solaris), maybe FD is closed, maybe not, and in a
2379 multithreaded program there can be no way to tell.
2380
2381 So, in this case, pretend that the close succeeded. This works
2382 well on systems like GNU/Linux that close FD. Although it may
2383 leak a file descriptor on other systems, the leak is unlikely and
2384 it's better to leak than to close a random victim. */
2385 return close (fd) == 0 || errno == EINTR ? 0 : -1;
2386 }
2387 #endif
2388
2389 /* Close FD, retrying if interrupted. If successful, return 0;
2390 otherwise, return -1 and set errno to a non-EINTR value. Consider
2391 an EINPROGRESS error to be successful, as that's merely a signal
2392 arriving. FD is always closed when this function returns, even
2393 when it returns -1.
2394
2395 Do not call this function if FD is nonnegative and might already be closed,
2396 as that might close an innocent victim opened by some other thread. */
2397
2398 int
2399 emacs_close (int fd)
2400 {
2401 while (1)
2402 {
2403 int r = posix_close (fd, POSIX_CLOSE_RESTART);
2404 if (r == 0)
2405 return r;
2406 if (!POSIX_CLOSE_RESTART || errno != EINTR)
2407 {
2408 eassert (errno != EBADF || fd < 0);
2409 return errno == EINPROGRESS ? 0 : r;
2410 }
2411 }
2412 }
2413
2414 /* Maximum number of bytes to read or write in a single system call.
2415 This works around a serious bug in Linux kernels before 2.6.16; see
2416 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
2417 It's likely to work around similar bugs in other operating systems, so do it
2418 on all platforms. Round INT_MAX down to a page size, with the conservative
2419 assumption that page sizes are at most 2**18 bytes (any kernel with a
2420 page size larger than that shouldn't have the bug). */
2421 #ifndef MAX_RW_COUNT
2422 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
2423 #endif
2424
2425 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
2426 Return the number of bytes read, which might be less than NBYTE.
2427 On error, set errno and return -1. */
2428 ptrdiff_t
2429 emacs_read (int fildes, void *buf, ptrdiff_t nbyte)
2430 {
2431 ssize_t rtnval;
2432
2433 /* There is no need to check against MAX_RW_COUNT, since no caller ever
2434 passes a size that large to emacs_read. */
2435
2436 while ((rtnval = read (fildes, buf, nbyte)) == -1
2437 && (errno == EINTR))
2438 QUIT;
2439 return (rtnval);
2440 }
2441
2442 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
2443 or if a partial write occurs. If interrupted, process pending
2444 signals if PROCESS SIGNALS. Return the number of bytes written, setting
2445 errno if this is less than NBYTE. */
2446 static ptrdiff_t
2447 emacs_full_write (int fildes, char const *buf, ptrdiff_t nbyte,
2448 bool process_signals)
2449 {
2450 ptrdiff_t bytes_written = 0;
2451
2452 while (nbyte > 0)
2453 {
2454 ssize_t n = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
2455
2456 if (n < 0)
2457 {
2458 if (errno == EINTR)
2459 {
2460 /* I originally used `QUIT' but that might cause files to
2461 be truncated if you hit C-g in the middle of it. --Stef */
2462 if (process_signals && pending_signals)
2463 process_pending_signals ();
2464 continue;
2465 }
2466 else
2467 break;
2468 }
2469
2470 buf += n;
2471 nbyte -= n;
2472 bytes_written += n;
2473 }
2474
2475 return bytes_written;
2476 }
2477
2478 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if
2479 interrupted or if a partial write occurs. Return the number of
2480 bytes written, setting errno if this is less than NBYTE. */
2481 ptrdiff_t
2482 emacs_write (int fildes, void const *buf, ptrdiff_t nbyte)
2483 {
2484 return emacs_full_write (fildes, buf, nbyte, 0);
2485 }
2486
2487 /* Like emacs_write, but also process pending signals if interrupted. */
2488 ptrdiff_t
2489 emacs_write_sig (int fildes, void const *buf, ptrdiff_t nbyte)
2490 {
2491 return emacs_full_write (fildes, buf, nbyte, 1);
2492 }
2493
2494 /* Write a diagnostic to standard error that contains MESSAGE and a
2495 string derived from errno. Preserve errno. Do not buffer stderr.
2496 Do not process pending signals if interrupted. */
2497 void
2498 emacs_perror (char const *message)
2499 {
2500 int err = errno;
2501 char const *error_string = emacs_strerror (err);
2502 char const *command = (initial_argv && initial_argv[0]
2503 ? initial_argv[0] : "emacs");
2504 /* Write it out all at once, if it's short; this is less likely to
2505 be interleaved with other output. */
2506 char buf[BUFSIZ];
2507 int nbytes = snprintf (buf, sizeof buf, "%s: %s: %s\n",
2508 command, message, error_string);
2509 if (0 <= nbytes && nbytes < BUFSIZ)
2510 emacs_write (STDERR_FILENO, buf, nbytes);
2511 else
2512 {
2513 emacs_write (STDERR_FILENO, command, strlen (command));
2514 emacs_write (STDERR_FILENO, ": ", 2);
2515 emacs_write (STDERR_FILENO, message, strlen (message));
2516 emacs_write (STDERR_FILENO, ": ", 2);
2517 emacs_write (STDERR_FILENO, error_string, strlen (error_string));
2518 emacs_write (STDERR_FILENO, "\n", 1);
2519 }
2520 errno = err;
2521 }
2522 \f
2523 /* Return a struct timeval that is roughly equivalent to T.
2524 Use the least timeval not less than T.
2525 Return an extremal value if the result would overflow. */
2526 struct timeval
2527 make_timeval (struct timespec t)
2528 {
2529 struct timeval tv;
2530 tv.tv_sec = t.tv_sec;
2531 tv.tv_usec = t.tv_nsec / 1000;
2532
2533 if (t.tv_nsec % 1000 != 0)
2534 {
2535 if (tv.tv_usec < 999999)
2536 tv.tv_usec++;
2537 else if (tv.tv_sec < TYPE_MAXIMUM (time_t))
2538 {
2539 tv.tv_sec++;
2540 tv.tv_usec = 0;
2541 }
2542 }
2543
2544 return tv;
2545 }
2546
2547 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2548 ATIME and MTIME, respectively.
2549 FD must be either negative -- in which case it is ignored --
2550 or a file descriptor that is open on FILE.
2551 If FD is nonnegative, then FILE can be NULL. */
2552 int
2553 set_file_times (int fd, const char *filename,
2554 struct timespec atime, struct timespec mtime)
2555 {
2556 struct timespec timespec[2];
2557 timespec[0] = atime;
2558 timespec[1] = mtime;
2559 return fdutimens (fd, filename, timespec);
2560 }
2561 \f
2562 /* Like strsignal, except async-signal-safe, and this function typically
2563 returns a string in the C locale rather than the current locale. */
2564 char const *
2565 safe_strsignal (int code)
2566 {
2567 char const *signame = 0;
2568
2569 if (0 <= code && code < sys_siglist_entries)
2570 signame = sys_siglist[code];
2571 if (! signame)
2572 signame = "Unknown signal";
2573
2574 return signame;
2575 }
2576 \f
2577 #ifndef DOS_NT
2578 /* For make-serial-process */
2579 int
2580 serial_open (Lisp_Object port)
2581 {
2582 int fd = emacs_open (SSDATA (port), O_RDWR | O_NOCTTY | O_NONBLOCK, 0);
2583 if (fd < 0)
2584 report_file_error ("Opening serial port", port);
2585 #ifdef TIOCEXCL
2586 ioctl (fd, TIOCEXCL, (char *) 0);
2587 #endif
2588
2589 return fd;
2590 }
2591
2592 #if !defined (HAVE_CFMAKERAW)
2593 /* Workaround for targets which are missing cfmakeraw. */
2594 /* Pasted from man page. */
2595 static void
2596 cfmakeraw (struct termios *termios_p)
2597 {
2598 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2599 termios_p->c_oflag &= ~OPOST;
2600 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2601 termios_p->c_cflag &= ~(CSIZE|PARENB);
2602 termios_p->c_cflag |= CS8;
2603 }
2604 #endif /* !defined (HAVE_CFMAKERAW */
2605
2606 #if !defined (HAVE_CFSETSPEED)
2607 /* Workaround for targets which are missing cfsetspeed. */
2608 static int
2609 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2610 {
2611 return (cfsetispeed (termios_p, vitesse)
2612 + cfsetospeed (termios_p, vitesse));
2613 }
2614 #endif
2615
2616 /* For serial-process-configure */
2617 void
2618 serial_configure (struct Lisp_Process *p,
2619 Lisp_Object contact)
2620 {
2621 Lisp_Object childp2 = Qnil;
2622 Lisp_Object tem = Qnil;
2623 struct termios attr;
2624 int err;
2625 char summary[4] = "???"; /* This usually becomes "8N1". */
2626
2627 childp2 = Fcopy_sequence (p->childp);
2628
2629 /* Read port attributes and prepare default configuration. */
2630 err = tcgetattr (p->outfd, &attr);
2631 if (err != 0)
2632 report_file_error ("Failed tcgetattr", Qnil);
2633 cfmakeraw (&attr);
2634 #if defined (CLOCAL)
2635 attr.c_cflag |= CLOCAL;
2636 #endif
2637 #if defined (CREAD)
2638 attr.c_cflag |= CREAD;
2639 #endif
2640
2641 /* Configure speed. */
2642 if (!NILP (Fplist_member (contact, QCspeed)))
2643 tem = Fplist_get (contact, QCspeed);
2644 else
2645 tem = Fplist_get (p->childp, QCspeed);
2646 CHECK_NUMBER (tem);
2647 err = cfsetspeed (&attr, XINT (tem));
2648 if (err != 0)
2649 report_file_error ("Failed cfsetspeed", tem);
2650 childp2 = Fplist_put (childp2, QCspeed, tem);
2651
2652 /* Configure bytesize. */
2653 if (!NILP (Fplist_member (contact, QCbytesize)))
2654 tem = Fplist_get (contact, QCbytesize);
2655 else
2656 tem = Fplist_get (p->childp, QCbytesize);
2657 if (NILP (tem))
2658 tem = make_number (8);
2659 CHECK_NUMBER (tem);
2660 if (XINT (tem) != 7 && XINT (tem) != 8)
2661 error (":bytesize must be nil (8), 7, or 8");
2662 summary[0] = XINT (tem) + '0';
2663 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2664 attr.c_cflag &= ~CSIZE;
2665 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2666 #else
2667 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2668 if (XINT (tem) != 8)
2669 error ("Bytesize cannot be changed");
2670 #endif
2671 childp2 = Fplist_put (childp2, QCbytesize, tem);
2672
2673 /* Configure parity. */
2674 if (!NILP (Fplist_member (contact, QCparity)))
2675 tem = Fplist_get (contact, QCparity);
2676 else
2677 tem = Fplist_get (p->childp, QCparity);
2678 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2679 error (":parity must be nil (no parity), `even', or `odd'");
2680 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2681 attr.c_cflag &= ~(PARENB | PARODD);
2682 attr.c_iflag &= ~(IGNPAR | INPCK);
2683 if (NILP (tem))
2684 {
2685 summary[1] = 'N';
2686 }
2687 else if (EQ (tem, Qeven))
2688 {
2689 summary[1] = 'E';
2690 attr.c_cflag |= PARENB;
2691 attr.c_iflag |= (IGNPAR | INPCK);
2692 }
2693 else if (EQ (tem, Qodd))
2694 {
2695 summary[1] = 'O';
2696 attr.c_cflag |= (PARENB | PARODD);
2697 attr.c_iflag |= (IGNPAR | INPCK);
2698 }
2699 #else
2700 /* Don't error on no parity, which should be set by cfmakeraw. */
2701 if (!NILP (tem))
2702 error ("Parity cannot be configured");
2703 #endif
2704 childp2 = Fplist_put (childp2, QCparity, tem);
2705
2706 /* Configure stopbits. */
2707 if (!NILP (Fplist_member (contact, QCstopbits)))
2708 tem = Fplist_get (contact, QCstopbits);
2709 else
2710 tem = Fplist_get (p->childp, QCstopbits);
2711 if (NILP (tem))
2712 tem = make_number (1);
2713 CHECK_NUMBER (tem);
2714 if (XINT (tem) != 1 && XINT (tem) != 2)
2715 error (":stopbits must be nil (1 stopbit), 1, or 2");
2716 summary[2] = XINT (tem) + '0';
2717 #if defined (CSTOPB)
2718 attr.c_cflag &= ~CSTOPB;
2719 if (XINT (tem) == 2)
2720 attr.c_cflag |= CSTOPB;
2721 #else
2722 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2723 if (XINT (tem) != 1)
2724 error ("Stopbits cannot be configured");
2725 #endif
2726 childp2 = Fplist_put (childp2, QCstopbits, tem);
2727
2728 /* Configure flowcontrol. */
2729 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2730 tem = Fplist_get (contact, QCflowcontrol);
2731 else
2732 tem = Fplist_get (p->childp, QCflowcontrol);
2733 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2734 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2735 #if defined (CRTSCTS)
2736 attr.c_cflag &= ~CRTSCTS;
2737 #endif
2738 #if defined (CNEW_RTSCTS)
2739 attr.c_cflag &= ~CNEW_RTSCTS;
2740 #endif
2741 #if defined (IXON) && defined (IXOFF)
2742 attr.c_iflag &= ~(IXON | IXOFF);
2743 #endif
2744 if (NILP (tem))
2745 {
2746 /* Already configured. */
2747 }
2748 else if (EQ (tem, Qhw))
2749 {
2750 #if defined (CRTSCTS)
2751 attr.c_cflag |= CRTSCTS;
2752 #elif defined (CNEW_RTSCTS)
2753 attr.c_cflag |= CNEW_RTSCTS;
2754 #else
2755 error ("Hardware flowcontrol (RTS/CTS) not supported");
2756 #endif
2757 }
2758 else if (EQ (tem, Qsw))
2759 {
2760 #if defined (IXON) && defined (IXOFF)
2761 attr.c_iflag |= (IXON | IXOFF);
2762 #else
2763 error ("Software flowcontrol (XON/XOFF) not supported");
2764 #endif
2765 }
2766 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2767
2768 /* Activate configuration. */
2769 err = tcsetattr (p->outfd, TCSANOW, &attr);
2770 if (err != 0)
2771 report_file_error ("Failed tcsetattr", Qnil);
2772
2773 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2774 pset_childp (p, childp2);
2775 }
2776 #endif /* not DOS_NT */
2777 \f
2778 /* System depended enumeration of and access to system processes a-la ps(1). */
2779
2780 #ifdef HAVE_PROCFS
2781
2782 /* Process enumeration and access via /proc. */
2783
2784 Lisp_Object
2785 list_system_processes (void)
2786 {
2787 Lisp_Object procdir, match, proclist, next;
2788 Lisp_Object tail;
2789
2790 /* For every process on the system, there's a directory in the
2791 "/proc" pseudo-directory whose name is the numeric ID of that
2792 process. */
2793 procdir = build_string ("/proc");
2794 match = build_string ("[0-9]+");
2795 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2796
2797 /* `proclist' gives process IDs as strings. Destructively convert
2798 each string into a number. */
2799 for (tail = proclist; CONSP (tail); tail = next)
2800 {
2801 next = XCDR (tail);
2802 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2803 }
2804
2805 /* directory_files_internal returns the files in reverse order; undo
2806 that. */
2807 proclist = Fnreverse (proclist);
2808 return proclist;
2809 }
2810
2811 #elif defined DARWIN_OS || defined __FreeBSD__
2812
2813 Lisp_Object
2814 list_system_processes (void)
2815 {
2816 #ifdef DARWIN_OS
2817 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2818 #else
2819 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2820 #endif
2821 size_t len;
2822 struct kinfo_proc *procs;
2823 size_t i;
2824
2825 Lisp_Object proclist = Qnil;
2826
2827 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2828 return proclist;
2829
2830 procs = xmalloc (len);
2831 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2832 {
2833 xfree (procs);
2834 return proclist;
2835 }
2836
2837 len /= sizeof (struct kinfo_proc);
2838 for (i = 0; i < len; i++)
2839 {
2840 #ifdef DARWIN_OS
2841 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2842 #else
2843 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2844 #endif
2845 }
2846
2847 xfree (procs);
2848
2849 return proclist;
2850 }
2851
2852 /* The WINDOWSNT implementation is in w32.c.
2853 The MSDOS implementation is in dosfns.c. */
2854 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2855
2856 Lisp_Object
2857 list_system_processes (void)
2858 {
2859 return Qnil;
2860 }
2861
2862 #endif /* !defined (WINDOWSNT) */
2863
2864 #if defined GNU_LINUX && defined HAVE_LONG_LONG_INT
2865 static struct timespec
2866 time_from_jiffies (unsigned long long tval, long hz)
2867 {
2868 unsigned long long s = tval / hz;
2869 unsigned long long frac = tval % hz;
2870 int ns;
2871
2872 if (TYPE_MAXIMUM (time_t) < s)
2873 time_overflow ();
2874 if (LONG_MAX - 1 <= ULLONG_MAX / TIMESPEC_RESOLUTION
2875 || frac <= ULLONG_MAX / TIMESPEC_RESOLUTION)
2876 ns = frac * TIMESPEC_RESOLUTION / hz;
2877 else
2878 {
2879 /* This is reachable only in the unlikely case that HZ * HZ
2880 exceeds ULLONG_MAX. It calculates an approximation that is
2881 guaranteed to be in range. */
2882 long hz_per_ns = (hz / TIMESPEC_RESOLUTION
2883 + (hz % TIMESPEC_RESOLUTION != 0));
2884 ns = frac / hz_per_ns;
2885 }
2886
2887 return make_timespec (s, ns);
2888 }
2889
2890 static Lisp_Object
2891 ltime_from_jiffies (unsigned long long tval, long hz)
2892 {
2893 struct timespec t = time_from_jiffies (tval, hz);
2894 return make_lisp_time (t);
2895 }
2896
2897 static struct timespec
2898 get_up_time (void)
2899 {
2900 FILE *fup;
2901 struct timespec up = make_timespec (0, 0);
2902
2903 block_input ();
2904 fup = emacs_fopen ("/proc/uptime", "r");
2905
2906 if (fup)
2907 {
2908 unsigned long long upsec, upfrac, idlesec, idlefrac;
2909 int upfrac_start, upfrac_end, idlefrac_start, idlefrac_end;
2910
2911 if (fscanf (fup, "%llu.%n%llu%n %llu.%n%llu%n",
2912 &upsec, &upfrac_start, &upfrac, &upfrac_end,
2913 &idlesec, &idlefrac_start, &idlefrac, &idlefrac_end)
2914 == 4)
2915 {
2916 if (TYPE_MAXIMUM (time_t) < upsec)
2917 {
2918 upsec = TYPE_MAXIMUM (time_t);
2919 upfrac = TIMESPEC_RESOLUTION - 1;
2920 }
2921 else
2922 {
2923 int upfraclen = upfrac_end - upfrac_start;
2924 for (; upfraclen < LOG10_TIMESPEC_RESOLUTION; upfraclen++)
2925 upfrac *= 10;
2926 for (; LOG10_TIMESPEC_RESOLUTION < upfraclen; upfraclen--)
2927 upfrac /= 10;
2928 upfrac = min (upfrac, TIMESPEC_RESOLUTION - 1);
2929 }
2930 up = make_timespec (upsec, upfrac);
2931 }
2932 fclose (fup);
2933 }
2934 unblock_input ();
2935
2936 return up;
2937 }
2938
2939 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2940 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2941
2942 static Lisp_Object
2943 procfs_ttyname (int rdev)
2944 {
2945 FILE *fdev;
2946 char name[PATH_MAX];
2947
2948 block_input ();
2949 fdev = emacs_fopen ("/proc/tty/drivers", "r");
2950 name[0] = 0;
2951
2952 if (fdev)
2953 {
2954 unsigned major;
2955 unsigned long minor_beg, minor_end;
2956 char minor[25]; /* 2 32-bit numbers + dash */
2957 char *endp;
2958
2959 for (; !feof (fdev) && !ferror (fdev); name[0] = 0)
2960 {
2961 if (fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor) >= 3
2962 && major == MAJOR (rdev))
2963 {
2964 minor_beg = strtoul (minor, &endp, 0);
2965 if (*endp == '\0')
2966 minor_end = minor_beg;
2967 else if (*endp == '-')
2968 minor_end = strtoul (endp + 1, &endp, 0);
2969 else
2970 continue;
2971
2972 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
2973 {
2974 sprintf (name + strlen (name), "%u", MINOR (rdev));
2975 break;
2976 }
2977 }
2978 }
2979 fclose (fdev);
2980 }
2981 unblock_input ();
2982 return build_string (name);
2983 }
2984
2985 static uintmax_t
2986 procfs_get_total_memory (void)
2987 {
2988 FILE *fmem;
2989 uintmax_t retval = 2 * 1024 * 1024; /* default: 2 GiB */
2990 int c;
2991
2992 block_input ();
2993 fmem = emacs_fopen ("/proc/meminfo", "r");
2994
2995 if (fmem)
2996 {
2997 uintmax_t entry_value;
2998 bool done;
2999
3000 do
3001 switch (fscanf (fmem, "MemTotal: %"SCNuMAX, &entry_value))
3002 {
3003 case 1:
3004 retval = entry_value;
3005 done = 1;
3006 break;
3007
3008 case 0:
3009 while ((c = getc (fmem)) != EOF && c != '\n')
3010 continue;
3011 done = c == EOF;
3012 break;
3013
3014 default:
3015 done = 1;
3016 break;
3017 }
3018 while (!done);
3019
3020 fclose (fmem);
3021 }
3022 unblock_input ();
3023 return retval;
3024 }
3025
3026 Lisp_Object
3027 system_process_attributes (Lisp_Object pid)
3028 {
3029 char procfn[PATH_MAX], fn[PATH_MAX];
3030 struct stat st;
3031 struct passwd *pw;
3032 struct group *gr;
3033 long clocks_per_sec;
3034 char *procfn_end;
3035 char procbuf[1025], *p, *q;
3036 int fd;
3037 ssize_t nread;
3038 static char const default_cmd[] = "???";
3039 const char *cmd = default_cmd;
3040 int cmdsize = sizeof default_cmd - 1;
3041 char *cmdline = NULL;
3042 ptrdiff_t cmdline_size;
3043 char c;
3044 printmax_t proc_id;
3045 int ppid, pgrp, sess, tty, tpgid, thcount;
3046 uid_t uid;
3047 gid_t gid;
3048 unsigned long long u_time, s_time, cutime, cstime, start;
3049 long priority, niceness, rss;
3050 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3051 struct timespec tnow, tstart, tboot, telapsed, us_time;
3052 double pcpu, pmem;
3053 Lisp_Object attrs = Qnil;
3054 Lisp_Object decoded_cmd;
3055 ptrdiff_t count;
3056
3057 CHECK_NUMBER_OR_FLOAT (pid);
3058 CONS_TO_INTEGER (pid, pid_t, proc_id);
3059 sprintf (procfn, "/proc/%"pMd, proc_id);
3060 if (stat (procfn, &st) < 0)
3061 return attrs;
3062
3063 /* euid egid */
3064 uid = st.st_uid;
3065 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3066 block_input ();
3067 pw = getpwuid (uid);
3068 unblock_input ();
3069 if (pw)
3070 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3071
3072 gid = st.st_gid;
3073 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3074 block_input ();
3075 gr = getgrgid (gid);
3076 unblock_input ();
3077 if (gr)
3078 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3079
3080 count = SPECPDL_INDEX ();
3081 strcpy (fn, procfn);
3082 procfn_end = fn + strlen (fn);
3083 strcpy (procfn_end, "/stat");
3084 fd = emacs_open (fn, O_RDONLY, 0);
3085 if (fd < 0)
3086 nread = 0;
3087 else
3088 {
3089 record_unwind_protect_int (close_file_unwind, fd);
3090 nread = emacs_read (fd, procbuf, sizeof procbuf - 1);
3091 }
3092 if (0 < nread)
3093 {
3094 procbuf[nread] = '\0';
3095 p = procbuf;
3096
3097 p = strchr (p, '(');
3098 if (p != NULL)
3099 {
3100 q = strrchr (p + 1, ')');
3101 /* comm */
3102 if (q != NULL)
3103 {
3104 cmd = p + 1;
3105 cmdsize = q - cmd;
3106 }
3107 }
3108 else
3109 q = NULL;
3110 /* Command name is encoded in locale-coding-system; decode it. */
3111 AUTO_STRING_WITH_LEN (cmd_str, cmd, cmdsize);
3112 decoded_cmd = code_convert_string_norecord (cmd_str,
3113 Vlocale_coding_system, 0);
3114 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3115
3116 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt
3117 utime stime cutime cstime priority nice thcount . start vsize rss */
3118 if (q
3119 && (sscanf (q + 2, ("%c %d %d %d %d %d %*u %lu %lu %lu %lu "
3120 "%Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld"),
3121 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3122 &minflt, &cminflt, &majflt, &cmajflt,
3123 &u_time, &s_time, &cutime, &cstime,
3124 &priority, &niceness, &thcount, &start, &vsize, &rss)
3125 == 20))
3126 {
3127 char state_str[2];
3128 state_str[0] = c;
3129 state_str[1] = '\0';
3130 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3131 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid)), attrs);
3132 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp)), attrs);
3133 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess)), attrs);
3134 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3135 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid)), attrs);
3136 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3137 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3138 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)),
3139 attrs);
3140 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)),
3141 attrs);
3142 clocks_per_sec = sysconf (_SC_CLK_TCK);
3143 if (clocks_per_sec < 0)
3144 clocks_per_sec = 100;
3145 attrs = Fcons (Fcons (Qutime,
3146 ltime_from_jiffies (u_time, clocks_per_sec)),
3147 attrs);
3148 attrs = Fcons (Fcons (Qstime,
3149 ltime_from_jiffies (s_time, clocks_per_sec)),
3150 attrs);
3151 attrs = Fcons (Fcons (Qtime,
3152 ltime_from_jiffies (s_time + u_time,
3153 clocks_per_sec)),
3154 attrs);
3155 attrs = Fcons (Fcons (Qcutime,
3156 ltime_from_jiffies (cutime, clocks_per_sec)),
3157 attrs);
3158 attrs = Fcons (Fcons (Qcstime,
3159 ltime_from_jiffies (cstime, clocks_per_sec)),
3160 attrs);
3161 attrs = Fcons (Fcons (Qctime,
3162 ltime_from_jiffies (cstime + cutime,
3163 clocks_per_sec)),
3164 attrs);
3165 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3166 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
3167 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount)),
3168 attrs);
3169 tnow = current_timespec ();
3170 telapsed = get_up_time ();
3171 tboot = timespec_sub (tnow, telapsed);
3172 tstart = time_from_jiffies (start, clocks_per_sec);
3173 tstart = timespec_add (tboot, tstart);
3174 attrs = Fcons (Fcons (Qstart, make_lisp_time (tstart)), attrs);
3175 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize / 1024)),
3176 attrs);
3177 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4 * rss)), attrs);
3178 telapsed = timespec_sub (tnow, tstart);
3179 attrs = Fcons (Fcons (Qetime, make_lisp_time (telapsed)), attrs);
3180 us_time = time_from_jiffies (u_time + s_time, clocks_per_sec);
3181 pcpu = timespectod (us_time) / timespectod (telapsed);
3182 if (pcpu > 1.0)
3183 pcpu = 1.0;
3184 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3185 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3186 if (pmem > 100)
3187 pmem = 100;
3188 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3189 }
3190 }
3191 unbind_to (count, Qnil);
3192
3193 /* args */
3194 strcpy (procfn_end, "/cmdline");
3195 fd = emacs_open (fn, O_RDONLY, 0);
3196 if (fd >= 0)
3197 {
3198 ptrdiff_t readsize, nread_incr;
3199 record_unwind_protect_int (close_file_unwind, fd);
3200 record_unwind_protect_nothing ();
3201 nread = cmdline_size = 0;
3202
3203 do
3204 {
3205 cmdline = xpalloc (cmdline, &cmdline_size, 2, STRING_BYTES_BOUND, 1);
3206 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3207
3208 /* Leave room even if every byte needs escaping below. */
3209 readsize = (cmdline_size >> 1) - nread;
3210
3211 nread_incr = emacs_read (fd, cmdline + nread, readsize);
3212 nread += max (0, nread_incr);
3213 }
3214 while (nread_incr == readsize);
3215
3216 if (nread)
3217 {
3218 /* We don't want trailing null characters. */
3219 for (p = cmdline + nread; cmdline < p && !p[-1]; p--)
3220 continue;
3221
3222 /* Escape-quote whitespace and backslashes. */
3223 q = cmdline + cmdline_size;
3224 while (cmdline < p)
3225 {
3226 char c = *--p;
3227 *--q = c ? c : ' ';
3228 if (c_isspace (c) || c == '\\')
3229 *--q = '\\';
3230 }
3231
3232 nread = cmdline + cmdline_size - q;
3233 }
3234
3235 if (!nread)
3236 {
3237 nread = cmdsize + 2;
3238 cmdline_size = nread + 1;
3239 q = cmdline = xrealloc (cmdline, cmdline_size);
3240 set_unwind_protect_ptr (count + 1, xfree, cmdline);
3241 sprintf (cmdline, "[%.*s]", cmdsize, cmd);
3242 }
3243 /* Command line is encoded in locale-coding-system; decode it. */
3244 AUTO_STRING_WITH_LEN (cmd_str, q, nread);
3245 decoded_cmd = code_convert_string_norecord (cmd_str,
3246 Vlocale_coding_system, 0);
3247 unbind_to (count, Qnil);
3248 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3249 }
3250
3251 return attrs;
3252 }
3253
3254 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3255
3256 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3257 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3258 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3259 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3260 #undef _FILE_OFFSET_BITS
3261 #else
3262 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3263 #endif
3264
3265 #include <procfs.h>
3266
3267 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3268 #define _FILE_OFFSET_BITS 64
3269 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3270 #endif
3271 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3272
3273 Lisp_Object
3274 system_process_attributes (Lisp_Object pid)
3275 {
3276 char procfn[PATH_MAX], fn[PATH_MAX];
3277 struct stat st;
3278 struct passwd *pw;
3279 struct group *gr;
3280 char *procfn_end;
3281 struct psinfo pinfo;
3282 int fd;
3283 ssize_t nread;
3284 printmax_t proc_id;
3285 uid_t uid;
3286 gid_t gid;
3287 Lisp_Object attrs = Qnil;
3288 Lisp_Object decoded_cmd;
3289 ptrdiff_t count;
3290
3291 CHECK_NUMBER_OR_FLOAT (pid);
3292 CONS_TO_INTEGER (pid, pid_t, proc_id);
3293 sprintf (procfn, "/proc/%"pMd, proc_id);
3294 if (stat (procfn, &st) < 0)
3295 return attrs;
3296
3297 /* euid egid */
3298 uid = st.st_uid;
3299 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3300 block_input ();
3301 pw = getpwuid (uid);
3302 unblock_input ();
3303 if (pw)
3304 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3305
3306 gid = st.st_gid;
3307 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3308 block_input ();
3309 gr = getgrgid (gid);
3310 unblock_input ();
3311 if (gr)
3312 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3313
3314 count = SPECPDL_INDEX ();
3315 strcpy (fn, procfn);
3316 procfn_end = fn + strlen (fn);
3317 strcpy (procfn_end, "/psinfo");
3318 fd = emacs_open (fn, O_RDONLY, 0);
3319 if (fd < 0)
3320 nread = 0;
3321 else
3322 {
3323 record_unwind_protect (close_file_unwind, fd);
3324 nread = emacs_read (fd, &pinfo, sizeof pinfo);
3325 }
3326
3327 if (nread == sizeof pinfo)
3328 {
3329 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3330 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3331 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3332
3333 {
3334 char state_str[2];
3335 state_str[0] = pinfo.pr_lwp.pr_sname;
3336 state_str[1] = '\0';
3337 attrs = Fcons (Fcons (Qstate, build_string (state_str)), attrs);
3338 }
3339
3340 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3341 need to get a string from it. */
3342
3343 /* FIXME: missing: Qtpgid */
3344
3345 /* FIXME: missing:
3346 Qminflt
3347 Qmajflt
3348 Qcminflt
3349 Qcmajflt
3350
3351 Qutime
3352 Qcutime
3353 Qstime
3354 Qcstime
3355 Are they available? */
3356
3357 attrs = Fcons (Fcons (Qtime, make_lisp_time (pinfo.pr_time)), attrs);
3358 attrs = Fcons (Fcons (Qctime, make_lisp_time (pinfo.pr_ctime)), attrs);
3359 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3360 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3361 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)),
3362 attrs);
3363
3364 attrs = Fcons (Fcons (Qstart, make_lisp_time (pinfo.pr_start)), attrs);
3365 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)),
3366 attrs);
3367 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)),
3368 attrs);
3369
3370 /* pr_pctcpu and pr_pctmem are unsigned integers in the
3371 range 0 .. 2**15, representing 0.0 .. 1.0. */
3372 attrs = Fcons (Fcons (Qpcpu,
3373 make_float (100.0 / 0x8000 * pinfo.pr_pctcpu)),
3374 attrs);
3375 attrs = Fcons (Fcons (Qpmem,
3376 make_float (100.0 / 0x8000 * pinfo.pr_pctmem)),
3377 attrs);
3378
3379 AUTO_STRING (fname, pinfo.pr_fname);
3380 decoded_cmd = code_convert_string_norecord (fname,
3381 Vlocale_coding_system, 0);
3382 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3383 AUTO_STRING (psargs, pinfo.pr_psargs);
3384 decoded_cmd = code_convert_string_norecord (psargs,
3385 Vlocale_coding_system, 0);
3386 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3387 }
3388 unbind_to (count, Qnil);
3389 return attrs;
3390 }
3391
3392 #elif defined __FreeBSD__
3393
3394 static struct timespec
3395 timeval_to_timespec (struct timeval t)
3396 {
3397 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3398 }
3399
3400 static Lisp_Object
3401 make_lisp_timeval (struct timeval t)
3402 {
3403 return make_lisp_time (timeval_to_timespec (t));
3404 }
3405
3406 Lisp_Object
3407 system_process_attributes (Lisp_Object pid)
3408 {
3409 int proc_id;
3410 int pagesize = getpagesize ();
3411 unsigned long npages;
3412 int fscale;
3413 struct passwd *pw;
3414 struct group *gr;
3415 char *ttyname;
3416 size_t len;
3417 char args[MAXPATHLEN];
3418 struct timespec t, now;
3419
3420 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3421 struct kinfo_proc proc;
3422 size_t proclen = sizeof proc;
3423
3424 Lisp_Object attrs = Qnil;
3425 Lisp_Object decoded_comm;
3426
3427 CHECK_NUMBER_OR_FLOAT (pid);
3428 CONS_TO_INTEGER (pid, int, proc_id);
3429 mib[3] = proc_id;
3430
3431 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3432 return attrs;
3433
3434 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3435
3436 block_input ();
3437 pw = getpwuid (proc.ki_uid);
3438 unblock_input ();
3439 if (pw)
3440 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3441
3442 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3443
3444 block_input ();
3445 gr = getgrgid (proc.ki_svgid);
3446 unblock_input ();
3447 if (gr)
3448 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3449
3450 AUTO_STRING (comm, proc.ki_comm);
3451 decoded_comm = code_convert_string_norecord (comm, Vlocale_coding_system, 0);
3452
3453 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3454 {
3455 char state[2] = {'\0', '\0'};
3456 switch (proc.ki_stat)
3457 {
3458 case SRUN:
3459 state[0] = 'R';
3460 break;
3461
3462 case SSLEEP:
3463 state[0] = 'S';
3464 break;
3465
3466 case SLOCK:
3467 state[0] = 'D';
3468 break;
3469
3470 case SZOMB:
3471 state[0] = 'Z';
3472 break;
3473
3474 case SSTOP:
3475 state[0] = 'T';
3476 break;
3477 }
3478 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3479 }
3480
3481 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3482 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3483 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3484
3485 block_input ();
3486 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3487 unblock_input ();
3488 if (ttyname)
3489 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3490
3491 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3492 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3493 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3494 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3495 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3496
3497 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (proc.ki_rusage.ru_utime)),
3498 attrs);
3499 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (proc.ki_rusage.ru_stime)),
3500 attrs);
3501 t = timespec_add (timeval_to_timespec (proc.ki_rusage.ru_utime),
3502 timeval_to_timespec (proc.ki_rusage.ru_stime));
3503 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3504
3505 attrs = Fcons (Fcons (Qcutime,
3506 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3507 attrs);
3508 attrs = Fcons (Fcons (Qcstime,
3509 make_lisp_timeval (proc.ki_rusage_ch.ru_utime)),
3510 attrs);
3511 t = timespec_add (timeval_to_timespec (proc.ki_rusage_ch.ru_utime),
3512 timeval_to_timespec (proc.ki_rusage_ch.ru_stime));
3513 attrs = Fcons (Fcons (Qctime, make_lisp_time (t)), attrs);
3514
3515 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3516 attrs);
3517 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3518 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3519 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (proc.ki_start)), attrs);
3520 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3521 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3522 attrs);
3523
3524 now = current_timespec ();
3525 t = timespec_sub (now, timeval_to_timespec (proc.ki_start));
3526 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3527
3528 len = sizeof fscale;
3529 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3530 {
3531 double pcpu;
3532 fixpt_t ccpu;
3533 len = sizeof ccpu;
3534 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3535 {
3536 pcpu = (100.0 * proc.ki_pctcpu / fscale
3537 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3538 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3539 }
3540 }
3541
3542 len = sizeof npages;
3543 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3544 {
3545 double pmem = (proc.ki_flag & P_INMEM
3546 ? 100.0 * proc.ki_rssize / npages
3547 : 0);
3548 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3549 }
3550
3551 mib[2] = KERN_PROC_ARGS;
3552 len = MAXPATHLEN;
3553 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3554 {
3555 int i;
3556 for (i = 0; i < len; i++)
3557 {
3558 if (! args[i] && i < len - 1)
3559 args[i] = ' ';
3560 }
3561
3562 AUTO_STRING (comm, args);
3563 decoded_comm = code_convert_string_norecord (comm,
3564 Vlocale_coding_system, 0);
3565
3566 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3567 }
3568
3569 return attrs;
3570 }
3571
3572 #elif defined DARWIN_OS
3573
3574 static struct timespec
3575 timeval_to_timespec (struct timeval t)
3576 {
3577 return make_timespec (t.tv_sec, t.tv_usec * 1000);
3578 }
3579
3580 static Lisp_Object
3581 make_lisp_timeval (struct timeval t)
3582 {
3583 return make_lisp_time (timeval_to_timespec (t));
3584 }
3585
3586 Lisp_Object
3587 system_process_attributes (Lisp_Object pid)
3588 {
3589 int proc_id;
3590 int pagesize = getpagesize ();
3591 unsigned long npages;
3592 int fscale;
3593 struct passwd *pw;
3594 struct group *gr;
3595 char *ttyname;
3596 size_t len;
3597 char args[MAXPATHLEN];
3598 struct timeval starttime;
3599 struct timespec t, now;
3600 struct rusage *rusage;
3601 dev_t tdev;
3602 uid_t uid;
3603 gid_t gid;
3604
3605 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3606 struct kinfo_proc proc;
3607 size_t proclen = sizeof proc;
3608
3609 Lisp_Object attrs = Qnil;
3610 Lisp_Object decoded_comm;
3611
3612 CHECK_NUMBER_OR_FLOAT (pid);
3613 CONS_TO_INTEGER (pid, int, proc_id);
3614 mib[3] = proc_id;
3615
3616 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3617 return attrs;
3618
3619 uid = proc.kp_eproc.e_ucred.cr_uid;
3620 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3621
3622 block_input ();
3623 pw = getpwuid (uid);
3624 unblock_input ();
3625 if (pw)
3626 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3627
3628 gid = proc.kp_eproc.e_pcred.p_svgid;
3629 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3630
3631 block_input ();
3632 gr = getgrgid (gid);
3633 unblock_input ();
3634 if (gr)
3635 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3636
3637 decoded_comm = (code_convert_string_norecord
3638 (build_unibyte_string (proc.kp_proc.p_comm),
3639 Vlocale_coding_system, 0));
3640
3641 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3642 {
3643 char state[2] = {'\0', '\0'};
3644 switch (proc.kp_proc.p_stat)
3645 {
3646 case SRUN:
3647 state[0] = 'R';
3648 break;
3649
3650 case SSLEEP:
3651 state[0] = 'S';
3652 break;
3653
3654 case SZOMB:
3655 state[0] = 'Z';
3656 break;
3657
3658 case SSTOP:
3659 state[0] = 'T';
3660 break;
3661
3662 case SIDL:
3663 state[0] = 'I';
3664 break;
3665 }
3666 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3667 }
3668
3669 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.kp_eproc.e_ppid)),
3670 attrs);
3671 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.kp_eproc.e_pgid)),
3672 attrs);
3673
3674 tdev = proc.kp_eproc.e_tdev;
3675 block_input ();
3676 ttyname = tdev == NODEV ? NULL : devname (tdev, S_IFCHR);
3677 unblock_input ();
3678 if (ttyname)
3679 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3680
3681 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.kp_eproc.e_tpgid)),
3682 attrs);
3683
3684 rusage = proc.kp_proc.p_ru;
3685 if (rusage)
3686 {
3687 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (rusage->ru_minflt)),
3688 attrs);
3689 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (rusage->ru_majflt)),
3690 attrs);
3691
3692 attrs = Fcons (Fcons (Qutime, make_lisp_timeval (rusage->ru_utime)),
3693 attrs);
3694 attrs = Fcons (Fcons (Qstime, make_lisp_timeval (rusage->ru_stime)),
3695 attrs);
3696 t = timespec_add (timeval_to_timespec (rusage->ru_utime),
3697 timeval_to_timespec (rusage->ru_stime));
3698 attrs = Fcons (Fcons (Qtime, make_lisp_time (t)), attrs);
3699 }
3700
3701 starttime = proc.kp_proc.p_starttime;
3702 attrs = Fcons (Fcons (Qnice, make_number (proc.kp_proc.p_nice)), attrs);
3703 attrs = Fcons (Fcons (Qstart, make_lisp_timeval (starttime)), attrs);
3704
3705 now = current_timespec ();
3706 t = timespec_sub (now, timeval_to_timespec (starttime));
3707 attrs = Fcons (Fcons (Qetime, make_lisp_time (t)), attrs);
3708
3709 return attrs;
3710 }
3711
3712 /* The WINDOWSNT implementation is in w32.c.
3713 The MSDOS implementation is in dosfns.c. */
3714 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3715
3716 Lisp_Object
3717 system_process_attributes (Lisp_Object pid)
3718 {
3719 return Qnil;
3720 }
3721
3722 #endif /* !defined (WINDOWSNT) */
3723 \f
3724 /* Wide character string collation. */
3725
3726 #ifdef __STDC_ISO_10646__
3727 # include <wchar.h>
3728 # include <wctype.h>
3729
3730 # if defined HAVE_NEWLOCALE || defined HAVE_SETLOCALE
3731 # include <locale.h>
3732 # endif
3733 # ifndef LC_COLLATE
3734 # define LC_COLLATE 0
3735 # endif
3736 # ifndef LC_COLLATE_MASK
3737 # define LC_COLLATE_MASK 0
3738 # endif
3739 # ifndef LC_CTYPE
3740 # define LC_CTYPE 0
3741 # endif
3742 # ifndef LC_CTYPE_MASK
3743 # define LC_CTYPE_MASK 0
3744 # endif
3745
3746 # ifndef HAVE_NEWLOCALE
3747 # undef freelocale
3748 # undef locale_t
3749 # undef newlocale
3750 # undef wcscoll_l
3751 # undef towlower_l
3752 # define freelocale emacs_freelocale
3753 # define locale_t emacs_locale_t
3754 # define newlocale emacs_newlocale
3755 # define wcscoll_l emacs_wcscoll_l
3756 # define towlower_l emacs_towlower_l
3757
3758 typedef char const *locale_t;
3759
3760 static locale_t
3761 newlocale (int category_mask, char const *locale, locale_t loc)
3762 {
3763 return locale;
3764 }
3765
3766 static void
3767 freelocale (locale_t loc)
3768 {
3769 }
3770
3771 static char *
3772 emacs_setlocale (int category, char const *locale)
3773 {
3774 # ifdef HAVE_SETLOCALE
3775 errno = 0;
3776 char *loc = setlocale (category, locale);
3777 if (loc || errno)
3778 return loc;
3779 errno = EINVAL;
3780 # else
3781 errno = ENOTSUP;
3782 # endif
3783 return 0;
3784 }
3785
3786 static int
3787 wcscoll_l (wchar_t const *a, wchar_t const *b, locale_t loc)
3788 {
3789 int result = 0;
3790 char *oldloc = emacs_setlocale (LC_COLLATE, NULL);
3791 int err;
3792
3793 if (! oldloc)
3794 err = errno;
3795 else
3796 {
3797 USE_SAFE_ALLOCA;
3798 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3799 strcpy (oldcopy, oldloc);
3800 if (! emacs_setlocale (LC_COLLATE, loc))
3801 err = errno;
3802 else
3803 {
3804 errno = 0;
3805 result = wcscoll (a, b);
3806 err = errno;
3807 if (! emacs_setlocale (LC_COLLATE, oldcopy))
3808 err = errno;
3809 }
3810 SAFE_FREE ();
3811 }
3812
3813 errno = err;
3814 return result;
3815 }
3816
3817 static wint_t
3818 towlower_l (wint_t wc, locale_t loc)
3819 {
3820 wint_t result = wc;
3821 char *oldloc = emacs_setlocale (LC_CTYPE, NULL);
3822
3823 if (oldloc)
3824 {
3825 USE_SAFE_ALLOCA;
3826 char *oldcopy = SAFE_ALLOCA (strlen (oldloc) + 1);
3827 strcpy (oldcopy, oldloc);
3828 if (emacs_setlocale (LC_CTYPE, loc))
3829 {
3830 result = towlower (wc);
3831 emacs_setlocale (LC_COLLATE, oldcopy);
3832 }
3833 SAFE_FREE ();
3834 }
3835
3836 return result;
3837 }
3838 # endif
3839
3840 int
3841 str_collate (Lisp_Object s1, Lisp_Object s2,
3842 Lisp_Object locale, Lisp_Object ignore_case)
3843 {
3844 int res, err;
3845 ptrdiff_t len, i, i_byte;
3846 wchar_t *p1, *p2;
3847
3848 USE_SAFE_ALLOCA;
3849
3850 /* Convert byte stream to code points. */
3851 len = SCHARS (s1); i = i_byte = 0;
3852 SAFE_NALLOCA (p1, 1, len + 1);
3853 while (i < len)
3854 FETCH_STRING_CHAR_ADVANCE (*(p1+i-1), s1, i, i_byte);
3855 *(p1+len) = 0;
3856
3857 len = SCHARS (s2); i = i_byte = 0;
3858 SAFE_NALLOCA (p2, 1, len + 1);
3859 while (i < len)
3860 FETCH_STRING_CHAR_ADVANCE (*(p2+i-1), s2, i, i_byte);
3861 *(p2+len) = 0;
3862
3863 if (STRINGP (locale))
3864 {
3865 locale_t loc = newlocale (LC_COLLATE_MASK | LC_CTYPE_MASK,
3866 SSDATA (locale), 0);
3867 if (!loc)
3868 error ("Invalid locale %s: %s", SSDATA (locale), emacs_strerror (errno));
3869
3870 if (! NILP (ignore_case))
3871 for (int i = 1; i < 3; i++)
3872 {
3873 wchar_t *p = (i == 1) ? p1 : p2;
3874 for (; *p; p++)
3875 *p = towlower_l (*p, loc);
3876 }
3877
3878 errno = 0;
3879 res = wcscoll_l (p1, p2, loc);
3880 err = errno;
3881 freelocale (loc);
3882 }
3883 else
3884 {
3885 if (! NILP (ignore_case))
3886 for (int i = 1; i < 3; i++)
3887 {
3888 wchar_t *p = (i == 1) ? p1 : p2;
3889 for (; *p; p++)
3890 *p = towlower (*p);
3891 }
3892
3893 errno = 0;
3894 res = wcscoll (p1, p2);
3895 err = errno;
3896 }
3897 # ifndef HAVE_NEWLOCALE
3898 if (err)
3899 error ("Invalid locale or string for collation: %s", emacs_strerror (err));
3900 # else
3901 if (err)
3902 error ("Invalid string for collation: %s", emacs_strerror (err));
3903 # endif
3904
3905 SAFE_FREE ();
3906 return res;
3907 }
3908 #endif /* __STDC_ISO_10646__ */
3909
3910 #ifdef WINDOWSNT
3911 int
3912 str_collate (Lisp_Object s1, Lisp_Object s2,
3913 Lisp_Object locale, Lisp_Object ignore_case)
3914 {
3915
3916 char *loc = STRINGP (locale) ? SSDATA (locale) : NULL;
3917 int res, err = errno;
3918
3919 errno = 0;
3920 res = w32_compare_strings (SSDATA (s1), SSDATA (s2), loc, !NILP (ignore_case));
3921 if (errno)
3922 error ("Invalid string for collation: %s", strerror (errno));
3923
3924 errno = err;
3925 return res;
3926 }
3927 #endif /* WINDOWSNT */