metamod/mplugin.cpp
author bailopan
Tue Jul 12 23:23:35 2005 +0000 (2005-07-12)
branchB-work
changeset 133 fbe73f167e7d
parent 130 4bfb3f26c519
child 139 2995153b596c
permissions -rw-r--r--
Fixed bug in plugin info reporting, added ifvers reporting
     1 // vi: set ts=4 sw=4 :
     2 // vim: set tw=75 :
     3 
     4 // mplugin.cpp - functions for individual plugin (class MPlugin)
     5 
     6 /*
     7  * Copyright (c) 2001-2003 Will Day <[email protected]>
     8  *
     9  *    This file is part of Metamod.
    10  *
    11  *    Metamod is free software; you can redistribute it and/or modify it
    12  *    under the terms of the GNU General Public License as published by the
    13  *    Free Software Foundation; either version 2 of the License, or (at
    14  *    your option) any later version.
    15  *
    16  *    Metamod is distributed in the hope that it will be useful, but
    17  *    WITHOUT ANY WARRANTY; without even the implied warranty of
    18  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    19  *    General Public License for more details.
    20  *
    21  *    You should have received a copy of the GNU General Public License
    22  *    along with Metamod; if not, write to the Free Software Foundation,
    23  *    Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    24  *
    25  *    In addition, as a special exception, the author gives permission to
    26  *    link the code of this program with the Half-Life Game Engine ("HL
    27  *    Engine") and Modified Game Libraries ("MODs") developed by Valve,
    28  *    L.L.C ("Valve").  You must obey the GNU General Public License in all
    29  *    respects for all of the code used other than the HL Engine and MODs
    30  *    from Valve.  If you modify this file, you may extend this exception
    31  *    to your version of the file, but you are not obligated to do so.  If
    32  *    you do not wish to do so, delete this exception statement from your
    33  *    version.
    34  *
    35  */
    36 
    37 #include <errno.h>				// errno, etc
    38 #include <malloc.h>				// malloc, etc
    39 #include <sys/types.h>			// stat
    40 #include <sys/stat.h>			// stat
    41 
    42 #include <extdll.h>				// always
    43 
    44 #include "mplugin.h"			// me
    45 #include "metamod.h"			// GameDLL, etc
    46 #include "mreg.h"				// MRegCmdList::show(int), etc
    47 #include "mhook.h"				// class MHook
    48 #include "h_export.h"			// GIVE_ENGINE_FUNCTIONS_FN, etc
    49 #include "dllapi.h"				// FN_GAMEINIT, etc
    50 #include "support_meta.h"		// full_gamedir_path,
    51 #include "types_meta.h"			// mBOOL
    52 #include "log_meta.h"			// logging functions, etc
    53 #include "osdep.h"				// win32 snprintf, is_absolute_path,
    54 
    55 
    56 // Parse a line from plugins.ini into a plugin.
    57 // meta_errno values:
    58 //  - ME_COMMENT	ignored commented line
    59 //  - ME_FORMAT		invalid line format
    60 //  - ME_OSNOTSUP	plugin is not for this OS
    61 mBOOL MPlugin::ini_parseline(char *line) {
    62 	char *token;
    63 	char *ptr_token;
    64 	char *cp;
    65 
    66 	// skip whitespace at start of line
    67 	while(*line==' ' || *line=='\t' ) line++;
    68 
    69 	// remove whitespace at end of line
    70 	cp = line + strlen(line) -1;
    71 	while(*cp==' ' || *cp=='\t') *cp--='\0';
    72 
    73 	// skip empty lines
    74 	if(line[0]=='\0') {
    75 		META_DEBUG(7, ("ini: Ignoring empty line: %s", line));
    76 		RETURN_ERRNO(mFALSE, ME_BLANK);
    77 	}
    78 
    79 	if(line[0]=='#' || line[0]==';' || strstr(line, "//")==line) {
    80 		META_DEBUG(7, ("ini: Ignoring commented line: %s", line));
    81 		RETURN_ERRNO(mFALSE, ME_COMMENT);
    82 	}
    83 
    84 	// grab platform ("win32" or "linux")
    85 	token=strtok_r(line, " \t", &ptr_token);
    86 	if(!token)
    87 		RETURN_ERRNO(mFALSE, ME_FORMAT);
    88 	if(strcasecmp(token, PLATFORM) == 0) {
    89 		pfspecific=0;
    90 	} else if(strcasecmp(token, PLATFORM_SPC) == 0) {
    91 		pfspecific=1;
    92 	} else {
    93 		// plugin is not for this OS
    94 		META_DEBUG(7, ("ini: Ignoring entry for %s", token));
    95 		RETURN_ERRNO(mFALSE, ME_OSNOTSUP);
    96 	}
    97 
    98 	// grab filename
    99 	token=strtok_r(NULL, " \t\r\n", &ptr_token);
   100 	if(!token)
   101 		RETURN_ERRNO(mFALSE, ME_FORMAT);
   102 	STRNCPY(filename, token, sizeof(filename));
   103 	normalize_pathname(filename);
   104 	// Store name of just the actual _file_, without dir components.
   105 	cp=strrchr(filename, '/');
   106 	if(cp)
   107 		file=cp+1;
   108 	else
   109 		file=filename;
   110 
   111 	// Grab description.
   112 	// Just get the the rest of the line, minus line-termination.
   113 	token=strtok_r(NULL, "\n\r", &ptr_token);
   114 	if(token) {
   115 		token=token+strspn(token, " \t");			// skip whitespace
   116 		STRNCPY(desc, token, sizeof(desc));
   117 	}
   118 	else {
   119 		// If no description is specified, temporarily use plugin file,
   120 		// until plugin can be queried, and desc replaced with info->name.
   121 		snprintf(desc, sizeof(desc), "<%s>", file);
   122 	}
   123 
   124 	// Make full pathname (from gamedir if relative, remove "..",
   125 	// backslashes, etc).
   126 	full_gamedir_path(filename, pathname);
   127 
   128 	source=PS_INI;
   129 	status=PL_VALID;
   130 	return(mTRUE);
   131 }
   132 
   133 // Unload a plugin from plugin request
   134 // meta_errno values:
   135 //  - errno's from unload()
   136 mBOOL MPlugin::plugin_unload(plid_t plid, PLUG_LOADTIME now, PL_UNLOAD_REASON reason)
   137 {
   138 	PLUG_ACTION old_action;
   139 	MPlugin *pl_unloader;
   140 
   141 	if ( !(pl_unloader=Plugins->find(plid)) )
   142 	{
   143 		META_WARNING("dll: Not unloading plugin '%s'; plugin that requested unload is not found.", desc);
   144 		RETURN_ERRNO(mFALSE, ME_BADREQ);
   145 	} else if (pl_unloader->index == index) {
   146 		META_WARNING("dll: Not unloading plugin '%s'; Plugin tried to unload itself.", desc);
   147 		RETURN_ERRNO(mFALSE, ME_UNLOAD_SELF);
   148 	} else if (is_unloader) {
   149 		META_WARNING("dll: Not unloading plugin '%s'; Plugin is unloading plugin that tried to unload it.", desc);
   150 		RETURN_ERRNO(mFALSE, ME_UNLOAD_UNLOADER);
   151 	} else {
   152 		unloader_index = pl_unloader->index;
   153 	}
   154 
   155 	//block unloader from being unloaded by other plugin
   156 	pl_unloader->is_unloader = mTRUE;
   157 
   158 	//try unload
   159 	old_action = action;
   160 	action = PA_UNLOAD;
   161 	if (unload(now, reason, PNL_PLG_FORCED))
   162 	{
   163 		META_DEBUG(1,("Unloaded plugin '%s'", desc));
   164 		pl_unloader->is_unloader = mFALSE;
   165 		return mTRUE;
   166 	}
   167 
   168 	pl_unloader->is_unloader = mFALSE;
   169 
   170 	//can't unload plugin now, set delayed
   171 	if (meta_errno==ME_DELAYED)
   172 	{
   173 		action = old_action;
   174 		meta_errno = ME_NOTALLOWED;
   175 		META_DEBUG(2, ("dll: Failed unload plugin '%s'; can't detach now: allowed=%s; now=%s", desc, str_unloadable(), str_loadtime(PT_ANYTIME, SL_SIMPLE)));
   176 	}
   177 
   178 	return mFALSE;
   179 }
   180 
   181 // Parse a filename string from PEXT_LOAD_PLUGIN_BY_* function into a plugin.
   182 // meta_errno values:
   183 mBOOL MPlugin::plugin_parseline(const char *fname, int loader_index)
   184 {
   185 	char *cp;
   186 
   187 	source_plugin_index = loader_index;
   188 
   189 	STRNCPY(filename, fname, sizeof(filename));
   190 	normalize_pathname(filename);
   191 
   192 	//store just name of the actual _file, without path
   193 	cp = strrchr(filename, '/');
   194 	if (cp)
   195 		file = cp+1;
   196 	else
   197 		file = filename;
   198 
   199 	//grab description
   200 	//temporarily use plugin file until plugin can be queried
   201 	snprintf(desc, sizeof(desc), "<%s>", file);
   202 
   203 	//make full pathname
   204 	full_gamedir_path(filename, pathname);
   205 
   206 	source = PS_PLUGIN;
   207 	status = PL_VALID;
   208 
   209 	return mTRUE;
   210 }
   211 
   212 // Parse a line from console "load" command into a plugin.
   213 // meta_errno values:
   214 //  - ME_FORMAT		invalid line format
   215 mBOOL MPlugin::cmd_parseline(const char *line) {
   216 	char buf[NAME_MAX + PATH_MAX + MAX_DESC_LEN];
   217 	char *token;
   218 	char *ptr_token;
   219 	char *cp;
   220 
   221 	STRNCPY(buf, line, sizeof(buf));
   222 
   223 	// remove "load"
   224 	token=strtok_r(buf, " \t", &ptr_token);
   225 	if(!token)
   226 		RETURN_ERRNO(mFALSE, ME_FORMAT);
   227 
   228 	// grab filename
   229 	token=strtok_r(NULL, " \t", &ptr_token);
   230 	if(!token)
   231 		RETURN_ERRNO(mFALSE, ME_FORMAT);
   232 	STRNCPY(filename, token, sizeof(filename));
   233 	normalize_pathname(filename);
   234 	// store name of just the actual _file_, without dir components
   235 	cp=strrchr(filename, '/');
   236 	if(cp)
   237 		file=cp+1;
   238 	else
   239 		file=filename;
   240 
   241 	// Grab description.
   242 	// Specify no delimiter chars, as we just want the rest of the line.
   243 	token=strtok_r(NULL, "", &ptr_token);
   244 	if(token) {
   245 		token=token+strspn(token, " \t");			// skip whitespace
   246 		STRNCPY(desc, token, sizeof(desc));
   247 	}
   248 	else {
   249 		// if no description is specified, temporarily use plugin file,
   250 		// until plugin can be queried, and desc replaced with info->name.
   251 		snprintf(desc, sizeof(desc), "<%s>", file);
   252 	}
   253 
   254 	// Make full pathname (from gamedir if relative, remove "..",
   255 	// backslashes, etc).
   256 	full_gamedir_path(filename, pathname);
   257 
   258 	source=PS_CMD;
   259 	status=PL_VALID;
   260 	return(mTRUE);
   261 }
   262 
   263 // Make sure this plugin has the necessary minimal information.
   264 // meta_errno values:
   265 //  - ME_ARGUMENT	missing necessary fields in plugin
   266 mBOOL MPlugin::check_input(void) {
   267 	// doublecheck our input/state
   268 	if(status < PL_VALID) {
   269 		META_ERROR("dll: Tried to operate on plugin[%d] with a non-valid status (%d)", index, str_status());
   270 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   271 	}
   272 	if(!file || !file[0]) {
   273 		META_ERROR("dll: Tried to operate on plugin[%d] with an empty file", 
   274 				index);
   275 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   276 	}
   277 	if(!filename[0]) {
   278 		META_ERROR("dll: Tried to operate on plugin[%d] with an empty filename",
   279 				index);
   280 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   281 	}
   282 	if(!pathname[0]) {
   283 		META_ERROR("dll: Tried to operate on plugin[%d] with an empty pathname",
   284 				index);
   285 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   286 	}
   287 	if(!desc[0]) {
   288 		// if no description is specified, temporarily use plugin file,
   289 		// until plugin can be queried, and desc replaced with info->name.
   290 		snprintf(desc, sizeof(desc), "<%s>", file);
   291 	}
   292 	return(mTRUE);
   293 }
   294 
   295 // Try to resolve a plugin's filename as a (possibly partial) path to an
   296 // actual filename on disk, to facilitate easier console load-command
   297 // arguments.  Uses resolve_dirs, resolve_prefix, and resolve_suffix below.  
   298 // Example paths that it tries:
   299 //    filename
   300 //    Gamedir/filename.dll, Gamedir/filename.so
   301 //    Gamedir/filename_i386.so
   302 //    Gamedir/dlls/mm_filename_i386.so
   303 //    Gamedir/dlls/filename_mm_i386.so
   304 //    Gamedir/dlls/filename_MM_i386.so
   305 // meta_errno values:
   306 //  - ME_NOTFOUND	couldn't find a matching file for the partial name
   307 //  - errno's from check_input()
   308 mBOOL MPlugin::resolve(void) {
   309 	char *found;
   310 	char *cp;
   311 	int len;
   312 	if(!check_input()) {
   313 		// details logged, meta_errno set in check_input()
   314 		return(mFALSE);
   315 	}
   316 	if(is_absolute_path(filename))
   317 		found=resolve_prefix(filename);
   318 	else
   319 		found=resolve_dirs(filename);
   320 
   321 	if(!found) {
   322 		META_DEBUG(2, ("Couldn't resolve '%s' to file", filename));
   323 		RETURN_ERRNO(mFALSE, ME_NOTFOUND);
   324 	}
   325 	META_DEBUG(2, ("Resolved '%s' to file '%s'", filename, found));
   326 	// store pathname: the resolved path (should be absolute)
   327 	STRNCPY(pathname, found, sizeof(pathname));
   328 	// store file: the name of the file (without dir)
   329 	cp=strrchr(pathname, '/');
   330 	if(cp)
   331 		file=cp+1;
   332 	else
   333 		file=pathname;
   334 	// store pathname: the gamedir relative path, or an absolute path
   335 	len=strlen(GameDLL.gamedir);
   336 	if(strncasecmp(pathname, GameDLL.gamedir, len) == 0)
   337 		STRNCPY(filename, pathname+len+1, sizeof(filename));
   338 	else
   339 		STRNCPY(filename, pathname, sizeof(filename));
   340 
   341 	return(mTRUE);
   342 }
   343 
   344 // For the given path, tries to find file in several possible 
   345 // directories.
   346 // Try:
   347 //     GAMEDIR/filename
   348 //     GAMEDIR/dlls/filename
   349 // meta_errno values:
   350 //  - none
   351 char *MPlugin::resolve_dirs(char *path) {
   352 	struct stat st;
   353 	static char buf[PATH_MAX];
   354 	char *found;
   355 
   356 	snprintf(buf, sizeof(buf), "%s/%s", GameDLL.gamedir, path);
   357 	// try this path
   358 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   359 		return(buf);
   360 	// try other file prefixes in this path
   361 	if((found=resolve_prefix(buf)))
   362 		return(found);
   363 
   364 	snprintf(buf, sizeof(buf), "%s/dlls/%s", GameDLL.gamedir, path);
   365 	// try this path
   366 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   367 		return(buf);
   368 	// try other file prefixes for this path
   369 	if((found=resolve_prefix(buf)))
   370 		return(found);
   371 
   372 	return(NULL);
   373 }
   374 
   375 // For the given path, tries several possible filename prefixes.
   376 // Try:
   377 //     dir/mm_file
   378 //     dir/file
   379 // meta_errno values:
   380 //  - none
   381 char *MPlugin::resolve_prefix(char *path) {
   382 	struct stat st;
   383 	char *cp, *fname;
   384 	char dname[PATH_MAX];
   385 	static char buf[PATH_MAX];
   386 	char *found;
   387 
   388 	// try "mm_" prefix FIRST.
   389 	// split into dirname and filename
   390 	STRNCPY(dname, path, sizeof(dname));
   391 	cp=strrchr(dname, '/');
   392 	if(cp) {
   393 		*cp='\0';
   394 		fname=cp+1;
   395 		snprintf(buf, sizeof(buf), "%s/mm_%s", dname, fname);
   396 	}
   397 	else {
   398 		// no directory in given path
   399 		snprintf(buf, sizeof(buf), "mm_%s", path);
   400 	}
   401 	// try this path
   402 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   403 		return(buf);
   404 	// try other suffixes for this path
   405 	if((found=resolve_suffix(buf)))
   406 		return(found);
   407 
   408 	// try other suffixes for the original path
   409 	if((found=resolve_suffix(path)))
   410 		return(found);
   411 
   412 	return(NULL);
   413 }
   414 
   415 // For the given path, tries several different filename suffixes.
   416 // Try:
   417 //     path
   418 //     path_mm
   419 //     path_MM
   420 //     path.so (linux), path.dll (win32)
   421 //     path_i386.so, path_i486.so, etc (if linux)
   422 // meta_errno values:
   423 //  - none
   424 char *MPlugin::resolve_suffix(char *path) {
   425 	struct stat st;
   426 	static char buf[PATH_MAX];
   427 	char *found;
   428 
   429 	// Hmm, recursion.
   430 	if(!strstr(path, "_mm")) {
   431 		char *tmpbuf;
   432 		snprintf(buf, sizeof(buf), "%s_mm", path);
   433 		tmpbuf=strdup(buf);
   434 		found=resolve_suffix(tmpbuf);
   435 		free(tmpbuf);
   436 		if(found) return(found);
   437 	}
   438 	if(!strstr(path, "_MM")) {
   439 		char *tmpbuf;
   440 		snprintf(buf, sizeof(buf), "%s_MM", path);
   441 		tmpbuf=strdup(buf);
   442 		found=resolve_suffix(tmpbuf);
   443 		free(tmpbuf);
   444 		if(found) return(found);
   445 	}
   446 
   447 #ifdef _WIN32
   448 	snprintf(buf, sizeof(buf), "%s.dll", path);
   449 #elif defined(linux)
   450 	snprintf(buf, sizeof(buf), "%s.so", path);
   451 #else
   452 #error "OS unrecognized"
   453 #endif /* _WIN32 */
   454 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   455 		return(buf);
   456 
   457 #ifdef linux
   458 	snprintf(buf, sizeof(buf), "%s_i386.so", path);
   459 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   460 		return(buf);
   461 	snprintf(buf, sizeof(buf), "%s_i486.so", path);
   462 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   463 		return(buf);
   464 	snprintf(buf, sizeof(buf), "%s_i586.so", path);
   465 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   466 		return(buf);
   467 	snprintf(buf, sizeof(buf), "%s_i686.so", path);
   468 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   469 		return(buf);
   470 	snprintf(buf, sizeof(buf), "%s_amd64.so", path);
   471 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   472 		return(buf);
   473 #endif /* linux */
   474 
   475 	return(NULL);
   476 }
   477 
   478 
   479 // Check if a passed string starts with a known platform postfix.
   480 // It does not check beyond the period in order to work for both
   481 // Linux and Win32.
   482 static mBOOL is_platform_postfix(char* pf)
   483 {
   484 	if ( NULL == pf ) return mFALSE;
   485 
   486 	if ( 0 == strncmp(pf, "_i386.", 6) ) return mTRUE;
   487 	if ( 0 == strncmp(pf, "_i486.", 6) ) return mTRUE;
   488 	if ( 0 == strncmp(pf, "_i586.", 6) ) return mTRUE;
   489 	if ( 0 == strncmp(pf, "_i686.", 6) ) return mTRUE;
   490 	if ( 0 == strncmp(pf, "_amd64.", 7) ) return mTRUE;
   491 
   492 	return mFALSE;
   493 }
   494 
   495 
   496 // Check if a given plugin is the same but possibly for a
   497 // different platform. A match is considered to be found if
   498 // 1.  the filename without the path is the same, or
   499 // 2a. for an attached plugin the logtag is the same, or
   500 // 2b. the description is the same, or
   501 // 3.  a significant part of the filename is the same.
   502 // A significant part of a plugin name is currently defined to:
   503 //  the part up to a known platform postfix as determined by 
   504 //  the is_platform_postfix() function (see above), or
   505 //  the part up to the last dot, if one exists.
   506 // meta_errno values:
   507 //  - none
   508 mBOOL MPlugin::platform_match(MPlugin* other) {
   509 	char *end, *other_end;
   510 	int prefixlen;
   511 
   512 	if(status == PL_EMPTY || other->status == PL_EMPTY) return mFALSE;
   513 
   514 	if(strcmp(file, other->file) == 0) return mTRUE;
   515 
   516 	if(status >= PL_OPENED && other->status >= PL_OPENED &&
   517        strcmp(info->logtag, other->info->logtag) == 0 ) return mTRUE;
   518 	if(*desc != '\0' && strcasecmp(desc,other->desc) == 0) return mTRUE;
   519 
   520 	end=strrchr(file, '_');
   521 	if(end == NULL || !is_platform_postfix(end)) end=strrchr(file, '.');
   522 	other_end=strrchr(other->file, '_');
   523 	if(other_end == NULL || !is_platform_postfix(other_end)) other_end=strrchr(other->file, '.');
   524 
   525 	if(end == NULL || other_end == NULL) return mFALSE;
   526 
   527 	prefixlen=end-file;
   528 	if((other_end-other->file) != prefixlen) return mFALSE;
   529 
   530 	if(strncmp(file,other->file, prefixlen) == 0) return mTRUE;
   531 
   532 	return mFALSE;
   533 }
   534 
   535 
   536 // Load a plugin; query, check allowed time, attach.
   537 // meta_errno values:
   538 //  - ME_ARGUMENT	missing necessary fields in plugin
   539 //  - ME_ALREADY	this plugin already loaded
   540 //  - ME_BADREQ		plugin not marked for load
   541 //  - ME_DELAYED	load request is delayed (till changelevel?)
   542 //  - ME_NOTALLOWED	plugin not loadable after startup
   543 //  - errno's from query()
   544 //  - errno's from attach()
   545 //  - errno's from check_input()
   546 mBOOL MPlugin::load(PLUG_LOADTIME now) {
   547 	if(!check_input()) {
   548 		// details logged, meta_errno set in check_input()
   549 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   550 	}
   551 	if(status >= PL_RUNNING) {
   552 		META_ERROR("dll: Not loading plugin '%s'; already loaded (status=%s)", 
   553 				desc, str_status());
   554 		RETURN_ERRNO(mFALSE, ME_ALREADY);
   555 	}
   556 	if(action != PA_LOAD && action != PA_ATTACH) {
   557 		META_ERROR("dll: Not loading plugin '%s'; not marked for load (action=%s)", desc, str_action());
   558 		RETURN_ERRNO(mFALSE, ME_BADREQ);
   559 	}
   560 
   561 	if(status != PL_OPENED) {
   562 		// query plugin; open file and get info about it
   563 		if(!query()) {
   564 			META_ERROR("dll: Skipping plugin '%s'; couldn't query", desc);
   565 			if(meta_errno != ME_DLOPEN) {
   566 				if(DLCLOSE(handle) != 0) {
   567 					META_ERROR("dll: Couldn't close plugin file '%s': %s", 
   568 							file, DLERROR());
   569 				}
   570 				else
   571 					handle=NULL;
   572 			}
   573 			status=PL_BADFILE;
   574 			// meta_errno should be already set in query()
   575 			return(mFALSE);
   576 		}
   577 		status=PL_OPENED;
   578 	}
   579 
   580 	// are we allowed to attach this plugin at this time?
   581 	if(info->loadable < now) {
   582 		if(info->loadable > PT_STARTUP) {
   583 			// will try to attach again at next opportunity
   584 			META_DEBUG(2, ("dll: Delaying load plugin '%s'; can't attach now: allowed=%s; now=%s", 
   585 						desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
   586 			RETURN_ERRNO(mFALSE, ME_DELAYED);
   587 		}
   588 		else {
   589 			META_DEBUG(2, ("dll: Failed load plugin '%s'; can't attach now: allowed=%s; now=%s", 
   590 						desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
   591 			// don't try to attach again later
   592 			action=PA_NONE;
   593 			RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
   594 		}
   595 	}
   596 
   597 	// attach plugin; get function tables
   598 	if(attach(now) != mTRUE) {
   599 		META_ERROR("dll: Failed to attach plugin '%s'", desc);
   600 		// Note we don't dlclose() here, since we're returning PL_FAILED,
   601 		// which implies that it's been dlopened and queried successfully.
   602 		// Doing so causes crashes, because things like "meta list" try to
   603 		// look at *info, which is in the DLL memory space and unaccessible
   604 		// (segfault) after dlclosed.
   605 		status=PL_FAILED;
   606 		// meta_errno should be already set in attach()
   607 		return(mFALSE);
   608 	}
   609 	status=PL_RUNNING;
   610 	action=PA_NONE;
   611 
   612 	// If not loading at server startup, then need to call plugin's
   613 	// GameInit, since we've passed that.
   614 	if(now != PT_STARTUP) {
   615 		FN_GAMEINIT pfn_gameinit=NULL;
   616 		if(dllapi_table && (pfn_gameinit=dllapi_table->pfnGameInit))
   617 			pfn_gameinit();
   618 	}
   619 	// If loading during map, then I'd like to call plugin's
   620 	// ServerActivate, since we've passed that.  However, I'm not sure what
   621 	// arguments to give it...  So, we'll just have to say for the
   622 	// moment that plugins that are loadable during a map can't need to
   623 	// hook ServerActivate.
   624 
   625 	META_LOG("dll: Loaded plugin '%s': %s v%s %s, %s", desc, info->name, 
   626 			info->version, info->date, info->author);
   627 	return(mTRUE);
   628 }
   629 
   630 // Query a plugin:
   631 //  - dlopen() the file, store the handle
   632 //  - dlsym() and call:
   633 //	    Meta_Init (if present) - tell dll it'll be used as a metamod plugin
   634 //	    GiveFnptrsToDll - give engine function ptrs 
   635 //	    Meta_Query - say "hi" and get info about plugin
   636 // meta_errno values:
   637 //  - ME_DLOPEN		dlopen/loadlibrary failed; see dlerror() for details
   638 //  - ME_DLMISSING	couldn't find a query() or giveFuncs() in plugin
   639 //  - ME_DLERROR	plugin query() returned error
   640 //  - ME_NULLDATA	info struct from query() was null
   641 mBOOL MPlugin::query(void) {
   642 	META_INIT_FN pfn_init;
   643 	GIVE_ENGINE_FUNCTIONS_FN pfn_give_engfuncs;
   644 	META_QUERY_FN pfn_query;
   645 
   646 	// open the plugin DLL
   647 	if(!(handle=DLOPEN(pathname))) {
   648 		META_ERROR("dll: Failed query plugin '%s'; Couldn't open file '%s': %s",
   649 				desc, pathname, DLERROR());
   650 		RETURN_ERRNO(mFALSE, ME_DLOPEN);
   651 	}
   652 
   653 	// First, we check to see if they have a Meta_Query.  We would normally
   654 	// dlsym this just prior to calling it, after having called
   655 	// GiveFnptrsToDll, but things like standalone-DLL bots do all their
   656 	// startup in GiveFnptrsToDll, and trying to load them as metamod
   657 	// plugins creates all sorts of crashes.  So, we do a trivial check
   658 	// first to see if the DLL looks like a metamod plugin before
   659 	// proceeding with the normal order.  Note that we still have to call 
   660 	// GiveFnptrsToDll before Meta_Query, because the latter typically uses 
   661 	// engine functions like AlertMessage, which have to be passed along via 
   662 	// GiveFnptrsToDll.
   663 	pfn_query = (META_QUERY_FN) DLSYM(handle, "Meta_Query");
   664 	if(!pfn_query) {
   665 		META_ERROR("dll: Failed query plugin '%s'; Couldn't find Meta_Query(): %s", desc, DLERROR());
   666 		// caller will dlclose()
   667 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
   668 	}
   669 
   670 	// Call Meta_Init, if present.  This is an optional plugin routine to
   671 	// allow plugin to do any special initializing or other processing
   672 	// prior to the standard query/attach procedure.  
   673 	//
   674 	// In particular, this should allow for DLL's that can operate as both
   675 	// a standalone dll AND a metamod plugin.  This routine has to be
   676 	// called _before_ GiveFnptrsToDll, since the dll will usually do all
   677 	// its startup processing in GiveFn, and has to know at that point
   678 	// whether it needs to do just mm plugin startup, or all the extra
   679 	// startup needed for a standalone DLL.
   680 	//
   681 	// This passes nothing and returns nothing, and the routine in the
   682 	// plugin can NOT use any Engine functions, as they haven't been
   683 	// provided yet (done next, in GiveFnptrsToDll).
   684 	pfn_init = (META_INIT_FN) DLSYM(handle, "Meta_Init");
   685 	if(pfn_init) {
   686 		pfn_init();
   687 		META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Init()", desc));
   688 	}
   689 	else {
   690 		META_DEBUG(5, ("dll: no Meta_Init present in plugin '%s'", desc));
   691 		// don't return; not an error
   692 	}
   693 	
   694 	// pass on engine function table and globals to plugin
   695 	if(!(pfn_give_engfuncs = (GIVE_ENGINE_FUNCTIONS_FN) DLSYM(handle, "GiveFnptrsToDll"))) {
   696 		// META_ERROR("dll: Couldn't find GiveFnptrsToDll() in plugin '%s': %s", desc, DLERROR());
   697 		META_ERROR("dll: Failed query plugin '%s'; Couldn't find GiveFnptrsToDll(): %s", desc, DLERROR());
   698 		// caller will dlclose()
   699 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
   700 	}
   701 	pfn_give_engfuncs(Engine.pl_funcs, Engine.globals);
   702 	META_DEBUG(6, ("dll: Plugin '%s': Called GiveFnptrsToDll()", desc));
   703 
   704 	// Call plugin's Meta_Query(), to pass our meta interface version, and get
   705 	// plugin's info structure.
   706 	meta_errno=ME_NOERROR;
   707 	info=NULL;
   708 	// Make a copy of the meta_util function table for each plugin, for the
   709 	// same reason.
   710 	memcpy(&mutil_funcs, &MetaUtilFunctions, sizeof(mutil_funcs));
   711 
   712 	if(pfn_query(META_INTERFACE_VERSION, &info, &mutil_funcs) != TRUE) {
   713 		META_ERROR("dll: Failed query plugin '%s'; Meta_Query returned error", 
   714 				desc);
   715 		meta_errno=ME_DLERROR;
   716 	}
   717 	else {
   718 		META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Query() successfully", 
   719 					desc));
   720 	}
   721 
   722 	// Check for interface differences...  Generally, a difference in major
   723 	// version will be incompatible, and a plugin that expects a later
   724 	// minor version will be incompatible (it's expecting things that this
   725 	// Metamod won't be supplying).  Plugins that use an older minor
   726 	// version will still work, as backward-compability within major
   727 	// version is expected (forward-compatibility is not).
   728 	//
   729 	// Note, this check is done regardless of whether meta_query returns an
   730 	// error.
   731 	if(info && !FStrEq(info->ifvers, META_INTERFACE_VERSION)) {
   732 		int mmajor=0, mminor=0, pmajor=0, pminor=0;
   733 		META_DEBUG(3, ("dll: Note: Plugin '%s' interface version didn't match; expected %s, found %s", desc, META_INTERFACE_VERSION, info->ifvers));
   734 		sscanf(META_INTERFACE_VERSION, "%d:%d", &mmajor, &mminor);
   735 		sscanf(info->ifvers, "%d:%d", &pmajor, &pminor);
   736 		// If plugin has later interface version, it's incompatible 
   737 		// (update metamod).
   738 		if(pmajor > mmajor || (pmajor==mmajor && pminor > mminor)) {
   739 			META_ERROR("dll: Plugin '%s' requires a newer version of Metamod (Metamod needs at least interface %s not the current %s)", desc, info->ifvers, META_INTERFACE_VERSION);
   740 			meta_errno=ME_IFVERSION;
   741 		}
   742 		// If plugin has older major interface version, it's incompatible
   743 		// (update plugin).
   744 		else if(pmajor < mmajor) {
   745 			META_ERROR("dll: Plugin '%s' is out of date and incompatible with this version of Metamod; please find a newer version of the plugin (plugin needs at least interface %s not the current %s)", desc, META_INTERFACE_VERSION, info->ifvers);
   746 			meta_errno=ME_IFVERSION;
   747 		}
   748 		// Plugin has identical major, with older minor.  This is supposed to be
   749 		// backwards compatible, so we warn, but we still accept it.
   750 		else if(pmajor==mmajor && pminor < mminor)
   751 			META_LOG("dll: Note: plugin '%s' is using an older interface version (%s), not the latest interface version (%s); there might be an updated version of the plugin", desc, info->ifvers, META_INTERFACE_VERSION);
   752 		else
   753 			META_LOG("dll: Plugin '%s': unexpected version comparision; metavers=%s, mmajor=%d, mminor=%d; plugvers=%s, pmajor=%d, pminor=%d", 
   754 					desc, META_INTERFACE_VERSION, mmajor, mminor, info->ifvers, pmajor, pminor);
   755 	}
   756 
   757 	if(meta_errno == ME_IFVERSION) {
   758 		META_ERROR("dll: Rejected plugin '%s' due to interface version incompatibility (mm=%s, pl=%s)", desc, META_INTERFACE_VERSION, info->ifvers);
   759 		// meta_errno is set already above
   760 		// caller will dlclose()
   761 		return(mFALSE);
   762 	}
   763 	else if(meta_errno != ME_NOERROR)
   764 		// some other error, already logged
   765 		return(mFALSE);
   766 
   767 	if(!info) {
   768 		META_ERROR("dll: Failed query plugin '%s'; Empty info structure", desc);
   769 		// caller will dlclose()
   770 		RETURN_ERRNO(mFALSE, ME_NULLRESULT);
   771 	}
   772 	// Replace temporary desc with plugin's internal name.
   773 	if(desc[0] == '<')
   774 		STRNCPY(desc, info->name, sizeof(desc));
   775 	META_DEBUG(6, ("dll: Plugin '%s': Query successful", desc));
   776 	return(mTRUE);
   777 }
   778 
   779 // Attach a plugin:
   780 //	- dlsym() and call:
   781 //	    Meta_Attach - get table of api tables, give meta_globals
   782 //  - if provided by plugin, call various "Get" function pointers, 
   783 //    and store resulting function tables:
   784 //		GetEntityAPI			(std)
   785 //		GetEntityAPI2			(std sdk2)
   786 //		GetNewDLLFunctions		(std sdk2)
   787 //
   788 //		GetEntityAPI_Post		(meta)
   789 //		GetEntityAPI2_Post		(meta)
   790 //		GetNewDLLFunctions_Post	(meta)
   791 //
   792 //		GetEngineFunctions		(meta)
   793 //		GetEngineFunctions_Post	(meta)
   794 // meta_errno values:
   795 //  - ME_DLMISSING	couldn't find meta_attach() in plugin
   796 //  - ME_DLERROR	plugin attach() returned error
   797 //  - ME_NOMEM		failed malloc
   798 mBOOL MPlugin::attach(PLUG_LOADTIME now) {
   799 	int ret;
   800 	int iface_vers;
   801 
   802 	META_ATTACH_FN pfn_attach;
   803 	META_FUNCTIONS meta_table;
   804 
   805 	// Make copy of gameDLL's function tables for each plugin, so we don't
   806 	// risk the plugins screwing with the tables everyone uses.
   807 	if(GameDLL.funcs.dllapi_table && !gamedll_funcs.dllapi_table) {
   808 		gamedll_funcs.dllapi_table = (DLL_FUNCTIONS *) calloc(1, sizeof(DLL_FUNCTIONS));
   809 		if(!gamedll_funcs.dllapi_table) {
   810 			META_ERROR("dll: Failed attach plugin '%s': Failed malloc() for dllapi_table");
   811 			RETURN_ERRNO(mFALSE, ME_NOMEM);
   812 		}
   813 		memcpy(gamedll_funcs.dllapi_table, GameDLL.funcs.dllapi_table, 
   814 				sizeof(DLL_FUNCTIONS));
   815 	}
   816 	if(GameDLL.funcs.newapi_table && !gamedll_funcs.newapi_table) {
   817 		gamedll_funcs.newapi_table = (NEW_DLL_FUNCTIONS *) malloc(sizeof(NEW_DLL_FUNCTIONS));
   818 		if(!gamedll_funcs.newapi_table) {
   819 			META_ERROR("dll: Failed attach plugin '%s': Failed malloc() for newapi_table");
   820 			RETURN_ERRNO(mFALSE, ME_NOMEM);
   821 		}
   822 		memcpy(gamedll_funcs.newapi_table, GameDLL.funcs.newapi_table, 
   823 				sizeof(NEW_DLL_FUNCTIONS));
   824 	}
   825 	if(!(pfn_attach = (META_ATTACH_FN) DLSYM(handle, "Meta_Attach"))) {
   826 		META_ERROR("dll: Failed attach plugin '%s': Couldn't find Meta_Attach(): %s", desc, DLERROR());
   827 		// caller will dlclose()
   828 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
   829 	}
   830 
   831 	memset(&meta_table, 0, sizeof(meta_table));
   832 	// get table of function tables,
   833 	// give public meta globals
   834 	ret=pfn_attach(now, &meta_table, &PublicMetaGlobals, &gamedll_funcs);
   835 	if(ret != TRUE) {
   836 		META_ERROR("dll: Failed attach plugin '%s': Error from Meta_Attach(): %d", desc, ret);
   837 		// caller will dlclose()
   838 		RETURN_ERRNO(mFALSE, ME_DLERROR);
   839 	}
   840 	META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Attach() successfully", desc));
   841 
   842 	// Rather than duplicate code, we use another ugly macro.  Again,
   843 	// a function isn't an option since we have varying types.
   844 #define GET_FUNC_TABLE_FROM_PLUGIN(pfnGetFuncs, STR_GetFuncs, struct_field, API_TYPE, TABLE_TYPE, vers_pass, vers_int, vers_want) \
   845 	if(meta_table.pfnGetFuncs) { \
   846 		if (!struct_field) \
   847 			struct_field = (TABLE_TYPE*) calloc(1, sizeof(TABLE_TYPE)); \
   848 		if(meta_table.pfnGetFuncs(struct_field, vers_pass)) { \
   849 			META_DEBUG(3, ("dll: Plugin '%s': Found %s", desc, STR_GetFuncs)); \
   850 		} \
   851 		else { \
   852 			META_ERROR("dll: Failure calling %s in plugin '%s'", STR_GetFuncs, desc); \
   853 			if(vers_int != vers_want) \
   854 				META_ERROR("dll: Interface version didn't match; expected %d, found %d", vers_want, vers_int); \
   855 		} \
   856 	} \
   857 	else { \
   858 		META_DEBUG(5, ("dll: Plugin '%s': No %s", desc, STR_GetFuncs)); \
   859 		if (struct_field) \
   860 			free(struct_field); \
   861 		struct_field=NULL; \
   862 	}
   863 
   864 	// Look for API-NEW interface in plugin.  We do this before API2/API, because
   865 	// that's what the engine appears to do..
   866 	// But we only do this if the gamedll provides these, so that we don't
   867 	// give a plugin the idea that we'll call them, when in fact we won't
   868 	// (since we don't export them to the engine when the gamedll doesn't
   869 	// provide them).
   870 	if(GameDLL.funcs.newapi_table) {
   871 		iface_vers=NEW_DLL_FUNCTIONS_VERSION;
   872 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetNewDLLFunctions, 
   873 				"GetNewDLLFunctions", newapi_table, 
   874 				NEW_DLL_FUNCTIONS_FN, NEW_DLL_FUNCTIONS,
   875 				&iface_vers, iface_vers, NEW_DLL_FUNCTIONS_VERSION);
   876 		iface_vers=NEW_DLL_FUNCTIONS_VERSION;
   877 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetNewDLLFunctions_Post, 
   878 				"GetNewDLLFunctions_Post", newapi_post_table, 
   879 				NEW_DLL_FUNCTIONS_FN, NEW_DLL_FUNCTIONS,
   880 				&iface_vers, iface_vers, NEW_DLL_FUNCTIONS_VERSION);
   881 	}
   882 
   883 	// Look for API2 interface in plugin; preferred over API-1.
   884 	iface_vers=INTERFACE_VERSION;
   885 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI2, 
   886 			"GetEntityAPI2", dllapi_table, 
   887 			APIFUNCTION2, DLL_FUNCTIONS,
   888 			&iface_vers, iface_vers, INTERFACE_VERSION);
   889 	iface_vers=INTERFACE_VERSION;
   890 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI2_Post, 
   891 			"GetEntityAPI2_Post", dllapi_post_table, 
   892 			APIFUNCTION2, DLL_FUNCTIONS,
   893 			&iface_vers, iface_vers, INTERFACE_VERSION);
   894 
   895 	// Look for old-style API in plugin, if API2 interface wasn't found.
   896 	if(!dllapi_table && !dllapi_post_table) {
   897 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI, 
   898 				"GetEntityAPI", dllapi_table, 
   899 				APIFUNCTION, DLL_FUNCTIONS,
   900 				INTERFACE_VERSION, INTERFACE_VERSION, INTERFACE_VERSION);
   901 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI_Post, 
   902 				"GetEntityAPI_Post", dllapi_post_table, 
   903 				APIFUNCTION, DLL_FUNCTIONS,
   904 				INTERFACE_VERSION, INTERFACE_VERSION, INTERFACE_VERSION);
   905 	}
   906 
   907 	// Look for Engine interface.
   908 	iface_vers=ENGINE_INTERFACE_VERSION;
   909 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEngineFunctions, 
   910 			"GetEngineFunctions", engine_table, 
   911 			GET_ENGINE_FUNCTIONS_FN, enginefuncs_t,
   912 			&iface_vers, iface_vers, ENGINE_INTERFACE_VERSION);
   913 	iface_vers=ENGINE_INTERFACE_VERSION;
   914 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEngineFunctions_Post, 
   915 			"GetEngineFunctions_Post", engine_post_table, 
   916 			GET_ENGINE_FUNCTIONS_FN, enginefuncs_t,
   917 			&iface_vers, iface_vers, ENGINE_INTERFACE_VERSION);
   918 
   919 	if(!dllapi_table && !dllapi_post_table 
   920 		&& !newapi_table && !newapi_post_table
   921 		&& !engine_table && !engine_post_table)
   922 	{
   923 		META_LOG("dll: Plugin '%s' isn't catching _any_ functions ??", desc);
   924 	}
   925 
   926 	time_loaded=time(NULL);
   927 	return(mTRUE);
   928 }
   929 
   930 // Unload a plugin.  Check time, detach.
   931 // meta_errno values:
   932 //  - ME_ARGUMENT	missing necessary fields in plugin
   933 //  - ME_ALREADY	this plugin already unloaded
   934 //  - ME_BADREQ		plugin not marked for unload
   935 //  - ME_DELAYED	unload request is delayed (till changelevel?)
   936 //  - ME_NOTALLOWED	plugin not unloadable after startup
   937 //  - errno's from check_input()
   938 mBOOL MPlugin::unload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason, PL_UNLOAD_REASON real_reason) {
   939 	if(!check_input()) {
   940 		// details logged, meta_errno set in check_input()
   941 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   942 	}
   943 	if(status < PL_RUNNING) {
   944 		META_ERROR("dll: Not unloading plugin '%s'; already unloaded (status=%s)", desc, str_status());
   945 		RETURN_ERRNO(mFALSE, ME_ALREADY);
   946 	}
   947 	if(action != PA_UNLOAD && action != PA_RELOAD) {
   948 		META_ERROR("dll: Not unloading plugin '%s'; not marked for unload (action=%s)", desc, str_action());
   949 		RETURN_ERRNO(mFALSE, ME_BADREQ);
   950 	}
   951 
   952 	// Are we allowed to detach this plugin at this time?
   953 	// If forcing unload, we disregard when plugin wants to be unloaded.
   954 	if(info->unloadable < now) {
   955 		if(reason == PNL_CMD_FORCED) {
   956 			META_DEBUG(2, ("dll: Forced unload plugin '%s' overriding allowed times: allowed=%s; now=%s", desc, str_unloadable(), str_loadtime(now, SL_SIMPLE)));
   957 		}
   958 		else {
   959 			if(info->unloadable > PT_STARTUP) {
   960 				META_DEBUG(2, ("dll: Delaying unload plugin '%s'; can't detach now: allowed=%s; now=%s", desc, str_unloadable(), str_loadtime(now, SL_SIMPLE)));
   961 				// caller should give message to user
   962 				// try to unload again at next opportunity
   963 				RETURN_ERRNO(mFALSE, ME_DELAYED);
   964 			}
   965 			else {
   966 				META_DEBUG(2, ("dll: Failed unload plugin '%s'; can't detach now: allowed=%s; now=%s", desc, str_unloadable(), str_loadtime(now, SL_SIMPLE)));
   967 				// don't try to unload again later
   968 				action=PA_NONE;
   969 				RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
   970 			}
   971 		}
   972 	}
   973 
   974 	// If unloading during map, then I'd like to call plugin's
   975 	// ServerDeactivate.  However, I don't want to do this until I start
   976 	// calling ServerActivate when loading during map, since the SDK
   977 	// indicates these two routines should match call for call.
   978 
   979 	// detach plugin
   980 	if(!detach(now, reason)) {
   981 		if(reason == PNL_CMD_FORCED) {
   982 			META_DEBUG(2, ("dll: Forced unload plugin '%s' overriding failed detach"));
   983 		}
   984 		else {
   985 			META_ERROR("dll: Failed to detach plugin '%s'; ", desc);
   986 			// meta_errno should be already set in detach()
   987 			return(mFALSE);
   988 		}
   989 	}
   990 
   991 	// successful detach, or forced unload
   992 
   993 	// Unmark registered commands for this plugin (by index number).
   994 	RegCmds->disable(index);
   995 	// Unmark registered cvars for this plugin (by index number).
   996 	RegCvars->disable(index);
   997 
   998 #ifdef UNFINISHED
   999 	// Remove all requested hooks from this plugin (by index number).
  1000 	Hooks->remove_all(info);
  1001 #endif /* UNFINISHED */
  1002 
  1003 	// Close the file.  Note: after this, attempts to reference any memory
  1004 	// locations in the file will produce a segfault.
  1005 	if(DLCLOSE(handle) != 0) {
  1006 		META_ERROR("dll: Couldn't close plugin file '%s': %s", file, DLERROR());
  1007 		status=PL_FAILED;
  1008 		RETURN_ERRNO(mFALSE, ME_DLERROR);
  1009 	}
  1010 	handle=NULL;
  1011 
  1012 	if(action==PA_UNLOAD) {
  1013 		status=PL_EMPTY;
  1014 		clear();
  1015 	}
  1016 	else if(action==PA_RELOAD) {
  1017 		status=PL_VALID;
  1018 		action=PA_LOAD;
  1019 		clear();
  1020 	}
  1021 	META_LOG("dll: Unloaded plugin '%s' for reason '%s'", desc, str_reason(reason, real_reason));
  1022 	return(mTRUE);
  1023 }
  1024 
  1025 // Inform plugin we're going to unload it.
  1026 // meta_errno values:
  1027 //  - ME_DLMISSING	couldn't find meta_detach() in plugin
  1028 //  - ME_DLERROR	plugin detach() returned error
  1029 mBOOL MPlugin::detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) {
  1030 	int ret;
  1031 	META_DETACH_FN pfn_detach;
  1032 
  1033 	if(!(pfn_detach = (META_DETACH_FN) DLSYM(handle, "Meta_Detach"))) {
  1034 		META_ERROR("dll: Error detach plugin '%s': Couldn't find Meta_detach(): %s", desc, DLERROR());
  1035 		// caller will dlclose()
  1036 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
  1037 	}
  1038 
  1039 	ret=pfn_detach(now, reason);
  1040 	if(ret != TRUE) {
  1041 		META_ERROR("dll: Failed detach plugin '%s': Error from Meta_Detach(): %d", desc, ret);
  1042 		RETURN_ERRNO(mFALSE, ME_DLERROR);
  1043 	}
  1044 	META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Detach() successfully", desc));
  1045 	return(mTRUE);
  1046 }
  1047 
  1048 // Reload a plugin; unload and load again.
  1049 // meta_errno values:
  1050 //  - ME_NOTALLOWED	plugin not loadable after startup
  1051 //  - errno's from check_input()
  1052 //  - errno's from unload()
  1053 //  - errno's from load()
  1054 mBOOL MPlugin::reload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) {
  1055 	if(!check_input()) {
  1056 		// details logged, meta_errno set in check_input()
  1057 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
  1058 	}
  1059 	// Are we allowed to load this plugin at this time?
  1060 	// If we cannot load the plugin after unloading it, we keep it.
  1061 	if (info && info->loadable < now)
  1062 	{
  1063 		if(info->loadable > PT_STARTUP) {
  1064 			META_DEBUG(2, ("dll: Delaying reload plugin '%s'; would not be able to reattach now: allowed=%s; now=%s", desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
  1065 			// caller should give message to user
  1066 			// try to reload again at next opportunity
  1067 			RETURN_ERRNO(mFALSE, ME_DELAYED);
  1068 		}
  1069 		else {
  1070 			META_DEBUG(2, ("dll: Failed reload plugin '%s'; would not be able to reattach now: allowed=%s; now=%s", desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
  1071 			// don't try to reload again later
  1072 			action=PA_NONE;
  1073 			RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
  1074 		}
  1075 	}
  1076 
  1077 	if(status>=PL_RUNNING && !unload(now, reason, PNL_PLG_FORCED)) {
  1078 		META_ERROR("dll: Failed to unload plugin '%s' for reloading", desc);
  1079 		// meta_errno should be set already in unload()
  1080 		return(mFALSE);
  1081 	}
  1082 	if(!load(now)) {
  1083 		META_ERROR("dll: Failed to reload plugin '%s' after unloading", desc);
  1084 		// meta_errno should be set already in load()
  1085 		return(mFALSE);
  1086 	}
  1087 	return(mTRUE);
  1088 }
  1089 
  1090 // Pause a plugin; temporarily disabled for API routines.
  1091 // meta_errno values:
  1092 //  - ME_ALREADY	this plugin already paused
  1093 //  - ME_BADREQ		can't pause; not running
  1094 //  - ME_NOTALLOWED	plugin doesn't want to be paused
  1095 mBOOL MPlugin::pause(void) {
  1096 	if(status == PL_PAUSED) {
  1097 		META_ERROR("Not pausing plugin '%s'; already paused", desc);
  1098 		RETURN_ERRNO(mFALSE, ME_ALREADY);
  1099 	}
  1100 	if(status != PL_RUNNING) {
  1101 		META_ERROR("Cannot pause plugin '%s'; not currently running (status=%s)", desc, str_status());
  1102 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1103 	}
  1104 
  1105 	// are we allowed to pause this plugin?
  1106 	if(info->unloadable < PT_ANYPAUSE) {
  1107 		META_ERROR("Cannot pause plugin '%s'; not allowed by plugin (allowed=%s)", desc, str_unloadable());
  1108 		action=PA_NONE;
  1109 		RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
  1110 	}
  1111 
  1112 	status=PL_PAUSED;
  1113 	META_LOG("Paused plugin '%s'", desc);
  1114 	return(mTRUE);
  1115 }
  1116 
  1117 // Unpause a plugin.
  1118 // meta_errno values:
  1119 //  - ME_BADREQ		can't unpause; not paused
  1120 mBOOL MPlugin::unpause(void) {
  1121 	if(status != PL_PAUSED) {
  1122 		META_ERROR("Cannot unpause plugin '%s'; not currently paused (status=%s)", desc, str_status());
  1123 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1124 	}
  1125 	status=PL_RUNNING;
  1126 	META_LOG("Unpaused plugin '%s'", desc);
  1127 	return(mTRUE);
  1128 }
  1129 
  1130 // Retry pending action, presumably from a previous failure.
  1131 // meta_errno values:
  1132 //  - ME_BADREQ		no pending action
  1133 //  - errno's from load()
  1134 //  - errno's from unload()
  1135 //  - errno's from reload()
  1136 mBOOL MPlugin::retry(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) {
  1137 	if(action==PA_LOAD)
  1138 		return(load(now));
  1139 	else if(action==PA_ATTACH)
  1140 		return(load(now));
  1141 	else if(action==PA_UNLOAD)
  1142 		return(unload(now, reason, reason));
  1143 	else if(action==PA_RELOAD)
  1144 		return(reload(now, reason));
  1145 	else {
  1146 		META_ERROR("No pending action to retry for plugin '%s'; (status=%s, action=%s)", desc, str_status(), str_action());
  1147 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1148 	}
  1149 }
  1150 
  1151 // Clear a plugin (it failed a previous action and should be
  1152 // removed from the list, or it's being unloaded).
  1153 // meta_errno values:
  1154 //  - ME_BADREQ		not marked for clearing
  1155 //  - ME_DLERROR	failed to dlclose
  1156 mBOOL MPlugin::clear(void) {
  1157 	if(status != PL_FAILED && status != PL_BADFILE
  1158 			&& status != PL_EMPTY && status != PL_OPENED) {
  1159 		META_ERROR("Cannot clear plugin '%s'; not marked as failed, empty, or open (status=%s)", desc, str_status());
  1160 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1161 	}
  1162 	// If file is open, close the file.  Note: after this, attempts to
  1163 	// reference any memory locations in the file will produce a segfault.
  1164 	if(handle && DLCLOSE(handle) != 0) {
  1165 		META_ERROR("dll: Couldn't close plugin file '%s': %s", file, DLERROR());
  1166 		status=PL_FAILED;
  1167 		RETURN_ERRNO(mFALSE, ME_DLERROR);
  1168 	}
  1169 	handle=NULL;
  1170 
  1171 	if(gamedll_funcs.dllapi_table) free(gamedll_funcs.dllapi_table);
  1172 	if(gamedll_funcs.newapi_table) free(gamedll_funcs.newapi_table);
  1173 	if(dllapi_table) free(dllapi_table);
  1174 	if(dllapi_post_table) free(dllapi_post_table);
  1175 	if(newapi_table) free(newapi_table);
  1176 	if(newapi_post_table) free(newapi_post_table);
  1177 	if(engine_table) free(engine_table);
  1178 	if(engine_post_table) free(engine_post_table);
  1179 
  1180 	status=PL_EMPTY;
  1181 	action=PA_NULL;
  1182 	handle=NULL;
  1183 	info=NULL;
  1184 	time_loaded=0;
  1185 	dllapi_table=NULL;
  1186 	dllapi_post_table=NULL;
  1187 	newapi_table=NULL;
  1188 	newapi_post_table=NULL;
  1189 	engine_table=NULL;
  1190 	engine_post_table=NULL;
  1191 	gamedll_funcs.dllapi_table = NULL;
  1192 	gamedll_funcs.newapi_table = NULL;
  1193 	return(mTRUE);
  1194 }
  1195 
  1196 // List information about plugin to console.
  1197 void MPlugin::show(void) {
  1198 	char *cp, *tstr;
  1199 	int n, width;
  1200 	width=13;
  1201 	META_CONS("%*s: %s", width, "name", info ? info->name : "(nil)");
  1202 	META_CONS("%*s: %s", width, "desc", desc);
  1203 	META_CONS("%*s: %s", width, "status", str_status());
  1204 	META_CONS("%*s: %s", width, "action", str_action());
  1205 	META_CONS("%*s: %s", width, "filename", filename);
  1206 	META_CONS("%*s: %s", width, "file", file);
  1207 	META_CONS("%*s: %s", width, "pathname", pathname);
  1208 	META_CONS("%*s: %d", width, "index", index);
  1209 	META_CONS("%*s: %s", width, "source", str_source());
  1210 	META_CONS("%*s: %s", width, "loadable", str_loadable(SL_ALLOWED));
  1211 	META_CONS("%*s: %s", width, "unloadable", str_unloadable(SL_ALLOWED));
  1212 	META_CONS("%*s: %s", width, "version", info ? info->version : "(nil)");
  1213 	META_CONS("%*s: %s", width, "date", info ? info->date : "(nil)");
  1214 	META_CONS("%*s: %s", width, "author", info ? info->author : "(nil)");
  1215 	META_CONS("%*s: %s", width, "url", info ? info->url : "(nil)");
  1216 	META_CONS("%*s: %s", width, "logtag", info ? info->logtag : "(nil)");
  1217 	META_CONS("%*s: %s", width, "ifvers", info ? info->ifvers : "(nil)");
  1218 	// ctime() includes newline at EOL
  1219 	tstr=ctime(&time_loaded);
  1220 	if((cp=strchr(tstr, '\n')))
  1221 		*cp='\0';
  1222 	META_CONS("%*s: %s", width, "last loaded", tstr);
  1223 	// XXX show file time ?
  1224 
  1225 	if(dllapi_table) {
  1226 		META_CONS("DLLAPI functions:");
  1227 		SHOW_DEF_DLLAPI(dllapi_table, "   ", "");
  1228 		META_CONS("%d functions (dllapi)", n);
  1229 	}
  1230 	else
  1231 		META_CONS("No DLLAPI functions.");
  1232 	if(dllapi_post_table) {
  1233 		META_CONS("DLLAPI-Post functions:");
  1234 		SHOW_DEF_DLLAPI(dllapi_post_table, "   ", "_Post");
  1235 		META_CONS("%d functions (dllapi post)", n);
  1236 	}
  1237 	else
  1238 		META_CONS("No DLLAPI-Post functions.");
  1239 
  1240 	if(newapi_table) {
  1241 		META_CONS("NEWAPI functions:");
  1242 		SHOW_DEF_NEWAPI(newapi_table, "   ", "");
  1243 		META_CONS("%d functions (newapi)", n);
  1244 	}
  1245 	else
  1246 		META_CONS("No NEWAPI functions.");
  1247 	if(newapi_post_table) {
  1248 		META_CONS("NEWAPI-Post functions:");
  1249 		SHOW_DEF_NEWAPI(newapi_post_table, "   ", "_Post");
  1250 		META_CONS("%d functions (newapi post)", n);
  1251 	}
  1252 	else
  1253 		META_CONS("No NEWAPI-Post functions.");
  1254 
  1255 	if(engine_table) {
  1256 		META_CONS("Engine functions:");
  1257 		SHOW_DEF_ENGINE(engine_table, "   ", "");
  1258 		META_CONS("%d functions (engine)", n);
  1259 	}
  1260 	else
  1261 		META_CONS("No Engine functions.");
  1262 	if(engine_post_table) {
  1263 		META_CONS("Engine-Post functions:");
  1264 		SHOW_DEF_ENGINE(engine_post_table, "   ", "_Post");
  1265 		META_CONS("%d functions (engine post)", n);
  1266 	}
  1267 	else
  1268 		META_CONS("No Engine-Post functions.");
  1269 	RegCmds->show(index);
  1270 	RegCvars->show(index);
  1271 }
  1272 
  1273 // Check whether the file on disk looks like it's been updated since we
  1274 // last loaded the plugin.
  1275 // meta_errno values:
  1276 //  - ME_NOFILE		couldn't find file
  1277 //  - ME_NOERROR	no error; false indicates file not newer
  1278 mBOOL MPlugin::newer_file(void) {
  1279 	struct stat st;
  1280 	time_t file_time;
  1281 
  1282 	if(stat(pathname, &st) != 0)
  1283 		RETURN_ERRNO(mFALSE, ME_NOFILE);
  1284 	file_time=max(st.st_ctime, st.st_mtime);
  1285 	META_DEBUG(5, ("newer_file? file=%s; load=%d, file=%d; ctime=%d, mtime=%d",
  1286 				file, time_loaded, file_time, st.st_ctime, st.st_mtime));
  1287 	if(file_time > time_loaded)
  1288 		return(mTRUE);
  1289 	else
  1290 		RETURN_ERRNO(mFALSE, ME_NOERROR);
  1291 }
  1292 
  1293 // Return a string describing status of plugin.
  1294 // SIMPLE is the default.
  1295 // SHOW is max 4 chars, for "show" output.
  1296 // meta_errno values:
  1297 //  - none
  1298 char *MPlugin::str_status(STR_STATUS fmt) {
  1299 	switch(status) {
  1300 		case PL_EMPTY:
  1301 			if(fmt==ST_SHOW) return("empt");
  1302 			else return("empty");
  1303 		case PL_VALID:
  1304 			if(fmt==ST_SHOW) return("info");
  1305 			else return("valid");
  1306 		case PL_BADFILE:
  1307 			if(fmt==ST_SHOW) return("badf");
  1308 			else return("badfile");
  1309 		case PL_OPENED:
  1310 			if(fmt==ST_SHOW) return("open");
  1311 			else return("opened");
  1312 		case PL_FAILED:
  1313 			if(fmt==ST_SHOW) return("fail");
  1314 			else return("failed");
  1315 		case PL_RUNNING:
  1316 			if(fmt==ST_SHOW) return("RUN");
  1317 			else return("running");
  1318 		case PL_PAUSED:
  1319 			if(fmt==ST_SHOW) return("PAUS");
  1320 			else return("paused");
  1321 		default:
  1322 			if(fmt==ST_SHOW) return(UTIL_VarArgs("UNK%d", status));
  1323 			return(UTIL_VarArgs("unknown (%d)", status));
  1324 	}
  1325 }
  1326 
  1327 // Return a string (one word) describing requested action for plugin.
  1328 // SIMPLE is the default.
  1329 // SHOW is max 4 chars, for "show" output.
  1330 // meta_errno values:
  1331 //  - none
  1332 char *MPlugin::str_action(STR_ACTION fmt) {
  1333 	switch(action) {
  1334 		case PA_NULL:
  1335 			if(fmt==SA_SHOW) return("NULL");
  1336 			else return("null");
  1337 		case PA_NONE:
  1338 			if(fmt==SA_SHOW) return(" -  ");
  1339 			else return("none");
  1340 		case PA_KEEP:
  1341 			if(fmt==SA_SHOW) return("keep");
  1342 			else return("keep");
  1343 		case PA_LOAD:
  1344 			if(fmt==SA_SHOW) return("load");
  1345 			else return("load");
  1346 		case PA_ATTACH:
  1347 			if(fmt==SA_SHOW) return("atch");
  1348 			else return("attach");
  1349 		case PA_UNLOAD:
  1350 			if(fmt==SA_SHOW) return("unld");
  1351 			else return("unload");
  1352 		case PA_RELOAD:
  1353 			if(fmt==SA_SHOW) return("relo");
  1354 			else return("reload");
  1355 		default:
  1356 			if(fmt==SA_SHOW) return(UTIL_VarArgs("UNK%d", action));
  1357 			else return(UTIL_VarArgs("unknown (%d)", action));
  1358 	}
  1359 }
  1360 
  1361 // Return a string describing given plugin loadtime.
  1362 // SIMPLE is the default.
  1363 // SHOW is max 3 chars, for "show" output.
  1364 // ALLOWED is in terms of when it's allowed to load/unload.
  1365 // NOW is to describe current situation of load/unload attempt.
  1366 // meta_errno values:
  1367 //  - none
  1368 char *MPlugin::str_loadtime(PLUG_LOADTIME ptime, STR_LOADTIME fmt) {
  1369 	switch(ptime) {
  1370 		case PT_NEVER:
  1371 			if(fmt==SL_SHOW) return("Never");
  1372 			else return("never");
  1373 		case PT_STARTUP:
  1374 			if(fmt==SL_SHOW) return("Start");
  1375 			else if(fmt==SL_ALLOWED) return("at server startup");
  1376 			else if(fmt==SL_NOW) return("during server startup");
  1377 			else return("startup");
  1378 		case PT_CHANGELEVEL:
  1379 			if(fmt==SL_SHOW) return("Chlvl");
  1380 			else if(fmt==SL_ALLOWED) return("at changelevel");
  1381 			else if(fmt==SL_NOW) return("during changelevel");
  1382 			else return("changelevel");
  1383 		case PT_ANYTIME:
  1384 			if(fmt==SL_SHOW) return("ANY");
  1385 			else if(fmt==SL_ALLOWED) return("at any time");
  1386 			else if(fmt==SL_NOW) return("during map");
  1387 			else return("anytime");
  1388 		case PT_ANYPAUSE:
  1389 			if(fmt==SL_SHOW) return("Pause");
  1390 			else if(fmt==SL_ALLOWED) return("at any time, and pausable");
  1391 			else if(fmt==SL_NOW) return("for requested pause");
  1392 			else return("pausable");
  1393 		default:
  1394 			if(fmt==SL_SHOW) return(UTIL_VarArgs("UNK-%d", ptime));
  1395 			else return(UTIL_VarArgs("unknown (%d)", ptime));
  1396 	}
  1397 }
  1398 
  1399 // Return a string describing why a plugin is to be unloaded.
  1400 // meta_errno values:
  1401 //  - none
  1402 char *MPlugin::str_reason(PL_UNLOAD_REASON preason, PL_UNLOAD_REASON preal_reason) {
  1403 	char buf[128];
  1404 	
  1405 	if(preason == PNL_PLUGIN)
  1406 		preason = PNL_NULL;
  1407 	if(preason == PNL_PLG_FORCED)
  1408 		preason = PNL_NULL;
  1409 
  1410 	switch(preal_reason) {
  1411 		case PNL_NULL:
  1412 			return("null");
  1413 		case PNL_INI_DELETED:
  1414 			return("deleted from ini file");
  1415 		case PNL_FILE_NEWER:
  1416 			return("file on disk is newer");
  1417 		case PNL_COMMAND:
  1418 			return("server command");
  1419 		case PNL_CMD_FORCED:
  1420 			return("forced by server command");
  1421 		case PNL_PLUGIN:
  1422 			STRNCPY(buf, str_reason(PNL_NULL, preason), sizeof(buf));
  1423 			return(UTIL_VarArgs("%s (request from plugin[%d])", buf, unloader_index));
  1424 		case PNL_PLG_FORCED:
  1425 			STRNCPY(buf, str_reason(PNL_NULL, preason), sizeof(buf));
  1426 			return(UTIL_VarArgs("%s (forced request from plugin[%d])", buf, unloader_index));
  1427 		default:
  1428 			return(UTIL_VarArgs("unknown (%d)", preal_reason));
  1429 	}
  1430 }
  1431 
  1432 // Return a string describing how the plugin was loaded.
  1433 // meta_errno values:
  1434 //  - none
  1435 char *MPlugin::str_source(STR_SOURCE fmt) {
  1436 	switch(source) {
  1437 		case PS_INI:
  1438 			if(fmt==SO_SHOW) return("ini");
  1439 			else return("ini file");
  1440 		case PS_CMD:
  1441 			if(fmt==SO_SHOW) return("cmd");
  1442 			else return("console command");
  1443 		case PS_PLUGIN:
  1444 			if (source_plugin_index <= 0) {
  1445 				if (fmt==SO_SHOW) 
  1446 					return("plUN");
  1447 				else 
  1448 					return("unloaded plugin");
  1449 			} else {
  1450 				if(fmt==SO_SHOW) return(UTIL_VarArgs("pl%d", source_plugin_index));
  1451 				else return(UTIL_VarArgs("plugin [%d]", source_plugin_index));
  1452 			}
  1453 		default:
  1454 			if(fmt==SO_SHOW) return(UTIL_VarArgs("UNK%d", source));
  1455 			else return(UTIL_VarArgs("unknown (%d)", source));
  1456 	}
  1457 }