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