2010-06-15 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / utils / mono-filemap.c
1 /*
2  * mono-filemap.c: Unix/Windows implementation for filemap.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *
7  * Copyright 2008-2008 Novell, Inc.
8  */
9
10 #include "config.h"
11
12 #if HAVE_SYS_STAT_H
13 #include <sys/stat.h>
14 #endif
15 #include <fcntl.h>
16 #include <string.h>
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #include <stdlib.h>
21 #include <stdio.h>
22
23 #include "mono-mmap.h"
24
25 MonoFileMap *
26 mono_file_map_open (const char* name)
27 {
28         return (MonoFileMap *)fopen (name, "rb");
29 }
30
31 guint64 
32 mono_file_map_size (MonoFileMap *fmap)
33 {
34         struct stat stat_buf;
35         if (fstat (fileno ((FILE*)fmap), &stat_buf) < 0)
36                 return 0;
37         return stat_buf.st_size;
38 }
39
40 int
41 mono_file_map_fd (MonoFileMap *fmap)
42 {
43         return fileno ((FILE*)fmap);
44 }
45
46 int 
47 mono_file_map_close (MonoFileMap *fmap)
48 {
49         return fclose ((FILE*)fmap);
50 }
51
52 #if !defined(HAVE_MMAP) && !defined (HOST_WIN32)
53
54 static mono_file_map_alloc_fn alloc_fn = (mono_file_map_alloc_fn) malloc;
55 static mono_file_map_release_fn release_fn = (mono_file_map_release_fn) free;
56
57 void
58 mono_file_map_set_allocator (mono_file_map_alloc_fn alloc, mono_file_map_release_fn release)
59 {
60         alloc_fn = alloc == NULL     ? (mono_file_map_alloc_fn) malloc : alloc;
61         release_fn = release == NULL ? (mono_file_map_release_fn) free : release;
62 }
63
64 void *
65 mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
66 {
67         guint64 cur_offset;
68         size_t bytes_read;
69         void *ptr = (*alloc_fn) (length);
70         if (!ptr)
71                 return NULL;
72         cur_offset = lseek (fd, 0, SEEK_CUR);
73         if (lseek (fd, offset, SEEK_SET) != offset) {
74                 free (ptr);
75                 return NULL;
76         }
77         bytes_read = read (fd, ptr, length);
78         lseek (fd, cur_offset, SEEK_SET);
79         *ret_handle = NULL;
80         return ptr;
81 }
82
83 int
84 mono_file_unmap (void *addr, void *handle)
85 {
86         (*release_fn) (addr);
87         return 0;
88 }
89 #endif