]> code.delx.au - gnu-emacs/blob - src/sysdep.c
Simplify last change.
[gnu-emacs] / src / sysdep.c
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1999, 2000, 2001,
3 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
4 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <ctype.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <setjmp.h>
29 #ifdef HAVE_PWD_H
30 #include <pwd.h>
31 #include <grp.h>
32 #endif /* HAVE_PWD_H */
33 #ifdef HAVE_LIMITS_H
34 #include <limits.h>
35 #endif /* HAVE_LIMITS_H */
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifdef HAVE_ALLOCA_H
40 #include <alloca.h>
41 #endif /* HAVE_ALLOCA_H */
42
43 #include "lisp.h"
44 /* Including stdlib.h isn't necessarily enough to get srandom
45 declared, e.g. without __USE_XOPEN_EXTENDED with glibc 2. */
46
47 /* The w32 build defines select stuff in w32.h, which is included by
48 sys/select.h (included below). */
49 #ifndef WINDOWSNT
50 #include "sysselect.h"
51 #endif
52
53 #include "blockinput.h"
54
55 #ifdef WINDOWSNT
56 #define read sys_read
57 #define write sys_write
58 #include <windows.h>
59 #ifndef NULL
60 #define NULL 0
61 #endif
62 #endif /* not WINDOWSNT */
63
64 /* Does anyone other than VMS need this? */
65 #ifndef fwrite
66 #define sys_fwrite fwrite
67 #else
68 #undef fwrite
69 #endif
70
71 #include <sys/types.h>
72 #include <sys/stat.h>
73 #include <errno.h>
74
75 #ifdef HAVE_SETPGID
76 #if !defined (USG) || defined (BSD_PGRPS)
77 #undef setpgrp
78 #define setpgrp setpgid
79 #endif
80 #endif
81
82 /* Get SI_SRPC_DOMAIN, if it is available. */
83 #ifdef HAVE_SYS_SYSTEMINFO_H
84 #include <sys/systeminfo.h>
85 #endif
86
87 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
88 #include <dos.h>
89 #include "dosfns.h"
90 #include "msdos.h"
91 #include <sys/param.h>
92
93 #if __DJGPP__ > 1
94 extern int etext;
95 extern unsigned start __asm__ ("start");
96 #endif
97 #endif
98
99 #ifndef USE_CRT_DLL
100 #ifndef errno
101 extern int errno;
102 #endif
103 #endif
104
105 #include <sys/file.h>
106
107 #ifdef HAVE_FCNTL_H
108 #include <fcntl.h>
109 #endif
110
111 #ifndef MSDOS
112 #include <sys/ioctl.h>
113 #endif
114
115 #include "systty.h"
116 #include "syswait.h"
117
118 #if defined (USG)
119 #include <sys/utsname.h>
120 #include <memory.h>
121 #endif /* USG */
122
123 extern int quit_char;
124
125 #include "keyboard.h"
126 #include "frame.h"
127 #include "window.h"
128 #include "termhooks.h"
129 #include "termchar.h"
130 #include "termopts.h"
131 #include "dispextern.h"
132 #include "process.h"
133 #include "cm.h" /* for reset_sys_modes */
134
135 /* For serial_configure and serial_open. */
136 extern Lisp_Object QCport, QCspeed, QCprocess;
137 extern Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
138 extern Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
139
140 #ifdef WINDOWSNT
141 #include <direct.h>
142 /* In process.h which conflicts with the local copy. */
143 #define _P_WAIT 0
144 int _cdecl _spawnlp (int, const char *, const char *, ...);
145 int _cdecl _getpid (void);
146 extern char *getwd (char *);
147 #endif
148
149 #include "syssignal.h"
150 #include "systime.h"
151 #ifdef HAVE_UTIME_H
152 #include <utime.h>
153 #endif
154
155 #ifndef HAVE_UTIMES
156 #ifndef HAVE_STRUCT_UTIMBUF
157 /* We want to use utime rather than utimes, but we couldn't find the
158 structure declaration. We'll use the traditional one. */
159 struct utimbuf {
160 long actime;
161 long modtime;
162 };
163 #endif
164 #endif
165
166 /* LPASS8 is new in 4.3, and makes cbreak mode provide all 8 bits. */
167 #ifndef LPASS8
168 #define LPASS8 0
169 #endif
170
171 static int baud_convert[] =
172 {
173 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
174 1800, 2400, 4800, 9600, 19200, 38400
175 };
176
177 #ifdef HAVE_SPEED_T
178 #include <termios.h>
179 #else
180 #if defined (HAVE_LIBNCURSES) && ! defined (NCURSES_OSPEED_T)
181 #else
182 #if defined (HAVE_TERMIOS_H) && defined (GNU_LINUX)
183 #include <termios.h>
184 #endif
185 #endif
186 #endif
187
188 int emacs_ospeed;
189
190 void croak P_ ((char *)) NO_RETURN;
191
192 /* Temporary used by `sigblock' when defined in terms of signprocmask. */
193
194 SIGMASKTYPE sigprocmask_set;
195
196
197 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
198
199 /* Return the current working directory. Returns NULL on errors.
200 Any other returned value must be freed with free. This is used
201 only when get_current_dir_name is not defined on the system. */
202 char*
203 get_current_dir_name ()
204 {
205 char *buf;
206 char *pwd;
207 struct stat dotstat, pwdstat;
208 /* If PWD is accurate, use it instead of calling getwd. PWD is
209 sometimes a nicer name, and using it may avoid a fatal error if a
210 parent directory is searchable but not readable. */
211 if ((pwd = getenv ("PWD")) != 0
212 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
213 && stat (pwd, &pwdstat) == 0
214 && stat (".", &dotstat) == 0
215 && dotstat.st_ino == pwdstat.st_ino
216 && dotstat.st_dev == pwdstat.st_dev
217 #ifdef MAXPATHLEN
218 && strlen (pwd) < MAXPATHLEN
219 #endif
220 )
221 {
222 buf = (char *) malloc (strlen (pwd) + 1);
223 if (!buf)
224 return NULL;
225 strcpy (buf, pwd);
226 }
227 #ifdef HAVE_GETCWD
228 else
229 {
230 size_t buf_size = 1024;
231 buf = (char *) malloc (buf_size);
232 if (!buf)
233 return NULL;
234 for (;;)
235 {
236 if (getcwd (buf, buf_size) == buf)
237 break;
238 if (errno != ERANGE)
239 {
240 int tmp_errno = errno;
241 free (buf);
242 errno = tmp_errno;
243 return NULL;
244 }
245 buf_size *= 2;
246 buf = (char *) realloc (buf, buf_size);
247 if (!buf)
248 return NULL;
249 }
250 }
251 #else
252 else
253 {
254 /* We need MAXPATHLEN here. */
255 buf = (char *) malloc (MAXPATHLEN + 1);
256 if (!buf)
257 return NULL;
258 if (getwd (buf) == NULL)
259 {
260 int tmp_errno = errno;
261 free (buf);
262 errno = tmp_errno;
263 return NULL;
264 }
265 }
266 #endif
267 return buf;
268 }
269 #endif
270
271 \f
272 /* Discard pending input on all input descriptors. */
273
274 void
275 discard_tty_input ()
276 {
277 #ifndef WINDOWSNT
278 struct emacs_tty buf;
279
280 if (noninteractive)
281 return;
282
283 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
284 while (dos_keyread () != -1)
285 ;
286 #else /* not MSDOS */
287 {
288 struct tty_display_info *tty;
289 for (tty = tty_list; tty; tty = tty->next)
290 {
291 if (tty->input) /* Is the device suspended? */
292 {
293 EMACS_GET_TTY (fileno (tty->input), &buf);
294 EMACS_SET_TTY (fileno (tty->input), &buf, 0);
295 }
296 }
297 }
298 #endif /* not MSDOS */
299 #endif /* not WINDOWSNT */
300 }
301
302 \f
303 #ifdef SIGTSTP
304
305 /* Arrange for character C to be read as the next input from
306 the terminal.
307 XXX What if we have multiple ttys?
308 */
309
310 void
311 stuff_char (char c)
312 {
313 if (! FRAME_TERMCAP_P (SELECTED_FRAME ()))
314 return;
315
316 /* Should perhaps error if in batch mode */
317 #ifdef TIOCSTI
318 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
319 #else /* no TIOCSTI */
320 error ("Cannot stuff terminal input characters in this version of Unix");
321 #endif /* no TIOCSTI */
322 }
323
324 #endif /* SIGTSTP */
325 \f
326 void
327 init_baud_rate (int fd)
328 {
329 if (noninteractive)
330 emacs_ospeed = 0;
331 else
332 {
333 #ifdef DOS_NT
334 emacs_ospeed = 15;
335 #else /* not DOS_NT */
336 #ifdef HAVE_TERMIOS
337 struct termios sg;
338
339 sg.c_cflag = B9600;
340 tcgetattr (fd, &sg);
341 emacs_ospeed = cfgetospeed (&sg);
342 #else /* not TERMIOS */
343 #ifdef HAVE_TERMIO
344 struct termio sg;
345
346 sg.c_cflag = B9600;
347 #ifdef HAVE_TCATTR
348 tcgetattr (fd, &sg);
349 #else
350 ioctl (fd, TCGETA, &sg);
351 #endif
352 emacs_ospeed = sg.c_cflag & CBAUD;
353 #else /* neither TERMIOS nor TERMIO */
354 struct sgttyb sg;
355
356 sg.sg_ospeed = B9600;
357 if (ioctl (fd, TIOCGETP, &sg) < 0)
358 abort ();
359 emacs_ospeed = sg.sg_ospeed;
360 #endif /* not HAVE_TERMIO */
361 #endif /* not HAVE_TERMIOS */
362 #endif /* not DOS_NT */
363 }
364
365 baud_rate = (emacs_ospeed < sizeof baud_convert / sizeof baud_convert[0]
366 ? baud_convert[emacs_ospeed] : 9600);
367 if (baud_rate == 0)
368 baud_rate = 1200;
369 }
370
371 \f
372 /*ARGSUSED*/
373 void
374 set_exclusive_use (fd)
375 int fd;
376 {
377 #ifdef FIOCLEX
378 ioctl (fd, FIOCLEX, 0);
379 #endif
380 /* Ok to do nothing if this feature does not exist */
381 }
382 \f
383 #ifndef subprocesses
384
385 wait_without_blocking ()
386 {
387 #ifdef BSD_SYSTEM
388 wait3 (0, WNOHANG | WUNTRACED, 0);
389 #else
390 croak ("wait_without_blocking");
391 #endif
392 synch_process_alive = 0;
393 }
394
395 #endif /* not subprocesses */
396
397 int wait_debugging; /* Set nonzero to make following function work under dbx
398 (at least for bsd). */
399
400 SIGTYPE
401 wait_for_termination_signal ()
402 {}
403
404 /* Wait for subprocess with process id `pid' to terminate and
405 make sure it will get eliminated (not remain forever as a zombie) */
406
407 void
408 wait_for_termination (pid)
409 int pid;
410 {
411 while (1)
412 {
413 #ifdef subprocesses
414 #if defined (BSD_SYSTEM) || defined (HPUX)
415 /* Note that kill returns -1 even if the process is just a zombie now.
416 But inevitably a SIGCHLD interrupt should be generated
417 and child_sig will do wait3 and make the process go away. */
418 /* There is some indication that there is a bug involved with
419 termination of subprocesses, perhaps involving a kernel bug too,
420 but no idea what it is. Just as a hunch we signal SIGCHLD to see
421 if that causes the problem to go away or get worse. */
422 sigsetmask (sigmask (SIGCHLD));
423 if (0 > kill (pid, 0))
424 {
425 sigsetmask (SIGEMPTYMASK);
426 kill (getpid (), SIGCHLD);
427 break;
428 }
429 if (wait_debugging)
430 sleep (1);
431 else
432 sigpause (SIGEMPTYMASK);
433 #else /* not BSD_SYSTEM, and not HPUX version >= 6 */
434 #ifdef POSIX_SIGNALS /* would this work for GNU/Linux as well? */
435 sigblock (sigmask (SIGCHLD));
436 errno = 0;
437 if (kill (pid, 0) == -1 && errno == ESRCH)
438 {
439 sigunblock (sigmask (SIGCHLD));
440 break;
441 }
442
443 sigsuspend (&empty_mask);
444 #else /* not POSIX_SIGNALS */
445 #ifdef HAVE_SYSV_SIGPAUSE
446 sighold (SIGCHLD);
447 if (0 > kill (pid, 0))
448 {
449 sigrelse (SIGCHLD);
450 break;
451 }
452 sigpause (SIGCHLD);
453 #else /* not HAVE_SYSV_SIGPAUSE */
454 #ifdef WINDOWSNT
455 wait (0);
456 break;
457 #else /* not WINDOWSNT */
458 if (0 > kill (pid, 0))
459 break;
460 /* Using sleep instead of pause avoids timing error.
461 If the inferior dies just before the sleep,
462 we lose just one second. */
463 sleep (1);
464 #endif /* not WINDOWSNT */
465 #endif /* not HAVE_SYSV_SIGPAUSE */
466 #endif /* not POSIX_SIGNALS */
467 #endif /* not BSD_SYSTEM, and not HPUX version >= 6 */
468 #else /* not subprocesses */
469 #if __DJGPP__ > 1
470 break;
471 #else /* not __DJGPP__ > 1 */
472 if (kill (pid, 0) < 0)
473 break;
474 wait (0);
475 #endif /* not __DJGPP__ > 1*/
476 #endif /* not subprocesses */
477 }
478 }
479
480 #ifdef subprocesses
481
482 /*
483 * flush any pending output
484 * (may flush input as well; it does not matter the way we use it)
485 */
486
487 void
488 flush_pending_output (channel)
489 int channel;
490 {
491 #ifdef HAVE_TERMIOS
492 /* If we try this, we get hit with SIGTTIN, because
493 the child's tty belongs to the child's pgrp. */
494 #else
495 #ifdef TCFLSH
496 ioctl (channel, TCFLSH, 1);
497 #else
498 #ifdef TIOCFLUSH
499 int zero = 0;
500 /* 3rd arg should be ignored
501 but some 4.2 kernels actually want the address of an int
502 and nonzero means something different. */
503 ioctl (channel, TIOCFLUSH, &zero);
504 #endif
505 #endif
506 #endif
507 }
508 \f
509 /* Set up the terminal at the other end of a pseudo-terminal that
510 we will be controlling an inferior through.
511 It should not echo or do line-editing, since that is done
512 in Emacs. No padding needed for insertion into an Emacs buffer. */
513
514 void
515 child_setup_tty (out)
516 int out;
517 {
518 #ifndef DOS_NT
519 struct emacs_tty s;
520
521 EMACS_GET_TTY (out, &s);
522
523 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
524 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
525 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
526 #ifdef NLDLY
527 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
528 Some versions of GNU Hurd do not have FFDLY? */
529 #ifdef FFDLY
530 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
531 /* No output delays */
532 #else
533 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
534 /* No output delays */
535 #endif
536 #endif
537 s.main.c_lflag &= ~ECHO; /* Disable echo */
538 s.main.c_lflag |= ISIG; /* Enable signals */
539 #ifdef IUCLC
540 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
541 #endif
542 #ifdef ISTRIP
543 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
544 #endif
545 #ifdef OLCUC
546 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
547 #endif
548 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
549 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
550 s.main.c_lflag |= ICANON; /* Enable erase/kill and eof processing */
551 s.main.c_cc[VEOF] = 04; /* insure that EOF is Control-D */
552 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
553 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
554
555 #ifdef HPUX
556 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
557 #endif /* HPUX */
558
559 #ifdef SIGNALS_VIA_CHARACTERS
560 /* the QUIT and INTR character are used in process_send_signal
561 so set them here to something useful. */
562 if (s.main.c_cc[VQUIT] == CDISABLE)
563 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
564 if (s.main.c_cc[VINTR] == CDISABLE)
565 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
566 #endif /* not SIGNALS_VIA_CHARACTERS */
567
568 #ifdef AIX
569 /* AIX enhanced edit loses NULs, so disable it */
570 #ifndef IBMR2AIX
571 s.main.c_line = 0;
572 s.main.c_iflag &= ~ASCEDIT;
573 #endif
574 /* Also, PTY overloads NUL and BREAK.
575 don't ignore break, but don't signal either, so it looks like NUL. */
576 s.main.c_iflag &= ~IGNBRK;
577 s.main.c_iflag &= ~BRKINT;
578 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
579 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
580 would force it to 0377. That looks like duplicated code. */
581 s.main.c_cc[VEOL] = CDISABLE;
582 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
583 #endif /* AIX */
584
585 #else /* not HAVE_TERMIO */
586
587 s.main.sg_flags &= ~(ECHO | CRMOD | ANYP | ALLDELAY | RAW | LCASE
588 | CBREAK | TANDEM);
589 s.main.sg_flags |= LPASS8;
590 s.main.sg_erase = 0377;
591 s.main.sg_kill = 0377;
592 s.lmode = LLITOUT | s.lmode; /* Don't strip 8th bit */
593
594 #endif /* not HAVE_TERMIO */
595
596 EMACS_SET_TTY (out, &s, 0);
597
598 #endif /* not DOS_NT */
599 }
600
601 #endif /* subprocesses */
602 \f
603 /* Record a signal code and the handler for it. */
604 struct save_signal
605 {
606 int code;
607 SIGTYPE (*handler) P_ ((int));
608 };
609
610 static void save_signal_handlers P_ ((struct save_signal *));
611 static void restore_signal_handlers P_ ((struct save_signal *));
612
613 /* Suspend the Emacs process; give terminal to its superior. */
614
615 void
616 sys_suspend ()
617 {
618 #if defined (SIGTSTP) && !defined (MSDOS)
619
620 {
621 int pgrp = EMACS_GETPGRP (0);
622 EMACS_KILLPG (pgrp, SIGTSTP);
623 }
624
625 #else /* No SIGTSTP */
626 #ifdef USG_JOBCTRL /* If you don't know what this is don't mess with it */
627 ptrace (0, 0, 0, 0); /* set for ptrace - caught by csh */
628 kill (getpid (), SIGQUIT);
629
630 #else /* No SIGTSTP or USG_JOBCTRL */
631
632 /* On a system where suspending is not implemented,
633 instead fork a subshell and let it talk directly to the terminal
634 while we wait. */
635 sys_subshell ();
636
637 #endif /* no USG_JOBCTRL */
638 #endif /* no SIGTSTP */
639 }
640
641 /* Fork a subshell. */
642
643 void
644 sys_subshell ()
645 {
646 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
647 int st;
648 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
649 #endif
650 int pid;
651 struct save_signal saved_handlers[5];
652 Lisp_Object dir;
653 unsigned char *str = 0;
654 int len;
655
656 saved_handlers[0].code = SIGINT;
657 saved_handlers[1].code = SIGQUIT;
658 saved_handlers[2].code = SIGTERM;
659 #ifdef SIGIO
660 saved_handlers[3].code = SIGIO;
661 saved_handlers[4].code = 0;
662 #else
663 saved_handlers[3].code = 0;
664 #endif
665
666 /* Mentioning current_buffer->buffer would mean including buffer.h,
667 which somehow wedges the hp compiler. So instead... */
668
669 dir = intern ("default-directory");
670 if (NILP (Fboundp (dir)))
671 goto xyzzy;
672 dir = Fsymbol_value (dir);
673 if (!STRINGP (dir))
674 goto xyzzy;
675
676 dir = expand_and_dir_to_file (Funhandled_file_name_directory (dir), Qnil);
677 str = (unsigned char *) alloca (SCHARS (dir) + 2);
678 len = SCHARS (dir);
679 bcopy (SDATA (dir), str, len);
680 if (str[len - 1] != '/') str[len++] = '/';
681 str[len] = 0;
682 xyzzy:
683
684 #ifdef DOS_NT
685 pid = 0;
686 #if __DJGPP__ > 1
687 save_signal_handlers (saved_handlers);
688 synch_process_alive = 1;
689 #endif /* __DJGPP__ > 1 */
690 #else
691 pid = vfork ();
692 if (pid == -1)
693 error ("Can't spawn subshell");
694 #endif
695
696 if (pid == 0)
697 {
698 char *sh = 0;
699
700 #ifdef DOS_NT /* MW, Aug 1993 */
701 getwd (oldwd);
702 if (sh == 0)
703 sh = (char *) egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
704 #endif
705 if (sh == 0)
706 sh = (char *) egetenv ("SHELL");
707 if (sh == 0)
708 sh = "sh";
709
710 /* Use our buffer's default directory for the subshell. */
711 if (str)
712 chdir ((char *) str);
713
714 #ifdef subprocesses
715 close_process_descs (); /* Close Emacs's pipes/ptys */
716 #endif
717
718 #ifdef SET_EMACS_PRIORITY
719 {
720 extern EMACS_INT emacs_priority;
721
722 if (emacs_priority < 0)
723 nice (-emacs_priority);
724 }
725 #endif
726
727 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
728 {
729 char *epwd = getenv ("PWD");
730 char old_pwd[MAXPATHLEN+1+4];
731
732 /* If PWD is set, pass it with corrected value. */
733 if (epwd)
734 {
735 strcpy (old_pwd, epwd);
736 if (str[len - 1] == '/')
737 str[len - 1] = '\0';
738 setenv ("PWD", str, 1);
739 }
740 st = system (sh);
741 chdir (oldwd);
742 if (epwd)
743 putenv (old_pwd); /* restore previous value */
744 }
745 #else /* not MSDOS */
746 #ifdef WINDOWSNT
747 /* Waits for process completion */
748 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
749 chdir (oldwd);
750 if (pid == -1)
751 write (1, "Can't execute subshell", 22);
752 #else /* not WINDOWSNT */
753 execlp (sh, sh, (char *) 0);
754 write (1, "Can't execute subshell", 22);
755 _exit (1);
756 #endif /* not WINDOWSNT */
757 #endif /* not MSDOS */
758 }
759
760 /* Do this now if we did not do it before. */
761 #if !defined (MSDOS) || __DJGPP__ == 1
762 save_signal_handlers (saved_handlers);
763 synch_process_alive = 1;
764 #endif
765
766 #ifndef DOS_NT
767 wait_for_termination (pid);
768 #endif
769 restore_signal_handlers (saved_handlers);
770 synch_process_alive = 0;
771 }
772
773 static void
774 save_signal_handlers (saved_handlers)
775 struct save_signal *saved_handlers;
776 {
777 while (saved_handlers->code)
778 {
779 saved_handlers->handler
780 = (SIGTYPE (*) P_ ((int))) signal (saved_handlers->code, SIG_IGN);
781 saved_handlers++;
782 }
783 }
784
785 static void
786 restore_signal_handlers (saved_handlers)
787 struct save_signal *saved_handlers;
788 {
789 while (saved_handlers->code)
790 {
791 signal (saved_handlers->code, saved_handlers->handler);
792 saved_handlers++;
793 }
794 }
795 \f
796 #ifndef SIGIO
797 /* If SIGIO is broken, don't do anything. */
798 void
799 init_sigio (int fd)
800 {
801 }
802
803 void
804 reset_sigio (int fd)
805 {
806 }
807
808 void
809 request_sigio (void)
810 {
811 }
812
813 void
814 unrequest_sigio (void)
815 {
816 }
817
818 #else
819 #ifdef F_SETFL
820
821 int old_fcntl_flags[MAXDESC];
822
823 void
824 init_sigio (fd)
825 int fd;
826 {
827 #ifdef FASYNC
828 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
829 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
830 #endif
831 interrupts_deferred = 0;
832 }
833
834 void
835 reset_sigio (fd)
836 int fd;
837 {
838 #ifdef FASYNC
839 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
840 #endif
841 }
842
843 #ifdef FASYNC /* F_SETFL does not imply existence of FASYNC */
844 /* XXX Uhm, FASYNC is not used anymore here. */
845 /* XXX Yeah, but you need it for SIGIO, don't you? */
846
847 void
848 request_sigio ()
849 {
850 if (noninteractive)
851 return;
852
853 #ifdef SIGWINCH
854 sigunblock (sigmask (SIGWINCH));
855 #endif
856 sigunblock (sigmask (SIGIO));
857
858 interrupts_deferred = 0;
859 }
860
861 void
862 unrequest_sigio (void)
863 {
864 if (noninteractive)
865 return;
866
867 #if 0 /* XXX What's wrong with blocking SIGIO under X? */
868 if (x_display_list)
869 return;
870 #endif
871
872 #ifdef SIGWINCH
873 sigblock (sigmask (SIGWINCH));
874 #endif
875 sigblock (sigmask (SIGIO));
876 interrupts_deferred = 1;
877 }
878
879 #else /* no FASYNC */
880 #ifndef MSDOS
881
882 void
883 request_sigio ()
884 {
885 if (noninteractive || read_socket_hook)
886 return;
887
888 croak ("request_sigio");
889 }
890
891 void
892 unrequest_sigio ()
893 {
894 if (noninteractive || read_socket_hook)
895 return;
896
897 croak ("unrequest_sigio");
898 }
899
900 #endif /* MSDOS */
901 #endif /* FASYNC */
902 #endif /* F_SETFL */
903 #endif /* SIGIO */
904 \f
905 /* Saving and restoring the process group of Emacs's terminal. */
906
907 #ifdef BSD_PGRPS
908
909 /* The process group of which Emacs was a member when it initially
910 started.
911
912 If Emacs was in its own process group (i.e. inherited_pgroup ==
913 getpid ()), then we know we're running under a shell with job
914 control (Emacs would never be run as part of a pipeline).
915 Everything is fine.
916
917 If Emacs was not in its own process group, then we know we're
918 running under a shell (or a caller) that doesn't know how to
919 separate itself from Emacs (like sh). Emacs must be in its own
920 process group in order to receive SIGIO correctly. In this
921 situation, we put ourselves in our own pgroup, forcibly set the
922 tty's pgroup to our pgroup, and make sure to restore and reinstate
923 the tty's pgroup just like any other terminal setting. If
924 inherited_group was not the tty's pgroup, then we'll get a
925 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
926 it goes foreground in the future, which is what should happen.
927
928 This variable is initialized in emacs.c. */
929 int inherited_pgroup;
930
931 /* Split off the foreground process group to Emacs alone. When we are
932 in the foreground, but not started in our own process group,
933 redirect the tty device handle FD to point to our own process
934 group. We need to be in our own process group to receive SIGIO
935 properly. */
936 static void
937 narrow_foreground_group (int fd)
938 {
939 int me = getpid ();
940
941 setpgrp (0, inherited_pgroup);
942 #if 0
943 /* XXX inherited_pgroup should not be zero here, but GTK seems to
944 mess this up. */
945 if (! inherited_pgroup)
946 abort (); /* Should not happen. */
947 #endif
948 if (inherited_pgroup != me)
949 EMACS_SET_TTY_PGRP (fd, &me); /* XXX This only works on the controlling tty. */
950 setpgrp (0, me);
951 }
952
953 /* Set the tty to our original foreground group. */
954 static void
955 widen_foreground_group (int fd)
956 {
957 if (inherited_pgroup != getpid ())
958 EMACS_SET_TTY_PGRP (fd, &inherited_pgroup);
959 setpgrp (0, inherited_pgroup);
960 }
961
962 #endif /* BSD_PGRPS */
963 \f
964 /* Getting and setting emacs_tty structures. */
965
966 /* Set *TC to the parameters associated with the terminal FD.
967 Return zero if all's well, or -1 if we ran into an error we
968 couldn't deal with. */
969 int
970 emacs_get_tty (fd, settings)
971 int fd;
972 struct emacs_tty *settings;
973 {
974 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
975 #ifdef HAVE_TCATTR
976 /* We have those nifty POSIX tcmumbleattr functions. */
977 bzero (&settings->main, sizeof (settings->main));
978 if (tcgetattr (fd, &settings->main) < 0)
979 return -1;
980
981 #else
982 #ifdef HAVE_TERMIO
983 /* The SYSV-style interface? */
984 if (ioctl (fd, TCGETA, &settings->main) < 0)
985 return -1;
986
987 #else
988 #ifndef DOS_NT
989 /* I give up - I hope you have the BSD ioctls. */
990 if (ioctl (fd, TIOCGETP, &settings->main) < 0)
991 return -1;
992 #endif /* not DOS_NT */
993 #endif
994 #endif
995
996 /* Suivant - Do we have to get struct ltchars data? */
997 #ifdef HAVE_LTCHARS
998 if (ioctl (fd, TIOCGLTC, &settings->ltchars) < 0)
999 return -1;
1000 #endif
1001
1002 /* How about a struct tchars and a wordful of lmode bits? */
1003 #ifdef HAVE_TCHARS
1004 if (ioctl (fd, TIOCGETC, &settings->tchars) < 0
1005 || ioctl (fd, TIOCLGET, &settings->lmode) < 0)
1006 return -1;
1007 #endif
1008
1009 /* We have survived the tempest. */
1010 return 0;
1011 }
1012
1013
1014 /* Set the parameters of the tty on FD according to the contents of
1015 *SETTINGS. If FLUSHP is non-zero, we discard input.
1016 Return 0 if all went well, and -1 if anything failed. */
1017
1018 int
1019 emacs_set_tty (fd, settings, flushp)
1020 int fd;
1021 struct emacs_tty *settings;
1022 int flushp;
1023 {
1024 /* Set the primary parameters - baud rate, character size, etcetera. */
1025 #ifdef HAVE_TCATTR
1026 int i;
1027 /* We have those nifty POSIX tcmumbleattr functions.
1028 William J. Smith <wjs@wiis.wang.com> writes:
1029 "POSIX 1003.1 defines tcsetattr to return success if it was
1030 able to perform any of the requested actions, even if some
1031 of the requested actions could not be performed.
1032 We must read settings back to ensure tty setup properly.
1033 AIX requires this to keep tty from hanging occasionally." */
1034 /* This make sure that we don't loop indefinitely in here. */
1035 for (i = 0 ; i < 10 ; i++)
1036 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
1037 {
1038 if (errno == EINTR)
1039 continue;
1040 else
1041 return -1;
1042 }
1043 else
1044 {
1045 struct termios new;
1046
1047 bzero (&new, sizeof (new));
1048 /* Get the current settings, and see if they're what we asked for. */
1049 tcgetattr (fd, &new);
1050 /* We cannot use memcmp on the whole structure here because under
1051 * aix386 the termios structure has some reserved field that may
1052 * not be filled in.
1053 */
1054 if ( new.c_iflag == settings->main.c_iflag
1055 && new.c_oflag == settings->main.c_oflag
1056 && new.c_cflag == settings->main.c_cflag
1057 && new.c_lflag == settings->main.c_lflag
1058 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
1059 break;
1060 else
1061 continue;
1062 }
1063
1064 #else
1065 #ifdef HAVE_TERMIO
1066 /* The SYSV-style interface? */
1067 if (ioctl (fd, flushp ? TCSETAF : TCSETAW, &settings->main) < 0)
1068 return -1;
1069
1070 #else
1071 #ifndef DOS_NT
1072 /* I give up - I hope you have the BSD ioctls. */
1073 if (ioctl (fd, (flushp) ? TIOCSETP : TIOCSETN, &settings->main) < 0)
1074 return -1;
1075 #endif /* not DOS_NT */
1076
1077 #endif
1078 #endif
1079
1080 /* Suivant - Do we have to get struct ltchars data? */
1081 #ifdef HAVE_LTCHARS
1082 if (ioctl (fd, TIOCSLTC, &settings->ltchars) < 0)
1083 return -1;
1084 #endif
1085
1086 /* How about a struct tchars and a wordful of lmode bits? */
1087 #ifdef HAVE_TCHARS
1088 if (ioctl (fd, TIOCSETC, &settings->tchars) < 0
1089 || ioctl (fd, TIOCLSET, &settings->lmode) < 0)
1090 return -1;
1091 #endif
1092
1093 /* We have survived the tempest. */
1094 return 0;
1095 }
1096
1097 \f
1098
1099 #ifdef F_SETOWN
1100 int old_fcntl_owner[MAXDESC];
1101 #endif /* F_SETOWN */
1102
1103 /* This may also be defined in stdio,
1104 but if so, this does no harm,
1105 and using the same name avoids wasting the other one's space. */
1106
1107 #if defined (USG)
1108 unsigned char _sobuf[BUFSIZ+8];
1109 #else
1110 char _sobuf[BUFSIZ];
1111 #endif
1112
1113 #ifdef HAVE_LTCHARS
1114 static struct ltchars new_ltchars = {-1,-1,-1,-1,-1,-1};
1115 #endif
1116 #ifdef HAVE_TCHARS
1117 static struct tchars new_tchars = {-1,-1,-1,-1,-1,-1};
1118 #endif
1119
1120 /* Initialize the terminal mode on all tty devices that are currently
1121 open. */
1122
1123 void
1124 init_all_sys_modes (void)
1125 {
1126 struct tty_display_info *tty;
1127 for (tty = tty_list; tty; tty = tty->next)
1128 init_sys_modes (tty);
1129 }
1130
1131 /* Initialize the terminal mode on the given tty device. */
1132
1133 void
1134 init_sys_modes (tty_out)
1135 struct tty_display_info *tty_out;
1136 {
1137 struct emacs_tty tty;
1138
1139 Vtty_erase_char = Qnil;
1140
1141 if (noninteractive)
1142 return;
1143
1144 if (!tty_out->output)
1145 return; /* The tty is suspended. */
1146
1147 #ifdef BSD_PGRPS
1148 #if 0
1149 /* read_socket_hook is not global anymore. I think doing this
1150 unconditionally will not cause any problems. */
1151 if (! read_socket_hook && EQ (Vinitial_window_system, Qnil))
1152 #endif
1153 narrow_foreground_group (fileno (tty_out->input));
1154 #endif
1155
1156 if (! tty_out->old_tty)
1157 tty_out->old_tty = (struct emacs_tty *) xmalloc (sizeof (struct emacs_tty));
1158
1159 EMACS_GET_TTY (fileno (tty_out->input), tty_out->old_tty);
1160
1161 tty = *tty_out->old_tty;
1162
1163 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
1164 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
1165
1166 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1167 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1168 #ifdef INLCR /* I'm just being cautious,
1169 since I can't check how widespread INLCR is--rms. */
1170 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1171 #endif
1172 #ifdef ISTRIP
1173 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1174 #endif
1175 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1176 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1177 #ifdef IEXTEN
1178 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1179 #endif
1180 tty.main.c_lflag |= ISIG; /* Enable signals */
1181 if (tty_out->flow_control)
1182 {
1183 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1184 #ifdef IXANY
1185 tty.main.c_iflag &= ~IXANY;
1186 #endif /* IXANY */
1187 }
1188 else
1189 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1190 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1191 on output */
1192 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1193 #ifdef CS8
1194 if (tty_out->meta_key)
1195 {
1196 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1197 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1198 }
1199 #endif
1200 if (tty_out->input == stdin)
1201 {
1202 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1203 /* Set up C-g for both SIGQUIT and SIGINT.
1204 We don't know which we will get, but we handle both alike
1205 so which one it really gives us does not matter. */
1206 tty.main.c_cc[VQUIT] = quit_char;
1207 }
1208 else
1209 {
1210 /* We normally don't get interrupt or quit signals from tty
1211 devices other than our controlling terminal; therefore,
1212 we must handle C-g as normal input. Unfortunately, this
1213 means that the interrupt and quit feature must be
1214 disabled on secondary ttys, or we would not even see the
1215 keypress.
1216
1217 Note that even though emacsclient could have special code
1218 to pass SIGINT to Emacs, we should _not_ enable
1219 interrupt/quit keys for emacsclient frames. This means
1220 that we can't break out of loops in C code from a
1221 secondary tty frame, but we can always decide what
1222 display the C-g came from, which is more important from a
1223 usability point of view. (Consider the case when two
1224 people work together using the same Emacs instance.) */
1225 tty.main.c_cc[VINTR] = CDISABLE;
1226 tty.main.c_cc[VQUIT] = CDISABLE;
1227 }
1228 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1229 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1230 #ifdef VSWTCH
1231 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1232 of C-z */
1233 #endif /* VSWTCH */
1234
1235 #if defined (__mips__) || defined (HAVE_TCATTR)
1236 #ifdef VSUSP
1237 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off mips handling of C-z. */
1238 #endif /* VSUSP */
1239 #ifdef V_DSUSP
1240 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off mips handling of C-y. */
1241 #endif /* V_DSUSP */
1242 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1243 tty.main.c_cc[VDSUSP] = CDISABLE;
1244 #endif /* VDSUSP */
1245 #ifdef VLNEXT
1246 tty.main.c_cc[VLNEXT] = CDISABLE;
1247 #endif /* VLNEXT */
1248 #ifdef VREPRINT
1249 tty.main.c_cc[VREPRINT] = CDISABLE;
1250 #endif /* VREPRINT */
1251 #ifdef VWERASE
1252 tty.main.c_cc[VWERASE] = CDISABLE;
1253 #endif /* VWERASE */
1254 #ifdef VDISCARD
1255 tty.main.c_cc[VDISCARD] = CDISABLE;
1256 #endif /* VDISCARD */
1257
1258 if (tty_out->flow_control)
1259 {
1260 #ifdef VSTART
1261 tty.main.c_cc[VSTART] = '\021';
1262 #endif /* VSTART */
1263 #ifdef VSTOP
1264 tty.main.c_cc[VSTOP] = '\023';
1265 #endif /* VSTOP */
1266 }
1267 else
1268 {
1269 #ifdef VSTART
1270 tty.main.c_cc[VSTART] = CDISABLE;
1271 #endif /* VSTART */
1272 #ifdef VSTOP
1273 tty.main.c_cc[VSTOP] = CDISABLE;
1274 #endif /* VSTOP */
1275 }
1276 #endif /* mips or HAVE_TCATTR */
1277
1278 #ifdef AIX
1279 #ifndef IBMR2AIX
1280 /* AIX enhanced edit loses NULs, so disable it. */
1281 tty.main.c_line = 0;
1282 tty.main.c_iflag &= ~ASCEDIT;
1283 #else
1284 tty.main.c_cc[VSTRT] = CDISABLE;
1285 tty.main.c_cc[VSTOP] = CDISABLE;
1286 tty.main.c_cc[VSUSP] = CDISABLE;
1287 tty.main.c_cc[VDSUSP] = CDISABLE;
1288 #endif /* IBMR2AIX */
1289 if (tty_out->flow_control)
1290 {
1291 #ifdef VSTART
1292 tty.main.c_cc[VSTART] = '\021';
1293 #endif /* VSTART */
1294 #ifdef VSTOP
1295 tty.main.c_cc[VSTOP] = '\023';
1296 #endif /* VSTOP */
1297 }
1298 /* Also, PTY overloads NUL and BREAK.
1299 don't ignore break, but don't signal either, so it looks like NUL.
1300 This really serves a purpose only if running in an XTERM window
1301 or via TELNET or the like, but does no harm elsewhere. */
1302 tty.main.c_iflag &= ~IGNBRK;
1303 tty.main.c_iflag &= ~BRKINT;
1304 #endif
1305 #else /* if not HAVE_TERMIO */
1306 #ifndef DOS_NT
1307 XSETINT (Vtty_erase_char, tty.main.sg_erase);
1308 tty.main.sg_flags &= ~(ECHO | CRMOD | XTABS);
1309 if (meta_key)
1310 tty.main.sg_flags |= ANYP;
1311 tty.main.sg_flags |= interrupt_input ? RAW : CBREAK;
1312 #endif /* not DOS_NT */
1313 #endif /* not HAVE_TERMIO */
1314
1315 /* If going to use CBREAK mode, we must request C-g to interrupt
1316 and turn off start and stop chars, etc. If not going to use
1317 CBREAK mode, do this anyway so as to turn off local flow
1318 control for user coming over network on 4.2; in this case,
1319 only t_stopc and t_startc really matter. */
1320 #ifndef HAVE_TERMIO
1321 #ifdef HAVE_TCHARS
1322 /* Note: if not using CBREAK mode, it makes no difference how we
1323 set this */
1324 tty.tchars = new_tchars;
1325 tty.tchars.t_intrc = quit_char;
1326 if (tty_out->flow_control)
1327 {
1328 tty.tchars.t_startc = '\021';
1329 tty.tchars.t_stopc = '\023';
1330 }
1331
1332 tty.lmode = LDECCTQ | LLITOUT | LPASS8 | LNOFLSH | tty_out->old_tty.lmode;
1333
1334 #endif /* HAVE_TCHARS */
1335 #endif /* not HAVE_TERMIO */
1336
1337 #ifdef HAVE_LTCHARS
1338 tty.ltchars = new_ltchars;
1339 #endif /* HAVE_LTCHARS */
1340 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1341 if (!tty_out->term_initted)
1342 internal_terminal_init ();
1343 dos_ttraw (tty_out);
1344 #endif
1345
1346 EMACS_SET_TTY (fileno (tty_out->input), &tty, 0);
1347
1348 /* This code added to insure that, if flow-control is not to be used,
1349 we have an unlocked terminal at the start. */
1350
1351 #ifdef TCXONC
1352 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1353 #endif
1354 #ifdef TIOCSTART
1355 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1356 #endif
1357
1358 #if defined (HAVE_TERMIOS) || defined (HPUX)
1359 #ifdef TCOON
1360 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1361 #endif
1362 #endif
1363
1364 #ifdef F_SETFL
1365 #ifdef F_GETOWN /* F_SETFL does not imply existence of F_GETOWN */
1366 if (interrupt_input)
1367 {
1368 old_fcntl_owner[fileno (tty_out->input)] =
1369 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1370 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1371 init_sigio (fileno (tty_out->input));
1372 #ifdef HAVE_GPM
1373 if (gpm_tty == tty_out)
1374 {
1375 /* Arrange for mouse events to give us SIGIO signals. */
1376 fcntl (gpm_fd, F_SETOWN, getpid ());
1377 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1378 init_sigio (gpm_fd);
1379 }
1380 #endif /* HAVE_GPM */
1381 }
1382 #endif /* F_GETOWN */
1383 #endif /* F_SETFL */
1384
1385 #ifdef _IOFBF
1386 /* This symbol is defined on recent USG systems.
1387 Someone says without this call USG won't really buffer the file
1388 even with a call to setbuf. */
1389 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1390 #else
1391 setbuf (tty_out->output, (char *) _sobuf);
1392 #endif
1393
1394 if (tty_out->terminal->set_terminal_modes_hook)
1395 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1396
1397 if (!tty_out->term_initted)
1398 {
1399 Lisp_Object tail, frame;
1400 FOR_EACH_FRAME (tail, frame)
1401 {
1402 /* XXX This needs to be revised. */
1403 if (FRAME_TERMCAP_P (XFRAME (frame))
1404 && FRAME_TTY (XFRAME (frame)) == tty_out)
1405 init_frame_faces (XFRAME (frame));
1406 }
1407 }
1408
1409 if (tty_out->term_initted && no_redraw_on_reenter)
1410 {
1411 /* XXX This seems wrong on multi-tty. */
1412 if (display_completed)
1413 direct_output_forward_char (0);
1414 }
1415 else
1416 {
1417 Lisp_Object tail, frame;
1418 frame_garbaged = 1;
1419 FOR_EACH_FRAME (tail, frame)
1420 {
1421 if ((FRAME_TERMCAP_P (XFRAME (frame))
1422 || FRAME_MSDOS_P (XFRAME (frame)))
1423 && FRAME_TTY (XFRAME (frame)) == tty_out)
1424 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1425 }
1426 }
1427
1428 tty_out->term_initted = 1;
1429 }
1430
1431 /* Return nonzero if safe to use tabs in output.
1432 At the time this is called, init_sys_modes has not been done yet. */
1433
1434 int
1435 tabs_safe_p (int fd)
1436 {
1437 struct emacs_tty etty;
1438
1439 EMACS_GET_TTY (fd, &etty);
1440 return EMACS_TTY_TABS_OK (&etty);
1441 }
1442 \f
1443 /* Get terminal size from system.
1444 Store number of lines into *HEIGHTP and width into *WIDTHP.
1445 We store 0 if there's no valid information. */
1446
1447 void
1448 get_tty_size (int fd, int *widthp, int *heightp)
1449 {
1450
1451 #ifdef TIOCGWINSZ
1452
1453 /* BSD-style. */
1454 struct winsize size;
1455
1456 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1457 *widthp = *heightp = 0;
1458 else
1459 {
1460 *widthp = size.ws_col;
1461 *heightp = size.ws_row;
1462 }
1463
1464 #else
1465 #ifdef TIOCGSIZE
1466
1467 /* SunOS - style. */
1468 struct ttysize size;
1469
1470 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1471 *widthp = *heightp = 0;
1472 else
1473 {
1474 *widthp = size.ts_cols;
1475 *heightp = size.ts_lines;
1476 }
1477
1478 #else
1479 #ifdef MSDOS
1480 *widthp = ScreenCols ();
1481 *heightp = ScreenRows ();
1482 #else /* system doesn't know size */
1483 *widthp = 0;
1484 *heightp = 0;
1485 #endif
1486 #endif /* not SunOS-style */
1487 #endif /* not BSD-style */
1488 }
1489
1490 /* Set the logical window size associated with descriptor FD
1491 to HEIGHT and WIDTH. This is used mainly with ptys. */
1492
1493 int
1494 set_window_size (fd, height, width)
1495 int fd, height, width;
1496 {
1497 #ifdef TIOCSWINSZ
1498
1499 /* BSD-style. */
1500 struct winsize size;
1501 size.ws_row = height;
1502 size.ws_col = width;
1503
1504 if (ioctl (fd, TIOCSWINSZ, &size) == -1)
1505 return 0; /* error */
1506 else
1507 return 1;
1508
1509 #else
1510 #ifdef TIOCSSIZE
1511
1512 /* SunOS - style. */
1513 struct ttysize size;
1514 size.ts_lines = height;
1515 size.ts_cols = width;
1516
1517 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1518 return 0;
1519 else
1520 return 1;
1521 #else
1522 return -1;
1523 #endif /* not SunOS-style */
1524 #endif /* not BSD-style */
1525 }
1526
1527 \f
1528
1529 /* Prepare all terminal devices for exiting Emacs. */
1530
1531 void
1532 reset_all_sys_modes (void)
1533 {
1534 struct tty_display_info *tty;
1535 for (tty = tty_list; tty; tty = tty->next)
1536 reset_sys_modes (tty);
1537 }
1538
1539 /* Prepare the terminal for closing it; move the cursor to the
1540 bottom of the frame, turn off interrupt-driven I/O, etc. */
1541
1542 void
1543 reset_sys_modes (tty_out)
1544 struct tty_display_info *tty_out;
1545 {
1546 if (noninteractive)
1547 {
1548 fflush (stdout);
1549 return;
1550 }
1551 if (!tty_out->term_initted)
1552 return;
1553
1554 if (!tty_out->output)
1555 return; /* The tty is suspended. */
1556
1557 /* Go to and clear the last line of the terminal. */
1558
1559 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1560
1561 /* Code adapted from tty_clear_end_of_line. */
1562 if (tty_out->TS_clr_line)
1563 {
1564 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1565 }
1566 else
1567 { /* have to do it the hard way */
1568 int i;
1569 tty_turn_off_insert (tty_out);
1570
1571 for (i = curX (tty_out); i < FrameCols (tty_out) - 1; i++)
1572 {
1573 fputc (' ', tty_out->output);
1574 }
1575 }
1576
1577 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1578 fflush (tty_out->output);
1579
1580 if (tty_out->terminal->reset_terminal_modes_hook)
1581 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1582
1583 #ifdef BSD_SYSTEM
1584 /* Avoid possible loss of output when changing terminal modes. */
1585 fsync (fileno (tty_out->output));
1586 #endif
1587
1588 #ifdef F_SETFL
1589 #ifdef F_SETOWN /* F_SETFL does not imply existence of F_SETOWN */
1590 if (interrupt_input)
1591 {
1592 reset_sigio (fileno (tty_out->input));
1593 fcntl (fileno (tty_out->input), F_SETOWN,
1594 old_fcntl_owner[fileno (tty_out->input)]);
1595 }
1596 #endif /* F_SETOWN */
1597 #ifdef O_NDELAY
1598 fcntl (fileno (tty_out->input), F_SETFL,
1599 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NDELAY);
1600 #endif
1601 #endif /* F_SETFL */
1602
1603 if (tty_out->old_tty)
1604 while (EMACS_SET_TTY (fileno (tty_out->input),
1605 tty_out->old_tty, 0) < 0 && errno == EINTR)
1606 ;
1607
1608 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1609 dos_ttcooked ();
1610 #endif
1611
1612 #ifdef BSD_PGRPS
1613 widen_foreground_group (fileno (tty_out->input));
1614 #endif
1615 }
1616 \f
1617 #ifdef HAVE_PTYS
1618
1619 /* Set up the proper status flags for use of a pty. */
1620
1621 void
1622 setup_pty (fd)
1623 int fd;
1624 {
1625 /* I'm told that TOICREMOTE does not mean control chars
1626 "can't be sent" but rather that they don't have
1627 input-editing or signaling effects.
1628 That should be good, because we have other ways
1629 to do those things in Emacs.
1630 However, telnet mode seems not to work on 4.2.
1631 So TIOCREMOTE is turned off now. */
1632
1633 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1634 will hang. In particular, the "timeout" feature (which
1635 causes a read to return if there is no data available)
1636 does this. Also it is known that telnet mode will hang
1637 in such a way that Emacs must be stopped (perhaps this
1638 is the same problem).
1639
1640 If TIOCREMOTE is turned off, then there is a bug in
1641 hp-ux which sometimes loses data. Apparently the
1642 code which blocks the master process when the internal
1643 buffer fills up does not work. Other than this,
1644 though, everything else seems to work fine.
1645
1646 Since the latter lossage is more benign, we may as well
1647 lose that way. -- cph */
1648 #ifdef FIONBIO
1649 #if defined(UNIX98_PTYS)
1650 {
1651 int on = 1;
1652 ioctl (fd, FIONBIO, &on);
1653 }
1654 #endif
1655 #endif
1656 }
1657 #endif /* HAVE_PTYS */
1658 \f
1659 #if !defined(CANNOT_DUMP) || !defined(SYSTEM_MALLOC)
1660 /* Some systems that cannot dump also cannot implement these. */
1661
1662 /*
1663 * Return the address of the start of the text segment prior to
1664 * doing an unexec. After unexec the return value is undefined.
1665 * See crt0.c for further explanation and _start.
1666 *
1667 */
1668
1669 #if !(defined (__NetBSD__) && defined (__ELF__))
1670 #ifndef HAVE_TEXT_START
1671 char *
1672 start_of_text ()
1673 {
1674 #ifdef TEXT_START
1675 return ((char *) TEXT_START);
1676 #else
1677 extern int _start ();
1678 return ((char *) _start);
1679 #endif /* TEXT_START */
1680 }
1681 #endif /* not HAVE_TEXT_START */
1682 #endif
1683
1684 /*
1685 * Return the address of the start of the data segment prior to
1686 * doing an unexec. After unexec the return value is undefined.
1687 * See crt0.c for further information and definition of data_start.
1688 *
1689 * Apparently, on BSD systems this is etext at startup. On
1690 * USG systems (swapping) this is highly mmu dependent and
1691 * is also dependent on whether or not the program is running
1692 * with shared text. Generally there is a (possibly large)
1693 * gap between end of text and start of data with shared text.
1694 *
1695 * On Uniplus+ systems with shared text, data starts at a
1696 * fixed address. Each port (from a given oem) is generally
1697 * different, and the specific value of the start of data can
1698 * be obtained via the UniPlus+ specific "uvar" system call,
1699 * however the method outlined in crt0.c seems to be more portable.
1700 *
1701 * Probably what will have to happen when a USG unexec is available,
1702 * at least on UniPlus, is temacs will have to be made unshared so
1703 * that text and data are contiguous. Then once loadup is complete,
1704 * unexec will produce a shared executable where the data can be
1705 * at the normal shared text boundary and the startofdata variable
1706 * will be patched by unexec to the correct value.
1707 *
1708 */
1709
1710 #ifndef start_of_data
1711 char *
1712 start_of_data ()
1713 {
1714 #ifdef DATA_START
1715 return ((char *) DATA_START);
1716 #else
1717 #ifdef ORDINARY_LINK
1718 /*
1719 * This is a hack. Since we're not linking crt0.c or pre_crt0.c,
1720 * data_start isn't defined. We take the address of environ, which
1721 * is known to live at or near the start of the system crt0.c, and
1722 * we don't sweat the handful of bytes that might lose.
1723 */
1724 extern char **environ;
1725
1726 return ((char *) &environ);
1727 #else
1728 extern int data_start;
1729 return ((char *) &data_start);
1730 #endif /* ORDINARY_LINK */
1731 #endif /* DATA_START */
1732 }
1733 #endif /* start_of_data */
1734 #endif /* NEED_STARTS (not CANNOT_DUMP or not SYSTEM_MALLOC) */
1735 \f
1736 /* init_system_name sets up the string for the Lisp function
1737 system-name to return. */
1738
1739 extern Lisp_Object Vsystem_name;
1740
1741 #ifdef HAVE_SOCKETS
1742 #include <sys/socket.h>
1743 #include <netdb.h>
1744 #endif /* HAVE_SOCKETS */
1745
1746 #ifdef TRY_AGAIN
1747 #ifndef HAVE_H_ERRNO
1748 extern int h_errno;
1749 #endif
1750 #endif /* TRY_AGAIN */
1751
1752 void
1753 init_system_name ()
1754 {
1755 #ifndef HAVE_GETHOSTNAME
1756 struct utsname uts;
1757 uname (&uts);
1758 Vsystem_name = build_string (uts.nodename);
1759 #else /* HAVE_GETHOSTNAME */
1760 unsigned int hostname_size = 256;
1761 char *hostname = (char *) alloca (hostname_size);
1762
1763 /* Try to get the host name; if the buffer is too short, try
1764 again. Apparently, the only indication gethostname gives of
1765 whether the buffer was large enough is the presence or absence
1766 of a '\0' in the string. Eech. */
1767 for (;;)
1768 {
1769 gethostname (hostname, hostname_size - 1);
1770 hostname[hostname_size - 1] = '\0';
1771
1772 /* Was the buffer large enough for the '\0'? */
1773 if (strlen (hostname) < hostname_size - 1)
1774 break;
1775
1776 hostname_size <<= 1;
1777 hostname = (char *) alloca (hostname_size);
1778 }
1779 #ifdef HAVE_SOCKETS
1780 /* Turn the hostname into the official, fully-qualified hostname.
1781 Don't do this if we're going to dump; this can confuse system
1782 libraries on some machines and make the dumped emacs core dump. */
1783 #ifndef CANNOT_DUMP
1784 if (initialized)
1785 #endif /* not CANNOT_DUMP */
1786 if (! index (hostname, '.'))
1787 {
1788 int count;
1789 #ifdef HAVE_GETADDRINFO
1790 struct addrinfo *res;
1791 struct addrinfo hints;
1792 int ret;
1793
1794 memset (&hints, 0, sizeof(hints));
1795 hints.ai_socktype = SOCK_STREAM;
1796 hints.ai_flags = AI_CANONNAME;
1797
1798 for (count = 0;; count++)
1799 {
1800 if ((ret = getaddrinfo (hostname, NULL, &hints, &res)) == 0
1801 || ret != EAI_AGAIN)
1802 break;
1803
1804 if (count >= 5)
1805 break;
1806 Fsleep_for (make_number (1), Qnil);
1807 }
1808
1809 if (ret == 0)
1810 {
1811 struct addrinfo *it = res;
1812 while (it)
1813 {
1814 char *fqdn = it->ai_canonname;
1815 if (fqdn && index (fqdn, '.')
1816 && strcmp (fqdn, "localhost.localdomain") != 0)
1817 break;
1818 it = it->ai_next;
1819 }
1820 if (it)
1821 {
1822 hostname = alloca (strlen (it->ai_canonname) + 1);
1823 strcpy (hostname, it->ai_canonname);
1824 }
1825 freeaddrinfo (res);
1826 }
1827 #else /* !HAVE_GETADDRINFO */
1828 struct hostent *hp;
1829 for (count = 0;; count++)
1830 {
1831
1832 #ifdef TRY_AGAIN
1833 h_errno = 0;
1834 #endif
1835 hp = gethostbyname (hostname);
1836 #ifdef TRY_AGAIN
1837 if (! (hp == 0 && h_errno == TRY_AGAIN))
1838 #endif
1839
1840 break;
1841
1842 if (count >= 5)
1843 break;
1844 Fsleep_for (make_number (1), Qnil);
1845 }
1846
1847 if (hp)
1848 {
1849 char *fqdn = (char *) hp->h_name;
1850
1851 if (!index (fqdn, '.'))
1852 {
1853 /* We still don't have a fully qualified domain name.
1854 Try to find one in the list of alternate names */
1855 char **alias = hp->h_aliases;
1856 while (*alias
1857 && (!index (*alias, '.')
1858 || !strcmp (*alias, "localhost.localdomain")))
1859 alias++;
1860 if (*alias)
1861 fqdn = *alias;
1862 }
1863 hostname = fqdn;
1864 }
1865 #endif /* !HAVE_GETADDRINFO */
1866 }
1867 #endif /* HAVE_SOCKETS */
1868 Vsystem_name = build_string (hostname);
1869 #endif /* HAVE_GETHOSTNAME */
1870 {
1871 unsigned char *p;
1872 for (p = SDATA (Vsystem_name); *p; p++)
1873 if (*p == ' ' || *p == '\t')
1874 *p = '-';
1875 }
1876 }
1877 \f
1878 #ifndef MSDOS
1879 #if !defined (HAVE_SELECT)
1880
1881 #include "sysselect.h"
1882 #undef select
1883
1884 #if defined (HAVE_X_WINDOWS) && !defined (HAVE_SELECT)
1885 /* Cause explanatory error message at compile time,
1886 since the select emulation is not good enough for X. */
1887 int *x = &x_windows_lose_if_no_select_system_call;
1888 #endif
1889
1890 /* Emulate as much as select as is possible under 4.1 and needed by Gnu Emacs
1891 * Only checks read descriptors.
1892 */
1893 /* How long to wait between checking fds in select */
1894 #define SELECT_PAUSE 1
1895 int select_alarmed;
1896
1897 /* For longjmp'ing back to read_input_waiting. */
1898
1899 jmp_buf read_alarm_throw;
1900
1901 /* Nonzero if the alarm signal should throw back to read_input_waiting.
1902 The read_socket_hook function sets this to 1 while it is waiting. */
1903
1904 int read_alarm_should_throw;
1905
1906 SIGTYPE
1907 select_alarm ()
1908 {
1909 select_alarmed = 1;
1910 signal (SIGALRM, SIG_IGN);
1911 SIGNAL_THREAD_CHECK (SIGALRM);
1912 if (read_alarm_should_throw)
1913 longjmp (read_alarm_throw, 1);
1914 }
1915
1916 #ifndef WINDOWSNT
1917 /* Only rfds are checked. */
1918 int
1919 sys_select (nfds, rfds, wfds, efds, timeout)
1920 int nfds;
1921 SELECT_TYPE *rfds, *wfds, *efds;
1922 EMACS_TIME *timeout;
1923 {
1924 /* XXX This needs to be updated for multi-tty support. Is there
1925 anybody who needs to emulate select these days? */
1926 int ravail = 0;
1927 SELECT_TYPE orfds;
1928 int timeoutval;
1929 int *local_timeout;
1930 extern int proc_buffered_char[];
1931 #ifndef subprocesses
1932 int process_tick = 0, update_tick = 0;
1933 #else
1934 extern int process_tick, update_tick;
1935 #endif
1936 unsigned char buf;
1937
1938 #if defined (HAVE_SELECT) && defined (HAVE_X_WINDOWS)
1939 /* If we're using X, then the native select will work; we only need the
1940 emulation for non-X usage. */
1941 if (!NILP (Vinitial_window_system))
1942 return select (nfds, rfds, wfds, efds, timeout);
1943 #endif
1944 timeoutval = timeout ? EMACS_SECS (*timeout) : 100000;
1945 local_timeout = &timeoutval;
1946 FD_ZERO (&orfds);
1947 if (rfds)
1948 {
1949 orfds = *rfds;
1950 FD_ZERO (rfds);
1951 }
1952 if (wfds)
1953 FD_ZERO (wfds);
1954 if (efds)
1955 FD_ZERO (efds);
1956
1957 /* If we are looking only for the terminal, with no timeout,
1958 just read it and wait -- that's more efficient. */
1959 if (*local_timeout == 100000 && process_tick == update_tick
1960 && FD_ISSET (0, &orfds))
1961 {
1962 int fd;
1963 for (fd = 1; fd < nfds; ++fd)
1964 if (FD_ISSET (fd, &orfds))
1965 goto hardway;
1966 if (! detect_input_pending ())
1967 read_input_waiting ();
1968 FD_SET (0, rfds);
1969 return 1;
1970 }
1971
1972 hardway:
1973 /* Once a second, till the timer expires, check all the flagged read
1974 * descriptors to see if any input is available. If there is some then
1975 * set the corresponding bit in the return copy of rfds.
1976 */
1977 while (1)
1978 {
1979 register int to_check, fd;
1980
1981 if (rfds)
1982 {
1983 for (to_check = nfds, fd = 0; --to_check >= 0; fd++)
1984 {
1985 if (FD_ISSET (fd, &orfds))
1986 {
1987 int avail = 0, status = 0;
1988
1989 if (fd == 0)
1990 avail = detect_input_pending (); /* Special keyboard handler */
1991 else
1992 {
1993 #ifdef FIONREAD
1994 status = ioctl (fd, FIONREAD, &avail);
1995 #else /* no FIONREAD */
1996 /* Hoping it will return -1 if nothing available
1997 or 0 if all 0 chars requested are read. */
1998 if (proc_buffered_char[fd] >= 0)
1999 avail = 1;
2000 else
2001 {
2002 avail = read (fd, &buf, 1);
2003 if (avail > 0)
2004 proc_buffered_char[fd] = buf;
2005 }
2006 #endif /* no FIONREAD */
2007 }
2008 if (status >= 0 && avail > 0)
2009 {
2010 FD_SET (fd, rfds);
2011 ravail++;
2012 }
2013 }
2014 }
2015 }
2016 if (*local_timeout == 0 || ravail != 0 || process_tick != update_tick)
2017 break;
2018
2019 turn_on_atimers (0);
2020 signal (SIGALRM, select_alarm);
2021 select_alarmed = 0;
2022 alarm (SELECT_PAUSE);
2023
2024 /* Wait for a SIGALRM (or maybe a SIGTINT) */
2025 while (select_alarmed == 0 && *local_timeout != 0
2026 && process_tick == update_tick)
2027 {
2028 /* If we are interested in terminal input,
2029 wait by reading the terminal.
2030 That makes instant wakeup for terminal input at least. */
2031 if (FD_ISSET (0, &orfds))
2032 {
2033 read_input_waiting ();
2034 if (detect_input_pending ())
2035 select_alarmed = 1;
2036 }
2037 else
2038 pause ();
2039 }
2040 (*local_timeout) -= SELECT_PAUSE;
2041
2042 /* Reset the old alarm if there was one. */
2043 turn_on_atimers (1);
2044
2045 if (*local_timeout == 0) /* Stop on timer being cleared */
2046 break;
2047 }
2048 return ravail;
2049 }
2050 #endif /* not WINDOWSNT */
2051
2052 /* Read keyboard input into the standard buffer,
2053 waiting for at least one character. */
2054
2055 void
2056 read_input_waiting ()
2057 {
2058 /* XXX This needs to be updated for multi-tty support. Is there
2059 anybody who needs to emulate select these days? */
2060 int nread, i;
2061 extern int quit_char;
2062
2063 if (read_socket_hook)
2064 {
2065 struct input_event hold_quit;
2066
2067 EVENT_INIT (hold_quit);
2068 hold_quit.kind = NO_EVENT;
2069
2070 read_alarm_should_throw = 0;
2071 if (! setjmp (read_alarm_throw))
2072 nread = (*read_socket_hook) (0, 1, &hold_quit);
2073 else
2074 nread = -1;
2075
2076 if (hold_quit.kind != NO_EVENT)
2077 kbd_buffer_store_event (&hold_quit);
2078 }
2079 else
2080 {
2081 struct input_event e;
2082 char buf[3];
2083 nread = read (fileno (stdin), buf, 1);
2084 EVENT_INIT (e);
2085
2086 /* Scan the chars for C-g and store them in kbd_buffer. */
2087 e.kind = ASCII_KEYSTROKE_EVENT;
2088 e.frame_or_window = selected_frame;
2089 e.modifiers = 0;
2090 for (i = 0; i < nread; i++)
2091 {
2092 /* Convert chars > 0177 to meta events if desired.
2093 We do this under the same conditions that read_avail_input does. */
2094 if (read_socket_hook == 0)
2095 {
2096 /* If the user says she has a meta key, then believe her. */
2097 if (meta_key == 1 && (buf[i] & 0x80))
2098 e.modifiers = meta_modifier;
2099 if (meta_key != 2)
2100 buf[i] &= ~0x80;
2101 }
2102
2103 XSETINT (e.code, buf[i]);
2104 kbd_buffer_store_event (&e);
2105 /* Don't look at input that follows a C-g too closely.
2106 This reduces lossage due to autorepeat on C-g. */
2107 if (buf[i] == quit_char)
2108 break;
2109 }
2110 }
2111 }
2112
2113 #if !defined (HAVE_SELECT)
2114 #define select sys_select
2115 #endif
2116
2117 #endif /* not HAVE_SELECT */
2118 #endif /* not MSDOS */
2119 \f
2120 /* POSIX signals support - DJB */
2121 /* Anyone with POSIX signals should have ANSI C declarations */
2122
2123 #ifdef POSIX_SIGNALS
2124
2125 sigset_t empty_mask, full_mask;
2126
2127 signal_handler_t
2128 sys_signal (int signal_number, signal_handler_t action)
2129 {
2130 struct sigaction new_action, old_action;
2131 sigemptyset (&new_action.sa_mask);
2132 new_action.sa_handler = action;
2133 new_action.sa_flags = 0;
2134 #if defined (SA_RESTART)
2135 /* Emacs mostly works better with restartable system services. If this
2136 flag exists, we probably want to turn it on here.
2137 However, on some systems this resets the timeout of `select'
2138 which means that `select' never finishes if it keeps getting signals.
2139 BROKEN_SA_RESTART is defined on those systems. */
2140 /* It's not clear why the comment above says "mostly works better". --Stef
2141 When SYNC_INPUT is set, we don't want SA_RESTART because we need to poll
2142 for pending input so we need long-running syscalls to be interrupted
2143 after a signal that sets the interrupt_input_pending flag. */
2144 /* Non-interactive keyboard input goes through stdio, where we always
2145 want restartable system calls. */
2146 # if defined (BROKEN_SA_RESTART) || defined(SYNC_INPUT)
2147 if (noninteractive)
2148 # endif
2149 new_action.sa_flags = SA_RESTART;
2150 #endif
2151 sigaction (signal_number, &new_action, &old_action);
2152 return (old_action.sa_handler);
2153 }
2154
2155 #ifndef __GNUC__
2156 /* If we're compiling with GCC, we don't need this function, since it
2157 can be written as a macro. */
2158 sigset_t
2159 sys_sigmask (int sig)
2160 {
2161 sigset_t mask;
2162 sigemptyset (&mask);
2163 sigaddset (&mask, sig);
2164 return mask;
2165 }
2166 #endif
2167
2168 /* I'd like to have these guys return pointers to the mask storage in here,
2169 but there'd be trouble if the code was saving multiple masks. I'll be
2170 safe and pass the structure. It normally won't be more than 2 bytes
2171 anyhow. - DJB */
2172
2173 sigset_t
2174 sys_sigblock (sigset_t new_mask)
2175 {
2176 sigset_t old_mask;
2177 sigprocmask (SIG_BLOCK, &new_mask, &old_mask);
2178 return (old_mask);
2179 }
2180
2181 sigset_t
2182 sys_sigunblock (sigset_t new_mask)
2183 {
2184 sigset_t old_mask;
2185 sigprocmask (SIG_UNBLOCK, &new_mask, &old_mask);
2186 return (old_mask);
2187 }
2188
2189 sigset_t
2190 sys_sigsetmask (sigset_t new_mask)
2191 {
2192 sigset_t old_mask;
2193 sigprocmask (SIG_SETMASK, &new_mask, &old_mask);
2194 return (old_mask);
2195 }
2196
2197 #endif /* POSIX_SIGNALS */
2198 \f
2199 #if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
2200 static char *my_sys_siglist[NSIG];
2201 # ifdef sys_siglist
2202 # undef sys_siglist
2203 # endif
2204 # define sys_siglist my_sys_siglist
2205 #endif
2206
2207 void
2208 init_signals ()
2209 {
2210 #ifdef POSIX_SIGNALS
2211 sigemptyset (&empty_mask);
2212 sigfillset (&full_mask);
2213 #endif
2214
2215 #if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
2216 if (! initialized)
2217 {
2218 # ifdef SIGABRT
2219 sys_siglist[SIGABRT] = "Aborted";
2220 # endif
2221 # ifdef SIGAIO
2222 sys_siglist[SIGAIO] = "LAN I/O interrupt";
2223 # endif
2224 # ifdef SIGALRM
2225 sys_siglist[SIGALRM] = "Alarm clock";
2226 # endif
2227 # ifdef SIGBUS
2228 sys_siglist[SIGBUS] = "Bus error";
2229 # endif
2230 # ifdef SIGCLD
2231 sys_siglist[SIGCLD] = "Child status changed";
2232 # endif
2233 # ifdef SIGCHLD
2234 sys_siglist[SIGCHLD] = "Child status changed";
2235 # endif
2236 # ifdef SIGCONT
2237 sys_siglist[SIGCONT] = "Continued";
2238 # endif
2239 # ifdef SIGDANGER
2240 sys_siglist[SIGDANGER] = "Swap space dangerously low";
2241 # endif
2242 # ifdef SIGDGNOTIFY
2243 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
2244 # endif
2245 # ifdef SIGEMT
2246 sys_siglist[SIGEMT] = "Emulation trap";
2247 # endif
2248 # ifdef SIGFPE
2249 sys_siglist[SIGFPE] = "Arithmetic exception";
2250 # endif
2251 # ifdef SIGFREEZE
2252 sys_siglist[SIGFREEZE] = "SIGFREEZE";
2253 # endif
2254 # ifdef SIGGRANT
2255 sys_siglist[SIGGRANT] = "Monitor mode granted";
2256 # endif
2257 # ifdef SIGHUP
2258 sys_siglist[SIGHUP] = "Hangup";
2259 # endif
2260 # ifdef SIGILL
2261 sys_siglist[SIGILL] = "Illegal instruction";
2262 # endif
2263 # ifdef SIGINT
2264 sys_siglist[SIGINT] = "Interrupt";
2265 # endif
2266 # ifdef SIGIO
2267 sys_siglist[SIGIO] = "I/O possible";
2268 # endif
2269 # ifdef SIGIOINT
2270 sys_siglist[SIGIOINT] = "I/O intervention required";
2271 # endif
2272 # ifdef SIGIOT
2273 sys_siglist[SIGIOT] = "IOT trap";
2274 # endif
2275 # ifdef SIGKILL
2276 sys_siglist[SIGKILL] = "Killed";
2277 # endif
2278 # ifdef SIGLOST
2279 sys_siglist[SIGLOST] = "Resource lost";
2280 # endif
2281 # ifdef SIGLWP
2282 sys_siglist[SIGLWP] = "SIGLWP";
2283 # endif
2284 # ifdef SIGMSG
2285 sys_siglist[SIGMSG] = "Monitor mode data available";
2286 # endif
2287 # ifdef SIGPHONE
2288 sys_siglist[SIGWIND] = "SIGPHONE";
2289 # endif
2290 # ifdef SIGPIPE
2291 sys_siglist[SIGPIPE] = "Broken pipe";
2292 # endif
2293 # ifdef SIGPOLL
2294 sys_siglist[SIGPOLL] = "Pollable event occurred";
2295 # endif
2296 # ifdef SIGPROF
2297 sys_siglist[SIGPROF] = "Profiling timer expired";
2298 # endif
2299 # ifdef SIGPTY
2300 sys_siglist[SIGPTY] = "PTY I/O interrupt";
2301 # endif
2302 # ifdef SIGPWR
2303 sys_siglist[SIGPWR] = "Power-fail restart";
2304 # endif
2305 # ifdef SIGQUIT
2306 sys_siglist[SIGQUIT] = "Quit";
2307 # endif
2308 # ifdef SIGRETRACT
2309 sys_siglist[SIGRETRACT] = "Need to relinguish monitor mode";
2310 # endif
2311 # ifdef SIGSAK
2312 sys_siglist[SIGSAK] = "Secure attention";
2313 # endif
2314 # ifdef SIGSEGV
2315 sys_siglist[SIGSEGV] = "Segmentation violation";
2316 # endif
2317 # ifdef SIGSOUND
2318 sys_siglist[SIGSOUND] = "Sound completed";
2319 # endif
2320 # ifdef SIGSTOP
2321 sys_siglist[SIGSTOP] = "Stopped (signal)";
2322 # endif
2323 # ifdef SIGSTP
2324 sys_siglist[SIGSTP] = "Stopped (user)";
2325 # endif
2326 # ifdef SIGSYS
2327 sys_siglist[SIGSYS] = "Bad argument to system call";
2328 # endif
2329 # ifdef SIGTERM
2330 sys_siglist[SIGTERM] = "Terminated";
2331 # endif
2332 # ifdef SIGTHAW
2333 sys_siglist[SIGTHAW] = "SIGTHAW";
2334 # endif
2335 # ifdef SIGTRAP
2336 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2337 # endif
2338 # ifdef SIGTSTP
2339 sys_siglist[SIGTSTP] = "Stopped (user)";
2340 # endif
2341 # ifdef SIGTTIN
2342 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2343 # endif
2344 # ifdef SIGTTOU
2345 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2346 # endif
2347 # ifdef SIGURG
2348 sys_siglist[SIGURG] = "Urgent I/O condition";
2349 # endif
2350 # ifdef SIGUSR1
2351 sys_siglist[SIGUSR1] = "User defined signal 1";
2352 # endif
2353 # ifdef SIGUSR2
2354 sys_siglist[SIGUSR2] = "User defined signal 2";
2355 # endif
2356 # ifdef SIGVTALRM
2357 sys_siglist[SIGVTALRM] = "Virtual timer expired";
2358 # endif
2359 # ifdef SIGWAITING
2360 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
2361 # endif
2362 # ifdef SIGWINCH
2363 sys_siglist[SIGWINCH] = "Window size changed";
2364 # endif
2365 # ifdef SIGWIND
2366 sys_siglist[SIGWIND] = "SIGWIND";
2367 # endif
2368 # ifdef SIGXCPU
2369 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
2370 # endif
2371 # ifdef SIGXFSZ
2372 sys_siglist[SIGXFSZ] = "File size limit exceeded";
2373 # endif
2374 }
2375 #endif /* !defined HAVE_STRSIGNAL && !defined HAVE_DECL_SYS_SIGLIST */
2376 }
2377 \f
2378 #ifndef HAVE_RANDOM
2379 #ifdef random
2380 #define HAVE_RANDOM
2381 #endif
2382 #endif
2383
2384 /* Figure out how many bits the system's random number generator uses.
2385 `random' and `lrand48' are assumed to return 31 usable bits.
2386 BSD `rand' returns a 31 bit value but the low order bits are unusable;
2387 so we'll shift it and treat it like the 15-bit USG `rand'. */
2388
2389 #ifndef RAND_BITS
2390 # ifdef HAVE_RANDOM
2391 # define RAND_BITS 31
2392 # else /* !HAVE_RANDOM */
2393 # ifdef HAVE_LRAND48
2394 # define RAND_BITS 31
2395 # define random lrand48
2396 # else /* !HAVE_LRAND48 */
2397 # define RAND_BITS 15
2398 # if RAND_MAX == 32767
2399 # define random rand
2400 # else /* RAND_MAX != 32767 */
2401 # if RAND_MAX == 2147483647
2402 # define random() (rand () >> 16)
2403 # else /* RAND_MAX != 2147483647 */
2404 # ifdef USG
2405 # define random rand
2406 # else
2407 # define random() (rand () >> 16)
2408 # endif /* !USG */
2409 # endif /* RAND_MAX != 2147483647 */
2410 # endif /* RAND_MAX != 32767 */
2411 # endif /* !HAVE_LRAND48 */
2412 # endif /* !HAVE_RANDOM */
2413 #endif /* !RAND_BITS */
2414
2415 void
2416 seed_random (arg)
2417 long arg;
2418 {
2419 #ifdef HAVE_RANDOM
2420 srandom ((unsigned int)arg);
2421 #else
2422 # ifdef HAVE_LRAND48
2423 srand48 (arg);
2424 # else
2425 srand ((unsigned int)arg);
2426 # endif
2427 #endif
2428 }
2429
2430 /*
2431 * Build a full Emacs-sized word out of whatever we've got.
2432 * This suffices even for a 64-bit architecture with a 15-bit rand.
2433 */
2434 long
2435 get_random ()
2436 {
2437 long val = random ();
2438 #if VALBITS > RAND_BITS
2439 val = (val << RAND_BITS) ^ random ();
2440 #if VALBITS > 2*RAND_BITS
2441 val = (val << RAND_BITS) ^ random ();
2442 #if VALBITS > 3*RAND_BITS
2443 val = (val << RAND_BITS) ^ random ();
2444 #if VALBITS > 4*RAND_BITS
2445 val = (val << RAND_BITS) ^ random ();
2446 #endif /* need at least 5 */
2447 #endif /* need at least 4 */
2448 #endif /* need at least 3 */
2449 #endif /* need at least 2 */
2450 return val & ((1L << VALBITS) - 1);
2451 }
2452
2453 #ifndef HAVE_STRERROR
2454 #ifndef WINDOWSNT
2455 char *
2456 strerror (errnum)
2457 int errnum;
2458 {
2459 extern char *sys_errlist[];
2460 extern int sys_nerr;
2461
2462 if (errnum >= 0 && errnum < sys_nerr)
2463 return sys_errlist[errnum];
2464 return (char *) "Unknown error";
2465 }
2466 #endif /* not WINDOWSNT */
2467 #endif /* ! HAVE_STRERROR */
2468 \f
2469 int
2470 emacs_open (path, oflag, mode)
2471 const char *path;
2472 int oflag, mode;
2473 {
2474 register int rtnval;
2475
2476 while ((rtnval = open (path, oflag, mode)) == -1
2477 && (errno == EINTR))
2478 QUIT;
2479 return (rtnval);
2480 }
2481
2482 int
2483 emacs_close (fd)
2484 int fd;
2485 {
2486 int did_retry = 0;
2487 register int rtnval;
2488
2489 while ((rtnval = close (fd)) == -1
2490 && (errno == EINTR))
2491 did_retry = 1;
2492
2493 /* If close is interrupted SunOS 4.1 may or may not have closed the
2494 file descriptor. If it did the second close will fail with
2495 errno = EBADF. That means we have succeeded. */
2496 if (rtnval == -1 && did_retry && errno == EBADF)
2497 return 0;
2498
2499 return rtnval;
2500 }
2501
2502 int
2503 emacs_read (fildes, buf, nbyte)
2504 int fildes;
2505 char *buf;
2506 unsigned int nbyte;
2507 {
2508 register int rtnval;
2509
2510 while ((rtnval = read (fildes, buf, nbyte)) == -1
2511 && (errno == EINTR))
2512 QUIT;
2513 return (rtnval);
2514 }
2515
2516 int
2517 emacs_write (fildes, buf, nbyte)
2518 int fildes;
2519 const char *buf;
2520 unsigned int nbyte;
2521 {
2522 register int rtnval, bytes_written;
2523
2524 bytes_written = 0;
2525
2526 while (nbyte > 0)
2527 {
2528 rtnval = write (fildes, buf, nbyte);
2529
2530 if (rtnval == -1)
2531 {
2532 if (errno == EINTR)
2533 {
2534 #ifdef SYNC_INPUT
2535 /* I originally used `QUIT' but that might causes files to
2536 be truncated if you hit C-g in the middle of it. --Stef */
2537 process_pending_signals ();
2538 #endif
2539 continue;
2540 }
2541 else
2542 return (bytes_written ? bytes_written : -1);
2543 }
2544
2545 buf += rtnval;
2546 nbyte -= rtnval;
2547 bytes_written += rtnval;
2548 }
2549 return (bytes_written);
2550 }
2551 \f
2552 #ifdef USG
2553 /*
2554 * All of the following are for USG.
2555 *
2556 * On USG systems the system calls are INTERRUPTIBLE by signals
2557 * that the user program has elected to catch. Thus the system call
2558 * must be retried in these cases. To handle this without massive
2559 * changes in the source code, we remap the standard system call names
2560 * to names for our own functions in sysdep.c that do the system call
2561 * with retries. Actually, for portability reasons, it is good
2562 * programming practice, as this example shows, to limit all actual
2563 * system calls to a single occurrence in the source. Sure, this
2564 * adds an extra level of function call overhead but it is almost
2565 * always negligible. Fred Fish, Unisoft Systems Inc.
2566 */
2567
2568 /*
2569 * Warning, this function may not duplicate 4.2 action properly
2570 * under error conditions.
2571 */
2572
2573 #ifndef MAXPATHLEN
2574 /* In 4.1, param.h fails to define this. */
2575 #define MAXPATHLEN 1024
2576 #endif
2577
2578 #ifndef HAVE_GETWD
2579
2580 char *
2581 getwd (pathname)
2582 char *pathname;
2583 {
2584 char *npath, *spath;
2585 extern char *getcwd ();
2586
2587 BLOCK_INPUT; /* getcwd uses malloc */
2588 spath = npath = getcwd ((char *) 0, MAXPATHLEN);
2589 if (spath == 0)
2590 {
2591 UNBLOCK_INPUT;
2592 return spath;
2593 }
2594 /* On Altos 3068, getcwd can return @hostname/dir, so discard
2595 up to first slash. Should be harmless on other systems. */
2596 while (*npath && *npath != '/')
2597 npath++;
2598 strcpy (pathname, npath);
2599 free (spath); /* getcwd uses malloc */
2600 UNBLOCK_INPUT;
2601 return pathname;
2602 }
2603
2604 #endif /* HAVE_GETWD */
2605
2606 /*
2607 * Emulate rename using unlink/link. Note that this is
2608 * only partially correct. Also, doesn't enforce restriction
2609 * that files be of same type (regular->regular, dir->dir, etc).
2610 */
2611
2612 #ifndef HAVE_RENAME
2613
2614 rename (from, to)
2615 const char *from;
2616 const char *to;
2617 {
2618 if (access (from, 0) == 0)
2619 {
2620 unlink (to);
2621 if (link (from, to) == 0)
2622 if (unlink (from) == 0)
2623 return (0);
2624 }
2625 return (-1);
2626 }
2627
2628 #endif
2629
2630
2631 #if defined(HPUX) && !defined(HAVE_PERROR)
2632
2633 /* HPUX curses library references perror, but as far as we know
2634 it won't be called. Anyway this definition will do for now. */
2635
2636 perror ()
2637 {
2638 }
2639 #endif /* HPUX and not HAVE_PERROR */
2640
2641 #ifndef HAVE_DUP2
2642
2643 /*
2644 * Emulate BSD dup2. First close newd if it already exists.
2645 * Then, attempt to dup oldd. If not successful, call dup2 recursively
2646 * until we are, then close the unsuccessful ones.
2647 */
2648
2649 dup2 (oldd, newd)
2650 int oldd;
2651 int newd;
2652 {
2653 register int fd, ret;
2654
2655 emacs_close (newd);
2656
2657 #ifdef F_DUPFD
2658 return fcntl (oldd, F_DUPFD, newd);
2659 #else
2660 fd = dup (old);
2661 if (fd == -1)
2662 return -1;
2663 if (fd == new)
2664 return new;
2665 ret = dup2 (old,new);
2666 emacs_close (fd);
2667 return ret;
2668 #endif
2669 }
2670
2671 #endif /* not HAVE_DUP2 */
2672
2673 /*
2674 * Gettimeofday. Simulate as much as possible. Only accurate
2675 * to nearest second. Emacs doesn't use tzp so ignore it for now.
2676 * Only needed when subprocesses are defined.
2677 */
2678
2679 #ifdef subprocesses
2680 #ifndef HAVE_GETTIMEOFDAY
2681 #ifdef HAVE_TIMEVAL
2682
2683 /* ARGSUSED */
2684 int
2685 gettimeofday (tp, tzp)
2686 struct timeval *tp;
2687 struct timezone *tzp;
2688 {
2689 extern long time ();
2690
2691 tp->tv_sec = time ((long *)0);
2692 tp->tv_usec = 0;
2693 if (tzp != 0)
2694 tzp->tz_minuteswest = -1;
2695 return 0;
2696 }
2697
2698 #endif
2699 #endif
2700 #endif /* subprocess && !HAVE_GETTIMEOFDAY && HAVE_TIMEVAL */
2701
2702 /*
2703 * This function will go away as soon as all the stubs fixed. (fnf)
2704 */
2705
2706 void
2707 croak (badfunc)
2708 char *badfunc;
2709 {
2710 printf ("%s not yet implemented\r\n", badfunc);
2711 reset_all_sys_modes ();
2712 exit (1);
2713 }
2714
2715 #endif /* USG */
2716 \f
2717 /* Directory routines for systems that don't have them. */
2718
2719 #ifdef SYSV_SYSTEM_DIR
2720
2721 #include <dirent.h>
2722
2723 #if !defined (HAVE_CLOSEDIR)
2724
2725 int
2726 closedir (DIR *dirp /* stream from opendir */)
2727 {
2728 int rtnval;
2729
2730 rtnval = emacs_close (dirp->dd_fd);
2731
2732 /* Some systems (like Solaris) allocate the buffer and the DIR all
2733 in one block. Why in the world are we freeing this ourselves
2734 anyway? */
2735 #if ! defined (SOLARIS2)
2736 xfree ((char *) dirp->dd_buf); /* directory block defined in <dirent.h> */
2737 #endif
2738 xfree ((char *) dirp);
2739
2740 return rtnval;
2741 }
2742 #endif /* not HAVE_CLOSEDIR */
2743 #endif /* SYSV_SYSTEM_DIR */
2744
2745 \f
2746 int
2747 set_file_times (filename, atime, mtime)
2748 const char *filename;
2749 EMACS_TIME atime, mtime;
2750 {
2751 #ifdef HAVE_UTIMES
2752 struct timeval tv[2];
2753 tv[0] = atime;
2754 tv[1] = mtime;
2755 return utimes (filename, tv);
2756 #else /* not HAVE_UTIMES */
2757 struct utimbuf utb;
2758 utb.actime = EMACS_SECS (atime);
2759 utb.modtime = EMACS_SECS (mtime);
2760 return utime (filename, &utb);
2761 #endif /* not HAVE_UTIMES */
2762 }
2763 \f
2764 /* mkdir and rmdir functions, for systems which don't have them. */
2765
2766 #ifndef HAVE_MKDIR
2767 /*
2768 * Written by Robert Rother, Mariah Corporation, August 1985.
2769 *
2770 * If you want it, it's yours. All I ask in return is that if you
2771 * figure out how to do this in a Bourne Shell script you send me
2772 * a copy.
2773 * sdcsvax!rmr or rmr@uscd
2774 *
2775 * Severely hacked over by John Gilmore to make a 4.2BSD compatible
2776 * subroutine. 11Mar86; hoptoad!gnu
2777 *
2778 * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
2779 * subroutine didn't return EEXIST. It does now.
2780 */
2781
2782 /*
2783 * Make a directory.
2784 */
2785 #ifdef MKDIR_PROTOTYPE
2786 MKDIR_PROTOTYPE
2787 #else
2788 int
2789 mkdir (dpath, dmode)
2790 char *dpath;
2791 int dmode;
2792 #endif
2793 {
2794 int cpid, status, fd;
2795 struct stat statbuf;
2796
2797 if (stat (dpath, &statbuf) == 0)
2798 {
2799 errno = EEXIST; /* Stat worked, so it already exists */
2800 return -1;
2801 }
2802
2803 /* If stat fails for a reason other than non-existence, return error */
2804 if (errno != ENOENT)
2805 return -1;
2806
2807 synch_process_alive = 1;
2808 switch (cpid = fork ())
2809 {
2810
2811 case -1: /* Error in fork */
2812 return (-1); /* Errno is set already */
2813
2814 case 0: /* Child process */
2815 /*
2816 * Cheap hack to set mode of new directory. Since this
2817 * child process is going away anyway, we zap its umask.
2818 * FIXME, this won't suffice to set SUID, SGID, etc. on this
2819 * directory. Does anybody care?
2820 */
2821 status = umask (0); /* Get current umask */
2822 status = umask (status | (0777 & ~dmode)); /* Set for mkdir */
2823 fd = emacs_open ("/dev/null", O_RDWR, 0);
2824 if (fd >= 0)
2825 {
2826 dup2 (fd, 0);
2827 dup2 (fd, 1);
2828 dup2 (fd, 2);
2829 }
2830 execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
2831 _exit (-1); /* Can't exec /bin/mkdir */
2832
2833 default: /* Parent process */
2834 wait_for_termination (cpid);
2835 }
2836
2837 if (synch_process_death != 0 || synch_process_retcode != 0
2838 || synch_process_termsig != 0)
2839 {
2840 errno = EIO; /* We don't know why, but */
2841 return -1; /* /bin/mkdir failed */
2842 }
2843
2844 return 0;
2845 }
2846 #endif /* not HAVE_MKDIR */
2847
2848 #ifndef HAVE_RMDIR
2849 int
2850 rmdir (dpath)
2851 char *dpath;
2852 {
2853 int cpid, status, fd;
2854 struct stat statbuf;
2855
2856 if (stat (dpath, &statbuf) != 0)
2857 {
2858 /* Stat just set errno. We don't have to */
2859 return -1;
2860 }
2861
2862 synch_process_alive = 1;
2863 switch (cpid = fork ())
2864 {
2865
2866 case -1: /* Error in fork */
2867 return (-1); /* Errno is set already */
2868
2869 case 0: /* Child process */
2870 fd = emacs_open ("/dev/null", O_RDWR, 0);
2871 if (fd >= 0)
2872 {
2873 dup2 (fd, 0);
2874 dup2 (fd, 1);
2875 dup2 (fd, 2);
2876 }
2877 execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
2878 _exit (-1); /* Can't exec /bin/rmdir */
2879
2880 default: /* Parent process */
2881 wait_for_termination (cpid);
2882 }
2883
2884 if (synch_process_death != 0 || synch_process_retcode != 0
2885 || synch_process_termsig != 0)
2886 {
2887 errno = EIO; /* We don't know why, but */
2888 return -1; /* /bin/rmdir failed */
2889 }
2890
2891 return 0;
2892 }
2893 #endif /* !HAVE_RMDIR */
2894
2895 \f
2896 #ifndef BSTRING
2897
2898 #ifndef bzero
2899
2900 void
2901 bzero (b, length)
2902 register char *b;
2903 register int length;
2904 {
2905 while (length-- > 0)
2906 *b++ = 0;
2907 }
2908
2909 #endif /* no bzero */
2910 #endif /* BSTRING */
2911
2912 #if (!defined (BSTRING) && !defined (bcopy)) || defined (NEED_BCOPY)
2913 #undef bcopy
2914
2915 /* Saying `void' requires a declaration, above, where bcopy is used
2916 and that declaration causes pain for systems where bcopy is a macro. */
2917 bcopy (b1, b2, length)
2918 register char *b1;
2919 register char *b2;
2920 register int length;
2921 {
2922 while (length-- > 0)
2923 *b2++ = *b1++;
2924 }
2925 #endif /* (!defined (BSTRING) && !defined (bcopy)) || defined (NEED_BCOPY) */
2926
2927 #ifndef BSTRING
2928 #ifndef bcmp
2929 int
2930 bcmp (b1, b2, length) /* This could be a macro! */
2931 register char *b1;
2932 register char *b2;
2933 register int length;
2934 {
2935 while (length-- > 0)
2936 if (*b1++ != *b2++)
2937 return 1;
2938
2939 return 0;
2940 }
2941 #endif /* no bcmp */
2942 #endif /* not BSTRING */
2943 \f
2944 #ifndef HAVE_STRSIGNAL
2945 char *
2946 strsignal (code)
2947 int code;
2948 {
2949 char *signame = 0;
2950
2951 if (0 <= code && code < NSIG)
2952 {
2953 /* Cast to suppress warning if the table has const char *. */
2954 signame = (char *) sys_siglist[code];
2955 }
2956
2957 return signame;
2958 }
2959 #endif /* HAVE_STRSIGNAL */
2960 \f
2961 #ifdef HAVE_TERMIOS
2962 /* For make-serial-process */
2963 int serial_open (char *port)
2964 {
2965 int fd = -1;
2966
2967 fd = emacs_open ((char*) port,
2968 O_RDWR
2969 #ifdef O_NONBLOCK
2970 | O_NONBLOCK
2971 #else
2972 | O_NDELAY
2973 #endif
2974 #ifdef O_NOCTTY
2975 | O_NOCTTY
2976 #endif
2977 , 0);
2978 if (fd < 0)
2979 {
2980 error ("Could not open %s: %s",
2981 port, emacs_strerror (errno));
2982 }
2983 #ifdef TIOCEXCL
2984 ioctl (fd, TIOCEXCL, (char *) 0);
2985 #endif
2986
2987 return fd;
2988 }
2989 #endif /* TERMIOS */
2990
2991 #ifdef HAVE_TERMIOS
2992
2993 #if !defined (HAVE_CFMAKERAW)
2994 /* Workaround for targets which are missing cfmakeraw. */
2995 /* Pasted from man page. */
2996 static void cfmakeraw (struct termios *termios_p)
2997 {
2998 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2999 termios_p->c_oflag &= ~OPOST;
3000 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
3001 termios_p->c_cflag &= ~(CSIZE|PARENB);
3002 termios_p->c_cflag |= CS8;
3003 }
3004 #endif /* !defined (HAVE_CFMAKERAW */
3005
3006 #if !defined (HAVE_CFSETSPEED)
3007 /* Workaround for targets which are missing cfsetspeed. */
3008 static int cfsetspeed (struct termios *termios_p, speed_t vitesse)
3009 {
3010 return (cfsetispeed (termios_p, vitesse)
3011 + cfsetospeed (termios_p, vitesse));
3012 }
3013 #endif
3014
3015 /* For serial-process-configure */
3016 void
3017 serial_configure (struct Lisp_Process *p,
3018 Lisp_Object contact)
3019 {
3020 Lisp_Object childp2 = Qnil;
3021 Lisp_Object tem = Qnil;
3022 struct termios attr;
3023 int err = -1;
3024 char summary[4] = "???"; /* This usually becomes "8N1". */
3025
3026 childp2 = Fcopy_sequence (p->childp);
3027
3028 /* Read port attributes and prepare default configuration. */
3029 err = tcgetattr (p->outfd, &attr);
3030 if (err != 0)
3031 error ("tcgetattr() failed: %s", emacs_strerror (errno));
3032 cfmakeraw (&attr);
3033 #if defined (CLOCAL)
3034 attr.c_cflag |= CLOCAL;
3035 #endif
3036 #if defined (CREAD)
3037 attr.c_cflag |= CREAD;
3038 #endif
3039
3040 /* Configure speed. */
3041 if (!NILP (Fplist_member (contact, QCspeed)))
3042 tem = Fplist_get (contact, QCspeed);
3043 else
3044 tem = Fplist_get (p->childp, QCspeed);
3045 CHECK_NUMBER (tem);
3046 err = cfsetspeed (&attr, XINT (tem));
3047 if (err != 0)
3048 error ("cfsetspeed(%d) failed: %s", XINT (tem), emacs_strerror (errno));
3049 childp2 = Fplist_put (childp2, QCspeed, tem);
3050
3051 /* Configure bytesize. */
3052 if (!NILP (Fplist_member (contact, QCbytesize)))
3053 tem = Fplist_get (contact, QCbytesize);
3054 else
3055 tem = Fplist_get (p->childp, QCbytesize);
3056 if (NILP (tem))
3057 tem = make_number (8);
3058 CHECK_NUMBER (tem);
3059 if (XINT (tem) != 7 && XINT (tem) != 8)
3060 error (":bytesize must be nil (8), 7, or 8");
3061 summary[0] = XINT(tem) + '0';
3062 #if defined (CSIZE) && defined (CS7) && defined (CS8)
3063 attr.c_cflag &= ~CSIZE;
3064 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
3065 #else
3066 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
3067 if (XINT (tem) != 8)
3068 error ("Bytesize cannot be changed");
3069 #endif
3070 childp2 = Fplist_put (childp2, QCbytesize, tem);
3071
3072 /* Configure parity. */
3073 if (!NILP (Fplist_member (contact, QCparity)))
3074 tem = Fplist_get (contact, QCparity);
3075 else
3076 tem = Fplist_get (p->childp, QCparity);
3077 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
3078 error (":parity must be nil (no parity), `even', or `odd'");
3079 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
3080 attr.c_cflag &= ~(PARENB | PARODD);
3081 attr.c_iflag &= ~(IGNPAR | INPCK);
3082 if (NILP (tem))
3083 {
3084 summary[1] = 'N';
3085 }
3086 else if (EQ (tem, Qeven))
3087 {
3088 summary[1] = 'E';
3089 attr.c_cflag |= PARENB;
3090 attr.c_iflag |= (IGNPAR | INPCK);
3091 }
3092 else if (EQ (tem, Qodd))
3093 {
3094 summary[1] = 'O';
3095 attr.c_cflag |= (PARENB | PARODD);
3096 attr.c_iflag |= (IGNPAR | INPCK);
3097 }
3098 #else
3099 /* Don't error on no parity, which should be set by cfmakeraw. */
3100 if (!NILP (tem))
3101 error ("Parity cannot be configured");
3102 #endif
3103 childp2 = Fplist_put (childp2, QCparity, tem);
3104
3105 /* Configure stopbits. */
3106 if (!NILP (Fplist_member (contact, QCstopbits)))
3107 tem = Fplist_get (contact, QCstopbits);
3108 else
3109 tem = Fplist_get (p->childp, QCstopbits);
3110 if (NILP (tem))
3111 tem = make_number (1);
3112 CHECK_NUMBER (tem);
3113 if (XINT (tem) != 1 && XINT (tem) != 2)
3114 error (":stopbits must be nil (1 stopbit), 1, or 2");
3115 summary[2] = XINT (tem) + '0';
3116 #if defined (CSTOPB)
3117 attr.c_cflag &= ~CSTOPB;
3118 if (XINT (tem) == 2)
3119 attr.c_cflag |= CSTOPB;
3120 #else
3121 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
3122 if (XINT (tem) != 1)
3123 error ("Stopbits cannot be configured");
3124 #endif
3125 childp2 = Fplist_put (childp2, QCstopbits, tem);
3126
3127 /* Configure flowcontrol. */
3128 if (!NILP (Fplist_member (contact, QCflowcontrol)))
3129 tem = Fplist_get (contact, QCflowcontrol);
3130 else
3131 tem = Fplist_get (p->childp, QCflowcontrol);
3132 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
3133 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
3134 #if defined (CRTSCTS)
3135 attr.c_cflag &= ~CRTSCTS;
3136 #endif
3137 #if defined (CNEW_RTSCTS)
3138 attr.c_cflag &= ~CNEW_RTSCTS;
3139 #endif
3140 #if defined (IXON) && defined (IXOFF)
3141 attr.c_iflag &= ~(IXON | IXOFF);
3142 #endif
3143 if (NILP (tem))
3144 {
3145 /* Already configured. */
3146 }
3147 else if (EQ (tem, Qhw))
3148 {
3149 #if defined (CRTSCTS)
3150 attr.c_cflag |= CRTSCTS;
3151 #elif defined (CNEW_RTSCTS)
3152 attr.c_cflag |= CNEW_RTSCTS;
3153 #else
3154 error ("Hardware flowcontrol (RTS/CTS) not supported");
3155 #endif
3156 }
3157 else if (EQ (tem, Qsw))
3158 {
3159 #if defined (IXON) && defined (IXOFF)
3160 attr.c_iflag |= (IXON | IXOFF);
3161 #else
3162 error ("Software flowcontrol (XON/XOFF) not supported");
3163 #endif
3164 }
3165 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
3166
3167 /* Activate configuration. */
3168 err = tcsetattr (p->outfd, TCSANOW, &attr);
3169 if (err != 0)
3170 error ("tcsetattr() failed: %s", emacs_strerror (errno));
3171
3172 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
3173 p->childp = childp2;
3174
3175 }
3176 #endif /* TERMIOS */
3177 \f
3178 /* System depended enumeration of and access to system processes a-la ps(1). */
3179
3180 #ifdef HAVE_PROCFS
3181
3182 /* Process enumeration and access via /proc. */
3183
3184 Lisp_Object
3185 list_system_processes ()
3186 {
3187 Lisp_Object procdir, match, proclist, next;
3188 struct gcpro gcpro1, gcpro2;
3189 register Lisp_Object tail;
3190
3191 GCPRO2 (procdir, match);
3192 /* For every process on the system, there's a directory in the
3193 "/proc" pseudo-directory whose name is the numeric ID of that
3194 process. */
3195 procdir = build_string ("/proc");
3196 match = build_string ("[0-9]+");
3197 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
3198
3199 /* `proclist' gives process IDs as strings. Destructively convert
3200 each string into a number. */
3201 for (tail = proclist; CONSP (tail); tail = next)
3202 {
3203 next = XCDR (tail);
3204 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
3205 }
3206 UNGCPRO;
3207
3208 /* directory_files_internal returns the files in reverse order; undo
3209 that. */
3210 proclist = Fnreverse (proclist);
3211 return proclist;
3212 }
3213
3214 /* The WINDOWSNT implementation is on w32.c.
3215 The MSDOS implementation is on dosfns.c. */
3216 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3217
3218 Lisp_Object
3219 list_system_processes ()
3220 {
3221 return Qnil;
3222 }
3223
3224 #endif /* !defined (WINDOWSNT) */
3225
3226 #ifdef GNU_LINUX
3227 static void
3228 time_from_jiffies (unsigned long long tval, long hz,
3229 time_t *sec, unsigned *usec)
3230 {
3231 unsigned long long ullsec;
3232
3233 *sec = tval / hz;
3234 ullsec = *sec;
3235 tval -= ullsec * hz;
3236 /* Careful: if HZ > 1 million, then integer division by it yields zero. */
3237 if (hz <= 1000000)
3238 *usec = tval * 1000000 / hz;
3239 else
3240 *usec = tval / (hz / 1000000);
3241 }
3242
3243 static Lisp_Object
3244 ltime_from_jiffies (unsigned long long tval, long hz)
3245 {
3246 time_t sec;
3247 unsigned usec;
3248
3249 time_from_jiffies (tval, hz, &sec, &usec);
3250
3251 return list3 (make_number ((sec >> 16) & 0xffff),
3252 make_number (sec & 0xffff),
3253 make_number (usec));
3254 }
3255
3256 static void
3257 get_up_time (time_t *sec, unsigned *usec)
3258 {
3259 FILE *fup;
3260
3261 *sec = *usec = 0;
3262
3263 BLOCK_INPUT;
3264 fup = fopen ("/proc/uptime", "r");
3265
3266 if (fup)
3267 {
3268 double uptime, idletime;
3269
3270 /* The numbers in /proc/uptime use C-locale decimal point, but
3271 we already set ourselves to the C locale (see `fixup_locale'
3272 in emacs.c). */
3273 if (2 <= fscanf (fup, "%lf %lf", &uptime, &idletime))
3274 {
3275 *sec = uptime;
3276 *usec = (uptime - *sec) * 1000000;
3277 }
3278 fclose (fup);
3279 }
3280 UNBLOCK_INPUT;
3281 }
3282
3283 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3284 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3285
3286 static Lisp_Object
3287 procfs_ttyname (int rdev)
3288 {
3289 FILE *fdev = NULL;
3290 char name[PATH_MAX];
3291
3292 BLOCK_INPUT;
3293 fdev = fopen ("/proc/tty/drivers", "r");
3294
3295 if (fdev)
3296 {
3297 unsigned major;
3298 unsigned long minor_beg, minor_end;
3299 char minor[25]; /* 2 32-bit numbers + dash */
3300 char *endp;
3301
3302 while (!feof (fdev) && !ferror (fdev))
3303 {
3304 if (3 <= fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor)
3305 && major == MAJOR (rdev))
3306 {
3307 minor_beg = strtoul (minor, &endp, 0);
3308 if (*endp == '\0')
3309 minor_end = minor_beg;
3310 else if (*endp == '-')
3311 minor_end = strtoul (endp + 1, &endp, 0);
3312 else
3313 continue;
3314
3315 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3316 {
3317 sprintf (name + strlen (name), "%lu", MINOR (rdev));
3318 break;
3319 }
3320 }
3321 }
3322 fclose (fdev);
3323 }
3324 UNBLOCK_INPUT;
3325 return build_string (name);
3326 }
3327
3328 static unsigned long
3329 procfs_get_total_memory (void)
3330 {
3331 FILE *fmem = NULL;
3332 unsigned long retval = 2 * 1024 * 1024; /* default: 2GB */
3333
3334 BLOCK_INPUT;
3335 fmem = fopen ("/proc/meminfo", "r");
3336
3337 if (fmem)
3338 {
3339 unsigned long entry_value;
3340 char entry_name[20]; /* the longest I saw is 13+1 */
3341
3342 while (!feof (fmem) && !ferror (fmem))
3343 {
3344 if (2 <= fscanf (fmem, "%s %lu kB\n", entry_name, &entry_value)
3345 && strcmp (entry_name, "MemTotal:") == 0)
3346 {
3347 retval = entry_value;
3348 break;
3349 }
3350 }
3351 fclose (fmem);
3352 }
3353 UNBLOCK_INPUT;
3354 return retval;
3355 }
3356
3357 Lisp_Object
3358 system_process_attributes (Lisp_Object pid)
3359 {
3360 char procfn[PATH_MAX], fn[PATH_MAX];
3361 struct stat st;
3362 struct passwd *pw;
3363 struct group *gr;
3364 long clocks_per_sec;
3365 char *procfn_end;
3366 char procbuf[1025], *p, *q;
3367 int fd;
3368 ssize_t nread;
3369 const char *cmd = NULL;
3370 char *cmdline = NULL;
3371 size_t cmdsize = 0, cmdline_size;
3372 unsigned char c;
3373 int proc_id, ppid, uid, gid, pgrp, sess, tty, tpgid, thcount;
3374 unsigned long long utime, stime, cutime, cstime, start;
3375 long priority, nice, rss;
3376 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3377 time_t sec;
3378 unsigned usec;
3379 EMACS_TIME tnow, tstart, tboot, telapsed,ttotal;
3380 double pcpu, pmem;
3381 Lisp_Object attrs = Qnil;
3382 Lisp_Object cmd_str, decoded_cmd, tem;
3383 struct gcpro gcpro1, gcpro2;
3384 EMACS_INT uid_eint, gid_eint;
3385
3386 CHECK_NUMBER_OR_FLOAT (pid);
3387 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
3388 sprintf (procfn, "/proc/%lu", proc_id);
3389 if (stat (procfn, &st) < 0)
3390 return attrs;
3391
3392 GCPRO2 (attrs, decoded_cmd);
3393
3394 /* euid egid */
3395 uid = st.st_uid;
3396 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
3397 uid_eint = uid;
3398 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
3399 BLOCK_INPUT;
3400 pw = getpwuid (uid);
3401 UNBLOCK_INPUT;
3402 if (pw)
3403 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3404
3405 gid = st.st_gid;
3406 gid_eint = gid;
3407 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
3408 BLOCK_INPUT;
3409 gr = getgrgid (gid);
3410 UNBLOCK_INPUT;
3411 if (gr)
3412 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3413
3414 strcpy (fn, procfn);
3415 procfn_end = fn + strlen (fn);
3416 strcpy (procfn_end, "/stat");
3417 fd = emacs_open (fn, O_RDONLY, 0);
3418 if (fd >= 0 && (nread = emacs_read (fd, procbuf, sizeof(procbuf) - 1)) > 0)
3419 {
3420 procbuf[nread] = '\0';
3421 p = procbuf;
3422
3423 p = strchr (p, '(');
3424 if (p != NULL)
3425 {
3426 q = strrchr (p + 1, ')');
3427 /* comm */
3428 if (q != NULL)
3429 {
3430 cmd = p + 1;
3431 cmdsize = q - cmd;
3432 }
3433 }
3434 else
3435 q = NULL;
3436 if (cmd == NULL)
3437 {
3438 cmd = "???";
3439 cmdsize = 3;
3440 }
3441 /* Command name is encoded in locale-coding-system; decode it. */
3442 cmd_str = make_unibyte_string (cmd, cmdsize);
3443 decoded_cmd = code_convert_string_norecord (cmd_str,
3444 Vlocale_coding_system, 0);
3445 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3446
3447 if (q)
3448 {
3449 EMACS_INT ppid_eint, pgrp_eint, sess_eint, tpgid_eint, thcount_eint;
3450 p = q + 2;
3451 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt utime stime cutime cstime priority nice thcount . start vsize rss */
3452 sscanf (p, "%c %d %d %d %d %d %*u %lu %lu %lu %lu %Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld",
3453 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3454 &minflt, &cminflt, &majflt, &cmajflt,
3455 &utime, &stime, &cutime, &cstime,
3456 &priority, &nice, &thcount, &start, &vsize, &rss);
3457 {
3458 char state_str[2];
3459
3460 state_str[0] = c;
3461 state_str[1] = '\0';
3462 tem = build_string (state_str);
3463 attrs = Fcons (Fcons (Qstate, tem), attrs);
3464 }
3465 /* Stops GCC whining about limited range of data type. */
3466 ppid_eint = ppid;
3467 pgrp_eint = pgrp;
3468 sess_eint = sess;
3469 tpgid_eint = tpgid;
3470 thcount_eint = thcount;
3471 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid_eint)), attrs);
3472 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp_eint)), attrs);
3473 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess_eint)), attrs);
3474 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3475 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid_eint)), attrs);
3476 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3477 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3478 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)), attrs);
3479 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)), attrs);
3480 clocks_per_sec = sysconf (_SC_CLK_TCK);
3481 if (clocks_per_sec < 0)
3482 clocks_per_sec = 100;
3483 attrs = Fcons (Fcons (Qutime,
3484 ltime_from_jiffies (utime, clocks_per_sec)),
3485 attrs);
3486 attrs = Fcons (Fcons (Qstime,
3487 ltime_from_jiffies (stime, clocks_per_sec)),
3488 attrs);
3489 attrs = Fcons (Fcons (Qtime,
3490 ltime_from_jiffies (stime+utime, clocks_per_sec)),
3491 attrs);
3492 attrs = Fcons (Fcons (Qcutime,
3493 ltime_from_jiffies (cutime, clocks_per_sec)),
3494 attrs);
3495 attrs = Fcons (Fcons (Qcstime,
3496 ltime_from_jiffies (cstime, clocks_per_sec)),
3497 attrs);
3498 attrs = Fcons (Fcons (Qctime,
3499 ltime_from_jiffies (cstime+cutime, clocks_per_sec)),
3500 attrs);
3501 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3502 attrs = Fcons (Fcons (Qnice, make_number (nice)), attrs);
3503 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount_eint)), attrs);
3504 EMACS_GET_TIME (tnow);
3505 get_up_time (&sec, &usec);
3506 EMACS_SET_SECS (telapsed, sec);
3507 EMACS_SET_USECS (telapsed, usec);
3508 EMACS_SUB_TIME (tboot, tnow, telapsed);
3509 time_from_jiffies (start, clocks_per_sec, &sec, &usec);
3510 EMACS_SET_SECS (tstart, sec);
3511 EMACS_SET_USECS (tstart, usec);
3512 EMACS_ADD_TIME (tstart, tboot, tstart);
3513 attrs = Fcons (Fcons (Qstart,
3514 list3 (make_number
3515 ((EMACS_SECS (tstart) >> 16) & 0xffff),
3516 make_number
3517 (EMACS_SECS (tstart) & 0xffff),
3518 make_number
3519 (EMACS_USECS (tstart)))),
3520 attrs);
3521 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize/1024)), attrs);
3522 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4*rss)), attrs);
3523 EMACS_SUB_TIME (telapsed, tnow, tstart);
3524 attrs = Fcons (Fcons (Qetime,
3525 list3 (make_number
3526 ((EMACS_SECS (telapsed) >> 16) & 0xffff),
3527 make_number
3528 (EMACS_SECS (telapsed) & 0xffff),
3529 make_number
3530 (EMACS_USECS (telapsed)))),
3531 attrs);
3532 time_from_jiffies (utime + stime, clocks_per_sec, &sec, &usec);
3533 pcpu = (sec + usec / 1000000.0) / (EMACS_SECS (telapsed) + EMACS_USECS (telapsed) / 1000000.0);
3534 if (pcpu > 1.0)
3535 pcpu = 1.0;
3536 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3537 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3538 if (pmem > 100)
3539 pmem = 100;
3540 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3541 }
3542 }
3543 if (fd >= 0)
3544 emacs_close (fd);
3545
3546 /* args */
3547 strcpy (procfn_end, "/cmdline");
3548 fd = emacs_open (fn, O_RDONLY, 0);
3549 if (fd >= 0)
3550 {
3551 for (cmdline_size = 0; emacs_read (fd, &c, 1) == 1; cmdline_size++)
3552 {
3553 if (isspace (c) || c == '\\')
3554 cmdline_size++; /* for later quoting, see below */
3555 }
3556 if (cmdline_size)
3557 {
3558 cmdline = xmalloc (cmdline_size + 1);
3559 lseek (fd, 0L, SEEK_SET);
3560 cmdline[0] = '\0';
3561 if ((nread = read (fd, cmdline, cmdline_size)) >= 0)
3562 cmdline[nread++] = '\0';
3563 else
3564 {
3565 /* Assigning zero to `nread' makes us skip the following
3566 two loops, assign zero to cmdline_size, and enter the
3567 following `if' clause that handles unknown command
3568 lines. */
3569 nread = 0;
3570 }
3571 /* We don't want trailing null characters. */
3572 for (p = cmdline + nread - 1; p > cmdline && !*p; p--)
3573 nread--;
3574 for (p = cmdline; p < cmdline + nread; p++)
3575 {
3576 /* Escape-quote whitespace and backslashes. */
3577 if (isspace (*p) || *p == '\\')
3578 {
3579 memmove (p + 1, p, nread - (p - cmdline));
3580 nread++;
3581 *p++ = '\\';
3582 }
3583 else if (*p == '\0')
3584 *p = ' ';
3585 }
3586 cmdline_size = nread;
3587 }
3588 if (!cmdline_size)
3589 {
3590 if (!cmd)
3591 cmd = "???";
3592 if (!cmdsize)
3593 cmdsize = strlen (cmd);
3594 cmdline_size = cmdsize + 2;
3595 cmdline = xmalloc (cmdline_size + 1);
3596 strcpy (cmdline, "[");
3597 strcat (strncat (cmdline, cmd, cmdsize), "]");
3598 }
3599 emacs_close (fd);
3600 /* Command line is encoded in locale-coding-system; decode it. */
3601 cmd_str = make_unibyte_string (cmdline, cmdline_size);
3602 decoded_cmd = code_convert_string_norecord (cmd_str,
3603 Vlocale_coding_system, 0);
3604 xfree (cmdline);
3605 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3606 }
3607
3608 UNGCPRO;
3609 return attrs;
3610 }
3611
3612 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3613
3614 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3615 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3616 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3617 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3618 #undef _FILE_OFFSET_BITS
3619 #else
3620 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3621 #endif
3622
3623 #include <procfs.h>
3624
3625 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3626 #define _FILE_OFFSET_BITS 64
3627 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3628
3629 Lisp_Object
3630 system_process_attributes (Lisp_Object pid)
3631 {
3632 char procfn[PATH_MAX], fn[PATH_MAX];
3633 struct stat st;
3634 struct passwd *pw;
3635 struct group *gr;
3636 char *procfn_end;
3637 struct psinfo pinfo;
3638 int fd;
3639 ssize_t nread;
3640 int proc_id, uid, gid;
3641 Lisp_Object attrs = Qnil;
3642 Lisp_Object decoded_cmd, tem;
3643 struct gcpro gcpro1, gcpro2;
3644 EMACS_INT uid_eint, gid_eint;
3645
3646 CHECK_NUMBER_OR_FLOAT (pid);
3647 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
3648 sprintf (procfn, "/proc/%u", proc_id);
3649 if (stat (procfn, &st) < 0)
3650 return attrs;
3651
3652 GCPRO2 (attrs, decoded_cmd);
3653
3654 /* euid egid */
3655 uid = st.st_uid;
3656 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
3657 uid_eint = uid;
3658 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
3659 BLOCK_INPUT;
3660 pw = getpwuid (uid);
3661 UNBLOCK_INPUT;
3662 if (pw)
3663 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3664
3665 gid = st.st_gid;
3666 gid_eint = gid;
3667 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
3668 BLOCK_INPUT;
3669 gr = getgrgid (gid);
3670 UNBLOCK_INPUT;
3671 if (gr)
3672 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3673
3674 strcpy (fn, procfn);
3675 procfn_end = fn + strlen (fn);
3676 strcpy (procfn_end, "/psinfo");
3677 fd = emacs_open (fn, O_RDONLY, 0);
3678 if (fd >= 0
3679 && (nread = read (fd, (char*)&pinfo, sizeof(struct psinfo)) > 0))
3680 {
3681 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3682 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3683 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3684
3685 {
3686 char state_str[2];
3687 state_str[0] = pinfo.pr_lwp.pr_sname;
3688 state_str[1] = '\0';
3689 tem = build_string (state_str);
3690 attrs = Fcons (Fcons (Qstate, tem), attrs);
3691 }
3692
3693 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3694 need to get a string from it. */
3695
3696 /* FIXME: missing: Qtpgid */
3697
3698 /* FIXME: missing:
3699 Qminflt
3700 Qmajflt
3701 Qcminflt
3702 Qcmajflt
3703
3704 Qutime
3705 Qcutime
3706 Qstime
3707 Qcstime
3708 Are they available? */
3709
3710 attrs = Fcons (Fcons (Qtime,
3711 list3 (make_number (pinfo.pr_time.tv_sec >> 16),
3712 make_number (pinfo.pr_time.tv_sec & 0xffff),
3713 make_number (pinfo.pr_time.tv_nsec))),
3714 attrs);
3715
3716 attrs = Fcons (Fcons (Qctime,
3717 list3 (make_number (pinfo.pr_ctime.tv_sec >> 16),
3718 make_number (pinfo.pr_ctime.tv_sec & 0xffff),
3719 make_number (pinfo.pr_ctime.tv_nsec))),
3720 attrs);
3721
3722 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3723 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3724 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)), attrs);
3725
3726 attrs = Fcons (Fcons (Qstart,
3727 list3 (make_number (pinfo.pr_start.tv_sec >> 16),
3728 make_number (pinfo.pr_start.tv_sec & 0xffff),
3729 make_number (pinfo.pr_start.tv_nsec))),
3730 attrs);
3731 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)), attrs);
3732 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)), attrs);
3733
3734 /* pr_pctcpu and pr_pctmem are encoded as a fixed point 16 bit number in [0 ... 1]. */
3735 attrs = Fcons (Fcons (Qpcpu, (pinfo.pr_pctcpu * 100.0) / (double)0x8000), attrs);
3736 attrs = Fcons (Fcons (Qpmem, (pinfo.pr_pctmem * 100.0) / (double)0x8000), attrs);
3737
3738 decoded_cmd
3739 = code_convert_string_norecord (make_unibyte_string (pinfo.pr_fname,
3740 strlen (pinfo.pr_fname)),
3741 Vlocale_coding_system, 0);
3742 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3743 decoded_cmd
3744 = code_convert_string_norecord (make_unibyte_string (pinfo.pr_psargs,
3745 strlen (pinfo.pr_psargs)),
3746 Vlocale_coding_system, 0);
3747 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3748 }
3749
3750 if (fd >= 0)
3751 emacs_close (fd);
3752
3753 UNGCPRO;
3754 return attrs;
3755 }
3756
3757 /* The WINDOWSNT implementation is on w32.c.
3758 The MSDOS implementation is on dosfns.c. */
3759 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3760
3761 Lisp_Object
3762 system_process_attributes (Lisp_Object pid)
3763 {
3764 return Qnil;
3765 }
3766
3767 #endif /* !defined (WINDOWSNT) */
3768
3769
3770 /* arch-tag: edb43589-4e09-4544-b325-978b5b121dcf
3771 (do not change this comment) */