* lisp/thingatpt.el (forward-same-syntax): Handle no ARG case.
[emacs.git] / src / sysdep.c
bloba82f802a785282ec34061dad741d48d4903fdf08
1 /* Interfaces to system-dependent kernel and library entries.
2 Copyright (C) 1985-1988, 1993-1995, 1999-2012
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <ctype.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <setjmp.h>
25 #ifdef HAVE_PWD_H
26 #include <pwd.h>
27 #include <grp.h>
28 #endif /* HAVE_PWD_H */
29 #include <limits.h>
30 #include <unistd.h>
32 #include <allocator.h>
33 #include <careadlinkat.h>
34 #include <ignore-value.h>
36 #include "lisp.h"
37 #include "sysselect.h"
38 #include "blockinput.h"
40 #ifdef __FreeBSD__
41 #include <sys/sysctl.h>
42 #include <sys/user.h>
43 #include <sys/resource.h> */
44 #include <math.h>
45 #endif
47 #ifdef DARWIN_OS
48 #include <sys/sysctl.h>
49 #endif
51 #ifdef WINDOWSNT
52 #define read sys_read
53 #define write sys_write
54 #include <windows.h>
55 #endif /* not WINDOWSNT */
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <errno.h>
61 #ifdef HAVE_SETPGID
62 #if !defined (USG)
63 #undef setpgrp
64 #define setpgrp setpgid
65 #endif
66 #endif
68 /* Get SI_SRPC_DOMAIN, if it is available. */
69 #ifdef HAVE_SYS_SYSTEMINFO_H
70 #include <sys/systeminfo.h>
71 #endif
73 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
74 #include <dos.h>
75 #include "dosfns.h"
76 #include "msdos.h"
77 #include <sys/param.h>
78 #endif
80 #include <sys/file.h>
81 #include <fcntl.h>
83 #include "systty.h"
84 #include "syswait.h"
86 #ifdef HAVE_SYS_UTSNAME_H
87 #include <sys/utsname.h>
88 #include <memory.h>
89 #endif /* HAVE_SYS_UTSNAME_H */
91 #include "keyboard.h"
92 #include "frame.h"
93 #include "window.h"
94 #include "termhooks.h"
95 #include "termchar.h"
96 #include "termopts.h"
97 #include "dispextern.h"
98 #include "process.h"
99 #include "cm.h" /* for reset_sys_modes */
101 #ifdef WINDOWSNT
102 #include <direct.h>
103 /* In process.h which conflicts with the local copy. */
104 #define _P_WAIT 0
105 int _cdecl _spawnlp (int, const char *, const char *, ...);
106 int _cdecl _getpid (void);
107 extern char *getwd (char *);
108 #endif
110 #include "syssignal.h"
111 #include "systime.h"
112 #ifdef HAVE_UTIME_H
113 #include <utime.h>
114 #endif
116 #ifndef HAVE_UTIMES
117 #ifndef HAVE_STRUCT_UTIMBUF
118 /* We want to use utime rather than utimes, but we couldn't find the
119 structure declaration. We'll use the traditional one. */
120 struct utimbuf {
121 long actime;
122 long modtime;
124 #endif
125 #endif
127 static int emacs_get_tty (int, struct emacs_tty *);
128 static int emacs_set_tty (int, struct emacs_tty *, int);
129 #if defined TIOCNOTTY || defined USG5 || defined CYGWIN
130 static void croak (char *) NO_RETURN;
131 #endif
133 /* Declare here, including term.h is problematic on some systems. */
134 extern void tputs (const char *, int, int (*)(int));
136 static const int baud_convert[] =
138 0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
139 1800, 2400, 4800, 9600, 19200, 38400
143 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
145 /* Return the current working directory. Returns NULL on errors.
146 Any other returned value must be freed with free. This is used
147 only when get_current_dir_name is not defined on the system. */
148 char*
149 get_current_dir_name (void)
151 char *buf;
152 char *pwd;
153 struct stat dotstat, pwdstat;
154 /* If PWD is accurate, use it instead of calling getwd. PWD is
155 sometimes a nicer name, and using it may avoid a fatal error if a
156 parent directory is searchable but not readable. */
157 if ((pwd = getenv ("PWD")) != 0
158 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
159 && stat (pwd, &pwdstat) == 0
160 && stat (".", &dotstat) == 0
161 && dotstat.st_ino == pwdstat.st_ino
162 && dotstat.st_dev == pwdstat.st_dev
163 #ifdef MAXPATHLEN
164 && strlen (pwd) < MAXPATHLEN
165 #endif
168 buf = (char *) malloc (strlen (pwd) + 1);
169 if (!buf)
170 return NULL;
171 strcpy (buf, pwd);
173 #ifdef HAVE_GETCWD
174 else
176 size_t buf_size = 1024;
177 buf = (char *) malloc (buf_size);
178 if (!buf)
179 return NULL;
180 for (;;)
182 if (getcwd (buf, buf_size) == buf)
183 break;
184 if (errno != ERANGE)
186 int tmp_errno = errno;
187 free (buf);
188 errno = tmp_errno;
189 return NULL;
191 buf_size *= 2;
192 buf = (char *) realloc (buf, buf_size);
193 if (!buf)
194 return NULL;
197 #else
198 else
200 /* We need MAXPATHLEN here. */
201 buf = (char *) malloc (MAXPATHLEN + 1);
202 if (!buf)
203 return NULL;
204 if (getwd (buf) == NULL)
206 int tmp_errno = errno;
207 free (buf);
208 errno = tmp_errno;
209 return NULL;
212 #endif
213 return buf;
215 #endif
218 /* Discard pending input on all input descriptors. */
220 void
221 discard_tty_input (void)
223 #ifndef WINDOWSNT
224 struct emacs_tty buf;
226 if (noninteractive)
227 return;
229 #ifdef MSDOS /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
230 while (dos_keyread () != -1)
232 #else /* not MSDOS */
234 struct tty_display_info *tty;
235 for (tty = tty_list; tty; tty = tty->next)
237 if (tty->input) /* Is the device suspended? */
239 emacs_get_tty (fileno (tty->input), &buf);
240 emacs_set_tty (fileno (tty->input), &buf, 0);
244 #endif /* not MSDOS */
245 #endif /* not WINDOWSNT */
249 #ifdef SIGTSTP
251 /* Arrange for character C to be read as the next input from
252 the terminal.
253 XXX What if we have multiple ttys?
256 void
257 stuff_char (char c)
259 if (! FRAME_TERMCAP_P (SELECTED_FRAME ()))
260 return;
262 /* Should perhaps error if in batch mode */
263 #ifdef TIOCSTI
264 ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
265 #else /* no TIOCSTI */
266 error ("Cannot stuff terminal input characters in this version of Unix");
267 #endif /* no TIOCSTI */
270 #endif /* SIGTSTP */
272 void
273 init_baud_rate (int fd)
275 int emacs_ospeed;
277 if (noninteractive)
278 emacs_ospeed = 0;
279 else
281 #ifdef DOS_NT
282 emacs_ospeed = 15;
283 #else /* not DOS_NT */
284 struct termios sg;
286 sg.c_cflag = B9600;
287 tcgetattr (fd, &sg);
288 emacs_ospeed = cfgetospeed (&sg);
289 #endif /* not DOS_NT */
292 baud_rate = (emacs_ospeed < sizeof baud_convert / sizeof baud_convert[0]
293 ? baud_convert[emacs_ospeed] : 9600);
294 if (baud_rate == 0)
295 baud_rate = 1200;
300 /* Set nonzero to make following function work under dbx
301 (at least for bsd). */
302 int wait_debugging EXTERNALLY_VISIBLE;
304 #ifndef MSDOS
306 static void
307 wait_for_termination_1 (pid_t pid, int interruptible)
309 while (1)
311 #if (defined (BSD_SYSTEM) || defined (HPUX)) && !defined (__GNU__)
312 /* Note that kill returns -1 even if the process is just a zombie now.
313 But inevitably a SIGCHLD interrupt should be generated
314 and child_sig will do wait3 and make the process go away. */
315 /* There is some indication that there is a bug involved with
316 termination of subprocesses, perhaps involving a kernel bug too,
317 but no idea what it is. Just as a hunch we signal SIGCHLD to see
318 if that causes the problem to go away or get worse. */
319 sigsetmask (sigmask (SIGCHLD));
320 if (0 > kill (pid, 0))
322 sigsetmask (SIGEMPTYMASK);
323 kill (getpid (), SIGCHLD);
324 break;
326 if (wait_debugging)
327 sleep (1);
328 else
329 sigpause (SIGEMPTYMASK);
330 #else /* not BSD_SYSTEM, and not HPUX version >= 6 */
331 #ifdef WINDOWSNT
332 wait (0);
333 break;
334 #else /* not WINDOWSNT */
335 sigblock (sigmask (SIGCHLD));
336 errno = 0;
337 if (kill (pid, 0) == -1 && errno == ESRCH)
339 sigunblock (sigmask (SIGCHLD));
340 break;
343 sigsuspend (&empty_mask);
344 #endif /* not WINDOWSNT */
345 #endif /* not BSD_SYSTEM, and not HPUX version >= 6 */
346 if (interruptible)
347 QUIT;
351 /* Wait for subprocess with process id `pid' to terminate and
352 make sure it will get eliminated (not remain forever as a zombie) */
354 void
355 wait_for_termination (pid_t pid)
357 wait_for_termination_1 (pid, 0);
360 /* Like the above, but allow keyboard interruption. */
361 void
362 interruptible_wait_for_termination (pid_t pid)
364 wait_for_termination_1 (pid, 1);
368 * flush any pending output
369 * (may flush input as well; it does not matter the way we use it)
372 void
373 flush_pending_output (int channel)
375 /* FIXME: maybe this function should be removed */
378 /* Set up the terminal at the other end of a pseudo-terminal that
379 we will be controlling an inferior through.
380 It should not echo or do line-editing, since that is done
381 in Emacs. No padding needed for insertion into an Emacs buffer. */
383 void
384 child_setup_tty (int out)
386 #ifndef WINDOWSNT
387 struct emacs_tty s;
389 emacs_get_tty (out, &s);
390 s.main.c_oflag |= OPOST; /* Enable output postprocessing */
391 s.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL on output */
392 #ifdef NLDLY
393 /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
394 Some versions of GNU Hurd do not have FFDLY? */
395 #ifdef FFDLY
396 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
397 /* No output delays */
398 #else
399 s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
400 /* No output delays */
401 #endif
402 #endif
403 s.main.c_lflag &= ~ECHO; /* Disable echo */
404 s.main.c_lflag |= ISIG; /* Enable signals */
405 #ifdef IUCLC
406 s.main.c_iflag &= ~IUCLC; /* Disable downcasing on input. */
407 #endif
408 #ifdef ISTRIP
409 s.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
410 #endif
411 #ifdef OLCUC
412 s.main.c_oflag &= ~OLCUC; /* Disable upcasing on output. */
413 #endif
414 s.main.c_oflag &= ~TAB3; /* Disable tab expansion */
415 s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
416 s.main.c_cc[VERASE] = CDISABLE; /* disable erase processing */
417 s.main.c_cc[VKILL] = CDISABLE; /* disable kill processing */
419 #ifdef HPUX
420 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
421 #endif /* HPUX */
423 #ifdef SIGNALS_VIA_CHARACTERS
424 /* the QUIT and INTR character are used in process_send_signal
425 so set them here to something useful. */
426 if (s.main.c_cc[VQUIT] == CDISABLE)
427 s.main.c_cc[VQUIT] = '\\'&037; /* Control-\ */
428 if (s.main.c_cc[VINTR] == CDISABLE)
429 s.main.c_cc[VINTR] = 'C'&037; /* Control-C */
430 #endif /* not SIGNALS_VIA_CHARACTERS */
432 #ifdef AIX
433 /* Also, PTY overloads NUL and BREAK.
434 don't ignore break, but don't signal either, so it looks like NUL. */
435 s.main.c_iflag &= ~IGNBRK;
436 s.main.c_iflag &= ~BRKINT;
437 /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
438 unconditionally. Then a SIGNALS_VIA_CHARACTERS conditional
439 would force it to 0377. That looks like duplicated code. */
440 s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
441 #endif /* AIX */
443 /* We originally enabled ICANON (and set VEOF to 04), and then had
444 process.c send additional EOF chars to flush the output when faced
445 with long lines, but this leads to weird effects when the
446 subprocess has disabled ICANON and ends up seeing those spurious
447 extra EOFs. So we don't send EOFs any more in
448 process.c:send_process. First we tried to disable ICANON by
449 default, so if a subsprocess sets up ICANON, it's his problem (or
450 the Elisp package that talks to it) to deal with lines that are
451 too long. But this disables some features, such as the ability
452 to send EOF signals. So we re-enabled ICANON but there is no
453 more "send eof to flush" going on (which is wrong and unportable
454 in itself). The correct way to handle too much output is to
455 buffer what could not be written and then write it again when
456 select returns ok for writing. This has it own set of
457 problems. Write is now asynchronous, is that a problem? How much
458 do we buffer, and what do we do when that limit is reached? */
460 s.main.c_lflag |= ICANON; /* Enable line editing and eof processing */
461 s.main.c_cc[VEOF] = 'D'&037; /* Control-D */
462 #if 0 /* These settings only apply to non-ICANON mode. */
463 s.main.c_cc[VMIN] = 1;
464 s.main.c_cc[VTIME] = 0;
465 #endif
467 emacs_set_tty (out, &s, 0);
468 #endif /* not WINDOWSNT */
470 #endif /* not MSDOS */
473 /* Record a signal code and the handler for it. */
474 struct save_signal
476 int code;
477 void (*handler) (int);
480 static void save_signal_handlers (struct save_signal *);
481 static void restore_signal_handlers (struct save_signal *);
483 /* Suspend the Emacs process; give terminal to its superior. */
485 void
486 sys_suspend (void)
488 #if defined (SIGTSTP) && !defined (MSDOS)
491 int pgrp = EMACS_GETPGRP (0);
492 EMACS_KILLPG (pgrp, SIGTSTP);
495 #else /* No SIGTSTP */
496 /* On a system where suspending is not implemented,
497 instead fork a subshell and let it talk directly to the terminal
498 while we wait. */
499 sys_subshell ();
501 #endif /* no SIGTSTP */
504 /* Fork a subshell. */
506 void
507 sys_subshell (void)
509 #ifdef DOS_NT /* Demacs 1.1.2 91/10/20 Manabu Higashida */
510 int st;
511 char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS. */
512 #endif
513 int pid;
514 struct save_signal saved_handlers[5];
515 Lisp_Object dir;
516 unsigned char *volatile str_volatile = 0;
517 unsigned char *str;
518 int len;
520 saved_handlers[0].code = SIGINT;
521 saved_handlers[1].code = SIGQUIT;
522 saved_handlers[2].code = SIGTERM;
523 #ifdef SIGIO
524 saved_handlers[3].code = SIGIO;
525 saved_handlers[4].code = 0;
526 #else
527 saved_handlers[3].code = 0;
528 #endif
530 /* Mentioning current_buffer->buffer would mean including buffer.h,
531 which somehow wedges the hp compiler. So instead... */
533 dir = intern ("default-directory");
534 if (NILP (Fboundp (dir)))
535 goto xyzzy;
536 dir = Fsymbol_value (dir);
537 if (!STRINGP (dir))
538 goto xyzzy;
540 dir = expand_and_dir_to_file (Funhandled_file_name_directory (dir), Qnil);
541 str_volatile = str = (unsigned char *) alloca (SCHARS (dir) + 2);
542 len = SCHARS (dir);
543 memcpy (str, SDATA (dir), len);
544 if (str[len - 1] != '/') str[len++] = '/';
545 str[len] = 0;
546 xyzzy:
548 #ifdef DOS_NT
549 pid = 0;
550 save_signal_handlers (saved_handlers);
551 synch_process_alive = 1;
552 #else
553 pid = vfork ();
554 if (pid == -1)
555 error ("Can't spawn subshell");
556 #endif
558 if (pid == 0)
560 const char *sh = 0;
562 #ifdef DOS_NT /* MW, Aug 1993 */
563 getwd (oldwd);
564 if (sh == 0)
565 sh = (char *) egetenv ("SUSPEND"); /* KFS, 1994-12-14 */
566 #endif
567 if (sh == 0)
568 sh = (char *) egetenv ("SHELL");
569 if (sh == 0)
570 sh = "sh";
572 /* Use our buffer's default directory for the subshell. */
573 str = str_volatile;
574 if (str && chdir ((char *) str) != 0)
576 #ifndef DOS_NT
577 ignore_value (write (1, "Can't chdir\n", 12));
578 _exit (1);
579 #endif
582 close_process_descs (); /* Close Emacs's pipes/ptys */
584 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
586 char *epwd = getenv ("PWD");
587 char old_pwd[MAXPATHLEN+1+4];
589 /* If PWD is set, pass it with corrected value. */
590 if (epwd)
592 strcpy (old_pwd, epwd);
593 if (str[len - 1] == '/')
594 str[len - 1] = '\0';
595 setenv ("PWD", str, 1);
597 st = system (sh);
598 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
599 if (epwd)
600 putenv (old_pwd); /* restore previous value */
602 #else /* not MSDOS */
603 #ifdef WINDOWSNT
604 /* Waits for process completion */
605 pid = _spawnlp (_P_WAIT, sh, sh, NULL);
606 chdir (oldwd); /* FIXME: Do the right thing on chdir failure. */
607 if (pid == -1)
608 write (1, "Can't execute subshell", 22);
609 #else /* not WINDOWSNT */
610 execlp (sh, sh, (char *) 0);
611 ignore_value (write (1, "Can't execute subshell", 22));
612 _exit (1);
613 #endif /* not WINDOWSNT */
614 #endif /* not MSDOS */
617 /* Do this now if we did not do it before. */
618 #ifndef MSDOS
619 save_signal_handlers (saved_handlers);
620 synch_process_alive = 1;
621 #endif
623 #ifndef DOS_NT
624 wait_for_termination (pid);
625 #endif
626 restore_signal_handlers (saved_handlers);
627 synch_process_alive = 0;
630 static void
631 save_signal_handlers (struct save_signal *saved_handlers)
633 while (saved_handlers->code)
635 saved_handlers->handler
636 = (void (*) (int)) signal (saved_handlers->code, SIG_IGN);
637 saved_handlers++;
641 static void
642 restore_signal_handlers (struct save_signal *saved_handlers)
644 while (saved_handlers->code)
646 signal (saved_handlers->code, saved_handlers->handler);
647 saved_handlers++;
651 #ifndef SIGIO
652 /* If SIGIO is broken, don't do anything. */
653 void
654 init_sigio (int fd)
658 static void
659 reset_sigio (int fd)
663 void
664 request_sigio (void)
668 void
669 unrequest_sigio (void)
673 #else
674 #ifdef F_SETFL
676 static int old_fcntl_flags[MAXDESC];
678 void
679 init_sigio (int fd)
681 #ifdef FASYNC
682 old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
683 fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
684 #endif
685 interrupts_deferred = 0;
688 static void
689 reset_sigio (int fd)
691 #ifdef FASYNC
692 fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
693 #endif
696 #ifdef FASYNC /* F_SETFL does not imply existence of FASYNC */
697 /* XXX Uhm, FASYNC is not used anymore here. */
698 /* XXX Yeah, but you need it for SIGIO, don't you? */
700 void
701 request_sigio (void)
703 if (noninteractive)
704 return;
706 #ifdef SIGWINCH
707 sigunblock (sigmask (SIGWINCH));
708 #endif
709 sigunblock (sigmask (SIGIO));
711 interrupts_deferred = 0;
714 void
715 unrequest_sigio (void)
717 if (noninteractive)
718 return;
720 #if 0 /* XXX What's wrong with blocking SIGIO under X? */
721 if (x_display_list)
722 return;
723 #endif
725 #ifdef SIGWINCH
726 sigblock (sigmask (SIGWINCH));
727 #endif
728 sigblock (sigmask (SIGIO));
729 interrupts_deferred = 1;
732 #else /* no FASYNC */
733 #ifndef MSDOS
735 void
736 request_sigio (void)
738 if (noninteractive || read_socket_hook)
739 return;
741 croak ("request_sigio");
744 void
745 unrequest_sigio (void)
747 if (noninteractive || read_socket_hook)
748 return;
750 croak ("unrequest_sigio");
753 #endif /* MSDOS */
754 #endif /* FASYNC */
755 #endif /* F_SETFL */
756 #endif /* SIGIO */
759 /* Getting and setting emacs_tty structures. */
761 /* Set *TC to the parameters associated with the terminal FD.
762 Return zero if all's well, or -1 if we ran into an error we
763 couldn't deal with. */
765 emacs_get_tty (int fd, struct emacs_tty *settings)
767 /* Retrieve the primary parameters - baud rate, character size, etcetera. */
768 #ifndef DOS_NT
769 /* We have those nifty POSIX tcmumbleattr functions. */
770 memset (&settings->main, 0, sizeof (settings->main));
771 if (tcgetattr (fd, &settings->main) < 0)
772 return -1;
773 #endif
775 /* We have survived the tempest. */
776 return 0;
780 /* Set the parameters of the tty on FD according to the contents of
781 *SETTINGS. If FLUSHP is non-zero, we discard input.
782 Return 0 if all went well, and -1 if anything failed. */
785 emacs_set_tty (int fd, struct emacs_tty *settings, int flushp)
787 /* Set the primary parameters - baud rate, character size, etcetera. */
788 #ifndef DOS_NT
789 int i;
790 /* We have those nifty POSIX tcmumbleattr functions.
791 William J. Smith <wjs@wiis.wang.com> writes:
792 "POSIX 1003.1 defines tcsetattr to return success if it was
793 able to perform any of the requested actions, even if some
794 of the requested actions could not be performed.
795 We must read settings back to ensure tty setup properly.
796 AIX requires this to keep tty from hanging occasionally." */
797 /* This make sure that we don't loop indefinitely in here. */
798 for (i = 0 ; i < 10 ; i++)
799 if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
801 if (errno == EINTR)
802 continue;
803 else
804 return -1;
806 else
808 struct termios new;
810 memset (&new, 0, sizeof (new));
811 /* Get the current settings, and see if they're what we asked for. */
812 tcgetattr (fd, &new);
813 /* We cannot use memcmp on the whole structure here because under
814 * aix386 the termios structure has some reserved field that may
815 * not be filled in.
817 if ( new.c_iflag == settings->main.c_iflag
818 && new.c_oflag == settings->main.c_oflag
819 && new.c_cflag == settings->main.c_cflag
820 && new.c_lflag == settings->main.c_lflag
821 && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
822 break;
823 else
824 continue;
826 #endif
828 /* We have survived the tempest. */
829 return 0;
834 #ifdef F_SETOWN
835 static int old_fcntl_owner[MAXDESC];
836 #endif /* F_SETOWN */
838 /* This may also be defined in stdio,
839 but if so, this does no harm,
840 and using the same name avoids wasting the other one's space. */
842 #if defined (USG)
843 unsigned char _sobuf[BUFSIZ+8];
844 #else
845 char _sobuf[BUFSIZ];
846 #endif
848 /* Initialize the terminal mode on all tty devices that are currently
849 open. */
851 void
852 init_all_sys_modes (void)
854 struct tty_display_info *tty;
855 for (tty = tty_list; tty; tty = tty->next)
856 init_sys_modes (tty);
859 /* Initialize the terminal mode on the given tty device. */
861 void
862 init_sys_modes (struct tty_display_info *tty_out)
864 struct emacs_tty tty;
865 Lisp_Object terminal;
867 Vtty_erase_char = Qnil;
869 if (noninteractive)
870 return;
872 if (!tty_out->output)
873 return; /* The tty is suspended. */
875 if (! tty_out->old_tty)
876 tty_out->old_tty = (struct emacs_tty *) xmalloc (sizeof (struct emacs_tty));
878 emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
880 tty = *tty_out->old_tty;
882 #if !defined (DOS_NT)
883 XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
885 tty.main.c_iflag |= (IGNBRK); /* Ignore break condition */
886 tty.main.c_iflag &= ~ICRNL; /* Disable map of CR to NL on input */
887 #ifdef INLCR /* I'm just being cautious,
888 since I can't check how widespread INLCR is--rms. */
889 tty.main.c_iflag &= ~INLCR; /* Disable map of NL to CR on input */
890 #endif
891 #ifdef ISTRIP
892 tty.main.c_iflag &= ~ISTRIP; /* don't strip 8th bit on input */
893 #endif
894 tty.main.c_lflag &= ~ECHO; /* Disable echo */
895 tty.main.c_lflag &= ~ICANON; /* Disable erase/kill processing */
896 #ifdef IEXTEN
897 tty.main.c_lflag &= ~IEXTEN; /* Disable other editing characters. */
898 #endif
899 tty.main.c_lflag |= ISIG; /* Enable signals */
900 if (tty_out->flow_control)
902 tty.main.c_iflag |= IXON; /* Enable start/stop output control */
903 #ifdef IXANY
904 tty.main.c_iflag &= ~IXANY;
905 #endif /* IXANY */
907 else
908 tty.main.c_iflag &= ~IXON; /* Disable start/stop output control */
909 tty.main.c_oflag &= ~ONLCR; /* Disable map of NL to CR-NL
910 on output */
911 tty.main.c_oflag &= ~TAB3; /* Disable tab expansion */
912 #ifdef CS8
913 if (tty_out->meta_key)
915 tty.main.c_cflag |= CS8; /* allow 8th bit on input */
916 tty.main.c_cflag &= ~PARENB;/* Don't check parity */
918 #endif
920 XSETTERMINAL(terminal, tty_out->terminal);
921 if (!NILP (Fcontrolling_tty_p (terminal)))
923 tty.main.c_cc[VINTR] = quit_char; /* C-g (usually) gives SIGINT */
924 /* Set up C-g for both SIGQUIT and SIGINT.
925 We don't know which we will get, but we handle both alike
926 so which one it really gives us does not matter. */
927 tty.main.c_cc[VQUIT] = quit_char;
929 else
931 /* We normally don't get interrupt or quit signals from tty
932 devices other than our controlling terminal; therefore,
933 we must handle C-g as normal input. Unfortunately, this
934 means that the interrupt and quit feature must be
935 disabled on secondary ttys, or we would not even see the
936 keypress.
938 Note that even though emacsclient could have special code
939 to pass SIGINT to Emacs, we should _not_ enable
940 interrupt/quit keys for emacsclient frames. This means
941 that we can't break out of loops in C code from a
942 secondary tty frame, but we can always decide what
943 display the C-g came from, which is more important from a
944 usability point of view. (Consider the case when two
945 people work together using the same Emacs instance.) */
946 tty.main.c_cc[VINTR] = CDISABLE;
947 tty.main.c_cc[VQUIT] = CDISABLE;
949 tty.main.c_cc[VMIN] = 1; /* Input should wait for at least 1 char */
950 tty.main.c_cc[VTIME] = 0; /* no matter how long that takes. */
951 #ifdef VSWTCH
952 tty.main.c_cc[VSWTCH] = CDISABLE; /* Turn off shell layering use
953 of C-z */
954 #endif /* VSWTCH */
956 #ifdef VSUSP
957 tty.main.c_cc[VSUSP] = CDISABLE; /* Turn off handling of C-z. */
958 #endif /* VSUSP */
959 #ifdef V_DSUSP
960 tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y. */
961 #endif /* V_DSUSP */
962 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
963 tty.main.c_cc[VDSUSP] = CDISABLE;
964 #endif /* VDSUSP */
965 #ifdef VLNEXT
966 tty.main.c_cc[VLNEXT] = CDISABLE;
967 #endif /* VLNEXT */
968 #ifdef VREPRINT
969 tty.main.c_cc[VREPRINT] = CDISABLE;
970 #endif /* VREPRINT */
971 #ifdef VWERASE
972 tty.main.c_cc[VWERASE] = CDISABLE;
973 #endif /* VWERASE */
974 #ifdef VDISCARD
975 tty.main.c_cc[VDISCARD] = CDISABLE;
976 #endif /* VDISCARD */
978 if (tty_out->flow_control)
980 #ifdef VSTART
981 tty.main.c_cc[VSTART] = '\021';
982 #endif /* VSTART */
983 #ifdef VSTOP
984 tty.main.c_cc[VSTOP] = '\023';
985 #endif /* VSTOP */
987 else
989 #ifdef VSTART
990 tty.main.c_cc[VSTART] = CDISABLE;
991 #endif /* VSTART */
992 #ifdef VSTOP
993 tty.main.c_cc[VSTOP] = CDISABLE;
994 #endif /* VSTOP */
997 #ifdef AIX
998 tty.main.c_cc[VSTRT] = CDISABLE;
999 tty.main.c_cc[VSTOP] = CDISABLE;
1000 tty.main.c_cc[VSUSP] = CDISABLE;
1001 tty.main.c_cc[VDSUSP] = CDISABLE;
1002 if (tty_out->flow_control)
1004 #ifdef VSTART
1005 tty.main.c_cc[VSTART] = '\021';
1006 #endif /* VSTART */
1007 #ifdef VSTOP
1008 tty.main.c_cc[VSTOP] = '\023';
1009 #endif /* VSTOP */
1011 /* Also, PTY overloads NUL and BREAK.
1012 don't ignore break, but don't signal either, so it looks like NUL.
1013 This really serves a purpose only if running in an XTERM window
1014 or via TELNET or the like, but does no harm elsewhere. */
1015 tty.main.c_iflag &= ~IGNBRK;
1016 tty.main.c_iflag &= ~BRKINT;
1017 #endif
1018 #endif /* not DOS_NT */
1020 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
1021 if (!tty_out->term_initted)
1022 internal_terminal_init ();
1023 dos_ttraw (tty_out);
1024 #endif
1026 emacs_set_tty (fileno (tty_out->input), &tty, 0);
1028 /* This code added to insure that, if flow-control is not to be used,
1029 we have an unlocked terminal at the start. */
1031 #ifdef TCXONC
1032 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TCXONC, 1);
1033 #endif
1034 #ifdef TIOCSTART
1035 if (!tty_out->flow_control) ioctl (fileno (tty_out->input), TIOCSTART, 0);
1036 #endif
1038 #if !defined (DOS_NT)
1039 #ifdef TCOON
1040 if (!tty_out->flow_control) tcflow (fileno (tty_out->input), TCOON);
1041 #endif
1042 #endif
1044 #ifdef F_SETFL
1045 #ifdef F_GETOWN /* F_SETFL does not imply existence of F_GETOWN */
1046 if (interrupt_input)
1048 old_fcntl_owner[fileno (tty_out->input)] =
1049 fcntl (fileno (tty_out->input), F_GETOWN, 0);
1050 fcntl (fileno (tty_out->input), F_SETOWN, getpid ());
1051 init_sigio (fileno (tty_out->input));
1052 #ifdef HAVE_GPM
1053 if (gpm_tty == tty_out)
1055 /* Arrange for mouse events to give us SIGIO signals. */
1056 fcntl (gpm_fd, F_SETOWN, getpid ());
1057 fcntl (gpm_fd, F_SETFL, fcntl (gpm_fd, F_GETFL, 0) | O_NONBLOCK);
1058 init_sigio (gpm_fd);
1060 #endif /* HAVE_GPM */
1062 #endif /* F_GETOWN */
1063 #endif /* F_SETFL */
1065 #ifdef _IOFBF
1066 /* This symbol is defined on recent USG systems.
1067 Someone says without this call USG won't really buffer the file
1068 even with a call to setbuf. */
1069 setvbuf (tty_out->output, (char *) _sobuf, _IOFBF, sizeof _sobuf);
1070 #else
1071 setbuf (tty_out->output, (char *) _sobuf);
1072 #endif
1074 if (tty_out->terminal->set_terminal_modes_hook)
1075 tty_out->terminal->set_terminal_modes_hook (tty_out->terminal);
1077 if (!tty_out->term_initted)
1079 Lisp_Object tail, frame;
1080 FOR_EACH_FRAME (tail, frame)
1082 /* XXX This needs to be revised. */
1083 if (FRAME_TERMCAP_P (XFRAME (frame))
1084 && FRAME_TTY (XFRAME (frame)) == tty_out)
1085 init_frame_faces (XFRAME (frame));
1089 if (tty_out->term_initted && no_redraw_on_reenter)
1091 /* We used to call "direct_output_forward_char(0)" here,
1092 but it's not clear why, since it may not do anything anyway. */
1094 else
1096 Lisp_Object tail, frame;
1097 frame_garbaged = 1;
1098 FOR_EACH_FRAME (tail, frame)
1100 if ((FRAME_TERMCAP_P (XFRAME (frame))
1101 || FRAME_MSDOS_P (XFRAME (frame)))
1102 && FRAME_TTY (XFRAME (frame)) == tty_out)
1103 FRAME_GARBAGED_P (XFRAME (frame)) = 1;
1107 tty_out->term_initted = 1;
1110 /* Return nonzero if safe to use tabs in output.
1111 At the time this is called, init_sys_modes has not been done yet. */
1114 tabs_safe_p (int fd)
1116 struct emacs_tty etty;
1118 emacs_get_tty (fd, &etty);
1119 #ifndef DOS_NT
1120 #ifdef TABDLY
1121 return ((etty.main.c_oflag & TABDLY) != TAB3);
1122 #else /* not TABDLY */
1123 return 1;
1124 #endif /* not TABDLY */
1125 #else /* DOS_NT */
1126 return 0;
1127 #endif /* DOS_NT */
1130 /* Get terminal size from system.
1131 Store number of lines into *HEIGHTP and width into *WIDTHP.
1132 We store 0 if there's no valid information. */
1134 void
1135 get_tty_size (int fd, int *widthp, int *heightp)
1137 #if defined TIOCGWINSZ
1139 /* BSD-style. */
1140 struct winsize size;
1142 if (ioctl (fd, TIOCGWINSZ, &size) == -1)
1143 *widthp = *heightp = 0;
1144 else
1146 *widthp = size.ws_col;
1147 *heightp = size.ws_row;
1150 #elif defined TIOCGSIZE
1152 /* SunOS - style. */
1153 struct ttysize size;
1155 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1156 *widthp = *heightp = 0;
1157 else
1159 *widthp = size.ts_cols;
1160 *heightp = size.ts_lines;
1163 #elif defined WINDOWSNT
1165 CONSOLE_SCREEN_BUFFER_INFO info;
1166 if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info))
1168 *widthp = info.srWindow.Right - info.srWindow.Left + 1;
1169 *heightp = info.srWindow.Bottom - info.srWindow.Top + 1;
1171 else
1172 *widthp = *heightp = 0;
1174 #elif defined MSDOS
1176 *widthp = ScreenCols ();
1177 *heightp = ScreenRows ();
1179 #else /* system doesn't know size */
1181 *widthp = 0;
1182 *heightp = 0;
1184 #endif
1187 /* Set the logical window size associated with descriptor FD
1188 to HEIGHT and WIDTH. This is used mainly with ptys. */
1191 set_window_size (int fd, int height, int width)
1193 #ifdef TIOCSWINSZ
1195 /* BSD-style. */
1196 struct winsize size;
1197 size.ws_row = height;
1198 size.ws_col = width;
1200 if (ioctl (fd, TIOCSWINSZ, &size) == -1)
1201 return 0; /* error */
1202 else
1203 return 1;
1205 #else
1206 #ifdef TIOCSSIZE
1208 /* SunOS - style. */
1209 struct ttysize size;
1210 size.ts_lines = height;
1211 size.ts_cols = width;
1213 if (ioctl (fd, TIOCGSIZE, &size) == -1)
1214 return 0;
1215 else
1216 return 1;
1217 #else
1218 return -1;
1219 #endif /* not SunOS-style */
1220 #endif /* not BSD-style */
1225 /* Prepare all terminal devices for exiting Emacs. */
1227 void
1228 reset_all_sys_modes (void)
1230 struct tty_display_info *tty;
1231 for (tty = tty_list; tty; tty = tty->next)
1232 reset_sys_modes (tty);
1235 /* Prepare the terminal for closing it; move the cursor to the
1236 bottom of the frame, turn off interrupt-driven I/O, etc. */
1238 void
1239 reset_sys_modes (struct tty_display_info *tty_out)
1241 if (noninteractive)
1243 fflush (stdout);
1244 return;
1246 if (!tty_out->term_initted)
1247 return;
1249 if (!tty_out->output)
1250 return; /* The tty is suspended. */
1252 /* Go to and clear the last line of the terminal. */
1254 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1256 /* Code adapted from tty_clear_end_of_line. */
1257 if (tty_out->TS_clr_line)
1259 emacs_tputs (tty_out, tty_out->TS_clr_line, 1, cmputc);
1261 else
1262 { /* have to do it the hard way */
1263 int i;
1264 tty_turn_off_insert (tty_out);
1266 for (i = curX (tty_out); i < FrameCols (tty_out) - 1; i++)
1268 fputc (' ', tty_out->output);
1272 cmgoto (tty_out, FrameRows (tty_out) - 1, 0);
1273 fflush (tty_out->output);
1275 if (tty_out->terminal->reset_terminal_modes_hook)
1276 tty_out->terminal->reset_terminal_modes_hook (tty_out->terminal);
1278 #ifdef BSD_SYSTEM
1279 /* Avoid possible loss of output when changing terminal modes. */
1280 fsync (fileno (tty_out->output));
1281 #endif
1283 #ifdef F_SETFL
1284 #ifdef F_SETOWN /* F_SETFL does not imply existence of F_SETOWN */
1285 if (interrupt_input)
1287 reset_sigio (fileno (tty_out->input));
1288 fcntl (fileno (tty_out->input), F_SETOWN,
1289 old_fcntl_owner[fileno (tty_out->input)]);
1291 #endif /* F_SETOWN */
1292 #ifdef O_NDELAY
1293 fcntl (fileno (tty_out->input), F_SETFL,
1294 fcntl (fileno (tty_out->input), F_GETFL, 0) & ~O_NDELAY);
1295 #endif
1296 #endif /* F_SETFL */
1298 if (tty_out->old_tty)
1299 while (emacs_set_tty (fileno (tty_out->input),
1300 tty_out->old_tty, 0) < 0 && errno == EINTR)
1303 #ifdef MSDOS /* Demacs 1.1.2 91/10/20 Manabu Higashida */
1304 dos_ttcooked ();
1305 #endif
1309 #ifdef HAVE_PTYS
1311 /* Set up the proper status flags for use of a pty. */
1313 void
1314 setup_pty (int fd)
1316 /* I'm told that TOICREMOTE does not mean control chars
1317 "can't be sent" but rather that they don't have
1318 input-editing or signaling effects.
1319 That should be good, because we have other ways
1320 to do those things in Emacs.
1321 However, telnet mode seems not to work on 4.2.
1322 So TIOCREMOTE is turned off now. */
1324 /* Under hp-ux, if TIOCREMOTE is turned on, some calls
1325 will hang. In particular, the "timeout" feature (which
1326 causes a read to return if there is no data available)
1327 does this. Also it is known that telnet mode will hang
1328 in such a way that Emacs must be stopped (perhaps this
1329 is the same problem).
1331 If TIOCREMOTE is turned off, then there is a bug in
1332 hp-ux which sometimes loses data. Apparently the
1333 code which blocks the master process when the internal
1334 buffer fills up does not work. Other than this,
1335 though, everything else seems to work fine.
1337 Since the latter lossage is more benign, we may as well
1338 lose that way. -- cph */
1339 #ifdef FIONBIO
1340 #if defined (UNIX98_PTYS)
1342 int on = 1;
1343 ioctl (fd, FIONBIO, &on);
1345 #endif
1346 #endif
1348 #endif /* HAVE_PTYS */
1350 #ifdef HAVE_SOCKETS
1351 #include <sys/socket.h>
1352 #include <netdb.h>
1353 #endif /* HAVE_SOCKETS */
1355 #ifdef TRY_AGAIN
1356 #ifndef HAVE_H_ERRNO
1357 extern int h_errno;
1358 #endif
1359 #endif /* TRY_AGAIN */
1361 void
1362 init_system_name (void)
1364 #ifndef HAVE_GETHOSTNAME
1365 struct utsname uts;
1366 uname (&uts);
1367 Vsystem_name = build_string (uts.nodename);
1368 #else /* HAVE_GETHOSTNAME */
1369 unsigned int hostname_size = 256;
1370 char *hostname = (char *) alloca (hostname_size);
1372 /* Try to get the host name; if the buffer is too short, try
1373 again. Apparently, the only indication gethostname gives of
1374 whether the buffer was large enough is the presence or absence
1375 of a '\0' in the string. Eech. */
1376 for (;;)
1378 gethostname (hostname, hostname_size - 1);
1379 hostname[hostname_size - 1] = '\0';
1381 /* Was the buffer large enough for the '\0'? */
1382 if (strlen (hostname) < hostname_size - 1)
1383 break;
1385 hostname_size <<= 1;
1386 hostname = (char *) alloca (hostname_size);
1388 #ifdef HAVE_SOCKETS
1389 /* Turn the hostname into the official, fully-qualified hostname.
1390 Don't do this if we're going to dump; this can confuse system
1391 libraries on some machines and make the dumped emacs core dump. */
1392 #ifndef CANNOT_DUMP
1393 if (initialized)
1394 #endif /* not CANNOT_DUMP */
1395 if (! strchr (hostname, '.'))
1397 int count;
1398 #ifdef HAVE_GETADDRINFO
1399 struct addrinfo *res;
1400 struct addrinfo hints;
1401 int ret;
1403 memset (&hints, 0, sizeof (hints));
1404 hints.ai_socktype = SOCK_STREAM;
1405 hints.ai_flags = AI_CANONNAME;
1407 for (count = 0;; count++)
1409 if ((ret = getaddrinfo (hostname, NULL, &hints, &res)) == 0
1410 || ret != EAI_AGAIN)
1411 break;
1413 if (count >= 5)
1414 break;
1415 Fsleep_for (make_number (1), Qnil);
1418 if (ret == 0)
1420 struct addrinfo *it = res;
1421 while (it)
1423 char *fqdn = it->ai_canonname;
1424 if (fqdn && strchr (fqdn, '.')
1425 && strcmp (fqdn, "localhost.localdomain") != 0)
1426 break;
1427 it = it->ai_next;
1429 if (it)
1431 hostname = alloca (strlen (it->ai_canonname) + 1);
1432 strcpy (hostname, it->ai_canonname);
1434 freeaddrinfo (res);
1436 #else /* !HAVE_GETADDRINFO */
1437 struct hostent *hp;
1438 for (count = 0;; count++)
1441 #ifdef TRY_AGAIN
1442 h_errno = 0;
1443 #endif
1444 hp = gethostbyname (hostname);
1445 #ifdef TRY_AGAIN
1446 if (! (hp == 0 && h_errno == TRY_AGAIN))
1447 #endif
1449 break;
1451 if (count >= 5)
1452 break;
1453 Fsleep_for (make_number (1), Qnil);
1456 if (hp)
1458 char *fqdn = (char *) hp->h_name;
1460 if (!strchr (fqdn, '.'))
1462 /* We still don't have a fully qualified domain name.
1463 Try to find one in the list of alternate names */
1464 char **alias = hp->h_aliases;
1465 while (*alias
1466 && (!strchr (*alias, '.')
1467 || !strcmp (*alias, "localhost.localdomain")))
1468 alias++;
1469 if (*alias)
1470 fqdn = *alias;
1472 hostname = fqdn;
1474 #endif /* !HAVE_GETADDRINFO */
1476 #endif /* HAVE_SOCKETS */
1477 Vsystem_name = build_string (hostname);
1478 #endif /* HAVE_GETHOSTNAME */
1480 unsigned char *p;
1481 for (p = SDATA (Vsystem_name); *p; p++)
1482 if (*p == ' ' || *p == '\t')
1483 *p = '-';
1487 /* POSIX signals support - DJB */
1488 /* Anyone with POSIX signals should have ANSI C declarations */
1490 sigset_t empty_mask;
1492 #ifndef WINDOWSNT
1494 signal_handler_t
1495 sys_signal (int signal_number, signal_handler_t action)
1497 struct sigaction new_action, old_action;
1498 sigemptyset (&new_action.sa_mask);
1499 new_action.sa_handler = action;
1500 new_action.sa_flags = 0;
1501 #if defined (SA_RESTART)
1502 /* Emacs mostly works better with restartable system services. If this
1503 flag exists, we probably want to turn it on here.
1504 However, on some systems this resets the timeout of `select'
1505 which means that `select' never finishes if it keeps getting signals.
1506 BROKEN_SA_RESTART is defined on those systems. */
1507 /* It's not clear why the comment above says "mostly works better". --Stef
1508 When SYNC_INPUT is set, we don't want SA_RESTART because we need to poll
1509 for pending input so we need long-running syscalls to be interrupted
1510 after a signal that sets the interrupt_input_pending flag. */
1511 /* Non-interactive keyboard input goes through stdio, where we always
1512 want restartable system calls. */
1513 # if defined (BROKEN_SA_RESTART) || defined (SYNC_INPUT)
1514 if (noninteractive)
1515 # endif
1516 new_action.sa_flags = SA_RESTART;
1517 #endif
1518 sigaction (signal_number, &new_action, &old_action);
1519 return (old_action.sa_handler);
1522 #endif /* WINDOWSNT */
1524 #ifndef __GNUC__
1525 /* If we're compiling with GCC, we don't need this function, since it
1526 can be written as a macro. */
1527 sigset_t
1528 sys_sigmask (int sig)
1530 sigset_t mask;
1531 sigemptyset (&mask);
1532 sigaddset (&mask, sig);
1533 return mask;
1535 #endif
1537 /* I'd like to have these guys return pointers to the mask storage in here,
1538 but there'd be trouble if the code was saving multiple masks. I'll be
1539 safe and pass the structure. It normally won't be more than 2 bytes
1540 anyhow. - DJB */
1542 sigset_t
1543 sys_sigblock (sigset_t new_mask)
1545 sigset_t old_mask;
1546 pthread_sigmask (SIG_BLOCK, &new_mask, &old_mask);
1547 return (old_mask);
1550 sigset_t
1551 sys_sigunblock (sigset_t new_mask)
1553 sigset_t old_mask;
1554 pthread_sigmask (SIG_UNBLOCK, &new_mask, &old_mask);
1555 return (old_mask);
1558 sigset_t
1559 sys_sigsetmask (sigset_t new_mask)
1561 sigset_t old_mask;
1562 pthread_sigmask (SIG_SETMASK, &new_mask, &old_mask);
1563 return (old_mask);
1567 #if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
1568 static char *my_sys_siglist[NSIG];
1569 # ifdef sys_siglist
1570 # undef sys_siglist
1571 # endif
1572 # define sys_siglist my_sys_siglist
1573 #endif
1575 void
1576 init_signals (void)
1578 sigemptyset (&empty_mask);
1580 #if !defined HAVE_STRSIGNAL && !HAVE_DECL_SYS_SIGLIST
1581 if (! initialized)
1583 # ifdef SIGABRT
1584 sys_siglist[SIGABRT] = "Aborted";
1585 # endif
1586 # ifdef SIGAIO
1587 sys_siglist[SIGAIO] = "LAN I/O interrupt";
1588 # endif
1589 # ifdef SIGALRM
1590 sys_siglist[SIGALRM] = "Alarm clock";
1591 # endif
1592 # ifdef SIGBUS
1593 sys_siglist[SIGBUS] = "Bus error";
1594 # endif
1595 # ifdef SIGCLD
1596 sys_siglist[SIGCLD] = "Child status changed";
1597 # endif
1598 # ifdef SIGCHLD
1599 sys_siglist[SIGCHLD] = "Child status changed";
1600 # endif
1601 # ifdef SIGCONT
1602 sys_siglist[SIGCONT] = "Continued";
1603 # endif
1604 # ifdef SIGDANGER
1605 sys_siglist[SIGDANGER] = "Swap space dangerously low";
1606 # endif
1607 # ifdef SIGDGNOTIFY
1608 sys_siglist[SIGDGNOTIFY] = "Notification message in queue";
1609 # endif
1610 # ifdef SIGEMT
1611 sys_siglist[SIGEMT] = "Emulation trap";
1612 # endif
1613 # ifdef SIGFPE
1614 sys_siglist[SIGFPE] = "Arithmetic exception";
1615 # endif
1616 # ifdef SIGFREEZE
1617 sys_siglist[SIGFREEZE] = "SIGFREEZE";
1618 # endif
1619 # ifdef SIGGRANT
1620 sys_siglist[SIGGRANT] = "Monitor mode granted";
1621 # endif
1622 # ifdef SIGHUP
1623 sys_siglist[SIGHUP] = "Hangup";
1624 # endif
1625 # ifdef SIGILL
1626 sys_siglist[SIGILL] = "Illegal instruction";
1627 # endif
1628 # ifdef SIGINT
1629 sys_siglist[SIGINT] = "Interrupt";
1630 # endif
1631 # ifdef SIGIO
1632 sys_siglist[SIGIO] = "I/O possible";
1633 # endif
1634 # ifdef SIGIOINT
1635 sys_siglist[SIGIOINT] = "I/O intervention required";
1636 # endif
1637 # ifdef SIGIOT
1638 sys_siglist[SIGIOT] = "IOT trap";
1639 # endif
1640 # ifdef SIGKILL
1641 sys_siglist[SIGKILL] = "Killed";
1642 # endif
1643 # ifdef SIGLOST
1644 sys_siglist[SIGLOST] = "Resource lost";
1645 # endif
1646 # ifdef SIGLWP
1647 sys_siglist[SIGLWP] = "SIGLWP";
1648 # endif
1649 # ifdef SIGMSG
1650 sys_siglist[SIGMSG] = "Monitor mode data available";
1651 # endif
1652 # ifdef SIGPHONE
1653 sys_siglist[SIGWIND] = "SIGPHONE";
1654 # endif
1655 # ifdef SIGPIPE
1656 sys_siglist[SIGPIPE] = "Broken pipe";
1657 # endif
1658 # ifdef SIGPOLL
1659 sys_siglist[SIGPOLL] = "Pollable event occurred";
1660 # endif
1661 # ifdef SIGPROF
1662 sys_siglist[SIGPROF] = "Profiling timer expired";
1663 # endif
1664 # ifdef SIGPTY
1665 sys_siglist[SIGPTY] = "PTY I/O interrupt";
1666 # endif
1667 # ifdef SIGPWR
1668 sys_siglist[SIGPWR] = "Power-fail restart";
1669 # endif
1670 # ifdef SIGQUIT
1671 sys_siglist[SIGQUIT] = "Quit";
1672 # endif
1673 # ifdef SIGRETRACT
1674 sys_siglist[SIGRETRACT] = "Need to relinquish monitor mode";
1675 # endif
1676 # ifdef SIGSAK
1677 sys_siglist[SIGSAK] = "Secure attention";
1678 # endif
1679 # ifdef SIGSEGV
1680 sys_siglist[SIGSEGV] = "Segmentation violation";
1681 # endif
1682 # ifdef SIGSOUND
1683 sys_siglist[SIGSOUND] = "Sound completed";
1684 # endif
1685 # ifdef SIGSTOP
1686 sys_siglist[SIGSTOP] = "Stopped (signal)";
1687 # endif
1688 # ifdef SIGSTP
1689 sys_siglist[SIGSTP] = "Stopped (user)";
1690 # endif
1691 # ifdef SIGSYS
1692 sys_siglist[SIGSYS] = "Bad argument to system call";
1693 # endif
1694 # ifdef SIGTERM
1695 sys_siglist[SIGTERM] = "Terminated";
1696 # endif
1697 # ifdef SIGTHAW
1698 sys_siglist[SIGTHAW] = "SIGTHAW";
1699 # endif
1700 # ifdef SIGTRAP
1701 sys_siglist[SIGTRAP] = "Trace/breakpoint trap";
1702 # endif
1703 # ifdef SIGTSTP
1704 sys_siglist[SIGTSTP] = "Stopped (user)";
1705 # endif
1706 # ifdef SIGTTIN
1707 sys_siglist[SIGTTIN] = "Stopped (tty input)";
1708 # endif
1709 # ifdef SIGTTOU
1710 sys_siglist[SIGTTOU] = "Stopped (tty output)";
1711 # endif
1712 # ifdef SIGURG
1713 sys_siglist[SIGURG] = "Urgent I/O condition";
1714 # endif
1715 # ifdef SIGUSR1
1716 sys_siglist[SIGUSR1] = "User defined signal 1";
1717 # endif
1718 # ifdef SIGUSR2
1719 sys_siglist[SIGUSR2] = "User defined signal 2";
1720 # endif
1721 # ifdef SIGVTALRM
1722 sys_siglist[SIGVTALRM] = "Virtual timer expired";
1723 # endif
1724 # ifdef SIGWAITING
1725 sys_siglist[SIGWAITING] = "Process's LWPs are blocked";
1726 # endif
1727 # ifdef SIGWINCH
1728 sys_siglist[SIGWINCH] = "Window size changed";
1729 # endif
1730 # ifdef SIGWIND
1731 sys_siglist[SIGWIND] = "SIGWIND";
1732 # endif
1733 # ifdef SIGXCPU
1734 sys_siglist[SIGXCPU] = "CPU time limit exceeded";
1735 # endif
1736 # ifdef SIGXFSZ
1737 sys_siglist[SIGXFSZ] = "File size limit exceeded";
1738 # endif
1740 #endif /* !defined HAVE_STRSIGNAL && !defined HAVE_DECL_SYS_SIGLIST */
1743 #ifndef HAVE_RANDOM
1744 #ifdef random
1745 #define HAVE_RANDOM
1746 #endif
1747 #endif
1749 /* Figure out how many bits the system's random number generator uses.
1750 `random' and `lrand48' are assumed to return 31 usable bits.
1751 BSD `rand' returns a 31 bit value but the low order bits are unusable;
1752 so we'll shift it and treat it like the 15-bit USG `rand'. */
1754 #ifndef RAND_BITS
1755 # ifdef HAVE_RANDOM
1756 # define RAND_BITS 31
1757 # else /* !HAVE_RANDOM */
1758 # ifdef HAVE_LRAND48
1759 # define RAND_BITS 31
1760 # define random lrand48
1761 # else /* !HAVE_LRAND48 */
1762 # define RAND_BITS 15
1763 # if RAND_MAX == 32767
1764 # define random rand
1765 # else /* RAND_MAX != 32767 */
1766 # if RAND_MAX == 2147483647
1767 # define random() (rand () >> 16)
1768 # else /* RAND_MAX != 2147483647 */
1769 # ifdef USG
1770 # define random rand
1771 # else
1772 # define random() (rand () >> 16)
1773 # endif /* !USG */
1774 # endif /* RAND_MAX != 2147483647 */
1775 # endif /* RAND_MAX != 32767 */
1776 # endif /* !HAVE_LRAND48 */
1777 # endif /* !HAVE_RANDOM */
1778 #endif /* !RAND_BITS */
1780 void
1781 seed_random (long int arg)
1783 #ifdef HAVE_RANDOM
1784 srandom ((unsigned int)arg);
1785 #else
1786 # ifdef HAVE_LRAND48
1787 srand48 (arg);
1788 # else
1789 srand ((unsigned int)arg);
1790 # endif
1791 #endif
1795 * Return a nonnegative random integer out of whatever we've got.
1796 * It contains enough bits to make a random (signed) Emacs fixnum.
1797 * This suffices even for a 64-bit architecture with a 15-bit rand.
1799 EMACS_INT
1800 get_random (void)
1802 EMACS_UINT val = 0;
1803 int i;
1804 for (i = 0; i < (FIXNUM_BITS + RAND_BITS - 1) / RAND_BITS; i++)
1805 val = (random () ^ (val << RAND_BITS)
1806 ^ (val >> (BITS_PER_EMACS_INT - RAND_BITS)));
1807 val ^= val >> (BITS_PER_EMACS_INT - FIXNUM_BITS);
1808 return val & INTMASK;
1811 #ifndef HAVE_STRERROR
1812 #ifndef WINDOWSNT
1813 char *
1814 strerror (int errnum)
1816 extern char *sys_errlist[];
1817 extern int sys_nerr;
1819 if (errnum >= 0 && errnum < sys_nerr)
1820 return sys_errlist[errnum];
1821 return (char *) "Unknown error";
1823 #endif /* not WINDOWSNT */
1824 #endif /* ! HAVE_STRERROR */
1826 #ifndef HAVE_SNPRINTF
1827 /* Approximate snprintf as best we can on ancient hosts that lack it. */
1829 snprintf (char *buf, size_t bufsize, char const *format, ...)
1831 ptrdiff_t size = min (bufsize, PTRDIFF_MAX);
1832 ptrdiff_t nbytes = size - 1;
1833 va_list ap;
1835 if (size)
1837 va_start (ap, format);
1838 nbytes = doprnt (buf, size, format, 0, ap);
1839 va_end (ap);
1842 if (nbytes == size - 1)
1844 /* Calculate the length of the string that would have been created
1845 had the buffer been large enough. */
1846 char stackbuf[4000];
1847 char *b = stackbuf;
1848 ptrdiff_t bsize = sizeof stackbuf;
1849 va_start (ap, format);
1850 nbytes = evxprintf (&b, &bsize, stackbuf, -1, format, ap);
1851 va_end (ap);
1852 if (b != stackbuf)
1853 xfree (b);
1856 if (INT_MAX < nbytes)
1858 #ifdef EOVERFLOW
1859 errno = EOVERFLOW;
1860 #else
1861 errno = EDOM;
1862 #endif
1863 return -1;
1865 return nbytes;
1867 #endif
1870 emacs_open (const char *path, int oflag, int mode)
1872 register int rtnval;
1874 while ((rtnval = open (path, oflag, mode)) == -1
1875 && (errno == EINTR))
1876 QUIT;
1877 return (rtnval);
1881 emacs_close (int fd)
1883 int did_retry = 0;
1884 register int rtnval;
1886 while ((rtnval = close (fd)) == -1
1887 && (errno == EINTR))
1888 did_retry = 1;
1890 /* If close is interrupted SunOS 4.1 may or may not have closed the
1891 file descriptor. If it did the second close will fail with
1892 errno = EBADF. That means we have succeeded. */
1893 if (rtnval == -1 && did_retry && errno == EBADF)
1894 return 0;
1896 return rtnval;
1899 /* Maximum number of bytes to read or write in a single system call.
1900 This works around a serious bug in Linux kernels before 2.6.16; see
1901 <https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=612839>.
1902 It's likely to work around similar bugs in other operating systems, so do it
1903 on all platforms. Round INT_MAX down to a page size, with the conservative
1904 assumption that page sizes are at most 2**18 bytes (any kernel with a
1905 page size larger than that shouldn't have the bug). */
1906 #ifndef MAX_RW_COUNT
1907 #define MAX_RW_COUNT (INT_MAX >> 18 << 18)
1908 #endif
1910 /* Read from FILEDESC to a buffer BUF with size NBYTE, retrying if interrupted.
1911 Return the number of bytes read, which might be less than NBYTE.
1912 On error, set errno and return -1. */
1913 ptrdiff_t
1914 emacs_read (int fildes, char *buf, ptrdiff_t nbyte)
1916 register ssize_t rtnval;
1918 /* There is no need to check against MAX_RW_COUNT, since no caller ever
1919 passes a size that large to emacs_read. */
1921 while ((rtnval = read (fildes, buf, nbyte)) == -1
1922 && (errno == EINTR))
1923 QUIT;
1924 return (rtnval);
1927 /* Write to FILEDES from a buffer BUF with size NBYTE, retrying if interrupted
1928 or if a partial write occurs. Return the number of bytes written, setting
1929 errno if this is less than NBYTE. */
1930 ptrdiff_t
1931 emacs_write (int fildes, const char *buf, ptrdiff_t nbyte)
1933 ssize_t rtnval;
1934 ptrdiff_t bytes_written;
1936 bytes_written = 0;
1938 while (nbyte > 0)
1940 rtnval = write (fildes, buf, min (nbyte, MAX_RW_COUNT));
1942 if (rtnval < 0)
1944 if (errno == EINTR)
1946 #ifdef SYNC_INPUT
1947 /* I originally used `QUIT' but that might causes files to
1948 be truncated if you hit C-g in the middle of it. --Stef */
1949 process_pending_signals ();
1950 #endif
1951 continue;
1953 else
1954 break;
1957 buf += rtnval;
1958 nbyte -= rtnval;
1959 bytes_written += rtnval;
1962 return (bytes_written);
1965 static struct allocator const emacs_norealloc_allocator =
1966 { xmalloc, NULL, xfree, memory_full };
1968 /* Get the symbolic link value of FILENAME. Return a pointer to a
1969 NUL-terminated string. If readlink fails, return NULL and set
1970 errno. If the value fits in INITIAL_BUF, return INITIAL_BUF.
1971 Otherwise, allocate memory and return a pointer to that memory. If
1972 memory allocation fails, diagnose and fail without returning. If
1973 successful, store the length of the symbolic link into *LINKLEN. */
1974 char *
1975 emacs_readlink (char const *filename, char initial_buf[READLINK_BUFSIZE])
1977 return careadlinkat (AT_FDCWD, filename, initial_buf, READLINK_BUFSIZE,
1978 &emacs_norealloc_allocator, careadlinkatcwd);
1981 #ifdef USG
1983 * All of the following are for USG.
1985 * On USG systems the system calls are INTERRUPTIBLE by signals
1986 * that the user program has elected to catch. Thus the system call
1987 * must be retried in these cases. To handle this without massive
1988 * changes in the source code, we remap the standard system call names
1989 * to names for our own functions in sysdep.c that do the system call
1990 * with retries. Actually, for portability reasons, it is good
1991 * programming practice, as this example shows, to limit all actual
1992 * system calls to a single occurrence in the source. Sure, this
1993 * adds an extra level of function call overhead but it is almost
1994 * always negligible. Fred Fish, Unisoft Systems Inc.
1998 * Warning, this function may not duplicate 4.2 action properly
1999 * under error conditions.
2002 #ifndef HAVE_GETWD
2004 #ifndef MAXPATHLEN
2005 /* In 4.1, param.h fails to define this. */
2006 #define MAXPATHLEN 1024
2007 #endif
2009 char *
2010 getwd (char *pathname)
2012 char *npath, *spath;
2013 extern char *getcwd (char *, size_t);
2015 BLOCK_INPUT; /* getcwd uses malloc */
2016 spath = npath = getcwd ((char *) 0, MAXPATHLEN);
2017 if (spath == 0)
2019 UNBLOCK_INPUT;
2020 return spath;
2022 /* On Altos 3068, getcwd can return @hostname/dir, so discard
2023 up to first slash. Should be harmless on other systems. */
2024 while (*npath && *npath != '/')
2025 npath++;
2026 strcpy (pathname, npath);
2027 free (spath); /* getcwd uses malloc */
2028 UNBLOCK_INPUT;
2029 return pathname;
2032 #endif /* HAVE_GETWD */
2035 * Emulate rename using unlink/link. Note that this is
2036 * only partially correct. Also, doesn't enforce restriction
2037 * that files be of same type (regular->regular, dir->dir, etc).
2040 #ifndef HAVE_RENAME
2043 rename (const char *from, const char *to)
2045 if (access (from, 0) == 0)
2047 unlink (to);
2048 if (link (from, to) == 0)
2049 if (unlink (from) == 0)
2050 return (0);
2052 return (-1);
2055 #endif
2058 #if defined (HPUX) && !defined (HAVE_PERROR)
2060 /* HPUX curses library references perror, but as far as we know
2061 it won't be called. Anyway this definition will do for now. */
2063 void
2064 perror (void)
2067 #endif /* HPUX and not HAVE_PERROR */
2070 * Gettimeofday. Simulate as much as possible. Only accurate
2071 * to nearest second. Emacs doesn't use tzp so ignore it for now.
2072 * Only needed when subprocesses are defined.
2075 #ifndef HAVE_GETTIMEOFDAY
2076 #ifdef HAVE_TIMEVAL
2079 gettimeofday (struct timeval *tp, struct timezone *tzp)
2081 extern long time (long);
2083 tp->tv_sec = time ((long *)0);
2084 tp->tv_usec = 0;
2085 if (tzp != 0)
2086 tzp->tz_minuteswest = -1;
2087 return 0;
2090 #endif
2091 #endif /* !HAVE_GETTIMEOFDAY && HAVE_TIMEVAL */
2094 * This function will go away as soon as all the stubs fixed. (fnf)
2097 void
2098 croak (char *badfunc)
2100 printf ("%s not yet implemented\r\n", badfunc);
2101 reset_all_sys_modes ();
2102 exit (1);
2105 #endif /* USG */
2107 /* Directory routines for systems that don't have them. */
2109 #ifdef HAVE_DIRENT_H
2111 #include <dirent.h>
2113 #if !defined (HAVE_CLOSEDIR)
2116 closedir (DIR *dirp /* stream from opendir */)
2118 int rtnval;
2120 rtnval = emacs_close (dirp->dd_fd);
2121 xfree ((char *) dirp);
2123 return rtnval;
2125 #endif /* not HAVE_CLOSEDIR */
2126 #endif /* HAVE_DIRENT_H */
2130 set_file_times (const char *filename, EMACS_TIME atime, EMACS_TIME mtime)
2132 #ifdef HAVE_UTIMES
2133 struct timeval tv[2];
2134 tv[0] = atime;
2135 tv[1] = mtime;
2136 return utimes (filename, tv);
2137 #else /* not HAVE_UTIMES */
2138 struct utimbuf utb;
2139 utb.actime = EMACS_SECS (atime);
2140 utb.modtime = EMACS_SECS (mtime);
2141 return utime (filename, &utb);
2142 #endif /* not HAVE_UTIMES */
2145 /* mkdir and rmdir functions, for systems which don't have them. */
2147 #ifndef HAVE_MKDIR
2149 * Written by Robert Rother, Mariah Corporation, August 1985.
2151 * If you want it, it's yours. All I ask in return is that if you
2152 * figure out how to do this in a Bourne Shell script you send me
2153 * a copy.
2154 * sdcsvax!rmr or rmr@uscd
2156 * Severely hacked over by John Gilmore to make a 4.2BSD compatible
2157 * subroutine. 11Mar86; hoptoad!gnu
2159 * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
2160 * subroutine didn't return EEXIST. It does now.
2164 * Make a directory.
2167 mkdir (char *dpath, int dmode)
2169 pid_t cpid;
2170 int status, fd;
2171 struct stat statbuf;
2173 if (stat (dpath, &statbuf) == 0)
2175 errno = EEXIST; /* Stat worked, so it already exists */
2176 return -1;
2179 /* If stat fails for a reason other than non-existence, return error */
2180 if (errno != ENOENT)
2181 return -1;
2183 synch_process_alive = 1;
2184 switch (cpid = fork ())
2187 case -1: /* Error in fork */
2188 return (-1); /* Errno is set already */
2190 case 0: /* Child process */
2192 * Cheap hack to set mode of new directory. Since this
2193 * child process is going away anyway, we zap its umask.
2194 * FIXME, this won't suffice to set SUID, SGID, etc. on this
2195 * directory. Does anybody care?
2197 status = umask (0); /* Get current umask */
2198 status = umask (status | (0777 & ~dmode)); /* Set for mkdir */
2199 fd = emacs_open ("/dev/null", O_RDWR, 0);
2200 if (fd >= 0)
2202 dup2 (fd, 0);
2203 dup2 (fd, 1);
2204 dup2 (fd, 2);
2206 execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
2207 _exit (-1); /* Can't exec /bin/mkdir */
2209 default: /* Parent process */
2210 wait_for_termination (cpid);
2213 if (synch_process_death != 0 || synch_process_retcode != 0
2214 || synch_process_termsig != 0)
2216 errno = EIO; /* We don't know why, but */
2217 return -1; /* /bin/mkdir failed */
2220 return 0;
2222 #endif /* not HAVE_MKDIR */
2224 #ifndef HAVE_RMDIR
2226 rmdir (char *dpath)
2228 int cpid, status, fd;
2229 struct stat statbuf;
2231 if (stat (dpath, &statbuf) != 0)
2233 /* Stat just set errno. We don't have to */
2234 return -1;
2237 synch_process_alive = 1;
2238 switch (cpid = fork ())
2241 case -1: /* Error in fork */
2242 return (-1); /* Errno is set already */
2244 case 0: /* Child process */
2245 fd = emacs_open ("/dev/null", O_RDWR, 0);
2246 if (fd >= 0)
2248 dup2 (fd, 0);
2249 dup2 (fd, 1);
2250 dup2 (fd, 2);
2252 execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
2253 _exit (-1); /* Can't exec /bin/rmdir */
2255 default: /* Parent process */
2256 wait_for_termination (cpid);
2259 if (synch_process_death != 0 || synch_process_retcode != 0
2260 || synch_process_termsig != 0)
2262 errno = EIO; /* We don't know why, but */
2263 return -1; /* /bin/rmdir failed */
2266 return 0;
2268 #endif /* !HAVE_RMDIR */
2271 #ifndef HAVE_STRSIGNAL
2272 char *
2273 strsignal (int code)
2275 char *signame = 0;
2277 if (0 <= code && code < NSIG)
2279 /* Cast to suppress warning if the table has const char *. */
2280 signame = (char *) sys_siglist[code];
2283 return signame;
2285 #endif /* HAVE_STRSIGNAL */
2287 #ifndef DOS_NT
2288 /* For make-serial-process */
2290 serial_open (char *port)
2292 int fd = -1;
2294 fd = emacs_open ((char*) port,
2295 O_RDWR
2296 #ifdef O_NONBLOCK
2297 | O_NONBLOCK
2298 #else
2299 | O_NDELAY
2300 #endif
2301 #ifdef O_NOCTTY
2302 | O_NOCTTY
2303 #endif
2304 , 0);
2305 if (fd < 0)
2307 error ("Could not open %s: %s",
2308 port, emacs_strerror (errno));
2310 #ifdef TIOCEXCL
2311 ioctl (fd, TIOCEXCL, (char *) 0);
2312 #endif
2314 return fd;
2317 #if !defined (HAVE_CFMAKERAW)
2318 /* Workaround for targets which are missing cfmakeraw. */
2319 /* Pasted from man page. */
2320 static void
2321 cfmakeraw (struct termios *termios_p)
2323 termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2324 termios_p->c_oflag &= ~OPOST;
2325 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2326 termios_p->c_cflag &= ~(CSIZE|PARENB);
2327 termios_p->c_cflag |= CS8;
2329 #endif /* !defined (HAVE_CFMAKERAW */
2331 #if !defined (HAVE_CFSETSPEED)
2332 /* Workaround for targets which are missing cfsetspeed. */
2333 static int
2334 cfsetspeed (struct termios *termios_p, speed_t vitesse)
2336 return (cfsetispeed (termios_p, vitesse)
2337 + cfsetospeed (termios_p, vitesse));
2339 #endif
2341 /* For serial-process-configure */
2342 void
2343 serial_configure (struct Lisp_Process *p,
2344 Lisp_Object contact)
2346 Lisp_Object childp2 = Qnil;
2347 Lisp_Object tem = Qnil;
2348 struct termios attr;
2349 int err = -1;
2350 char summary[4] = "???"; /* This usually becomes "8N1". */
2352 childp2 = Fcopy_sequence (p->childp);
2354 /* Read port attributes and prepare default configuration. */
2355 err = tcgetattr (p->outfd, &attr);
2356 if (err != 0)
2357 error ("tcgetattr() failed: %s", emacs_strerror (errno));
2358 cfmakeraw (&attr);
2359 #if defined (CLOCAL)
2360 attr.c_cflag |= CLOCAL;
2361 #endif
2362 #if defined (CREAD)
2363 attr.c_cflag |= CREAD;
2364 #endif
2366 /* Configure speed. */
2367 if (!NILP (Fplist_member (contact, QCspeed)))
2368 tem = Fplist_get (contact, QCspeed);
2369 else
2370 tem = Fplist_get (p->childp, QCspeed);
2371 CHECK_NUMBER (tem);
2372 err = cfsetspeed (&attr, XINT (tem));
2373 if (err != 0)
2374 error ("cfsetspeed(%"pI"d) failed: %s", XINT (tem),
2375 emacs_strerror (errno));
2376 childp2 = Fplist_put (childp2, QCspeed, tem);
2378 /* Configure bytesize. */
2379 if (!NILP (Fplist_member (contact, QCbytesize)))
2380 tem = Fplist_get (contact, QCbytesize);
2381 else
2382 tem = Fplist_get (p->childp, QCbytesize);
2383 if (NILP (tem))
2384 tem = make_number (8);
2385 CHECK_NUMBER (tem);
2386 if (XINT (tem) != 7 && XINT (tem) != 8)
2387 error (":bytesize must be nil (8), 7, or 8");
2388 summary[0] = XINT (tem) + '0';
2389 #if defined (CSIZE) && defined (CS7) && defined (CS8)
2390 attr.c_cflag &= ~CSIZE;
2391 attr.c_cflag |= ((XINT (tem) == 7) ? CS7 : CS8);
2392 #else
2393 /* Don't error on bytesize 8, which should be set by cfmakeraw. */
2394 if (XINT (tem) != 8)
2395 error ("Bytesize cannot be changed");
2396 #endif
2397 childp2 = Fplist_put (childp2, QCbytesize, tem);
2399 /* Configure parity. */
2400 if (!NILP (Fplist_member (contact, QCparity)))
2401 tem = Fplist_get (contact, QCparity);
2402 else
2403 tem = Fplist_get (p->childp, QCparity);
2404 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
2405 error (":parity must be nil (no parity), `even', or `odd'");
2406 #if defined (PARENB) && defined (PARODD) && defined (IGNPAR) && defined (INPCK)
2407 attr.c_cflag &= ~(PARENB | PARODD);
2408 attr.c_iflag &= ~(IGNPAR | INPCK);
2409 if (NILP (tem))
2411 summary[1] = 'N';
2413 else if (EQ (tem, Qeven))
2415 summary[1] = 'E';
2416 attr.c_cflag |= PARENB;
2417 attr.c_iflag |= (IGNPAR | INPCK);
2419 else if (EQ (tem, Qodd))
2421 summary[1] = 'O';
2422 attr.c_cflag |= (PARENB | PARODD);
2423 attr.c_iflag |= (IGNPAR | INPCK);
2425 #else
2426 /* Don't error on no parity, which should be set by cfmakeraw. */
2427 if (!NILP (tem))
2428 error ("Parity cannot be configured");
2429 #endif
2430 childp2 = Fplist_put (childp2, QCparity, tem);
2432 /* Configure stopbits. */
2433 if (!NILP (Fplist_member (contact, QCstopbits)))
2434 tem = Fplist_get (contact, QCstopbits);
2435 else
2436 tem = Fplist_get (p->childp, QCstopbits);
2437 if (NILP (tem))
2438 tem = make_number (1);
2439 CHECK_NUMBER (tem);
2440 if (XINT (tem) != 1 && XINT (tem) != 2)
2441 error (":stopbits must be nil (1 stopbit), 1, or 2");
2442 summary[2] = XINT (tem) + '0';
2443 #if defined (CSTOPB)
2444 attr.c_cflag &= ~CSTOPB;
2445 if (XINT (tem) == 2)
2446 attr.c_cflag |= CSTOPB;
2447 #else
2448 /* Don't error on 1 stopbit, which should be set by cfmakeraw. */
2449 if (XINT (tem) != 1)
2450 error ("Stopbits cannot be configured");
2451 #endif
2452 childp2 = Fplist_put (childp2, QCstopbits, tem);
2454 /* Configure flowcontrol. */
2455 if (!NILP (Fplist_member (contact, QCflowcontrol)))
2456 tem = Fplist_get (contact, QCflowcontrol);
2457 else
2458 tem = Fplist_get (p->childp, QCflowcontrol);
2459 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
2460 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
2461 #if defined (CRTSCTS)
2462 attr.c_cflag &= ~CRTSCTS;
2463 #endif
2464 #if defined (CNEW_RTSCTS)
2465 attr.c_cflag &= ~CNEW_RTSCTS;
2466 #endif
2467 #if defined (IXON) && defined (IXOFF)
2468 attr.c_iflag &= ~(IXON | IXOFF);
2469 #endif
2470 if (NILP (tem))
2472 /* Already configured. */
2474 else if (EQ (tem, Qhw))
2476 #if defined (CRTSCTS)
2477 attr.c_cflag |= CRTSCTS;
2478 #elif defined (CNEW_RTSCTS)
2479 attr.c_cflag |= CNEW_RTSCTS;
2480 #else
2481 error ("Hardware flowcontrol (RTS/CTS) not supported");
2482 #endif
2484 else if (EQ (tem, Qsw))
2486 #if defined (IXON) && defined (IXOFF)
2487 attr.c_iflag |= (IXON | IXOFF);
2488 #else
2489 error ("Software flowcontrol (XON/XOFF) not supported");
2490 #endif
2492 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
2494 /* Activate configuration. */
2495 err = tcsetattr (p->outfd, TCSANOW, &attr);
2496 if (err != 0)
2497 error ("tcsetattr() failed: %s", emacs_strerror (errno));
2499 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
2500 p->childp = childp2;
2503 #endif /* not DOS_NT */
2505 /* System depended enumeration of and access to system processes a-la ps(1). */
2507 #ifdef HAVE_PROCFS
2509 /* Process enumeration and access via /proc. */
2511 Lisp_Object
2512 list_system_processes (void)
2514 Lisp_Object procdir, match, proclist, next;
2515 struct gcpro gcpro1, gcpro2;
2516 register Lisp_Object tail;
2518 GCPRO2 (procdir, match);
2519 /* For every process on the system, there's a directory in the
2520 "/proc" pseudo-directory whose name is the numeric ID of that
2521 process. */
2522 procdir = build_string ("/proc");
2523 match = build_string ("[0-9]+");
2524 proclist = directory_files_internal (procdir, Qnil, match, Qt, 0, Qnil);
2526 /* `proclist' gives process IDs as strings. Destructively convert
2527 each string into a number. */
2528 for (tail = proclist; CONSP (tail); tail = next)
2530 next = XCDR (tail);
2531 XSETCAR (tail, Fstring_to_number (XCAR (tail), Qnil));
2533 UNGCPRO;
2535 /* directory_files_internal returns the files in reverse order; undo
2536 that. */
2537 proclist = Fnreverse (proclist);
2538 return proclist;
2541 #elif defined BSD_SYSTEM
2543 Lisp_Object
2544 list_system_processes (void)
2546 #ifdef DARWIN_OS
2547 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
2548 #else
2549 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC};
2550 #endif
2551 size_t len;
2552 struct kinfo_proc *procs;
2553 size_t i;
2555 struct gcpro gcpro1;
2556 Lisp_Object proclist = Qnil;
2558 if (sysctl (mib, 3, NULL, &len, NULL, 0) != 0)
2559 return proclist;
2561 procs = xmalloc (len);
2562 if (sysctl (mib, 3, procs, &len, NULL, 0) != 0)
2564 xfree (procs);
2565 return proclist;
2568 GCPRO1 (proclist);
2569 len /= sizeof (struct kinfo_proc);
2570 for (i = 0; i < len; i++)
2572 #ifdef DARWIN_OS
2573 proclist = Fcons (make_fixnum_or_float (procs[i].kp_proc.p_pid), proclist);
2574 #else
2575 proclist = Fcons (make_fixnum_or_float (procs[i].ki_pid), proclist);
2576 #endif
2578 UNGCPRO;
2580 xfree (procs);
2582 return proclist;
2585 /* The WINDOWSNT implementation is in w32.c.
2586 The MSDOS implementation is in dosfns.c. */
2587 #elif !defined (WINDOWSNT) && !defined (MSDOS)
2589 Lisp_Object
2590 list_system_processes (void)
2592 return Qnil;
2595 #endif /* !defined (WINDOWSNT) */
2597 #ifdef GNU_LINUX
2598 static void
2599 time_from_jiffies (unsigned long long tval, long hz,
2600 time_t *sec, unsigned *usec)
2602 unsigned long long ullsec;
2604 *sec = tval / hz;
2605 ullsec = *sec;
2606 tval -= ullsec * hz;
2607 /* Careful: if HZ > 1 million, then integer division by it yields zero. */
2608 if (hz <= 1000000)
2609 *usec = tval * 1000000 / hz;
2610 else
2611 *usec = tval / (hz / 1000000);
2614 static Lisp_Object
2615 ltime_from_jiffies (unsigned long long tval, long hz)
2617 time_t sec;
2618 unsigned usec;
2620 time_from_jiffies (tval, hz, &sec, &usec);
2622 return list3 (make_number ((sec >> 16) & 0xffff),
2623 make_number (sec & 0xffff),
2624 make_number (usec));
2627 static void
2628 get_up_time (time_t *sec, unsigned *usec)
2630 FILE *fup;
2632 *sec = *usec = 0;
2634 BLOCK_INPUT;
2635 fup = fopen ("/proc/uptime", "r");
2637 if (fup)
2639 double uptime, idletime;
2641 /* The numbers in /proc/uptime use C-locale decimal point, but
2642 we already set ourselves to the C locale (see `fixup_locale'
2643 in emacs.c). */
2644 if (2 <= fscanf (fup, "%lf %lf", &uptime, &idletime))
2646 *sec = uptime;
2647 *usec = (uptime - *sec) * 1000000;
2649 fclose (fup);
2651 UNBLOCK_INPUT;
2654 #define MAJOR(d) (((unsigned)(d) >> 8) & 0xfff)
2655 #define MINOR(d) (((unsigned)(d) & 0xff) | (((unsigned)(d) & 0xfff00000) >> 12))
2657 static Lisp_Object
2658 procfs_ttyname (int rdev)
2660 FILE *fdev = NULL;
2661 char name[PATH_MAX];
2663 BLOCK_INPUT;
2664 fdev = fopen ("/proc/tty/drivers", "r");
2666 if (fdev)
2668 unsigned major;
2669 unsigned long minor_beg, minor_end;
2670 char minor[25]; /* 2 32-bit numbers + dash */
2671 char *endp;
2673 while (!feof (fdev) && !ferror (fdev))
2675 if (3 <= fscanf (fdev, "%*s %s %u %s %*s\n", name, &major, minor)
2676 && major == MAJOR (rdev))
2678 minor_beg = strtoul (minor, &endp, 0);
2679 if (*endp == '\0')
2680 minor_end = minor_beg;
2681 else if (*endp == '-')
2682 minor_end = strtoul (endp + 1, &endp, 0);
2683 else
2684 continue;
2686 if (MINOR (rdev) >= minor_beg && MINOR (rdev) <= minor_end)
2688 sprintf (name + strlen (name), "%u", MINOR (rdev));
2689 break;
2693 fclose (fdev);
2695 UNBLOCK_INPUT;
2696 return build_string (name);
2699 static unsigned long
2700 procfs_get_total_memory (void)
2702 FILE *fmem = NULL;
2703 unsigned long retval = 2 * 1024 * 1024; /* default: 2GB */
2705 BLOCK_INPUT;
2706 fmem = fopen ("/proc/meminfo", "r");
2708 if (fmem)
2710 unsigned long entry_value;
2711 char entry_name[20]; /* the longest I saw is 13+1 */
2713 while (!feof (fmem) && !ferror (fmem))
2715 if (2 <= fscanf (fmem, "%s %lu kB\n", entry_name, &entry_value)
2716 && strcmp (entry_name, "MemTotal:") == 0)
2718 retval = entry_value;
2719 break;
2722 fclose (fmem);
2724 UNBLOCK_INPUT;
2725 return retval;
2728 Lisp_Object
2729 system_process_attributes (Lisp_Object pid)
2731 char procfn[PATH_MAX], fn[PATH_MAX];
2732 struct stat st;
2733 struct passwd *pw;
2734 struct group *gr;
2735 long clocks_per_sec;
2736 char *procfn_end;
2737 char procbuf[1025], *p, *q;
2738 int fd;
2739 ssize_t nread;
2740 const char *cmd = NULL;
2741 char *cmdline = NULL;
2742 ptrdiff_t cmdsize = 0, cmdline_size;
2743 unsigned char c;
2744 printmax_t proc_id;
2745 int ppid, pgrp, sess, tty, tpgid, thcount;
2746 uid_t uid;
2747 gid_t gid;
2748 unsigned long long u_time, s_time, cutime, cstime, start;
2749 long priority, niceness, rss;
2750 unsigned long minflt, majflt, cminflt, cmajflt, vsize;
2751 time_t sec;
2752 unsigned usec;
2753 EMACS_TIME tnow, tstart, tboot, telapsed;
2754 double pcpu, pmem;
2755 Lisp_Object attrs = Qnil;
2756 Lisp_Object cmd_str, decoded_cmd, tem;
2757 struct gcpro gcpro1, gcpro2;
2759 CHECK_NUMBER_OR_FLOAT (pid);
2760 CONS_TO_INTEGER (pid, pid_t, proc_id);
2761 sprintf (procfn, "/proc/%"pMd, proc_id);
2762 if (stat (procfn, &st) < 0)
2763 return attrs;
2765 GCPRO2 (attrs, decoded_cmd);
2767 /* euid egid */
2768 uid = st.st_uid;
2769 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
2770 BLOCK_INPUT;
2771 pw = getpwuid (uid);
2772 UNBLOCK_INPUT;
2773 if (pw)
2774 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
2776 gid = st.st_gid;
2777 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
2778 BLOCK_INPUT;
2779 gr = getgrgid (gid);
2780 UNBLOCK_INPUT;
2781 if (gr)
2782 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
2784 strcpy (fn, procfn);
2785 procfn_end = fn + strlen (fn);
2786 strcpy (procfn_end, "/stat");
2787 fd = emacs_open (fn, O_RDONLY, 0);
2788 if (fd >= 0 && (nread = emacs_read (fd, procbuf, sizeof (procbuf) - 1)) > 0)
2790 procbuf[nread] = '\0';
2791 p = procbuf;
2793 p = strchr (p, '(');
2794 if (p != NULL)
2796 q = strrchr (p + 1, ')');
2797 /* comm */
2798 if (q != NULL)
2800 cmd = p + 1;
2801 cmdsize = q - cmd;
2804 else
2805 q = NULL;
2806 if (cmd == NULL)
2808 cmd = "???";
2809 cmdsize = 3;
2811 /* Command name is encoded in locale-coding-system; decode it. */
2812 cmd_str = make_unibyte_string (cmd, cmdsize);
2813 decoded_cmd = code_convert_string_norecord (cmd_str,
2814 Vlocale_coding_system, 0);
2815 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
2817 if (q)
2819 EMACS_INT ppid_eint, pgrp_eint, sess_eint, tpgid_eint, thcount_eint;
2820 p = q + 2;
2821 /* state ppid pgrp sess tty tpgid . minflt cminflt majflt cmajflt utime stime cutime cstime priority nice thcount . start vsize rss */
2822 sscanf (p, "%c %d %d %d %d %d %*u %lu %lu %lu %lu %Lu %Lu %Lu %Lu %ld %ld %d %*d %Lu %lu %ld",
2823 &c, &ppid, &pgrp, &sess, &tty, &tpgid,
2824 &minflt, &cminflt, &majflt, &cmajflt,
2825 &u_time, &s_time, &cutime, &cstime,
2826 &priority, &niceness, &thcount, &start, &vsize, &rss);
2828 char state_str[2];
2830 state_str[0] = c;
2831 state_str[1] = '\0';
2832 tem = build_string (state_str);
2833 attrs = Fcons (Fcons (Qstate, tem), attrs);
2835 /* Stops GCC whining about limited range of data type. */
2836 ppid_eint = ppid;
2837 pgrp_eint = pgrp;
2838 sess_eint = sess;
2839 tpgid_eint = tpgid;
2840 thcount_eint = thcount;
2841 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (ppid_eint)), attrs);
2842 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pgrp_eint)), attrs);
2843 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (sess_eint)), attrs);
2844 attrs = Fcons (Fcons (Qttname, procfs_ttyname (tty)), attrs);
2845 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (tpgid_eint)), attrs);
2846 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (minflt)), attrs);
2847 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (majflt)), attrs);
2848 attrs = Fcons (Fcons (Qcminflt, make_fixnum_or_float (cminflt)), attrs);
2849 attrs = Fcons (Fcons (Qcmajflt, make_fixnum_or_float (cmajflt)), attrs);
2850 clocks_per_sec = sysconf (_SC_CLK_TCK);
2851 if (clocks_per_sec < 0)
2852 clocks_per_sec = 100;
2853 attrs = Fcons (Fcons (Qutime,
2854 ltime_from_jiffies (u_time, clocks_per_sec)),
2855 attrs);
2856 attrs = Fcons (Fcons (Qstime,
2857 ltime_from_jiffies (s_time, clocks_per_sec)),
2858 attrs);
2859 attrs = Fcons (Fcons (Qtime,
2860 ltime_from_jiffies (s_time + u_time,
2861 clocks_per_sec)),
2862 attrs);
2863 attrs = Fcons (Fcons (Qcutime,
2864 ltime_from_jiffies (cutime, clocks_per_sec)),
2865 attrs);
2866 attrs = Fcons (Fcons (Qcstime,
2867 ltime_from_jiffies (cstime, clocks_per_sec)),
2868 attrs);
2869 attrs = Fcons (Fcons (Qctime,
2870 ltime_from_jiffies (cstime+cutime, clocks_per_sec)),
2871 attrs);
2872 attrs = Fcons (Fcons (Qpri, make_number (priority)), attrs);
2873 attrs = Fcons (Fcons (Qnice, make_number (niceness)), attrs);
2874 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (thcount_eint)), attrs);
2875 EMACS_GET_TIME (tnow);
2876 get_up_time (&sec, &usec);
2877 EMACS_SET_SECS (telapsed, sec);
2878 EMACS_SET_USECS (telapsed, usec);
2879 EMACS_SUB_TIME (tboot, tnow, telapsed);
2880 time_from_jiffies (start, clocks_per_sec, &sec, &usec);
2881 EMACS_SET_SECS (tstart, sec);
2882 EMACS_SET_USECS (tstart, usec);
2883 EMACS_ADD_TIME (tstart, tboot, tstart);
2884 attrs = Fcons (Fcons (Qstart,
2885 list3 (make_number
2886 ((EMACS_SECS (tstart) >> 16) & 0xffff),
2887 make_number
2888 (EMACS_SECS (tstart) & 0xffff),
2889 make_number
2890 (EMACS_USECS (tstart)))),
2891 attrs);
2892 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (vsize/1024)), attrs);
2893 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (4*rss)), attrs);
2894 EMACS_SUB_TIME (telapsed, tnow, tstart);
2895 attrs = Fcons (Fcons (Qetime,
2896 list3 (make_number
2897 ((EMACS_SECS (telapsed) >> 16) & 0xffff),
2898 make_number
2899 (EMACS_SECS (telapsed) & 0xffff),
2900 make_number
2901 (EMACS_USECS (telapsed)))),
2902 attrs);
2903 time_from_jiffies (u_time + s_time, clocks_per_sec, &sec, &usec);
2904 pcpu = (sec + usec / 1000000.0) / (EMACS_SECS (telapsed) + EMACS_USECS (telapsed) / 1000000.0);
2905 if (pcpu > 1.0)
2906 pcpu = 1.0;
2907 attrs = Fcons (Fcons (Qpcpu, make_float (100 * pcpu)), attrs);
2908 pmem = 4.0 * 100 * rss / procfs_get_total_memory ();
2909 if (pmem > 100)
2910 pmem = 100;
2911 attrs = Fcons (Fcons (Qpmem, make_float (pmem)), attrs);
2914 if (fd >= 0)
2915 emacs_close (fd);
2917 /* args */
2918 strcpy (procfn_end, "/cmdline");
2919 fd = emacs_open (fn, O_RDONLY, 0);
2920 if (fd >= 0)
2922 char ch;
2923 for (cmdline_size = 0; cmdline_size < STRING_BYTES_BOUND; cmdline_size++)
2925 if (emacs_read (fd, &ch, 1) != 1)
2926 break;
2927 c = ch;
2928 if (isspace (c) || c == '\\')
2929 cmdline_size++; /* for later quoting, see below */
2931 if (cmdline_size)
2933 cmdline = xmalloc (cmdline_size + 1);
2934 lseek (fd, 0L, SEEK_SET);
2935 cmdline[0] = '\0';
2936 if ((nread = read (fd, cmdline, cmdline_size)) >= 0)
2937 cmdline[nread++] = '\0';
2938 else
2940 /* Assigning zero to `nread' makes us skip the following
2941 two loops, assign zero to cmdline_size, and enter the
2942 following `if' clause that handles unknown command
2943 lines. */
2944 nread = 0;
2946 /* We don't want trailing null characters. */
2947 for (p = cmdline + nread; p > cmdline + 1 && !p[-1]; p--)
2948 nread--;
2949 for (p = cmdline; p < cmdline + nread; p++)
2951 /* Escape-quote whitespace and backslashes. */
2952 if (isspace (*p) || *p == '\\')
2954 memmove (p + 1, p, nread - (p - cmdline));
2955 nread++;
2956 *p++ = '\\';
2958 else if (*p == '\0')
2959 *p = ' ';
2961 cmdline_size = nread;
2963 if (!cmdline_size)
2965 if (!cmd)
2966 cmd = "???";
2967 if (!cmdsize)
2968 cmdsize = strlen (cmd);
2969 cmdline_size = cmdsize + 2;
2970 cmdline = xmalloc (cmdline_size + 1);
2971 strcpy (cmdline, "[");
2972 strcat (strncat (cmdline, cmd, cmdsize), "]");
2974 emacs_close (fd);
2975 /* Command line is encoded in locale-coding-system; decode it. */
2976 cmd_str = make_unibyte_string (cmdline, cmdline_size);
2977 decoded_cmd = code_convert_string_norecord (cmd_str,
2978 Vlocale_coding_system, 0);
2979 xfree (cmdline);
2980 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
2983 UNGCPRO;
2984 return attrs;
2987 #elif defined (SOLARIS2) && defined (HAVE_PROCFS)
2989 /* The <procfs.h> header does not like to be included if _LP64 is defined and
2990 __FILE_OFFSET_BITS == 64. This is an ugly workaround that. */
2991 #if !defined (_LP64) && defined (_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
2992 #define PROCFS_FILE_OFFSET_BITS_HACK 1
2993 #undef _FILE_OFFSET_BITS
2994 #else
2995 #define PROCFS_FILE_OFFSET_BITS_HACK 0
2996 #endif
2998 #include <procfs.h>
3000 #if PROCFS_FILE_OFFSET_BITS_HACK == 1
3001 #define _FILE_OFFSET_BITS 64
3002 #ifdef _FILE_OFFSET_BITS /* Avoid unused-macro warnings. */
3003 #endif
3004 #endif /* PROCFS_FILE_OFFSET_BITS_HACK == 1 */
3006 Lisp_Object
3007 system_process_attributes (Lisp_Object pid)
3009 char procfn[PATH_MAX], fn[PATH_MAX];
3010 struct stat st;
3011 struct passwd *pw;
3012 struct group *gr;
3013 char *procfn_end;
3014 struct psinfo pinfo;
3015 int fd;
3016 ssize_t nread;
3017 printmax_t proc_id;
3018 uid_t uid;
3019 gid_t gid;
3020 Lisp_Object attrs = Qnil;
3021 Lisp_Object decoded_cmd, tem;
3022 struct gcpro gcpro1, gcpro2;
3024 CHECK_NUMBER_OR_FLOAT (pid);
3025 CONS_TO_INTEGER (pid, pid_t, proc_id);
3026 sprintf (procfn, "/proc/%"pMd, proc_id);
3027 if (stat (procfn, &st) < 0)
3028 return attrs;
3030 GCPRO2 (attrs, decoded_cmd);
3032 /* euid egid */
3033 uid = st.st_uid;
3034 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (uid)), attrs);
3035 BLOCK_INPUT;
3036 pw = getpwuid (uid);
3037 UNBLOCK_INPUT;
3038 if (pw)
3039 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3041 gid = st.st_gid;
3042 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (gid)), attrs);
3043 BLOCK_INPUT;
3044 gr = getgrgid (gid);
3045 UNBLOCK_INPUT;
3046 if (gr)
3047 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3049 strcpy (fn, procfn);
3050 procfn_end = fn + strlen (fn);
3051 strcpy (procfn_end, "/psinfo");
3052 fd = emacs_open (fn, O_RDONLY, 0);
3053 if (fd >= 0
3054 && (nread = read (fd, (char*)&pinfo, sizeof (struct psinfo)) > 0))
3056 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (pinfo.pr_ppid)), attrs);
3057 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (pinfo.pr_pgid)), attrs);
3058 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (pinfo.pr_sid)), attrs);
3061 char state_str[2];
3062 state_str[0] = pinfo.pr_lwp.pr_sname;
3063 state_str[1] = '\0';
3064 tem = build_string (state_str);
3065 attrs = Fcons (Fcons (Qstate, tem), attrs);
3068 /* FIXME: missing Qttyname. psinfo.pr_ttydev is a dev_t,
3069 need to get a string from it. */
3071 /* FIXME: missing: Qtpgid */
3073 /* FIXME: missing:
3074 Qminflt
3075 Qmajflt
3076 Qcminflt
3077 Qcmajflt
3079 Qutime
3080 Qcutime
3081 Qstime
3082 Qcstime
3083 Are they available? */
3085 attrs = Fcons (Fcons (Qtime,
3086 list3 (make_number (pinfo.pr_time.tv_sec >> 16),
3087 make_number (pinfo.pr_time.tv_sec & 0xffff),
3088 make_number (pinfo.pr_time.tv_nsec))),
3089 attrs);
3091 attrs = Fcons (Fcons (Qctime,
3092 list3 (make_number (pinfo.pr_ctime.tv_sec >> 16),
3093 make_number (pinfo.pr_ctime.tv_sec & 0xffff),
3094 make_number (pinfo.pr_ctime.tv_nsec))),
3095 attrs);
3097 attrs = Fcons (Fcons (Qpri, make_number (pinfo.pr_lwp.pr_pri)), attrs);
3098 attrs = Fcons (Fcons (Qnice, make_number (pinfo.pr_lwp.pr_nice)), attrs);
3099 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (pinfo.pr_nlwp)), attrs);
3101 attrs = Fcons (Fcons (Qstart,
3102 list3 (make_number (pinfo.pr_start.tv_sec >> 16),
3103 make_number (pinfo.pr_start.tv_sec & 0xffff),
3104 make_number (pinfo.pr_start.tv_nsec))),
3105 attrs);
3106 attrs = Fcons (Fcons (Qvsize, make_fixnum_or_float (pinfo.pr_size)), attrs);
3107 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (pinfo.pr_rssize)), attrs);
3109 /* pr_pctcpu and pr_pctmem are encoded as a fixed point 16 bit number in [0 ... 1]. */
3110 attrs = Fcons (Fcons (Qpcpu, (pinfo.pr_pctcpu * 100.0) / (double)0x8000), attrs);
3111 attrs = Fcons (Fcons (Qpmem, (pinfo.pr_pctmem * 100.0) / (double)0x8000), attrs);
3113 decoded_cmd
3114 = code_convert_string_norecord (make_unibyte_string (pinfo.pr_fname,
3115 strlen (pinfo.pr_fname)),
3116 Vlocale_coding_system, 0);
3117 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
3118 decoded_cmd
3119 = code_convert_string_norecord (make_unibyte_string (pinfo.pr_psargs,
3120 strlen (pinfo.pr_psargs)),
3121 Vlocale_coding_system, 0);
3122 attrs = Fcons (Fcons (Qargs, decoded_cmd), attrs);
3125 if (fd >= 0)
3126 emacs_close (fd);
3128 UNGCPRO;
3129 return attrs;
3132 #elif defined __FreeBSD__
3134 Lisp_Object
3135 system_process_attributes (Lisp_Object pid)
3137 int proc_id;
3138 int pagesize = getpagesize ();
3139 int npages;
3140 int fscale;
3141 struct passwd *pw;
3142 struct group *gr;
3143 char *ttyname;
3144 size_t len;
3145 char args[MAXPATHLEN];
3146 EMACS_TIME t, now;
3148 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID};
3149 struct kinfo_proc proc;
3150 size_t proclen = sizeof proc;
3152 struct gcpro gcpro1, gcpro2;
3153 Lisp_Object attrs = Qnil;
3154 Lisp_Object decoded_comm;
3156 CHECK_NUMBER_OR_FLOAT (pid);
3157 CONS_TO_INTEGER (pid, int, proc_id);
3158 mib[3] = proc_id;
3160 if (sysctl (mib, 4, &proc, &proclen, NULL, 0) != 0)
3161 return attrs;
3163 GCPRO2 (attrs, decoded_comm);
3165 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (proc.ki_uid)), attrs);
3167 BLOCK_INPUT;
3168 pw = getpwuid (proc.ki_uid);
3169 UNBLOCK_INPUT;
3170 if (pw)
3171 attrs = Fcons (Fcons (Quser, build_string (pw->pw_name)), attrs);
3173 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (proc.ki_svgid)), attrs);
3175 BLOCK_INPUT;
3176 gr = getgrgid (proc.ki_svgid);
3177 UNBLOCK_INPUT;
3178 if (gr)
3179 attrs = Fcons (Fcons (Qgroup, build_string (gr->gr_name)), attrs);
3181 decoded_comm = code_convert_string_norecord
3182 (make_unibyte_string (proc.ki_comm, strlen (proc.ki_comm)),
3183 Vlocale_coding_system, 0);
3185 attrs = Fcons (Fcons (Qcomm, decoded_comm), attrs);
3187 char state[2] = {'\0', '\0'};
3188 switch (proc.ki_stat)
3190 case SRUN:
3191 state[0] = 'R';
3192 break;
3194 case SSLEEP:
3195 state[0] = 'S';
3196 break;
3198 case SLOCK:
3199 state[0] = 'D';
3200 break;
3202 case SZOMB:
3203 state[0] = 'Z';
3204 break;
3206 case SSTOP:
3207 state[0] = 'T';
3208 break;
3210 attrs = Fcons (Fcons (Qstate, build_string (state)), attrs);
3213 attrs = Fcons (Fcons (Qppid, make_fixnum_or_float (proc.ki_ppid)), attrs);
3214 attrs = Fcons (Fcons (Qpgrp, make_fixnum_or_float (proc.ki_pgid)), attrs);
3215 attrs = Fcons (Fcons (Qsess, make_fixnum_or_float (proc.ki_sid)), attrs);
3217 BLOCK_INPUT;
3218 ttyname = proc.ki_tdev == NODEV ? NULL : devname (proc.ki_tdev, S_IFCHR);
3219 UNBLOCK_INPUT;
3220 if (ttyname)
3221 attrs = Fcons (Fcons (Qtty, build_string (ttyname)), attrs);
3223 attrs = Fcons (Fcons (Qtpgid, make_fixnum_or_float (proc.ki_tpgid)), attrs);
3224 attrs = Fcons (Fcons (Qminflt, make_fixnum_or_float (proc.ki_rusage.ru_minflt)), attrs);
3225 attrs = Fcons (Fcons (Qmajflt, make_fixnum_or_float (proc.ki_rusage.ru_majflt)), attrs);
3226 attrs = Fcons (Fcons (Qcminflt, make_number (proc.ki_rusage_ch.ru_minflt)), attrs);
3227 attrs = Fcons (Fcons (Qcmajflt, make_number (proc.ki_rusage_ch.ru_majflt)), attrs);
3229 #define TIMELIST(ts) \
3230 list3 (make_number (EMACS_SECS (ts) >> 16 & 0xffff), \
3231 make_number (EMACS_SECS (ts) & 0xffff), \
3232 make_number (EMACS_USECS (ts)))
3234 attrs = Fcons (Fcons (Qutime, TIMELIST (proc.ki_rusage.ru_utime)), attrs);
3235 attrs = Fcons (Fcons (Qstime, TIMELIST (proc.ki_rusage.ru_stime)), attrs);
3236 EMACS_ADD_TIME (t, proc.ki_rusage.ru_utime, proc.ki_rusage.ru_stime);
3237 attrs = Fcons (Fcons (Qtime, TIMELIST (t)), attrs);
3239 attrs = Fcons (Fcons (Qcutime, TIMELIST (proc.ki_rusage_ch.ru_utime)), attrs);
3240 attrs = Fcons (Fcons (Qcstime, TIMELIST (proc.ki_rusage_ch.ru_utime)), attrs);
3241 EMACS_ADD_TIME (t, proc.ki_rusage_ch.ru_utime, proc.ki_rusage_ch.ru_stime);
3242 attrs = Fcons (Fcons (Qctime, TIMELIST (t)), attrs);
3244 attrs = Fcons (Fcons (Qthcount, make_fixnum_or_float (proc.ki_numthreads)),
3245 attrs);
3246 attrs = Fcons (Fcons (Qpri, make_number (proc.ki_pri.pri_native)), attrs);
3247 attrs = Fcons (Fcons (Qnice, make_number (proc.ki_nice)), attrs);
3248 attrs = Fcons (Fcons (Qstart, TIMELIST (proc.ki_start)), attrs);
3249 attrs = Fcons (Fcons (Qvsize, make_number (proc.ki_size >> 10)), attrs);
3250 attrs = Fcons (Fcons (Qrss, make_number (proc.ki_rssize * pagesize >> 10)),
3251 attrs);
3253 EMACS_GET_TIME (now);
3254 EMACS_SUB_TIME (t, now, proc.ki_start);
3255 attrs = Fcons (Fcons (Qetime, TIMELIST (t)), attrs);
3257 #undef TIMELIST
3259 len = sizeof fscale;
3260 if (sysctlbyname ("kern.fscale", &fscale, &len, NULL, 0) == 0)
3262 double pcpu;
3263 fixpt_t ccpu;
3264 len = sizeof ccpu;
3265 if (sysctlbyname ("kern.ccpu", &ccpu, &len, NULL, 0) == 0)
3267 pcpu = (100.0 * proc.ki_pctcpu / fscale
3268 / (1 - exp (proc.ki_swtime * log ((double) ccpu / fscale))));
3269 attrs = Fcons (Fcons (Qpcpu, make_fixnum_or_float (pcpu)), attrs);
3273 len = sizeof npages;
3274 if (sysctlbyname ("hw.availpages", &npages, &len, NULL, 0) == 0)
3276 double pmem = (proc.ki_flag & P_INMEM
3277 ? 100.0 * proc.ki_rssize / npages
3278 : 0);
3279 attrs = Fcons (Fcons (Qpmem, make_fixnum_or_float (pmem)), attrs);
3282 mib[2] = KERN_PROC_ARGS;
3283 len = MAXPATHLEN;
3284 if (sysctl (mib, 4, args, &len, NULL, 0) == 0)
3286 int i;
3287 for (i = 0; i < len; i++)
3289 if (! args[i] && i < len - 1)
3290 args[i] = ' ';
3293 decoded_comm =
3294 (code_convert_string_norecord
3295 (make_unibyte_string (args, strlen (args)),
3296 Vlocale_coding_system, 0));
3298 attrs = Fcons (Fcons (Qargs, decoded_comm), attrs);
3301 UNGCPRO;
3302 return attrs;
3305 /* The WINDOWSNT implementation is in w32.c.
3306 The MSDOS implementation is in dosfns.c. */
3307 #elif !defined (WINDOWSNT) && !defined (MSDOS)
3309 Lisp_Object
3310 system_process_attributes (Lisp_Object pid)
3312 return Qnil;
3315 #endif /* !defined (WINDOWSNT) */