core/sourcehook/sh_pagealloc.h
author David Anderson <dvander@alliedmods.net>
Sat Nov 15 23:46:27 2008 -0600 (2008-11-15)
changeset 552 4b73ffd6e176
parent 539 db914129ae01
child 684 8015336442cb
permissions -rw-r--r--
Initial commit of vsp bridge for new core. Not tested, barely compiles.
     1 #ifndef __SH_PAGEALLOC_H__
     2 #define __SH_PAGEALLOC_H__
     3 
     4 # if	/********/ defined _WIN32
     5 #		include <windows.h>
     6 # elif /******/ defined __linux__
     7 #		include <sys/mman.h>
     8 #		include <unistd.h>
     9 # else
    10 #		error Unsupported OS/Compiler
    11 # endif
    12 
    13 
    14 namespace SourceHook
    15 {
    16 
    17 	/*
    18 	Class which lets us allocate memory regions in special pages only meant for on the fly code generation.
    19 
    20 	If we alloc with malloc and then set the page access type to read/exec only, other regions returned by
    21 	malloc that are in the same page would lose their write access as well and the process could crash.
    22 
    23 	Allocating one page per code generation session is usually a waste of memory and on some platforms also
    24 	a waste of virtual address space (Windows� VirtualAlloc has a granularity of 64K).
    25 
    26 
    27 	IMPORTANT: the memory that Alloc() returns is not a in a defined state!
    28 	It could be in read+exec OR read+write mode.
    29 	-> call SetRE() or SetRW() before using allocated memory!
    30 	*/
    31 	class CPageAlloc
    32 	{
    33 		struct AllocationUnit
    34 		{
    35 			size_t begin_offset;
    36 			size_t size;
    37 
    38 			AllocationUnit(size_t p_offs, size_t p_size) : begin_offset(p_offs), size(p_size)
    39 			{
    40 			}
    41 
    42 			bool operator < (const AllocationUnit &other) const
    43 			{
    44 				return begin_offset < other.begin_offset;
    45 			}
    46 		};
    47 
    48 		typedef List<AllocationUnit> AUList;
    49 		struct AllocatedRegion
    50 		{
    51 			void *startPtr;
    52 			size_t size;
    53 			bool isolated;					// may contain only one AU
    54 			size_t minAlignment;
    55 			AUList allocUnits;
    56 
    57 			void CheckGap(size_t gap_begin, size_t gap_end, size_t reqsize,
    58 				size_t &smallestgap_pos, size_t &smallestgap_size, size_t &outAlignBytes)
    59 			{
    60 				size_t gapsize = gap_end - gap_begin;
    61 				// How many bytes do we actually need here?
    62 				//   = requested size + alignment bytes
    63 				size_t neededSize = reqsize;
    64 				size_t alignBytes = minAlignment - ((reinterpret_cast<intptr_t>(startPtr) + gap_begin) % minAlignment);
    65 
    66 				alignBytes %= minAlignment;
    67 				neededSize += alignBytes;
    68 
    69 				if (gapsize >= neededSize)
    70 				{
    71 					if (gapsize < smallestgap_size)
    72 					{
    73 						smallestgap_size = gapsize;
    74 						smallestgap_pos = gap_begin;
    75 						outAlignBytes = alignBytes;
    76 					}
    77 				}
    78 			}
    79 
    80 			bool TryAlloc(size_t reqsize, void * &outAddr)
    81 			{
    82 				// Check for isolated
    83 				if (isolated && !allocUnits.empty())
    84 					return false;
    85 
    86 				// Find the smallest gap where req fits
    87 				size_t lastend = 0;
    88 				size_t smallestgap_pos = size + 1;
    89 				size_t smallestgap_size = size + 1;
    90 				size_t alignmentbytes = 0;
    91 
    92 				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
    93 				{
    94 					CheckGap(lastend, iter->begin_offset, reqsize, smallestgap_pos, smallestgap_size, alignmentbytes);
    95 					lastend = iter->begin_offset + iter->size;
    96 				}
    97 
    98 				CheckGap(lastend, size, reqsize, smallestgap_pos, smallestgap_size, alignmentbytes);
    99 
   100 				if (smallestgap_pos < size)
   101 				{
   102 					outAddr = reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + smallestgap_pos + alignmentbytes);
   103 					allocUnits.push_sorted( AllocationUnit(smallestgap_pos, reqsize + alignmentbytes) );
   104 					return true;
   105 				}
   106 				else
   107 				{
   108 					return false;
   109 				}
   110 			}
   111 
   112 			bool TryFree(void *addr)
   113 			{
   114 				if (addr < startPtr || addr >= reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size))
   115 					return false;
   116 
   117 				intptr_t start = reinterpret_cast<intptr_t>(startPtr);
   118 
   119 				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
   120 				{
   121 					size_t AUBegin = start + iter->begin_offset;
   122 					void *alignedAUBegin = reinterpret_cast<void*>(
   123 						AUBegin + ((minAlignment - AUBegin % minAlignment) % minAlignment)
   124 						);
   125 					
   126 					if (addr == alignedAUBegin)
   127 					{
   128 						allocUnits.erase(iter);
   129 						return true;
   130 					}
   131 				}
   132 
   133 				return false;
   134 			}
   135 
   136 			bool Contains(void *addr)
   137 			{
   138 				return addr >= startPtr && addr < reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size);
   139 			}
   140 
   141 			void FreeRegion()
   142 			{
   143 #ifdef __linux__
   144 				munmap(startPtr, size);
   145 #else
   146 				VirtualFree(startPtr, 0, MEM_RELEASE);
   147 #endif
   148 			}
   149 		};
   150 
   151 		typedef List<AllocatedRegion> ARList;
   152 
   153 		size_t m_MinAlignment;
   154 		size_t m_PageSize;
   155 		ARList m_Regions;
   156 
   157 		bool AddRegion(size_t minSize, bool isolated)
   158 		{
   159 			AllocatedRegion newRegion;
   160 			newRegion.startPtr = 0;
   161 			newRegion.isolated = isolated;
   162 			newRegion.minAlignment = m_MinAlignment;
   163 
   164 			// Compute real size -> align up to m_PageSize boundary
   165 
   166 			newRegion.size = minSize - (minSize % m_PageSize);
   167 			if (newRegion.size < minSize)
   168 				newRegion.size += m_PageSize;
   169 
   170 #ifdef __linux__
   171 			newRegion.startPtr = mmap(0, newRegion.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   172 #else
   173 			newRegion.startPtr = VirtualAlloc(NULL, newRegion.size, MEM_COMMIT, PAGE_READWRITE);
   174 #endif
   175 
   176 			if (newRegion.startPtr)
   177 			{
   178 				m_Regions.push_back(newRegion);
   179 				return true;
   180 			}
   181 			else
   182 			{
   183 				return false;
   184 			}
   185 
   186 		}
   187 
   188 		void *AllocPriv(size_t size, bool isolated)
   189 		{
   190 			void *addr;
   191 
   192 			if (!isolated)
   193 			{
   194 				for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   195 				{
   196 					if (iter->TryAlloc(size, addr))
   197 						return addr;
   198 				}
   199 			}
   200 
   201 			if (!AddRegion(size, isolated))
   202 				return NULL;
   203 
   204 			bool tmp = m_Regions.back().TryAlloc(size, addr);
   205 			SH_ASSERT(tmp, ("TryAlloc fails after AddRegion"));
   206 			return tmp ? addr : NULL;
   207 		}
   208 
   209 	public:
   210 		CPageAlloc(size_t minAlignment = 1 /* power of 2 */ ) : m_MinAlignment(minAlignment)
   211 		{
   212 #ifdef __linux__
   213 			m_PageSize = sysconf(_SC_PAGESIZE);
   214 #else
   215 			SYSTEM_INFO sysInfo;
   216 			GetSystemInfo(&sysInfo);
   217 			m_PageSize = sysInfo.dwPageSize;
   218 #endif
   219 		}
   220 
   221 		~CPageAlloc()
   222 		{
   223 			// Free all regions
   224 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   225 			{
   226 				iter->FreeRegion();
   227 			}
   228 		}
   229 
   230 		void *Alloc(size_t size)
   231 		{
   232 			return AllocPriv(size, false);
   233 		}
   234 
   235 		void *AllocIsolated(size_t size)
   236 		{
   237 			return AllocPriv(size, true);
   238 		}
   239 
   240 		void Free(void *ptr)
   241 		{
   242 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   243 			{
   244 				if (iter->TryFree(ptr))
   245 				{
   246 					if (iter->allocUnits.empty())
   247 					{
   248 						iter->FreeRegion();
   249 						m_Regions.erase(iter);
   250 					}
   251 					break;
   252 				}
   253 			}
   254 		}
   255 
   256 		void SetRE(void *ptr)
   257 		{
   258 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   259 			{
   260 				if (iter->Contains(ptr))
   261 				{
   262 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_EXEC);
   263 					break;
   264 				}
   265 			}
   266 		}
   267 
   268 		void SetRW(void *ptr)
   269 		{
   270 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   271 			{
   272 				if (iter->Contains(ptr))
   273 				{
   274 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_WRITE);
   275 					break;
   276 				}
   277 			}
   278 		}
   279 
   280 		size_t GetPageSize()
   281 		{
   282 			return m_PageSize;
   283 		}
   284 	};
   285 }
   286 
   287 #endif
   288