-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathplatform_posix.cpp
1082 lines (903 loc) · 25.7 KB
/
platform_posix.cpp
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 Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "tier0/platform.h"
#include "tier0/vcrmode.h"
#include "tier0/memalloc.h"
#include "tier0/dbg.h"
#include <algorithm>
#include <vector>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#if defined(OSX) || defined(PLATFORM_BSD)
# ifdef PLATFORM_BSD
# include <sys/proc.h>
# include <sys/user.h>
# else
# include <mach/mach.h>
# include <mach/mach_time.h>
# endif
#include <stdbool.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#ifdef LINUX
#include <time.h>
#include <fcntl.h>
#endif
#ifdef ANDROID
#include <linux/stat.h>
#endif
#include "tier0/memdbgon.h"
// Benchmark mode uses this heavy-handed method
// *** WARNING ***. On Linux gettimeofday returns the system's best guess at
// actual wall clock time and this can go backwards. You need to use
// clock_gettime( CLOCK_MONOTONIC ... ) if this isn't what you want.
// If you want to try using rdtsc for Plat_FloatTime(), enable USE_RDTSC_FOR_FLOATTIME:
//
// Make sure you know what you're doing. This was disabled due to the long startup time, and
// in our testing, even though constant_tsc was set, we couldn't rely on the
// max frequency result returned from CalculateCPUFreq() (ie /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq).
//
// #define USE_RDTSC_FOR_FLOATTIME
extern VCRMode_t g_VCRMode;
static bool g_bBenchmarkMode = false;
static double g_FakeBenchmarkTime = 0;
static double g_FakeBenchmarkTimeInc = 1.0 / 66.0;
#ifdef USE_RDTSC_FOR_FLOATTIME
static bool s_bTimeInitted;
static bool s_bUseRDTSC;
static uint64 s_nRDTSCBase;
static float s_flRDTSCToMicroSeconds;
static double s_flRDTSCScale;
#endif // USE_RDTSC_FOR_FLOATTIME
bool Plat_IsInBenchmarkMode()
{
return g_bBenchmarkMode;
}
void Plat_SetBenchmarkMode( bool bBenchmark )
{
g_bBenchmarkMode = bBenchmark;
}
#define N_ITERATIONS_OF_RDTSC_TEST_TO_RUN 5 // should be odd
#define TEST_RDTSC_FLOATTIME 0
size_t ApproximateProcessMemoryUsage( void )
{
/*
From http://man7.org/linux/man-pages/man5/proc.5.html:
/proc/[pid]/statm
Provides information about memory usage, measured in pages.
The columns are:
size (1) total program size
(same as VmSize in /proc/[pid]/status)
resident (2) resident set size
(same as VmRSS in /proc/[pid]/status)
share (3) shared pages (i.e., backed by a file)
text (4) text (code)
lib (5) library (unused in Linux 2.6)
data (6) data + stack
dt (7) dirty pages (unused in Linux 2.6)
*/
// This returns the resident memory size (RES column in 'top') in bytes.
size_t nRet = 0;
FILE *pFile = fopen( "/proc/self/statm", "r" );
if ( pFile )
{
size_t nSize, nResident, nShare, nText, nLib_Unused, nDataPlusStack, nDt_Unused;
if ( fscanf( pFile, "%zu %zu %zu %zu %zu %zu %zu", &nSize, &nResident, &nShare, &nText, &nLib_Unused, &nDataPlusStack, &nDt_Unused ) >= 2 )
{
nRet = 4096 * nResident;
}
fclose( pFile );
}
return nRet;
}
#ifdef USE_RDTSC_FOR_FLOATTIME
static void InitTimeSystem( void )
{
s_bTimeInitted = true;
// now, see if we can use rdtsc instead. If this is one of the chips with a separate constant clock for rdtsc, we can
FILE *pCpuInfo = fopen( "/proc/cpuinfo", "r" );
if ( pCpuInfo )
{
bool bAnyBadCores = false;
char lbuf[2048];
while( fgets( lbuf, sizeof( lbuf ), pCpuInfo ) )
{
if ( memcmp( lbuf, "flags", 4 ) == 0 )
{
if ( ! strstr( lbuf, "constant_tsc" ) )
{
bAnyBadCores = true;
break;
}
}
}
fclose( pCpuInfo );
if ( ! bAnyBadCores )
{
// this system appears to have the proper cpu setup to use rdtsc from reliable timing. Let's either read the cpu frequency from an
// environment variable, or time it ourselves
char const *pEnv = getenv( "RDTSC_FREQUENCY" );
if ( pEnv )
{
// the environment variable is allowed to hold either a benchmark result, or a string such as "disable"
if ( pEnv && ( ( pEnv[0] > '9' ) || ( pEnv[0] < '0' ) ) )
return; // leave rdtsc disabled
// the variable holds the number of ticks per microsecond
s_flRDTSCToMicroSeconds = atof( pEnv );
// sanity check
if ( s_flRDTSCToMicroSeconds > 1.0 )
{
s_bUseRDTSC = true;
s_flRDTSCScale = 1.0 / ( 1000.0 * 1000.0 * s_flRDTSCToMicroSeconds );
s_nRDTSCBase = Plat_Rdtsc();
return;
}
}
else
{
printf( "Running a benchmark to measure system clock frequency...\n" );
// run n iterations and use the median
double flRDTSCToMicroSeconds[N_ITERATIONS_OF_RDTSC_TEST_TO_RUN];
for( int i = 0; i < ARRAYSIZE( flRDTSCToMicroSeconds ) ; i++ )
{
uint64 stime = Plat_Rdtsc();
struct timeval stimeval;
gettimeofday( &stimeval, NULL );
sleep( 1 );
uint64 etime = Plat_Rdtsc() - stime;
struct timeval etimeval;
gettimeofday( &etimeval, NULL );
// subtract timevals to get elapsed microseconds
struct timeval elapsedtimeval;
timersub( &etimeval, &stimeval, &elapsedtimeval );
uint64 nUs = 1000000 * elapsedtimeval.tv_sec + elapsedtimeval.tv_usec;
flRDTSCToMicroSeconds[ i ] = ( etime / nUs );
}
std::make_heap( flRDTSCToMicroSeconds, flRDTSCToMicroSeconds + ARRAYSIZE( flRDTSCToMicroSeconds ) - 1 );
std::sort_heap( flRDTSCToMicroSeconds, flRDTSCToMicroSeconds + ARRAYSIZE( flRDTSCToMicroSeconds ) - 1 );
s_flRDTSCToMicroSeconds = flRDTSCToMicroSeconds[ARRAYSIZE( flRDTSCToMicroSeconds ) / 2 ];
s_flRDTSCScale = 1.0 / ( 1000.0 * 1000.0 * s_flRDTSCToMicroSeconds );
printf( "Finished RDTSC test. To prevent the startup delay from this benchmark, set the environment variable RDTSC_FREQUENCY to %f on this system."
" This value is dependent upon the CPU clock speed and architecture and should be determined separately for each server. The use of this mechanism"
" for timing can be disabled by setting RDTSC_FREQUENCY to 'disabled'.\n",
s_flRDTSCToMicroSeconds );
s_nRDTSCBase = Plat_Rdtsc();
s_bUseRDTSC = true;
#if TEST_RDTSC_FLOATTIME
printf( "RDTSC test results:\n" );
for( int i = 0; i < ARRAYSIZE( flRDTSCToMicroSeconds ); i++ )
printf(" [%d] = %f\n", i, flRDTSCToMicroSeconds[i] );
printf( "scale factor = %f\n", s_flRDTSCScale );
uint64 srdtsc_time = Plat_Rdtsc();
for( int i = 0; i < 1000 * 1000 * 10; i++ )
{
float p = Plat_FloatTime();
}
printf( "slow = %lld\n", Plat_Rdtsc() - srdtsc_time );
// now, run a benchmark to see how much this optimization buys us
srdtsc_time = Plat_Rdtsc();
for( int i = 0; i < 1000 * 1000 * 10; i++ )
{
float p = Plat_FloatTime();
}
printf( "sfast = %lld\n", Plat_Rdtsc() - srdtsc_time );
#endif
}
}
}
}
static FORCEINLINE void TestTimeSystem( void )
{
#if TEST_RDTSC_FLOATTIME
// now, test that plat_float time actually works
for( int t = 0 ; t < 5; t++ )
{
float flStartT = Plat_FloatTime();
struct timeval stime;
gettimeofday( &stime, NULL );
sleep( 5 );
float flElapsedT = Plat_FloatTime() - flStartT;
struct timeval etime;
gettimeofday( &etime, NULL );
struct timeval dtime;
timersub( &etime, &stime, &dtime );
printf( " plat_float time says %f elapsed. gettimeofday says %f\n",
flElapsedT, dtime.tv_sec + dtime.tv_usec / 1000000.0 );
}
#endif
}
#endif // USE_RDTSC_FOR_FLOATTIME
double Plat_FloatTime()
{
if ( g_bBenchmarkMode )
{
g_FakeBenchmarkTime += g_FakeBenchmarkTimeInc;
return g_FakeBenchmarkTime;
}
#ifdef OSX
// OSX
static uint64 start_time = 0;
static mach_timebase_info_data_t sTimebaseInfo;
static double conversion = 0.0;
if ( !start_time )
{
start_time = mach_absolute_time();
mach_timebase_info(&sTimebaseInfo);
conversion = 1e-9 * (double) sTimebaseInfo.numer / (double) sTimebaseInfo.denom;
}
uint64 now = mach_absolute_time();
return ( now - start_time ) * conversion;
#else
// Linux
static struct timespec start_time = { 0, 0 };
static bool bInitialized = false;
if ( !bInitialized )
{
bInitialized = true;
clock_gettime( CLOCK_MONOTONIC, &start_time );
}
struct timespec now;
clock_gettime( CLOCK_MONOTONIC, &now );
return ( now.tv_sec - start_time.tv_sec ) + ( now.tv_nsec * 1e-9 );
#ifdef USE_RDTSC_FOR_FLOATTIME
if ( ! s_bTimeInitted )
{
InitTimeSystem();
TestTimeSystem();
}
if ( s_bUseRDTSC )
{
uint64 nTicks = Plat_Rdtsc() - s_nRDTSCBase;
return ( (double) nTicks) * s_flRDTSCScale;
}
else
{
struct timeval tp;
gettimeofday( &tp, NULL );
if (VCRGetMode() == VCR_Disabled)
return (( tp.tv_sec - s_nSecBase ) + tp.tv_usec / 1000000.0 );
return VCRHook_Sys_FloatTime( ( tp.tv_sec - s_nSecBase ) + tp.tv_usec / 1000000.0 );
}
#endif // USE_RDTSC_FOR_FLOATTIME
#endif
}
unsigned int Plat_MSTime()
{
if ( g_bBenchmarkMode )
{
g_FakeBenchmarkTime += g_FakeBenchmarkTimeInc;
return (unsigned int)(g_FakeBenchmarkTime * 1000.0);
}
#ifdef USE_RDTSC_FOR_FLOATTIME
if ( ! s_bTimeInitted )
{
InitTimeSystem();
TestTimeSystem();
}
if ( s_bUseRDTSC )
{
uint64 nTicks = Plat_Rdtsc() - s_nRDTSCBase;
return 1000.0 * nTicks * s_flRDTSCScale;
}
else
#endif // USE_RDTSC_FOR_FLOATTIME
{
return ( uint )( Plat_FloatTime() * 1000 );
}
}
uint64 Plat_USTime()
{
if ( g_bBenchmarkMode )
{
g_FakeBenchmarkTime += g_FakeBenchmarkTimeInc;
return (unsigned int)(g_FakeBenchmarkTime * 1000000.0);
}
#ifdef USE_RDTSC_FOR_FLOATTIME
if ( ! s_bTimeInitted )
{
InitTimeSystem();
TestTimeSystem();
}
if ( s_bUseRDTSC )
{
uint64 nTicks = Plat_Rdtsc() - s_nRDTSCBase;
return 1000000.0 * nTicks * s_flRDTSCScale;
}
else
#endif // USE_RDTSC_FOR_FLOATTIME
{
return ( uint64 )( Plat_FloatTime() * 1000000 );
}
}
// Wraps the thread-safe versions of ctime. buf must be at least 26 bytes
char *Plat_ctime( const time_t *timep, char *buf, size_t bufsize )
{
return ctime_r( timep, buf );
}
// Wraps the thread-safe versions of gmtime
struct tm *Plat_gmtime( const time_t *timep, struct tm *result )
{
return gmtime_r( timep, result );
}
time_t Plat_timegm( struct tm *timeptr )
{
return timegm( timeptr );
}
// Wraps the thread-safe versions of localtime
struct tm *Plat_localtime( const time_t *timep, struct tm *result )
{
return localtime_r( timep, result );
}
bool vtune( bool resume )
{
return 0;
}
// -------------------------------------------------------------------------------------------------- //
// Memory stuff.
// -------------------------------------------------------------------------------------------------- //
#ifndef NO_HOOK_MALLOC
PLATFORM_INTERFACE void Plat_DefaultAllocErrorFn( unsigned long size )
{
}
typedef void (*Plat_AllocErrorFn)( unsigned long size );
Plat_AllocErrorFn g_AllocError = Plat_DefaultAllocErrorFn;
PLATFORM_INTERFACE void* Plat_Alloc( unsigned long size )
{
void *pRet = MemAlloc_Alloc( size );
if ( pRet )
{
return pRet;
}
else
{
g_AllocError( size );
return 0;
}
}
PLATFORM_INTERFACE void* Plat_Realloc( void *ptr, unsigned long size )
{
void *pRet = g_pMemAlloc->Realloc( ptr, size );
if ( pRet )
{
return pRet;
}
else
{
g_AllocError( size );
return 0;
}
}
PLATFORM_INTERFACE void Plat_Free( void *ptr )
{
g_pMemAlloc->Free( ptr );
}
PLATFORM_INTERFACE void Plat_SetAllocErrorFn( Plat_AllocErrorFn fn )
{
g_AllocError = fn;
}
#endif // !NO_HOOK_MALLOC
#if defined( OSX ) || defined(PLATFORM_BSD)
// From the Apple tech note: http://developer.apple.com/library/mac/#qa/qa1361/_index.html
bool Plat_IsInDebugSession()
{
static int s_IsInDebugSession;
int junk;
struct kinfo_proc info;
size_t size;
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
#ifndef PLATFORM_BSD
info.kp_proc.p_flag = 0;
#endif
size = sizeof(info);
junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
// We're being debugged if the P_TRACED flag is set.
#ifdef PLATFORM_BSD
s_IsInDebugSession = info.ki_flag & P_TRACED;
#else
s_IsInDebugSession = info.kp_proc.p_flag & P_TRACED;
#endif
return !!s_IsInDebugSession;
}
#elif defined( LINUX )
bool Plat_IsInDebugSession()
{
// For linux: http://stackoverflow.com/questions/3596781/detect-if-gdb-is-running
// Don't use "if (ptrace(PTRACE_TRACEME, 0, NULL, 0) == -1)" as it means debuggers can't attach.
// Other solutions they mention involve forking. Ugh.
//
// Good solution from Pierre-Loup: Check TracerPid in /proc/self/status.
// from "man proc"
// TracerPid: PID of process tracing this process (0 if not being traced).
int tracerpid = -1;
int fd = open( "/proc/self/status", O_RDONLY, S_IRUSR );
if( fd >= 0 )
{
char buf[ 1024 ];
static const char s_TracerPid[] = "TracerPid:";
int len = read( fd, buf, sizeof( buf ) - 1 );
if ( len > 0 )
{
buf[ len ] = 0;
const char *str = strstr( buf, s_TracerPid );
tracerpid = str ? atoi( str + sizeof( s_TracerPid ) ) : -1;
}
close( fd );
}
return ( tracerpid > 0 );
}
#endif // defined( LINUX )
void Plat_DebugString( const char * psz )
{
printf( "%s", psz );
}
static char g_CmdLine[ 2048 ];
PLATFORM_INTERFACE void Plat_SetCommandLine( const char *cmdLine )
{
strncpy( g_CmdLine, cmdLine, sizeof(g_CmdLine) );
g_CmdLine[ sizeof(g_CmdLine) -1 ] = 0;
}
PLATFORM_INTERFACE const tchar *Plat_GetCommandLine()
{
#ifdef LINUX
if( !g_CmdLine[ 0 ] )
{
FILE *fp = fopen( "/proc/self/cmdline", "rb" );
if( fp )
{
size_t nCharRead = 0;
// -1 to leave room for the '\0'
nCharRead = fread( g_CmdLine, sizeof( g_CmdLine[0] ), ARRAYSIZE( g_CmdLine ) - 1, fp );
if ( feof( fp ) && !ferror( fp ) ) // Should have read the whole command line without error
{
Assert ( nCharRead < ARRAYSIZE( g_CmdLine ) );
for( uint i = 0; i < nCharRead; i++ )
{
if( g_CmdLine[ i ] == '\0' )
g_CmdLine[ i ] = ' ';
}
g_CmdLine[ nCharRead ] = '\0';
}
fclose( fp );
}
Assert( g_CmdLine[ 0 ] );
}
#endif // LINUX
return g_CmdLine;
}
PLATFORM_INTERFACE const char *Plat_GetCommandLineA()
{
return Plat_GetCommandLine();
}
PLATFORM_INTERFACE bool GetMemoryInformation( MemoryInformation *pOutMemoryInfo )
{
#if defined( LINUX ) || defined( OSX ) || defined(PLATFORM_BSD)
return false;
#else
#error "Need to fill out GetMemoryInformation or at least return false for this platform"
#endif
}
PLATFORM_INTERFACE bool Is64BitOS()
{
#if defined OSX
return true;
#elif defined(LINUX) || defined(PLATFORM_BSD)
FILE *pp = popen( "uname -m", "r" );
if ( pp != NULL )
{
char rgchArchString[256];
fgets( rgchArchString, sizeof( rgchArchString ), pp );
pclose( pp );
if ( !strncasecmp( rgchArchString, "x86_64", strlen( "x86_64" ) ) )
return true;
}
#else
Assert( !"implement Is64BitOS" );
#endif
return false;
}
PLATFORM_INTERFACE void Plat_ExitProcess( int nCode )
{
_exit( nCode );
}
static int s_nWatchDogTimerTimeScale = 0;
static bool s_bInittedWD = false;
static int s_WatchdogTime = 0;
static Plat_WatchDogHandlerFunction_t s_pWatchDogHandlerFunction;
static void InitWatchDogTimer( void )
{
if( !strstr( g_CmdLine, "-nowatchdog" ) )
{
#ifdef _DEBUG
s_nWatchDogTimerTimeScale = 10; // debug is slow
#else
s_nWatchDogTimerTimeScale = 1;
#endif
}
}
// SIGALRM handler. Used by Watchdog timer code.
static void WatchDogHandler( int s )
{
Plat_DebugString( "WatchDog! Server took too long to process (probably infinite loop).\n" );
DebuggerBreakIfDebugging();
if ( s_pWatchDogHandlerFunction )
{
s_pWatchDogHandlerFunction();
}
else
{
// force a crash
abort();
}
}
// watchdog timer support
PLATFORM_INTERFACE void Plat_BeginWatchdogTimer( int nSecs )
{
if ( !s_bInittedWD )
{
s_bInittedWD = true;
InitWatchDogTimer();
}
nSecs *= s_nWatchDogTimerTimeScale;
nSecs = MIN( nSecs, 5 * 60 ); // no more than 5 minutes no matter what
if ( nSecs )
{
s_WatchdogTime = nSecs;
signal( SIGALRM, WatchDogHandler );
alarm( nSecs );
}
}
PLATFORM_INTERFACE void Plat_EndWatchdogTimer( void )
{
alarm( 0 );
signal( SIGALRM, SIG_DFL );
s_WatchdogTime = 0;
}
PLATFORM_INTERFACE int Plat_GetWatchdogTime( void )
{
return s_WatchdogTime;
}
PLATFORM_INTERFACE void Plat_SetWatchdogHandlerFunction( Plat_WatchDogHandlerFunction_t function )
{
s_pWatchDogHandlerFunction = function;
}
#ifndef NO_HOOK_MALLOC
// memory logging this functionality is portable code, except for the way in which it hooks
// malloc/free. glibc contains the ability for the app to install hooks into malloc/free.
#ifdef OSX
#include <malloc/malloc.h>
#else
#include <malloc.h>
#endif
#include <tier1/utlintrusivelist.h>
#include <execinfo.h>
#include <tier1/utlvector.h>
#define MEMALLOC_HASHSIZE 8193
typedef uintp ptrint_t;
struct CLinuxMemStats
{
int nNumMallocs; // total every
int nNumFrees; // total
int nNumMallocsInUse;
int nTotalMallocInUse;
};
#define MAX_STACK_TRACEBACK 20
struct CLinuxMallocContext
{
CLinuxMallocContext *m_pNext;
void *pStackTraceBack[MAX_STACK_TRACEBACK];
int m_nCurrentAllocSize;
int m_nNumAllocsInUse;
int m_nMaximumSize;
int m_TotalNumAllocs;
int m_nLastAllocSize;
CLinuxMallocContext( void )
{
memset( this, 0, sizeof( *this ) );
}
};
static CUtlIntrusiveList<CLinuxMallocContext> s_ContextHash[MEMALLOC_HASHSIZE];
CLinuxMemStats g_LinuxMemStats;
struct RememberedAlloc_t
{
RememberedAlloc_t *m_pNext, *m_pPrev; // all addresses that hash to the same value are linked
CLinuxMallocContext *m_pAllocContext;
ptrint_t m_nAddress; // the address of the memory that came from malloc/realloc
size_t m_nSize;
void AdjustSize( size_t nsize )
{
int nDelta = nsize - m_nSize;
m_nSize = nsize;
m_pAllocContext->m_nCurrentAllocSize += nDelta;
m_pAllocContext->m_nMaximumSize = MAX( m_pAllocContext->m_nMaximumSize, m_pAllocContext->m_nCurrentAllocSize );
}
};
static inline int AddressHash( ptrint_t nAdr )
{
return ( nAdr % MEMALLOC_HASHSIZE );
}
static CUtlIntrusiveDList<RememberedAlloc_t> s_AddressData[MEMALLOC_HASHSIZE];
static struct RememberedAlloc_t *FindAddress( void *pAdr, int *pHash = NULL )
{
ptrint_t nAdr = ( ptrint_t ) pAdr;
int nHash = AddressHash( nAdr );
if ( pHash )
*pHash = nHash;
for( RememberedAlloc_t *i = s_AddressData[nHash].m_pHead; i; i = i->m_pNext )
{
if ( i->m_nAddress == nAdr )
return i;
}
return NULL;
}
#ifdef LINUX
static void *MallocHook( size_t, const void * );
static void FreeHook( void*, const void * );
static void *ReallocHook( void *ptr, size_t size, const void *caller );
static void RemoveHooks( void )
{
__malloc_hook = NULL;
__free_hook = NULL;
__realloc_hook = NULL;
}
static void InstallHooks( void )
{
__malloc_hook = MallocHook;
__free_hook = FreeHook;
__realloc_hook = ReallocHook;
}
#elif OSX || PLATFORM_BSD
static void RemoveHooks( void )
{
}
static void InstallHooks( void )
{
}
#else
#error
#endif
static void AddMemoryAllocation( void *pResult, size_t size )
{
if ( pResult )
{
g_LinuxMemStats.nNumMallocs++;
g_LinuxMemStats.nNumMallocsInUse++;
g_LinuxMemStats.nTotalMallocInUse += size;
RememberedAlloc_t *pNew = new RememberedAlloc_t;
pNew->m_nAddress = ( ptrint_t ) pResult;
pNew->m_nSize = size;
s_AddressData[AddressHash( pNew->m_nAddress )].AddToHead( pNew );
// now, find the stack traceback context for this call
void *pTraceBack[MAX_STACK_TRACEBACK];
int nNumGot = backtrace( pTraceBack, ARRAYSIZE( pTraceBack ) );
for( int n = MAX( 0, nNumGot - 1 ); n < MAX_STACK_TRACEBACK; n++ )
pTraceBack[n] = NULL;
uint32 nHash = 0;
for( int i = 0; i < MAX_STACK_TRACEBACK; i++ )
{
nHash = ( nHash * 3 ) + ( ( ptrint_t ) pTraceBack[i] );
}
nHash %= MEMALLOC_HASHSIZE;
CLinuxMallocContext *pFoundCtx = NULL;
// see if we have this context
for( CLinuxMallocContext *i = s_ContextHash[nHash].m_pHead; i ; i = i->m_pNext )
{
if ( memcmp( pTraceBack, i->pStackTraceBack, sizeof( pTraceBack ) ) == 0 )
{
pFoundCtx = i;
break;
}
}
if ( ! pFoundCtx )
{
pFoundCtx = new CLinuxMallocContext;
memcpy( pFoundCtx->pStackTraceBack, pTraceBack, sizeof( pTraceBack ) );
s_ContextHash[nHash].AddToHead( pFoundCtx );
}
pNew->m_pAllocContext = pFoundCtx;
pFoundCtx->m_nCurrentAllocSize += size;
pFoundCtx->m_nNumAllocsInUse++;
pFoundCtx->m_nMaximumSize = MAX( pFoundCtx->m_nCurrentAllocSize, pFoundCtx->m_nMaximumSize );
pFoundCtx->m_TotalNumAllocs++;
}
}
static CThreadFastMutex s_MemoryMutex;
static void *ReallocHook( void *ptr, size_t size, const void *caller )
{
AUTO_LOCK( s_MemoryMutex );
RemoveHooks();
void *nResult = realloc( ptr, size );
if ( ptr ) // did we have this memory before
{
int nHash;
RememberedAlloc_t *pBlock = FindAddress( ptr, &nHash );
if ( pBlock )
{
if ( ptr == nResult )
{
// it successfully alloced, just need to update size info, etc
pBlock->AdjustSize( size );
g_LinuxMemStats.nTotalMallocInUse += ( size - pBlock->m_nSize );
}
else
{
pBlock->m_pAllocContext->m_nCurrentAllocSize -= pBlock->m_nSize;
pBlock->m_pAllocContext->m_nNumAllocsInUse--;
s_AddressData[nHash].RemoveNode( pBlock ); // throw away this node
AddMemoryAllocation( nResult, size );
}
}
else
AddMemoryAllocation( nResult, size );
}
else
AddMemoryAllocation( nResult, size );
InstallHooks();
return nResult;
}
static void *MallocHook(size_t size, const void *caller)
{
// turn off hooking so we won't recurse
AUTO_LOCK( s_MemoryMutex );
RemoveHooks();
void *pResult = malloc (size);
// now, add this memory chunk to our list
AddMemoryAllocation( pResult, size );
InstallHooks();
return pResult;
}
static void FreeHook(void *ptr, const void *caller )
{
AUTO_LOCK( s_MemoryMutex );
RemoveHooks();
// call real free
free (ptr);
// look in our list
if ( ptr )
{
int nHash;
RememberedAlloc_t *pFound = FindAddress( ptr, &nHash );
if ( !pFound )
{
//printf(" free of unallocated adr %p (maybe)\n", ptr );
}
else
{
pFound->m_pAllocContext->m_nCurrentAllocSize -= pFound->m_nSize;
pFound->m_pAllocContext->m_nNumAllocsInUse--;
g_LinuxMemStats.nTotalMallocInUse -= pFound->m_nSize;
g_LinuxMemStats.nNumFrees++;
g_LinuxMemStats.nNumMallocsInUse--;
s_AddressData[nHash].RemoveNode( pFound );
delete pFound;
}
}
InstallHooks();
}
void EnableMemoryLogging( bool bOnOff )
{
if ( bOnOff )
{
InstallHooks();
#if 0
// simple test
char *p[10];
for( int i =0; i < 10; i++ )
p[i] = new char[10];
printf( "log with memory\n" );
DumpMemoryLog();
for( int i = 0; i < 10; i++ )
delete[] p[i];
printf( "after free,\n" );
DumpMemoryLog();
// now, try som realloc action
int *p1 = NULL;
int *p2;
for( int i =1 ; i < 10; i++ )
{
p1 = (int * ) realloc( p1, i * 100 );
if ( i == 3 )
p2 = new int[300];
}
printf(" after realloc loop\n" );
DumpMemoryLog();
delete[] p2;
free( p1 );
printf(" after realloc frees\n" );
DumpMemoryLog();
#endif
}
else
RemoveHooks();
}
static inline bool SortLessFunc( CLinuxMallocContext * const &left, CLinuxMallocContext * const &right )
{
return left->m_nCurrentAllocSize > right->m_nCurrentAllocSize;
}
void DumpMemoryLog( int nThresh )
{
AUTO_LOCK( s_MemoryMutex );
Plat_EndWatchdogTimer();
RemoveHooks();
std::vector<CLinuxMallocContext *> memList;
for( int i =0 ; i < MEMALLOC_HASHSIZE; i++ )
{
for( CLinuxMallocContext *p = s_ContextHash[i].m_pHead; p; p=p->m_pNext )
{
if ( p->m_nCurrentAllocSize >= nThresh )