core/logic/HandleSys.h
author Nicholas Hastings <skamonkey@gmail.com>
Wed May 21 17:25:30 2014 -0400 (2014-05-21)
changeset 4377 7a44be5b7162
parent 4175 3ae24e84c028
permissions -rw-r--r--
Trigger build for hl2sdk-l4d changes.
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     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_namehashset.h>
    38 #include <am-string.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 	ke::AutoPtr<ke::AString> name;
   107 
   108 	static inline bool matches(const char *key, const QHandleType *type)
   109 	{
   110 		return type->name && type->name->compare(key) == 0;
   111 	}
   112 };
   113 
   114 typedef void (HANDLE_REPORTER)(const char *str, ...);
   115 
   116 class HandleSystem : 
   117 	public IHandleSys
   118 {
   119 	friend HandleError IdentityHandle(IdentityToken_t *token, unsigned int *index);
   120 	friend class ShareSystem;
   121 public:
   122 	HandleSystem();
   123 	~HandleSystem();
   124 public: //IHandleSystem
   125 
   126 	HandleType_t CreateType(const char *name,
   127 		IHandleTypeDispatch *dispatch,
   128 		HandleType_t parent,
   129 		const TypeAccess *typeAccess,
   130 		const HandleAccess *hndlAccess,
   131 		IdentityToken_t *ident,
   132 		HandleError *err);
   133 
   134 	bool RemoveType(HandleType_t type, IdentityToken_t *ident);
   135 
   136 	bool FindHandleType(const char *name, HandleType_t *type);
   137 
   138 	Handle_t CreateHandle(HandleType_t type, 
   139 		void *object,
   140 		IdentityToken_t *owner,
   141 		IdentityToken_t *ident,
   142 		HandleError *err);
   143 
   144 	HandleError FreeHandle(Handle_t handle, const HandleSecurity *pSecurity);
   145 
   146 	HandleError CloneHandle(Handle_t handle, 
   147 		Handle_t *newhandle, 
   148 		IdentityToken_t *newOwner,
   149 		const HandleSecurity *pSecurity);
   150 
   151 	HandleError ReadHandle(Handle_t handle, 
   152 		HandleType_t type, 
   153 		const HandleSecurity *pSecurity,
   154 		void **object);
   155 
   156 	bool InitAccessDefaults(TypeAccess *pTypeAccess, HandleAccess *pHandleAccess);
   157 
   158 	bool TypeCheck(HandleType_t intype, HandleType_t outtype);
   159 
   160 	virtual Handle_t CreateHandleEx(HandleType_t type, 
   161 		void *object,
   162 		const HandleSecurity *pSec,
   163 		const HandleAccess *pAccess,
   164 		HandleError *err);
   165 
   166 	void Dump(HANDLE_REPORTER rep);
   167 
   168 	/* Bypasses security checks. */
   169 	Handle_t FastCloneHandle(Handle_t hndl);
   170 protected:
   171 	/**
   172 	 * Decodes a handle with sanity and security checking.
   173 	 */
   174 	HandleError GetHandle(Handle_t handle, 
   175 						  IdentityToken_t *ident, 
   176 						  QHandle **pHandle, 
   177 						  unsigned int *index,
   178 						  bool ignoreFree=false);
   179 
   180 	Handle_t FastCloneHandle(QHandle *pHandle, unsigned int index);
   181 	void GetHandleUnchecked(Handle_t hndl, QHandle *& pHandle, unsigned int &index);
   182 
   183 	/**
   184 	 * Creates a basic handle and sets its reference count to 1.
   185 	 * Does not do any type or security checking.
   186 	 */
   187 	HandleError MakePrimHandle(HandleType_t type, 
   188 							   QHandle **pHandle, 
   189 							   unsigned int *index, 
   190 							   HandleType_t *handle,
   191 							   IdentityToken_t *owner,
   192 							   bool identity=false);
   193 
   194 	/**
   195 	 * Frees a primitive handle.  Does no object freeing, only reference count, bookkeeping, 
   196 	 * and linked list maintenance.
   197 	 * If used on an Identity handle, destroys all Handles under that identity.
   198 	 */
   199 	void ReleasePrimHandle(unsigned int index);
   200 
   201 	/**
   202 	 * Sets the security owner of a type.
   203 	 */
   204 	void SetTypeSecurityOwner(HandleType_t type, IdentityToken_t *pToken);
   205 
   206 	/**
   207 	 * Helper function to check access rights.
   208 	 */
   209 	bool CheckAccess(QHandle *pHandle, HandleAccessRight right, const HandleSecurity *pSecurity);
   210 
   211 	/** 
   212 	 * Some wrappers for internal functions, so we can pass indexes instead of encoded handles.
   213 	 */
   214 	HandleError FreeHandle(QHandle *pHandle, unsigned int index);
   215 	void UnlinkHandleFromOwner(QHandle *pHandle, unsigned int index);
   216 	HandleError CloneHandle(QHandle *pHandle, unsigned int index, Handle_t *newhandle, IdentityToken_t *newOwner);
   217 	Handle_t CreateHandleInt(HandleType_t type, void *object, const HandleSecurity *pSec, HandleError *err, const HandleAccess *pAccess, bool identity);
   218 
   219 	bool TryAndFreeSomeHandles();
   220 	HandleError TryAllocHandle(unsigned int *handle);
   221 private:
   222 	QHandle *m_Handles;
   223 	QHandleType *m_Types;
   224 	NameHashSet<QHandleType *> m_TypeLookup;
   225 	unsigned int m_TypeTail;
   226 	unsigned int m_FreeTypes;
   227 	unsigned int m_HandleTail;
   228 	unsigned int m_FreeHandles;
   229 	unsigned int m_HSerial;
   230 };
   231 
   232 extern HandleSystem g_HandleSys;
   233 
   234 struct AutoHandleRooter
   235 {
   236 public:
   237 	AutoHandleRooter(Handle_t hndl)
   238 	{
   239 		if (hndl != BAD_HANDLE)
   240 			this->hndl = g_HandleSys.FastCloneHandle(hndl);
   241 		else
   242 			this->hndl = BAD_HANDLE;
   243 	}
   244 
   245 	~AutoHandleRooter()
   246 	{
   247 		if (hndl != BAD_HANDLE)
   248 		{
   249 			HandleSecurity sec(g_pCoreIdent, g_pCoreIdent);
   250 			g_HandleSys.FreeHandle(hndl, &sec);
   251 		}
   252 	}
   253 private:
   254 	Handle_t hndl;
   255 };
   256 
   257 #endif //_INCLUDE_SOURCEMOD_HANDLESYSTEM_H_