mmsplugin.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /**
  2. * vim: set ts=4 sw=4 tw=99 noet :
  3. * ======================================================
  4. * TF2 Dynamic Schema Injector
  5. * Written by nosoop
  6. * ======================================================
  7. */
  8. #include <stdio.h>
  9. #include "mmsplugin.h"
  10. #include <utlmap.h>
  11. #include <utlstring.h>
  12. #include <KeyValues.h>
  13. #include <filesystem.h>
  14. #include "memscan.h"
  15. void BindToSourceMod();
  16. bool SM_LoadExtension(char *error, size_t maxlength);
  17. void SM_UnloadExtension();
  18. SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
  19. SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, 0, bool, char const *, char const *, char const *, char const *, bool, bool);
  20. DynSchema g_Plugin;
  21. IServerGameDLL *server = nullptr;
  22. IVEngineServer *engine = NULL;
  23. IFileSystem *filesystem = nullptr;
  24. PLUGIN_EXPOSE(DynSchema, g_Plugin);
  25. class ISchemaAttributeType;
  26. // this may need to be updated in the future
  27. class CEconItemAttributeDefinition
  28. {
  29. public:
  30. // TODO implementing ~CEconItemAttributeDefinition segfaults. not sure what's up.
  31. // ideally we implement it to match the game so InsertOrReplace is sure to work correctly
  32. /* 0x00 */ KeyValues *m_KeyValues;
  33. /* 0x04 */ unsigned short m_iIndex;
  34. /* 0x08 */ ISchemaAttributeType *m_AttributeType;
  35. /* 0x0c */ bool m_bHidden;
  36. /* 0x0d */ bool m_bForceOutputDescription;
  37. /* 0x0e */ bool m_bStoreAsInteger;
  38. /* 0x0f */ bool m_bInstanceData;
  39. /* 0x10 */ int m_iAssetClassExportType;
  40. /* 0x14 */ int m_iAssetClassBucket;
  41. /* 0x18 */ bool m_bIsSetBonus;
  42. /* 0x1c */ int m_iIsUserGenerated;
  43. /* 0x20 */ int m_iEffectType;
  44. /* 0x24 */ int m_iDescriptionFormat;
  45. /* 0x28 */ char *m_pszDescriptionString;
  46. /* 0x2c */ char *m_pszArmoryDesc;
  47. /* 0x30 */ char *m_pszName;
  48. /* 0x34 */ char *m_pszAttributeClass;
  49. /* 0x38 */ bool m_bCanAffectMarketName;
  50. /* 0x39 */ bool m_bCanAffectRecipeCompName;
  51. /* 0x3c */ int m_nTagHandle;
  52. /* 0x40 */ string_t m_iszAttributeClass;
  53. };
  54. // binary refers to 0x58 when iterating over the attribute map, so we'll refer to that value
  55. // we could also do a runtime assertion
  56. static_assert(sizeof(CEconItemAttributeDefinition) + 0x14 == 0x58, "CEconItemAttributeDefinition size mismatch");
  57. // pointer to item schema attribute map singleton
  58. using AttributeMap = CUtlMap<int, CEconItemAttributeDefinition, int>;
  59. AttributeMap *g_SchemaAttributes;
  60. typedef uintptr_t (*GetEconItemSchema_fn)(void);
  61. GetEconItemSchema_fn fnGetEconItemSchema = nullptr;
  62. // https://www.unknowncheats.me/wiki/Calling_Functions_From_Injected_Library_Using_Function_Pointers_in_C%2B%2B
  63. #ifdef WIN32
  64. typedef bool (__thiscall *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  65. #elif defined(_LINUX)
  66. typedef bool (__cdecl *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  67. #endif
  68. CEconItemAttributeInitFromKV_fn fnItemAttributeInitFromKV = nullptr;
  69. const char* NATIVE_ATTRIB_DIR = "addons/sourcemod/configs/tf2nativeattribs";
  70. bool DynSchema::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
  71. {
  72. PLUGIN_SAVEVARS();
  73. GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
  74. GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
  75. GET_V_IFACE_CURRENT(GetFileSystemFactory, filesystem, IFileSystem, FILESYSTEM_INTERFACE_VERSION);
  76. SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  77. return true;
  78. }
  79. bool DynSchema::OnExtensionLoad(IExtension *me, IShareSys *sys, char *error, size_t maxlength, bool late) {
  80. sharesys = sys;
  81. myself = me;
  82. /* Get the default interfaces from our configured SDK header */
  83. if (!SM_AcquireInterfaces(error, maxlength)) {
  84. return false;
  85. }
  86. // get the base address of the server
  87. {
  88. #if _WINDOWS
  89. fnGetEconItemSchema = reinterpret_cast<GetEconItemSchema_fn>(sm_memutils->FindPattern(server, "\xE8\x2A\x2A\x2A\x2A\x83\xC0\x04\xC3", 9));
  90. fnItemAttributeInitFromKV = reinterpret_cast<CEconItemAttributeInitFromKV_fn>(sm_memutils->FindPattern(server, "\x55\x8B\xEC\x53\x8B\x5D\x08\x56\x8B\xF1\x8B\xCB\x57\xE8\x2A\x2A\x2A\x2A", 18));
  91. #elif _LINUX
  92. Dl_info info;
  93. if (dladdr(server, &info) == 0) {
  94. snprintf(error, maxlength, "dladdr failed");
  95. return 0;
  96. }
  97. void *handle = dlopen(info.dli_fname, RTLD_NOW);
  98. if (!handle) {
  99. snprintf(error, maxlength, "Failed to dlopen server.");
  100. return 0;
  101. }
  102. fnGetEconItemSchema = reinterpret_cast<GetEconItemSchema_fn>(sm_memutils->ResolveSymbol(handle, "_Z15GEconItemSchemav"));
  103. fnItemAttributeInitFromKV = reinterpret_cast<CEconItemAttributeInitFromKV_fn>(sm_memutils->ResolveSymbol(handle, "_ZN28CEconItemAttributeDefinition11BInitFromKVEP9KeyValuesP10CUtlVectorI10CUtlString10CUtlMemoryIS3_iEE"));
  104. dlclose(handle);
  105. #endif
  106. }
  107. if (fnGetEconItemSchema == nullptr) {
  108. snprintf(error, maxlength, "Failed to setup call to GetEconItemSchema()");
  109. return false;
  110. } else if (fnItemAttributeInitFromKV == nullptr) {
  111. snprintf(error, maxlength, "Failed to setup call to CEconItemAttributeDefinition::BInitFromKV");
  112. return false;
  113. }
  114. // is this late enough in the MM:S load stage? we might just have to hold the function
  115. g_SchemaAttributes = reinterpret_cast<AttributeMap*>(fnGetEconItemSchema() + 0x1BC);
  116. return true;
  117. }
  118. bool DynSchema::Unload(char *error, size_t maxlen) {
  119. SM_UnloadExtension();
  120. SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  121. return true;
  122. }
  123. /**
  124. * Initializes a CEconItemAttributeDefinition from a KeyValues definition, then inserts or
  125. * replaces the appropriate entry in the schema.
  126. */
  127. bool InsertOrReplaceAttribute(KeyValues *pAttribKV) {
  128. /**
  129. * TODO implement special handling when "auto" is provided; use an autoincrementing value
  130. * that checks for a free slot in the attribute mapping, then internally map the attribute
  131. * name to that value for persistence and so we don't add that attribute multiple times
  132. */
  133. int attrdef = atoi(pAttribKV->GetName());
  134. if (attrdef <= 0) {
  135. return false;
  136. }
  137. // only replace existing injected attributes; fail on schema attributes
  138. auto existingIndex = g_SchemaAttributes->Find(attrdef);
  139. if (existingIndex != g_SchemaAttributes->InvalidIndex()) {
  140. auto &existingAttr = g_SchemaAttributes->Element(existingIndex);
  141. if (!existingAttr.m_KeyValues->GetBool("injected")) {
  142. META_CONPRINTF("WARN: Not overriding native attribute '%s'\n",
  143. existingAttr.m_pszName);
  144. return false;
  145. }
  146. }
  147. // embed additional custom data into attribute KV; econdata and the like can deal with this
  148. // one could also add this data into the file itself, but this leaves less room for error
  149. pAttribKV->SetBool("injected", true);
  150. CEconItemAttributeDefinition def;
  151. fnItemAttributeInitFromKV(&def, pAttribKV, nullptr);
  152. // TODO verify that this doesn't leak, or just shrug it off
  153. g_SchemaAttributes->InsertOrReplace(attrdef, def);
  154. return true;
  155. }
  156. bool DynSchema::Hook_LevelInitPost(const char *pMapName, char const *pMapEntities,
  157. char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) {
  158. // this hook should fire shortly after the schema is (re)initialized
  159. char game_path[256];
  160. engine->GetGameDir(game_path, sizeof(game_path));
  161. char buffer[1024];
  162. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s",
  163. game_path, "addons/dynattrs/items_dynamic.txt");
  164. // always initialize attributes -- it's better than losing attributes on schema reinit
  165. // coughhiddendevattributescough
  166. // collect raw attribute keyvalue entries scattered across files
  167. KeyValues::AutoDelete rawAttributes("attributes");
  168. // read our own dynamic schema file -- this one supports other sections
  169. KeyValues::AutoDelete pKVMainConfig("DynamicSchema");
  170. if (pKVMainConfig->LoadFromFile(filesystem, buffer)) {
  171. KeyValues *pKVAttributes = pKVMainConfig->FindKey( "attributes" );
  172. if (pKVAttributes) {
  173. rawAttributes->RecursiveMergeKeyValues(pKVAttributes);
  174. META_CONPRINTF("Successfully injected custom schema %s\n", buffer);
  175. } else {
  176. META_CONPRINTF("Failed to inject custom schema %s\n", buffer);
  177. }
  178. }
  179. // iterate over TF2 Hidden Dev Attributes KV format
  180. // https://forums.alliedmods.net/showthread.php?t=326853
  181. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s/*", game_path, NATIVE_ATTRIB_DIR);
  182. FileFindHandle_t findHandle;
  183. const char *filename = filesystem->FindFirst(buffer, &findHandle);
  184. while (filename) {
  185. char pathbuf[1024];
  186. g_SMAPI->PathFormat(pathbuf, sizeof(pathbuf), "%s/%s/%s", game_path,
  187. NATIVE_ATTRIB_DIR, filename);
  188. if (!filesystem->FindIsDirectory(findHandle)) {
  189. KeyValues::AutoDelete nativeAttribConfig("attributes");
  190. nativeAttribConfig->LoadFromFile(filesystem, pathbuf);
  191. rawAttributes->RecursiveMergeKeyValues(nativeAttribConfig);
  192. META_CONPRINTF("Discovered custom schema %s\n", pathbuf);
  193. }
  194. filename = filesystem->FindNext(findHandle);
  195. }
  196. filesystem->FindClose(findHandle);
  197. // perhaps add some other validations before we actually process our attributes?
  198. // TODO ensure the name doesn't clash with existing / newly injected attributes
  199. // finally process our attributes
  200. FOR_EACH_TRUE_SUBKEY(rawAttributes, kv) {
  201. InsertOrReplaceAttribute(kv);
  202. }
  203. return true;
  204. }
  205. void DynSchema::AllPluginsLoaded() {
  206. /* This is where we'd do stuff that relies on the mod or other plugins
  207. * being initialized (for example, cvars added and events registered).
  208. */
  209. BindToSourceMod();
  210. }
  211. void* DynSchema::OnMetamodQuery(const char* iface, int *ret) {
  212. if (strcmp(iface, SOURCEMOD_NOTICE_EXTENSIONS) == 0) {
  213. BindToSourceMod();
  214. }
  215. if (ret != NULL) {
  216. *ret = IFACE_OK;
  217. }
  218. return NULL;
  219. }
  220. void BindToSourceMod() {
  221. char error[256];
  222. if (!SM_LoadExtension(error, sizeof(error))) {
  223. char message[512];
  224. snprintf(message, sizeof(message), "Could not load as a SourceMod extension: %s\n", error);
  225. engine->LogPrint(message);
  226. }
  227. }
  228. bool SM_LoadExtension(char *error, size_t maxlength) {
  229. if ((smexts = (IExtensionManager *)
  230. g_SMAPI->MetaFactory(SOURCEMOD_INTERFACE_EXTENSIONS, NULL, NULL)) == NULL) {
  231. if (error && maxlength) {
  232. snprintf(error, maxlength, SOURCEMOD_INTERFACE_EXTENSIONS " interface not found");
  233. }
  234. return false;
  235. }
  236. /* This could be more dynamic */
  237. char path[256];
  238. g_SMAPI->PathFormat(path, sizeof(path), "addons/dynattrs/tf2dynschema%s",
  239. #if defined __linux__
  240. "_mm.so"
  241. #else
  242. ".dll"
  243. #endif
  244. );
  245. if ((myself = smexts->LoadExternal(&g_Plugin, path, "dynschema.ext", error, maxlength))
  246. == NULL) {
  247. SM_UnsetInterfaces();
  248. return false;
  249. }
  250. return true;
  251. }
  252. void SM_UnloadExtension() {
  253. smexts->UnloadExtension(myself);
  254. }
  255. bool DynSchema::Pause(char *error, size_t maxlen) {
  256. return true;
  257. }
  258. bool DynSchema::Unpause(char *error, size_t maxlen) {
  259. return true;
  260. }
  261. const char *DynSchema::GetLicense() {
  262. return "GPLv3+";
  263. }
  264. const char *DynSchema::GetVersion() {
  265. return "1.2.1";
  266. }
  267. const char *DynSchema::GetDate() {
  268. return __DATE__;
  269. }
  270. const char *DynSchema::GetLogTag() {
  271. return "dynschema";
  272. }
  273. const char *DynSchema::GetAuthor() {
  274. return "nosoop";
  275. }
  276. const char *DynSchema::GetDescription() {
  277. return "Injects user-defined content into the game schema";
  278. }
  279. const char *DynSchema::GetName() {
  280. return "TF2 Dynamic Schema";
  281. }
  282. const char *DynSchema::GetURL() {
  283. return "https://git.csrd.science/";
  284. }
  285. void DynSchema::OnExtensionUnload() {
  286. SM_UnsetInterfaces();
  287. }
  288. void DynSchema::OnExtensionsAllLoaded() {
  289. // no-op
  290. }
  291. void DynSchema::OnExtensionPauseChange(bool pause) {
  292. // no-op
  293. }
  294. bool DynSchema::QueryRunning(char *error, size_t maxlength) {
  295. return true;
  296. }
  297. bool DynSchema::IsMetamodExtension() {
  298. return true;
  299. }
  300. const char *DynSchema::GetExtensionName() {
  301. return this->GetName();
  302. }
  303. const char *DynSchema::GetExtensionURL() {
  304. return this->GetURL();
  305. }
  306. const char *DynSchema::GetExtensionTag() {
  307. return this->GetLogTag();
  308. }
  309. const char *DynSchema::GetExtensionAuthor() {
  310. return this->GetAuthor();
  311. }
  312. const char *DynSchema::GetExtensionVerString() {
  313. return this->GetVersion();
  314. }
  315. const char *DynSchema::GetExtensionDescription() {
  316. return this->GetDescription();
  317. }
  318. const char *DynSchema::GetExtensionDateString() {
  319. return this->GetDate();
  320. }