(File Shadowing): New.
[emacs.git] / src / sysdep.c
blobdc70bb8fb7cb4257517186c4a403d6b80606f1ae
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985, 86,87,88,93,94,95, 1999 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
22 #include <config.h>
23 #include <signal.h>
24 #include <setjmp.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
29 #include "lisp.h"
30 #include "blockinput.h"
31 #undef NULL
33 #ifdef macintosh
34 #ifdef __MRC__
35 __sigfun sys_signal (int signal, __sigfun signal_func);
36 #elif __MWERKS__
37 __signal_func_ptr sys_signal (int signal, __signal_func_ptr signal_func);
38 #else
39 You lose!!!
40 #endif
41 #ifndef subprocesses
42 /* Nonzero means delete a process right away if it exits (process.c). */
43 static int delete_exited_processes;
44 #endif
45 #ifndef HAVE_X_WINDOWS
46 /* Search path for bitmap files (xfns.c). */
47 Lisp_Object Vx_bitmap_file_path;
48 #endif
49 #endif /* macintosh */
51 #define min(x,y) ((x) > (y) ? (y) : (x))
53 #ifdef WINDOWSNT
54 #define read sys_read
55 #define write sys_write
56 #include <windows.h>
57 extern int errno;
58 #endif /* not WINDOWSNT */
60 /* Does anyone other than VMS need this? */
61 #ifndef fwrite
62 #define sys_fwrite fwrite
63 #else
64 #undef fwrite
65 #endif
67 #ifndef HAVE_H_ERRNO
68 extern int h_errno;
69 #endif
71 #include <stdio.h>
72 #include <sys/types.h>
73 #include <sys/stat.h>
74 #include <errno.h>
76 /* Get _POSIX_VDISABLE, if it is available. */
77 #ifdef HAVE_UNISTD_H
78 #include <unistd.h>
79 #endif
81 #ifdef HAVE_STDLIB_H
82 #include <stdlib.h>
83 #endif
85 #ifdef HAVE_SETPGID
86 #if !defined (USG) || defined (BSD_PGRPS)
87 #undef setpgrp
88 #define setpgrp setpgid
89 #endif
90 #endif
92 /* Get SI_SRPC_DOMAIN, if it is available. */
93 #ifdef HAVE_SYS_SYSTEMINFO_H
94 #include <sys/systeminfo.h>
95 #endif
97 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
98 #include <dos.h>
99 #include "dosfns.h"
100 #include "msdos.h"
101 #include <sys/param.h>
103 #if __DJGPP__ > 1
104 extern int etext;
105 extern unsigned start __asm__ ("start");
106 #endif
107 #endif
109 #ifndef errno
110 extern int errno;
111 #endif
113 #ifdef VMS
114 #include <rms.h>
115 #include <ttdef.h>
116 #include <tt2def.h>
117 #include <iodef.h>
118 #include <ssdef.h>
119 #include <descrip.h>
120 #include <fibdef.h>
121 #include <atrdef.h>
122 #include <ctype.h>
123 #include <string.h>
124 #ifdef __GNUC__
125 #include <sys/file.h>
126 #else
127 #include <file.h>
128 #endif
129 #undef F_SETFL
130 #ifndef RAB$C_BID
131 #include <rab.h>
132 #endif
133 #define MAXIOSIZE (32 * PAGESIZE) /* Don't I/O more than 32 blocks at a time */
134 #endif /* VMS */
136 #ifndef BSD4_1
137 #ifdef BSD_SYSTEM /* avoid writing defined (BSD_SYSTEM) || defined (USG)
138 because the vms compiler doesn't grok `defined' */
139 #include <fcntl.h>
140 #endif
141 #ifdef USG
142 #ifndef USG5
143 #include <fcntl.h>
144 #endif
145 #endif
146 #endif /* not 4.1 bsd */
148 #ifndef MSDOS
149 #include <sys/ioctl.h>
150 #endif
152 #include "systty.h"
153 #include "syswait.h"
155 #ifdef BROKEN_TIOCGWINSZ
156 #undef TIOCGWINSZ
157 #undef TIOCSWINSZ
158 #endif
160 #if defined (USG) || defined (DGUX)
161 #include <sys/utsname.h>
162 #include <string.h>
163 #ifndef MEMORY_IN_STRING_H
164 #include <memory.h>
165 #endif
166 #if defined (TIOCGWINSZ) || defined (ISC4_0)
167 #ifdef NEED_SIOCTL
168 #include <sys/sioctl.h>
169 #endif
170 #ifdef NEED_PTEM_H
171 #include <sys/stream.h>
172 #include <sys/ptem.h>
173 #endif
174 #endif /* TIOCGWINSZ or ISC4_0 */
175 #endif /* USG or DGUX */
177 extern int quit_char;
179 #include "frame.h"
180 #include "window.h"
181 #include "termhooks.h"
182 #include "termchar.h"
183 #include "termopts.h"
184 #include "dispextern.h"
185 #include "process.h"
187 #ifdef WINDOWSNT
188 #include <direct.h>
189 /* In process.h which conflicts with the local copy. */
190 #define _P_WAIT 0
191 int _CRTAPI1 _spawnlp (int, const char *, const char *, ...);
192 int _CRTAPI1 _getpid (void);
193 #endif
195 #ifdef NONSYSTEM_DIR_LIBRARY
196 #include "ndir.h"
197 #endif /* NONSYSTEM_DIR_LIBRARY */
199 #include "syssignal.h"
200 #include "systime.h"
201 #ifdef HAVE_UTIME_H
202 #include <utime.h>
203 #endif
205 #ifndef HAVE_UTIMES
206 #ifndef HAVE_STRUCT_UTIMBUF
207 /* We want to use utime rather than utimes, but we couldn't find the
208 structure declaration. We'll use the traditional one. */
209 struct utimbuf {
210 long actime;
211 long modtime;
213 #endif
214 #endif
216 /* LPASS8 is new in 4.3, and makes cbreak mode provide all 8 bits. */
217 #ifndef LPASS8
218 #define LPASS8 0
219 #endif
221 #ifdef BSD4_1
222 #define LNOFLSH 0100000
223 #endif
225 static int baud_convert[] =
226 #ifdef BAUD_CONVERT
227 BAUD_CONVERT;
228 #else
230 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
231 1800, 2400, 4800, 9600, 19200, 38400
233 #endif
235 #ifdef HAVE_SPEED_T
236 #include <termios.h>
237 extern speed_t ospeed;
238 #else
239 #if defined (HAVE_LIBNCURSES) && ! defined (NCURSES_OSPEED_T)
240 extern short ospeed;
241 #else
242 #if defined (HAVE_TERMIOS_H) && defined (LINUX)
243 #include <termios.h>
244 /* HJL's version of libc is said to need this on the Alpha.
245 On the other hand, DEC OSF1 on the Alpha needs ospeed to be a short. */
246 extern speed_t ospeed;
247 #else
248 extern short ospeed;
249 #endif
250 #endif
251 #endif
253 /* The file descriptor for Emacs's input terminal.
254 Under Unix, this is normally zero except when using X;
255 under VMS, we place the input channel number here. */
256 int input_fd;
258 void croak P_ ((char *));
260 #ifdef AIXHFT
261 void hft_init ();
262 void hft_reset ();
263 #endif
265 /* Temporary used by `sigblock' when defined in terms of signprocmask. */
267 SIGMASKTYPE sigprocmask_set;
270 /* Specify a different file descriptor for further input operations. */
272 void
273 change_input_fd (fd)
274 int fd;
276 input_fd = fd;
279 /* Discard pending input on descriptor input_fd. */
281 void
282 discard_tty_input ()
284 #ifndef WINDOWSNT
285 struct emacs_tty buf;
287 if (noninteractive)
288 return;
290 /* Discarding input is not safe when the input could contain
291 replies from the X server. So don't do it. */
292 if (read_socket_hook)
293 return;
295 #ifdef VMS
296 end_kbd_input ();
297 SYS$QIOW (0, input_fd, IO$_READVBLK|IO$M_PURGE, input_iosb, 0, 0,
298 &buf.main, 0, 0, terminator_mask, 0, 0);
299 queue_kbd_input ();
300 #else /* not VMS */
301 #ifdef APOLLO
303 int zero = 0;
304 ioctl (input_fd, TIOCFLUSH, &zero);
306 #else /* not Apollo */
307 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
308 while (dos_keyread () != -1)
310 #else /* not MSDOS */
311 EMACS_GET_TTY (input_fd, &buf);
312 EMACS_SET_TTY (input_fd, &buf, 0);
313 #endif /* not MSDOS */
314 #endif /* not Apollo */
315 #endif /* not VMS */
316 #endif /* not WINDOWSNT */
319 #ifdef SIGTSTP
321 /* Arrange for character C to be read as the next input from
322 the terminal. */
324 void
325 stuff_char (c)
326 char c;
328 if (read_socket_hook)
329 return;
331 /* Should perhaps error if in batch mode */
332 #ifdef TIOCSTI
333 ioctl (input_fd, TIOCSTI, &c);
334 #else /* no TIOCSTI */
335 error ("Cannot stuff terminal input characters in this version of Unix");
336 #endif /* no TIOCSTI */
339 #endif /* SIGTSTP */
341 void
342 init_baud_rate ()
344 if (noninteractive)
345 ospeed = 0;
346 else
348 #ifdef INIT_BAUD_RATE
349 INIT_BAUD_RATE ();
350 #else
351 #ifdef DOS_NT
352 ospeed = 15;
353 #else /* not DOS_NT */
354 #ifdef VMS
355 struct sensemode sg;
357 SYS$QIOW (0, input_fd, IO$_SENSEMODE, &sg, 0, 0,
358 &sg.class, 12, 0, 0, 0, 0 );
359 ospeed = sg.xmit_baud;
360 #else /* not VMS */
361 #ifdef HAVE_TERMIOS
362 struct termios sg;
364 sg.c_cflag = B9600;
365 tcgetattr (input_fd, &sg);
366 ospeed = cfgetospeed (&sg);
367 #if defined (USE_GETOBAUD) && defined (getobaud)
368 /* m88k-motorola-sysv3 needs this (ghazi@noc.rutgers.edu) 9/1/94. */
369 if (ospeed == 0)
370 ospeed = getobaud (sg.c_cflag);
371 #endif
372 #else /* neither VMS nor TERMIOS */
373 #ifdef HAVE_TERMIO
374 struct termio sg;
376 sg.c_cflag = B9600;
377 #ifdef HAVE_TCATTR
378 tcgetattr (input_fd, &sg);
379 #else
380 ioctl (input_fd, TCGETA, &sg);
381 #endif
382 ospeed = sg.c_cflag & CBAUD;
383 #else /* neither VMS nor TERMIOS nor TERMIO */
384 struct sgttyb sg;
386 sg.sg_ospeed = B9600;
387 if (ioctl (input_fd, TIOCGETP, &sg) < 0)
388 abort ();
389 ospeed = sg.sg_ospeed;
390 #endif /* not HAVE_TERMIO */
391 #endif /* not HAVE_TERMIOS */
392 #endif /* not VMS */
393 #endif /* not DOS_NT */
394 #endif /* not INIT_BAUD_RATE */
397 baud_rate = (ospeed < sizeof baud_convert / sizeof baud_convert[0]
398 ? baud_convert[ospeed] : 9600);
399 if (baud_rate == 0)
400 baud_rate = 1200;
403 /*ARGSUSED*/
404 void
405 set_exclusive_use (fd)
406 int fd;
408 #ifdef FIOCLEX
409 ioctl (fd, FIOCLEX, 0);
410 #endif
411 /* Ok to do nothing if this feature does not exist */
414 #ifndef subprocesses
416 wait_without_blocking ()
418 #ifdef BSD_SYSTEM
419 wait3 (0, WNOHANG | WUNTRACED, 0);
420 #else
421 croak ("wait_without_blocking");
422 #endif
423 synch_process_alive = 0;
426 #endif /* not subprocesses */
428 int wait_debugging; /* Set nonzero to make following function work under dbx
429 (at least for bsd). */
431 SIGTYPE
432 wait_for_termination_signal ()
435 /* Wait for subprocess with process id `pid' to terminate and
436 make sure it will get eliminated (not remain forever as a zombie) */
438 void
439 wait_for_termination (pid)
440 int pid;
442 while (1)
444 #ifdef subprocesses
445 #ifdef VMS
446 int status;
448 status = SYS$FORCEX (&pid, 0, 0);
449 break;
450 #else /* not VMS */
451 #if defined (BSD_SYSTEM) || (defined (HPUX) && !defined (HPUX_5))
452 /* Note that kill returns -1 even if the process is just a zombie now.
453 But inevitably a SIGCHLD interrupt should be generated
454 and child_sig will do wait3 and make the process go away. */
455 /* There is some indication that there is a bug involved with
456 termination of subprocesses, perhaps involving a kernel bug too,
457 but no idea what it is. Just as a hunch we signal SIGCHLD to see
458 if that causes the problem to go away or get worse. */
459 sigsetmask (sigmask (SIGCHLD));
460 if (0 > kill (pid, 0))
462 sigsetmask (SIGEMPTYMASK);
463 kill (getpid (), SIGCHLD);
464 break;
466 if (wait_debugging)
467 sleep (1);
468 else
469 sigpause (SIGEMPTYMASK);
470 #else /* not BSD_SYSTEM, and not HPUX version >= 6 */
471 #if defined (UNIPLUS)
472 if (0 > kill (pid, 0))
473 break;
474 wait (0);
475 #else /* neither BSD_SYSTEM nor UNIPLUS: random sysV */
476 #ifdef POSIX_SIGNALS /* would this work for LINUX as well? */
477 sigblock (sigmask (SIGCHLD));
478 if (0 > kill (pid, 0))
480 sigunblock (sigmask (SIGCHLD));
481 break;
483 sigpause (SIGEMPTYMASK);
484 #else /* not POSIX_SIGNALS */
485 #ifdef HAVE_SYSV_SIGPAUSE
486 sighold (SIGCHLD);
487 if (0 > kill (pid, 0))
489 sigrelse (SIGCHLD);
490 break;
492 sigpause (SIGCHLD);
493 #else /* not HAVE_SYSV_SIGPAUSE */
494 #ifdef WINDOWSNT
495 wait (0);
496 break;
497 #else /* not WINDOWSNT */
498 if (0 > kill (pid, 0))
499 break;
500 /* Using sleep instead of pause avoids timing error.
501 If the inferior dies just before the sleep,
502 we lose just one second. */
503 sleep (1);
504 #endif /* not WINDOWSNT */
505 #endif /* not HAVE_SYSV_SIGPAUSE */
506 #endif /* not POSIX_SIGNALS */
507 #endif /* not UNIPLUS */
508 #endif /* not BSD_SYSTEM, and not HPUX version >= 6 */
509 #endif /* not VMS */
510 #else /* not subprocesses */
511 #if __DJGPP__ > 1
512 break;
513 #else /* not __DJGPP__ > 1 */
514 #ifndef BSD4_1
515 if (kill (pid, 0) < 0)
516 break;
517 wait (0);
518 #else /* BSD4_1 */
519 int status;
520 status = wait (0);
521 if (status == pid || status == -1)
522 break;
523 #endif /* BSD4_1 */
524 #endif /* not __DJGPP__ > 1*/
525 #endif /* not subprocesses */
529 #ifdef subprocesses
532 * flush any pending output
533 * (may flush input as well; it does not matter the way we use it)
536 void
537 flush_pending_output (channel)
538 int channel;
540 #ifdef HAVE_TERMIOS
541 /* If we try this, we get hit with SIGTTIN, because
542 the child's tty belongs to the child's pgrp. */
543 #else
544 #ifdef TCFLSH
545 ioctl (channel, TCFLSH, 1);
546 #else
547 #ifdef TIOCFLUSH
548 int zero = 0;
549 /* 3rd arg should be ignored
550 but some 4.2 kernels actually want the address of an int
551 and nonzero means something different. */
552 ioctl (channel, TIOCFLUSH, &zero);
553 #endif
554 #endif
555 #endif
558 #ifndef VMS
559 /* Set up the terminal at the other end of a pseudo-terminal that
560 we will be controlling an inferior through.
561 It should not echo or do line-editing, since that is done
562 in Emacs. No padding needed for insertion into an Emacs buffer. */
564 void
565 child_setup_tty (out)
566 int out;
568 #ifndef DOS_NT
569 struct emacs_tty s;
571 EMACS_GET_TTY (out, &s);
573 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
574 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
575 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
576 #ifdef NLDLY
577 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
578 /* No output delays */
579 #endif
580 s.main.c_lflag &= ~ECHO; /* Disable echo */
581 s.main.c_lflag |= ISIG; /* Enable signals */
582 #ifdef IUCLC
583 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
584 #endif
585 #ifdef ISTRIP
586 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
587 #endif
588 #ifdef OLCUC
589 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
590 #endif
591 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
592 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
593 #if 0
594 /* Said to be unnecessary: */
595 s.main.c_cc[VMIN] = 1; /* minimum number of characters to accept */
596 s.main.c_cc[VTIME] = 0; /* wait forever for at least 1 character */
597 #endif
599 s.main.c_lflag |= ICANON; /* Enable erase/kill and eof processing */
600 s.main.c_cc[VEOF] = 04; /* insure that EOF is Control-D */
601 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
602 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
604 #ifdef HPUX
605 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
606 #endif /* HPUX */
608 #ifdef AIX
609 /* AIX enhanced edit loses NULs, so disable it */
610 #ifndef IBMR2AIX
611 s.main.c_line = 0;
612 s.main.c_iflag &= ~ASCEDIT;
613 #endif
614 /* Also, PTY overloads NUL and BREAK.
615 don't ignore break, but don't signal either, so it looks like NUL. */
616 s.main.c_iflag &= ~IGNBRK;
617 s.main.c_iflag &= ~BRKINT;
618 /* QUIT and INTR work better as signals, so disable character forms */
619 s.main.c_cc[VINTR] = 0377;
620 #ifdef SIGNALS_VIA_CHARACTERS
621 /* the QUIT and INTR character are used in process_send_signal
622 so set them here to something useful. */
623 if (s.main.c_cc[VQUIT] == 0377)
624 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
625 if (s.main.c_cc[VINTR] == 0377)
626 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
627 #else /* no TIOCGPGRP or no TIOCGLTC or no TIOCGETC */
628 /* QUIT and INTR work better as signals, so disable character forms */
629 s.main.c_cc[VQUIT] = 0377;
630 s.main.c_cc[VINTR] = 0377;
631 s.main.c_lflag &= ~ISIG;
632 #endif /* no TIOCGPGRP or no TIOCGLTC or no TIOCGETC */
633 s.main.c_cc[VEOL] = 0377;
634 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
635 #endif /* AIX */
637 #else /* not HAVE_TERMIO */
639 s.main.sg_flags &= ~(ECHO | CRMOD | ANYP | ALLDELAY | RAW | LCASE
640 | CBREAK | TANDEM);
641 s.main.sg_flags |= LPASS8;
642 s.main.sg_erase = 0377;
643 s.main.sg_kill = 0377;
644 s.lmode = LLITOUT | s.lmode; /* Don't strip 8th bit */
646 #endif /* not HAVE_TERMIO */
648 EMACS_SET_TTY (out, &s, 0);
650 #ifdef BSD4_1
651 if (interrupt_input)
652 reset_sigio ();
653 #endif /* BSD4_1 */
654 #ifdef RTU
656 int zero = 0;
657 ioctl (out, FIOASYNC, &zero);
659 #endif /* RTU */
660 #endif /* not DOS_NT */
662 #endif /* not VMS */
664 #endif /* subprocesses */
666 /* Record a signal code and the handler for it. */
667 struct save_signal
669 int code;
670 SIGTYPE (*handler) P_ ((int));
673 static void save_signal_handlers P_ ((struct save_signal *));
674 static void restore_signal_handlers P_ ((struct save_signal *));
676 /* Suspend the Emacs process; give terminal to its superior. */
678 void
679 sys_suspend ()
681 #ifdef VMS
682 /* "Foster" parentage allows emacs to return to a subprocess that attached
683 to the current emacs as a cheaper than starting a whole new process. This
684 is set up by KEPTEDITOR.COM. */
685 unsigned long parent_id, foster_parent_id;
686 char *fpid_string;
688 fpid_string = getenv ("EMACS_PARENT_PID");
689 if (fpid_string != NULL)
691 sscanf (fpid_string, "%x", &foster_parent_id);
692 if (foster_parent_id != 0)
693 parent_id = foster_parent_id;
694 else
695 parent_id = getppid ();
697 else
698 parent_id = getppid ();
700 xfree (fpid_string); /* On VMS, this was malloc'd */
702 if (parent_id && parent_id != 0xffffffff)
704 SIGTYPE (*oldsig)() = (int) signal (SIGINT, SIG_IGN);
705 int status = LIB$ATTACH (&parent_id) & 1;
706 signal (SIGINT, oldsig);
707 return status;
709 else
711 struct {
712 int l;
713 char *a;
714 } d_prompt;
715 d_prompt.l = sizeof ("Emacs: "); /* Our special prompt */
716 d_prompt.a = "Emacs: "; /* Just a reminder */
717 LIB$SPAWN (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, &d_prompt, 0);
718 return 1;
720 return -1;
721 #else
722 #if defined (SIGTSTP) && !defined (MSDOS)
725 int pgrp = EMACS_GETPGRP (0);
726 EMACS_KILLPG (pgrp, SIGTSTP);
729 #else /* No SIGTSTP */
730 #ifdef USG_JOBCTRL /* If you don't know what this is don't mess with it */
731 ptrace (0, 0, 0, 0); /* set for ptrace - caught by csh */
732 kill (getpid (), SIGQUIT);
734 #else /* No SIGTSTP or USG_JOBCTRL */
736 /* On a system where suspending is not implemented,
737 instead fork a subshell and let it talk directly to the terminal
738 while we wait. */
739 sys_subshell ();
741 #endif /* no USG_JOBCTRL */
742 #endif /* no SIGTSTP */
743 #endif /* not VMS */
746 /* Fork a subshell. */
748 void
749 sys_subshell ()
751 #ifdef macintosh
752 error ("Can't spawn subshell");
753 #else
754 #ifndef VMS
755 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
756 int st;
757 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
758 #endif
759 int pid;
760 struct save_signal saved_handlers[5];
761 Lisp_Object dir;
762 unsigned char *str = 0;
763 int len;
765 saved_handlers[0].code = SIGINT;
766 saved_handlers[1].code = SIGQUIT;
767 saved_handlers[2].code = SIGTERM;
768 #ifdef SIGIO
769 saved_handlers[3].code = SIGIO;
770 saved_handlers[4].code = 0;
771 #else
772 saved_handlers[3].code = 0;
773 #endif
775 /* Mentioning current_buffer->buffer would mean including buffer.h,
776 which somehow wedges the hp compiler. So instead... */
778 dir = intern ("default-directory");
779 if (NILP (Fboundp (dir)))
780 goto xyzzy;
781 dir = Fsymbol_value (dir);
782 if (!STRINGP (dir))
783 goto xyzzy;
785 dir = expand_and_dir_to_file (Funhandled_file_name_directory (dir), Qnil);
786 str = (unsigned char *) alloca (XSTRING (dir)->size + 2);
787 len = XSTRING (dir)->size;
788 bcopy (XSTRING (dir)->data, str, len);
789 if (str[len - 1] != '/') str[len++] = '/';
790 str[len] = 0;
791 xyzzy:
793 #ifdef DOS_NT
794 pid = 0;
795 #if __DJGPP__ > 1
796 save_signal_handlers (saved_handlers);
797 synch_process_alive = 1;
798 #endif /* __DJGPP__ > 1 */
799 #else
800 pid = vfork ();
801 if (pid == -1)
802 error ("Can't spawn subshell");
803 #endif
805 if (pid == 0)
807 char *sh = 0;
809 #ifdef DOS_NT /* MW, Aug 1993 */
810 getwd (oldwd);
811 if (sh == 0)
812 sh = (char *) egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
813 #endif
814 if (sh == 0)
815 sh = (char *) egetenv ("SHELL");
816 if (sh == 0)
817 sh = "sh";
819 /* Use our buffer's default directory for the subshell. */
820 if (str)
821 chdir ((char *) str);
823 #ifdef subprocesses
824 close_process_descs (); /* Close Emacs's pipes/ptys */
825 #endif
827 #ifdef SET_EMACS_PRIORITY
829 extern int emacs_priority;
831 if (emacs_priority < 0)
832 nice (-emacs_priority);
834 #endif
836 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
837 st = system (sh);
838 chdir (oldwd);
839 #if 0 /* This is also reported if last command executed in subshell failed, KFS */
840 if (st)
841 report_file_error ("Can't execute subshell", Fcons (build_string (sh), Qnil));
842 #endif
843 #else /* not MSDOS */
844 #ifdef WINDOWSNT
845 /* Waits for process completion */
846 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
847 chdir (oldwd);
848 if (pid == -1)
849 write (1, "Can't execute subshell", 22);
850 #else /* not WINDOWSNT */
851 execlp (sh, sh, 0);
852 write (1, "Can't execute subshell", 22);
853 _exit (1);
854 #endif /* not WINDOWSNT */
855 #endif /* not MSDOS */
858 /* Do this now if we did not do it before. */
859 #if !defined (MSDOS) || __DJGPP__ == 1
860 save_signal_handlers (saved_handlers);
861 synch_process_alive = 1;
862 #endif
864 #ifndef DOS_NT
865 wait_for_termination (pid);
866 #endif
867 restore_signal_handlers (saved_handlers);
868 synch_process_alive = 0;
869 #endif /* !VMS */
870 #endif /* !macintosh */
873 static void
874 save_signal_handlers (saved_handlers)
875 struct save_signal *saved_handlers;
877 while (saved_handlers->code)
879 saved_handlers->handler
880 = (SIGTYPE (*) P_ ((int))) signal (saved_handlers->code, SIG_IGN);
881 saved_handlers++;
885 static void
886 restore_signal_handlers (saved_handlers)
887 struct save_signal *saved_handlers;
889 while (saved_handlers->code)
891 signal (saved_handlers->code, saved_handlers->handler);
892 saved_handlers++;
896 #ifdef F_SETFL
898 int old_fcntl_flags;
900 void
901 init_sigio (fd)
902 int fd;
904 #ifdef FASYNC
905 old_fcntl_flags = fcntl (fd, F_GETFL, 0) & ~FASYNC;
906 fcntl (fd, F_SETFL, old_fcntl_flags | FASYNC);
907 #endif
908 interrupts_deferred = 0;
911 void
912 reset_sigio ()
914 unrequest_sigio ();
917 #ifdef FASYNC /* F_SETFL does not imply existence of FASYNC */
919 void
920 request_sigio ()
922 if (read_socket_hook)
923 return;
925 #ifdef SIGWINCH
926 sigunblock (sigmask (SIGWINCH));
927 #endif
928 fcntl (input_fd, F_SETFL, old_fcntl_flags | FASYNC);
930 interrupts_deferred = 0;
933 void
934 unrequest_sigio ()
936 if (read_socket_hook)
937 return;
939 #ifdef SIGWINCH
940 sigblock (sigmask (SIGWINCH));
941 #endif
942 fcntl (input_fd, F_SETFL, old_fcntl_flags);
943 interrupts_deferred = 1;
946 #else /* no FASYNC */
947 #ifdef STRIDE /* Stride doesn't have FASYNC - use FIOASYNC */
949 void
950 request_sigio ()
952 int on = 1;
954 if (read_socket_hook)
955 return;
957 ioctl (input_fd, FIOASYNC, &on);
958 interrupts_deferred = 0;
961 void
962 unrequest_sigio ()
964 int off = 0;
966 if (read_socket_hook)
967 return;
969 ioctl (input_fd, FIOASYNC, &off);
970 interrupts_deferred = 1;
973 #else /* not FASYNC, not STRIDE */
975 #ifdef _CX_UX
977 #include <termios.h>
979 void
980 request_sigio ()
982 int on = 1;
983 sigset_t st;
985 if (read_socket_hook)
986 return;
988 sigemptyset (&st);
989 sigaddset (&st, SIGIO);
990 ioctl (input_fd, FIOASYNC, &on);
991 interrupts_deferred = 0;
992 sigprocmask (SIG_UNBLOCK, &st, (sigset_t *)0);
995 void
996 unrequest_sigio ()
998 int off = 0;
1000 if (read_socket_hook)
1001 return;
1003 ioctl (input_fd, FIOASYNC, &off);
1004 interrupts_deferred = 1;
1007 #else /* ! _CX_UX */
1009 void
1010 request_sigio ()
1012 if (read_socket_hook)
1013 return;
1015 croak ("request_sigio");
1018 void
1019 unrequest_sigio ()
1021 if (read_socket_hook)
1022 return;
1024 croak ("unrequest_sigio");
1027 #endif /* _CX_UX */
1028 #endif /* STRIDE */
1029 #endif /* FASYNC */
1030 #endif /* F_SETFL */
1032 /* Saving and restoring the process group of Emacs's terminal. */
1034 #ifdef BSD_PGRPS
1036 /* The process group of which Emacs was a member when it initially
1037 started.
1039 If Emacs was in its own process group (i.e. inherited_pgroup ==
1040 getpid ()), then we know we're running under a shell with job
1041 control (Emacs would never be run as part of a pipeline).
1042 Everything is fine.
1044 If Emacs was not in its own process group, then we know we're
1045 running under a shell (or a caller) that doesn't know how to
1046 separate itself from Emacs (like sh). Emacs must be in its own
1047 process group in order to receive SIGIO correctly. In this
1048 situation, we put ourselves in our own pgroup, forcibly set the
1049 tty's pgroup to our pgroup, and make sure to restore and reinstate
1050 the tty's pgroup just like any other terminal setting. If
1051 inherited_group was not the tty's pgroup, then we'll get a
1052 SIGTTmumble when we try to change the tty's pgroup, and a CONT if
1053 it goes foreground in the future, which is what should happen. */
1054 int inherited_pgroup;
1056 /* Split off the foreground process group to Emacs alone.
1057 When we are in the foreground, but not started in our own process
1058 group, redirect the TTY to point to our own process group. We need
1059 to be in our own process group to receive SIGIO properly. */
1060 void
1061 narrow_foreground_group ()
1063 int me = getpid ();
1065 setpgrp (0, inherited_pgroup);
1066 if (inherited_pgroup != me)
1067 EMACS_SET_TTY_PGRP (input_fd, &me);
1068 setpgrp (0, me);
1071 /* Set the tty to our original foreground group. */
1072 void
1073 widen_foreground_group ()
1075 if (inherited_pgroup != getpid ())
1076 EMACS_SET_TTY_PGRP (input_fd, &inherited_pgroup);
1077 setpgrp (0, inherited_pgroup);
1080 #endif /* BSD_PGRPS */
1082 /* Getting and setting emacs_tty structures. */
1084 /* Set *TC to the parameters associated with the terminal FD.
1085 Return zero if all's well, or -1 if we ran into an error we
1086 couldn't deal with. */
1088 emacs_get_tty (fd, settings)
1089 int fd;
1090 struct emacs_tty *settings;
1092 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
1093 #ifdef HAVE_TCATTR
1094 /* We have those nifty POSIX tcmumbleattr functions. */
1095 bzero (&settings->main, sizeof (settings->main));
1096 if (tcgetattr (fd, &settings->main) < 0)
1097 return -1;
1099 #else
1100 #ifdef HAVE_TERMIO
1101 /* The SYSV-style interface? */
1102 if (ioctl (fd, TCGETA, &settings->main) < 0)
1103 return -1;
1105 #else
1106 #ifdef VMS
1107 /* Vehemently Monstrous System? :-) */
1108 if (! (SYS$QIOW (0, fd, IO$_SENSEMODE, settings, 0, 0,
1109 &settings->main.class, 12, 0, 0, 0, 0)
1110 & 1))
1111 return -1;
1113 #else
1114 #ifndef DOS_NT
1115 /* I give up - I hope you have the BSD ioctls. */
1116 if (ioctl (fd, TIOCGETP, &settings->main) < 0)
1117 return -1;
1118 #endif /* not DOS_NT */
1119 #endif
1120 #endif
1121 #endif
1123 /* Suivant - Do we have to get struct ltchars data? */
1124 #ifdef HAVE_LTCHARS
1125 if (ioctl (fd, TIOCGLTC, &settings->ltchars) < 0)
1126 return -1;
1127 #endif
1129 /* How about a struct tchars and a wordful of lmode bits? */
1130 #ifdef HAVE_TCHARS
1131 if (ioctl (fd, TIOCGETC, &settings->tchars) < 0
1132 || ioctl (fd, TIOCLGET, &settings->lmode) < 0)
1133 return -1;
1134 #endif
1136 /* We have survived the tempest. */
1137 return 0;
1141 /* Set the parameters of the tty on FD according to the contents of
1142 *SETTINGS. If FLUSHP is non-zero, we discard input.
1143 Return 0 if all went well, and -1 if anything failed. */
1146 emacs_set_tty (fd, settings, flushp)
1147 int fd;
1148 struct emacs_tty *settings;
1149 int flushp;
1151 /* Set the primary parameters - baud rate, character size, etcetera. */
1152 #ifdef HAVE_TCATTR
1153 int i;
1154 /* We have those nifty POSIX tcmumbleattr functions.
1155 William J. Smith <wjs@wiis.wang.com> writes:
1156 "POSIX 1003.1 defines tcsetattr to return success if it was
1157 able to perform any of the requested actions, even if some
1158 of the requested actions could not be performed.
1159 We must read settings back to ensure tty setup properly.
1160 AIX requires this to keep tty from hanging occasionally." */
1161 /* This make sure that we don't loop indefinitely in here. */
1162 for (i = 0 ; i < 10 ; i++)
1163 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
1165 if (errno == EINTR)
1166 continue;
1167 else
1168 return -1;
1170 else
1172 struct termios new;
1174 bzero (&new, sizeof (new));
1175 /* Get the current settings, and see if they're what we asked for. */
1176 tcgetattr (fd, &new);
1177 /* We cannot use memcmp on the whole structure here because under
1178 * aix386 the termios structure has some reserved field that may
1179 * not be filled in.
1181 if ( new.c_iflag == settings->main.c_iflag
1182 && new.c_oflag == settings->main.c_oflag
1183 && new.c_cflag == settings->main.c_cflag
1184 && new.c_lflag == settings->main.c_lflag
1185 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
1186 break;
1187 else
1188 continue;
1191 #else
1192 #ifdef HAVE_TERMIO
1193 /* The SYSV-style interface? */
1194 if (ioctl (fd, flushp ? TCSETAF : TCSETAW, &settings->main) < 0)
1195 return -1;
1197 #else
1198 #ifdef VMS
1199 /* Vehemently Monstrous System? :-) */
1200 if (! (SYS$QIOW (0, fd, IO$_SETMODE, &input_iosb, 0, 0,
1201 &settings->main.class, 12, 0, 0, 0, 0)
1202 & 1))
1203 return -1;
1205 #else
1206 #ifndef DOS_NT
1207 /* I give up - I hope you have the BSD ioctls. */
1208 if (ioctl (fd, (flushp) ? TIOCSETP : TIOCSETN, &settings->main) < 0)
1209 return -1;
1210 #endif /* not DOS_NT */
1212 #endif
1213 #endif
1214 #endif
1216 /* Suivant - Do we have to get struct ltchars data? */
1217 #ifdef HAVE_LTCHARS
1218 if (ioctl (fd, TIOCSLTC, &settings->ltchars) < 0)
1219 return -1;
1220 #endif
1222 /* How about a struct tchars and a wordful of lmode bits? */
1223 #ifdef HAVE_TCHARS
1224 if (ioctl (fd, TIOCSETC, &settings->tchars) < 0
1225 || ioctl (fd, TIOCLSET, &settings->lmode) < 0)
1226 return -1;
1227 #endif
1229 /* We have survived the tempest. */
1230 return 0;
1234 /* The initial tty mode bits */
1235 struct emacs_tty old_tty;
1237 /* 1 if we have been through init_sys_modes. */
1238 int term_initted;
1240 /* 1 if outer tty status has been recorded. */
1241 int old_tty_valid;
1243 #ifdef BSD4_1
1244 /* BSD 4.1 needs to keep track of the lmode bits in order to start
1245 sigio. */
1246 int lmode;
1247 #endif
1249 #ifndef F_SETOWN_BUG
1250 #ifdef F_SETOWN
1251 int old_fcntl_owner;
1252 #endif /* F_SETOWN */
1253 #endif /* F_SETOWN_BUG */
1255 /* This may also be defined in stdio,
1256 but if so, this does no harm,
1257 and using the same name avoids wasting the other one's space. */
1259 #ifdef nec_ews_svr4
1260 extern char *_sobuf ;
1261 #else
1262 #if defined (USG) || defined (DGUX)
1263 unsigned char _sobuf[BUFSIZ+8];
1264 #else
1265 char _sobuf[BUFSIZ];
1266 #endif
1267 #endif
1269 #ifdef HAVE_LTCHARS
1270 static struct ltchars new_ltchars = {-1,-1,-1,-1,-1,-1};
1271 #endif
1272 #ifdef HAVE_TCHARS
1273 static struct tchars new_tchars = {-1,-1,-1,-1,-1,-1};
1274 #endif
1276 void
1277 init_sys_modes ()
1279 struct emacs_tty tty;
1281 #ifdef macintosh
1282 Vwindow_system = intern ("mac");
1283 Vwindow_system_version = make_number (1);
1285 /* cus-start.el complains if delete-exited-processes and x-bitmap-file-path not defined */
1286 #ifndef subprocesses
1287 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
1288 "*Non-nil means delete processes immediately when they exit.\n\
1289 nil means don't delete them until `list-processes' is run.");
1290 delete_exited_processes = 0;
1291 #endif
1293 #ifndef HAVE_X_WINDOWS
1294 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
1295 "List of directories to search for bitmap files for X.");
1296 Vx_bitmap_file_path = decode_env_path ((char *) 0, ".");
1297 #endif
1299 #endif /* not macintosh */
1301 #ifdef VMS
1302 #if 0
1303 static int oob_chars[2] = {0, 1 << 7}; /* catch C-g's */
1304 extern int (*interrupt_signal) ();
1305 #endif
1306 #endif
1308 Vtty_erase_char = Qnil;
1310 if (noninteractive)
1311 return;
1313 #ifdef VMS
1314 if (!input_ef)
1315 input_ef = get_kbd_event_flag ();
1316 /* LIB$GET_EF (&input_ef); */
1317 SYS$CLREF (input_ef);
1318 waiting_for_ast = 0;
1319 if (!timer_ef)
1320 timer_ef = get_timer_event_flag ();
1321 /* LIB$GET_EF (&timer_ef); */
1322 SYS$CLREF (timer_ef);
1323 #if 0
1324 if (!process_ef)
1326 LIB$GET_EF (&process_ef);
1327 SYS$CLREF (process_ef);
1329 if (input_ef / 32 != process_ef / 32)
1330 croak ("Input and process event flags in different clusters.");
1331 #endif
1332 if (input_ef / 32 != timer_ef / 32)
1333 croak ("Input and timer event flags in different clusters.");
1334 #if 0
1335 input_eflist = ((unsigned) 1 << (input_ef % 32)) |
1336 ((unsigned) 1 << (process_ef % 32));
1337 #endif
1338 timer_eflist = ((unsigned) 1 << (input_ef % 32)) |
1339 ((unsigned) 1 << (timer_ef % 32));
1340 #ifndef VMS4_4
1341 sys_access_reinit ();
1342 #endif
1343 #endif /* not VMS */
1345 #ifdef BSD_PGRPS
1346 if (! read_socket_hook && EQ (Vwindow_system, Qnil))
1347 narrow_foreground_group ();
1348 #endif
1350 #ifdef HAVE_WINDOW_SYSTEM
1351 /* Emacs' window system on MSDOG uses the `internal terminal' and therefore
1352 needs the initialization code below. */
1353 if (!read_socket_hook && EQ (Vwindow_system, Qnil))
1354 #endif
1356 EMACS_GET_TTY (input_fd, &old_tty);
1358 old_tty_valid = 1;
1360 tty = old_tty;
1362 #if defined (HAVE_TERMIO) || defined (HAVE_TERMIOS)
1363 XSETINT (Vtty_erase_char, old_tty.main.c_cc[VERASE]);
1365 #ifdef DGUX
1366 /* This allows meta to be sent on 8th bit. */
1367 tty.main.c_iflag &= ~INPCK; /* don't check input for parity */
1368 #endif
1369 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
1370 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
1371 #ifdef INLCR /* I'm just being cautious,
1372 since I can't check how widespread INLCR is--rms. */
1373 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
1374 #endif
1375 #ifdef ISTRIP
1376 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
1377 #endif
1378 tty.main.c_lflag &= ~ECHO; /* Disable echo */
1379 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
1380 #ifdef IEXTEN
1381 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
1382 #endif
1383 tty.main.c_lflag |= ISIG; /* Enable signals */
1384 if (flow_control)
1386 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
1387 #ifdef IXANY
1388 tty.main.c_iflag &= ~IXANY;
1389 #endif /* IXANY */
1391 else
1392 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
1393 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
1394 on output */
1395 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
1396 #ifdef CS8
1397 if (meta_key)
1399 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
1400 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
1402 #endif
1403 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
1404 /* Set up C-g for both SIGQUIT and SIGINT.
1405 We don't know which we will get, but we handle both alike
1406 so which one it really gives us does not matter. */
1407 tty.main.c_cc[VQUIT] = quit_char;
1408 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
1409 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
1410 #ifdef VSWTCH
1411 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
1412 of C-z */
1413 #endif /* VSWTCH */
1415 #if defined (mips) || defined (HAVE_TCATTR)
1416 #ifdef VSUSP
1417 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off mips handling of C-z. */
1418 #endif /* VSUSP */
1419 #ifdef V_DSUSP
1420 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off mips handling of C-y. */
1421 #endif /* V_DSUSP */
1422 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
1423 tty.main.c_cc[VDSUSP] = CDISABLE;
1424 #endif /* VDSUSP */
1425 #ifdef VLNEXT
1426 tty.main.c_cc[VLNEXT] = CDISABLE;
1427 #endif /* VLNEXT */
1428 #ifdef VREPRINT
1429 tty.main.c_cc[VREPRINT] = CDISABLE;
1430 #endif /* VREPRINT */
1431 #ifdef VWERASE
1432 tty.main.c_cc[VWERASE] = CDISABLE;
1433 #endif /* VWERASE */
1434 #ifdef VDISCARD
1435 tty.main.c_cc[VDISCARD] = CDISABLE;
1436 #endif /* VDISCARD */
1438 if (flow_control)
1440 #ifdef VSTART
1441 tty.main.c_cc[VSTART] = '\021';
1442 #endif /* VSTART */
1443 #ifdef VSTOP
1444 tty.main.c_cc[VSTOP] = '\023';
1445 #endif /* VSTOP */
1447 else
1449 #ifdef VSTART
1450 tty.main.c_cc[VSTART] = CDISABLE;
1451 #endif /* VSTART */
1452 #ifdef VSTOP
1453 tty.main.c_cc[VSTOP] = CDISABLE;
1454 #endif /* VSTOP */
1456 #endif /* mips or HAVE_TCATTR */
1458 #ifdef SET_LINE_DISCIPLINE
1459 /* Need to explicitly request TERMIODISC line discipline or
1460 Ultrix's termios does not work correctly. */
1461 tty.main.c_line = SET_LINE_DISCIPLINE;
1462 #endif
1463 #ifdef AIX
1464 #ifndef IBMR2AIX
1465 /* AIX enhanced edit loses NULs, so disable it. */
1466 tty.main.c_line = 0;
1467 tty.main.c_iflag &= ~ASCEDIT;
1468 #else
1469 tty.main.c_cc[VSTRT] = 255;
1470 tty.main.c_cc[VSTOP] = 255;
1471 tty.main.c_cc[VSUSP] = 255;
1472 tty.main.c_cc[VDSUSP] = 255;
1473 #endif /* IBMR2AIX */
1474 if (flow_control)
1476 #ifdef VSTART
1477 tty.main.c_cc[VSTART] = '\021';
1478 #endif /* VSTART */
1479 #ifdef VSTOP
1480 tty.main.c_cc[VSTOP] = '\023';
1481 #endif /* VSTOP */
1483 /* Also, PTY overloads NUL and BREAK.
1484 don't ignore break, but don't signal either, so it looks like NUL.
1485 This really serves a purpose only if running in an XTERM window
1486 or via TELNET or the like, but does no harm elsewhere. */
1487 tty.main.c_iflag &= ~IGNBRK;
1488 tty.main.c_iflag &= ~BRKINT;
1489 #endif
1490 #else /* if not HAVE_TERMIO */
1491 #ifdef VMS
1492 tty.main.tt_char |= TT$M_NOECHO;
1493 if (meta_key)
1494 tty.main.tt_char |= TT$M_EIGHTBIT;
1495 if (flow_control)
1496 tty.main.tt_char |= TT$M_TTSYNC;
1497 else
1498 tty.main.tt_char &= ~TT$M_TTSYNC;
1499 tty.main.tt2_char |= TT2$M_PASTHRU | TT2$M_XON;
1500 #else /* not VMS (BSD, that is) */
1501 #ifndef DOS_NT
1502 XSETINT (Vtty_erase_char, tty.main.sg_erase);
1503 tty.main.sg_flags &= ~(ECHO | CRMOD | XTABS);
1504 if (meta_key)
1505 tty.main.sg_flags |= ANYP;
1506 tty.main.sg_flags |= interrupt_input ? RAW : CBREAK;
1507 #endif /* not DOS_NT */
1508 #endif /* not VMS (BSD, that is) */
1509 #endif /* not HAVE_TERMIO */
1511 /* If going to use CBREAK mode, we must request C-g to interrupt
1512 and turn off start and stop chars, etc. If not going to use
1513 CBREAK mode, do this anyway so as to turn off local flow
1514 control for user coming over network on 4.2; in this case,
1515 only t_stopc and t_startc really matter. */
1516 #ifndef HAVE_TERMIO
1517 #ifdef HAVE_TCHARS
1518 /* Note: if not using CBREAK mode, it makes no difference how we
1519 set this */
1520 tty.tchars = new_tchars;
1521 tty.tchars.t_intrc = quit_char;
1522 if (flow_control)
1524 tty.tchars.t_startc = '\021';
1525 tty.tchars.t_stopc = '\023';
1528 tty.lmode = LDECCTQ | LLITOUT | LPASS8 | LNOFLSH | old_tty.lmode;
1529 #ifdef ultrix
1530 /* Under Ultrix 4.2a, leaving this out doesn't seem to hurt
1531 anything, and leaving it in breaks the meta key. Go figure. */
1532 tty.lmode &= ~LLITOUT;
1533 #endif
1535 #ifdef BSD4_1
1536 lmode = tty.lmode;
1537 #endif
1539 #endif /* HAVE_TCHARS */
1540 #endif /* not HAVE_TERMIO */
1542 #ifdef HAVE_LTCHARS
1543 tty.ltchars = new_ltchars;
1544 #endif /* HAVE_LTCHARS */
1545 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1546 if (!term_initted)
1547 internal_terminal_init ();
1548 dos_ttraw ();
1549 #endif
1551 EMACS_SET_TTY (input_fd, &tty, 0);
1553 /* This code added to insure that, if flow-control is not to be used,
1554 we have an unlocked terminal at the start. */
1556 #ifdef TCXONC
1557 if (!flow_control) ioctl (input_fd, TCXONC, 1);
1558 #endif
1559 #ifndef APOLLO
1560 #ifdef TIOCSTART
1561 if (!flow_control) ioctl (input_fd, TIOCSTART, 0);
1562 #endif
1563 #endif
1565 #if defined (HAVE_TERMIOS) || defined (HPUX9)
1566 #ifdef TCOON
1567 if (!flow_control) tcflow (input_fd, TCOON);
1568 #endif
1569 #endif
1571 #ifdef AIXHFT
1572 hft_init ();
1573 #ifdef IBMR2AIX
1575 /* IBM's HFT device usually thinks a ^J should be LF/CR. We need it
1576 to be only LF. This is the way that is done. */
1577 struct termio tty;
1579 if (ioctl (1, HFTGETID, &tty) != -1)
1580 write (1, "\033[20l", 5);
1582 #endif
1583 #endif /* AIXHFT */
1585 #ifdef VMS
1586 /* Appears to do nothing when in PASTHRU mode.
1587 SYS$QIOW (0, input_fd, IO$_SETMODE|IO$M_OUTBAND, 0, 0, 0,
1588 interrupt_signal, oob_chars, 0, 0, 0, 0);
1590 queue_kbd_input (0);
1591 #endif /* VMS */
1594 #ifdef F_SETFL
1595 #ifndef F_SETOWN_BUG
1596 #ifdef F_GETOWN /* F_SETFL does not imply existence of F_GETOWN */
1597 if (interrupt_input
1598 && ! read_socket_hook && EQ (Vwindow_system, Qnil))
1600 old_fcntl_owner = fcntl (input_fd, F_GETOWN, 0);
1601 fcntl (input_fd, F_SETOWN, getpid ());
1602 init_sigio (input_fd);
1604 #endif /* F_GETOWN */
1605 #endif /* F_SETOWN_BUG */
1606 #endif /* F_SETFL */
1608 #ifdef BSD4_1
1609 if (interrupt_input)
1610 init_sigio (input_fd);
1611 #endif
1613 #ifdef VMS /* VMS sometimes has this symbol but lacks setvbuf. */
1614 #undef _IOFBF
1615 #endif
1616 #ifdef _IOFBF
1617 /* This symbol is defined on recent USG systems.
1618 Someone says without this call USG won't really buffer the file
1619 even with a call to setbuf. */
1620 setvbuf (stdout, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1621 #else
1622 setbuf (stdout, (char *) _sobuf);
1623 #endif
1624 #ifdef HAVE_WINDOW_SYSTEM
1625 /* Emacs' window system on MSDOG uses the `internal terminal' and therefore
1626 needs the initialization code below. */
1627 if (EQ (Vwindow_system, Qnil)
1628 #ifndef WINDOWSNT
1629 /* When running in tty mode on NT/Win95, we have a read_socket
1630 hook, but still need the rest of the initialization code below. */
1631 && (! read_socket_hook)
1632 #endif
1634 #endif
1635 set_terminal_modes ();
1637 if (!term_initted
1638 && FRAMEP (Vterminal_frame)
1639 && FRAME_TERMCAP_P (XFRAME (Vterminal_frame)))
1640 init_frame_faces (XFRAME (Vterminal_frame));
1642 if (term_initted && no_redraw_on_reenter)
1644 if (display_completed)
1645 direct_output_forward_char (0);
1647 else
1649 frame_garbaged = 1;
1650 if (FRAMEP (Vterminal_frame))
1651 FRAME_GARBAGED_P (XFRAME (Vterminal_frame)) = 1;
1654 term_initted = 1;
1657 /* Return nonzero if safe to use tabs in output.
1658 At the time this is called, init_sys_modes has not been done yet. */
1661 tabs_safe_p ()
1663 struct emacs_tty tty;
1665 EMACS_GET_TTY (input_fd, &tty);
1666 return EMACS_TTY_TABS_OK (&tty);
1669 /* Get terminal size from system.
1670 Store number of lines into *HEIGHTP and width into *WIDTHP.
1671 We store 0 if there's no valid information. */
1673 void
1674 get_frame_size (widthp, heightp)
1675 int *widthp, *heightp;
1678 #ifdef TIOCGWINSZ
1680 /* BSD-style. */
1681 struct winsize size;
1683 if (ioctl (input_fd, TIOCGWINSZ, &size) == -1)
1684 *widthp = *heightp = 0;
1685 else
1687 *widthp = size.ws_col;
1688 *heightp = size.ws_row;
1691 #else
1692 #ifdef TIOCGSIZE
1694 /* SunOS - style. */
1695 struct ttysize size;
1697 if (ioctl (input_fd, TIOCGSIZE, &size) == -1)
1698 *widthp = *heightp = 0;
1699 else
1701 *widthp = size.ts_cols;
1702 *heightp = size.ts_lines;
1705 #else
1706 #ifdef VMS
1708 struct sensemode tty;
1710 SYS$QIOW (0, input_fd, IO$_SENSEMODE, &tty, 0, 0,
1711 &tty.class, 12, 0, 0, 0, 0);
1712 *widthp = tty.scr_wid;
1713 *heightp = tty.scr_len;
1715 #else
1716 #ifdef MSDOS
1717 *widthp = ScreenCols ();
1718 *heightp = ScreenRows ();
1719 #else /* system doesn't know size */
1720 *widthp = 0;
1721 *heightp = 0;
1722 #endif
1724 #endif /* not VMS */
1725 #endif /* not SunOS-style */
1726 #endif /* not BSD-style */
1729 /* Set the logical window size associated with descriptor FD
1730 to HEIGHT and WIDTH. This is used mainly with ptys. */
1733 set_window_size (fd, height, width)
1734 int fd, height, width;
1736 #ifdef TIOCSWINSZ
1738 /* BSD-style. */
1739 struct winsize size;
1740 size.ws_row = height;
1741 size.ws_col = width;
1743 if (ioctl (fd, TIOCSWINSZ, &size) == -1)
1744 return 0; /* error */
1745 else
1746 return 1;
1748 #else
1749 #ifdef TIOCSSIZE
1751 /* SunOS - style. */
1752 struct ttysize size;
1753 size.ts_lines = height;
1754 size.ts_cols = width;
1756 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1757 return 0;
1758 else
1759 return 1;
1760 #else
1761 return -1;
1762 #endif /* not SunOS-style */
1763 #endif /* not BSD-style */
1767 /* Prepare the terminal for exiting Emacs; move the cursor to the
1768 bottom of the frame, turn off interrupt-driven I/O, etc. */
1769 void
1770 reset_sys_modes ()
1772 struct frame *sf;
1774 if (noninteractive)
1776 fflush (stdout);
1777 return;
1779 if (!term_initted)
1780 return;
1781 #ifdef HAVE_WINDOW_SYSTEM
1782 /* Emacs' window system on MSDOG uses the `internal terminal' and therefore
1783 needs the clean-up code below. */
1784 if (!EQ (Vwindow_system, Qnil)
1785 #ifndef WINDOWSNT
1786 /* When running in tty mode on NT/Win95, we have a read_socket
1787 hook, but still need the rest of the clean-up code below. */
1788 || read_socket_hook
1789 #endif
1791 return;
1792 #endif
1793 sf = SELECTED_FRAME ();
1794 cursor_to (FRAME_HEIGHT (sf) - 1, 0);
1795 clear_end_of_line (FRAME_WIDTH (sf));
1796 /* clear_end_of_line may move the cursor */
1797 cursor_to (FRAME_HEIGHT (sf) - 1, 0);
1798 #if defined (IBMR2AIX) && defined (AIXHFT)
1800 /* HFT devices normally use ^J as a LF/CR. We forced it to
1801 do the LF only. Now, we need to reset it. */
1802 struct termio tty;
1804 if (ioctl (1, HFTGETID, &tty) != -1)
1805 write (1, "\033[20h", 5);
1807 #endif
1809 reset_terminal_modes ();
1810 fflush (stdout);
1811 #ifdef BSD_SYSTEM
1812 #ifndef BSD4_1
1813 /* Avoid possible loss of output when changing terminal modes. */
1814 fsync (fileno (stdout));
1815 #endif
1816 #endif
1818 #ifdef F_SETFL
1819 #ifndef F_SETOWN_BUG
1820 #ifdef F_SETOWN /* F_SETFL does not imply existence of F_SETOWN */
1821 if (interrupt_input)
1823 reset_sigio ();
1824 fcntl (input_fd, F_SETOWN, old_fcntl_owner);
1826 #endif /* F_SETOWN */
1827 #endif /* F_SETOWN_BUG */
1828 #ifdef O_NDELAY
1829 fcntl (input_fd, F_SETFL, fcntl (input_fd, F_GETFL, 0) & ~O_NDELAY);
1830 #endif
1831 #endif /* F_SETFL */
1832 #ifdef BSD4_1
1833 if (interrupt_input)
1834 reset_sigio ();
1835 #endif /* BSD4_1 */
1837 if (old_tty_valid)
1838 while (EMACS_SET_TTY (input_fd, &old_tty, 0) < 0 && errno == EINTR)
1841 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1842 dos_ttcooked ();
1843 #endif
1845 #ifdef SET_LINE_DISCIPLINE
1846 /* Ultrix's termios *ignores* any line discipline except TERMIODISC.
1847 A different old line discipline is therefore not restored, yet.
1848 Restore the old line discipline by hand. */
1849 ioctl (0, TIOCSETD, &old_tty.main.c_line);
1850 #endif
1852 #ifdef AIXHFT
1853 hft_reset ();
1854 #endif
1856 #ifdef BSD_PGRPS
1857 widen_foreground_group ();
1858 #endif
1861 #ifdef HAVE_PTYS
1863 /* Set up the proper status flags for use of a pty. */
1865 void
1866 setup_pty (fd)
1867 int fd;
1869 /* I'm told that TOICREMOTE does not mean control chars
1870 "can't be sent" but rather that they don't have
1871 input-editing or signaling effects.
1872 That should be good, because we have other ways
1873 to do those things in Emacs.
1874 However, telnet mode seems not to work on 4.2.
1875 So TIOCREMOTE is turned off now. */
1877 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1878 will hang. In particular, the "timeout" feature (which
1879 causes a read to return if there is no data available)
1880 does this. Also it is known that telnet mode will hang
1881 in such a way that Emacs must be stopped (perhaps this
1882 is the same problem).
1884 If TIOCREMOTE is turned off, then there is a bug in
1885 hp-ux which sometimes loses data. Apparently the
1886 code which blocks the master process when the internal
1887 buffer fills up does not work. Other than this,
1888 though, everything else seems to work fine.
1890 Since the latter lossage is more benign, we may as well
1891 lose that way. -- cph */
1892 #ifdef FIONBIO
1893 #if defined(SYSV_PTYS) || defined(UNIX98_PTYS)
1895 int on = 1;
1896 ioctl (fd, FIONBIO, &on);
1898 #endif
1899 #endif
1900 #ifdef IBMRTAIX
1901 /* On AIX, the parent gets SIGHUP when a pty attached child dies. So, we */
1902 /* ignore SIGHUP once we've started a child on a pty. Note that this may */
1903 /* cause EMACS not to die when it should, i.e., when its own controlling */
1904 /* tty goes away. I've complained to the AIX developers, and they may */
1905 /* change this behavior, but I'm not going to hold my breath. */
1906 signal (SIGHUP, SIG_IGN);
1907 #endif
1909 #endif /* HAVE_PTYS */
1911 #ifdef VMS
1913 /* Assigning an input channel is done at the start of Emacs execution.
1914 This is called each time Emacs is resumed, also, but does nothing
1915 because input_chain is no longer zero. */
1917 void
1918 init_vms_input ()
1920 int status;
1922 if (input_fd == 0)
1924 status = SYS$ASSIGN (&input_dsc, &input_fd, 0, 0);
1925 if (! (status & 1))
1926 LIB$STOP (status);
1930 /* Deassigning the input channel is done before exiting. */
1932 void
1933 stop_vms_input ()
1935 return SYS$DASSGN (input_fd);
1938 short input_buffer;
1940 /* Request reading one character into the keyboard buffer.
1941 This is done as soon as the buffer becomes empty. */
1943 void
1944 queue_kbd_input ()
1946 int status;
1947 extern kbd_input_ast ();
1949 waiting_for_ast = 0;
1950 stop_input = 0;
1951 status = SYS$QIO (0, input_fd, IO$_READVBLK,
1952 &input_iosb, kbd_input_ast, 1,
1953 &input_buffer, 1, 0, terminator_mask, 0, 0);
1956 int input_count;
1958 /* Ast routine that is called when keyboard input comes in
1959 in accord with the SYS$QIO above. */
1961 void
1962 kbd_input_ast ()
1964 register int c = -1;
1965 int old_errno = errno;
1966 extern EMACS_TIME *input_available_clear_time;
1968 if (waiting_for_ast)
1969 SYS$SETEF (input_ef);
1970 waiting_for_ast = 0;
1971 input_count++;
1972 #ifdef ASTDEBUG
1973 if (input_count == 25)
1974 exit (1);
1975 printf ("Ast # %d,", input_count);
1976 printf (" iosb = %x, %x, %x, %x",
1977 input_iosb.offset, input_iosb.status, input_iosb.termlen,
1978 input_iosb.term);
1979 #endif
1980 if (input_iosb.offset)
1982 c = input_buffer;
1983 #ifdef ASTDEBUG
1984 printf (", char = 0%o", c);
1985 #endif
1987 #ifdef ASTDEBUG
1988 printf ("\n");
1989 fflush (stdout);
1990 sleep (1);
1991 #endif
1992 if (! stop_input)
1993 queue_kbd_input ();
1994 if (c >= 0)
1996 struct input_event e;
1997 e.kind = ascii_keystroke;
1998 XSETINT (e.code, c);
1999 e.frame_or_window = selected_frame;
2000 kbd_buffer_store_event (&e);
2002 if (input_available_clear_time)
2003 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
2004 errno = old_errno;
2007 /* Wait until there is something in kbd_buffer. */
2009 void
2010 wait_for_kbd_input ()
2012 extern int have_process_input, process_exited;
2014 /* If already something, avoid doing system calls. */
2015 if (detect_input_pending ())
2017 return;
2019 /* Clear a flag, and tell ast routine above to set it. */
2020 SYS$CLREF (input_ef);
2021 waiting_for_ast = 1;
2022 /* Check for timing error: ast happened while we were doing that. */
2023 if (!detect_input_pending ())
2025 /* No timing error: wait for flag to be set. */
2026 set_waiting_for_input (0);
2027 SYS$WFLOR (input_ef, input_eflist);
2028 clear_waiting_for_input (0);
2029 if (!detect_input_pending ())
2030 /* Check for subprocess input availability */
2032 int dsp = have_process_input || process_exited;
2034 SYS$CLREF (process_ef);
2035 if (have_process_input)
2036 process_command_input ();
2037 if (process_exited)
2038 process_exit ();
2039 if (dsp)
2041 update_mode_lines++;
2042 prepare_menu_bars ();
2043 redisplay_preserve_echo_area ();
2047 waiting_for_ast = 0;
2050 /* Get rid of any pending QIO, when we are about to suspend
2051 or when we want to throw away pending input.
2052 We wait for a positive sign that the AST routine has run
2053 and therefore there is no I/O request queued when we return.
2054 SYS$SETAST is used to avoid a timing error. */
2056 void
2057 end_kbd_input ()
2059 #ifdef ASTDEBUG
2060 printf ("At end_kbd_input.\n");
2061 fflush (stdout);
2062 sleep (1);
2063 #endif
2064 if (LIB$AST_IN_PROG ()) /* Don't wait if suspending from kbd_buffer_store_event! */
2066 SYS$CANCEL (input_fd);
2067 return;
2070 SYS$SETAST (0);
2071 /* Clear a flag, and tell ast routine above to set it. */
2072 SYS$CLREF (input_ef);
2073 waiting_for_ast = 1;
2074 stop_input = 1;
2075 SYS$CANCEL (input_fd);
2076 SYS$SETAST (1);
2077 SYS$WAITFR (input_ef);
2078 waiting_for_ast = 0;
2081 /* Wait for either input available or time interval expiry. */
2083 void
2084 input_wait_timeout (timeval)
2085 int timeval; /* Time to wait, in seconds */
2087 int time [2];
2088 static int zero = 0;
2089 static int large = -10000000;
2091 LIB$EMUL (&timeval, &large, &zero, time); /* Convert to VMS format */
2093 /* If already something, avoid doing system calls. */
2094 if (detect_input_pending ())
2096 return;
2098 /* Clear a flag, and tell ast routine above to set it. */
2099 SYS$CLREF (input_ef);
2100 waiting_for_ast = 1;
2101 /* Check for timing error: ast happened while we were doing that. */
2102 if (!detect_input_pending ())
2104 /* No timing error: wait for flag to be set. */
2105 SYS$CANTIM (1, 0);
2106 if (SYS$SETIMR (timer_ef, time, 0, 1) & 1) /* Set timer */
2107 SYS$WFLOR (timer_ef, timer_eflist); /* Wait for timer expiry or input */
2109 waiting_for_ast = 0;
2112 /* The standard `sleep' routine works some other way
2113 and it stops working if you have ever quit out of it.
2114 This one continues to work. */
2116 sys_sleep (timeval)
2117 int timeval;
2119 int time [2];
2120 static int zero = 0;
2121 static int large = -10000000;
2123 LIB$EMUL (&timeval, &large, &zero, time); /* Convert to VMS format */
2125 SYS$CANTIM (1, 0);
2126 if (SYS$SETIMR (timer_ef, time, 0, 1) & 1) /* Set timer */
2127 SYS$WAITFR (timer_ef); /* Wait for timer expiry only */
2130 void
2131 init_sigio (fd)
2132 int fd;
2134 request_sigio ();
2137 reset_sigio ()
2139 unrequest_sigio ();
2142 void
2143 request_sigio ()
2145 croak ("request sigio");
2148 void
2149 unrequest_sigio ()
2151 croak ("unrequest sigio");
2154 #endif /* VMS */
2156 /* Note that VMS compiler won't accept defined (CANNOT_DUMP). */
2157 #ifndef CANNOT_DUMP
2158 #define NEED_STARTS
2159 #endif
2161 #ifndef SYSTEM_MALLOC
2162 #ifndef NEED_STARTS
2163 #define NEED_STARTS
2164 #endif
2165 #endif
2167 #ifdef NEED_STARTS
2168 /* Some systems that cannot dump also cannot implement these. */
2171 * Return the address of the start of the text segment prior to
2172 * doing an unexec. After unexec the return value is undefined.
2173 * See crt0.c for further explanation and _start.
2177 #if !(defined (__NetBSD__) && defined (__ELF__))
2178 #ifndef HAVE_TEXT_START
2179 char *
2180 start_of_text ()
2182 #ifdef TEXT_START
2183 return ((char *) TEXT_START);
2184 #else
2185 #ifdef GOULD
2186 extern csrt ();
2187 return ((char *) csrt);
2188 #else /* not GOULD */
2189 extern int _start ();
2190 return ((char *) _start);
2191 #endif /* GOULD */
2192 #endif /* TEXT_START */
2194 #endif /* not HAVE_TEXT_START */
2195 #endif
2198 * Return the address of the start of the data segment prior to
2199 * doing an unexec. After unexec the return value is undefined.
2200 * See crt0.c for further information and definition of data_start.
2202 * Apparently, on BSD systems this is etext at startup. On
2203 * USG systems (swapping) this is highly mmu dependent and
2204 * is also dependent on whether or not the program is running
2205 * with shared text. Generally there is a (possibly large)
2206 * gap between end of text and start of data with shared text.
2208 * On Uniplus+ systems with shared text, data starts at a
2209 * fixed address. Each port (from a given oem) is generally
2210 * different, and the specific value of the start of data can
2211 * be obtained via the UniPlus+ specific "uvar" system call,
2212 * however the method outlined in crt0.c seems to be more portable.
2214 * Probably what will have to happen when a USG unexec is available,
2215 * at least on UniPlus, is temacs will have to be made unshared so
2216 * that text and data are contiguous. Then once loadup is complete,
2217 * unexec will produce a shared executable where the data can be
2218 * at the normal shared text boundary and the startofdata variable
2219 * will be patched by unexec to the correct value.
2223 char *
2224 start_of_data ()
2226 #ifdef DATA_START
2227 return ((char *) DATA_START);
2228 #else
2229 #ifdef ORDINARY_LINK
2231 * This is a hack. Since we're not linking crt0.c or pre_crt0.c,
2232 * data_start isn't defined. We take the address of environ, which
2233 * is known to live at or near the start of the system crt0.c, and
2234 * we don't sweat the handful of bytes that might lose.
2236 extern char **environ;
2238 return ((char *) &environ);
2239 #else
2240 extern int data_start;
2241 return ((char *) &data_start);
2242 #endif /* ORDINARY_LINK */
2243 #endif /* DATA_START */
2245 #endif /* NEED_STARTS (not CANNOT_DUMP or not SYSTEM_MALLOC) */
2247 #ifndef CANNOT_DUMP
2248 /* Some systems that cannot dump also cannot implement these. */
2251 * Return the address of the end of the text segment prior to
2252 * doing an unexec. After unexec the return value is undefined.
2255 char *
2256 end_of_text ()
2258 #ifdef TEXT_END
2259 return ((char *) TEXT_END);
2260 #else
2261 extern int etext;
2262 return ((char *) &etext);
2263 #endif
2267 * Return the address of the end of the data segment prior to
2268 * doing an unexec. After unexec the return value is undefined.
2271 char *
2272 end_of_data ()
2274 #ifdef DATA_END
2275 return ((char *) DATA_END);
2276 #else
2277 extern int edata;
2278 return ((char *) &edata);
2279 #endif
2282 #endif /* not CANNOT_DUMP */
2284 /* init_system_name sets up the string for the Lisp function
2285 system-name to return. */
2287 #ifdef BSD4_1
2288 #include <whoami.h>
2289 #endif
2291 extern Lisp_Object Vsystem_name;
2293 #ifndef BSD4_1
2294 #ifndef VMS
2295 #ifdef HAVE_SOCKETS
2296 #include <sys/socket.h>
2297 #include <netdb.h>
2298 #endif /* HAVE_SOCKETS */
2299 #endif /* not VMS */
2300 #endif /* not BSD4_1 */
2302 void
2303 init_system_name ()
2305 #ifdef BSD4_1
2306 Vsystem_name = build_string (sysname);
2307 #else
2308 #ifdef VMS
2309 char *sp, *end;
2310 if ((sp = egetenv ("SYS$NODE")) == 0)
2311 Vsystem_name = build_string ("vax-vms");
2312 else if ((end = index (sp, ':')) == 0)
2313 Vsystem_name = build_string (sp);
2314 else
2315 Vsystem_name = make_string (sp, end - sp);
2316 #else
2317 #ifndef HAVE_GETHOSTNAME
2318 struct utsname uts;
2319 uname (&uts);
2320 Vsystem_name = build_string (uts.nodename);
2321 #else /* HAVE_GETHOSTNAME */
2322 unsigned int hostname_size = 256;
2323 char *hostname = (char *) alloca (hostname_size);
2325 /* Try to get the host name; if the buffer is too short, try
2326 again. Apparently, the only indication gethostname gives of
2327 whether the buffer was large enough is the presence or absence
2328 of a '\0' in the string. Eech. */
2329 for (;;)
2331 gethostname (hostname, hostname_size - 1);
2332 hostname[hostname_size - 1] = '\0';
2334 /* Was the buffer large enough for the '\0'? */
2335 if (strlen (hostname) < hostname_size - 1)
2336 break;
2338 hostname_size <<= 1;
2339 hostname = (char *) alloca (hostname_size);
2341 #ifdef HAVE_SOCKETS
2342 /* Turn the hostname into the official, fully-qualified hostname.
2343 Don't do this if we're going to dump; this can confuse system
2344 libraries on some machines and make the dumped emacs core dump. */
2345 #ifndef CANNOT_DUMP
2346 if (initialized)
2347 #endif /* not CANNOT_DUMP */
2348 if (! index (hostname, '.'))
2350 struct hostent *hp;
2351 int count;
2352 for (count = 0;; count++)
2354 #ifdef TRY_AGAIN
2355 h_errno = 0;
2356 #endif
2357 hp = gethostbyname (hostname);
2358 #ifdef TRY_AGAIN
2359 if (! (hp == 0 && h_errno == TRY_AGAIN))
2360 #endif
2361 break;
2362 if (count >= 5)
2363 break;
2364 Fsleep_for (make_number (1), Qnil);
2366 if (hp)
2368 char *fqdn = (char *) hp->h_name;
2369 char *p;
2371 if (!index (fqdn, '.'))
2373 /* We still don't have a fully qualified domain name.
2374 Try to find one in the list of alternate names */
2375 char **alias = hp->h_aliases;
2376 while (*alias && !index (*alias, '.'))
2377 alias++;
2378 if (*alias)
2379 fqdn = *alias;
2381 hostname = fqdn;
2382 #if 0
2383 /* Convert the host name to lower case. */
2384 /* Using ctype.h here would introduce a possible locale
2385 dependence that is probably wrong for hostnames. */
2386 p = hostname;
2387 while (*p)
2389 if (*p >= 'A' && *p <= 'Z')
2390 *p += 'a' - 'A';
2391 p++;
2393 #endif
2396 #endif /* HAVE_SOCKETS */
2397 /* We used to try using getdomainname here,
2398 but NIIBE Yutaka <gniibe@etl.go.jp> says that
2399 getdomainname gets the NIS/YP domain which often is not the same
2400 as in Internet domain name. */
2401 #if 0 /* Turned off because sysinfo is not really likely to return the
2402 correct Internet domain. */
2403 #if (HAVE_SYSINFO && defined (SI_SRPC_DOMAIN))
2404 if (! index (hostname, '.'))
2406 /* The hostname is not fully qualified. Append the domain name. */
2408 int hostlen = strlen (hostname);
2409 int domain_size = 256;
2411 for (;;)
2413 char *domain = (char *) alloca (domain_size + 1);
2414 char *fqdn = (char *) alloca (hostlen + 1 + domain_size + 1);
2415 int sys_domain_size = sysinfo (SI_SRPC_DOMAIN, domain, domain_size);
2416 if (sys_domain_size <= 0)
2417 break;
2418 if (domain_size < sys_domain_size)
2420 domain_size = sys_domain_size;
2421 continue;
2423 strcpy (fqdn, hostname);
2424 if (domain[0] == '.')
2425 strcpy (fqdn + hostlen, domain);
2426 else if (domain[0] != 0)
2428 fqdn[hostlen] = '.';
2429 strcpy (fqdn + hostlen + 1, domain);
2431 hostname = fqdn;
2432 break;
2435 #endif /* HAVE_SYSINFO && defined (SI_SRPC_DOMAIN) */
2436 #endif /* 0 */
2437 Vsystem_name = build_string (hostname);
2438 #endif /* HAVE_GETHOSTNAME */
2439 #endif /* VMS */
2440 #endif /* BSD4_1 */
2442 unsigned char *p;
2443 for (p = XSTRING (Vsystem_name)->data; *p; p++)
2444 if (*p == ' ' || *p == '\t')
2445 *p = '-';
2449 #ifndef MSDOS
2450 #ifndef VMS
2451 #if !defined (HAVE_SELECT) || defined (BROKEN_SELECT_NON_X)
2453 #include "sysselect.h"
2454 #undef select
2456 #if defined (HAVE_X_WINDOWS) && !defined (HAVE_SELECT)
2457 /* Cause explanatory error message at compile time,
2458 since the select emulation is not good enough for X. */
2459 int *x = &x_windows_lose_if_no_select_system_call;
2460 #endif
2462 /* Emulate as much as select as is possible under 4.1 and needed by Gnu Emacs
2463 * Only checks read descriptors.
2465 /* How long to wait between checking fds in select */
2466 #define SELECT_PAUSE 1
2467 int select_alarmed;
2469 /* For longjmp'ing back to read_input_waiting. */
2471 jmp_buf read_alarm_throw;
2473 /* Nonzero if the alarm signal should throw back to read_input_waiting.
2474 The read_socket_hook function sets this to 1 while it is waiting. */
2476 int read_alarm_should_throw;
2478 SIGTYPE
2479 select_alarm ()
2481 select_alarmed = 1;
2482 #ifdef BSD4_1
2483 sigrelse (SIGALRM);
2484 #else /* not BSD4_1 */
2485 signal (SIGALRM, SIG_IGN);
2486 #endif /* not BSD4_1 */
2487 if (read_alarm_should_throw)
2488 longjmp (read_alarm_throw, 1);
2491 #ifndef WINDOWSNT
2492 /* Only rfds are checked. */
2494 sys_select (nfds, rfds, wfds, efds, timeout)
2495 int nfds;
2496 SELECT_TYPE *rfds, *wfds, *efds;
2497 EMACS_TIME *timeout;
2499 int ravail = 0;
2500 SELECT_TYPE orfds;
2501 int timeoutval;
2502 int *local_timeout;
2503 extern int proc_buffered_char[];
2504 #ifndef subprocesses
2505 int process_tick = 0, update_tick = 0;
2506 #else
2507 extern int process_tick, update_tick;
2508 #endif
2509 unsigned char buf;
2511 #if defined (HAVE_SELECT) && defined (HAVE_X_WINDOWS)
2512 /* If we're using X, then the native select will work; we only need the
2513 emulation for non-X usage. */
2514 if (!NILP (Vwindow_system))
2515 return select (nfds, rfds, wfds, efds, timeout);
2516 #endif
2517 timeoutval = timeout ? EMACS_SECS (*timeout) : 100000;
2518 local_timeout = &timeoutval;
2519 FD_ZERO (&orfds);
2520 if (rfds)
2522 orfds = *rfds;
2523 FD_ZERO (rfds);
2525 if (wfds)
2526 FD_ZERO (wfds);
2527 if (efds)
2528 FD_ZERO (efds);
2530 /* If we are looking only for the terminal, with no timeout,
2531 just read it and wait -- that's more efficient. */
2532 if (*local_timeout == 100000 && process_tick == update_tick
2533 && FD_ISSET (0, &orfds))
2535 int fd;
2536 for (fd = 1; fd < nfds; ++fd)
2537 if (FD_ISSET (fd, &orfds))
2538 goto hardway;
2539 if (! detect_input_pending ())
2540 read_input_waiting ();
2541 FD_SET (0, rfds);
2542 return 1;
2545 hardway:
2546 /* Once a second, till the timer expires, check all the flagged read
2547 * descriptors to see if any input is available. If there is some then
2548 * set the corresponding bit in the return copy of rfds.
2550 while (1)
2552 register int to_check, fd;
2554 if (rfds)
2556 for (to_check = nfds, fd = 0; --to_check >= 0; fd++)
2558 if (FD_ISSET (fd, &orfds))
2560 int avail = 0, status = 0;
2562 if (fd == 0)
2563 avail = detect_input_pending (); /* Special keyboard handler */
2564 else
2566 #ifdef FIONREAD
2567 status = ioctl (fd, FIONREAD, &avail);
2568 #else /* no FIONREAD */
2569 /* Hoping it will return -1 if nothing available
2570 or 0 if all 0 chars requested are read. */
2571 if (proc_buffered_char[fd] >= 0)
2572 avail = 1;
2573 else
2575 avail = read (fd, &buf, 1);
2576 if (avail > 0)
2577 proc_buffered_char[fd] = buf;
2579 #endif /* no FIONREAD */
2581 if (status >= 0 && avail > 0)
2583 FD_SET (fd, rfds);
2584 ravail++;
2589 if (*local_timeout == 0 || ravail != 0 || process_tick != update_tick)
2590 break;
2592 turn_on_atimers (0);
2593 signal (SIGALRM, select_alarm);
2594 select_alarmed = 0;
2595 alarm (SELECT_PAUSE);
2597 /* Wait for a SIGALRM (or maybe a SIGTINT) */
2598 while (select_alarmed == 0 && *local_timeout != 0
2599 && process_tick == update_tick)
2601 /* If we are interested in terminal input,
2602 wait by reading the terminal.
2603 That makes instant wakeup for terminal input at least. */
2604 if (FD_ISSET (0, &orfds))
2606 read_input_waiting ();
2607 if (detect_input_pending ())
2608 select_alarmed = 1;
2610 else
2611 pause ();
2613 (*local_timeout) -= SELECT_PAUSE;
2615 /* Reset the old alarm if there was one. */
2616 turn_on_atimers (1);
2618 if (*local_timeout == 0) /* Stop on timer being cleared */
2619 break;
2621 return ravail;
2623 #endif /* not WINDOWSNT */
2625 /* Read keyboard input into the standard buffer,
2626 waiting for at least one character. */
2628 /* Make all keyboard buffers much bigger when using a window system. */
2629 #ifdef HAVE_WINDOW_SYSTEM
2630 #define BUFFER_SIZE_FACTOR 16
2631 #else
2632 #define BUFFER_SIZE_FACTOR 1
2633 #endif
2635 void
2636 read_input_waiting ()
2638 struct input_event e;
2639 int nread, i;
2640 extern int quit_char;
2642 if (read_socket_hook)
2644 struct input_event buf[256];
2646 read_alarm_should_throw = 0;
2647 if (! setjmp (read_alarm_throw))
2648 nread = (*read_socket_hook) (0, buf, 256, 1);
2649 else
2650 nread = -1;
2652 /* Scan the chars for C-g and store them in kbd_buffer. */
2653 for (i = 0; i < nread; i++)
2655 kbd_buffer_store_event (&buf[i]);
2656 /* Don't look at input that follows a C-g too closely.
2657 This reduces lossage due to autorepeat on C-g. */
2658 if (buf[i].kind == ascii_keystroke
2659 && buf[i].code == quit_char)
2660 break;
2663 else
2665 char buf[3];
2666 nread = read (fileno (stdin), buf, 1);
2668 /* Scan the chars for C-g and store them in kbd_buffer. */
2669 e.kind = ascii_keystroke;
2670 e.frame_or_window = selected_frame;
2671 e.modifiers = 0;
2672 for (i = 0; i < nread; i++)
2674 /* Convert chars > 0177 to meta events if desired.
2675 We do this under the same conditions that read_avail_input does. */
2676 if (read_socket_hook == 0)
2678 /* If the user says she has a meta key, then believe her. */
2679 if (meta_key == 1 && (buf[i] & 0x80))
2680 e.modifiers = meta_modifier;
2681 if (meta_key != 2)
2682 buf[i] &= ~0x80;
2685 XSETINT (e.code, buf[i]);
2686 kbd_buffer_store_event (&e);
2687 /* Don't look at input that follows a C-g too closely.
2688 This reduces lossage due to autorepeat on C-g. */
2689 if (buf[i] == quit_char)
2690 break;
2695 #endif /* not HAVE_SELECT */
2696 #endif /* not VMS */
2697 #endif /* not MSDOS */
2699 #ifdef BSD4_1
2700 void
2701 init_sigio (fd)
2702 int fd;
2704 if (noninteractive)
2705 return;
2706 lmode = LINTRUP | lmode;
2707 ioctl (fd, TIOCLSET, &lmode);
2710 void
2711 reset_sigio ()
2713 if (noninteractive)
2714 return;
2715 lmode = ~LINTRUP & lmode;
2716 ioctl (0, TIOCLSET, &lmode);
2719 void
2720 request_sigio ()
2722 sigrelse (SIGTINT);
2724 interrupts_deferred = 0;
2727 void
2728 unrequest_sigio ()
2730 sighold (SIGTINT);
2732 interrupts_deferred = 1;
2735 /* still inside #ifdef BSD4_1 */
2736 #ifdef subprocesses
2738 int sigheld; /* Mask of held signals */
2740 void
2741 sigholdx (signum)
2742 int signum;
2744 sigheld |= sigbit (signum);
2745 sighold (signum);
2748 void
2749 sigisheld (signum)
2750 int signum;
2752 sigheld |= sigbit (signum);
2755 void
2756 sigunhold (signum)
2757 int signum;
2759 sigheld &= ~sigbit (signum);
2760 sigrelse (signum);
2763 void
2764 sigfree () /* Free all held signals */
2766 int i;
2767 for (i = 0; i < NSIG; i++)
2768 if (sigheld & sigbit (i))
2769 sigrelse (i);
2770 sigheld = 0;
2774 sigbit (i)
2776 return 1 << (i - 1);
2778 #endif /* subprocesses */
2779 #endif /* BSD4_1 */
2781 /* POSIX signals support - DJB */
2782 /* Anyone with POSIX signals should have ANSI C declarations */
2784 #ifdef POSIX_SIGNALS
2786 sigset_t empty_mask, full_mask;
2788 signal_handler_t
2789 sys_signal (int signal_number, signal_handler_t action)
2791 struct sigaction new_action, old_action;
2792 sigemptyset (&new_action.sa_mask);
2793 new_action.sa_handler = action;
2794 #ifdef SA_RESTART
2795 /* Emacs mostly works better with restartable system services. If this
2796 * flag exists, we probably want to turn it on here.
2798 new_action.sa_flags = SA_RESTART;
2799 #else
2800 new_action.sa_flags = 0;
2801 #endif
2802 sigaction (signal_number, &new_action, &old_action);
2803 return (old_action.sa_handler);
2806 #ifndef __GNUC__
2807 /* If we're compiling with GCC, we don't need this function, since it
2808 can be written as a macro. */
2809 sigset_t
2810 sys_sigmask (int sig)
2812 sigset_t mask;
2813 sigemptyset (&mask);
2814 sigaddset (&mask, sig);
2815 return mask;
2817 #endif
2819 /* I'd like to have these guys return pointers to the mask storage in here,
2820 but there'd be trouble if the code was saving multiple masks. I'll be
2821 safe and pass the structure. It normally won't be more than 2 bytes
2822 anyhow. - DJB */
2824 sigset_t
2825 sys_sigblock (sigset_t new_mask)
2827 sigset_t old_mask;
2828 sigprocmask (SIG_BLOCK, &new_mask, &old_mask);
2829 return (old_mask);
2832 sigset_t
2833 sys_sigunblock (sigset_t new_mask)
2835 sigset_t old_mask;
2836 sigprocmask (SIG_UNBLOCK, &new_mask, &old_mask);
2837 return (old_mask);
2840 sigset_t
2841 sys_sigsetmask (sigset_t new_mask)
2843 sigset_t old_mask;
2844 sigprocmask (SIG_SETMASK, &new_mask, &old_mask);
2845 return (old_mask);
2848 #endif /* POSIX_SIGNALS */
2850 #if !defined HAVE_STRSIGNAL && !defined SYS_SIGLIST_DECLARED
2851 static char *my_sys_siglist[NSIG];
2852 # ifdef sys_siglist
2853 # undef sys_siglist
2854 # endif
2855 # define sys_siglist my_sys_siglist
2856 #endif
2858 void
2859 init_signals ()
2861 #ifdef POSIX_SIGNALS
2862 sigemptyset (&empty_mask);
2863 sigfillset (&full_mask);
2864 #endif
2866 #if !defined HAVE_STRSIGNAL && !defined SYS_SIGLIST_DECLARED
2867 if (! initialized)
2869 # ifdef SIGABRT
2870 sys_siglist[SIGABRT] = "Aborted";
2871 # endif
2872 # ifdef SIGAIO
2873 sys_siglist[SIGAIO] = "LAN I/O interrupt";
2874 # endif
2875 # ifdef SIGALRM
2876 sys_siglist[SIGALRM] = "Alarm clock";
2877 # endif
2878 # ifdef SIGBUS
2879 sys_siglist[SIGBUS] = "Bus error";
2880 # endif
2881 # ifdef SIGCLD
2882 sys_siglist[SIGCLD] = "Child status changed";
2883 # endif
2884 # ifdef SIGCHLD
2885 sys_siglist[SIGCHLD] = "Child status changed";
2886 # endif
2887 # ifdef SIGCONT
2888 sys_siglist[SIGCONT] = "Continued";
2889 # endif
2890 # ifdef SIGDANGER
2891 sys_siglist[SIGDANGER] = "Swap space dangerously low";
2892 # endif
2893 # ifdef SIGDGNOTIFY
2894 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
2895 # endif
2896 # ifdef SIGEMT
2897 sys_siglist[SIGEMT] = "Emulation trap";
2898 # endif
2899 # ifdef SIGFPE
2900 sys_siglist[SIGFPE] = "Arithmetic exception";
2901 # endif
2902 # ifdef SIGFREEZE
2903 sys_siglist[SIGFREEZE] = "SIGFREEZE";
2904 # endif
2905 # ifdef SIGGRANT
2906 sys_siglist[SIGGRANT] = "Monitor mode granted";
2907 # endif
2908 # ifdef SIGHUP
2909 sys_siglist[SIGHUP] = "Hangup";
2910 # endif
2911 # ifdef SIGILL
2912 sys_siglist[SIGILL] = "Illegal instruction";
2913 # endif
2914 # ifdef SIGINT
2915 sys_siglist[SIGINT] = "Interrupt";
2916 # endif
2917 # ifdef SIGIO
2918 sys_siglist[SIGIO] = "I/O possible";
2919 # endif
2920 # ifdef SIGIOINT
2921 sys_siglist[SIGIOINT] = "I/O intervention required";
2922 # endif
2923 # ifdef SIGIOT
2924 sys_siglist[SIGIOT] = "IOT trap";
2925 # endif
2926 # ifdef SIGKILL
2927 sys_siglist[SIGKILL] = "Killed";
2928 # endif
2929 # ifdef SIGLOST
2930 sys_siglist[SIGLOST] = "Resource lost";
2931 # endif
2932 # ifdef SIGLWP
2933 sys_siglist[SIGLWP] = "SIGLWP";
2934 # endif
2935 # ifdef SIGMSG
2936 sys_siglist[SIGMSG] = "Monitor mode data available";
2937 # endif
2938 # ifdef SIGPHONE
2939 sys_siglist[SIGWIND] = "SIGPHONE";
2940 # endif
2941 # ifdef SIGPIPE
2942 sys_siglist[SIGPIPE] = "Broken pipe";
2943 # endif
2944 # ifdef SIGPOLL
2945 sys_siglist[SIGPOLL] = "Pollable event occurred";
2946 # endif
2947 # ifdef SIGPROF
2948 sys_siglist[SIGPROF] = "Profiling timer expired";
2949 # endif
2950 # ifdef SIGPTY
2951 sys_siglist[SIGPTY] = "PTY I/O interrupt";
2952 # endif
2953 # ifdef SIGPWR
2954 sys_siglist[SIGPWR] = "Power-fail restart";
2955 # endif
2956 # ifdef SIGQUIT
2957 sys_siglist[SIGQUIT] = "Quit";
2958 # endif
2959 # ifdef SIGRETRACT
2960 sys_siglist[SIGRETRACT] = "Need to relinguish monitor mode";
2961 # endif
2962 # ifdef SIGSAK
2963 sys_siglist[SIGSAK] = "Secure attention";
2964 # endif
2965 # ifdef SIGSEGV
2966 sys_siglist[SIGSEGV] = "Segmentation violation";
2967 # endif
2968 # ifdef SIGSOUND
2969 sys_siglist[SIGSOUND] = "Sound completed";
2970 # endif
2971 # ifdef SIGSTOP
2972 sys_siglist[SIGSTOP] = "Stopped (signal)";
2973 # endif
2974 # ifdef SIGSTP
2975 sys_siglist[SIGSTP] = "Stopped (user)";
2976 # endif
2977 # ifdef SIGSYS
2978 sys_siglist[SIGSYS] = "Bad argument to system call";
2979 # endif
2980 # ifdef SIGTERM
2981 sys_siglist[SIGTERM] = "Terminated";
2982 # endif
2983 # ifdef SIGTHAW
2984 sys_siglist[SIGTHAW] = "SIGTHAW";
2985 # endif
2986 # ifdef SIGTRAP
2987 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
2988 # endif
2989 # ifdef SIGTSTP
2990 sys_siglist[SIGTSTP] = "Stopped (user)";
2991 # endif
2992 # ifdef SIGTTIN
2993 sys_siglist[SIGTTIN] = "Stopped (tty input)";
2994 # endif
2995 # ifdef SIGTTOU
2996 sys_siglist[SIGTTOU] = "Stopped (tty output)";
2997 # endif
2998 # ifdef SIGURG
2999 sys_siglist[SIGURG] = "Urgent I/O condition";
3000 # endif
3001 # ifdef SIGUSR1
3002 sys_siglist[SIGUSR1] = "User defined signal 1";
3003 # endif
3004 # ifdef SIGUSR2
3005 sys_siglist[SIGUSR2] = "User defined signal 2";
3006 # endif
3007 # ifdef SIGVTALRM
3008 sys_siglist[SIGVTALRM] = "Virtual timer expired";
3009 # endif
3010 # ifdef SIGWAITING
3011 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
3012 # endif
3013 # ifdef SIGWINCH
3014 sys_siglist[SIGWINCH] = "Window size changed";
3015 # endif
3016 # ifdef SIGWIND
3017 sys_siglist[SIGWIND] = "SIGWIND";
3018 # endif
3019 # ifdef SIGXCPU
3020 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
3021 # endif
3022 # ifdef SIGXFSZ
3023 sys_siglist[SIGXFSZ] = "File size limit exceeded";
3024 # endif
3026 #endif /* !defined HAVE_STRSIGNAL && !defined SYS_SIGLIST_DECLARED */
3029 #ifndef HAVE_RANDOM
3030 #ifdef random
3031 #define HAVE_RANDOM
3032 #endif
3033 #endif
3035 /* Figure out how many bits the system's random number generator uses.
3036 `random' and `lrand48' are assumed to return 31 usable bits.
3037 BSD `rand' returns a 31 bit value but the low order bits are unusable;
3038 so we'll shift it and treat it like the 15-bit USG `rand'. */
3040 #ifndef RAND_BITS
3041 # ifdef HAVE_RANDOM
3042 # define RAND_BITS 31
3043 # else /* !HAVE_RANDOM */
3044 # ifdef HAVE_LRAND48
3045 # define RAND_BITS 31
3046 # define random lrand48
3047 # else /* !HAVE_LRAND48 */
3048 # define RAND_BITS 15
3049 # if RAND_MAX == 32767
3050 # define random rand
3051 # else /* RAND_MAX != 32767 */
3052 # if RAND_MAX == 2147483647
3053 # define random() (rand () >> 16)
3054 # else /* RAND_MAX != 2147483647 */
3055 # ifdef USG
3056 # define random rand
3057 # else
3058 # define random() (rand () >> 16)
3059 # endif /* !USG */
3060 # endif /* RAND_MAX != 2147483647 */
3061 # endif /* RAND_MAX != 32767 */
3062 # endif /* !HAVE_LRAND48 */
3063 # endif /* !HAVE_RANDOM */
3064 #endif /* !RAND_BITS */
3066 void
3067 seed_random (arg)
3068 long arg;
3070 #ifdef HAVE_RANDOM
3071 srandom ((unsigned int)arg);
3072 #else
3073 # ifdef HAVE_LRAND48
3074 srand48 (arg);
3075 # else
3076 srand ((unsigned int)arg);
3077 # endif
3078 #endif
3082 * Build a full Emacs-sized word out of whatever we've got.
3083 * This suffices even for a 64-bit architecture with a 15-bit rand.
3085 long
3086 get_random ()
3088 long val = random ();
3089 #if VALBITS > RAND_BITS
3090 val = (val << RAND_BITS) ^ random ();
3091 #if VALBITS > 2*RAND_BITS
3092 val = (val << RAND_BITS) ^ random ();
3093 #if VALBITS > 3*RAND_BITS
3094 val = (val << RAND_BITS) ^ random ();
3095 #if VALBITS > 4*RAND_BITS
3096 val = (val << RAND_BITS) ^ random ();
3097 #endif /* need at least 5 */
3098 #endif /* need at least 4 */
3099 #endif /* need at least 3 */
3100 #endif /* need at least 2 */
3101 return val & ((1L << VALBITS) - 1);
3104 #ifdef WRONG_NAME_INSQUE
3106 insque (q,p)
3107 caddr_t q,p;
3109 _insque (q,p);
3112 #endif
3114 #ifdef VMS
3116 #ifdef getenv
3117 /* If any place else asks for the TERM variable,
3118 allow it to be overridden with the EMACS_TERM variable
3119 before attempting to translate the logical name TERM. As a last
3120 resort, ask for VAX C's special idea of the TERM variable. */
3121 #undef getenv
3122 char *
3123 sys_getenv (name)
3124 char *name;
3126 register char *val;
3127 static char buf[256];
3128 static struct dsc$descriptor_s equiv
3129 = {sizeof (buf), DSC$K_DTYPE_T, DSC$K_CLASS_S, buf};
3130 static struct dsc$descriptor_s d_name
3131 = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
3132 short eqlen;
3134 if (!strcmp (name, "TERM"))
3136 val = (char *) getenv ("EMACS_TERM");
3137 if (val)
3138 return val;
3141 d_name.dsc$w_length = strlen (name);
3142 d_name.dsc$a_pointer = name;
3143 if (LIB$SYS_TRNLOG (&d_name, &eqlen, &equiv) == 1)
3145 char *str = (char *) xmalloc (eqlen + 1);
3146 bcopy (buf, str, eqlen);
3147 str[eqlen] = '\0';
3148 /* This is a storage leak, but a pain to fix. With luck,
3149 no one will ever notice. */
3150 return str;
3152 return (char *) getenv (name);
3154 #endif /* getenv */
3156 #ifdef abort
3157 /* Since VMS doesn't believe in core dumps, the only way to debug this beast is
3158 to force a call on the debugger from within the image. */
3159 #undef abort
3160 sys_abort ()
3162 reset_sys_modes ();
3163 LIB$SIGNAL (SS$_DEBUG);
3165 #endif /* abort */
3166 #endif /* VMS */
3168 #ifdef VMS
3169 #ifdef LINK_CRTL_SHARE
3170 #ifdef SHARABLE_LIB_BUG
3171 /* Variables declared noshare and initialized in sharable libraries
3172 cannot be shared. The VMS linker incorrectly forces you to use a private
3173 version which is uninitialized... If not for this "feature", we
3174 could use the C library definition of sys_nerr and sys_errlist. */
3175 int sys_nerr = 35;
3176 char *sys_errlist[] =
3178 "error 0",
3179 "not owner",
3180 "no such file or directory",
3181 "no such process",
3182 "interrupted system call",
3183 "i/o error",
3184 "no such device or address",
3185 "argument list too long",
3186 "exec format error",
3187 "bad file number",
3188 "no child process",
3189 "no more processes",
3190 "not enough memory",
3191 "permission denied",
3192 "bad address",
3193 "block device required",
3194 "mount devices busy",
3195 "file exists",
3196 "cross-device link",
3197 "no such device",
3198 "not a directory",
3199 "is a directory",
3200 "invalid argument",
3201 "file table overflow",
3202 "too many open files",
3203 "not a typewriter",
3204 "text file busy",
3205 "file too big",
3206 "no space left on device",
3207 "illegal seek",
3208 "read-only file system",
3209 "too many links",
3210 "broken pipe",
3211 "math argument",
3212 "result too large",
3213 "I/O stream empty",
3214 "vax/vms specific error code nontranslatable error"
3216 #endif /* SHARABLE_LIB_BUG */
3217 #endif /* LINK_CRTL_SHARE */
3218 #endif /* VMS */
3220 #ifndef HAVE_STRERROR
3221 #ifndef WINDOWSNT
3222 char *
3223 strerror (errnum)
3224 int errnum;
3226 extern char *sys_errlist[];
3227 extern int sys_nerr;
3229 if (errnum >= 0 && errnum < sys_nerr)
3230 return sys_errlist[errnum];
3231 return (char *) "Unknown error";
3233 #endif /* not WINDOWSNT */
3234 #endif /* ! HAVE_STRERROR */
3237 emacs_open (path, oflag, mode)
3238 char *path;
3239 int oflag, mode;
3241 register int rtnval;
3243 #ifdef BSD4_1
3244 if (oflag & O_CREAT)
3245 return creat (path, mode);
3246 #endif
3248 while ((rtnval = open (path, oflag, mode)) == -1
3249 && (errno == EINTR));
3250 return (rtnval);
3254 emacs_close (fd)
3255 int fd;
3257 int did_retry = 0;
3258 register int rtnval;
3260 while ((rtnval = close (fd)) == -1
3261 && (errno == EINTR))
3262 did_retry = 1;
3264 /* If close is interrupted SunOS 4.1 may or may not have closed the
3265 file descriptor. If it did the second close will fail with
3266 errno = EBADF. That means we have succeeded. */
3267 if (rtnval == -1 && did_retry && errno == EBADF)
3268 return 0;
3270 return rtnval;
3274 emacs_read (fildes, buf, nbyte)
3275 int fildes;
3276 char *buf;
3277 unsigned int nbyte;
3279 register int rtnval;
3281 while ((rtnval = read (fildes, buf, nbyte)) == -1
3282 && (errno == EINTR));
3283 return (rtnval);
3287 emacs_write (fildes, buf, nbyte)
3288 int fildes;
3289 char *buf;
3290 unsigned int nbyte;
3292 register int rtnval, bytes_written;
3294 bytes_written = 0;
3296 while (nbyte > 0)
3298 rtnval = write (fildes, buf, nbyte);
3300 if (rtnval == -1)
3302 if (errno == EINTR)
3303 continue;
3304 else
3305 return (bytes_written ? bytes_written : -1);
3308 buf += rtnval;
3309 nbyte -= rtnval;
3310 bytes_written += rtnval;
3312 return (bytes_written);
3315 #ifdef USG
3317 * All of the following are for USG.
3319 * On USG systems the system calls are INTERRUPTIBLE by signals
3320 * that the user program has elected to catch. Thus the system call
3321 * must be retried in these cases. To handle this without massive
3322 * changes in the source code, we remap the standard system call names
3323 * to names for our own functions in sysdep.c that do the system call
3324 * with retries. Actually, for portability reasons, it is good
3325 * programming practice, as this example shows, to limit all actual
3326 * system calls to a single occurrence in the source. Sure, this
3327 * adds an extra level of function call overhead but it is almost
3328 * always negligible. Fred Fish, Unisoft Systems Inc.
3332 * Warning, this function may not duplicate 4.2 action properly
3333 * under error conditions.
3336 #ifndef MAXPATHLEN
3337 /* In 4.1, param.h fails to define this. */
3338 #define MAXPATHLEN 1024
3339 #endif
3341 #ifndef HAVE_GETWD
3343 char *
3344 getwd (pathname)
3345 char *pathname;
3347 char *npath, *spath;
3348 extern char *getcwd ();
3350 BLOCK_INPUT; /* getcwd uses malloc */
3351 spath = npath = getcwd ((char *) 0, MAXPATHLEN);
3352 if (spath == 0)
3353 return spath;
3354 /* On Altos 3068, getcwd can return @hostname/dir, so discard
3355 up to first slash. Should be harmless on other systems. */
3356 while (*npath && *npath != '/')
3357 npath++;
3358 strcpy (pathname, npath);
3359 free (spath); /* getcwd uses malloc */
3360 UNBLOCK_INPUT;
3361 return pathname;
3364 #endif /* HAVE_GETWD */
3367 * Emulate rename using unlink/link. Note that this is
3368 * only partially correct. Also, doesn't enforce restriction
3369 * that files be of same type (regular->regular, dir->dir, etc).
3372 #ifndef HAVE_RENAME
3374 rename (from, to)
3375 const char *from;
3376 const char *to;
3378 if (access (from, 0) == 0)
3380 unlink (to);
3381 if (link (from, to) == 0)
3382 if (unlink (from) == 0)
3383 return (0);
3385 return (-1);
3388 #endif
3391 #ifdef HPUX
3392 #ifndef HAVE_PERROR
3394 /* HPUX curses library references perror, but as far as we know
3395 it won't be called. Anyway this definition will do for now. */
3397 perror ()
3401 #endif /* not HAVE_PERROR */
3402 #endif /* HPUX */
3404 #ifndef HAVE_DUP2
3407 * Emulate BSD dup2. First close newd if it already exists.
3408 * Then, attempt to dup oldd. If not successful, call dup2 recursively
3409 * until we are, then close the unsuccessful ones.
3412 dup2 (oldd, newd)
3413 int oldd;
3414 int newd;
3416 register int fd, ret;
3418 emacs_close (newd);
3420 #ifdef F_DUPFD
3421 return fcntl (oldd, F_DUPFD, newd);
3422 #else
3423 fd = dup (old);
3424 if (fd == -1)
3425 return -1;
3426 if (fd == new)
3427 return new;
3428 ret = dup2 (old,new);
3429 emacs_close (fd);
3430 return ret;
3431 #endif
3434 #endif /* not HAVE_DUP2 */
3437 * Gettimeofday. Simulate as much as possible. Only accurate
3438 * to nearest second. Emacs doesn't use tzp so ignore it for now.
3439 * Only needed when subprocesses are defined.
3442 #ifdef subprocesses
3443 #ifndef VMS
3444 #ifndef HAVE_GETTIMEOFDAY
3445 #ifdef HAVE_TIMEVAL
3447 /* ARGSUSED */
3449 gettimeofday (tp, tzp)
3450 struct timeval *tp;
3451 struct timezone *tzp;
3453 extern long time ();
3455 tp->tv_sec = time ((long *)0);
3456 tp->tv_usec = 0;
3457 if (tzp != 0)
3458 tzp->tz_minuteswest = -1;
3459 return 0;
3462 #endif
3463 #endif
3464 #endif
3465 #endif /* subprocess && !HAVE_GETTIMEOFDAY && HAVE_TIMEVAL && !VMS */
3468 * This function will go away as soon as all the stubs fixed. (fnf)
3471 void
3472 croak (badfunc)
3473 char *badfunc;
3475 printf ("%s not yet implemented\r\n", badfunc);
3476 reset_sys_modes ();
3477 exit (1);
3480 #endif /* USG */
3482 /* Directory routines for systems that don't have them. */
3484 #ifdef SYSV_SYSTEM_DIR
3486 #include <dirent.h>
3488 #if defined (BROKEN_CLOSEDIR) || !defined (HAVE_CLOSEDIR)
3491 closedir (dirp)
3492 register DIR *dirp; /* stream from opendir */
3494 int rtnval;
3496 rtnval = emacs_close (dirp->dd_fd);
3498 /* Some systems (like Solaris) allocate the buffer and the DIR all
3499 in one block. Why in the world are we freeing this ourselves
3500 anyway? */
3501 #if ! (defined (sun) && defined (USG5_4))
3502 xfree ((char *) dirp->dd_buf); /* directory block defined in <dirent.h> */
3503 #endif
3504 xfree ((char *) dirp);
3506 return rtnval;
3508 #endif /* BROKEN_CLOSEDIR or not HAVE_CLOSEDIR */
3509 #endif /* SYSV_SYSTEM_DIR */
3511 #ifdef NONSYSTEM_DIR_LIBRARY
3513 DIR *
3514 opendir (filename)
3515 char *filename; /* name of directory */
3517 register DIR *dirp; /* -> malloc'ed storage */
3518 register int fd; /* file descriptor for read */
3519 struct stat sbuf; /* result of fstat */
3521 fd = emacs_open (filename, O_RDONLY, 0);
3522 if (fd < 0)
3523 return 0;
3525 BLOCK_INPUT;
3526 if (fstat (fd, &sbuf) < 0
3527 || (sbuf.st_mode & S_IFMT) != S_IFDIR
3528 || (dirp = (DIR *) xmalloc (sizeof (DIR))) == 0)
3530 emacs_close (fd);
3531 UNBLOCK_INPUT;
3532 return 0; /* bad luck today */
3534 UNBLOCK_INPUT;
3536 dirp->dd_fd = fd;
3537 dirp->dd_loc = dirp->dd_size = 0; /* refill needed */
3539 return dirp;
3542 void
3543 closedir (dirp)
3544 register DIR *dirp; /* stream from opendir */
3546 emacs_close (dirp->dd_fd);
3547 xfree ((char *) dirp);
3551 #ifndef VMS
3552 #define DIRSIZ 14
3553 struct olddir
3555 ino_t od_ino; /* inode */
3556 char od_name[DIRSIZ]; /* filename */
3558 #endif /* not VMS */
3560 struct direct dir_static; /* simulated directory contents */
3562 /* ARGUSED */
3563 struct direct *
3564 readdir (dirp)
3565 register DIR *dirp; /* stream from opendir */
3567 #ifndef VMS
3568 register struct olddir *dp; /* -> directory data */
3569 #else /* VMS */
3570 register struct dir$_name *dp; /* -> directory data */
3571 register struct dir$_version *dv; /* -> version data */
3572 #endif /* VMS */
3574 for (; ;)
3576 if (dirp->dd_loc >= dirp->dd_size)
3577 dirp->dd_loc = dirp->dd_size = 0;
3579 if (dirp->dd_size == 0 /* refill buffer */
3580 && (dirp->dd_size = emacs_read (dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ)) <= 0)
3581 return 0;
3583 #ifndef VMS
3584 dp = (struct olddir *) &dirp->dd_buf[dirp->dd_loc];
3585 dirp->dd_loc += sizeof (struct olddir);
3587 if (dp->od_ino != 0) /* not deleted entry */
3589 dir_static.d_ino = dp->od_ino;
3590 strncpy (dir_static.d_name, dp->od_name, DIRSIZ);
3591 dir_static.d_name[DIRSIZ] = '\0';
3592 dir_static.d_namlen = strlen (dir_static.d_name);
3593 dir_static.d_reclen = sizeof (struct direct)
3594 - MAXNAMLEN + 3
3595 + dir_static.d_namlen - dir_static.d_namlen % 4;
3596 return &dir_static; /* -> simulated structure */
3598 #else /* VMS */
3599 dp = (struct dir$_name *) dirp->dd_buf;
3600 if (dirp->dd_loc == 0)
3601 dirp->dd_loc = (dp->dir$b_namecount&1) ? dp->dir$b_namecount + 1
3602 : dp->dir$b_namecount;
3603 dv = (struct dir$_version *)&dp->dir$t_name[dirp->dd_loc];
3604 dir_static.d_ino = dv->dir$w_fid_num;
3605 dir_static.d_namlen = dp->dir$b_namecount;
3606 dir_static.d_reclen = sizeof (struct direct)
3607 - MAXNAMLEN + 3
3608 + dir_static.d_namlen - dir_static.d_namlen % 4;
3609 strncpy (dir_static.d_name, dp->dir$t_name, dp->dir$b_namecount);
3610 dir_static.d_name[dir_static.d_namlen] = '\0';
3611 dirp->dd_loc = dirp->dd_size; /* only one record at a time */
3612 return &dir_static;
3613 #endif /* VMS */
3617 #ifdef VMS
3618 /* readdirver is just like readdir except it returns all versions of a file
3619 as separate entries. */
3621 /* ARGUSED */
3622 struct direct *
3623 readdirver (dirp)
3624 register DIR *dirp; /* stream from opendir */
3626 register struct dir$_name *dp; /* -> directory data */
3627 register struct dir$_version *dv; /* -> version data */
3629 if (dirp->dd_loc >= dirp->dd_size - sizeof (struct dir$_name))
3630 dirp->dd_loc = dirp->dd_size = 0;
3632 if (dirp->dd_size == 0 /* refill buffer */
3633 && (dirp->dd_size = sys_read (dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ)) <= 0)
3634 return 0;
3636 dp = (struct dir$_name *) dirp->dd_buf;
3637 if (dirp->dd_loc == 0)
3638 dirp->dd_loc = (dp->dir$b_namecount & 1) ? dp->dir$b_namecount + 1
3639 : dp->dir$b_namecount;
3640 dv = (struct dir$_version *) &dp->dir$t_name[dirp->dd_loc];
3641 strncpy (dir_static.d_name, dp->dir$t_name, dp->dir$b_namecount);
3642 sprintf (&dir_static.d_name[dp->dir$b_namecount], ";%d", dv->dir$w_version);
3643 dir_static.d_namlen = strlen (dir_static.d_name);
3644 dir_static.d_ino = dv->dir$w_fid_num;
3645 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3
3646 + dir_static.d_namlen - dir_static.d_namlen % 4;
3647 dirp->dd_loc = ((char *) (++dv) - dp->dir$t_name);
3648 return &dir_static;
3651 #endif /* VMS */
3653 #endif /* NONSYSTEM_DIR_LIBRARY */
3657 set_file_times (filename, atime, mtime)
3658 char *filename;
3659 EMACS_TIME atime, mtime;
3661 #ifdef HAVE_UTIMES
3662 struct timeval tv[2];
3663 tv[0] = atime;
3664 tv[1] = mtime;
3665 return utimes (filename, tv);
3666 #else /* not HAVE_UTIMES */
3667 struct utimbuf utb;
3668 utb.actime = EMACS_SECS (atime);
3669 utb.modtime = EMACS_SECS (mtime);
3670 return utime (filename, &utb);
3671 #endif /* not HAVE_UTIMES */
3674 /* mkdir and rmdir functions, for systems which don't have them. */
3676 #ifndef HAVE_MKDIR
3678 * Written by Robert Rother, Mariah Corporation, August 1985.
3680 * If you want it, it's yours. All I ask in return is that if you
3681 * figure out how to do this in a Bourne Shell script you send me
3682 * a copy.
3683 * sdcsvax!rmr or rmr@uscd
3685 * Severely hacked over by John Gilmore to make a 4.2BSD compatible
3686 * subroutine. 11Mar86; hoptoad!gnu
3688 * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
3689 * subroutine didn't return EEXIST. It does now.
3693 * Make a directory.
3695 #ifdef MKDIR_PROTOTYPE
3696 MKDIR_PROTOTYPE
3697 #else
3699 mkdir (dpath, dmode)
3700 char *dpath;
3701 int dmode;
3702 #endif
3704 int cpid, status, fd;
3705 struct stat statbuf;
3707 if (stat (dpath, &statbuf) == 0)
3709 errno = EEXIST; /* Stat worked, so it already exists */
3710 return -1;
3713 /* If stat fails for a reason other than non-existence, return error */
3714 if (errno != ENOENT)
3715 return -1;
3717 synch_process_alive = 1;
3718 switch (cpid = fork ())
3721 case -1: /* Error in fork */
3722 return (-1); /* Errno is set already */
3724 case 0: /* Child process */
3726 * Cheap hack to set mode of new directory. Since this
3727 * child process is going away anyway, we zap its umask.
3728 * FIXME, this won't suffice to set SUID, SGID, etc. on this
3729 * directory. Does anybody care?
3731 status = umask (0); /* Get current umask */
3732 status = umask (status | (0777 & ~dmode)); /* Set for mkdir */
3733 fd = emacs_open ("/dev/null", O_RDWR, 0);
3734 if (fd >= 0)
3736 dup2 (fd, 0);
3737 dup2 (fd, 1);
3738 dup2 (fd, 2);
3740 execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
3741 _exit (-1); /* Can't exec /bin/mkdir */
3743 default: /* Parent process */
3744 wait_for_termination (cpid);
3747 if (synch_process_death != 0 || synch_process_retcode != 0)
3749 errno = EIO; /* We don't know why, but */
3750 return -1; /* /bin/mkdir failed */
3753 return 0;
3755 #endif /* not HAVE_MKDIR */
3757 #ifndef HAVE_RMDIR
3759 rmdir (dpath)
3760 char *dpath;
3762 int cpid, status, fd;
3763 struct stat statbuf;
3765 if (stat (dpath, &statbuf) != 0)
3767 /* Stat just set errno. We don't have to */
3768 return -1;
3771 synch_process_alive = 1;
3772 switch (cpid = fork ())
3775 case -1: /* Error in fork */
3776 return (-1); /* Errno is set already */
3778 case 0: /* Child process */
3779 fd = emacs_open ("/dev/null", O_RDWR, 0);
3780 if (fd >= 0)
3782 dup2 (fd, 0);
3783 dup2 (fd, 1);
3784 dup2 (fd, 2);
3786 execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
3787 _exit (-1); /* Can't exec /bin/rmdir */
3789 default: /* Parent process */
3790 wait_for_termination (cpid);
3793 if (synch_process_death != 0 || synch_process_retcode != 0)
3795 errno = EIO; /* We don't know why, but */
3796 return -1; /* /bin/rmdir failed */
3799 return 0;
3801 #endif /* !HAVE_RMDIR */
3805 /* Functions for VMS */
3806 #ifdef VMS
3807 #include "vms-pwd.h"
3808 #include <acldef.h>
3809 #include <chpdef.h>
3810 #include <jpidef.h>
3812 /* Return as a string the VMS error string pertaining to STATUS.
3813 Reuses the same static buffer each time it is called. */
3815 char *
3816 vmserrstr (status)
3817 int status; /* VMS status code */
3819 int bufadr[2];
3820 short len;
3821 static char buf[257];
3823 bufadr[0] = sizeof buf - 1;
3824 bufadr[1] = (int) buf;
3825 if (! (SYS$GETMSG (status, &len, bufadr, 0x1, 0) & 1))
3826 return "untranslatable VMS error status";
3827 buf[len] = '\0';
3828 return buf;
3831 #ifdef access
3832 #undef access
3834 /* The following is necessary because 'access' emulation by VMS C (2.0) does
3835 * not work correctly. (It also doesn't work well in version 2.3.)
3838 #ifdef VMS4_4
3840 #define DESCRIPTOR(name,string) struct dsc$descriptor_s name = \
3841 { strlen (string), DSC$K_DTYPE_T, DSC$K_CLASS_S, string }
3843 typedef union {
3844 struct {
3845 unsigned short s_buflen;
3846 unsigned short s_code;
3847 char *s_bufadr;
3848 unsigned short *s_retlenadr;
3849 } s;
3850 int end;
3851 } item;
3852 #define buflen s.s_buflen
3853 #define code s.s_code
3854 #define bufadr s.s_bufadr
3855 #define retlenadr s.s_retlenadr
3857 #define R_OK 4 /* test for read permission */
3858 #define W_OK 2 /* test for write permission */
3859 #define X_OK 1 /* test for execute (search) permission */
3860 #define F_OK 0 /* test for presence of file */
3863 sys_access (path, mode)
3864 char *path;
3865 int mode;
3867 static char *user = NULL;
3868 char dir_fn[512];
3870 /* translate possible directory spec into .DIR file name, so brain-dead
3871 * access can treat the directory like a file. */
3872 if (directory_file_name (path, dir_fn))
3873 path = dir_fn;
3875 if (mode == F_OK)
3876 return access (path, mode);
3877 if (user == NULL && (user = (char *) getenv ("USER")) == NULL)
3878 return -1;
3880 int stat;
3881 int flags;
3882 int acces;
3883 unsigned short int dummy;
3884 item itemlst[3];
3885 static int constant = ACL$C_FILE;
3886 DESCRIPTOR (path_desc, path);
3887 DESCRIPTOR (user_desc, user);
3889 flags = 0;
3890 acces = 0;
3891 if ((mode & X_OK) && ((stat = access (path, mode)) < 0 || mode == X_OK))
3892 return stat;
3893 if (mode & R_OK)
3894 acces |= CHP$M_READ;
3895 if (mode & W_OK)
3896 acces |= CHP$M_WRITE;
3897 itemlst[0].buflen = sizeof (int);
3898 itemlst[0].code = CHP$_FLAGS;
3899 itemlst[0].bufadr = (char *) &flags;
3900 itemlst[0].retlenadr = &dummy;
3901 itemlst[1].buflen = sizeof (int);
3902 itemlst[1].code = CHP$_ACCESS;
3903 itemlst[1].bufadr = (char *) &acces;
3904 itemlst[1].retlenadr = &dummy;
3905 itemlst[2].end = CHP$_END;
3906 stat = SYS$CHECK_ACCESS (&constant, &path_desc, &user_desc, itemlst);
3907 return stat == SS$_NORMAL ? 0 : -1;
3911 #else /* not VMS4_4 */
3913 #include <prvdef.h>
3914 #define ACE$M_WRITE 2
3915 #define ACE$C_KEYID 1
3917 static unsigned short memid, grpid;
3918 static unsigned int uic;
3920 /* Called from init_sys_modes, so it happens not very often
3921 but at least each time Emacs is loaded. */
3922 void
3923 sys_access_reinit ()
3925 uic = 0;
3929 sys_access (filename, type)
3930 char * filename;
3931 int type;
3933 struct FAB fab;
3934 struct XABPRO xab;
3935 int status, size, i, typecode, acl_controlled;
3936 unsigned int *aclptr, *aclend, aclbuf[60];
3937 union prvdef prvmask;
3939 /* Get UIC and GRP values for protection checking. */
3940 if (uic == 0)
3942 status = LIB$GETJPI (&JPI$_UIC, 0, 0, &uic, 0, 0);
3943 if (! (status & 1))
3944 return -1;
3945 memid = uic & 0xFFFF;
3946 grpid = uic >> 16;
3949 if (type != 2) /* not checking write access */
3950 return access (filename, type);
3952 /* Check write protection. */
3954 #define CHECKPRIV(bit) (prvmask.bit)
3955 #define WRITABLE(field) (! ((xab.xab$w_pro >> field) & XAB$M_NOWRITE))
3957 /* Find privilege bits */
3958 status = SYS$SETPRV (0, 0, 0, prvmask);
3959 if (! (status & 1))
3960 error ("Unable to find privileges: %s", vmserrstr (status));
3961 if (CHECKPRIV (PRV$V_BYPASS))
3962 return 0; /* BYPASS enabled */
3963 fab = cc$rms_fab;
3964 fab.fab$b_fac = FAB$M_GET;
3965 fab.fab$l_fna = filename;
3966 fab.fab$b_fns = strlen (filename);
3967 fab.fab$l_xab = &xab;
3968 xab = cc$rms_xabpro;
3969 xab.xab$l_aclbuf = aclbuf;
3970 xab.xab$w_aclsiz = sizeof (aclbuf);
3971 status = SYS$OPEN (&fab, 0, 0);
3972 if (! (status & 1))
3973 return -1;
3974 SYS$CLOSE (&fab, 0, 0);
3975 /* Check system access */
3976 if (CHECKPRIV (PRV$V_SYSPRV) && WRITABLE (XAB$V_SYS))
3977 return 0;
3978 /* Check ACL entries, if any */
3979 acl_controlled = 0;
3980 if (xab.xab$w_acllen > 0)
3982 aclptr = aclbuf;
3983 aclend = &aclbuf[xab.xab$w_acllen / 4];
3984 while (*aclptr && aclptr < aclend)
3986 size = (*aclptr & 0xff) / 4;
3987 typecode = (*aclptr >> 8) & 0xff;
3988 if (typecode == ACE$C_KEYID)
3989 for (i = size - 1; i > 1; i--)
3990 if (aclptr[i] == uic)
3992 acl_controlled = 1;
3993 if (aclptr[1] & ACE$M_WRITE)
3994 return 0; /* Write access through ACL */
3996 aclptr = &aclptr[size];
3998 if (acl_controlled) /* ACL specified, prohibits write access */
3999 return -1;
4001 /* No ACL entries specified, check normal protection */
4002 if (WRITABLE (XAB$V_WLD)) /* World writable */
4003 return 0;
4004 if (WRITABLE (XAB$V_GRP) &&
4005 (unsigned short) (xab.xab$l_uic >> 16) == grpid)
4006 return 0; /* Group writable */
4007 if (WRITABLE (XAB$V_OWN) &&
4008 (xab.xab$l_uic & 0xFFFF) == memid)
4009 return 0; /* Owner writable */
4011 return -1; /* Not writable */
4013 #endif /* not VMS4_4 */
4014 #endif /* access */
4016 static char vtbuf[NAM$C_MAXRSS+1];
4018 /* translate a vms file spec to a unix path */
4019 char *
4020 sys_translate_vms (vfile)
4021 char * vfile;
4023 char * p;
4024 char * targ;
4026 if (!vfile)
4027 return 0;
4029 targ = vtbuf;
4031 /* leading device or logical name is a root directory */
4032 if (p = strchr (vfile, ':'))
4034 *targ++ = '/';
4035 while (vfile < p)
4036 *targ++ = *vfile++;
4037 vfile++;
4038 *targ++ = '/';
4040 p = vfile;
4041 if (*p == '[' || *p == '<')
4043 while (*++vfile != *p + 2)
4044 switch (*vfile)
4046 case '.':
4047 if (vfile[-1] == *p)
4048 *targ++ = '.';
4049 *targ++ = '/';
4050 break;
4052 case '-':
4053 *targ++ = '.';
4054 *targ++ = '.';
4055 break;
4057 default:
4058 *targ++ = *vfile;
4059 break;
4061 vfile++;
4062 *targ++ = '/';
4064 while (*vfile)
4065 *targ++ = *vfile++;
4067 return vtbuf;
4070 static char utbuf[NAM$C_MAXRSS+1];
4072 /* translate a unix path to a VMS file spec */
4073 char *
4074 sys_translate_unix (ufile)
4075 char * ufile;
4077 int slash_seen = 0;
4078 char *p;
4079 char * targ;
4081 if (!ufile)
4082 return 0;
4084 targ = utbuf;
4086 if (*ufile == '/')
4088 ufile++;
4091 while (*ufile)
4093 switch (*ufile)
4095 case '/':
4096 if (slash_seen)
4097 if (index (&ufile[1], '/'))
4098 *targ++ = '.';
4099 else
4100 *targ++ = ']';
4101 else
4103 *targ++ = ':';
4104 if (index (&ufile[1], '/'))
4105 *targ++ = '[';
4106 slash_seen = 1;
4108 break;
4110 case '.':
4111 if (strncmp (ufile, "./", 2) == 0)
4113 if (!slash_seen)
4115 *targ++ = '[';
4116 slash_seen = 1;
4118 ufile++; /* skip the dot */
4119 if (index (&ufile[1], '/'))
4120 *targ++ = '.';
4121 else
4122 *targ++ = ']';
4124 else if (strncmp (ufile, "../", 3) == 0)
4126 if (!slash_seen)
4128 *targ++ = '[';
4129 slash_seen = 1;
4131 *targ++ = '-';
4132 ufile += 2; /* skip the dots */
4133 if (index (&ufile[1], '/'))
4134 *targ++ = '.';
4135 else
4136 *targ++ = ']';
4138 else
4139 *targ++ = *ufile;
4140 break;
4142 default:
4143 *targ++ = *ufile;
4144 break;
4146 ufile++;
4148 *targ = '\0';
4150 return utbuf;
4153 char *
4154 getwd (pathname)
4155 char *pathname;
4157 char *ptr, *val;
4158 extern char *getcwd ();
4160 #define MAXPATHLEN 1024
4162 ptr = xmalloc (MAXPATHLEN);
4163 val = getcwd (ptr, MAXPATHLEN);
4164 if (val == 0)
4166 xfree (ptr);
4167 return val;
4169 strcpy (pathname, ptr);
4170 xfree (ptr);
4172 return pathname;
4176 getppid ()
4178 long item_code = JPI$_OWNER;
4179 unsigned long parent_id;
4180 int status;
4182 if (((status = LIB$GETJPI (&item_code, 0, 0, &parent_id)) & 1) == 0)
4184 errno = EVMSERR;
4185 vaxc$errno = status;
4186 return -1;
4188 return parent_id;
4191 #undef getuid
4192 unsigned
4193 sys_getuid ()
4195 return (getgid () << 16) | getuid ();
4198 #undef read
4200 sys_read (fildes, buf, nbyte)
4201 int fildes;
4202 char *buf;
4203 unsigned int nbyte;
4205 return read (fildes, buf, (nbyte < MAXIOSIZE ? nbyte : MAXIOSIZE));
4208 #if 0
4210 sys_write (fildes, buf, nbyte)
4211 int fildes;
4212 char *buf;
4213 unsigned int nbyte;
4215 register int nwrote, rtnval = 0;
4217 while (nbyte > MAXIOSIZE && (nwrote = write (fildes, buf, MAXIOSIZE)) > 0) {
4218 nbyte -= nwrote;
4219 buf += nwrote;
4220 rtnval += nwrote;
4222 if (nwrote < 0)
4223 return rtnval ? rtnval : -1;
4224 if ((nwrote = write (fildes, buf, nbyte)) < 0)
4225 return rtnval ? rtnval : -1;
4226 return (rtnval + nwrote);
4228 #endif /* 0 */
4231 * VAX/VMS VAX C RTL really loses. It insists that records
4232 * end with a newline (carriage return) character, and if they
4233 * don't it adds one (nice of it isn't it!)
4235 * Thus we do this stupidity below.
4238 #undef write
4240 sys_write (fildes, buf, nbytes)
4241 int fildes;
4242 char *buf;
4243 unsigned int nbytes;
4245 register char *p;
4246 register char *e;
4247 int sum = 0;
4248 struct stat st;
4250 fstat (fildes, &st);
4251 p = buf;
4252 while (nbytes > 0)
4254 int len, retval;
4256 /* Handle fixed-length files with carriage control. */
4257 if (st.st_fab_rfm == FAB$C_FIX
4258 && ((st.st_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4260 len = st.st_fab_mrs;
4261 retval = write (fildes, p, min (len, nbytes));
4262 if (retval != len)
4263 return -1;
4264 retval++; /* This skips the implied carriage control */
4266 else
4268 e = p + min (MAXIOSIZE, nbytes) - 1;
4269 while (*e != '\n' && e > p) e--;
4270 if (p == e) /* Ok.. so here we add a newline... sigh. */
4271 e = p + min (MAXIOSIZE, nbytes) - 1;
4272 len = e + 1 - p;
4273 retval = write (fildes, p, len);
4274 if (retval != len)
4275 return -1;
4277 p += retval;
4278 sum += retval;
4279 nbytes -= retval;
4281 return sum;
4284 /* Create file NEW copying its attributes from file OLD. If
4285 OLD is 0 or does not exist, create based on the value of
4286 vms_stmlf_recfm. */
4288 /* Protection value the file should ultimately have.
4289 Set by create_copy_attrs, and use by rename_sansversions. */
4290 static unsigned short int fab_final_pro;
4293 creat_copy_attrs (old, new)
4294 char *old, *new;
4296 struct FAB fab = cc$rms_fab;
4297 struct XABPRO xabpro;
4298 char aclbuf[256]; /* Choice of size is arbitrary. See below. */
4299 extern int vms_stmlf_recfm;
4301 if (old)
4303 fab.fab$b_fac = FAB$M_GET;
4304 fab.fab$l_fna = old;
4305 fab.fab$b_fns = strlen (old);
4306 fab.fab$l_xab = (char *) &xabpro;
4307 xabpro = cc$rms_xabpro;
4308 xabpro.xab$l_aclbuf = aclbuf;
4309 xabpro.xab$w_aclsiz = sizeof aclbuf;
4310 /* Call $OPEN to fill in the fab & xabpro fields. */
4311 if (SYS$OPEN (&fab, 0, 0) & 1)
4313 SYS$CLOSE (&fab, 0, 0);
4314 fab.fab$l_alq = 0; /* zero the allocation quantity */
4315 if (xabpro.xab$w_acllen > 0)
4317 if (xabpro.xab$w_acllen > sizeof aclbuf)
4318 /* If the acl buffer was too short, redo open with longer one.
4319 Wouldn't need to do this if there were some system imposed
4320 limit on the size of an ACL, but I can't find any such. */
4322 xabpro.xab$l_aclbuf = (char *) alloca (xabpro.xab$w_acllen);
4323 xabpro.xab$w_aclsiz = xabpro.xab$w_acllen;
4324 if (SYS$OPEN (&fab, 0, 0) & 1)
4325 SYS$CLOSE (&fab, 0, 0);
4326 else
4327 old = 0;
4330 else
4331 xabpro.xab$l_aclbuf = 0;
4333 else
4334 old = 0;
4336 fab.fab$l_fna = new;
4337 fab.fab$b_fns = strlen (new);
4338 if (!old)
4340 fab.fab$l_xab = 0;
4341 fab.fab$b_rfm = vms_stmlf_recfm ? FAB$C_STMLF : FAB$C_VAR;
4342 fab.fab$b_rat = FAB$M_CR;
4345 /* Set the file protections such that we will be able to manipulate
4346 this file. Once we are done writing and renaming it, we will set
4347 the protections back. */
4348 if (old)
4349 fab_final_pro = xabpro.xab$w_pro;
4350 else
4351 SYS$SETDFPROT (0, &fab_final_pro);
4352 xabpro.xab$w_pro &= 0xff0f; /* set O:rewd for now. This is set back later. */
4354 /* Create the new file with either default attrs or attrs copied
4355 from old file. */
4356 if (!(SYS$CREATE (&fab, 0, 0) & 1))
4357 return -1;
4358 SYS$CLOSE (&fab, 0, 0);
4359 /* As this is a "replacement" for creat, return a file descriptor
4360 opened for writing. */
4361 return open (new, O_WRONLY);
4364 #ifdef creat
4365 #undef creat
4366 #include <varargs.h>
4367 #ifdef __GNUC__
4368 #ifndef va_count
4369 #define va_count(X) ((X) = *(((int *) &(va_alist)) - 1))
4370 #endif
4371 #endif
4374 sys_creat (va_alist)
4375 va_dcl
4377 va_list list_incrementer;
4378 char *name;
4379 int mode;
4380 int rfd; /* related file descriptor */
4381 int fd; /* Our new file descriptor */
4382 int count;
4383 struct stat st_buf;
4384 char rfm[12];
4385 char rat[15];
4386 char mrs[13];
4387 char fsz[13];
4388 extern int vms_stmlf_recfm;
4390 va_count (count);
4391 va_start (list_incrementer);
4392 name = va_arg (list_incrementer, char *);
4393 mode = va_arg (list_incrementer, int);
4394 if (count > 2)
4395 rfd = va_arg (list_incrementer, int);
4396 va_end (list_incrementer);
4397 if (count > 2)
4399 /* Use information from the related file descriptor to set record
4400 format of the newly created file. */
4401 fstat (rfd, &st_buf);
4402 switch (st_buf.st_fab_rfm)
4404 case FAB$C_FIX:
4405 strcpy (rfm, "rfm = fix");
4406 sprintf (mrs, "mrs = %d", st_buf.st_fab_mrs);
4407 strcpy (rat, "rat = ");
4408 if (st_buf.st_fab_rat & FAB$M_CR)
4409 strcat (rat, "cr");
4410 else if (st_buf.st_fab_rat & FAB$M_FTN)
4411 strcat (rat, "ftn");
4412 else if (st_buf.st_fab_rat & FAB$M_PRN)
4413 strcat (rat, "prn");
4414 if (st_buf.st_fab_rat & FAB$M_BLK)
4415 if (st_buf.st_fab_rat & (FAB$M_CR|FAB$M_FTN|FAB$M_PRN))
4416 strcat (rat, ", blk");
4417 else
4418 strcat (rat, "blk");
4419 return creat (name, 0, rfm, rat, mrs);
4421 case FAB$C_VFC:
4422 strcpy (rfm, "rfm = vfc");
4423 sprintf (fsz, "fsz = %d", st_buf.st_fab_fsz);
4424 strcpy (rat, "rat = ");
4425 if (st_buf.st_fab_rat & FAB$M_CR)
4426 strcat (rat, "cr");
4427 else if (st_buf.st_fab_rat & FAB$M_FTN)
4428 strcat (rat, "ftn");
4429 else if (st_buf.st_fab_rat & FAB$M_PRN)
4430 strcat (rat, "prn");
4431 if (st_buf.st_fab_rat & FAB$M_BLK)
4432 if (st_buf.st_fab_rat & (FAB$M_CR|FAB$M_FTN|FAB$M_PRN))
4433 strcat (rat, ", blk");
4434 else
4435 strcat (rat, "blk");
4436 return creat (name, 0, rfm, rat, fsz);
4438 case FAB$C_STM:
4439 strcpy (rfm, "rfm = stm");
4440 break;
4442 case FAB$C_STMCR:
4443 strcpy (rfm, "rfm = stmcr");
4444 break;
4446 case FAB$C_STMLF:
4447 strcpy (rfm, "rfm = stmlf");
4448 break;
4450 case FAB$C_UDF:
4451 strcpy (rfm, "rfm = udf");
4452 break;
4454 case FAB$C_VAR:
4455 strcpy (rfm, "rfm = var");
4456 break;
4458 strcpy (rat, "rat = ");
4459 if (st_buf.st_fab_rat & FAB$M_CR)
4460 strcat (rat, "cr");
4461 else if (st_buf.st_fab_rat & FAB$M_FTN)
4462 strcat (rat, "ftn");
4463 else if (st_buf.st_fab_rat & FAB$M_PRN)
4464 strcat (rat, "prn");
4465 if (st_buf.st_fab_rat & FAB$M_BLK)
4466 if (st_buf.st_fab_rat & (FAB$M_CR|FAB$M_FTN|FAB$M_PRN))
4467 strcat (rat, ", blk");
4468 else
4469 strcat (rat, "blk");
4471 else
4473 strcpy (rfm, vms_stmlf_recfm ? "rfm = stmlf" : "rfm=var");
4474 strcpy (rat, "rat=cr");
4476 /* Until the VAX C RTL fixes the many bugs with modes, always use
4477 mode 0 to get the user's default protection. */
4478 fd = creat (name, 0, rfm, rat);
4479 if (fd < 0 && errno == EEXIST)
4481 if (unlink (name) < 0)
4482 report_file_error ("delete", build_string (name));
4483 fd = creat (name, 0, rfm, rat);
4485 return fd;
4487 #endif /* creat */
4489 /* fwrite to stdout is S L O W. Speed it up by using fputc...*/
4491 sys_fwrite (ptr, size, num, fp)
4492 register char * ptr;
4493 FILE * fp;
4495 register int tot = num * size;
4497 while (tot--)
4498 fputc (*ptr++, fp);
4499 return num;
4503 * The VMS C library routine creat actually creates a new version of an
4504 * existing file rather than truncating the old version. There are times
4505 * when this is not the desired behavior, for instance, when writing an
4506 * auto save file (you only want one version), or when you don't have
4507 * write permission in the directory containing the file (but the file
4508 * itself is writable). Hence this routine, which is equivalent to
4509 * "close (creat (fn, 0));" on Unix if fn already exists.
4512 vms_truncate (fn)
4513 char *fn;
4515 struct FAB xfab = cc$rms_fab;
4516 struct RAB xrab = cc$rms_rab;
4517 int status;
4519 xfab.fab$l_fop = FAB$M_TEF; /* free allocated but unused blocks on close */
4520 xfab.fab$b_fac = FAB$M_TRN | FAB$M_GET; /* allow truncate and get access */
4521 xfab.fab$b_shr = FAB$M_NIL; /* allow no sharing - file must be locked */
4522 xfab.fab$l_fna = fn;
4523 xfab.fab$b_fns = strlen (fn);
4524 xfab.fab$l_dna = ";0"; /* default to latest version of the file */
4525 xfab.fab$b_dns = 2;
4526 xrab.rab$l_fab = &xfab;
4528 /* This gibberish opens the file, positions to the first record, and
4529 deletes all records from there until the end of file. */
4530 if ((SYS$OPEN (&xfab) & 01) == 01)
4532 if ((SYS$CONNECT (&xrab) & 01) == 01 &&
4533 (SYS$FIND (&xrab) & 01) == 01 &&
4534 (SYS$TRUNCATE (&xrab) & 01) == 01)
4535 status = 0;
4536 else
4537 status = -1;
4539 else
4540 status = -1;
4541 SYS$CLOSE (&xfab);
4542 return status;
4545 /* Define this symbol to actually read SYSUAF.DAT. This requires either
4546 SYSPRV or a readable SYSUAF.DAT. */
4548 #ifdef READ_SYSUAF
4550 * getuaf.c
4552 * Routine to read the VMS User Authorization File and return
4553 * a specific user's record.
4556 static struct UAF retuaf;
4558 struct UAF *
4559 get_uaf_name (uname)
4560 char * uname;
4562 register status;
4563 struct FAB uaf_fab;
4564 struct RAB uaf_rab;
4566 uaf_fab = cc$rms_fab;
4567 uaf_rab = cc$rms_rab;
4568 /* initialize fab fields */
4569 uaf_fab.fab$l_fna = "SYS$SYSTEM:SYSUAF.DAT";
4570 uaf_fab.fab$b_fns = 21;
4571 uaf_fab.fab$b_fac = FAB$M_GET;
4572 uaf_fab.fab$b_org = FAB$C_IDX;
4573 uaf_fab.fab$b_shr = FAB$M_GET|FAB$M_PUT|FAB$M_UPD|FAB$M_DEL;
4574 /* initialize rab fields */
4575 uaf_rab.rab$l_fab = &uaf_fab;
4576 /* open the User Authorization File */
4577 status = SYS$OPEN (&uaf_fab);
4578 if (!(status&1))
4580 errno = EVMSERR;
4581 vaxc$errno = status;
4582 return 0;
4584 status = SYS$CONNECT (&uaf_rab);
4585 if (!(status&1))
4587 errno = EVMSERR;
4588 vaxc$errno = status;
4589 return 0;
4591 /* read the requested record - index is in uname */
4592 uaf_rab.rab$l_kbf = uname;
4593 uaf_rab.rab$b_ksz = strlen (uname);
4594 uaf_rab.rab$b_rac = RAB$C_KEY;
4595 uaf_rab.rab$l_ubf = (char *)&retuaf;
4596 uaf_rab.rab$w_usz = sizeof retuaf;
4597 status = SYS$GET (&uaf_rab);
4598 if (!(status&1))
4600 errno = EVMSERR;
4601 vaxc$errno = status;
4602 return 0;
4604 /* close the User Authorization File */
4605 status = SYS$DISCONNECT (&uaf_rab);
4606 if (!(status&1))
4608 errno = EVMSERR;
4609 vaxc$errno = status;
4610 return 0;
4612 status = SYS$CLOSE (&uaf_fab);
4613 if (!(status&1))
4615 errno = EVMSERR;
4616 vaxc$errno = status;
4617 return 0;
4619 return &retuaf;
4622 struct UAF *
4623 get_uaf_uic (uic)
4624 unsigned long uic;
4626 register status;
4627 struct FAB uaf_fab;
4628 struct RAB uaf_rab;
4630 uaf_fab = cc$rms_fab;
4631 uaf_rab = cc$rms_rab;
4632 /* initialize fab fields */
4633 uaf_fab.fab$l_fna = "SYS$SYSTEM:SYSUAF.DAT";
4634 uaf_fab.fab$b_fns = 21;
4635 uaf_fab.fab$b_fac = FAB$M_GET;
4636 uaf_fab.fab$b_org = FAB$C_IDX;
4637 uaf_fab.fab$b_shr = FAB$M_GET|FAB$M_PUT|FAB$M_UPD|FAB$M_DEL;
4638 /* initialize rab fields */
4639 uaf_rab.rab$l_fab = &uaf_fab;
4640 /* open the User Authorization File */
4641 status = SYS$OPEN (&uaf_fab);
4642 if (!(status&1))
4644 errno = EVMSERR;
4645 vaxc$errno = status;
4646 return 0;
4648 status = SYS$CONNECT (&uaf_rab);
4649 if (!(status&1))
4651 errno = EVMSERR;
4652 vaxc$errno = status;
4653 return 0;
4655 /* read the requested record - index is in uic */
4656 uaf_rab.rab$b_krf = 1; /* 1st alternate key */
4657 uaf_rab.rab$l_kbf = (char *) &uic;
4658 uaf_rab.rab$b_ksz = sizeof uic;
4659 uaf_rab.rab$b_rac = RAB$C_KEY;
4660 uaf_rab.rab$l_ubf = (char *)&retuaf;
4661 uaf_rab.rab$w_usz = sizeof retuaf;
4662 status = SYS$GET (&uaf_rab);
4663 if (!(status&1))
4665 errno = EVMSERR;
4666 vaxc$errno = status;
4667 return 0;
4669 /* close the User Authorization File */
4670 status = SYS$DISCONNECT (&uaf_rab);
4671 if (!(status&1))
4673 errno = EVMSERR;
4674 vaxc$errno = status;
4675 return 0;
4677 status = SYS$CLOSE (&uaf_fab);
4678 if (!(status&1))
4680 errno = EVMSERR;
4681 vaxc$errno = status;
4682 return 0;
4684 return &retuaf;
4687 static struct passwd retpw;
4689 struct passwd *
4690 cnv_uaf_pw (up)
4691 struct UAF * up;
4693 char * ptr;
4695 /* copy these out first because if the username is 32 chars, the next
4696 section will overwrite the first byte of the UIC */
4697 retpw.pw_uid = up->uaf$w_mem;
4698 retpw.pw_gid = up->uaf$w_grp;
4700 /* I suppose this is not the best style, to possibly overwrite one
4701 byte beyond the end of the field, but what the heck... */
4702 ptr = &up->uaf$t_username[UAF$S_USERNAME];
4703 while (ptr[-1] == ' ')
4704 ptr--;
4705 *ptr = '\0';
4706 strcpy (retpw.pw_name, up->uaf$t_username);
4708 /* the rest of these are counted ascii strings */
4709 strncpy (retpw.pw_gecos, &up->uaf$t_owner[1], up->uaf$t_owner[0]);
4710 retpw.pw_gecos[up->uaf$t_owner[0]] = '\0';
4711 strncpy (retpw.pw_dir, &up->uaf$t_defdev[1], up->uaf$t_defdev[0]);
4712 retpw.pw_dir[up->uaf$t_defdev[0]] = '\0';
4713 strncat (retpw.pw_dir, &up->uaf$t_defdir[1], up->uaf$t_defdir[0]);
4714 retpw.pw_dir[up->uaf$t_defdev[0] + up->uaf$t_defdir[0]] = '\0';
4715 strncpy (retpw.pw_shell, &up->uaf$t_defcli[1], up->uaf$t_defcli[0]);
4716 retpw.pw_shell[up->uaf$t_defcli[0]] = '\0';
4718 return &retpw;
4720 #else /* not READ_SYSUAF */
4721 static struct passwd retpw;
4722 #endif /* not READ_SYSUAF */
4724 struct passwd *
4725 getpwnam (name)
4726 char * name;
4728 #ifdef READ_SYSUAF
4729 struct UAF *up;
4730 #else
4731 char * user;
4732 char * dir;
4733 unsigned char * full;
4734 #endif /* READ_SYSUAF */
4735 char *ptr = name;
4737 while (*ptr)
4739 if ('a' <= *ptr && *ptr <= 'z')
4740 *ptr -= 040;
4741 ptr++;
4743 #ifdef READ_SYSUAF
4744 if (!(up = get_uaf_name (name)))
4745 return 0;
4746 return cnv_uaf_pw (up);
4747 #else
4748 if (strcmp (name, getenv ("USER")) == 0)
4750 retpw.pw_uid = getuid ();
4751 retpw.pw_gid = getgid ();
4752 strcpy (retpw.pw_name, name);
4753 if (full = egetenv ("FULLNAME"))
4754 strcpy (retpw.pw_gecos, full);
4755 else
4756 *retpw.pw_gecos = '\0';
4757 strcpy (retpw.pw_dir, egetenv ("HOME"));
4758 *retpw.pw_shell = '\0';
4759 return &retpw;
4761 else
4762 return 0;
4763 #endif /* not READ_SYSUAF */
4766 struct passwd *
4767 getpwuid (uid)
4768 unsigned long uid;
4770 #ifdef READ_SYSUAF
4771 struct UAF * up;
4773 if (!(up = get_uaf_uic (uid)))
4774 return 0;
4775 return cnv_uaf_pw (up);
4776 #else
4777 if (uid == sys_getuid ())
4778 return getpwnam (egetenv ("USER"));
4779 else
4780 return 0;
4781 #endif /* not READ_SYSUAF */
4784 /* return total address space available to the current process. This is
4785 the sum of the current p0 size, p1 size and free page table entries
4786 available. */
4788 vlimit ()
4790 int item_code;
4791 unsigned long free_pages;
4792 unsigned long frep0va;
4793 unsigned long frep1va;
4794 register status;
4796 item_code = JPI$_FREPTECNT;
4797 if (((status = LIB$GETJPI (&item_code, 0, 0, &free_pages)) & 1) == 0)
4799 errno = EVMSERR;
4800 vaxc$errno = status;
4801 return -1;
4803 free_pages *= 512;
4805 item_code = JPI$_FREP0VA;
4806 if (((status = LIB$GETJPI (&item_code, 0, 0, &frep0va)) & 1) == 0)
4808 errno = EVMSERR;
4809 vaxc$errno = status;
4810 return -1;
4812 item_code = JPI$_FREP1VA;
4813 if (((status = LIB$GETJPI (&item_code, 0, 0, &frep1va)) & 1) == 0)
4815 errno = EVMSERR;
4816 vaxc$errno = status;
4817 return -1;
4820 return free_pages + frep0va + (0x7fffffff - frep1va);
4824 define_logical_name (varname, string)
4825 char *varname;
4826 char *string;
4828 struct dsc$descriptor_s strdsc =
4829 {strlen (string), DSC$K_DTYPE_T, DSC$K_CLASS_S, string};
4830 struct dsc$descriptor_s envdsc =
4831 {strlen (varname), DSC$K_DTYPE_T, DSC$K_CLASS_S, varname};
4832 struct dsc$descriptor_s lnmdsc =
4833 {7, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$JOB"};
4835 return LIB$SET_LOGICAL (&envdsc, &strdsc, &lnmdsc, 0, 0);
4839 delete_logical_name (varname)
4840 char *varname;
4842 struct dsc$descriptor_s envdsc =
4843 {strlen (varname), DSC$K_DTYPE_T, DSC$K_CLASS_S, varname};
4844 struct dsc$descriptor_s lnmdsc =
4845 {7, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$JOB"};
4847 return LIB$DELETE_LOGICAL (&envdsc, &lnmdsc);
4851 ulimit ()
4853 return 0;
4857 setpgrp ()
4859 return 0;
4863 execvp ()
4865 error ("execvp system call not implemented");
4866 return -1;
4870 rename (from, to)
4871 char *from, *to;
4873 int status;
4874 struct FAB from_fab = cc$rms_fab, to_fab = cc$rms_fab;
4875 struct NAM from_nam = cc$rms_nam, to_nam = cc$rms_nam;
4876 char from_esn[NAM$C_MAXRSS];
4877 char to_esn[NAM$C_MAXRSS];
4879 from_fab.fab$l_fna = from;
4880 from_fab.fab$b_fns = strlen (from);
4881 from_fab.fab$l_nam = &from_nam;
4882 from_fab.fab$l_fop = FAB$M_NAM;
4884 from_nam.nam$l_esa = from_esn;
4885 from_nam.nam$b_ess = sizeof from_esn;
4887 to_fab.fab$l_fna = to;
4888 to_fab.fab$b_fns = strlen (to);
4889 to_fab.fab$l_nam = &to_nam;
4890 to_fab.fab$l_fop = FAB$M_NAM;
4892 to_nam.nam$l_esa = to_esn;
4893 to_nam.nam$b_ess = sizeof to_esn;
4895 status = SYS$RENAME (&from_fab, 0, 0, &to_fab);
4897 if (status & 1)
4898 return 0;
4899 else
4901 if (status == RMS$_DEV)
4902 errno = EXDEV;
4903 else
4904 errno = EVMSERR;
4905 vaxc$errno = status;
4906 return -1;
4910 /* This function renames a file like `rename', but it strips
4911 the version number from the "to" filename, such that the "to" file is
4912 will always be a new version. It also sets the file protection once it is
4913 finished. The protection that we will use is stored in fab_final_pro,
4914 and was set when we did a creat_copy_attrs to create the file that we
4915 are renaming.
4917 We could use the chmod function, but Eunichs uses 3 bits per user category
4918 to describe the protection, and VMS uses 4 (write and delete are separate
4919 bits). To maintain portability, the VMS implementation of `chmod' wires
4920 the W and D bits together. */
4923 static struct fibdef fib; /* We need this initialized to zero */
4924 char vms_file_written[NAM$C_MAXRSS];
4927 rename_sans_version (from,to)
4928 char *from, *to;
4930 short int chan;
4931 int stat;
4932 short int iosb[4];
4933 int status;
4934 struct FAB to_fab = cc$rms_fab;
4935 struct NAM to_nam = cc$rms_nam;
4936 struct dsc$descriptor fib_d ={sizeof (fib),0,0,(char*) &fib};
4937 struct dsc$descriptor fib_attr[2]
4938 = {{sizeof (fab_final_pro),ATR$C_FPRO,0,(char*) &fab_final_pro},{0,0,0,0}};
4939 char to_esn[NAM$C_MAXRSS];
4941 $DESCRIPTOR (disk,to_esn);
4943 to_fab.fab$l_fna = to;
4944 to_fab.fab$b_fns = strlen (to);
4945 to_fab.fab$l_nam = &to_nam;
4946 to_fab.fab$l_fop = FAB$M_NAM;
4948 to_nam.nam$l_esa = to_esn;
4949 to_nam.nam$b_ess = sizeof to_esn;
4951 status = SYS$PARSE (&to_fab, 0, 0); /* figure out the full file name */
4953 if (to_nam.nam$l_fnb && NAM$M_EXP_VER)
4954 *(to_nam.nam$l_ver) = '\0';
4956 stat = rename (from, to_esn);
4957 if (stat < 0)
4958 return stat;
4960 strcpy (vms_file_written, to_esn);
4962 to_fab.fab$l_fna = vms_file_written; /* this points to the versionless name */
4963 to_fab.fab$b_fns = strlen (vms_file_written);
4965 /* Now set the file protection to the correct value */
4966 SYS$OPEN (&to_fab, 0, 0); /* This fills in the nam$w_fid fields */
4968 /* Copy these fields into the fib */
4969 fib.fib$r_fid_overlay.fib$w_fid[0] = to_nam.nam$w_fid[0];
4970 fib.fib$r_fid_overlay.fib$w_fid[1] = to_nam.nam$w_fid[1];
4971 fib.fib$r_fid_overlay.fib$w_fid[2] = to_nam.nam$w_fid[2];
4973 SYS$CLOSE (&to_fab, 0, 0);
4975 stat = SYS$ASSIGN (&disk, &chan, 0, 0); /* open a channel to the disk */
4976 if (!stat)
4977 LIB$SIGNAL (stat);
4978 stat = SYS$QIOW (0, chan, IO$_MODIFY, iosb, 0, 0, &fib_d,
4979 0, 0, 0, &fib_attr, 0);
4980 if (!stat)
4981 LIB$SIGNAL (stat);
4982 stat = SYS$DASSGN (chan);
4983 if (!stat)
4984 LIB$SIGNAL (stat);
4985 strcpy (vms_file_written, to_esn); /* We will write this to the terminal*/
4986 return 0;
4990 link (file, new)
4991 char * file, * new;
4993 register status;
4994 struct FAB fab;
4995 struct NAM nam;
4996 unsigned short fid[3];
4997 char esa[NAM$C_MAXRSS];
4999 fab = cc$rms_fab;
5000 fab.fab$l_fop = FAB$M_OFP;
5001 fab.fab$l_fna = file;
5002 fab.fab$b_fns = strlen (file);
5003 fab.fab$l_nam = &nam;
5005 nam = cc$rms_nam;
5006 nam.nam$l_esa = esa;
5007 nam.nam$b_ess = NAM$C_MAXRSS;
5009 status = SYS$PARSE (&fab);
5010 if ((status & 1) == 0)
5012 errno = EVMSERR;
5013 vaxc$errno = status;
5014 return -1;
5016 status = SYS$SEARCH (&fab);
5017 if ((status & 1) == 0)
5019 errno = EVMSERR;
5020 vaxc$errno = status;
5021 return -1;
5024 fid[0] = nam.nam$w_fid[0];
5025 fid[1] = nam.nam$w_fid[1];
5026 fid[2] = nam.nam$w_fid[2];
5028 fab.fab$l_fna = new;
5029 fab.fab$b_fns = strlen (new);
5031 status = SYS$PARSE (&fab);
5032 if ((status & 1) == 0)
5034 errno = EVMSERR;
5035 vaxc$errno = status;
5036 return -1;
5039 nam.nam$w_fid[0] = fid[0];
5040 nam.nam$w_fid[1] = fid[1];
5041 nam.nam$w_fid[2] = fid[2];
5043 nam.nam$l_esa = nam.nam$l_name;
5044 nam.nam$b_esl = nam.nam$b_name + nam.nam$b_type + nam.nam$b_ver;
5046 status = SYS$ENTER (&fab);
5047 if ((status & 1) == 0)
5049 errno = EVMSERR;
5050 vaxc$errno = status;
5051 return -1;
5054 return 0;
5057 void
5058 croak (badfunc)
5059 char *badfunc;
5061 printf ("%s not yet implemented\r\n", badfunc);
5062 reset_sys_modes ();
5063 exit (1);
5066 long
5067 random ()
5069 /* Arrange to return a range centered on zero. */
5070 return rand () - (1 << 30);
5073 void
5074 srandom (seed)
5076 srand (seed);
5078 #endif /* VMS */
5080 #ifdef AIXHFT
5082 /* Called from init_sys_modes. */
5083 void
5084 hft_init ()
5086 int junk;
5088 /* If we're not on an HFT we shouldn't do any of this. We determine
5089 if we are on an HFT by trying to get an HFT error code. If this
5090 call fails, we're not on an HFT. */
5091 #ifdef IBMR2AIX
5092 if (ioctl (0, HFQERROR, &junk) < 0)
5093 return;
5094 #else /* not IBMR2AIX */
5095 if (ioctl (0, HFQEIO, 0) < 0)
5096 return;
5097 #endif /* not IBMR2AIX */
5099 /* On AIX the default hft keyboard mapping uses backspace rather than delete
5100 as the rubout key's ASCII code. Here this is changed. The bug is that
5101 there's no way to determine the old mapping, so in reset_sys_modes
5102 we need to assume that the normal map had been present. Of course, this
5103 code also doesn't help if on a terminal emulator which doesn't understand
5104 HFT VTD's. */
5106 struct hfbuf buf;
5107 struct hfkeymap keymap;
5109 buf.hf_bufp = (char *)&keymap;
5110 buf.hf_buflen = sizeof (keymap);
5111 keymap.hf_nkeys = 2;
5112 keymap.hfkey[0].hf_kpos = 15;
5113 keymap.hfkey[0].hf_kstate = HFMAPCHAR | HFSHFNONE;
5114 #ifdef IBMR2AIX
5115 keymap.hfkey[0].hf_keyidh = '<';
5116 #else /* not IBMR2AIX */
5117 keymap.hfkey[0].hf_page = '<';
5118 #endif /* not IBMR2AIX */
5119 keymap.hfkey[0].hf_char = 127;
5120 keymap.hfkey[1].hf_kpos = 15;
5121 keymap.hfkey[1].hf_kstate = HFMAPCHAR | HFSHFSHFT;
5122 #ifdef IBMR2AIX
5123 keymap.hfkey[1].hf_keyidh = '<';
5124 #else /* not IBMR2AIX */
5125 keymap.hfkey[1].hf_page = '<';
5126 #endif /* not IBMR2AIX */
5127 keymap.hfkey[1].hf_char = 127;
5128 hftctl (0, HFSKBD, &buf);
5130 /* The HFT system on AIX doesn't optimize for scrolling, so it's really ugly
5131 at times. */
5132 line_ins_del_ok = char_ins_del_ok = 0;
5135 /* Reset the rubout key to backspace. */
5137 void
5138 hft_reset ()
5140 struct hfbuf buf;
5141 struct hfkeymap keymap;
5142 int junk;
5144 #ifdef IBMR2AIX
5145 if (ioctl (0, HFQERROR, &junk) < 0)
5146 return;
5147 #else /* not IBMR2AIX */
5148 if (ioctl (0, HFQEIO, 0) < 0)
5149 return;
5150 #endif /* not IBMR2AIX */
5152 buf.hf_bufp = (char *)&keymap;
5153 buf.hf_buflen = sizeof (keymap);
5154 keymap.hf_nkeys = 2;
5155 keymap.hfkey[0].hf_kpos = 15;
5156 keymap.hfkey[0].hf_kstate = HFMAPCHAR | HFSHFNONE;
5157 #ifdef IBMR2AIX
5158 keymap.hfkey[0].hf_keyidh = '<';
5159 #else /* not IBMR2AIX */
5160 keymap.hfkey[0].hf_page = '<';
5161 #endif /* not IBMR2AIX */
5162 keymap.hfkey[0].hf_char = 8;
5163 keymap.hfkey[1].hf_kpos = 15;
5164 keymap.hfkey[1].hf_kstate = HFMAPCHAR | HFSHFSHFT;
5165 #ifdef IBMR2AIX
5166 keymap.hfkey[1].hf_keyidh = '<';
5167 #else /* not IBMR2AIX */
5168 keymap.hfkey[1].hf_page = '<';
5169 #endif /* not IBMR2AIX */
5170 keymap.hfkey[1].hf_char = 8;
5171 hftctl (0, HFSKBD, &buf);
5174 #endif /* AIXHFT */
5176 #ifdef USE_DL_STUBS
5178 /* These are included on Sunos 4.1 when we do not use shared libraries.
5179 X11 libraries may refer to these functions but (we hope) do not
5180 actually call them. */
5182 void *
5183 dlopen ()
5185 return 0;
5188 void *
5189 dlsym ()
5191 return 0;
5195 dlclose ()
5197 return -1;
5200 #endif /* USE_DL_STUBS */
5202 #ifndef BSTRING
5204 #ifndef bzero
5206 void
5207 bzero (b, length)
5208 register char *b;
5209 register int length;
5211 #ifdef VMS
5212 short zero = 0;
5213 long max_str = 65535;
5215 while (length > max_str) {
5216 (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b);
5217 length -= max_str;
5218 b += max_str;
5220 max_str = length;
5221 (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b);
5222 #else
5223 while (length-- > 0)
5224 *b++ = 0;
5225 #endif /* not VMS */
5228 #endif /* no bzero */
5229 #endif /* BSTRING */
5231 #if (!defined (BSTRING) && !defined (bcopy)) || defined (NEED_BCOPY)
5232 #undef bcopy
5234 /* Saying `void' requires a declaration, above, where bcopy is used
5235 and that declaration causes pain for systems where bcopy is a macro. */
5236 bcopy (b1, b2, length)
5237 register char *b1;
5238 register char *b2;
5239 register int length;
5241 #ifdef VMS
5242 long max_str = 65535;
5244 while (length > max_str) {
5245 (void) LIB$MOVC3 (&max_str, b1, b2);
5246 length -= max_str;
5247 b1 += max_str;
5248 b2 += max_str;
5250 max_str = length;
5251 (void) LIB$MOVC3 (&length, b1, b2);
5252 #else
5253 while (length-- > 0)
5254 *b2++ = *b1++;
5255 #endif /* not VMS */
5257 #endif /* (!defined (BSTRING) && !defined (bcopy)) || defined (NEED_BCOPY) */
5259 #ifndef BSTRING
5260 #ifndef bcmp
5262 bcmp (b1, b2, length) /* This could be a macro! */
5263 register char *b1;
5264 register char *b2;
5265 register int length;
5267 #ifdef VMS
5268 struct dsc$descriptor_s src1 = {length, DSC$K_DTYPE_T, DSC$K_CLASS_S, b1};
5269 struct dsc$descriptor_s src2 = {length, DSC$K_DTYPE_T, DSC$K_CLASS_S, b2};
5271 return STR$COMPARE (&src1, &src2);
5272 #else
5273 while (length-- > 0)
5274 if (*b1++ != *b2++)
5275 return 1;
5277 return 0;
5278 #endif /* not VMS */
5280 #endif /* no bcmp */
5281 #endif /* not BSTRING */
5283 #ifndef HAVE_STRSIGNAL
5284 char *
5285 strsignal (code)
5286 int code;
5288 char *signame = 0;
5290 if (0 <= code && code < NSIG)
5292 #ifdef VMS
5293 signame = sys_errlist[code];
5294 #else
5295 /* Cast to suppress warning if the table has const char *. */
5296 signame = (char *) sys_siglist[code];
5297 #endif
5300 return signame;
5302 #endif /* HAVE_STRSIGNAL */
5304 /* All the Macintosh stuffs go here */
5306 #ifdef macintosh
5308 #include <Files.h>
5309 #include <MacTypes.h>
5310 #include <TextUtils.h>
5311 #include <Folders.h>
5313 #include <dirent.h>
5314 #include <sys/stat.h>
5315 #include <string.h>
5316 #include <pwd.h>
5317 #include <sys/param.h>
5319 /* Convert a Mac pathname to Unix form. A Mac full pathname is one
5320 that does not begin with a ':' and contains at least one ':'. A Mac
5321 full pathname causes an '/' to be prepended to the Unix pathname.
5322 The algorithm for the rest of the pathname is as follows:
5323 For each segment between two ':',
5324 if it is non-null, copy as is and then add a '/' at the end,
5325 otherwise, insert a "../" into the Unix pathname.
5326 Returns 1 if successful; 0 if fails. */
5329 Mac2UnixPathname (const char *mfn, char *ufn, int ufnbuflen)
5331 const char *p, *q, *pe;
5333 strcpy (ufn, "");
5335 if (*mfn == '\0')
5336 return 1;
5338 p = strchr (mfn, ':');
5339 if (p != 0 && p != mfn) /* full pathname */
5340 strcat (ufn, "/");
5342 p = mfn;
5343 if (*p == ':')
5344 p++;
5346 pe = mfn + strlen (mfn);
5347 while (p < pe)
5349 q = strchr (p, ':');
5350 if (q)
5352 if (q == p)
5353 { /* two consecutive ':' */
5354 if (strlen (ufn) + 3 >= ufnbuflen)
5355 return 0;
5356 strcat (ufn, "../");
5358 else
5360 if (strlen (ufn) + (q - p) + 1 >= ufnbuflen)
5361 return 0;
5362 strncat (ufn, p, q - p);
5363 strcat (ufn, "/");
5365 p = q + 1;
5367 else
5369 if (strlen (ufn) + (pe - p) >= ufnbuflen)
5370 return 0;
5371 strncat (ufn, p, pe - p); /* no separator for last one */
5372 p = pe;
5376 return 1;
5379 extern char *GetTempDirName ();
5381 /* Convert a Unix pathname to Mac form. Approximately reverse of the
5382 above in algorithm. */
5384 Unix2MacPathname (const char *ufn, char *mfn, int mfnbuflen)
5386 const char *p, *q, *pe;
5387 char expandedPathname[MAXPATHLEN+1];
5389 strcpy (mfn, "");
5391 if (*ufn == '\0')
5392 return 1;
5394 p = ufn;
5396 /* Check for and handle volume names. Last comparison: strangely
5397 somewhere `/.emacs' is passed. A temporary fix for now. */
5398 if (*p == '/' && strchr (p+1, '/') == NULL && strcmp (p, "/.emacs") != 0)
5400 if (strlen (p) + 1 > mfnbuflen)
5401 return 0;
5402 strcpy (mfn, p+1);
5403 strcat (mfn, ":");
5404 return 1;
5407 if (strncmp (p, "~emacs/", 7) == 0)
5408 { /* expand to emacs dir found by InitEmacsPasswdDir */
5409 struct passwd *pw = getpwnam ("emacs");
5410 p += 7;
5411 if (strlen (pw->pw_dir) + strlen (p) > MAXPATHLEN)
5412 return 0;
5413 strcpy (expandedPathname, pw->pw_dir);
5414 strcat (expandedPathname, p);
5415 p = expandedPathname;
5416 /* Now p points to the pathname with emacs dir prefix. */
5418 else if (strncmp (p, "/tmp/", 5) == 0)
5420 char *t = GetTempDirName ();
5421 p += 5;
5422 if (strlen (t) + strlen (p) > MAXPATHLEN)
5423 return 0;
5424 strcpy (expandedPathname, t);
5425 strcat (expandedPathname, p);
5426 p = expandedPathname;
5427 /* Now p points to the pathname with emacs dir prefix. */
5429 else if (*p != '/') /* relative pathname */
5430 strcat (mfn, ":");
5432 if (*p == '/')
5433 p++;
5435 pe = p + strlen (p);
5436 while (p < pe)
5438 q = strchr (p, '/');
5439 if (q)
5441 if (q - p == 2 && *p == '.' && *(p+1) == '.')
5443 if (strlen (mfn) + 1 >= mfnbuflen)
5444 return 0;
5445 strcat (mfn, ":");
5447 else
5449 if (strlen (mfn) + (q - p) + 1 >= mfnbuflen)
5450 return 0;
5451 strncat (mfn, p, q - p);
5452 strcat (mfn, ":");
5454 p = q + 1;
5456 else
5458 if (strlen (mfn) + (pe - p) >= mfnbuflen)
5459 return 0;
5460 strncat (mfn, p, pe - p);
5461 p = pe;
5465 return 1;
5468 /* The following functions with "sys_" prefix are stubs to Unix
5469 functions that have already been implemented by CW or MPW. The
5470 calls to them in Emacs source course are #define'd to call the sys_
5471 versions by the header files s-mac.h. In these stubs pathnames are
5472 converted between their Unix and Mac forms. */
5473 /* Unix Epoch is Jan 1, 1970 while Mac Epoch is Jan 1, 1904: 66 years
5474 + 17 leap days */
5475 #define MAC_UNIX_EPOCH_DIFF ((365L * 66 + 17) * 24 * 60 * 60)
5477 /* CW Epoch is Jan 1, 1900 (aaarghhhhh!); remember, 1900 is not a leap
5478 year! */
5479 #define CW_UNIX_EPOCH_DIFF ((365L * 70 + 17) * 24 * 60 * 60)
5481 /* Define our own stat function for both MrC and CW. The reason for
5482 doing this: "stat" is both the name of a struct and function name:
5483 we can't #define stat to something else to
5484 redirect Emacs's calls to our own version that converts Unix style
5485 filenames to Mac style filename because all sorts of compilation
5486 errors will be generated if stat is #define'd to be something else. */
5489 stat (const char *path, struct stat *buf)
5491 char MacPathname[MAXPATHLEN+1];
5492 CInfoPBRec cipb;
5494 if (Unix2MacPathname (path, MacPathname, MAXPATHLEN+1) == 0)
5495 return -1;
5497 c2pstr (MacPathname);
5498 cipb.hFileInfo.ioNamePtr = MacPathname;
5499 cipb.hFileInfo.ioVRefNum = 0;
5500 cipb.hFileInfo.ioDirID = 0;
5501 cipb.hFileInfo.ioFDirIndex = 0; /* set to 0 to get information about specific dir or file */
5503 errno = PBGetCatInfo (&cipb, false);
5504 if (errno == -43) /* -43: fnfErr defined in Errors.h */
5505 errno = ENOENT;
5506 if (errno != noErr)
5507 return -1;
5509 if (cipb.hFileInfo.ioFlAttrib & 0x10)
5510 { /* bit 4 = 1 for directories */
5511 buf->st_mode = S_IFDIR | S_IREAD | S_IEXEC;
5512 if (!(cipb.hFileInfo.ioFlAttrib & 0x1)) /* bit 1 = 1 for locked files/directories */
5513 buf->st_mode |= S_IWRITE;
5514 buf->st_ino = cipb.dirInfo.ioDrDirID;
5515 buf->st_dev = cipb.dirInfo.ioVRefNum;
5516 buf->st_size = cipb.dirInfo.ioDrNmFls; /* size of dir = number of files and dirs */
5517 buf->st_atime = buf->st_mtime = cipb.dirInfo.ioDrMdDat - MAC_UNIX_EPOCH_DIFF;
5518 buf->st_ctime = cipb.dirInfo.ioDrCrDat - MAC_UNIX_EPOCH_DIFF;
5520 else
5522 buf->st_mode = S_IFREG | S_IREAD;
5523 if (!(cipb.hFileInfo.ioFlAttrib & 0x1)) /* bit 1 = 1 for locked files/directories */
5524 buf->st_mode |= S_IWRITE;
5525 if (cipb.hFileInfo.ioFlFndrInfo.fdType == 'APPL')
5526 buf->st_mode |= S_IEXEC;
5527 buf->st_ino = cipb.hFileInfo.ioDirID;
5528 buf->st_dev = cipb.hFileInfo.ioVRefNum;
5529 buf->st_size = cipb.hFileInfo.ioFlLgLen;
5530 buf->st_atime = buf->st_mtime = cipb.hFileInfo.ioFlMdDat - MAC_UNIX_EPOCH_DIFF;
5531 buf->st_ctime = cipb.hFileInfo.ioFlCrDat - MAC_UNIX_EPOCH_DIFF;
5533 buf->st_nlink = 1;
5534 buf->st_uid = getuid ();
5535 buf->st_gid = getgid ();
5536 buf->st_rdev = 0;
5538 return 0;
5541 #if __MRC__
5543 /* CW defines fstat in stat.mac.c while MPW does not provide this
5544 function. Without the information of how to get from a file
5545 descriptor in MPW StdCLib to a Mac OS file spec, it should be hard
5546 to implement this function. Fortunately, there is only one place
5547 where this function is called in our configuration: in fileio.c,
5548 where only the st_dev and st_ino fields are used to determine
5549 whether two fildes point to different i-nodes to prevent copying
5550 a file onto itself equal. What we have here probably needs
5551 improvement. */
5553 fstat (int fildes, struct stat *buf)
5555 buf->st_dev = 0;
5556 buf->st_ino = fildes;
5557 return 0; /* success */
5560 #endif /* __MRC__ */
5562 /* From Think Reference code example */
5564 mkdir (const char *dirname, int mode)
5566 #pragma unused (mode)
5568 HFileParam hfpb;
5569 char MacPathname[MAXPATHLEN+1];
5571 if (Unix2MacPathname (dirname, MacPathname, MAXPATHLEN+1) == 0)
5572 return -1;
5574 c2pstr (MacPathname);
5575 hfpb.ioNamePtr = MacPathname;
5576 hfpb.ioVRefNum = 0; /*ignored unless name is invalid */
5577 hfpb.ioDirID = 0; /*parent is the root */
5579 /* Just return the Mac OSErr code for now. */
5580 errno = PBDirCreate ((HParmBlkPtr) &hfpb, false);
5581 return errno == noErr ? 0 : -1;
5585 rmdir (const char *dirname)
5587 HFileParam hfpb;
5588 char MacPathname[MAXPATHLEN+1];
5590 if (Unix2MacPathname (dirname, MacPathname, MAXPATHLEN+1) == 0)
5591 return -1;
5593 c2pstr (MacPathname);
5594 hfpb.ioNamePtr = MacPathname;
5595 hfpb.ioVRefNum = 0; /*ignored unless name is invalid */
5596 hfpb.ioDirID = 0; /*parent is the root */
5598 errno = PBHDelete ((HParmBlkPtr) &hfpb, false);
5599 return errno == noErr ? 0 : -1;
5602 #ifdef __MRC__
5604 /* No implementation yet. */
5606 execvp (const char *path, ...)
5608 return -1;
5611 #endif /* __MRC__ */
5614 utime (const char *path, const struct utimbuf *times)
5616 char MacPathname[MAXPATHLEN+1];
5617 CInfoPBRec cipb;
5619 if (Unix2MacPathname (path, MacPathname, MAXPATHLEN+1) == 0)
5620 return -1;
5622 c2pstr (MacPathname);
5623 cipb.hFileInfo.ioNamePtr = MacPathname;
5624 cipb.hFileInfo.ioVRefNum = 0;
5625 cipb.hFileInfo.ioDirID = 0;
5626 /* Set to 0 to get information about specific dir or file. */
5627 cipb.hFileInfo.ioFDirIndex = 0;
5629 errno = PBGetCatInfo (&cipb, false);
5630 if (errno != noErr)
5631 return -1;
5633 if (cipb.hFileInfo.ioFlAttrib & 0x10)
5634 { /* bit 4 = 1 for directories */
5635 if (times)
5636 cipb.dirInfo.ioDrMdDat = times->modtime + MAC_UNIX_EPOCH_DIFF;
5637 else
5638 GetDateTime (&cipb.dirInfo.ioDrMdDat);
5640 else
5642 if (times)
5643 cipb.hFileInfo.ioFlMdDat = times->modtime + MAC_UNIX_EPOCH_DIFF;
5644 else
5645 GetDateTime (&cipb.hFileInfo.ioFlMdDat);
5648 errno = PBSetCatInfo (&cipb, false);
5649 return errno == noErr ? 0 : -1;
5652 #define F_OK 0
5653 #define X_OK 1
5654 #define W_OK 2
5656 /* Like stat, but test for access mode in hfpb.ioFlAttrib. */
5658 access (const char *path, int mode)
5660 char MacPathname[MAXPATHLEN+1];
5661 CInfoPBRec cipb;
5663 if (Unix2MacPathname (path, MacPathname, MAXPATHLEN+1) == 0)
5664 return -1;
5666 c2pstr (MacPathname);
5667 cipb.hFileInfo.ioNamePtr = MacPathname;
5668 cipb.hFileInfo.ioVRefNum = 0;
5669 cipb.hFileInfo.ioDirID = 0;
5670 cipb.hFileInfo.ioFDirIndex = 0; /* set to 0 to get information about specific dir or file */
5672 errno = PBGetCatInfo (&cipb, false);
5673 if (errno != noErr)
5674 return -1;
5676 if (mode == F_OK) /* got this far, file exists */
5677 return 0;
5679 if (mode & X_OK)
5680 if (cipb.hFileInfo.ioFlAttrib & 0x10) /* path refers to a directory */
5681 return 0;
5682 else
5684 if (cipb.hFileInfo.ioFlFndrInfo.fdType == 'APPL')
5685 return 0;
5686 else
5687 return -1;
5690 if (mode & W_OK)
5691 return (cipb.hFileInfo.ioFlAttrib & 0x1) ? -1 : 0; /* don't allow if lock bit on */
5693 return -1;
5696 #define DEV_NULL_FD 0x10000
5698 #undef open
5700 sys_open (const char *path, int oflag)
5702 char MacPathname[MAXPATHLEN+1];
5704 if (strcmp (path, "/dev/null") == 0)
5705 return DEV_NULL_FD; /* some bogus fd to be ignored in write */
5707 if (Unix2MacPathname (path, MacPathname, MAXPATHLEN+1) == 0)
5708 return -1;
5709 else
5710 return open (MacPathname, oflag);
5713 #undef creat
5715 sys_creat (const char *path, mode_t mode)
5717 char MacPathname[MAXPATHLEN+1];
5719 if (Unix2MacPathname (path, MacPathname, MAXPATHLEN+1) == 0)
5720 return -1;
5721 else
5722 return creat (MacPathname, mode);
5725 #undef unlink
5727 sys_unlink (const char *path)
5729 char MacPathname[MAXPATHLEN+1];
5731 if (Unix2MacPathname (path, MacPathname, MAXPATHLEN+1) == 0)
5732 return -1;
5733 else
5734 return unlink (MacPathname);
5737 #undef read
5739 sys_read (int fildes, char *buf, int count)
5741 if (fildes == 0)
5742 { /* if stdin, call (non-echoing) "getch" in console.h */
5743 if (MacKeyPending ())
5744 { /* don't wait for a key if none has been pressed */
5745 *buf = MacGetChar ();
5746 return 1;
5748 else
5749 return 0;
5751 else
5752 return read (fildes, buf, count);
5755 #undef write
5757 sys_write (int fildes, char *buf, int count)
5759 if (fildes == DEV_NULL_FD)
5760 return count;
5761 else
5762 return write (fildes, buf, count);
5765 #undef rename
5767 sys_rename (const char * old_name, const char * new_name)
5769 char MacOldName[MAXPATHLEN+1], MacNewName[MAXPATHLEN+1];
5771 if (strcmp (old_name, new_name) == 0)
5772 return 0;
5774 if (Unix2MacPathname (old_name, MacOldName, MAXPATHLEN+1) == 0)
5775 return 1;
5777 if (Unix2MacPathname (new_name, MacNewName, MAXPATHLEN+1) == 0)
5778 return 1;
5780 return rename (MacOldName, MacNewName);
5783 #undef fopen
5784 extern FILE *fopen (const char *name, const char *mode);
5785 FILE
5786 sys_fopen (const char *name, const char *mode)
5788 char MacPathname[MAXPATHLEN+1];
5790 if (Unix2MacPathname (name, MacPathname, MAXPATHLEN+1) == 0)
5791 return 0;
5792 else
5793 return fopen (MacPathname, mode);
5796 #include <Events.h>
5798 long targetTicks = 0;
5800 #ifdef __MRC__
5801 __sigfun alarm_signal_func = (__sigfun) 0;
5802 #elif __MWERKS__
5803 __signal_func_ptr alarm_signal_func = (__signal_func_ptr) 0;
5804 #else
5805 You lose!!!
5806 #endif
5808 /* These functions simulate SIG_ALRM. The stub for function signal
5809 stores the signal handler function in alarm_signal_func if a
5810 SIG_ALRM is encountered. CheckAlarm is called in mac_read_socket,
5811 which emacs calls periodically. A pending alarm is represented by
5812 a non-zero targetTicks value. CheckAlarm calls the handler
5813 function pointed to by alarm_signal_func if one has been set up and
5814 an alarm is pending. */
5815 void
5816 CheckAlarm ()
5818 if (targetTicks && TickCount () > targetTicks)
5820 targetTicks = 0;
5821 if (alarm_signal_func)
5822 (*alarm_signal_func)(SIGALRM);
5826 /* Called in sys_select to wait for an alarm signal to arrive. */
5828 pause ()
5830 unsigned long finalTick;
5832 if (!targetTicks) /* no alarm pending */
5833 return -1;
5835 while (TickCount () <= targetTicks)
5836 Delay (1UL, &finalTick); /* wait for 1/60 second before trying again */
5838 targetTicks = 0;
5839 if (alarm_signal_func)
5840 (*alarm_signal_func)(SIGALRM);
5842 return 0;
5846 alarm (int seconds)
5848 long remaining = targetTicks ? (TickCount () - targetTicks) / 60 : 0;
5850 targetTicks = seconds ? TickCount () + 60 * seconds : 0;
5852 return (remaining < 0) ? 0 : (unsigned int) remaining;
5855 #undef signal
5856 #ifdef __MRC__
5857 extern __sigfun signal (int signal, __sigfun signal_func);
5858 __sigfun
5859 sys_signal (int signal_num, __sigfun signal_func)
5860 #elif __MWERKS__
5861 extern __signal_func_ptr signal (int signal, __signal_func_ptr signal_func);
5862 __signal_func_ptr
5863 sys_signal (int signal_num, __signal_func_ptr signal_func)
5864 #else
5865 You lose!!!
5866 #endif
5868 if (signal_num != SIGALRM)
5869 return signal (signal_num, signal_func);
5870 else
5872 #ifdef __MRC__
5873 __sigfun old_signal_func;
5874 #elif __MWERKS__
5875 __signal_func_ptr old_signal_func;
5876 #else
5877 You lose!!!
5878 #endif
5879 old_signal_func = alarm_signal_func;
5880 alarm_signal_func = signal_func;
5881 return old_signal_func;
5885 /* The time functions adjust time values according to the difference
5886 between the Unix and CW epoches. */
5888 #undef gmtime
5889 extern struct tm *gmtime (const time_t *);
5890 struct tm
5891 sys_gmtime (const time_t *timer)
5893 time_t unixTime = *timer + CW_UNIX_EPOCH_DIFF;
5895 return gmtime (&unixTime);
5898 #undef localtime
5899 extern struct tm *localtime (const time_t *);
5900 struct tm *
5901 sys_localtime (const time_t *timer)
5903 time_t unixTime = *timer + CW_UNIX_EPOCH_DIFF;
5905 return localtime (&unixTime);
5908 #undef ctime
5909 extern char *ctime (const time_t *);
5910 char *
5911 sys_ctime (const time_t *timer)
5913 time_t unixTime = *timer + CW_UNIX_EPOCH_DIFF;
5915 return ctime (&unixTime);
5918 #undef time
5919 extern time_t time (time_t *);
5920 time_t
5921 sys_time (time_t *timer)
5923 time_t macTime = time (NULL) - CW_UNIX_EPOCH_DIFF;
5925 if (timer)
5926 *timer = macTime;
5928 return macTime;
5931 /* no subprocesses, empty wait */
5933 wait (int pid)
5935 return 0;
5938 void
5939 croak (char *badfunc)
5941 printf ("%s not yet implemented\r\n", badfunc);
5942 exit (1);
5945 char *
5946 index (const char * str, int chr)
5948 return strchr (str, chr);
5951 char *e[] = { 0 };
5952 char **environ = &e[0];
5954 char *
5955 mktemp (char *template)
5957 int len, k;
5958 static seqnum = 0;
5960 len = strlen (template);
5961 k = len - 1;
5962 while (k >= 0 && template[k] == 'X')
5963 k--;
5965 k++; /* make k index of first 'X' */
5967 if (k < len)
5969 /* Zero filled, number of digits equal to the number of X's. */
5970 sprintf (&template[k], "%0*d", len-k, seqnum++);
5972 return template;
5974 else
5975 return 0;
5978 /* Emulate getpwuid, getpwnam and others. */
5980 #define PASSWD_FIELD_SIZE 256
5982 static char myPasswdName[PASSWD_FIELD_SIZE];
5983 static char myPasswdDir[MAXPATHLEN+1];
5985 static struct passwd myPasswd =
5987 myPasswdName,
5988 myPasswdDir,
5991 /* Initialized by main () in macterm.c to pathname of emacs directory. */
5992 char emacsPasswdDir[MAXPATHLEN+1];
5994 void
5995 InitEmacsPasswdDir ()
5997 int found = false;
5999 if (getwd (emacsPasswdDir) && getwd (myPasswdDir))
6001 /* Need pathname of first ancestor that begins with `emacs' since
6002 Mac emacs application is somewhere in the emacs-20.3 tree. */
6003 int len = strlen (emacsPasswdDir);
6004 /* J points to the "/" following the directory name being compared. */
6005 int j = len - 1;
6006 int i = j - 1;
6007 while (i >= 0 && !found)
6009 while (i >= 0 && emacsPasswdDir[i] != '/')
6010 i--;
6011 if (emacsPasswdDir[i] == '/' && i+5 < len)
6012 found = (strncmp (&(emacsPasswdDir[i+1]), "emacs", 5) == 0);
6013 if (found)
6014 emacsPasswdDir[j+1] = '\0';
6015 else
6017 j = i;
6018 i = j - 1;
6023 if (!found)
6024 { /* setting to "/" probably won't work,
6025 but set it to something anyway. */
6026 strcpy (emacsPasswdDir, "/");
6027 strcpy (myPasswdDir, "/");
6031 static struct passwd emacsPasswd =
6033 "emacs",
6034 emacsPasswdDir,
6037 static int myPasswdInited = 0;
6039 static void
6040 InitMyPasswd ()
6042 char **ownerName;
6044 /* Note: myPasswdDir initialized in InitEmacsPasswdDir to directory
6045 where Emacs was started. */
6047 ownerName = (char **) GetResource ('STR ',-16096);
6048 if (ownerName)
6050 HLock (ownerName);
6051 BlockMove ((unsigned char *) *ownerName,
6052 (unsigned char *) myPasswdName, *ownerName[0] + 1);
6053 HUnlock (ownerName);
6054 p2cstr ((unsigned char *) myPasswdName);
6056 else
6057 myPasswdName[0] = 0;
6060 struct passwd *
6061 getpwuid (uid_t uid)
6063 if (!myPasswdInited)
6065 InitMyPasswd ();
6066 myPasswdInited = 1;
6069 return &myPasswd;
6072 struct passwd *
6073 getpwnam (const char *name)
6075 if (strcmp (name, "emacs") == 0)
6076 return &emacsPasswd;
6078 if (!myPasswdInited)
6080 InitMyPasswd ();
6081 myPasswdInited = 1;
6084 return &myPasswd;
6087 /* The functions fork, kill, sigsetmask, sigblock, request_sigio,
6088 setpgrp, setpriority, and unrequest_sigio are defined to be empty
6089 as in msdos.c. */
6092 fork ()
6094 return -1;
6098 kill (int x, int y)
6100 return -1;
6104 sigsetmask (int x)
6106 return 0;
6110 sigblock (int mask)
6112 return 0;
6115 void
6116 request_sigio (void)
6121 setpgrp ()
6123 return 0;
6126 void
6127 unrequest_sigio (void)
6131 /* djgpp does not implement pipe either. */
6133 pipe (int _fildes[2])
6135 errno = EACCES;
6136 return -1;
6139 /* Hard and symbolic links. */
6141 symlink (const char *name1, const char *name2)
6143 errno = ENOENT;
6144 return -1;
6148 link (const char *name1, const char *name2)
6150 errno = ENOENT;
6151 return -1;
6155 lstat (const char *path, struct stat *sb)
6157 return stat (path, sb);
6161 readlink (const char *path, char *buf, int bufsiz)
6163 errno = ENOENT;
6164 return -1;
6167 mode_t
6168 umask (mode_t numask)
6170 static mode_t mask = 022;
6171 mode_t oldmask = mask;
6172 mask = numask;
6173 return oldmask;
6177 chmod (const char *path, mode_t mode)
6179 /* say it always succeed for now */
6180 return 0;
6184 dup (int oldd)
6186 #ifdef __MRC__
6187 return fcntl (oldd, F_DUPFD, 0);
6188 #elif __MWERKS__
6189 /* current implementation of fcntl in fcntl.mac.c simply returns old
6190 descriptor */
6191 return fcntl (oldd, F_DUPFD);
6192 #else
6193 You lose!!!
6194 #endif
6197 /* This is from the original sysdep.c. Emulate BSD dup2. First close
6198 newd if it already exists. Then, attempt to dup oldd. If not
6199 successful, call dup2 recursively until we are, then close the
6200 unsuccessful ones. */
6202 dup2 (int oldd, int newd)
6204 int fd, ret;
6206 close (newd);
6208 fd = dup (oldd);
6209 if (fd == -1)
6210 return -1;
6211 if (fd == newd)
6212 return newd;
6213 ret = dup2 (oldd, newd);
6214 close (fd);
6215 return ret;
6218 /* let it fail for now */
6219 char *
6220 sbrk (int incr)
6222 return (char *) -1;
6226 fsync (int fd)
6228 return 0;
6232 ioctl (int d, int request, void *argp)
6234 return -1;
6237 #ifdef __MRC__
6239 isatty (int fildes)
6241 if (fildes >=0 && fildes <= 2)
6242 return 1;
6243 else
6244 return 0;
6248 getgid ()
6250 return 100;
6254 getegid ()
6256 return 100;
6260 getuid ()
6262 return 200;
6266 geteuid ()
6268 return 200;
6271 unsigned int
6272 sleep (unsigned int seconds)
6274 unsigned long finalTick;
6276 Delay (seconds * 60UL, &finalTick);
6277 return (0);
6279 #endif /* __MRC__ */
6281 #ifdef __MWERKS__
6282 #undef getpid
6284 getpid ()
6286 return 9999;
6288 #endif /* __MWERKS__ */
6290 /* Return the path to the directory in which Emacs can create
6291 temporary files. The MacOS "temporary items" directory cannot be
6292 used because it removes the file written by a process when it
6293 exits. In that sense it's more like "/dev/null" than "/tmp" (but
6294 again not exactly). And of course Emacs needs to read back the
6295 files written by its subprocesses. So here we write the files to a
6296 directory "Emacs" in the Preferences Folder. This directory is
6297 created if it does not exist. */
6298 static char *
6299 GetTempDirName ()
6301 static char *TempDirName = NULL;
6302 short vRefNum;
6303 long dirID;
6304 OSErr err;
6305 Str255 dirName, fullPath;
6306 CInfoPBRec cpb;
6307 char unixDirName[MAXPATHLEN+1];
6308 DIR *dir;
6310 /* Cache directory name with pointer TempDirName.
6311 Look for it only the first time. */
6312 if (!TempDirName)
6314 err = FindFolder (kOnSystemDisk, kPreferencesFolderType,
6315 kCreateFolder, &vRefNum, &dirID);
6316 if (err != noErr)
6317 return NULL;
6319 *fullPath = '\0';
6320 cpb.dirInfo.ioNamePtr = dirName;
6321 cpb.dirInfo.ioDrParID = dirID;
6323 /* Standard ref num to full path name loop */
6324 do {
6325 cpb.dirInfo.ioVRefNum = vRefNum;
6326 cpb.dirInfo.ioFDirIndex = -1;
6327 cpb.dirInfo.ioDrDirID = cpb.dirInfo.ioDrParID;
6329 err = PBGetCatInfo (&cpb, false);
6331 p2cstr (dirName);
6332 strcat (dirName, ":");
6333 if (strlen (fullPath) + strlen (dirName) <= MAXPATHLEN)
6335 strcat (dirName, fullPath);
6336 strcpy (fullPath, dirName);
6338 else
6339 return NULL;
6341 while (cpb.dirInfo.ioDrDirID != fsRtDirID && err == noErr);
6343 if (strlen (fullPath) + 6 <= MAXPATHLEN)
6344 strcat (fullPath, "Emacs:");
6345 else
6346 return NULL;
6348 if (Mac2UnixPathname (fullPath, unixDirName, MAXPATHLEN+1) == 0)
6349 return NULL;
6351 dir = opendir (unixDirName); /* check whether temp directory exists */
6352 if (dir)
6353 closedir (dir);
6354 else if (mkdir (unixDirName, 0700) != 0) /* create it if not */
6355 return NULL;
6357 TempDirName = (char *) xmalloc (strlen (unixDirName) + 1);
6358 strcpy (TempDirName, unixDirName);
6361 return TempDirName;
6364 char *
6365 getenv (const char * name)
6367 if (strcmp (name, "TERM") == 0)
6368 return "vt100";
6369 else if (strcmp (name, "TERMCAP") == 0)
6370 /* for debugging purpose when code was still outputting to dumb terminal */
6371 return "d0|vt100|vt100-am|vt100am|dec vt100:do=[do]:co#100:li#32:cl=[cl]:sf=[sf]:km:\
6372 :le=[le]:bs:am:cm=[cm-%d,%d]:nd=[nd]:up=[up]:ce=[ce]:cd=[cd]:so=[so]:se=[se]:\
6373 :us=[us]:ue=[ue]:md=[md]:mr=[mr]:mb=[mb]:me=[me]:is=[is]:\
6374 :rf=/usr/share/lib/tabset/vt100:rs=[rs]:ks=[ks]:ke=[ke]:\
6375 :ku=\\036:kd=\\037:kr=\\035:kl=\\034:kb=[kb]:ho=[ho]:k1=[k1]:k2=[k2]:k3=[k3]:k4=[k4]:\
6376 :pt:sr=[sr]:vt#3:xn:sc=[sc]:rc=[rc]:cs=[cs-%d,%d]";
6377 else if (strcmp (name, "TMPDIR") == 0)
6378 return GetTempDirName ();
6379 else
6380 return (NULL);
6383 #ifdef __MRC__
6384 #include <utsname.h>
6387 uname (struct utsname *name)
6389 char **systemName;
6390 systemName = GetString (-16413); /* IM - Resource Manager Reference */
6391 if (systemName)
6393 BlockMove (*systemName, name->nodename, (*systemName)[0]+1);
6394 p2cstr (name->nodename);
6396 else
6397 return -1;
6399 #endif
6401 #include <Processes.h>
6402 #include <EPPC.h>
6404 /* Event class of HLE sent to subprocess. */
6405 const OSType kEmacsSubprocessSend = 'ESND';
6406 /* Event class of HLE sent back from subprocess. */
6407 const OSType kEmacsSubprocessReply = 'ERPY';
6409 char *
6410 mystrchr (char *s, char c)
6412 while (*s && *s != c)
6414 if (*s == '\\')
6415 s++;
6416 s++;
6419 if (*s)
6421 *s = '\0';
6422 return s;
6424 else
6425 return NULL;
6428 char *
6429 mystrtok (char *s)
6431 while (*s)
6432 s++;
6434 return s + 1;
6437 void
6438 mystrcpy (char *to, char *from)
6440 while (*from)
6442 if (*from == '\\')
6443 from++;
6444 *to++ = *from++;
6446 *to = '\0';
6449 /* Start a Mac subprocess. Arguments for it is passed in argv (null
6450 terminated). The process should run with the default directory
6451 "workdir", read input from "infn", and write output and error to
6452 "outfn" and "errfn", resp. The Process Manager call
6453 LaunchApplication is used to start the subprocess. We use high
6454 level events as the mechanism to pass arguments to the subprocess
6455 and to make Emacs wait for the subprocess to terminate and pass
6456 back a result code. The bulk of the code here packs the arguments
6457 into one message to be passed together with the high level event.
6458 Emacs also sometimes starts a subprocess using a shell to perform
6459 wildcard filename expansion. Since we don't really have a shell on
6460 the Mac, this case is detected and the starting of the shell is
6461 by-passed. We really need to add code here to do filename
6462 expansion to support such functionality. */
6464 run_mac_command (argv, workdir, infn, outfn, errfn)
6465 unsigned char **argv;
6466 const char *workdir;
6467 const char *infn, *outfn, errfn;
6469 char macappname[MAXPATHLEN+1], macworkdir[MAXPATHLEN+1];
6470 char macinfn[MAXPATHLEN+1], macoutfn[MAXPATHLEN+1], macerrfn[MAXPATHLEN+1];
6471 int paramlen, argc, newargc, j, retries;
6472 char **newargv, *param, *p;
6473 OSErr iErr;
6474 FSSpec spec;
6475 LaunchParamBlockRec lpbr;
6476 EventRecord sendEvent, replyEvent;
6477 RgnHandle cursorRegionHdl;
6478 TargetID targ;
6479 unsigned long refCon, len;
6481 if (Unix2MacPathname (workdir, macworkdir, MAXPATHLEN+1) == 0)
6482 return -1;
6483 if (Unix2MacPathname (infn, macinfn, MAXPATHLEN+1) == 0)
6484 return -1;
6485 if (Unix2MacPathname (outfn, macoutfn, MAXPATHLEN+1) == 0)
6486 return -1;
6487 if (Unix2MacPathname (errfn, macerrfn, MAXPATHLEN+1) == 0)
6488 return -1;
6490 paramlen = strlen (macworkdir) + strlen (macinfn) + strlen (macoutfn) + strlen (macerrfn) + 4;
6491 /* count nulls at end of strings */
6493 argc = 0;
6494 while (argv[argc])
6495 argc++;
6497 if (argc == 0)
6498 return -1;
6500 /* If a subprocess is invoked with a shell, we receive 3 arguments of the form:
6501 "<path to emacs bins>/sh" "-c" "<path to emacs bins>/<command> <command args>" */
6502 j = strlen (argv[0]);
6503 if (j >= 3 && strcmp (argv[0]+j-3, "/sh") == 0 && argc == 3 && strcmp (argv[1], "-c") == 0)
6505 char *command, *t, tempmacpathname[MAXPATHLEN+1];
6507 /* The arguments for the command in argv[2] are separated by
6508 spaces. Count them and put the count in newargc. */
6509 command = (char *) alloca (strlen (argv[2])+2);
6510 strcpy (command, argv[2]);
6511 if (command[strlen (command) - 1] != ' ')
6512 strcat (command, " ");
6514 t = command;
6515 newargc = 0;
6516 t = mystrchr (t, ' ');
6517 while (t)
6519 newargc++;
6520 t = mystrchr (t+1, ' ');
6523 newargv = (char **) alloca (sizeof (char *) * newargc);
6525 t = command;
6526 for (j = 0; j < newargc; j++)
6528 newargv[j] = (char *) alloca (strlen (t) + 1);
6529 mystrcpy (newargv[j], t);
6531 t = mystrtok (t);
6532 paramlen += strlen (newargv[j]) + 1;
6535 if (strncmp (newargv[0], "~emacs/", 7) == 0)
6537 if (Unix2MacPathname (newargv[0], tempmacpathname, MAXPATHLEN+1) == 0)
6538 return -1;
6540 else
6541 { /* sometimes Emacs call "sh" without a path for the command */
6542 #if 0
6543 char *t = (char *) alloca (strlen (newargv[0]) + 7 + 1);
6544 strcpy (t, "~emacs/");
6545 strcat (t, newargv[0]);
6546 #endif
6547 Lisp_Object path;
6548 openp (Vexec_path, build_string (newargv[0]), EXEC_SUFFIXES, &path, 1);
6550 if (NILP (path))
6551 return -1;
6552 if (Unix2MacPathname (XSTRING (path)->data, tempmacpathname, MAXPATHLEN+1) == 0)
6553 return -1;
6555 strcpy (macappname, tempmacpathname);
6557 else
6559 if (Unix2MacPathname (argv[0], macappname, MAXPATHLEN+1) == 0)
6560 return -1;
6562 newargv = (char **) alloca (sizeof (char *) * argc);
6563 newargc = argc;
6564 for (j = 1; j < argc; j++)
6566 if (strncmp (argv[j], "~emacs/", 7) == 0)
6568 char *t = strchr (argv[j], ' ');
6569 if (t)
6571 char tempcmdname[MAXPATHLEN+1], tempmaccmdname[MAXPATHLEN+1];
6572 strncpy (tempcmdname, argv[j], t-argv[j]);
6573 tempcmdname[t-argv[j]] = '\0';
6574 if (Unix2MacPathname (tempcmdname, tempmaccmdname, MAXPATHLEN+1) == 0)
6575 return -1;
6576 newargv[j] = (char *) alloca (strlen (tempmaccmdname) + strlen (t) + 1);
6577 strcpy (newargv[j], tempmaccmdname);
6578 strcat (newargv[j], t);
6580 else
6582 char tempmaccmdname[MAXPATHLEN+1];
6583 if (Unix2MacPathname (argv[j], tempmaccmdname, MAXPATHLEN+1) == 0)
6584 return -1;
6585 newargv[j] = (char *) alloca (strlen (tempmaccmdname)+1);
6586 strcpy (newargv[j], tempmaccmdname);
6589 else
6590 newargv[j] = argv[j];
6591 paramlen += strlen (newargv[j]) + 1;
6595 /* After expanding all the arguments, we now know the length of the parameter block to be
6596 sent to the subprocess as a message attached to the HLE. */
6597 param = (char *) xmalloc (paramlen + 1);
6598 if (!param)
6599 return -1;
6601 p = param;
6602 *p++ = newargc; /* first byte of message contains number of arguments for command */
6603 strcpy (p, macworkdir);
6604 p += strlen (macworkdir);
6605 *p++ = '\0'; /* null terminate strings sent so it's possible to use strcpy over there */
6606 strcpy (p, macinfn);
6607 p += strlen (macinfn);
6608 *p++ = '\0';
6609 strcpy (p, macoutfn);
6610 p += strlen (macoutfn);
6611 *p++ = '\0';
6612 strcpy (p, macerrfn);
6613 p += strlen (macerrfn);
6614 *p++ = '\0';
6615 for (j = 1; j < newargc; j++) {
6616 strcpy (p, newargv[j]);
6617 p += strlen (newargv[j]);
6618 *p++ = '\0';
6621 c2pstr (macappname);
6623 iErr = FSMakeFSSpec (0, 0, macappname, &spec);
6625 if (iErr != noErr) {
6626 xfree (param);
6627 return -1;
6630 lpbr.launchBlockID = extendedBlock;
6631 lpbr.launchEPBLength = extendedBlockLen;
6632 lpbr.launchControlFlags = launchContinue + launchNoFileFlags;
6633 lpbr.launchAppSpec = &spec;
6634 lpbr.launchAppParameters = NULL;
6636 iErr = LaunchApplication (&lpbr); /* call the subprocess */
6637 if (iErr != noErr)
6639 xfree (param);
6640 return -1;
6643 sendEvent.what = kHighLevelEvent;
6644 sendEvent.message = kEmacsSubprocessSend; /* Event ID stored in "where" unused */
6646 retries = 3;
6647 do { /* OS may think current subprocess has terminated if previous one terminated recently */
6648 iErr = PostHighLevelEvent (&sendEvent, &lpbr.launchProcessSN, 0, param, paramlen + 1, receiverIDisPSN);
6650 while (iErr == sessClosedErr && retries-- > 0);
6652 if (iErr != noErr) {
6653 xfree (param);
6654 return -1;
6657 cursorRegionHdl = NewRgn ();
6659 /* Wait for the subprocess to finish, when it will send us a ERPY high level event */
6660 while (1)
6661 if (WaitNextEvent (highLevelEventMask, &replyEvent, 180, cursorRegionHdl) && replyEvent.message == kEmacsSubprocessReply)
6662 break;
6664 /* The return code is sent through the refCon */
6665 iErr = AcceptHighLevelEvent (&targ, &refCon, NULL, &len);
6666 if (iErr != noErr) {
6667 DisposeHandle ((Handle) cursorRegionHdl);
6668 xfree (param);
6669 return -1;
6672 DisposeHandle ((Handle) cursorRegionHdl);
6673 xfree (param);
6675 return refCon;
6678 DIR *
6679 opendir (const char *dirname)
6681 char MacPathname[MAXPATHLEN+1];
6682 DIR *dirp;
6683 CInfoPBRec cipb;
6684 int len;
6686 dirp = (DIR *) xmalloc (sizeof (DIR));
6687 if (!dirp)
6688 return 0;
6690 /* Handle special case when dirname is "/": sets up for readir to
6691 get all mount volumes. */
6692 if (strcmp (dirname, "/") == 0) {
6693 dirp->getting_volumes = 1; /* special all mounted volumes DIR struct */
6694 dirp->current_index = 1; /* index for first volume */
6695 return dirp;
6698 /* Handle typical cases: not accessing all mounted volumes. */
6699 if (Unix2MacPathname (dirname, MacPathname, MAXPATHLEN+1) == 0)
6700 return 0;
6702 /* Emacs calls opendir without the trailing '/', Mac needs trailing ':' */
6703 len = strlen (MacPathname);
6704 if (MacPathname[len - 1] != ':' && len < MAXPATHLEN)
6705 strcat (MacPathname, ":");
6707 c2pstr (MacPathname);
6708 cipb.hFileInfo.ioNamePtr = MacPathname; /* using full pathname so vRefNum and dirID ignored */
6709 cipb.hFileInfo.ioVRefNum = 0;
6710 cipb.hFileInfo.ioDirID = 0;
6711 cipb.hFileInfo.ioFDirIndex = 0; /* set to 0 to get information about specific dir or file */
6713 errno = PBGetCatInfo (&cipb, false);
6714 if (errno != noErr) {
6715 errno = ENOENT;
6716 return 0;
6719 if (!(cipb.hFileInfo.ioFlAttrib & 0x10)) /* bit 4 = 1 for directories */
6720 return 0; /* not a directory */
6722 dirp->dir_id = cipb.dirInfo.ioDrDirID; /* used later in readdir */
6723 dirp->getting_volumes = 0;
6724 dirp->current_index = 1; /* index for first file/directory */
6726 return dirp;
6730 closedir (DIR *dp)
6732 xfree (dp);
6733 return 0;
6736 struct dirent *
6737 readdir (DIR *dp)
6739 HParamBlockRec HPBlock;
6740 CInfoPBRec cipb;
6741 static struct dirent s_dirent;
6742 static Str255 s_name;
6743 int done;
6745 /* Handle the root directory containing the mounted volumes. Call
6746 PBHGetVInfo specifying an index to obtain the info for a volume.
6747 PBHGetVInfo returns an error when it receives an index beyond the
6748 last volume, at which time we should return a nil dirent struct
6749 pointer. */
6750 if (dp->getting_volumes) {
6751 HPBlock.volumeParam.ioNamePtr = s_name;
6752 HPBlock.volumeParam.ioVRefNum = 0;
6753 HPBlock.volumeParam.ioVolIndex = dp->current_index;
6755 errno = PBHGetVInfo (&HPBlock, false);
6756 if (errno != noErr) {
6757 errno = ENOENT;
6758 return 0;
6761 p2cstr (s_name);
6762 strcat (s_name, "/"); /* need "/" for stat to work correctly */
6764 dp->current_index++;
6766 s_dirent.d_ino = cipb.dirInfo.ioDrDirID;
6767 s_dirent.d_name = s_name;
6769 return &s_dirent;
6771 else {
6772 cipb.hFileInfo.ioVRefNum = 0;
6773 cipb.hFileInfo.ioNamePtr = s_name; /* location to receive filename returned */
6775 /* return only visible files */
6776 done = false;
6777 while (!done) {
6778 cipb.hFileInfo.ioDirID = dp->dir_id; /* directory ID found by opendir */
6779 cipb.hFileInfo.ioFDirIndex = dp->current_index;
6781 errno = PBGetCatInfo (&cipb, false);
6782 if (errno != noErr) {
6783 errno = ENOENT;
6784 return 0;
6787 /* insist on an visibile entry */
6788 if (cipb.hFileInfo.ioFlAttrib & 0x10) /* directory? */
6789 done = !(cipb.dirInfo.ioDrUsrWds.frFlags & fInvisible);
6790 else
6791 done = !(cipb.hFileInfo.ioFlFndrInfo.fdFlags & fInvisible);
6793 dp->current_index++;
6796 p2cstr (s_name);
6798 s_dirent.d_ino = cipb.dirInfo.ioDrDirID; /* value unimportant: non-zero for valid file */
6799 s_dirent.d_name = s_name;
6801 return &s_dirent;
6805 char *
6806 getwd (char *path)
6808 char MacPathname[MAXPATHLEN+1];
6809 Str255 directoryName;
6810 OSErr errno;
6811 CInfoPBRec cipb;
6813 MacPathname[0] = '\0';
6814 directoryName[0] = '\0';
6815 cipb.dirInfo.ioDrParID = 0;
6816 cipb.dirInfo.ioNamePtr = directoryName; /* empty string = default directory */
6818 do {
6819 cipb.dirInfo.ioVRefNum = 0;
6820 cipb.dirInfo.ioFDirIndex = -1;
6821 cipb.dirInfo.ioDrDirID = cipb.dirInfo.ioDrParID; /* go up to parent each time */
6823 errno = PBGetCatInfo (&cipb, false);
6824 if (errno != noErr) {
6825 errno = ENOENT;
6826 return 0;
6829 p2cstr (directoryName);
6830 strcat (directoryName, ":");
6831 strcat (directoryName, MacPathname); /* attach to front since going up directory tree */
6832 strcpy (MacPathname, directoryName);
6833 } while (cipb.dirInfo.ioDrDirID != fsRtDirID); /* until volume's root directory */
6835 if (Mac2UnixPathname (MacPathname, path, MAXPATHLEN+1) == 0)
6836 return 0;
6837 else
6838 return path;
6841 #endif /* macintosh */