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