1//===- Unix/Memory.cpp - Generic UNIX System Configuration ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines some functions for various memory management utilities.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Unix.h"
14#include "llvm/Config/config.h"
15#include "llvm/Support/DataTypes.h"
16#include "llvm/Support/ErrorHandling.h"
17#include "llvm/Support/Process.h"
18
19#ifdef HAVE_SYS_MMAN_H
20#include <sys/mman.h>
21#endif
22
23#ifdef __APPLE__
24#include <mach/mach.h>
25#endif
26
27#ifdef __Fuchsia__
28#include <zircon/syscalls.h>
29#endif
30
31#if defined(__mips__)
32#  if defined(__OpenBSD__)
33#    include <mips64/sysarch.h>
34#  elif !defined(__FreeBSD__)
35#    include <sys/cachectl.h>
36#  endif
37#endif
38
39#if defined(__APPLE__)
40extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
41#else
42extern "C" void __clear_cache(void *, void*);
43#endif
44
45namespace {
46
47int getPosixProtectionFlags(unsigned Flags) {
48  switch (Flags & llvm::sys::Memory::MF_RWE_MASK) {
49  case llvm::sys::Memory::MF_READ:
50    return PROT_READ;
51  case llvm::sys::Memory::MF_WRITE:
52    return PROT_WRITE;
53  case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
54    return PROT_READ | PROT_WRITE;
55  case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
56    return PROT_READ | PROT_EXEC;
57  case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_WRITE |
58      llvm::sys::Memory::MF_EXEC:
59    return PROT_READ | PROT_WRITE | PROT_EXEC;
60  case llvm::sys::Memory::MF_EXEC:
61#if defined(__FreeBSD__)
62    // On PowerPC, having an executable page that has no read permission
63    // can have unintended consequences.  The function InvalidateInstruction-
64    // Cache uses instructions dcbf and icbi, both of which are treated by
65    // the processor as loads.  If the page has no read permissions,
66    // executing these instructions will result in a segmentation fault.
67    // Somehow, this problem is not present on Linux, but it does happen
68    // on FreeBSD.
69    return PROT_READ | PROT_EXEC;
70#else
71    return PROT_EXEC;
72#endif
73  default:
74    llvm_unreachable("Illegal memory protection flag specified!");
75  }
76  // Provide a default return value as required by some compilers.
77  return PROT_NONE;
78}
79
80} // anonymous namespace
81
82namespace llvm {
83namespace sys {
84
85MemoryBlock
86Memory::allocateMappedMemory(size_t NumBytes,
87                             const MemoryBlock *const NearBlock,
88                             unsigned PFlags,
89                             std::error_code &EC) {
90  EC = std::error_code();
91  if (NumBytes == 0)
92    return MemoryBlock();
93
94  int fd = -1;
95
96  int MMFlags = MAP_PRIVATE |
97#ifdef MAP_ANONYMOUS
98  MAP_ANONYMOUS
99#else
100  MAP_ANON
101#endif
102  ; // Ends statement above
103
104  int Protect = getPosixProtectionFlags(PFlags);
105
106#if defined(__NetBSD__) && defined(PROT_MPROTECT)
107  Protect |= PROT_MPROTECT(PROT_READ | PROT_WRITE | PROT_EXEC);
108#endif
109
110  // Use any near hint and the page size to set a page-aligned starting address
111  uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
112                                      NearBlock->size() : 0;
113  static const size_t PageSize = Process::getPageSize();
114  if (Start && Start % PageSize)
115    Start += PageSize - Start % PageSize;
116
117  // FIXME: Handle huge page requests (MF_HUGE_HINT).
118  void *Addr = ::mmap(reinterpret_cast<void *>(Start), NumBytes, Protect,
119                      MMFlags, fd, 0);
120  if (Addr == MAP_FAILED) {
121    if (NearBlock) //Try again without a near hint
122      return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
123
124    EC = std::error_code(errno, std::generic_category());
125    return MemoryBlock();
126  }
127
128  MemoryBlock Result;
129  Result.Address = Addr;
130  Result.Size = NumBytes;
131  Result.Flags = PFlags;
132
133  // Rely on protectMappedMemory to invalidate instruction cache.
134  if (PFlags & MF_EXEC) {
135    EC = Memory::protectMappedMemory (Result, PFlags);
136    if (EC != std::error_code())
137      return MemoryBlock();
138  }
139
140  return Result;
141}
142
143std::error_code
144Memory::releaseMappedMemory(MemoryBlock &M) {
145  if (M.Address == nullptr || M.Size == 0)
146    return std::error_code();
147
148  if (0 != ::munmap(M.Address, M.Size))
149    return std::error_code(errno, std::generic_category());
150
151  M.Address = nullptr;
152  M.Size = 0;
153
154  return std::error_code();
155}
156
157std::error_code
158Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
159  static const size_t PageSize = Process::getPageSize();
160  if (M.Address == nullptr || M.Size == 0)
161    return std::error_code();
162
163  if (!Flags)
164    return std::error_code(EINVAL, std::generic_category());
165
166  int Protect = getPosixProtectionFlags(Flags);
167  uintptr_t Start = alignAddr((uint8_t *)M.Address - PageSize + 1, PageSize);
168  uintptr_t End = alignAddr((uint8_t *)M.Address + M.Size, PageSize);
169
170  bool InvalidateCache = (Flags & MF_EXEC);
171
172#if defined(__arm__) || defined(__aarch64__)
173  // Certain ARM implementations treat icache clear instruction as a memory read,
174  // and CPU segfaults on trying to clear cache on !PROT_READ page.  Therefore we need
175  // to temporarily add PROT_READ for the sake of flushing the instruction caches.
176  if (InvalidateCache && !(Protect & PROT_READ)) {
177    int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ);
178    if (Result != 0)
179      return std::error_code(errno, std::generic_category());
180
181    Memory::InvalidateInstructionCache(M.Address, M.Size);
182    InvalidateCache = false;
183  }
184#endif
185
186  int Result = ::mprotect((void *)Start, End - Start, Protect);
187
188  if (Result != 0)
189    return std::error_code(errno, std::generic_category());
190
191  if (InvalidateCache)
192    Memory::InvalidateInstructionCache(M.Address, M.Size);
193
194  return std::error_code();
195}
196
197/// InvalidateInstructionCache - Before the JIT can run a block of code
198/// that has been emitted it must invalidate the instruction cache on some
199/// platforms.
200void Memory::InvalidateInstructionCache(const void *Addr,
201                                        size_t Len) {
202
203// icache invalidation for PPC and ARM.
204#if defined(__APPLE__)
205
206#  if (defined(__POWERPC__) || defined (__ppc__) || \
207       defined(_POWER) || defined(_ARCH_PPC) || defined(__arm__) || \
208       defined(__arm64__))
209  sys_icache_invalidate(const_cast<void *>(Addr), Len);
210#  endif
211
212#elif defined(__Fuchsia__)
213
214  zx_status_t Status = zx_cache_flush(Addr, Len, ZX_CACHE_FLUSH_INSN);
215  assert(Status == ZX_OK && "cannot invalidate instruction cache");
216
217#else
218
219#  if (defined(__POWERPC__) || defined (__ppc__) || \
220       defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
221  const size_t LineSize = 32;
222
223  const intptr_t Mask = ~(LineSize - 1);
224  const intptr_t StartLine = ((intptr_t) Addr) & Mask;
225  const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
226
227  for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
228    asm volatile("dcbf 0, %0" : : "r"(Line));
229  asm volatile("sync");
230
231  for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
232    asm volatile("icbi 0, %0" : : "r"(Line));
233  asm volatile("isync");
234#  elif (defined(__arm__) || defined(__aarch64__) || defined(__mips__)) && \
235        defined(__GNUC__)
236  // FIXME: Can we safely always call this for __GNUC__ everywhere?
237  const char *Start = static_cast<const char *>(Addr);
238  const char *End = Start + Len;
239  __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
240#  endif
241
242#endif  // end apple
243
244  ValgrindDiscardTranslations(Addr, Len);
245}
246
247} // namespace sys
248} // namespace llvm
249