Fixed typo in Nuclear Dawn gamedata backcompat fix.
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
35 #include "sm_stringutil.h"
36 #include "sm_globals.h"
37 #include "sourcemod.h"
38 #include "LibrarySys.h"
40 #include "ForwardSys.h"
42 #include <sm_trie_tpl.h>
43 #include <sh_memory.h>
44 #include "logic_bridge.h"
46 #if defined PLATFORM_WINDOWS
48 #elif defined PLATFORM_POSIX
51 #include <sys/times.h>
54 HandleType_t g_PlIter;
55 ConVar sm_datetime_format("sm_datetime_format", "%m/%d/%Y - %H:%M:%S", 0, "Default formatting time rules");
56 IForward *g_OnLogAction = NULL;
58 class CoreNativeHelpers :
60 public IHandleTypeDispatch
63 void OnSourceModAllInitialized()
66 handlesys->InitAccessDefaults(NULL, &hacc);
67 hacc.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
69 g_PlIter = handlesys->CreateType("PluginIterator", this, 0, NULL, NULL, g_pCoreIdent, NULL);
71 g_OnLogAction = g_Forwards.CreateForward("OnLogAction",
81 void OnHandleDestroy(HandleType_t type, void *object)
83 IPluginIterator *iter = (IPluginIterator *)object;
86 void OnSourceModShutdown()
88 g_Forwards.ReleaseForward(g_OnLogAction);
89 handlesys->RemoveType(g_PlIter, g_pCoreIdent);
91 } g_CoreNativeHelpers;
93 void LogAction(Handle_t hndl, int type, int client, int target, const char *message)
95 if (g_OnLogAction->GetFunctionCount())
98 g_OnLogAction->PushCell(hndl);
99 g_OnLogAction->PushCell(type);
100 g_OnLogAction->PushCell(client);
101 g_OnLogAction->PushCell(target);
102 g_OnLogAction->PushString(message);
103 g_OnLogAction->Execute(&result);
105 if (result >= (ResultType)Pl_Handled)
111 const char *logtag = "SM";
115 IPlugin *pPlugin = scripts->FindPluginByHandle(hndl, &err);
118 logtag = pPlugin->GetFilename();
122 g_Logger.LogMessage("[%s] %s", logtag, message);
125 static cell_t ThrowError(IPluginContext *pContext, const cell_t *params)
129 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
131 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
133 if (pContext->GetLastNativeError() == SP_ERROR_NONE)
135 pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
141 static cell_t GetTime(IPluginContext *pContext, const cell_t *params)
143 time_t t = GetAdjustedTime();
145 pContext->LocalToPhysAddr(params[1], &addr);
149 return static_cast<cell_t>(t);
152 #if defined SUBPLATFORM_SECURECRT
153 void _ignore_invalid_parameter(
154 const wchar_t * expression,
155 const wchar_t * function,
156 const wchar_t * file,
161 /* Wow we don't care, thanks Microsoft. */
165 static cell_t FormatTime(IPluginContext *pContext, const cell_t *params)
167 char *format, *buffer;
168 pContext->LocalToString(params[1], &buffer);
169 pContext->LocalToStringNULL(params[3], &format);
173 format = const_cast<char *>(sm_datetime_format.GetString());
176 #if defined SUBPLATFORM_SECURECRT
177 _invalid_parameter_handler handler = _set_invalid_parameter_handler(_ignore_invalid_parameter);
180 time_t t = (params[4] == -1) ? GetAdjustedTime() : (time_t)params[4];
181 size_t written = strftime(buffer, params[2], format, localtime(&t));
183 #if defined SUBPLATFORM_SECURECRT
184 _set_invalid_parameter_handler(handler);
187 if (params[2] && format[0] != '\0' && !written)
189 pContext->ThrowNativeError("Invalid time format or buffer too small");
196 static cell_t GetPluginIterator(IPluginContext *pContext, const cell_t *params)
198 IPluginIterator *iter = scripts->GetPluginIterator();
200 Handle_t hndl = handlesys->CreateHandle(g_PlIter, iter, pContext->GetIdentity(), g_pCoreIdent, NULL);
202 if (hndl == BAD_HANDLE)
210 static cell_t MorePlugins(IPluginContext *pContext, const cell_t *params)
212 Handle_t hndl = (Handle_t)params[1];
214 IPluginIterator *pIter;
217 sec.pIdentity = g_pCoreIdent;
218 sec.pOwner = pContext->GetIdentity();
220 if ((err=handlesys->ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
222 return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
225 return pIter->MorePlugins() ? 1 : 0;
228 static cell_t ReadPlugin(IPluginContext *pContext, const cell_t *params)
230 Handle_t hndl = (Handle_t)params[1];
232 IPluginIterator *pIter;
235 sec.pIdentity = g_pCoreIdent;
236 sec.pOwner = pContext->GetIdentity();
238 if ((err=handlesys->ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
240 return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
243 IPlugin *pPlugin = pIter->GetPlugin();
251 return pPlugin->GetMyHandle();
254 IPlugin *GetPluginFromHandle(IPluginContext *pContext, Handle_t hndl)
256 if (hndl == BAD_HANDLE)
258 return scripts->FindPluginByContext(pContext->GetContext());
261 IPlugin *pPlugin = scripts->FindPluginByHandle(hndl, &err);
264 pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
270 static cell_t GetPluginStatus(IPluginContext *pContext, const cell_t *params)
272 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
278 return pPlugin->GetStatus();
281 static cell_t GetPluginFilename(IPluginContext *pContext, const cell_t *params)
283 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
289 pContext->StringToLocalUTF8(params[2], params[3], pPlugin->GetFilename(), NULL);
294 static cell_t IsPluginDebugging(IPluginContext *pContext, const cell_t *params)
296 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
302 return pPlugin->IsDebugging() ? 1 : 0;
305 /* Local to plugins only */
308 PlInfo_Name, /**< Plugin name */
309 PlInfo_Author, /**< Plugin author */
310 PlInfo_Description, /**< Plugin description */
311 PlInfo_Version, /**< Plugin verison */
312 PlInfo_URL, /**< Plugin URL */
315 static cell_t GetPluginInfo(IPluginContext *pContext, const cell_t *params)
317 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
323 const sm_plugininfo_t *info = pPlugin->GetPublicInfo();
330 const char *str = NULL;
332 switch ((PluginInfo)params[2])
344 case PlInfo_Description:
346 str = info->description;
361 if (!str || str[0] == '\0')
366 pContext->StringToLocalUTF8(params[3], params[4], str, NULL);
371 static cell_t SetFailState(IPluginContext *pContext, const cell_t *params)
376 pContext->LocalToString(params[1], &str);
377 pPlugin = scripts->FindPluginByContext(pContext->GetContext());
381 pPlugin->SetErrorState(Plugin_Error, "%s", str);
383 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", str);
389 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
390 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
392 pPlugin->SetErrorState(Plugin_Error, "%s", str);
393 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "Formatting error (%s)", str);
397 pPlugin->SetErrorState(Plugin_Error, "%s", buffer);
398 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
405 static cell_t GetSysTickCount(IPluginContext *pContext, const cell_t *params)
407 #if defined PLATFORM_WINDOWS
408 return (cell_t)GetTickCount();
409 #elif defined PLATFORM_POSIX
411 clock_t ticks = times(&tm);
412 long ticks_per_sec = sysconf(_SC_CLK_TCK);
413 double fticks = (double)ticks / (double)ticks_per_sec;
415 if (fticks > INT_MAX)
417 double r = (int)(fticks / INT_MAX) * (double)INT_MAX;
420 return (cell_t)fticks;
424 static cell_t AutoExecConfig(IPluginContext *pContext, const cell_t *params)
426 SMPlugin *plugin = scripts->FindPluginByContext(pContext->GetContext());
429 pContext->LocalToString(params[2], &cfg);
430 pContext->LocalToString(params[3], &folder);
434 static char temp_str[255];
435 static char temp_file[PLATFORM_MAX_PATH];
438 g_LibSys.GetFileFromPath(temp_str, sizeof(temp_str), plugin->GetFilename());
439 if ((ptr = strstr(temp_str, ".smx")) != NULL)
444 /* We have the raw filename! */
445 UTIL_Format(temp_file, sizeof(temp_file), "plugin.%s", temp_str);
449 plugin->AddConfig(params[1] ? true : false, cfg, folder);
454 static cell_t MarkNativeAsOptional(IPluginContext *pContext, const cell_t *params)
460 pContext->LocalToString(params[1], &name);
461 if (pContext->FindNativeByName(name, &idx) != SP_ERROR_NONE)
463 /* Oops! This HAS to silently fail! */
467 pContext->GetNativeByIndex(idx, &native);
469 native->flags |= SP_NTVFLAG_OPTIONAL;
474 static cell_t RegPluginLibrary(IPluginContext *pContext, const cell_t *params)
477 SMPlugin *pl = scripts->FindPluginByContext(pContext->GetContext());
479 pContext->LocalToString(params[1], &name);
481 pl->AddLibrary(name);
485 static cell_t LibraryExists(IPluginContext *pContext, const cell_t *params)
488 pContext->LocalToString(params[1], &str);
490 if (strcmp(str, "__CanTestFeatures__") == 0)
495 if (scripts->LibraryExists(str))
500 if (extsys->LibraryExists(str))
508 static cell_t sm_LogAction(IPluginContext *pContext, const cell_t *params)
511 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
512 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
514 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
519 IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
521 LogAction(pPlugin->GetMyHandle(), 2, params[1], params[2], buffer);
526 static cell_t LogToFile(IPluginContext *pContext, const cell_t *params)
529 pContext->LocalToString(params[1], &file);
531 char path[PLATFORM_MAX_PATH];
532 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
534 FILE *fp = fopen(path, "at");
537 return pContext->ThrowNativeError("Could not open file \"%s\"", path);
541 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
542 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
544 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
550 IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
552 g_Logger.LogToOpenFile(fp, "[%s] %s", pPlugin->GetFilename(), buffer);
559 static cell_t LogToFileEx(IPluginContext *pContext, const cell_t *params)
562 pContext->LocalToString(params[1], &file);
564 char path[PLATFORM_MAX_PATH];
565 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
567 FILE *fp = fopen(path, "at");
570 return pContext->ThrowNativeError("Could not open file \"%s\"", path);
574 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
575 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
577 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
583 g_Logger.LogToOpenFile(fp, "%s", buffer);
590 static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *params)
593 pContext->LocalToString(params[1], &str);
595 IExtension *pExtension = extsys->FindExtensionByFile(str);
602 if (!pExtension->IsLoaded())
608 pContext->LocalToString(params[2], &error);
609 if (!pExtension->IsRunning(error, params[3]))
617 static cell_t FindPluginByNumber(IPluginContext *pContext, const cell_t *params)
619 IPlugin *pPlugin = scripts->FindPluginByOrder(params[1]);
626 return pPlugin->GetMyHandle();
629 static cell_t VerifyCoreVersion(IPluginContext *pContext, const cell_t *params)
634 static cell_t GetFeatureStatus(IPluginContext *pContext, const cell_t *params)
636 FeatureType type = (FeatureType)params[1];
639 pContext->LocalToString(params[2], &name);
641 return sharesys->TestFeature(pContext->GetRuntime(), type, name);
644 static cell_t RequireFeature(IPluginContext *pContext, const cell_t *params)
646 FeatureType type = (FeatureType)params[1];
649 pContext->LocalToString(params[2], &name);
651 if (sharesys->TestFeature(pContext->GetRuntime(), type, name) != FeatureStatus_Available)
655 char default_message[255];
656 SMPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
658 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
659 if (pContext->GetLastNativeError() != SP_ERROR_NONE || buffer[0] == '\0')
661 UTIL_Format(default_message, sizeof(default_message), "Feature \"%s\" not available", name);
662 msg = default_message;
664 pPlugin->SetErrorState(Plugin_Error, "%s", msg);
665 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", msg);
678 //memory addresses below 0x10000 are automatically considered invalid for dereferencing
679 #define VALID_MINIMUM_MEMORY_ADDRESS 0x10000
681 static cell_t LoadFromAddress(IPluginContext *pContext, const cell_t *params)
683 void *addr = reinterpret_cast<void*>(params[1]);
687 pContext->ThrowNativeError("Address cannot be null");
689 else if (reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
691 pContext->ThrowNativeError("Invalid address 0x%x is pointing to reserved memory.", addr);
693 NumberType size = static_cast<NumberType>(params[2]);
697 case NumberType_Int8:
698 return *reinterpret_cast<uint8_t*>(addr);
699 case NumberType_Int16:
700 return *reinterpret_cast<uint16_t*>(addr);
701 case NumberType_Int32:
702 return *reinterpret_cast<uint32_t*>(addr);
704 pContext->ThrowNativeError("Invalid number types %d", size);
711 static cell_t StoreToAddress(IPluginContext *pContext, const cell_t *params)
713 void *addr = reinterpret_cast<void*>(params[1]);
717 pContext->ThrowNativeError("Address cannot be null");
719 else if (reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
721 pContext->ThrowNativeError("Invalid address 0x%x is pointing to reserved memory.", addr);
723 cell_t data = params[2];
725 NumberType size = static_cast<NumberType>(params[3]);
729 case NumberType_Int8:
730 SourceHook::SetMemAccess(addr, sizeof(uint8_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
731 *reinterpret_cast<uint8_t*>(addr) = data;
733 case NumberType_Int16:
734 SourceHook::SetMemAccess(addr, sizeof(uint16_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
735 *reinterpret_cast<uint16_t*>(addr) = data;
737 case NumberType_Int32:
738 SourceHook::SetMemAccess(addr, sizeof(uint32_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
739 *reinterpret_cast<uint32_t*>(addr) = data;
742 pContext->ThrowNativeError("Invalid number types %d", size);
748 REGISTER_NATIVES(coreNatives)
750 {"AutoExecConfig", AutoExecConfig},
751 {"GetPluginFilename", GetPluginFilename},
752 {"GetPluginInfo", GetPluginInfo},
753 {"GetPluginIterator", GetPluginIterator},
754 {"GetPluginStatus", GetPluginStatus},
755 {"GetSysTickCount", GetSysTickCount},
756 {"GetTime", GetTime},
757 {"IsPluginDebugging", IsPluginDebugging},
758 {"MorePlugins", MorePlugins},
759 {"ReadPlugin", ReadPlugin},
760 {"ThrowError", ThrowError},
761 {"SetFailState", SetFailState},
762 {"FormatTime", FormatTime},
763 {"MarkNativeAsOptional", MarkNativeAsOptional},
764 {"RegPluginLibrary", RegPluginLibrary},
765 {"LibraryExists", LibraryExists},
766 {"LogAction", sm_LogAction},
767 {"LogToFile", LogToFile},
768 {"LogToFileEx", LogToFileEx},
769 {"GetExtensionFileStatus", GetExtensionFileStatus},
770 {"FindPluginByNumber", FindPluginByNumber},
771 {"VerifyCoreVersion", VerifyCoreVersion},
772 {"GetFeatureStatus", GetFeatureStatus},
773 {"RequireFeature", RequireFeature},
774 {"LoadFromAddress", LoadFromAddress},
775 {"StoreToAddress", StoreToAddress},