+(defmacro with-growing-c-string ((buffer size) &body body)
+ (sb-int:with-unique-names (c-string-block)
+ `(block ,c-string-block
+ (let (,buffer)
+ (flet ((,buffer (&optional (size-incl-null))
+ (when size-incl-null
+ (setf (sb-sys:sap-ref-8 (sb-alien:alien-sap ,buffer) size-incl-null)
+ 0))
+ (return-from ,c-string-block
+ (sb-alien::c-string-to-string
+ (sb-alien:alien-sap ,buffer)
+ (sb-impl::default-external-format)
+ 'character))))
+ (loop for ,size = 128 then (* 2 ,size)
+ do (unwind-protect
+ (progn
+ (setf ,buffer (make-alien c-string ,size))
+ ,@body)
+ (when ,buffer
+ (free-alien ,buffer)))))))))
+
+#-win32
+(progn
+ (export 'readlink :sb-posix)
+ (defun readlink (pathspec)
+ "Returns the resolved target of a symbolic link as a string."
+ (flet ((%readlink (path buf length)
+ (alien-funcall
+ (extern-alien "readlink" (function int c-string (* t) int))
+ path buf length)))
+ (with-growing-c-string (buf size)
+ (let ((count (%readlink (filename pathspec) buf size)))
+ (cond ((minusp count)
+ (syscall-error))
+ ((< 0 count size)
+ (buf count))))))))
+
+(progn
+ (export 'getcwd :sb-posix)
+ (defun getcwd ()
+ "Returns the process's current working directory as a string."
+ (flet ((%getcwd (buffer size)
+ (alien-funcall
+ (extern-alien #-win32 "getcwd"
+ #+win32 "_getcwd" (function c-string (* t) int))
+ buffer size)))
+ (with-growing-c-string (buf size)
+ (let ((result (%getcwd buf size)))
+ (cond (result
+ (buf))
+ ((/= (get-errno) sb-posix:erange)
+ (syscall-error))))))))