Fix NET_2_0 build
[mono-project.git] / mono / utils / mono-filemap.c
blob36c7fd6df93abbdec09fb325c2957bad9dbe1e61
1 /*
2 * mono-filemap.c: Unix/Windows implementation for filemap.
4 * Author:
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2008-2008 Novell, Inc.
8 */
10 #include "config.h"
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>
23 #include "mono-mmap.h"
25 MonoFileMap *
26 mono_file_map_open (const char* name)
28 #ifdef WIN32
29 gunichar2 *wname = g_utf8_to_utf16 (name, -1, 0, 0, 0);
30 MonoFileMap *result;
32 if (wname == NULL)
33 return NULL;
34 result = (MonoFileMap *) _wfopen ((wchar_t *) wname, L"rb");
35 g_free (wname);
36 return result;
37 #else
38 return (MonoFileMap *)fopen (name, "rb");
39 #endif
42 guint64
43 mono_file_map_size (MonoFileMap *fmap)
45 struct stat stat_buf;
46 if (fstat (fileno ((FILE*)fmap), &stat_buf) < 0)
47 return 0;
48 return stat_buf.st_size;
51 int
52 mono_file_map_fd (MonoFileMap *fmap)
54 return fileno ((FILE*)fmap);
57 int
58 mono_file_map_close (MonoFileMap *fmap)
60 return fclose ((FILE*)fmap);
63 #if !defined (HOST_WIN32)
65 static mono_file_map_alloc_fn alloc_fn = (mono_file_map_alloc_fn) malloc;
66 static mono_file_map_release_fn release_fn = (mono_file_map_release_fn) free;
68 void
69 mono_file_map_set_allocator (mono_file_map_alloc_fn alloc, mono_file_map_release_fn release)
71 alloc_fn = alloc == NULL ? (mono_file_map_alloc_fn) malloc : alloc;
72 release_fn = release == NULL ? (mono_file_map_release_fn) free : release;
75 void *
76 mono_file_map_fileio (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
78 guint64 cur_offset;
79 size_t bytes_read;
80 void *ptr = (*alloc_fn) (length);
81 if (!ptr)
82 return NULL;
83 cur_offset = lseek (fd, 0, SEEK_CUR);
84 if (lseek (fd, offset, SEEK_SET) != offset) {
85 (*release_fn) (ptr);
86 return NULL;
88 bytes_read = read (fd, ptr, length);
89 if (bytes_read != length)
90 return NULL;
91 lseek (fd, cur_offset, SEEK_SET);
92 *ret_handle = NULL;
93 return ptr;
96 int
97 mono_file_unmap_fileio (void *addr, void *handle)
99 (*release_fn) (addr);
100 return 0;
102 #if !defined(HAVE_MMAP)
103 void *
104 mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
106 return mono_file_map_fileio (length, flags, fd, offset, ret_handle);
110 mono_file_unmap (void *addr, void *handle)
112 return mono_file_unmap_fileio(addr, handle);
114 #endif
115 #endif