sb-win32: offer low-level bindings for file mapping functions
[sbcl.git] / contrib / sb-posix / interface.lisp
1 (cl:in-package :sb-posix)
2
3 (defmacro define-protocol-class
4     (name alien-type superclasses slots &rest options)
5   (let ((to-protocol (intern (format nil "ALIEN-TO-~A" name)))
6         (to-alien (intern (format nil "~A-TO-ALIEN" name))))
7     `(progn
8       (export ',name :sb-posix)
9       (defclass ,name ,superclasses
10         ,(loop for slotd in slots
11                ;; KLUDGE: Splice out :ARRAY-LENGTH options (they're
12                ;; for the conversion functions, not for DEFCLASS).
13                for array-length-option = (member :array-length slotd)
14                collect (append (ldiff slotd array-length-option)
15                                (cddr array-length-option)))
16         ,@options)
17       (declaim (inline ,to-alien ,to-protocol))
18       (declaim (inline ,to-protocol ,to-alien))
19       (defun ,to-protocol (alien &optional instance)
20         (declare (type (sb-alien:alien (* ,alien-type)) alien)
21                  (type (or null ,name) instance))
22         (unless instance
23           (setf instance (make-instance ',name)))
24         ,@(loop for slotd in slots
25                 ;; FIXME: slotds in source are more complicated in general
26                 ;;
27                 ;; FIXME: baroque construction of intricate fragility
28                 for array-length = (getf (cdr slotd) :array-length)
29                 if array-length
30                   collect `(progn
31                              (let ((array (make-array ,array-length)))
32                                (setf (slot-value instance ',(car slotd))
33                                      array)
34                                (dotimes (i ,array-length)
35                                  (setf (aref array i)
36                                        (sb-alien:deref
37                                         (sb-alien:slot alien ',(car slotd))
38                                         i)))))
39                 else
40                   collect `(setf (slot-value instance ',(car slotd))
41                                  (sb-alien:slot alien ',(car slotd))))
42         instance)
43       (defun ,to-alien (instance &optional alien)
44         (declare (type (or null (sb-alien:alien (* ,alien-type))) alien)
45                  (type ,name instance))
46         (unless alien
47           (setf alien (sb-alien:make-alien ,alien-type)))
48         ,@(loop for slotd in slots
49                 for array-length = (getf (cdr slotd) :array-length)
50                 if array-length
51                   collect `(progn
52                              (let ((array (slot-value instance ',(car slotd))))
53                                (dotimes (i ,array-length)
54                                  (setf (sb-alien:deref
55                                         (sb-alien:slot alien ',(car slotd))
56                                         i)
57                                        (aref array i)))))
58                 else
59                   collect `(setf (sb-alien:slot alien ',(car slotd))
60                                  (slot-value instance ',(car slotd)))))
61       (find-class ',name))))
62
63 (define-condition sb-posix:syscall-error (error)
64   ((errno :initarg :errno :reader sb-posix:syscall-errno)
65    (name :initarg :name :initform nil :reader sb-posix:syscall-name))
66   (:report (lambda (c s)
67              (let ((errno (sb-posix:syscall-errno c))
68                    (name (sb-posix:syscall-name c)))
69                (if name
70                    (format s "Error in ~S: ~A (~A)"
71                            name
72                            (sb-int:strerror errno)
73                            errno)
74                    (format s "Error in syscall: ~A (~A)"
75                            (sb-int:strerror errno)
76                            errno))))))
77
78 (declaim (ftype (function (&optional symbol) nil) syscall-error))
79 (defun syscall-error (&optional name)
80   (error 'sb-posix:syscall-error
81          :name name
82          :errno (get-errno)))
83
84 (defun unsupported-error (lisp-name c-name)
85   (error "~S is unsupported by SBCL on this platform due to lack of ~A()."
86          lisp-name c-name))
87
88 (defun unsupported-warning (lisp-name c-name)
89   (warn "~S is unsupported by SBCL on this platform due to lack of ~A()."
90         lisp-name c-name))
91
92 (declaim (inline never-fails))
93 (defun never-fails (&rest args)
94   (declare (ignore args))
95   nil)
96
97 ;;; Some systems may need C-level wrappers, which can live in the
98 ;;; runtime (so that save-lisp-and-die can produce standalone
99 ;;; executables).  See REAL-C-NAME in macros.lisp for the use of this
100 ;;; variable.
101 (eval-when (:compile-toplevel :load-toplevel)
102   (setf *c-functions-in-runtime*
103         '`(#+netbsd ,@("stat" "lstat" "fstat" "readdir" "opendir"))))
104
105
106 ;;; filesystem access
107 (defmacro define-call* (name &rest arguments)
108   #-win32 `(define-call ,name ,@arguments)
109   #+win32 `(define-call ,(if (consp name)
110                              `(,(concatenate 'string "_" (car name))
111                                 ,@(cdr name))
112                              (concatenate 'string "_" name))
113                ,@arguments))
114
115 (define-call* "access" int minusp (pathname filename) (mode int))
116 (define-call* "chdir" int minusp (pathname filename))
117 (define-call* "chmod" int minusp (pathname filename) (mode mode-t))
118 (define-call* "close" int minusp (fd file-descriptor))
119 (define-call* "creat" int minusp (pathname filename) (mode mode-t))
120 (define-call* "dup" int minusp (oldfd file-descriptor))
121 (define-call* "dup2" int minusp (oldfd file-descriptor)
122               (newfd file-descriptor))
123 (define-call* ("lseek" :options :largefile)
124     off-t minusp (fd file-descriptor) (offset off-t)
125     (whence int))
126 (define-call* "mkdir" int minusp (pathname filename) (mode mode-t))
127 (macrolet ((def (x)
128                `(progn
129                  (define-call-internally open-with-mode ,x int minusp
130                    (pathname filename) (flags int) (mode mode-t))
131                  (define-call-internally open-without-mode ,x int minusp
132                    (pathname filename) (flags int))
133                  (define-entry-point ,x
134                      (pathname flags &optional (mode nil mode-supplied))
135                    (if mode-supplied
136                        (open-with-mode pathname flags mode)
137                        (open-without-mode pathname flags))))))
138     (def #-win32 "open" #+win32 "_open"))
139 (define-call* "read" int minusp
140     (fd file-descriptor) (buf (* t)) (count int))
141 (define-call "rename" int minusp (oldpath filename) (newpath filename))
142 (define-call* "rmdir" int minusp (pathname filename))
143 (define-call* "unlink" int minusp (pathname filename))
144 (define-call #-netbsd "opendir" #+netbsd "_opendir"
145     (* t) null-alien (pathname filename))
146 (define-call* "write" int minusp
147     (fd file-descriptor) (buf (* t)) (count int))
148 #+inode64
149 (define-call ("readdir" :c-name "readdir$INODE64" :options :largefile)
150   (* dirent)
151   ;; readdir() has the worst error convention in the world.  It's just
152   ;; too painful to support.  (return is NULL _and_ errno "unchanged"
153   ;; is not an error, it's EOF).
154   not
155   (dir (* t)))
156 #-inode64
157 (define-call (#-netbsd "readdir" #+netbsd "_readdir" :options :largefile)
158   (* dirent)
159   ;; readdir() has the worst error convention in the world.  It's just
160   ;; too painful to support.  (return is NULL _and_ errno "unchanged"
161   ;; is not an error, it's EOF).
162   not
163   (dir (* t)))
164 (define-call "closedir" int minusp (dir (* t)))
165 ;; need to do this here because we can't do it in the DEFPACKAGE
166 (define-call* "umask" mode-t never-fails (mode mode-t))
167 (define-call* "getpid" pid-t never-fails)
168
169 #-win32
170 (progn
171   (define-call "chown" int minusp (pathname filename)
172                (owner uid-t) (group gid-t))
173   (define-call "chroot" int minusp (pathname filename))
174   (define-call "fchdir" int minusp (fd file-descriptor))
175   (define-call "fchmod" int minusp (fd file-descriptor) (mode mode-t))
176   (define-call "fchown" int minusp (fd file-descriptor)
177                (owner uid-t)  (group gid-t))
178   (define-call "fdatasync" int minusp (fd file-descriptor))
179   (define-call ("ftruncate" :options :largefile)
180       int minusp (fd file-descriptor) (length off-t))
181   (define-call "fsync" int minusp (fd file-descriptor))
182   (define-call "lchown" int minusp (pathname filename)
183                (owner uid-t)  (group gid-t))
184   (define-call "link" int minusp (oldpath filename) (newpath filename))
185   (define-call "lockf" int minusp (fd file-descriptor) (cmd int) (len off-t))
186   (define-call "mkfifo" int minusp (pathname filename) (mode mode-t))
187   (define-call "symlink" int minusp (oldpath filename) (newpath filename))
188   (define-call "sync" void never-fails)
189   (define-call ("truncate" :options :largefile)
190       int minusp (pathname filename) (length off-t))
191   #-win32
192   (macrolet ((def-mk*temp (lisp-name c-name result-type errorp dirp values)
193                (declare (ignore dirp))
194                (if (sb-sys:find-foreign-symbol-address c-name)
195                    `(progn
196                       (defun ,lisp-name (template)
197                         (let* ((external-format sb-alien::*default-c-string-external-format*)
198                                (arg (sb-ext:string-to-octets
199                                      (filename template)
200                                      :external-format external-format
201                                      :null-terminate t)))
202                           (sb-sys:with-pinned-objects (arg)
203                             ;; accommodate for the call-by-reference
204                             ;; nature of mks/dtemp's template strings.
205                             (let ((result (alien-funcall (extern-alien ,c-name
206                                                                        (function ,result-type system-area-pointer))
207                                                          (sb-alien::vector-sap arg))))
208                               (when (,errorp result)
209                                 (syscall-error ',lisp-name))
210                               ;; FIXME: We'd rather return pathnames, but other
211                               ;; SB-POSIX functions like this return strings...
212                               (let ((pathname (sb-ext:octets-to-string
213                                                arg :external-format external-format
214                                                :end (1- (length arg)))))
215                                 ,(if values
216                                      '(values result pathname)
217                                      'pathname))))))
218                       (export ',lisp-name))
219                    `(progn
220                       (defun ,lisp-name (template)
221                         (declare (ignore template))
222                         (unsupported-error ',lisp-name ,c-name))
223                       (define-compiler-macro ,lisp-name (&whole form template)
224                         (declare (ignore template))
225                         (unsupported-warning ',lisp-name ,c-name)
226                         form)
227                       (export ',lisp-name)))))
228     (def-mk*temp mktemp "mktemp" (* char) null-alien nil nil)
229     ;; FIXME: Windows does have _mktemp, which has a slightly different
230     ;; interface
231     (def-mk*temp mkstemp "mkstemp" int minusp nil t)
232     ;; FIXME: What about Windows?
233     (def-mk*temp mkdtemp "mkdtemp" (* char) null-alien t nil))
234   (define-call-internally ioctl-without-arg "ioctl" int minusp
235                           (fd file-descriptor) (cmd int))
236   (define-call-internally ioctl-with-int-arg "ioctl" int minusp
237                           (fd file-descriptor) (cmd int) (arg int))
238   (define-call-internally ioctl-with-pointer-arg "ioctl" int minusp
239                           (fd file-descriptor) (cmd int)
240                           (arg alien-pointer-to-anything-or-nil))
241   (define-entry-point "ioctl" (fd cmd &optional (arg nil argp))
242     (if argp
243         (etypecase arg
244           ((alien int) (ioctl-with-int-arg fd cmd arg))
245           ((or (alien (* t)) null) (ioctl-with-pointer-arg fd cmd arg)))
246         (ioctl-without-arg fd cmd)))
247   (define-call-internally fcntl-without-arg "fcntl" int minusp
248                           (fd file-descriptor) (cmd int))
249   (define-call-internally fcntl-with-int-arg "fcntl" int minusp
250                           (fd file-descriptor) (cmd int) (arg int))
251   (define-call-internally fcntl-with-pointer-arg "fcntl" int minusp
252                           (fd file-descriptor) (cmd int)
253                           (arg alien-pointer-to-anything-or-nil))
254   (define-protocol-class flock alien-flock ()
255    ((type :initarg :type :accessor flock-type
256           :documentation "Type of lock; F_RDLCK, F_WRLCK, F_UNLCK.")
257     (whence :initarg :whence :accessor flock-whence
258             :documentation "Flag for starting offset.")
259     (start :initarg :start :accessor flock-start
260            :documentation "Relative offset in bytes.")
261     (len :initarg :len :accessor flock-len
262          :documentation "Size; if 0 then until EOF.")
263     ;; Note: PID isn't initable, and is read-only.  But other stuff in
264     ;; SB-POSIX right now loses when a protocol-class slot is unbound,
265     ;; so we initialize it to 0.
266     (pid :initform 0 :reader flock-pid
267          :documentation
268          "Process ID of the process holding the lock; returned with F_GETLK."))
269    (:documentation "Class representing locks used in fcntl(2)."))
270   (define-entry-point "fcntl" (fd cmd &optional (arg nil argp))
271     (if argp
272         (etypecase arg
273           ((alien int) (fcntl-with-int-arg fd cmd arg))
274           ((or (alien (* t)) null) (fcntl-with-pointer-arg fd cmd arg))
275           (flock (with-alien-flock a-flock ()
276                    (flock-to-alien arg a-flock)
277                    (let ((r (fcntl-with-pointer-arg fd cmd a-flock)))
278                      (alien-to-flock a-flock arg)
279                      r))))
280         (fcntl-without-arg fd cmd)))
281
282   ;; uid, gid
283   (define-call "geteuid" uid-t never-fails) ; "always successful", it says
284 #-sunos  (define-call "getresuid" uid-t never-fails)
285   (define-call "getuid" uid-t never-fails)
286   (define-call "seteuid" int minusp (uid uid-t))
287 #-sunos  (define-call "setfsuid" int minusp (uid uid-t))
288   (define-call "setreuid" int minusp (ruid uid-t) (euid uid-t))
289 #-sunos  (define-call "setresuid" int minusp (ruid uid-t) (euid uid-t) (suid uid-t))
290   (define-call "setuid" int minusp (uid uid-t))
291   (define-call "getegid" gid-t never-fails)
292   (define-call "getgid" gid-t never-fails)
293 #-sunos  (define-call "getresgid" gid-t never-fails)
294   (define-call "setegid" int minusp (gid gid-t))
295 #-sunos  (define-call "setfsgid" int minusp (gid gid-t))
296   (define-call "setgid" int minusp (gid gid-t))
297   (define-call "setregid" int minusp (rgid gid-t) (egid gid-t))
298 #-sunos  (define-call "setresgid" int minusp (rgid gid-t) (egid gid-t) (sgid gid-t))
299
300   ;; processes, signals
301   (define-call "alarm" int never-fails (seconds unsigned))
302
303
304
305   ;; FIXME this is a lie, of course this can fail, but there's no
306   ;; error handling here yet!
307   #+mach-exception-handler
308   (define-call "setup_mach_exceptions" void never-fails)
309   (define-call ("posix_fork" :c-name "fork") pid-t minusp)
310   (defun fork ()
311     "Forks the current process, returning 0 in the new process and the PID of
312 the child process in the parent. Forking while multiple threads are running is
313 not supported."
314     (tagbody
315        (sb-thread::with-all-threads-lock
316          (when (cdr sb-thread::*all-threads*)
317            (go :error))
318          (let ((pid (posix-fork)))
319            #+mach-exception-handler
320            (when (= pid 0)
321              (setup-mach-exceptions))
322            (return-from fork pid)))
323      :error
324        (error "Cannot fork with multiple threads running.")))
325   (export 'fork :sb-posix)
326
327   (define-call "getpgid" pid-t minusp (pid pid-t))
328   (define-call "getppid" pid-t never-fails)
329   (define-call "getpgrp" pid-t never-fails)
330   (define-call "getsid" pid-t minusp  (pid pid-t))
331   (define-call "kill" int minusp (pid pid-t) (signal int))
332   (define-call "killpg" int minusp (pgrp int) (signal int))
333   (define-call "pause" int minusp)
334   (define-call "setpgid" int minusp (pid pid-t) (pgid pid-t))
335   (define-call "setpgrp" int minusp)
336   (define-call "setsid" pid-t minusp))
337
338 (defmacro with-growing-c-string ((buffer size) &body body)
339   (sb-int:with-unique-names (c-string-block)
340     `(block ,c-string-block
341        (let (,buffer)
342          (flet ((,buffer (&optional (size-incl-null))
343                   (when size-incl-null
344                     (setf (sb-sys:sap-ref-8 (sb-alien:alien-sap ,buffer) size-incl-null)
345                           0))
346                   (return-from ,c-string-block
347                     (sb-alien::c-string-to-string
348                      (sb-alien:alien-sap ,buffer)
349                      (sb-impl::default-external-format)
350                      'character))))
351            (loop for ,size = 128 then (* 2 ,size)
352                  do (unwind-protect
353                          (progn
354                            (setf ,buffer (make-alien c-string ,size))
355                            ,@body)
356                       (when ,buffer
357                         (free-alien ,buffer)))))))))
358
359 #-win32
360 (progn
361   (export 'readlink :sb-posix)
362   (defun readlink (pathspec)
363     "Returns the resolved target of a symbolic link as a string."
364     (flet ((%readlink (path buf length)
365              (alien-funcall
366               (extern-alien "readlink" (function int (c-string :not-null t) (* t) int))
367               path buf length)))
368       (with-growing-c-string (buf size)
369         (let ((count (%readlink (filename pathspec) buf size)))
370           (cond ((minusp count)
371                  (syscall-error 'readlink))
372                 ((< 0 count size)
373                  (buf count))))))))
374
375 (progn
376   (export 'getcwd :sb-posix)
377   (defun getcwd ()
378     "Returns the process's current working directory as a string."
379     (flet ((%getcwd (buffer size)
380              (alien-funcall
381               (extern-alien #-win32 "getcwd"
382                             #+win32 "_getcwd" (function c-string (* t) int))
383               buffer size)))
384       (with-growing-c-string (buf size)
385         (let ((result (%getcwd buf size)))
386           (cond (result
387                  (buf))
388                 ((/= (get-errno) sb-posix:erange)
389                  (syscall-error 'getcwd))))))))
390
391 #-win32
392 (progn
393  (export 'wait :sb-posix)
394  (declaim (inline wait))
395  (defun wait (&optional statusptr)
396    (declare (type (or null (simple-array (signed-byte 32) (1))) statusptr))
397    (let* ((ptr (or statusptr (make-array 1 :element-type '(signed-byte 32))))
398           (pid (sb-sys:with-pinned-objects (ptr)
399                  (alien-funcall
400                   (extern-alien "wait" (function pid-t (* int)))
401                   (sb-sys:vector-sap ptr)))))
402      (if (minusp pid)
403          (syscall-error 'wait)
404          (values pid (aref ptr 0))))))
405
406 #-win32
407 (progn
408  (export 'waitpid :sb-posix)
409  (declaim (inline waitpid))
410  (defun waitpid (pid options &optional statusptr)
411    (declare (type (sb-alien:alien pid-t) pid)
412             (type (sb-alien:alien int) options)
413             (type (or null (simple-array (signed-byte 32) (1))) statusptr))
414    (let* ((ptr (or statusptr (make-array 1 :element-type '(signed-byte 32))))
415           (pid (sb-sys:with-pinned-objects (ptr)
416                  (alien-funcall
417                   (extern-alien "waitpid" (function pid-t
418                                                     pid-t (* int) int))
419                   pid (sb-sys:vector-sap ptr) options))))
420      (if (minusp pid)
421          (syscall-error 'waitpid)
422          (values pid (aref ptr 0)))))
423  ;; waitpid macros
424  (define-call "wifexited" boolean never-fails (status int))
425  (define-call "wexitstatus" int never-fails (status int))
426  (define-call "wifsignaled" boolean never-fails (status int))
427  (define-call "wtermsig" int never-fails (status int))
428  (define-call "wifstopped" boolean never-fails (status int))
429  (define-call "wstopsig" int never-fails (status int))
430  #+nil ; see alien/waitpid-macros.c
431  (define-call "wifcontinued" boolean never-fails (status int)))
432
433 ;;; mmap, msync
434 #-win32
435 (progn
436  (define-call ("mmap" :options :largefile) sb-sys:system-area-pointer
437    (lambda (res)
438      (= (sb-sys:sap-int res) #.(1- (expt 2 sb-vm::n-machine-word-bits))))
439    (addr sap-or-nil) (length unsigned) (prot unsigned)
440    (flags unsigned) (fd file-descriptor) (offset off-t))
441
442  (define-call "munmap" int minusp
443    (start sb-sys:system-area-pointer) (length unsigned))
444
445 #-win32
446 (define-call "msync" int minusp
447   (addr sb-sys:system-area-pointer) (length unsigned) (flags int)))
448 #+win32
449 (progn
450   ;; No attempt is made to offer a full mmap-like interface on Windows.
451   ;; It would be possible to do so (and has been done by AK on his
452   ;; branch), but the use case is unclear to me.  However, the following
453   ;; definitions are needed to keep existing code in sb-simple-streams
454   ;; running. --DFL
455   (defconstant PROT-READ #x02)
456   (defconstant PROT-WRITE #x04)
457   (defconstant PROT-EXEC #x10)
458   (defconstant PROT-NONE 0)
459   (defconstant MAP-SHARED 0)
460   (defconstant MAP-PRIVATE 1)
461   (defconstant MS-ASYNC nil)
462   (defconstant MS-SYNC nil)
463   (export                            ;export on the fly like define-call
464    (defun msync (address length flags)
465      (declare (ignore flags))
466      (when (zerop (sb-win32:flush-view-of-file address length))
467        (sb-win32::win32-error "FlushViewOfFile")))))
468
469 ;;; mlockall, munlockall
470 (define-call "mlockall" int minusp (flags int))
471 (define-call "munlockall" int minusp)
472
473 #-win32
474 (define-call "getpagesize" int minusp)
475 #+win32
476 ;;; KLUDGE: This could be taken from GetSystemInfo
477 (export (defun getpagesize () 4096))
478
479 ;;; passwd database
480 ;; The docstrings are copied from the descriptions in SUSv3,
481 ;; where present.
482 #-win32
483 (define-protocol-class passwd alien-passwd ()
484   ((name :initarg :name :accessor passwd-name
485          :documentation "User's login name.")
486    ;; Note: SUSv3 doesn't require this member.
487    (passwd :initarg :passwd :accessor passwd-passwd
488            :documentation "The account's encrypted password.")
489    (uid :initarg :uid :accessor passwd-uid
490         :documentation "Numerical user ID.")
491    (gid :initarg :gid :accessor passwd-gid
492         :documentation "Numerical group ID.")
493    ;; Note: SUSv3 doesn't require this member.
494    (gecos :initarg :gecos :accessor passwd-gecos
495           :documentation "User's name or comment field.")
496    (dir :initarg :dir :accessor passwd-dir
497         :documentation "Initial working directory.")
498    (shell :initarg :shell :accessor passwd-shell
499           :documentation "Program to use as shell."))
500   (:documentation "Instances of this class represent entries in
501                    the system's user database."))
502
503 ;;; group database
504 #-win32
505 (define-protocol-class group alien-group ()
506   ((name :initarg :name :accessor group-name)
507    (passwd :initarg :passwd :accessor group-passwd)
508    (gid :initarg :gid :accessor group-gid)))
509
510 (defmacro define-obj-call (name arg type conv)
511   #-win32
512   ;; FIXME: this isn't the documented way of doing this, surely?
513   (let ((lisp-name (intern (string-upcase name) :sb-posix)))
514     `(progn
515       (export ',lisp-name :sb-posix)
516       (declaim (inline ,lisp-name))
517       (defun ,lisp-name (,arg)
518         (let ((r (alien-funcall (extern-alien ,name ,type) ,arg)))
519           (if (null-alien r)
520               nil
521               (,conv r)))))))
522
523 (define-obj-call "getpwnam" login-name (function (* alien-passwd) (c-string :not-null t))
524                  alien-to-passwd)
525 (define-obj-call "getpwuid" uid (function (* alien-passwd) uid-t)
526                  alien-to-passwd)
527 (define-obj-call "getgrnam" login-name (function (* alien-group) (c-string :not-null t))
528                  alien-to-group)
529 (define-obj-call "getgrgid" gid (function (* alien-group) gid-t)
530                  alien-to-group)
531
532
533 #-win32
534 (define-protocol-class timeval alien-timeval ()
535   ((sec :initarg :tv-sec :accessor timeval-sec
536         :documentation "Seconds.")
537    (usec :initarg :tv-usec :accessor timeval-usec
538          :documentation "Microseconds."))
539   (:documentation "Instances of this class represent time values."))
540
541 (define-protocol-class stat alien-stat ()
542   ((mode :initarg :mode :reader stat-mode
543          :documentation "Mode of file.")
544    (ino :initarg :ino :reader stat-ino
545         :documentation "File serial number.")
546    (dev :initarg :dev :reader stat-dev
547         :documentation "Device ID of device containing file.")
548    (nlink :initarg :nlink :reader stat-nlink
549           :documentation "Number of hard links to the file.")
550    (uid :initarg :uid :reader stat-uid
551         :documentation "User ID of file.")
552    (gid :initarg :gid :reader stat-gid
553         :documentation "Group ID of file.")
554    (size :initarg :size :reader stat-size
555          :documentation "For regular files, the file size in
556                          bytes.  For symbolic links, the length
557                          in bytes of the filename contained in
558                          the symbolic link.")
559    (rdev :initarg :rdev :reader stat-rdev
560           :documentation "For devices the device number.")
561    (atime :initarg :atime :reader stat-atime
562           :documentation "Time of last access.")
563    (mtime :initarg :mtime :reader stat-mtime
564           :documentation "Time of last data modification.")
565    (ctime :initarg :ctime :reader stat-ctime
566           :documentation "Time of last status change"))
567   (:documentation "Instances of this class represent Posix file
568                    metadata."))
569
570 (defmacro define-stat-call (name arg designator-fun type)
571   ;; FIXME: this isn't the documented way of doing this, surely?
572   (let ((lisp-name (lisp-for-c-symbol name))
573         (real-name #+inode64 (format nil "~A$INODE64" name)
574                    #-inode64 name))
575     `(progn
576       (export ',lisp-name :sb-posix)
577       (declaim (inline ,lisp-name))
578       (defun ,lisp-name (,arg &optional stat)
579         (declare (type (or null stat) stat))
580         (with-alien-stat a-stat ()
581           (let ((r (alien-funcall
582                     (extern-alien ,(real-c-name (list real-name :options :largefile)) ,type)
583                     (,designator-fun ,arg)
584                     a-stat)))
585             (when (minusp r)
586               (syscall-error ',lisp-name))
587             (alien-to-stat a-stat stat)))))))
588
589 (define-stat-call #-win32 "stat" #+win32 "_stat"
590                   pathname filename
591                   (function int (c-string :not-null t) (* alien-stat)))
592
593 #-win32
594 (define-stat-call "lstat"
595                   pathname filename
596                   (function int (c-string :not-null t) (* alien-stat)))
597 ;;; No symbolic links on Windows, so use stat
598 #+win32
599 (progn
600   (declaim (inline lstat))
601   (export (defun lstat (filename &optional stat)
602             (if stat (stat filename stat) (stat filename)))))
603
604 (define-stat-call #-win32 "fstat" #+win32 "_fstat"
605                   fd file-descriptor
606                   (function int int (* alien-stat)))
607
608
609 ;;; mode flags
610 (define-call "s_isreg" boolean never-fails (mode mode-t))
611 (define-call "s_isdir" boolean never-fails (mode mode-t))
612 (define-call "s_ischr" boolean never-fails (mode mode-t))
613 (define-call "s_isblk" boolean never-fails (mode mode-t))
614 (define-call "s_isfifo" boolean never-fails (mode mode-t))
615 (define-call "s_islnk" boolean never-fails (mode mode-t))
616 (define-call "s_issock" boolean never-fails (mode mode-t))
617
618 #-win32
619 (progn
620  (export 'pipe :sb-posix)
621  (declaim (inline pipe))
622  (defun pipe (&optional filedes2)
623    (declare (type (or null (simple-array (signed-byte 32) (2))) filedes2))
624    (unless filedes2
625      (setq filedes2 (make-array 2 :element-type '(signed-byte 32))))
626    (let ((r (sb-sys:with-pinned-objects (filedes2)
627               (alien-funcall
628                ;; FIXME: (* INT)?  (ARRAY INT 2) would be better
629                (extern-alien "pipe" (function int (* int)))
630                (sb-sys:vector-sap filedes2)))))
631      (when (minusp r)
632        (syscall-error 'pipe)))
633    (values (aref filedes2 0) (aref filedes2 1))))
634
635 #-win32
636 (define-protocol-class termios alien-termios ()
637   ((iflag :initarg :iflag :accessor sb-posix:termios-iflag
638           :documentation "Input modes.")
639    (oflag :initarg :oflag :accessor sb-posix:termios-oflag
640           :documentation "Output modes.")
641    (cflag :initarg :cflag :accessor sb-posix:termios-cflag
642           :documentation "Control modes.")
643    (lflag :initarg :lflag :accessor sb-posix:termios-lflag
644           :documentation "Local modes.")
645    (cc :initarg :cc :accessor sb-posix:termios-cc :array-length nccs
646        :documentation "Control characters."))
647   (:documentation "Instances of this class represent I/O
648                    characteristics of the terminal."))
649
650 #-win32
651 (progn
652  (export 'tcsetattr :sb-posix)
653  (declaim (inline tcsetattr))
654  (defun tcsetattr (fd actions termios)
655    (declare (type termios termios))
656    (with-alien-termios a-termios ()
657      (termios-to-alien termios a-termios)
658      (let ((fd (file-descriptor fd)))
659        (let* ((r (alien-funcall
660                   (extern-alien
661                    "tcsetattr"
662                    (function int int int (* alien-termios)))
663                   fd actions a-termios)))
664          (when (minusp r)
665            (syscall-error 'tcsetattr)))
666        (values))))
667  (export 'tcgetattr :sb-posix)
668  (declaim (inline tcgetattr))
669  (defun tcgetattr (fd &optional termios)
670    (declare (type (or null termios) termios))
671    (with-alien-termios a-termios ()
672      (let ((r (alien-funcall
673                (extern-alien "tcgetattr"
674                              (function int int (* alien-termios)))
675                (file-descriptor fd)
676                a-termios)))
677        (when (minusp r)
678          (syscall-error 'tcgetattr))
679        (setf termios (alien-to-termios a-termios termios))))
680    termios)
681  (define-call "tcdrain" int minusp (fd file-descriptor))
682  (define-call "tcflow" int minusp (fd file-descriptor) (action int))
683  (define-call "tcflush" int minusp (fd file-descriptor) (queue-selector int))
684  (define-call "tcgetsid" pid-t minusp (fd file-descriptor))
685  (define-call "tcsendbreak" int minusp (fd file-descriptor) (duration int))
686  (export 'cfsetispeed :sb-posix)
687  (declaim (inline cfsetispeed))
688  (defun cfsetispeed (speed &optional termios)
689    (declare (type (or null termios) termios))
690    (with-alien-termios a-termios ()
691      (let ((r (alien-funcall
692                (extern-alien "cfsetispeed"
693                              (function int (* alien-termios) speed-t))
694                a-termios
695                speed)))
696        (when (minusp r)
697          (syscall-error 'cfsetispeed))
698        (setf termios (alien-to-termios a-termios termios))))
699    termios)
700  (export 'cfsetospeed :sb-posix)
701  (declaim (inline cfsetospeed))
702  (defun cfsetospeed (speed &optional termios)
703    (declare (type (or null termios) termios))
704    (with-alien-termios a-termios ()
705      (let ((r (alien-funcall
706                (extern-alien "cfsetospeed"
707                              (function int (* alien-termios) speed-t))
708                a-termios
709                speed)))
710        (when (minusp r)
711          (syscall-error 'cfsetospeed))
712        (setf termios (alien-to-termios a-termios termios))))
713    termios)
714  (export 'cfgetispeed :sb-posix)
715  (declaim (inline cfgetispeed))
716  (defun cfgetispeed (termios)
717    (declare (type termios termios))
718    (with-alien-termios a-termios ()
719      (termios-to-alien termios a-termios)
720      (alien-funcall (extern-alien "cfgetispeed"
721                                   (function speed-t (* alien-termios)))
722                     a-termios)))
723  (export 'cfgetospeed :sb-posix)
724  (declaim (inline cfgetospeed))
725  (defun cfgetospeed (termios)
726    (declare (type termios termios))
727    (with-alien-termios a-termios ()
728      (termios-to-alien termios a-termios)
729      (alien-funcall (extern-alien "cfgetospeed"
730                                  (function speed-t (* alien-termios)))
731                     a-termios))))
732
733
734 #-win32
735 (progn
736   (export 'time :sb-posix)
737   (defun time ()
738     (let ((result (alien-funcall (extern-alien "time"
739                                                (function time-t (* time-t)))
740                                  nil)))
741       (if (minusp result)
742           (syscall-error 'time)
743           result)))
744   (export 'utime :sb-posix)
745   (defun utime (filename &optional access-time modification-time)
746     (let ((fun (extern-alien "utime" (function int (c-string :not-null t)
747                                                (* alien-utimbuf))))
748           (name (filename filename)))
749       (if (not (and access-time modification-time))
750           (alien-funcall fun name nil)
751           (with-alien ((utimbuf (struct alien-utimbuf)))
752             (setf (slot utimbuf 'actime) (or access-time 0)
753                   (slot utimbuf 'modtime) (or modification-time 0))
754             (let ((result (alien-funcall fun name (alien-sap utimbuf))))
755               (if (minusp result)
756                   (syscall-error 'utime)
757                   result))))))
758   (export 'utimes :sb-posix)
759   (defun utimes (filename &optional access-time modification-time)
760     (flet ((seconds-and-useconds (time)
761              (multiple-value-bind (integer fractional)
762                  (cl:truncate time)
763                (values integer (cl:truncate (* fractional 1000000)))))
764            (maybe-syscall-error (value)
765              (if (minusp value)
766                  (syscall-error 'utimes)
767                  value)))
768       (let ((fun (extern-alien "utimes" (function int (c-string :not-null t)
769                                                   (* (array alien-timeval 2)))))
770             (name (filename filename)))
771         (if (not (and access-time modification-time))
772             (maybe-syscall-error (alien-funcall fun name nil))
773             (with-alien ((buf (array alien-timeval 2)))
774               (let ((actime (deref buf 0))
775                     (modtime (deref buf 1)))
776                 (setf (values (slot actime 'sec)
777                               (slot actime 'usec))
778                       (seconds-and-useconds (or access-time 0))
779                       (values (slot modtime 'sec)
780                               (slot modtime 'usec))
781                       (seconds-and-useconds (or modification-time 0)))
782                 (maybe-syscall-error (alien-funcall fun name
783                                                     (alien-sap buf))))))))))
784
785
786 ;;; environment
787
788 (eval-when (:compile-toplevel :load-toplevel)
789   ;; Do this at compile-time as Win32 code below refers to it as
790   ;; sb-posix:getenv.
791   (export 'getenv :sb-posix))
792 (defun getenv (name)
793   (let ((r (alien-funcall
794             (extern-alien "getenv" (function (* char) (c-string :not-null t)))
795             name)))
796     (declare (type (alien (* char)) r))
797     (unless (null-alien r)
798       (cast r c-string))))
799 #-win32
800 (progn
801   (define-call "setenv" int minusp
802                (name (c-string :not-null t))
803                (value (c-string :not-null t))
804                (overwrite int))
805   (define-call "unsetenv" int minusp (name (c-string :not-null t)))
806   (export 'putenv :sb-posix)
807   (defun putenv (string)
808     (declare (string string))
809     ;; We don't want to call actual putenv: the string passed to putenv ends
810     ;; up in environ, and we any string we allocate GC might move.
811     ;;
812     ;; This makes our wrapper nonconformant if you squit hard enough, but
813     ;; users who care about that should really be calling putenv() directly in
814     ;; order to be able to manage memory sanely.
815     (let ((p (position #\= string))
816           (n (length string)))
817       (if p
818           (if (= p n)
819               (unsetenv (subseq string 0 p))
820               (setenv (subseq string 0 p) (subseq string (1+ p)) 1))
821           (error "Invalid argument to putenv: ~S" string)))))
822 #+win32
823 (progn
824   ;; Windows doesn't define a POSIX setenv, but happily their _putenv is sane.
825   (define-call* "putenv" int minusp (string (c-string :not-null t)))
826   (export 'setenv :sb-posix)
827   (defun setenv (name value overwrite)
828     (declare (string name value))
829     (if (and (zerop overwrite) (sb-posix:getenv name))
830         0
831         (putenv (concatenate 'string name "=" value))))
832   (export 'unsetenv :sb-posix)
833   (defun unsetenv (name)
834     (declare (string name))
835     (putenv (concatenate 'string name "="))))
836
837 ;;; syslog
838 #-win32
839 (progn
840   (export 'openlog :sb-posix)
841   (export 'syslog :sb-posix)
842   (export 'closelog :sb-posix)
843   (defun openlog (ident options &optional (facility log-user))
844     (alien-funcall (extern-alien
845                     "openlog" (function void (c-string :not-null t) int int))
846                    ident options facility))
847   (defun syslog (priority format &rest args)
848     "Send a message to the syslog facility, with severity level
849 PRIORITY.  The message will be formatted as by CL:FORMAT (rather
850 than C's printf) with format string FORMAT and arguments ARGS."
851     (flet ((syslog1 (priority message)
852              (alien-funcall (extern-alien
853                              "syslog" (function void int
854                                                 (c-string :not-null t)
855                                                 (c-string :not-null t)))
856                             priority "%s" message)))
857       (syslog1 priority (apply #'format nil format args))))
858   (define-call "closelog" void never-fails))