-
Notifications
You must be signed in to change notification settings - Fork 252
/
Remotery.c
10313 lines (8531 loc) · 326 KB
/
Remotery.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2014-2022 Celtoys Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
@Contents:
@DEPS: External Dependencies
@TIMERS: Platform-specific timers
@TLS: Thread-Local Storage
@ERROR: Error handling
@ATOMIC: Atomic Operations
@RNG: Random Number Generator
@LFSR: Galois Linear-feedback Shift Register
@VMBUFFER: Mirror Buffer using Virtual Memory for auto-wrap
@NEW: New/Delete operators with error values for simplifying object create/destroy
@SAFEC: Safe C Library excerpts
@OSTHREADS: Wrappers around OS-specific thread functions
@THREADS: Cross-platform thread object
@OBJALLOC: Reusable Object Allocator
@DYNBUF: Dynamic Buffer
@HASHTABLE: Integer pair hash map for inserts/finds. No removes for added simplicity.
@STRINGTABLE: Map from string hash to string offset in local buffer
@SOCKETS: Sockets TCP/IP Wrapper
@SHA1: SHA-1 Cryptographic Hash Function
@BASE64: Base-64 encoder
@MURMURHASH: Murmur-Hash 3
@WEBSOCKETS: WebSockets
@MESSAGEQ: Multiple producer, single consumer message queue
@NETWORK: Network Server
@SAMPLE: Base Sample Description (CPU by default)
@SAMPLETREE: A tree of samples with their allocator
@TPROFILER: Thread Profiler data, storing both sampling and instrumentation results
@TGATHER: Thread Gatherer, periodically polling for newly created threads
@TSAMPLER: Sampling thread contexts
@REMOTERY: Remotery
@CUDA: CUDA event sampling
@D3D11: Direct3D 11 event sampling
@D3D12: Direct3D 12 event sampling
@OPENGL: OpenGL event sampling
@METAL: Metal event sampling
@SAMPLEAPI: Sample API for user callbacks
@PROPERTYAPI: Property API for user callbacks
@PROPERTIES: Property API
*/
#define RMT_IMPL
#include "Remotery.h"
#ifdef RMT_PLATFORM_WINDOWS
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "winmm.lib")
#endif
#if RMT_ENABLED
// Global settings
static rmtSettings g_Settings;
static rmtBool g_SettingsInitialized = RMT_FALSE;
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@DEPS: External Dependencies
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
// clang-format off
//
// Required CRT dependencies
//
#if RMT_USE_TINYCRT
#include <TinyCRT/TinyCRT.h>
#include <TinyCRT/TinyWinsock.h>
#include <Memory/Memory.h>
#define CreateFileMapping CreateFileMappingA
#define RMT_ENABLE_THREAD_SAMPLER
#else
#ifdef RMT_PLATFORM_MACOS
#include <mach/mach_time.h>
#include <mach/vm_map.h>
#include <mach/mach.h>
#include <sys/time.h>
#else
#if !defined(__FreeBSD__) && !defined(__OpenBSD__)
#include <malloc.h>
#endif
#endif
#include <assert.h>
#include <stdio.h>
#include <time.h>
#include <limits.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#ifdef RMT_PLATFORM_WINDOWS
#include <winsock2.h>
#include <timeapi.h>
#ifndef __MINGW32__
#include <intrin.h>
#endif
#undef min
#undef max
#include <tlhelp32.h>
#include <winnt.h>
#include <processthreadsapi.h>
typedef long NTSTATUS; // winternl.h
#ifdef _XBOX_ONE
#ifdef _DURANGO
#include "xmem.h"
#endif
#else
#define RMT_ENABLE_THREAD_SAMPLER
#endif
#endif
#ifdef RMT_PLATFORM_LINUX
#if defined(__FreeBSD__) || defined(__OpenBSD__)
#include <pthread_np.h>
#else
#include <sys/prctl.h>
#endif
#endif
#if defined(RMT_PLATFORM_POSIX)
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>
#include <dlfcn.h>
#endif
#ifdef __MINGW32__
#include <pthread.h>
#endif
#endif
#if RMT_USE_CUDA
#include <cuda.h>
#endif
#if RMT_USE_LEGACY_ATOMICS==0
#if __cplusplus >= 199711L
#if !defined(RMT_USE_CPP_ATOMICS)
#define RMT_USE_CPP_ATOMICS
#endif
#elif __STDC_VERSION__ >= 201112L
#if !defined(__STDC_NO_ATOMICS__)
#if !defined(RMT_USE_C11_ATOMICS)
#define RMT_USE_C11_ATOMICS
#endif
#endif
#endif
#endif
#if defined(RMT_USE_C11_ATOMICS)
#include <stdatomic.h>
#elif defined(RMT_USE_CPP_ATOMICS)
#include <atomic>
#endif
// clang-format on
#if defined(_MSC_VER) && !defined(__clang__)
#define RMT_UNREFERENCED_PARAMETER(i) (i)
#else
#define RMT_UNREFERENCED_PARAMETER(i) (void)(1 ? (void)0 : ((void)i))
#endif
// Executes the given statement and returns from the calling function if it fails, returning the error with it
#define rmtTry(stmt) \
{ \
rmtError error = stmt; \
if (error != RMT_ERROR_NONE) \
return error; \
}
static rmtU8 minU8(rmtU8 a, rmtU8 b)
{
return a < b ? a : b;
}
static rmtU16 maxU16(rmtU16 a, rmtU16 b)
{
return a > b ? a : b;
}
static rmtS32 minS32(rmtS32 a, rmtS32 b)
{
return a < b ? a : b;
}
static rmtS32 maxS32(rmtS32 a, rmtS32 b)
{
return a > b ? a : b;
}
static rmtU32 minU32(rmtU32 a, rmtU32 b)
{
return a < b ? a : b;
}
static rmtU32 maxU32(rmtU32 a, rmtU32 b)
{
return a > b ? a : b;
}
static rmtS64 maxS64(rmtS64 a, rmtS64 b)
{
return a > b ? a : b;
}
// Memory management functions
static void* rmtMalloc(rmtU32 size)
{
return g_Settings.malloc(g_Settings.mm_context, size);
}
static void* rmtRealloc(void* ptr, rmtU32 size)
{
return g_Settings.realloc(g_Settings.mm_context, ptr, size);
}
static void rmtFree(void* ptr)
{
g_Settings.free(g_Settings.mm_context, ptr);
}
// File system functions
static FILE* rmtOpenFile(const char* filename, const char* mode)
{
#if defined(RMT_PLATFORM_WINDOWS) && !RMT_USE_TINYCRT
FILE* fp;
return fopen_s(&fp, filename, mode) == 0 ? fp : NULL;
#else
return fopen(filename, mode);
#endif
}
void rmtCloseFile(FILE* fp)
{
if (fp != NULL)
{
fclose(fp);
}
}
rmtBool rmtWriteFile(FILE* fp, const void* data, rmtU32 size)
{
assert(fp != NULL);
return fwrite(data, size, 1, fp) == size ? RMT_TRUE : RMT_FALSE;
}
#if RMT_USE_OPENGL
// DLL/Shared Library functions
static void* rmtLoadLibrary(const char* path)
{
#if defined(RMT_PLATFORM_WINDOWS)
return (void*)LoadLibraryA(path);
#elif defined(RMT_PLATFORM_POSIX)
return dlopen(path, RTLD_LOCAL | RTLD_LAZY);
#else
return NULL;
#endif
}
static void rmtFreeLibrary(void* handle)
{
#if defined(RMT_PLATFORM_WINDOWS)
FreeLibrary((HMODULE)handle);
#elif defined(RMT_PLATFORM_POSIX)
dlclose(handle);
#endif
}
#if defined(RMT_PLATFORM_WINDOWS)
typedef FARPROC ProcReturnType;
#else
typedef void* ProcReturnType;
#endif
static ProcReturnType rmtGetProcAddress(void* handle, const char* symbol)
{
#if defined(RMT_PLATFORM_WINDOWS)
return GetProcAddress((HMODULE)handle, (LPCSTR)symbol);
#elif defined(RMT_PLATFORM_POSIX)
return dlsym(handle, symbol);
#endif
}
#endif
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@TIMERS: Platform-specific timers
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
//
// Get millisecond timer value that has only one guarantee: multiple calls are consistently comparable.
// On some platforms, even though this returns milliseconds, the timer may be far less accurate.
//
static rmtU32 msTimer_Get()
{
#ifdef RMT_PLATFORM_WINDOWS
return (rmtU32)GetTickCount();
#else
clock_t time = clock();
// CLOCKS_PER_SEC is 128 on FreeBSD, causing div/0
#if defined(__FreeBSD__) || defined(__OpenBSD__)
rmtU32 msTime = (rmtU32)(time * 1000 / CLOCKS_PER_SEC);
#else
rmtU32 msTime = (rmtU32)(time / (CLOCKS_PER_SEC / 1000));
#endif
return msTime;
#endif
}
//
// Micro-second accuracy high performance counter
//
#ifndef RMT_PLATFORM_WINDOWS
typedef rmtU64 LARGE_INTEGER;
#endif
typedef struct
{
LARGE_INTEGER counter_start;
double counter_scale;
} usTimer;
static void usTimer_Init(usTimer* timer)
{
#if defined(RMT_PLATFORM_WINDOWS)
LARGE_INTEGER performance_frequency;
assert(timer != NULL);
// Calculate the scale from performance counter to microseconds
QueryPerformanceFrequency(&performance_frequency);
timer->counter_scale = 1000000.0 / performance_frequency.QuadPart;
// Record the offset for each read of the counter
QueryPerformanceCounter(&timer->counter_start);
#elif defined(RMT_PLATFORM_MACOS)
mach_timebase_info_data_t nsScale;
mach_timebase_info(&nsScale);
const double ns_per_us = 1.0e3;
timer->counter_scale = (double)(nsScale.numer) / ((double)nsScale.denom * ns_per_us);
timer->counter_start = mach_absolute_time();
#elif defined(RMT_PLATFORM_LINUX)
struct timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
timer->counter_start = (rmtU64)(tv.tv_sec * (rmtU64)1000000) + (rmtU64)(tv.tv_nsec * 0.001);
#endif
}
static rmtU64 usTimer_Get(usTimer* timer)
{
#if defined(RMT_PLATFORM_WINDOWS)
LARGE_INTEGER performance_count;
assert(timer != NULL);
// Read counter and convert to microseconds
QueryPerformanceCounter(&performance_count);
return (rmtU64)((performance_count.QuadPart - timer->counter_start.QuadPart) * timer->counter_scale);
#elif defined(RMT_PLATFORM_MACOS)
rmtU64 curr_time = mach_absolute_time();
return (rmtU64)((curr_time - timer->counter_start) * timer->counter_scale);
#elif defined(RMT_PLATFORM_LINUX)
struct timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
return ((rmtU64)(tv.tv_sec * (rmtU64)1000000) + (rmtU64)(tv.tv_nsec * 0.001)) - timer->counter_start;
#endif
}
static void msSleep(rmtU32 time_ms)
{
#ifdef RMT_PLATFORM_WINDOWS
Sleep(time_ms);
#elif defined(RMT_PLATFORM_POSIX)
usleep(time_ms * 1000);
#endif
}
static struct tm* TimeDateNow()
{
time_t time_now = time(NULL);
#if defined(RMT_PLATFORM_WINDOWS) && !RMT_USE_TINYCRT
// Discard the thread-safety benefit of gmtime_s
static struct tm tm_now;
gmtime_s(&tm_now, &time_now);
return &tm_now;
#else
return gmtime(&time_now);
#endif
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@TLS: Thread-Local Storage
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
#define TLS_INVALID_HANDLE 0xFFFFFFFF
#if defined(RMT_PLATFORM_WINDOWS)
typedef rmtU32 rmtTLS;
#else
typedef pthread_key_t rmtTLS;
#endif
static rmtError tlsAlloc(rmtTLS* handle)
{
assert(handle != NULL);
#if defined(RMT_PLATFORM_WINDOWS)
*handle = (rmtTLS)TlsAlloc();
if (*handle == TLS_OUT_OF_INDEXES)
{
*handle = TLS_INVALID_HANDLE;
return RMT_ERROR_TLS_ALLOC_FAIL;
}
#elif defined(RMT_PLATFORM_POSIX)
if (pthread_key_create(handle, NULL) != 0)
{
*handle = TLS_INVALID_HANDLE;
return RMT_ERROR_TLS_ALLOC_FAIL;
}
#endif
return RMT_ERROR_NONE;
}
static void tlsFree(rmtTLS handle)
{
assert(handle != TLS_INVALID_HANDLE);
#if defined(RMT_PLATFORM_WINDOWS)
TlsFree(handle);
#elif defined(RMT_PLATFORM_POSIX)
pthread_key_delete((pthread_key_t)handle);
#endif
}
static void tlsSet(rmtTLS handle, void* value)
{
assert(handle != TLS_INVALID_HANDLE);
#if defined(RMT_PLATFORM_WINDOWS)
TlsSetValue(handle, value);
#elif defined(RMT_PLATFORM_POSIX)
pthread_setspecific((pthread_key_t)handle, value);
#endif
}
static void* tlsGet(rmtTLS handle)
{
assert(handle != TLS_INVALID_HANDLE);
#if defined(RMT_PLATFORM_WINDOWS)
return TlsGetValue(handle);
#elif defined(RMT_PLATFORM_POSIX)
return pthread_getspecific((pthread_key_t)handle);
#endif
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@ERROR: Error handling
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
// Used to store per-thread error messages
// Static so that we can set error messages from code the Remotery object depends on
static rmtTLS g_lastErrorMessageTlsHandle = TLS_INVALID_HANDLE;
static const rmtU32 g_errorMessageSize = 1024;
static rmtError rmtMakeError(rmtError in_error, rmtPStr error_message)
{
char* thread_message_ptr;
rmtU32 error_len;
// Allocate the TLS on-demand
// TODO(don): Make this thread-safe
if (g_lastErrorMessageTlsHandle == TLS_INVALID_HANDLE)
{
rmtTry(tlsAlloc(&g_lastErrorMessageTlsHandle));
}
// Allocate the string storage for the error message on-demand
thread_message_ptr = (char*)tlsGet(g_lastErrorMessageTlsHandle);
if (thread_message_ptr == NULL)
{
thread_message_ptr = (char*)rmtMalloc(g_errorMessageSize);
if (thread_message_ptr == NULL)
{
return RMT_ERROR_MALLOC_FAIL;
}
tlsSet(g_lastErrorMessageTlsHandle, (void*)thread_message_ptr);
}
// Safe copy of the error text without going via strcpy_s down below
error_len = (rmtU32)strlen(error_message);
error_len = error_len >= g_errorMessageSize ? g_errorMessageSize - 1 : error_len;
memcpy(thread_message_ptr, error_message, error_len);
thread_message_ptr[error_len] = 0;
return in_error;
}
RMT_API rmtPStr rmt_GetLastErrorMessage()
{
rmtPStr thread_message_ptr;
// No message to specify if `rmtMakeError` failed or one hasn't been set yet
if (g_lastErrorMessageTlsHandle == TLS_INVALID_HANDLE)
{
return "No error message";
}
thread_message_ptr = (rmtPStr)tlsGet(g_lastErrorMessageTlsHandle);
if (thread_message_ptr == NULL)
{
return "No error message";
}
return thread_message_ptr;
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@MUTEX: Mutexes
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
#ifdef RMT_PLATFORM_WINDOWS
typedef CRITICAL_SECTION rmtMutex;
#else
typedef pthread_mutex_t rmtMutex;
#endif
static void mtxInit(rmtMutex* mutex)
{
assert(mutex != NULL);
#if defined(RMT_PLATFORM_WINDOWS)
InitializeCriticalSection(mutex);
#elif defined(RMT_PLATFORM_POSIX)
pthread_mutex_init(mutex, NULL);
#endif
}
static void mtxLock(rmtMutex* mutex)
{
assert(mutex != NULL);
#if defined(RMT_PLATFORM_WINDOWS)
EnterCriticalSection(mutex);
#elif defined(RMT_PLATFORM_POSIX)
pthread_mutex_lock(mutex);
#endif
}
static void mtxUnlock(rmtMutex* mutex)
{
assert(mutex != NULL);
#if defined(RMT_PLATFORM_WINDOWS)
LeaveCriticalSection(mutex);
#elif defined(RMT_PLATFORM_POSIX)
pthread_mutex_unlock(mutex);
#endif
}
static void mtxDelete(rmtMutex* mutex)
{
assert(mutex != NULL);
#if defined(RMT_PLATFORM_WINDOWS)
DeleteCriticalSection(mutex);
#elif defined(RMT_PLATFORM_POSIX)
pthread_mutex_destroy(mutex);
#endif
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@ATOMIC: Atomic Operations
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
// TODO(don): The CAS loops possible with this API are suboptimal. For example, AtomicCompareAndSwapU32 discards the
// return value which tells you the current (potentially mismatching) value of the location you want to modify. This
// means the CAS loop has to explicitly re-load this location on each modify attempt. Instead, the return value should
// be used to update the old value and an initial load only made once before the loop starts.
// TODO(don): Vary these types across versions of C and C++
#if defined(RMT_USE_C11_ATOMICS)
typedef _Atomic(rmtS32) rmtAtomicS32;
typedef _Atomic(rmtU32) rmtAtomicU32;
typedef _Atomic(rmtU64) rmtAtomicU64;
typedef _Atomic(rmtBool) rmtAtomicBool;
#define rmtAtomicPtr(type) _Atomic(type *)
#elif defined(RMT_USE_CPP_ATOMICS)
typedef std::atomic< rmtS32 > rmtAtomicS32;
typedef std::atomic< rmtU32 > rmtAtomicU32;
typedef std::atomic< rmtU64 > rmtAtomicU64;
typedef std::atomic< rmtBool > rmtAtomicBool;
#define rmtAtomicPtr(type) std::atomic< type * >
#else
typedef volatile rmtS32 rmtAtomicS32;
typedef volatile rmtU32 rmtAtomicU32;
typedef volatile rmtU64 rmtAtomicU64;
typedef volatile rmtBool rmtAtomicBool;
#define rmtAtomicPtr(type) volatile type*
#endif
typedef rmtAtomicPtr(void) rmtAtomicVoidPtr;
static rmtBool AtomicCompareAndSwapU32(rmtAtomicU32 volatile* val, rmtU32 old_val, rmtU32 new_val)
{
#if defined(RMT_USE_C11_ATOMICS)
return atomic_compare_exchange_strong(val, &old_val, new_val);
#elif defined(RMT_USE_CPP_ATOMICS)
return val->compare_exchange_strong(old_val, new_val);
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
return _InterlockedCompareExchange((long volatile*)val, new_val, old_val) == old_val ? RMT_TRUE : RMT_FALSE;
#elif defined(RMT_PLATFORM_POSIX) || defined(__MINGW32__)
return __sync_bool_compare_and_swap(val, old_val, new_val) ? RMT_TRUE : RMT_FALSE;
#endif
}
static rmtBool AtomicCompareAndSwapU64(rmtAtomicU64 volatile* val, rmtU64 old_val, rmtU64 new_val)
{
#if defined(RMT_USE_C11_ATOMICS)
return atomic_compare_exchange_strong(val, &old_val, new_val);
#elif defined(RMT_USE_CPP_ATOMICS)
return val->compare_exchange_strong(old_val, new_val);
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
return _InterlockedCompareExchange64((volatile LONG64*)val, (LONG64)new_val, (LONG64)old_val) == (LONG64)old_val
? RMT_TRUE
: RMT_FALSE;
#elif defined(RMT_PLATFORM_POSIX) || defined(__MINGW32__)
return __sync_bool_compare_and_swap(val, old_val, new_val) ? RMT_TRUE : RMT_FALSE;
#endif
}
static rmtBool AtomicCompareAndSwapPointer(rmtAtomicVoidPtr volatile* ptr, void* old_ptr, void* new_ptr)
{
#if defined(RMT_USE_C11_ATOMICS)
return atomic_compare_exchange_strong(ptr, &old_ptr, new_ptr);
#elif defined(RMT_USE_CPP_ATOMICS)
return ptr->compare_exchange_strong(old_ptr, new_ptr);
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
#ifdef _WIN64
return _InterlockedCompareExchange64((__int64 volatile*)ptr, (__int64)new_ptr, (__int64)old_ptr) == (__int64)old_ptr
? RMT_TRUE
: RMT_FALSE;
#else
return _InterlockedCompareExchange((long volatile*)ptr, (long)new_ptr, (long)old_ptr) == (long)old_ptr ? RMT_TRUE
: RMT_FALSE;
#endif
#elif defined(RMT_PLATFORM_POSIX) || defined(__MINGW32__)
return __sync_bool_compare_and_swap(ptr, old_ptr, new_ptr) ? RMT_TRUE : RMT_FALSE;
#endif
}
//
// NOTE: Does not guarantee a memory barrier
// TODO: Make sure all platforms don't insert a memory barrier as this is only for stats
// Alternatively, add strong/weak memory order equivalents
//
static rmtS32 AtomicAddS32(rmtAtomicS32* value, rmtS32 add)
{
#if defined(RMT_USE_C11_ATOMICS)
return atomic_fetch_add(value, add);
#elif defined(RMT_USE_CPP_ATOMICS)
return value->fetch_add(add);
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
return _InterlockedExchangeAdd((long volatile*)value, (long)add);
#elif defined(RMT_PLATFORM_POSIX) || defined(__MINGW32__)
return __sync_fetch_and_add(value, add);
#endif
}
static rmtU32 AtomicAddU32(rmtAtomicU32* value, rmtU32 add)
{
#if defined(RMT_USE_C11_ATOMICS)
return atomic_fetch_add(value, add);
#elif defined(RMT_USE_CPP_ATOMICS)
return value->fetch_add(add);
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
return (rmtU32)_InterlockedExchangeAdd((long volatile*)value, (long)add);
#elif defined(RMT_PLATFORM_POSIX) || defined(__MINGW32__)
return (rmtU32)__sync_fetch_and_add(value, add);
#endif
}
static void AtomicSubS32(rmtAtomicS32* value, rmtS32 sub)
{
// Not all platforms have an implementation so just negate and add
AtomicAddS32(value, -sub);
}
static rmtU32 AtomicStoreU32(rmtAtomicU32* value, rmtU32 set)
{
#if defined(RMT_USE_C11_ATOMICS)
return atomic_exchange(value, set);
#elif defined(RMT_USE_CPP_ATOMICS)
return value->exchange(set);
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
return (rmtU32)_InterlockedExchange((long volatile*)value, (long) set);
#elif defined(RMT_PLATFORM_POSIX) || defined(__MINGW32__)
return (rmtU32)__sync_lock_test_and_set(value, set);
#endif
}
static rmtU32 AtomicLoadU32(rmtAtomicU32* value)
{
#if defined(RMT_USE_C11_ATOMICS)
return atomic_load(value);
#elif defined(RMT_USE_CPP_ATOMICS)
return value->load();
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
return (rmtU32)_InterlockedExchangeAdd((long volatile*)value, (long)0);
#elif defined(RMT_PLATFORM_POSIX) || defined(__MINGW32__)
return (rmtU32)__sync_fetch_and_add(value, 0);
#endif
}
static void CompilerWriteFence()
{
#if defined(__clang__)
__asm__ volatile("" : : : "memory");
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
_WriteBarrier();
#else
asm volatile("" : : : "memory");
#endif
}
static void CompilerReadFence()
{
#if defined(__clang__)
__asm__ volatile("" : : : "memory");
#elif defined(RMT_PLATFORM_WINDOWS) && !defined(__MINGW32__)
_ReadBarrier();
#else
asm volatile("" : : : "memory");
#endif
}
static rmtU32 LoadAcquire(rmtAtomicU32* address)
{
rmtU32 value = *address;
CompilerReadFence();
return value;
}
static long* LoadAcquirePointer(long* volatile* ptr)
{
long* value = *ptr;
CompilerReadFence();
return value;
}
static void StoreRelease(rmtAtomicU32* address, rmtU32 value)
{
CompilerWriteFence();
*address = value;
}
static void StoreReleasePointer(long* volatile* ptr, long* value)
{
CompilerWriteFence();
*ptr = value;
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@RNG: Random Number Generator
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
//
// WELL: Well Equidistributed Long-period Linear
// These algorithms produce numbers with better equidistribution than MT19937 and improve upon "bit-mixing" properties. They are
// fast, come in many sizes, and produce higher quality random numbers.
//
// This implementation has a period of 2^512, or 10^154.
//
// Implementation from: Game Programming Gems 7, Random Number Generation Chris Lomont
// Documentation: http://www.lomont.org/Math/Papers/2008/Lomont_PRNG_2008.pdf
//
// Global RNG state for now
// Far better than interfering with the user's rand()
#define Well512_StateSize 16
static rmtU32 Well512_State[Well512_StateSize];
static rmtU32 Well512_Index;
static void Well512_Init(rmtU32 seed)
{
rmtU32 i;
// Generate initial state from seed
Well512_State[0] = seed;
for (i = 1; i < Well512_StateSize; i++)
{
rmtU32 prev = Well512_State[i - 1];
Well512_State[i] = (1812433253 * (prev ^ (prev >> 30)) + i);
}
Well512_Index = 0;
}
static rmtU32 Well512_RandomU32()
{
rmtU32 a, b, c, d;
a = Well512_State[Well512_Index];
c = Well512_State[(Well512_Index + 13) & 15];
b = a ^ c ^ (a << 16) ^ (c << 15);
c = Well512_State[(Well512_Index + 9) & 15];
c ^= (c >> 11);
a = Well512_State[Well512_Index] = b ^ c;
d = a ^ ((a << 5) & 0xDA442D24UL);
Well512_Index = (Well512_Index + 15) & 15;
a = Well512_State[Well512_Index];
Well512_State[Well512_Index] = a ^ b ^ d ^ (a << 2) ^ (b << 18) ^ (c << 28);
return Well512_State[Well512_Index];
}
static rmtU32 Well512_RandomOpenLimit(rmtU32 limit)
{
// Using % to modulo with range is just masking out the higher bits, leaving a result that's objectively biased.
// Dividing by RAND_MAX is better but leads to increased repetition at low ranges due to very large bucket sizes.
// Instead use multiple passes with smaller bucket sizes, rejecting results that don't fit into this smaller range.
rmtU32 bucket_size = UINT_MAX / limit;
rmtU32 bucket_limit = bucket_size * limit;
rmtU32 r;
do
{
r = Well512_RandomU32();
} while(r >= bucket_limit);
return r / bucket_size;
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@LFSR: Galois Linear-feedback Shift Register
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
static rmtU32 Log2i(rmtU32 x)
{
static const rmtU8 MultiplyDeBruijnBitPosition[32] =
{
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
// First round down to one less than a power of two
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return MultiplyDeBruijnBitPosition[(rmtU32)(x * 0x07C4ACDDU) >> 27];
}
static rmtU32 GaloisLFSRMask(rmtU32 table_size_log2)
{
// Taps for 4 to 8 bit ranges
static const rmtU8 XORMasks[] =
{
((1 << 0) | (1 << 1)), // 2
((1 << 1) | (1 << 2)), // 3
((1 << 2) | (1 << 3)), // 4
((1 << 2) | (1 << 4)), // 5
((1 << 4) | (1 << 5)), // 6
((1 << 5) | (1 << 6)), // 7
((1 << 3) | (1 << 4) | (1 << 5) | (1 << 7)), // 8
};
// Map table size to required XOR mask
assert(table_size_log2 >= 2);
assert(table_size_log2 <= 8);
return XORMasks[table_size_log2 - 2];
}
static rmtU32 GaloisLFSRNext(rmtU32 value, rmtU32 xor_mask)
{
// Output bit
rmtU32 lsb = value & 1;
// Apply the register shift
value >>= 1;
// Apply toggle mask if the output bit is set
if (lsb != 0)
{
value ^= xor_mask;
}
return value;
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@NEW: New/Delete operators with error values for simplifying object create/destroy
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
#define rmtTryMalloc(type, obj) \
obj = (type*)rmtMalloc(sizeof(type)); \
if (obj == NULL) \
{ \
return RMT_ERROR_MALLOC_FAIL; \
}
#define rmtTryMallocArray(type, obj, count) \
obj = (type*)rmtMalloc((count) * sizeof(type)); \
if (obj == NULL) \
{ \
return RMT_ERROR_MALLOC_FAIL; \
}
// Ensures the pointer is non-NULL, calls the destructor, frees memory and sets the pointer to NULL
#define rmtDelete(type, obj) \
if (obj != NULL) \
{ \
type##_Destructor(obj); \
rmtFree(obj); \
obj = NULL; \
}
// New will allocate enough space for the object and call the constructor
// If allocation fails the constructor won't be called
// If the constructor fails, the destructor is called and memory is released
// NOTE: Use of sizeof() requires that the type be defined at the point of call
// This is a disadvantage over requiring only a custom Create function
#define rmtTryNew(type, obj, ...) \
{ \
obj = (type*)rmtMalloc(sizeof(type)); \