brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.1 KiB · e18de4e Raw
68 lines · c
1//===-- enable_execute_stack.c - Implement __enable_execute_stack ---------===//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "int_lib.h"10 11#ifndef _WIN3212#include <sys/mman.h>13#endif14 15// #include "config.h"16// FIXME: CMake - include when cmake system is ready.17// Remove #define HAVE_SYSCONF 1 line.18#define HAVE_SYSCONF 119 20#ifdef _WIN3221#define WIN32_LEAN_AND_MEAN22#include <windows.h>23#else24#ifndef __APPLE__25#include <unistd.h>26#endif // __APPLE__27#endif // _WIN3228 29#if __LP64__30#define TRAMPOLINE_SIZE 4831#else32#define TRAMPOLINE_SIZE 4033#endif34 35// The compiler generates calls to __enable_execute_stack() when creating36// trampoline functions on the stack for use with nested functions.37// It is expected to mark the page(s) containing the address38// and the next 48 bytes as executable.  Since the stack is normally rw-39// that means changing the protection on those page(s) to rwx.40 41COMPILER_RT_ABI void __enable_execute_stack(void *addr) {42 43#if _WIN3244  MEMORY_BASIC_INFORMATION mbi;45  if (!VirtualQuery(addr, &mbi, sizeof(mbi)))46    return; // We should probably assert here because there is no return value47  VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_READWRITE,48                 &mbi.Protect);49#else50#if __APPLE__51  // On Darwin, pagesize is always 4096 bytes52  const uintptr_t pageSize = 4096;53#elif !defined(HAVE_SYSCONF)54#error "HAVE_SYSCONF not defined! See enable_execute_stack.c"55#else56  const uintptr_t pageSize = sysconf(_SC_PAGESIZE);57#endif // __APPLE__58 59  const uintptr_t pageAlignMask = ~(pageSize - 1);60  uintptr_t p = (uintptr_t)addr;61  unsigned char *startPage = (unsigned char *)(p & pageAlignMask);62  unsigned char *endPage =63      (unsigned char *)((p + TRAMPOLINE_SIZE + pageSize) & pageAlignMask);64  size_t length = endPage - startPage;65  (void)mprotect((void *)startPage, length, PROT_READ | PROT_WRITE | PROT_EXEC);66#endif67}68