2015-08-26 15:18:01 +00:00
|
|
|
#pragma once
|
|
|
|
|
2017-03-13 09:40:54 +00:00
|
|
|
namespace utils
|
2015-08-26 15:18:01 +00:00
|
|
|
{
|
2017-03-19 12:50:56 +00:00
|
|
|
// Memory protection type
|
|
|
|
enum class protection
|
|
|
|
{
|
|
|
|
rw, // Read + write (default)
|
|
|
|
ro, // Read only
|
|
|
|
no, // No access
|
|
|
|
wx, // Read + write + execute
|
|
|
|
rx, // Read + execute
|
|
|
|
};
|
|
|
|
|
2015-08-26 15:18:01 +00:00
|
|
|
/**
|
2016-06-27 16:34:08 +00:00
|
|
|
* Reserve `size` bytes of virtual memory and returns it.
|
2015-08-26 15:18:01 +00:00
|
|
|
* The memory should be commited before usage.
|
|
|
|
*/
|
2017-03-19 12:50:56 +00:00
|
|
|
void* memory_reserve(std::size_t size, void* use_addr = nullptr);
|
2015-08-26 15:18:01 +00:00
|
|
|
|
|
|
|
/**
|
2016-06-27 16:34:08 +00:00
|
|
|
* Commit `size` bytes of virtual memory starting at pointer.
|
2015-08-26 15:18:01 +00:00
|
|
|
* That is, bake reserved memory with physical memory.
|
|
|
|
* pointer should belong to a range of reserved memory.
|
|
|
|
*/
|
2017-03-19 12:50:56 +00:00
|
|
|
void memory_commit(void* pointer, std::size_t size, protection prot = protection::rw);
|
2015-08-26 15:18:01 +00:00
|
|
|
|
2018-09-22 20:14:28 +00:00
|
|
|
// Decommit all memory committed via commit_page_memory.
|
2017-03-13 09:40:54 +00:00
|
|
|
void memory_decommit(void* pointer, std::size_t size);
|
|
|
|
|
2018-09-22 20:14:28 +00:00
|
|
|
// Decommit all memory and commit it again.
|
|
|
|
void memory_reset(void* pointer, std::size_t size, protection prot = protection::rw);
|
|
|
|
|
2018-05-07 18:57:06 +00:00
|
|
|
// Free memory after reserved by memory_reserve, should specify original size
|
|
|
|
void memory_release(void* pointer, std::size_t size);
|
|
|
|
|
2017-03-19 12:50:56 +00:00
|
|
|
// Set memory protection
|
2017-03-13 09:40:54 +00:00
|
|
|
void memory_protect(void* pointer, std::size_t size, protection prot);
|
2018-05-07 18:57:06 +00:00
|
|
|
|
|
|
|
// Shared memory handle
|
|
|
|
class shm
|
|
|
|
{
|
|
|
|
#ifdef _WIN32
|
|
|
|
void* m_handle;
|
|
|
|
#else
|
|
|
|
int m_file;
|
|
|
|
#endif
|
|
|
|
u32 m_size;
|
|
|
|
|
|
|
|
public:
|
|
|
|
explicit shm(u32 size);
|
|
|
|
|
|
|
|
shm(const shm&) = delete;
|
|
|
|
|
2018-09-22 19:35:52 +00:00
|
|
|
shm& operator=(const shm&) = delete;
|
|
|
|
|
2018-05-07 18:57:06 +00:00
|
|
|
~shm();
|
|
|
|
|
|
|
|
// Map shared memory
|
|
|
|
u8* map(void* ptr, protection prot = protection::rw) const;
|
|
|
|
|
|
|
|
// Map shared memory over reserved memory region, which is unsafe (non-atomic) under Win32
|
|
|
|
u8* map_critical(void* ptr, protection prot = protection::rw);
|
|
|
|
|
|
|
|
// Unmap shared memory
|
|
|
|
void unmap(void* ptr) const;
|
|
|
|
|
|
|
|
// Unmap shared memory, undoing map_critical
|
|
|
|
void unmap_critical(void* ptr);
|
|
|
|
|
|
|
|
u32 size() const
|
|
|
|
{
|
|
|
|
return m_size;
|
|
|
|
}
|
|
|
|
};
|
2016-06-27 16:34:08 +00:00
|
|
|
}
|