3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
32 #include "HandleSys.h"
34 #include "PluginSys.h"
35 #include "ExtensionSys.h"
39 HandleSystem g_HandleSys;
41 QHandle *ignore_handle;
43 inline HandleType_t TypeParent(HandleType_t type)
45 return (type & ~HANDLESYS_SUBTYPE_MASK);
48 inline HandleError IdentityHandle(IdentityToken_t *token, unsigned int *index)
50 return g_HandleSys.GetHandle(token->ident, g_ShareSys.GetIdentRoot(), &ignore_handle, index);
53 HandleSystem::HandleSystem()
55 m_Handles = new QHandle[HANDLESYS_MAX_HANDLES + 1];
56 memset(m_Handles, 0, sizeof(QHandle) * (HANDLESYS_MAX_HANDLES + 1));
58 m_Types = new QHandleType[HANDLESYS_TYPEARRAY_SIZE];
59 memset(m_Types, 0, sizeof(QHandleType) * HANDLESYS_TYPEARRAY_SIZE);
61 m_TypeLookup = sm_trie_create();
62 m_strtab = new BaseStringTable(512);
67 HandleSystem::~HandleSystem()
71 sm_trie_destroy(m_TypeLookup);
76 HandleType_t HandleSystem::CreateType(const char *name,
77 IHandleTypeDispatch *dispatch,
79 const TypeAccess *typeAccess,
80 const HandleAccess *hndlAccess,
81 IdentityToken_t *ident,
88 *err = HandleError_Parameter;
93 if (typeAccess && typeAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
97 *err = HandleError_Version;
102 if (hndlAccess && hndlAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
106 *err = HandleError_Version;
111 bool isChild = false;
116 if (parent & HANDLESYS_SUBTYPE_MASK)
120 *err = HandleError_NoInherit;
124 if (parent >= HANDLESYS_TYPEARRAY_SIZE
125 || m_Types[parent].dispatch == NULL)
129 *err = HandleError_Parameter;
133 if (m_Types[parent].typeSec.access[HTypeAccess_Inherit] == false
134 && (m_Types[parent].typeSec.ident != ident))
138 *err = HandleError_Access;
144 if (name && name[0] != '\0')
146 if (sm_trie_retrieve(m_TypeLookup, name, NULL))
150 *err = HandleError_Parameter;
160 QHandleType *pParent = &m_Types[parent];
161 if (pParent->children >= HANDLESYS_MAX_SUBTYPES)
165 *err = HandleError_Limit;
170 for (unsigned int i=1; i<=HANDLESYS_MAX_SUBTYPES; i++)
172 if (m_Types[parent + i].dispatch == NULL)
182 *err = HandleError_Limit;
188 if (m_FreeTypes == 0)
190 /* Reserve another index */
191 if (m_TypeTail >= HANDLESYS_TYPEARRAY_SIZE)
195 *err = HandleError_Limit;
199 m_TypeTail += (HANDLESYS_MAX_SUBTYPES + 1);
203 /* The "free array" is compacted into the normal array for easiness */
204 index = m_Types[m_FreeTypes--].freeID;
208 QHandleType *pType = &m_Types[index];
210 pType->dispatch = dispatch;
211 if (name && name[0] != '\0')
213 pType->nameIdx = m_strtab->AddString(name);
214 sm_trie_insert(m_TypeLookup, name, (void *)pType);
223 pType->typeSec = *typeAccess;
225 InitAccessDefaults(&pType->typeSec, NULL);
226 pType->typeSec.ident = ident;
231 pType->hndlSec = *hndlAccess;
233 InitAccessDefaults(NULL, &pType->hndlSec);
244 bool HandleSystem::FindHandleType(const char *name, HandleType_t *type)
248 if (!sm_trie_retrieve(m_TypeLookup, name, (void **)&_type))
253 unsigned int offset = _type - m_Types;
263 HandleError HandleSystem::MakePrimHandle(HandleType_t type,
264 QHandle **in_pHandle,
265 unsigned int *in_index,
267 IdentityToken_t *owner,
270 unsigned int owner_index = 0;
272 if (owner && (IdentityHandle(owner, &owner_index) != HandleError_None))
274 return HandleError_Identity;
278 if (m_FreeHandles == 0)
280 if (m_HandleTail >= HANDLESYS_MAX_HANDLES)
282 return HandleError_Limit;;
284 handle = ++m_HandleTail;
286 handle = m_Handles[m_FreeHandles--].freeID;
289 QHandle *pHandle = &m_Handles[handle];
291 assert(pHandle->set == false);
293 if (++m_HSerial >= HANDLESYS_MAX_SERIALS)
298 /* Set essential information */
299 pHandle->set = identity ? HandleSet_Identity : HandleSet_Used;
300 pHandle->refcount = 1;
301 pHandle->type = type;
302 pHandle->serial = m_HSerial;
303 pHandle->owner = owner;
304 pHandle->ch_next = 0;
305 pHandle->access_special = false;
306 pHandle->is_destroying = false;
308 /* Create the hash value */
309 Handle_t hash = pHandle->serial;
313 /* Add a reference count to the type */
314 m_Types[type].opened++;
317 *in_pHandle = pHandle;
321 /* Decode the identity token
322 * For now, we don't allow nested ownership
324 if (owner && !identity)
326 QHandle *pIdentity = &m_Handles[owner_index];
327 if (pIdentity->ch_prev == 0)
329 pIdentity->ch_prev = handle;
330 pIdentity->ch_next = handle;
331 pHandle->ch_prev = 0;
333 /* Link previous node to us (forward) */
334 m_Handles[pIdentity->ch_next].ch_next = handle;
335 /* Link us to previous node (backwards) */
336 pHandle->ch_prev = pIdentity->ch_next;
338 pIdentity->ch_next = handle;
340 pIdentity->refcount++;
342 pHandle->ch_prev = 0;
345 return HandleError_None;
348 void HandleSystem::SetTypeSecurityOwner(HandleType_t type, IdentityToken_t *pToken)
351 || type >= HANDLESYS_TYPEARRAY_SIZE
352 || m_Types[type].dispatch == NULL)
357 m_Types[type].typeSec.ident = pToken;
360 Handle_t HandleSystem::CreateHandleInt(HandleType_t type,
362 const HandleSecurity *pSec,
364 const HandleAccess *pAccess,
367 IdentityToken_t *ident;
368 IdentityToken_t *owner;
372 ident = pSec->pIdentity;
373 owner = pSec->pOwner;
380 || type >= HANDLESYS_TYPEARRAY_SIZE
381 || m_Types[type].dispatch == NULL)
385 *err = HandleError_Parameter;
390 /* Check to see if we're allowed to create this handle type */
391 QHandleType *pType = &m_Types[type];
392 if (!pType->typeSec.access[HTypeAccess_Create]
393 && (!pType->typeSec.ident
394 || pType->typeSec.ident != ident))
398 *err = HandleError_Access;
408 if ((_err=MakePrimHandle(type, &pHandle, &index, &handle, owner, identity)) != HandleError_None)
419 pHandle->access_special = true;
420 pHandle->sec = *pAccess;
423 pHandle->object = object;
429 Handle_t HandleSystem::CreateHandleEx(HandleType_t type, void *object, const HandleSecurity *pSec, const HandleAccess *pAccess, HandleError *err)
431 return CreateHandleInt(type, object, pSec, err, pAccess, false);
434 Handle_t HandleSystem::CreateHandle(HandleType_t type, void *object, IdentityToken_t *owner, IdentityToken_t *ident, HandleError *err)
438 sec.pIdentity = ident;
441 return CreateHandleEx(type, object, &sec, NULL, err);
444 bool HandleSystem::TypeCheck(HandleType_t intype, HandleType_t outtype)
446 /* Check the type inheritance */
447 if (intype & HANDLESYS_SUBTYPE_MASK)
449 if (intype != outtype
450 && (TypeParent(intype) != TypeParent(outtype)))
455 if (intype != outtype)
464 HandleError HandleSystem::GetHandle(Handle_t handle,
465 IdentityToken_t *ident,
466 QHandle **in_pHandle,
467 unsigned int *in_index,
470 unsigned int serial = (handle >> 16);
471 unsigned int index = (handle & HANDLESYS_HANDLE_MASK);
473 if (index == 0 || index == 0xFFFF)
475 return HandleError_Index;
478 QHandle *pHandle = &m_Handles[index];
481 || (pHandle->set == HandleSet_Freed && !ignoreFree))
483 return HandleError_Freed;
484 } else if (pHandle->set == HandleSet_Identity
485 && ident != g_ShareSys.GetIdentRoot())
487 /* Only IdentityHandle() can read this! */
488 return HandleError_Identity;
490 if (pHandle->serial != serial)
492 return HandleError_Changed;
495 *in_pHandle = pHandle;
498 return HandleError_None;
501 bool HandleSystem::CheckAccess(QHandle *pHandle, HandleAccessRight right, const HandleSecurity *pSecurity)
503 QHandleType *pType = &m_Types[pHandle->type];
506 if (pHandle->access_special)
508 access = pHandle->sec.access[right];
510 access = pType->hndlSec.access[right];
513 /* Check if the type's identity matches */
514 if (access & HANDLE_RESTRICT_IDENTITY)
516 IdentityToken_t *owner = pType->typeSec.ident;
518 || (!pSecurity || pSecurity->pIdentity != owner))
524 /* Check if the owner is allowed */
525 if (access & HANDLE_RESTRICT_OWNER)
527 IdentityToken_t *owner = pHandle->owner;
529 && (!pSecurity || pSecurity->pOwner != owner))
538 HandleError HandleSystem::CloneHandle(QHandle *pHandle, unsigned int index, Handle_t *newhandle, IdentityToken_t *newOwner)
540 /* Get a new Handle ID */
541 unsigned int new_index;
546 if ((err=MakePrimHandle(pHandle->type, &pNewHandle, &new_index, &new_handle, newOwner)) != HandleError_None)
551 /* Assign permissions from parent */
552 if (pHandle->access_special)
554 pNewHandle->access_special = true;
555 pNewHandle->sec = pHandle->sec;
558 pNewHandle->clone = index;
561 *newhandle = new_handle;
563 return HandleError_None;
566 HandleError HandleSystem::CloneHandle(Handle_t handle, Handle_t *newhandle, IdentityToken_t *newOwner, const HandleSecurity *pSecurity)
571 IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL;
573 if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None)
578 /* Identities cannot be cloned */
579 if (pHandle->set == HandleSet_Identity)
581 return HandleError_Identity;
584 /* Check if the handle can be cloned */
585 if (!CheckAccess(pHandle, HandleAccess_Clone, pSecurity))
587 return HandleError_Access;
590 /* Make sure we're not cloning a clone */
593 QHandle *pParent = &m_Handles[pHandle->clone];
594 return CloneHandle(pParent, pHandle->clone, newhandle, newOwner);
597 return CloneHandle(pHandle, index, newhandle, newOwner);
600 HandleError HandleSystem::FreeHandle(QHandle *pHandle, unsigned int index)
602 QHandleType *pType = &m_Types[pHandle->type];
606 /* If we're a clone, decrease the parent reference count */
610 /* Note that if we ever have per-handle security, we would need to re-check
611 * the access on this Handle. */
612 master = pHandle->clone;
613 pMaster = &m_Handles[master];
615 /* Release the clone now */
616 ReleasePrimHandle(index);
618 /* Decrement the master's reference count */
619 if (--pMaster->refcount == 0)
621 /* Type should be the same but do this anyway... */
622 pType = &m_Types[pMaster->type];
623 pMaster->is_destroying = true;
624 pType->dispatch->OnHandleDestroy(pMaster->type, pMaster->object);
625 ReleasePrimHandle(master);
627 } else if (pHandle->set == HandleSet_Identity) {
628 /* If we're an identity, skip all this stuff!
629 * NOTE: SHARESYS DOES NOT CARE ABOUT THE DESTRUCTOR
631 ReleasePrimHandle(index);
633 /* Decrement, free if necessary */
634 if (--pHandle->refcount == 0)
636 pHandle->is_destroying = true;
637 pType->dispatch->OnHandleDestroy(pHandle->type, pHandle->object);
638 ReleasePrimHandle(index);
640 /* We must be cloned, so mark ourselves as freed */
641 pHandle->set = HandleSet_Freed;
642 /* Now, unlink us, so we're not being tracked by the owner */
645 UnlinkHandleFromOwner(pHandle, index);
650 return HandleError_None;
653 HandleError HandleSystem::FreeHandle(Handle_t handle, const HandleSecurity *pSecurity)
658 IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL;
660 if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None)
665 if (!CheckAccess(pHandle, HandleAccess_Delete, pSecurity))
667 return HandleError_Access;
670 if (pHandle->is_destroying)
672 /* Someone tried to free this recursively.
673 * We'll just ignore this safely.
675 return HandleError_None;
678 return FreeHandle(pHandle, index);
681 HandleError HandleSystem::ReadHandle(Handle_t handle, HandleType_t type, const HandleSecurity *pSecurity, void **object)
686 IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL;
688 if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None)
693 if (!CheckAccess(pHandle, HandleAccess_Read, pSecurity))
695 return HandleError_Access;
698 /* Check the type inheritance */
699 if (pHandle->type & HANDLESYS_SUBTYPE_MASK)
701 if (pHandle->type != type
702 && (TypeParent(pHandle->type) != TypeParent(type)))
704 return HandleError_Type;
707 if (pHandle->type != type)
709 return HandleError_Type;
715 /* if we're a clone, the rules change - object is ONLY in our reference */
718 pHandle = &m_Handles[pHandle->clone];
720 *object = pHandle->object;
723 return HandleError_None;
726 void HandleSystem::UnlinkHandleFromOwner(QHandle *pHandle, unsigned int index)
728 /* Unlink us if necessary */
729 unsigned int ident_index;
730 if (IdentityHandle(pHandle->owner, &ident_index) != HandleError_None)
733 assert(pHandle->owner == 0);
736 /* Note that since 0 is an invalid handle, if any of these links are 0,
737 * the data can still be set.
739 QHandle *pIdentity = &m_Handles[ident_index];
741 /* Unlink case: We're the head AND tail node */
742 if (index == pIdentity->ch_prev && index == pIdentity->ch_next)
744 pIdentity->ch_prev = 0;
745 pIdentity->ch_next = 0;
747 /* Unlink case: We're the head node */
748 else if (index == pIdentity->ch_prev) {
749 /* Link us to the next in the chain */
750 pIdentity->ch_prev = pHandle->ch_next;
751 /* Patch up the previous link */
752 m_Handles[pHandle->ch_next].ch_prev = 0;
754 /* Unlink case: We're the tail node */
755 else if (index == pIdentity->ch_next) {
756 /* Link us to the previous in the chain */
757 pIdentity->ch_next = pHandle->ch_prev;
758 /* Patch up the next link */
759 m_Handles[pHandle->ch_prev].ch_next = 0;
761 /* Unlink case: We're in the middle! */
763 /* Patch the forward reference */
764 m_Handles[pHandle->ch_next].ch_prev = pHandle->ch_prev;
765 /* Patch the backward reference */
766 m_Handles[pHandle->ch_prev].ch_next = pHandle->ch_next;
769 /* Lastly, decrease the reference count */
770 pIdentity->refcount--;
773 void HandleSystem::ReleasePrimHandle(unsigned int index)
775 QHandle *pHandle = &m_Handles[index];
776 HandleSet set = pHandle->set;
778 if (pHandle->owner && (set != HandleSet_Identity))
780 UnlinkHandleFromOwner(pHandle, index);
783 /* Were we an identity ourself? */
785 if (set == HandleSet_Identity)
787 /* Extra work to do. We need to find everything connected to this identity and release it. */
788 unsigned int ch_index;
790 unsigned int old_index = 0;
792 while ((ch_index = pHandle->ch_next) != 0)
794 pLocal = &m_Handles[ch_index];
796 assert(old_index != ch_index);
797 assert(pLocal->set == HandleSet_Used);
798 old_index = ch_index;
800 FreeHandle(pLocal, ch_index);
804 pHandle->set = HandleSet_None;
805 m_Types[pHandle->type].opened--;
806 m_Handles[++m_FreeHandles].freeID = index;
809 bool HandleSystem::RemoveType(HandleType_t type, IdentityToken_t *ident)
811 if (type == 0 || type >= HANDLESYS_TYPEARRAY_SIZE)
816 QHandleType *pType = &m_Types[type];
818 if (pType->typeSec.ident
819 && pType->typeSec.ident != ident)
824 if (pType->dispatch == NULL)
829 /* Remove children if we have to */
830 if (!(type & HANDLESYS_SUBTYPE_MASK))
832 QHandleType *childType;
833 for (unsigned int i=1; i<=HANDLESYS_MAX_SUBTYPES; i++)
835 childType = &m_Types[type + i];
836 if (childType->dispatch)
838 RemoveType(type + i, childType->typeSec.ident);
841 /* Link us into the free chain */
842 m_Types[++m_FreeTypes].freeID = type;
845 /* Invalidate the type now */
846 IHandleTypeDispatch *dispatch = pType->dispatch;
847 pType->dispatch = NULL;
849 /* Make sure nothing is using this type. */
853 for (unsigned int i=1; i<=m_HandleTail; i++)
855 pHandle = &m_Handles[i];
856 if (!pHandle->set || pHandle->type != type)
863 QHandle *pOther = &m_Handles[pHandle->clone];
864 if (--pOther->refcount == 0)
867 dispatch->OnHandleDestroy(type, pOther->object);
868 ReleasePrimHandle(pHandle->clone);
870 /* Unlink ourselves since we don't have a reference count */
871 ReleasePrimHandle(i);
873 /* If it's not a clone, we still have to check the reference count.
874 * Either way, we'll be destroyed eventually because the handle types do not change.
876 if (--pHandle->refcount == 0)
879 dispatch->OnHandleDestroy(type, pHandle->object);
880 ReleasePrimHandle(i);
883 if (pType->opened == 0)
893 bool HandleSystem::InitAccessDefaults(TypeAccess *pTypeAccess, HandleAccess *pHandleAccess)
897 if (pTypeAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
901 pTypeAccess->access[HTypeAccess_Create] = false;
902 pTypeAccess->access[HTypeAccess_Inherit] = false;
903 pTypeAccess->ident = NULL;
908 if (pHandleAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
913 pHandleAccess->access[HandleAccess_Clone] = 0;
914 pHandleAccess->access[HandleAccess_Delete] = HANDLE_RESTRICT_OWNER;
915 pHandleAccess->access[HandleAccess_Read] = HANDLE_RESTRICT_IDENTITY;
921 void HandleSystem::Dump(FILE *fp)
923 fprintf(fp, "%-10.10s\t%-20.20s\t%-20.20s\n", "Handle", "Owner", "Type");
924 fprintf(fp, "---------------------------------------------\n");
925 for (unsigned int i=1; i<=m_HandleTail; i++)
927 if (m_Handles[i].set != HandleSet_Used)
932 unsigned int index = (m_Handles[i].serial << 16) | i;
933 /* Determine the owner */
934 const char *owner = "UNKNOWN";
935 if (m_Handles[i].owner)
937 IdentityToken_t *pOwner = m_Handles[i].owner;
938 if (pOwner == g_pCoreIdent)
941 } else if (pOwner == g_PluginSys.GetIdentity()) {
944 CExtension *ext = g_Extensions.GetExtensionFromIdent(pOwner);
947 owner = ext->GetFilename();
949 CPlugin *pPlugin = g_PluginSys.GetPluginFromIdentity(pOwner);
952 owner = pPlugin->GetFilename();
959 const char *type = "ANON";
960 QHandleType *pType = &m_Types[m_Handles[i].type];
961 if (pType->nameIdx != -1)
963 type = m_strtab->GetString(pType->nameIdx);
965 fprintf(fp, "0x%08x\t%-20.20s\t%-20.20s\n", index, owner, type);