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