;;; ;;; libsys.scm - builtin system inteface ;;; ;;; Copyright (c) 2000-2024 Shiro Kawai ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; 3. Neither the name of the authors nor the names of its contributors ;;; may be used to endorse or promote products derived from this ;;; software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; System interface functions. Mostly I followed POSIX.1, but included ;; some non-posix functions which are important for programming on Unix. (select-module gauche) (inline-stub (.include "gauche/priv/configP.h" "gauche/priv/mmapP.h") (.include ) (.unless (defined "GAUCHE_WINDOWS") (.include )) (.when "HAVE_CRYPT_H" (.include )) (.when "HAVE_SYS_RESOURCE_H" (.include )) (.when "HAVE_SYS_LOADAVG_H" (.include )) (.when "HAVE_UNISTD_H" (.include )) (.when "HAVE_SYS_MMAN_H" (.include )) (.when (defined "GAUCHE_WINDOWS") (.undef _SC_CLK_TCK)) ;; avoid undefined reference to sysconf ) ;;--------------------------------------------------------------------- ;; dirent.h - read directory ;; we don't have correspoinding functions, but provide these: (select-module gauche) (define-cproc sys-readdir (pathname::) Scm_ReadDirectory) (define-cproc sys-tmpdir () Scm_TmpDir) (define-cproc sys-basename (pathname::) Scm_BaseName) (define-cproc sys-dirname (pathname::) Scm_DirName) (select-module gauche.internal) ;; This isn't POSIX, but we need it in bootstrap so we have it here. (define-in-module gauche (sys-normalize-pathname pathname :key (absolute #f) (expand #f) (canonicalize #f)) ;; NB: We can't use cond-expand, for this file is cross-precompiled. (define windows? (assq 'gauche.os.windows (cond-features))) (define separator (if windows? "\\" "/")) (define (expand-tilde path) (if-let1 m (and expand (rxmatch #/^~([^\\\/]*)/ path)) (let* ([user (m 1)] [home (if (equal? user "") (if windows? (get-windows-home) (get-unix-home (sys-getpwuid (sys-getuid)))) (if windows? (error "'~user' expansil isn't supported on Windows:" path) (get-unix-home (sys-getpwnam (m 1)))))]) (string-append home (m 'after))) path)) (define (get-windows-home) (or (sys-getenv "HOME") ; MSYS (sys-getenv "USERPROFILE") ; cmd.exe "")) (define (get-unix-home pw) (if pw (~ pw'dir) (error "Couldn't obtain username for :" pathname))) (define (absolute? path) (if windows? (rxmatch #/^([A-Za-z]:)?[\\\/]/ path) (rxmatch #/^\// path))) (define (abs-path path) (if (and absolute (not (absolute? path))) (string-append (sys-getcwd) separator path) path)) (define (root? comps) (or (equal? comps '("")) (and windows? (length=? comps 1) (rxmatch #/^[A-Za-z]:$/ (car comps))))) (define (canon-path path) (if canonicalize (let loop ([comps (string-split path #[\\/])] [r '()] [dir? #f]) ;whether we add '/' at end (cond [(null? comps) (let1 r (if dir? (cons "" r) r) (string-join (reverse r) separator))] [(equal? (car comps) ".") (loop (cdr comps) r #t)] [(equal? (car comps) "..") ;; If we've reached to the root dir, we go like "/../" (if (or (null? r) (equal? (car r) "..") (root? r)) (loop (cdr comps) (cons (car comps) r) #f) (loop (cdr comps) (cdr r) #t))] [else (loop (cdr comps) (cons (car comps) r) #f)])) (if windows? (string-join (string-split path #\/) "\\") path))) ($ canon-path $ abs-path $ expand-tilde pathname)) ;;--------------------------------------------------------------------- ;; errno.h - error numbers ;; We won't (and can't) cover every possible errnos, including system ;; specific ones. The following list is taken from Linux asm/errno.h. (select-module gauche) (inline-stub "ScmHashTable *errno_n2y;" ;integer -> symbol "ScmHashTable *errno_y2n;" ;symbol -> integer (initcode (set! errno_n2y (SCM_HASH_TABLE (Scm_MakeHashTableSimple SCM_HASH_EQV 0))) (set! errno_y2n (SCM_HASH_TABLE (Scm_MakeHashTableSimple SCM_HASH_EQ 0))))) (define-macro (define-errno symbol) `(inline-stub (initcode (.when (defined ,symbol) (begin (Scm_Define (Scm_GaucheModule) (SCM_SYMBOL ',symbol) (SCM_MAKE_INT ,symbol)) (Scm_HashTableSet errno_n2y (SCM_MAKE_INT ,symbol) ',symbol 0) (Scm_HashTableSet errno_y2n ',symbol (SCM_MAKE_INT ,symbol) 0)))))) (define-cproc sys-errno->symbol (num::) (return (Scm_HashTableRef errno_n2y (SCM_MAKE_INT num) SCM_FALSE))) (define-cproc sys-symbol->errno (name::) (return (Scm_HashTableRef errno_y2n (SCM_OBJ name) SCM_FALSE))) (define-errno E2BIG) (define-errno EACCES) (define-errno EADDRINUSE) (define-errno EADDRNOTAVAIL) (define-errno EADV) (define-errno EAFNOSUPPORT) (define-errno EAGAIN) (define-errno EALREADY) (define-errno EBADE) (define-errno EBADF) (define-errno EBADFD) (define-errno EBADMSG) (define-errno EBADR) (define-errno EBADRQC) (define-errno EBADSLT) (define-errno EBFONT) (define-errno EBUSY) (define-errno ECANCELED) (define-errno ECHILD) (define-errno ECHRNG) (define-errno ECOMM) (define-errno ECONNABORTED) (define-errno ECONNREFUSED) (define-errno ECONNRESET) (define-errno EDEADLK) (define-errno EDEADLOCK) (define-errno EDESTADDRREQ) (define-errno EDOM) (define-errno EDOTDOT) (define-errno EDQUOT) (define-errno EEXIST) (define-errno EFAULT) (define-errno EFBIG) (define-errno EHOSTDOWN) (define-errno EHOSTUNREACH) (define-errno EIDRM) (define-errno EILSEQ) (define-errno EINPROGRESS) (define-errno EINTR) (define-errno EINVAL) (define-errno EIO) (define-errno EISCONN) (define-errno EISDIR) (define-errno EISNAM) (define-errno EKEYEXPIRED) (define-errno EKEYREJECTED) (define-errno EKEYREVOKED) (define-errno EL2HLT) (define-errno EL2NSYNC) (define-errno EL3HLT) (define-errno EL3RST) (define-errno ELIBACC) (define-errno ELIBBAD) (define-errno ELIBEXEC) (define-errno ELIBMAX) (define-errno ELIBSCN) (define-errno ELNRNG) (define-errno ELOOP) (define-errno EMEDIUMTYPE) (define-errno EMFILE) (define-errno EMLINK) (define-errno EMSGSIZE) (define-errno EMULTIHOP) (define-errno ENAMETOOLONG) (define-errno ENAVAIL) (define-errno ENETDOWN) (define-errno ENETRESET) (define-errno ENETUNREACH) (define-errno ENFILE) (define-errno ENOANO) (define-errno ENOBUFS) (define-errno ENOCSI) (define-errno ENODATA) (define-errno ENODEV) (define-errno ENOENT) (define-errno ENOEXEC) (define-errno ENOKEY) (define-errno ENOLCK) (define-errno ENOLINK) (define-errno ENOMEDIUM) (define-errno ENOMEM) (define-errno ENOMSG) (define-errno ENONET) (define-errno ENOPKG) (define-errno ENOPROTOOPT) (define-errno ENOSPC) (define-errno ENOSR) (define-errno ENOSTR) (define-errno ENOSYS) (define-errno ENOTBLK) (define-errno ENOTCONN) (define-errno ENOTDIR) (define-errno ENOTEMPTY) (define-errno ENOTNAM) (define-errno ENOTSOCK) (define-errno ENOTTY) (define-errno ENOTUNIQ) (define-errno ENXIO) (define-errno EOPNOTSUPP) (define-errno EOVERFLOW) (define-errno EPERM) (define-errno EPFNOSUPPORT) (define-errno EPIPE) (define-errno EPROTO) (define-errno EPROTONOSUPPORT) (define-errno EPROTOTYPE) (define-errno ERANGE) (define-errno EREMCHG) (define-errno EREMOTE) (define-errno EREMOTEIO) (define-errno ERESTART) (define-errno EROFS) (define-errno ESHUTDOWN) (define-errno ESOCKTNOSUPPORT) (define-errno ESPIPE) (define-errno ESRCH) (define-errno ESRMNT) (define-errno ESTALE) (define-errno ESTRPIPE) (define-errno ETIME) (define-errno ETIMEDOUT) (define-errno ETOOMANYREFS) (define-errno ETXTBSY) (define-errno EUCLEAN) (define-errno EUNATCH) (define-errno EUSERS) (define-errno EWOULDBLOCK) (define-errno EXDEV) (define-errno EXFULL) ;;--------------------------------------------------------------------- ;; grp.h - groups (define-cproc sys-getgrgid (gid::) Scm_GetGroupById) (define-cproc sys-getgrnam (name::) Scm_GetGroupByName) ;; faster functions; bypassing creation of group object (define-cproc sys-gid->group-name (gid::) (let* ([g::(struct group*) (getgrgid gid)]) (cond [(== g NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] [else (return (SCM_MAKE_STR_COPYING (-> g gr_name)))]))) (define-cproc sys-group-name->gid (name::) (let* ([g::(struct group*) (getgrnam name)]) (cond [(== g NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] [else (return (Scm_MakeInteger (-> g gr_gid)))]))) ;;--------------------------------------------------------------------- ;; locale.h (inline-stub (define-enum LC_ALL) (define-enum LC_COLLATE) (define-enum LC_CTYPE) (define-enum LC_MONETARY) (define-enum LC_NUMERIC) (define-enum LC_TIME) (define-cise-expr lc-elt [(_ conv sym) `(Scm_Cons ',sym (,conv (-> lc ,sym)))]) ) (define-cproc sys-setlocale (category:: locale::?) ::? setlocale) (define-cproc sys-localeconv () (let* ([lc::(struct lconv*) (localeconv)]) (return (list (lc-elt SCM_MAKE_STR_COPYING decimal_point) (lc-elt SCM_MAKE_STR_COPYING thousands_sep) (lc-elt SCM_MAKE_STR_COPYING grouping) (lc-elt SCM_MAKE_STR_COPYING int_curr_symbol) (lc-elt SCM_MAKE_STR_COPYING currency_symbol) (lc-elt SCM_MAKE_STR_COPYING mon_decimal_point) (lc-elt SCM_MAKE_STR_COPYING mon_thousands_sep) (lc-elt SCM_MAKE_STR_COPYING mon_grouping) (lc-elt SCM_MAKE_STR_COPYING positive_sign) (lc-elt SCM_MAKE_STR_COPYING negative_sign) (lc-elt SCM_MAKE_INT int_frac_digits) (lc-elt SCM_MAKE_INT frac_digits) (lc-elt SCM_MAKE_BOOL p_cs_precedes) (lc-elt SCM_MAKE_BOOL p_sep_by_space) (lc-elt SCM_MAKE_BOOL n_cs_precedes) (lc-elt SCM_MAKE_BOOL n_sep_by_space) (lc-elt SCM_MAKE_INT p_sign_posn) (lc-elt SCM_MAKE_INT n_sign_posn))))) ;;--------------------------------------------------------------------- ;; math.h ;; fmod, frexp, modf, ldexp, log10 - in libnum.scm ;;--------------------------------------------------------------------- ;; pwd.h - passwords (define-cproc sys-getpwuid (uid::) Scm_GetPasswdById) (define-cproc sys-getpwnam (name::) Scm_GetPasswdByName) ;; faster functions; bypassing creation of passwd object (define-cproc sys-uid->user-name (uid::) (let* ([p::(struct passwd*) (getpwuid uid)]) (cond [(== p NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] [else (return (SCM_MAKE_STR_COPYING (-> p pw_name)))]))) (define-cproc sys-user-name->uid (name::) (let* ([p::(struct passwd*) (getpwnam name)]) (cond [(== p NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] [else (return (Scm_MakeInteger (-> p pw_uid)))]))) ;;--------------------------------------------------------------------- ;; signal.h (inline-stub (define-enum SIG_SETMASK) (define-enum SIG_BLOCK) (define-enum SIG_UNBLOCK) ) (define-cproc sys-sigset-add! (set:: :rest sigs) (return (Scm_SysSigsetOp set sigs FALSE))) (define-cproc sys-sigset-delete! (set:: :rest sigs) (return (Scm_SysSigsetOp set sigs TRUE))) (define-cproc sys-sigset-fill! (set::) (return (Scm_SysSigsetFill set FALSE))) (define-cproc sys-sigset-empty! (set::) (return (Scm_SysSigsetFill set TRUE))) (define-cproc sys-signal-name (sig::) Scm_SignalName) (define-cproc sys-kill (process sig::) :: Scm_SysKill) (define-cproc set-signal-handler! (sig proc :optional (mask::? #f)) Scm_SetSignalHandler) (define-cproc get-signal-handler (sig::) Scm_GetSignalHandler) (define-cproc get-signal-handler-mask (sig::) Scm_GetSignalHandlerMask) (define-cproc get-signal-handlers () Scm_GetSignalHandlers) (define-cproc set-signal-pending-limit (limit::) :: Scm_SetSignalPendingLimit) (define-cproc get-signal-pending-limit () :: Scm_GetSignalPendingLimit) (define-cproc sys-sigmask (how:: mask::?) Scm_SysSigmask) (define-cproc sys-sigsuspend (mask::) Scm_SigSuspend) (define-cproc sys-sigwait (mask::) :: Scm_SigWait) (define (sys-sigset . signals) (if (null? signals) (make ) (apply sys-sigset-add! (make ) signals))) ;;--------------------------------------------------------------------- ;; stdio.h (define-cproc sys-remove (filename::) :: (let* ([r::int]) (SCM_SYSCALL r (remove filename)) (when (< r 0) (Scm_SysError "remove failed on %s" filename)))) (define-cproc sys-rename (oldname:: newname::) :: (let* ([r::int]) (.when (defined "GAUCHE_WINDOWS") ;; Windows doesn't allow renaming to the existing file, so we unlink ;; it first. This breaks the atomicity of rename operation. ;; We don't check and raise an error here, since the error will be ;; caught by rename() call. (chmod newname #o666) (unlink newname)) (SCM_SYSCALL r (rename oldname newname)) (when (< r 0) (Scm_SysError "renaming %s to %s failed" oldname newname)))) ;; NB: Alghough tmpnam() is in POSIX, its use is discouraged because of ;; potential security risk. We mimic it's behavior by mkstemp() if possible. (define-cproc sys-tmpnam () (.if "HAVE_MKSTEMP" (let* ([nam::(.array char [*]) "/tmp/fileXXXXXX"] [fd::int]) (SCM_SYSCALL fd (mkstemp nam)) (when (< fd 0) (Scm_SysError "mkstemp failed")) (close fd) (unlink nam) (return (SCM_MAKE_STR_COPYING nam))) (let* ([s::char* (tmpnam NULL)]) (return (SCM_MAKE_STR_COPYING s))))) (define-cproc sys-mkstemp (template::) Scm_SysMkstemp) (define-cproc sys-mkdtemp (template::) Scm_SysMkdtemp) ;; ctermid (define-cproc sys-ctermid () (.if (defined "GAUCHE_WINDOWS") (return '"CON") (let* ([buf::(.array char [(+ L_ctermid 1)])]) (return (SCM_MAKE_STR_COPYING (ctermid buf)))))) ;;--------------------------------------------------------------------- ;; stdlib.h (define-cproc sys-exit (code) :: (_exit (Scm_ObjToExitCode code))) (define-cproc sys-getenv (name::) ::? Scm_GetEnv) (define-cproc sys-abort () :: abort) ;; sys-realpath is in autoloaded sysutil.scm. ;; Note: the return value of system() is not portable. ;; NB: on WinNT, system("") aborts, so we filter it. (define-cproc sys-system (command::) :: (if (== (aref command 0) 0) (return 0) (SCM_SYSCALL SCM_RESULT (system command)))) (define-cproc sys-random () :: (.cond [(and (defined "HAVE_RANDOM") (defined "HAVE_SRANDOM")) (return (random))] [(and (defined "LRAND48") (defined "SRAND48")) (return (lrand48))] [else ;; fallback - we don't want to use rand(), for it is not ;; a very good RNG. (return (rand))])) (define-cproc sys-srandom (seed) :: (unless (SCM_EXACTP seed) (Scm_Error "exact integer required: %S" seed)) (.cond [(and (defined "HAVE_RANDOM") (defined "HAVE_SRANDOM")) (srandom (Scm_GetUInteger seed))] [(and (defined "LRAND48") (defined "SRAND48")) (srand48 (Scm_GetUInteger seed))] [else ;; fallback - we don't want to use rand(), for it is not ;; a very good RNG. (srand (Scm_GetUInteger seed))])) (inline-stub (define-constant RAND_MAX (c "Scm_MakeIntegerFromUI(RAND_MAX)")) ) (define-cproc sys-environ () Scm_Environ) ;; NB: (define-cproc sys-setenv (name:: value:: :optional (overwrite:: #f)) :: Scm_SetEnv) (define-cproc sys-unsetenv (name::) :: Scm_UnsetEnv) (define-cproc sys-clearenv () :: Scm_ClearEnv) (define (sys-environ->alist :optional (envlist (sys-environ))) (map (^[envstr] (receive (pre post) (string-scan envstr #\= 'both) (if pre (cons pre post) (cons envstr "")))) envlist)) ;; We implement sys-putenv on top of sys-setenv, which in turn uses ;; either setenv(3) or putenv(3) based on the availability. ;; We had old sys-putenv API as (sys-putenv name value), while the new one ;; takes a single argument for the consistency to putenv(3). We support ;; both APIs. ;; NB: We don't check the platform allows modifying environments. If not, ;; sys-setenv throws an error. It's up to the application to check the ;; availability by (cond-expand [gauche.sys.setenv ...]). (define (sys-putenv name=value . other) (cond [(null? other) (check-arg string? name=value) (receive (name value) (string-scan name=value #\= 'both) (unless name (error "sys-putenv: argument doesn't contain '=':" name=value)) (sys-setenv name value #t))] [else (sys-setenv name=value (car other) #t)])) ;;--------------------------------------------------------------------- ;; string.h ;; TODO: for thread safety, we should use strerror_r when available. ;; unfortunately there are conflicting versions of strerror_r among ;; various systems. (define-cproc sys-strerror (errno_::) :: strerror) ;; Added in POSIX.1-2008. We could do something more meaningful if ;; the platform doesn't have it, but this is the minimum support. ;; TODO: strsignal() isn't MT-safe; not only with another thread ;; calling strsignal(), but also with setlocale(). Eventually we'll ;; add manual global lock. ;; POSIX also doesn't say anything when signum isn't a supported signal ;; number. We can't do much about it, though, so it's better just to expose ;; the underlying function. (inline-stub (.if HAVE_STRSIGNAL (define-cproc sys-strsignal (signum::) ::? (return (strsignal signum))) (define-cproc sys-strsignal (_::) ::? (return NULL)))) ;;--------------------------------------------------------------------- ;; sys/loadavg.h (inline-stub (.if (defined HAVE_GETLOADAVG) (define-cproc sys-getloadavg (:optional (nsamples:: 3)) (let* ([samples::(.array double [3])] [_ (when (or (<= nsamples 0) (> nsamples 3)) (Scm_Error "sys-getloadavg: argument out of range: %d" nsamples))] [count::int (getloadavg samples nsamples)]) (if (< count 0) (return '#f) (let* ([h '()] [t '()]) (dotimes [i count] (let* ([n (Scm_MakeFlonum (aref samples i))]) (SCM_APPEND1 h t n))) (return h))))) (define-cproc sys-getloadavg (:optional _::) (begin (Scm_Error "sys-getloadavg isn't supported on this platform") (return SCM_UNDEFINED)))) ) ;;--------------------------------------------------------------------- ;; sys/mman.h (inline-stub (define-cclass "ScmMemoryRegion*" "Scm_MemoryRegionClass" () ((address :c-name "ptr" :c-spec "Scm_MakeIntegerU((uintptr_t)obj->ptr)" :setter #f) (size :type :setter #f) (protection :c-name "prot" :type :setter #f) (flags :type :setter #f)) (printer (let* ((m::ScmMemoryRegion* (SCM_MEMORY_REGION obj))) (Scm_Printf port "#" (-> m ptr) (-> m size) (?: (logand (-> m prot) PROT_READ) "r" "") (?: (logand (-> m prot) PROT_WRITE) "w" "") (?: (logand (-> m prot) PROT_EXEC) "x" "")))))) (define-cproc sys-mmap (maybe-port prot:: flags:: size:: :optional (off:: 0)) (let* ([fd::int -1]) (cond [(SCM_PORTP maybe-port) (set! fd (Scm_PortFileNo (SCM_PORT maybe-port))) (when (< fd 0) (Scm_Error "non-file-backed port can't be used to mmap: %S" maybe-port))] [(SCM_FALSEP maybe-port)] [else (SCM_TYPE_ERROR maybe-port "port or #f")]) (return (Scm_SysMmap NULL fd size off prot flags)))) (inline-stub (define-enum PROT_EXEC) (define-enum PROT_READ) (define-enum PROT_WRITE) (define-enum PROT_NONE) (define-enum MAP_SHARED) (define-enum MAP_PRIVATE) (define-enum MAP_ANONYMOUS)) ;;--------------------------------------------------------------------- ;; sys/resource.h (inline-stub (.when (defined "HAVE_SYS_RESOURCE_H") (.if (== SIZEOF_RLIM_T 4) (begin (.define MAKERLIMIT (val) (Scm_MakeIntegerU val)) (.define GETRLIMIT (obj) (Scm_GetIntegerU obj))) (.if (== SIZEOF_RLIM_T 8) (begin (.define MAKERLIMIT (val) (Scm_MakeIntegerU64 val)) (.define GETRLIMIT (obj) (Scm_GetIntegerU64 obj))) (.error "rlim_t must be 32bit or 64bit"))) (define-cproc sys-getrlimit (rsrc::) ::( ) (let* ([limit::(struct rlimit)] [ret::int]) (SCM_SYSCALL ret (getrlimit rsrc (& limit))) (when (< ret 0) (Scm_SysError "getrlimit failed")) (return (MAKERLIMIT (ref limit rlim_cur)) (MAKERLIMIT (ref limit rlim_max))))) (define-cproc sys-setrlimit (rsrc:: cur :optional (max #f)) :: (let* ([limit::(struct rlimit)] [ret::int]) (when (or (SCM_FALSEP cur) (SCM_FALSEP max)) (SCM_SYSCALL ret (getrlimit rsrc (& limit))) (when (< ret 0) (Scm_SysError "getrlimit in sys-setrlimit failed"))) (cond [(SCM_INTEGERP cur) (set! (ref limit rlim_cur) (GETRLIMIT cur))] [(not (SCM_FALSEP cur)) (SCM_TYPE_ERROR cur "non-negative integer or #f")]) (cond [(SCM_INTEGERP max) (set! (ref limit rlim_max) (GETRLIMIT max))] [(not (SCM_FALSEP max)) (SCM_TYPE_ERROR max "non-negative integer or #f")]) (SCM_SYSCALL ret (setrlimit rsrc (& limit))) (when (< ret 0) (Scm_SysError "setrlimit failed")))) (define-constant RLIM_INFINITY (c "MAKERLIMIT(RLIM_INFINITY)")) (define-enum-conditionally RLIMIT_AS) (define-enum-conditionally RLIMIT_CORE) (define-enum-conditionally RLIMIT_CPU) (define-enum-conditionally RLIMIT_DATA) (define-enum-conditionally RLIMIT_FSIZE) (define-enum-conditionally RLIMIT_LOCKS) (define-enum-conditionally RLIMIT_MEMLOCK) (define-enum-conditionally RLIMIT_MSGQUEUE) (define-enum-conditionally RLIMIT_NICE) (define-enum-conditionally RLIMIT_NOFILE) (define-enum-conditionally RLIMIT_NPROC) (define-enum-conditionally RLIMIT_RSS) (define-enum-conditionally RLIMIT_RTPRIO) (define-enum-conditionally RLIMIT_SIGPENDING) (define-enum-conditionally RLIMIT_SBSIZE) (define-enum-conditionally RLIMIT_STACK) (define-enum-conditionally RLIMIT_OFILE) ) ;; HAVE_SYS_RESOURCE_H ) ;;--------------------------------------------------------------------- ;; sys/stat.h (inline-stub ;; Commn code for stat and lstat. (define-cise-stmt stat-common [(_ statfn) `(let* ([s::ScmSysStat* (SCM_SYS_STAT (Scm_MakeSysStat))] [r::int] [p::(const char*) (check-trailing-separator path)]) (SCM_SYSCALL r (,statfn p (SCM_SYS_STAT_STAT s))) (when (< r 0) (Scm_SysError "%s failed for %s" ,(x->string statfn) p)) (return s))]) ;; On Windows stat() fails if PATH has a trailing directory separator, ;; except if we're stat()-ing the root directory. For the convenience ;; we remove the trailing separator if any. It is quite complicated, ;; for we have to deal with optional drive letters. (.when (defined "GAUCHE_WINDOWS") (define-cfn check-trailing-separator (path::(const char*)) ::(const char*) :static (let* ([size::int (strlen path)] [ends::(const char*) (+ path size)] [lastchar::(const char*)]) (when (== size 0) (return path)) (SCM_CHAR_BACKWARD ends path lastchar) (unless (and (>= lastchar path) (< lastchar ends)) (Scm_SysError "invalid pathname: %s" path)) (when (and (not (== lastchar path)) (not (and (== lastchar (+ path 2)) (== (aref path 1) #\:))) (or (== (* lastchar) #\\) (== (* lastchar) #\/))) (let* ([pcopy::(char *) (SCM_NEW_ATOMIC_ARRAY (char) size)]) (memcpy pcopy path (- size 1)) (set! (aref pcopy (- size 1)) 0) (set! path (cast (const char *) pcopy)))) (return path)))) (.unless (defined "GAUCHE_WINDOWS") (define-cfn check-trailing-separator (path::(const char*)) ::(const char*) :static (return path))) (define-cproc sys-stat (path::) :: (stat-common stat)) ;; On Windows we don't have lstat. Omitting sys-lstat from Windows is ;; a bit inconvenient, however, to write a portable code if we do so. ;; Since lstat() works identical to stat() if the path is a symlink, and ;; on Windows path can never be a symlink, so we can just make sys-lstat ;; work the same as sys-stat. (.if (not (defined "GAUCHE_WINDOWS")) (define-cproc sys-lstat (path::) :: (stat-common lstat)) (define-cproc sys-lstat (path::) :: (stat-common stat))) (.unless (defined "GAUCHE_WINDOWS") (define-cproc sys-mkfifo (path:: mode::) :: (SCM_SYSCALL SCM_RESULT (mkfifo path mode)) (when (< SCM_RESULT 0) (Scm_SysError "mkfifo failed on %s" path)))) ) (define-cproc sys-fstat (port-or-fd) (let* ([s::ScmSysStat* (SCM_SYS_STAT (Scm_MakeSysStat))] [fd::int (Scm_GetPortFd port-or-fd FALSE)] [r::int]) (cond [(< fd 0) (return SCM_FALSE)] [else (SCM_SYSCALL r (fstat fd (SCM_SYS_STAT_STAT s))) (when (< r 0) (Scm_SysError "fstat failed for %d" fd)) (return (SCM_OBJ s))]))) (define-cproc file-exists? (path::) :: (let* ([r::int]) (SCM_SYSCALL r (access path F_OK)) (return (== r 0)))) (inline-stub (define-cise-stmt file-check-common [(_ checker) `(let* ([r::int] [s::ScmStat] [p::(const char*) (check-trailing-separator path)]) (SCM_SYSCALL r (access p F_OK)) (if (== r 0) (begin (SCM_SYSCALL r (stat p (& s))) (when (< r 0) (Scm_SysError "stat failed for %s" path)) (return (,checker (ref s st_mode)))) (return FALSE)))]) (define-cproc file-is-regular? (path::) :: (file-check-common S_ISREG)) (define-cproc file-is-directory? (path::) :: (file-check-common S_ISDIR)) ) ;; utime.h (define-cfn utime-ts (ts::ScmTimeSpec* arg) ::void :static (cond [(SCM_FALSEP arg) (set! (-> ts tv_nsec) UTIME_NOW)] [(SCM_TRUEP arg) (set! (-> ts tv_nsec) UTIME_OMIT)] [(SCM_REALP arg) (let* ([s::double]) (set! (-> ts tv_nsec) (cast u_long (* (modf (Scm_GetDouble arg) (& s)) 1.0e9))) (set! (-> ts tv_sec) (cast u_long s)) (while (>= (-> ts tv_nsec) #e1e9) (set! (-> ts tv_nsec) (- (-> ts tv_nsec) #e1e9)) (pre++ (-> ts tv_sec))))] [(SCM_TIMEP arg) (Scm_GetTimeSpec arg ts)] [else (Scm_Error "