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