| 1 |
;;; |
| 2 |
;;; libsys.scm - builtin system inteface |
| 3 |
;;; |
| 4 |
;;; Copyright (c) 2000-2024 Shiro Kawai <[email protected]> |
| 5 |
;;; |
| 6 |
;;; Redistribution and use in source and binary forms, with or without |
| 7 |
;;; modification, are permitted provided that the following conditions |
| 8 |
;;; are met: |
| 9 |
;;; |
| 10 |
;;; 1. Redistributions of source code must retain the above copyright |
| 11 |
;;; notice, this list of conditions and the following disclaimer. |
| 12 |
;;; |
| 13 |
;;; 2. Redistributions in binary form must reproduce the above copyright |
| 14 |
;;; notice, this list of conditions and the following disclaimer in the |
| 15 |
;;; documentation and/or other materials provided with the distribution. |
| 16 |
;;; |
| 17 |
;;; 3. Neither the name of the authors nor the names of its contributors |
| 18 |
;;; may be used to endorse or promote products derived from this |
| 19 |
;;; software without specific prior written permission. |
| 20 |
;;; |
| 21 |
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 22 |
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 23 |
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 24 |
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 25 |
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 26 |
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED |
| 27 |
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR |
| 28 |
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF |
| 29 |
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING |
| 30 |
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 31 |
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 32 |
;;; |
| 33 |
|
| 34 |
;; System interface functions. Mostly I followed POSIX.1, but included |
| 35 |
;; some non-posix functions which are important for programming on Unix. |
| 36 |
|
| 37 |
(select-module gauche) |
| 38 |
(inline-stub |
| 39 |
(.include "gauche/priv/configP.h" |
| 40 |
"gauche/priv/mmapP.h") |
| 41 |
(.include <stdlib.h> <locale.h> <math.h> <sys/types.h> <sys/stat.h> <fcntl.h>) |
| 42 |
(.unless (defined "GAUCHE_WINDOWS") |
| 43 |
(.include <grp.h> <pwd.h> <sys/wait.h> <utime.h> |
| 44 |
<sys/times.h> <sys/utsname.h>)) |
| 45 |
(.when "HAVE_CRYPT_H" (.include <crypt.h>)) |
| 46 |
(.when "HAVE_SYS_RESOURCE_H" (.include <sys/resource.h>)) |
| 47 |
(.when "HAVE_SYS_LOADAVG_H" (.include <sys/loadavg.h>)) |
| 48 |
(.when "HAVE_UNISTD_H" (.include <unistd.h>)) |
| 49 |
(.when "HAVE_SYS_MMAN_H" (.include <sys/mman.h>)) |
| 50 |
|
| 51 |
(.when (defined "GAUCHE_WINDOWS") |
| 52 |
(.undef _SC_CLK_TCK)) ;; avoid undefined reference to sysconf |
| 53 |
) |
| 54 |
|
| 55 |
;;--------------------------------------------------------------------- |
| 56 |
;; dirent.h - read directory |
| 57 |
;; we don't have correspoinding functions, but provide these: |
| 58 |
|
| 59 |
(select-module gauche) |
| 60 |
(define-cproc sys-readdir (pathname::<string>) Scm_ReadDirectory) |
| 61 |
(define-cproc sys-tmpdir () Scm_TmpDir) |
| 62 |
(define-cproc sys-basename (pathname::<string>) Scm_BaseName) |
| 63 |
(define-cproc sys-dirname (pathname::<string>) Scm_DirName) |
| 64 |
|
| 65 |
(select-module gauche.internal) |
| 66 |
|
| 67 |
;; This isn't POSIX, but we need it in bootstrap so we have it here. |
| 68 |
(define-in-module gauche (sys-normalize-pathname pathname |
| 69 |
:key |
| 70 |
(absolute #f) |
| 71 |
(expand #f) |
| 72 |
(canonicalize #f)) |
| 73 |
;; NB: We can't use cond-expand, for this file is cross-precompiled. |
| 74 |
(define windows? (assq 'gauche.os.windows (cond-features))) |
| 75 |
(define separator (if windows? "\\" "/")) |
| 76 |
(define (expand-tilde path) |
| 77 |
(if-let1 m (and expand (rxmatch #/^~([^\\\/]*)/ path)) |
| 78 |
(let* ([user (m 1)] |
| 79 |
[home (if (equal? user "") |
| 80 |
(if windows? |
| 81 |
(get-windows-home) |
| 82 |
(get-unix-home (sys-getpwuid (sys-getuid)))) |
| 83 |
(if windows? |
| 84 |
(error "'~user' expansil isn't supported on Windows:" |
| 85 |
path) |
| 86 |
(get-unix-home (sys-getpwnam (m 1)))))]) |
| 87 |
(string-append home (m 'after))) |
| 88 |
path)) |
| 89 |
(define (get-windows-home) |
| 90 |
(or (sys-getenv "HOME") ; MSYS |
| 91 |
(sys-getenv "USERPROFILE") ; cmd.exe |
| 92 |
"")) |
| 93 |
(define (get-unix-home pw) |
| 94 |
(if pw (~ pw'dir) (error "Couldn't obtain username for :" pathname))) |
| 95 |
(define (absolute? path) |
| 96 |
(if windows? |
| 97 |
(rxmatch #/^([A-Za-z]:)?[\\\/]/ path) |
| 98 |
(rxmatch #/^\// path))) |
| 99 |
(define (abs-path path) |
| 100 |
(if (and absolute (not (absolute? path))) |
| 101 |
(string-append (sys-getcwd) separator path) |
| 102 |
path)) |
| 103 |
(define (root? comps) |
| 104 |
(or (equal? comps '("")) |
| 105 |
(and windows? |
| 106 |
(length=? comps 1) |
| 107 |
(rxmatch #/^[A-Za-z]:$/ (car comps))))) |
| 108 |
(define (canon-path path) |
| 109 |
(if canonicalize |
| 110 |
(let loop ([comps (string-split path #[\\/])] |
| 111 |
[r '()] |
| 112 |
[dir? #f]) ;whether we add '/' at end |
| 113 |
(cond [(null? comps) |
| 114 |
(let1 r (if dir? (cons "" r) r) |
| 115 |
(string-join (reverse r) separator))] |
| 116 |
[(equal? (car comps) ".") (loop (cdr comps) r #t)] |
| 117 |
[(equal? (car comps) "..") |
| 118 |
;; If we've reached to the root dir, we go like "/../" |
| 119 |
(if (or (null? r) (equal? (car r) "..") (root? r)) |
| 120 |
(loop (cdr comps) (cons (car comps) r) #f) |
| 121 |
(loop (cdr comps) (cdr r) #t))] |
| 122 |
[else (loop (cdr comps) (cons (car comps) r) #f)])) |
| 123 |
(if windows? |
| 124 |
(string-join (string-split path #\/) "\\") |
| 125 |
path))) |
| 126 |
($ canon-path $ abs-path $ expand-tilde pathname)) |
| 127 |
|
| 128 |
;;--------------------------------------------------------------------- |
| 129 |
;; errno.h - error numbers |
| 130 |
|
| 131 |
;; We won't (and can't) cover every possible errnos, including system |
| 132 |
;; specific ones. The following list is taken from Linux asm/errno.h. |
| 133 |
|
| 134 |
(select-module gauche) |
| 135 |
|
| 136 |
(inline-stub |
| 137 |
"ScmHashTable *errno_n2y;" ;integer -> symbol |
| 138 |
"ScmHashTable *errno_y2n;" ;symbol -> integer |
| 139 |
(initcode |
| 140 |
(set! errno_n2y (SCM_HASH_TABLE (Scm_MakeHashTableSimple SCM_HASH_EQV 0))) |
| 141 |
(set! errno_y2n (SCM_HASH_TABLE (Scm_MakeHashTableSimple SCM_HASH_EQ 0))))) |
| 142 |
|
| 143 |
|
| 144 |
(define-macro (define-errno symbol) |
| 145 |
`(inline-stub |
| 146 |
(initcode |
| 147 |
(.when (defined ,symbol) |
| 148 |
(begin |
| 149 |
(Scm_Define (Scm_GaucheModule) |
| 150 |
(SCM_SYMBOL ',symbol) (SCM_MAKE_INT ,symbol)) |
| 151 |
(Scm_HashTableSet errno_n2y (SCM_MAKE_INT ,symbol) ',symbol 0) |
| 152 |
(Scm_HashTableSet errno_y2n ',symbol (SCM_MAKE_INT ,symbol) 0)))))) |
| 153 |
|
| 154 |
(define-cproc sys-errno->symbol (num::<fixnum>) |
| 155 |
(return (Scm_HashTableRef errno_n2y (SCM_MAKE_INT num) SCM_FALSE))) |
| 156 |
(define-cproc sys-symbol->errno (name::<symbol>) |
| 157 |
(return (Scm_HashTableRef errno_y2n (SCM_OBJ name) SCM_FALSE))) |
| 158 |
|
| 159 |
(define-errno E2BIG) |
| 160 |
(define-errno EACCES) |
| 161 |
(define-errno EADDRINUSE) |
| 162 |
(define-errno EADDRNOTAVAIL) |
| 163 |
(define-errno EADV) |
| 164 |
(define-errno EAFNOSUPPORT) |
| 165 |
(define-errno EAGAIN) |
| 166 |
(define-errno EALREADY) |
| 167 |
(define-errno EBADE) |
| 168 |
(define-errno EBADF) |
| 169 |
(define-errno EBADFD) |
| 170 |
(define-errno EBADMSG) |
| 171 |
(define-errno EBADR) |
| 172 |
(define-errno EBADRQC) |
| 173 |
(define-errno EBADSLT) |
| 174 |
(define-errno EBFONT) |
| 175 |
(define-errno EBUSY) |
| 176 |
(define-errno ECANCELED) |
| 177 |
(define-errno ECHILD) |
| 178 |
(define-errno ECHRNG) |
| 179 |
(define-errno ECOMM) |
| 180 |
(define-errno ECONNABORTED) |
| 181 |
(define-errno ECONNREFUSED) |
| 182 |
(define-errno ECONNRESET) |
| 183 |
(define-errno EDEADLK) |
| 184 |
(define-errno EDEADLOCK) |
| 185 |
(define-errno EDESTADDRREQ) |
| 186 |
(define-errno EDOM) |
| 187 |
(define-errno EDOTDOT) |
| 188 |
(define-errno EDQUOT) |
| 189 |
(define-errno EEXIST) |
| 190 |
(define-errno EFAULT) |
| 191 |
(define-errno EFBIG) |
| 192 |
(define-errno EHOSTDOWN) |
| 193 |
(define-errno EHOSTUNREACH) |
| 194 |
(define-errno EIDRM) |
| 195 |
(define-errno EILSEQ) |
| 196 |
(define-errno EINPROGRESS) |
| 197 |
(define-errno EINTR) |
| 198 |
(define-errno EINVAL) |
| 199 |
(define-errno EIO) |
| 200 |
(define-errno EISCONN) |
| 201 |
(define-errno EISDIR) |
| 202 |
(define-errno EISNAM) |
| 203 |
(define-errno EKEYEXPIRED) |
| 204 |
(define-errno EKEYREJECTED) |
| 205 |
(define-errno EKEYREVOKED) |
| 206 |
(define-errno EL2HLT) |
| 207 |
(define-errno EL2NSYNC) |
| 208 |
(define-errno EL3HLT) |
| 209 |
(define-errno EL3RST) |
| 210 |
(define-errno ELIBACC) |
| 211 |
(define-errno ELIBBAD) |
| 212 |
(define-errno ELIBEXEC) |
| 213 |
(define-errno ELIBMAX) |
| 214 |
(define-errno ELIBSCN) |
| 215 |
(define-errno ELNRNG) |
| 216 |
(define-errno ELOOP) |
| 217 |
(define-errno EMEDIUMTYPE) |
| 218 |
(define-errno EMFILE) |
| 219 |
(define-errno EMLINK) |
| 220 |
(define-errno EMSGSIZE) |
| 221 |
(define-errno EMULTIHOP) |
| 222 |
(define-errno ENAMETOOLONG) |
| 223 |
(define-errno ENAVAIL) |
| 224 |
(define-errno ENETDOWN) |
| 225 |
(define-errno ENETRESET) |
| 226 |
(define-errno ENETUNREACH) |
| 227 |
(define-errno ENFILE) |
| 228 |
(define-errno ENOANO) |
| 229 |
(define-errno ENOBUFS) |
| 230 |
(define-errno ENOCSI) |
| 231 |
(define-errno ENODATA) |
| 232 |
(define-errno ENODEV) |
| 233 |
(define-errno ENOENT) |
| 234 |
(define-errno ENOEXEC) |
| 235 |
(define-errno ENOKEY) |
| 236 |
(define-errno ENOLCK) |
| 237 |
(define-errno ENOLINK) |
| 238 |
(define-errno ENOMEDIUM) |
| 239 |
(define-errno ENOMEM) |
| 240 |
(define-errno ENOMSG) |
| 241 |
(define-errno ENONET) |
| 242 |
(define-errno ENOPKG) |
| 243 |
(define-errno ENOPROTOOPT) |
| 244 |
(define-errno ENOSPC) |
| 245 |
(define-errno ENOSR) |
| 246 |
(define-errno ENOSTR) |
| 247 |
(define-errno ENOSYS) |
| 248 |
(define-errno ENOTBLK) |
| 249 |
(define-errno ENOTCONN) |
| 250 |
(define-errno ENOTDIR) |
| 251 |
(define-errno ENOTEMPTY) |
| 252 |
(define-errno ENOTNAM) |
| 253 |
(define-errno ENOTSOCK) |
| 254 |
(define-errno ENOTTY) |
| 255 |
(define-errno ENOTUNIQ) |
| 256 |
(define-errno ENXIO) |
| 257 |
(define-errno EOPNOTSUPP) |
| 258 |
(define-errno EOVERFLOW) |
| 259 |
(define-errno EPERM) |
| 260 |
(define-errno EPFNOSUPPORT) |
| 261 |
(define-errno EPIPE) |
| 262 |
(define-errno EPROTO) |
| 263 |
(define-errno EPROTONOSUPPORT) |
| 264 |
(define-errno EPROTOTYPE) |
| 265 |
(define-errno ERANGE) |
| 266 |
(define-errno EREMCHG) |
| 267 |
(define-errno EREMOTE) |
| 268 |
(define-errno EREMOTEIO) |
| 269 |
(define-errno ERESTART) |
| 270 |
(define-errno EROFS) |
| 271 |
(define-errno ESHUTDOWN) |
| 272 |
(define-errno ESOCKTNOSUPPORT) |
| 273 |
(define-errno ESPIPE) |
| 274 |
(define-errno ESRCH) |
| 275 |
(define-errno ESRMNT) |
| 276 |
(define-errno ESTALE) |
| 277 |
(define-errno ESTRPIPE) |
| 278 |
(define-errno ETIME) |
| 279 |
(define-errno ETIMEDOUT) |
| 280 |
(define-errno ETOOMANYREFS) |
| 281 |
(define-errno ETXTBSY) |
| 282 |
(define-errno EUCLEAN) |
| 283 |
(define-errno EUNATCH) |
| 284 |
(define-errno EUSERS) |
| 285 |
(define-errno EWOULDBLOCK) |
| 286 |
(define-errno EXDEV) |
| 287 |
(define-errno EXFULL) |
| 288 |
|
| 289 |
;;--------------------------------------------------------------------- |
| 290 |
;; grp.h - groups |
| 291 |
|
| 292 |
(define-cproc sys-getgrgid (gid::<int>) Scm_GetGroupById) |
| 293 |
(define-cproc sys-getgrnam (name::<string>) Scm_GetGroupByName) |
| 294 |
|
| 295 |
;; faster functions; bypassing creation of group object |
| 296 |
(define-cproc sys-gid->group-name (gid::<int>) |
| 297 |
(let* ([g::(struct group*) (getgrgid gid)]) |
| 298 |
(cond [(== g NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] |
| 299 |
[else (return (SCM_MAKE_STR_COPYING (-> g gr_name)))]))) |
| 300 |
(define-cproc sys-group-name->gid (name::<const-cstring>) |
| 301 |
(let* ([g::(struct group*) (getgrnam name)]) |
| 302 |
(cond [(== g NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] |
| 303 |
[else (return (Scm_MakeInteger (-> g gr_gid)))]))) |
| 304 |
|
| 305 |
;;--------------------------------------------------------------------- |
| 306 |
;; locale.h |
| 307 |
|
| 308 |
(inline-stub |
| 309 |
(define-enum LC_ALL) |
| 310 |
(define-enum LC_COLLATE) |
| 311 |
(define-enum LC_CTYPE) |
| 312 |
(define-enum LC_MONETARY) |
| 313 |
(define-enum LC_NUMERIC) |
| 314 |
(define-enum LC_TIME) |
| 315 |
|
| 316 |
(define-cise-expr lc-elt |
| 317 |
[(_ conv sym) `(Scm_Cons ',sym (,conv (-> lc ,sym)))]) |
| 318 |
) |
| 319 |
|
| 320 |
(define-cproc sys-setlocale (category::<fixnum> locale::<const-cstring>?) |
| 321 |
::<const-cstring>? setlocale) |
| 322 |
|
| 323 |
(define-cproc sys-localeconv () |
| 324 |
(let* ([lc::(struct lconv*) (localeconv)]) |
| 325 |
(return (list (lc-elt SCM_MAKE_STR_COPYING decimal_point) |
| 326 |
(lc-elt SCM_MAKE_STR_COPYING thousands_sep) |
| 327 |
(lc-elt SCM_MAKE_STR_COPYING grouping) |
| 328 |
(lc-elt SCM_MAKE_STR_COPYING int_curr_symbol) |
| 329 |
(lc-elt SCM_MAKE_STR_COPYING currency_symbol) |
| 330 |
(lc-elt SCM_MAKE_STR_COPYING mon_decimal_point) |
| 331 |
(lc-elt SCM_MAKE_STR_COPYING mon_thousands_sep) |
| 332 |
(lc-elt SCM_MAKE_STR_COPYING mon_grouping) |
| 333 |
(lc-elt SCM_MAKE_STR_COPYING positive_sign) |
| 334 |
(lc-elt SCM_MAKE_STR_COPYING negative_sign) |
| 335 |
(lc-elt SCM_MAKE_INT int_frac_digits) |
| 336 |
(lc-elt SCM_MAKE_INT frac_digits) |
| 337 |
(lc-elt SCM_MAKE_BOOL p_cs_precedes) |
| 338 |
(lc-elt SCM_MAKE_BOOL p_sep_by_space) |
| 339 |
(lc-elt SCM_MAKE_BOOL n_cs_precedes) |
| 340 |
(lc-elt SCM_MAKE_BOOL n_sep_by_space) |
| 341 |
(lc-elt SCM_MAKE_INT p_sign_posn) |
| 342 |
(lc-elt SCM_MAKE_INT n_sign_posn))))) |
| 343 |
|
| 344 |
;;--------------------------------------------------------------------- |
| 345 |
;; math.h |
| 346 |
|
| 347 |
;; fmod, frexp, modf, ldexp, log10 - in libnum.scm |
| 348 |
|
| 349 |
;;--------------------------------------------------------------------- |
| 350 |
;; pwd.h - passwords |
| 351 |
|
| 352 |
(define-cproc sys-getpwuid (uid::<int>) Scm_GetPasswdById) |
| 353 |
(define-cproc sys-getpwnam (name::<string>) Scm_GetPasswdByName) |
| 354 |
|
| 355 |
;; faster functions; bypassing creation of passwd object |
| 356 |
(define-cproc sys-uid->user-name (uid::<int>) |
| 357 |
(let* ([p::(struct passwd*) (getpwuid uid)]) |
| 358 |
(cond [(== p NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] |
| 359 |
[else (return (SCM_MAKE_STR_COPYING (-> p pw_name)))]))) |
| 360 |
(define-cproc sys-user-name->uid (name::<const-cstring>) |
| 361 |
(let* ([p::(struct passwd*) (getpwnam name)]) |
| 362 |
(cond [(== p NULL) (Scm_SigCheck (Scm_VM)) (return '#f)] |
| 363 |
[else (return (Scm_MakeInteger (-> p pw_uid)))]))) |
| 364 |
|
| 365 |
;;--------------------------------------------------------------------- |
| 366 |
;; signal.h |
| 367 |
|
| 368 |
(inline-stub |
| 369 |
(define-enum SIG_SETMASK) |
| 370 |
(define-enum SIG_BLOCK) |
| 371 |
(define-enum SIG_UNBLOCK) |
| 372 |
) |
| 373 |
|
| 374 |
(define-cproc sys-sigset-add! (set::<sys-sigset> :rest sigs) |
| 375 |
(return (Scm_SysSigsetOp set sigs FALSE))) |
| 376 |
|
| 377 |
(define-cproc sys-sigset-delete! (set::<sys-sigset> :rest sigs) |
| 378 |
(return (Scm_SysSigsetOp set sigs TRUE))) |
| 379 |
|
| 380 |
(define-cproc sys-sigset-fill! (set::<sys-sigset>) |
| 381 |
(return (Scm_SysSigsetFill set FALSE))) |
| 382 |
|
| 383 |
(define-cproc sys-sigset-empty! (set::<sys-sigset>) |
| 384 |
(return (Scm_SysSigsetFill set TRUE))) |
| 385 |
|
| 386 |
(define-cproc sys-signal-name (sig::<fixnum>) Scm_SignalName) |
| 387 |
|
| 388 |
(define-cproc sys-kill (process sig::<fixnum>) ::<void> Scm_SysKill) |
| 389 |
|
| 390 |
(define-cproc set-signal-handler! (sig proc :optional (mask::<sys-sigset>? #f)) |
| 391 |
Scm_SetSignalHandler) |
| 392 |
(define-cproc get-signal-handler (sig::<fixnum>) Scm_GetSignalHandler) |
| 393 |
(define-cproc get-signal-handler-mask (sig::<fixnum>) Scm_GetSignalHandlerMask) |
| 394 |
(define-cproc get-signal-handlers () Scm_GetSignalHandlers) |
| 395 |
|
| 396 |
(define-cproc set-signal-pending-limit (limit::<fixnum>) ::<void> |
| 397 |
Scm_SetSignalPendingLimit) |
| 398 |
(define-cproc get-signal-pending-limit () ::<int> |
| 399 |
Scm_GetSignalPendingLimit) |
| 400 |
|
| 401 |
(define-cproc sys-sigmask (how::<fixnum> mask::<sys-sigset>?) Scm_SysSigmask) |
| 402 |
|
| 403 |
(define-cproc sys-sigsuspend (mask::<sys-sigset>) Scm_SigSuspend) |
| 404 |
|
| 405 |
(define-cproc sys-sigwait (mask::<sys-sigset>) ::<int> Scm_SigWait) |
| 406 |
|
| 407 |
(define (sys-sigset . signals) |
| 408 |
(if (null? signals) |
| 409 |
(make <sys-sigset>) |
| 410 |
(apply sys-sigset-add! (make <sys-sigset>) signals))) |
| 411 |
|
| 412 |
;;--------------------------------------------------------------------- |
| 413 |
;; stdio.h |
| 414 |
|
| 415 |
(define-cproc sys-remove (filename::<const-cstring>) ::<void> |
| 416 |
(let* ([r::int]) |
| 417 |
(SCM_SYSCALL r (remove filename)) |
| 418 |
(when (< r 0) (Scm_SysError "remove failed on %s" filename)))) |
| 419 |
|
| 420 |
(define-cproc sys-rename (oldname::<const-cstring> |
| 421 |
newname::<const-cstring>) |
| 422 |
::<void> |
| 423 |
(let* ([r::int]) |
| 424 |
(.when (defined "GAUCHE_WINDOWS") |
| 425 |
;; Windows doesn't allow renaming to the existing file, so we unlink |
| 426 |
;; it first. This breaks the atomicity of rename operation. |
| 427 |
;; We don't check and raise an error here, since the error will be |
| 428 |
;; caught by rename() call. |
| 429 |
(chmod newname #o666) |
| 430 |
(unlink newname)) |
| 431 |
(SCM_SYSCALL r (rename oldname newname)) |
| 432 |
(when (< r 0) (Scm_SysError "renaming %s to %s failed" oldname newname)))) |
| 433 |
|
| 434 |
;; NB: Alghough tmpnam() is in POSIX, its use is discouraged because of |
| 435 |
;; potential security risk. We mimic it's behavior by mkstemp() if possible. |
| 436 |
(define-cproc sys-tmpnam () |
| 437 |
(.if "HAVE_MKSTEMP" |
| 438 |
(let* ([nam::(.array char [*]) "/tmp/fileXXXXXX"] [fd::int]) |
| 439 |
(SCM_SYSCALL fd (mkstemp nam)) |
| 440 |
(when (< fd 0) (Scm_SysError "mkstemp failed")) |
| 441 |
(close fd) |
| 442 |
(unlink nam) |
| 443 |
(return (SCM_MAKE_STR_COPYING nam))) |
| 444 |
(let* ([s::char* (tmpnam NULL)]) |
| 445 |
(return (SCM_MAKE_STR_COPYING s))))) |
| 446 |
|
| 447 |
(define-cproc sys-mkstemp (template::<string>) Scm_SysMkstemp) |
| 448 |
(define-cproc sys-mkdtemp (template::<string>) Scm_SysMkdtemp) |
| 449 |
|
| 450 |
;; ctermid |
| 451 |
(define-cproc sys-ctermid () |
| 452 |
(.if (defined "GAUCHE_WINDOWS") |
| 453 |
(return '"CON") |
| 454 |
(let* ([buf::(.array char [(+ L_ctermid 1)])]) |
| 455 |
(return (SCM_MAKE_STR_COPYING (ctermid buf)))))) |
| 456 |
|
| 457 |
;;--------------------------------------------------------------------- |
| 458 |
;; stdlib.h |
| 459 |
|
| 460 |
(define-cproc sys-exit (code) ::<void> |
| 461 |
(_exit (Scm_ObjToExitCode code))) |
| 462 |
|
| 463 |
(define-cproc sys-getenv (name::<const-cstring>) ::<const-cstring>? Scm_GetEnv) |
| 464 |
|
| 465 |
(define-cproc sys-abort () ::<void> abort) |
| 466 |
|
| 467 |
;; sys-realpath is in autoloaded sysutil.scm. |
| 468 |
|
| 469 |
;; Note: the return value of system() is not portable. |
| 470 |
;; NB: on WinNT, system("") aborts, so we filter it. |
| 471 |
(define-cproc sys-system (command::<const-cstring>) ::<int> |
| 472 |
(if (== (aref command 0) 0) |
| 473 |
(return 0) |
| 474 |
(SCM_SYSCALL SCM_RESULT (system command)))) |
| 475 |
|
| 476 |
(define-cproc sys-random () ::<long> |
| 477 |
(.cond [(and (defined "HAVE_RANDOM") (defined "HAVE_SRANDOM")) |
| 478 |
(return (random))] |
| 479 |
[(and (defined "LRAND48") (defined "SRAND48")) |
| 480 |
(return (lrand48))] |
| 481 |
[else |
| 482 |
;; fallback - we don't want to use rand(), for it is not |
| 483 |
;; a very good RNG. |
| 484 |
(return (rand))])) |
| 485 |
|
| 486 |
(define-cproc sys-srandom (seed) ::<void> |
| 487 |
(unless (SCM_EXACTP seed) (Scm_Error "exact integer required: %S" seed)) |
| 488 |
(.cond [(and (defined "HAVE_RANDOM") (defined "HAVE_SRANDOM")) |
| 489 |
(srandom (Scm_GetUInteger seed))] |
| 490 |
[(and (defined "LRAND48") (defined "SRAND48")) |
| 491 |
(srand48 (Scm_GetUInteger seed))] |
| 492 |
[else |
| 493 |
;; fallback - we don't want to use rand(), for it is not |
| 494 |
;; a very good RNG. |
| 495 |
(srand (Scm_GetUInteger seed))])) |
| 496 |
|
| 497 |
(inline-stub |
| 498 |
(define-constant RAND_MAX (c "Scm_MakeIntegerFromUI(RAND_MAX)")) |
| 499 |
) |
| 500 |
|
| 501 |
(define-cproc sys-environ () Scm_Environ) |
| 502 |
|
| 503 |
;; NB: |
| 504 |
(define-cproc sys-setenv (name::<const-cstring> |
| 505 |
value::<const-cstring> |
| 506 |
:optional (overwrite::<boolean> #f)) |
| 507 |
::<void> Scm_SetEnv) |
| 508 |
(define-cproc sys-unsetenv (name::<const-cstring>) ::<void> Scm_UnsetEnv) |
| 509 |
(define-cproc sys-clearenv () ::<void> Scm_ClearEnv) |
| 510 |
|
| 511 |
(define (sys-environ->alist :optional (envlist (sys-environ))) |
| 512 |
(map (^[envstr] (receive (pre post) (string-scan envstr #\= 'both) |
| 513 |
(if pre (cons pre post) (cons envstr "")))) |
| 514 |
envlist)) |
| 515 |
|
| 516 |
;; We implement sys-putenv on top of sys-setenv, which in turn uses |
| 517 |
;; either setenv(3) or putenv(3) based on the availability. |
| 518 |
;; We had old sys-putenv API as (sys-putenv name value), while the new one |
| 519 |
;; takes a single argument for the consistency to putenv(3). We support |
| 520 |
;; both APIs. |
| 521 |
;; NB: We don't check the platform allows modifying environments. If not, |
| 522 |
;; sys-setenv throws an error. It's up to the application to check the |
| 523 |
;; availability by (cond-expand [gauche.sys.setenv ...]). |
| 524 |
(define (sys-putenv name=value . other) |
| 525 |
(cond |
| 526 |
[(null? other) |
| 527 |
(check-arg string? name=value) |
| 528 |
(receive (name value) (string-scan name=value #\= 'both) |
| 529 |
(unless name |
| 530 |
(error "sys-putenv: argument doesn't contain '=':" name=value)) |
| 531 |
(sys-setenv name value #t))] |
| 532 |
[else (sys-setenv name=value (car other) #t)])) |
| 533 |
|
| 534 |
;;--------------------------------------------------------------------- |
| 535 |
;; string.h |
| 536 |
|
| 537 |
;; TODO: for thread safety, we should use strerror_r when available. |
| 538 |
;; unfortunately there are conflicting versions of strerror_r among |
| 539 |
;; various systems. |
| 540 |
(define-cproc sys-strerror (errno_::<int>) ::<const-cstring> strerror) |
| 541 |
|
| 542 |
;; Added in POSIX.1-2008. We could do something more meaningful if |
| 543 |
;; the platform doesn't have it, but this is the minimum support. |
| 544 |
;; TODO: strsignal() isn't MT-safe; not only with another thread |
| 545 |
;; calling strsignal(), but also with setlocale(). Eventually we'll |
| 546 |
;; add manual global lock. |
| 547 |
;; POSIX also doesn't say anything when signum isn't a supported signal |
| 548 |
;; number. We can't do much about it, though, so it's better just to expose |
| 549 |
;; the underlying function. |
| 550 |
(inline-stub |
| 551 |
(.if HAVE_STRSIGNAL |
| 552 |
(define-cproc sys-strsignal (signum::<int>) ::<const-cstring>? |
| 553 |
(return (strsignal signum))) |
| 554 |
(define-cproc sys-strsignal (_::<int>) ::<const-cstring>? |
| 555 |
(return NULL)))) |
| 556 |
|
| 557 |
;;--------------------------------------------------------------------- |
| 558 |
;; sys/loadavg.h |
| 559 |
|
| 560 |
(inline-stub |
| 561 |
(.if (defined HAVE_GETLOADAVG) |
| 562 |
(define-cproc sys-getloadavg (:optional (nsamples::<int> 3)) |
| 563 |
(let* ([samples::(.array double [3])] |
| 564 |
[_ (when (or (<= nsamples 0) (> nsamples 3)) |
| 565 |
(Scm_Error "sys-getloadavg: argument out of range: %d" nsamples))] |
| 566 |
[count::int (getloadavg samples nsamples)]) |
| 567 |
(if (< count 0) |
| 568 |
(return '#f) |
| 569 |
(let* ([h '()] [t '()]) |
| 570 |
(dotimes [i count] |
| 571 |
(let* ([n (Scm_MakeFlonum (aref samples i))]) |
| 572 |
(SCM_APPEND1 h t n))) |
| 573 |
(return h))))) |
| 574 |
(define-cproc sys-getloadavg (:optional _::<int>) |
| 575 |
(begin |
| 576 |
(Scm_Error "sys-getloadavg isn't supported on this platform") |
| 577 |
(return SCM_UNDEFINED)))) |
| 578 |
) |
| 579 |
;;--------------------------------------------------------------------- |
| 580 |
;; sys/mman.h |
| 581 |
|
| 582 |
(inline-stub |
| 583 |
(define-cclass <memory-region> |
| 584 |
"ScmMemoryRegion*" "Scm_MemoryRegionClass" |
| 585 |
() |
| 586 |
((address :c-name "ptr" |
| 587 |
:c-spec "Scm_MakeIntegerU((uintptr_t)obj->ptr)" :setter #f) |
| 588 |
(size :type <size_t> :setter #f) |
| 589 |
(protection :c-name "prot" :type <int> :setter #f) |
| 590 |
(flags :type <int> :setter #f)) |
| 591 |
(printer (let* ((m::ScmMemoryRegion* (SCM_MEMORY_REGION obj))) |
| 592 |
(Scm_Printf port "#<memory-region %p[%lx] (%s%s%s)>" |
| 593 |
(-> m ptr) (-> m size) |
| 594 |
(?: (logand (-> m prot) PROT_READ) "r" "") |
| 595 |
(?: (logand (-> m prot) PROT_WRITE) "w" "") |
| 596 |
(?: (logand (-> m prot) PROT_EXEC) "x" "")))))) |
| 597 |
|
| 598 |
(define-cproc sys-mmap (maybe-port prot::<int> flags::<int> size::<size_t> |
| 599 |
:optional (off::<off_t> 0)) |
| 600 |
(let* ([fd::int -1]) |
| 601 |
(cond [(SCM_PORTP maybe-port) |
| 602 |
(set! fd (Scm_PortFileNo (SCM_PORT maybe-port))) |
| 603 |
(when (< fd 0) |
| 604 |
(Scm_Error "non-file-backed port can't be used to mmap: %S" |
| 605 |
maybe-port))] |
| 606 |
[(SCM_FALSEP maybe-port)] |
| 607 |
[else (SCM_TYPE_ERROR maybe-port "port or #f")]) |
| 608 |
(return (Scm_SysMmap NULL fd size off prot flags)))) |
| 609 |
|
| 610 |
(inline-stub |
| 611 |
(define-enum PROT_EXEC) |
| 612 |
(define-enum PROT_READ) |
| 613 |
(define-enum PROT_WRITE) |
| 614 |
(define-enum PROT_NONE) |
| 615 |
(define-enum MAP_SHARED) |
| 616 |
(define-enum MAP_PRIVATE) |
| 617 |
(define-enum MAP_ANONYMOUS)) |
| 618 |
|
| 619 |
;;--------------------------------------------------------------------- |
| 620 |
;; sys/resource.h |
| 621 |
|
| 622 |
(inline-stub |
| 623 |
(.when (defined "HAVE_SYS_RESOURCE_H") |
| 624 |
(.if (== SIZEOF_RLIM_T 4) |
| 625 |
(begin |
| 626 |
(.define MAKERLIMIT (val) (Scm_MakeIntegerU val)) |
| 627 |
(.define GETRLIMIT (obj) (Scm_GetIntegerU obj))) |
| 628 |
(.if (== SIZEOF_RLIM_T 8) |
| 629 |
(begin |
| 630 |
(.define MAKERLIMIT (val) (Scm_MakeIntegerU64 val)) |
| 631 |
(.define GETRLIMIT (obj) (Scm_GetIntegerU64 obj))) |
| 632 |
(.error "rlim_t must be 32bit or 64bit"))) |
| 633 |
|
| 634 |
(define-cproc sys-getrlimit (rsrc::<int>) ::(<integer> <integer>) |
| 635 |
(let* ([limit::(struct rlimit)] [ret::int]) |
| 636 |
(SCM_SYSCALL ret (getrlimit rsrc (& limit))) |
| 637 |
(when (< ret 0) (Scm_SysError "getrlimit failed")) |
| 638 |
(return (MAKERLIMIT (ref limit rlim_cur)) |
| 639 |
(MAKERLIMIT (ref limit rlim_max))))) |
| 640 |
|
| 641 |
(define-cproc sys-setrlimit (rsrc::<int> cur :optional (max #f)) ::<void> |
| 642 |
(let* ([limit::(struct rlimit)] [ret::int]) |
| 643 |
(when (or (SCM_FALSEP cur) (SCM_FALSEP max)) |
| 644 |
(SCM_SYSCALL ret (getrlimit rsrc (& limit))) |
| 645 |
(when (< ret 0) (Scm_SysError "getrlimit in sys-setrlimit failed"))) |
| 646 |
(cond [(SCM_INTEGERP cur) (set! (ref limit rlim_cur) (GETRLIMIT cur))] |
| 647 |
[(not (SCM_FALSEP cur)) |
| 648 |
(SCM_TYPE_ERROR cur "non-negative integer or #f")]) |
| 649 |
(cond [(SCM_INTEGERP max) (set! (ref limit rlim_max) (GETRLIMIT max))] |
| 650 |
[(not (SCM_FALSEP max)) |
| 651 |
(SCM_TYPE_ERROR max "non-negative integer or #f")]) |
| 652 |
(SCM_SYSCALL ret (setrlimit rsrc (& limit))) |
| 653 |
(when (< ret 0) (Scm_SysError "setrlimit failed")))) |
| 654 |
|
| 655 |
(define-constant RLIM_INFINITY (c "MAKERLIMIT(RLIM_INFINITY)")) |
| 656 |
(define-enum-conditionally RLIMIT_AS) |
| 657 |
(define-enum-conditionally RLIMIT_CORE) |
| 658 |
(define-enum-conditionally RLIMIT_CPU) |
| 659 |
(define-enum-conditionally RLIMIT_DATA) |
| 660 |
(define-enum-conditionally RLIMIT_FSIZE) |
| 661 |
(define-enum-conditionally RLIMIT_LOCKS) |
| 662 |
(define-enum-conditionally RLIMIT_MEMLOCK) |
| 663 |
(define-enum-conditionally RLIMIT_MSGQUEUE) |
| 664 |
(define-enum-conditionally RLIMIT_NICE) |
| 665 |
(define-enum-conditionally RLIMIT_NOFILE) |
| 666 |
(define-enum-conditionally RLIMIT_NPROC) |
| 667 |
(define-enum-conditionally RLIMIT_RSS) |
| 668 |
(define-enum-conditionally RLIMIT_RTPRIO) |
| 669 |
(define-enum-conditionally RLIMIT_SIGPENDING) |
| 670 |
(define-enum-conditionally RLIMIT_SBSIZE) |
| 671 |
(define-enum-conditionally RLIMIT_STACK) |
| 672 |
(define-enum-conditionally RLIMIT_OFILE) |
| 673 |
) ;; HAVE_SYS_RESOURCE_H |
| 674 |
) |
| 675 |
|
| 676 |
;;--------------------------------------------------------------------- |
| 677 |
;; sys/stat.h |
| 678 |
|
| 679 |
(inline-stub |
| 680 |
;; Commn code for stat and lstat. |
| 681 |
(define-cise-stmt stat-common |
| 682 |
[(_ statfn) |
| 683 |
`(let* ([s::ScmSysStat* (SCM_SYS_STAT (Scm_MakeSysStat))] [r::int] |
| 684 |
[p::(const char*) (check-trailing-separator path)]) |
| 685 |
(SCM_SYSCALL r (,statfn p (SCM_SYS_STAT_STAT s))) |
| 686 |
(when (< r 0) (Scm_SysError "%s failed for %s" ,(x->string statfn) p)) |
| 687 |
(return s))]) |
| 688 |
|
| 689 |
;; On Windows stat() fails if PATH has a trailing directory separator, |
| 690 |
;; except if we're stat()-ing the root directory. For the convenience |
| 691 |
;; we remove the trailing separator if any. It is quite complicated, |
| 692 |
;; for we have to deal with optional drive letters. |
| 693 |
(.when (defined "GAUCHE_WINDOWS") |
| 694 |
(define-cfn check-trailing-separator (path::(const char*)) |
| 695 |
::(const char*) :static |
| 696 |
(let* ([size::int (strlen path)] |
| 697 |
[ends::(const char*) (+ path size)] |
| 698 |
[lastchar::(const char*)]) |
| 699 |
(when (== size 0) (return path)) |
| 700 |
(SCM_CHAR_BACKWARD ends path lastchar) |
| 701 |
(unless (and (>= lastchar path) (< lastchar ends)) |
| 702 |
(Scm_SysError "invalid pathname: %s" path)) |
| 703 |
(when (and (not (== lastchar path)) |
| 704 |
(not (and (== lastchar (+ path 2)) |
| 705 |
(== (aref path 1) #\:))) |
| 706 |
(or (== (* lastchar) #\\) |
| 707 |
(== (* lastchar) #\/))) |
| 708 |
(let* ([pcopy::(char *) (SCM_NEW_ATOMIC_ARRAY (char) size)]) |
| 709 |
(memcpy pcopy path (- size 1)) |
| 710 |
(set! (aref pcopy (- size 1)) 0) |
| 711 |
(set! path (cast (const char *) pcopy)))) |
| 712 |
(return path)))) |
| 713 |
(.unless (defined "GAUCHE_WINDOWS") |
| 714 |
(define-cfn check-trailing-separator (path::(const char*)) |
| 715 |
::(const char*) :static (return path))) |
| 716 |
|
| 717 |
(define-cproc sys-stat (path::<const-cstring>) |
| 718 |
::<sys-stat> (stat-common stat)) |
| 719 |
|
| 720 |
;; On Windows we don't have lstat. Omitting sys-lstat from Windows is |
| 721 |
;; a bit inconvenient, however, to write a portable code if we do so. |
| 722 |
;; Since lstat() works identical to stat() if the path is a symlink, and |
| 723 |
;; on Windows path can never be a symlink, so we can just make sys-lstat |
| 724 |
;; work the same as sys-stat. |
| 725 |
(.if (not (defined "GAUCHE_WINDOWS")) |
| 726 |
(define-cproc sys-lstat (path::<const-cstring>) ::<sys-stat> |
| 727 |
(stat-common lstat)) |
| 728 |
(define-cproc sys-lstat (path::<const-cstring>) ::<sys-stat> |
| 729 |
(stat-common stat))) |
| 730 |
|
| 731 |
(.unless (defined "GAUCHE_WINDOWS") |
| 732 |
(define-cproc sys-mkfifo (path::<const-cstring> mode::<int>) ::<int> |
| 733 |
(SCM_SYSCALL SCM_RESULT (mkfifo path mode)) |
| 734 |
(when (< SCM_RESULT 0) (Scm_SysError "mkfifo failed on %s" path)))) |
| 735 |
) |
| 736 |
|
| 737 |
(define-cproc sys-fstat (port-or-fd) |
| 738 |
(let* ([s::ScmSysStat* (SCM_SYS_STAT (Scm_MakeSysStat))] |
| 739 |
[fd::int (Scm_GetPortFd port-or-fd FALSE)] |
| 740 |
[r::int]) |
| 741 |
(cond [(< fd 0) (return SCM_FALSE)] |
| 742 |
[else (SCM_SYSCALL r (fstat fd (SCM_SYS_STAT_STAT s))) |
| 743 |
(when (< r 0) (Scm_SysError "fstat failed for %d" fd)) |
| 744 |
(return (SCM_OBJ s))]))) |
| 745 |
|
| 746 |
(define-cproc file-exists? (path::<const-cstring>) ::<boolean> |
| 747 |
(let* ([r::int]) |
| 748 |
(SCM_SYSCALL r (access path F_OK)) |
| 749 |
(return (== r 0)))) |
| 750 |
|
| 751 |
(inline-stub |
| 752 |
(define-cise-stmt file-check-common |
| 753 |
[(_ checker) |
| 754 |
`(let* ([r::int] [s::ScmStat] |
| 755 |
[p::(const char*) (check-trailing-separator path)]) |
| 756 |
(SCM_SYSCALL r (access p F_OK)) |
| 757 |
(if (== r 0) |
| 758 |
(begin (SCM_SYSCALL r (stat p (& s))) |
| 759 |
(when (< r 0) |
| 760 |
(Scm_SysError "stat failed for %s" path)) |
| 761 |
(return (,checker (ref s st_mode)))) |
| 762 |
(return FALSE)))]) |
| 763 |
|
| 764 |
(define-cproc file-is-regular? (path::<const-cstring>) ::<boolean> |
| 765 |
(file-check-common S_ISREG)) |
| 766 |
(define-cproc file-is-directory? (path::<const-cstring>) ::<boolean> |
| 767 |
(file-check-common S_ISDIR)) |
| 768 |
) |
| 769 |
|
| 770 |
;; utime.h |
| 771 |
(define-cfn utime-ts (ts::ScmTimeSpec* arg) ::void :static |
| 772 |
(cond [(SCM_FALSEP arg) (set! (-> ts tv_nsec) UTIME_NOW)] |
| 773 |
[(SCM_TRUEP arg) (set! (-> ts tv_nsec) UTIME_OMIT)] |
| 774 |
[(SCM_REALP arg) |
| 775 |
(let* ([s::double]) |
| 776 |
(set! (-> ts tv_nsec) |
| 777 |
(cast u_long (* (modf (Scm_GetDouble arg) (& s)) |
| 778 |
1.0e9))) |
| 779 |
(set! (-> ts tv_sec) (cast u_long s)) |
| 780 |
(while (>= (-> ts tv_nsec) #e1e9) |
| 781 |
(set! (-> ts tv_nsec) (- (-> ts tv_nsec) #e1e9)) |
| 782 |
(pre++ (-> ts tv_sec))))] |
| 783 |
[(SCM_TIMEP arg) (Scm_GetTimeSpec arg ts)] |
| 784 |
[else (Scm_Error "<time> object, real number or boolean required, but got: %S" arg)])) |
| 785 |
|
| 786 |
(define-cproc sys-utime |
| 787 |
(path::<const-cstring> :optional (atime #f) (mtime #f)) ::<void> |
| 788 |
(let* ([tss::(.array ScmTimeSpec [2])] [r::int]) |
| 789 |
(utime-ts (& (aref tss 0)) atime) |
| 790 |
(utime-ts (& (aref tss 1)) mtime) |
| 791 |
(SCM_SYSCALL r (utimensat AT_FDCWD path tss 0)) |
| 792 |
(when (< r 0) (Scm_SysError "utimensat failed on %s" path)))) |
| 793 |
|
| 794 |
;;--------------------------------------------------------------------- |
| 795 |
;; sys/times.h |
| 796 |
|
| 797 |
;; we have emulation of times() in auxsys.c for mingw. |
| 798 |
(define-cproc sys-times () |
| 799 |
(let* ([info::(struct tms)] [r::clock_t] [tick::long]) |
| 800 |
(SCM_SYSCALL3 r (times (& info)) (== r (cast clock_t -1))) |
| 801 |
(when (== r (cast clock_t -1)) (Scm_SysError "times failed")) |
| 802 |
(.if (defined "_SC_CLK_TCK") |
| 803 |
(set! tick (sysconf _SC_CLK_TCK)) |
| 804 |
(.if (defined "CLK_TCK") |
| 805 |
(set! tick CLK_TCK) ; older name |
| 806 |
(set! tick 100))) ; fallback |
| 807 |
(return (list (Scm_MakeInteger (ref info tms_utime)) |
| 808 |
(Scm_MakeInteger (ref info tms_stime)) |
| 809 |
(Scm_MakeInteger (ref info tms_cutime)) |
| 810 |
(Scm_MakeInteger (ref info tms_cstime)) |
| 811 |
(Scm_MakeInteger tick))))) |
| 812 |
|
| 813 |
;;--------------------------------------------------------------------- |
| 814 |
;; sys/utsname.h |
| 815 |
|
| 816 |
(define-cproc sys-uname () |
| 817 |
(.if (not (defined "GAUCHE_WINDOWS")) |
| 818 |
(let* ([info::(struct utsname)]) |
| 819 |
(when (< (uname (& info)) 0) (Scm_SysError "uname failed")) |
| 820 |
(return (list (SCM_MAKE_STR_COPYING (ref info sysname)) |
| 821 |
(SCM_MAKE_STR_COPYING (ref info nodename)) |
| 822 |
(SCM_MAKE_STR_COPYING (ref info release)) |
| 823 |
(SCM_MAKE_STR_COPYING (ref info version)) |
| 824 |
(SCM_MAKE_STR_COPYING (ref info machine))))) |
| 825 |
;; TODO: Fill with appropriate info. |
| 826 |
(return (list SCM_FALSE SCM_FALSE SCM_FALSE SCM_FALSE SCM_FALSE)))) |
| 827 |
|
| 828 |
;;--------------------------------------------------------------------- |
| 829 |
;; sys/wait.h |
| 830 |
|
| 831 |
;; returns pid and status |
| 832 |
(define-cproc sys-wait () (return (Scm_SysWait (SCM_MAKE_INT -1) 0))) |
| 833 |
|
| 834 |
(define-cproc sys-waitpid (process :key (nohang #f) (untraced #f)) |
| 835 |
(let* ([options::int 0]) |
| 836 |
(unless (SCM_FALSEP nohang) (logior= options WNOHANG)) |
| 837 |
(unless (SCM_FALSEP untraced) (logior= options WUNTRACED)) |
| 838 |
(return (Scm_SysWait process options)))) |
| 839 |
|
| 840 |
;; status interpretation |
| 841 |
(define-cproc sys-wait-exited? (status::<int>) ::<boolean> WIFEXITED) |
| 842 |
(define-cproc sys-wait-exit-status (status::<int>) ::<int> WEXITSTATUS) |
| 843 |
(define-cproc sys-wait-signaled? (status::<int>) ::<boolean> WIFSIGNALED) |
| 844 |
(define-cproc sys-wait-termsig (status::<int>) ::<int> WTERMSIG) |
| 845 |
(define-cproc sys-wait-stopped? (status::<int>) ::<boolean> |
| 846 |
(cast void status) ; suppress unused var warning |
| 847 |
(return (WIFSTOPPED status))) |
| 848 |
(define-cproc sys-wait-stopsig (status::<int>) ::<int> WSTOPSIG) |
| 849 |
|
| 850 |
;;--------------------------------------------------------------------- |
| 851 |
;; time.h |
| 852 |
|
| 853 |
(define-cproc sys-time () (return (Scm_MakeSysTime (time NULL)))) |
| 854 |
|
| 855 |
(define-cproc sys-gettimeofday () ::(<ulong> <ulong>) |
| 856 |
(Scm_GetTimeOfDay (& SCM_RESULT0) (& SCM_RESULT1))) |
| 857 |
|
| 858 |
(define-cproc current-microseconds () ;EXPERIMENTAL |
| 859 |
::<long> Scm_CurrentMicroseconds) |
| 860 |
|
| 861 |
;; Returns #f and #f if the system doesn't provide monotonic time. |
| 862 |
(define-cproc sys-clock-gettime-monotonic () ::(<top> <top>) |
| 863 |
(let* ([sec::u_long] [nsec::u_long] |
| 864 |
[r::int (Scm_ClockGetTimeMonotonic (& sec) (& nsec))]) |
| 865 |
(if r |
| 866 |
(begin (set! SCM_RESULT0 (Scm_MakeIntegerU sec)) |
| 867 |
(set! SCM_RESULT1 (Scm_MakeIntegerU nsec))) |
| 868 |
(begin (set! SCM_RESULT0 SCM_FALSE) |
| 869 |
(set! SCM_RESULT1 SCM_FALSE))))) |
| 870 |
|
| 871 |
;; Returns #f and #f if the system doesn't provide monotonic time. |
| 872 |
(define-cproc sys-clock-getres-monotonic () ::(<top> <top>) |
| 873 |
(let* ([sec::u_long] [nsec::u_long] |
| 874 |
[r::int (Scm_ClockGetResMonotonic (& sec) (& nsec))]) |
| 875 |
(if r |
| 876 |
(begin (set! SCM_RESULT0 (Scm_MakeIntegerU sec)) |
| 877 |
(set! SCM_RESULT1 (Scm_MakeIntegerU nsec))) |
| 878 |
(begin (set! SCM_RESULT0 SCM_FALSE) |
| 879 |
(set! SCM_RESULT1 SCM_FALSE))))) |
| 880 |
|
| 881 |
(define-cproc current-time () ;SRFI-18, SRFI-19, SRFI-21, SRFI-226 |
| 882 |
Scm_CurrentTime) |
| 883 |
|
| 884 |
(define-cproc time? (obj) ;SRFI-18, SRFI-19, SRFI-21, SRFI-226 |
| 885 |
::<boolean> SCM_TIMEP) |
| 886 |
|
| 887 |
;; Obj can be <time>, real num or #f, as used in timeout argument for many |
| 888 |
;; procedures. Returns (<?> <time>) |
| 889 |
(define-cproc absolute-time (obj :optional (t0::<time>? #f)) ::<time>? |
| 890 |
(let* ([ts::ScmTimeSpec] |
| 891 |
[pts::ScmTimeSpec* (Scm_ToTimeSpec obj t0 (& ts))]) |
| 892 |
(if (== pts NULL) |
| 893 |
(return NULL) |
| 894 |
(return (SCM_TIME (Scm_MakeTime64 (?: t0 (-> t0 type) 'time-utc) |
| 895 |
(-> pts tv_sec) |
| 896 |
(-> pts tv_nsec))))))) |
| 897 |
|
| 898 |
(define (seconds+ t dt) |
| 899 |
(assume-type t <time>) |
| 900 |
(assume-type dt <real>) |
| 901 |
(absolute-time dt t)) ;SRFI-226 comatibility |
| 902 |
|
| 903 |
(define-cproc time->seconds (t::<time>) ;SRFI-18 |
| 904 |
Scm_TimeToSeconds) |
| 905 |
|
| 906 |
(define-cproc seconds->time (t::<double>) ;SRFI-18 |
| 907 |
Scm_RealSecondsToTime) |
| 908 |
|
| 909 |
(define time-comparator |
| 910 |
(make-comparator time? |
| 911 |
(^[a b] (zero? (compare a b))) |
| 912 |
(^[a b] (< (compare a b) 0)) |
| 913 |
default-hash)) |
| 914 |
|
| 915 |
(inline-stub |
| 916 |
(declare-cfn tm_print (obj port::ScmPort* ctx::ScmWriteContext*) |
| 917 |
::void :static) |
| 918 |
|
| 919 |
(define-cstruct <sys-tm> "struct tm" |
| 920 |
(sec::<int> "tm_sec" |
| 921 |
min::<int> "tm_min" |
| 922 |
hour::<int> "tm_hour" |
| 923 |
mday::<int> "tm_mday" |
| 924 |
mon::<int> "tm_mon" |
| 925 |
year::<int> "tm_year" |
| 926 |
wday::<int> "tm_wday" |
| 927 |
yday::<int> "tm_yday" |
| 928 |
isdst::<int> "tm_isdst") |
| 929 |
(printer (c "tm_print"))) |
| 930 |
|
| 931 |
(define-cfn tm_print (obj port::ScmPort* _::ScmWriteContext*) ::void |
| 932 |
(let* ([st::(struct tm*) (SCM_SYS_TM obj)] |
| 933 |
[fmt::(const char*)]) |
| 934 |
(.if (not (defined "GAUCHE_WINDOWS")) |
| 935 |
(set! fmt "%a %b %e %T %Y") |
| 936 |
(set! fmt "%a %b %d %H:%M:%S %Y")) |
| 937 |
(Scm_Printf port "#<sys-tm %S>" (Scm_StrfTime fmt st SCM_FALSE)))) |
| 938 |
) |
| 939 |
|
| 940 |
(define-cproc sys-asctime (tm::<sys-tm>) |
| 941 |
(return (SCM_MAKE_STR_COPYING (asctime tm)))) |
| 942 |
|
| 943 |
;; NB: For sys-ctime and sys-strftime, we don't use <const-cstring> return |
| 944 |
;; type to use autoboxing. |
| 945 |
;; See https://github.com/shirok/Gauche/issues/638#issuecomment-601777334 |
| 946 |
(define-cproc sys-ctime (time) |
| 947 |
(let* ([tim::time_t (Scm_GetSysTime time)]) |
| 948 |
(return (SCM_MAKE_STR_COPYING (ctime (& tim)))))) |
| 949 |
|
| 950 |
(define-cproc sys-difftime (time1 time0) ::<double> |
| 951 |
(return (difftime (Scm_GetSysTime time1) (Scm_GetSysTime time0)))) |
| 952 |
|
| 953 |
(define-cproc sys-strftime (format::<const-cstring> tm::<sys-tm>) |
| 954 |
(return (Scm_StrfTime format tm SCM_FALSE))) |
| 955 |
|
| 956 |
;; NB: Windows doesn't have gmtime_r/localtime_r, but its gmtime/localtime |
| 957 |
;; is thread-safe. |
| 958 |
;; On Unix, we pass struct tm buf to gmtime_r/localtime_r, and we need |
| 959 |
;; to copy it before the buf goes out of scope. So we don't use |
| 960 |
;; auto-boxing feature but manually call Scm_Make_sys_tm. |
| 961 |
(define-cproc sys-gmtime (time) |
| 962 |
(.if (defined "GAUCHE_WINDOWS") |
| 963 |
(let* ([tim::time_t (Scm_GetSysTime time)]) |
| 964 |
(return (Scm_Make_sys_tm (gmtime (& tim))))) |
| 965 |
(let* ([tim::time_t (Scm_GetSysTime time)] |
| 966 |
[buf::(struct tm)]) |
| 967 |
(return (Scm_Make_sys_tm (gmtime_r (& tim) (& buf))))))) |
| 968 |
|
| 969 |
(define-cproc sys-localtime (time) |
| 970 |
(.if (defined "GAUCHE_WINDOWS") |
| 971 |
(let* ([tim::time_t (Scm_GetSysTime time)]) |
| 972 |
(return (Scm_Make_sys_tm (localtime (& tim))))) |
| 973 |
(let* ([tim::time_t (Scm_GetSysTime time)] |
| 974 |
[buf::(struct tm)]) |
| 975 |
(return (Scm_Make_sys_tm (localtime_r (& tim) (& buf))))))) |
| 976 |
|
| 977 |
(define-cproc sys-mktime (tm::<sys-tm>) |
| 978 |
(return (Scm_MakeSysTime (mktime tm)))) |
| 979 |
|
| 980 |
;;--------------------------------------------------------------------- |
| 981 |
;; unistd.h - miscellaneous functions |
| 982 |
|
| 983 |
(inline-stub |
| 984 |
(define-enum R_OK) |
| 985 |
(define-enum W_OK) |
| 986 |
(define-enum X_OK) |
| 987 |
(define-enum F_OK) |
| 988 |
) |
| 989 |
|
| 990 |
(define-cproc sys-access (pathname::<const-cstring> amode::<int>) |
| 991 |
::<boolean> |
| 992 |
(let* ([r::int]) |
| 993 |
(when (Scm_IsSugid) |
| 994 |
(Scm_Error "cannot use sys-access in suid/sgid program.")) |
| 995 |
(SCM_SYSCALL r (access pathname amode)) |
| 996 |
(return (== r 0)))) |
| 997 |
|
| 998 |
(define-cproc sys-chdir (pathname::<const-cstring>) ::<void> |
| 999 |
(let* ([r::int]) |
| 1000 |
(SCM_SYSCALL r (chdir pathname)) |
| 1001 |
(when (< r 0) (Scm_SysError "chdir failed")))) |
| 1002 |
|
| 1003 |
(define-cproc sys-chmod (pathname::<const-cstring> mode::<int>) ::<void> |
| 1004 |
(let* ([r::int]) |
| 1005 |
(SCM_SYSCALL r (chmod pathname mode)) |
| 1006 |
(when (< r 0) (Scm_SysError "chmod failed")))) |
| 1007 |
|
| 1008 |
(inline-stub |
| 1009 |
(.unless (defined "GAUCHE_WINDOWS") |
| 1010 |
(define-cproc sys-fchmod (port-or-fd mode::<int>) ::<void> |
| 1011 |
(let* ([r::int] [fd::int (Scm_GetPortFd port-or-fd TRUE)]) |
| 1012 |
(SCM_SYSCALL r (fchmod fd mode)) |
| 1013 |
(when (< r 0) (Scm_SysError "fchmod failed")))) |
| 1014 |
) ;; !defined(GAUCHE_WINDOWS) |
| 1015 |
) |
| 1016 |
|
| 1017 |
;; chown |
| 1018 |
(define-cproc sys-chown (path::<const-cstring> owner::<int> group::<int>) |
| 1019 |
::<int> |
| 1020 |
(cast void owner) ; suppress unused var warning |
| 1021 |
(cast void group) ; suppress unused var warning |
| 1022 |
(.if (not (defined "GAUCHE_WINDOWS")) |
| 1023 |
(SCM_SYSCALL SCM_RESULT (chown path owner group)) |
| 1024 |
(set! SCM_RESULT 0)) |
| 1025 |
(when (< SCM_RESULT 0) (Scm_SysError "chown failed on %s" path))) |
| 1026 |
|
| 1027 |
(inline-stub |
| 1028 |
;; lchown |
| 1029 |
(.when (defined "HAVE_LCHOWN") |
| 1030 |
(define-cproc sys-lchown (path::<const-cstring> owner::<int> group::<int>) |
| 1031 |
::<int> |
| 1032 |
(SCM_SYSCALL SCM_RESULT (lchown path owner group)) |
| 1033 |
(when (< SCM_RESULT 0) (Scm_SysError "lchown failed on %S" path))) |
| 1034 |
) |
| 1035 |
) |
| 1036 |
|
| 1037 |
;; NB: we force GC just before fork(). It appears necessary on some |
| 1038 |
;; platform to synchronize the page dirty bit information, so that incremental |
| 1039 |
;; GC can work properly. |
| 1040 |
(define-cproc sys-fork () ::<int> |
| 1041 |
(let* ([pid::pid_t]) |
| 1042 |
(GC_gcollect) |
| 1043 |
(SCM_SYSCALL pid (fork)) |
| 1044 |
(when (< pid 0) (Scm_SysError "fork failed")) |
| 1045 |
(return pid))) |
| 1046 |
|
| 1047 |
(define-cproc sys-exec (command::<string> |
| 1048 |
args::<list> |
| 1049 |
:key |
| 1050 |
(iomap ()) |
| 1051 |
(sigmask::<sys-sigset>? #f) |
| 1052 |
(directory::<string>? #f) |
| 1053 |
(detached::<boolean> #f) |
| 1054 |
(environment #f)) |
| 1055 |
::<void> |
| 1056 |
(let* ([flags::u_long (?: detached SCM_EXEC_DETACHED 0)]) |
| 1057 |
(Scm_SysExec command args iomap sigmask directory environment flags))) |
| 1058 |
|
| 1059 |
(define-cproc sys-fork-and-exec (command::<string> |
| 1060 |
args::<list> |
| 1061 |
:key (iomap ()) (sigmask::<sys-sigset>? #f) |
| 1062 |
(directory::<string>? #f) |
| 1063 |
(detached::<boolean> #f) |
| 1064 |
(environment #f)) |
| 1065 |
(let* ([flags::u_int SCM_EXEC_WITH_FORK]) |
| 1066 |
(when detached |
| 1067 |
(set! flags (logior flags SCM_EXEC_DETACHED))) |
| 1068 |
(return |
| 1069 |
(Scm_SysExec command args iomap sigmask directory environment flags)))) |
| 1070 |
|
| 1071 |
(define-cproc sys-getcwd () Scm_GetCwd) |
| 1072 |
(define-cproc sys-getegid () ::<int> getegid) |
| 1073 |
(define-cproc sys-getgid () ::<int> getgid) |
| 1074 |
(define-cproc sys-geteuid () ::<int> geteuid) |
| 1075 |
(define-cproc sys-getuid () ::<int> getuid) |
| 1076 |
|
| 1077 |
(define-cproc sys-setugid? () ::<boolean> Scm_IsSugid) ; xBSD's issetugid() |
| 1078 |
|
| 1079 |
(define-cproc sys-getpid () ::<int> getpid) |
| 1080 |
(define-cproc sys-getppid () ::<int> getppid) |
| 1081 |
|
| 1082 |
(inline-stub |
| 1083 |
(.unless (defined "GAUCHE_WINDOWS") |
| 1084 |
(define-cproc sys-setgid (gid::<int>) ::<int> |
| 1085 |
(SCM_SYSCALL SCM_RESULT (setgid gid)) |
| 1086 |
(when (< SCM_RESULT 0) (Scm_SysError "setgid failed on %d" gid))) |
| 1087 |
|
| 1088 |
(define-cproc sys-setpgid (pid::<int> pgid::<int>) ::<int> |
| 1089 |
(SCM_SYSCALL SCM_RESULT (setpgid pid pgid)) |
| 1090 |
(when (< SCM_RESULT 0) |
| 1091 |
(Scm_SysError "setpgid failed on process %d for pgid %d" pid pgid))) |
| 1092 |
|
| 1093 |
;; The prototype of setpgrp() differs between platforms. We use |
| 1094 |
;; setpgid to implement sys-setpgrp. |
| 1095 |
;;(if (defined? "HAVE_SETPGRP") |
| 1096 |
;; (define-cproc %sys-setpgrp () |
| 1097 |
;; " int r = Scm_SysCall(setpgrp()); |
| 1098 |
;; if (r < 0) Scm_SysError(\"setpgrp failed\"); |
| 1099 |
;; SCM_RETURN(Scm_MakeInteger(r));")) |
| 1100 |
|
| 1101 |
(.when (defined "HAVE_GETPGID") |
| 1102 |
(define-cproc sys-getpgid (pid::<int>) ::<int> |
| 1103 |
(SCM_SYSCALL SCM_RESULT (cast int (getpgid pid))) |
| 1104 |
(when (< SCM_RESULT 0) (Scm_SysError "getpgid failed"))) |
| 1105 |
) |
| 1106 |
|
| 1107 |
(define-cproc sys-getpgrp () ::<int> |
| 1108 |
(SCM_SYSCALL SCM_RESULT (cast int (getpgrp))) |
| 1109 |
(when (< SCM_RESULT 0) (Scm_SysError "getpgrp failed"))) |
| 1110 |
|
| 1111 |
(define-cproc sys-setsid () ::<int> |
| 1112 |
(SCM_SYSCALL SCM_RESULT (setsid)) |
| 1113 |
(when (< SCM_RESULT 0) (Scm_SysError "setsid failed"))) |
| 1114 |
|
| 1115 |
(define-cproc sys-setuid (uid::<int>) ::<int> |
| 1116 |
(SCM_SYSCALL SCM_RESULT (setuid uid)) |
| 1117 |
(when (< SCM_RESULT 0) (Scm_SysError "setuid failed"))) |
| 1118 |
|
| 1119 |
(define-cfn call-nice (inc::int errno_save::int*) ::int |
| 1120 |
(set! errno 0) |
| 1121 |
(let* ([r::int (nice inc)]) |
| 1122 |
(set! (* errno_save) errno) |
| 1123 |
(return r))) |
| 1124 |
|
| 1125 |
(define-cproc sys-nice (inc::<int>) ::<int> |
| 1126 |
(let* ([errno_save::int 0]) |
| 1127 |
(SCM_SYSCALL SCM_RESULT (call-nice inc (& errno_save))) |
| 1128 |
(when (and (< SCM_RESULT 0) (!= errno 0)) |
| 1129 |
(Scm_SysError "nice failed")))) |
| 1130 |
|
| 1131 |
;; some less-frequently used get-* |
| 1132 |
|
| 1133 |
(define-cproc sys-getgroups () |
| 1134 |
(let* ([size::int 32] |
| 1135 |
[glist::(.array gid_t [32])] |
| 1136 |
[pglist::gid_t* glist]) |
| 1137 |
(loop (let* ([n::int (getgroups size pglist)]) |
| 1138 |
(when (>= n 0) |
| 1139 |
(let* ([h '()] [t '()]) |
| 1140 |
(dotimes [i n] |
| 1141 |
(SCM_APPEND1 h t (Scm_MakeInteger (aref pglist i)))) |
| 1142 |
(set! SCM_RESULT h) |
| 1143 |
(break))) |
| 1144 |
(cond [(== errno EINVAL) |
| 1145 |
(+= size size) |
| 1146 |
(set! pglist (SCM_NEW_ATOMIC_ARRAY gid_t size))] |
| 1147 |
[else (Scm_SysError "getgroups failed")]))))) |
| 1148 |
|
| 1149 |
(.when (defined "HAVE_SETGROUPS") |
| 1150 |
(define-cproc sys-setgroups (gids) ::<void> |
| 1151 |
(let* ([ngid::int (Scm_Length gids)] |
| 1152 |
[glist::gid_t* NULL] |
| 1153 |
[k::int 0] [r::int]) |
| 1154 |
(when (< ngid 0) |
| 1155 |
(Scm_Error "List of integer gids required, but got: %S" gids)) |
| 1156 |
(set! glist (SCM_NEW_ATOMIC_ARRAY gid_t ngid)) |
| 1157 |
(for-each (lambda (gid) |
| 1158 |
(unless (SCM_INTP gid) |
| 1159 |
(Scm_Error "gid list contains invalid value: %S" gid)) |
| 1160 |
(set! (aref glist k) (SCM_INT_VALUE gid)) |
| 1161 |
(post++ k)) |
| 1162 |
gids) |
| 1163 |
(SCM_SYSCALL r (setgroups ngid glist)) |
| 1164 |
(when (< r 0) |
| 1165 |
(Scm_SysError "setgroups failed with %S" gids))))) |
| 1166 |
) ;; !defined(GAUCHE_WINDOWS) |
| 1167 |
) |
| 1168 |
|
| 1169 |
(define (sys-setpgrp) (sys-setpgid 0 0)) |
| 1170 |
|
| 1171 |
(define-cproc sys-getlogin () ::<const-cstring>? getlogin) |
| 1172 |
|
| 1173 |
(define-cproc sys-link (existing::<const-cstring> |
| 1174 |
newpath::<const-cstring>) |
| 1175 |
::<void> |
| 1176 |
(let* ([r::int]) |
| 1177 |
(SCM_SYSCALL r (link existing newpath)) |
| 1178 |
(when (< r 0) (Scm_SysError "link failed")))) |
| 1179 |
|
| 1180 |
(define-cproc sys-pause () |
| 1181 |
;; We can't simply use pause(). If a signal is delivered after the last |
| 1182 |
;; Scm_SigCheck and before the call of pause(), the signal will just sit |
| 1183 |
;; in a queue and pause() may not return. |
| 1184 |
Scm_Pause) |
| 1185 |
|
| 1186 |
(define-cproc sys-alarm (seconds::<fixnum>) ::<int> |
| 1187 |
(SCM_SYSCALL SCM_RESULT (alarm seconds))) |
| 1188 |
|
| 1189 |
;; returns a list of two ports |
| 1190 |
(define-cproc sys-pipe (:key (name "(pipe)") (buffering #f) (buffered? #f)) |
| 1191 |
::(<top> <top>) |
| 1192 |
(let* ([fds::(.array int [2])] [mode::int] [r::int]) |
| 1193 |
(SCM_SYSCALL r (pipe fds)) |
| 1194 |
(when (< r 0) (Scm_SysError "pipe failed")) |
| 1195 |
(if (SCM_TRUEP buffered?) |
| 1196 |
(set! mode SCM_PORT_BUFFER_FULL) ; for backward compatibility |
| 1197 |
(set! mode (Scm_BufferingMode buffering -1 SCM_PORT_BUFFER_LINE))) |
| 1198 |
(return (Scm_MakePortWithFd name SCM_PORT_INPUT (aref fds 0) mode TRUE) |
| 1199 |
(Scm_MakePortWithFd name SCM_PORT_OUTPUT (aref fds 1)mode TRUE)))) |
| 1200 |
|
| 1201 |
;; close integer file descriptor. should only be used for |
| 1202 |
;; low-level file descriptor handling, and you know what you're doing. |
| 1203 |
;; closing a file descriptor that is still used by Scheme port would |
| 1204 |
;; result a disaster. |
| 1205 |
;; NB: close() is not retried on EINTR. By the time it returns EINTR the |
| 1206 |
;; fd has actually been closed, and if other thread happens to grab the same |
| 1207 |
;; fd, retrying close() inadvertently closes that one. |
| 1208 |
(define-cproc sys-close (fd::<int>) ::<void> |
| 1209 |
(let* ([r::int (close fd)]) |
| 1210 |
(when (< r 0) (Scm_SysError "close failed on file descriptor %d" fd)))) |
| 1211 |
|
| 1212 |
(define-cproc sys-mkdir (pathname::<const-cstring> mode::<int>) ::<void> |
| 1213 |
(let* ([r::int]) |
| 1214 |
(cast void mode) ; suppress unused var warning |
| 1215 |
(.if (not (defined "GAUCHE_WINDOWS")) |
| 1216 |
(SCM_SYSCALL r (mkdir pathname mode)) |
| 1217 |
(SCM_SYSCALL r (mkdir pathname))) |
| 1218 |
(when (< r 0) (Scm_SysError "mkdir failed on %s" pathname)))) |
| 1219 |
|
| 1220 |
(define-cproc sys-rmdir (pathname::<const-cstring>) ::<void> |
| 1221 |
(let* ([r::int]) |
| 1222 |
(SCM_SYSCALL r (rmdir pathname)) |
| 1223 |
(when (< r 0) (Scm_SysError "rmdir failed for %s" pathname)))) |
| 1224 |
|
| 1225 |
(define-cproc sys-umask (:optional mode) ::<int> |
| 1226 |
(cond [(or (SCM_UNBOUNDP mode) (SCM_FALSEP mode)) |
| 1227 |
(let* ([prev::int (umask 0)]) |
| 1228 |
(umask prev) |
| 1229 |
(return prev))] |
| 1230 |
[(SCM_INTP mode) (return (umask (SCM_INT_VALUE mode)))] |
| 1231 |
[else (SCM_TYPE_ERROR mode "fixnum or #f") (return 0)])) |
| 1232 |
|
| 1233 |
(define-cproc sys-sleep (seconds::<fixnum> |
| 1234 |
:optional (no-retry::<boolean> #f)) |
| 1235 |
::<int> |
| 1236 |
(cast void no-retry) ; suppress unused var warning |
| 1237 |
(.if (defined "GAUCHE_WINDOWS") |
| 1238 |
(begin (Sleep (* seconds 1000)) (return 0)) |
| 1239 |
(let* ([k::u_int (cast (u_int) seconds)] |
| 1240 |
[vm::ScmVM* (Scm_VM)]) |
| 1241 |
(while (> k 0) |
| 1242 |
(set! k (sleep k)) |
| 1243 |
(SCM_SIGCHECK vm) |
| 1244 |
(when no-retry (break))) |
| 1245 |
(return k)))) |
| 1246 |
|
| 1247 |
(inline-stub |
| 1248 |
(.when (or (defined "HAVE_NANOSLEEP") (defined "GAUCHE_WINDOWS")) |
| 1249 |
(define-cproc sys-nanosleep (nanoseconds |
| 1250 |
:optional (no-retry::<boolean> #f)) |
| 1251 |
(let* ([spec::ScmTimeSpec] [rem::ScmTimeSpec] |
| 1252 |
[vm::ScmVM* (Scm_VM)]) |
| 1253 |
(cond |
| 1254 |
[(SCM_TIMEP nanoseconds) |
| 1255 |
(set! (ref spec tv_sec) (-> (SCM_TIME nanoseconds) sec) |
| 1256 |
(ref spec tv_nsec) (-> (SCM_TIME nanoseconds) nsec))] |
| 1257 |
[(not (SCM_REALP nanoseconds)) |
| 1258 |
(Scm_Error "bad timeout spec: <time> object or real number is \ |
| 1259 |
required, but got %S" nanoseconds)] |
| 1260 |
[else |
| 1261 |
(let* ([v::double (Scm_GetDouble nanoseconds)]) |
| 1262 |
(when (< v 0) |
| 1263 |
(Scm_Error "bad timeout spec: positive number required, but got %S" |
| 1264 |
nanoseconds)) |
| 1265 |
(set! (ref spec tv_sec) (cast (unsigned long) (floor (/ v 1.0e9))) |
| 1266 |
(ref spec tv_nsec) (cast (unsigned long) (fmod v 1.0e9))) |
| 1267 |
(while (>= (ref spec tv_nsec) 1000000000) |
| 1268 |
(-= (ref spec tv_nsec) 1000000000) |
| 1269 |
(+= (ref spec tv_sec) 1)))]) |
| 1270 |
(set! (ref rem tv_sec) 0 (ref rem tv_nsec) 0) |
| 1271 |
(while (< (Scm_NanoSleep (& spec) (& rem)) 0) |
| 1272 |
(unless (== errno EINTR) |
| 1273 |
(Scm_SysError "nanosleep failed")) |
| 1274 |
(SCM_SIGCHECK vm) |
| 1275 |
(when no-retry (break)) |
| 1276 |
(set! spec rem) |
| 1277 |
(set! (ref rem tv_sec) 0 (ref rem tv_nsec) 0)) |
| 1278 |
(if (and (== (ref rem tv_sec) 0) (== (ref rem tv_nsec) 0)) |
| 1279 |
(return '#f) |
| 1280 |
(return (Scm_MakeTime '#f (ref rem tv_sec) (ref rem tv_nsec)))))) |
| 1281 |
) ; defined(HAVE_NANOSLEEP)||defined(GAUCHE_WINDOWS) |
| 1282 |
) |
| 1283 |
|
| 1284 |
(define-cproc sys-unlink (pathname::<const-cstring>) |
| 1285 |
(let* ([r::int]) |
| 1286 |
(.if (defined "GAUCHE_WINDOWS") |
| 1287 |
;; Windows doesn't allow unlinking a read-only file. We don't check |
| 1288 |
;; an error here, since the error will be caught by next unlink call. |
| 1289 |
(when (not (access pathname F_OK)) |
| 1290 |
(chmod pathname #o600))) |
| 1291 |
(SCM_SYSCALL r (unlink pathname)) |
| 1292 |
(if (< r 0) |
| 1293 |
(begin |
| 1294 |
(unless (== errno ENOENT) |
| 1295 |
(Scm_SysError "unlink failed on %s" pathname)) |
| 1296 |
(return '#f)) |
| 1297 |
(return '#t)))) |
| 1298 |
|
| 1299 |
(define-cproc sys-isatty (port_or_fd) ::<boolean> |
| 1300 |
(let* ([fd::int (Scm_GetPortFd port_or_fd FALSE)]) |
| 1301 |
(return (and (>= fd 0) (isatty fd))))) |
| 1302 |
|
| 1303 |
(define-cproc sys-ttyname (port_or_fd) ::<const-cstring>? |
| 1304 |
(let* ([fd::int (Scm_GetPortFd port_or_fd FALSE)]) |
| 1305 |
(return (?: (< fd 0) NULL (ttyname fd))))) |
| 1306 |
|
| 1307 |
(define-cproc sys-truncate (path::<const-cstring> length::<integer>) |
| 1308 |
::<void> |
| 1309 |
(let* ([r::int]) |
| 1310 |
(SCM_SYSCALL r (truncate path (Scm_IntegerToOffset length))) |
| 1311 |
(when (< r 0) (Scm_SysError "truncate failed on %s" path)))) |
| 1312 |
|
| 1313 |
(define-cproc sys-ftruncate (port_or_fd length::<integer>) ::<void> |
| 1314 |
(let* ([r::int] [fd::int (Scm_GetPortFd port_or_fd TRUE)]) |
| 1315 |
(SCM_SYSCALL r (ftruncate fd (Scm_IntegerToOffset length))) |
| 1316 |
(when (< r 0) (Scm_SysError "ftruncate failed on %S" port_or_fd)))) |
| 1317 |
|
| 1318 |
(inline-stub |
| 1319 |
;; NB. Linux needs _XOPEN_SOURCE defined before unistd.h to get crypt() |
| 1320 |
;; prototype. However, it screws up something else. Just for now I |
| 1321 |
;; cast the return value of crypt() to avoid it...such a kludge... |
| 1322 |
(.when (defined "HAVE_CRYPT") |
| 1323 |
(define-cproc sys-crypt (key::<const-cstring> salt::<const-cstring>) |
| 1324 |
::<const-cstring> (return (cast (const char *) (crypt key salt)))) |
| 1325 |
) |
| 1326 |
) |
| 1327 |
|
| 1328 |
(inline-stub |
| 1329 |
(.when (not (defined HOSTNAMELEN)) |
| 1330 |
(.define HOSTNAMELEN 1024))) |
| 1331 |
|
| 1332 |
(define-cproc sys-gethostname () |
| 1333 |
(.if (defined "HAVE_GETHOSTNAME") |
| 1334 |
(let* ([buf::(.array char [HOSTNAMELEN])] [r::int]) |
| 1335 |
(SCM_SYSCALL r (gethostname buf HOSTNAMELEN)) |
| 1336 |
(when (< r 0) (Scm_SysError "gethostname failed")) |
| 1337 |
(return (SCM_MAKE_STR_COPYING buf))) |
| 1338 |
;; TODO: find better alternative |
| 1339 |
(return (SCM_MAKE_STR_IMMUTABLE "localhost")))) |
| 1340 |
|
| 1341 |
(define-cproc sys-getdomainname () |
| 1342 |
(.if (defined "HAVE_GETDOMAINNAME") |
| 1343 |
(let* ([buf::(.array char [HOSTNAMELEN])] [r::int]) |
| 1344 |
(SCM_SYSCALL r (getdomainname buf HOSTNAMELEN)) |
| 1345 |
(when (< r 0) (Scm_SysError "getdomainame failed")) |
| 1346 |
(return (SCM_MAKE_STR_COPYING buf))) |
| 1347 |
;; TODO: find better alternative |
| 1348 |
(return (SCM_MAKE_STR_IMMUTABLE "local")))) |
| 1349 |
|
| 1350 |
;; not supported yet: |
| 1351 |
;; fpathconf lseek pathconf read sysconf write |
| 1352 |
|
| 1353 |
;;--------------------------------------------------------------------- |
| 1354 |
;; symbolic link |
| 1355 |
|
| 1356 |
(inline-stub |
| 1357 |
(.when (defined "HAVE_SYMLINK") |
| 1358 |
(define-cproc sys-symlink (existing::<const-cstring> |
| 1359 |
newpath::<const-cstring>) |
| 1360 |
::<void> |
| 1361 |
(let* ([r::int]) |
| 1362 |
(SCM_SYSCALL r (symlink existing newpath)) |
| 1363 |
(when (< r 0) |
| 1364 |
(Scm_SysError "symlink from %s to %s failed" newpath existing)))) |
| 1365 |
) |
| 1366 |
|
| 1367 |
(.when (defined "HAVE_READLINK") |
| 1368 |
(define-cproc sys-readlink (path::<const-cstring>) |
| 1369 |
(let* ([buf::(.array char [1024])] ; TODO: needs to be configured |
| 1370 |
[n::int]) |
| 1371 |
(SCM_SYSCALL n (readlink path buf 1024)) |
| 1372 |
(when (< n 0) (Scm_SysError "readlink failed on %s" path)) |
| 1373 |
(when (== n 1024) (Scm_Error "readlink result too long on %s" path)) |
| 1374 |
(return (Scm_MakeString buf n -1 SCM_STRING_COPYING)))) |
| 1375 |
) |
| 1376 |
) |
| 1377 |
|
| 1378 |
;;--------------------------------------------------------------------- |
| 1379 |
;; select |
| 1380 |
|
| 1381 |
(inline-stub |
| 1382 |
(.when (defined "HAVE_SELECT") |
| 1383 |
;; NB: On Windows, FD_SETSIZE merely indicates the maximum # of socket |
| 1384 |
;; descriptors fd_set can contain, and unrelated to the actual value |
| 1385 |
;; of the descriptor. This check is thus only valid on unixen. |
| 1386 |
(define-cise-stmt check-fd-range |
| 1387 |
[(_ fd) |
| 1388 |
(let1 fd_ (gensym) |
| 1389 |
`(.unless (defined "GAUCHE_WINDOWS") |
| 1390 |
(let* ((,fd_ :: int ,fd)) |
| 1391 |
(when (or (< ,fd_ 0) (>= ,fd_ FD_SETSIZE)) |
| 1392 |
(Scm_Error "File descriptor value is out of range: %d \ |
| 1393 |
(must be between 0 and %d, inclusive)" |
| 1394 |
,fd_ (- FD_SETSIZE 1))))))]) |
| 1395 |
|
| 1396 |
(define-cproc sys-fdset-ref (fdset::<sys-fdset> pf) ::<boolean> |
| 1397 |
(setter sys-fdset-set!) |
| 1398 |
(let* ([fd::int (Scm_GetPortFd pf FALSE)]) |
| 1399 |
(if (< fd 0) |
| 1400 |
(return TRUE) |
| 1401 |
(begin (check-fd-range fd) |
| 1402 |
(return (FD_ISSET fd (& (-> fdset fdset)))))))) |
| 1403 |
|
| 1404 |
(define-cproc sys-fdset-set! (fdset::<sys-fdset> pf flag::<boolean>) ::<void> |
| 1405 |
(let* ([fd::int (Scm_GetPortFd pf FALSE)]) |
| 1406 |
(when (>= fd 0) |
| 1407 |
(check-fd-range fd) |
| 1408 |
(cond [flag (FD_SET fd (& (-> fdset fdset))) |
| 1409 |
(when (< (-> fdset maxfd) fd) (set! (-> fdset maxfd) fd))] |
| 1410 |
[else (FD_CLR fd (& (-> fdset fdset))) |
| 1411 |
(when (== (-> fdset maxfd) fd) |
| 1412 |
(let* ([i::int (- (-> fdset maxfd) 1)]) |
| 1413 |
(for [() (>= i 0) (post-- i)] |
| 1414 |
(when (FD_ISSET i (& (-> fdset fdset))) (break))) |
| 1415 |
(set! (-> fdset maxfd) i)))])))) |
| 1416 |
|
| 1417 |
(define-cproc sys-fdset-max-fd (fdset::<sys-fdset>) ::<int> |
| 1418 |
(return (-> fdset maxfd))) |
| 1419 |
|
| 1420 |
(define-cproc sys-fdset-clear! (fdset::<sys-fdset>) |
| 1421 |
(FD_ZERO (& (-> fdset fdset))) |
| 1422 |
(set! (-> fdset maxfd) -1) |
| 1423 |
(return (SCM_OBJ fdset))) |
| 1424 |
|
| 1425 |
(define-cproc sys-fdset-copy! (dst::<sys-fdset> src::<sys-fdset>) |
| 1426 |
(set! (-> dst fdset) (-> src fdset) |
| 1427 |
(-> dst maxfd) (-> src maxfd)) |
| 1428 |
(return (SCM_OBJ dst))) |
| 1429 |
|
| 1430 |
(define-cproc sys-select (rfds wfds efds :optional (timeout #f)) |
| 1431 |
Scm_SysSelect) |
| 1432 |
|
| 1433 |
(define-cproc sys-select! (rfds wfds efds :optional (timeout #f)) |
| 1434 |
Scm_SysSelectX) |
| 1435 |
|
| 1436 |
) ;; when defined(HAVE_SELECT) |
| 1437 |
) |
| 1438 |
|
| 1439 |
;;--------------------------------------------------------------------- |
| 1440 |
;; miscellaneous |
| 1441 |
|
| 1442 |
(inline-stub |
| 1443 |
(define-cproc sys-available-processors () ::<int> |
| 1444 |
Scm_AvailableProcessors)) |
| 1445 |
|
| 1446 |
;;--------------------------------------------------------------------- |
| 1447 |
;; globbing |
| 1448 |
|
| 1449 |
(select-module gauche) |
| 1450 |
|
| 1451 |
;; glob-fold provides the fundamental logic of glob. It does not |
| 1452 |
;; depend on filesystems---any tree structure that has "pathname" |
| 1453 |
;; will do. |
| 1454 |
;; |
| 1455 |
;; <glob-pattern> : [<separator>] (<selector> <separator>)* [<separator>] |
| 1456 |
;; <selector> : '**' | <element>* |
| 1457 |
;; <element> : <ordinary> | '*' | '?' | <char-range> |
| 1458 |
;; <char-range> : '[' <char-set-spec> ']' |
| 1459 |
;; <ordinary> : characters except #[,*?\{\}\[\]\\] and <separator> |
| 1460 |
;; | '\\' <character> |
| 1461 |
;; |
| 1462 |
;; <separator> splits the components in the path. |
| 1463 |
|
| 1464 |
(define (glob patterns . opts) |
| 1465 |
(apply glob-fold patterns cons '() opts)) |
| 1466 |
|
| 1467 |
(define sys-glob glob) ;; backward compatibility |
| 1468 |
|
| 1469 |
(define (glob-fold patterns proc seed :key (separator #f) |
| 1470 |
(folder glob-fs-folder) |
| 1471 |
(sorter sort) |
| 1472 |
(prefix #f)) |
| 1473 |
(let* ([sep (or separator |
| 1474 |
;; Avoid using cond-expand, for this may be precompiled |
| 1475 |
;; on different architecture. |
| 1476 |
(if (assq 'gauche.os.windows |
| 1477 |
(with-module gauche.internal (cond-features))) |
| 1478 |
#[/\\] |
| 1479 |
#[/]))] |
| 1480 |
[r (fold (cut glob-fold-1 <> proc <> sep folder prefix) seed |
| 1481 |
(fold glob-expand-braces '() |
| 1482 |
(if (list? patterns) patterns (list patterns))))]) |
| 1483 |
(if sorter (sorter r) r))) |
| 1484 |
|
| 1485 |
;; NB: we avoid util.match due to the hairy dependency problem. |
| 1486 |
(define (glob-fold-1 pattern proc seed separator folder prefix) |
| 1487 |
(define (rec node matcher seed) |
| 1488 |
(cond [(null? matcher) seed] |
| 1489 |
[(eq? (car matcher) '**) (rec* node (cdr matcher) seed)] |
| 1490 |
[(null? (cdr matcher)) (folder proc seed node (car matcher) #f)] |
| 1491 |
[else (folder (^[node seed] (rec node (cdr matcher) seed)) |
| 1492 |
seed node (car matcher) #t)])) |
| 1493 |
(define (rec* node matcher seed) |
| 1494 |
(fold (cut rec* <> matcher <>) |
| 1495 |
(rec node matcher seed) |
| 1496 |
(folder cons '() node #/^[^.].*$/ #t))) |
| 1497 |
(let1 p (glob-prepare-pattern pattern separator prefix) |
| 1498 |
(rec (car p) (cdr p) seed))) |
| 1499 |
|
| 1500 |
(define (glob-prepare-pattern pattern separator prefix) |
| 1501 |
(define (f comp) |
| 1502 |
(cond [(equal? comp "") 'dir?] ; pattern ends with '/' |
| 1503 |
[(equal? comp "**") '**] |
| 1504 |
[else (glob-component->regexp comp)])) |
| 1505 |
(let1 comps (string-split pattern separator) |
| 1506 |
(if (equal? (car comps) "") |
| 1507 |
(cons #t (map f (cdr comps))) |
| 1508 |
(cons prefix (map f comps))))) |
| 1509 |
|
| 1510 |
;; */*.{c,scm} -> '(*/*.c */*.scm) |
| 1511 |
;; |
| 1512 |
;; NB: we first expand the braces to separate patterns. This is how |
| 1513 |
;; zsh and tcsh handles {...}. However, it is not good in terms of |
| 1514 |
;; performance, since the common prefix are searched mulitple times. |
| 1515 |
;; Hopefully we'll put some optimization here, making single traversal |
| 1516 |
;; for the common prefix. |
| 1517 |
;; |
| 1518 |
;; The treatment of backslashes is tricky. |
| 1519 |
;; |
| 1520 |
(define (glob-expand-braces pattern seed) |
| 1521 |
(define (parse str pres level) |
| 1522 |
(let loop ([str str] |
| 1523 |
[segs pres]) |
| 1524 |
(cond |
| 1525 |
[(rxmatch #/[{}]/ str) => |
| 1526 |
(^m |
| 1527 |
(cond [(equal? (m 0) "{") |
| 1528 |
(receive (ins post) (parse (m'after) '("") (+ level 1)) |
| 1529 |
(loop post |
| 1530 |
(fold (^[seg seed] |
| 1531 |
(fold (^[in seed] |
| 1532 |
(cons (string-append seg in) seed)) |
| 1533 |
seed ins)) |
| 1534 |
'() |
| 1535 |
(map (cute string-append <> (m'before)) segs))))] |
| 1536 |
[(= level 0) |
| 1537 |
(error "extra closing curly-brace in glob pattern:" pattern)] |
| 1538 |
[else ; closing curly-brace |
| 1539 |
(values (fold expand '() |
| 1540 |
(map (cute string-append <> (m'before)) segs)) |
| 1541 |
(m'after))]))] |
| 1542 |
[(= level 0) (values (map (cute string-append <> str) segs) #f)] |
| 1543 |
[else (error "unclosed curly-brace in glob pattern:" pattern)]))) |
| 1544 |
(define (expand pat seed) |
| 1545 |
(let1 segs (string-split pat #\,) |
| 1546 |
(if (null? seed) segs (append segs seed)))) |
| 1547 |
(if (string-scan pattern #\{) |
| 1548 |
(append (values-ref (parse pattern '("") 0) 0) seed) |
| 1549 |
(cons pattern seed))) |
| 1550 |
|
| 1551 |
;; Translate glob pattern to regexp. This is applied for each component, |
| 1552 |
;; so it assumes "**" is already expanded. |
| 1553 |
;; |
| 1554 |
;; This can also be used for shell's pattern matching (e.g. 'case'), |
| 1555 |
;; but it uses slightly different criteria. Notably, the glob mode (default) |
| 1556 |
;; treats the initial dot differently (e.g. '*' and '?' at the beginning |
| 1557 |
;; of the pattern doesn't match the beginning dot). The shell mode |
| 1558 |
;; doesn't have such criterion. |
| 1559 |
(define (glob-component->regexp pattern :key (mode :glob)) |
| 1560 |
(define n read-char) |
| 1561 |
(define nd '(comp . #[.])) |
| 1562 |
(define ra '(rep 0 #f any)) |
| 1563 |
(regexp-compile |
| 1564 |
(regexp-optimize |
| 1565 |
(with-input-from-string pattern |
| 1566 |
(^[] |
| 1567 |
(define (element0 ch ct) ;initial character |
| 1568 |
(case ch |
| 1569 |
[(#\*) (element0* (n) ct)] |
| 1570 |
[(#\?) `(,nd ,@(element1 (n) ct))] |
| 1571 |
[(#\\) (let1 next (n) |
| 1572 |
(if (eof-object? next) |
| 1573 |
'(eol) |
| 1574 |
`(,next ,@(element1 (n) ct))))] |
| 1575 |
[else (element1 ch ct)])) |
| 1576 |
(define (element0* ch ct) ;next to initial '*' |
| 1577 |
(case ch |
| 1578 |
[(#\*) (element0* (n) ct)] |
| 1579 |
[(#\?) `(,nd ,ra ,@(element1 (n) ct))] |
| 1580 |
[(#\.) `(,nd ,ra #\. ,@(element1 (n) ct))] |
| 1581 |
[(#\\) (let1 next (n) |
| 1582 |
`(,nd ,ra ,(if (eof-object? next) '(eol) next) |
| 1583 |
,@(element1 (n) ct)))] |
| 1584 |
[else `((rep 0 1 (seq ,nd ,ra)) |
| 1585 |
,@(element1 ch ct))])) |
| 1586 |
(define (element1 ch ct) |
| 1587 |
(cond [(eof-object? ch) '(eol)] |
| 1588 |
[(eqv? ch #\*) `(,ra ,@(element1* (n) ct))] |
| 1589 |
[(eqv? ch #\?) `(any ,@(element1 (n) ct))] |
| 1590 |
[(eqv? ch #\\) (let1 next (n) |
| 1591 |
(if (eof-object? next) |
| 1592 |
'(eol) |
| 1593 |
`(,next ,@(element1 (n) ct))))] |
| 1594 |
[(eqv? ch #\[) |
| 1595 |
(case (peek-char) |
| 1596 |
;; we have to treat [!...] as [^...] |
| 1597 |
[(#\!) (n) |
| 1598 |
(let1 cs (read-char-set (current-input-port)) |
| 1599 |
(cons (char-set-complement! cs) (element1 (n) ct)))] |
| 1600 |
[else |
| 1601 |
(let1 cs (read-char-set (current-input-port)) |
| 1602 |
(cons cs (element1 (n) ct)))])] |
| 1603 |
[else (cons ch (element1 (n) ct))])) |
| 1604 |
(define (element1* ch ct) |
| 1605 |
(case ch |
| 1606 |
[(#\*) (element1* (n) ct)] |
| 1607 |
[else (element1 ch ct)])) |
| 1608 |
(case mode |
| 1609 |
[(:glob) `(0 #f bol ,@(element0 (n) '()))] |
| 1610 |
[(:shell) `(0 #f bol ,@(element1 (n) '()))] |
| 1611 |
[else (error "mode argument must be :glob or :shell, but got" mode)])))))) |
| 1612 |
|
| 1613 |
;; if rx is just test perfect match, e.g. #/^string$/, returns |
| 1614 |
;; string portion. |
| 1615 |
(define (fixed-regexp? rx) |
| 1616 |
(let1 ast (regexp-ast rx) |
| 1617 |
(and (> (length ast) 4) |
| 1618 |
(eq? (caddr ast) 'bol) |
| 1619 |
(let loop ([cs (cdddr ast)] [r '()]) |
| 1620 |
(cond [(null? (cdr cs)) |
| 1621 |
(and (eq? (car cs) 'eol) (list->string (reverse r)))] |
| 1622 |
[(char? (car cs)) (loop (cdr cs) (cons (car cs) r))] |
| 1623 |
[else #f]))))) |
| 1624 |
|
| 1625 |
(define (make-glob-fs-fold :key (root-path #f) (current-path #f)) |
| 1626 |
;; NB: We don't use cond-expand, for precompilation may be done on |
| 1627 |
;; different architecture. |
| 1628 |
(let1 separ (if (#/mingw/ (gauche-architecture)) "\\" "/") |
| 1629 |
(define (ensure-dirname s) |
| 1630 |
(and s |
| 1631 |
(or (and-let* ([len (string-length s)] |
| 1632 |
[ (> len 0) ] |
| 1633 |
[ (not (eqv? (string-ref s (- len 1)) |
| 1634 |
(string-ref separ 0))) ]) |
| 1635 |
(string-append s separ)) |
| 1636 |
s))) |
| 1637 |
(define root-path/ (ensure-dirname root-path)) |
| 1638 |
(define current-path/ (ensure-dirname current-path)) |
| 1639 |
(^[proc seed node regexp non-leaf?] |
| 1640 |
(let1 prefix (case node |
| 1641 |
[(#t) (or root-path/ separ)] |
| 1642 |
[(#f) (or current-path/ "")] |
| 1643 |
[else (string-append node separ)]) |
| 1644 |
;; NB: we can't use filter, for it is not built-in. |
| 1645 |
;; also we can't use build-path from the same reason. |
| 1646 |
;; We treat fixed-regexp specially, since it allows |
| 1647 |
;; us not to search the directory---sometimes the directory |
| 1648 |
;; has 'x' permission but not 'r' permission, and it would be |
| 1649 |
;; unreasonable if we fail to go down the path even if we know |
| 1650 |
;; the exact name. |
| 1651 |
(cond [(eq? regexp 'dir?) (proc prefix seed)] |
| 1652 |
[(fixed-regexp? regexp) |
| 1653 |
=> (^s (let1 full (string-append prefix s) |
| 1654 |
(if (and (file-exists? full) |
| 1655 |
(or (not non-leaf?) |
| 1656 |
(file-is-directory? full))) |
| 1657 |
(proc full seed) |
| 1658 |
seed)))] |
| 1659 |
[else |
| 1660 |
(fold (^[child seed] |
| 1661 |
(or (and-let* ([ (regexp child) ] |
| 1662 |
[full (string-append prefix child)] |
| 1663 |
[ (or (not non-leaf?) |
| 1664 |
(file-is-directory? full)) ]) |
| 1665 |
(proc full seed)) |
| 1666 |
seed)) |
| 1667 |
seed |
| 1668 |
(sys-readdir (case node |
| 1669 |
[(#t) (or root-path/ "/")] |
| 1670 |
[(#f) (or current-path/ ".")] |
| 1671 |
[else node])))]))) |
| 1672 |
)) |
| 1673 |
|
| 1674 |
(define glob-fs-folder (make-glob-fs-fold)) |
| 1675 |
|
| 1676 |
;;; |
| 1677 |
;;; Windows-specific utility |
| 1678 |
;;; |
| 1679 |
|
| 1680 |
(inline-stub |
| 1681 |
(.when (defined "GAUCHE_WINDOWS") |
| 1682 |
;; Windows HANDLE wrapper |
| 1683 |
;; We use foreign pointer for HANDLE. If the type of handle is known at |
| 1684 |
;; the creation time, it is attached as the foreign pointer attribute |
| 1685 |
;; with the key 'handle-type. |
| 1686 |
|
| 1687 |
(define-cfn handle-cleanup (h) ::void :static |
| 1688 |
(CloseHandle (SCM_FOREIGN_POINTER_REF HANDLE h))) |
| 1689 |
|
| 1690 |
(define-cfn handle-print (h p::ScmPort* _::ScmWriteContext*) ::void :static |
| 1691 |
(let* ([type (Scm_ForeignPointerAttrGet (SCM_FOREIGN_POINTER h) |
| 1692 |
'handle-type '#f)]) |
| 1693 |
(cond |
| 1694 |
[(SCM_EQ type 'process) |
| 1695 |
(Scm_Printf p "#<win:handle process %d @%p>" (Scm_WinProcessPID h) h)] |
| 1696 |
[else |
| 1697 |
(Scm_Printf p "#<win:handle @%p>" h)]))) |
| 1698 |
|
| 1699 |
(declcode "static ScmClass *WinHandleClass = NULL;") |
| 1700 |
(initcode (= WinHandleClass (Scm_MakeForeignPointerClass |
| 1701 |
(Scm_CurrentModule) |
| 1702 |
"<win:handle>" handle-print handle-cleanup |
| 1703 |
SCM_FOREIGN_POINTER_KEEP_IDENTITY))) |
| 1704 |
|
| 1705 |
(define-cfn Scm_MakeWinHandle (wh::HANDLE type) |
| 1706 |
(let* ([h (Scm_MakeForeignPointer WinHandleClass wh)]) |
| 1707 |
(unless (SCM_FALSEP type) |
| 1708 |
(Scm_ForeignPointerAttrSet (SCM_FOREIGN_POINTER h) 'handle-type type)) |
| 1709 |
(return h))) |
| 1710 |
|
| 1711 |
(define-cfn Scm_WinHandleP (obj type) ::int |
| 1712 |
(unless (SCM_XTYPEP obj WinHandleClass) (return FALSE)) |
| 1713 |
(return |
| 1714 |
(or (SCM_FALSEP type) |
| 1715 |
(SCM_EQ type (Scm_ForeignPointerAttrGet (SCM_FOREIGN_POINTER obj) |
| 1716 |
'handle-type SCM_FALSE))))) |
| 1717 |
|
| 1718 |
(define-cfn Scm_WinHandle (h type) ::HANDLE |
| 1719 |
(unless (Scm_WinHandleP h type) (SCM_TYPE_ERROR h "<win:handle>")) |
| 1720 |
(return (SCM_FOREIGN_POINTER_REF HANDLE h))) |
| 1721 |
|
| 1722 |
;; windows process |
| 1723 |
|
| 1724 |
(define-cfn Scm_MakeWinProcess (h::HANDLE) |
| 1725 |
(return (Scm_MakeWinHandle h 'process))) |
| 1726 |
|
| 1727 |
(define-cfn Scm_WinProcessP (obj) ::int |
| 1728 |
(return (Scm_WinHandleP obj 'process))) |
| 1729 |
|
| 1730 |
(define-cfn Scm_WinProcess (obj) ::HANDLE |
| 1731 |
(return (Scm_WinHandle obj 'process))) |
| 1732 |
|
| 1733 |
(define-cproc sys-win-process? (obj) ::<boolean> Scm_WinProcessP) |
| 1734 |
(define-cproc sys-win-process-pid (obj) ::<int> Scm_WinProcessPID) |
| 1735 |
|
| 1736 |
;; windows handle |
| 1737 |
|
| 1738 |
(define-cproc sys-get-osfhandle (port-or-fd) |
| 1739 |
(let* ([fd::int (Scm_GetPortFd port-or-fd TRUE)] |
| 1740 |
[h::HANDLE (cast HANDLE (_get_osfhandle fd))]) |
| 1741 |
(when (== h INVALID_HANDLE_VALUE) (Scm_SysError "get_osfhandle failed")) |
| 1742 |
(return (Scm_MakeWinHandle h '#f)))) |
| 1743 |
|
| 1744 |
(define-cproc sys-win-pipe-name (port-or-fd) |
| 1745 |
(let* ([fd::int (Scm_GetPortFd port-or-fd FALSE)]) |
| 1746 |
(if (< fd 0) |
| 1747 |
(return '#f) |
| 1748 |
(return (Scm_WinGetPipeName (cast HANDLE (_get_osfhandle fd))))))) |
| 1749 |
|
| 1750 |
) ;; GAUCHE_WINDOWS |
| 1751 |
) |
| 1752 |
|
| 1753 |
;; MSYS Specific |
| 1754 |
;; When gosh is invoked in MSYS shell interactively, isatty() returns |
| 1755 |
;; FALSE since stdio communicates mintty with pipes. We can detect the |
| 1756 |
;; situation by checking pipe name. |
| 1757 |
;; This idea of using pipe name to detect mintty is taken from |
| 1758 |
;; http://github.com/k-takata/ptycheck. |
| 1759 |
(with-module gauche.internal |
| 1760 |
(define (%sys-mintty? port-or-fd) |
| 1761 |
(and-let* ([ (module-binds? 'gauche 'sys-win-pipe-name) ] |
| 1762 |
[n (sys-win-pipe-name port-or-fd)]) |
| 1763 |
(boolean (#/^\\msys-[\da-f]+-pty\d+-(to|from)-master.*$/ n)))) |
| 1764 |
) |
| 1765 |
|
| 1766 |
;; This is originally a part of shell-escape-string in gauche.process, |
| 1767 |
;; but the lower level function Scm_Exec() requires this to build |
| 1768 |
;; windows command line string from given argument list. It would be |
| 1769 |
;; clumsy to implement this in C, so we provide this here to be shared |
| 1770 |
;; by Scm_Exec() and shell-escape-string. |
| 1771 |
;; |
| 1772 |
;; NB: There is no reliable way to escape command line arguments on |
| 1773 |
;; windows, since the parsing is up to each application. However, most |
| 1774 |
;; applications rely on MSVC runtime library and we also follow it here. |
| 1775 |
;; Unfortunately, the official document lacks crucial details, and even |
| 1776 |
;; the described specification is twisted, as if the one who designed |
| 1777 |
;; it had a bad day and wanted to punish future programmers---or maybe |
| 1778 |
;; he wanted to punish MS so that future programmers would curse the |
| 1779 |
;; company forever. |
| 1780 |
;; |
| 1781 |
;; Anyway, the official document is here: |
| 1782 |
;; https://msdn.microsoft.com/en-us/library/a1y7w461.aspx |
| 1783 |
;; and what it doesn't tell is that a double-quote immediately following a |
| 1784 |
;; *closing* double-quote becomes a literal double-quote. (A double-quote |
| 1785 |
;; following an opening double-quote is just a closing double quote.) |
| 1786 |
;; Also, if the command line ends while within quoted span, a closing quote |
| 1787 |
;; is assumed. |
| 1788 |
;; |
| 1789 |
;; "" = open, close = empty string |
| 1790 |
;; """ = open, close, and literal = single #\" |
| 1791 |
;; """" = open, close, literal, open (+ assumed close) = single #\" |
| 1792 |
;; """"" = open, close, literal, open, close = single #\" |
| 1793 |
;; """""" = open, close, literal, open, close, literal = two #\"s |
| 1794 |
;; |
| 1795 |
;; The rule of backslash is also tricky, though this is documented. |
| 1796 |
;; |
| 1797 |
;; - If 2n backslashes immediately followed by #\", it becomes |
| 1798 |
;; n backslashes and we parse #\" normally in the context. |
| 1799 |
;; - If 2n+1 backslashes immediately followed by #\", it becomes |
| 1800 |
;; n backslahses and a literal #\". |
| 1801 |
;; - Otherwise, every backslash is literal. |
| 1802 |
;; |
| 1803 |
;; For example, simply escaping <"> to <\"> won't work, since if the |
| 1804 |
;; original double-quote is preceded by a backslash, resulting sequence |
| 1805 |
;; becomes <\\">, which is interpreted as single backslash and |
| 1806 |
;; delimiting (not literal) double-quote. |
| 1807 |
;; However, if we also escape every <\> to <\\>, it would be incorrect if |
| 1808 |
;; it isn't followed by double-quote. |
| 1809 |
;; The correct way is to get {N consecutive backslashes + double-quote}, |
| 1810 |
;; then replace it to {2N+1 consecutive backslashes + double-quote}. |
| 1811 |
;; |
| 1812 |
;; The flag BATFILEP is true when the command to be executed is a batch |
| 1813 |
;; file. In that case, the command line is parsed differently and the rule |
| 1814 |
;; is so twisted that it is virtually impossible to make it right. |
| 1815 |
;; For now, we reject arguments that contain 'unsafe' characters. |
| 1816 |
;; Cf. https://nvd.nist.gov/vuln/detail/CVE-2024-3566 |
| 1817 |
(define (%sys-escape-windows-command-line s batfilep) |
| 1818 |
(cond [(not (string? s)) |
| 1819 |
(%sys-escape-windows-command-line (write-to-string s))] |
| 1820 |
[(equal? s "") "\"\""] |
| 1821 |
[batfilep |
| 1822 |
(when (#/[()%!^<>&|\"]/ s) |
| 1823 |
(errorf "It is unsafe to pass argument ~s to BAT or CMD file." s)) |
| 1824 |
(if (string-scan s #\space) |
| 1825 |
(string-append "\"" s "\"") |
| 1826 |
s)] |
| 1827 |
[(#/[&<>\[\]{}^=\;!\'+,`~\s]/ s) |
| 1828 |
($ string-append "\"" |
| 1829 |
($ regexp-replace-all #/(\\*)\"/ s |
| 1830 |
(^m ($ string-append |
| 1831 |
(make-string (+ (* 2 (string-length (m 1))) 1) #\\) |
| 1832 |
"\""))) |
| 1833 |
"\"")] |
| 1834 |
[else s])) |