Added mmap utility and test
[rrq/lsp-utils.git] / lsp-misc / mmap.lsp
1 ;; This newlisp module implements mmap access to file regions.
2 ;;
3
4 (unless foop (load "foop.lsp"))
5
6 (context 'MAIN:MMap)
7
8 (FOOP base len prot flags fd offset)
9
10 (constant 'LIBC (exists file? '("/lib/x86_64-linux-gnu/libc.so.6")))
11 (unless LIBC (die "cannot find libc"))
12
13 (import LIBC "mmap" "void*" 
14         "void*" ; void *addr
15         "long" ; size_t length
16         "int" ; int prot
17         "int" ; int flags
18         "int" ; int fd
19         "long" ; off_t offset
20         )
21 (import LIBC "munmap" "int"
22         "void*" ; void *addr
23         "long" ; size_t length
24         )
25 (import LIBC "lseek" "long"
26         "int" ; int fd
27         "long" ; off_t offset,
28         "int" ; int whence
29         )
30
31 (constant
32  'PROT_READ 0x01
33  'MAP_SHARED 0x01
34  'SEEK_END 2
35  )
36
37 ;; Creates a new mapping in the virtual address space of the calling
38 ;; process.
39 (define (MMap:MMap FD LENGTH (OFFSET 0))
40   (when (string? FD) (setf FD (open FD "r")))
41   (let ((D (list (context) nil LENGTH 0 0 FD OFFSET)))
42     (when (< LENGTH) (setf (D 2) (lseek FD 0 SEEK_END)))
43     (setf (D 1) (mmap 0 (D 2) PROT_READ MAP_SHARED FD OFFSET))
44     D))
45
46 (define (Unmap)
47   (munmap (%base) (%len)))