forked from id-Software/Quake-III-Arena
/
common.c
3878 lines (3218 loc) · 85.4 KB
/
common.c
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
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// common.c -- misc functions used in client and server
#include "q_shared.h"
#include "qcommon.h"
#include <setjmp.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <sys/stat.h> // umask
#else
#include <winsock.h>
#endif
int demo_protocols[] =
#ifdef ELITEFORCE
{ 0 };
#else
{ 67, 66, 0 };
#endif
#define MAX_NUM_ARGVS 50
#define MIN_DEDICATED_COMHUNKMEGS 1
#define MIN_COMHUNKMEGS 56
#define DEF_COMHUNKMEGS 128
#ifdef ELITEFORCE
#define DEF_COMZONEMEGS 32
#else
#define DEF_COMZONEMEGS 24
#endif
#define DEF_COMHUNKMEGS_S XSTRING(DEF_COMHUNKMEGS)
#define DEF_COMZONEMEGS_S XSTRING(DEF_COMZONEMEGS)
int com_argc;
char *com_argv[MAX_NUM_ARGVS+1];
jmp_buf abortframe; // an ERR_DROP occurred, exit the entire frame
FILE *debuglogfile;
static fileHandle_t pipefile;
static fileHandle_t logfile;
fileHandle_t com_journalFile; // events are written here
fileHandle_t com_journalDataFile; // config files are written here
cvar_t *com_speeds;
cvar_t *com_developer;
cvar_t *com_dedicated;
cvar_t *com_timescale;
cvar_t *com_fixedtime;
cvar_t *com_journal;
cvar_t *com_maxfps;
cvar_t *com_altivec;
cvar_t *com_timedemo;
cvar_t *com_sv_running;
cvar_t *com_cl_running;
cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
cvar_t *com_pipefile;
cvar_t *com_showtrace;
cvar_t *com_version;
cvar_t *com_blood;
cvar_t *com_buildScript; // for automated data building scripts
#ifdef CINEMATICS_INTRO
cvar_t *com_introPlayed;
#endif
cvar_t *cl_paused;
cvar_t *sv_paused;
cvar_t *cl_packetdelay;
cvar_t *sv_packetdelay;
cvar_t *com_cameraMode;
cvar_t *com_ansiColor;
cvar_t *com_unfocused;
cvar_t *com_maxfpsUnfocused;
cvar_t *com_minimized;
cvar_t *com_maxfpsMinimized;
cvar_t *com_abnormalExit;
cvar_t *com_standalone;
cvar_t *com_gamename;
cvar_t *com_protocol;
#ifdef LEGACY_PROTOCOL
cvar_t *com_legacyprotocol;
#endif
cvar_t *com_basegame;
cvar_t *com_homepath;
cvar_t *com_busyWait;
#ifndef DEDICATED
cvar_t *con_autochat;
#endif
#if idx64
int (*Q_VMftol)(void);
#elif id386
long (QDECL *Q_ftol)(float f);
int (QDECL *Q_VMftol)(void);
void (QDECL *Q_SnapVector)(vec3_t vec);
#endif
// com_speeds times
int time_game;
int time_frontend; // renderer frontend time
int time_backend; // renderer backend time
int com_frameTime;
int com_frameNumber;
qboolean com_errorEntered = qfalse;
qboolean com_fullyInitialized = qfalse;
qboolean com_gameRestarting = qfalse;
qboolean com_gameClientRestarting = qfalse;
char com_errorMessage[MAXPRINTMSG];
void Com_WriteConfig_f( void );
void CIN_CloseAllVideos( void );
//============================================================================
static char *rd_buffer;
static int rd_buffersize;
static void (*rd_flush)( char *buffer );
void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) )
{
if (!buffer || !buffersize || !flush)
return;
rd_buffer = buffer;
rd_buffersize = buffersize;
rd_flush = flush;
*rd_buffer = 0;
}
void Com_EndRedirect (void)
{
if ( rd_flush ) {
rd_flush(rd_buffer);
}
rd_buffer = NULL;
rd_buffersize = 0;
rd_flush = NULL;
}
/*
=============
Com_Printf
Both client and server can use this, and it will output
to the appropriate place.
A raw string should NEVER be passed as fmt, because of "%f" type crashers.
=============
*/
void QDECL Com_Printf( const char *fmt, ... ) {
va_list argptr;
char msg[MAXPRINTMSG];
static qboolean opening_qconsole = qfalse;
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
if ( rd_buffer ) {
if ((strlen (msg) + strlen(rd_buffer)) > (rd_buffersize - 1)) {
rd_flush(rd_buffer);
*rd_buffer = 0;
}
Q_strcat(rd_buffer, rd_buffersize, msg);
// TTimo nooo .. that would defeat the purpose
//rd_flush(rd_buffer);
//*rd_buffer = 0;
return;
}
#ifndef DEDICATED
CL_ConsolePrint( msg );
#endif
// echo to dedicated console and early console
Sys_Print( msg );
// logfile
if ( com_logfile && com_logfile->integer ) {
// TTimo: only open the qconsole.log if the filesystem is in an initialized state
// also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
if ( !logfile && FS_Initialized() && !opening_qconsole) {
struct tm *newtime;
time_t aclock;
opening_qconsole = qtrue;
time( &aclock );
newtime = localtime( &aclock );
logfile = FS_FOpenFileWrite( "qconsole.log" );
if(logfile)
{
Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
if ( com_logfile->integer > 1 )
{
// force it to not buffer so we get valid
// data even if we are crashing
FS_ForceFlush(logfile);
}
}
else
{
Com_Printf("Opening qconsole.log failed!\n");
Cvar_SetValue("logfile", 0);
}
opening_qconsole = qfalse;
}
if ( logfile && FS_Initialized()) {
FS_Write(msg, strlen(msg), logfile);
}
}
}
/*
================
Com_DPrintf
A Com_Printf that only shows up if the "developer" cvar is set
================
*/
void QDECL Com_DPrintf( const char *fmt, ...) {
va_list argptr;
char msg[MAXPRINTMSG];
if ( !com_developer || !com_developer->integer ) {
return; // don't confuse non-developers with techie stuff...
}
va_start (argptr,fmt);
Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
va_end (argptr);
Com_Printf ("%s", msg);
}
/*
=============
Com_Error
Both client and server can use this, and it will
do the appropriate thing.
=============
*/
void QDECL Com_Error( int code, const char *fmt, ... ) {
va_list argptr;
static int lastErrorTime;
static int errorCount;
int currentTime;
qboolean restartClient;
if(com_errorEntered)
Sys_Error("recursive error after: %s", com_errorMessage);
com_errorEntered = qtrue;
Cvar_Set("com_errorCode", va("%i", code));
// when we are running automated scripts, make sure we
// know if anything failed
if ( com_buildScript && com_buildScript->integer ) {
code = ERR_FATAL;
}
// if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
currentTime = Sys_Milliseconds();
if ( currentTime - lastErrorTime < 100 ) {
if ( ++errorCount > 3 ) {
code = ERR_FATAL;
}
} else {
errorCount = 0;
}
lastErrorTime = currentTime;
va_start (argptr,fmt);
Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage),fmt,argptr);
va_end (argptr);
if (code != ERR_DISCONNECT && code != ERR_NEED_CD)
Cvar_Set("com_errorMessage", com_errorMessage);
restartClient = com_gameClientRestarting && !( com_cl_running && com_cl_running->integer );
com_gameRestarting = qfalse;
com_gameClientRestarting = qfalse;
if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server disconnected" );
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory( );
VM_Forced_Unload_Done();
// make sure we can get at our local stuff
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp (abortframe, -1);
} else if (code == ERR_DROP) {
Com_Printf ("********************\nERROR: %s\n********************\n", com_errorMessage);
VM_Forced_Unload_Start();
SV_Shutdown (va("Server crashed: %s", com_errorMessage));
if ( restartClient ) {
CL_Init();
}
CL_Disconnect( qtrue );
CL_FlushMemory( );
VM_Forced_Unload_Done();
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp (abortframe, -1);
} else if ( code == ERR_NEED_CD ) {
VM_Forced_Unload_Start();
SV_Shutdown( "Server didn't have CD" );
if ( restartClient ) {
CL_Init();
}
if ( com_cl_running && com_cl_running->integer ) {
CL_Disconnect( qtrue );
CL_FlushMemory( );
VM_Forced_Unload_Done();
CL_CDDialog();
} else {
Com_Printf("Server didn't have CD\n" );
VM_Forced_Unload_Done();
}
FS_PureServerSetLoadedPaks("", "");
com_errorEntered = qfalse;
longjmp (abortframe, -1);
} else {
VM_Forced_Unload_Start();
CL_Shutdown(va("Client fatal crashed: %s", com_errorMessage), qtrue, qtrue);
SV_Shutdown(va("Server fatal crashed: %s", com_errorMessage));
VM_Forced_Unload_Done();
}
Com_Shutdown ();
Sys_Error ("%s", com_errorMessage);
}
/*
=============
Com_Quit_f
Both client and server can use this, and it will
do the appropriate things.
=============
*/
void Com_Quit_f( void ) {
// don't try to shutdown if we are in a recursive error
char *p = Cmd_Args( );
if ( !com_errorEntered ) {
// Some VMs might execute "quit" command directly,
// which would trigger an unload of active VM error.
// Sys_Quit will kill this process anyways, so
// a corrupt call stack makes no difference
VM_Forced_Unload_Start();
SV_Shutdown(p[0] ? p : "Server quit");
CL_Shutdown(p[0] ? p : "Client quit", qtrue, qtrue);
VM_Forced_Unload_Done();
Com_Shutdown ();
FS_Shutdown(qtrue);
}
Sys_Quit ();
}
/*
============================================================================
COMMAND LINE FUNCTIONS
+ characters separate the commandLine string into multiple console
command lines.
All of these are valid:
quake3 +set test blah +map test
quake3 set test blah+map test
quake3 set test blah + map test
============================================================================
*/
#define MAX_CONSOLE_LINES 32
int com_numConsoleLines;
char *com_consoleLines[MAX_CONSOLE_LINES];
/*
==================
Com_ParseCommandLine
Break it up into multiple console lines
==================
*/
void Com_ParseCommandLine( char *commandLine ) {
int inq = 0;
com_consoleLines[0] = commandLine;
com_numConsoleLines = 1;
while ( *commandLine ) {
if (*commandLine == '"') {
inq = !inq;
}
// look for a + separating character
// if commandLine came from a file, we might have real line seperators
if ( (*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r' ) {
if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
return;
}
com_consoleLines[com_numConsoleLines] = commandLine + 1;
com_numConsoleLines++;
*commandLine = 0;
}
commandLine++;
}
}
/*
===================
Com_SafeMode
Check for "safe" on the command line, which will
skip loading of q3config.cfg
===================
*/
qboolean Com_SafeMode( void ) {
int i;
for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( !Q_stricmp( Cmd_Argv(0), "safe" )
|| !Q_stricmp( Cmd_Argv(0), "cvar_restart" ) ) {
com_consoleLines[i][0] = 0;
return qtrue;
}
}
return qfalse;
}
/*
===============
Com_StartupVariable
Searches for command line parameters that are set commands.
If match is not NULL, only that cvar will be looked for.
That is necessary because cddir and basedir need to be set
before the filesystem is started, but all other sets should
be after execing the config and default.
===============
*/
void Com_StartupVariable( const char *match ) {
int i;
char *s;
for (i=0 ; i < com_numConsoleLines ; i++) {
Cmd_TokenizeString( com_consoleLines[i] );
if ( strcmp( Cmd_Argv(0), "set" ) ) {
continue;
}
s = Cmd_Argv(1);
if(!match || !strcmp(s, match))
{
if(Cvar_Flags(s) == CVAR_NONEXISTENT)
Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED);
else
Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse);
}
}
}
/*
=================
Com_AddStartupCommands
Adds command line parameters as script statements
Commands are separated by + signs
Returns qtrue if any late commands were added, which
will keep the demoloop from immediately starting
=================
*/
qboolean Com_AddStartupCommands( void ) {
int i;
qboolean added;
added = qfalse;
// quote every token, so args with semicolons can work
for (i=0 ; i < com_numConsoleLines ; i++) {
if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
continue;
}
// set commands already added with Com_StartupVariable
if ( !Q_stricmpn( com_consoleLines[i], "set ", 4 ) ) {
continue;
}
added = qtrue;
Cbuf_AddText( com_consoleLines[i] );
Cbuf_AddText( "\n" );
}
return added;
}
//============================================================================
void Info_Print( const char *s ) {
char key[BIG_INFO_KEY];
char value[BIG_INFO_VALUE];
char *o;
int l;
if (*s == '\\')
s++;
while (*s)
{
o = key;
while (*s && *s != '\\')
*o++ = *s++;
l = o - key;
if (l < 20)
{
Com_Memset (o, ' ', 20-l);
key[20] = 0;
}
else
*o = 0;
Com_Printf ("%s ", key);
if (!*s)
{
Com_Printf ("MISSING VALUE\n");
return;
}
o = value;
s++;
while (*s && *s != '\\')
*o++ = *s++;
*o = 0;
if (*s)
s++;
Com_Printf ("%s\n", value);
}
}
/*
============
Com_StringContains
============
*/
char *Com_StringContains(char *str1, char *str2, int casesensitive) {
int len, i, j;
len = strlen(str1) - strlen(str2);
for (i = 0; i <= len; i++, str1++) {
for (j = 0; str2[j]; j++) {
if (casesensitive) {
if (str1[j] != str2[j]) {
break;
}
}
else {
if (toupper(str1[j]) != toupper(str2[j])) {
break;
}
}
}
if (!str2[j]) {
return str1;
}
}
return NULL;
}
/*
============
Com_Filter
============
*/
int Com_Filter(char *filter, char *name, int casesensitive)
{
char buf[MAX_TOKEN_CHARS];
char *ptr;
int i, found;
while(*filter) {
if (*filter == '*') {
filter++;
for (i = 0; *filter; i++) {
if (*filter == '*' || *filter == '?') break;
buf[i] = *filter;
filter++;
}
buf[i] = '\0';
if (strlen(buf)) {
ptr = Com_StringContains(name, buf, casesensitive);
if (!ptr) return qfalse;
name = ptr + strlen(buf);
}
}
else if (*filter == '?') {
filter++;
name++;
}
else if (*filter == '[' && *(filter+1) == '[') {
filter++;
}
else if (*filter == '[') {
filter++;
found = qfalse;
while(*filter && !found) {
if (*filter == ']' && *(filter+1) != ']') break;
if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) {
if (casesensitive) {
if (*name >= *filter && *name <= *(filter+2)) found = qtrue;
}
else {
if (toupper(*name) >= toupper(*filter) &&
toupper(*name) <= toupper(*(filter+2))) found = qtrue;
}
filter += 3;
}
else {
if (casesensitive) {
if (*filter == *name) found = qtrue;
}
else {
if (toupper(*filter) == toupper(*name)) found = qtrue;
}
filter++;
}
}
if (!found) return qfalse;
while(*filter) {
if (*filter == ']' && *(filter+1) != ']') break;
filter++;
}
filter++;
name++;
}
else {
if (casesensitive) {
if (*filter != *name) return qfalse;
}
else {
if (toupper(*filter) != toupper(*name)) return qfalse;
}
filter++;
name++;
}
}
return qtrue;
}
/*
============
Com_FilterPath
============
*/
int Com_FilterPath(char *filter, char *name, int casesensitive)
{
int i;
char new_filter[MAX_QPATH];
char new_name[MAX_QPATH];
for (i = 0; i < MAX_QPATH-1 && filter[i]; i++) {
if ( filter[i] == '\\' || filter[i] == ':' ) {
new_filter[i] = '/';
}
else {
new_filter[i] = filter[i];
}
}
new_filter[i] = '\0';
for (i = 0; i < MAX_QPATH-1 && name[i]; i++) {
if ( name[i] == '\\' || name[i] == ':' ) {
new_name[i] = '/';
}
else {
new_name[i] = name[i];
}
}
new_name[i] = '\0';
return Com_Filter(new_filter, new_name, casesensitive);
}
/*
================
Com_RealTime
================
*/
int Com_RealTime(qtime_t *qtime) {
time_t t;
struct tm *tms;
t = time(NULL);
if (!qtime)
return t;
tms = localtime(&t);
if (tms) {
qtime->tm_sec = tms->tm_sec;
qtime->tm_min = tms->tm_min;
qtime->tm_hour = tms->tm_hour;
qtime->tm_mday = tms->tm_mday;
qtime->tm_mon = tms->tm_mon;
qtime->tm_year = tms->tm_year;
qtime->tm_wday = tms->tm_wday;
qtime->tm_yday = tms->tm_yday;
qtime->tm_isdst = tms->tm_isdst;
}
return t;
}
/*
==============================================================================
ZONE MEMORY ALLOCATION
There is never any space between memblocks, and there will never be two
contiguous free memblocks.
The rover can be left pointing at a non-empty block
The zone calls are pretty much only used for small strings and structures,
all big things are allocated on the hunk.
==============================================================================
*/
#define ZONEID 0x1d4a11
#define MINFRAGMENT 64
typedef struct zonedebug_s {
char *label;
char *file;
int line;
int allocSize;
} zonedebug_t;
typedef struct memblock_s {
int size; // including the header and possibly tiny fragments
int tag; // a tag of 0 is a free block
struct memblock_s *next, *prev;
int id; // should be ZONEID
#ifdef ZONE_DEBUG
zonedebug_t d;
#endif
} memblock_t;
typedef struct {
int size; // total bytes malloced, including header
int used; // total bytes used
memblock_t blocklist; // start / end cap for linked list
memblock_t *rover;
} memzone_t;
// main zone for all "dynamic" memory allocation
static memzone_t *mainzone;
// we also have a small zone for small allocations that would only
// fragment the main zone (think of cvar and cmd strings)
static memzone_t *smallzone;
static void Z_CheckHeap( void );
/*
========================
Z_ClearZone
========================
*/
static void Z_ClearZone( memzone_t *zone, int size ) {
memblock_t *block;
// set the entire zone to one free block
zone->blocklist.next = zone->blocklist.prev = block =
(memblock_t *)( (byte *)zone + sizeof(memzone_t) );
zone->blocklist.tag = 1; // in use block
zone->blocklist.id = 0;
zone->blocklist.size = 0;
zone->rover = block;
zone->size = size;
zone->used = 0;
block->prev = block->next = &zone->blocklist;
block->tag = 0; // free block
block->id = ZONEID;
block->size = size - sizeof(memzone_t);
}
/*
========================
Z_AvailableZoneMemory
========================
*/
static int Z_AvailableZoneMemory( memzone_t *zone ) {
return zone->size - zone->used;
}
/*
========================
Z_AvailableMemory
========================
*/
int Z_AvailableMemory( void ) {
return Z_AvailableZoneMemory( mainzone );
}
/*
========================
Z_Free
========================
*/
void Z_Free( void *ptr ) {
memblock_t *block, *other;
memzone_t *zone;
if (!ptr) {
Com_Error( ERR_DROP, "Z_Free: NULL pointer" );
}
block = (memblock_t *) ( (byte *)ptr - sizeof(memblock_t));
if (block->id != ZONEID) {
Com_Error( ERR_FATAL, "Z_Free: freed a pointer without ZONEID" );
}
if (block->tag == 0) {
Com_Error( ERR_FATAL, "Z_Free: freed a freed pointer" );
}
// if static memory
if (block->tag == TAG_STATIC) {
return;
}
// check the memory trash tester
if ( *(int *)((byte *)block + block->size - 4 ) != ZONEID ) {
Com_Error( ERR_FATAL, "Z_Free: memory block wrote past end" );
}
if (block->tag == TAG_SMALL) {
zone = smallzone;
}
else {
zone = mainzone;
}
zone->used -= block->size;
// set the block to something that should cause problems
// if it is referenced...
Com_Memset( ptr, 0xaa, block->size - sizeof( *block ) );
block->tag = 0; // mark as free
other = block->prev;
if (!other->tag) {
// merge with previous free block
other->size += block->size;
other->next = block->next;
other->next->prev = other;
if (block == zone->rover) {
zone->rover = other;
}
block = other;
}
zone->rover = block;
other = block->next;
if ( !other->tag ) {
// merge the next free block onto the end
block->size += other->size;
block->next = other->next;
block->next->prev = block;
}
}
/*
================
Z_FreeTags
================
*/
void Z_FreeTags( int tag ) {
memzone_t *zone;
if ( tag == TAG_SMALL ) {
zone = smallzone;
}
else {
zone = mainzone;
}
// use the rover as our pointer, because
// Z_Free automatically adjusts it
zone->rover = zone->blocklist.next;
do {
if ( zone->rover->tag == tag ) {
Z_Free( (void *)(zone->rover + 1) );
continue;
}
zone->rover = zone->rover->next;
} while ( zone->rover != &zone->blocklist );
}
/*
================
Z_TagMalloc
================
*/
#ifdef ZONE_DEBUG
void *Z_TagMallocDebug( int size, int tag, char *label, char *file, int line ) {
int allocSize;
#else
void *Z_TagMalloc( int size, int tag ) {
#endif
int extra;
memblock_t *start, *rover, *new, *base;
memzone_t *zone;
if (!tag) {
Com_Error( ERR_FATAL, "Z_TagMalloc: tried to use a 0 tag" );
}
if ( tag == TAG_SMALL ) {
zone = smallzone;
}
else {
zone = mainzone;
}
#ifdef ZONE_DEBUG
allocSize = size;
#endif
//
// scan through the block list looking for the first free block
// of sufficient size
//
size += sizeof(memblock_t); // account for size of block header
size += 4; // space for memory trash tester
size = PAD(size, sizeof(intptr_t)); // align to 32/64 bit boundary
base = rover = zone->rover;
start = base->prev;
do {
if (rover == start) {
// scaned all the way around the list
#ifdef ZONE_DEBUG
Z_LogHeap();
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone: %s, line: %d (%s)",
size, zone == smallzone ? "small" : "main", file, line, label);
#else
Com_Error(ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone",