core/sourcehook/sh_pagealloc.h
changeset 539 db914129ae01
parent 480 d096210677d4
child 684 8015336442cb
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/core/sourcehook/sh_pagealloc.h	Fri Nov 14 04:04:02 2008 -0600
     1.3 @@ -0,0 +1,288 @@
     1.4 +#ifndef __SH_PAGEALLOC_H__
     1.5 +#define __SH_PAGEALLOC_H__
     1.6 +
     1.7 +# if	/********/ defined _WIN32
     1.8 +#		include <windows.h>
     1.9 +# elif /******/ defined __linux__
    1.10 +#		include <sys/mman.h>
    1.11 +#		include <unistd.h>
    1.12 +# else
    1.13 +#		error Unsupported OS/Compiler
    1.14 +# endif
    1.15 +
    1.16 +
    1.17 +namespace SourceHook
    1.18 +{
    1.19 +
    1.20 +	/*
    1.21 +	Class which lets us allocate memory regions in special pages only meant for on the fly code generation.
    1.22 +
    1.23 +	If we alloc with malloc and then set the page access type to read/exec only, other regions returned by
    1.24 +	malloc that are in the same page would lose their write access as well and the process could crash.
    1.25 +
    1.26 +	Allocating one page per code generation session is usually a waste of memory and on some platforms also
    1.27 +	a waste of virtual address space (Windows� VirtualAlloc has a granularity of 64K).
    1.28 +
    1.29 +
    1.30 +	IMPORTANT: the memory that Alloc() returns is not a in a defined state!
    1.31 +	It could be in read+exec OR read+write mode.
    1.32 +	-> call SetRE() or SetRW() before using allocated memory!
    1.33 +	*/
    1.34 +	class CPageAlloc
    1.35 +	{
    1.36 +		struct AllocationUnit
    1.37 +		{
    1.38 +			size_t begin_offset;
    1.39 +			size_t size;
    1.40 +
    1.41 +			AllocationUnit(size_t p_offs, size_t p_size) : begin_offset(p_offs), size(p_size)
    1.42 +			{
    1.43 +			}
    1.44 +
    1.45 +			bool operator < (const AllocationUnit &other) const
    1.46 +			{
    1.47 +				return begin_offset < other.begin_offset;
    1.48 +			}
    1.49 +		};
    1.50 +
    1.51 +		typedef List<AllocationUnit> AUList;
    1.52 +		struct AllocatedRegion
    1.53 +		{
    1.54 +			void *startPtr;
    1.55 +			size_t size;
    1.56 +			bool isolated;					// may contain only one AU
    1.57 +			size_t minAlignment;
    1.58 +			AUList allocUnits;
    1.59 +
    1.60 +			void CheckGap(size_t gap_begin, size_t gap_end, size_t reqsize,
    1.61 +				size_t &smallestgap_pos, size_t &smallestgap_size, size_t &outAlignBytes)
    1.62 +			{
    1.63 +				size_t gapsize = gap_end - gap_begin;
    1.64 +				// How many bytes do we actually need here?
    1.65 +				//   = requested size + alignment bytes
    1.66 +				size_t neededSize = reqsize;
    1.67 +				size_t alignBytes = minAlignment - ((reinterpret_cast<intptr_t>(startPtr) + gap_begin) % minAlignment);
    1.68 +
    1.69 +				alignBytes %= minAlignment;
    1.70 +				neededSize += alignBytes;
    1.71 +
    1.72 +				if (gapsize >= neededSize)
    1.73 +				{
    1.74 +					if (gapsize < smallestgap_size)
    1.75 +					{
    1.76 +						smallestgap_size = gapsize;
    1.77 +						smallestgap_pos = gap_begin;
    1.78 +						outAlignBytes = alignBytes;
    1.79 +					}
    1.80 +				}
    1.81 +			}
    1.82 +
    1.83 +			bool TryAlloc(size_t reqsize, void * &outAddr)
    1.84 +			{
    1.85 +				// Check for isolated
    1.86 +				if (isolated && !allocUnits.empty())
    1.87 +					return false;
    1.88 +
    1.89 +				// Find the smallest gap where req fits
    1.90 +				size_t lastend = 0;
    1.91 +				size_t smallestgap_pos = size + 1;
    1.92 +				size_t smallestgap_size = size + 1;
    1.93 +				size_t alignmentbytes = 0;
    1.94 +
    1.95 +				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
    1.96 +				{
    1.97 +					CheckGap(lastend, iter->begin_offset, reqsize, smallestgap_pos, smallestgap_size, alignmentbytes);
    1.98 +					lastend = iter->begin_offset + iter->size;
    1.99 +				}
   1.100 +
   1.101 +				CheckGap(lastend, size, reqsize, smallestgap_pos, smallestgap_size, alignmentbytes);
   1.102 +
   1.103 +				if (smallestgap_pos < size)
   1.104 +				{
   1.105 +					outAddr = reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + smallestgap_pos + alignmentbytes);
   1.106 +					allocUnits.push_sorted( AllocationUnit(smallestgap_pos, reqsize + alignmentbytes) );
   1.107 +					return true;
   1.108 +				}
   1.109 +				else
   1.110 +				{
   1.111 +					return false;
   1.112 +				}
   1.113 +			}
   1.114 +
   1.115 +			bool TryFree(void *addr)
   1.116 +			{
   1.117 +				if (addr < startPtr || addr >= reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size))
   1.118 +					return false;
   1.119 +
   1.120 +				intptr_t start = reinterpret_cast<intptr_t>(startPtr);
   1.121 +
   1.122 +				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
   1.123 +				{
   1.124 +					size_t AUBegin = start + iter->begin_offset;
   1.125 +					void *alignedAUBegin = reinterpret_cast<void*>(
   1.126 +						AUBegin + ((minAlignment - AUBegin % minAlignment) % minAlignment)
   1.127 +						);
   1.128 +					
   1.129 +					if (addr == alignedAUBegin)
   1.130 +					{
   1.131 +						allocUnits.erase(iter);
   1.132 +						return true;
   1.133 +					}
   1.134 +				}
   1.135 +
   1.136 +				return false;
   1.137 +			}
   1.138 +
   1.139 +			bool Contains(void *addr)
   1.140 +			{
   1.141 +				return addr >= startPtr && addr < reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size);
   1.142 +			}
   1.143 +
   1.144 +			void FreeRegion()
   1.145 +			{
   1.146 +#ifdef __linux__
   1.147 +				munmap(startPtr, size);
   1.148 +#else
   1.149 +				VirtualFree(startPtr, 0, MEM_RELEASE);
   1.150 +#endif
   1.151 +			}
   1.152 +		};
   1.153 +
   1.154 +		typedef List<AllocatedRegion> ARList;
   1.155 +
   1.156 +		size_t m_MinAlignment;
   1.157 +		size_t m_PageSize;
   1.158 +		ARList m_Regions;
   1.159 +
   1.160 +		bool AddRegion(size_t minSize, bool isolated)
   1.161 +		{
   1.162 +			AllocatedRegion newRegion;
   1.163 +			newRegion.startPtr = 0;
   1.164 +			newRegion.isolated = isolated;
   1.165 +			newRegion.minAlignment = m_MinAlignment;
   1.166 +
   1.167 +			// Compute real size -> align up to m_PageSize boundary
   1.168 +
   1.169 +			newRegion.size = minSize - (minSize % m_PageSize);
   1.170 +			if (newRegion.size < minSize)
   1.171 +				newRegion.size += m_PageSize;
   1.172 +
   1.173 +#ifdef __linux__
   1.174 +			newRegion.startPtr = mmap(0, newRegion.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   1.175 +#else
   1.176 +			newRegion.startPtr = VirtualAlloc(NULL, newRegion.size, MEM_COMMIT, PAGE_READWRITE);
   1.177 +#endif
   1.178 +
   1.179 +			if (newRegion.startPtr)
   1.180 +			{
   1.181 +				m_Regions.push_back(newRegion);
   1.182 +				return true;
   1.183 +			}
   1.184 +			else
   1.185 +			{
   1.186 +				return false;
   1.187 +			}
   1.188 +
   1.189 +		}
   1.190 +
   1.191 +		void *AllocPriv(size_t size, bool isolated)
   1.192 +		{
   1.193 +			void *addr;
   1.194 +
   1.195 +			if (!isolated)
   1.196 +			{
   1.197 +				for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   1.198 +				{
   1.199 +					if (iter->TryAlloc(size, addr))
   1.200 +						return addr;
   1.201 +				}
   1.202 +			}
   1.203 +
   1.204 +			if (!AddRegion(size, isolated))
   1.205 +				return NULL;
   1.206 +
   1.207 +			bool tmp = m_Regions.back().TryAlloc(size, addr);
   1.208 +			SH_ASSERT(tmp, ("TryAlloc fails after AddRegion"));
   1.209 +			return tmp ? addr : NULL;
   1.210 +		}
   1.211 +
   1.212 +	public:
   1.213 +		CPageAlloc(size_t minAlignment = 1 /* power of 2 */ ) : m_MinAlignment(minAlignment)
   1.214 +		{
   1.215 +#ifdef __linux__
   1.216 +			m_PageSize = sysconf(_SC_PAGESIZE);
   1.217 +#else
   1.218 +			SYSTEM_INFO sysInfo;
   1.219 +			GetSystemInfo(&sysInfo);
   1.220 +			m_PageSize = sysInfo.dwPageSize;
   1.221 +#endif
   1.222 +		}
   1.223 +
   1.224 +		~CPageAlloc()
   1.225 +		{
   1.226 +			// Free all regions
   1.227 +			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   1.228 +			{
   1.229 +				iter->FreeRegion();
   1.230 +			}
   1.231 +		}
   1.232 +
   1.233 +		void *Alloc(size_t size)
   1.234 +		{
   1.235 +			return AllocPriv(size, false);
   1.236 +		}
   1.237 +
   1.238 +		void *AllocIsolated(size_t size)
   1.239 +		{
   1.240 +			return AllocPriv(size, true);
   1.241 +		}
   1.242 +
   1.243 +		void Free(void *ptr)
   1.244 +		{
   1.245 +			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   1.246 +			{
   1.247 +				if (iter->TryFree(ptr))
   1.248 +				{
   1.249 +					if (iter->allocUnits.empty())
   1.250 +					{
   1.251 +						iter->FreeRegion();
   1.252 +						m_Regions.erase(iter);
   1.253 +					}
   1.254 +					break;
   1.255 +				}
   1.256 +			}
   1.257 +		}
   1.258 +
   1.259 +		void SetRE(void *ptr)
   1.260 +		{
   1.261 +			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   1.262 +			{
   1.263 +				if (iter->Contains(ptr))
   1.264 +				{
   1.265 +					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_EXEC);
   1.266 +					break;
   1.267 +				}
   1.268 +			}
   1.269 +		}
   1.270 +
   1.271 +		void SetRW(void *ptr)
   1.272 +		{
   1.273 +			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   1.274 +			{
   1.275 +				if (iter->Contains(ptr))
   1.276 +				{
   1.277 +					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_WRITE);
   1.278 +					break;
   1.279 +				}
   1.280 +			}
   1.281 +		}
   1.282 +
   1.283 +		size_t GetPageSize()
   1.284 +		{
   1.285 +			return m_PageSize;
   1.286 +		}
   1.287 +	};
   1.288 +}
   1.289 +
   1.290 +#endif
   1.291 +