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"
40 HandleSystem g_HandleSys;
42 QHandle *ignore_handle;
44 inline HandleType_t TypeParent(HandleType_t type)
46 return (type & ~HANDLESYS_SUBTYPE_MASK);
49 inline HandleError IdentityHandle(IdentityToken_t *token, unsigned int *index)
51 return g_HandleSys.GetHandle(token->ident, g_ShareSys.GetIdentRoot(), &ignore_handle, index);
54 HandleSystem::HandleSystem()
56 m_Handles = new QHandle[HANDLESYS_MAX_HANDLES + 1];
57 memset(m_Handles, 0, sizeof(QHandle) * (HANDLESYS_MAX_HANDLES + 1));
59 m_Types = new QHandleType[HANDLESYS_TYPEARRAY_SIZE];
60 memset(m_Types, 0, sizeof(QHandleType) * HANDLESYS_TYPEARRAY_SIZE);
62 m_TypeLookup = sm_trie_create();
63 m_strtab = new BaseStringTable(512);
68 HandleSystem::~HandleSystem()
72 sm_trie_destroy(m_TypeLookup);
77 HandleType_t HandleSystem::CreateType(const char *name,
78 IHandleTypeDispatch *dispatch,
80 const TypeAccess *typeAccess,
81 const HandleAccess *hndlAccess,
82 IdentityToken_t *ident,
89 *err = HandleError_Parameter;
94 if (typeAccess && typeAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
98 *err = HandleError_Version;
103 if (hndlAccess && hndlAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
107 *err = HandleError_Version;
112 bool isChild = false;
117 if (parent & HANDLESYS_SUBTYPE_MASK)
121 *err = HandleError_NoInherit;
125 if (parent >= HANDLESYS_TYPEARRAY_SIZE
126 || m_Types[parent].dispatch == NULL)
130 *err = HandleError_Parameter;
134 if (m_Types[parent].typeSec.access[HTypeAccess_Inherit] == false
135 && (m_Types[parent].typeSec.ident != ident))
139 *err = HandleError_Access;
145 if (name && name[0] != '\0')
147 if (sm_trie_retrieve(m_TypeLookup, name, NULL))
151 *err = HandleError_Parameter;
161 QHandleType *pParent = &m_Types[parent];
162 if (pParent->children >= HANDLESYS_MAX_SUBTYPES)
166 *err = HandleError_Limit;
171 for (unsigned int i=1; i<=HANDLESYS_MAX_SUBTYPES; i++)
173 if (m_Types[parent + i].dispatch == NULL)
183 *err = HandleError_Limit;
189 if (m_FreeTypes == 0)
191 /* Reserve another index */
192 if (m_TypeTail >= HANDLESYS_TYPEARRAY_SIZE)
196 *err = HandleError_Limit;
200 m_TypeTail += (HANDLESYS_MAX_SUBTYPES + 1);
204 /* The "free array" is compacted into the normal array for easiness */
205 index = m_Types[m_FreeTypes--].freeID;
209 QHandleType *pType = &m_Types[index];
211 pType->dispatch = dispatch;
212 if (name && name[0] != '\0')
214 pType->nameIdx = m_strtab->AddString(name);
215 sm_trie_insert(m_TypeLookup, name, (void *)pType);
224 pType->typeSec = *typeAccess;
226 InitAccessDefaults(&pType->typeSec, NULL);
227 pType->typeSec.ident = ident;
232 pType->hndlSec = *hndlAccess;
234 InitAccessDefaults(NULL, &pType->hndlSec);
245 bool HandleSystem::FindHandleType(const char *name, HandleType_t *type)
249 if (!sm_trie_retrieve(m_TypeLookup, name, (void **)&_type))
254 unsigned int offset = _type - m_Types;
264 HandleError HandleSystem::TryAllocHandle(unsigned int *handle)
266 if (m_FreeHandles == 0)
268 if (m_HandleTail >= HANDLESYS_MAX_HANDLES)
270 return HandleError_Limit;;
272 *handle = ++m_HandleTail;
276 *handle = m_Handles[m_FreeHandles--].freeID;
279 return HandleError_None;
282 HandleError HandleSystem::MakePrimHandle(HandleType_t type,
283 QHandle **in_pHandle,
284 unsigned int *in_index,
286 IdentityToken_t *owner,
290 unsigned int owner_index = 0;
292 if (owner && (IdentityHandle(owner, &owner_index) != HandleError_None))
294 return HandleError_Identity;
298 if ((err = TryAllocHandle(&handle)) != HandleError_None)
300 if (!TryAndFreeSomeHandles()
301 || (err = TryAllocHandle(&handle)) != HandleError_None)
307 QHandle *pHandle = &m_Handles[handle];
309 assert(pHandle->set == false);
311 if (++m_HSerial >= HANDLESYS_MAX_SERIALS)
316 /* Set essential information */
317 pHandle->set = identity ? HandleSet_Identity : HandleSet_Used;
318 pHandle->refcount = 1;
319 pHandle->type = type;
320 pHandle->serial = m_HSerial;
321 pHandle->owner = owner;
322 pHandle->ch_next = 0;
323 pHandle->access_special = false;
324 pHandle->is_destroying = false;
326 /* Create the hash value */
327 Handle_t hash = pHandle->serial;
331 /* Add a reference count to the type */
332 m_Types[type].opened++;
335 *in_pHandle = pHandle;
339 /* Decode the identity token
340 * For now, we don't allow nested ownership
342 if (owner && !identity)
344 QHandle *pIdentity = &m_Handles[owner_index];
345 if (pIdentity->ch_prev == 0)
347 pIdentity->ch_prev = handle;
348 pIdentity->ch_next = handle;
349 pHandle->ch_prev = 0;
353 /* Link previous node to us (forward) */
354 m_Handles[pIdentity->ch_next].ch_next = handle;
355 /* Link us to previous node (backwards) */
356 pHandle->ch_prev = pIdentity->ch_next;
358 pIdentity->ch_next = handle;
360 pIdentity->refcount++;
364 pHandle->ch_prev = 0;
367 return HandleError_None;
370 void HandleSystem::SetTypeSecurityOwner(HandleType_t type, IdentityToken_t *pToken)
373 || type >= HANDLESYS_TYPEARRAY_SIZE
374 || m_Types[type].dispatch == NULL)
379 m_Types[type].typeSec.ident = pToken;
382 Handle_t HandleSystem::CreateHandleInt(HandleType_t type,
384 const HandleSecurity *pSec,
386 const HandleAccess *pAccess,
389 IdentityToken_t *ident;
390 IdentityToken_t *owner;
394 ident = pSec->pIdentity;
395 owner = pSec->pOwner;
402 || type >= HANDLESYS_TYPEARRAY_SIZE
403 || m_Types[type].dispatch == NULL)
407 *err = HandleError_Parameter;
412 /* Check to see if we're allowed to create this handle type */
413 QHandleType *pType = &m_Types[type];
414 if (!pType->typeSec.access[HTypeAccess_Create]
415 && (!pType->typeSec.ident
416 || pType->typeSec.ident != ident))
420 *err = HandleError_Access;
430 if ((_err=MakePrimHandle(type, &pHandle, &index, &handle, owner, identity)) != HandleError_None)
441 pHandle->access_special = true;
442 pHandle->sec = *pAccess;
445 pHandle->object = object;
451 Handle_t HandleSystem::CreateHandleEx(HandleType_t type, void *object, const HandleSecurity *pSec, const HandleAccess *pAccess, HandleError *err)
453 return CreateHandleInt(type, object, pSec, err, pAccess, false);
456 Handle_t HandleSystem::CreateHandle(HandleType_t type, void *object, IdentityToken_t *owner, IdentityToken_t *ident, HandleError *err)
460 sec.pIdentity = ident;
463 return CreateHandleEx(type, object, &sec, NULL, err);
466 bool HandleSystem::TypeCheck(HandleType_t intype, HandleType_t outtype)
468 /* Check the type inheritance */
469 if (intype & HANDLESYS_SUBTYPE_MASK)
471 if (intype != outtype
472 && (TypeParent(intype) != TypeParent(outtype)))
477 if (intype != outtype)
486 HandleError HandleSystem::GetHandle(Handle_t handle,
487 IdentityToken_t *ident,
488 QHandle **in_pHandle,
489 unsigned int *in_index,
492 unsigned int serial = (handle >> 16);
493 unsigned int index = (handle & HANDLESYS_HANDLE_MASK);
495 if (index == 0 || index == 0xFFFF)
497 return HandleError_Index;
500 QHandle *pHandle = &m_Handles[index];
503 || (pHandle->set == HandleSet_Freed && !ignoreFree))
505 return HandleError_Freed;
506 } else if (pHandle->set == HandleSet_Identity
507 && ident != g_ShareSys.GetIdentRoot())
509 /* Only IdentityHandle() can read this! */
510 return HandleError_Identity;
512 if (pHandle->serial != serial)
514 return HandleError_Changed;
517 *in_pHandle = pHandle;
520 return HandleError_None;
523 bool HandleSystem::CheckAccess(QHandle *pHandle, HandleAccessRight right, const HandleSecurity *pSecurity)
525 QHandleType *pType = &m_Types[pHandle->type];
528 if (pHandle->access_special)
530 access = pHandle->sec.access[right];
532 access = pType->hndlSec.access[right];
535 /* Check if the type's identity matches */
536 if (access & HANDLE_RESTRICT_IDENTITY)
538 IdentityToken_t *owner = pType->typeSec.ident;
540 || (!pSecurity || pSecurity->pIdentity != owner))
546 /* Check if the owner is allowed */
547 if (access & HANDLE_RESTRICT_OWNER)
549 IdentityToken_t *owner = pHandle->owner;
551 && (!pSecurity || pSecurity->pOwner != owner))
560 HandleError HandleSystem::CloneHandle(QHandle *pHandle, unsigned int index, Handle_t *newhandle, IdentityToken_t *newOwner)
562 /* Get a new Handle ID */
563 unsigned int new_index;
568 if ((err=MakePrimHandle(pHandle->type, &pNewHandle, &new_index, &new_handle, newOwner)) != HandleError_None)
573 /* Assign permissions from parent */
574 if (pHandle->access_special)
576 pNewHandle->access_special = true;
577 pNewHandle->sec = pHandle->sec;
580 pNewHandle->clone = index;
583 *newhandle = new_handle;
585 return HandleError_None;
588 HandleError HandleSystem::CloneHandle(Handle_t handle, Handle_t *newhandle, IdentityToken_t *newOwner, const HandleSecurity *pSecurity)
593 IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL;
595 if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None)
600 /* Identities cannot be cloned */
601 if (pHandle->set == HandleSet_Identity)
603 return HandleError_Identity;
606 /* Check if the handle can be cloned */
607 if (!CheckAccess(pHandle, HandleAccess_Clone, pSecurity))
609 return HandleError_Access;
612 /* Make sure we're not cloning a clone */
615 QHandle *pParent = &m_Handles[pHandle->clone];
616 return CloneHandle(pParent, pHandle->clone, newhandle, newOwner);
619 return CloneHandle(pHandle, index, newhandle, newOwner);
622 HandleError HandleSystem::FreeHandle(QHandle *pHandle, unsigned int index)
624 QHandleType *pType = &m_Types[pHandle->type];
628 /* If we're a clone, decrease the parent reference count */
632 /* Note that if we ever have per-handle security, we would need to re-check
633 * the access on this Handle. */
634 master = pHandle->clone;
635 pMaster = &m_Handles[master];
637 /* Release the clone now */
638 ReleasePrimHandle(index);
640 /* Decrement the master's reference count */
641 if (--pMaster->refcount == 0)
643 /* Type should be the same but do this anyway... */
644 pType = &m_Types[pMaster->type];
645 pMaster->is_destroying = true;
646 pType->dispatch->OnHandleDestroy(pMaster->type, pMaster->object);
647 ReleasePrimHandle(master);
649 } else if (pHandle->set == HandleSet_Identity) {
650 /* If we're an identity, skip all this stuff!
651 * NOTE: SHARESYS DOES NOT CARE ABOUT THE DESTRUCTOR
653 ReleasePrimHandle(index);
655 /* Decrement, free if necessary */
656 if (--pHandle->refcount == 0)
658 pHandle->is_destroying = true;
659 pType->dispatch->OnHandleDestroy(pHandle->type, pHandle->object);
660 ReleasePrimHandle(index);
662 /* We must be cloned, so mark ourselves as freed */
663 pHandle->set = HandleSet_Freed;
664 /* Now, unlink us, so we're not being tracked by the owner */
667 UnlinkHandleFromOwner(pHandle, index);
672 return HandleError_None;
675 HandleError HandleSystem::FreeHandle(Handle_t handle, const HandleSecurity *pSecurity)
680 IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL;
682 if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None)
687 if (!CheckAccess(pHandle, HandleAccess_Delete, pSecurity))
689 return HandleError_Access;
692 if (pHandle->is_destroying)
694 /* Someone tried to free this recursively.
695 * We'll just ignore this safely.
697 return HandleError_None;
700 return FreeHandle(pHandle, index);
703 HandleError HandleSystem::ReadHandle(Handle_t handle, HandleType_t type, const HandleSecurity *pSecurity, void **object)
708 IdentityToken_t *ident = pSecurity ? pSecurity->pIdentity : NULL;
710 if ((err=GetHandle(handle, ident, &pHandle, &index)) != HandleError_None)
715 if (!CheckAccess(pHandle, HandleAccess_Read, pSecurity))
717 return HandleError_Access;
720 /* Check the type inheritance */
721 if (pHandle->type & HANDLESYS_SUBTYPE_MASK)
723 if (pHandle->type != type
724 && (TypeParent(pHandle->type) != TypeParent(type)))
726 return HandleError_Type;
729 if (pHandle->type != type)
731 return HandleError_Type;
737 /* if we're a clone, the rules change - object is ONLY in our reference */
740 pHandle = &m_Handles[pHandle->clone];
742 *object = pHandle->object;
745 return HandleError_None;
748 void HandleSystem::UnlinkHandleFromOwner(QHandle *pHandle, unsigned int index)
750 /* Unlink us if necessary */
751 unsigned int ident_index;
752 if (IdentityHandle(pHandle->owner, &ident_index) != HandleError_None)
755 assert(pHandle->owner == 0);
758 /* Note that since 0 is an invalid handle, if any of these links are 0,
759 * the data can still be set.
761 QHandle *pIdentity = &m_Handles[ident_index];
763 /* Unlink case: We're the head AND tail node */
764 if (index == pIdentity->ch_prev && index == pIdentity->ch_next)
766 pIdentity->ch_prev = 0;
767 pIdentity->ch_next = 0;
769 /* Unlink case: We're the head node */
770 else if (index == pIdentity->ch_prev) {
771 /* Link us to the next in the chain */
772 pIdentity->ch_prev = pHandle->ch_next;
773 /* Patch up the previous link */
774 m_Handles[pHandle->ch_next].ch_prev = 0;
776 /* Unlink case: We're the tail node */
777 else if (index == pIdentity->ch_next) {
778 /* Link us to the previous in the chain */
779 pIdentity->ch_next = pHandle->ch_prev;
780 /* Patch up the next link */
781 m_Handles[pHandle->ch_prev].ch_next = 0;
783 /* Unlink case: We're in the middle! */
785 /* Patch the forward reference */
786 m_Handles[pHandle->ch_next].ch_prev = pHandle->ch_prev;
787 /* Patch the backward reference */
788 m_Handles[pHandle->ch_prev].ch_next = pHandle->ch_next;
791 /* Lastly, decrease the reference count */
792 pIdentity->refcount--;
795 void HandleSystem::ReleasePrimHandle(unsigned int index)
797 QHandle *pHandle = &m_Handles[index];
798 HandleSet set = pHandle->set;
800 if (pHandle->owner && (set != HandleSet_Identity))
802 UnlinkHandleFromOwner(pHandle, index);
805 /* Were we an identity ourself? */
807 if (set == HandleSet_Identity)
809 /* Extra work to do. We need to find everything connected to this identity and release it. */
810 unsigned int ch_index;
812 unsigned int old_index = 0;
814 while ((ch_index = pHandle->ch_next) != 0)
816 pLocal = &m_Handles[ch_index];
818 assert(old_index != ch_index);
819 assert(pLocal->set == HandleSet_Used);
820 old_index = ch_index;
822 FreeHandle(pLocal, ch_index);
826 pHandle->set = HandleSet_None;
827 m_Types[pHandle->type].opened--;
828 m_Handles[++m_FreeHandles].freeID = index;
831 bool HandleSystem::RemoveType(HandleType_t type, IdentityToken_t *ident)
833 if (type == 0 || type >= HANDLESYS_TYPEARRAY_SIZE)
838 QHandleType *pType = &m_Types[type];
840 if (pType->typeSec.ident
841 && pType->typeSec.ident != ident)
846 if (pType->dispatch == NULL)
851 /* Remove children if we have to */
852 if (!(type & HANDLESYS_SUBTYPE_MASK))
854 QHandleType *childType;
855 for (unsigned int i=1; i<=HANDLESYS_MAX_SUBTYPES; i++)
857 childType = &m_Types[type + i];
858 if (childType->dispatch)
860 RemoveType(type + i, childType->typeSec.ident);
863 /* Link us into the free chain */
864 m_Types[++m_FreeTypes].freeID = type;
867 /* Invalidate the type now */
868 IHandleTypeDispatch *dispatch = pType->dispatch;
869 pType->dispatch = NULL;
871 /* Make sure nothing is using this type. */
875 for (unsigned int i=1; i<=m_HandleTail; i++)
877 pHandle = &m_Handles[i];
878 if (!pHandle->set || pHandle->type != type)
885 QHandle *pOther = &m_Handles[pHandle->clone];
886 if (--pOther->refcount == 0)
889 dispatch->OnHandleDestroy(type, pOther->object);
890 ReleasePrimHandle(pHandle->clone);
892 /* Unlink ourselves since we don't have a reference count */
893 ReleasePrimHandle(i);
895 /* If it's not a clone, we still have to check the reference count.
896 * Either way, we'll be destroyed eventually because the handle types do not change.
898 if (--pHandle->refcount == 0)
901 dispatch->OnHandleDestroy(type, pHandle->object);
902 ReleasePrimHandle(i);
905 if (pType->opened == 0)
915 bool HandleSystem::InitAccessDefaults(TypeAccess *pTypeAccess, HandleAccess *pHandleAccess)
919 if (pTypeAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
923 pTypeAccess->access[HTypeAccess_Create] = false;
924 pTypeAccess->access[HTypeAccess_Inherit] = false;
925 pTypeAccess->ident = NULL;
930 if (pHandleAccess->hsVersion > SMINTERFACE_HANDLESYSTEM_VERSION)
935 pHandleAccess->access[HandleAccess_Clone] = 0;
936 pHandleAccess->access[HandleAccess_Delete] = HANDLE_RESTRICT_OWNER;
937 pHandleAccess->access[HandleAccess_Read] = HANDLE_RESTRICT_IDENTITY;
943 bool HandleSystem::TryAndFreeSomeHandles()
945 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
946 IPlugin *highest_owner = NULL;
947 unsigned int highest_handle_count = 0;
949 /* Search all plugins */
950 while (pl_iter->MorePlugins())
952 IPlugin *plugin = pl_iter->GetPlugin();
953 IdentityToken_t *identity = plugin->GetIdentity();
954 unsigned int handle_count = 0;
956 if (identity == NULL)
961 /* Search all handles */
962 for (unsigned int i = 1; i <= m_HandleTail; i++)
964 if (m_Handles[i].set != HandleSet_Used)
968 if (m_Handles[i].owner == identity)
974 if (handle_count > highest_handle_count)
976 highest_owner = plugin;
977 highest_handle_count = handle_count;
980 pl_iter->NextPlugin();
983 if (highest_owner == NULL || highest_handle_count == 0)
988 g_Logger.LogFatal("[SM] MEMORY LEAK DETECTED IN PLUGIN (file \"%s\")", highest_owner->GetFilename());
989 g_Logger.LogFatal("[SM] Reloading plugin to free %d handles.", highest_handle_count);
990 g_Logger.LogFatal("[SM] Contact the author(s) of this plugin to correct this error.", highest_handle_count);
992 highest_owner->GetContext()->n_err = SP_ERROR_MEMACCESS;
994 return g_PluginSys.UnloadPlugin(highest_owner);
997 void HandleSystem::Dump(HANDLE_REPORTER rep)
999 rep("%-10.10s\t%-20.20s\t%-20.20s", "Handle", "Owner", "Type");
1000 rep("---------------------------------------------");
1001 for (unsigned int i = 1; i <= m_HandleTail; i++)
1003 if (m_Handles[i].set != HandleSet_Used)
1008 unsigned int index = (m_Handles[i].serial << 16) | i;
1009 /* Determine the owner */
1010 const char *owner = "UNKNOWN";
1011 if (m_Handles[i].owner)
1013 IdentityToken_t *pOwner = m_Handles[i].owner;
1014 if (pOwner == g_pCoreIdent)
1018 else if (pOwner == g_PluginSys.GetIdentity())
1020 owner = "PLUGINSYS";
1024 CExtension *ext = g_Extensions.GetExtensionFromIdent(pOwner);
1027 owner = ext->GetFilename();
1031 CPlugin *pPlugin = g_PluginSys.GetPluginFromIdentity(pOwner);
1034 owner = pPlugin->GetFilename();
1043 const char *type = "ANON";
1044 QHandleType *pType = &m_Types[m_Handles[i].type];
1045 if (pType->nameIdx != -1)
1047 type = m_strtab->GetString(pType->nameIdx);
1049 rep("0x%08x\t%-20.20s\t%-20.20s", index, owner, type);