Remove spurious semicolons.
[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, 2009
4 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <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 process_pending_signals ();
2543 #endif
2544 continue;
2545 }
2546 else
2547 return (bytes_written ? bytes_written : -1);
2548 }
2549
2550 buf += rtnval;
2551 nbyte -= rtnval;
2552 bytes_written += rtnval;
2553 }
2554 return (bytes_written);
2555 }
2556 \f
2557 #ifdef USG
2558 /*
2559 * All of the following are for USG.
2560 *
2561 * On USG systems the system calls are INTERRUPTIBLE by signals
2562 * that the user program has elected to catch. Thus the system call
2563 * must be retried in these cases. To handle this without massive
2564 * changes in the source code, we remap the standard system call names
2565 * to names for our own functions in sysdep.c that do the system call
2566 * with retries. Actually, for portability reasons, it is good
2567 * programming practice, as this example shows, to limit all actual
2568 * system calls to a single occurrence in the source. Sure, this
2569 * adds an extra level of function call overhead but it is almost
2570 * always negligible. Fred Fish, Unisoft Systems Inc.
2571 */
2572
2573 /*
2574 * Warning, this function may not duplicate 4.2 action properly
2575 * under error conditions.
2576 */
2577
2578 #ifndef MAXPATHLEN
2579 /* In 4.1, param.h fails to define this. */
2580 #define MAXPATHLEN 1024
2581 #endif
2582
2583 #ifndef HAVE_GETWD
2584
2585 char *
2586 getwd (pathname)
2587 char *pathname;
2588 {
2589 char *npath, *spath;
2590 extern char *getcwd ();
2591
2592 BLOCK_INPUT; /* getcwd uses malloc */
2593 spath = npath = getcwd ((char *) 0, MAXPATHLEN);
2594 if (spath == 0)
2595 {
2596 UNBLOCK_INPUT;
2597 return spath;
2598 }
2599 /* On Altos 3068, getcwd can return @hostname/dir, so discard
2600 up to first slash. Should be harmless on other systems. */
2601 while (*npath && *npath != '/')
2602 npath++;
2603 strcpy (pathname, npath);
2604 free (spath); /* getcwd uses malloc */
2605 UNBLOCK_INPUT;
2606 return pathname;
2607 }
2608
2609 #endif /* HAVE_GETWD */
2610
2611 /*
2612 * Emulate rename using unlink/link. Note that this is
2613 * only partially correct. Also, doesn't enforce restriction
2614 * that files be of same type (regular->regular, dir->dir, etc).
2615 */
2616
2617 #ifndef HAVE_RENAME
2618
2619 rename (from, to)
2620 const char *from;
2621 const char *to;
2622 {
2623 if (access (from, 0) == 0)
2624 {
2625 unlink (to);
2626 if (link (from, to) == 0)
2627 if (unlink (from) == 0)
2628 return (0);
2629 }
2630 return (-1);
2631 }
2632
2633 #endif
2634
2635
2636 #if defined(HPUX) && !defined(HAVE_PERROR)
2637
2638 /* HPUX curses library references perror, but as far as we know
2639 it won't be called. Anyway this definition will do for now. */
2640
2641 perror ()
2642 {
2643 }
2644 #endif /* HPUX and not HAVE_PERROR */
2645
2646 #ifndef HAVE_DUP2
2647
2648 /*
2649 * Emulate BSD dup2. First close newd if it already exists.
2650 * Then, attempt to dup oldd. If not successful, call dup2 recursively
2651 * until we are, then close the unsuccessful ones.
2652 */
2653
2654 dup2 (oldd, newd)
2655 int oldd;
2656 int newd;
2657 {
2658 register int fd, ret;
2659
2660 emacs_close (newd);
2661
2662 #ifdef F_DUPFD
2663 return fcntl (oldd, F_DUPFD, newd);
2664 #else
2665 fd = dup (old);
2666 if (fd == -1)
2667 return -1;
2668 if (fd == new)
2669 return new;
2670 ret = dup2 (old,new);
2671 emacs_close (fd);
2672 return ret;
2673 #endif
2674 }
2675
2676 #endif /* not HAVE_DUP2 */
2677
2678 /*
2679 * Gettimeofday. Simulate as much as possible. Only accurate
2680 * to nearest second. Emacs doesn't use tzp so ignore it for now.
2681 * Only needed when subprocesses are defined.
2682 */
2683
2684 #ifdef subprocesses
2685 #ifndef HAVE_GETTIMEOFDAY
2686 #ifdef HAVE_TIMEVAL
2687
2688 /* ARGSUSED */
2689 int
2690 gettimeofday (tp, tzp)
2691 struct timeval *tp;
2692 struct timezone *tzp;
2693 {
2694 extern long time ();
2695
2696 tp->tv_sec = time ((long *)0);
2697 tp->tv_usec = 0;
2698 if (tzp != 0)
2699 tzp->tz_minuteswest = -1;
2700 return 0;
2701 }
2702
2703 #endif
2704 #endif
2705 #endif /* subprocess && !HAVE_GETTIMEOFDAY && HAVE_TIMEVAL */
2706
2707 /*
2708 * This function will go away as soon as all the stubs fixed. (fnf)
2709 */
2710
2711 void
2712 croak (badfunc)
2713 char *badfunc;
2714 {
2715 printf ("%s not yet implemented\r\n", badfunc);
2716 reset_all_sys_modes ();
2717 exit (1);
2718 }
2719
2720 #endif /* USG */
2721 \f
2722 /* Directory routines for systems that don't have them. */
2723
2724 #ifdef SYSV_SYSTEM_DIR
2725
2726 #include <dirent.h>
2727
2728 #if !defined (HAVE_CLOSEDIR)
2729
2730 int
2731 closedir (DIR *dirp /* stream from opendir */)
2732 {
2733 int rtnval;
2734
2735 rtnval = emacs_close (dirp->dd_fd);
2736
2737 /* Some systems (like Solaris) allocate the buffer and the DIR all
2738 in one block. Why in the world are we freeing this ourselves
2739 anyway? */
2740 #if ! defined (SOLARIS2)
2741 xfree ((char *) dirp->dd_buf); /* directory block defined in <dirent.h> */
2742 #endif
2743 xfree ((char *) dirp);
2744
2745 return rtnval;
2746 }
2747 #endif /* not HAVE_CLOSEDIR */
2748 #endif /* SYSV_SYSTEM_DIR */
2749
2750 \f
2751 int
2752 set_file_times (filename, atime, mtime)
2753 const char *filename;
2754 EMACS_TIME atime, mtime;
2755 {
2756 #ifdef HAVE_UTIMES
2757 struct timeval tv[2];
2758 tv[0] = atime;
2759 tv[1] = mtime;
2760 return utimes (filename, tv);
2761 #else /* not HAVE_UTIMES */
2762 struct utimbuf utb;
2763 utb.actime = EMACS_SECS (atime);
2764 utb.modtime = EMACS_SECS (mtime);
2765 return utime (filename, &utb);
2766 #endif /* not HAVE_UTIMES */
2767 }
2768 \f
2769 /* mkdir and rmdir functions, for systems which don't have them. */
2770
2771 #ifndef HAVE_MKDIR
2772 /*
2773 * Written by Robert Rother, Mariah Corporation, August 1985.
2774 *
2775 * If you want it, it's yours. All I ask in return is that if you
2776 * figure out how to do this in a Bourne Shell script you send me
2777 * a copy.
2778 * sdcsvax!rmr or rmr@uscd
2779 *
2780 * Severely hacked over by John Gilmore to make a 4.2BSD compatible
2781 * subroutine. 11Mar86; hoptoad!gnu
2782 *
2783 * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
2784 * subroutine didn't return EEXIST. It does now.
2785 */
2786
2787 /*
2788 * Make a directory.
2789 */
2790 #ifdef MKDIR_PROTOTYPE
2791 MKDIR_PROTOTYPE
2792 #else
2793 int
2794 mkdir (dpath, dmode)
2795 char *dpath;
2796 int dmode;
2797 #endif
2798 {
2799 int cpid, status, fd;
2800 struct stat statbuf;
2801
2802 if (stat (dpath, &statbuf) == 0)
2803 {
2804 errno = EEXIST; /* Stat worked, so it already exists */
2805 return -1;
2806 }
2807
2808 /* If stat fails for a reason other than non-existence, return error */
2809 if (errno != ENOENT)
2810 return -1;
2811
2812 synch_process_alive = 1;
2813 switch (cpid = fork ())
2814 {
2815
2816 case -1: /* Error in fork */
2817 return (-1); /* Errno is set already */
2818
2819 case 0: /* Child process */
2820 /*
2821 * Cheap hack to set mode of new directory. Since this
2822 * child process is going away anyway, we zap its umask.
2823 * FIXME, this won't suffice to set SUID, SGID, etc. on this
2824 * directory. Does anybody care?
2825 */
2826 status = umask (0); /* Get current umask */
2827 status = umask (status | (0777 & ~dmode)); /* Set for mkdir */
2828 fd = emacs_open ("/dev/null", O_RDWR, 0);
2829 if (fd >= 0)
2830 {
2831 dup2 (fd, 0);
2832 dup2 (fd, 1);
2833 dup2 (fd, 2);
2834 }
2835 execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
2836 _exit (-1); /* Can't exec /bin/mkdir */
2837
2838 default: /* Parent process */
2839 wait_for_termination (cpid);
2840 }
2841
2842 if (synch_process_death != 0 || synch_process_retcode != 0
2843 || synch_process_termsig != 0)
2844 {
2845 errno = EIO; /* We don't know why, but */
2846 return -1; /* /bin/mkdir failed */
2847 }
2848
2849 return 0;
2850 }
2851 #endif /* not HAVE_MKDIR */
2852
2853 #ifndef HAVE_RMDIR
2854 int
2855 rmdir (dpath)
2856 char *dpath;
2857 {
2858 int cpid, status, fd;
2859 struct stat statbuf;
2860
2861 if (stat (dpath, &statbuf) != 0)
2862 {
2863 /* Stat just set errno. We don't have to */
2864 return -1;
2865 }
2866
2867 synch_process_alive = 1;
2868 switch (cpid = fork ())
2869 {
2870
2871 case -1: /* Error in fork */
2872 return (-1); /* Errno is set already */
2873
2874 case 0: /* Child process */
2875 fd = emacs_open ("/dev/null", O_RDWR, 0);
2876 if (fd >= 0)
2877 {
2878 dup2 (fd, 0);
2879 dup2 (fd, 1);
2880 dup2 (fd, 2);
2881 }
2882 execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
2883 _exit (-1); /* Can't exec /bin/rmdir */
2884
2885 default: /* Parent process */
2886 wait_for_termination (cpid);
2887 }
2888
2889 if (synch_process_death != 0 || synch_process_retcode != 0
2890 || synch_process_termsig != 0)
2891 {
2892 errno = EIO; /* We don't know why, but */
2893 return -1; /* /bin/rmdir failed */
2894 }
2895
2896 return 0;
2897 }
2898 #endif /* !HAVE_RMDIR */
2899
2900 \f
2901 #ifndef BSTRING
2902
2903 #ifndef bzero
2904
2905 void
2906 bzero (b, length)
2907 register char *b;
2908 register int length;
2909 {
2910 while (length-- > 0)
2911 *b++ = 0;
2912 }
2913
2914 #endif /* no bzero */
2915 #endif /* BSTRING */
2916
2917 #if (!defined (BSTRING) && !defined (bcopy)) || defined (NEED_BCOPY)
2918 #undef bcopy
2919
2920 /* Saying `void' requires a declaration, above, where bcopy is used
2921 and that declaration causes pain for systems where bcopy is a macro. */
2922 bcopy (b1, b2, length)
2923 register char *b1;
2924 register char *b2;
2925 register int length;
2926 {
2927 while (length-- > 0)
2928 *b2++ = *b1++;
2929 }
2930 #endif /* (!defined (BSTRING) && !defined (bcopy)) || defined (NEED_BCOPY) */
2931
2932 #ifndef BSTRING
2933 #ifndef bcmp
2934 int
2935 bcmp (b1, b2, length) /* This could be a macro! */
2936 register char *b1;
2937 register char *b2;
2938 register int length;
2939 {
2940 while (length-- > 0)
2941 if (*b1++ != *b2++)
2942 return 1;
2943
2944 return 0;
2945 }
2946 #endif /* no bcmp */
2947 #endif /* not BSTRING */
2948 \f
2949 #ifndef HAVE_STRSIGNAL
2950 char *
2951 strsignal (code)
2952 int code;
2953 {
2954 char *signame = 0;
2955
2956 if (0 <= code && code < NSIG)
2957 {
2958 /* Cast to suppress warning if the table has const char *. */
2959 signame = (char *) sys_siglist[code];
2960 }
2961
2962 return signame;
2963 }
2964 #endif /* HAVE_STRSIGNAL */
2965 \f
2966 #ifdef HAVE_TERMIOS
2967 /* For make-serial-process */
2968 int serial_open (char *port)
2969 {
2970 int fd = -1;
2971
2972 fd = emacs_open ((char*) port,
2973 O_RDWR
2974 #ifdef O_NONBLOCK
2975 | O_NONBLOCK
2976 #else
2977 | O_NDELAY
2978 #endif
2979 #ifdef O_NOCTTY
2980 | O_NOCTTY
2981 #endif
2982 , 0);
2983 if (fd < 0)
2984 {
2985 error ("Could not open %s: %s",
2986 port, emacs_strerror (errno));
2987 }
2988 #ifdef TIOCEXCL
2989 ioctl (fd, TIOCEXCL, (char *) 0);
2990 #endif
2991
2992 return fd;
2993 }
2994 #endif /* TERMIOS */
2995
2996 #ifdef HAVE_TERMIOS
2997
2998 #if !defined (HAVE_CFMAKERAW)
2999 /* Workaround for targets which are missing cfmakeraw. */
3000 /* Pasted from man page. */
3001 static void cfmakeraw (struct termios *termios_p)
3002 {
3003 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
3004 termios_p->c_oflag &= ~OPOST;
3005 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
3006 termios_p->c_cflag &= ~(CSIZE|PARENB);
3007 termios_p->c_cflag |= CS8;
3008 }
3009 #endif /* !defined (HAVE_CFMAKERAW */
3010
3011 #if !defined (HAVE_CFSETSPEED)
3012 /* Workaround for targets which are missing cfsetspeed. */
3013 static int cfsetspeed (struct termios *termios_p, speed_t vitesse)
3014 {
3015 return (cfsetispeed (termios_p, vitesse)
3016 + cfsetospeed (termios_p, vitesse));
3017 }
3018 #endif
3019
3020 /* For serial-process-configure */
3021 void
3022 serial_configure (struct Lisp_Process *p,
3023 Lisp_Object contact)
3024 {
3025 Lisp_Object childp2 = Qnil;
3026 Lisp_Object tem = Qnil;
3027 struct termios attr;
3028 int err = -1;
3029 char summary[4] = "???"; /* This usually becomes "8N1". */
3030
3031 childp2 = Fcopy_sequence (p->childp);
3032
3033 /* Read port attributes and prepare default configuration. */
3034 err = tcgetattr (p->outfd, &attr);
3035 if (err != 0)
3036 error ("tcgetattr() failed: %s", emacs_strerror (errno));
3037 cfmakeraw (&attr);
3038 #if defined (CLOCAL)
3039 attr.c_cflag |= CLOCAL;
3040 #endif
3041 #if defined (CREAD)
3042 attr.c_cflag |= CREAD;
3043 #endif
3044
3045 /* Configure speed. */
3046 if (!NILP (Fplist_member (contact, QCspeed)))
3047 tem = Fplist_get (contact, QCspeed);
3048 else
3049 tem = Fplist_get (p->childp, QCspeed);
3050 CHECK_NUMBER (tem);
3051 err = cfsetspeed (&attr, XINT (tem));
3052 if (err != 0)
3053 error ("cfsetspeed(%d) failed: %s", XINT (tem), emacs_strerror (errno));
3054 childp2 = Fplist_put (childp2, QCspeed, tem);
3055
3056 /* Configure bytesize. */
3057 if (!NILP (Fplist_member (contact, QCbytesize)))
3058 tem = Fplist_get (contact, QCbytesize);
3059 else
3060 tem = Fplist_get (p->childp, QCbytesize);
3061 if (NILP (tem))
3062 tem = make_number (8);
3063 CHECK_NUMBER (tem);
3064 if (XINT (tem) != 7 && XINT (tem) != 8)
3065 error (":bytesize must be nil (8), 7, or 8");
3066 summary[0] = XINT(tem) + '0';
3067 #if defined (CSIZE) && defined (CS7) && defined (CS8)
3068 attr.c_cflag &= ~CSIZE;
3069 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
3070 #else
3071 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
3072 if (XINT (tem) != 8)
3073 error ("Bytesize cannot be changed");
3074 #endif
3075 childp2 = Fplist_put (childp2, QCbytesize, tem);
3076
3077 /* Configure parity. */
3078 if (!NILP (Fplist_member (contact, QCparity)))
3079 tem = Fplist_get (contact, QCparity);
3080 else
3081 tem = Fplist_get (p->childp, QCparity);
3082 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
3083 error (":parity must be nil (no parity), `even', or `odd'");
3084 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
3085 attr.c_cflag &= ~(PARENB | PARODD);
3086 attr.c_iflag &= ~(IGNPAR | INPCK);
3087 if (NILP (tem))
3088 {
3089 summary[1] = 'N';
3090 }
3091 else if (EQ (tem, Qeven))
3092 {
3093 summary[1] = 'E';
3094 attr.c_cflag |= PARENB;
3095 attr.c_iflag |= (IGNPAR | INPCK);
3096 }
3097 else if (EQ (tem, Qodd))
3098 {
3099 summary[1] = 'O';
3100 attr.c_cflag |= (PARENB | PARODD);
3101 attr.c_iflag |= (IGNPAR | INPCK);
3102 }
3103 #else
3104 /* Don't error on no parity, which should be set by cfmakeraw. */
3105 if (!NILP (tem))
3106 error ("Parity cannot be configured");
3107 #endif
3108 childp2 = Fplist_put (childp2, QCparity, tem);
3109
3110 /* Configure stopbits. */
3111 if (!NILP (Fplist_member (contact, QCstopbits)))
3112 tem = Fplist_get (contact, QCstopbits);
3113 else
3114 tem = Fplist_get (p->childp, QCstopbits);
3115 if (NILP (tem))
3116 tem = make_number (1);
3117 CHECK_NUMBER (tem);
3118 if (XINT (tem) != 1 && XINT (tem) != 2)
3119 error (":stopbits must be nil (1 stopbit), 1, or 2");
3120 summary[2] = XINT (tem) + '0';
3121 #if defined (CSTOPB)
3122 attr.c_cflag &= ~CSTOPB;
3123 if (XINT (tem) == 2)
3124 attr.c_cflag |= CSTOPB;
3125 #else
3126 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
3127 if (XINT (tem) != 1)
3128 error ("Stopbits cannot be configured");
3129 #endif
3130 childp2 = Fplist_put (childp2, QCstopbits, tem);
3131
3132 /* Configure flowcontrol. */
3133 if (!NILP (Fplist_member (contact, QCflowcontrol)))
3134 tem = Fplist_get (contact, QCflowcontrol);
3135 else
3136 tem = Fplist_get (p->childp, QCflowcontrol);
3137 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
3138 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
3139 #if defined (CRTSCTS)
3140 attr.c_cflag &= ~CRTSCTS;
3141 #endif
3142 #if defined (CNEW_RTSCTS)
3143 attr.c_cflag &= ~CNEW_RTSCTS;
3144 #endif
3145 #if defined (IXON) && defined (IXOFF)
3146 attr.c_iflag &= ~(IXON | IXOFF);
3147 #endif
3148 if (NILP (tem))
3149 {
3150 /* Already configured. */
3151 }
3152 else if (EQ (tem, Qhw))
3153 {
3154 #if defined (CRTSCTS)
3155 attr.c_cflag |= CRTSCTS;
3156 #elif defined (CNEW_RTSCTS)
3157 attr.c_cflag |= CNEW_RTSCTS;
3158 #else
3159 error ("Hardware flowcontrol (RTS/CTS) not supported");
3160 #endif
3161 }
3162 else if (EQ (tem, Qsw))
3163 {
3164 #if defined (IXON) && defined (IXOFF)
3165 attr.c_iflag |= (IXON | IXOFF);
3166 #else
3167 error ("Software flowcontrol (XON/XOFF) not supported");
3168 #endif
3169 }
3170 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
3171
3172 /* Activate configuration. */
3173 err = tcsetattr (p->outfd, TCSANOW, &attr);
3174 if (err != 0)
3175 error ("tcsetattr() failed: %s", emacs_strerror (errno));
3176
3177 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
3178 p->childp = childp2;
3179
3180 }
3181 #endif /* TERMIOS */
3182 \f
3183 /* System depended enumeration of and access to system processes a-la ps(1). */
3184
3185 #ifdef HAVE_PROCFS
3186
3187 /* Process enumeration and access via /proc. */
3188
3189 Lisp_Object
3190 list_system_processes ()
3191 {
3192 Lisp_Object procdir, match, proclist, next;
3193 struct gcpro gcpro1, gcpro2;
3194 register Lisp_Object tail;
3195
3196 GCPRO2 (procdir, match);
3197 /* For every process on the system, there's a directory in the
3198 "/proc" pseudo-directory whose name is the numeric ID of that
3199 process. */
3200 procdir = build_string ("/proc");
3201 match = build_string ("[0-9]+");
3202 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
3203
3204 /* `proclist' gives process IDs as strings. Destructively convert
3205 each string into a number. */
3206 for (tail = proclist; CONSP (tail); tail = next)
3207 {
3208 next = XCDR (tail);
3209 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
3210 }
3211 UNGCPRO;
3212
3213 /* directory_files_internal returns the files in reverse order; undo
3214 that. */
3215 proclist = Fnreverse (proclist);
3216 return proclist;
3217 }
3218
3219 /* The WINDOWSNT implementation is on w32.c.
3220 The MSDOS implementation is on dosfns.c. */
3221 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3222
3223 Lisp_Object
3224 list_system_processes ()
3225 {
3226 return Qnil;
3227 }
3228
3229 #endif /* !defined (WINDOWSNT) */
3230
3231 #ifdef GNU_LINUX
3232 static void
3233 time_from_jiffies (unsigned long long tval, long hz,
3234 time_t *sec, unsigned *usec)
3235 {
3236 unsigned long long ullsec;
3237
3238 *sec = tval / hz;
3239 ullsec = *sec;
3240 tval -= ullsec * hz;
3241 /* Careful: if HZ > 1 million, then integer division by it yields zero. */
3242 if (hz <= 1000000)
3243 *usec = tval * 1000000 / hz;
3244 else
3245 *usec = tval / (hz / 1000000);
3246 }
3247
3248 static Lisp_Object
3249 ltime_from_jiffies (unsigned long long tval, long hz)
3250 {
3251 time_t sec;
3252 unsigned usec;
3253
3254 time_from_jiffies (tval, hz, &sec, &usec);
3255
3256 return list3 (make_number ((sec >> 16) & 0xffff),
3257 make_number (sec & 0xffff),
3258 make_number (usec));
3259 }
3260
3261 static void
3262 get_up_time (time_t *sec, unsigned *usec)
3263 {
3264 FILE *fup;
3265
3266 *sec = *usec = 0;
3267
3268 BLOCK_INPUT;
3269 fup = fopen ("/proc/uptime", "r");
3270
3271 if (fup)
3272 {
3273 double uptime, idletime;
3274
3275 /* The numbers in /proc/uptime use C-locale decimal point, but
3276 we already set ourselves to the C locale (see `fixup_locale'
3277 in emacs.c). */
3278 if (2 <= fscanf (fup, "%lf %lf", &uptime, &idletime))
3279 {
3280 *sec = uptime;
3281 *usec = (uptime - *sec) * 1000000;
3282 }
3283 fclose (fup);
3284 }
3285 UNBLOCK_INPUT;
3286 }
3287
3288 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
3289 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
3290
3291 static Lisp_Object
3292 procfs_ttyname (int rdev)
3293 {
3294 FILE *fdev = NULL;
3295 char name[PATH_MAX];
3296
3297 BLOCK_INPUT;
3298 fdev = fopen ("/proc/tty/drivers", "r");
3299
3300 if (fdev)
3301 {
3302 unsigned major;
3303 unsigned long minor_beg, minor_end;
3304 char minor[25]; /* 2 32-bit numbers + dash */
3305 char *endp;
3306
3307 while (!feof (fdev) && !ferror (fdev))
3308 {
3309 if (3 <= fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor)
3310 && major == MAJOR (rdev))
3311 {
3312 minor_beg = strtoul (minor, &endp, 0);
3313 if (*endp == '\0')
3314 minor_end = minor_beg;
3315 else if (*endp == '-')
3316 minor_end = strtoul (endp + 1, &endp, 0);
3317 else
3318 continue;
3319
3320 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
3321 {
3322 sprintf (name + strlen (name), "%lu", MINOR (rdev));
3323 break;
3324 }
3325 }
3326 }
3327 fclose (fdev);
3328 }
3329 UNBLOCK_INPUT;
3330 return build_string (name);
3331 }
3332
3333 static unsigned long
3334 procfs_get_total_memory (void)
3335 {
3336 FILE *fmem = NULL;
3337 unsigned long retval = 2 * 1024 * 1024; /* default: 2GB */
3338
3339 BLOCK_INPUT;
3340 fmem = fopen ("/proc/meminfo", "r");
3341
3342 if (fmem)
3343 {
3344 unsigned long entry_value;
3345 char entry_name[20]; /* the longest I saw is 13+1 */
3346
3347 while (!feof (fmem) && !ferror (fmem))
3348 {
3349 if (2 <= fscanf (fmem, "%s %lu kB\n", entry_name, &entry_value)
3350 && strcmp (entry_name, "MemTotal:") == 0)
3351 {
3352 retval = entry_value;
3353 break;
3354 }
3355 }
3356 fclose (fmem);
3357 }
3358 UNBLOCK_INPUT;
3359 return retval;
3360 }
3361
3362 Lisp_Object
3363 system_process_attributes (Lisp_Object pid)
3364 {
3365 char procfn[PATH_MAX], fn[PATH_MAX];
3366 struct stat st;
3367 struct passwd *pw;
3368 struct group *gr;
3369 long clocks_per_sec;
3370 char *procfn_end;
3371 char procbuf[1025], *p, *q;
3372 int fd;
3373 ssize_t nread;
3374 const char *cmd = NULL;
3375 char *cmdline = NULL;
3376 size_t cmdsize = 0, cmdline_size;
3377 unsigned char c;
3378 int proc_id, ppid, uid, gid, pgrp, sess, tty, tpgid, thcount;
3379 unsigned long long utime, stime, cutime, cstime, start;
3380 long priority, nice, rss;
3381 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
3382 time_t sec;
3383 unsigned usec;
3384 EMACS_TIME tnow, tstart, tboot, telapsed,ttotal;
3385 double pcpu, pmem;
3386 Lisp_Object attrs = Qnil;
3387 Lisp_Object cmd_str, decoded_cmd, tem;
3388 struct gcpro gcpro1, gcpro2;
3389 EMACS_INT uid_eint, gid_eint;
3390
3391 CHECK_NUMBER_OR_FLOAT (pid);
3392 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
3393 sprintf (procfn, "/proc/%lu", proc_id);
3394 if (stat (procfn, &st) < 0)
3395 return attrs;
3396
3397 GCPRO2 (attrs, decoded_cmd);
3398
3399 /* euid egid */
3400 uid = st.st_uid;
3401 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
3402 uid_eint = uid;
3403 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
3404 BLOCK_INPUT;
3405 pw = getpwuid (uid);
3406 UNBLOCK_INPUT;
3407 if (pw)
3408 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3409
3410 gid = st.st_gid;
3411 gid_eint = gid;
3412 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
3413 BLOCK_INPUT;
3414 gr = getgrgid (gid);
3415 UNBLOCK_INPUT;
3416 if (gr)
3417 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3418
3419 strcpy (fn, procfn);
3420 procfn_end = fn + strlen (fn);
3421 strcpy (procfn_end, "/stat");
3422 fd = emacs_open (fn, O_RDONLY, 0);
3423 if (fd >= 0 && (nread = emacs_read (fd, procbuf, sizeof(procbuf) - 1)) > 0)
3424 {
3425 procbuf[nread] = '\0';
3426 p = procbuf;
3427
3428 p = strchr (p, '(');
3429 if (p != NULL)
3430 {
3431 q = strrchr (p + 1, ')');
3432 /* comm */
3433 if (q != NULL)
3434 {
3435 cmd = p + 1;
3436 cmdsize = q - cmd;
3437 }
3438 }
3439 else
3440 q = NULL;
3441 if (cmd == NULL)
3442 {
3443 cmd = "???";
3444 cmdsize = 3;
3445 }
3446 /* Command name is encoded in locale-coding-system; decode it. */
3447 cmd_str = make_unibyte_string (cmd, cmdsize);
3448 decoded_cmd = code_convert_string_norecord (cmd_str,
3449 Vlocale_coding_system, 0);
3450 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3451
3452 if (q)
3453 {
3454 EMACS_INT ppid_eint, pgrp_eint, sess_eint, tpgid_eint, thcount_eint;
3455 p = q + 2;
3456 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt utime stime cutime cstime priority nice thcount . start vsize rss */
3457 sscanf (p, "%c %d %d %d %d %d %*u %lu %lu %lu %lu %Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld",
3458 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
3459 &minflt, &cminflt, &majflt, &cmajflt,
3460 &utime, &stime, &cutime, &cstime,
3461 &priority, &nice, &thcount, &start, &vsize, &rss);
3462 {
3463 char state_str[2];
3464
3465 state_str[0] = c;
3466 state_str[1] = '\0';
3467 tem = build_string (state_str);
3468 attrs = Fcons (Fcons (Qstate, tem), attrs);
3469 }
3470 /* Stops GCC whining about limited range of data type. */
3471 ppid_eint = ppid;
3472 pgrp_eint = pgrp;
3473 sess_eint = sess;
3474 tpgid_eint = tpgid;
3475 thcount_eint = thcount;
3476 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid_eint)), attrs);
3477 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp_eint)), attrs);
3478 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess_eint)), attrs);
3479 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
3480 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid_eint)), attrs);
3481 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
3482 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
3483 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)), attrs);
3484 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)), attrs);
3485 clocks_per_sec = sysconf (_SC_CLK_TCK);
3486 if (clocks_per_sec < 0)
3487 clocks_per_sec = 100;
3488 attrs = Fcons (Fcons (Qutime,
3489 ltime_from_jiffies (utime, clocks_per_sec)),
3490 attrs);
3491 attrs = Fcons (Fcons (Qstime,
3492 ltime_from_jiffies (stime, clocks_per_sec)),
3493 attrs);
3494 attrs = Fcons (Fcons (Qtime,
3495 ltime_from_jiffies (stime+utime, clocks_per_sec)),
3496 attrs);
3497 attrs = Fcons (Fcons (Qcutime,
3498 ltime_from_jiffies (cutime, clocks_per_sec)),
3499 attrs);
3500 attrs = Fcons (Fcons (Qcstime,
3501 ltime_from_jiffies (cstime, clocks_per_sec)),
3502 attrs);
3503 attrs = Fcons (Fcons (Qctime,
3504 ltime_from_jiffies (cstime+cutime, clocks_per_sec)),
3505 attrs);
3506 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
3507 attrs = Fcons (Fcons (Qnice, make_number (nice)), attrs);
3508 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount_eint)), attrs);
3509 EMACS_GET_TIME (tnow);
3510 get_up_time (&sec, &usec);
3511 EMACS_SET_SECS (telapsed, sec);
3512 EMACS_SET_USECS (telapsed, usec);
3513 EMACS_SUB_TIME (tboot, tnow, telapsed);
3514 time_from_jiffies (start, clocks_per_sec, &sec, &usec);
3515 EMACS_SET_SECS (tstart, sec);
3516 EMACS_SET_USECS (tstart, usec);
3517 EMACS_ADD_TIME (tstart, tboot, tstart);
3518 attrs = Fcons (Fcons (Qstart,
3519 list3 (make_number
3520 ((EMACS_SECS (tstart) >> 16) & 0xffff),
3521 make_number
3522 (EMACS_SECS (tstart) & 0xffff),
3523 make_number
3524 (EMACS_USECS (tstart)))),
3525 attrs);
3526 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize/1024)), attrs);
3527 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4*rss)), attrs);
3528 EMACS_SUB_TIME (telapsed, tnow, tstart);
3529 attrs = Fcons (Fcons (Qetime,
3530 list3 (make_number
3531 ((EMACS_SECS (telapsed) >> 16) & 0xffff),
3532 make_number
3533 (EMACS_SECS (telapsed) & 0xffff),
3534 make_number
3535 (EMACS_USECS (telapsed)))),
3536 attrs);
3537 time_from_jiffies (utime + stime, clocks_per_sec, &sec, &usec);
3538 pcpu = (sec + usec / 1000000.0) / (EMACS_SECS (telapsed) + EMACS_USECS (telapsed) / 1000000.0);
3539 if (pcpu > 1.0)
3540 pcpu = 1.0;
3541 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
3542 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
3543 if (pmem > 100)
3544 pmem = 100;
3545 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
3546 }
3547 }
3548 if (fd >= 0)
3549 emacs_close (fd);
3550
3551 /* args */
3552 strcpy (procfn_end, "/cmdline");
3553 fd = emacs_open (fn, O_RDONLY, 0);
3554 if (fd >= 0)
3555 {
3556 for (cmdline_size = 0; emacs_read (fd, &c, 1) == 1; cmdline_size++)
3557 {
3558 if (isspace (c) || c == '\\')
3559 cmdline_size++; /* for later quoting, see below */
3560 }
3561 if (cmdline_size)
3562 {
3563 cmdline = xmalloc (cmdline_size + 1);
3564 lseek (fd, 0L, SEEK_SET);
3565 cmdline[0] = '\0';
3566 if ((nread = read (fd, cmdline, cmdline_size)) >= 0)
3567 cmdline[nread++] = '\0';
3568 else
3569 {
3570 /* Assigning zero to `nread' makes us skip the following
3571 two loops, assign zero to cmdline_size, and enter the
3572 following `if' clause that handles unknown command
3573 lines. */
3574 nread = 0;
3575 }
3576 /* We don't want trailing null characters. */
3577 for (p = cmdline + nread - 1; p > cmdline && !*p; p--)
3578 nread--;
3579 for (p = cmdline; p < cmdline + nread; p++)
3580 {
3581 /* Escape-quote whitespace and backslashes. */
3582 if (isspace (*p) || *p == '\\')
3583 {
3584 memmove (p + 1, p, nread - (p - cmdline));
3585 nread++;
3586 *p++ = '\\';
3587 }
3588 else if (*p == '\0')
3589 *p = ' ';
3590 }
3591 cmdline_size = nread;
3592 }
3593 if (!cmdline_size)
3594 {
3595 if (!cmd)
3596 cmd = "???";
3597 if (!cmdsize)
3598 cmdsize = strlen (cmd);
3599 cmdline_size = cmdsize + 2;
3600 cmdline = xmalloc (cmdline_size + 1);
3601 strcpy (cmdline, "[");
3602 strcat (strncat (cmdline, cmd, cmdsize), "]");
3603 }
3604 emacs_close (fd);
3605 /* Command line is encoded in locale-coding-system; decode it. */
3606 cmd_str = make_unibyte_string (cmdline, cmdline_size);
3607 decoded_cmd = code_convert_string_norecord (cmd_str,
3608 Vlocale_coding_system, 0);
3609 xfree (cmdline);
3610 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3611 }
3612
3613 UNGCPRO;
3614 return attrs;
3615 }
3616
3617 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
3618
3619 /* The <procfs.h> header does not like to be included if _LP64 is defined and
3620 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
3621 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3622 #define PROCFS_FILE_OFFSET_BITS_HACK 1
3623 #undef _FILE_OFFSET_BITS
3624 #else
3625 #define PROCFS_FILE_OFFSET_BITS_HACK 0
3626 #endif
3627
3628 #include <procfs.h>
3629
3630 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3631 #define _FILE_OFFSET_BITS 64
3632 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3633
3634 Lisp_Object
3635 system_process_attributes (Lisp_Object pid)
3636 {
3637 char procfn[PATH_MAX], fn[PATH_MAX];
3638 struct stat st;
3639 struct passwd *pw;
3640 struct group *gr;
3641 char *procfn_end;
3642 struct psinfo pinfo;
3643 int fd;
3644 ssize_t nread;
3645 int proc_id, uid, gid;
3646 Lisp_Object attrs = Qnil;
3647 Lisp_Object decoded_cmd, tem;
3648 struct gcpro gcpro1, gcpro2;
3649 EMACS_INT uid_eint, gid_eint;
3650
3651 CHECK_NUMBER_OR_FLOAT (pid);
3652 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
3653 sprintf (procfn, "/proc/%u", proc_id);
3654 if (stat (procfn, &st) < 0)
3655 return attrs;
3656
3657 GCPRO2 (attrs, decoded_cmd);
3658
3659 /* euid egid */
3660 uid = st.st_uid;
3661 /* Use of EMACS_INT stops GCC whining about limited range of data type. */
3662 uid_eint = uid;
3663 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid_eint)), attrs);
3664 BLOCK_INPUT;
3665 pw = getpwuid (uid);
3666 UNBLOCK_INPUT;
3667 if (pw)
3668 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3669
3670 gid = st.st_gid;
3671 gid_eint = gid;
3672 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid_eint)), attrs);
3673 BLOCK_INPUT;
3674 gr = getgrgid (gid);
3675 UNBLOCK_INPUT;
3676 if (gr)
3677 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3678
3679 strcpy (fn, procfn);
3680 procfn_end = fn + strlen (fn);
3681 strcpy (procfn_end, "/psinfo");
3682 fd = emacs_open (fn, O_RDONLY, 0);
3683 if (fd >= 0
3684 && (nread = read (fd, (char*)&pinfo, sizeof(struct psinfo)) > 0))
3685 {
3686 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3687 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3688 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3689
3690 {
3691 char state_str[2];
3692 state_str[0] = pinfo.pr_lwp.pr_sname;
3693 state_str[1] = '\0';
3694 tem = build_string (state_str);
3695 attrs = Fcons (Fcons (Qstate, tem), attrs);
3696 }
3697
3698 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3699 need to get a string from it. */
3700
3701 /* FIXME: missing: Qtpgid */
3702
3703 /* FIXME: missing:
3704 Qminflt
3705 Qmajflt
3706 Qcminflt
3707 Qcmajflt
3708
3709 Qutime
3710 Qcutime
3711 Qstime
3712 Qcstime
3713 Are they available? */
3714
3715 attrs = Fcons (Fcons (Qtime,
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 (Qctime,
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 The MSDOS implementation is on dosfns.c. */
3764 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3765
3766 Lisp_Object
3767 system_process_attributes (Lisp_Object pid)
3768 {
3769 return Qnil;
3770 }
3771
3772 #endif /* !defined (WINDOWSNT) */
3773
3774
3775 /* arch-tag: edb43589-4e09-4544-b325-978b5b121dcf
3776 (do not change this comment) */