06106605e21b953c2b8af52a8d4011c1e8bdbb43
[mono.git] / mono / utils / mono-mmap.c
1 /*
2  * mono-mmap.c: Support for mapping code into the process address space
3  *
4  * Author:
5  *   Mono Team (mono-list@lists.ximian.com)
6  *
7  * Copyright 2001-2008 Novell, Inc.
8  */
9
10 #include "config.h"
11
12 #ifdef HOST_WIN32
13 #include <windows.h>
14 #include <io.h>
15 #else
16 #include <sys/types.h>
17 #if HAVE_SYS_STAT_H
18 #include <sys/stat.h>
19 #endif
20 #if HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
23 #ifdef HAVE_SIGNAL_H
24 #include <signal.h>
25 #endif
26 #include <fcntl.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <errno.h>
31 #endif
32
33 #include "mono-mmap.h"
34 #include "mono-mmap-internal.h"
35 #include "mono-proclib.h"
36
37 #ifndef MAP_ANONYMOUS
38 #define MAP_ANONYMOUS MAP_ANON
39 #endif
40
41 #ifndef MAP_32BIT
42 #define MAP_32BIT 0
43 #endif
44
45 typedef struct {
46         int size;
47         int pid;
48         int reserved;
49         short stats_start;
50         short stats_end;
51 } SAreaHeader;
52
53 static void* malloced_shared_area = NULL;
54
55 static void*
56 malloc_shared_area (int pid)
57 {
58         int size = mono_pagesize ();
59         SAreaHeader *sarea = g_malloc0 (size);
60         sarea->size = size;
61         sarea->pid = pid;
62         sarea->stats_start = sizeof (SAreaHeader);
63         sarea->stats_end = sizeof (SAreaHeader);
64
65         return sarea;
66 }
67
68 static char*
69 aligned_address (char *mem, size_t size, size_t alignment)
70 {
71         char *aligned = (char*)((size_t)(mem + (alignment - 1)) & ~(alignment - 1));
72         g_assert (aligned >= mem && aligned + size <= mem + size + alignment && !((size_t)aligned & (alignment - 1)));
73         return aligned;
74 }
75
76 #ifdef HOST_WIN32
77
78 int
79 mono_pagesize (void)
80 {
81         SYSTEM_INFO info;
82         static int saved_pagesize = 0;
83         if (saved_pagesize)
84                 return saved_pagesize;
85         GetSystemInfo (&info);
86         saved_pagesize = info.dwAllocationGranularity;
87         return saved_pagesize;
88 }
89
90 static int
91 prot_from_flags (int flags)
92 {
93         int prot = flags & (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
94         switch (prot) {
95         case 0: prot = PAGE_NOACCESS; break;
96         case MONO_MMAP_READ: prot = PAGE_READONLY; break;
97         case MONO_MMAP_READ|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READ; break;
98         case MONO_MMAP_READ|MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
99         case MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
100         case MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
101         case MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
102         case MONO_MMAP_EXEC: prot = PAGE_EXECUTE; break;
103         default:
104                 g_assert_not_reached ();
105         }
106         return prot;
107 }
108
109 void*
110 mono_valloc (void *addr, size_t length, int flags)
111 {
112         void *ptr;
113         int mflags = MEM_RESERVE|MEM_COMMIT;
114         int prot = prot_from_flags (flags);
115         /* translate the flags */
116
117         ptr = VirtualAlloc (addr, length, mflags, prot);
118         return ptr;
119 }
120
121 void*
122 mono_valloc_aligned (size_t length, size_t alignment, int flags)
123 {
124         int prot = prot_from_flags (flags);
125         char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot);
126         char *aligned;
127
128         if (!mem)
129                 return NULL;
130
131         aligned = aligned_address (mem, length, alignment);
132
133         aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot);
134         g_assert (aligned);
135
136         return aligned;
137 }
138
139 #define HAVE_VALLOC_ALIGNED
140
141 int
142 mono_vfree (void *addr, size_t length)
143 {
144         MEMORY_BASIC_INFORMATION mbi;
145         SIZE_T query_result = VirtualQuery (addr, &mbi, sizeof (mbi));
146         BOOL res;
147
148         g_assert (query_result);
149
150         res = VirtualFree (mbi.AllocationBase, 0, MEM_RELEASE);
151
152         g_assert (res);
153
154         return 0;
155 }
156
157 void*
158 mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
159 {
160         void *ptr;
161         int mflags = 0;
162         HANDLE file, mapping;
163         int prot = prot_from_flags (flags);
164         /* translate the flags */
165         /*if (flags & MONO_MMAP_PRIVATE)
166                 mflags |= MAP_PRIVATE;
167         if (flags & MONO_MMAP_SHARED)
168                 mflags |= MAP_SHARED;
169         if (flags & MONO_MMAP_ANON)
170                 mflags |= MAP_ANONYMOUS;
171         if (flags & MONO_MMAP_FIXED)
172                 mflags |= MAP_FIXED;
173         if (flags & MONO_MMAP_32BIT)
174                 mflags |= MAP_32BIT;*/
175
176         mflags = FILE_MAP_READ;
177         if (flags & MONO_MMAP_WRITE)
178                 mflags = FILE_MAP_COPY;
179
180         file = (HANDLE) _get_osfhandle (fd);
181         mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
182         if (mapping == NULL)
183                 return NULL;
184         ptr = MapViewOfFile (mapping, mflags, 0, offset, length);
185         if (ptr == NULL) {
186                 CloseHandle (mapping);
187                 return NULL;
188         }
189         *ret_handle = (void*)mapping;
190         return ptr;
191 }
192
193 int
194 mono_file_unmap (void *addr, void *handle)
195 {
196         UnmapViewOfFile (addr);
197         CloseHandle ((HANDLE)handle);
198         return 0;
199 }
200
201 int
202 mono_mprotect (void *addr, size_t length, int flags)
203 {
204         DWORD oldprot;
205         int prot = prot_from_flags (flags);
206
207         if (flags & MONO_MMAP_DISCARD) {
208                 VirtualFree (addr, length, MEM_DECOMMIT);
209                 VirtualAlloc (addr, length, MEM_COMMIT, prot);
210                 return 0;
211         }
212         return VirtualProtect (addr, length, prot, &oldprot) == 0;
213 }
214
215 void*
216 mono_shared_area (void)
217 {
218         if (!malloced_shared_area)
219                 malloced_shared_area = malloc_shared_area (0);
220         /* get the pid here */
221         return malloced_shared_area;
222 }
223
224 void
225 mono_shared_area_remove (void)
226 {
227         if (malloced_shared_area)
228                 g_free (malloced_shared_area);
229         malloced_shared_area = NULL;
230 }
231
232 void*
233 mono_shared_area_for_pid (void *pid)
234 {
235         return NULL;
236 }
237
238 void
239 mono_shared_area_unload (void *area)
240 {
241 }
242
243 int
244 mono_shared_area_instances (void **array, int count)
245 {
246         return 0;
247 }
248
249 #else
250 #if defined(HAVE_MMAP)
251
252 /**
253  * mono_pagesize:
254  * Get the page size in use on the system. Addresses and sizes in the
255  * mono_mmap(), mono_munmap() and mono_mprotect() calls must be pagesize
256  * aligned.
257  *
258  * Returns: the page size in bytes.
259  */
260 int
261 mono_pagesize (void)
262 {
263         static int saved_pagesize = 0;
264         if (saved_pagesize)
265                 return saved_pagesize;
266         saved_pagesize = getpagesize ();
267         return saved_pagesize;
268 }
269
270 static int
271 prot_from_flags (int flags)
272 {
273         int prot = PROT_NONE;
274         /* translate the protection bits */
275         if (flags & MONO_MMAP_READ)
276                 prot |= PROT_READ;
277         if (flags & MONO_MMAP_WRITE)
278                 prot |= PROT_WRITE;
279         if (flags & MONO_MMAP_EXEC)
280                 prot |= PROT_EXEC;
281         return prot;
282 }
283
284 /**
285  * mono_valloc:
286  * @addr: memory address
287  * @length: memory area size
288  * @flags: protection flags
289  *
290  * Allocates @length bytes of virtual memory with the @flags
291  * protection. @addr can be a preferred memory address or a
292  * mandatory one if MONO_MMAP_FIXED is set in @flags.
293  * @addr must be pagesize aligned and can be NULL.
294  * @length must be a multiple of pagesize.
295  *
296  * Returns: NULL on failure, the address of the memory area otherwise
297  */
298 void*
299 mono_valloc (void *addr, size_t length, int flags)
300 {
301         void *ptr;
302         int mflags = 0;
303         int prot = prot_from_flags (flags);
304         /* translate the flags */
305         if (flags & MONO_MMAP_FIXED)
306                 mflags |= MAP_FIXED;
307         if (flags & MONO_MMAP_32BIT)
308                 mflags |= MAP_32BIT;
309
310         mflags |= MAP_ANONYMOUS;
311         mflags |= MAP_PRIVATE;
312
313         ptr = mmap (addr, length, prot, mflags, -1, 0);
314         if (ptr == MAP_FAILED) {
315                 int fd = open ("/dev/zero", O_RDONLY);
316                 if (fd != -1) {
317                         ptr = mmap (addr, length, prot, mflags, fd, 0);
318                         close (fd);
319                 }
320                 if (ptr == MAP_FAILED)
321                         return NULL;
322         }
323         return ptr;
324 }
325
326 /**
327  * mono_vfree:
328  * @addr: memory address returned by mono_valloc ()
329  * @length: size of memory area
330  *
331  * Remove the memory mapping at the address @addr.
332  *
333  * Returns: 0 on success.
334  */
335 int
336 mono_vfree (void *addr, size_t length)
337 {
338         return munmap (addr, length);
339 }
340
341 /**
342  * mono_file_map:
343  * @length: size of data to map
344  * @flags: protection flags
345  * @fd: file descriptor
346  * @offset: offset in the file
347  * @ret_handle: pointer to storage for returning a handle for the map
348  *
349  * Map the area of the file pointed to by the file descriptor @fd, at offset
350  * @offset and of size @length in memory according to the protection flags
351  * @flags.
352  * @offset and @length must be multiples of the page size.
353  * @ret_handle must point to a void*: this value must be used when unmapping
354  * the memory area using mono_file_unmap ().
355  *
356  */
357 void*
358 mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
359 {
360         void *ptr;
361         int mflags = 0;
362         int prot = prot_from_flags (flags);
363         /* translate the flags */
364         if (flags & MONO_MMAP_PRIVATE)
365                 mflags |= MAP_PRIVATE;
366         if (flags & MONO_MMAP_SHARED)
367                 mflags |= MAP_SHARED;
368         if (flags & MONO_MMAP_FIXED)
369                 mflags |= MAP_FIXED;
370         if (flags & MONO_MMAP_32BIT)
371                 mflags |= MAP_32BIT;
372
373         ptr = mmap (0, length, prot, mflags, fd, offset);
374         if (ptr == MAP_FAILED)
375                 return NULL;
376         *ret_handle = (void*)length;
377         return ptr;
378 }
379
380 /**
381  * mono_file_unmap:
382  * @addr: memory address returned by mono_file_map ()
383  * @handle: handle of memory map
384  *
385  * Remove the memory mapping at the address @addr.
386  * @handle must be the value returned in ret_handle by mono_file_map ().
387  *
388  * Returns: 0 on success.
389  */
390 int
391 mono_file_unmap (void *addr, void *handle)
392 {
393         return munmap (addr, (size_t)handle);
394 }
395
396 /**
397  * mono_mprotect:
398  * @addr: memory address
399  * @length: size of memory area
400  * @flags: new protection flags
401  *
402  * Change the protection for the memory area at @addr for @length bytes
403  * to matche the supplied @flags.
404  * If @flags includes MON_MMAP_DISCARD the pages are discarded from memory
405  * and the area is cleared to zero.
406  * @addr must be aligned to the page size.
407  * @length must be a multiple of the page size.
408  *
409  * Returns: 0 on success.
410  */
411 #if defined(__native_client__)
412 int
413 mono_mprotect (void *addr, size_t length, int flags)
414 {
415         int prot = prot_from_flags (flags);
416         void *new_addr;
417
418         if (flags & MONO_MMAP_DISCARD) memset (addr, 0, length);
419
420         new_addr = mmap(addr, length, prot, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0);
421         if (new_addr == addr) return 0;
422         return -1;
423 }
424 #else
425 int
426 mono_mprotect (void *addr, size_t length, int flags)
427 {
428         int prot = prot_from_flags (flags);
429
430         if (flags & MONO_MMAP_DISCARD) {
431                 /* on non-linux the pages are not guaranteed to be zeroed (*bsd, osx at least) */
432 #ifdef __linux__
433                 if (madvise (addr, length, MADV_DONTNEED))
434                         memset (addr, 0, length);
435 #else
436                 memset (addr, 0, length);
437 #ifdef HAVE_MADVISE
438                 madvise (addr, length, MADV_DONTNEED);
439                 madvise (addr, length, MADV_FREE);
440 #else
441                 posix_madvise (addr, length, POSIX_MADV_DONTNEED);
442 #endif
443 #endif
444         }
445         return mprotect (addr, length, prot);
446 }
447 #endif // __native_client__
448
449 #else
450
451 /* dummy malloc-based implementation */
452 int
453 mono_pagesize (void)
454 {
455         return 4096;
456 }
457
458 void*
459 mono_valloc (void *addr, size_t length, int flags)
460 {
461         return malloc (length);
462 }
463
464 void*
465 mono_valloc_aligned (size_t length, size_t alignment, int flags)
466 {
467         g_assert_not_reached ();
468 }
469
470 #define HAVE_VALLOC_ALIGNED
471
472 int
473 mono_vfree (void *addr, size_t length)
474 {
475         free (addr);
476         return 0;
477 }
478
479 int
480 mono_mprotect (void *addr, size_t length, int flags)
481 {
482         if (flags & MONO_MMAP_DISCARD) {
483                 memset (addr, 0, length);
484         }
485         return 0;
486 }
487
488 #endif // HAVE_MMAP
489
490 #if defined(HAVE_SHM_OPEN) && !defined (DISABLE_SHARED_PERFCOUNTERS)
491
492 static int use_shared_area;
493
494 static gboolean
495 shared_area_disabled (void)
496 {
497         if (!use_shared_area) {
498                 if (g_getenv ("MONO_DISABLE_SHARED_AREA"))
499                         use_shared_area = -1;
500                 else
501                         use_shared_area = 1;
502         }
503         return use_shared_area == -1;
504 }
505
506 static int
507 mono_shared_area_instances_slow (void **array, int count, gboolean cleanup)
508 {
509         int i, j = 0;
510         int num;
511         void *data;
512         gpointer *processes = mono_process_list (&num);
513         for (i = 0; i < num; ++i) {
514                 data = mono_shared_area_for_pid (processes [i]);
515                 if (!data)
516                         continue;
517                 mono_shared_area_unload (data);
518                 if (!cleanup) {
519                         if (j < count)
520                                 array [j++] = processes [i];
521                         else
522                                 break;
523                 }
524         }
525         g_free (processes);
526         return j;
527 }
528
529 static int
530 mono_shared_area_instances_helper (void **array, int count, gboolean cleanup)
531 {
532         const char *name;
533         int i = 0;
534         int curpid = getpid ();
535         GDir *dir = g_dir_open ("/dev/shm/", 0, NULL);
536         if (!dir)
537                 return mono_shared_area_instances_slow (array, count, cleanup);
538         while ((name = g_dir_read_name (dir))) {
539                 int pid;
540                 char *nend;
541                 if (strncmp (name, "mono.", 5))
542                         continue;
543                 pid = strtol (name + 5, &nend, 10);
544                 if (pid <= 0 || nend == name + 5 || *nend)
545                         continue;
546                 if (!cleanup) {
547                         if (i < count)
548                                 array [i++] = GINT_TO_POINTER (pid);
549                         else
550                                 break;
551                 }
552                 if (curpid != pid && kill (pid, 0) == -1 && (errno == ESRCH || errno == ENOMEM)) {
553                         char buf [128];
554                         g_snprintf (buf, sizeof (buf), "/mono.%d", pid);
555                         shm_unlink (buf);
556                 }
557         }
558         g_dir_close (dir);
559         return i;
560 }
561
562 void*
563 mono_shared_area (void)
564 {
565         int fd;
566         int pid = getpid ();
567         /* we should allow the user to configure the size */
568         int size = mono_pagesize ();
569         char buf [128];
570         void *res;
571         SAreaHeader *header;
572
573         if (shared_area_disabled ()) {
574                 if (!malloced_shared_area)
575                         malloced_shared_area = malloc_shared_area (0);
576                 /* get the pid here */
577                 return malloced_shared_area;
578         }
579
580         /* perform cleanup of segments left over from dead processes */
581         mono_shared_area_instances_helper (NULL, 0, TRUE);
582
583         g_snprintf (buf, sizeof (buf), "/mono.%d", pid);
584
585         fd = shm_open (buf, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
586         if (fd == -1 && errno == EEXIST) {
587                 /* leftover */
588                 shm_unlink (buf);
589                 fd = shm_open (buf, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
590         }
591         /* in case of failure we try to return a memory area anyway,
592          * even if it means the data can't be read by other processes
593          */
594         if (fd == -1)
595                 return malloc_shared_area (pid);
596         if (ftruncate (fd, size) != 0) {
597                 shm_unlink (buf);
598                 close (fd);
599         }
600         res = mmap (NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
601         if (res == MAP_FAILED) {
602                 shm_unlink (buf);
603                 close (fd);
604                 return malloc_shared_area (pid);
605         }
606         /* we don't need the file descriptor anymore */
607         close (fd);
608         header = res;
609         header->size = size;
610         header->pid = pid;
611         header->stats_start = sizeof (SAreaHeader);
612         header->stats_end = sizeof (SAreaHeader);
613
614         mono_atexit (mono_shared_area_remove);
615         return res;
616 }
617
618 void
619 mono_shared_area_remove (void)
620 {
621         char buf [128];
622
623         if (shared_area_disabled ()) {
624                 if (malloced_shared_area)
625                         g_free (malloced_shared_area);
626                 return;
627         }
628
629         g_snprintf (buf, sizeof (buf), "/mono.%d", getpid ());
630         shm_unlink (buf);
631         if (malloced_shared_area)
632                 g_free (malloced_shared_area);
633 }
634
635 void*
636 mono_shared_area_for_pid (void *pid)
637 {
638         int fd;
639         /* we should allow the user to configure the size */
640         int size = mono_pagesize ();
641         char buf [128];
642         void *res;
643
644         if (shared_area_disabled ())
645                 return NULL;
646
647         g_snprintf (buf, sizeof (buf), "/mono.%d", GPOINTER_TO_INT (pid));
648
649         fd = shm_open (buf, O_RDONLY, S_IRUSR|S_IRGRP);
650         if (fd == -1)
651                 return NULL;
652         res = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
653         if (res == MAP_FAILED) {
654                 close (fd);
655                 return NULL;
656         }
657         /* FIXME: validate the area */
658         /* we don't need the file descriptor anymore */
659         close (fd);
660         return res;
661 }
662
663 void
664 mono_shared_area_unload  (void *area)
665 {
666         /* FIXME: currently we load only a page */
667         munmap (area, mono_pagesize ());
668 }
669
670 int
671 mono_shared_area_instances (void **array, int count)
672 {
673         return mono_shared_area_instances_helper (array, count, FALSE);
674 }
675 #else
676 void*
677 mono_shared_area (void)
678 {
679         if (!malloced_shared_area)
680                 malloced_shared_area = malloc_shared_area (getpid ());
681         /* get the pid here */
682         return malloced_shared_area;
683 }
684
685 void
686 mono_shared_area_remove (void)
687 {
688         if (malloced_shared_area)
689                 g_free (malloced_shared_area);
690         malloced_shared_area = NULL;
691 }
692
693 void*
694 mono_shared_area_for_pid (void *pid)
695 {
696         return NULL;
697 }
698
699 void
700 mono_shared_area_unload (void *area)
701 {
702 }
703
704 int
705 mono_shared_area_instances (void **array, int count)
706 {
707         return 0;
708 }
709
710 #endif // HAVE_SHM_OPEN
711
712 #endif // HOST_WIN32
713
714 #ifndef HAVE_VALLOC_ALIGNED
715 void*
716 mono_valloc_aligned (size_t size, size_t alignment, int flags)
717 {
718         /* Allocate twice the memory to be able to put the block on an aligned address */
719         char *mem = mono_valloc (NULL, size + alignment, flags);
720         char *aligned;
721
722         if (!mem)
723                 return NULL;
724
725         aligned = aligned_address (mem, size, alignment);
726
727         if (aligned > mem)
728                 mono_vfree (mem, aligned - mem);
729         if (aligned + size < mem + size + alignment)
730                 mono_vfree (aligned + size, (mem + size + alignment) - (aligned + size));
731
732         return aligned;
733 }
734 #endif
735
736 int
737 mono_pages_not_faulted (void *addr, size_t size)
738 {
739 #ifdef HAVE_MINCORE
740         int i;
741         gint64 count;
742         int pagesize = mono_pagesize ();
743         int npages = (size + pagesize - 1) / pagesize;
744         char *faulted = g_malloc0 (sizeof (char*) * npages);
745
746         if (mincore (addr, size, faulted) != 0) {
747                 count = -1;
748         } else {
749                 count = 0;
750                 for (i = 0; i < npages; ++i) {
751                         if (faulted [i] != 0)
752                                 ++count;
753                 }
754         }
755
756         g_free (faulted);
757
758         return count;
759 #else
760         return -1;
761 #endif
762 }