-
Notifications
You must be signed in to change notification settings - Fork 33
/
sys_unix.cpp
1404 lines (1164 loc) · 33.9 KB
/
sys_unix.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
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <pwd.h>
#include <pthread.h>
#include <fenv.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <setjmp.h>
#ifdef __GNU_LIBRARY__
#include <gnu/libc-version.h>
#endif
#ifdef MACOS_X
#include <mach-o/dyld.h>
#endif
#include "../qcommon/q_shared.h"
#include "../qcommon/qcommon.h"
#include "../qcommon/vm_local.h"
#include "con_local.h"
#include <mv_setup.h>
//=============================================================================
// Used to determine CD Path
static char cdPath[MAX_OSPATH];
// Used to determine local installation path
static char installPath[MAX_OSPATH];
// Used to determine where to store user-specific files
static char homePath[MAX_OSPATH];
/*
================
Sys_Milliseconds
================
*/
/* base time in seconds, that's our origin
timeval:tv_sec is an int:
assuming this wraps every 0x7fffffff - ~68 years since the Epoch (1970) - we're safe till 2038 */
unsigned long sys_timeBase = 0;
/* current time in ms, using sys_timeBase as origin
NOTE: sys_timeBase*1000 + curtime -> ms since the Epoch
0x7fffffff ms - ~24 days
although timeval:tv_usec is an int, I'm not sure wether it is actually used as an unsigned int
(which would affect the wrap period) */
int curtime;
int Sys_Milliseconds (bool baseTime)
{
struct timeval tp;
gettimeofday(&tp, NULL);
if (!sys_timeBase)
{
sys_timeBase = tp.tv_sec;
return tp.tv_usec/1000;
}
curtime = (tp.tv_sec - sys_timeBase)*1000 + tp.tv_usec/1000;
static int sys_timeBase = curtime;
if (!baseTime)
{
curtime -= sys_timeBase;
}
return curtime;
}
int Sys_Milliseconds2( void )
{
return Sys_Milliseconds(false);
}
qboolean Sys_Mkdir( const char *path )
{
int result = mkdir( path, 0750 );
if( result != 0 )
return (qboolean)(errno == EEXIST);
return qtrue;
}
//============================================
#define MAX_FOUND_FILES 0x1000
// bk001129 - new in 1.26
static void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, const char **list, int *numfiles ) {
char search[MAX_OSPATH], newsubdirs[MAX_OSPATH];
char filename[MAX_OSPATH];
DIR *fdir;
struct dirent *d;
struct stat st;
if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
return;
}
if (strlen(subdirs)) {
Com_sprintf( search, sizeof(search), "%s/%s", basedir, subdirs );
}
else {
Com_sprintf( search, sizeof(search), "%s", basedir );
}
if ((fdir = opendir(search)) == NULL) {
return;
}
while ((d = readdir(fdir)) != NULL) {
Com_sprintf(filename, sizeof(filename), "%s/%s", search, d->d_name);
if (stat(filename, &st) == -1)
continue;
if (st.st_mode & S_IFDIR) {
if (Q_stricmp(d->d_name, ".") && Q_stricmp(d->d_name, "..")) {
if (strlen(subdirs)) {
Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s/%s", subdirs, d->d_name);
}
else {
Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s", d->d_name);
}
Sys_ListFilteredFiles( basedir, newsubdirs, filter, list, numfiles );
}
}
if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
break;
}
Com_sprintf( filename, sizeof(filename), "%s/%s", subdirs, d->d_name );
if (!Com_FilterPath( filter, filename, qfalse ))
continue;
list[ *numfiles ] = CopyString( filename, TAG_LISTFILES );
(*numfiles)++;
}
closedir(fdir);
}
/*
================
Sys_ListFiles
Both level pointers in return value must be freed using Z_Free()
unless they are NULL pointers
================
*/
// bk001129 - in 1.17 this used to be
// char **Sys_ListFiles( const char *directory, const char *extension, int *numfiles, qboolean wantsubs )
const char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs )
{
struct dirent *d;
// char *p; // bk001204 - unused
DIR *fdir;
qboolean dironly = wantsubs;
char search[MAX_OSPATH];
int nfiles;
const char **listCopy;
const char *list[MAX_FOUND_FILES];
//int flag; // bk001204 - unused
int i;
struct stat st;
int extLen;
if (filter) {
nfiles = 0;
Sys_ListFilteredFiles( directory, "", filter, list, &nfiles );
list[ nfiles ] = 0;
*numfiles = nfiles;
if (!nfiles)
return NULL;
listCopy = (const char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ),TAG_LISTFILES,qfalse );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
if ( !extension)
extension = "";
if ( extension[0] == '/' && extension[1] == 0 ) {
extension = "";
dironly = qtrue;
}
extLen = strlen( extension );
// search
nfiles = 0;
if ((fdir = opendir(directory)) == NULL) {
*numfiles = 0;
return NULL;
}
while ((d = readdir(fdir)) != NULL) {
Com_sprintf(search, sizeof(search), "%s/%s", directory, d->d_name);
if (stat(search, &st) == -1)
continue;
if ((dironly && !(st.st_mode & S_IFDIR)) ||
(!dironly && (st.st_mode & S_IFDIR)))
continue;
if (*extension) {
if ( strlen( d->d_name ) < strlen( extension ) ||
Q_stricmp(
d->d_name + strlen( d->d_name ) - strlen( extension ),
extension ) ) {
continue; // didn't match
}
}
if ( nfiles == MAX_FOUND_FILES - 1 )
break;
list[ nfiles ] = CopyString( d->d_name, TAG_LISTFILES );
nfiles++;
}
list[ nfiles ] = 0;
closedir(fdir);
// return a copy of the list
*numfiles = nfiles;
if ( !nfiles ) {
return NULL;
}
listCopy = (const char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ),TAG_LISTFILES,qfalse );
for ( i = 0 ; i < nfiles ; i++ ) {
listCopy[i] = list[i];
}
listCopy[i] = NULL;
return listCopy;
}
void Sys_FreeFileList( const char **list ) {
int i;
if ( !list ) {
return;
}
for ( i = 0 ; list[i] ; i++ ) {
Z_Free( (void *)list[i] );
}
Z_Free( list );
}
char *Sys_Cwd( void )
{
static char cwd[MAX_OSPATH];
if ( !getcwd( cwd, sizeof( cwd ) - 1 ) ) {
return "";
}
cwd[MAX_OSPATH-1] = 0;
return cwd;
}
void Sys_SetDefaultCDPath(const char *path)
{
Q_strncpyz(cdPath, path, sizeof(cdPath));
}
char *Sys_DefaultCDPath(void)
{
return cdPath;
}
void Sys_SetDefaultInstallPath(const char *path)
{
Q_strncpyz(installPath, path, sizeof(installPath));
}
#if defined(MACOS_X)
static char *last_strstr(const char *haystack, const char *needle)
{
if (*needle == '\0')
return (char *) haystack;
char *result = NULL;
for (;;) {
char *p = (char *)strstr(haystack, needle);
if (p == NULL)
break;
result = p;
haystack = p + 1;
}
return result;
}
#endif // MACOS_X
#if !defined(MACOS_X) && defined(INSTALLED)
char *Sys_LinuxGetInstallPrefix() {
static char path[MAX_OSPATH];
int i;
readlink("/proc/self/exe", path, sizeof(path));
// from: /usr/local/bin/jk2mvmp
// to: /usr/local
for (i = 0; i < 2; i++) {
char *l = strrchr(path, '/');
if (!l) {
break;
}
*l = 0;
}
return path;
}
#endif
char *Sys_DefaultInstallPath(void)
{
if (*installPath) {
return installPath;
} else {
#if defined(MACOS_X) && defined(INSTALLED)
// Inside the app...
static char path[MAX_OSPATH];
char *override;
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size)) {
return Sys_Cwd();
}
override = last_strstr(path, "MacOS");
if (!override) {
return Sys_Cwd();
}
override[5] = 0;
return path;
#elif !defined(MACOS_X) && defined(INSTALLED)
static char path[MAX_OSPATH];
Com_sprintf(path, sizeof(path), "%s/share/jk2mv", Sys_LinuxGetInstallPrefix());
return path;
#else
return Sys_Cwd();
#endif
}
}
void Sys_SetDefaultHomePath(const char *path)
{
Q_strncpyz(homePath, path, sizeof(homePath));
}
// if dedicated, i think it's a good idea to default fs_homepath to fs_basepath on unix, too
// remember it's only the default value
char *Sys_DefaultHomePath(void)
{
#if defined(INSTALLED)
char *p;
if (*homePath)
return homePath;
if ((p = getenv("HOME")) != NULL) {
Q_strncpyz(homePath, p, sizeof(homePath));
#ifdef MACOS_X
Q_strcat(homePath, sizeof(homePath), "/Library/Application Support/jk2mv");
#else
Q_strcat(homePath, sizeof(homePath), "/.jk2mv");
#endif
if (mkdir(homePath, 0777)) {
if (errno != EEXIST)
Sys_Error("Unable to create directory \"%s\", error is %s(%d)\n", homePath, strerror(errno), errno);
}
return homePath;
}
return ""; // assume current dir
#else
return Sys_Cwd();
#endif
}
// try to find assets from /Applications (Appstore JK2) or Steam
// if not found try to find it in the same directory this app is
char *Sys_DefaultAssetsPath() {
#if defined(MACOS_X) && defined(INSTALLED)
static char path[MAX_OSPATH];
char *override;
// AppStore version
if (access("/Applications/Jedi Knight II.app/Contents/base/assets0.pk3", F_OK) != -1) {
return "/Applications/Jedi Knight II.app/Contents";
}
// Steam version
if (access(va("%s/Library/Application Support/Steam/steamapps/common/Jedi Outcast/Jedi Knight II.app/Contents/base/assets0.pk3", getenv("HOME")), F_OK) != -1) {
Q_strncpyz(path, va("%s/Library/Application Support/Steam/steamapps/common/Jedi Outcast/Jedi Knight II.app/Contents", getenv("HOME")), sizeof(path));
return path;
}
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size)) {
return NULL;
}
override = last_strstr(path, ".app/");
if (!override) {
return NULL;
}
*override = 0;
override = last_strstr(path, "/");
if (!override) {
return NULL;
}
strcpy(override, "/Jedi Knight II.app/Contents");
if (access(va("%s/base/assets0.pk3", path), F_OK) == -1) {
return NULL;
}
return path;
#else
return NULL;
#endif
}
// Try to find assets from /Applications (Appstore JKA) or Steam.
// If neither worked try to find them in the same directory the jk2mv app is in.
char *Sys_DefaultAssetsPathJKA() {
#if defined(MACOS_X) && defined(INSTALLED)
static char path[MAX_OSPATH];
char *ptr;
// AppStore version (App name not verified, because the AppStore version
// doesn't support 32-bit and can't easily be obtained from the AppStore
// on modern Mac anymore; name guessed based on Steam version)
if (access("/Applications/SWJKJA.app/Contents/base/assets0.pk3", F_OK) != -1) {
return "/Applications/SWJKJA.app/Contents";
}
// Steam version
if (access(va("%s/Library/Application Support/Steam/steamapps/common/Jedi Academy/SWJKJA.app/Contents/base/assets0.pk3", getenv("HOME")), F_OK) != -1) {
Q_strncpyz(path, va("%s/Library/Application Support/Steam/steamapps/common/Jedi Academy/SWJKJA.app/Contents", getenv("HOME")), sizeof(path));
return path;
}
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size)) {
return NULL;
}
ptr = last_strstr(path, ".app/");
if (!ptr) {
return NULL;
}
*ptr = 0;
ptr = last_strstr(path, "/");
if (!ptr) {
return NULL;
}
strcpy(ptr, "/SWJKA.app/Contents");
if (access(va("%s/base/assets0.pk3", path), F_OK) == -1) {
return NULL;
}
return path;
#else
return NULL;
#endif
}
qboolean stdin_active = qtrue;
qboolean stdinIsATTY = qfalse;
int crashlogfd;
extern void Sys_SigHandler( int signal );
static void Sys_SigHandlerFatal(int sig, siginfo_t *info, void *context);
static Q_NORETURN void Sys_CrashLogger(int fd, int argc, char *argv[]);
// Max open file descriptors. Mostly used by pk3 files with
// MAX_SEARCH_PATHS limit.
#define MAX_OPEN_FILES 4096
void Sys_PlatformInit( int argc, char *argv[] )
{
int crashfd[2];
pid_t crashpid;
if (pipe(crashfd) == -1) {
perror("pipe()");
goto skip_crash;
}
if ((crashpid = fork()) == -1) {
perror("fork()");
goto skip_crash;
}
if (crashpid == 0) {
close(crashfd[1]);
Sys_CrashLogger(crashfd[0], argc, argv);
} else {
close(crashfd[0]);
crashlogfd = crashfd[1];
}
skip_crash:
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = Sys_SigHandler;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, SIGHUP);
sigaddset(&act.sa_mask, SIGINT);
sigaddset(&act.sa_mask, SIGTERM);
sigaction(SIGHUP, &act, NULL);
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
act.sa_handler = NULL;
act.sa_sigaction = Sys_SigHandlerFatal;
act.sa_flags = SA_SIGINFO | SA_NODEFER;
sigaction(SIGQUIT, &act, NULL);
sigaction(SIGILL, &act, NULL);
sigaction(SIGABRT, &act, NULL);
sigaction(SIGFPE, &act, NULL);
sigaction(SIGSEGV, &act, NULL);
sigaction(SIGBUS, &act, NULL);
sigaction(SIGSYS, &act, NULL);
sigaction(SIGTRAP, &act, NULL);
const char* term = getenv( "TERM" );
if (isatty( STDIN_FILENO ) && !( term && ( !strcmp( term, "raw" ) || !strcmp( term, "dumb" ) ) )) {
stdinIsATTY = qtrue;
} else {
stdinIsATTY = qfalse;
}
// raise open file limit to allow more pk3 files
int retval;
struct rlimit rlim;
rlim_t maxfds = MAX_OPEN_FILES;
for (int i = 1; i + 1 < argc; i++) {
if (!Q_stricmp(argv[i], "-maxfds")) {
maxfds = atoi(argv[i + 1]);
}
}
getrlimit(RLIMIT_NOFILE, &rlim);
rlim.rlim_cur = MIN(maxfds, rlim.rlim_max);
retval = setrlimit(RLIMIT_NOFILE, &rlim);
if (retval == -1) {
Com_Printf("Warning: Failed to raise open file limit. %s\n", strerror(errno));
}
}
void Sys_PlatformExit( void )
{
}
int Sys_PID( void )
{
return getpid( );
}
//============================================
int Sys_GetProcessorId( void )
{
return CPUID_GENERIC;
}
char *Sys_GetCurrentUser( void )
{
struct passwd *p;
if ( (p = getpwuid( getuid() )) == NULL ) {
return "player";
}
return p->pw_name;
}
// from ioq3 requires sse
// i do not care about processors without sse
#if defined(__i386__) || defined(__amd64__)
#if idx64
#define EAX "%%rax"
#define EBX "%%rbx"
#define ESP "%%rsp"
#define EDI "%%rdi"
#else
#define EAX "%%eax"
#define EBX "%%ebx"
#define ESP "%%esp"
#define EDI "%%edi"
#endif
static unsigned char ssemask[16] __attribute__((aligned(16))) = {
"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00\x00"
};
void Sys_SnapVector(vec3_t vec) {
__asm__ volatile
(
"movaps (%0), %%xmm1\n"
"movups (%1), %%xmm0\n"
"movaps %%xmm0, %%xmm2\n"
"andps %%xmm1, %%xmm0\n"
"andnps %%xmm2, %%xmm1\n"
"cvtps2dq %%xmm0, %%xmm0\n"
"cvtdq2ps %%xmm0, %%xmm0\n"
"orps %%xmm1, %%xmm0\n"
"movups %%xmm0, (%1)\n"
:
: "r" (ssemask), "r" (vec)
: "memory", "%xmm0", "%xmm1", "%xmm2"
);
}
#else
void Sys_SnapVector(float *v) {
v[0] = nearbyintf(v[0]);
v[1] = nearbyintf(v[1]);
v[2] = nearbyintf(v[2]);
}
#endif
/*
==================
Sys_Sleep
Block execution for msec or until input is recieved.
==================
*/
void Sys_Sleep( int msec )
{
if( msec == 0 )
return;
if( stdinIsATTY )
{
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(STDIN_FILENO, &fdset);
if( msec < 0 )
{
select(STDIN_FILENO + 1, &fdset, NULL, NULL, NULL);
}
else
{
struct timeval timeout;
timeout.tv_sec = msec/1000;
timeout.tv_usec = (msec%1000)*1000;
select(STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout);
}
}
else
{
// With nothing to select() on, we can't wait indefinitely
if( msec < 0 )
msec = 10;
usleep( msec * 1000 );
}
}
/*
=================
Sys_UnloadModuleLibrary
=================
*/
void Sys_UnloadModuleLibrary(void *dllHandle) {
if (!dllHandle) {
return;
}
dlclose(dllHandle);
}
/*
=================
Sys_LoadModuleLibrary
Used to load a module (jk2mpgame, cgame, ui) so/dylib
=================
*/
void *Sys_LoadModuleLibrary(const char *name, qboolean mvOverride, VM_EntryPoint_t *entryPoint, intptr_t(QDECL *systemcalls)(intptr_t, ...)) {
void (*dllEntry)(intptr_t(*syscallptr)(intptr_t, ...));
char filename[MAX_QPATH];
const char *path, *filePath;
void *libHandle;
Com_sprintf(filename, sizeof(filename), "%s_" ARCH_STRING "." LIBRARY_EXTENSION, name);
if (!mvOverride) {
path = Cvar_VariableString("fs_basepath");
filePath = FS_BuildOSPath(path, NULL, filename);
Com_DPrintf("Loading module: %s...", filePath);
assert(!dlopen(filePath, RTLD_NOLOAD));
libHandle = dlopen(filePath, RTLD_NOW);
if (!libHandle) {
Com_DPrintf(" failed: %s\n", dlerror());
path = Cvar_VariableString("fs_homepath");
filePath = FS_BuildOSPath(path, NULL, filename);
Com_DPrintf("Loading module: %s...", filePath);
assert(!dlopen(filePath, RTLD_NOLOAD));
libHandle = dlopen(filePath, RTLD_NOW);
if (!libHandle) {
Com_DPrintf(" failed: %s\n", dlerror());
return NULL;
} else {
Com_DPrintf(" success!\n");
}
} else {
Com_DPrintf(" success!\n");
}
} else {
char lpath[1024];
#if !defined(MACOS_X) && defined(INSTALLED)
Com_sprintf(lpath, sizeof(lpath), "%s/lib/%s", Sys_LinuxGetInstallPrefix(), filename);
#else
path = Cvar_VariableString("fs_basepath");
Com_sprintf(lpath, sizeof(lpath), "%s/%s", path, filename);
#endif
Com_DPrintf("Loading module: %s...", lpath);
assert(!dlopen(lpath, RTLD_NOLOAD));
libHandle = dlopen(lpath, RTLD_NOW);
if (!libHandle) {
Com_DPrintf(" failed: %s\n", dlerror());
return NULL;
} else {
Com_DPrintf(" success!\n");
}
}
dllEntry = (void (*)(intptr_t (*)(intptr_t,...))) dlsym(libHandle, "dllEntry");
*entryPoint = (VM_EntryPoint_t)dlsym(libHandle, "vmMain");
if ( !*entryPoint ) {
Com_DPrintf("Could not find vmMain in %s\n", filename);
dlclose(libHandle);
return NULL;
}
if (!dllEntry) {
Com_DPrintf("Could not find dllEntry in %s\n", filename);
dlclose(libHandle);
return NULL;
}
dllEntry(systemcalls);
return libHandle;
}
void Sys_SetTaskbarState(void *win_handle, tbstate_t state, uint64_t current, uint64_t total) {
// TODO: OSX Dock support
}
int Sys_FLock(int fd, flockCmd_t cmd, qboolean nb) {
struct flock l = { 0 };
l.l_whence = SEEK_SET;
l.l_pid = getpid();
switch (cmd) {
case FLOCK_SH: l.l_type = F_RDLCK; break;
case FLOCK_EX: l.l_type = F_WRLCK; break;
case FLOCK_UN: l.l_type = F_UNLCK; break;
}
return fcntl(fd, nb ? F_SETLK : F_SETLKW, &l);
}
static int Sys_Backtrace(void **buffer, int size);
void Sys_PrintBacktrace(void) {
#define BT_LEN 20
void *buf[BT_LEN + 2];
int size;
size = Sys_Backtrace(buf, BT_LEN + 2);
for (int i = 2; i < size; i++) {
const char *desc = VM_SymbolForCompiledPointer(buf[i]);
#ifdef Q_BACKTRACE
char **sym = NULL;
if (!desc) {
sym = backtrace_symbols(&buf[i], 1);
if (sym) {
desc = sym[0];
}
}
#endif
if (!desc) {
desc = va("[%p]", buf[i]);
}
Com_Printf(" #%-2d %s\n", i - 2, desc);
#ifdef Q_BACKTRACE
if (sym) {
free(sym);
}
#endif
}
}
/*
==============================================================
Asynchronous Crash Logging
==============================================================
*/
typedef struct backtrace_s {
int size;
void *buf[100];
} backtrace_t;
static int Sys_CrashBacktrace(void **buffer, int size, const ucontext_t *context);
static qboolean Sys_CrashWrite(int fd, const void *buf, size_t len);
static void Sys_CrashWriteVm(int fd);
static void Sys_CrashWriteContext(int fd, const ucontext_t *context);
static void Sys_SigHandlerFatal(int sig, siginfo_t *info, void *context) {
static volatile sig_atomic_t signalcaught = 0;
ucontext_t *ucontext = (ucontext_t *)context;
if (!signalcaught) {
backtrace_t trace = { 0 };
signalcaught = 1;
Sys_CrashWrite(crashlogfd, info, sizeof(*info));
Sys_CrashWriteVm(crashlogfd);
Sys_CrashWriteContext(crashlogfd, ucontext);
trace.size = Sys_CrashBacktrace(trace.buf, ARRAY_LEN(trace.buf), ucontext);
Sys_CrashWrite(crashlogfd, &trace, sizeof(trace));
Sys_CrashWrite(crashlogfd, &consoleLog, sizeof(consoleLog));
close(crashlogfd);
}
// reraise the signal with default handler
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = SIG_DFL;
sigemptyset(&act.sa_mask);
sigaction(sig, &act, NULL);
raise(sig);
}
static qboolean Sys_CrashWrite(int fd, const void *buf, size_t len) {
unsigned count = 0;
while (count < len) {
int ret = write(fd, buf, len - count);
if (ret == 0) {
return qfalse;
}
if (ret == -1) {
if (errno == EINTR) {
continue; // a signal was caught
} else {
perror("Sys_CrashWrite()");
return qfalse;
}
}
count += ret;
}
return qtrue;
}
static qboolean Sys_CrashRead(int fd, void *buf, size_t len) {
unsigned count = 0;
while (count < len) {
int ret = read(fd, buf, len - count);
if (ret == 0) {
return qfalse;
}
if (ret == -1) {
if (errno == EINTR) {
continue; // a signal was caught
} else {
perror("Sys_CrashRead()");
return qfalse;
}
}
count += ret;
}
return qtrue;
}
extern vm_t vmTable[MAX_VM];
static void Sys_CrashWriteVm(int fd) {
for (int i = 0; i < MAX_VM; i++) {
vm_t *vm = &vmTable[i];
Sys_CrashWrite(fd, vm, sizeof(*vm));
Sys_CrashWrite(fd, vm->instructionPointers, sizeof(intptr_t) * vm->instructionCount);
for (vmSymbol_t *sym = vm->symbols; sym; sym = sym->next) {
int size = sizeof(vmSymbol_t) + strlen(sym->symName); // ending '\0' is in vmSymbol_t
Sys_CrashWrite(fd, &size, sizeof(size));
Sys_CrashWrite(fd, sym, size);
}
}
}
static void Sys_CrashReadVm(int fd) {
for (int i = 0; i < MAX_VM; i++) {
vm_t *vm = &vmTable[i];
Sys_CrashRead(fd, vm, sizeof(*vm));
vm->instructionPointers = (intptr_t *)malloc(sizeof(intptr_t) * vm->instructionCount);
Sys_CrashRead(fd, vm->instructionPointers, sizeof(intptr_t) * vm->instructionCount);
for (vmSymbol_t **sym = &(vm->symbols); *sym; sym = &((*sym)->next)) {
int size;
Sys_CrashRead(fd, &size, sizeof(size));
*sym = (vmSymbol_t *)malloc(size);
Sys_CrashRead(fd, *sym, size);
}
}
}
static void Sys_CrashWriteContext(int fd, const ucontext_t *context) {
#ifdef __GNU_LIBRARY__
#if defined(__i386__) || defined(__amd64__)
Sys_CrashWrite(crashlogfd, context, sizeof(ucontext_t));
Sys_CrashWrite(crashlogfd, context->uc_mcontext.fpregs, sizeof(*context->uc_mcontext.fpregs));
#endif
#endif
}
static qboolean Sys_CrashReadContext(int fd, ucontext_t *context) {
#ifdef __GNU_LIBRARY__
#if defined(__i386__) || defined(__amd64__)
if (!Sys_CrashRead(fd, context, sizeof(ucontext_t))) {
return qfalse;
}
context->uc_mcontext.fpregs = (fpregset_t)malloc(sizeof(*context->uc_mcontext.fpregs));
if (!Sys_CrashRead(fd, context->uc_mcontext.fpregs, sizeof(*context->uc_mcontext.fpregs))) {
return qfalse;
}
#endif
#endif
return qtrue;
}
static sigjmp_buf invalidFP;
static void Sys_SigHandlerInvalidFP(int sig) {