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