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