Merge pull request #3056 from BrzVlad/fix-multiple-binprot
[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 *ioerror)
231 {
232         MonoError error;
233         struct stat buf;
234         char *c_path = NULL;
235         MmapHandle *handle = NULL;
236         int result, fd;
237
238         if (path) {
239                 c_path = mono_string_to_utf8_checked (path, &error);
240                 mono_error_raise_exception (&error); /* FIXME don't raise here */
241         }
242
243         if (path)
244                 result = stat (c_path, &buf);
245         else
246                 result = fstat (input_fd, &buf);
247
248         if (mode == FILE_MODE_TRUNCATE || mode == FILE_MODE_APPEND || mode == FILE_MODE_OPEN) {
249                 if (result == -1) { //XXX translate errno?
250                         *ioerror = FILE_NOT_FOUND;
251                         goto done;
252                 }
253         }
254
255         if (mode == FILE_MODE_CREATE_NEW && result == 0) {
256                 *ioerror = FILE_ALREADY_EXISTS;
257                 goto done;
258         }
259
260         if (result == 0) {
261                 if (*capacity == 0) {
262                         /**
263                          * Special files such as FIFOs, sockets, and devices can have a size of 0. Specifying a capacity for these
264                          * also makes little sense, so don't do the check if th file is one of these.
265                          */
266                         if (buf.st_size == 0 && !is_special_zero_size_file (&buf)) {
267                                 *ioerror = CAPACITY_SMALLER_THAN_FILE_SIZE;
268                                 goto done;
269                         }
270                         *capacity = buf.st_size;
271                 } else if (*capacity < buf.st_size) {
272                         *ioerror = CAPACITY_SMALLER_THAN_FILE_SIZE;
273                         goto done;
274                 }
275         } else {
276                 if (mode == FILE_MODE_CREATE_NEW && *capacity == 0) {
277                         *ioerror = CAPACITY_SMALLER_THAN_FILE_SIZE;
278                         goto done;
279                 }
280         }
281
282         if (path) //FIXME use io portability?
283                 fd = open (c_path, file_mode_to_unix (mode) | access_mode_to_unix (access), DEFAULT_FILEMODE);
284         else
285                 fd = dup (input_fd);
286
287         if (fd == -1) { //XXX translate errno?
288                 *ioerror = COULD_NOT_OPEN;
289                 goto done;
290         }
291
292         if (result != 0 || *capacity > buf.st_size) {
293                 int unused G_GNUC_UNUSED = ftruncate (fd, (off_t)*capacity);
294         }
295
296         handle = g_new0 (MmapHandle, 1);
297         handle->ref_count = 1;
298         handle->capacity = *capacity;
299         handle->fd = fd;
300
301 done:
302         g_free (c_path);
303         return (void*)handle;
304 }
305
306 #define MONO_ANON_FILE_TEMPLATE "/mono.anonmap.XXXXXXXXX"
307 static void*
308 open_memory_map (MonoString *mapName, int mode, gint64 *capacity, int access, int options, int *ioerror)
309 {
310         MonoError error;
311         char *c_mapName;
312         MmapHandle *handle;
313         if (*capacity <= 1) {
314                 *ioerror = CAPACITY_MUST_BE_POSITIVE;
315                 return NULL;
316         }
317
318         if (!(mode == FILE_MODE_CREATE_NEW || mode == FILE_MODE_OPEN_OR_CREATE || mode == FILE_MODE_OPEN)) {
319                 *ioerror = INVALID_FILE_MODE;
320                 return NULL;
321         }
322
323         c_mapName = mono_string_to_utf8_checked (mapName, &error);
324         mono_error_raise_exception (&error); /* FIXME don't raise here */
325
326         named_regions_lock ();
327         handle = (MmapHandle*)g_hash_table_lookup (named_regions, c_mapName);
328         if (handle) {
329                 if (mode == FILE_MODE_CREATE_NEW) {
330                         *ioerror = FILE_ALREADY_EXISTS;
331                         goto done;
332                 }
333
334                 handle->ref_count++;
335                 //XXX should we ftruncate if the file is smaller than capacity?
336         } else {
337                 int fd;
338                 char *file_name;
339                 const char *tmp_dir;
340                 int unused G_GNUC_UNUSED, alloc_size;
341
342                 if (mode == FILE_MODE_OPEN) {
343                         *ioerror = FILE_NOT_FOUND;
344                         goto done;
345                 }
346                 *capacity = align_up_to_page_size (*capacity);
347
348                 tmp_dir = g_get_tmp_dir ();
349                 alloc_size = strlen (tmp_dir) + strlen (MONO_ANON_FILE_TEMPLATE) + 1;
350                 if (alloc_size > 1024) {//rather fail that stack overflow
351                         *ioerror = COULD_NOT_MAP_MEMORY;
352                         goto done;
353                 }
354                 file_name = (char *)alloca (alloc_size);
355                 strcpy (file_name, tmp_dir);
356                 strcat (file_name, MONO_ANON_FILE_TEMPLATE);
357
358                 fd = mkstemp (file_name);
359                 if (fd == -1) {
360                         *ioerror = COULD_NOT_MAP_MEMORY;
361                         goto done;
362                 }
363
364                 unlink (file_name);
365                 unused = ftruncate (fd, (off_t)*capacity);
366
367                 handle = g_new0 (MmapHandle, 1);
368                 handle->ref_count = 1;
369                 handle->capacity = *capacity;
370                 handle->fd = fd;
371                 handle->name = g_strdup (c_mapName);
372
373                 g_hash_table_insert (named_regions, handle->name, handle);
374
375         }
376
377 done:
378         named_regions_unlock ();
379
380         g_free (c_mapName);
381         return handle;
382 }
383
384
385 void *
386 mono_mmap_open_file (MonoString *path, int mode, MonoString *mapName, gint64 *capacity, int access, int options, int *ioerror)
387 {
388         MonoError error;
389         g_assert (path || mapName);
390
391         if (!mapName)
392                 return open_file_map (path, -1, mode, capacity, access, options, ioerror);
393
394         if (path) {
395                 MmapHandle *handle;
396                 char *c_mapName = mono_string_to_utf8_checked (mapName, &error);
397                 mono_error_raise_exception (&error); /* FIXME don't raise here */
398
399                 named_regions_lock ();
400                 handle = (MmapHandle*)g_hash_table_lookup (named_regions, c_mapName);
401                 if (handle) {
402                         *ioerror = FILE_ALREADY_EXISTS;
403                         handle = NULL;
404                 } else {
405                         handle = (MmapHandle *)open_file_map (path, -1, mode, capacity, access, options, ioerror);
406                         if (handle) {
407                                 handle->name = g_strdup (c_mapName);
408                                 g_hash_table_insert (named_regions, handle->name, handle);
409                         }
410                 }
411                 named_regions_unlock ();
412
413                 g_free (c_mapName);
414                 return handle;
415         }
416
417         return open_memory_map (mapName, mode, capacity, access, options, ioerror);
418 }
419
420 void *
421 mono_mmap_open_handle (void *input_fd, MonoString *mapName, gint64 *capacity, int access, int options, int *ioerror)
422 {
423         MonoError error;
424         MmapHandle *handle;
425         if (!mapName) {
426                 handle = (MmapHandle *)open_file_map (NULL, GPOINTER_TO_INT (input_fd), FILE_MODE_OPEN, capacity, access, options, ioerror);
427         } else {
428                 char *c_mapName = mono_string_to_utf8_checked (mapName, &error);
429                 mono_error_raise_exception (&error); /* FIXME don't raise here */
430
431                 named_regions_lock ();
432                 handle = (MmapHandle*)g_hash_table_lookup (named_regions, c_mapName);
433                 if (handle) {
434                         *ioerror = FILE_ALREADY_EXISTS;
435                         handle = NULL;
436                 } else {
437                         //XXX we're exploiting wapi HANDLE == FD equivalence. THIS IS FRAGILE, create a _wapi_handle_to_fd call
438                         handle = (MmapHandle *)open_file_map (NULL, GPOINTER_TO_INT (input_fd), FILE_MODE_OPEN, capacity, access, options, ioerror);
439                         handle->name = g_strdup (c_mapName);
440                         g_hash_table_insert (named_regions, handle->name, handle);
441                 }
442                 named_regions_unlock ();
443
444                 g_free (c_mapName);
445         }
446         return handle;
447 }
448
449 void
450 mono_mmap_close (void *mmap_handle)
451 {
452         MmapHandle *handle = (MmapHandle *)mmap_handle;
453
454         named_regions_lock ();
455         --handle->ref_count;
456         if (handle->ref_count == 0) {
457                 if (handle->name)
458                         g_hash_table_remove (named_regions, handle->name);
459
460                 g_free (handle->name);
461                 close (handle->fd);
462                 g_free (handle);
463         }
464         named_regions_unlock ();
465 }
466
467 void
468 mono_mmap_configure_inheritability (void *mmap_handle, gboolean inheritability)
469 {
470         MmapHandle *h = (MmapHandle *)mmap_handle;
471         int fd, flags;
472
473         fd = h->fd;
474         flags = fcntl (fd, F_GETFD, 0);
475         if (inheritability)
476                 flags &= ~FD_CLOEXEC;
477         else
478                 flags |= FD_CLOEXEC;
479         fcntl (fd, F_SETFD, flags);     
480 }
481
482 void
483 mono_mmap_flush (void *mmap_handle)
484 {
485         MmapInstance *h = (MmapInstance *)mmap_handle;
486
487         if (h)
488                 msync (h->address, h->length, MS_SYNC);
489 }
490
491 int
492 mono_mmap_map (void *handle, gint64 offset, gint64 *size, int access, void **mmap_handle, void **base_address)
493 {
494         gint64 mmap_offset = 0;
495         MmapHandle *fh = (MmapHandle *)handle;
496         MmapInstance res = { 0 };
497         size_t eff_size = *size;
498         struct stat buf = { 0 };
499         fstat (fh->fd, &buf); //FIXME error handling
500
501         if (offset > buf.st_size || ((eff_size + offset) > buf.st_size && !is_special_zero_size_file (&buf)))
502                 goto error;
503         /**
504           * We use the file size if one of the following conditions is true:
505           *  -input size is zero
506           *  -input size is bigger than the file and the file is not a magical zero size file such as /dev/mem.
507           */
508         if (eff_size == 0)
509                 eff_size = align_up_to_page_size (buf.st_size) - offset;
510         *size = eff_size;
511
512         mmap_offset = align_down_to_page_size (offset);
513         eff_size += (offset - mmap_offset);
514         //FIXME translate some interesting errno values
515         res.address = mono_file_map ((size_t)eff_size, acess_to_mmap_flags (access), fh->fd, mmap_offset, &res.free_handle);
516         res.length = eff_size;
517
518         if (res.address) {
519                 *mmap_handle = g_memdup (&res, sizeof (MmapInstance));
520                 *base_address = (char*)res.address + (offset - mmap_offset);
521                 return 0;
522         }
523
524 error:
525         *mmap_handle = NULL;
526         *base_address = NULL;
527         return COULD_NOT_MAP_MEMORY;
528 }
529
530 gboolean
531 mono_mmap_unmap (void *mmap_handle)
532 {
533         int res = 0;
534         MmapInstance *h = (MmapInstance *)mmap_handle;
535
536         res = mono_file_unmap (h->address, h->free_handle);
537
538         g_free (h);
539         return res == 0;
540 }
541
542 #endif