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