sourcemod/core/logic/common_logic.cpp
Benoist 6439769d50
Some checks failed
Continuous Integration / ${{ matrix.os_short }}-${{ matrix.compiler_cc }} (clang, clang++, ubuntu-latest, linux) (push) Has been cancelled
Continuous Integration / ${{ matrix.os_short }}-${{ matrix.compiler_cc }} (clang-14, clang++-14, ubuntu-22.04, linux) (push) Has been cancelled
Continuous Integration / ${{ matrix.os_short }}-${{ matrix.compiler_cc }} (msvc, windows-latest, win) (push) Has been cancelled
hl2sdk-mock tests / mock (push) Has been cancelled
SourcePawn scripting / build (ubuntu-latest, linux) (push) Has been cancelled
SourcePawn scripting / build (windows-latest, win) (push) Has been cancelled
Introduce Virtual Address (#2226)
In the current ongoing effort for sourcemod to fully support 64 bits, we are introducing "virtual address".

# Explanation

Because SourcePawn does not yet support a 64 bits-wide type it's been impossible for any plugins to hold addresses in regular 32-bits wide variable.

A first attempt at solving this issue was made in commit ce1a4dcac0 therein dubbed "PseudoAddress", however this turned out to be an unsatisfactory solution, as any 'high' address if offsetted could turn invalid (or outright be impossible to map).

This leaves us with three alternatives :
- New type
- Convert Address into a handle
- Virtual Address

A new type is the most destructive solution, as it entails breaking every single Address related method. While that solution is still not off the table, we're reserving it as the last attempt should this commit fail.

Converting into a handle type is a good compromise between a brand new type whilst also preserving the Address methods. However, this comes with two issues: the first being that you can no longer offset Address, the second is that we would require authors to free the handle type which will be very confusing. This will likely not be implemented.

# Virtual address

Under a reasonable assumption, we've noted that the average plugin is unlikely to play with more than 4 GB of memory; this shouldn't be too surprising as all valve games were once 32bits and therefore limited to 4GB. Assuming this stays mostly true and a plugin isn't interested with the mapped memory of lesser known modules (like soundlib or matlib), it is fair to assume plugins are unlikely to access more than 4GB of mapped memory. Working with this in mind, we map the memory the plugins are likely to access to our custom virtual address ranges (from 0 to 4Gb, the values of which can fit on 32bits variable). If any memory was missed and plugins were to try an access it later those ranges will be late-mapped to our virtual address ranges until we run out of them.

In order to use virtual addressing, whether on 32 bits or 64 bits. Plugins must now "#include <virtual_address>", as well as use the new SDKCall_VirtualAddress, SDKType_VirtualAddress, LoadAddressFromAddress & StoreAddressToAddress where it's appropriate to.
2025-11-13 13:23:13 +01:00

284 lines
7.0 KiB
C++

/**
* vim: set ts=4 sw=4 tw=99 noet:
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <new>
#include <stdlib.h>
#include <sm_platform.h>
#include <string.h>
#include <stdarg.h>
#include "common_logic.h"
#include "TextParsers.h"
#include "sm_crc32.h"
#include "MemoryUtils.h"
#include "stringutil.h"
#include "ThreadSupport.h"
#include "Translator.h"
#include "GameConfigs.h"
#include "DebugReporter.h"
#include "PluginSys.h"
#include "ShareSys.h"
#include "NativeOwner.h"
#include "HandleSys.h"
#include "ExtensionSys.h"
#include "ForwardSys.h"
#include "AdminCache.h"
#include "ProfileTools.h"
#include "Logger.h"
#include "frame_tasks.h"
#include "sprintf.h"
#include "LibrarySys.h"
#include "RootConsoleMenu.h"
#include "CellArray.h"
#include "smn_entitylump.h"
#include "PseudoAddrManager.h"
#include <bridge/include/BridgeAPI.h>
#include <bridge/include/IProviderCallbacks.h>
SMGlobalClass *SMGlobalClass::head = NULL;
CoreProvider *bridge = nullptr;
ISourceMod *g_pSM = nullptr;
IVEngineServerBridge *engine = nullptr;
IdentityToken_t *g_pCoreIdent = nullptr;
ITimerSystem *timersys = nullptr;
IGameHelpers *gamehelpers = nullptr;
IMenuManager *menus = nullptr;
IPlayerManager *playerhelpers = nullptr;
IHandleSys *handlesys = &g_HandleSys;
ILibrarySys *libsys = &g_LibSys;
ITextParsers *textparser = &g_TextParser;
IShareSys *sharesys = &g_ShareSys;
IRootConsole *rootmenu = &g_RootMenu;
IPluginManager *pluginsys = g_PluginSys.GetOldAPI();
IForwardManager *forwardsys = &g_Forwards;
ServerGlobals serverGlobals;
IAdminSystem *adminsys = &g_Admins;
ISourcePawnEngine *g_pSourcePawn;
ISourcePawnEngine2 *g_pSourcePawn2;
IScriptManager *scripts = &g_PluginSys;
IExtensionSys *extsys = &g_Extensions;
ILogger *logger = &g_Logger;
CNativeOwner g_CoreNatives;
PseudoAddressManager pseudoAddr;
EntityLumpParseResult lastParseResult;
static void AddCorePhraseFile(const char *filename)
{
g_pCorePhrases->AddPhraseFile(filename);
}
static IGameConfig *GetCoreGameConfig()
{
return g_pGameConf;
}
static void GenerateError(IPluginContext *ctx, cell_t idx, int err, const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
g_DbgReporter.GenerateErrorVA(ctx, idx, err, msg, ap);
va_end(ap);
}
static void AddNatives(sp_nativeinfo_t *natives)
{
g_CoreNatives.AddNatives(natives);
}
static void RegisterProfiler(IProfilingTool *tool)
{
g_ProfileToolManager.RegisterTool(tool);
}
static void *FromPseudoAddress(uint32_t paddr)
{
return pseudoAddr.FromPseudoAddress(paddr);
}
static uint32_t ToPseudoAddress(void *addr)
{
return pseudoAddr.ToPseudoAddress(addr);
}
static void SetEntityLumpWritable(bool writable)
{
g_bLumpAvailableForWriting = writable;
// write-lock causes the map entities to be serialized out to string
if (!writable)
{
g_strMapEntities = lumpmanager->Dump();
}
}
static bool ParseEntityLumpString(const char *pMapEntities, int &status, size_t &position)
{
lastParseResult = lumpmanager->Parse(pMapEntities);
status = static_cast<int>(lastParseResult.m_Status);
position = static_cast<size_t>(lastParseResult.m_Position);
return lastParseResult;
}
// returns nullptr if the original lump failed to parse
static const char* GetEntityLumpString()
{
if (!lastParseResult)
{
return nullptr;
}
return g_strMapEntities.c_str();
}
// Defined in smn_filesystem.cpp.
extern bool OnLogPrint(const char *msg);
class ProviderCallbackListener : public IProviderCallbacks
{
public:
bool OnLogPrint(const char *msg) override {
return ::OnLogPrint(msg);
}
void OnThink(bool simulating) override {
RunScheduledFrameTasks(simulating);
}
} sProviderCallbackListener;
static sm_logic_t logic =
{
NULL,
g_pThreader,
&g_Translator,
stristr,
atcprintf,
CoreTranslate,
AddCorePhraseFile,
UTIL_ReplaceAll,
UTIL_ReplaceEx,
UTIL_DecodeHexString,
GetCoreGameConfig,
&g_DbgReporter,
GenerateError,
AddNatives,
RegisterProfiler,
CellArray::New,
CellArray::Free,
FromPseudoAddress,
ToPseudoAddress,
SetEntityLumpWritable,
ParseEntityLumpString,
GetEntityLumpString,
&g_PluginSys,
&g_ShareSys,
&g_Extensions,
&g_HandleSys,
&g_Forwards,
&g_Admins,
NULL,
&g_Logger,
&g_RootMenu,
&sProviderCallbackListener,
-1.0f
};
static void logic_init(CoreProvider* core, sm_logic_t* _logic)
{
logic.head = SMGlobalClass::head;
bridge = core;
memcpy(_logic, &logic, sizeof(sm_logic_t));
memcpy(&serverGlobals, core->serverGlobals, sizeof(ServerGlobals));
engine = core->engine;
g_pSM = core->sm;
timersys = core->timersys;
playerhelpers = core->playerhelpers;
gamehelpers = core->gamehelpers;
menus = core->menus;
g_pSourcePawn = *core->spe1;
g_pSourcePawn2 = *core->spe2;
SMGlobalClass::head = core->listeners;
pseudoAddr.Initialize();
g_ShareSys.Initialize();
g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
_logic->core_ident = g_pCoreIdent;
}
PLATFORM_EXTERN_C ITextParsers *get_textparsers()
{
return &g_TextParser;
}
PLATFORM_EXTERN_C LogicInitFunction logic_load(uint32_t magic)
{
if (magic != SM_LOGIC_MAGIC)
{
return NULL;
}
return logic_init;
}
void CoreNativesToAdd::OnSourceModAllInitialized()
{
g_CoreNatives.AddNatives(m_NativeList);
}
/* Overload a few things to prevent libstdc++ linking */
#if defined __linux__ || defined __APPLE__
extern "C" void __cxa_pure_virtual(void)
{
}
void *operator new(size_t size)
{
return malloc(size);
}
void *operator new[](size_t size)
{
return malloc(size);
}
void operator delete(void *ptr)
{
free(ptr);
}
void operator delete[](void * ptr)
{
free(ptr);
}
#endif