1.0.39.11: fix readdir for :inode64 builds
[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   (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   (define-call "setfsuid" int minusp (uid uid-t))
269   (define-call "setreuid" int minusp (ruid uid-t) (euid uid-t))
270   (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   (define-call "getresgid" gid-t never-fails)
275   (define-call "setegid" int minusp (gid gid-t))
276   (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   (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   #+mach-exception-handler
287   (progn
288     ;; FIXME this is a lie, of course this can fail, but there's no
289     ;; error handling here yet!
290     (define-call "setup_mach_exceptions" void never-fails)
291     (define-call ("posix_fork" :c-name "fork") pid-t minusp)
292     (defun fork ()
293       (tagbody
294          (sb-thread::with-all-threads-lock
295            (when (cdr sb-thread::*all-threads*)
296              (go :error))
297            (let ((pid (posix-fork)))
298              (when (= pid 0)
299                (setup-mach-exceptions))
300              (return-from fork pid)))
301        :error
302          (error "Cannot fork with multiple threads running.")))
303     (export 'fork :sb-posix))
304
305   #-mach-exception-handler
306   (define-call "fork" pid-t minusp)
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 (* 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) alien-to-passwd)
484 (define-obj-call "getpwuid" uid (function (* alien-passwd) uid-t) alien-to-passwd)
485 (define-obj-call "getgrnam" login-name (function (* alien-group) c-string) alien-to-group)
486 (define-obj-call "getgrgid" gid (function (* alien-group) gid-t) alien-to-group)
487
488
489 #-win32
490 (define-protocol-class timeval alien-timeval ()
491   ((sec :initarg :tv-sec :accessor timeval-sec
492         :documentation "Seconds.")
493    (usec :initarg :tv-usec :accessor timeval-usec
494          :documentation "Microseconds."))
495   (:documentation "Instances of this class represent time values."))
496
497 (define-protocol-class stat alien-stat ()
498   ((mode :initarg :mode :reader stat-mode
499          :documentation "Mode of file.")
500    (ino :initarg :ino :reader stat-ino
501         :documentation "File serial number.")
502    (dev :initarg :dev :reader stat-dev
503         :documentation "Device ID of device containing file.")
504    (nlink :initarg :nlink :reader stat-nlink
505           :documentation "Number of hard links to the file.")
506    (uid :initarg :uid :reader stat-uid
507         :documentation "User ID of file.")
508    (gid :initarg :gid :reader stat-gid
509         :documentation "Group ID of file.")
510    (size :initarg :size :reader stat-size
511          :documentation "For regular files, the file size in
512                          bytes.  For symbolic links, the length
513                          in bytes of the filename contained in
514                          the symbolic link.")
515    (atime :initarg :atime :reader stat-atime
516           :documentation "Time of last access.")
517    (mtime :initarg :mtime :reader stat-mtime
518           :documentation "Time of last data modification.")
519    (ctime :initarg :ctime :reader stat-ctime
520           :documentation "Time of last status change"))
521   (:documentation "Instances of this class represent Posix file
522                    metadata."))
523
524 (defmacro define-stat-call (name arg designator-fun type)
525   ;; FIXME: this isn't the documented way of doing this, surely?
526   (let ((lisp-name (lisp-for-c-symbol name))
527         (real-name #+inode64 (format nil "~A$INODE64" name)
528                    #-inode64 name))
529     `(progn
530       (export ',lisp-name :sb-posix)
531       (declaim (inline ,lisp-name))
532       (defun ,lisp-name (,arg &optional stat)
533         (declare (type (or null stat) stat))
534         (with-alien-stat a-stat ()
535           (let ((r (alien-funcall
536                     (extern-alien ,(real-c-name (list real-name :options :largefile)) ,type)
537                     (,designator-fun ,arg)
538                     a-stat)))
539             (when (minusp r)
540               (syscall-error))
541             (alien-to-stat a-stat stat)))))))
542
543 (define-stat-call #-win32 "stat" #+win32 "_stat"
544                   pathname filename
545                   (function int c-string (* alien-stat)))
546
547 #-win32
548 (define-stat-call "lstat"
549                   pathname filename
550                   (function int c-string (* alien-stat)))
551 ;;; No symbolic links on Windows, so use stat
552 #+win32
553 (progn
554   (declaim (inline lstat))
555   (export (defun lstat (filename &optional stat)
556             (if stat (stat filename stat) (stat filename)))))
557
558 (define-stat-call #-win32 "fstat" #+win32 "_fstat"
559                   fd file-descriptor
560                   (function int int (* alien-stat)))
561
562
563 ;;; mode flags
564 (define-call "s_isreg" boolean never-fails (mode mode-t))
565 (define-call "s_isdir" boolean never-fails (mode mode-t))
566 (define-call "s_ischr" boolean never-fails (mode mode-t))
567 (define-call "s_isblk" boolean never-fails (mode mode-t))
568 (define-call "s_isfifo" boolean never-fails (mode mode-t))
569 (define-call "s_islnk" boolean never-fails (mode mode-t))
570 (define-call "s_issock" boolean never-fails (mode mode-t))
571
572 #-win32
573 (progn
574  (export 'pipe :sb-posix)
575  (declaim (inline pipe))
576  (defun pipe (&optional filedes2)
577    (declare (type (or null (simple-array (signed-byte 32) (2))) filedes2))
578    (unless filedes2
579      (setq filedes2 (make-array 2 :element-type '(signed-byte 32))))
580    (let ((r (sb-sys:with-pinned-objects (filedes2)
581               (alien-funcall
582                ;; FIXME: (* INT)?  (ARRAY INT 2) would be better
583                (extern-alien "pipe" (function int (* int)))
584                (sb-sys:vector-sap filedes2)))))
585      (when (minusp r)
586        (syscall-error)))
587    (values (aref filedes2 0) (aref filedes2 1))))
588
589 #-win32
590 (define-protocol-class termios alien-termios ()
591   ((iflag :initarg :iflag :accessor sb-posix:termios-iflag
592           :documentation "Input modes.")
593    (oflag :initarg :oflag :accessor sb-posix:termios-oflag
594           :documentation "Output modes.")
595    (cflag :initarg :cflag :accessor sb-posix:termios-cflag
596           :documentation "Control modes.")
597    (lflag :initarg :lflag :accessor sb-posix:termios-lflag
598           :documentation "Local modes.")
599    (cc :initarg :cc :accessor sb-posix:termios-cc :array-length nccs
600        :documentation "Control characters"))
601   (:documentation "Instances of this class represent I/O
602                    characteristics of the terminal."))
603
604 #-win32
605 (progn
606  (export 'tcsetattr :sb-posix)
607  (declaim (inline tcsetattr))
608  (defun tcsetattr (fd actions termios)
609    (declare (type termios termios))
610    (with-alien-termios a-termios ()
611      (termios-to-alien termios a-termios)
612      (let ((fd (file-descriptor fd)))
613        (let* ((r (alien-funcall
614                   (extern-alien
615                    "tcsetattr"
616                    (function int int int (* alien-termios)))
617                   fd actions a-termios)))
618          (when (minusp r)
619            (syscall-error)))
620        (values))))
621  (export 'tcgetattr :sb-posix)
622  (declaim (inline tcgetattr))
623  (defun tcgetattr (fd &optional termios)
624    (declare (type (or null termios) termios))
625    (with-alien-termios a-termios ()
626      (let ((r (alien-funcall
627                (extern-alien "tcgetattr"
628                              (function int int (* alien-termios)))
629                (file-descriptor fd)
630                a-termios)))
631        (when (minusp r)
632          (syscall-error))
633        (setf termios (alien-to-termios a-termios termios))))
634    termios)
635  (define-call "tcdrain" int minusp (fd file-descriptor))
636  (define-call "tcflow" int minusp (fd file-descriptor) (action int))
637  (define-call "tcflush" int minusp (fd file-descriptor) (queue-selector int))
638  (define-call "tcgetsid" pid-t minusp (fd file-descriptor))
639  (define-call "tcsendbreak" int minusp (fd file-descriptor) (duration int))
640  (export 'cfsetispeed :sb-posix)
641  (declaim (inline cfsetispeed))
642  (defun cfsetispeed (speed &optional termios)
643    (declare (type (or null termios) termios))
644    (with-alien-termios a-termios ()
645      (let ((r (alien-funcall
646                (extern-alien "cfsetispeed"
647                              (function int (* alien-termios) speed-t))
648                a-termios
649                speed)))
650        (when (minusp r)
651          (syscall-error))
652        (setf termios (alien-to-termios a-termios termios))))
653    termios)
654  (export 'cfsetospeed :sb-posix)
655  (declaim (inline cfsetospeed))
656  (defun cfsetospeed (speed &optional termios)
657    (declare (type (or null termios) termios))
658    (with-alien-termios a-termios ()
659      (let ((r (alien-funcall
660                (extern-alien "cfsetospeed"
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 'cfgetispeed :sb-posix)
669  (declaim (inline cfgetispeed))
670  (defun cfgetispeed (termios)
671    (declare (type termios termios))
672    (with-alien-termios a-termios ()
673      (termios-to-alien termios a-termios)
674      (alien-funcall (extern-alien "cfgetispeed"
675                                   (function speed-t (* alien-termios)))
676                     a-termios)))
677  (export 'cfgetospeed :sb-posix)
678  (declaim (inline cfgetospeed))
679  (defun cfgetospeed (termios)
680    (declare (type termios termios))
681    (with-alien-termios a-termios ()
682      (termios-to-alien termios a-termios)
683      (alien-funcall (extern-alien "cfgetospeed"
684                                  (function speed-t (* alien-termios)))
685                     a-termios))))
686
687
688 #-win32
689 (progn
690   (export 'time :sb-posix)
691   (defun time ()
692     (let ((result (alien-funcall (extern-alien "time"
693                                                (function time-t (* time-t)))
694                                  nil)))
695       (if (minusp result)
696           (syscall-error)
697           result)))
698   (export 'utime :sb-posix)
699   (defun utime (filename &optional access-time modification-time)
700     (let ((fun (extern-alien "utime" (function int c-string
701                                                (* alien-utimbuf))))
702           (name (filename filename)))
703       (if (not (and access-time modification-time))
704           (alien-funcall fun name nil)
705           (with-alien ((utimbuf (struct alien-utimbuf)))
706             (setf (slot utimbuf 'actime) (or access-time 0)
707                   (slot utimbuf 'modtime) (or modification-time 0))
708             (let ((result (alien-funcall fun name (alien-sap utimbuf))))
709               (if (minusp result)
710                   (syscall-error)
711                   result))))))
712   (export 'utimes :sb-posix)
713   (defun utimes (filename &optional access-time modification-time)
714     (flet ((seconds-and-useconds (time)
715              (multiple-value-bind (integer fractional)
716                  (cl:truncate time)
717                (values integer (cl:truncate (* fractional 1000000)))))
718            (maybe-syscall-error (value)
719              (if (minusp value)
720                  (syscall-error)
721                  value)))
722       (let ((fun (extern-alien "utimes" (function int c-string
723                                                   (* (array alien-timeval 2)))))
724             (name (filename filename)))
725         (if (not (and access-time modification-time))
726             (maybe-syscall-error (alien-funcall fun name nil))
727             (with-alien ((buf (array alien-timeval 2)))
728               (let ((actime (deref buf 0))
729                     (modtime (deref buf 1)))
730                 (setf (values (slot actime 'sec)
731                               (slot actime 'usec))
732                       (seconds-and-useconds (or access-time 0))
733                       (values (slot modtime 'sec)
734                               (slot modtime 'usec))
735                       (seconds-and-useconds (or modification-time 0)))
736                 (maybe-syscall-error (alien-funcall fun name
737                                                     (alien-sap buf))))))))))
738
739
740 ;;; environment
741
742 (eval-when (:compile-toplevel :load-toplevel)
743   ;; Do this at compile-time as Win32 code below refers to it as
744   ;; sb-posix:getenv.
745   (export 'getenv :sb-posix))
746 (defun getenv (name)
747   (let ((r (alien-funcall
748             (extern-alien "getenv" (function (* char) c-string))
749             name)))
750     (declare (type (alien (* char)) r))
751     (unless (null-alien r)
752       (cast r c-string))))
753 #-win32
754 (progn
755   (define-call "setenv" int minusp (name c-string) (value c-string) (overwrite int))
756   (define-call "unsetenv" int minusp (name c-string))
757   (export 'putenv :sb-posix)
758   (defun putenv (string)
759     (declare (string string))
760     ;; We don't want to call actual putenv: the string passed to putenv ends
761     ;; up in environ, and we any string we allocate GC might move.
762     ;;
763     ;; This makes our wrapper nonconformant if you squit hard enough, but
764     ;; users who care about that should really be calling putenv() directly in
765     ;; order to be able to manage memory sanely.
766     (let ((p (position #\= string))
767           (n (length string)))
768       (if p
769           (if (= p n)
770               (unsetenv (subseq string 0 p))
771               (setenv (subseq string 0 p) (subseq string (1+ p)) 1))
772           (error "Invalid argument to putenv: ~S" string)))))
773 #+win32
774 (progn
775   ;; Windows doesn't define a POSIX setenv, but happily their _putenv is sane.
776   (define-call* "putenv" int minusp (string c-string))
777   (export 'setenv :sb-posix)
778   (defun setenv (name value overwrite)
779     (declare (string name value))
780     (if (and (zerop overwrite) (sb-posix:getenv name))
781         0
782         (putenv (concatenate 'string name "=" value))))
783   (export 'unsetenv :sb-posix)
784   (defun unsetenv (name)
785     (declare (string name))
786     (putenv (concatenate 'string name "="))))
787
788 ;;; syslog
789 #-win32
790 (progn
791   (export 'openlog :sb-posix)
792   (export 'syslog :sb-posix)
793   (export 'closelog :sb-posix)
794   (defun openlog (ident options &optional (facility log-user))
795     (alien-funcall (extern-alien
796                     "openlog" (function void c-string int int))
797                    ident options facility))
798   (defun syslog (priority format &rest args)
799     "Send a message to the syslog facility, with severity level
800 PRIORITY.  The message will be formatted as by CL:FORMAT (rather
801 than C's printf) with format string FORMAT and arguments ARGS."
802     (flet ((syslog1 (priority message)
803              (alien-funcall (extern-alien
804                              "syslog" (function void int c-string c-string))
805                             priority "%s" message)))
806       (syslog1 priority (apply #'format nil format args))))
807   (define-call "closelog" void never-fails))