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