3 * Support for mapping code into the process address space
6 * Mono Team (mono-list@lists.ximian.com)
8 * Copyright 2001-2008 Novell, Inc.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include <sys/types.h>
30 #endif /* !HOST_WIN32 */
32 #include "mono-mmap.h"
33 #include "mono-mmap-internals.h"
34 #include "mono-proclib.h"
35 #include <mono/utils/mono-threads.h>
36 #include <mono/utils/atomic.h>
37 #include <mono/utils/mono-counters.h>
39 #define BEGIN_CRITICAL_SECTION do { \
40 MonoThreadInfo *__info = mono_thread_info_current_unchecked (); \
41 if (__info) __info->inside_critical_region = TRUE; \
43 #define END_CRITICAL_SECTION \
44 if (__info) __info->inside_critical_region = FALSE; \
48 #define MAP_ANONYMOUS MAP_ANON
64 malloc_shared_area (int pid)
66 int size = mono_pagesize ();
67 SAreaHeader *sarea = (SAreaHeader *) g_malloc0 (size);
70 sarea->stats_start = sizeof (SAreaHeader);
71 sarea->stats_end = sizeof (SAreaHeader);
77 aligned_address (char *mem, size_t size, size_t alignment)
79 char *aligned = (char*)((size_t)(mem + (alignment - 1)) & ~(alignment - 1));
80 g_assert (aligned >= mem && aligned + size <= mem + size + alignment && !((size_t)aligned & (alignment - 1)));
84 static volatile size_t allocation_count [MONO_MEM_ACCOUNT_MAX];
87 account_mem (MonoMemAccountType type, ssize_t size)
89 #if SIZEOF_VOID_P == 4
90 InterlockedAdd ((volatile gint32*)&allocation_count [type], (gint32)size);
92 InterlockedAdd64 ((volatile gint64*)&allocation_count [type], (gint64)size);
97 mono_mem_account_type_name (MonoMemAccountType type)
99 static const char *names[] = {
108 "SGen shadow card table",
110 "SGen binary protocol",
120 mono_mem_account_register_counters (void)
122 for (int i = 0; i < MONO_MEM_ACCOUNT_MAX; ++i) {
123 const char *prefix = "Valloc ";
124 const char *name = mono_mem_account_type_name (i);
126 g_assert (strlen (prefix) + strlen (name) < sizeof (descr));
127 sprintf (descr, "%s%s", prefix, name);
128 mono_counters_register (descr, MONO_COUNTER_WORD | MONO_COUNTER_RUNTIME | MONO_COUNTER_BYTES | MONO_COUNTER_VARIABLE, (void*)&allocation_count [i]);
133 // Windows specific implementation in mono-mmap-windows.c
134 #define HAVE_VALLOC_ALIGNED
138 static void* malloced_shared_area = NULL;
139 #if defined(HAVE_MMAP)
143 * Get the page size in use on the system. Addresses and sizes in the
144 * mono_mmap(), mono_munmap() and mono_mprotect() calls must be pagesize
147 * Returns: the page size in bytes.
152 static int saved_pagesize = 0;
154 return saved_pagesize;
155 saved_pagesize = getpagesize ();
156 return saved_pagesize;
160 mono_valloc_granule (void)
162 return mono_pagesize ();
166 prot_from_flags (int flags)
168 int prot = PROT_NONE;
169 /* translate the protection bits */
170 if (flags & MONO_MMAP_READ)
172 if (flags & MONO_MMAP_WRITE)
174 if (flags & MONO_MMAP_EXEC)
181 * \param addr memory address
182 * \param length memory area size
183 * \param flags protection flags
184 * Allocates \p length bytes of virtual memory with the \p flags
185 * protection. \p addr can be a preferred memory address or a
186 * mandatory one if MONO_MMAP_FIXED is set in \p flags.
187 * \p addr must be pagesize aligned and can be NULL.
188 * \p length must be a multiple of pagesize.
189 * \returns NULL on failure, the address of the memory area otherwise
192 mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
196 int prot = prot_from_flags (flags);
197 /* translate the flags */
198 if (flags & MONO_MMAP_FIXED)
200 if (flags & MONO_MMAP_32BIT)
203 mflags |= MAP_ANONYMOUS;
204 mflags |= MAP_PRIVATE;
206 BEGIN_CRITICAL_SECTION;
207 ptr = mmap (addr, length, prot, mflags, -1, 0);
208 if (ptr == MAP_FAILED) {
209 int fd = open ("/dev/zero", O_RDONLY);
211 ptr = mmap (addr, length, prot, mflags, fd, 0);
215 END_CRITICAL_SECTION;
217 if (ptr == MAP_FAILED)
220 account_mem (type, (ssize_t)length);
227 * \param addr memory address returned by mono_valloc ()
228 * \param length size of memory area
229 * Remove the memory mapping at the address \p addr.
230 * \returns \c 0 on success.
233 mono_vfree (void *addr, size_t length, MonoMemAccountType type)
236 BEGIN_CRITICAL_SECTION;
237 res = munmap (addr, length);
238 END_CRITICAL_SECTION;
240 account_mem (type, -(ssize_t)length);
247 * \param length size of data to map
248 * \param flags protection flags
249 * \param fd file descriptor
250 * \param offset offset in the file
251 * \param ret_handle pointer to storage for returning a handle for the map
252 * Map the area of the file pointed to by the file descriptor \p fd, at offset
253 * \p offset and of size \p length in memory according to the protection flags
255 * \p offset and \p length must be multiples of the page size.
256 * \p ret_handle must point to a void*: this value must be used when unmapping
257 * the memory area using \c mono_file_unmap().
260 mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
264 int prot = prot_from_flags (flags);
265 /* translate the flags */
266 if (flags & MONO_MMAP_PRIVATE)
267 mflags |= MAP_PRIVATE;
268 if (flags & MONO_MMAP_SHARED)
269 mflags |= MAP_SHARED;
270 if (flags & MONO_MMAP_FIXED)
272 if (flags & MONO_MMAP_32BIT)
275 BEGIN_CRITICAL_SECTION;
276 ptr = mmap (0, length, prot, mflags, fd, offset);
277 END_CRITICAL_SECTION;
278 if (ptr == MAP_FAILED)
280 *ret_handle = (void*)length;
286 * \param addr memory address returned by mono_file_map ()
287 * \param handle handle of memory map
288 * Remove the memory mapping at the address \p addr.
289 * \p handle must be the value returned in ret_handle by \c mono_file_map().
290 * \returns \c 0 on success.
293 mono_file_unmap (void *addr, void *handle)
297 BEGIN_CRITICAL_SECTION;
298 res = munmap (addr, (size_t)handle);
299 END_CRITICAL_SECTION;
306 * \param addr memory address
307 * \param length size of memory area
308 * \param flags new protection flags
309 * Change the protection for the memory area at \p addr for \p length bytes
310 * to matche the supplied \p flags.
311 * If \p flags includes MON_MMAP_DISCARD the pages are discarded from memory
312 * and the area is cleared to zero.
313 * \p addr must be aligned to the page size.
314 * \p length must be a multiple of the page size.
315 * \returns \c 0 on success.
317 #if defined(__native_client__)
319 mono_mprotect (void *addr, size_t length, int flags)
321 int prot = prot_from_flags (flags);
324 if (flags & MONO_MMAP_DISCARD) memset (addr, 0, length);
326 new_addr = mmap(addr, length, prot, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0);
327 if (new_addr == addr) return 0;
332 mono_mprotect (void *addr, size_t length, int flags)
334 int prot = prot_from_flags (flags);
336 if (flags & MONO_MMAP_DISCARD) {
337 /* on non-linux the pages are not guaranteed to be zeroed (*bsd, osx at least) */
339 if (madvise (addr, length, MADV_DONTNEED))
340 memset (addr, 0, length);
342 memset (addr, 0, length);
344 madvise (addr, length, MADV_DONTNEED);
345 madvise (addr, length, MADV_FREE);
347 posix_madvise (addr, length, POSIX_MADV_DONTNEED);
351 return mprotect (addr, length, prot);
353 #endif // __native_client__
357 /* dummy malloc-based implementation */
365 mono_valloc_granule (void)
367 return mono_pagesize ();
371 mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
373 return g_malloc (length);
377 mono_valloc_aligned (size_t size, size_t alignment, int flags, MonoMemAccountType type)
379 g_assert_not_reached ();
382 #define HAVE_VALLOC_ALIGNED
385 mono_vfree (void *addr, size_t length, MonoMemAccountType type)
392 mono_mprotect (void *addr, size_t length, int flags)
394 if (flags & MONO_MMAP_DISCARD) {
395 memset (addr, 0, length);
402 #if defined(HAVE_SHM_OPEN) && !defined (DISABLE_SHARED_PERFCOUNTERS)
404 static int use_shared_area;
407 shared_area_disabled (void)
409 if (!use_shared_area) {
410 if (g_hasenv ("MONO_DISABLE_SHARED_AREA"))
411 use_shared_area = -1;
415 return use_shared_area == -1;
419 mono_shared_area_instances_slow (void **array, int count, gboolean cleanup)
424 gpointer *processes = mono_process_list (&num);
425 for (i = 0; i < num; ++i) {
426 data = mono_shared_area_for_pid (processes [i]);
429 mono_shared_area_unload (data);
432 array [j++] = processes [i];
442 mono_shared_area_instances_helper (void **array, int count, gboolean cleanup)
446 int curpid = getpid ();
447 GDir *dir = g_dir_open ("/dev/shm/", 0, NULL);
449 return mono_shared_area_instances_slow (array, count, cleanup);
450 while ((name = g_dir_read_name (dir))) {
453 if (strncmp (name, "mono.", 5))
455 pid = strtol (name + 5, &nend, 10);
456 if (pid <= 0 || nend == name + 5 || *nend)
460 array [i++] = GINT_TO_POINTER (pid);
464 if (curpid != pid && kill (pid, 0) == -1 && (errno == ESRCH || errno == ENOMEM)) {
466 g_snprintf (buf, sizeof (buf), "/mono.%d", pid);
475 mono_shared_area (void)
479 /* we should allow the user to configure the size */
480 int size = mono_pagesize ();
485 if (shared_area_disabled ()) {
486 if (!malloced_shared_area)
487 malloced_shared_area = malloc_shared_area (0);
488 /* get the pid here */
489 return malloced_shared_area;
492 /* perform cleanup of segments left over from dead processes */
493 mono_shared_area_instances_helper (NULL, 0, TRUE);
495 g_snprintf (buf, sizeof (buf), "/mono.%d", pid);
497 fd = shm_open (buf, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
498 if (fd == -1 && errno == EEXIST) {
501 fd = shm_open (buf, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
503 /* in case of failure we try to return a memory area anyway,
504 * even if it means the data can't be read by other processes
507 return malloc_shared_area (pid);
508 if (ftruncate (fd, size) != 0) {
512 BEGIN_CRITICAL_SECTION;
513 res = mmap (NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
514 END_CRITICAL_SECTION;
516 if (res == MAP_FAILED) {
519 return malloc_shared_area (pid);
521 /* we don't need the file descriptor anymore */
523 header = (SAreaHeader *) res;
526 header->stats_start = sizeof (SAreaHeader);
527 header->stats_end = sizeof (SAreaHeader);
529 mono_atexit (mono_shared_area_remove);
534 mono_shared_area_remove (void)
538 if (shared_area_disabled ()) {
539 if (malloced_shared_area)
540 g_free (malloced_shared_area);
544 g_snprintf (buf, sizeof (buf), "/mono.%d", getpid ());
546 if (malloced_shared_area)
547 g_free (malloced_shared_area);
551 mono_shared_area_for_pid (void *pid)
554 /* we should allow the user to configure the size */
555 int size = mono_pagesize ();
559 if (shared_area_disabled ())
562 g_snprintf (buf, sizeof (buf), "/mono.%d", GPOINTER_TO_INT (pid));
564 fd = shm_open (buf, O_RDONLY, S_IRUSR|S_IRGRP);
567 BEGIN_CRITICAL_SECTION;
568 res = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
569 END_CRITICAL_SECTION;
571 if (res == MAP_FAILED) {
575 /* FIXME: validate the area */
576 /* we don't need the file descriptor anymore */
582 mono_shared_area_unload (void *area)
584 /* FIXME: currently we load only a page */
585 BEGIN_CRITICAL_SECTION;
586 munmap (area, mono_pagesize ());
587 END_CRITICAL_SECTION;
591 mono_shared_area_instances (void **array, int count)
593 return mono_shared_area_instances_helper (array, count, FALSE);
597 mono_shared_area (void)
599 if (!malloced_shared_area)
600 malloced_shared_area = malloc_shared_area (getpid ());
601 /* get the pid here */
602 return malloced_shared_area;
606 mono_shared_area_remove (void)
608 if (malloced_shared_area)
609 g_free (malloced_shared_area);
610 malloced_shared_area = NULL;
614 mono_shared_area_for_pid (void *pid)
620 mono_shared_area_unload (void *area)
625 mono_shared_area_instances (void **array, int count)
630 #endif // HAVE_SHM_OPEN
634 #ifndef HAVE_VALLOC_ALIGNED
636 mono_valloc_aligned (size_t size, size_t alignment, int flags, MonoMemAccountType type)
638 /* Allocate twice the memory to be able to put the block on an aligned address */
639 char *mem = (char *) mono_valloc (NULL, size + alignment, flags, type);
645 aligned = aligned_address (mem, size, alignment);
648 mono_vfree (mem, aligned - mem, type);
649 if (aligned + size < mem + size + alignment)
650 mono_vfree (aligned + size, (mem + size + alignment) - (aligned + size), type);
657 mono_pages_not_faulted (void *addr, size_t size)
662 int pagesize = mono_pagesize ();
663 int npages = (size + pagesize - 1) / pagesize;
664 char *faulted = (char *) g_malloc0 (sizeof (char*) * npages);
667 * We cast `faulted` to void* because Linux wants an unsigned
668 * char* while BSD wants a char*.
671 if (mincore (addr, size, (unsigned char *)faulted) != 0) {
673 if (mincore (addr, size, (char *)faulted) != 0) {
678 for (i = 0; i < npages; ++i) {
679 if (faulted [i] != 0)