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