core/logic/HandleSys.h
author Kyle Sanderson <kyle.leet@gmail.com>
Thu Jul 18 15:50:50 2013 -0400 (2013-07-18)
changeset 3950 d467a6526f8d
parent 3872 4c93f74cae51
child 4064 d7ca1e28949d
permissions -rw-r--r--
Fixed accidental assignment in each of SDKTools and sp compiler (bug 5745, r=psychonic).
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #ifndef _INCLUDE_SOURCEMOD_HANDLESYSTEM_H_
    33 #define _INCLUDE_SOURCEMOD_HANDLESYSTEM_H_
    34 
    35 #include <IHandleSys.h>
    36 #include <stdio.h>
    37 #include <sm_trie_tpl.h>
    38 #include "sm_memtable.h"
    39 #include "common_logic.h"
    40 
    41 #define HANDLESYS_MAX_HANDLES		(1<<14)
    42 #define HANDLESYS_MAX_TYPES			(1<<9)
    43 #define HANDLESYS_MAX_SUBTYPES		0xF
    44 #define HANDLESYS_SUBTYPE_MASK		0xF
    45 #define HANDLESYS_TYPEARRAY_SIZE	(HANDLESYS_MAX_TYPES * (HANDLESYS_MAX_SUBTYPES + 1))
    46 #define HANDLESYS_MAX_SERIALS		0xFFFF
    47 #define HANDLESYS_SERIAL_MASK		0xFFFF0000
    48 #define HANDLESYS_HANDLE_MASK		0x0000FFFF
    49 
    50 #define HANDLESYS_MEMUSAGE_MIN_VERSION		3
    51 
    52 /**
    53  *   The QHandle is a nasty structure that compacts the handle system into a big vector.
    54  * The members of the vector each encapsulate one Handle, however, they also act as nodes
    55  * in an inlined linked list and an inlined vector.
    56  *
    57  *   The first of these lists is the 'freeID' list.  Each node from 1 to N (where N
    58  * is the number of free nodes) has a 'freeID' that specifies a free Handle ID.  This
    59  * is a quick hack to get around allocating a second base vector.
    60  *
    61  *   The second vector is the identity linked list.  An identity has its own handle, so
    62  * these handles are used as sentinel nodes for index linking.  They point to the first and last
    63  * index into the handle array.  Each subsequent Handle who is owned by that identity is mapped into
    64  * that list.  This lets owning identities be unloaded in O(n) time.
    65  *
    66  *   Eventually, there may be a third list for type chains.
    67  */
    68 
    69 enum HandleSet
    70 {
    71 	HandleSet_None = 0,
    72 	HandleSet_Used,			/* The Handle is in use */
    73 	HandleSet_Freed,		/* The "master" Handle of a clone chain is freed */
    74 	HandleSet_Identity,		/* The Handle is a special identity */
    75 };
    76 
    77 struct QHandle
    78 {
    79 	HandleType_t type;			/* Handle type */
    80 	void *object;				/* Unmaintained object pointer */
    81 	IdentityToken_t *owner;		/* Identity of object which owns this */
    82 	unsigned int serial;		/* Serial no. for sanity checking */
    83 	unsigned int refcount;		/* Reference count for safe destruction */
    84 	unsigned int clone;			/* If non-zero, this is our cloned parent index */
    85 	HandleSet set;				/* Information about the handle's state */
    86 	bool access_special;		/* Whether or not access rules are special or type-derived */
    87 	bool is_destroying;			/* Whether or not the handle is being destroyed */
    88 	HandleAccess sec;			/* Security rules */
    89 	/* The following variables are unrelated to the Handle array, and used 
    90 	 * as an inlined chain of information */
    91 	unsigned int freeID;		/* ID of a free handle in the free handle chain */
    92 	/* Indexes into the handle array for owner membership.
    93 	 * For identity roots, these are treated as the head/tail. */
    94 	unsigned int ch_prev;		/* chained previous handle */
    95 	unsigned int ch_next;		/* chained next handle */
    96 };
    97 
    98 struct QHandleType
    99 {
   100 	IHandleTypeDispatch *dispatch;
   101 	unsigned int freeID;
   102 	unsigned int children;
   103 	TypeAccess typeSec;
   104 	HandleAccess hndlSec;
   105 	unsigned int opened;
   106 	int nameIdx;
   107 };
   108 
   109 typedef void (HANDLE_REPORTER)(const char *str, ...);
   110 
   111 class HandleSystem : 
   112 	public IHandleSys
   113 {
   114 	friend HandleError IdentityHandle(IdentityToken_t *token, unsigned int *index);
   115 	friend class ShareSystem;
   116 public:
   117 	HandleSystem();
   118 	~HandleSystem();
   119 public: //IHandleSystem
   120 
   121 	HandleType_t CreateType(const char *name,
   122 		IHandleTypeDispatch *dispatch,
   123 		HandleType_t parent,
   124 		const TypeAccess *typeAccess,
   125 		const HandleAccess *hndlAccess,
   126 		IdentityToken_t *ident,
   127 		HandleError *err);
   128 
   129 	bool RemoveType(HandleType_t type, IdentityToken_t *ident);
   130 
   131 	bool FindHandleType(const char *name, HandleType_t *type);
   132 
   133 	Handle_t CreateHandle(HandleType_t type, 
   134 		void *object,
   135 		IdentityToken_t *owner,
   136 		IdentityToken_t *ident,
   137 		HandleError *err);
   138 
   139 	HandleError FreeHandle(Handle_t handle, const HandleSecurity *pSecurity);
   140 
   141 	HandleError CloneHandle(Handle_t handle, 
   142 		Handle_t *newhandle, 
   143 		IdentityToken_t *newOwner,
   144 		const HandleSecurity *pSecurity);
   145 
   146 	HandleError ReadHandle(Handle_t handle, 
   147 		HandleType_t type, 
   148 		const HandleSecurity *pSecurity,
   149 		void **object);
   150 
   151 	bool InitAccessDefaults(TypeAccess *pTypeAccess, HandleAccess *pHandleAccess);
   152 
   153 	bool TypeCheck(HandleType_t intype, HandleType_t outtype);
   154 
   155 	virtual Handle_t CreateHandleEx(HandleType_t type, 
   156 		void *object,
   157 		const HandleSecurity *pSec,
   158 		const HandleAccess *pAccess,
   159 		HandleError *err);
   160 
   161 	void Dump(HANDLE_REPORTER rep);
   162 
   163 	/* Bypasses security checks. */
   164 	Handle_t FastCloneHandle(Handle_t hndl);
   165 protected:
   166 	/**
   167 	 * Decodes a handle with sanity and security checking.
   168 	 */
   169 	HandleError GetHandle(Handle_t handle, 
   170 						  IdentityToken_t *ident, 
   171 						  QHandle **pHandle, 
   172 						  unsigned int *index,
   173 						  bool ignoreFree=false);
   174 
   175 	Handle_t FastCloneHandle(QHandle *pHandle, unsigned int index);
   176 	void GetHandleUnchecked(Handle_t hndl, QHandle *& pHandle, unsigned int &index);
   177 
   178 	/**
   179 	 * Creates a basic handle and sets its reference count to 1.
   180 	 * Does not do any type or security checking.
   181 	 */
   182 	HandleError MakePrimHandle(HandleType_t type, 
   183 							   QHandle **pHandle, 
   184 							   unsigned int *index, 
   185 							   HandleType_t *handle,
   186 							   IdentityToken_t *owner,
   187 							   bool identity=false);
   188 
   189 	/**
   190 	 * Frees a primitive handle.  Does no object freeing, only reference count, bookkeeping, 
   191 	 * and linked list maintenance.
   192 	 * If used on an Identity handle, destroys all Handles under that identity.
   193 	 */
   194 	void ReleasePrimHandle(unsigned int index);
   195 
   196 	/**
   197 	 * Sets the security owner of a type.
   198 	 */
   199 	void SetTypeSecurityOwner(HandleType_t type, IdentityToken_t *pToken);
   200 
   201 	/**
   202 	 * Helper function to check access rights.
   203 	 */
   204 	bool CheckAccess(QHandle *pHandle, HandleAccessRight right, const HandleSecurity *pSecurity);
   205 
   206 	/** 
   207 	 * Some wrappers for internal functions, so we can pass indexes instead of encoded handles.
   208 	 */
   209 	HandleError FreeHandle(QHandle *pHandle, unsigned int index);
   210 	void UnlinkHandleFromOwner(QHandle *pHandle, unsigned int index);
   211 	HandleError CloneHandle(QHandle *pHandle, unsigned int index, Handle_t *newhandle, IdentityToken_t *newOwner);
   212 	Handle_t CreateHandleInt(HandleType_t type, void *object, const HandleSecurity *pSec, HandleError *err, const HandleAccess *pAccess, bool identity);
   213 
   214 	bool TryAndFreeSomeHandles();
   215 	HandleError TryAllocHandle(unsigned int *handle);
   216 private:
   217 	QHandle *m_Handles;
   218 	QHandleType *m_Types;
   219 	KTrie<QHandleType *> m_TypeLookup;
   220 	unsigned int m_TypeTail;
   221 	unsigned int m_FreeTypes;
   222 	unsigned int m_HandleTail;
   223 	unsigned int m_FreeHandles;
   224 	unsigned int m_HSerial;
   225 	BaseStringTable *m_strtab;
   226 };
   227 
   228 extern HandleSystem g_HandleSys;
   229 
   230 struct AutoHandleRooter
   231 {
   232 public:
   233 	AutoHandleRooter(Handle_t hndl)
   234 	{
   235 		if (hndl != BAD_HANDLE)
   236 			this->hndl = g_HandleSys.FastCloneHandle(hndl);
   237 		else
   238 			this->hndl = BAD_HANDLE;
   239 	}
   240 
   241 	~AutoHandleRooter()
   242 	{
   243 		if (hndl != BAD_HANDLE)
   244 		{
   245 			HandleSecurity sec(g_pCoreIdent, g_pCoreIdent);
   246 			g_HandleSys.FreeHandle(hndl, &sec);
   247 		}
   248 	}
   249 private:
   250 	Handle_t hndl;
   251 };
   252 
   253 #endif //_INCLUDE_SOURCEMOD_HANDLESYSTEM_H_