Repository navigation
Expand file tree
/
Copy pathPrecacheExtended.c
More file actions
2138 lines (1833 loc) · 76.8 KB
/
Copy pathPrecacheExtended.c
File metadata and controls
2138 lines (1833 loc) · 76.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PrecacheExtended.dll — Reconstructed C source
*
* MetaHook plugin for GoldSrc (Half-Life 1) engine.
* Extends the precache system limits from 512 to 4096 for sounds and models,
* and the resource list limit from 1280 to 5120.
*
* Build date (from binary): 2026-03-15T21:08:23
* Plugin API: METAHOOK_PLUGIN_API_VERSION004
* Architecture: x86 (32-bit), MSVC compiled
*
* Reverse engineered from PrecacheExtended.dll
*/
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* =========================================================================
* Constants
* ========================================================================= */
#define MAX_PRECACHE_ORIG 512 /* Engine's original precache limit */
#define MAX_PRECACHE_EX 4096 /* Extended precache limit (0x1000) */
#define MAX_RESOURCES_ORIG 1280 /* Engine's original resource limit (0x500) */
#define MAX_RESOURCES_EX 5120 /* Extended resource limit (0x1400) */
#define MAX_RESOURCE_ENTRIES 0xFFF
#define RESOURCE_STRUCT_SIZE 0x88 /* sizeof(resource_t) = 136 bytes */
#define EXTENDED_RES_ALLOC_SIZE 0xAA000 /* MAX_RESOURCES_EX * RESOURCE_STRUCT_SIZE */
#define PRECACHE_ARRAY_SIZE 0x4000 /* MAX_PRECACHE_EX * sizeof(void*) */
#define PLUGIN_INTERFACE_NAME "METAHOOK_PLUGIN_API_VERSION004"
#define BUILD_DATE_STRING "2026-03-15T21:08:23"
#define DIAG_LOG_FILENAME "clientprecache_diag.log"
/* =========================================================================
* Forward declarations & Types
* ========================================================================= */
typedef unsigned char byte;
typedef unsigned int uint;
typedef int qboolean;
typedef void *(*CreateInterfaceFn)(const char *pName, int *pReturnCode);
typedef struct InterfaceReg_s {
CreateInterfaceFn m_CreateFn;
const char *m_pName;
struct InterfaceReg_s *m_pNext;
} InterfaceReg_t;
/* GoldSrc resource_t structure (136 bytes / 0x88) */
typedef struct resource_s {
char szFileName[64]; /* 0x00 */
int type; /* 0x40 resourcetype_t */
int nIndex; /* 0x44 */
int nDownloadSize; /* 0x48 */
byte ucFlags; /* 0x4C */
byte rgucMD5_hash[16]; /* 0x4D */
byte playernum; /* 0x5D */
byte rguc_reserved[32]; /* 0x5E */
void *pNext; /* 0x80 (actually struct resource_s*) */
void *pPrev; /* 0x84 */
} resource_t;
/* Module section info (8 ints per module) */
typedef struct {
uint dwModuleBase; /* +0x00 */
uint dwModuleSize; /* +0x04 */
uint dwTextBase; /* +0x08 */
uint dwTextSize; /* +0x0C */
uint dwDataBase; /* +0x10 */
uint dwDataSize; /* +0x14 */
uint dwRdataBase; /* +0x18 */
uint dwRdataSize; /* +0x1C */
} ModuleInfo_t;
/*
* MetaHook API function table (accessed via offsets from g_pMetaHookAPI).
* Offset map (from decompiled vtable accesses):
*
* [0x00] UninstallHook(hook_handle)
* [0x04] InlineHook(target, detour, &original) -> returns hook_handle
* ...
* [0x20] GetEngineModule() -> module base
* [0x24] GetEngineModuleSize() -> module size
* [0x28] SearchPattern(base, size, pattern, patlen) -> address or 0
* ...
* [0x34] WriteMemory(dest, src, len)
* ...
* [0x40] GetEngineBuildNumber() -> int
* ...
* [0x58] GetVideoMode() or InitVideoMode()
* ...
* [0x64] GetSectionByName(module, name, &size) -> base
* ...
* [0x78] GetServerModule() -> server module base
* [0x7C] GetServerModuleSize() -> server module size
* ...
* [0x98] Con_Printf(fmt, ...)
* ...
* [0x124] GetClientModule() -> client module base (or server dll)
* [0x128] GetClientModuleSize()
* [0x12C] GetServerDllModule() -> (different from hw server)
* [0x130] GetServerDllModuleSize()
*/
/* We model the API as an array of function pointers accessed by byte offset */
typedef void **MetaHookAPI_t;
/* Macro to call MetaHookAPI by byte offset */
#define MH_CALL(offset) (*(void (**)())(((byte*)g_pMetaHookAPI) + (offset)))
#define MH_CALL_RET(offset) (*(uint (**)())(((byte*)g_pMetaHookAPI) + (offset)))
/* =========================================================================
* Global variables
* ========================================================================= */
/* Interface registration linked list */
static InterfaceReg_t *g_pInterfaceList = NULL;
/* MetaHook API pointer */
static MetaHookAPI_t g_pMetaHookAPI = NULL;
/* Engine build number */
static int g_nEngineBuildnum = 0;
/* Engine module info (hw.dll / sw.dll) */
static ModuleInfo_t g_EngineModule;
/* Client module info (client.dll) */
static ModuleInfo_t g_ClientModule;
/* Server module info (server DLL from engine side) */
static ModuleInfo_t g_ServerModule;
/* SV_WriteResourceList module info copy */
static ModuleInfo_t g_RLModuleInfo;
/* Engine callback tables (copied from MetaHook) */
static byte g_EngineCallbacks[0x218]; /* engine funcs */
static byte g_ClientCallbacks[0xAC]; /* client funcs */
/* ---- Extended precache arrays (calloc'd) ---- */
static void **g_pModelPrecacheEx = NULL; /* [MAX_PRECACHE_EX] model name ptrs */
static void **g_pModelStringPoolEx = NULL; /* [MAX_PRECACHE_EX] model string pool */
static byte *g_pResourceFlagsEx = NULL; /* [MAX_PRECACHE_EX] resource flags */
static void **g_pSoundPrecacheEx = NULL; /* [MAX_PRECACHE_EX] sound name ptrs (strdup'd) */
static void **g_pResourceTypeEx = NULL; /* [0x1FFF * 2] resource type array */
static void **g_pModelHashEx = NULL; /* [MAX_PRECACHE_EX] model hash */
static void **g_pSoundCacheEx = NULL; /* [MAX_PRECACHE_EX] sound cache entries */
/* ---- Extended resource list arrays (VirtualAlloc'd) ---- */
static void *g_pSvResourceListEx = NULL; /* sv extended resource array */
static void *g_pClResourceListEx = NULL; /* cl extended resource array */
static void *g_pClModelPrecacheEx = NULL; /* cl model precache extended */
/* ---- Engine function pointers found by pattern matching ---- */
static byte *g_pfnPrecacheModel = NULL; /* PF_precache_model_I */
static byte *g_pfnPrecacheSound = NULL; /* PF_precache_sound_I */
static byte *g_pfnSV_ModelIndex = NULL; /* SV_ModelIndex */
static uint g_pfnPF_setmodel_I = 0; /* PF_setmodel_I (found via xref) */
static byte *g_pfnSV_BuildSoundMsg = NULL;
static byte *g_pfnSV_LookupSoundIndex = NULL;
/* ---- Network message function pointers (found by pattern scan) ---- */
static void (*g_pfnMSG_StartBitWriting)(void *buf, int msgId) = NULL;
static void (*g_pfnMSG_EndBitWriting)(void *buf) = NULL;
static void (*g_pfnMSG_WriteBits)(uint value, int nbits) = NULL;
static void (*g_pfnMSG_WriteBitData)(void *data, int nbits) = NULL;
static void (*g_pfnMSG_WriteBitString)(const char *str) = NULL;
/* ---- Client-side parsing function pointers ---- */
static void (*g_pfnCL_ReadBits)(void *buf) = NULL; /* MSG_ReadBits equivalent */
static void (*g_pfnCL_ReadBits2)(int nbits) = NULL;
static void (*g_pfnCL_ReadBitOrigin)(void *out) = NULL;
static void (*g_pfnCL_ReadBitData)(void *buf) = NULL;
/* ---- Sound engine function pointers ---- */
static void (*g_pfnS_FindName)(const char *name, int flag) = NULL;
static void (*g_pfnS_LoadSound)(int handle, int flag) = NULL;
static void (*g_pfnS_StartDynamicSound)(void) = NULL;
static byte *g_pfnS_StartStaticSound = NULL;
/* ---- Pointers into engine data structures ---- */
static int *g_pMsg_readcount = NULL; /* &msg_readcount */
static void **g_pCLSoundPrecache = NULL; /* cl.sound_precache base */
static void *g_pMsg_readbuf = NULL; /* message read buffer */
/* ---- Resource list function pointers ---- */
static byte *g_pfnSV_WriteResourceList = NULL;
static byte *g_pfnSV_AddResource = NULL;
static byte *g_pfnCL_AddResource = NULL;
/* Resource list network functions (found in SV_WriteResourceList context) */
static void (*g_pfnRL_MSG_WriteByte)(void *buf, int val) = NULL;
static void (*g_pfnRL_MSG_WriteLong)(void *buf, int val) = NULL;
static void (*g_pfnRL_MSG_WriteString)(void *buf, const char *) = NULL;
static void (*g_pfnRL_MSG_StartBitWriting)(void *buf) = NULL;
static void (*g_pfnRL_MSG_EndBitWriting)(void *buf) = NULL;
static void (*g_pfnRL_MSG_WriteBits)(uint val, int nbits) = NULL;
static void (*g_pfnRL_MSG_WriteBitString)(void *buf, int nbits) = NULL;
static void (*g_pfnRL_MSG_WriteBitData)(void *data, int nbits) = NULL;
static void (*g_pfnSV_WriteConsistencyInfo)(void *buf) = NULL;
/* ---- Pointers into engine data (resource list context) ---- */
static int *g_pSvNumResources = NULL; /* &sv.num_resources */
static void *g_pSvResourceList = NULL; /* sv.resourcelist */
static int *g_pClNumResources = NULL; /* &cl.num_resources */
static void *g_pClResourceList = NULL; /* cl.resourcelist */
static uint *g_pSvServerCount = NULL; /* &sv.servercount */
static void **g_pSvDownloadUrl = NULL; /* &sv_downloadurl */
/* ---- Misc engine pointers ---- */
static void (*g_pfnSV_GetEntityIndex)(int ent) = NULL;
static void *g_pSvModelPrecache = NULL; /* sv.model_precache (original) */
static void *g_pSvSoundPrecache = NULL; /* sv.sound_precache (original) */
static byte *g_pfnCL_ParseResources = NULL; /* #GameUI_PrecachingResources ref */
/* ---- Hook handles ---- */
static int g_hkPrecacheModel = 0;
static int g_hkPrecacheSound = 0;
static int g_hkSV_ModelIndex = 0;
static int g_hkPF_setmodel_I = 0;
static int g_hkSV_BuildSoundMsg = 0;
static int g_hkSV_LookupSoundIndex = 0;
static int g_hkCL_ParseSound = 0;
static int g_hkCL_ParseResources = 0;
static int g_hkSV_WriteResourceList = 0;
/* ---- Original function pointers (saved by InlineHook) ---- */
static int (__cdecl *g_origPrecacheSound)(byte *name) = NULL;
static int (__cdecl *g_origPrecacheModel)(byte *name) = NULL;
static int (__cdecl *g_origSV_ModelIndex)(byte *name) = NULL;
static void (__cdecl *g_origPF_setmodel_I)(int ent, byte *name) = NULL;
static int (__cdecl *g_origSV_BuildSoundMsg)(int ent, int chan, byte *sample,
int vol, float attn, uint flags, int pitch, void *origin, void *dest) = NULL;
static int (__cdecl *g_origSV_LookupSoundIndex)(byte *name) = NULL;
static void (*g_origCL_ParseSound)(void) = NULL;
static void (*g_origCL_ParseResources)(void) = NULL;
static void (__cdecl *g_origSV_WriteResourceList)(void *buf) = NULL;
/* Diagnostic log file */
static FILE *g_pDiagLog = NULL;
/* Build date constant */
static const char g_szBuildDate[] = BUILD_DATE_STRING;
/* Fprintf format state buffer */
static byte g_fmtState[256];
/* Default zero origin for memcmp */
static const byte g_vecZeroOrigin[32] = {0};
/* ---- Byte patterns for patching ---- */
/* CMP EAX, 0x500 (original resource limit check) */
static const byte g_patCmpResOrig[5] = { 0x3D, 0x00, 0x05, 0x00, 0x00 };
/* CMP EAX, 0x1400 (extended resource limit check) */
static const byte g_patCmpResNew[5] = { 0x3D, 0x00, 0x14, 0x00, 0x00 };
/* Overflow disable pattern */
static const byte g_patOverflowCheck[9] = {
0x3D, 0x00, 0x00, 0x00, 0x08, /* CMP EAX, 0x08000000 */
0x7E, 0x0A, /* JLE +10 */
0xC7, 0x05 /* MOV DWORD [...], ... */
};
/* Jump offset patches: JNE +5 -> JNE +8, JNE +5 -> JNE +12 */
static const byte g_patchJmpShort8 = 0x08;
static const byte g_patchJmpShort12 = 0x0C;
/* String search patterns for finding engine functions */
static const char *g_szPrecacheModelPatterns[] = {
"PF_precache_model_I: NULL pointer",
"PF_precache_model_I: Model",
"PF_precache_model_I: Bad string"
};
static const char *g_szPrecacheSoundPatterns[] = {
"PF_precache_sound_I: NULL pointer",
"PF_precache_sound_I: Bad string"
};
static const char *g_szSV_ModelIndexPattern[] = {
"SV_ModelIndex: model %s not precached"
};
/* =========================================================================
* Helper / Utility functions
* ========================================================================= */
static void DiagLog(const char *fmt, ...)
{
va_list ap;
if (g_pDiagLog == NULL) {
g_pDiagLog = fopen(DIAG_LOG_FILENAME, "w");
if (g_pDiagLog == NULL)
return;
setvbuf(g_pDiagLog, NULL, _IONBF, 0);
}
va_start(ap, fmt);
vfprintf(g_pDiagLog, fmt, ap);
va_end(ap);
}
static void Con_Printf(const char *fmt, ...)
{
va_list ap;
void (__cdecl *fn)(const char *fmt, ...);
fn = (void (__cdecl *)(const char *, ...))MH_CALL(0x98);
va_start(ap, fmt);
/* Direct call — engine's Con_Printf is variadic */
fn(fmt, ap);
va_end(ap);
}
/* =========================================================================
* Pattern search helpers
*
* These functions scan engine .text/.rdata sections for byte patterns
* or string references, then walk backwards to find the containing
* function's entry point (PUSH EBP; MOV EBP,ESP or MOV EDI,EDI etc.)
* ========================================================================= */
/*
* SearchPattern: find a string reference in a module's .text section
* and walk backwards to find the function prologue.
*
* pModInfo: pointer to ModuleInfo_t (text+rdata base/size pairs)
* pRefBase: pointer to the base address to subtract for relocation
* szPattern: string to search for
*
* Returns: function address (rebased) or NULL
*/
static byte *FindFunctionByString(ModuleInfo_t *pModInfo, ModuleInfo_t *pRefBase,
const char *szPattern)
{
uint dwTextBase = pModInfo->dwRdataBase; /* search rdata first */
uint dwTextSize = pModInfo->dwRdataSize;
uint dwTextBase2 = pModInfo->dwTextBase;
uint dwTextSize2 = pModInfo->dwTextSize;
size_t len;
uint match;
int i;
byte *p;
len = strlen(szPattern);
/* Search rdata for the string, then search text for a reference to it */
match = MH_CALL_RET(0x28)(dwTextBase, dwTextSize, szPattern, len);
if (match == 0) {
/* Fall back to searching in .text (inline string) */
match = MH_CALL_RET(0x28)(dwTextBase2, dwTextSize2, szPattern, len);
if (match == 0)
return NULL;
}
/* Now search .text for a CALL/reference that loads this string address */
i = MH_CALL_RET(0x28)(pModInfo->dwTextBase, pModInfo->dwTextSize, &match, 4);
if (i == 0)
return NULL;
/* Walk backwards from the reference to find function prologue:
* Looking for PUSH EBP; MOV EBP,ESP (55 8B EC) or MOV EDI,EDI (81 ... EC) */
for (int j = 1; j < 0x201; j++) {
p = (byte *)(i - j);
if (p[0] == 0x55 && p[1] == 0x8B && p[2] == 0xEC) {
/* PUSH EBP; MOV EBP,ESP — standard prologue */
return p + (*(uint *)pRefBase - *(uint *)pModInfo);
}
if (p[0] == 0x81 && p[1] == 0xEC) {
/* SUB ESP, imm32 — alternative prologue */
return p + (*(uint *)pRefBase - *(uint *)pModInfo);
}
}
return NULL;
}
/*
* FindFunctionByStringArray: try multiple string patterns, return first match.
*/
static byte *FindFunctionByStringArray(ModuleInfo_t *pModInfo, ModuleInfo_t *pRefBase,
const char **patterns, int count)
{
int i;
byte *result;
for (i = 0; i < count; i++) {
result = FindFunctionByString(pModInfo, pRefBase, patterns[i]);
if (result != NULL)
return result;
}
return NULL;
}
/*
* ExtractImmediateFromCode: scan for MOV [imm32] or similar and extract
* the 32-bit immediate operand as a pointer.
*/
static uint ExtractJmpTarget(byte *pCode)
{
int i;
if (pCode == NULL)
return 0;
for (i = 0; i < 0x1FC; i++) {
/* Look for opcode pattern: 89 3C B5 => MOV [imm32*4+base], EDI
* Actually looking for: 0x89 0x3C 0xB5 (specific encoding) */
if ((pCode[i] == (byte)0x89) && (pCode[i+1] == 0x3C) && (pCode[i+2] == (byte)0xB5)) {
return *(uint *)(pCode + i + 3);
}
}
return 0;
}
/*
* ResolveCallTarget: given CALL rel32 instruction, resolve the target.
*/
static uint ResolveCallTarget(void **pModInfo, int offset)
{
byte *pCode = (byte *)*pModInfo;
uint target;
if (pCode[offset] == (byte)0xE8) {
target = (uint)(pCode + offset + 5) + *(int *)(pCode + offset + 1);
if (target >= *(uint *)((byte *)pModInfo + 4) &&
target < *(uint *)((byte *)pModInfo + 4) + *(uint *)((byte *)pModInfo + 8)) {
return target;
}
}
return 0;
}
/*
* CollectCallTargets: scan a code region for E8 (CALL rel32) instructions
* and collect unique call targets within the module's .text range.
*/
static int CollectCallTargets(byte *pCode, int codeLen, ModuleInfo_t *pModInfo,
uint *pTargets, int maxTargets)
{
int count = 0;
int i, j;
uint target;
uint textBase, textEnd;
if (pCode == NULL)
return 0;
textBase = *(uint *)((byte *)pModInfo + 8);
textEnd = *(uint *)((byte *)pModInfo + 0xC) + textBase;
for (i = 0; i < codeLen - 5; i++) {
if (count >= maxTargets)
return count;
if (pCode[i] == (byte)0xE8) {
target = (uint)(pCode + i + 5) + *(int *)(pCode + i + 1);
if (target >= textBase && target < textEnd) {
/* Check for duplicates */
for (j = 0; j < count; j++) {
if (pTargets[j] == target)
goto next;
}
pTargets[count++] = target;
}
}
next:;
}
return count;
}
/* =========================================================================
* Engine function discovery
*
* Scans the engine binary for known function signatures using string
* references and opcode patterns.
* ========================================================================= */
/*
* DiscoverNetworkFunctions: Find MSG_StartBitWriting, MSG_EndBitWriting,
* MSG_WriteBits, MSG_WriteBitData, MSG_WriteBitString by analyzing the
* call pattern in SV_BuildSoundMsg and cross-referencing.
*/
static void DiscoverNetworkFunctions(ModuleInfo_t *pModInfo)
{
byte *pCode;
uint callTargets[64];
uint dwTextBase, dwTextEnd;
int numTargets, i, j;
uint bestTarget = 0;
uint secondTarget = 0;
int foundIdx = -1;
qboolean bFoundSecond;
int searchStart;
if (g_pfnSV_BuildSoundMsg == NULL)
return;
/* Already found? */
if (g_pfnMSG_StartBitWriting && g_pfnMSG_EndBitWriting &&
g_pfnMSG_WriteBits && g_pfnMSG_WriteBitData && g_pfnMSG_WriteBitString)
return;
dwTextBase = pModInfo->dwTextBase;
dwTextEnd = pModInfo->dwTextSize + dwTextBase;
pCode = g_pfnSV_BuildSoundMsg;
memset(callTargets, 0, sizeof(callTargets));
/* Collect all CALL targets from SV_BuildSoundMsg */
numTargets = 0;
for (i = 0; i < 0x4AB; i++) {
if (numTargets >= 64)
break;
if (pCode[i] == (byte)0xE8) {
uint target = (uint)(pCode + i + 5) + *(int *)(pCode + i + 1);
if (target >= dwTextBase && target < dwTextEnd) {
callTargets[numTargets++] = target;
}
}
}
/* Analyze the call pattern to identify MSG functions.
* In SV_BuildSoundMsg, the call pattern is:
* MSG_StartBitWriting(buf, 6) <- unique, called once
* MSG_EndBitWriting(buf) <- unique, called once
* MSG_WriteBits(val, nbits) <- called many times (most frequent)
* MSG_WriteBitData(data, nbits) <- called once or twice
* MSG_WriteBitString(str) <- called once
*
* The pattern is: A B C C C C ... D E
* where C is most frequent (MSG_WriteBits)
*/
if (numTargets < 4)
goto fallback;
/* Look for the distinctive pattern: three different targets in a row
* where target[i] != target[i+1] and target[i+1] != target[i+2]
* and target[i+2] == target[i+3] and target[i] != target[i+2] */
for (i = 0; i < numTargets - 3; i++) {
if (callTargets[i] != callTargets[i+1] &&
callTargets[i+1] != callTargets[i+2] &&
callTargets[i+2] == callTargets[i+3] &&
callTargets[i] != callTargets[i+2])
{
if (!g_pfnMSG_StartBitWriting)
g_pfnMSG_StartBitWriting = (void (*)(void*, int))callTargets[i];
if (!g_pfnMSG_EndBitWriting)
g_pfnMSG_EndBitWriting = (void (*)(void*))callTargets[i+1];
if (!g_pfnMSG_WriteBits)
g_pfnMSG_WriteBits = (void (*)(uint, int))callTargets[i+2];
/* Find MSG_WriteBitData: different from WriteBits, sandwiched between WriteBits calls */
for (j = i + 2; j < numTargets - 1; j++) {
if (callTargets[j] != callTargets[i+2] &&
j > 0 && callTargets[j-1] == callTargets[i+2] &&
j + 1 < numTargets && callTargets[j+1] == callTargets[i+2])
{
bestTarget = callTargets[j];
foundIdx = j;
}
}
if (bestTarget != 0) {
if (!g_pfnMSG_WriteBitData)
g_pfnMSG_WriteBitData = (void (*)(void*, int))bestTarget;
/* Find MSG_WriteBitString: next non-WriteBits after WriteBitData */
for (j = foundIdx + 1; j < numTargets; j++) {
if (callTargets[j] != callTargets[i+2]) {
if (!g_pfnMSG_WriteBitString)
g_pfnMSG_WriteBitString = (void (*)(const char*))callTargets[j];
break;
}
}
} else {
/* Fallback: look for any non-WriteBits targets after the main block */
bFoundSecond = 0;
for (j = i + 2; j < numTargets; j++) {
if (callTargets[j] != callTargets[i+2]) {
if (bFoundSecond) {
if (!g_pfnMSG_WriteBitString)
g_pfnMSG_WriteBitString = (void (*)(const char*))callTargets[j];
break;
}
bFoundSecond = 1;
if (!g_pfnMSG_WriteBitData)
g_pfnMSG_WriteBitData = (void (*)(void*, int))callTargets[j];
}
}
}
break;
}
}
return;
fallback:
/* If the distinctive pattern wasn't found, try to find MSG_EndBitWriting
* by scanning backwards from where it calls MSG_StartBitWriting */
if (g_pfnMSG_EndBitWriting != NULL) {
uint endAddr = (uint)g_pfnMSG_EndBitWriting;
for (i = 0; i < 0x4AB; i++) {
if (pCode[i] == (byte)0xE8 &&
(uint)(pCode + i + 5) + *(int *)(pCode + i + 1) == endAddr)
{
searchStart = 5;
if (i < 5)
return;
for (j = searchStart; j < 0x81; j++) {
int off = (int)i - j;
if (off < 0)
return;
if (pCode[off] == (byte)0xE8) {
uint tgt = (uint)(pCode + off + 5) + *(int *)(pCode + off + 1);
if (tgt >= dwTextBase && tgt < dwTextEnd && tgt != endAddr) {
/* Look for next non-matching call to confirm */
int k = off + 5;
while (k < (int)i) {
if (pCode[k] == (byte)0xE8) {
uint tgt2 = (uint)(pCode + k + 5) + *(int *)(pCode + k + 1);
if (tgt2 >= dwTextBase && tgt2 < dwTextEnd)
break;
}
k++;
}
g_pfnMSG_StartBitWriting = (void (*)(void*, int))tgt;
return;
}
}
}
return;
}
}
}
}
/*
* DiscoverCLParseFunctions: Find client-side sound parsing functions
* by locating the "CL_Parse_Sound: ent = %i" string and analyzing the
* call graph.
*/
static void DiscoverCLParseFunctions(void)
{
byte *pCode;
uint callTargets[10];
int numTargets;
int i;
uint dwDataBase, dwDataEnd;
byte *pResult;
uint val;
pCode = FindFunctionByString(&g_EngineModule, &g_EngineModule,
"CL_Parse_Sound: ent = %i, cl.max_edicts %i\n");
if (pCode == NULL)
return;
g_pfnCL_ParseResources = pCode; /* Store for hooking later */
memset(callTargets, 0, sizeof(callTargets));
numTargets = CollectCallTargets(pCode, 600, &g_EngineModule, callTargets, 10);
/* First call target = MSG_ReadBits / CL_ReadBits */
if (numTargets > 0 && !g_pfnCL_ReadBits)
g_pfnCL_ReadBits = (void (*)(void*))callTargets[0];
if (numTargets > 1 && !g_pfnCL_ReadBits2)
g_pfnCL_ReadBits2 = (void (*)(int))callTargets[1];
if (numTargets > 2 && !g_pfnCL_ReadBitOrigin)
g_pfnCL_ReadBitOrigin = (void (*)(void*))callTargets[2];
if (numTargets > 3 && !g_pfnCL_ReadBitData)
g_pfnCL_ReadBitData = (void (*)(void*))callTargets[3];
if (numTargets > 6 && !g_pfnS_StartDynamicSound) {
g_pfnS_StartDynamicSound = (void (*)(void))callTargets[6];
/* Also try to find S_StartStaticSound by string */
FindFunctionByString(&g_EngineModule, &g_EngineModule, "S_StartDynamicSound: ");
}
if (!g_pfnS_StartStaticSound) {
pResult = FindFunctionByString(&g_EngineModule, &g_EngineModule, "S_StartStaticSound");
if (pResult == NULL && numTargets > 5)
pResult = (byte *)callTargets[5];
g_pfnS_StartStaticSound = pResult;
}
/* Find msg_readcount pointer in .data section */
dwDataBase = g_EngineModule.dwDataBase;
dwDataEnd = g_EngineModule.dwDataSize + dwDataBase;
if (g_pMsg_readbuf == NULL) {
for (i = 0; i < 50; i++) {
if (pCode[i] == (byte)0x68) { /* PUSH imm32 */
val = *(uint *)(pCode + i + 1);
if (val >= dwDataBase && val < dwDataEnd) {
g_pMsg_readbuf = (void *)val;
break;
}
}
}
}
if (!g_pMsg_readcount) {
if (g_pfnCL_ReadBits) {
for (i = 0; i < 64; i++) {
if (((byte *)g_pfnCL_ReadBits)[i] == (byte)0xA1) {
val = *(uint *)(((byte *)g_pfnCL_ReadBits) + i + 1);
if (val >= dwDataBase && val < dwDataEnd) {
g_pMsg_readcount = (int *)val;
if (val != 0) goto found_readcount;
break;
}
} else if (((byte *)g_pfnCL_ReadBits)[i] == (byte)0x8B &&
((byte *)g_pfnCL_ReadBits)[i+1] == 0x0D) {
val = *(uint *)(((byte *)g_pfnCL_ReadBits) + i + 2);
if (val >= dwDataBase && val < dwDataEnd) {
g_pMsg_readcount = (int *)val;
if (val != 0) goto found_readcount;
break;
}
}
}
DiagLog("[CL] WARNING: msg_readcount NOT found in MSG_StartBitReading\n");
}
}
found_readcount:
/* Find cl.sound_precache base pointer */
if (!g_pCLSoundPrecache) {
for (i = 0; i < 400; i++) {
if ((pCode[i] == (byte)0x8B) &&
((pCode[i+1] == 0x04 || pCode[i+1] == 0x14)) &&
((val = *(uint *)(pCode + i + 3), val >= dwDataBase && val < dwDataEnd &&
(val & 3) == 0)))
{
g_pCLSoundPrecache = (void **)val;
if (val != 0) goto found_soundbase;
break;
}
}
DiagLog("[CL] WARNING: cl.sound_precache base NOT found -- "
"engine sounds use Orig fallback\n");
}
found_soundbase:
/* Find S_FindName */
pResult = FindFunctionByString(&g_EngineModule, &g_EngineModule, "S_FindName: NULL\n");
if (pResult != NULL) {
if (!g_pfnS_FindName)
g_pfnS_FindName = (void (*)(const char*, int))pResult;
/* Walk backwards from S_FindName to find its caller and S_LoadSound */
if (!g_pfnS_LoadSound) {
uint textBase = g_EngineModule.dwTextBase;
uint textSize = g_EngineModule.dwTextSize;
for (i = 0; i < (int)textSize - 5; i++) {
byte *p = (byte *)(textBase + i);
if (p[0] == (byte)0xE8) {
byte *tgt = p + 5 + *(int *)(p + 1);
if (tgt == pResult) {
/* Found a caller of S_FindName; look backwards for prologue */
int k;
for (k = 1; k < 0x51; k++) {
byte *pp = p - k;
if (pp < (byte *)textBase) break;
if (pp[0] == 0x55 && pp[1] == 0x8B && pp[2] == 0xEC) {
g_pfnS_LoadSound = (void (*)(int, int))pp;
/* Look for next call after S_FindName for S_LoadSound entry */
uint nextTarget;
int m;
for (m = 5; m < 200; m++) {
if (p[m] == (byte)0xE8) {
nextTarget = (uint)(p + m + 5) + *(int *)(p + m + 1);
if (nextTarget >= textBase &&
nextTarget < textBase + textSize &&
nextTarget != (uint)pResult && m > 15)
{
g_pfnS_LoadSound = (void (*)(int, int))nextTarget;
break;
}
}
}
if (g_pfnS_LoadSound) break;
}
}
if (g_pfnS_LoadSound) break;
}
}
}
}
}
/* Find #GameUI_PrecachingResources handler */
if (!g_pfnCL_ParseResources) {
pResult = FindFunctionByString(&g_EngineModule, &g_EngineModule,
"#GameUI_PrecachingResources");
if (pResult != NULL)
g_pfnCL_ParseResources = pResult;
}
}
/* =========================================================================
* FindEngineFunctions: Master function that locates all needed engine
* functions by pattern-matching string references in the engine binary.
* Called during LoadEngine.
* ========================================================================= */
static void FindEngineFunctions(ModuleInfo_t *pEngModule, ModuleInfo_t *pSvModule)
{
byte *pResult;
int callTargets[12];
int numTargets, i;
/* Find PF_precache_model_I */
g_pfnPrecacheModel = FindFunctionByStringArray(pEngModule, pEngModule,
g_szPrecacheModelPatterns, 3);
/* Find PF_precache_sound_I */
g_pfnPrecacheSound = FindFunctionByStringArray(pEngModule, pEngModule,
g_szPrecacheSoundPatterns, 2);
/* Find SV_ModelIndex */
g_pfnSV_ModelIndex = FindFunctionByStringArray(pEngModule, pEngModule,
g_szSV_ModelIndexPattern, 1);
/* Find PF_setmodel_I via cross-reference table in PF_precache_model_I */
if (g_pfnPrecacheModel != NULL) {
uint dwDataBase = pEngModule->dwDataBase;
uint dwDataEnd = pEngModule->dwDataSize + dwDataBase;
/* Scan the import/xref table entries near PF_precache_model_I */
byte *p = (byte *)g_pfnPrecacheModel;
for (i = 0; i < (int)pEngModule->dwTextSize - 12; i += 4) {
byte *entry = (byte *)(pEngModule->dwTextBase + i);
if (*(byte **)entry == g_pfnPrecacheModel) {
uint setmodel_ref = *(uint *)(entry + 8);
if (setmodel_ref >= pEngModule->dwTextBase &&
setmodel_ref < pEngModule->dwTextBase + pEngModule->dwTextSize)
{
g_pfnPF_setmodel_I = setmodel_ref;
break;
}
}
}
}
/* Find SV_BuildSoundMsg via "SV_StartSound: volume = %i" */
pResult = FindFunctionByString(pEngModule, pEngModule, "SV_StartSound: volume = %i");
if (pResult != NULL) {
g_pfnSV_BuildSoundMsg = pResult;
/* SV_LookupSoundIndex is typically at a CALL E8 just after SV_BuildSoundMsg + 0x23F */
if (pResult[0x23F] == (byte)0xE8) {
byte *target = pResult + 0x244 + *(int *)(pResult + 0x240);
if (target >= (byte *)pEngModule->dwTextBase &&
target < (byte *)(pEngModule->dwTextBase + pEngModule->dwTextSize))
{
g_pfnSV_LookupSoundIndex = target;
}
}
}
/* Extract sv.model_precache and sv.sound_precache from xref tables */
g_pSvModelPrecache = (void *)ExtractJmpTarget(g_pfnPrecacheSound);
g_pSvSoundPrecache = (void *)ExtractJmpTarget(g_pfnPrecacheModel);
/* Discover network message functions */
DiscoverNetworkFunctions(pEngModule);
/* Find g_pfnSV_GetEntityIndex (called right before MSG_StartBitWriting in SV_BuildSoundMsg) */
if (!g_pfnSV_GetEntityIndex && g_pfnMSG_StartBitWriting && g_pfnSV_BuildSoundMsg) {
memset(callTargets, 0, sizeof(callTargets));
numTargets = CollectCallTargets(g_pfnSV_BuildSoundMsg, 0x4B0,
pEngModule, (uint *)callTargets, 12);
for (i = 1; i < numTargets; i++) {
if ((uint)callTargets[i] == (uint)g_pfnMSG_StartBitWriting) {
g_pfnSV_GetEntityIndex = (void (*)(int))callTargets[i - 1];
break;
}
}
}
/* Report missing functions */
if (!g_pfnPrecacheModel)
Con_Printf("[ClientPrecache] Could not find: %s\nEngine buildnum: %d",
"PF_precache_model_I", g_nEngineBuildnum);
if (!g_pfnPrecacheSound)
Con_Printf("[ClientPrecache] Could not find: %s\nEngine buildnum: %d",
"PF_precache_sound_I", g_nEngineBuildnum);
if (!g_pfnSV_ModelIndex)
Con_Printf("[ClientPrecache] Could not find: %s\nEngine buildnum: %d",
"SV_ModelIndex", g_nEngineBuildnum);
if (!g_pfnPF_setmodel_I)
Con_Printf("[ClientPrecache] Could not find: %s\nEngine buildnum: %d",
"PF_setmodel_I", g_nEngineBuildnum);
if (!g_pfnSV_BuildSoundMsg)
Con_Printf("[ClientPrecache] Could not find: %s\nEngine buildnum: %d",
"SV_BuildSoundMsg", g_nEngineBuildnum);
if (!g_pfnSV_LookupSoundIndex)
Con_Printf("[ClientPrecache] Could not find: %s\nEngine buildnum: %d",
"SV_LookupSoundIndex", g_nEngineBuildnum);
}
/* =========================================================================
* Resource List Extension
*
* This section handles extending the resource list from 1280 to 5120,
* patching the engine binary to use larger arrays and adjusted limits.
* ========================================================================= */
static void ResourceList_Alloc(void)
{
g_pSvResourceListEx = VirtualAlloc(NULL, EXTENDED_RES_ALLOC_SIZE,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
g_pClResourceListEx = VirtualAlloc(NULL, EXTENDED_RES_ALLOC_SIZE,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
g_pClModelPrecacheEx = VirtualAlloc(NULL, PRECACHE_ARRAY_SIZE,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!g_pSvResourceListEx || !g_pClResourceListEx || !g_pClModelPrecacheEx) {
Con_Printf("[ResourceListExt] VirtualAlloc failed for extended arrays!\n");
}
DiagLog("[RL] ResourceList_Alloc: sv_ext=%p cl_ext=%p (%d entries each, %d bytes each array)\n",
g_pSvResourceListEx, g_pClResourceListEx, MAX_RESOURCES_EX, EXTENDED_RES_ALLOC_SIZE);
DiagLog("[RL] ResourceList_Alloc: cl_model_precache_ex=%p (%d entries, %d bytes)\n",
g_pClModelPrecacheEx, MAX_PRECACHE_EX, PRECACHE_ARRAY_SIZE);
}
/*
* PatchResourceLimitChecks: Find CMP EAX, 0x500 patterns in the engine
* and replace with CMP EAX, 0x1400 to extend the resource limit.
*/
static void PatchResourceLimitChecks(void)
{
byte *pTextBase;
uint dwTextSize;
uint i;
uint svResBase, clResBase;
if (!g_pSvResourceList || !g_pClResourceList)
return;
if (!g_pSvResourceListEx)
return;
if (!g_pClResourceListEx)
return;
svResBase = (uint)g_pSvResourceList;
clResBase = (uint)g_pClResourceList;
pTextBase = (byte *)g_RLModuleInfo.dwTextBase;
dwTextSize = g_RLModuleInfo.dwTextSize;
/* Patch relocations: redirect resource array base references */
if (dwTextSize > 3) {
for (i = 0; i + 4 <= dwTextSize; i++) {
uint val = *(uint *)(pTextBase + i);
if (val >= svResBase && val < svResBase + RESOURCE_STRUCT_SIZE) {
/* Reference to sv.resourcelist — redirect to extended array */
uint newVal = (uint)g_pSvResourceListEx + (val - svResBase);
DiagLog("[RL-PATCH] sv base+%#x at text+%05X (VA=%p) -> %08X\n",
val - svResBase, i, pTextBase + i, newVal);
MH_CALL(0x34)(pTextBase + i, &newVal, 4);
}
else if (val >= clResBase && val < clResBase + RESOURCE_STRUCT_SIZE) {
/* Reference to cl.resourcelist — redirect to extended array */
uint newVal = (uint)g_pClResourceListEx + (val - clResBase);
DiagLog("[RL-PATCH] cl base+%#x at text+%05X (VA=%p) -> %08X\n",
val - clResBase, i, pTextBase + i, newVal);
MH_CALL(0x34)(pTextBase + i, &newVal, 4);
}
}
}
/* Replace CMP EAX, 0x500 with CMP EAX, 0x1400 throughout .text */
if (dwTextSize > 4) {
for (i = 0; i + 5 <= dwTextSize; i++) {
if (memcmp(pTextBase + i, g_patCmpResOrig, 5) == 0) {
MH_CALL(0x34)(pTextBase + i, g_patCmpResNew, 5);
}
}
}