| 1 |
#!r6rs |
| 2 |
;; Copyright 2009 Derick Eddington. My MIT-style license is in the file named |
| 3 |
;; LICENSE from the original collection this file is distributed with. |
| 4 |
|
| 5 |
;; NOTE: I believe this currently works only on Linux. |
| 6 |
;; NOTE: If Larceny's FFI changes, this may no longer work. |
| 7 |
|
| 8 |
(library (srfi :98 os-environment-variables) |
| 9 |
(export |
| 10 |
get-environment-variable get-environment-variables) |
| 11 |
(import |
| 12 |
(rnrs base) |
| 13 |
(rnrs control) |
| 14 |
(rnrs bytevectors) |
| 15 |
(rnrs io ports) |
| 16 |
(primitives |
| 17 |
foreign-procedure #;foreign-variable foreign-null-pointer? sizeof:pointer |
| 18 |
%peek-pointer %peek8u void*->address ffi/dlopen ffi/dlsym) |
| 19 |
(srfi private feature-cond)) |
| 20 |
|
| 21 |
;; TODO: Will the convenient string converters use the native transcoder in |
| 22 |
;; the future? So that scheme-str->c-str-bv and c-str-ptr->scheme-str |
| 23 |
;; won't be needed. |
| 24 |
|
| 25 |
(define (scheme-str->c-str-bv x) |
| 26 |
(let* ((bv (string->bytevector x (native-transcoder))) |
| 27 |
(len (bytevector-length bv)) |
| 28 |
(bv/z (make-bytevector (+ 1 len)))) |
| 29 |
(bytevector-copy! bv 0 bv/z 0 len) |
| 30 |
(bytevector-u8-set! bv/z len 0) |
| 31 |
bv/z)) |
| 32 |
|
| 33 |
(define (c-str-ptr->scheme-str x) |
| 34 |
(let loop ((x x) (a '())) |
| 35 |
(let ((b (%peek8u x))) |
| 36 |
(if (zero? b) |
| 37 |
(bytevector->string (u8-list->bytevector (reverse a)) |
| 38 |
(native-transcoder)) |
| 39 |
(loop (+ 1 x) (cons b a)))))) |
| 40 |
|
| 41 |
(define getenv |
| 42 |
(foreign-procedure "getenv" '(boxed) 'void*)) |
| 43 |
|
| 44 |
(define (get-environment-variable name) |
| 45 |
(unless (string? name) |
| 46 |
(assertion-violation 'get-environment-variable "not a string" name)) |
| 47 |
(let ((p (getenv (scheme-str->c-str-bv name)))) |
| 48 |
(and p |
| 49 |
(c-str-ptr->scheme-str (void*->address p))))) |
| 50 |
|
| 51 |
;; TODO: Will foreign-variable support a pointer type in the future? |
| 52 |
;; Would this be the correct way to use it? |
| 53 |
#;(define environ |
| 54 |
(foreign-variable "environ" 'void*)) |
| 55 |
|
| 56 |
;; TODO: Is (ffi/dlopen "") okay? It works for me on Ubuntu Linux 8.10. |
| 57 |
(define environ |
| 58 |
(feature-cond |
| 59 |
(linux |
| 60 |
(%peek-pointer (ffi/dlsym (ffi/dlopen "") "environ"))))) |
| 61 |
|
| 62 |
(define (get-environment-variables) |
| 63 |
(define (entry->pair x) |
| 64 |
(let* ((s (c-str-ptr->scheme-str x)) |
| 65 |
(len (string-length s))) |
| 66 |
(let loop ((i 0)) |
| 67 |
(if (< i len) |
| 68 |
(if (char=? #\= (string-ref s i)) |
| 69 |
(cons (substring s 0 i) |
| 70 |
(substring s (+ 1 i) len)) |
| 71 |
(loop (+ 1 i))) |
| 72 |
(cons s #F))))) |
| 73 |
(let loop ((e environ) (a '())) |
| 74 |
(let ((entry (%peek-pointer e))) |
| 75 |
(if (foreign-null-pointer? entry) |
| 76 |
a |
| 77 |
(loop (+ sizeof:pointer e) |
| 78 |
(cons (entry->pair entry) a)))))) |
| 79 |
) |