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