mmsplugin.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 <map>
  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. size_t g_nAutoAttributeBase = 4000;
  61. std::map<std::string, int> g_AutoNumberedAttributes;
  62. typedef uintptr_t (*GetEconItemSchema_fn)(void);
  63. GetEconItemSchema_fn fnGetEconItemSchema = nullptr;
  64. // https://www.unknowncheats.me/wiki/Calling_Functions_From_Injected_Library_Using_Function_Pointers_in_C%2B%2B
  65. #ifdef WIN32
  66. typedef bool (__thiscall *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  67. #elif defined(_LINUX)
  68. typedef bool (__cdecl *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  69. #endif
  70. CEconItemAttributeInitFromKV_fn fnItemAttributeInitFromKV = nullptr;
  71. const char* NATIVE_ATTRIB_DIR = "addons/sourcemod/configs/tf2nativeattribs";
  72. bool DynSchema::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
  73. {
  74. PLUGIN_SAVEVARS();
  75. GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
  76. GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
  77. GET_V_IFACE_CURRENT(GetFileSystemFactory, filesystem, IFileSystem, FILESYSTEM_INTERFACE_VERSION);
  78. SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  79. return true;
  80. }
  81. bool DynSchema::OnExtensionLoad(IExtension *me, IShareSys *sys, char *error, size_t maxlength, bool late) {
  82. sharesys = sys;
  83. myself = me;
  84. /* Get the default interfaces from our configured SDK header */
  85. if (!SM_AcquireInterfaces(error, maxlength)) {
  86. return false;
  87. }
  88. // get the base address of the server
  89. {
  90. #if _WINDOWS
  91. fnGetEconItemSchema = reinterpret_cast<GetEconItemSchema_fn>(sm_memutils->FindPattern(server, "\xE8\x2A\x2A\x2A\x2A\x83\xC0\x04\xC3", 9));
  92. 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));
  93. #elif _LINUX
  94. Dl_info info;
  95. if (dladdr(server, &info) == 0) {
  96. snprintf(error, maxlength, "dladdr failed");
  97. return 0;
  98. }
  99. void *handle = dlopen(info.dli_fname, RTLD_NOW);
  100. if (!handle) {
  101. snprintf(error, maxlength, "Failed to dlopen server.");
  102. return 0;
  103. }
  104. fnGetEconItemSchema = reinterpret_cast<GetEconItemSchema_fn>(sm_memutils->ResolveSymbol(handle, "_Z15GEconItemSchemav"));
  105. fnItemAttributeInitFromKV = reinterpret_cast<CEconItemAttributeInitFromKV_fn>(sm_memutils->ResolveSymbol(handle, "_ZN28CEconItemAttributeDefinition11BInitFromKVEP9KeyValuesP10CUtlVectorI10CUtlString10CUtlMemoryIS3_iEE"));
  106. dlclose(handle);
  107. #endif
  108. }
  109. if (fnGetEconItemSchema == nullptr) {
  110. snprintf(error, maxlength, "Failed to setup call to GetEconItemSchema()");
  111. return false;
  112. } else if (fnItemAttributeInitFromKV == nullptr) {
  113. snprintf(error, maxlength, "Failed to setup call to CEconItemAttributeDefinition::BInitFromKV");
  114. return false;
  115. }
  116. // is this late enough in the MM:S load stage? we might just have to hold the function
  117. g_SchemaAttributes = reinterpret_cast<AttributeMap*>(fnGetEconItemSchema() + 0x1BC);
  118. return true;
  119. }
  120. bool DynSchema::Unload(char *error, size_t maxlen) {
  121. SM_UnloadExtension();
  122. SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  123. return true;
  124. }
  125. /**
  126. * Initializes a CEconItemAttributeDefinition from a KeyValues definition, then inserts or
  127. * replaces the appropriate entry in the schema.
  128. */
  129. bool InsertOrReplaceAttribute(KeyValues *pAttribKV) {
  130. const char* attrID = pAttribKV->GetName();
  131. const char* attrName = pAttribKV->GetString("name");
  132. int attrdef;
  133. if (strcmp(attrID, "auto") == 0) {
  134. /**
  135. * Have the plugin automatically allocate an attribute ID.
  136. * - if the name is already mapped to an ID, then use that
  137. * - otherwise, continue to increment our counter until we find an unused one
  138. */
  139. auto search = g_AutoNumberedAttributes.find(attrName);
  140. if (search != g_AutoNumberedAttributes.end()) {
  141. attrdef = search->second;
  142. } else {
  143. while (g_SchemaAttributes->Find(g_nAutoAttributeBase) != g_SchemaAttributes->InvalidIndex()) {
  144. g_nAutoAttributeBase++;
  145. }
  146. attrdef = g_nAutoAttributeBase;
  147. g_AutoNumberedAttributes[attrName] = attrdef;
  148. }
  149. } else {
  150. attrdef = atoi(attrID);
  151. if (attrdef <= 0) {
  152. META_CONPRINTF("Attribute '%s' has invalid index string '%s'\n", attrName, attrID);
  153. return false;
  154. }
  155. }
  156. // only replace existing injected attributes; fail on schema attributes
  157. auto existingIndex = g_SchemaAttributes->Find(attrdef);
  158. if (existingIndex != g_SchemaAttributes->InvalidIndex()) {
  159. auto &existingAttr = g_SchemaAttributes->Element(existingIndex);
  160. if (!existingAttr.m_KeyValues->GetBool("injected")) {
  161. META_CONPRINTF("WARN: Not overriding native attribute '%s'\n",
  162. existingAttr.m_pszName);
  163. return false;
  164. }
  165. }
  166. // embed additional custom data into attribute KV; econdata and the like can deal with this
  167. // one could also add this data into the file itself, but this leaves less room for error
  168. pAttribKV->SetBool("injected", true);
  169. CEconItemAttributeDefinition def;
  170. fnItemAttributeInitFromKV(&def, pAttribKV, nullptr);
  171. // TODO verify that this doesn't leak, or just shrug it off
  172. g_SchemaAttributes->InsertOrReplace(attrdef, def);
  173. return true;
  174. }
  175. bool DynSchema::Hook_LevelInitPost(const char *pMapName, char const *pMapEntities,
  176. char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) {
  177. // this hook should fire shortly after the schema is (re)initialized
  178. char game_path[256];
  179. engine->GetGameDir(game_path, sizeof(game_path));
  180. char buffer[1024];
  181. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s",
  182. game_path, "addons/dynattrs/items_dynamic.txt");
  183. // always initialize attributes -- it's better than losing attributes on schema reinit
  184. // coughhiddendevattributescough
  185. // read our own dynamic schema file -- this one supports other sections
  186. KeyValues::AutoDelete pKVMainConfig("DynamicSchema");
  187. if (pKVMainConfig->LoadFromFile(filesystem, buffer)) {
  188. KeyValues *pKVAttributes = pKVMainConfig->FindKey( "attributes" );
  189. if (pKVAttributes) {
  190. FOR_EACH_TRUE_SUBKEY(pKVAttributes, kv) {
  191. InsertOrReplaceAttribute(kv);
  192. }
  193. META_CONPRINTF("Successfully injected custom schema %s\n", buffer);
  194. } else {
  195. META_CONPRINTF("Failed to inject custom schema %s\n", buffer);
  196. }
  197. }
  198. // iterate over TF2 Hidden Dev Attributes KV format
  199. // https://forums.alliedmods.net/showthread.php?t=326853
  200. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s/*", game_path, NATIVE_ATTRIB_DIR);
  201. FileFindHandle_t findHandle;
  202. const char *filename = filesystem->FindFirst(buffer, &findHandle);
  203. while (filename) {
  204. char pathbuf[1024];
  205. g_SMAPI->PathFormat(pathbuf, sizeof(pathbuf), "%s/%s/%s", game_path,
  206. NATIVE_ATTRIB_DIR, filename);
  207. if (!filesystem->FindIsDirectory(findHandle)) {
  208. KeyValues::AutoDelete nativeAttribConfig("attributes");
  209. nativeAttribConfig->LoadFromFile(filesystem, pathbuf);
  210. FOR_EACH_TRUE_SUBKEY(nativeAttribConfig, kv) {
  211. InsertOrReplaceAttribute(kv);
  212. }
  213. META_CONPRINTF("Discovered custom schema %s\n", pathbuf);
  214. }
  215. filename = filesystem->FindNext(findHandle);
  216. }
  217. filesystem->FindClose(findHandle);
  218. // perhaps add some other validations before we actually process our attributes?
  219. // TODO ensure the name doesn't clash with existing / newly injected attributes
  220. return true;
  221. }
  222. void DynSchema::AllPluginsLoaded() {
  223. /* This is where we'd do stuff that relies on the mod or other plugins
  224. * being initialized (for example, cvars added and events registered).
  225. */
  226. BindToSourceMod();
  227. }
  228. void* DynSchema::OnMetamodQuery(const char* iface, int *ret) {
  229. if (strcmp(iface, SOURCEMOD_NOTICE_EXTENSIONS) == 0) {
  230. BindToSourceMod();
  231. }
  232. if (ret != NULL) {
  233. *ret = IFACE_OK;
  234. }
  235. return NULL;
  236. }
  237. void BindToSourceMod() {
  238. char error[256];
  239. if (!SM_LoadExtension(error, sizeof(error))) {
  240. char message[512];
  241. snprintf(message, sizeof(message), "Could not load as a SourceMod extension: %s\n", error);
  242. engine->LogPrint(message);
  243. }
  244. }
  245. bool SM_LoadExtension(char *error, size_t maxlength) {
  246. if ((smexts = (IExtensionManager *)
  247. g_SMAPI->MetaFactory(SOURCEMOD_INTERFACE_EXTENSIONS, NULL, NULL)) == NULL) {
  248. if (error && maxlength) {
  249. snprintf(error, maxlength, SOURCEMOD_INTERFACE_EXTENSIONS " interface not found");
  250. }
  251. return false;
  252. }
  253. /* This could be more dynamic */
  254. char path[256];
  255. g_SMAPI->PathFormat(path, sizeof(path), "addons/dynattrs/tf2dynschema%s",
  256. #if defined __linux__
  257. "_mm.so"
  258. #else
  259. ".dll"
  260. #endif
  261. );
  262. if ((myself = smexts->LoadExternal(&g_Plugin, path, "dynschema.ext", error, maxlength))
  263. == NULL) {
  264. SM_UnsetInterfaces();
  265. return false;
  266. }
  267. return true;
  268. }
  269. void SM_UnloadExtension() {
  270. smexts->UnloadExtension(myself);
  271. }
  272. bool DynSchema::Pause(char *error, size_t maxlen) {
  273. return true;
  274. }
  275. bool DynSchema::Unpause(char *error, size_t maxlen) {
  276. return true;
  277. }
  278. const char *DynSchema::GetLicense() {
  279. return "GPLv3+";
  280. }
  281. const char *DynSchema::GetVersion() {
  282. return "1.3.0";
  283. }
  284. const char *DynSchema::GetDate() {
  285. return __DATE__;
  286. }
  287. const char *DynSchema::GetLogTag() {
  288. return "dynschema";
  289. }
  290. const char *DynSchema::GetAuthor() {
  291. return "nosoop";
  292. }
  293. const char *DynSchema::GetDescription() {
  294. return "Injects user-defined content into the game schema";
  295. }
  296. const char *DynSchema::GetName() {
  297. return "TF2 Dynamic Schema";
  298. }
  299. const char *DynSchema::GetURL() {
  300. return "https://git.csrd.science/";
  301. }
  302. void DynSchema::OnExtensionUnload() {
  303. SM_UnsetInterfaces();
  304. }
  305. void DynSchema::OnExtensionsAllLoaded() {
  306. // no-op
  307. }
  308. void DynSchema::OnExtensionPauseChange(bool pause) {
  309. // no-op
  310. }
  311. bool DynSchema::QueryRunning(char *error, size_t maxlength) {
  312. return true;
  313. }
  314. bool DynSchema::IsMetamodExtension() {
  315. return true;
  316. }
  317. const char *DynSchema::GetExtensionName() {
  318. return this->GetName();
  319. }
  320. const char *DynSchema::GetExtensionURL() {
  321. return this->GetURL();
  322. }
  323. const char *DynSchema::GetExtensionTag() {
  324. return this->GetLogTag();
  325. }
  326. const char *DynSchema::GetExtensionAuthor() {
  327. return this->GetAuthor();
  328. }
  329. const char *DynSchema::GetExtensionVerString() {
  330. return this->GetVersion();
  331. }
  332. const char *DynSchema::GetExtensionDescription() {
  333. return this->GetDescription();
  334. }
  335. const char *DynSchema::GetExtensionDateString() {
  336. return this->GetDate();
  337. }