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