sourcehook/sh_pagealloc.h
author Pavol Marko <pavolmarko@gmail.com>
Wed Nov 07 16:56:03 2007 +0000 (2007-11-07)
branchhookman_autogen
changeset 448 742b470c0e5c
parent 446 bb400f1c758e
child 452 2efe13dab607
permissions -rw-r--r--
ForcedByRef works; next step will be: returns!
     1 #ifndef __SH_PAGEALLOC_H__
     2 #define __SH_PAGEALLOC_H__
     3 
     4 # if	/********/ defined _WIN32
     5 #		include <windows.h>
     6 #		define SH_MEM_READ 1
     7 #		define SH_MEM_WRITE 2
     8 #		define SH_MEM_EXEC 4
     9 # elif /******/ defined __linux__
    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 plattforms 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 
    53 		struct AllocatedRegion
    54 		{
    55 			void *startPtr;
    56 			size_t size;
    57 			bool isolated;					// may contain only one AU
    58 			AUList allocUnits;
    59 
    60 			bool TryAlloc(size_t reqsize, void * &outAddr)
    61 			{
    62 				// Check for isolated
    63 				if (isolated && !allocUnits.empty())
    64 					return false;
    65 
    66 				// Find the smallest gap where req fits
    67 				size_t lastend = 0;
    68 				size_t smallestgap_pos = size + 1;
    69 				size_t smallestgap_size = size + 1;
    70 
    71 				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
    72 				{
    73 					if (iter->begin_offset - lastend >= reqsize)
    74 					{
    75 						if (iter->begin_offset - lastend < smallestgap_size)
    76 						{
    77 							smallestgap_size = iter->begin_offset - lastend;
    78 							smallestgap_pos = lastend;
    79 						}
    80 					}
    81 					lastend = iter->begin_offset + iter->size;
    82 				}
    83 
    84 				if (size - lastend >= reqsize)
    85 				{
    86 					if (size - lastend < smallestgap_size)
    87 					{
    88 						smallestgap_size = size - lastend;
    89 						smallestgap_pos = lastend;
    90 					}
    91 				}
    92 
    93 				if (smallestgap_pos < size)
    94 				{
    95 					outAddr = reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + smallestgap_pos);
    96 					allocUnits.push_sorted( AllocationUnit(smallestgap_pos, reqsize) );
    97 					return true;
    98 				}
    99 				else
   100 				{
   101 					return false;
   102 				}
   103 			}
   104 
   105 			bool TryFree(void *addr)
   106 			{
   107 				if (addr < startPtr || addr >= reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size))
   108 					return false;
   109 
   110 				size_t offs = reinterpret_cast<char*>(addr) - reinterpret_cast<char*>(startPtr);
   111 
   112 				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
   113 				{
   114 					if (iter->begin_offset == offs)
   115 					{
   116 						allocUnits.erase(iter);
   117 						return true;
   118 					}
   119 				}
   120 
   121 				return false;
   122 			}
   123 
   124 			bool Contains(void *addr)
   125 			{
   126 				return addr >= startPtr && addr < reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size);
   127 			}
   128 
   129 			void FreeRegion()
   130 			{
   131 #ifdef __linux__
   132 				munmap(startPtr, size);
   133 #else
   134 				VirtualFree(startPtr, 0, MEM_RELEASE);
   135 #endif
   136 			}
   137 		};
   138 
   139 		typedef List<AllocatedRegion> ARList;
   140 
   141 		size_t m_PageSize;
   142 		ARList m_Regions;
   143 
   144 		bool AddRegion(size_t minSize, bool isolated)
   145 		{
   146 			AllocatedRegion newRegion;
   147 			newRegion.startPtr = 0;
   148 			newRegion.isolated = isolated;
   149 
   150 			// Compute real size -> align up to m_PageSize boundary
   151 
   152 			newRegion.size = minSize - (minSize % m_PageSize);
   153 			if (newRegion.size < minSize)
   154 				newRegion.size += m_PageSize;
   155 
   156 #ifdef __linux__
   157 			newRegion.startPtr = mmap(0, newRegion.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   158 #else
   159 			newRegion.startPtr = VirtualAlloc(NULL, newRegion.size, MEM_COMMIT, PAGE_READWRITE);
   160 #endif
   161 
   162 			if (newRegion.startPtr)
   163 			{
   164 				m_Regions.push_back(newRegion);
   165 				return true;
   166 			}
   167 			else
   168 			{
   169 				return false;
   170 			}
   171 
   172 		}
   173 
   174 		void *AllocPriv(size_t size, bool isolated)
   175 		{
   176 			void *addr;
   177 
   178 			if (!isolated)
   179 			{
   180 				for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   181 				{
   182 					if (iter->TryAlloc(size, addr))
   183 						return addr;
   184 				}
   185 			}
   186 
   187 			if (!AddRegion(size, isolated))
   188 				return NULL;
   189 
   190 			bool tmp = m_Regions.back().TryAlloc(size, addr);
   191 			SH_ASSERT(tmp, ("TryAlloc fails after AddRegion"));
   192 			return addr;
   193 		}
   194 
   195 	public:
   196 		CPageAlloc()
   197 		{
   198 #ifdef __linux__
   199 			m_PageSize = sysconf(_SC_PAGESIZE);
   200 #else
   201 			SYSTEM_INFO sysInfo;
   202 			GetSystemInfo(&sysInfo);
   203 			m_PageSize = sysInfo.dwPageSize;
   204 #endif
   205 		}
   206 
   207 		~CPageAlloc()
   208 		{
   209 			// Free all regions
   210 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   211 			{
   212 				iter->FreeRegion();
   213 			}
   214 		}
   215 
   216 		void *Alloc(size_t size)
   217 		{
   218 			return AllocPriv(size, false);
   219 		}
   220 
   221 		void *AllocIsolated(size_t size)
   222 		{
   223 			return AllocPriv(size, true);
   224 		}
   225 
   226 		void Free(void *ptr)
   227 		{
   228 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   229 			{
   230 				if (iter->TryFree(ptr))
   231 				{
   232 					if (iter->allocUnits.empty())
   233 					{
   234 						iter->FreeRegion();
   235 						m_Regions.erase(iter);
   236 					}
   237 					break;
   238 				}
   239 			}
   240 		}
   241 
   242 		void SetRE(void *ptr)
   243 		{
   244 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   245 			{
   246 				if (iter->Contains(ptr))
   247 				{
   248 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_EXEC);
   249 					break;
   250 				}
   251 			}
   252 		}
   253 
   254 		void SetRW(void *ptr)
   255 		{
   256 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   257 			{
   258 				if (iter->Contains(ptr))
   259 				{
   260 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_WRITE);
   261 					break;
   262 				}
   263 			}
   264 		}
   265 
   266 		size_t GetPageSize()
   267 		{
   268 			return m_PageSize;
   269 		}
   270 	};
   271 }
   272 
   273 #endif
   274