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