forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsys_dll2.cpp
2578 lines (2132 loc) · 70.9 KB
/
sys_dll2.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: $
//===========================================================================//
#define DISABLE_PROTECTED_THINGS
#if defined( USE_SDL )
#include "appframework/ilaunchermgr.h"
#endif
#if defined( _WIN32 ) && !defined( _X360 )
#include "winlite.h"
#include <Psapi.h>
#endif
#if defined( OSX ) || defined(PLATFORM_BSD)
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#if defined( POSIX )
#include <setjmp.h>
#include <signal.h>
#endif
#include <stdarg.h>
#include "quakedef.h"
#include "idedicatedexports.h"
#include "engine_launcher_api.h"
#include "ivideomode.h"
#include "common.h"
#include "iregistry.h"
#include "keys.h"
#include "cdll_engine_int.h"
#include "traceinit.h"
#include "iengine.h"
#include "igame.h"
#include "tier0/etwprof.h"
#include "tier0/vcrmode.h"
#include "tier0/icommandline.h"
#include "tier0/minidump.h"
#include "engine_hlds_api.h"
#include "filesystem_engine.h"
#include "cl_main.h"
#include "client.h"
#include "tier3/tier3.h"
#include "MapReslistGenerator.h"
#include "toolframework/itoolframework.h"
#include "sourcevr/isourcevirtualreality.h"
#include "DevShotGenerator.h"
#include "gl_shader.h"
#include "l_studio.h"
#include "IHammer.h"
#include "sys_dll.h"
#include "materialsystem/materialsystem_config.h"
#include "server.h"
#include "video/ivideoservices.h"
#include "datacache/idatacache.h"
#include "vphysics_interface.h"
#include "inputsystem/iinputsystem.h"
#include "appframework/IAppSystemGroup.h"
#include "tier0/systeminformation.h"
#include "host_cmd.h"
#ifdef _WIN32
#include "VGuiMatSurface/IMatSystemSurface.h"
#endif
#ifdef GPROFILER
#include "gperftools/profiler.h"
#endif
// This is here just for legacy support of older .dlls!!!
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "eiface.h"
#include "tier1/fmtstr.h"
#include "steam/steam_api.h"
#ifndef SWDS
#include "sys_mainwind.h"
#include "vgui/ISystem.h"
#include "vgui_controls/Controls.h"
#include "IGameUIFuncs.h"
#include "cl_steamauth.h"
#endif // SWDS
#if defined(_WIN32)
#include <eh.h>
#endif
#if POSIX
#include <dlfcn.h>
#endif
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#else
#include "xbox/xboxstubs.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#include "tier0/memalloc.h"
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
IDedicatedExports *dedicated = NULL;
extern CreateInterfaceFn g_AppSystemFactory;
IHammer *g_pHammer = NULL;
IPhysics *g_pPhysics = NULL;
ISourceVirtualReality *g_pSourceVR = NULL;
#if defined( USE_SDL )
ILauncherMgr *g_pLauncherMgr = NULL;
#endif
#ifndef SWDS
extern CreateInterfaceFn g_ClientFactory;
#endif
static SteamInfVersionInfo_t g_SteamInfIDVersionInfo;
const SteamInfVersionInfo_t& GetSteamInfIDVersionInfo()
{
Assert( g_SteamInfIDVersionInfo.AppID != k_uAppIdInvalid );
return g_SteamInfIDVersionInfo;
}
int build_number( void )
{
return GetSteamInfIDVersionInfo().ServerVersion;
}
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
void Host_GetHostInfo(float *fps, int *nActive, int *nMaxPlayers, char *pszMap, int maxlen );
const char *Key_BindingForKey( int keynum );
void COM_ShutdownFileSystem( void );
void COM_InitFilesystem( const char *pFullModPath );
void Host_ReadPreStartupConfiguration();
//-----------------------------------------------------------------------------
// ConVars and console commands
//-----------------------------------------------------------------------------
#ifndef SWDS
//-----------------------------------------------------------------------------
// Purpose: exports an interface that can be used by the launcher to run the engine
// this is the exported function when compiled as a blob
//-----------------------------------------------------------------------------
void EXPORT F( IEngineAPI **api )
{
CreateInterfaceFn factory = Sys_GetFactoryThis(); // This silly construction is necessary to prevent the LTCG compiler from crashing.
*api = ( IEngineAPI * )(factory(VENGINE_LAUNCHER_API_VERSION, NULL));
}
#endif // SWDS
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ClearIOStates( void )
{
#ifndef SWDS
if ( g_ClientDLL )
{
g_ClientDLL->IN_ClearStates();
}
#endif
}
//-----------------------------------------------------------------------------
// The SDK launches the game with the full path to gameinfo.txt, so we need
// to strip off the path.
//-----------------------------------------------------------------------------
const char *GetModDirFromPath( const char *pszPath )
{
char *pszSlash = Q_strrchr( pszPath, '\\' );
if ( pszSlash )
{
return pszSlash + 1;
}
else if ( ( pszSlash = Q_strrchr( pszPath, '/' ) ) != NULL )
{
return pszSlash + 1;
}
// Must just be a mod directory already.
return pszPath;
}
//-----------------------------------------------------------------------------
// Purpose: Main entry
//-----------------------------------------------------------------------------
#ifndef SWDS
#include "gl_matsysiface.h"
#endif
//-----------------------------------------------------------------------------
// Inner loop: initialize, shutdown main systems, load steam to
//-----------------------------------------------------------------------------
class CModAppSystemGroup : public CAppSystemGroup
{
typedef CAppSystemGroup BaseClass;
public:
// constructor
CModAppSystemGroup( bool bServerOnly, CAppSystemGroup *pParentAppSystem = NULL )
: BaseClass( pParentAppSystem ),
m_bServerOnly( bServerOnly )
{
}
CreateInterfaceFn GetFactory()
{
return CAppSystemGroup::GetFactory();
}
// Methods of IApplication
virtual bool Create();
virtual bool PreInit();
virtual int Main();
virtual void PostShutdown();
virtual void Destroy();
private:
bool IsServerOnly() const
{
return m_bServerOnly;
}
bool ModuleAlreadyInList( CUtlVector< AppSystemInfo_t >& list, const char *moduleName, const char *interfaceName );
bool AddLegacySystems();
bool m_bServerOnly;
};
#if defined( STAGING_ONLY )
CON_COMMAND( bigalloc, "huge alloc crash" )
{
Msg( "pre-crash %d\n", MemAlloc_MemoryAllocFailed() );
// Alloc a bit less than UINT_MAX so there is room for heap headers in the malloc functions.
void *buf = malloc( UINT_MAX - 0x4000 );
Msg( "post-alloc %d. buf: %p\n", MemAlloc_MemoryAllocFailed(), buf );
*(int *)buf = 0;
}
#endif
extern void S_ClearBuffer();
extern char g_minidumpinfo[ 4096 ];
extern PAGED_POOL_INFO_t g_pagedpoolinfo;
extern bool g_bUpdateMinidumpComment;
void GetSpew( char *buf, size_t buflen );
extern int gHostSpawnCount;
extern int g_nMapLoadCount;
extern int g_HostServerAbortCount;
extern int g_HostErrorCount;
extern int g_HostEndDemo;
// Turn this to 1 to allow for expanded spew in minidump comments.
static ConVar sys_minidumpexpandedspew( "sys_minidumpexpandedspew", "1" );
#ifdef IS_WINDOWS_PC
extern "C" void __cdecl FailSafe( unsigned int uStructuredExceptionCode, struct _EXCEPTION_POINTERS * pExceptionInfo )
{
// Nothing, this just catches a crash when creating the comment block
}
#endif
#if defined( POSIX )
static sigjmp_buf g_mark;
static void posix_signal_handler( int i )
{
siglongjmp( g_mark, -1 );
}
#define DO_TRY if ( sigsetjmp( g_mark, 1 ) == 0 )
#define DO_CATCH else
#if !defined(PLATFORM_GLIBC)
#define __sighandler_t sig_t
#endif
#else
#define DO_TRY try
#define DO_CATCH catch ( ... )
#endif // POSIX
//-----------------------------------------------------------------------------
// Purpose: Check whether any mods are loaded.
// Currently looks for metamod and sourcemod.
//-----------------------------------------------------------------------------
static bool IsSourceModLoaded()
{
#if defined( _WIN32 )
static const char *s_pFileNames[] = { "metamod.2.tf2.dll", "sourcemod.2.tf2.dll", "sdkhooks.ext.2.ep2v.dll", "sdkhooks.ext.2.tf2.dll" };
for ( size_t i = 0; i < Q_ARRAYSIZE( s_pFileNames ); i++ )
{
// GetModuleHandle function returns a handle to a mapped module
// without incrementing its reference count.
if ( GetModuleHandleA( s_pFileNames[ i ] ) )
return true;
}
#else
FILE *fh = fopen( "/proc/self/maps", "r" );
if ( fh )
{
char buf[ 1024 ];
static const char *s_pFileNames[] = { "metamod.2.tf2.so", "sourcemod.2.tf2.so", "sdkhooks.ext.2.ep2v.so", "sdkhooks.ext.2.tf2.so" };
while ( fgets( buf, sizeof( buf ), fh ) )
{
for ( size_t i = 0; i < Q_ARRAYSIZE( s_pFileNames ); i++ )
{
if ( strstr( buf, s_pFileNames[ i ] ) )
{
fclose( fh );
return true;
}
}
}
fclose( fh );
}
#endif
return false;
}
template< int _SIZE >
class CErrorText
{
public:
CErrorText() : m_bIsDedicatedServer( false ) {}
~CErrorText() {}
void Steam_SetMiniDumpComment()
{
#if !defined( NO_STEAM )
SteamAPI_SetMiniDumpComment( m_errorText );
#endif
}
void CommentCat( const char * str )
{
V_strcat_safe( m_errorText, str );
}
void CommentPrintf( const char *fmt, ... )
{
va_list args;
va_start( args, fmt );
size_t len = strlen( m_errorText );
vsnprintf( m_errorText + len, sizeof( m_errorText ) - len - 1, fmt, args );
m_errorText[ sizeof( m_errorText ) - 1 ] = 0;
va_end( args );
}
void BuildComment( char const *pchSysErrorText, bool bRealCrash )
{
// Try and detect whether this
bool bSourceModLoaded = false;
if ( m_bIsDedicatedServer )
{
bSourceModLoaded = IsSourceModLoaded();
if ( bSourceModLoaded )
{
AppId_t AppId = GetSteamInfIDVersionInfo().ServerAppID;
// Bump up the number and report the crash. This should be something
// like 232251 (instead of 232250). 232251 is for the TF2 Windows client,
// but we actually report those crashes under ID 440, so this should be ok.
SteamAPI_SetBreakpadAppID( AppId + 1 );
}
}
#ifdef IS_WINDOWS_PC
// This warning only applies if you want to catch structured exceptions (crashes)
// using C++ exceptions. We do not want to do that so we can build with C++ exceptions
// completely disabled, and just suppress this warning.
// warning C4535: calling _set_se_translator() requires /EHa
#pragma warning( suppress : 4535 )
_se_translator_function curfilter = _set_se_translator( &FailSafe );
#elif defined( POSIX )
// Only need to worry about this function crashing when we're dealing with a real crash.
__sighandler_t curfilter = bRealCrash ? signal( SIGSEGV, posix_signal_handler ) : 0;
#endif
DO_TRY
{
Q_memset( m_errorText, 0x00, sizeof( m_errorText ) );
if ( pchSysErrorText )
{
CommentCat( "Sys_Error( " );
CommentCat( pchSysErrorText );
// Trim trailing \n.
int len = V_strlen( m_errorText );
if ( len > 0 && m_errorText[ len - 1 ] == '\n' )
m_errorText[ len - 1 ] = 0;
CommentCat( " )\n" );
}
else
{
CommentCat( "Crash\n" );
}
CommentPrintf( "Uptime( %f )\n", Plat_FloatTime() );
CommentPrintf( "SourceMod:%d,DS:%d,Crash:%d\n\n", bSourceModLoaded, m_bIsDedicatedServer, bRealCrash );
// Add g_minidumpinfo from CL_SetSteamCrashComment().
CommentCat( g_minidumpinfo );
// Latch in case extended stuff below crashes
Steam_SetMiniDumpComment();
// Add Memory Status
BuildCommentMemStatus();
// Spew out paged pool stuff, etc.
PAGED_POOL_INFO_t ppi_info;
if ( Plat_GetPagedPoolInfo( &ppi_info ) != SYSCALL_UNSUPPORTED )
{
CommentPrintf( "\nPaged Pool\nprev PP PAGES: used: %lu, free %lu\nfinal PP PAGES: used: %lu, free %lu\n",
g_pagedpoolinfo.numPagesUsed, g_pagedpoolinfo.numPagesFree,
ppi_info.numPagesUsed, ppi_info.numPagesFree );
}
CommentPrintf( "memallocfail? = %u\nActive: %s\nSpawnCount %d MapLoad Count %d\nError count %d, end demo %d, abort count %d\n",
MemAlloc_MemoryAllocFailed(),
( game && game->IsActiveApp() ) ? "active" : "inactive",
gHostSpawnCount,
g_nMapLoadCount,
g_HostErrorCount,
g_HostEndDemo,
g_HostServerAbortCount );
// Latch in case extended stuff below crashes
Steam_SetMiniDumpComment();
// Add user comment strings. 4096 is just a large sanity number we should
// never ever reach (currently our minidump supports 32 of these.)
for( int i = 0; i < 4096; i++ )
{
const char *pUserStreamInfo = MinidumpUserStreamInfoGet( i );
if( !pUserStreamInfo )
break;
if ( pUserStreamInfo[ 0 ] )
CommentPrintf( "%s", pUserStreamInfo );
}
bool bExtendedSpew = sys_minidumpexpandedspew.GetBool();
if ( bExtendedSpew )
{
BuildCommentExtended();
Steam_SetMiniDumpComment();
#if defined( LINUX )
if ( bRealCrash )
{
// bRealCrash is set when we're actually making a comment for a dump or error.
AddFileToComment( "/proc/meminfo" );
AddFileToComment( "/proc/self/status" );
Steam_SetMiniDumpComment();
// Useful, but really big, so disable for now.
//$ AddFileToComment( "/proc/self/maps" );
}
#endif
}
}
DO_CATCH
{
// Oh oh
}
#ifdef IS_WINDOWS_PC
_set_se_translator( curfilter );
#elif defined( POSIX )
if ( bRealCrash )
signal( SIGSEGV, curfilter );
#endif
}
void BuildCommentMemStatus()
{
#ifdef _WIN32
const double MbDiv = 1024.0 * 1024.0;
MEMORYSTATUSEX memStat;
ZeroMemory( &memStat, sizeof( MEMORYSTATUSEX ) );
memStat.dwLength = sizeof( MEMORYSTATUSEX );
if ( GlobalMemoryStatusEx( &memStat ) )
{
CommentPrintf( "\nMemory\nmemusage( %d %% )\ntotalPhysical Mb(%.2f)\nfreePhysical Mb(%.2f)\ntotalPaging Mb(%.2f)\nfreePaging Mb(%.2f)\ntotalVirtualMem Mb(%.2f)\nfreeVirtualMem Mb(%.2f)\nextendedVirtualFree Mb(%.2f)\n",
memStat.dwMemoryLoad,
(double)memStat.ullTotalPhys / MbDiv,
(double)memStat.ullAvailPhys / MbDiv,
(double)memStat.ullTotalPageFile / MbDiv,
(double)memStat.ullAvailPageFile / MbDiv,
(double)memStat.ullTotalVirtual / MbDiv,
(double)memStat.ullAvailVirtual / MbDiv,
(double)memStat.ullAvailExtendedVirtual / MbDiv);
}
HINSTANCE hInst = LoadLibrary( "Psapi.dll" );
if ( hInst )
{
typedef BOOL (WINAPI *GetProcessMemoryInfoFn)(HANDLE, PPROCESS_MEMORY_COUNTERS, DWORD);
GetProcessMemoryInfoFn fn = (GetProcessMemoryInfoFn)GetProcAddress( hInst, "GetProcessMemoryInfo" );
if ( fn )
{
PROCESS_MEMORY_COUNTERS counters;
ZeroMemory( &counters, sizeof( PROCESS_MEMORY_COUNTERS ) );
counters.cb = sizeof( PROCESS_MEMORY_COUNTERS );
if ( fn( GetCurrentProcess(), &counters, sizeof( PROCESS_MEMORY_COUNTERS ) ) )
{
CommentPrintf( "\nProcess Memory\nWorkingSetSize Mb(%.2f)\nQuotaPagedPoolUsage Mb(%.2f)\nQuotaNonPagedPoolUsage: Mb(%.2f)\nPagefileUsage: Mb(%.2f)\n",
(double)counters.WorkingSetSize / MbDiv,
(double)counters.QuotaPagedPoolUsage / MbDiv,
(double)counters.QuotaNonPagedPoolUsage / MbDiv,
(double)counters.PagefileUsage / MbDiv );
}
}
FreeLibrary( hInst );
}
#elif defined( OSX ) || defined(PLATFORM_BSD)
static const struct
{
int ctl;
const char *name;
} s_ctl_names[] =
{
#define _XTAG( _x ) { _x, #_x }
_XTAG( HW_PHYSMEM ),
_XTAG( HW_USERMEM ),
#ifdef PLATFORM_BSD
_XTAG( HW_PHYSMEM ),
_XTAG( HW_NCPU ),
#else
_XTAG( HW_MEMSIZE ),
_XTAG( HW_AVAILCPU ),
#endif
#undef _XTAG
};
for ( size_t i = 0; i < Q_ARRAYSIZE( s_ctl_names ); i++ )
{
uint64_t val = 0;
size_t len = sizeof( val );
int mib[] = { CTL_HW, s_ctl_names[ i ].ctl };
if ( sysctl( mib, Q_ARRAYSIZE( mib ), &val, &len, NULL, 0 ) == 0 )
{
CommentPrintf( " %s: %d\n", s_ctl_names[ i ].name, val );
}
}
#endif
}
void BuildCommentExtended()
{
try
{
CommentCat( "\nConVars (non-default)\n\n" );
CommentPrintf( "%s %s %s\n", "var", "value", "default" );
for ( const ConCommandBase *var = g_pCVar->GetCommands() ; var ; var = var->GetNext())
{
if ( var->IsCommand() )
continue;
ConVar *pCvar = ( ConVar * )var;
if ( pCvar->IsFlagSet( FCVAR_SERVER_CANNOT_QUERY | FCVAR_PROTECTED ) )
continue;
if ( !(pCvar->IsFlagSet( FCVAR_NEVER_AS_STRING ) ) )
{
char var1[ MAX_OSPATH ];
char var2[ MAX_OSPATH ];
Q_strncpy( var1, Host_CleanupConVarStringValue( pCvar->GetString() ), sizeof( var1 ) );
Q_strncpy( var2, Host_CleanupConVarStringValue( pCvar->GetDefault() ), sizeof( var2 ) );
if ( !Q_stricmp( var1, var2 ) )
continue;
}
else
{
if ( pCvar->GetFloat() == Q_atof( pCvar->GetDefault() ) )
continue;
}
if ( !(pCvar->IsFlagSet( FCVAR_NEVER_AS_STRING ) ) )
CommentPrintf( "%s '%s' '%s'\n", pCvar->GetName(), Host_CleanupConVarStringValue( pCvar->GetString() ), pCvar->GetDefault() );
else
CommentPrintf( "%s '%f' '%f'\n", pCvar->GetName(), pCvar->GetFloat(), Q_atof( pCvar->GetDefault() ) );
}
CommentCat( "\nConsole History (reversed)\n\n" );
// Get console
int len = V_strlen( m_errorText );
if ( len < sizeof( m_errorText ) )
{
GetSpew( m_errorText + len, sizeof( m_errorText ) - len - 1 );
m_errorText[ sizeof( m_errorText ) - 1 ] = 0;
}
}
catch ( ... )
{
CommentCat( "Exception thrown building console/convar history.\n" );
}
}
#if defined( LINUX )
void AddFileToComment( const char *filename )
{
CommentPrintf( "\n%s:\n", filename );
int nStart = Q_strlen( m_errorText );
int nMaxLen = sizeof( m_errorText ) - nStart - 1;
if ( nMaxLen > 0 )
{
FILE *fh = fopen( filename, "r" );
if ( fh )
{
size_t ret = fread( m_errorText + nStart, 1, nMaxLen, fh );
fclose( fh );
// Replace tab characters with spaces.
for ( size_t i = 0; i < ret; i++ )
{
if ( m_errorText[ nStart + i ] == '\t' )
m_errorText[ nStart + i ] = ' ';
}
}
// Entire buffer should have been zeroed out, but just super sure...
m_errorText[ sizeof( m_errorText ) - 1 ] = 0;
}
}
#endif // LINUX
public:
char m_errorText[ _SIZE ];
bool m_bIsDedicatedServer;
};
#if defined( _X360 )
static CErrorText<3500> errorText;
#else
static CErrorText<95000> errorText;
#endif
void BuildMinidumpComment( char const *pchSysErrorText, bool bRealCrash )
{
#if !defined(NO_STEAM)
/*
// Uncomment this code if you are testing max minidump comment length issues
// It allows you to asked for a dummy comment of a certain length
int nCommentLength = CommandLine()->ParmValue( "-commentlen", 0 );
if ( nCommentLength > 0 )
{
nCommentLength = MIN( nCommentLength, 128*1024 );
char *cbuf = new char[ nCommentLength + 1 ];
for ( int i = 0; i < nCommentLength; ++i )
{
cbuf[ i ] = (char)('0' + (i % 10));
}
cbuf[ nCommentLength ] = 0;
SteamAPI_SetMiniDumpComment( cbuf );
delete[] cbuf;
return;
}
*/
errorText.BuildComment( pchSysErrorText, bRealCrash );
#endif
}
#if defined( POSIX )
static void PosixPreMinidumpCallback( void *context )
{
BuildMinidumpComment( NULL, true );
}
#endif
//-----------------------------------------------------------------------------
// Purpose: Attempt to initialize appid/steam.inf/minidump information. May only return partial information if called
// before Filesystem is ready.
//
// The desire is to be able to call this ASAP to init basic minidump and AppID info, then re-call later on when
// the filesystem is setup, so full version # information and such can be propagated to the minidump system.
// (Currently, SDK mods will generally only have partial information prior to filesystem init)
//-----------------------------------------------------------------------------
// steam.inf keys.
#define VERSION_KEY "PatchVersion="
#define PRODUCT_KEY "ProductName="
#define SERVER_VERSION_KEY "ServerVersion="
#define APPID_KEY "AppID="
#define SERVER_APPID_KEY "ServerAppID="
enum eSteamInfoInit
{
eSteamInfo_Uninitialized,
eSteamInfo_Partial,
eSteamInfo_Initialized
};
static eSteamInfoInit Sys_TryInitSteamInfo( void *pvAPI, SteamInfVersionInfo_t& VerInfo, const char *pchMod, const char *pchBaseDir, bool bDedicated )
{
static eSteamInfoInit initState = eSteamInfo_Uninitialized;
eSteamInfoInit previousInitState = initState;
//
//
// Initialize with some defaults.
VerInfo.ClientVersion = 0;
VerInfo.ServerVersion = 0;
V_strcpy_safe( VerInfo.szVersionString, "valve" );
V_strcpy_safe( VerInfo.szProductString, "1.0.1.0" );
VerInfo.AppID = k_uAppIdInvalid;
VerInfo.ServerAppID = k_uAppIdInvalid;
// Filesystem may or may not be up
CUtlBuffer infBuf;
bool bFoundInf = false;
if ( g_pFileSystem )
{
FileHandle_t fh;
fh = g_pFileSystem->Open( "steam.inf", "rb", "GAME" );
bFoundInf = fh && g_pFileSystem->ReadToBuffer( fh, infBuf );
}
if ( !bFoundInf )
{
// We may try to load the steam.inf BEFORE we turn on the filesystem, so use raw filesystem API's here.
char szFullPath[ MAX_PATH ] = { 0 };
char szModSteamInfPath[ MAX_PATH ] = { 0 };
V_ComposeFileName( pchMod, "steam.inf", szModSteamInfPath, sizeof( szModSteamInfPath ) );
V_MakeAbsolutePath( szFullPath, sizeof( szFullPath ), szModSteamInfPath, pchBaseDir );
// Try opening steam.inf
FILE *fp = fopen( szFullPath, "rb" );
if ( fp )
{
// Read steam.inf data.
fseek( fp, 0, SEEK_END );
size_t bufsize = ftell( fp );
fseek( fp, 0, SEEK_SET );
infBuf.EnsureCapacity( bufsize + 1 );
size_t iBytesRead = fread( infBuf.Base(), 1, bufsize, fp );
((char *)infBuf.Base())[iBytesRead] = 0;
infBuf.SeekPut( CUtlBuffer::SEEK_CURRENT, iBytesRead + 1 );
fclose( fp );
bFoundInf = ( iBytesRead == bufsize );
}
}
if ( bFoundInf )
{
const char *pbuf = (const char*)infBuf.Base();
while ( 1 )
{
pbuf = COM_Parse( pbuf );
if ( !pbuf || !com_token[ 0 ] )
break;
if ( !Q_strnicmp( com_token, VERSION_KEY, Q_strlen( VERSION_KEY ) ) )
{
V_strcpy_safe( VerInfo.szVersionString, com_token + Q_strlen( VERSION_KEY ) );
VerInfo.ClientVersion = atoi( VerInfo.szVersionString );
}
else if ( !Q_strnicmp( com_token, PRODUCT_KEY, Q_strlen( PRODUCT_KEY ) ) )
{
V_strcpy_safe( VerInfo.szProductString, com_token + Q_strlen( PRODUCT_KEY ) );
}
else if ( !Q_strnicmp( com_token, SERVER_VERSION_KEY, Q_strlen( SERVER_VERSION_KEY ) ) )
{
VerInfo.ServerVersion = atoi( com_token + Q_strlen( SERVER_VERSION_KEY ) );
}
else if ( !Q_strnicmp( com_token, APPID_KEY, Q_strlen( APPID_KEY ) ) )
{
VerInfo.AppID = atoi( com_token + Q_strlen( APPID_KEY ) );
}
else if ( !Q_strnicmp( com_token, SERVER_APPID_KEY, Q_strlen( SERVER_APPID_KEY ) ) )
{
VerInfo.ServerAppID = atoi( com_token + Q_strlen( SERVER_APPID_KEY ) );
}
}
// If we found a steam.inf we're as good as we're going to get, but don't tell callers we're fully initialized
// if it doesn't at least have an AppID
initState = ( VerInfo.AppID != k_uAppIdInvalid ) ? eSteamInfo_Initialized : eSteamInfo_Partial;
}
else if ( !bDedicated )
{
// Opening steam.inf failed - try to open gameinfo.txt and read in just SteamAppId from that.
// (gameinfo.txt lacks the dedicated server steamid, so we'll just have to live until filesystem init to setup
// breakpad there when we hit this case)
char szModGameinfoPath[ MAX_PATH ] = { 0 };
char szFullPath[ MAX_PATH ] = { 0 };
V_ComposeFileName( pchMod, "gameinfo.txt", szModGameinfoPath, sizeof( szModGameinfoPath ) );
V_MakeAbsolutePath( szFullPath, sizeof( szFullPath ), szModGameinfoPath, pchBaseDir );
// Try opening gameinfo.txt
FILE *fp = fopen( szFullPath, "rb" );
if( fp )
{
fseek( fp, 0, SEEK_END );
size_t bufsize = ftell( fp );
fseek( fp, 0, SEEK_SET );
char *buffer = ( char * )_alloca( bufsize + 1 );
size_t iBytesRead = fread( buffer, 1, bufsize, fp );
buffer[ iBytesRead ] = 0;
fclose( fp );
KeyValuesAD pkvGameInfo( "gameinfo" );
if ( pkvGameInfo->LoadFromBuffer( "gameinfo.txt", buffer ) )
{
VerInfo.AppID = (AppId_t)pkvGameInfo->GetInt( "FileSystem/SteamAppId", k_uAppIdInvalid );
}
}
initState = eSteamInfo_Partial;
}
// In partial state the ServerAppID might be unknown, but if we found the full steam.inf and it's not set, it shares AppID.
if ( initState == eSteamInfo_Initialized && VerInfo.ServerAppID == k_uAppIdInvalid )
VerInfo.ServerAppID = VerInfo.AppID;
#if !defined(_X360)
if ( VerInfo.AppID )
{
// steamclient.dll doesn't know about steam.inf files in mod folder,
// it accepts a steam_appid.txt in the root directory if the game is
// not started through Steam. So we create one there containing the
// current AppID
FILE *fh = fopen( "steam_appid.txt", "wb" );
if ( fh )
{
CFmtStrN< 128 > strAppID( "%u\n", VerInfo.AppID );
fwrite( strAppID.Get(), strAppID.Length() + 1, 1, fh );
fclose( fh );
}
}
#endif // !_X360
//
// Update minidump info if we have more information than before
//
#ifndef NO_STEAM
// If -nobreakpad was specified or we found metamod or sourcemod, don't register breakpad.
bool bUseBreakpad = !CommandLine()->FindParm( "-nobreakpad" ) && ( !bDedicated || !IsSourceModLoaded() );
AppId_t BreakpadAppId = bDedicated ? VerInfo.ServerAppID : VerInfo.AppID;
Assert( BreakpadAppId != k_uAppIdInvalid || initState < eSteamInfo_Initialized );
if ( BreakpadAppId != k_uAppIdInvalid && initState > previousInitState && bUseBreakpad )
{
void *pvMiniDumpContext = NULL;
PFNPreMinidumpCallback pfnPreMinidumpCallback = NULL;
bool bFullMemoryDump = !bDedicated && IsWindows() && CommandLine()->FindParm( "-full_memory_dumps" );
#if defined( POSIX )
// On Windows we're relying on the try/except to build the minidump comment. On Linux, we don't have that
// so we need to register the minidumpcallback handler here.
pvMiniDumpContext = pvAPI;
pfnPreMinidumpCallback = PosixPreMinidumpCallback;
#endif
CFmtStrN<128> pchVersion( "%d", build_number() );
Msg( "Using Breakpad minidump system. Version: %s AppID: %u\n", pchVersion.Get(), BreakpadAppId );
// We can filter various crash dumps differently in the Socorro backend code:
// Steam/min/web/crash_reporter/socorro/scripts/config/collectorconfig.py
SteamAPI_SetBreakpadAppID( BreakpadAppId );
SteamAPI_UseBreakpadCrashHandler( pchVersion, __DATE__, __TIME__, bFullMemoryDump, pvMiniDumpContext, pfnPreMinidumpCallback );
// Tell errorText class if this is dedicated server.
errorText.m_bIsDedicatedServer = bDedicated;
}
#endif // NO_STEAM
MinidumpUserStreamInfoSetHeader( "%sLaunching \"%s\"\n", ( bDedicated ? "DedicatedServerAPI " : "" ), CommandLine()->GetCmdLine() );
return initState;
}
#ifndef SWDS
//-----------------------------------------------------------------------------
//
// Main engine interface exposed to launcher
//
//-----------------------------------------------------------------------------
class CEngineAPI : public CTier3AppSystem< IEngineAPI >
{
typedef CTier3AppSystem< IEngineAPI > BaseClass;
public:
virtual bool Connect( CreateInterfaceFn factory );
virtual void Disconnect();
virtual void *QueryInterface( const char *pInterfaceName );
virtual InitReturnVal_t Init();
virtual void Shutdown();
// This function must be called before init
virtual void SetStartupInfo( StartupInfo_t &info );
virtual int Run( );
// Sets the engine to run in a particular editor window
virtual void SetEngineWindow( void *hWnd );
// Posts a console command
virtual void PostConsoleCommand( const char *pConsoleCommand );
// Are we running the simulation?
virtual bool IsRunningSimulation( ) const;
// Start/stop running the simulation
virtual void ActivateSimulation( bool bActive );
// Reset the map we're on
virtual void SetMap( const char *pMapName );
bool MainLoop();
int RunListenServer();
private:
// Hooks a particular mod up to the registry
void SetRegistryMod( const char *pModName );
// One-time setup, based on the initially selected mod
// FIXME: This should move into the launcher!
bool OnStartup( void *pInstance, const char *pStartupModName );
void OnShutdown();
// Initialization, shutdown of a mod.
bool ModInit( const char *pModName, const char *pGameDir );
void ModShutdown();
// Initializes, shuts down the registry
bool InitRegistry( const char *pModName );
void ShutdownRegistry();
// Handles there being an error setting up the video mode
InitReturnVal_t HandleSetModeError();
// Initializes, shuts down VR
bool InitVR();
void ShutdownVR();
// Purpose: Message pump when running stand-alone
void PumpMessages();
// Purpose: Message pump when running with the editor
void PumpMessagesEditMode( bool &bIdle, long &lIdleCount );
// Activate/deactivates edit mode shaders
void ActivateEditModeShaders( bool bActive );
private:
void *m_hEditorHWnd;
bool m_bRunningSimulation;
bool m_bSupportsVR;
StartupInfo_t m_StartupInfo;
};