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 <sh_memory.h>
43 #include "logic_bridge.h"
45 #if defined PLATFORM_WINDOWS
47 #elif defined PLATFORM_POSIX
50 #include <sys/times.h>
53 HandleType_t g_PlIter;
54 ConVar sm_datetime_format("sm_datetime_format", "%m/%d/%Y - %H:%M:%S", 0, "Default formatting time rules");
55 IForward *g_OnLogAction = NULL;
57 class CoreNativeHelpers :
59 public IHandleTypeDispatch
62 void OnSourceModAllInitialized()
65 handlesys->InitAccessDefaults(NULL, &hacc);
66 hacc.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
68 g_PlIter = handlesys->CreateType("PluginIterator", this, 0, NULL, NULL, g_pCoreIdent, NULL);
70 g_OnLogAction = g_Forwards.CreateForward("OnLogAction",
80 void OnHandleDestroy(HandleType_t type, void *object)
82 IPluginIterator *iter = (IPluginIterator *)object;
85 void OnSourceModShutdown()
87 g_Forwards.ReleaseForward(g_OnLogAction);
88 handlesys->RemoveType(g_PlIter, g_pCoreIdent);
90 } g_CoreNativeHelpers;
92 void LogAction(Handle_t hndl, int type, int client, int target, const char *message)
94 if (g_OnLogAction->GetFunctionCount())
97 g_OnLogAction->PushCell(hndl);
98 g_OnLogAction->PushCell(type);
99 g_OnLogAction->PushCell(client);
100 g_OnLogAction->PushCell(target);
101 g_OnLogAction->PushString(message);
102 g_OnLogAction->Execute(&result);
104 if (result >= (ResultType)Pl_Handled)
110 const char *logtag = "SM";
114 IPlugin *pPlugin = scripts->FindPluginByHandle(hndl, &err);
117 logtag = pPlugin->GetFilename();
121 g_Logger.LogMessage("[%s] %s", logtag, message);
124 static cell_t ThrowError(IPluginContext *pContext, const cell_t *params)
128 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
130 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
132 if (pContext->GetLastNativeError() == SP_ERROR_NONE)
134 pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
140 static cell_t GetTime(IPluginContext *pContext, const cell_t *params)
142 time_t t = GetAdjustedTime();
144 pContext->LocalToPhysAddr(params[1], &addr);
148 return static_cast<cell_t>(t);
151 #if defined SUBPLATFORM_SECURECRT
152 void _ignore_invalid_parameter(
153 const wchar_t * expression,
154 const wchar_t * function,
155 const wchar_t * file,
160 /* Wow we don't care, thanks Microsoft. */
164 static cell_t FormatTime(IPluginContext *pContext, const cell_t *params)
166 char *format, *buffer;
167 pContext->LocalToString(params[1], &buffer);
168 pContext->LocalToStringNULL(params[3], &format);
172 format = const_cast<char *>(sm_datetime_format.GetString());
175 #if defined SUBPLATFORM_SECURECRT
176 _invalid_parameter_handler handler = _set_invalid_parameter_handler(_ignore_invalid_parameter);
179 time_t t = (params[4] == -1) ? GetAdjustedTime() : (time_t)params[4];
180 size_t written = strftime(buffer, params[2], format, localtime(&t));
182 #if defined SUBPLATFORM_SECURECRT
183 _set_invalid_parameter_handler(handler);
186 if (params[2] && format[0] != '\0' && !written)
188 pContext->ThrowNativeError("Invalid time format or buffer too small");
195 static cell_t GetPluginIterator(IPluginContext *pContext, const cell_t *params)
197 IPluginIterator *iter = scripts->GetPluginIterator();
199 Handle_t hndl = handlesys->CreateHandle(g_PlIter, iter, pContext->GetIdentity(), g_pCoreIdent, NULL);
201 if (hndl == BAD_HANDLE)
209 static cell_t MorePlugins(IPluginContext *pContext, const cell_t *params)
211 Handle_t hndl = (Handle_t)params[1];
213 IPluginIterator *pIter;
216 sec.pIdentity = g_pCoreIdent;
217 sec.pOwner = pContext->GetIdentity();
219 if ((err=handlesys->ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
221 return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
224 return pIter->MorePlugins() ? 1 : 0;
227 static cell_t ReadPlugin(IPluginContext *pContext, const cell_t *params)
229 Handle_t hndl = (Handle_t)params[1];
231 IPluginIterator *pIter;
234 sec.pIdentity = g_pCoreIdent;
235 sec.pOwner = pContext->GetIdentity();
237 if ((err=handlesys->ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
239 return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
242 IPlugin *pPlugin = pIter->GetPlugin();
250 return pPlugin->GetMyHandle();
253 IPlugin *GetPluginFromHandle(IPluginContext *pContext, Handle_t hndl)
255 if (hndl == BAD_HANDLE)
257 return scripts->FindPluginByContext(pContext->GetContext());
260 IPlugin *pPlugin = scripts->FindPluginByHandle(hndl, &err);
263 pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
269 static cell_t GetPluginStatus(IPluginContext *pContext, const cell_t *params)
271 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
277 return pPlugin->GetStatus();
280 static cell_t GetPluginFilename(IPluginContext *pContext, const cell_t *params)
282 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
288 pContext->StringToLocalUTF8(params[2], params[3], pPlugin->GetFilename(), NULL);
293 static cell_t IsPluginDebugging(IPluginContext *pContext, const cell_t *params)
295 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
301 return pPlugin->IsDebugging() ? 1 : 0;
304 /* Local to plugins only */
307 PlInfo_Name, /**< Plugin name */
308 PlInfo_Author, /**< Plugin author */
309 PlInfo_Description, /**< Plugin description */
310 PlInfo_Version, /**< Plugin verison */
311 PlInfo_URL, /**< Plugin URL */
314 static cell_t GetPluginInfo(IPluginContext *pContext, const cell_t *params)
316 IPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
322 const sm_plugininfo_t *info = pPlugin->GetPublicInfo();
329 const char *str = NULL;
331 switch ((PluginInfo)params[2])
343 case PlInfo_Description:
345 str = info->description;
360 if (!str || str[0] == '\0')
365 pContext->StringToLocalUTF8(params[3], params[4], str, NULL);
370 static cell_t SetFailState(IPluginContext *pContext, const cell_t *params)
375 pContext->LocalToString(params[1], &str);
376 pPlugin = scripts->FindPluginByContext(pContext->GetContext());
380 pPlugin->SetErrorState(Plugin_Error, "%s", str);
382 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", str);
388 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
389 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
391 pPlugin->SetErrorState(Plugin_Error, "%s", str);
392 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "Formatting error (%s)", str);
396 pPlugin->SetErrorState(Plugin_Error, "%s", buffer);
397 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
404 static cell_t GetSysTickCount(IPluginContext *pContext, const cell_t *params)
406 #if defined PLATFORM_WINDOWS
407 return (cell_t)GetTickCount();
408 #elif defined PLATFORM_POSIX
410 clock_t ticks = times(&tm);
411 long ticks_per_sec = sysconf(_SC_CLK_TCK);
412 double fticks = (double)ticks / (double)ticks_per_sec;
414 if (fticks > INT_MAX)
416 double r = (int)(fticks / INT_MAX) * (double)INT_MAX;
419 return (cell_t)fticks;
423 static cell_t AutoExecConfig(IPluginContext *pContext, const cell_t *params)
425 SMPlugin *plugin = scripts->FindPluginByContext(pContext->GetContext());
428 pContext->LocalToString(params[2], &cfg);
429 pContext->LocalToString(params[3], &folder);
433 static char temp_str[255];
434 static char temp_file[PLATFORM_MAX_PATH];
437 g_LibSys.GetFileFromPath(temp_str, sizeof(temp_str), plugin->GetFilename());
438 if ((ptr = strstr(temp_str, ".smx")) != NULL)
443 /* We have the raw filename! */
444 UTIL_Format(temp_file, sizeof(temp_file), "plugin.%s", temp_str);
448 plugin->AddConfig(params[1] ? true : false, cfg, folder);
453 static cell_t MarkNativeAsOptional(IPluginContext *pContext, const cell_t *params)
459 pContext->LocalToString(params[1], &name);
460 if (pContext->FindNativeByName(name, &idx) != SP_ERROR_NONE)
462 /* Oops! This HAS to silently fail! */
466 pContext->GetNativeByIndex(idx, &native);
468 native->flags |= SP_NTVFLAG_OPTIONAL;
473 static cell_t RegPluginLibrary(IPluginContext *pContext, const cell_t *params)
476 SMPlugin *pl = scripts->FindPluginByContext(pContext->GetContext());
478 pContext->LocalToString(params[1], &name);
480 pl->AddLibrary(name);
484 static cell_t LibraryExists(IPluginContext *pContext, const cell_t *params)
487 pContext->LocalToString(params[1], &str);
489 if (strcmp(str, "__CanTestFeatures__") == 0)
494 if (scripts->LibraryExists(str))
499 if (extsys->LibraryExists(str))
507 static cell_t sm_LogAction(IPluginContext *pContext, const cell_t *params)
510 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
511 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
513 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
518 IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
520 LogAction(pPlugin->GetMyHandle(), 2, params[1], params[2], buffer);
525 static cell_t LogToFile(IPluginContext *pContext, const cell_t *params)
528 pContext->LocalToString(params[1], &file);
530 char path[PLATFORM_MAX_PATH];
531 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
533 FILE *fp = fopen(path, "at");
536 return pContext->ThrowNativeError("Could not open file \"%s\"", path);
540 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
541 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
543 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
549 IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
551 g_Logger.LogToOpenFile(fp, "[%s] %s", pPlugin->GetFilename(), buffer);
558 static cell_t LogToFileEx(IPluginContext *pContext, const cell_t *params)
561 pContext->LocalToString(params[1], &file);
563 char path[PLATFORM_MAX_PATH];
564 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
566 FILE *fp = fopen(path, "at");
569 return pContext->ThrowNativeError("Could not open file \"%s\"", path);
573 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
574 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
576 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
582 g_Logger.LogToOpenFile(fp, "%s", buffer);
589 static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *params)
592 pContext->LocalToString(params[1], &str);
594 IExtension *pExtension = extsys->FindExtensionByFile(str);
601 if (!pExtension->IsLoaded())
607 pContext->LocalToString(params[2], &error);
608 if (!pExtension->IsRunning(error, params[3]))
616 static cell_t FindPluginByNumber(IPluginContext *pContext, const cell_t *params)
618 IPlugin *pPlugin = scripts->FindPluginByOrder(params[1]);
625 return pPlugin->GetMyHandle();
628 static cell_t VerifyCoreVersion(IPluginContext *pContext, const cell_t *params)
633 static cell_t GetFeatureStatus(IPluginContext *pContext, const cell_t *params)
635 FeatureType type = (FeatureType)params[1];
638 pContext->LocalToString(params[2], &name);
640 return sharesys->TestFeature(pContext->GetRuntime(), type, name);
643 static cell_t RequireFeature(IPluginContext *pContext, const cell_t *params)
645 FeatureType type = (FeatureType)params[1];
648 pContext->LocalToString(params[2], &name);
650 if (sharesys->TestFeature(pContext->GetRuntime(), type, name) != FeatureStatus_Available)
654 char default_message[255];
655 SMPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
657 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
658 if (pContext->GetLastNativeError() != SP_ERROR_NONE || buffer[0] == '\0')
660 UTIL_Format(default_message, sizeof(default_message), "Feature \"%s\" not available", name);
661 msg = default_message;
663 pPlugin->SetErrorState(Plugin_Error, "%s", msg);
664 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", msg);
677 //memory addresses below 0x10000 are automatically considered invalid for dereferencing
678 #define VALID_MINIMUM_MEMORY_ADDRESS 0x10000
680 static cell_t LoadFromAddress(IPluginContext *pContext, const cell_t *params)
682 void *addr = reinterpret_cast<void*>(params[1]);
686 pContext->ThrowNativeError("Address cannot be null");
688 else if (reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
690 pContext->ThrowNativeError("Invalid address 0x%x is pointing to reserved memory.", addr);
692 NumberType size = static_cast<NumberType>(params[2]);
696 case NumberType_Int8:
697 return *reinterpret_cast<uint8_t*>(addr);
698 case NumberType_Int16:
699 return *reinterpret_cast<uint16_t*>(addr);
700 case NumberType_Int32:
701 return *reinterpret_cast<uint32_t*>(addr);
703 pContext->ThrowNativeError("Invalid number types %d", size);
710 static cell_t StoreToAddress(IPluginContext *pContext, const cell_t *params)
712 void *addr = reinterpret_cast<void*>(params[1]);
716 pContext->ThrowNativeError("Address cannot be null");
718 else if (reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
720 pContext->ThrowNativeError("Invalid address 0x%x is pointing to reserved memory.", addr);
722 cell_t data = params[2];
724 NumberType size = static_cast<NumberType>(params[3]);
728 case NumberType_Int8:
729 SourceHook::SetMemAccess(addr, sizeof(uint8_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
730 *reinterpret_cast<uint8_t*>(addr) = data;
732 case NumberType_Int16:
733 SourceHook::SetMemAccess(addr, sizeof(uint16_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
734 *reinterpret_cast<uint16_t*>(addr) = data;
736 case NumberType_Int32:
737 SourceHook::SetMemAccess(addr, sizeof(uint32_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
738 *reinterpret_cast<uint32_t*>(addr) = data;
741 pContext->ThrowNativeError("Invalid number types %d", size);
747 REGISTER_NATIVES(coreNatives)
749 {"AutoExecConfig", AutoExecConfig},
750 {"GetPluginFilename", GetPluginFilename},
751 {"GetPluginInfo", GetPluginInfo},
752 {"GetPluginIterator", GetPluginIterator},
753 {"GetPluginStatus", GetPluginStatus},
754 {"GetSysTickCount", GetSysTickCount},
755 {"GetTime", GetTime},
756 {"IsPluginDebugging", IsPluginDebugging},
757 {"MorePlugins", MorePlugins},
758 {"ReadPlugin", ReadPlugin},
759 {"ThrowError", ThrowError},
760 {"SetFailState", SetFailState},
761 {"FormatTime", FormatTime},
762 {"MarkNativeAsOptional", MarkNativeAsOptional},
763 {"RegPluginLibrary", RegPluginLibrary},
764 {"LibraryExists", LibraryExists},
765 {"LogAction", sm_LogAction},
766 {"LogToFile", LogToFile},
767 {"LogToFileEx", LogToFileEx},
768 {"GetExtensionFileStatus", GetExtensionFileStatus},
769 {"FindPluginByNumber", FindPluginByNumber},
770 {"VerifyCoreVersion", VerifyCoreVersion},
771 {"GetFeatureStatus", GetFeatureStatus},
772 {"RequireFeature", RequireFeature},
773 {"LoadFromAddress", LoadFromAddress},
774 {"StoreToAddress", StoreToAddress},