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