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