First set of licensing changes
[mono.git] / mono / metadata / file-mmap-posix.c
1 /*
2  * file-mmap-posix.c: File mmap internal calls
3  *
4  * Author:
5  *      Rodrigo Kumpera
6  *
7  * Copyright 2014 Xamarin Inc (http://www.xamarin.com)
8  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
9  */
10
11 #include <config.h>
12
13 #ifndef HOST_WIN32
14
15 #include <glib.h>
16 #include <string.h>
17 #include <errno.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #ifdef HAVE_SYS_TYPES_H
25 #include <sys/types.h>
26 #endif
27 #if HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30
31 #include <fcntl.h>
32
33
34 #include <mono/metadata/object.h>
35 #include <mono/metadata/file-io.h>
36 #include <mono/metadata/file-mmap.h>
37 #include <mono/utils/atomic.h>
38 #include <mono/utils/mono-memory-model.h>
39 #include <mono/utils/mono-mmap.h>
40 #include <mono/utils/mono-coop-mutex.h>
41 #include <mono/utils/mono-threads.h>
42
43 typedef struct {
44         int kind;
45         int ref_count;
46         size_t capacity;
47         char *name;
48         int fd;
49 } MmapHandle;
50
51 typedef struct {
52         void *address;
53         void *free_handle;
54         size_t length;
55 } MmapInstance;
56
57 enum {
58         BAD_CAPACITY_FOR_FILE_BACKED = 1,
59         CAPACITY_SMALLER_THAN_FILE_SIZE,
60         FILE_NOT_FOUND,
61         FILE_ALREADY_EXISTS,
62         PATH_TOO_LONG,
63         COULD_NOT_OPEN,
64         CAPACITY_MUST_BE_POSITIVE,
65         INVALID_FILE_MODE,
66         COULD_NOT_MAP_MEMORY
67 };
68
69 enum {
70         FILE_MODE_CREATE_NEW = 1,
71         FILE_MODE_CREATE = 2,
72         FILE_MODE_OPEN = 3,
73         FILE_MODE_OPEN_OR_CREATE = 4,
74         FILE_MODE_TRUNCATE = 5,
75         FILE_MODE_APPEND = 6,
76 };
77
78 enum {
79         MMAP_FILE_ACCESS_READ_WRITE = 0,
80         MMAP_FILE_ACCESS_READ = 1,
81         MMAP_FILE_ACCESS_WRITE = 2,
82         MMAP_FILE_ACCESS_COPY_ON_WRITE = 3,
83         MMAP_FILE_ACCESS_READ_EXECUTE = 4,
84         MMAP_FILE_ACCESS_READ_WRITE_EXECUTE = 5,
85 };
86
87 #ifdef DEFFILEMODE
88 #define DEFAULT_FILEMODE DEFFILEMODE
89 #else
90 #define DEFAULT_FILEMODE 0666
91 #endif
92
93 static int mmap_init_state;
94 static MonoCoopMutex named_regions_mutex;
95 static GHashTable *named_regions;
96
97
98 static gint64
99 align_up_to_page_size (gint64 size)
100 {
101         gint64 page_size = mono_pagesize ();
102         return (size + page_size - 1) & ~(page_size - 1);
103 }
104
105 static gint64
106 align_down_to_page_size (gint64 size)
107 {
108         gint64 page_size = mono_pagesize ();
109         return size & ~(page_size - 1);
110 }
111
112 static void
113 file_mmap_init (void)
114 {
115 retry:  
116         switch (mmap_init_state) {
117         case  0:
118                 if (InterlockedCompareExchange (&mmap_init_state, 1, 0) != 0)
119                         goto retry;
120                 named_regions = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);
121                 mono_coop_mutex_init (&named_regions_mutex);
122
123                 mono_atomic_store_release (&mmap_init_state, 2);
124                 break;
125
126         case 1:
127                 do {
128                         mono_thread_info_sleep (1, NULL); /* Been init'd by other threads, this is very rare. */
129                 } while (mmap_init_state != 2);
130                 break;
131         case 2:
132                 break;
133         default:
134                 g_error ("Invalid init state %d", mmap_init_state);
135         }
136 }
137
138 static void
139 named_regions_lock (void)
140 {
141         file_mmap_init ();
142         mono_coop_mutex_lock (&named_regions_mutex);
143 }
144
145 static void
146 named_regions_unlock (void)
147 {
148         mono_coop_mutex_unlock (&named_regions_mutex);
149 }
150
151
152 static int
153 file_mode_to_unix (int mode)
154 {
155         switch (mode) {
156         case FILE_MODE_CREATE_NEW:
157         return O_CREAT | O_EXCL; 
158         case FILE_MODE_CREATE:
159         return O_CREAT | O_TRUNC;
160         case FILE_MODE_OPEN:
161                 return 0;
162         case FILE_MODE_OPEN_OR_CREATE:
163         return O_CREAT;
164         case FILE_MODE_TRUNCATE:
165         return O_TRUNC;
166         case FILE_MODE_APPEND:
167                 return O_APPEND;
168         default:
169                 g_error ("unknown FileMode %d", mode);
170         }
171 }
172
173 static int
174 access_mode_to_unix (int access)
175 {
176         switch (access) {
177         case MMAP_FILE_ACCESS_READ_WRITE:
178         case MMAP_FILE_ACCESS_COPY_ON_WRITE:
179         case MMAP_FILE_ACCESS_READ_WRITE_EXECUTE:
180                 return O_RDWR;
181         case MMAP_FILE_ACCESS_READ:
182         case MMAP_FILE_ACCESS_READ_EXECUTE:
183                 return O_RDONLY;
184         case MMAP_FILE_ACCESS_WRITE:
185                 return O_WRONLY;
186         default:
187                 g_error ("unknown MemoryMappedFileAccess %d", access);
188         }
189 }
190
191 static int
192 acess_to_mmap_flags (int access)
193 {
194         switch (access) {
195         case MMAP_FILE_ACCESS_READ_WRITE:
196         return MONO_MMAP_WRITE | MONO_MMAP_READ | MONO_MMAP_SHARED;
197         
198         case MMAP_FILE_ACCESS_WRITE:
199         return MONO_MMAP_WRITE | MONO_MMAP_SHARED;
200         
201         case MMAP_FILE_ACCESS_COPY_ON_WRITE:
202         return MONO_MMAP_WRITE | MONO_MMAP_READ | MONO_MMAP_PRIVATE;
203         
204         case MMAP_FILE_ACCESS_READ_EXECUTE:
205         return MONO_MMAP_EXEC | MONO_MMAP_PRIVATE | MONO_MMAP_SHARED;
206         
207         case MMAP_FILE_ACCESS_READ_WRITE_EXECUTE:
208         return MONO_MMAP_WRITE | MONO_MMAP_READ | MONO_MMAP_EXEC | MONO_MMAP_SHARED;
209         
210         case MMAP_FILE_ACCESS_READ:
211         return MONO_MMAP_READ | MONO_MMAP_SHARED;
212         default:
213                 g_error ("unknown MemoryMappedFileAccess %d", access);
214         }
215 }
216
217 /*
218 This allow us to special case zero size files that can be arbitrarily mapped.
219 */
220 static gboolean
221 is_special_zero_size_file (struct stat *buf)
222 {
223         return buf->st_size == 0 && (buf->st_mode & (S_IFCHR | S_IFBLK | S_IFIFO | S_IFSOCK)) != 0;
224 }
225
226 /*
227 XXX implement options
228 */
229 static void*
230 open_file_map (MonoString *path, int input_fd, int mode, gint64 *capacity, int access, int options, int *error)
231 {
232         struct stat buf;
233         char *c_path = path ? mono_string_to_utf8 (path) : NULL;
234         MmapHandle *handle = NULL;
235         int result, fd;
236
237         if (path)
238                 result = stat (c_path, &buf);
239         else
240                 result = fstat (input_fd, &buf);
241
242         if (mode == FILE_MODE_TRUNCATE || mode == FILE_MODE_APPEND || mode == FILE_MODE_OPEN) {
243                 if (result == -1) { //XXX translate errno?
244                         *error = FILE_NOT_FOUND;
245                         goto done;
246                 }
247         }
248
249         if (mode == FILE_MODE_CREATE_NEW && result == 0) {
250                 *error = FILE_ALREADY_EXISTS;
251                 goto done;
252         }
253
254         if (result == 0) {
255                 if (*capacity == 0) {
256                         /**
257                          * Special files such as FIFOs, sockets, and devices can have a size of 0. Specifying a capacity for these
258                          * also makes little sense, so don't do the check if th file is one of these.
259                          */
260                         if (buf.st_size == 0 && !is_special_zero_size_file (&buf)) {
261                                 *error = CAPACITY_SMALLER_THAN_FILE_SIZE;
262                                 goto done;
263                         }
264                         *capacity = buf.st_size;
265                 } else if (*capacity < buf.st_size) {
266                         *error = CAPACITY_SMALLER_THAN_FILE_SIZE;
267                         goto done;
268                 }
269         } else {
270                 if (mode == FILE_MODE_CREATE_NEW && *capacity == 0) {
271                         *error = CAPACITY_SMALLER_THAN_FILE_SIZE;
272                         goto done;
273                 }
274         }
275
276         if (path) //FIXME use io portability?
277                 fd = open (c_path, file_mode_to_unix (mode) | access_mode_to_unix (access), DEFAULT_FILEMODE);
278         else
279                 fd = dup (input_fd);
280
281         if (fd == -1) { //XXX translate errno?
282                 *error = COULD_NOT_OPEN;
283                 goto done;
284         }
285
286         if (result != 0 || *capacity > buf.st_size) {
287                 int unused G_GNUC_UNUSED = ftruncate (fd, (off_t)*capacity);
288         }
289
290         handle = g_new0 (MmapHandle, 1);
291         handle->ref_count = 1;
292         handle->capacity = *capacity;
293         handle->fd = fd;
294
295 done:
296         g_free (c_path);
297         return (void*)handle;
298 }
299
300 #define MONO_ANON_FILE_TEMPLATE "/mono.anonmap.XXXXXXXXX"
301 static void*
302 open_memory_map (MonoString *mapName, int mode, gint64 *capacity, int access, int options, int *error)
303 {
304         char *c_mapName;
305         MmapHandle *handle;
306         if (*capacity <= 1) {
307                 *error = CAPACITY_MUST_BE_POSITIVE;
308                 return NULL;
309         }
310
311         if (!(mode == FILE_MODE_CREATE_NEW || mode == FILE_MODE_OPEN_OR_CREATE || mode == FILE_MODE_OPEN)) {
312                 *error = INVALID_FILE_MODE;
313                 return NULL;
314         }
315
316         c_mapName = mono_string_to_utf8 (mapName);
317
318         named_regions_lock ();
319         handle = (MmapHandle*)g_hash_table_lookup (named_regions, c_mapName);
320         if (handle) {
321                 if (mode == FILE_MODE_CREATE_NEW) {
322                         *error = FILE_ALREADY_EXISTS;
323                         goto done;
324                 }
325
326                 handle->ref_count++;
327                 //XXX should we ftruncate if the file is smaller than capacity?
328         } else {
329                 int fd;
330                 char *file_name;
331                 const char *tmp_dir;
332                 int unused G_GNUC_UNUSED, alloc_size;
333
334                 if (mode == FILE_MODE_OPEN) {
335                         *error = FILE_NOT_FOUND;
336                         goto done;
337                 }
338                 *capacity = align_up_to_page_size (*capacity);
339
340                 tmp_dir = g_get_tmp_dir ();
341                 alloc_size = strlen (tmp_dir) + strlen (MONO_ANON_FILE_TEMPLATE) + 1;
342                 if (alloc_size > 1024) {//rather fail that stack overflow
343                         *error = COULD_NOT_MAP_MEMORY;
344                         goto done;
345                 }
346                 file_name = (char *)alloca (alloc_size);
347                 strcpy (file_name, tmp_dir);
348                 strcat (file_name, MONO_ANON_FILE_TEMPLATE);
349
350                 fd = mkstemp (file_name);
351                 if (fd == -1) {
352                         *error = COULD_NOT_MAP_MEMORY;
353                         goto done;
354                 }
355
356                 unlink (file_name);
357                 unused = ftruncate (fd, (off_t)*capacity);
358
359                 handle = g_new0 (MmapHandle, 1);
360                 handle->ref_count = 1;
361                 handle->capacity = *capacity;
362                 handle->fd = fd;
363                 handle->name = g_strdup (c_mapName);
364
365                 g_hash_table_insert (named_regions, handle->name, handle);
366
367         }
368
369 done:
370         named_regions_unlock ();
371
372         g_free (c_mapName);
373         return handle;
374 }
375
376
377 void *
378 mono_mmap_open_file (MonoString *path, int mode, MonoString *mapName, gint64 *capacity, int access, int options, int *error)
379 {
380         g_assert (path || mapName);
381
382         if (!mapName)
383                 return open_file_map (path, -1, mode, capacity, access, options, error);
384
385         if (path) {
386                 MmapHandle *handle;
387                 char *c_mapName = mono_string_to_utf8 (mapName);
388
389                 named_regions_lock ();
390                 handle = (MmapHandle*)g_hash_table_lookup (named_regions, c_mapName);
391                 if (handle) {
392                         *error = FILE_ALREADY_EXISTS;
393                         handle = NULL;
394                 } else {
395                         handle = (MmapHandle *)open_file_map (path, -1, mode, capacity, access, options, error);
396                         if (handle) {
397                                 handle->name = g_strdup (c_mapName);
398                                 g_hash_table_insert (named_regions, handle->name, handle);
399                         }
400                 }
401                 named_regions_unlock ();
402
403                 g_free (c_mapName);
404                 return handle;
405         }
406
407         return open_memory_map (mapName, mode, capacity, access, options, error);
408 }
409
410 void *
411 mono_mmap_open_handle (void *input_fd, MonoString *mapName, gint64 *capacity, int access, int options, int *error)
412 {
413         MmapHandle *handle;
414         if (!mapName) {
415                 handle = (MmapHandle *)open_file_map (NULL, GPOINTER_TO_INT (input_fd), FILE_MODE_OPEN, capacity, access, options, error);
416         } else {
417                 char *c_mapName = mono_string_to_utf8 (mapName);
418
419                 named_regions_lock ();
420                 handle = (MmapHandle*)g_hash_table_lookup (named_regions, c_mapName);
421                 if (handle) {
422                         *error = FILE_ALREADY_EXISTS;
423                         handle = NULL;
424                 } else {
425                         //XXX we're exploiting wapi HANDLE == FD equivalence. THIS IS FRAGILE, create a _wapi_handle_to_fd call
426                         handle = (MmapHandle *)open_file_map (NULL, GPOINTER_TO_INT (input_fd), FILE_MODE_OPEN, capacity, access, options, error);
427                         handle->name = g_strdup (c_mapName);
428                         g_hash_table_insert (named_regions, handle->name, handle);
429                 }
430                 named_regions_unlock ();
431
432                 g_free (c_mapName);
433         }
434         return handle;
435 }
436
437 void
438 mono_mmap_close (void *mmap_handle)
439 {
440         MmapHandle *handle = (MmapHandle *)mmap_handle;
441
442         named_regions_lock ();
443         --handle->ref_count;
444         if (handle->ref_count == 0) {
445                 if (handle->name)
446                         g_hash_table_remove (named_regions, handle->name);
447
448                 g_free (handle->name);
449                 close (handle->fd);
450                 g_free (handle);
451         }
452         named_regions_unlock ();
453 }
454
455 void
456 mono_mmap_configure_inheritability (void *mmap_handle, gboolean inheritability)
457 {
458         MmapHandle *h = (MmapHandle *)mmap_handle;
459         int fd, flags;
460
461         fd = h->fd;
462         flags = fcntl (fd, F_GETFD, 0);
463         if (inheritability)
464                 flags &= ~FD_CLOEXEC;
465         else
466                 flags |= FD_CLOEXEC;
467         fcntl (fd, F_SETFD, flags);     
468 }
469
470 void
471 mono_mmap_flush (void *mmap_handle)
472 {
473         MmapInstance *h = (MmapInstance *)mmap_handle;
474
475         if (h)
476                 msync (h->address, h->length, MS_SYNC);
477 }
478
479 int
480 mono_mmap_map (void *handle, gint64 offset, gint64 *size, int access, void **mmap_handle, void **base_address)
481 {
482         gint64 mmap_offset = 0;
483         MmapHandle *fh = (MmapHandle *)handle;
484         MmapInstance res = { 0 };
485         size_t eff_size = *size;
486         struct stat buf = { 0 };
487         fstat (fh->fd, &buf); //FIXME error handling
488
489         if (offset > buf.st_size || ((eff_size + offset) > buf.st_size && !is_special_zero_size_file (&buf)))
490                 goto error;
491         /**
492           * We use the file size if one of the following conditions is true:
493           *  -input size is zero
494           *  -input size is bigger than the file and the file is not a magical zero size file such as /dev/mem.
495           */
496         if (eff_size == 0)
497                 eff_size = align_up_to_page_size (buf.st_size) - offset;
498         *size = eff_size;
499
500         mmap_offset = align_down_to_page_size (offset);
501         eff_size += (offset - mmap_offset);
502         //FIXME translate some interesting errno values
503         res.address = mono_file_map ((size_t)eff_size, acess_to_mmap_flags (access), fh->fd, mmap_offset, &res.free_handle);
504         res.length = eff_size;
505
506         if (res.address) {
507                 *mmap_handle = g_memdup (&res, sizeof (MmapInstance));
508                 *base_address = (char*)res.address + (offset - mmap_offset);
509                 return 0;
510         }
511
512 error:
513         *mmap_handle = NULL;
514         *base_address = NULL;
515         return COULD_NOT_MAP_MEMORY;
516 }
517
518 gboolean
519 mono_mmap_unmap (void *mmap_handle)
520 {
521         int res = 0;
522         MmapInstance *h = (MmapInstance *)mmap_handle;
523
524         res = mono_file_unmap (h->address, h->free_handle);
525
526         g_free (h);
527         return res == 0;
528 }
529
530 #endif