core/systems/PluginSys.cpp
author David Anderson <dvander@alliedmods.net>
Wed Jan 17 03:01:38 2007 +0000 (2007-01-17)
changeset 304 fa485d2f25ed
parent 298 07f6b2fe8468
child 305 59ef1afbe958
permissions -rw-r--r--
Added extension loading/unloading
Extended SDK for interface sharing
Completed Metamod extension support
     1 #include <stdio.h>
     2 #include "PluginSys.h"
     3 #include "ShareSys.h"
     4 #include "LibrarySys.h"
     5 #include "HandleSys.h"
     6 #include "sourcemm_api.h"
     7 #include "sourcemod.h"
     8 #include "CTextParsers.h"
     9 #include "CLogger.h"
    10 #include "ExtensionSys.h"
    11 
    12 CPluginManager g_PluginSys;
    13 HandleType_t g_PluginType = 0;
    14 IdentityType_t g_PluginIdent = 0;
    15 
    16 CPlugin::CPlugin(const char *file)
    17 {
    18 	static int MySerial = 0;
    19 
    20 	m_type = PluginType_Private;
    21 	m_status = Plugin_Uncompiled;
    22 	m_serial = ++MySerial;
    23 	m_plugin = NULL;
    24 	m_funcsnum = 0;
    25 	m_priv_funcs = NULL;
    26 	m_pub_funcs = NULL;
    27 	m_errormsg[256] = '\0';
    28 	snprintf(m_filename, sizeof(m_filename), "%s", file);
    29 	m_handle = 0;
    30 	m_ident = NULL;
    31 }
    32 
    33 CPlugin::~CPlugin()
    34 {
    35 	if (m_handle)
    36 	{
    37 		HandleSecurity sec;
    38 		sec.pOwner = g_PluginSys.GetIdentity();
    39 		sec.pIdentity = sec.pOwner;
    40 
    41 		g_HandleSys.FreeHandle(m_handle, &sec);
    42 		g_ShareSys.DestroyIdentity(m_ident);
    43 	}
    44 
    45 	if (m_ctx.base)
    46 	{
    47 		delete m_ctx.base;
    48 		m_ctx.base = NULL;
    49 	}
    50 	if (m_ctx.ctx)
    51 	{
    52 		m_ctx.vm->FreeContext(m_ctx.ctx);
    53 		m_ctx.ctx = NULL;
    54 	}
    55 	if (m_ctx.co)
    56 	{
    57 		m_ctx.vm->AbortCompilation(m_ctx.co);
    58 		m_ctx.co = NULL;
    59 	}
    60 
    61 	if (m_pub_funcs)
    62 	{
    63 		for (uint32_t i=0; i<m_plugin->info.publics_num; i++)
    64 		{
    65 			g_PluginSys.ReleaseFunctionToPool(m_pub_funcs[i]);
    66 		}
    67 		delete [] m_pub_funcs;
    68 		m_pub_funcs = NULL;
    69 	}
    70 
    71 	if (m_priv_funcs)
    72 	{
    73 		for (unsigned int i=0; i<m_funcsnum; i++)
    74 		{
    75 			g_PluginSys.ReleaseFunctionToPool(m_priv_funcs[i]);
    76 		}
    77 		delete [] m_priv_funcs;
    78 		m_priv_funcs = NULL;
    79 	}
    80 
    81 	if (m_plugin)
    82 	{
    83 		g_pSourcePawn->FreeFromMemory(m_plugin);
    84 		m_plugin = NULL;
    85 	}
    86 }
    87 
    88 void CPlugin::InitIdentity()
    89 {
    90 	if (!m_handle)
    91 	{
    92 		m_ident = g_ShareSys.CreateIdentity(g_PluginIdent);
    93 		m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
    94 		m_ctx.base->SetIdentity(m_ident);
    95 	}
    96 }
    97 
    98 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
    99 {
   100 	char fullpath[PLATFORM_MAX_PATH+1];
   101 	g_LibSys.PathFormat(fullpath, sizeof(fullpath), "%s/plugins/%s", g_SourceMod.GetSMBaseDir(), file);
   102 	FILE *fp = fopen(fullpath, "rb");
   103 
   104 	CPlugin *pPlugin = new CPlugin(file);
   105 
   106 	if (!fp)
   107 	{
   108 		if (error)
   109 		{
   110 			snprintf(error, maxlength, "Unable to open file");
   111 		}
   112 		pPlugin->m_status = Plugin_BadLoad;
   113 		return pPlugin;
   114 	}
   115 
   116 	int err;
   117 	sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
   118 	if (pl == NULL)
   119 	{
   120 		fclose(fp);
   121 		if (error)
   122 		{
   123 			snprintf(error, maxlength, "Error %d while parsing plugin", err);
   124 		}
   125 		pPlugin->m_status = Plugin_BadLoad;
   126 		return pPlugin;
   127 	}
   128 
   129 	fclose(fp);
   130 
   131 	pPlugin->m_plugin = pl;
   132 
   133 	return pPlugin;
   134 }
   135 
   136 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
   137 {
   138 	if (!m_plugin)
   139 	{
   140 		return NULL;
   141 	}
   142 
   143 	/* :NOTICE: We will eventually need to change these natives
   144 	 * for swapping in new contexts
   145 	 */
   146 	if (m_ctx.co || m_ctx.ctx)
   147 	{
   148 		return NULL;
   149 	}
   150 
   151 	m_status = Plugin_Uncompiled;
   152 
   153 	m_ctx.vm = vm;
   154 	m_ctx.co = vm->StartCompilation(m_plugin);
   155 
   156 	return m_ctx.co;
   157 }
   158 
   159 void CPlugin::CancelMyCompile()
   160 {
   161 	if (!m_ctx.co)
   162 	{
   163 		return;
   164 	}
   165 
   166 	m_ctx.vm->AbortCompilation(m_ctx.co);
   167 	m_ctx.co = NULL;
   168 	m_ctx.vm = NULL;
   169 }
   170 
   171 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
   172 {
   173 	if (!m_ctx.co)
   174 	{
   175 		return false;
   176 	}
   177 
   178 	int err;
   179 	m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
   180 	if (!m_ctx.ctx)
   181 	{
   182 		memset(&m_ctx, 0, sizeof(m_ctx));
   183 		if (error)
   184 		{
   185 			snprintf(error, maxlength, "Failed to compile (error %d)", err);
   186 		}
   187 		return false;
   188 	}
   189 
   190 	m_ctx.base = new BaseContext(m_ctx.ctx);
   191 	m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
   192 
   193 	m_funcsnum = m_ctx.vm->FunctionCount(m_ctx.ctx);
   194 
   195 	/**
   196 	 * Note: Since the m_plugin member will never change,
   197 	 * it is safe to assume the function count will never change
   198 	 */
   199 	if (m_funcsnum && m_priv_funcs == NULL)
   200 	{
   201 		m_priv_funcs = new CFunction *[m_funcsnum];
   202 		memset(m_priv_funcs, 0, sizeof(CFunction *) * m_funcsnum);
   203 	} else {
   204 		m_priv_funcs = NULL;
   205 	}
   206 
   207 	if (m_plugin->info.publics_num && m_pub_funcs == NULL)
   208 	{
   209 		m_pub_funcs = new CFunction *[m_plugin->info.publics_num];
   210 		memset(m_pub_funcs, 0, sizeof(CFunction *) * m_plugin->info.publics_num);
   211 	} else {
   212 		m_pub_funcs = NULL;
   213 	}
   214 
   215 	m_status = Plugin_Created;
   216 	m_ctx.co = NULL;
   217 
   218 	UpdateInfo();
   219 
   220 	return true;
   221 }
   222 
   223 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
   224 {
   225 	m_status = status;
   226 
   227 	va_list ap;
   228 	va_start(ap, error_fmt);
   229 	vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
   230 	va_end(ap);
   231 }
   232 
   233 IPluginFunction *CPlugin::GetFunctionById(funcid_t func_id)
   234 {
   235 	CFunction *pFunc = NULL;
   236 	funcid_t save = func_id;
   237 
   238 	if (func_id & 1)
   239 	{
   240 		func_id >>= 1;
   241 		if (func_id >= m_plugin->info.publics_num)
   242 		{
   243 			return NULL;
   244 		}
   245 		pFunc = m_pub_funcs[func_id];
   246 		if (!pFunc)
   247 		{
   248 			pFunc = g_PluginSys.GetFunctionFromPool(save, this);
   249 			m_pub_funcs[func_id] = pFunc;
   250 		}
   251 	} else {
   252 		func_id >>= 1;
   253 		unsigned int index;
   254 		if (!g_pVM->FunctionLookup(m_ctx.ctx, func_id, &index))
   255 		{
   256 			return NULL;
   257 		}
   258 		pFunc = m_priv_funcs[func_id];
   259 		if (!pFunc)
   260 		{
   261 			pFunc = g_PluginSys.GetFunctionFromPool(save, this);
   262 			m_priv_funcs[func_id] = pFunc;
   263 		}
   264 	}
   265 
   266 	return pFunc;
   267 }
   268 
   269 IPluginFunction *CPlugin::GetFunctionByName(const char *public_name)
   270 {
   271 	uint32_t index;
   272 	IPluginContext *base = m_ctx.base;
   273 
   274 	if (base->FindPublicByName(public_name, &index) != SP_ERROR_NONE)
   275 	{
   276 		return NULL;
   277 	}
   278 
   279 	CFunction *pFunc = m_pub_funcs[index];
   280 	if (!pFunc)
   281 	{
   282 		sp_public_t *pub = NULL;
   283 		base->GetPublicByIndex(index, &pub);
   284 		if (pub)
   285 		{
   286 			pFunc = g_PluginSys.GetFunctionFromPool(pub->funcid, this);
   287 			m_pub_funcs[index] = pFunc;
   288 		}
   289 	}
   290 
   291 	return pFunc;
   292 }
   293 
   294 void CPlugin::UpdateInfo()
   295 {
   296 	/* Now grab the info */
   297 	uint32_t idx;
   298 	IPluginContext *base = GetBaseContext();
   299 	int err = base->FindPubvarByName("myinfo", &idx);
   300 
   301 	if (err == SP_ERROR_NONE)
   302 	{
   303 		struct sm_plugininfo_c_t
   304 		{
   305 			cell_t name;
   306 			cell_t description;
   307 			cell_t author;
   308 			cell_t version;
   309 			cell_t url;
   310 		};
   311 		sm_plugininfo_c_t *cinfo;
   312 		cell_t local_addr;
   313 
   314 		base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
   315 		base->LocalToString(cinfo->name, (char **)&m_info.name);
   316 		base->LocalToString(cinfo->description, (char **)&m_info.description);
   317 		base->LocalToString(cinfo->author, (char **)&m_info.author);
   318 		base->LocalToString(cinfo->url, (char **)&m_info.url);
   319 		base->LocalToString(cinfo->version, (char **)&m_info.version);
   320 	}
   321 
   322 	m_info.author = m_info.author ? m_info.author : "";
   323 	m_info.description = m_info.description ? m_info.description : "";
   324 	m_info.name = m_info.name ? m_info.name : "";
   325 	m_info.url = m_info.url ? m_info.url : "";
   326 	m_info.version = m_info.version ? m_info.version : "";
   327 }
   328 
   329 void CPlugin::Call_OnPluginInit()
   330 {
   331 	if (m_status != Plugin_Loaded)
   332 	{
   333 		return;
   334 	}
   335 
   336 	m_status = Plugin_Running;
   337 
   338 	cell_t result;
   339 	IPluginFunction *pFunction = GetFunctionByName("OnPluginInit");
   340 	if (!pFunction)
   341 	{
   342 		return;
   343 	}
   344 
   345 	pFunction->PushCell(m_handle);
   346 	pFunction->Execute(&result);
   347 }
   348 
   349 void CPlugin::Call_OnPluginUnload()
   350 {
   351 	if (m_status < Plugin_Paused)
   352 	{
   353 		return;
   354 	}
   355 
   356 	cell_t result;
   357 	IPluginFunction *pFunction = GetFunctionByName("OnPluginUnload");
   358 	if (!pFunction)
   359 	{
   360 		return;
   361 	}
   362 
   363 	pFunction->Execute(&result);
   364 }
   365 
   366 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
   367 {
   368 	if (m_status != Plugin_Created)
   369 	{
   370 		return false;
   371 	}
   372 
   373 	m_status = Plugin_Loaded;
   374 
   375 	int err;
   376 	cell_t result;
   377 	IPluginFunction *pFunction = GetFunctionByName("AskPluginLoad");
   378 
   379 	if (!pFunction)
   380 	{
   381 		return true;
   382 	}
   383 
   384 	pFunction->PushCell(m_handle);
   385 	pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
   386 	pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
   387 	pFunction->PushCell(maxlength);
   388 	if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
   389 	{
   390 		m_status = Plugin_Failed;
   391 		return false;
   392 	}
   393 
   394 	if (!result || m_status != Plugin_Loaded)
   395 	{
   396 		m_status = Plugin_Failed;
   397 		return false;
   398 	}
   399 
   400 	return true;
   401 }
   402 
   403 const sp_plugin_t *CPlugin::GetPluginStructure() const
   404 {
   405 	return m_plugin;
   406 }
   407 
   408 IPluginContext *CPlugin::GetBaseContext() const
   409 {
   410 	return m_ctx.base;
   411 }
   412 
   413 sp_context_t *CPlugin::GetContext() const
   414 {
   415 	return m_ctx.ctx;
   416 }
   417 
   418 const char *CPlugin::GetFilename() const
   419 {
   420 	return m_filename;
   421 }
   422 
   423 PluginType CPlugin::GetType() const
   424 {
   425 	return m_type;
   426 }
   427 
   428 const sm_plugininfo_t *CPlugin::GetPublicInfo() const
   429 {
   430 	return &m_info;
   431 }
   432 
   433 unsigned int CPlugin::GetSerial() const
   434 {
   435 	return m_serial;
   436 }
   437 
   438 PluginStatus CPlugin::GetStatus() const
   439 {
   440 	return m_status;
   441 }
   442 
   443 bool CPlugin::IsDebugging() const
   444 {
   445 	if (!m_ctx.ctx)
   446 	{
   447 		return false;
   448 	}
   449 
   450 	return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
   451 }
   452 
   453 bool CPlugin::SetPauseState(bool paused)
   454 {
   455 	if (paused && GetStatus() != Plugin_Paused)
   456 	{
   457 		return false;
   458 	} else if (!paused && GetStatus() != Plugin_Running) {
   459 		return false;
   460 	}
   461 
   462 	m_status = (paused) ? Plugin_Paused : Plugin_Running;
   463 
   464 	IPluginFunction *pFunction = GetFunctionByName("OnPluginPauseChange");
   465 	if (pFunction)
   466 	{
   467 		cell_t result;
   468 		pFunction->PushCell(paused ? 1 : 0);
   469 		pFunction->Execute(&result);
   470 	}
   471 
   472 	return true;
   473 }
   474 
   475 IdentityToken_t *CPlugin::GetIdentity() const
   476 {
   477 	return m_ident;
   478 }
   479 
   480 bool CPlugin::ToggleDebugMode(bool debug)
   481 {
   482 	int err;
   483 
   484 	if (!IsRunnable())
   485 	{
   486 		return false;
   487 	}
   488 
   489 	if ((debug && IsDebugging()) || (!debug && !IsDebugging()))
   490 	{
   491 		return false;
   492 	}
   493 	ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
   494 	if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
   495 	{
   496 		return false;
   497 	}
   498 	sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
   499 
   500 	memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
   501 	new_ctx->hp = m_ctx.ctx->hp;
   502 	new_ctx->sp = m_ctx.ctx->sp;
   503 	new_ctx->frm = m_ctx.ctx->frm;
   504 	new_ctx->dbreak = m_ctx.ctx->dbreak;
   505 	new_ctx->context = m_ctx.ctx->context;
   506 	memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
   507 
   508 	g_pVM->FreeContext(m_ctx.ctx);
   509 	m_ctx.ctx = new_ctx;
   510 	m_ctx.base->SetContext(new_ctx);
   511 
   512 	UpdateInfo();
   513 
   514 	return true;
   515 }
   516 
   517 bool CPlugin::IsRunnable() const
   518 {
   519 	return (m_status <= Plugin_Paused) ? true : false;
   520 }
   521 
   522 /*******************
   523  * PLUGIN ITERATOR *
   524  *******************/
   525 
   526 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
   527 {
   528 	mylist = _mylist;
   529 	Reset();
   530 }
   531 
   532 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
   533 {
   534 	return (*current);
   535 }
   536 
   537 bool CPluginManager::CPluginIterator::MorePlugins()
   538 {
   539 	return (current != mylist->end());
   540 }
   541 
   542 void CPluginManager::CPluginIterator::NextPlugin()
   543 {
   544 	current++;
   545 }
   546 
   547 void CPluginManager::CPluginIterator::Release()
   548 {
   549 	g_PluginSys.ReleaseIterator(this);
   550 }
   551 
   552 CPluginManager::CPluginIterator::~CPluginIterator()
   553 {
   554 }
   555 
   556 void CPluginManager::CPluginIterator::Reset()
   557 {
   558 	current = mylist->begin();
   559 }
   560 
   561 /******************
   562  * PLUGIN MANAGER *
   563  ******************/
   564 
   565 CPluginManager::CPluginManager()
   566 {
   567 	m_LoadLookup = sm_trie_create();
   568 	m_AllPluginsLoaded = false;
   569 	m_MyIdent = NULL;
   570 }
   571 
   572 CPluginManager::~CPluginManager()
   573 {
   574 	/* :NOTICE: 
   575 	 * Ignore the fact that there might be plugins in the cache.
   576 	 * This usually means that Core is not being unloaded properly, and everything
   577 	 * will crash anyway.  YAY
   578 	 */
   579 	sm_trie_destroy(m_LoadLookup);
   580 }
   581 
   582 
   583 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
   584 {
   585 	/* First read in the database of plugin settings */
   586 	SMCParseError err;
   587 	unsigned int line, col;
   588 	m_AllPluginsLoaded = false;
   589 	if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
   590 	{
   591 		g_Logger.LogError("[SOURCEMOD] Encountered fatal error parsing file \"%s\"", config);
   592 		const char *err_msg = g_TextParser.GetSMCErrorString(err);
   593 		if (err_msg)
   594 		{
   595 			g_Logger.LogError("[SOURCEMOD] Parse error encountered: \"%s\"", err_msg);
   596 		}
   597 	}
   598 
   599 	LoadPluginsFromDir(basedir, NULL);
   600 }
   601 
   602 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
   603 {
   604 	char base_path[PLATFORM_MAX_PATH+1];
   605 
   606 	/* Form the current path to start reading from */
   607 	if (localpath == NULL)
   608 	{
   609 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
   610 	} else {
   611 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
   612 	}
   613 
   614 	IDirectory *dir = g_LibSys.OpenDirectory(base_path);
   615 
   616 	if (!dir)
   617 	{
   618 		char error[256];
   619 		g_LibSys.GetPlatformError(error, sizeof(error));
   620 		g_Logger.LogError("[SOURCEMOD] Failure reading from plugins path: %s", localpath);
   621 		g_Logger.LogError("[SOURCEMOD] Platform returned error: %s", error);
   622 		return;
   623 	}
   624 
   625 	while (dir->MoreFiles())
   626 	{
   627 		if (dir->IsEntryDirectory() 
   628 			&& (strcmp(dir->GetEntryName(), ".") != 0)
   629 			&& (strcmp(dir->GetEntryName(), "..") != 0)
   630 			&& (strcmp(dir->GetEntryName(), "disabled") != 0)
   631 			&& (strcmp(dir->GetEntryName(), "optional") != 0))
   632 		{
   633 			char new_local[PLATFORM_MAX_PATH+1];
   634 			if (localpath == NULL)
   635 			{
   636 				/* If no path yet, don't add a former slash */
   637 				snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
   638 			} else {
   639 				g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
   640 			}
   641 			LoadPluginsFromDir(basedir, new_local);
   642 		} else if (dir->IsEntryFile()) {
   643 			const char *name = dir->GetEntryName();
   644 			size_t len = strlen(name);
   645 			if (len >= 4
   646 				&& strcmp(&name[len-4], ".smx") == 0)
   647 			{
   648 				/* If the filename matches, load the plugin */
   649 				char plugin[PLATFORM_MAX_PATH+1];
   650 				if (localpath == NULL)
   651 				{
   652 					snprintf(plugin, sizeof(plugin), "%s", name);
   653 				} else {
   654 					g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
   655 				}
   656 				LoadAutoPlugin(plugin);
   657 			}
   658 		}
   659 		dir->NextEntry();
   660 	}
   661 	g_LibSys.CloseDirectory(dir);
   662 }
   663 
   664 //well i have discovered that gabe newell is very fat, so i wrote this comment now
   665 //:TODO: remove this function, create a better wrapper for LoadPlugin()/LoadAutoPlugin()
   666 bool CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t err_max)
   667 {
   668 	/**
   669 	 * Does this plugin already exist?
   670 	 */
   671 	CPlugin *pPlugin;
   672 	if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
   673 	{
   674 		/* First check the type */
   675 		PluginType type = pPlugin->GetType();
   676 		if (type == PluginType_Private
   677 			|| type == PluginType_Global)
   678 		{
   679 			return true;
   680 		}
   681 		/* Check to see if we should try reloading it */
   682 		if (pPlugin->GetStatus() == Plugin_BadLoad
   683 			|| pPlugin->GetStatus() == Plugin_Error
   684 			|| pPlugin->GetStatus() == Plugin_Failed)
   685 		{
   686 			UnloadPlugin(pPlugin);
   687 		}
   688 	}
   689 
   690 	pPlugin = CPlugin::CreatePlugin(path, error, err_max);
   691 
   692 	assert(pPlugin != NULL);
   693 
   694 	pPlugin->m_type = PluginType_MapUpdated;
   695 
   696 	ICompilation *co = NULL;
   697 
   698 	if (pPlugin->m_status == Plugin_Uncompiled)
   699 	{
   700 		co = pPlugin->StartMyCompile(g_pVM);
   701 	}
   702 
   703 	PluginSettings *pset;
   704 	unsigned int setcount = m_PluginInfo.GetSettingsNum();
   705 	for (unsigned int i=0; i<setcount; i++)
   706 	{
   707 		if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
   708 		{
   709 			continue;
   710 		}
   711 		pPlugin->m_type = pset->type_val;
   712 		if (co)
   713 		{
   714 			for (unsigned int j=0; j<pset->opts_num; j++)
   715 			{
   716 				const char *key, *val;
   717 				m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
   718 				if (!key || !val)
   719 				{
   720 					continue;
   721 				}
   722 				if (!g_pVM->SetCompilationOption(co, key, val))
   723 				{
   724 					if (error)
   725 					{
   726 						snprintf(error, err_max, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
   727 					}
   728 					pPlugin->CancelMyCompile();
   729 					pPlugin->m_status = Plugin_Failed;
   730 					co = NULL;
   731 					break;
   732 				}
   733 			}
   734 		}
   735 	}
   736 
   737 	/* Do the actual compiling */
   738 	if (co)
   739 	{
   740 		pPlugin->FinishMyCompile(NULL, 0);
   741 		co = NULL;
   742 	}
   743 
   744 	/* Get the status */
   745 	if (pPlugin->GetStatus() == Plugin_Created)
   746 	{
   747 		AddCoreNativesToPlugin(pPlugin);
   748 		pPlugin->InitIdentity();
   749 		pPlugin->Call_AskPluginLoad(error, err_max);
   750 	}
   751 
   752 	if (_plugin)
   753 	{
   754 		*_plugin = pPlugin;
   755 	}
   756 
   757 	return (pPlugin->GetStatus() == Plugin_Loaded);
   758 }
   759 
   760 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t err_max)
   761 {
   762 	CPlugin *pl;
   763 
   764 	if (!_LoadPlugin(&pl, path, debug, type, error, err_max))
   765 	{
   766 		delete pl;
   767 		return NULL;
   768 	}
   769 
   770 	AddPlugin(pl);
   771 
   772 	return pl;
   773 }
   774 
   775 void CPluginManager::LoadAutoPlugin(const char *plugin)
   776 {
   777 	CPlugin *pl;
   778 	char error[255] = "Unknown error";
   779 
   780 	if (!_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error)))
   781 	{
   782 		g_Logger.LogError("[SOURCEMOD] Failed to load plugin \"%s\": %s", plugin, error);
   783 		pl->SetErrorState(Plugin_Failed, "%s", error);
   784 	}
   785 
   786 	AddPlugin(pl);
   787 }
   788 
   789 void CPluginManager::AddPlugin(CPlugin *pPlugin)
   790 {
   791 	List<IPluginsListener *>::iterator iter;
   792 	IPluginsListener *pListener;
   793 
   794 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   795 	{
   796 		pListener = (*iter);
   797 		pListener->OnPluginCreated(pPlugin);
   798 	}
   799 
   800 	m_plugins.push_back(pPlugin);
   801 	sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
   802 }
   803 
   804 void CPluginManager::LoadAll_SecondPass()
   805 {
   806 	List<CPlugin *>::iterator iter;
   807 	CPlugin *pPlugin;
   808 
   809 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
   810 	{
   811 		pPlugin = (*iter);
   812 		if (pPlugin->GetStatus() == Plugin_Loaded)
   813 		{
   814 			/* :TODO: fix */
   815 			RunSecondPass(pPlugin, NULL, 0);
   816 		}
   817 	}
   818 
   819 	m_AllPluginsLoaded = true;
   820 }
   821 
   822 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
   823 {
   824 	/* Find any extensions this plugin needs */
   825 	struct _ext
   826 	{
   827 		cell_t name;
   828 		cell_t file;
   829 		cell_t autoload;
   830 		cell_t required;
   831 	} *ext;
   832 
   833 	IPluginContext *pBase = pPlugin->GetBaseContext();
   834 	uint32_t num = pBase->GetPubVarsNum();
   835 	sp_pubvar_t *pubvar;
   836 	IExtension *pExt;
   837 	char path[PLATFORM_MAX_PATH+1];
   838 	char *file, *name;
   839 	for (uint32_t i=0; i<num; i++)
   840 	{
   841 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
   842 		{
   843 			continue;
   844 		}
   845 		if (strncmp(pubvar->name, "__ext_", 6) == 0)
   846 		{
   847 			ext = (_ext *)pubvar->offs;
   848 			if (!ext->required && !ext->autoload)
   849 			{
   850 				continue;
   851 			}
   852 			if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
   853 			{
   854 				continue;
   855 			}
   856 			if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
   857 			{
   858 				continue;
   859 			}
   860 			snprintf(path, PLATFORM_MAX_PATH, "%s.%s", file, PLATFORM_LIB_EXT);
   861 			pExt = NULL;
   862 			/* Attempt to auto-load if necessary */
   863 			if (ext->autoload)
   864 			{
   865 				pExt = g_Extensions.LoadAutoExtension(path);
   866 			}
   867 			if (ext->required && !pExt)
   868 			{
   869 				if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
   870 				{
   871 					pExt = g_Extensions.FindExtensionByName(name);
   872 				}
   873 			}
   874 			if (ext->required && (!pExt || !pExt->IsLoaded()))
   875 			{
   876 				if (error)
   877 				{
   878 					snprintf(error, maxlength, "Required extension \"%s\" (file \"%s\") not found", name, file);
   879 				}
   880 				pPlugin->m_status = Plugin_Failed;
   881 				return false;
   882 			}
   883 		}
   884 	}
   885 
   886 	/* Finish by telling all listeners */
   887 	List<IPluginsListener *>::iterator iter;
   888 	IPluginsListener *pListener;
   889 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   890 	{
   891 		pListener = (*iter);
   892 		pListener->OnPluginLoaded(pPlugin);
   893 	}
   894 	
   895 	/* Tell this plugin to finish initializing itself */
   896 	pPlugin->Call_OnPluginInit();
   897 
   898 	return true;
   899 }
   900 
   901 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
   902 {
   903 	List<sp_nativeinfo_t *>::iterator iter;
   904 
   905 	for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
   906 	{
   907 		sp_nativeinfo_t *natives = (*iter);
   908 		IPluginContext *ctx = pPlugin->GetBaseContext();
   909 		unsigned int i=0;
   910 		/* Attempt to bind every native! */
   911 		while (natives[i].func != NULL)
   912 		{
   913 			ctx->BindNative(&natives[i++]);
   914 		}
   915 	}
   916 }
   917 
   918 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
   919 {
   920 	CPlugin *pPlugin = (CPlugin *)plugin;
   921 
   922 	/* This prevents removal during insertion or anything else weird */
   923 	if (m_plugins.find(pPlugin) == m_plugins.end())
   924 	{
   925 		return false;
   926 	}
   927 
   928 	List<IPluginsListener *>::iterator iter;
   929 	IPluginsListener *pListener;
   930 
   931 	if (pPlugin->GetStatus() >= Plugin_Error)
   932 	{
   933 		/* Notify listeners of unloading */
   934 		for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   935 		{
   936 			pListener = (*iter);
   937 			pListener->OnPluginUnloaded(pPlugin);
   938 		}
   939 		/* Notify plugin */
   940 		pPlugin->Call_OnPluginUnload();
   941 	}
   942 
   943 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   944 	{
   945 		/* Notify listeners of destruction */
   946 		pListener = (*iter);
   947 		pListener->OnPluginDestroyed(pPlugin);
   948 	}
   949 
   950 	/* Remove us from the lookup table and linked list */
   951 	m_plugins.remove(pPlugin);
   952 	sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
   953 	
   954 	/* Tell the plugin to delete itself */
   955 	delete pPlugin;
   956 
   957 	return true;
   958 }
   959 
   960 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
   961 {
   962 	IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
   963 	return pl;
   964 }
   965 
   966 unsigned int CPluginManager::GetPluginCount()
   967 {
   968 	return m_plugins.size();
   969 }
   970 
   971 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
   972 {
   973 	m_listeners.push_back(listener);
   974 }
   975 
   976 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
   977 {
   978 	m_listeners.remove(listener);
   979 }
   980 
   981 IPluginIterator *CPluginManager::GetPluginIterator()
   982 {
   983 	if (m_iters.empty())
   984 	{
   985 		return new CPluginIterator(&m_plugins);
   986 	} else {
   987 		CPluginIterator *iter = m_iters.front();
   988 		m_iters.pop();
   989 		iter->Reset();
   990 		return iter;
   991 	}
   992 }
   993 
   994 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
   995 {
   996 	m_iters.push(iter);
   997 }
   998 
   999 void CPluginManager::ReleaseFunctionToPool(CFunction *func)
  1000 {
  1001 	if (!func)
  1002 	{
  1003 		return;
  1004 	}
  1005 	func->Cancel();
  1006 	m_funcpool.push(func);
  1007 }
  1008 
  1009 CFunction *CPluginManager::GetFunctionFromPool(funcid_t f, CPlugin *plugin)
  1010 {
  1011 	if (m_funcpool.empty())
  1012 	{
  1013 		return new CFunction(f, plugin);
  1014 	} else {
  1015 		CFunction *func = m_funcpool.front();
  1016 		m_funcpool.pop();
  1017 		func->Set(f, plugin);
  1018 		return func;
  1019 	}
  1020 }
  1021 
  1022 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
  1023 {
  1024 	/* As an optimization, we do not call strlen, but compute the length in the first pass */
  1025 	size_t alias_len = 0;
  1026 	size_t local_len = 0;
  1027 
  1028 	const char *ptr = alias;
  1029 	unsigned int alias_explicit_paths = 0;
  1030 	unsigned int alias_path_end = 0;
  1031 	while (*ptr != '\0')
  1032 	{
  1033 		if (*ptr == '\\' || *ptr == '/')
  1034 		{
  1035 			alias_explicit_paths++;
  1036 			alias_path_end = alias_len;
  1037 		}
  1038 		alias_len++;
  1039 		ptr++;
  1040 	}
  1041 
  1042 	if (alias_explicit_paths && alias_path_end == alias_len - 1)
  1043 	{
  1044 		/* Trailing slash is totally invalid here */
  1045 		return false;
  1046 	}
  1047 
  1048 	ptr = localpath;
  1049 	unsigned int local_explicit_paths = 0;
  1050 	unsigned int local_path_end = 0;
  1051 	while (*ptr != '\0')
  1052 	{
  1053 		if (*ptr == '\\' || *ptr == '/')
  1054 		{
  1055 			local_explicit_paths++;
  1056 			local_path_end = local_len;
  1057 		}
  1058 		local_len++;
  1059 		ptr++;
  1060 	}
  1061 
  1062 	/* If the alias has more explicit paths than the real path,
  1063 	 * no match will be possible.
  1064 	 */
  1065 	if (alias_explicit_paths > local_explicit_paths)
  1066 	{
  1067 		return false;
  1068 	}
  1069 
  1070 	if (alias_explicit_paths)
  1071 	{
  1072 		/* We need to find if the paths match now.  For example, these should all match:
  1073 		 * csdm     csdm
  1074 		 * csdm     optional/csdm
  1075 		 * csdm/ban optional/crab/csdm/ban
  1076 		*/
  1077 		const char *aliasptr = alias;
  1078 		const char *localptr = localpath;
  1079 		bool match = true;
  1080 		do
  1081 		{
  1082 			if (*aliasptr != *localptr)
  1083 			{
  1084 				/* We have to knock one path off */
  1085 				local_explicit_paths--;
  1086 				if (alias_explicit_paths > local_explicit_paths)
  1087 				{
  1088 					/* Skip out if we're gonna have an impossible match */
  1089 					return false;
  1090 				}
  1091 				/* Eat up localptr tokens until we get a result */
  1092 				while (((localptr - localpath) < (int)local_path_end)
  1093 					&& *localptr != '/'
  1094 					&& *localptr != '\\')
  1095 				{
  1096 					localptr++;
  1097 				}
  1098 				/* Check if we hit the end of our searchable area.
  1099 				 * This probably isn't possible because of the path 
  1100 				 * count check, but it's a good idea anyway.
  1101 				 */
  1102 				if ((localptr - localpath) >= (int)local_path_end)
  1103 				{
  1104 					return false;
  1105 				} else {
  1106 					/* Consume the slash token */
  1107 					localptr++;
  1108 				}
  1109 				/* Reset the alias pointer so we can continue consuming */
  1110 				aliasptr = alias;
  1111 				match = false;
  1112 				continue;
  1113 			}
  1114 			/* Note:
  1115 			 * This is safe because if localptr terminates early, aliasptr will too
  1116 			 */
  1117 			do
  1118 			{
  1119 				/* We should never reach the end of the string because of this check. */
  1120 				bool aliasend = (aliasptr - alias) > (int)alias_path_end;
  1121 				bool localend = (localptr - localpath) > (int)local_path_end;
  1122 				if (aliasend || localend)
  1123 				{
  1124 					if (aliasend && localend)
  1125 					{
  1126 						/* we matched, and we can break out now */
  1127 						match = true;
  1128 						break;
  1129 					}
  1130 					/* Otherwise, we've hit the end somehow and rest won't match up.  Break out. */
  1131 					match = false;
  1132 					break;
  1133 				}
  1134 
  1135 				/* If we got here, it's safe to compare the next two tokens */
  1136 				if (*localptr != *aliasptr)
  1137 				{
  1138 					match = false;
  1139 					break;
  1140 				}
  1141 				localptr++;
  1142 				aliasptr++;
  1143 			} while (true);
  1144 		} while (!match);
  1145 	}
  1146 
  1147 	/* If we got here, it's time to compare filenames */
  1148 	const char *aliasptr = alias;
  1149 	const char *localptr = localpath;
  1150 
  1151 	if (alias_explicit_paths)
  1152 	{
  1153 		aliasptr = &alias[alias_path_end + 1];
  1154 	}
  1155 
  1156 	if (local_explicit_paths)
  1157 	{
  1158 		localptr = &localpath[local_path_end + 1];
  1159 	}
  1160 
  1161 	while (true)
  1162 	{
  1163 		if (*aliasptr == '*')
  1164 		{
  1165 			/* First, see if this is the last character */
  1166 			if (aliasptr - alias == alias_len - 1)
  1167 			{
  1168 				/* If so, there's no need to match anything else */
  1169 				return true;
  1170 			}
  1171 			/* Otherwise, we need to search for an appropriate matching sequence in local.
  1172 			 * Note that we only need to search up to the next asterisk.
  1173 			 */
  1174 			aliasptr++;
  1175 			bool match = true;
  1176 			const char *local_orig = localptr;
  1177 			do
  1178 			{
  1179 				match = true;
  1180 				while (*aliasptr != '\0' && *aliasptr != '*')
  1181 				{
  1182 					/* Since aliasptr is never '\0', localptr hitting the end will fail */
  1183 					if (*aliasptr != *localptr)
  1184 					{
  1185 						match = false;
  1186 						break;
  1187 					}
  1188 					aliasptr++;
  1189 					localptr++;
  1190 				}
  1191 				if (!match)
  1192 				{
  1193 					/* If we didn't get a match, we need to advance the search stream.
  1194 					 * This will let us skip tokens while still searching for another match.
  1195 					 */
  1196 					localptr = ++local_orig;
  1197 					/* Make sure we don't go out of bounds */
  1198 					if (*localptr == '\0')
  1199 					{
  1200 						break;
  1201 					}
  1202 				}
  1203 			} while (!match);
  1204 
  1205 			if (!match)
  1206 			{
  1207 				return false;
  1208 			} else {
  1209 				/* If we got a match, move on to the next token */
  1210 				continue;
  1211 			}
  1212 		} else if (*aliasptr == '\0') {
  1213 			if (*localptr == '\0'
  1214 				||
  1215 				strcmp(localptr, ".smx") == 0)
  1216 			{
  1217 				return true;
  1218 			} else {
  1219 				return false;
  1220 			}
  1221 		} else if (*aliasptr != *localptr) {
  1222 			return false;
  1223 		}
  1224 		aliasptr++;
  1225 		localptr++;
  1226 	}
  1227 
  1228 	return true;
  1229 }
  1230 
  1231 bool CPluginManager::IsLateLoadTime() const
  1232 {
  1233 	return (m_AllPluginsLoaded || g_SourceMod.IsLateLoadInMap());
  1234 }
  1235 
  1236 void CPluginManager::OnSourceModAllInitialized()
  1237 {
  1238 	m_MyIdent = g_ShareSys.CreateCoreIdentity();
  1239 
  1240 	HandleAccess sec;
  1241 	g_HandleSys.InitAccessDefaults(NULL, &sec);
  1242 
  1243 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
  1244 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
  1245 
  1246 	g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
  1247 	g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
  1248 }
  1249 
  1250 void CPluginManager::OnSourceModShutdown()
  1251 {
  1252 	List<CPlugin *>::iterator iter;
  1253 	while ( (iter = m_plugins.begin()) != m_plugins.end() )
  1254 	{
  1255 		UnloadPlugin((*iter));
  1256 	}
  1257 
  1258 	g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
  1259 	g_ShareSys.DestroyIdentType(g_PluginIdent);
  1260 	g_ShareSys.DestroyIdentity(m_MyIdent);
  1261 }
  1262 
  1263 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
  1264 {
  1265 	/* We don't care about the internal object, actually */
  1266 }
  1267 
  1268 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
  1269 {
  1270 	m_natives.push_back(natives);
  1271 }
  1272 
  1273 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
  1274 {
  1275 	IPlugin *pPlugin;
  1276 	HandleError _err;
  1277 
  1278 	HandleSecurity sec;
  1279 
  1280 	sec.pOwner = NULL;
  1281 	sec.pIdentity = m_MyIdent;
  1282 
  1283 	if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
  1284 	{
  1285 		pPlugin = NULL;
  1286 	}
  1287 
  1288 	if (err)
  1289 	{
  1290 		*err = _err;
  1291 	}
  1292 
  1293 	return pPlugin;
  1294 }
  1295 
  1296 CPlugin *CPluginManager::GetPluginByOrder(int num)
  1297 {
  1298 	if (num < 1 || num > (int)GetPluginCount())
  1299 	{
  1300 		return NULL;
  1301 	}
  1302 
  1303 	CPlugin *pl;
  1304 	int id = 1;
  1305 
  1306 	IPluginIterator *iter = GetPluginIterator();
  1307 	for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
  1308 
  1309 	pl = (CPlugin *)(iter->GetPlugin());
  1310 	iter->Release();
  1311 
  1312 	return pl;
  1313 }