1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 # include "mozilla/TaggedAnonymousMemory.h"
11 # include <sys/types.h>
12 # include <sys/mman.h>
13 # include <sys/prctl.h>
14 # include <sys/syscall.h>
17 # include "mozilla/Assertions.h"
19 // These constants are copied from <sys/prctl.h>, because the headers
20 // used for building may not have them even though the running kernel
23 # define PR_SET_VMA 0x53564d41
25 # ifndef PR_SET_VMA_ANON_NAME
26 # define PR_SET_VMA_ANON_NAME 0
31 // Returns 0 for success and -1 (with errno) for error.
32 static int TagAnonymousMemoryAligned(const void* aPtr
, size_t aLength
,
34 return prctl(PR_SET_VMA
, PR_SET_VMA_ANON_NAME
,
35 reinterpret_cast<unsigned long>(aPtr
), aLength
,
36 reinterpret_cast<unsigned long>(aTag
));
39 // On some architectures, it's possible for the page size to be larger
40 // than the PAGE_SIZE we were compiled with. This computes the
41 // equivalent of PAGE_MASK.
42 static uintptr_t GetPageMask() {
43 static uintptr_t mask
= 0;
46 uintptr_t pageSize
= sysconf(_SC_PAGESIZE
);
47 mask
= ~(pageSize
- 1);
48 MOZ_ASSERT((pageSize
& (pageSize
- 1)) == 0,
49 "Page size must be a power of 2!");
54 } // namespace mozilla
56 void MozTagAnonymousMemory(const void* aPtr
, size_t aLength
, const char* aTag
) {
57 // The kernel will round up the end of the range to the next page
58 // boundary if it's not aligned (comments indicate this behavior is
59 // based on that of madvise), but it will reject the request if the
60 // start is not aligned. We therefore round down the start address
61 // and adjust the length accordingly.
62 uintptr_t addr
= reinterpret_cast<uintptr_t>(aPtr
);
63 uintptr_t end
= addr
+ aLength
;
64 uintptr_t addrRounded
= addr
& mozilla::GetPageMask();
65 const void* ptrRounded
= reinterpret_cast<const void*>(addrRounded
);
67 // Ignore the return value. TagAnonymousMemoryAligned will harmlessly fail on
68 // kernels without CONFIG_ANON_VMA_NAME.
69 mozilla::TagAnonymousMemoryAligned(ptrRounded
, end
- addrRounded
, aTag
);
72 void* MozTaggedAnonymousMmap(void* aAddr
, size_t aLength
, int aProt
, int aFlags
,
73 int aFd
, off_t aOffset
, const char* aTag
) {
74 void* mapped
= mmap(aAddr
, aLength
, aProt
, aFlags
, aFd
, aOffset
);
75 if ((aFlags
& MAP_ANONYMOUS
) == MAP_ANONYMOUS
&& mapped
!= MAP_FAILED
) {
76 // Ignore the return value. TagAnonymousMemoryAligned will harmlessly fail
77 // on kernels without CONFIG_ANON_VMA_NAME.
78 mozilla::TagAnonymousMemoryAligned(mapped
, aLength
, aTag
);