core/sourcehook/sh_pagealloc.h
author Scott Ehlert <ds@alliedmods.net>
Sat May 22 00:45:44 2010 -0500 (2010-05-22)
changeset 716 6925fbd2b9fa
parent 684 8015336442cb
child 733 2365240861a2
permissions -rw-r--r--
Added Mac OS X build support to stub/sample plugin makefiles (bug 4391, r=dvander).
     1 #ifndef __SH_PAGEALLOC_H__
     2 #define __SH_PAGEALLOC_H__
     3 
     4 # if SH_XP == SH_XP_WINAPI
     5 #		include <windows.h>
     6 # elif SH_XP == SH_XP_POSIX
     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 #if SH_XP == SH_XP_POSIX
   144 				munmap(startPtr, size);
   145 #elif SH_XP == SH_XP_WINAPI
   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 #if SH_XP == SH_XP_POSIX
   171 # if !defined MAP_ANONYMOUS
   172 #  define MAP_ANONYMOUS MAP_ANON
   173 # endif
   174 			newRegion.startPtr = mmap(0, newRegion.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   175 #elif SH_XP == SH_XP_WINAPI
   176 			newRegion.startPtr = VirtualAlloc(NULL, newRegion.size, MEM_COMMIT, PAGE_READWRITE);
   177 #endif
   178 
   179 			if (newRegion.startPtr)
   180 			{
   181 				m_Regions.push_back(newRegion);
   182 				return true;
   183 			}
   184 			else
   185 			{
   186 				return false;
   187 			}
   188 
   189 		}
   190 
   191 		void *AllocPriv(size_t size, bool isolated)
   192 		{
   193 			void *addr;
   194 
   195 			if (!isolated)
   196 			{
   197 				for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   198 				{
   199 					if (iter->TryAlloc(size, addr))
   200 						return addr;
   201 				}
   202 			}
   203 
   204 			if (!AddRegion(size, isolated))
   205 				return NULL;
   206 
   207 			bool tmp = m_Regions.back().TryAlloc(size, addr);
   208 			SH_ASSERT(tmp, ("TryAlloc fails after AddRegion"));
   209 			return tmp ? addr : NULL;
   210 		}
   211 
   212 	public:
   213 		CPageAlloc(size_t minAlignment = 1 /* power of 2 */ ) : m_MinAlignment(minAlignment)
   214 		{
   215 #if SH_XP == SH_XP_POSIX
   216 			m_PageSize = sysconf(_SC_PAGESIZE);
   217 #elif SH_XP == SH_XP_WINAPI
   218 			SYSTEM_INFO sysInfo;
   219 			GetSystemInfo(&sysInfo);
   220 			m_PageSize = sysInfo.dwPageSize;
   221 #endif
   222 		}
   223 
   224 		~CPageAlloc()
   225 		{
   226 			// Free all regions
   227 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   228 			{
   229 				iter->FreeRegion();
   230 			}
   231 		}
   232 
   233 		void *Alloc(size_t size)
   234 		{
   235 			return AllocPriv(size, false);
   236 		}
   237 
   238 		void *AllocIsolated(size_t size)
   239 		{
   240 			return AllocPriv(size, true);
   241 		}
   242 
   243 		void Free(void *ptr)
   244 		{
   245 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   246 			{
   247 				if (iter->TryFree(ptr))
   248 				{
   249 					if (iter->allocUnits.empty())
   250 					{
   251 						iter->FreeRegion();
   252 						m_Regions.erase(iter);
   253 					}
   254 					break;
   255 				}
   256 			}
   257 		}
   258 
   259 		void SetRE(void *ptr)
   260 		{
   261 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   262 			{
   263 				if (iter->Contains(ptr))
   264 				{
   265 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_EXEC);
   266 					break;
   267 				}
   268 			}
   269 		}
   270 
   271 		void SetRW(void *ptr)
   272 		{
   273 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   274 			{
   275 				if (iter->Contains(ptr))
   276 				{
   277 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_WRITE);
   278 					break;
   279 				}
   280 			}
   281 		}
   282 
   283 		size_t GetPageSize()
   284 		{
   285 			return m_PageSize;
   286 		}
   287 	};
   288 }
   289 
   290 #endif
   291