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