1 // Copyright 2020 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef V8_WASM_CODE_SPACE_ACCESS_H_ 6 #define V8_WASM_CODE_SPACE_ACCESS_H_ 7 8 #include "src/base/build_config.h" 9 #include "src/base/macros.h" 10 #include "src/common/globals.h" 11 12 namespace v8 { 13 namespace internal { 14 15 #if defined(V8_OS_MACOSX) && defined(V8_HOST_ARCH_ARM64) 16 17 // Ignoring this warning is considered better than relying on 18 // __builtin_available. 19 #pragma clang diagnostic push 20 #pragma clang diagnostic ignored "-Wunguarded-availability-new" SwitchMemoryPermissionsToWritable()21inline void SwitchMemoryPermissionsToWritable() { 22 pthread_jit_write_protect_np(0); 23 } SwitchMemoryPermissionsToExecutable()24inline void SwitchMemoryPermissionsToExecutable() { 25 pthread_jit_write_protect_np(1); 26 } 27 #pragma clang diagnostic pop 28 29 namespace wasm { 30 31 class CodeSpaceWriteScope { 32 public: 33 // TODO(jkummerow): Background threads could permanently stay in 34 // writable mode; only the main thread has to switch back and forth. CodeSpaceWriteScope()35 CodeSpaceWriteScope() { 36 if (code_space_write_nesting_level_ == 0) { 37 SwitchMemoryPermissionsToWritable(); 38 } 39 code_space_write_nesting_level_++; 40 } ~CodeSpaceWriteScope()41 ~CodeSpaceWriteScope() { 42 code_space_write_nesting_level_--; 43 if (code_space_write_nesting_level_ == 0) { 44 SwitchMemoryPermissionsToExecutable(); 45 } 46 } 47 48 private: 49 static thread_local int code_space_write_nesting_level_; 50 }; 51 52 #define CODE_SPACE_WRITE_SCOPE CodeSpaceWriteScope _write_access_; 53 54 } // namespace wasm 55 56 #else // Not Mac-on-arm64. 57 58 // Nothing to do, we map code memory with rwx permissions. 59 inline void SwitchMemoryPermissionsToWritable() {} 60 inline void SwitchMemoryPermissionsToExecutable() {} 61 62 #define CODE_SPACE_WRITE_SCOPE 63 64 #endif // V8_OS_MACOSX && V8_HOST_ARCH_ARM64 65 66 } // namespace internal 67 } // namespace v8 68 69 #endif // V8_WASM_CODE_SPACE_ACCESS_H_ 70