-
Notifications
You must be signed in to change notification settings - Fork 130
/
PosixCommon.cpp
2579 lines (2183 loc) · 64.2 KB
/
PosixCommon.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 "Common.h"
#include "BFPlatform.h"
#include <sys/stat.h>
#ifndef BF_PLATFORM_DARWIN
#include <sys/sysinfo.h>
#endif
#include <sys/wait.h>
#include <wchar.h>
#include <fcntl.h>
#include <time.h>
#ifdef BFP_HAS_DLINFO
#include <link.h>
#endif
#include <dirent.h>
#include <syslog.h>
#include <unistd.h>
#include <signal.h>
#include <spawn.h>
#include <dlfcn.h>
#include "../PlatformInterface.h"
#include "../PlatformHelper.h"
#include "../../util/CritSect.h"
#include "../../util/Dictionary.h"
#include "../../util/Hash.h"
#include "../../third_party/putty/wildcard.h"
#ifdef BFP_HAS_EXECINFO
#include <execinfo.h>
#endif
#ifdef BFP_HAS_BACKTRACE
#ifdef BFP_BACKTRACE_PATH
#include BFP_BACKTRACE_PATH
#elif BFP_HAS_BACKTRACE
#include "backtrace.h"
#include "backtrace-supported.h"
#endif
#endif
#define STB_SPRINTF_DECORATE(name) BF_stbsp_##name
#include "../../third_party/stb/stb_sprintf.h"
#include <cxxabi.h>
#include <random>
#ifndef BFP_PRINTF
#define BFP_PRINTF(...) printf (__VA_ARGS__)
#define BFP_ERRPRINTF(...) fprintf (stderr, __VA_ARGS__)
#endif
//#include <cxxabi.h>
//using __cxxabiv1::__cxa_demangle;
USING_NS_BF;
struct BfpPipeInfo
{
String mPipePath;
int mWriteHandle;
};
struct BfpFile
{
BfpPipeInfo* mPipeInfo;
int mHandle;
bool mNonBlocking;
bool mAllowTimeout;
bool mIsStd;
BfpFile()
{
mPipeInfo = NULL;
mHandle = -1;
mNonBlocking = false;
mAllowTimeout = false;
mIsStd = false;
}
BfpFile(int handle)
{
mPipeInfo = NULL;
mHandle = handle;
mNonBlocking = false;
mAllowTimeout = false;
mIsStd = false;
}
~BfpFile()
{
delete mPipeInfo;
}
};
class FileWatchManager;
static FileWatchManager* gFileWatchManager = NULL;
class FileWatchManager
{
public:
virtual bool Init() = 0;
virtual void Shutdown() = 0;
virtual BfpFileWatcher* WatchDirectory(const char* path, BfpDirectoryChangeFunc callback, BfpFileWatcherFlags flags, void* userData, BfpFileResult* outResult) = 0;
virtual void Remove(BfpFileWatcher* watcher) = 0;
static FileWatchManager* Get();
};
class NullFilewatchManager : public FileWatchManager
{
virtual bool Init() { return false; }
virtual void Shutdown() {}
virtual BfpFileWatcher* WatchDirectory(const char* path, BfpDirectoryChangeFunc callback, BfpFileWatcherFlags flags, void* userData, BfpFileResult* outResult) { NOT_IMPL; return NULL; }
virtual void Remove(BfpFileWatcher* watcher) { NOT_IMPL; }
};
#ifndef BFP_HAS_FILEWATCHER
FileWatchManager* FileWatchManager::Get()
{
if (gFileWatchManager == NULL)
{
gFileWatchManager = new NullFilewatchManager();
gFileWatchManager->Init();
}
return gFileWatchManager;
}
#endif
BfpTimeStamp BfpToTimeStamp(const timespec& ts)
{
return (int64)(ts.tv_sec * 10000000) + (int64)(ts.tv_nsec / 100) + 116444736000000000;
}
int gBFPlatformLastError = 0;
uint32 Beefy::BFTickCount()
{
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now))
return 0;
return (uint32)((uint64)now.tv_sec * 1000.0 + (uint64)now.tv_nsec / 1000000);
}
int64 Beefy::EndianSwap(int64 val)
{
return __builtin_bswap64(val);
}
/*int* GetStdHandle(int32 handleId)
{
if (handleId == STD_INPUT_HANDLE)
return (int*)STDIN_FILENO;
if (handleId == STD_OUTPUT_HANDLE)
return (int*)STDOUT_FILENO;
return (int*)STDERR_FILENO;
}*/
/*int32 GetFileType(HANDLE fileHandle)
{
if (isatty(file->mHandleHandle))
return FILE_TYPE_CHAR;
return FILE_TYPE_DISK;
}*/
/*bool WriteFile(HANDLE hFile, void* lpBuffer, uint32 nNumberOfBytesToWrite, uint32* lpNumberOfBytesWritten, OVERLAPPED* lpOverlapped)
{
#ifdef BF_PLATFORM_IOS
int logType = -1;
if (hFile == (int*)STDOUT_FILENO)
logType = LOG_WARNING;
else if (hFile == (int*)STDERR_FILENO)
logType = LOG_ERR;
if (logType != -1)
{
static std::string strOut;
strOut.resize(nNumberOfBytesToWrite);
memcpy(&strOut[0], lpBuffer, nNumberOfBytesToWrite);
if ((strOut[0] != '\r') && (strOut[0] != '\n'))
syslog(LOG_WARNING, "%s", strOut.c_str());
}
#endif
int writeCount = (int)::write((int)(intptr)hFile, lpBuffer, nNumberOfBytesToWrite);
if (writeCount == -1)
{
//TODO: set gBFPlatformLastError
lpNumberOfBytesWritten = 0;
return false;
}
*lpNumberOfBytesWritten = (uint32)writeCount;
return true;
}*/
int64 Beefy::GetFileTimeWrite(const StringImpl& path)
{
struct stat statbuf = {0};
int result = stat(path.c_str(), &statbuf);
if (result == -1)
return 0;
return statbuf.st_mtime;
}
/*DWORD GetTimeZoneInformation(TIME_ZONE_INFORMATION* lpTimeZoneInformation)
{
std::wstring tzName0 = Beefy::UTF8Decode(tzname[0]);
std::wstring tzName1 = Beefy::UTF8Decode(tzname[1]);
bool isDST = false;
time_t timeNow;
time(&timeNow);
tm tmNow = *gmtime(&timeNow);
isDST = tmNow.tm_isdst;
struct tm checkTM;
memset(&checkTM, 0, sizeof(tm));
checkTM.tm_mday = 1;
checkTM.tm_year = tmNow.tm_year;
time_t checkTime = mktime(&checkTM);
time_t lastOffset = 0;
time_t minOffset = 0;
time_t maxOffset = 0;
for (int pass = 0; pass < 2; pass++)
{
int searchDir = 60*60*24;
int thresholdCount = 0;
while (true)
{
checkTime += searchDir;
tm checkTM = *gmtime(&checkTime);
if (checkTM.tm_year != tmNow.tm_year)
break; // No DST
mktime(&checkTM);
time_t offset = checkTM.tm_gmtoff;
if (lastOffset != offset)
{
if (thresholdCount == 0)
{
minOffset = offset;
maxOffset = offset;
}
else if (thresholdCount == 3)
{
SYSTEMTIME* sysTimeP = (offset == minOffset) ?
&lpTimeZoneInformation->StandardDate :
&lpTimeZoneInformation->DaylightDate;
if (offset == minOffset)
tzName0 = Beefy::UTF8Decode(checkTM.tm_zone);
else
tzName1 = Beefy::UTF8Decode(checkTM.tm_zone);
sysTimeP->wDay = 0;
sysTimeP->wDayOfWeek = 0;
sysTimeP->wYear = checkTM.tm_year + 1900;
sysTimeP->wMonth = checkTM.tm_mon;
sysTimeP->wDay = checkTM.tm_mday + 1;
sysTimeP->wHour = checkTM.tm_hour;
sysTimeP->wMinute = checkTM.tm_min;
sysTimeP->wSecond = checkTM.tm_sec;
sysTimeP->wMilliseconds = 0;
break;
}
else
{
if (thresholdCount == 1)
searchDir /= -24;
else
searchDir /= -60;
minOffset = std::min(minOffset, offset);
maxOffset = std::max(maxOffset, offset);
}
thresholdCount++;
lastOffset = offset;
}
}
}
wcsncpy(lpTimeZoneInformation->StandardName, tzName0.c_str(), 32);
wcsncpy(lpTimeZoneInformation->DaylightName, tzName1.c_str(), 32);
lpTimeZoneInformation->DaylightBias = (int32)maxOffset;
lpTimeZoneInformation->StandardBias = (int32)minOffset;
if (minOffset == maxOffset)
return 0;
return isDST ? 2 : 1;
}*/
bool Beefy::FileExists(const StringImpl& path, String* outActualName)
{
struct stat statbuf = {0};
int result = stat(path.c_str(), &statbuf);
if (result != 0)
return false;
return !S_ISDIR(statbuf.st_mode);
}
bool Beefy::DirectoryExists(const StringImpl& path, String* outActualName)
{
struct stat statbuf = {0};
int result = stat(path.c_str(), &statbuf);
if (result != 0)
return false;
return S_ISDIR(statbuf.st_mode);
}
uint64 Beefy::BFGetTickCountMicro()
{
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now))
return 0;
return ((uint64)now.tv_sec * 1000000.0 + (uint64)now.tv_nsec / 1000);
}
uint64 Beefy::BFGetTickCountMicroFast()
{
return BFGetTickCountMicro();
}
/*
int64 abs(int64 val)
{
return llabs(val);
}
*/
void mkdir(const char* path)
{
mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
typedef void(*CrashInfoFunc)();
struct BfpGlobalData
{
CritSect mSysCritSect;
String mCrashInfo;
Array<CrashInfoFunc> mCrashInfoFuncs;
};
static BfpGlobalData* gBfpGlobal;
static BfpGlobalData* BfpGetGlobalData()
{
if (gBfpGlobal == NULL)
gBfpGlobal = new BfpGlobalData();
return gBfpGlobal;
}
#ifdef BFP_HAS_BACKTRACE
struct bt_ctx {
struct backtrace_state *state;
int error;
};
static void error_callback(void *data, const char *msg, int errnum)
{
struct bt_ctx *ctx = (bt_ctx*)data;
BFP_ERRPRINTF("ERROR: %s (%d)", msg, errnum);
ctx->error = 1;
}
static void syminfo_callback (void *data, uintptr_t pc, const char *symname, uintptr_t symval, uintptr_t symsize)
{
char str[4096];
if (symname)
BF_stbsp_snprintf(str, 4096, "%@ %s\n", pc, symname);
else
BF_stbsp_snprintf(str, 4096, "%@\n", pc);
BFP_ERRPRINTF("%s", str);
}
static int full_callback(void *data, uintptr_t pc, const char* filename, int lineno, const char* function)
{
struct bt_ctx *ctx = (bt_ctx*)data;
if (function)
{
int status = -1;
char* demangledName = abi::__cxa_demangle(function, NULL, NULL, &status );
const char* showName = (demangledName != NULL) ? demangledName : function;
char str[4096];
BF_stbsp_snprintf(str, 4096, "%@ %s %s:%d\n", pc, showName, filename?filename:"??", lineno);
BFP_ERRPRINTF("%s", str);
if (demangledName != NULL)
free(demangledName);
}
else
backtrace_syminfo (ctx->state, pc, syminfo_callback, error_callback, data);
return 0;
}
static int simple_callback(void *data, uintptr_t pc)
{
struct bt_ctx *ctx = (bt_ctx*)data;
backtrace_pcinfo(ctx->state, pc, full_callback, error_callback, data);
return 0;
}
static inline void bt(struct backtrace_state *state)
{
struct bt_ctx ctx = {state, 0};
//backtrace_print(state, 0, stdout);
backtrace_simple(state, 2, simple_callback, error_callback, &ctx);
}
#endif
typedef void(*CrashInfoFunc)();
static String gCmdLine;
static String gExePath;
typedef struct _Unwind_Context _Unwind_Context; // opaque
typedef enum {
_URC_NO_REASON = 0,
_URC_OK = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9
} _Unwind_Reason_Code;
typedef _Unwind_Reason_Code (*_Unwind_Trace_Fn)(struct _Unwind_Context *, void *);
extern "C" _Unwind_Reason_Code _Unwind_Backtrace(_Unwind_Trace_Fn, void *);
extern "C" uintptr_t _Unwind_GetIP(struct _Unwind_Context *context);
static String gUnwindExecStr;
static int gUnwindIdx = 0;
static _Unwind_Reason_Code UnwindHandler(struct _Unwind_Context* context, void* ref)
{
gUnwindIdx++;
if (gUnwindIdx < 2)
return _URC_NO_REASON;
void* addr = (void*)_Unwind_GetIP(context);
#if BFP_HAS_ATOS
gUnwindExecStr += StrFormat(" %p", addr);
#else
Dl_info info;
if (dladdr(addr, &info))
{
if (info.dli_sname)
BFP_ERRPRINTF("0x%p %s\n", addr, info.dli_sname);
else if (info.dli_fname)
BFP_ERRPRINTF("0x%p %s\n", addr, info.dli_fname);
else
BFP_ERRPRINTF("0x%p\n", addr);
}
#endif
return _URC_NO_REASON;
}
static bool FancyBacktrace()
{
gUnwindExecStr += StrFormat("atos -p %d", getpid());
_Unwind_Backtrace(&UnwindHandler, NULL);
#if BFP_HAS_ATOS
return system(gUnwindExecStr.c_str()) == 0;
#else
return true;
#endif
}
static void Crashed()
{
//
{
AutoCrit autoCrit(BfpGetGlobalData()->mSysCritSect);
String debugDump;
debugDump += "**** FATAL APPLICATION ERROR ****\n";
for (auto func : BfpGetGlobalData()->mCrashInfoFuncs)
func();
if (!BfpGetGlobalData()->mCrashInfo.IsEmpty())
{
debugDump += BfpGetGlobalData()->mCrashInfo;
debugDump += "\n";
}
BFP_ERRPRINTF("%s", debugDump.c_str());
}
if (!FancyBacktrace())
{
#ifdef BFP_HAS_EXECINFO
void* array[64];
size_t size;
char** strings;
size_t i;
size = backtrace(array, 64);
strings = backtrace_symbols(array, size);
for (i = 0; i < size; i++)
BFP_ERRPRINTF("%s\n", strings[i]);
free(strings);
#endif
}
exit(1);
}
static void SigHandler(int sig)
{
//printf("SigHandler paused...\n");
const char* sigName = NULL;
switch (sig)
{
case SIGFPE:
sigName = "SIGFPE";
break;
case SIGSEGV:
sigName = "SIGSEGV";
break;
case SIGABRT:
sigName = "SIGABRT";
break;
case SIGILL:
sigName = "SIGILL";
break;
}
if (sigName != NULL)
BfpGetGlobalData()->mCrashInfo += StrFormat("Signal: %s\n", sigName);
else
BfpGetGlobalData()->mCrashInfo += StrFormat("Signal: %d\n", sig);
Crashed();
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_Init(int version, BfpSystemInitFlags flags)
{
BfpGetGlobalData();
if (version != BFP_VERSION)
{
BfpSystem_FatalError(StrFormat("Bfp build version '%d' does not match requested version '%d'", BFP_VERSION, version).c_str(), "BFP FATAL ERROR");
}
struct sigaction ignoreAction = { SIG_IGN };
sigaction(SIGPIPE, &ignoreAction, NULL);
//if (ptrace(PTRACE_TRACEME, 0, 1, 0) != -1)
{
//ptrace(PTRACE_DETACH, 0, 1, 0);
//signal(SIGSEGV, SigHandler);
//signal(SIGFPE, SigHandler);
//signal(SIGABRT, SigHandler);
/*struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_sigaction = signal_segv;
action.sa_flags = SA_SIGINFO;
if(sigaction(SIGSEGV, &action, NULL) < 0)
perror("sigaction");*/
}
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_InitCrashCatcher(BfpSystemInitFlags flags)
{
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_ShutdownCrashCatcher()
{
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCommandLine(int argc, char** argv)
{
char exePath[PATH_MAX] = { 0 };
int nchar = readlink("/proc/self/exe", exePath, PATH_MAX);
if (nchar > 0)
{
gExePath = exePath;
}
else
{
char* relPath = argv[0];
char* cwd = getcwd(NULL, 0);
gExePath = GetAbsPath(relPath, cwd);
free(cwd);
}
for (int i = 0; i < argc; i++)
{
if (i != 0)
gCmdLine.Append(' ');
String arg = argv[i];
if (arg.IsEmpty() || arg.Contains(' ') || arg.Contains('\t') || arg.Contains('\r') || arg.Contains('\n') || arg.Contains('\"'))
{
arg.Replace("\"", "\\\"");
gCmdLine.Append("\"");
gCmdLine.Append(arg);
gCmdLine.Append("\"");
}
else
gCmdLine.Append(arg);
}
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCrashReportKind(BfpCrashReportKind crashReportKind)
{
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfoFunc(BfpCrashInfoFunc crashInfoFunc)
{
AutoCrit autoCrit(BfpGetGlobalData()->mSysCritSect);
BfpGetGlobalData()->mCrashInfoFuncs.Add(crashInfoFunc);
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_AddCrashInfo(const char* str) // Can do at any time, or during CrashInfoFunc callbacks
{
AutoCrit autoCrit(BfpGetGlobalData()->mSysCritSect);
BfpGetGlobalData()->mCrashInfo.Append(str);
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_SetCrashRelaunchCmd(const char* str)
{
}
void BfpSystem_Shutdown()
{
if (gFileWatchManager != NULL)
{
gFileWatchManager->Shutdown();
gFileWatchManager = NULL;
}
}
BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_TickCount()
{
return Beefy::BFTickCount();
}
BFP_EXPORT BfpTimeStamp BFP_CALLTYPE BfpSystem_GetTimeStamp()
{
struct timeval tv;
BfpTimeStamp result = 11644473600LL;
gettimeofday(&tv, NULL);
result += tv.tv_sec;
result *= 10000000LL;
result += tv.tv_usec * 10;
return result;
}
BFP_EXPORT uint16 BFP_CALLTYPE BfpSystem_EndianSwap16(uint16 val)
{
return __builtin_bswap16(val);
}
BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_EndianSwap32(uint32 val)
{
return __builtin_bswap32(val);
}
BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_EndianSwap64(uint64 val)
{
return __builtin_bswap64(val);
}
BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchange32(uint32* ptr, uint32 val)
{
// __sync_lock_test_and_set only has Acquire semantics, so we need a __sync_synchronize to enforce a full barrier
uint32 prevVal = __sync_lock_test_and_set(ptr, val);
__sync_synchronize();
return prevVal;
}
BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchange64(uint64* ptr, uint64 val)
{
// __sync_lock_test_and_set only has Acquire semantics, so we need a __sync_synchronize to enforce a full barrier
uint64 prevVal = __sync_lock_test_and_set(ptr, val);
__sync_synchronize();
return prevVal;
}
BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd32(uint32* ptr, uint32 val)
{
return __sync_fetch_and_add(ptr, val);
}
BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedExchangeAdd64(uint64* ptr, uint64 val)
{
return __sync_fetch_and_add(ptr, val);
}
BFP_EXPORT uint32 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange32(uint32* ptr, uint32 oldVal, uint32 newVal)
{
return __sync_val_compare_and_swap(ptr, oldVal, newVal);
}
BFP_EXPORT uint64 BFP_CALLTYPE BfpSystem_InterlockedCompareExchange64(uint64* ptr, uint64 oldVal, uint64 newVal)
{
return __sync_val_compare_and_swap(ptr, oldVal, newVal);
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_FatalError(const char* error, const char* title)
{
BFP_ERRPRINTF("%s\n", error);
fflush(stderr);
Crashed();
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetCommandLine(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
{
TryStringOut(gCmdLine, outStr, inOutStrSize, (BfpResult*)outResult);
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetExecutablePath(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
{
#ifdef BF_PLATFORM_DARWIN
if (gExePath.IsEmpty())
{
char path[4096];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0)
gExePath = path;
// When when running with a './file', we end up with an annoying '/./' in our path
gExePath.Replace("/./", "/");
}
#endif
TryStringOut(gExePath, outStr, inOutStrSize, (BfpResult*)outResult);
}
extern char **environ;
BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetEnvironmentStrings(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
{
String env;
char** envPtr = environ;
while (true)
{
char* envStr = *envPtr;
if (envStr == NULL)
break;
env.Append(envStr, strlen(envStr) + 1);
++envPtr;
}
TryStringOut(env, outStr, inOutStrSize, (BfpResult*)outResult);
}
BFP_EXPORT int BFP_CALLTYPE BfpSystem_GetNumLogicalCPUs(BfpSystemResult* outResult)
{
#ifdef BF_PLATFORM_ANDROID
//TODO: Handle this
OUTRESULT(BfpSystemResult_Ok);
return 1;
#elif defined BF_PLATFORM_DARWIN
OUTRESULT(BfpSystemResult_Ok);
int count = 1;
size_t count_len = sizeof(count);
sysctlbyname("hw.logicalcpu", &count, &count_len, NULL, 0);
return count;
#else
OUTRESULT(BfpSystemResult_Ok);
return get_nprocs_conf();
#endif
}
BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTick()
{
return 10000000;
}
BFP_EXPORT int64 BFP_CALLTYPE BfpSystem_GetCPUTickFreq()
{
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (now.tv_sec * 10000000LL) + now.tv_nsec / 100;
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_CreateGUID(BfpGUID* outGuid)
{
// uuid_t guid;
// uuid_generate(guid);
// BfpGUID bfpGuid;
// memcpy(&bfpGuid, guid, 16);
// return bfpGuid;
uint8* ptr = (uint8*)outGuid;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<uint8> dis(0, 255);
for (int i = 0; i < 16; i++)
ptr[i] = dis(gen);
// variant must be 10xxxxxx
ptr[8] &= 0xBF;
ptr[8] |= 0x80;
// version must be 0100xxxx
ptr[6] &= 0x4F;
ptr[6] |= 0x40;
}
BFP_EXPORT void BFP_CALLTYPE BfpSystem_GetComputerName(char* outStr, int* inOutStrSize, BfpSystemResult* outResult)
{
char hostName[1024];
gethostname(hostName, 1024);
TryStringOut(hostName, outStr, inOutStrSize, (BfpResult*)outResult);
}
// BfpProcess
BFP_EXPORT intptr BFP_CALLTYPE BfpProcess_GetCurrentId()
{
return getpid();
}
BFP_EXPORT bool BFP_CALLTYPE BfpProcess_IsRemoteMachine(const char* machineName)
{
return false;
}
BFP_EXPORT BfpProcess* BFP_CALLTYPE BfpProcess_GetById(const char* machineName, int processId, BfpProcessResult* outResult)
{
NOT_IMPL;
return NULL;
}
BFP_EXPORT void BFP_CALLTYPE BfpProcess_Enumerate(const char* machineName, BfpProcess** outProcesses, int* inOutProcessesSize, BfpProcessResult* outResult)
{
NOT_IMPL;
}
BFP_EXPORT void BFP_CALLTYPE BfpProcess_Release(BfpProcess* process)
{
NOT_IMPL;
}
BFP_EXPORT bool BFP_CALLTYPE BfpProcess_WaitFor(BfpProcess* process, int waitMS, int* outExitCode, BfpProcessResult* outResult)
{
NOT_IMPL;
}
BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetMainWindowTitle(BfpProcess* process, char* outTitle, int* inOutTitleSize, BfpProcessResult* outResult)
{
NOT_IMPL;
}
BFP_EXPORT void BFP_CALLTYPE BfpProcess_GetProcessName(BfpProcess* process, char* outName, int* inOutNameSize, BfpProcessResult* outResult)
{
NOT_IMPL;
}
BFP_EXPORT int BFP_CALLTYPE BfpProcess_GetProcessId(BfpProcess* process)
{
NOT_IMPL;
return 0;
}
// BfpSpawn
struct BfpSpawn
{
int mPid;
bool mExited;
int mStatus;
int mStdInFD;
int mStdOutFD;
int mStdErrFD;
};
BFP_EXPORT BfpSpawn* BFP_CALLTYPE BfpSpawn_Create(const char* inTargetPath, const char* args, const char* workingDir, const char* env, BfpSpawnFlags flags, BfpSpawnResult* outResult)
{
Beefy::Array<Beefy::StringView> stringViews;
//printf("BfpSpawn_Create: %s %s %x\n", inTargetPath, args, flags);
char* prevWorkingDir = NULL;
if ((workingDir != NULL) && (workingDir[0] != 0))
{
if (chdir(workingDir) != 0)
{
//printf("CHDIR failed %s\n", workingDir);
OUTRESULT(BfpSpawnResult_UnknownError);
return NULL;
}
prevWorkingDir = getcwd(NULL, 0);
}
defer(
{
if (prevWorkingDir != NULL)
{
chdir(prevWorkingDir);
free(prevWorkingDir);
}
});
String newArgs;
String tempFileName;
if ((flags & BfpSpawnFlag_UseArgsFile) != 0)
{
char tempFileNameStr[256];
int size = 256;
BfpFileResult fileResult;
BfpFile_GetTempFileName(tempFileNameStr, &size, &fileResult);
if (fileResult == BfpFileResult_Ok)
{
tempFileName = tempFileNameStr;
BfpFileResult fileResult;
BfpFile* file = BfpFile_Create(tempFileNameStr, BfpFileCreateKind_CreateAlways, BfpFileCreateFlag_Write, BfpFileAttribute_Normal, &fileResult);
if (file == NULL)
{
OUTRESULT(BfpSpawnResult_TempFileError);
return NULL;
}
if ((flags & BfpSpawnFlag_UseArgsFile_Native) != 0)
{
UTF16String wStr = UTF8Decode(args);
if ((flags & BfpSpawnFlag_UseArgsFile_BOM) != 0)
{
uint8 bom[2] = { 0xFF, 0xFE };
BfpFile_Write(file, bom, 2, -1, NULL);
}
BfpFile_Write(file, wStr.c_str(), wStr.length() * 2, -1, NULL);
}
else
BfpFile_Write(file, args, strlen(args), -1, NULL);
BfpFile_Release(file);
newArgs.Append("@");
newArgs.Append(tempFileName);
if (newArgs.Contains(' '))
{
newArgs.Insert(0, '\"');
newArgs.Append('\"');
}
args = newArgs.c_str();
}
}
int32 firstCharIdx = -1;
bool inQuote = false;
String targetPath = inTargetPath;
String verb;
if ((flags & BfpSpawnFlag_UseShellExecute) != 0)
{
String target = targetPath;
int barPos = (int)target.IndexOf('|');
if (barPos != -1)
{
verb = targetPath.Substring(barPos + 1);
targetPath.RemoveToEnd(barPos);
}
}
// When executing in a shell the arguments are not split
if ((flags & BfpSpawnFlag_UseShellExecute) == 0)
{
int32 i = 0;
for ( ; true; i++)
{
char c = args[i];
if (c == '\0')
break;
if ((c == ' ') && (!inQuote))
{
if (firstCharIdx != -1)
{