2 * rawbuffer.c: Manages buffers that might have been mmapped or malloced
5 * Miguel de Icaza (miguel@ximian.com)
7 * (C) 2001 Ximian, Inc.
10 #if defined(PLATFORM_WIN32)
11 #define USE_WIN32_API 1
21 #include <sys/types.h>
23 #include "rawbuffer.h"
25 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
26 #define ROUND_UP(VALUE,SIZE) (ROUND_DOWN((VALUE) + (SIZE) - 1, (SIZE)))
28 static GHashTable *mmap_map = NULL;
29 static size_t alignment = 0;
37 GetSystemInfo (&info);
38 alignment = info.dwAllocationGranularity;
40 alignment = getpagesize ();
45 mono_raw_buffer_load_malloc (int fd, int is_writable, guint32 base, size_t size)
49 ptr = g_malloc (size);
53 if (lseek (fd, base, 0) == (off_t) -1) {
63 mono_raw_buffer_free_malloc (void *base)
69 mono_raw_buffer_load_mmap (int fd, int is_writable, guint32 base, size_t size)
72 /* FileMapping implementation */
81 start = ROUND_DOWN (base, alignment);
85 prot = PAGE_WRITECOPY;
86 access = FILE_MAP_COPY;
90 access = FILE_MAP_READ;
93 file = (HANDLE) _get_osfhandle (fd);
94 mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
98 ptr = MapViewOfFile (mapping, access, 0, start, end - start);
100 CloseHandle (mapping);
104 if (mmap_map == NULL)
105 mmap_map = g_hash_table_new (g_direct_hash, g_direct_equal);
107 g_hash_table_insert (mmap_map, ptr, GINT_TO_POINTER (mapping));
109 return ((char *)ptr) + (base - start);
112 /* mmap implementation */
116 int prot = PROT_READ;
122 start = ROUND_DOWN (base, alignment);
123 end = ROUND_UP (base + size, alignment);
132 ptr = mmap (0, end - start, prot, flags, fd, start);
134 if (ptr == (void *) -1)
137 if (mmap_map == NULL)
138 mmap_map = g_hash_table_new (g_direct_hash, g_direct_equal);
140 g_hash_table_insert (mmap_map, ptr, GINT_TO_POINTER (size));
142 return ((char *)ptr) + (base - start);
147 mono_raw_buffer_free_mmap (void *base)
151 value = GPOINTER_TO_INT (g_hash_table_lookup (mmap_map, base));
154 UnmapViewOfFile (base);
155 CloseHandle ((HANDLE) value);
157 munmap (base, value);
162 mono_raw_buffer_update_mmap (void *base, size_t size)
165 FlushViewOfFile (base, size);
167 msync (base, size, MS_SYNC);
172 mono_raw_buffer_load (int fd, int is_writable, guint32 base, size_t size)
176 ptr = mono_raw_buffer_load_mmap (fd, is_writable, base, size);
178 ptr = mono_raw_buffer_load_malloc (fd, is_writable, base, size);
184 mono_raw_buffer_update (void *buffer, size_t size)
188 mmap_base = GINT_TO_POINTER (ROUND_DOWN (GPOINTER_TO_INT (buffer), alignment));
190 if (mmap_map && g_hash_table_lookup (mmap_map, mmap_base))
191 mono_raw_buffer_update_mmap (mmap_base, size);
195 mono_raw_buffer_free (void *buffer)
199 mmap_base = GINT_TO_POINTER (ROUND_DOWN (GPOINTER_TO_INT (buffer), alignment));
201 if (mmap_map && g_hash_table_lookup (mmap_map, mmap_base))
202 mono_raw_buffer_free_mmap (mmap_base);
204 mono_raw_buffer_free_malloc (buffer);