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