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