core/systems/PluginSys.cpp
author David Anderson <dvander@alliedmods.net>
Wed Jan 17 06:49:59 2007 +0000 (2007-01-17)
changeset 308 f0e65f92cb34
parent 305 59ef1afbe958
child 309 51e67f50830e
permissions -rw-r--r--
Redesigned how server commands work. The "plugins" command will be back soon.
     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("[SM] 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("[SM] 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("[SM] Failure reading from plugins path: %s", localpath);
   621 		g_Logger.LogError("[SM] 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("[SM] 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 			/* See if we can find a similar extension */
   868 			if (ext->required && !pExt)
   869 			{
   870 				if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
   871 				{
   872 					pExt = g_Extensions.FindExtensionByName(name);
   873 				}
   874 			}
   875 			/* If we're requiring and got an extension and it's loaded, bind it */
   876 			if (ext->required && pExt && pExt->IsLoaded())
   877 			{
   878 				g_Extensions.BindChildPlugin(pExt, pPlugin);
   879 			}
   880 			/* If we're requiring and we didn't get an extension or it's not loaded, error */
   881 			if (ext->required && (!pExt || !pExt->IsLoaded()))
   882 			{
   883 				if (error)
   884 				{
   885 					snprintf(error, maxlength, "Required extension \"%s\" (file \"%s\") not found", name, file);
   886 				}
   887 				pPlugin->m_status = Plugin_Failed;
   888 				return false;
   889 			}
   890 		}
   891 	}
   892 
   893 	/* Finish by telling all listeners */
   894 	List<IPluginsListener *>::iterator iter;
   895 	IPluginsListener *pListener;
   896 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   897 	{
   898 		pListener = (*iter);
   899 		pListener->OnPluginLoaded(pPlugin);
   900 	}
   901 	
   902 	/* Tell this plugin to finish initializing itself */
   903 	pPlugin->Call_OnPluginInit();
   904 
   905 	return true;
   906 }
   907 
   908 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
   909 {
   910 	List<sp_nativeinfo_t *>::iterator iter;
   911 
   912 	for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
   913 	{
   914 		sp_nativeinfo_t *natives = (*iter);
   915 		IPluginContext *ctx = pPlugin->GetBaseContext();
   916 		unsigned int i=0;
   917 		/* Attempt to bind every native! */
   918 		while (natives[i].func != NULL)
   919 		{
   920 			ctx->BindNative(&natives[i++]);
   921 		}
   922 	}
   923 }
   924 
   925 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
   926 {
   927 	CPlugin *pPlugin = (CPlugin *)plugin;
   928 
   929 	/* This prevents removal during insertion or anything else weird */
   930 	if (m_plugins.find(pPlugin) == m_plugins.end())
   931 	{
   932 		return false;
   933 	}
   934 
   935 	List<IPluginsListener *>::iterator iter;
   936 	IPluginsListener *pListener;
   937 
   938 	if (pPlugin->GetStatus() >= Plugin_Error)
   939 	{
   940 		/* Notify listeners of unloading */
   941 		for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   942 		{
   943 			pListener = (*iter);
   944 			pListener->OnPluginUnloaded(pPlugin);
   945 		}
   946 		/* Notify plugin */
   947 		pPlugin->Call_OnPluginUnload();
   948 	}
   949 
   950 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   951 	{
   952 		/* Notify listeners of destruction */
   953 		pListener = (*iter);
   954 		pListener->OnPluginDestroyed(pPlugin);
   955 	}
   956 
   957 	/* Remove us from the lookup table and linked list */
   958 	m_plugins.remove(pPlugin);
   959 	sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
   960 	
   961 	/* Tell the plugin to delete itself */
   962 	delete pPlugin;
   963 
   964 	return true;
   965 }
   966 
   967 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
   968 {
   969 	IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
   970 	return pl;
   971 }
   972 
   973 unsigned int CPluginManager::GetPluginCount()
   974 {
   975 	return m_plugins.size();
   976 }
   977 
   978 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
   979 {
   980 	m_listeners.push_back(listener);
   981 }
   982 
   983 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
   984 {
   985 	m_listeners.remove(listener);
   986 }
   987 
   988 IPluginIterator *CPluginManager::GetPluginIterator()
   989 {
   990 	if (m_iters.empty())
   991 	{
   992 		return new CPluginIterator(&m_plugins);
   993 	} else {
   994 		CPluginIterator *iter = m_iters.front();
   995 		m_iters.pop();
   996 		iter->Reset();
   997 		return iter;
   998 	}
   999 }
  1000 
  1001 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
  1002 {
  1003 	m_iters.push(iter);
  1004 }
  1005 
  1006 void CPluginManager::ReleaseFunctionToPool(CFunction *func)
  1007 {
  1008 	if (!func)
  1009 	{
  1010 		return;
  1011 	}
  1012 	func->Cancel();
  1013 	m_funcpool.push(func);
  1014 }
  1015 
  1016 CFunction *CPluginManager::GetFunctionFromPool(funcid_t f, CPlugin *plugin)
  1017 {
  1018 	if (m_funcpool.empty())
  1019 	{
  1020 		return new CFunction(f, plugin);
  1021 	} else {
  1022 		CFunction *func = m_funcpool.front();
  1023 		m_funcpool.pop();
  1024 		func->Set(f, plugin);
  1025 		return func;
  1026 	}
  1027 }
  1028 
  1029 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
  1030 {
  1031 	/* As an optimization, we do not call strlen, but compute the length in the first pass */
  1032 	size_t alias_len = 0;
  1033 	size_t local_len = 0;
  1034 
  1035 	const char *ptr = alias;
  1036 	unsigned int alias_explicit_paths = 0;
  1037 	unsigned int alias_path_end = 0;
  1038 	while (*ptr != '\0')
  1039 	{
  1040 		if (*ptr == '\\' || *ptr == '/')
  1041 		{
  1042 			alias_explicit_paths++;
  1043 			alias_path_end = alias_len;
  1044 		}
  1045 		alias_len++;
  1046 		ptr++;
  1047 	}
  1048 
  1049 	if (alias_explicit_paths && alias_path_end == alias_len - 1)
  1050 	{
  1051 		/* Trailing slash is totally invalid here */
  1052 		return false;
  1053 	}
  1054 
  1055 	ptr = localpath;
  1056 	unsigned int local_explicit_paths = 0;
  1057 	unsigned int local_path_end = 0;
  1058 	while (*ptr != '\0')
  1059 	{
  1060 		if (*ptr == '\\' || *ptr == '/')
  1061 		{
  1062 			local_explicit_paths++;
  1063 			local_path_end = local_len;
  1064 		}
  1065 		local_len++;
  1066 		ptr++;
  1067 	}
  1068 
  1069 	/* If the alias has more explicit paths than the real path,
  1070 	 * no match will be possible.
  1071 	 */
  1072 	if (alias_explicit_paths > local_explicit_paths)
  1073 	{
  1074 		return false;
  1075 	}
  1076 
  1077 	if (alias_explicit_paths)
  1078 	{
  1079 		/* We need to find if the paths match now.  For example, these should all match:
  1080 		 * csdm     csdm
  1081 		 * csdm     optional/csdm
  1082 		 * csdm/ban optional/crab/csdm/ban
  1083 		*/
  1084 		const char *aliasptr = alias;
  1085 		const char *localptr = localpath;
  1086 		bool match = true;
  1087 		do
  1088 		{
  1089 			if (*aliasptr != *localptr)
  1090 			{
  1091 				/* We have to knock one path off */
  1092 				local_explicit_paths--;
  1093 				if (alias_explicit_paths > local_explicit_paths)
  1094 				{
  1095 					/* Skip out if we're gonna have an impossible match */
  1096 					return false;
  1097 				}
  1098 				/* Eat up localptr tokens until we get a result */
  1099 				while (((localptr - localpath) < (int)local_path_end)
  1100 					&& *localptr != '/'
  1101 					&& *localptr != '\\')
  1102 				{
  1103 					localptr++;
  1104 				}
  1105 				/* Check if we hit the end of our searchable area.
  1106 				 * This probably isn't possible because of the path 
  1107 				 * count check, but it's a good idea anyway.
  1108 				 */
  1109 				if ((localptr - localpath) >= (int)local_path_end)
  1110 				{
  1111 					return false;
  1112 				} else {
  1113 					/* Consume the slash token */
  1114 					localptr++;
  1115 				}
  1116 				/* Reset the alias pointer so we can continue consuming */
  1117 				aliasptr = alias;
  1118 				match = false;
  1119 				continue;
  1120 			}
  1121 			/* Note:
  1122 			 * This is safe because if localptr terminates early, aliasptr will too
  1123 			 */
  1124 			do
  1125 			{
  1126 				/* We should never reach the end of the string because of this check. */
  1127 				bool aliasend = (aliasptr - alias) > (int)alias_path_end;
  1128 				bool localend = (localptr - localpath) > (int)local_path_end;
  1129 				if (aliasend || localend)
  1130 				{
  1131 					if (aliasend && localend)
  1132 					{
  1133 						/* we matched, and we can break out now */
  1134 						match = true;
  1135 						break;
  1136 					}
  1137 					/* Otherwise, we've hit the end somehow and rest won't match up.  Break out. */
  1138 					match = false;
  1139 					break;
  1140 				}
  1141 
  1142 				/* If we got here, it's safe to compare the next two tokens */
  1143 				if (*localptr != *aliasptr)
  1144 				{
  1145 					match = false;
  1146 					break;
  1147 				}
  1148 				localptr++;
  1149 				aliasptr++;
  1150 			} while (true);
  1151 		} while (!match);
  1152 	}
  1153 
  1154 	/* If we got here, it's time to compare filenames */
  1155 	const char *aliasptr = alias;
  1156 	const char *localptr = localpath;
  1157 
  1158 	if (alias_explicit_paths)
  1159 	{
  1160 		aliasptr = &alias[alias_path_end + 1];
  1161 	}
  1162 
  1163 	if (local_explicit_paths)
  1164 	{
  1165 		localptr = &localpath[local_path_end + 1];
  1166 	}
  1167 
  1168 	while (true)
  1169 	{
  1170 		if (*aliasptr == '*')
  1171 		{
  1172 			/* First, see if this is the last character */
  1173 			if (aliasptr - alias == alias_len - 1)
  1174 			{
  1175 				/* If so, there's no need to match anything else */
  1176 				return true;
  1177 			}
  1178 			/* Otherwise, we need to search for an appropriate matching sequence in local.
  1179 			 * Note that we only need to search up to the next asterisk.
  1180 			 */
  1181 			aliasptr++;
  1182 			bool match = true;
  1183 			const char *local_orig = localptr;
  1184 			do
  1185 			{
  1186 				match = true;
  1187 				while (*aliasptr != '\0' && *aliasptr != '*')
  1188 				{
  1189 					/* Since aliasptr is never '\0', localptr hitting the end will fail */
  1190 					if (*aliasptr != *localptr)
  1191 					{
  1192 						match = false;
  1193 						break;
  1194 					}
  1195 					aliasptr++;
  1196 					localptr++;
  1197 				}
  1198 				if (!match)
  1199 				{
  1200 					/* If we didn't get a match, we need to advance the search stream.
  1201 					 * This will let us skip tokens while still searching for another match.
  1202 					 */
  1203 					localptr = ++local_orig;
  1204 					/* Make sure we don't go out of bounds */
  1205 					if (*localptr == '\0')
  1206 					{
  1207 						break;
  1208 					}
  1209 				}
  1210 			} while (!match);
  1211 
  1212 			if (!match)
  1213 			{
  1214 				return false;
  1215 			} else {
  1216 				/* If we got a match, move on to the next token */
  1217 				continue;
  1218 			}
  1219 		} else if (*aliasptr == '\0') {
  1220 			if (*localptr == '\0'
  1221 				||
  1222 				strcmp(localptr, ".smx") == 0)
  1223 			{
  1224 				return true;
  1225 			} else {
  1226 				return false;
  1227 			}
  1228 		} else if (*aliasptr != *localptr) {
  1229 			return false;
  1230 		}
  1231 		aliasptr++;
  1232 		localptr++;
  1233 	}
  1234 
  1235 	return true;
  1236 }
  1237 
  1238 bool CPluginManager::IsLateLoadTime() const
  1239 {
  1240 	return (m_AllPluginsLoaded || g_SourceMod.IsLateLoadInMap());
  1241 }
  1242 
  1243 void CPluginManager::OnSourceModAllInitialized()
  1244 {
  1245 	m_MyIdent = g_ShareSys.CreateCoreIdentity();
  1246 
  1247 	HandleAccess sec;
  1248 	g_HandleSys.InitAccessDefaults(NULL, &sec);
  1249 
  1250 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
  1251 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
  1252 
  1253 	g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
  1254 	g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
  1255 }
  1256 
  1257 void CPluginManager::OnSourceModShutdown()
  1258 {
  1259 	List<CPlugin *>::iterator iter;
  1260 	while ( (iter = m_plugins.begin()) != m_plugins.end() )
  1261 	{
  1262 		UnloadPlugin((*iter));
  1263 	}
  1264 
  1265 	g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
  1266 	g_ShareSys.DestroyIdentType(g_PluginIdent);
  1267 	g_ShareSys.DestroyIdentity(m_MyIdent);
  1268 }
  1269 
  1270 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
  1271 {
  1272 	/* We don't care about the internal object, actually */
  1273 }
  1274 
  1275 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
  1276 {
  1277 	m_natives.push_back(natives);
  1278 }
  1279 
  1280 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
  1281 {
  1282 	IPlugin *pPlugin;
  1283 	HandleError _err;
  1284 
  1285 	HandleSecurity sec;
  1286 
  1287 	sec.pOwner = NULL;
  1288 	sec.pIdentity = m_MyIdent;
  1289 
  1290 	if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
  1291 	{
  1292 		pPlugin = NULL;
  1293 	}
  1294 
  1295 	if (err)
  1296 	{
  1297 		*err = _err;
  1298 	}
  1299 
  1300 	return pPlugin;
  1301 }
  1302 
  1303 CPlugin *CPluginManager::GetPluginByOrder(int num)
  1304 {
  1305 	if (num < 1 || num > (int)GetPluginCount())
  1306 	{
  1307 		return NULL;
  1308 	}
  1309 
  1310 	CPlugin *pl;
  1311 	int id = 1;
  1312 
  1313 	IPluginIterator *iter = GetPluginIterator();
  1314 	for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
  1315 
  1316 	pl = (CPlugin *)(iter->GetPlugin());
  1317 	iter->Release();
  1318 
  1319 	return pl;
  1320 }