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