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