y_hooks_impl.inc 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. /*
  2. Legal:
  3. Version: MPL 1.1
  4. The contents of this file are subject to the Mozilla Public License Version
  5. 1.1 the "License"; you may not use this file except in compliance with
  6. the License. You may obtain a copy of the License at
  7. http://www.mozilla.org/MPL/
  8. Software distributed under the License is distributed on an "AS IS" basis,
  9. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  10. for the specific language governing rights and limitations under the
  11. License.
  12. The Original Code is the YSI framework.
  13. The Initial Developer of the Original Code is Alex "Y_Less" Cole.
  14. Portions created by the Initial Developer are Copyright C 2011
  15. the Initial Developer. All Rights Reserved.
  16. Contributors:
  17. Y_Less
  18. koolk
  19. JoeBullet/Google63
  20. g_aSlice/Slice
  21. Misiur
  22. samphunter
  23. tianmeta
  24. maddinat0r
  25. spacemud
  26. Crayder
  27. Dayvison
  28. Ahmad45123
  29. Zeex
  30. irinel1996
  31. Yiin-
  32. Chaprnks
  33. Konstantinos
  34. Masterchen09
  35. Southclaws
  36. PatchwerkQWER
  37. m0k1
  38. paulommu
  39. udan111
  40. Thanks:
  41. JoeBullet/Google63 - Handy arbitrary ASM jump code using SCTRL.
  42. ZeeX - Very productive conversations.
  43. koolk - IsPlayerinAreaEx code.
  44. TheAlpha - Danish translation.
  45. breadfish - German translation.
  46. Fireburn - Dutch translation.
  47. yom - French translation.
  48. 50p - Polish translation.
  49. Zamaroht - Spanish translation.
  50. Los - Portuguese translation.
  51. Dracoblue, sintax, mabako, Xtreme, other coders - Producing other modes for
  52. me to strive to better.
  53. Pixels^ - Running XScripters where the idea was born.
  54. Matite - Pestering me to release it and using it.
  55. Very special thanks to:
  56. Thiadmer - PAWN, whose limits continue to amaze me!
  57. Kye/Kalcor - SA:MP.
  58. SA:MP Team past, present and future - SA:MP.
  59. Optional plugins:
  60. Gamer_Z - GPS.
  61. Incognito - Streamer.
  62. Me - sscanf2, fixes2, Whirlpool.
  63. */
  64. /*
  65. ad88888ba
  66. d8" "8b ,d
  67. Y8, 88
  68. `Y8aaaaa, ,adPPYba, MM88MMM 88 88 8b,dPPYba,
  69. `"""""8b, a8P_____88 88 88 88 88P' "8a
  70. `8b 8PP""""""" 88 88 88 88 d8
  71. Y8a a8P "8b, ,aa 88, "8a, ,a88 88b, ,a8"
  72. "Y88888P" `"Ybbd8"' "Y888 `"YbbdP'Y8 88`YbbdP"'
  73. 88
  74. 88
  75. */
  76. enum E_CHAIN_HOOK
  77. {
  78. E_CHAIN_HOOK_NAME[16],
  79. E_CHAIN_HOOK_VALUE
  80. }
  81. DEFINE_HOOK_RETURN__(OnPlayerCommandText, 0);
  82. DEFINE_HOOK_RETURN__(OnRconCommand, 0);
  83. // Create the default replacements.
  84. DEFINE_HOOK_REPLACEMENT__(Checkpoint, CP );
  85. DEFINE_HOOK_REPLACEMENT__(Container , Cnt);
  86. DEFINE_HOOK_REPLACEMENT__(Inventory , Inv);
  87. DEFINE_HOOK_REPLACEMENT__(Dynamic , Dyn);
  88. DEFINE_HOOK_REPLACEMENT__(TextDraw , TD );
  89. DEFINE_HOOK_REPLACEMENT__(Update , Upd);
  90. DEFINE_HOOK_REPLACEMENT__(Object , Obj);
  91. DEFINE_HOOK_REPLACEMENT__(Command , Cmd);
  92. DEFINE_HOOK_REPLACEMENT__(DynamicCP , DynamicCP);
  93. enum E_HOOK_NAME_REPLACEMENT_DATA
  94. {
  95. E_HOOK_NAME_REPLACEMENT_SHORT[16],
  96. E_HOOK_NAME_REPLACEMENT_LONG[16],
  97. E_HOOK_NAME_REPLACEMENT_MIN,
  98. E_HOOK_NAME_REPLACEMENT_MAX
  99. }
  100. static stock
  101. YSI_g_sReplacements[MAX_HOOK_REPLACEMENTS][E_HOOK_NAME_REPLACEMENT_DATA],
  102. YSI_g_sReplacementsLongOrder[MAX_HOOK_REPLACEMENTS],
  103. YSI_g_sReplacementsShortOrder[MAX_HOOK_REPLACEMENTS],
  104. YSI_g_sReplacePtr,
  105. YSI_g_sInitFSPtr,
  106. YSI_g_sInitFSIdx = -1,
  107. YSI_g_sInitFSRep,
  108. YSI_g_sInitGMPtr,
  109. YSI_g_sInitGMIdx = -1,
  110. YSI_g_sInitGMRep,
  111. YSI_g_sInitPublicDiff,
  112. YSI_g_sActiveHooks = 0,
  113. bool:YSI_g_sSortedOnce = false;
  114. /*-------------------------------------------------------------------------*//**
  115. * <param name="name">Function name to modify.</param>
  116. * <remarks>
  117. * Expands all name parts like "CP" and "Obj" to their full versions (in this
  118. * example "Checkpoint" and "Object").
  119. * </remarks>
  120. *//*------------------------------------------------------------------------**/
  121. stock Hooks_MakeLongName(name[64])
  122. {
  123. new
  124. end = 0,
  125. i = 0,
  126. pos = -1,
  127. idx = YSI_g_sReplacementsShortOrder[0];
  128. while (i != YSI_g_sReplacePtr)
  129. {
  130. // Allow for multiple replacements of the same string.
  131. if ((pos = strfind(name, YSI_g_sReplacements[idx][E_HOOK_NAME_REPLACEMENT_SHORT], false, pos + 1)) == -1)
  132. {
  133. ++i,
  134. idx = YSI_g_sReplacementsShortOrder[i];
  135. }
  136. // This assumes CamelCase. If the letter immediately following the end
  137. // of the string is lower-case, then the short word found is not a
  138. // complete word and should not be replaced.
  139. else if ('a' <= name[(end = pos + YSI_g_sReplacements[idx][E_HOOK_NAME_REPLACEMENT_MIN])] <= 'z')
  140. continue;
  141. else
  142. {
  143. P:5("Found hook name replacement: %d, %s", pos, YSI_g_sReplacements[idx][E_HOOK_NAME_REPLACEMENT_SHORT]);
  144. // Found a complete word according to CamelCase rules.
  145. strdel(name, pos + 1, end),
  146. name[pos] = 0x80000000 | idx;
  147. }
  148. }
  149. // All the replacements have been found and marked. Now actually insert.
  150. // If "end" is "0", it means that it was never assigned to within the loop
  151. // above, which means that no replacements were found.
  152. if (end)
  153. {
  154. // "pos" must be "-1" at the start of this loop.
  155. while (name[++pos])
  156. {
  157. P:7("Hooks_MakeLongName main loop: [%d] = 0x%04x%04x \"%s\"", pos, name[pos] >>> 16, name[pos] & 0xFFFF, name);
  158. if (name[pos] < '\0')
  159. {
  160. // Negative number instead of a character. Used to indicate
  161. // where a replacement should be inserted. They are not done
  162. // inline in the loop above because some replacements may be
  163. // contained within others - we don't want those to be both done
  164. // within each other.
  165. P:5("Inserting hook name replacement: %d, %s", pos, YSI_g_sReplacements[name[pos] & ~0x80000000][E_HOOK_NAME_REPLACEMENT_LONG]);
  166. P:6("Current character: 0x%04x%04x", name[pos] >>> 16, name[pos] & 0xFFFF);
  167. // It took me ages to find a bug in this code. For some reason,
  168. // "strins" was packing the result. This was because the value
  169. // in "name[pos]" was not a real character, so was seen as an
  170. // indication that the string was packed. I fixed it by moving
  171. // the assignment to "name[pos]" above "strins". So while the
  172. // two lines look independent, they aren't!
  173. i = name[pos] & ~0x80000000,
  174. name[pos] = YSI_g_sReplacements[i][E_HOOK_NAME_REPLACEMENT_LONG];
  175. // Use the original "strins" - we know this string is not
  176. // packed, but it might sometimes look like it is. The "fixed"
  177. // version is designed for working with packed strings, but thus
  178. // breaks on not packed strings that just look packed.
  179. #if defined BAD_strins
  180. BAD_strins
  181. #else
  182. strins
  183. #endif
  184. (name, YSI_g_sReplacements[i][E_HOOK_NAME_REPLACEMENT_LONG + E_HOOK_NAME_REPLACEMENT_DATA:1], pos + 1);
  185. pos += YSI_g_sReplacements[i][E_HOOK_NAME_REPLACEMENT_MAX] - 1;
  186. P:6("New string: %s", name);
  187. }
  188. }
  189. }
  190. // It is possible for the expansions to become TOO big.
  191. return Hooks_MakeShortName(name);
  192. }
  193. /*-------------------------------------------------------------------------*//**
  194. * <param name="name">Function name to modify.</param>
  195. * <remarks>
  196. * Compresses function names when required to fit within 32 characters
  197. * according to well defined rules (see "YSI_g_sReplacements").
  198. * </remarks>
  199. *//*------------------------------------------------------------------------**/
  200. stock Hooks_MakeShortName(name[64])
  201. {
  202. // Easy one.
  203. new
  204. len,
  205. pos = -1,
  206. idx = YSI_g_sReplacementsLongOrder[0];
  207. for (new i = 0; (len = strlen(name)) >= 32 && i != YSI_g_sReplacePtr; )
  208. {
  209. if ((pos = strfind(name, YSI_g_sReplacements[idx][E_HOOK_NAME_REPLACEMENT_LONG], false, pos + 1)) == -1)
  210. {
  211. ++i,
  212. idx = YSI_g_sReplacementsLongOrder[i];
  213. }
  214. else
  215. {
  216. strdel(name, pos, pos + YSI_g_sReplacements[idx][E_HOOK_NAME_REPLACEMENT_MAX]),
  217. strins(name, YSI_g_sReplacements[idx][E_HOOK_NAME_REPLACEMENT_SHORT], pos);
  218. }
  219. }
  220. return len;
  221. }
  222. /*-------------------------------------------------------------------------*//**
  223. * <param name="name">The string to get the hooked function name from.</param>
  224. * <returns>
  225. * The input string without y_hooks name decorations.
  226. * </returns>
  227. *//*------------------------------------------------------------------------**/
  228. _Y_HOOKS_STATIC Hooks_IsolateName(string:name[])
  229. {
  230. P:4("Hooks_IsolateName called");
  231. new
  232. pos = strfind(name, "@", false, 4);
  233. // Make "pos" a legal value inside the error message.
  234. if (pos == -1) P:E("Invalid hook name: %s", unpack(name), ++pos);
  235. name[pos] = '\0',
  236. strdel(name, 0, 4);
  237. }
  238. /*-------------------------------------------------------------------------*//**
  239. * <param name="preloads">Desination in which to store all the preloads.</param>
  240. * <param name="precount">Number of found preload libraries.</param>
  241. * <param name="size">Maximum number of libraries to store.</param>
  242. * <remarks>
  243. * Some includes, like "fixes.inc" and anti-cheats MUST come before all other
  244. * includes in order for everything to function correctly (at least fixes.inc
  245. * must). This function looks for these definitions:
  246. *
  247. * PRE_HOOK(FIXES)
  248. *
  249. * Which tell y_hooks that any "FIXES_" prefixed callbacks are part of one of
  250. * these chains.
  251. * </remarks>
  252. *//*------------------------------------------------------------------------**/
  253. _Y_HOOKS_STATIC stock Hooks_GetPreloadLibraries(preloads[][E_CHAIN_HOOK], &precount, size = sizeof (preloads))
  254. {
  255. P:4("Hooks_GetPreloadLibraries called");
  256. --size,
  257. precount = 0;
  258. new
  259. entry,
  260. idx;
  261. {
  262. new
  263. name[32 char],
  264. addr;
  265. while ((idx = AMX_GetPublicEntryPrefix(idx, entry, _A<@CO_>)))
  266. {
  267. if (precount == size)
  268. {
  269. P:E("y_hooks prehook array filled");
  270. break;
  271. }
  272. addr = AMX_Read(entry);
  273. AMX_ReadString(AMX_Read(entry + 4) + AMX_BASE_ADDRESS + 4, name),
  274. strunpack(preloads[precount][E_CHAIN_HOOK_NAME], name, 16),
  275. preloads[precount][E_CHAIN_HOOK_VALUE] = CallFunction(addr),
  276. ++precount;
  277. if (strlen(name) > 15)
  278. P:E("Overflow in prehook name \"%s\"", unpack(name));
  279. // {
  280. // new buffer[32];
  281. // strunpack(buffer, name);
  282. // printf("preload: %s", buffer);
  283. // }
  284. // Remove this public from the publics table. Means that future public
  285. // function calls will be faster by having a smaller search space.
  286. Hooks_InvalidateName(entry);
  287. }
  288. }
  289. // Sort the preload libraries.
  290. {
  291. new
  292. tmp[E_CHAIN_HOOK];
  293. for (entry = precount - 1; entry > 0; --entry)
  294. {
  295. for (idx = 0; idx != entry; ++idx)
  296. {
  297. if (preloads[idx][E_CHAIN_HOOK_VALUE] > preloads[idx + 1][E_CHAIN_HOOK_VALUE])
  298. {
  299. tmp = preloads[idx],
  300. preloads[idx] = preloads[idx + 1],
  301. preloads[idx + 1] = tmp;
  302. }
  303. }
  304. }
  305. }
  306. }
  307. /*-------------------------------------------------------------------------*//**
  308. * <param name="preloads">Names of libraries that come before y_hooks.</param>
  309. * <param name="precount">Number of pre libraries.</param>
  310. * <param name="name">Name of the callback.</param>
  311. * <param name="hooks">Destination in which to store the headers.</param>
  312. * <param name="count">Number of headers found.</param>
  313. * <remarks>
  314. * Finds all the AMX file headers for functions with a similar name to the
  315. * given callback that should be called before (or near) the given callback.
  316. * </remarks>
  317. *//*------------------------------------------------------------------------**/
  318. _Y_HOOKS_STATIC stock Hooks_GetPreHooks(const preloads[][E_CHAIN_HOOK], precount, const name[64], hooks[], &count)
  319. {
  320. P:4("Hooks_GetPreHooks called");
  321. new
  322. idx,
  323. lfunc[64];
  324. // Collect all the functions with something like this name.
  325. P:2("Hooks_GetPreHooks start: %s", unpack(name));
  326. do
  327. {
  328. strcat(lfunc, name),
  329. Hooks_MakeShortName(lfunc);
  330. P:5("Hooks_GetPreHooks: search = %s", unpack(lfunc));
  331. P:C(new oc = count;);
  332. if (AMX_GetPublicEntry(0, hooks[count], lfunc, true)) ++count;
  333. P:C(if (oc != count) { new buffer[32]; AMX_ReadString(AMX_Read(hooks[count] + 4) + AMX_BASE_ADDRESS, buffer); P:5("Hooks_GetPreHooks: found = %s", unpack(buffer)); });
  334. strcpy(lfunc, preloads[idx][E_CHAIN_HOOK_NAME]),
  335. strcat(lfunc, "_");
  336. }
  337. while (++idx <= precount);
  338. }
  339. /*-------------------------------------------------------------------------*//**
  340. * <param name="hooks">All the prehooks for this callback.</param>
  341. * <param name="num">The number of prehooks.</param>
  342. * <param name="ptr">A pointer to write the new stub address to.</param>
  343. * <param name="next">The pointer for the function called after y_hooks.</param>
  344. * <param name="name">The name of the callback being processed.</param>
  345. * <param name="nlen">Space available in the header to write text in.</param>
  346. *//*------------------------------------------------------------------------**/
  347. _Y_HOOKS_STATIC stock Hooks_GetPointerRewrite(const hooks[], num, &ptr, &next, const name[], nlen)
  348. {
  349. P:4("Hooks_GetPointerRewrite called");
  350. P:5("Hooks_GetPointerRewrite: (%s), num: %d, hoks: %08x, %08x, %08x, %08x", name, num, AMX_Read(hooks[0]), AMX_Read(hooks[1]), AMX_Read(hooks[2]), AMX_Read(hooks[3]));
  351. switch (num)
  352. {
  353. case 0:
  354. {
  355. next = 0;
  356. new
  357. len = strlen(name);
  358. if (nlen >= len)
  359. {
  360. // We don't have an existing callback with this name, only hooks.
  361. // We need to add the name of the callback to the AMX header,
  362. // and we have enough space in which to do so.
  363. new
  364. str[32];
  365. strpack(str, name),
  366. AMX_WriteString(AMX_BASE_ADDRESS + AMX_Read(ptr + 4), str, len);
  367. }
  368. else
  369. {
  370. P:F("Could not write function name in \"Hooks_MakePublicPointer\".");
  371. // TODO: Fix this. Use an alternate memory location (the actual
  372. // code segment in which we are writing seems like a good
  373. // choice).
  374. }
  375. }
  376. case 1:
  377. {
  378. // No "fixes.inc", but this callback already exists. In that case,
  379. // just replace the pointer address.
  380. next = ptr = hooks[0];
  381. }
  382. default:
  383. {
  384. // Special hooks. Optimise them.
  385. for (new cur = 1; cur != num; ++cur)
  386. {
  387. ptr = hooks[cur];
  388. new
  389. tmp = AMX_Read(ptr),
  390. nt = Hooks_GetStubEntry(tmp);
  391. tmp += AMX_HEADER_COD,
  392. AMX_Write(tmp, _:RelocateOpcode(OP_JUMP));
  393. switch (nt)
  394. {
  395. case -1: ptr = tmp + 4, next = 0;
  396. case 0: next = 0;
  397. default:
  398. {
  399. ptr = tmp + 4,
  400. next = tmp + nt,
  401. nt = AMX_Read(next),
  402. // Chain those not hooked.
  403. AMX_Write(ptr, nt),
  404. // Store the possible next address.
  405. AMX_Write(next, nt - (AMX_REAL_DATA + AMX_HEADER_COD));
  406. }
  407. }
  408. }
  409. }
  410. }
  411. }
  412. /*-------------------------------------------------------------------------*//**
  413. * <param name="stub">Starting address of the function.</param>
  414. * <returns>
  415. * The address at which the actual code in this function starts.
  416. * </returns>
  417. * <remarks>
  418. * This handles three cases. Regular functions end instantly as found.
  419. * Functions that start with a switch (even before "PROC") are assumed to be
  420. * state-based functions, and we find the most likely state to be used (i.e. we
  421. * remove all future state changes).
  422. * </remarks>
  423. *//*------------------------------------------------------------------------**/
  424. _Y_HOOKS_STATIC stock Hooks_GetStubEntry(stub)
  425. {
  426. P:4("Hooks_GetStubEntry called");
  427. // Get the address of the next function from the ALS state stub.
  428. new
  429. ctx[DisasmContext];
  430. DisasmInit(ctx, stub, stub + 64);
  431. switch (DisasmNextInsn(ctx))
  432. {
  433. case OP_LOAD_PRI:
  434. {
  435. if (DisasmNextInsn(ctx) == OP_SWITCH && DisasmNextInsn(ctx) == OP_CASETBL)
  436. {
  437. // Get the number of items in the casetable.
  438. if (DisasmGetNumOperands(ctx) == 3) // 2 means no used hook.
  439. {
  440. // Got a hook to return. Find it.
  441. new
  442. h0 = DisasmGetOperand(ctx, 3),
  443. h1 = DisasmGetOperand(ctx, 5),
  444. h2 = DisasmGetOperand(ctx, 7);
  445. if (h1 == h2) return 8 * 4; // Most likely.
  446. else if (h0 == h2) return 10 * 4;
  447. else if (h0 == h1) return 12 * 4;
  448. else P:E("y_hooks could not extract state stub jump");
  449. }
  450. else return -1;
  451. }
  452. }
  453. case OP_JUMP:
  454. {
  455. // Already replaced once (shouldn't happen, but may if two different
  456. // hooks use two different short versions of a callback).
  457. return 4; // DisasmGetOperand(ctx, 0);
  458. }
  459. case OP_PROC:
  460. {
  461. //return stub;
  462. P:E("y_hooks attempting to redirect a PROC hook");
  463. }
  464. }
  465. return 0;
  466. }
  467. /*-------------------------------------------------------------------------*//**
  468. * <param name="name">The name of the callback (with y_hooks prefix).</param>
  469. * <param name="hooks">Array in which to store the function headers.</param>
  470. * <param name="idx">Current position in the AMX header.</param>
  471. * <param name="namelen">Min bound of space used by all these names.</param>
  472. * <returns>
  473. * The number of hooks found.
  474. * </returns>
  475. * <remarks>
  476. * The name of the function currently being processed is derived from the first
  477. * found hook. This means we already know of one hook, but to simplify the
  478. * code we get that one again here. Above we only know the name not the
  479. * address. Hence the "- 1" in "i = idx - 1" (to go back one function name).
  480. *
  481. * Our "namelen" variable already contains the full length of the first found
  482. * hook - this is the length of "name", plus N extra characters. The following
  483. * are all valid, and may occur when orders are played with:
  484. *
  485. * @yH_OnX@
  486. * @yH_OnX@1
  487. * @yH_OnX@01
  488. * @yH_OnX@024
  489. * @yH_OnX@ZZZ
  490. * @yH_OnX@999@024
  491. *
  492. * If we want to get the EXACT space taken up by all these hook names we would
  493. * need to get the string of the name in this function then measure it. There
  494. * is really no point in doing this - if we have a second we will always have
  495. * enough space for our new names. Instead, we assume that they are all just
  496. *
  497. * @yH_OnX@
  498. *
  499. * And add on that minimum length accordingly (plus 1 for the NULL character).
  500. *
  501. * This length is used if the original callback doesn't exist but hooks do. In
  502. * that case we need to add the callback to the AMX header, and there is a tiny
  503. * chance that the original name will be longer than one hook's name. In that
  504. * case, having two or more hooks will (AFAIK) always ensure that we have
  505. * enough space to write the longer name.
  506. *
  507. * If there is only one hook, no original function, and the name of the hook is
  508. * shorter than the name of the original function then we have an issue and
  509. * will have to do something else instead.
  510. * </remarks>
  511. *//*------------------------------------------------------------------------**/
  512. _Y_HOOKS_STATIC stock Hooks_GetAllHooks(const name[], hooks[], idx, &namelen, size = sizeof (hooks))
  513. {
  514. P:4("Hooks_GetAllHooks called: %s %d", name, idx);
  515. // Start from the very start - repeats the first item.
  516. new
  517. len = strlen(name) + 1,
  518. count,
  519. tmpName[64];
  520. while ((idx = AMX_GetPublicEntryPrefix(idx, hooks[count], _A<@yH_>)))
  521. {
  522. AMX_GetStringFromEntry(hooks[count], tmpName),
  523. len = strlen(tmpName),
  524. strunpack(tmpName, tmpName),
  525. Hooks_IsolateName(tmpName),
  526. Hooks_MakeLongName(tmpName);
  527. // Check if the fully expanded name is the name.
  528. P:6("Hooks_GetAllHooks found: %s ?= %s %d", name, tmpName, idx);
  529. if (!strcmp(tmpName, name))
  530. {
  531. Hooks_InvalidateName(hooks[count]);
  532. // Record how much consecutive space we have to play with in the
  533. // AMX. I'm slightly concerned that this code assumes that the
  534. // hooks are all consecutive, when they might not be thanks to
  535. // replacements.
  536. if (count) namelen += len; // The first hook was already counted.
  537. // Increment and count how many hooks of this type we have.
  538. if (++count == size)
  539. {
  540. P:W("Hooks_GetAllHooks: Potential overflow." "\n" \
  541. "\n" \
  542. " `MAX_Y_HOOKS` is currently `%d`, recompile with a higher value for more hooks of a single callback:" "\n" \
  543. "\n" \
  544. " #define MAX_Y_HOOKS (%d)" "\n" \
  545. "\n" \
  546. , MAX_Y_HOOKS, MAX_Y_HOOKS * 2);
  547. break;
  548. }
  549. }
  550. }
  551. return count;
  552. }
  553. _Y_HOOKS_STATIC stock Hooks_DoAllHooks()
  554. {
  555. P:4("Hooks_DoAllHooks called");
  556. // Get the preloaders.
  557. new
  558. precount = 0,
  559. preloads[32][E_CHAIN_HOOK];
  560. Hooks_GetPreloadLibraries(preloads, precount);
  561. // Main loop
  562. new
  563. name[32],
  564. idx;
  565. // Get the next hook type.
  566. while ((idx = AMX_GetPublicNamePrefix(idx, name, _A<@yH_>)))
  567. {
  568. // Collect all the hooks of this function, and rewrite the call code.
  569. Hooks_Collate(preloads, precount, name, idx - 1);
  570. }
  571. }
  572. _Y_HOOKS_STATIC stock Hooks_Collate(const preloads[][E_CHAIN_HOOK], precount, const name[32], idx)
  573. {
  574. P:4("Hooks_Collate called: %s %d", unpack(name), idx);
  575. // This records the amount of space available in the nametable, currently
  576. // taken up by the names of hooks that we are about to destroy.
  577. new
  578. namelen = strlen(name);
  579. // For this function, note that:
  580. //
  581. // hook OnPlayerConnect(playerid)
  582. //
  583. // Compiles as:
  584. //
  585. // public @yH_OnPlayerConnect@XXX(playerid)
  586. //
  587. // Where "XXX" is some unique number (the exact value is irrelevant, it just
  588. // means that multiple hooks of the same function have different names).
  589. static
  590. sName[64],
  591. sHooks[MAX_Y_HOOKS];
  592. // The above now becomes:
  593. //
  594. // OnPlayerConnect
  595. //
  596. // This also handles cases such as:
  597. //
  598. // @yH_OnPlayerEnterRaceCheckpoint@162
  599. //
  600. // Being invalid (too long), so instead converts the shortened:
  601. //
  602. // @yH_OnPlayerEnterRaceCP@162
  603. //
  604. // To:
  605. //
  606. // OnPlayerEnterRaceCheckpoint
  607. //
  608. // Thus expanding common name length reductions.
  609. strunpack(sName, name),
  610. Hooks_IsolateName(sName),
  611. Hooks_MakeLongName(sName);
  612. new
  613. // Get all the hooks of this type. They are stored alphabetically.
  614. hookCount = Hooks_GetAllHooks(sName, sHooks, idx, namelen),
  615. writePtr = sHooks[0], // Header for the first found hook.
  616. nextPtr,
  617. pc, ph[16];
  618. // Get the preloads.
  619. Hooks_GetPreHooks(preloads, precount, sName, ph, pc),
  620. // Get where in the chain we are being inserted.
  621. Hooks_GetPointerRewrite(ph, pc, writePtr, nextPtr, sName, namelen);
  622. // Add ALS hooks to the end of the list.
  623. if ((sHooks[hookCount] = nextPtr)) ++hookCount;
  624. // Write the code.
  625. Hooks_GenerateCode(sName, sHooks, hookCount, writePtr, pc > 1);
  626. }
  627. /*-------------------------------------------------------------------------*//**
  628. * <param name="name">Name of the function to generate.</param>
  629. * <param name="hooks">All the functions to call.</param>
  630. * <param name="count">Number of functions to call.</param>
  631. * <param name="write">Where to write the new function's pointer.</param>
  632. * <param name="hasprehooks">Needs to call other stuff first.</param>
  633. *//*------------------------------------------------------------------------**/
  634. _Y_HOOKS_STATIC Hooks_GenerateCode(const name[64], const hooks[], count, write, bool:hasprehooks)
  635. {
  636. P:4("Hooks_GenerateCode called");
  637. // We now have:
  638. //
  639. // 1) All the hooks of this function.
  640. // 2) The original function if it exists.
  641. // 3) Special ALS chained functions if they exists.
  642. //
  643. // This took huge chunks of complex code in the old version. Now not so
  644. // much! I don't know if this code is faster (I suspect it is), but it is
  645. // absolutely simpler!
  646. new
  647. size = Hooks_WriteFunction(hooks, count, Hooks_GetDefaultReturn(name));
  648. P:4("Hooks_GenerateCode %32s called: %6d %6d %08x %d", name[4], hasprehooks, size, hasprehooks ? (write - AMX_HEADER_COD) : (write - AMX_BASE_ADDRESS), CGen_GetCodeSpace());
  649. if (size)
  650. {
  651. //AMX_Write(write, 40);
  652. if (hasprehooks) AMX_Write(write, CGen_GetCodeSpace() + AMX_REAL_DATA);
  653. else AMX_Write(write, CGen_GetCodeSpace() - AMX_HEADER_COD);
  654. CGen_AddCodeSpace(size);
  655. }
  656. else
  657. {
  658. if (hasprehooks) AMX_Write(write, AMX_Read(hooks[0]) + (AMX_REAL_DATA + AMX_HEADER_COD));
  659. else AMX_Write(write, AMX_Read(hooks[0]));
  660. }
  661. }
  662. /*-------------------------------------------------------------------------*//**
  663. * <param name="entry">The public function slot to destroy.</param>
  664. * <remarks>
  665. * Basically, once we know a function has been included, wipe it from the AMX
  666. * header.
  667. * </remarks>
  668. *//*------------------------------------------------------------------------**/
  669. _Y_HOOKS_STATIC Hooks_InvalidateName(entry)
  670. {
  671. P:4("Hooks_InvalidateName called");
  672. AMX_Write(AMX_BASE_ADDRESS + AMX_Read(entry + 4), 0);
  673. }
  674. /*
  675. 88888888888 88 88 ad88
  676. 88 ,d "" 88 d8"
  677. 88 88 88 88
  678. 88aaaaa 88 88 8b,dPPYba, ,adPPYba, MM88MMM 88 ,adPPYba, 8b,dPPYba, 88 8b,dPPYba, MM88MMM ,adPPYba,
  679. 88""""" 88 88 88P' `"8a a8" "" 88 88 a8" "8a 88P' `"8a 88 88P' `"8a 88 a8" "8a
  680. 88 88 88 88 88 8b 88 88 8b d8 88 88 88 88 88 88 8b d8
  681. 88 "8a, ,a88 88 88 "8a, ,aa 88, 88 "8a, ,a8" 88 88 88 88 88 88 "8a, ,a8"
  682. 88 `"YbbdP'Y8 88 88 `"Ybbd8"' "Y888 88 `"YbbdP"' 88 88 88 88 88 88 `"YbbdP"'
  683. */
  684. /*-------------------------------------------------------------------------*//**
  685. * <param name="name">The function to get the address pointer of.</param>
  686. * <param name="write">Destination variable.</param>
  687. * <returns>
  688. * The address at which this function's pointer is stored in the AMX header, if
  689. * the function exists of course.
  690. * </returns>
  691. *//*------------------------------------------------------------------------**/
  692. _Y_HOOKS_STATIC stock Hooks_GetFunctionWritePoint(const name[], &write)
  693. {
  694. P:4("Hooks_GetFunctionWritePoint called");
  695. AMX_GetPublicEntry(0, write, name, true);
  696. }
  697. /*-------------------------------------------------------------------------*//**
  698. * <param name="name">The function to get the default return of.</param>
  699. * <returns>
  700. * The default return for a callback, normally 1.
  701. * </returns>
  702. *//*------------------------------------------------------------------------**/
  703. _Y_HOOKS_STATIC stock Hooks_GetDefaultReturn(const name[64])
  704. {
  705. P:4("Hooks_GetDefaultReturn called");
  706. new
  707. dest[64] = "@y_H";
  708. strcat(dest, name);
  709. Hooks_MakeShortName(dest);
  710. new
  711. ptr;
  712. if (AMX_GetPublicEntry(0, ptr, dest, true))
  713. {
  714. // A "RET_OnWhatever" function exists - rationalise the return.
  715. return CallFunction(AMX_Read(ptr)) ? 1 : 0;
  716. }
  717. return 1;
  718. }
  719. /*
  720. ,ad8888ba, 88
  721. d8"' `"8b 88
  722. d8' 88
  723. 88 ,adPPYba, ,adPPYb,88 ,adPPYba, ,adPPYb,d8 ,adPPYba, 8b,dPPYba,
  724. 88 a8" "8a a8" `Y88 a8P_____88 a8" `Y88 a8P_____88 88P' `"8a
  725. Y8, 8b d8 8b 88 8PP""""""" 8b 88 8PP""""""" 88 88
  726. Y8a. .a8P "8a, ,a8" "8a, ,d88 "8b, ,aa "8a, ,d88 "8b, ,aa 88 88
  727. `"Y8888Y"' `"YbbdP"' `"8bbdP"Y8 `"Ybbd8"' `"YbbdP"Y8 `"Ybbd8"' 88 88
  728. aa, ,88
  729. "Y8bbdP"
  730. */
  731. /*-------------------------------------------------------------------------*//**
  732. * <param name="pointers">The hooks to link together.</param>
  733. * <param name="size">The number of functions in the array.</param>
  734. * <param name="ret">The default return.</param>
  735. * <param name="skipable">Can future hooks be ignored on -1?</param>
  736. * <returns>
  737. * The number of bytes written to memory.
  738. * </returns>
  739. * <remarks>
  740. * Generate some new code, very nicely :D.
  741. * </remarks>
  742. *//*------------------------------------------------------------------------**/
  743. _Y_HOOKS_STATIC Hooks_WriteFunction(const pointers[], const size, const ret = 1, const skipable = true)
  744. {
  745. P:4("Hooks_WriteFunction called");
  746. if (size == 0)
  747. {
  748. P:E("Hooks_WriteFunction: size is 0");
  749. return 0;
  750. }
  751. new
  752. bool:multiple = size != 1,
  753. base = (AMX_HEADER_COD - AMX_BASE_ADDRESS) + AMX_REAL_ADDRESS,
  754. ctx[AsmContext];
  755. // Make sure the underlying system doesn't change without us. Now supported
  756. // natively.
  757. CGen_UseCodeSpace(ctx);
  758. // Start of the function.
  759. @emit PROC // 1
  760. // Allocate space for our "ret" variable at "frm - 4" (may be unused).
  761. @emit PUSH.C ret // 3
  762. // Create the current active hooks stack at "frm - 8".
  763. @emit PUSH ref(YSI_g_sActiveHooks) // 5
  764. @emit ADDR.pri -8 // 7
  765. @emit STOR.pri ref(YSI_g_sActiveHooks) // 9
  766. // Copy the stack to itself (MOVS).
  767. // Allocate space.
  768. @emit LOAD.S.pri 8 // 11
  769. @emit JZER.label Hooks_NoStackCopy // 13
  770. @emit MOVE.alt // 14
  771. @emit LCTRL 4 // 16
  772. @emit SUB // 17
  773. @emit SCTRL 4 // 19
  774. @emit XCHG // 20
  775. if (Server_JITExists())
  776. {
  777. // Need to use memcpy to move about in the stack.
  778. @emit PUSH.C 4096
  779. @emit PUSH.pri
  780. @emit PUSH.C 0
  781. @emit LCTRL 5
  782. @emit ADD.C 12
  783. @emit PUSH.pri
  784. @emit PUSH.alt
  785. @emit PUSH.C 20
  786. @emit SYSREQ "memcpy"
  787. @emit STACK 24
  788. }
  789. else
  790. {
  791. // The "MOVS" OpCode only takes a constant, not a variable, so we need
  792. // to generate self-modifying code (just to be UBER meta)! This code is
  793. // generated AFTER the file is loaded so we bypass the data segment
  794. // checks and can freely write wherever we want.
  795. @emit STOR.pri (CGen_GetCodeSpace() + (27 * 4)) // 22
  796. // Do the copying. "alt" is already "STK", load the "FRM" offset.
  797. @emit LCTRL 5 // 24
  798. @emit ADD.C 12 // 26
  799. // This is the instruction we want to modify...
  800. @emit MOVS 0 // 28 (- 1) = 27 (see above).
  801. }
  802. @emit Hooks_NoStackCopy:
  803. // Push the (fake) number of parameters.
  804. @emit PUSH.C -4
  805. // Now loop over all our functions and insert "CALL" opcodes for them.
  806. if (multiple)
  807. {
  808. for (new i = 0; ; )
  809. {
  810. // Get the absolute offset from here.
  811. @emit CALL (AMX_Read(pointers[i]) + base) // 2
  812. if (skipable)
  813. {
  814. // =====================================
  815. // THIS SECTION IS CURRENTLY 10 CELLS.
  816. // =====================================
  817. // Note: Including the original call...
  818. //
  819. // if (func() < 0) break;
  820. // else ret = ret & func();
  821. //
  822. @emit ZERO.alt // 3
  823. @emit JSLESS.label Hooks_EndCall // 5
  824. // =========================
  825. // JUMP OVER THIS SECTION.
  826. // =========================
  827. }
  828. @emit LOAD.S.alt -4 // 7
  829. if (ret) @emit AND // 8
  830. else @emit OR // 8
  831. // Loop and do the very first items last.
  832. if (++i == size) break;
  833. else @emit STOR.S.pri -4 // 10
  834. }
  835. if (skipable)
  836. {
  837. @emit JUMP.label Hooks_SkipInvert // 10
  838. // This is the point the large "JSLESS" above goes to.
  839. // -1 = 0, -2 = 1
  840. @emit Hooks_EndCall:
  841. @emit INVERT
  842. }
  843. }
  844. else if (skipable)
  845. {
  846. // Still need this code as they may hook a function that doesn't exist,
  847. // but we still need to correctly process -1 or -2.
  848. @emit CALL (AMX_Read(pointers[0]) + base)
  849. @emit ZERO.alt
  850. @emit JSGEQ.label Hooks_SkipInvert
  851. @emit INVERT
  852. }
  853. else
  854. {
  855. // Just replace the original (turns out, this takes no code). Basically
  856. // just discard everything we've written so far (reclaims the memory).
  857. return 0;
  858. }
  859. @emit Hooks_SkipInvert:
  860. // This is the point the small "JUMP" above goes to.
  861. @emit MOVE.alt
  862. // Pop from the active hooks stack.
  863. @emit LOAD.S.pri -8
  864. @emit STOR.pri ref(YSI_g_sActiveHooks)
  865. // Remove the whole stack then get the return value.
  866. @emit LCTRL 5
  867. @emit SCTRL 4
  868. @emit MOVE.pri
  869. // Return.
  870. @emit RETN
  871. // Return the number of bytes written.
  872. return ctx[AsmContext_buffer_offset];
  873. }
  874. /*
  875. ad88888ba 88
  876. d8" "8b ,d ""
  877. Y8, 88
  878. `Y8aaaaa, ,adPPYba, 8b,dPPYba, MM88MMM 88 8b,dPPYba, ,adPPYb,d8
  879. `"""""8b, a8" "8a 88P' "Y8 88 88 88P' `"8a a8" `Y88
  880. `8b 8b d8 88 88 88 88 88 8b 88
  881. Y8a a8P "8a, ,a8" 88 88, 88 88 88 "8a, ,d88
  882. "Y88888P" `"YbbdP"' 88 "Y888 88 88 88 `"YbbdP"Y8
  883. aa, ,88
  884. "Y8bbdP"
  885. */
  886. /*-------------------------------------------------------------------------*//**
  887. * <param name="addr0">The 1st address to read.</param>
  888. * <param name="addr1">The 2nd address to read.</param>
  889. * <returns>
  890. * -1 - The first address is bigger.
  891. * 0 - The addresses are the same
  892. * 1 - The second address is bigger.
  893. * </returns>
  894. * <remarks>
  895. * Reads two addresses, converts them to big endian, and compares them as four
  896. * characters of a string at once.
  897. * </remarks>
  898. *//*------------------------------------------------------------------------**/
  899. _Y_HOOKS_STATIC Hooks_CompareNextCell(addr0, addr1)
  900. {
  901. // P:4("Hooks_CompareNextCell called");
  902. new
  903. s0 = Cell_ReverseBytes(AMX_Read(addr0)),
  904. s1 = Cell_ReverseBytes(AMX_Read(addr1));
  905. // Propogate NULLs.
  906. if (!(s0 & 0xFF000000)) s0 = 0;
  907. else if (!(s0 & 0x00FF0000)) s0 &= 0xFF000000;
  908. else if (!(s0 & 0x0000FF00)) s0 &= 0xFFFF0000;
  909. else if (!(s0 & 0x000000FF)) s0 &= 0xFFFFFF00;
  910. if (!(s1 & 0xFF000000)) s1 = 0;
  911. else if (!(s1 & 0x00FF0000)) s1 &= 0xFF000000;
  912. else if (!(s1 & 0x0000FF00)) s1 &= 0xFFFF0000;
  913. else if (!(s1 & 0x000000FF)) s1 &= 0xFFFFFF00;
  914. // We need the numbers to be compared as big-endian. Now any trailing NULLs
  915. // don't matter at all.
  916. if (s1 > s0) return 1;
  917. else if (s1 < s0) return -1;
  918. else return 0;
  919. }
  920. /*-------------------------------------------------------------------------*//**
  921. * <param name="idx0">The index of the 1st public.</param>
  922. * <param name="idx1">The index of the 2nd public.</param>
  923. * <remarks>
  924. * Compares two public function entries, and if need-be, swaps them over.
  925. * </remarks>
  926. *//*------------------------------------------------------------------------**/
  927. _Y_HOOKS_STATIC Hooks_ComparePublics(idx0, idx1)
  928. {
  929. // P:4("Hooks_ComparePublics called");
  930. idx0 = idx0 * 8 + AMX_HEADER_PUBLICS;
  931. idx1 = idx1 * 8 + AMX_HEADER_PUBLICS;
  932. new
  933. addr0 = AMX_BASE_ADDRESS + AMX_Read(idx0 + 4),
  934. addr1 = AMX_BASE_ADDRESS + AMX_Read(idx1 + 4);
  935. for ( ; ; )
  936. {
  937. switch (Hooks_CompareNextCell(addr0, addr1))
  938. {
  939. case -1:
  940. {
  941. // Swap them over.
  942. new
  943. tmpFunc = AMX_Read(idx0),
  944. tmpName = AMX_Read(idx0 + 4);
  945. AMX_Write(idx0, AMX_Read(idx1));
  946. AMX_Write(idx0 + 4, AMX_Read(idx1 + 4));
  947. AMX_Write(idx1, tmpFunc);
  948. AMX_Write(idx1 + 4, tmpName);
  949. return;
  950. }
  951. case 1:
  952. {
  953. // Already in order - good.
  954. return;
  955. }
  956. // case 0: // Loop.
  957. }
  958. addr0 += 4;
  959. addr1 += 4;
  960. }
  961. }
  962. /*-------------------------------------------------------------------------*//**
  963. * <remarks>
  964. * Goes through the whole of the public functions table and sorts them all in
  965. * to alphabetical order. This is done as we move and rename some so we need
  966. * to fix the virtual machine's binary search.
  967. * </remarks>
  968. *//*------------------------------------------------------------------------**/
  969. _Y_HOOKS_STATIC Hooks_SortPublics()
  970. {
  971. P:4("Hooks_SortPublics called");
  972. // Count the number of still active functions.
  973. YSI_g_sInitPublicDiff = Hooks_CountInvalidPublics() * 8;
  974. new
  975. oldCount = (AMX_HEADER_NATIVES - AMX_HEADER_PUBLICS) / 8;
  976. // Now I need to SORT the functions, and I have honestly no idea how to do
  977. // that. Fortunately I don't actually need to move the strings themselves
  978. // around as they just sit nicely in the nametable; I only need to sort the
  979. // pointers.
  980. for (new i = oldCount - 1; i > 0; --i)
  981. {
  982. for (new j = 0; j != i; ++j)
  983. {
  984. // This neatly moves all the functions with blanked names to the
  985. // start of the public functions table (which will soon be moved).
  986. Hooks_ComparePublics(j, j + 1);
  987. }
  988. }
  989. // Move the start address UP to reduce the VM's search space.
  990. if (YSI_g_sInitPublicDiff)
  991. {
  992. // Update stored values in y_amx so they reflect the new structure.
  993. if (!Server_JITExists() || YSI_g_sSortedOnce)
  994. {
  995. AMX_Write(AMX_BASE_ADDRESS + 32, AMX_Read(AMX_BASE_ADDRESS + 32) + YSI_g_sInitPublicDiff);
  996. AMX_HEADER_PUBLICS += YSI_g_sInitPublicDiff;
  997. ResetStaticAmxHeader();
  998. YSI_g_sSortedOnce = true;
  999. }
  1000. }
  1001. // TODO: Inform the fixes2 plugin of the change. That stores indexes, not
  1002. // addresses so it needs to update itself (somehow - I don't actually know
  1003. // HOW it will do this...) Probably inform it first, store the addresses,
  1004. // then inform it again to track down and replace those addresses.
  1005. }
  1006. /*-------------------------------------------------------------------------*//**
  1007. * <remarks>
  1008. * Counts the number of public functions that have had their names erased.
  1009. * </remarks>
  1010. *//*------------------------------------------------------------------------**/
  1011. _Y_HOOKS_STATIC Hooks_CountInvalidPublics()
  1012. {
  1013. P:4("Hooks_CountInvalidPublics called");
  1014. new
  1015. idx,
  1016. buf,
  1017. count;
  1018. // Search for functions whose names start with nothing.
  1019. while ((idx = AMX_GetPublicEntryPrefix(idx, buf, 0)))
  1020. ++count;
  1021. P:4("Hooks_CountInvalidPublics: Invalid = %d", count);
  1022. return count;
  1023. }
  1024. /*-------------------------------------------------------------------------*//**
  1025. * <remarks>
  1026. * Call the main hook run code, then advance the ALS chain.
  1027. * </remarks>
  1028. *//*------------------------------------------------------------------------**/
  1029. // New stuff.
  1030. stock _Hooks_AddReplacement(const longName[], const shortName[])
  1031. {
  1032. // MAY need to strip spaces off the input strings, but I don't think so.
  1033. if (YSI_g_sReplacePtr == MAX_HOOK_REPLACEMENTS)
  1034. {
  1035. P:E("Insufficient space in the replacements table.");
  1036. return;
  1037. }
  1038. strcpy(YSI_g_sReplacements[YSI_g_sReplacePtr][E_HOOK_NAME_REPLACEMENT_SHORT], shortName, 16),
  1039. strcpy(YSI_g_sReplacements[YSI_g_sReplacePtr][E_HOOK_NAME_REPLACEMENT_LONG] , longName , 16),
  1040. YSI_g_sReplacements[YSI_g_sReplacePtr][E_HOOK_NAME_REPLACEMENT_MIN] = strlen(shortName),
  1041. YSI_g_sReplacements[YSI_g_sReplacePtr][E_HOOK_NAME_REPLACEMENT_MAX] = strlen(longName),
  1042. YSI_g_sReplacementsLongOrder[YSI_g_sReplacePtr] = YSI_g_sReplacePtr,
  1043. YSI_g_sReplacementsShortOrder[YSI_g_sReplacePtr] = YSI_g_sReplacePtr,
  1044. ++YSI_g_sReplacePtr;
  1045. }
  1046. /*-------------------------------------------------------------------------*//**
  1047. * <remarks>
  1048. * Once all the replacement strings have been found, sort them by the length of
  1049. * the short versions of the strings. This is so that the longest (and special
  1050. * case, e.g. "DynamicCP"-> "DynamicCP") replacements are always done first.
  1051. * </remarks>
  1052. *//*------------------------------------------------------------------------**/
  1053. static stock Hooks_SortReplacements()
  1054. {
  1055. new
  1056. idx0,
  1057. idx1,
  1058. temp;
  1059. for (new i = YSI_g_sReplacePtr - 1; i > 0; --i)
  1060. {
  1061. for (new j = 0; j != i; ++j)
  1062. {
  1063. // Sort the strings in order of their short replacement.
  1064. idx0 = YSI_g_sReplacementsShortOrder[j],
  1065. idx1 = YSI_g_sReplacementsShortOrder[j + 1];
  1066. if (YSI_g_sReplacements[idx0][E_HOOK_NAME_REPLACEMENT_MIN] < YSI_g_sReplacements[idx1][E_HOOK_NAME_REPLACEMENT_MIN])
  1067. {
  1068. temp = YSI_g_sReplacementsShortOrder[j],
  1069. YSI_g_sReplacementsShortOrder[j] = YSI_g_sReplacementsShortOrder[j + 1],
  1070. YSI_g_sReplacementsShortOrder[j + 1] = temp;
  1071. }
  1072. // Sort the strings in order of their long replacement.
  1073. idx0 = YSI_g_sReplacementsLongOrder[j],
  1074. idx1 = YSI_g_sReplacementsLongOrder[j + 1];
  1075. if (YSI_g_sReplacements[idx0][E_HOOK_NAME_REPLACEMENT_MAX] < YSI_g_sReplacements[idx1][E_HOOK_NAME_REPLACEMENT_MAX])
  1076. {
  1077. temp = YSI_g_sReplacementsLongOrder[j],
  1078. YSI_g_sReplacementsLongOrder[j] = YSI_g_sReplacementsLongOrder[j + 1],
  1079. YSI_g_sReplacementsLongOrder[j + 1] = temp;
  1080. }
  1081. }
  1082. }
  1083. P:C(for (new i = 0 ; i != YSI_g_sReplacePtr; ++i) P:0("Hook Replacement: %d, %d, %s, %s", YSI_g_sReplacements[i][E_HOOK_NAME_REPLACEMENT_MIN], YSI_g_sReplacements[i][E_HOOK_NAME_REPLACEMENT_MAX], YSI_g_sReplacements[i][E_HOOK_NAME_REPLACEMENT_SHORT], YSI_g_sReplacements[i][E_HOOK_NAME_REPLACEMENT_LONG]););
  1084. }
  1085. /*-------------------------------------------------------------------------*//**
  1086. * <remarks>
  1087. * Call the main hook run code, then advance the ALS chain.
  1088. * </remarks>
  1089. * <transition keep="true" target="_ALS : _ALS_go"/>
  1090. *//*------------------------------------------------------------------------**/
  1091. public OnCodeInit()
  1092. {
  1093. P:1("Hooks_OnCodeInit called");
  1094. state _ALS : _ALS_go;
  1095. // Get the replacements.
  1096. new
  1097. idx,
  1098. entry;
  1099. if (Server_JITExists())
  1100. {
  1101. // Get the indexes of the startup functions that get recorded before the
  1102. // JIT plugin compiles, but called after it. We thus need to fiddle the
  1103. // hooking to ensure that the correct functions are always called.
  1104. YSI_g_sInitFSIdx = funcidx("OnFilterScriptInit");
  1105. YSI_g_sInitGMIdx = funcidx("OnGameModeInit");
  1106. }
  1107. // Loop over the redefinition functions and call them to have them call the
  1108. // "_Hooks_AddReplacement" function above. If we were being REALLY clever,
  1109. // these functions could be removed from the public functions table
  1110. // afterwards (there is already code in y_hooks for this) to reduce is size.
  1111. while ((idx = AMX_GetPublicEntryPrefix(idx, entry, _A<@_yH>)))
  1112. {
  1113. // From "amx\dynamic_call.inc" - check it is included in "y_hooks.inc".
  1114. CallFunction(AMX_Read(entry));
  1115. Hooks_InvalidateName(entry);
  1116. }
  1117. Hooks_SortReplacements();
  1118. Hooks_DoAllHooks();
  1119. // Remove a few other superfluous publics.
  1120. while ((idx = AMX_GetPublicEntryPrefix(idx, entry, _A<_@_y>)))
  1121. Hooks_InvalidateName(entry);
  1122. while ((idx = AMX_GetPublicEntryPrefix(idx, entry, _A<@CO_>)))
  1123. Hooks_InvalidateName(entry);
  1124. Hooks_SortPublics();
  1125. P:1("Hooks_OnCodeInit chain");
  1126. // Dump the generated callbacks for debugging.
  1127. //DisasmDump("YSI_TEST.asm");
  1128. #if defined Hooks_OnCodeInit
  1129. Hooks_OnCodeInit();
  1130. #endif
  1131. P:1("Hooks_OnCodeInit end");
  1132. if (Server_JITExists())
  1133. Hooks_RepairJITInit();
  1134. return 1;
  1135. }
  1136. #undef OnCodeInit
  1137. #define OnCodeInit Hooks_OnCodeInit
  1138. #if defined Hooks_OnCodeInit
  1139. forward Hooks_OnCodeInit();
  1140. #endif
  1141. /**--------------------------------------------------------------------------**\
  1142. <summary>Hooks_RepairJITInit</summary>
  1143. <returns>
  1144. -
  1145. </returns>
  1146. <remarks>
  1147. When using the JIT, the initialisation functions may have already had their
  1148. indexes looked up prior to calling the plugin. It that case we need to keep
  1149. the index constant, even if a different public is now in that slot.
  1150. The stub is the function put in to that index, which redirects the first
  1151. call to one of those publics to the correct place and restores whatever
  1152. public was previously in that slot.
  1153. </remarks>
  1154. \**--------------------------------------------------------------------------**/
  1155. _Y_HOOKS_STATIC _Hooks_RepairStub()
  1156. {
  1157. AMX_Write(AMX_HEADER_PUBLICS + YSI_g_sInitFSIdx * 8, YSI_g_sInitFSRep);
  1158. AMX_Write(AMX_HEADER_PUBLICS + YSI_g_sInitGMIdx * 8, YSI_g_sInitGMRep);
  1159. // Move the header up for searching.
  1160. if (YSI_g_sInitPublicDiff)
  1161. {
  1162. AMX_Write(AMX_BASE_ADDRESS + 32, AMX_Read(AMX_BASE_ADDRESS + 32) + YSI_g_sInitPublicDiff);
  1163. AMX_HEADER_PUBLICS += YSI_g_sInitPublicDiff;
  1164. ResetStaticAmxHeader();
  1165. YSI_g_sSortedOnce = true;
  1166. }
  1167. }
  1168. _Y_HOOKS_STATIC _Hooks_RepairStubFS()
  1169. {
  1170. _Hooks_RepairStub();
  1171. #emit PUSH.C 0
  1172. #emit LCTRL 6
  1173. #emit ADD.C 36
  1174. #emit LCTRL 8
  1175. #emit PUSH.pri
  1176. #emit LOAD.pri YSI_g_sInitFSPtr
  1177. #emit SCTRL 6
  1178. return 1;
  1179. }
  1180. _Y_HOOKS_STATIC _Hooks_RepairStubGM()
  1181. {
  1182. _Hooks_RepairStub();
  1183. #emit PUSH.C 0
  1184. #emit LCTRL 6
  1185. #emit ADD.C 36
  1186. #emit LCTRL 8
  1187. #emit PUSH.pri
  1188. #emit LOAD.pri YSI_g_sInitGMPtr
  1189. #emit SCTRL 6
  1190. return 1;
  1191. }
  1192. _Y_HOOKS_STATIC Hooks_RepairJITInit()
  1193. {
  1194. if (FALSE)
  1195. {
  1196. _Hooks_RepairStubFS();
  1197. _Hooks_RepairStubGM();
  1198. }
  1199. // The pointer at this index needs to remain constant. Replace it with a
  1200. // pointer to a stub that resets the pointer then calls the real init hook.
  1201. YSI_g_sInitFSPtr = GetPublicAddressFromName("OnFilterScriptInit");
  1202. YSI_g_sInitGMPtr = GetPublicAddressFromName("OnGameModeInit");
  1203. new
  1204. base,
  1205. stub;
  1206. base = AMX_HEADER_PUBLICS + YSI_g_sInitFSIdx * 8;
  1207. #emit CONST.pri _Hooks_RepairStubFS
  1208. #emit STOR.S.pri stub
  1209. YSI_g_sInitFSRep = AMX_Read(base),
  1210. AMX_Write(base, stub);
  1211. base = AMX_HEADER_PUBLICS + YSI_g_sInitGMIdx * 8;
  1212. #emit CONST.pri _Hooks_RepairStubGM
  1213. #emit STOR.S.pri stub
  1214. YSI_g_sInitGMRep = AMX_Read(base),
  1215. AMX_Write(base, stub);
  1216. }
  1217. #if !defined _ALS_numargs
  1218. native BAD_numargs() = numargs;
  1219. #endif
  1220. stock Hooks_NumArgs()
  1221. {
  1222. // Awkward code that allows us to jump backwards. It might appear that this
  1223. // code pushes something on the stack before the JZER that is never removed,
  1224. // but labels reset the stack always so it gets unconditionally wiped out.
  1225. #emit LOAD.S.alt 0
  1226. Hooks_NumArgs_load:
  1227. #emit CONST.pri 8
  1228. #emit ADD
  1229. #emit LOAD.I
  1230. #emit ZERO.alt
  1231. #emit PUSH.pri
  1232. #emit SGEQ
  1233. #emit LREF.S.alt 0
  1234. #emit JZER Hooks_NumArgs_load
  1235. #emit POP.pri
  1236. #emit SHR.C.pri 2
  1237. #emit RETN
  1238. // Ideal code, that can't be used due to having a forward jump.
  1239. /* #emit LOAD.S.pri 0
  1240. #emit ADD.C 8
  1241. #emit LOAD.I
  1242. #emit ZERO.alt
  1243. #emit JSLESS Hooks_NumArgs_negative
  1244. #emit SHR.C.pri 2
  1245. #emit RETN
  1246. Hooks_NumArgs_negative:
  1247. #emit LREF.S.pri 0
  1248. #emit ADD.C 8
  1249. #emit LOAD.I
  1250. #emit SHR.C.pri 2
  1251. #emit RETN*/
  1252. __COMPILER_NAKED
  1253. }
  1254. #if defined _ALS_numargs
  1255. #undef numargs
  1256. #else
  1257. #define _ALS_numargs
  1258. #endif
  1259. #define numargs Hooks_NumArgs
  1260. static stock Hooks_Ordinal(n)
  1261. {
  1262. new str[8];
  1263. valstr(str, n);
  1264. switch (n % 100)
  1265. {
  1266. case 11, 12, 13:
  1267. strcat(str, "th");
  1268. default:
  1269. switch (n % 10)
  1270. {
  1271. case 1:
  1272. strcat(str, "st");
  1273. case 2:
  1274. strcat(str, "nd");
  1275. case 3:
  1276. strcat(str, "rd");
  1277. default:
  1278. strcat(str, "th");
  1279. }
  1280. }
  1281. return str;
  1282. }
  1283. public OnRuntimeError(code, &bool:suppress)
  1284. {
  1285. #if defined Hooks_OnRuntimeError
  1286. Hooks_OnRuntimeError(code, suppress);
  1287. #endif
  1288. if (!suppress)
  1289. {
  1290. // TODO: y_hooks relies on the parameter counts being mangled, so we
  1291. // need to restore them after the current execution. That's going to be
  1292. // tricky. First we need to work out where in the stack the code will
  1293. // jump after this error is resolved, which will be wherever the current
  1294. // `CallLocalFunction` returns to, or nowhere for a callback. The
  1295. // latter is easy because it means we have no work to do. The former
  1296. // isn't.
  1297. //
  1298. // Tiny tiny crashdetect overhead in every hook stub:
  1299. //
  1300. // #emit PUSH YSI_g_sActiveHooks
  1301. // #emit ADDR.pri -8
  1302. // #emit STOR.pri YSI_g_sActiveHooks
  1303. //
  1304. // This makes a stack of active hooks. When a crash occurs, we walk
  1305. // this stack and fix up all the parameter counts.
  1306. new
  1307. cur = YSI_g_sActiveHooks;
  1308. for (new i; cur; cur = AMX_Read(cur))
  1309. {
  1310. if (++i == 1)
  1311. {
  1312. printf("[debug]");
  1313. printf("[debug] Parameter count corrections:");
  1314. printf("[debug]");
  1315. }
  1316. // Not 8, because `cur` is `- 8`.
  1317. printf("[debug] The %s mangled argments (e.g. `<1073741823 arguments>`) below should read `<%d arguments>`", Hooks_Ordinal(i), AMX_Read(cur + 16) / 4);
  1318. //// Get the current parameter count.
  1319. //printf("count: %d", count);
  1320. //// Write this out to the lower parameter count copy.
  1321. //AMX_Write(cur - count - 4, count);
  1322. //// Fixed.
  1323. }
  1324. if (YSI_g_sActiveHooks)
  1325. {
  1326. printf("[debug]");
  1327. // Blank the active hooks value. If this is the only public, this
  1328. // will reset it after the public is foribly ended. If it isn't, it
  1329. // will be reset to a correct value when the next still active hook
  1330. // ends. This is only a problem if there are two crashes at once,
  1331. // then the second corrections won't get displayed.
  1332. YSI_g_sActiveHooks = 0;
  1333. }
  1334. //new trace[32];
  1335. //GetStackTrace(trace);
  1336. //PrintStackTrace(trace);
  1337. }
  1338. return 1;
  1339. }
  1340. // No ALS check because it is done in `y_scriptinit`.
  1341. #undef OnRuntimeError
  1342. #define OnRuntimeError Hooks_OnRuntimeError
  1343. #if defined Hooks_OnRuntimeError
  1344. forward Hooks_OnRuntimeError(code, &bool:suppress);
  1345. #endif