d6290d8c956f7a7a2edd4e1d0663fe7005d6b3a5
[sbcl.git] / src / code / unix.lisp
1 ;;;; This file contains Unix support that SBCL needs to implement
2 ;;;; itself. It's derived from Peter Van Eynde's unix-glibc2.lisp for
3 ;;;; CMU CL, which was derived from CMU CL unix.lisp 1.56. But those
4 ;;;; files aspired to be complete Unix interfaces exported to the end
5 ;;;; user, while this file aims to be as simple as possible and is not
6 ;;;; intended for the end user.
7 ;;;;
8 ;;;; FIXME: The old CMU CL unix.lisp code was implemented as hand
9 ;;;; transcriptions from Unix headers into Lisp. It appears that this was as
10 ;;;; unmaintainable in practice as you'd expect in theory, so I really really
11 ;;;; don't want to do that. It'd be good to implement the various system calls
12 ;;;; as C code implemented using the Unix header files, and have their
13 ;;;; interface back to SBCL code be characterized by things like "32-bit-wide
14 ;;;; int" which are already in the interface between the runtime
15 ;;;; executable and the SBCL lisp code.
16
17 ;;;; This software is part of the SBCL system. See the README file for
18 ;;;; more information.
19 ;;;;
20 ;;;; This software is derived from the CMU CL system, which was
21 ;;;; written at Carnegie Mellon University and released into the
22 ;;;; public domain. The software is in the public domain and is
23 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
24 ;;;; files for more information.
25
26 (in-package "SB!UNIX")
27
28 (/show0 "unix.lisp 21")
29
30 (defmacro def-enum (inc cur &rest names)
31   (flet ((defform (name)
32            (prog1 (when name `(defconstant ,name ,cur))
33              (setf cur (funcall inc cur 1)))))
34     `(progn ,@(mapcar #'defform names))))
35
36 ;;; Given a C-level zero-terminated array of C strings, return a
37 ;;; corresponding Lisp-level list of SIMPLE-STRINGs.
38 (defun c-strings->string-list (c-strings)
39   (declare (type (alien (* c-string)) c-strings))
40   (let ((reversed-result nil))
41     (dotimes (i most-positive-fixnum (error "argh! can't happen"))
42       (declare (type index i))
43       (let ((c-string (deref c-strings i)))
44         (if c-string
45             (push c-string reversed-result)
46             (return (nreverse reversed-result)))))))
47 \f
48 ;;;; Lisp types used by syscalls
49
50 (deftype unix-pathname () #!-win32 'simple-base-string #!+win32 'simple-string)
51 (deftype unix-fd () `(integer 0 ,most-positive-fixnum))
52
53 (deftype unix-file-mode () '(unsigned-byte 32))
54 (deftype unix-pid () '(unsigned-byte 32))
55 (deftype unix-uid () '(unsigned-byte 32))
56 (deftype unix-gid () '(unsigned-byte 32))
57 \f
58 ;;;; system calls
59
60 (/show0 "unix.lisp 74")
61
62 ;;; FIXME: The various FOO-SYSCALL-BAR macros, and perhaps some other
63 ;;; macros in this file, are only used in this file, and could be
64 ;;; implemented using SB!XC:DEFMACRO wrapped in EVAL-WHEN.
65
66 (defmacro syscall ((name &rest arg-types) success-form &rest args)
67   `(locally
68     (declare (optimize (sb!c::float-accuracy 0)))
69     (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
70                                 ,@args)))
71       (if (minusp result)
72           (values nil (get-errno))
73           ,success-form))))
74
75 ;;; This is like SYSCALL, but if it fails, signal an error instead of
76 ;;; returning error codes. Should only be used for syscalls that will
77 ;;; never really get an error.
78 (defmacro syscall* ((name &rest arg-types) success-form &rest args)
79   `(locally
80     (declare (optimize (sb!c::float-accuracy 0)))
81     (let ((result (alien-funcall (extern-alien ,name (function int ,@arg-types))
82                                  ,@args)))
83       (if (minusp result)
84           (error "Syscall ~A failed: ~A" ,name (strerror))
85           ,success-form))))
86
87 (/show0 "unix.lisp 109")
88
89 (defmacro void-syscall ((name &rest arg-types) &rest args)
90   `(syscall (,name ,@arg-types) (values t 0) ,@args))
91
92 (defmacro int-syscall ((name &rest arg-types) &rest args)
93   `(syscall (,name ,@arg-types) (values result 0) ,@args))
94
95 (defmacro with-restarted-syscall ((&optional (value (gensym))
96                                              (errno (gensym)))
97                                   syscall-form &rest body)
98   #!+sb-doc
99   "Evaluate BODY with VALUE and ERRNO bound to the return values of
100 SYSCALL-FORM. Repeat evaluation of SYSCALL-FORM if it is interrupted."
101   `(let (,value ,errno)
102      (loop (multiple-value-setq (,value ,errno)
103              ,syscall-form)
104         (unless #!-win32 (eql ,errno sb!unix:eintr) #!+win32 nil
105           (return (values ,value ,errno))))
106      ,@body))
107
108 #!+win32
109 (progn
110   (defconstant o_rdonly  0)
111   (defconstant o_wronly  1)
112   (defconstant o_rdwr    2)
113   (defconstant o_creat  #x100)
114   (defconstant o_trunc  #x200)
115   (defconstant o_append #x008)
116   (defconstant o_excl   #x400)
117   (defconstant enoent 2)
118   (defconstant eexist 17)
119   (defconstant espipe 29)
120   (defconstant o_binary #x8000)
121   (defconstant s-ifmt #xf000)
122   (defconstant s-ifdir #x4000)
123   (defconstant s-ifreg #x8000)
124   (define-alien-type ino-t short)
125   (define-alien-type time-t long)
126   (define-alien-type off-t long)
127   (define-alien-type size-t long)
128   (define-alien-type mode-t unsigned-short)
129
130   ;; For stat-wrapper hack (different-type or non-existing win32 fields).
131   (define-alien-type nlink-t short)
132   (define-alien-type uid-t short)
133   (define-alien-type gid-t short))
134 \f
135 ;;;; hacking the Unix environment
136
137 #!-win32
138 (define-alien-routine ("getenv" posix-getenv) c-string
139   "Return the \"value\" part of the environment string \"name=value\" which
140    corresponds to NAME, or NIL if there is none."
141   (name c-string))
142 \f
143 ;;; from stdio.h
144
145 ;;; Rename the file with string NAME1 to the string NAME2. NIL and an
146 ;;; error code is returned if an error occurs.
147 #!-win32
148 (defun unix-rename (name1 name2)
149   (declare (type unix-pathname name1 name2))
150   (void-syscall ("rename" c-string c-string) name1 name2))
151 \f
152 ;;; from sys/types.h and gnu/types.h
153
154 (/show0 "unix.lisp 220")
155
156 ;;; FIXME: We shouldn't hand-copy types from header files into Lisp
157 ;;; like this unless we have extreme provocation. Reading directories
158 ;;; is not extreme enough, since it doesn't need to be blindingly
159 ;;; fast: we can just implement those functions in C as a wrapper
160 ;;; layer.
161 (define-alien-type fd-mask unsigned-long)
162
163 (eval-when (:compile-toplevel :load-toplevel :execute)
164   (defconstant fd-setsize 1024))
165
166 (define-alien-type nil
167   (struct fd-set
168           (fds-bits (array fd-mask #.(/ fd-setsize
169                                         sb!vm:n-machine-word-bits)))))
170
171 (/show0 "unix.lisp 304")
172 \f
173 \f
174 ;;;; fcntl.h
175 ;;;;
176 ;;;; POSIX Standard: 6.5 File Control Operations        <fcntl.h>
177
178 ;;; Open the file whose pathname is specified by PATH for reading
179 ;;; and/or writing as specified by the FLAGS argument. Various FLAGS
180 ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h.
181 ;;;
182 ;;; If the O_CREAT flag is specified, then the file is created with a
183 ;;; permission of argument MODE if the file doesn't exist. An integer
184 ;;; file descriptor is returned by UNIX-OPEN.
185 (defun unix-open (path flags mode)
186   (declare (type unix-pathname path)
187            (type fixnum flags)
188            (type unix-file-mode mode))
189   (int-syscall ("open" c-string int int) path (logior #!+win32 o_binary flags) mode))
190
191 ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file
192 ;;; associated with it.
193 (/show0 "unix.lisp 391")
194 (defun unix-close (fd)
195   (declare (type unix-fd fd))
196   (void-syscall ("close" int) fd))
197 \f
198 ;;;; timebits.h
199
200 ;; A time value that is accurate to the nearest
201 ;; microsecond but also has a range of years.
202 (define-alien-type nil
203   (struct timeval
204           (tv-sec time-t)               ; seconds
205           (tv-usec time-t)))            ; and microseconds
206 \f
207 ;;;; resourcebits.h
208
209 (defconstant rusage_self 0) ; the calling process
210 (defconstant rusage_children -1) ; terminated child processes
211 (defconstant rusage_both -2)
212
213 (define-alien-type nil
214   (struct rusage
215     (ru-utime (struct timeval))     ; user time used
216     (ru-stime (struct timeval))     ; system time used.
217     (ru-maxrss long)                ; maximum resident set size (in kilobytes)
218     (ru-ixrss long)                 ; integral shared memory size
219     (ru-idrss long)                 ; integral unshared data size
220     (ru-isrss long)                 ; integral unshared stack size
221     (ru-minflt long)                ; page reclaims
222     (ru-majflt long)                ; page faults
223     (ru-nswap long)                 ; swaps
224     (ru-inblock long)               ; block input operations
225     (ru-oublock long)               ; block output operations
226     (ru-msgsnd long)                ; messages sent
227     (ru-msgrcv long)                ; messages received
228     (ru-nsignals long)              ; signals received
229     (ru-nvcsw long)                 ; voluntary context switches
230     (ru-nivcsw long)))              ; involuntary context switches
231 \f
232 ;;;; unistd.h
233
234 ;;; Given a file path (a string) and one of four constant modes,
235 ;;; return T if the file is accessible with that mode and NIL if not.
236 ;;; When NIL, also return an errno value with NIL which tells why the
237 ;;; file was not accessible.
238 ;;;
239 ;;; The access modes are:
240 ;;;   r_ok     Read permission.
241 ;;;   w_ok     Write permission.
242 ;;;   x_ok     Execute permission.
243 ;;;   f_ok     Presence of file.
244
245 ;;; In Windows, the MODE argument to access is defined in terms of
246 ;;; literal magic numbers---there are no constants to grovel.  X_OK
247 ;;; is not defined.
248 #!+win32
249 (progn
250   (defconstant f_ok 0)
251   (defconstant w_ok 2)
252   (defconstant r_ok 4))
253
254 (defun unix-access (path mode)
255   (declare (type unix-pathname path)
256            (type (mod 8) mode))
257   (void-syscall ("access" c-string int) path mode))
258
259 ;;; values for the second argument to UNIX-LSEEK
260 (defconstant l_set 0) ; to set the file pointer
261 (defconstant l_incr 1) ; to increment the file pointer
262 (defconstant l_xtnd 2) ; to extend the file size
263
264 ;;; Is a stream interactive?
265 (defun unix-isatty (fd)
266   (declare (type unix-fd fd))
267   (int-syscall ("isatty" int) fd))
268
269 (defun unix-lseek (fd offset whence)
270   "Unix-lseek accepts a file descriptor and moves the file pointer by
271    OFFSET octets.  Whence can be any of the following:
272
273    L_SET        Set the file pointer.
274    L_INCR       Increment the file pointer.
275    L_XTND       Extend the file size.
276   "
277   (declare (type unix-fd fd)
278            (type (integer 0 2) whence))
279   (let ((result (alien-funcall (extern-alien "lseek" (function off-t int off-t int))
280                  fd offset whence)))
281     (if (minusp result )
282         (values nil (get-errno))
283       (values result 0))))
284
285 ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read.
286 ;;; It attempts to read len bytes from the device associated with fd
287 ;;; and store them into the buffer. It returns the actual number of
288 ;;; bytes read.
289 (defun unix-read (fd buf len)
290   (declare (type unix-fd fd)
291            (type (unsigned-byte 32) len))
292
293   (int-syscall ("read" int (* char) int) fd buf len))
294
295 ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the
296 ;;; length to write. It attempts to write len bytes to the device
297 ;;; associated with fd from the buffer starting at offset. It returns
298 ;;; the actual number of bytes written.
299 (defun unix-write (fd buf offset len)
300   (declare (type unix-fd fd)
301            (type (unsigned-byte 32) offset len))
302   (int-syscall ("write" int (* char) int)
303                fd
304                (with-alien ((ptr (* char) (etypecase buf
305                                             ((simple-array * (*))
306                                              (vector-sap buf))
307                                             (system-area-pointer
308                                              buf))))
309                  (addr (deref ptr offset)))
310                len))
311
312 ;;; Set up a unix-piping mechanism consisting of an input pipe and an
313 ;;; output pipe. Return two values: if no error occurred the first
314 ;;; value is the pipe to be read from and the second is can be written
315 ;;; to. If an error occurred the first value is NIL and the second the
316 ;;; unix error code.
317 #!-win32(defun unix-pipe ()
318   (with-alien ((fds (array int 2)))
319     (syscall ("pipe" (* int))
320              (values (deref fds 0) (deref fds 1))
321              (cast fds (* int)))))
322 #!+win32(defun msvcrt-raw-pipe (fds size mode)
323     (syscall ("_pipe" (* int) int int)
324              (values (deref fds 0) (deref fds 1))
325              (cast fds (* int)) size mode))
326 #!+win32(defun unix-pipe ()
327   (with-alien ((fds (array int 2)))
328               (msvcrt-raw-pipe fds 256 o_binary)))
329
330 ;; Windows mkdir() doesn't take the mode argument. It's cdecl, so we could
331 ;; actually call it passing the mode argument, but some sharp-eyed reader
332 ;; would put five and twenty-seven together and ask us about it, so...
333 ;;    -- AB, 2005-12-27
334 #!-win32
335 (defun unix-mkdir (name mode)
336   (declare (type unix-pathname name)
337            (type unix-file-mode mode)
338            #!+win32 (ignore mode))
339   (void-syscall ("mkdir" c-string #!-win32 int) name #!-win32 mode))
340
341 ;;; Given a C char* pointer allocated by malloc(), free it and return a
342 ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL).
343 (defun newcharstar-string (newcharstar)
344   (declare (type (alien (* char)) newcharstar))
345   (if (null-alien newcharstar)
346       nil
347       (prog1
348           (cast newcharstar c-string)
349         (free-alien newcharstar))))
350
351 ;;; Return the Unix current directory as a SIMPLE-STRING, in the
352 ;;; style returned by getcwd() (no trailing slash character).
353 #!-win32
354 (defun posix-getcwd ()
355   ;; This implementation relies on a BSD/Linux extension to getcwd()
356   ;; behavior, automatically allocating memory when a null buffer
357   ;; pointer is used. On a system which doesn't support that
358   ;; extension, it'll have to be rewritten somehow.
359   ;;
360   ;; SunOS and OSF/1 provide almost as useful an extension: if given a null
361   ;; buffer pointer, it will automatically allocate size space. The
362   ;; KLUDGE in this solution arises because we have just read off
363   ;; PATH_MAX+1 from the Solaris header files and stuck it in here as
364   ;; a constant. Going the grovel_headers route doesn't seem to be
365   ;; helpful, either, as Solaris doesn't export PATH_MAX from
366   ;; unistd.h.
367   ;;
368   ;; FIXME: The (,stub,) nastiness produces an error message about a
369   ;; comma not inside a backquote. This error has absolutely nothing
370   ;; to do with the actual meaning of the error (and little to do with
371   ;; its location, either).
372   #!-(or linux openbsd freebsd netbsd sunos osf1 darwin win32) (,stub,)
373   #!+(or linux openbsd freebsd netbsd sunos osf1 darwin win32)
374   (or (newcharstar-string (alien-funcall (extern-alien "getcwd"
375                                                        (function (* char)
376                                                                  (* char)
377                                                                  size-t))
378                                          nil
379                                          #!+(or linux openbsd freebsd netbsd darwin win32) 0
380                                          #!+(or sunos osf1) 1025))
381       (simple-perror "getcwd")))
382
383 ;;; Return the Unix current directory as a SIMPLE-STRING terminated
384 ;;; by a slash character.
385 (defun posix-getcwd/ ()
386   (concatenate 'string (posix-getcwd) "/"))
387
388 ;;; Duplicate an existing file descriptor (given as the argument) and
389 ;;; return it. If FD is not a valid file descriptor, NIL and an error
390 ;;; number are returned.
391 (defun unix-dup (fd)
392   (declare (type unix-fd fd))
393   (int-syscall ("dup" int) fd))
394
395 ;;; Terminate the current process with an optional error code. If
396 ;;; successful, the call doesn't return. If unsuccessful, the call
397 ;;; returns NIL and an error number.
398 (defun unix-exit (&optional (code 0))
399   (declare (type (signed-byte 32) code))
400   (void-syscall ("exit" int) code))
401
402 ;;; Return the process id of the current process.
403 (define-alien-routine ("getpid" unix-getpid) int)
404
405 ;;; Return the real user id associated with the current process.
406 #!-win32
407 (define-alien-routine ("getuid" unix-getuid) int)
408
409 ;;; Translate a user id into a login name.
410 #!-win32
411 (defun uid-username (uid)
412   (or (newcharstar-string (alien-funcall (extern-alien "uid_username"
413                                                        (function (* char) int))
414                                          uid))
415       (error "found no match for Unix uid=~S" uid)))
416
417 ;;; Return the namestring of the home directory, being careful to
418 ;;; include a trailing #\/
419 #!-win32
420 (defun uid-homedir (uid)
421   (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir"
422                                                        (function (* char) int))
423                                          uid))
424       (error "failed to resolve home directory for Unix uid=~S" uid)))
425
426 ;;; Invoke readlink(2) on the file name specified by PATH. Return
427 ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on
428 ;;; failure.
429 #!-win32
430 (defun unix-readlink (path)
431   (declare (type unix-pathname path))
432   (with-alien ((ptr (* char)
433                     (alien-funcall (extern-alien
434                                     "wrapped_readlink"
435                                     (function (* char) c-string))
436                                    path)))
437     (if (null-alien ptr)
438         (values nil (get-errno))
439         (multiple-value-prog1
440             (values (with-alien ((c-string c-string ptr)) c-string)
441                     nil)
442           (free-alien ptr)))))
443 #!+win32
444 ;; Win32 doesn't do links, but something likes to call this anyway.
445 ;; Something in this file, no less. But it only takes one result, so...
446 (defun unix-readlink (path)
447   (declare (ignore path))
448   nil)
449
450 ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that
451 ;;; name and the file if this is the last link.
452 (defun unix-unlink (name)
453   (declare (type unix-pathname name))
454   (void-syscall ("unlink" c-string) name))
455
456 ;;; Return the name of the host machine as a string.
457 #!-win32
458 (defun unix-gethostname ()
459   (with-alien ((buf (array char 256)))
460     (syscall ("gethostname" (* char) int)
461              (cast buf c-string)
462              (cast buf (* char)) 256)))
463
464 #!-win32
465 (defun unix-setsid ()
466   (int-syscall ("setsid")))
467
468 ;;;; sys/ioctl.h
469
470 ;;; UNIX-IOCTL performs a variety of operations on open i/o
471 ;;; descriptors. See the UNIX Programmer's Manual for more
472 ;;; information.
473 #!-win32
474 (defun unix-ioctl (fd cmd arg)
475   (declare (type unix-fd fd)
476            (type (signed-byte 32) cmd))
477   (void-syscall ("ioctl" int int (* char)) fd cmd arg))
478 \f
479 ;;;; sys/resource.h
480
481 ;;; FIXME: All we seem to need is the RUSAGE_SELF version of this.
482 ;;;
483 ;;; This is like getrusage(2), except it returns only the system and
484 ;;; user time, and returns the seconds and microseconds as separate
485 ;;; values.
486 #!-sb-fluid (declaim (inline unix-fast-getrusage))
487 #!-win32
488 (defun unix-fast-getrusage (who)
489   (declare (values (member t)
490                    (unsigned-byte 31) (integer 0 1000000)
491                    (unsigned-byte 31) (integer 0 1000000)))
492   (with-alien ((usage (struct rusage)))
493     (syscall* ("getrusage" int (* (struct rusage)))
494               (values t
495                       (slot (slot usage 'ru-utime) 'tv-sec)
496                       (slot (slot usage 'ru-utime) 'tv-usec)
497                       (slot (slot usage 'ru-stime) 'tv-sec)
498                       (slot (slot usage 'ru-stime) 'tv-usec))
499               who (addr usage))))
500
501 ;;; Return information about the resource usage of the process
502 ;;; specified by WHO. WHO can be either the current process
503 ;;; (rusage_self) or all of the terminated child processes
504 ;;; (rusage_children). NIL and an error number is returned if the call
505 ;;; fails.
506 #!-win32
507 (defun unix-getrusage (who)
508   (with-alien ((usage (struct rusage)))
509     (syscall ("getrusage" int (* (struct rusage)))
510               (values t
511                       (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000)
512                          (slot (slot usage 'ru-utime) 'tv-usec))
513                       (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000)
514                          (slot (slot usage 'ru-stime) 'tv-usec))
515                       (slot usage 'ru-maxrss)
516                       (slot usage 'ru-ixrss)
517                       (slot usage 'ru-idrss)
518                       (slot usage 'ru-isrss)
519                       (slot usage 'ru-minflt)
520                       (slot usage 'ru-majflt)
521                       (slot usage 'ru-nswap)
522                       (slot usage 'ru-inblock)
523                       (slot usage 'ru-oublock)
524                       (slot usage 'ru-msgsnd)
525                       (slot usage 'ru-msgrcv)
526                       (slot usage 'ru-nsignals)
527                       (slot usage 'ru-nvcsw)
528                       (slot usage 'ru-nivcsw))
529               who (addr usage))))
530 \f
531 ;;;; sys/select.h
532
533 ;;;; FIXME: Why have both UNIX-SELECT and UNIX-FAST-SELECT?
534
535 ;;; Perform the UNIX select(2) system call.
536 (declaim (inline unix-fast-select)) ; (used to be a macro in CMU CL)
537 (defun unix-fast-select (num-descriptors
538                          read-fds write-fds exception-fds
539                          timeout-secs &optional (timeout-usecs 0))
540   (declare (type (integer 0 #.fd-setsize) num-descriptors)
541            (type (or (alien (* (struct fd-set))) null)
542                  read-fds write-fds exception-fds)
543            (type (or null (unsigned-byte 31)) timeout-secs)
544            (type (unsigned-byte 31) timeout-usecs))
545   ;; FIXME: CMU CL had
546   ;;   (declare (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
547   ;; here. Is that important for SBCL? If so, why? Profiling might tell us..
548   (with-alien ((tv (struct timeval)))
549     (when timeout-secs
550       (setf (slot tv 'tv-sec) timeout-secs)
551       (setf (slot tv 'tv-usec) timeout-usecs))
552     (int-syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
553                   (* (struct fd-set)) (* (struct timeval)))
554                  num-descriptors read-fds write-fds exception-fds
555                  (if timeout-secs (alien-sap (addr tv)) (int-sap 0)))))
556
557 ;;; UNIX-SELECT accepts sets of file descriptors and waits for an event
558 ;;; to happen on one of them or to time out.
559 (defmacro num-to-fd-set (fdset num)
560   `(if (fixnump ,num)
561        (progn
562          (setf (deref (slot ,fdset 'fds-bits) 0) ,num)
563          ,@(loop for index upfrom 1 below (/ fd-setsize
564                                              sb!vm:n-machine-word-bits)
565              collect `(setf (deref (slot ,fdset 'fds-bits) ,index) 0)))
566        (progn
567          ,@(loop for index upfrom 0 below (/ fd-setsize
568                                              sb!vm:n-machine-word-bits)
569              collect `(setf (deref (slot ,fdset 'fds-bits) ,index)
570                             (ldb (byte sb!vm:n-machine-word-bits
571                                        ,(* index sb!vm:n-machine-word-bits))
572                                  ,num))))))
573
574 (defmacro fd-set-to-num (nfds fdset)
575   `(if (<= ,nfds sb!vm:n-machine-word-bits)
576        (deref (slot ,fdset 'fds-bits) 0)
577        (+ ,@(loop for index upfrom 0 below (/ fd-setsize
578                                               sb!vm:n-machine-word-bits)
579               collect `(ash (deref (slot ,fdset 'fds-bits) ,index)
580                             ,(* index sb!vm:n-machine-word-bits))))))
581
582 ;;; Examine the sets of descriptors passed as arguments to see whether
583 ;;; they are ready for reading and writing. See the UNIX Programmer's
584 ;;; Manual for more information.
585 (defun unix-select (nfds rdfds wrfds xpfds to-secs &optional (to-usecs 0))
586   (declare (type (integer 0 #.fd-setsize) nfds)
587            (type unsigned-byte rdfds wrfds xpfds)
588            (type (or (unsigned-byte 31) null) to-secs)
589            (type (unsigned-byte 31) to-usecs)
590            (optimize (speed 3) (safety 0) (inhibit-warnings 3)))
591   (with-alien ((tv (struct timeval))
592                (rdf (struct fd-set))
593                (wrf (struct fd-set))
594                (xpf (struct fd-set)))
595     (when to-secs
596       (setf (slot tv 'tv-sec) to-secs)
597      (setf (slot tv 'tv-usec) to-usecs))
598     (num-to-fd-set rdf rdfds)
599     (num-to-fd-set wrf wrfds)
600     (num-to-fd-set xpf xpfds)
601     (macrolet ((frob (lispvar alienvar)
602                  `(if (zerop ,lispvar)
603                       (int-sap 0)
604                       (alien-sap (addr ,alienvar)))))
605       (syscall ("select" int (* (struct fd-set)) (* (struct fd-set))
606                 (* (struct fd-set)) (* (struct timeval)))
607                (values result
608                        (fd-set-to-num nfds rdf)
609                        (fd-set-to-num nfds wrf)
610                        (fd-set-to-num nfds xpf))
611                nfds (frob rdfds rdf) (frob wrfds wrf) (frob xpfds xpf)
612                (if to-secs (alien-sap (addr tv)) (int-sap 0))))))
613 \f
614 ;;;; sys/stat.h
615
616 ;;; This is a structure defined in src/runtime/wrap.c, to look
617 ;;; basically like "struct stat" according to stat(2). It may not
618 ;;; actually correspond to the real in-memory stat structure that the
619 ;;; syscall uses, and that's OK. Linux in particular is packed full of
620 ;;; stat macros, and trying to keep Lisp code in correspondence with
621 ;;; it is more pain than it's worth, so we just let our C runtime
622 ;;; synthesize a nice consistent structure for us.
623 ;;;
624 ;;; Note that st-dev is a long, not a dev-t. This is because dev-t on
625 ;;; linux 32 bit archs is a 64 bit quantity, but alien doesn't support
626 ;;; those. We don't actually access that field anywhere, though, so
627 ;;; until we can get 64 bit alien support it'll do. Also note that
628 ;;; st_size is a long, not an off-t, because off-t is a 64-bit
629 ;;; quantity on Alpha. And FIXME: "No one would want a file length
630 ;;; longer than 32 bits anyway, right?":-|
631 (define-alien-type nil
632   (struct wrapped_stat
633     #!-mips
634     (st-dev unsigned-int)              ; would be dev-t in a real stat
635     #!+mips
636     (st-dev unsigned-long)             ; this is _not_ a dev-t on mips
637     (st-ino ino-t)
638     (st-mode mode-t)
639     (st-nlink nlink-t)
640     (st-uid uid-t)
641     (st-gid gid-t)
642     #!-mips
643     (st-rdev unsigned-int)             ; would be dev-t in a real stat
644     #!+mips
645     (st-rdev unsigned-long)             ; this is _not_ a dev-t on mips
646     #!-mips
647     (st-size unsigned-int)              ; would be off-t in a real stat
648     #!+mips
649     (st-size off-t)
650     (st-blksize unsigned-long)
651     (st-blocks unsigned-long)
652     (st-atime time-t)
653     (st-mtime time-t)
654     (st-ctime time-t)))
655
656 ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2)
657 ;;; family of Unix system calls
658 ;;;
659 ;;; FIXME: I think this should probably not be INLINE. However, when
660 ;;; this was not inline, it seemed to cause memory corruption
661 ;;; problems. My first guess is that it's a bug in the FFI code, where
662 ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped
663 ;;; around a call to a function returning >10 values. But I didn't try
664 ;;; to figure it out, just inlined it as a quick fix. Perhaps someone
665 ;;; who's motivated to debug the FFI code can go over the DISASSEMBLE
666 ;;; output in the not-inlined case and see whether there's a problem,
667 ;;; and maybe even find a fix..
668 (declaim (inline %extract-stat-results))
669 (defun %extract-stat-results (wrapped-stat)
670   (declare (type (alien (* (struct wrapped_stat))) wrapped-stat))
671   (values t
672           (slot wrapped-stat 'st-dev)
673           (slot wrapped-stat 'st-ino)
674           (slot wrapped-stat 'st-mode)
675           (slot wrapped-stat 'st-nlink)
676           (slot wrapped-stat 'st-uid)
677           (slot wrapped-stat 'st-gid)
678           (slot wrapped-stat 'st-rdev)
679           (slot wrapped-stat 'st-size)
680           (slot wrapped-stat 'st-atime)
681           (slot wrapped-stat 'st-mtime)
682           (slot wrapped-stat 'st-ctime)
683           (slot wrapped-stat 'st-blksize)
684           (slot wrapped-stat 'st-blocks)))
685
686 ;;; Unix system calls in the stat(2) family are handled by calls to
687 ;;; C-level wrapper functions which copy all the raw "struct stat"
688 ;;; slots into the system-independent wrapped_stat format.
689 ;;;    stat(2) <->  stat_wrapper()
690 ;;;   fstat(2) <-> fstat_wrapper()
691 ;;;   lstat(2) <-> lstat_wrapper()
692 (defun unix-stat (name)
693   (declare (type unix-pathname name))
694   (with-alien ((buf (struct wrapped_stat)))
695     (syscall ("stat_wrapper" c-string (* (struct wrapped_stat)))
696              (%extract-stat-results (addr buf))
697              name (addr buf))))
698 (defun unix-lstat (name)
699   (declare (type unix-pathname name))
700   (with-alien ((buf (struct wrapped_stat)))
701     (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat)))
702              (%extract-stat-results (addr buf))
703              name (addr buf))))
704 (defun unix-fstat (fd)
705   (declare (type unix-fd fd))
706   (with-alien ((buf (struct wrapped_stat)))
707     (syscall ("fstat_wrapper" int (* (struct wrapped_stat)))
708              (%extract-stat-results (addr buf))
709              fd (addr buf))))
710 \f
711 ;;;; time.h
712
713 ;; the POSIX.4 structure for a time value. This is like a "struct
714 ;; timeval" but has nanoseconds instead of microseconds.
715 (define-alien-type nil
716     (struct timespec
717             (tv-sec long)   ; seconds
718             (tv-nsec long))) ; nanoseconds
719
720 ;; used by other time functions
721 (define-alien-type nil
722     (struct tm
723             (tm-sec int)   ; Seconds.   [0-60] (1 leap second)
724             (tm-min int)   ; Minutes.   [0-59]
725             (tm-hour int)  ; Hours.     [0-23]
726             (tm-mday int)  ; Day.       [1-31]
727             (tm-mon int)   ; Month.     [0-11]
728             (tm-year int)  ; Year - 1900.
729             (tm-wday int)  ; Day of week. [0-6]
730             (tm-yday int)  ; Days in year. [0-365]
731             (tm-isdst int) ; DST.       [-1/0/1]
732             (tm-gmtoff long) ;  Seconds east of UTC.
733             (tm-zone c-string))) ; Timezone abbreviation.
734
735 (define-alien-routine get-timezone sb!alien:void
736   (when sb!alien:long :in)
737   (seconds-west sb!alien:int :out)
738   (daylight-savings-p sb!alien:boolean :out))
739
740 #!-win32
741 (defun nanosleep (secs nsecs)
742   (with-alien ((req (struct timespec))
743                (rem (struct timespec)))
744     (setf (slot req 'tv-sec) secs)
745     (setf (slot req 'tv-nsec) nsecs)
746     (loop while (eql sb!unix:eintr
747                      (nth-value 1
748                                 (int-syscall ("nanosleep" (* (struct timespec))
749                                                           (* (struct timespec)))
750                                              (addr req) (addr rem))))
751        do (rotatef req rem))))
752
753 (defun unix-get-seconds-west (secs)
754   (multiple-value-bind (ignore seconds dst) (get-timezone secs)
755     (declare (ignore ignore) (ignore dst))
756     (values seconds)))
757 \f
758 ;;;; sys/time.h
759
760 ;;; Structure crudely representing a timezone. KLUDGE: This is
761 ;;; obsolete and should never be used.
762 (define-alien-type nil
763   (struct timezone
764     (tz-minuteswest int)                ; minutes west of Greenwich
765     (tz-dsttime int)))                  ; type of dst correction
766
767 ;;; If it works, UNIX-GETTIMEOFDAY returns 5 values: T, the seconds
768 ;;; and microseconds of the current time of day, the timezone (in
769 ;;; minutes west of Greenwich), and a daylight-savings flag. If it
770 ;;; doesn't work, it returns NIL and the errno.
771 #!-sb-fluid (declaim (inline unix-gettimeofday))
772 (defun unix-gettimeofday ()
773   (with-alien ((tv (struct timeval))
774                (tz (struct timezone)))
775     (syscall* ("gettimeofday" (* (struct timeval))
776                               (* (struct timezone)))
777               (values t
778                       (slot tv 'tv-sec)
779                       (slot tv 'tv-usec)
780                       (slot tz 'tz-minuteswest)
781                       (slot tz 'tz-dsttime))
782               (addr tv)
783               (addr tz))))
784 \f
785
786 ;; Type of the second argument to `getitimer' and
787 ;; the second and third arguments `setitimer'.
788 (define-alien-type nil
789   (struct itimerval
790     (it-interval (struct timeval))      ; timer interval
791     (it-value (struct timeval))))       ; current value
792
793 (defconstant itimer-real 0)
794 (defconstant itimer-virtual 1)
795 (defconstant itimer-prof 2)
796
797 #!-win32
798 (defun unix-getitimer (which)
799   "Unix-getitimer returns the INTERVAL and VALUE slots of one of
800    three system timers (:real :virtual or :profile). On success,
801    unix-getitimer returns 5 values,
802    T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec."
803   (declare (type (member :real :virtual :profile) which)
804            (values t
805                    (unsigned-byte 29) (mod 1000000)
806                    (unsigned-byte 29) (mod 1000000)))
807   (let ((which (ecase which
808                  (:real itimer-real)
809                  (:virtual itimer-virtual)
810                  (:profile itimer-prof))))
811     (with-alien ((itv (struct itimerval)))
812       (syscall* ("getitimer" int (* (struct itimerval)))
813                 (values t
814                         (slot (slot itv 'it-interval) 'tv-sec)
815                         (slot (slot itv 'it-interval) 'tv-usec)
816                         (slot (slot itv 'it-value) 'tv-sec)
817                         (slot (slot itv 'it-value) 'tv-usec))
818                 which (alien-sap (addr itv))))))
819
820 #!-win32
821 (defun unix-setitimer (which int-secs int-usec val-secs val-usec)
822   " Unix-setitimer sets the INTERVAL and VALUE slots of one of
823    three system timers (:real :virtual or :profile). A SIGALRM signal
824    will be delivered VALUE <seconds+microseconds> from now. INTERVAL,
825    when non-zero, is <seconds+microseconds> to be loaded each time
826    the timer expires. Setting INTERVAL and VALUE to zero disables
827    the timer. See the Unix man page for more details. On success,
828    unix-setitimer returns the old contents of the INTERVAL and VALUE
829    slots as in unix-getitimer."
830   (declare (type (member :real :virtual :profile) which)
831            (type (unsigned-byte 29) int-secs val-secs)
832            (type (integer 0 (1000000)) int-usec val-usec)
833            (values t
834                    (unsigned-byte 29) (mod 1000000)
835                    (unsigned-byte 29) (mod 1000000)))
836   (let ((which (ecase which
837                  (:real itimer-real)
838                  (:virtual itimer-virtual)
839                  (:profile itimer-prof))))
840     (with-alien ((itvn (struct itimerval))
841                  (itvo (struct itimerval)))
842       (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs
843             (slot (slot itvn 'it-interval) 'tv-usec) int-usec
844             (slot (slot itvn 'it-value   ) 'tv-sec ) val-secs
845             (slot (slot itvn 'it-value   ) 'tv-usec) val-usec)
846       (syscall* ("setitimer" int (* (struct timeval))(* (struct timeval)))
847                 (values t
848                         (slot (slot itvo 'it-interval) 'tv-sec)
849                         (slot (slot itvo 'it-interval) 'tv-usec)
850                         (slot (slot itvo 'it-value) 'tv-sec)
851                         (slot (slot itvo 'it-value) 'tv-usec))
852                 which (alien-sap (addr itvn))(alien-sap (addr itvo))))))
853
854 \f
855 ;;; FIXME: Many Unix error code definitions were deleted from the old
856 ;;; CMU CL source code here, but not in the exports of SB-UNIX. I
857 ;;; (WHN) hope that someday I'll figure out an automatic way to detect
858 ;;; unused symbols in package exports, but if I don't, there are
859 ;;; enough of them all in one place here that they should probably be
860 ;;; removed by hand.
861 \f
862 ;;;; support routines for dealing with Unix pathnames
863
864 (defun unix-file-kind (name &optional check-for-links)
865   #!+sb-doc
866   "Return either :FILE, :DIRECTORY, :LINK, :SPECIAL, or NIL."
867   (declare (simple-base-string name))
868   (multiple-value-bind (res dev ino mode)
869       (if check-for-links (unix-lstat name) (unix-stat name))
870     (declare (type (or fixnum null) mode)
871              (ignore dev ino))
872     (when res
873       (let ((kind (logand mode s-ifmt)))
874         (cond ((eql kind s-ifdir) :directory)
875               ((eql kind s-ifreg) :file)
876               #!-win32
877               ((eql kind s-iflnk) :link)
878               (t :special))))))
879
880 ;;; Is the Unix pathname PATHNAME relative, instead of absolute? (E.g.
881 ;;; "passwd" or "etc/passwd" instead of "/etc/passwd"?)
882 (defun relative-unix-pathname? (pathname)
883   (declare (type simple-string pathname))
884   (or (zerop (length pathname))
885       (char/= (schar pathname 0) #\/)))
886
887 ;;; Return PATHNAME with all symbolic links resolved. PATHNAME should
888 ;;; already be a complete absolute Unix pathname, since at least in
889 ;;; sbcl-0.6.12.36 we're called only from TRUENAME, and only after
890 ;;; paths have been converted to absolute paths, so we don't need to
891 ;;; try to handle any more generality than that.
892 (defun unix-resolve-links (pathname)
893   (declare (type simple-base-string pathname))
894   ;; KLUDGE: The Win32 platform doesn't have symbolic links, so
895   ;; short-cut this computation (and the check for being an absolute
896   ;; unix pathname...)
897   #!+win32 (return-from unix-resolve-links pathname)
898   (aver (not (relative-unix-pathname? pathname)))
899   ;; KLUDGE: readlink and lstat are unreliable if given symlinks
900   ;; ending in slashes -- fix the issue here instead of waiting for
901   ;; libc to change...
902   ;;
903   ;; but be careful!  Must not strip the final slash from "/".  (This
904   ;; adjustment might be a candidate for being transferred into the C
905   ;; code in a wrap_readlink() function, too.) CSR, 2006-01-18
906   (let ((len (length pathname)))
907     (when (and (> len 1) (eql #\/ (schar pathname (1- len))))
908       (setf pathname (subseq pathname 0 (1- len)))))
909   (/noshow "entering UNIX-RESOLVE-LINKS")
910   (loop with previous-pathnames = nil do
911        (/noshow pathname previous-pathnames)
912        (let ((link (unix-readlink pathname)))
913           (/noshow link)
914           ;; Unlike the old CMU CL code, we handle a broken symlink by
915           ;; returning the link itself. That way, CL:TRUENAME on a
916           ;; broken link returns the link itself, so that CL:DIRECTORY
917           ;; can return broken links, so that even without
918           ;; Unix-specific extensions to do interesting things with
919           ;; them, at least Lisp programs can see them and, if
920           ;; necessary, delete them. (This is handy e.g. when your
921           ;; managed-by-Lisp directories are visited by Emacs, which
922           ;; creates broken links as notes to itself.)
923           (if (null link)
924               (return pathname)
925               (let ((new-pathname
926                      (unix-simplify-pathname
927                       (if (relative-unix-pathname? link)
928                           (let* ((dir-len (1+ (position #\/
929                                                         pathname
930                                                         :from-end t)))
931                                  (dir (subseq pathname 0 dir-len)))
932                             (/noshow dir)
933                             (concatenate 'base-string dir link))
934                           link))))
935                 (if (unix-file-kind new-pathname)
936                     (setf pathname new-pathname)
937                     (return pathname)))))
938         ;; To generalize the principle that even if portable Lisp code
939         ;; can't do anything interesting with a broken symlink, at
940         ;; least it should be able to see and delete it, when we
941         ;; detect a cyclic link, we return the link itself. (So even
942         ;; though portable Lisp code can't do anything interesting
943         ;; with a cyclic link, at least it can see it and delete it.)
944         (if (member pathname previous-pathnames :test #'string=)
945             (return pathname)
946             (push pathname previous-pathnames))))
947
948 (defun unix-simplify-pathname (src)
949   (declare (type simple-base-string src))
950   (let* ((src-len (length src))
951          (dst (make-string src-len :element-type 'base-char))
952          (dst-len 0)
953          (dots 0)
954          (last-slash nil))
955     (macrolet ((deposit (char)
956                  `(progn
957                     (setf (schar dst dst-len) ,char)
958                     (incf dst-len))))
959       (dotimes (src-index src-len)
960         (let ((char (schar src src-index)))
961           (cond ((char= char #\.)
962                  (when dots
963                    (incf dots))
964                  (deposit char))
965                 ((char= char #\/)
966                  (case dots
967                    (0
968                     ;; either ``/...' or ``...//...'
969                     (unless last-slash
970                       (setf last-slash dst-len)
971                       (deposit char)))
972                    (1
973                     ;; either ``./...'' or ``..././...''
974                     (decf dst-len))
975                    (2
976                     ;; We've found ..
977                     (cond
978                      ((and last-slash (not (zerop last-slash)))
979                       ;; There is something before this ..
980                       (let ((prev-prev-slash
981                              (position #\/ dst :end last-slash :from-end t)))
982                         (cond ((and (= (+ (or prev-prev-slash 0) 2)
983                                        last-slash)
984                                     (char= (schar dst (- last-slash 2)) #\.)
985                                     (char= (schar dst (1- last-slash)) #\.))
986                                ;; The something before this .. is another ..
987                                (deposit char)
988                                (setf last-slash dst-len))
989                               (t
990                                ;; The something is some directory or other.
991                                (setf dst-len
992                                      (if prev-prev-slash
993                                          (1+ prev-prev-slash)
994                                          0))
995                                (setf last-slash prev-prev-slash)))))
996                      (t
997                       ;; There is nothing before this .., so we need to keep it
998                       (setf last-slash dst-len)
999                       (deposit char))))
1000                    (t
1001                     ;; something other than a dot between slashes
1002                     (setf last-slash dst-len)
1003                     (deposit char)))
1004                  (setf dots 0))
1005                 (t
1006                  (setf dots nil)
1007                  (setf (schar dst dst-len) char)
1008                  (incf dst-len))))))
1009     (when (and last-slash (not (zerop last-slash)))
1010       (case dots
1011         (1
1012          ;; We've got  ``foobar/.''
1013          (decf dst-len))
1014         (2
1015          ;; We've got ``foobar/..''
1016          (unless (and (>= last-slash 2)
1017                       (char= (schar dst (1- last-slash)) #\.)
1018                       (char= (schar dst (- last-slash 2)) #\.)
1019                       (or (= last-slash 2)
1020                           (char= (schar dst (- last-slash 3)) #\/)))
1021            (let ((prev-prev-slash
1022                   (position #\/ dst :end last-slash :from-end t)))
1023              (if prev-prev-slash
1024                  (setf dst-len (1+ prev-prev-slash))
1025                  (return-from unix-simplify-pathname
1026                    (coerce "./" 'simple-base-string))))))))
1027     (cond ((zerop dst-len)
1028            "./")
1029           ((= dst-len src-len)
1030            dst)
1031           (t
1032            (subseq dst 0 dst-len)))))
1033 \f
1034 ;;;; A magic constant for wait3().
1035 ;;;;
1036 ;;;; FIXME: This used to be defined in run-program.lisp as
1037 ;;;; (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
1038 ;;;; According to some of the man pages, the #o177 is part of the API
1039 ;;;; for wait3(); that said, under SunOS there is a WSTOPPED thing in
1040 ;;;; the headers that may or may not be the same thing. To be
1041 ;;;; investigated. -- CSR, 2002-03-25
1042 (defconstant wstopped #o177)
1043
1044 \f
1045 ;;;; stuff not yet found in the header files
1046 ;;;;
1047 ;;;; Abandon all hope who enters here...
1048
1049 ;;; not checked for linux...
1050 (defmacro fd-set (offset fd-set)
1051   (let ((word (gensym))
1052         (bit (gensym)))
1053     `(multiple-value-bind (,word ,bit) (floor ,offset
1054                                               sb!vm:n-machine-word-bits)
1055        (setf (deref (slot ,fd-set 'fds-bits) ,word)
1056              (logior (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1057                                 (ash 1 ,bit))
1058                      (deref (slot ,fd-set 'fds-bits) ,word))))))
1059
1060 ;;; not checked for linux...
1061 (defmacro fd-clr (offset fd-set)
1062   (let ((word (gensym))
1063         (bit (gensym)))
1064     `(multiple-value-bind (,word ,bit) (floor ,offset
1065                                               sb!vm:n-machine-word-bits)
1066        (setf (deref (slot ,fd-set 'fds-bits) ,word)
1067              (logand (deref (slot ,fd-set 'fds-bits) ,word)
1068                      (sb!kernel:word-logical-not
1069                       (truly-the (unsigned-byte #.sb!vm:n-machine-word-bits)
1070                                  (ash 1 ,bit))))))))
1071
1072 ;;; not checked for linux...
1073 (defmacro fd-isset (offset fd-set)
1074   (let ((word (gensym))
1075         (bit (gensym)))
1076     `(multiple-value-bind (,word ,bit) (floor ,offset
1077                                               sb!vm:n-machine-word-bits)
1078        (logbitp ,bit (deref (slot ,fd-set 'fds-bits) ,word)))))
1079
1080 ;;; not checked for linux...
1081 (defmacro fd-zero (fd-set)
1082   `(progn
1083      ,@(loop for index upfrom 0 below (/ fd-setsize sb!vm:n-machine-word-bits)
1084          collect `(setf (deref (slot ,fd-set 'fds-bits) ,index) 0))))