// [AsmJit]
// Complete JIT Assembler for C++ Language.
//
// [License]
// Zlib - See COPYING file in this package.

// [Guard]
#ifndef _ASMJIT_CORE_VIRTUALMEMORY_H
#define _ASMJIT_CORE_VIRTUALMEMORY_H

// [Dependencies - AsmJit]
#include "../core/build.h"

// [Api-Begin]
#include "../core/apibegin.h"

namespace AsmJit {

//! @addtogroup AsmJit_Core
//! @{

// ============================================================================
// [AsmJit::VirtualMemory]
// ============================================================================

//! @brief Class that helps with allocating memory for executing code
//! generated by JIT compiler.
//!
//! There are defined functions that provides facility to allocate and free
//! memory where can be executed code. If processor and operating system
//! supports execution protection then you can't run code from normally
//! malloc()'ed memory.
//!
//! Functions are internally implemented by operating system dependent way.
//! VirtualAlloc() function is used for Windows operating system and mmap()
//! for posix ones. If you want to study or create your own functions, look
//! at VirtualAlloc() or mmap() documentation (depends on you target OS).
//!
//! Under posix operating systems is also useable mprotect() function, that
//! can enable execution protection to malloc()'ed memory block.
struct VirtualMemory
{
  //! @brief Allocate virtual memory.
  //!
  //! Pages are readable/writeable, but they are not guaranteed to be
  //! executable unless 'canExecute' is true. Returns the address of
  //! allocated memory, or NULL if failed.
  ASMJIT_API static void* alloc(size_t length, size_t* allocated, bool canExecute);

  //! @brief Free memory allocated by @c alloc()
  ASMJIT_API static void free(void* addr, size_t length);

#if defined(ASMJIT_WINDOWS)
  //! @brief Allocate virtual memory of @a hProcess.
  //!
  //! @note This function is Windows specific.
  ASMJIT_API static void* allocProcessMemory(HANDLE hProcess, size_t length, size_t* allocated, bool canExecute);

  //! @brief Free virtual memory of @a hProcess.
  //!
  //! @note This function is Windows specific.
  ASMJIT_API static void freeProcessMemory(HANDLE hProcess, void* addr, size_t length);
#endif // ASMJIT_WINDOWS

  //! @brief Get the alignment guaranteed by alloc().
  ASMJIT_API static size_t getAlignment();

  //! @brief Get size of single page.
  ASMJIT_API static size_t getPageSize();
};

//! @}

} // AsmJit namespace

// [Api-End]
#include "../core/apiend.h"

// [Guard]
#endif // _ASMJIT_CORE_VIRTUALMEMORY_H
