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