-
Notifications
You must be signed in to change notification settings - Fork 3
/
metamalloc.h
4454 lines (3653 loc) · 150 KB
/
metamalloc.h
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
// GENERATED BY VOLTRON.PY SCRIPT
/*
METAMALLOC VERSION 1.0.0
MIT License
Copyright (c) 2024 Akin Ocal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef __METAMALLOC__
#define __METAMALLOC__
// STD C
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdarg>
#include <cmath>
#include <cassert>
#include <cstring>
#include <cstdlib>
// STD
#include <type_traits>
#include <array>
#include <string_view>
#include <new>
// CPU INTRINSICS
#include <immintrin.h>
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__GNUC__)
#include <emmintrin.h>
#endif
// LINUX
#ifdef __linux__
#include <unistd.h>
#include <sys/mman.h>
#include <pthread.h>
#include <sched.h>
#include <sys/types.h>
#include <fcntl.h>
#ifdef ENABLE_NUMA
#include <numa.h>
#include <numaif.h>
#endif
#endif
// STATS
#ifdef ENABLE_STATS
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#endif
#if defined(ENABLE_PERF_TRACES) || defined(ENABLE_REPORT_LEAKS)
#include <cstdio>
#endif
// WINDOWS
#ifdef _WIN32
#include <windows.h>
#include <fibersapi.h>
#endif
// UNIT TESTS
#ifdef UNIT_TEST
#include <string>
#include <cstdio>
#endif
namespace metamalloc
{
#ifndef _CHECKS_H_
#define _CHECKS_H_
//////////////////////////////////////////////////////////////////////
// COMPILER CHECK
#if (! defined(_MSC_VER)) && (! defined(__GNUC__))
#error "This library is supported for only GCC and MSVC compilers"
#endif
//////////////////////////////////////////////////////////////////////
// C++ VERSION CHECK
#if defined(_MSC_VER)
#if _MSVC_LANG < 201703L
#error "This library requires to be compiled with C++17"
#endif
#elif defined(__GNUC__)
#if __cplusplus < 201703L
#error "This library requires to be compiled with C++17"
#endif
#endif
#endif
#ifndef _ARCHITECTURE_CHECK_H_
#define _ARCHITECTURE_CHECK_H_
//////////////////////////////////////////////////////////////////////
// ARCHITECTURE CHECK
#if defined(_MSC_VER)
#if (! defined(_M_X64))
#error "This library is supported for only x86-x64 architectures"
#endif
#elif defined(__GNUC__)
#if (! defined(__x86_64__)) && (! defined(__x86_64))
#error "This library is supported for only x86-x64 architectures"
#endif
#endif
#endif
#ifndef _OS_CHECK_
#define _OS_CHECK_
//////////////////////////////////////////////////////////////////////
// OPERATING SYSTEM CHECK
#if (! defined(__linux__)) && (! defined(_WIN32) )
#error "This library is supported for Linux and Windows systems"
#endif
#endif
#ifndef _BUILTIN_FUNCTIONS_H_
#define _BUILTIN_FUNCTIONS_H_
//////////////////////////////////////////////////////////////////////
// Count trailing zeroes
#if defined(__GNUC__)
#define builtin_ctzl(n) __builtin_ctzl(n)
#elif defined(_MSC_VER)
#if defined(_WIN64) // Implementation is for 64-bit only.
inline unsigned int builtin_ctzl(unsigned long long value)
{
unsigned long trailing_zero = 0;
if (_BitScanForward64(&trailing_zero, static_cast<unsigned __int64>(value)))
{
return static_cast<unsigned int>(trailing_zero);
}
else
{
return 64; // Sizeof unsigned long long.
}
}
#else
#error "This code is intended for 64-bit Windows platforms only."
#endif
#endif
//////////////////////////////////////////////////////////////////////
// Count leading zeroes
#if defined(__GNUC__)
#define builtin_clzl(n) __builtin_clzl(n)
#elif defined(_MSC_VER)
#if defined(_WIN64) // Implementation is for 64-bit only.
inline int builtin_clzl(unsigned long value)
{
unsigned long index = 0;
return _BitScanReverse64(&index, static_cast<unsigned __int64>(value)) ? static_cast<int>(63 - index) : 64;
}
#else
#error "This code is intended for 64-bit Windows platforms only."
#endif
#endif
//////////////////////////////////////////////////////////////////////
// Compare and swap, standard C++ provides them however it requires non-POD std::atomic usage
// They are needed when we want to embed spinlocks in "packed" data structures which need all members to be POD such as headers
#if defined(__GNUC__)
#define builtin_cas(pointer, old_value, new_value) __sync_val_compare_and_swap(pointer, old_value, new_value)
#elif defined(_MSC_VER)
#define builtin_cas(pointer, old_value, new_value) _InterlockedCompareExchange(reinterpret_cast<long*>(pointer), new_value, old_value)
#endif
//////////////////////////////////////////////////////////////////////
// memcpy
#if defined(__GNUC__)
#define builtin_memcpy(destination, source, size) __builtin_memcpy(destination, source, size)
#elif defined(_MSC_VER)
#define builtin_memcpy(destination, source, size) std::memcpy(destination, source, size)
#endif
//////////////////////////////////////////////////////////////////////
// memset
#if defined(__GNUC__)
#define builtin_memset(destination, character, count) __builtin_memset(destination, character, count)
#elif defined(_MSC_VER)
#define builtin_memset(destination, character, count) std::memset(destination, character, count)
#endif
//////////////////////////////////////////////////////////////////////
// aligned_alloc , It exists because MSVC does not provide std::aligned_alloc
#if defined(__GNUC__)
#define builtin_aligned_alloc(size, alignment) std::aligned_alloc(alignment, size)
#define builtin_aligned_free(ptr) std::free(ptr)
#elif defined(_MSC_VER)
#define builtin_aligned_alloc(size, alignment) _aligned_malloc(size, alignment)
#define builtin_aligned_free(ptr) _aligned_free(ptr)
#endif
#endif
#ifndef _HINTS_BRANCH_PREDICTOR_
#define _HINTS_BRANCH_PREDICTOR_
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LIKELY
#if defined(_MSC_VER)
//No implementation provided for MSVC for pre C++20 :
//https://social.msdn.microsoft.com/Forums/vstudio/en-US/2dbdca4d-c0c0-40a3-993b-dc78817be26e/branch-hints?forum=vclanguage
#define likely(x) x
#elif defined(__GNUC__)
#define likely(x) __builtin_expect(!!(x), 1)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// UNLIKELY
#if defined(_MSC_VER)
//No implementation provided for MSVC for pre C++20 :
//https://social.msdn.microsoft.com/Forums/vstudio/en-US/2dbdca4d-c0c0-40a3-993b-dc78817be26e/branch-hints?forum=vclanguage
#define unlikely(x) x
#elif defined(__GNUC__)
#define unlikely(x) __builtin_expect(!!(x), 0)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// VERY LIKELY
#if defined(_MSC_VER)
//No implementation provided for MSVC in any version :
//https://social.msdn.microsoft.com/Forums/vstudio/en-US/2dbdca4d-c0c0-40a3-993b-dc78817be26e/branch-hints?forum=vclanguage
#define very_likely(x) x
#elif defined(__GNUC__)
#define very_likely(x) __builtin_expect_with_probability(!!(x),1,0.99)
#endif
#endif
#ifndef _HINTS_HOT_CODE_
#define _HINTS_HOT_CODE_
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FORCE_INLINE
#if defined(_MSC_VER)
#define FORCE_INLINE __forceinline
#elif defined(__GNUC__)
#define FORCE_INLINE __attribute__((always_inline))
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HOT
#if defined(_MSC_VER)
//No implementation provided for MSVC :
#define HOT
#elif defined(__GNUC__)
#define HOT __attribute__((hot))
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ALIGN_DATA , some GCC versions gives warnings about standard C++ 'alignas' when applied to data
#ifdef __GNUC__
#define ALIGN_DATA( _alignment_ ) __attribute__((aligned( (_alignment_) )))
#elif _MSC_VER
#define ALIGN_DATA( _alignment_ ) alignas( _alignment_ )
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ALIGN_CODE, using alignas(64) or __attribute__(aligned(alignment)) for a function will work in GCC but MSVC won't compile
#ifdef __GNUC__
#define ALIGN_CODE( _alignment_ ) __attribute__((aligned( (_alignment_) )))
#elif _MSC_VER
//No implementation provided for MSVC :
#define ALIGN_CODE( _alignment_ )
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FORCE_LOOP_VECTORISATION
/*
Usage :
FORCE_LOOP_VECTORISATION
for (int j = 0; j < M; j++)
{
// loop body
}
_Pragma ( since C++11 ) allows to use pragma directives in macros.
In MSVC, it is not supported but instead MSVC provides __pragma : https://learn.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword?view=msvc-170
In MSVC, if you pass "-openmp:experimental" option to the compiler , it will inform you if vectorization failed :
info C5002: Omp simd loop not vectorized due to reason '1303' -> means that there was too few iterations
*/
#ifdef _MSC_VER
#define FORCE_LOOP_VECTORISATION __pragma(omp simd)
/*
MSVC also supports #pragma ivdep
But they recommend pragma omp simd :
https://learn.microsoft.com/en-us/cpp/parallel/openmp/openmp-simd?view=msvc-170
*/
#elif defined(__GNUC__)
#define FORCE_LOOP_VECTORISATION _Pragma("GCC ivdep")
#endif
#endif
#ifndef _PACKED_H_
#define _PACKED_H_
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PACKED
// Compilers may add additional padding zeroes for alignment
// Though those additions may increase the size of your structs/classes
// The ideal way is manually aligning data structures and minimising the memory footprint
// Compilers won`t add additional padding zeroes for "packed" data structures
#ifdef __GNUC__
#define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__))
#elif _MSC_VER
#define PACKED( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop))
#endif
#endif
#ifndef _UNUSED_H_
#define _UNUSED_H_
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// UNUSED
//To avoid unused variable warnings
#if defined(__GNUC__)
#define UNUSED(x) (void)(x)
#elif defined(_MSC_VER)
#define UNUSED(x) __pragma(warning(suppress:4100)) x
#endif
#endif
#ifndef _ALIGNMENT_CONSTANTS_
#define _ALIGNMENT_CONSTANTS_
namespace AlignmentConstants
{
// All constants are in bytes
constexpr std::size_t CACHE_LINE_SIZE = 64;
// SIMD REGISTER WIDTHS
constexpr std::size_t SIMD_SSE42_WIDTH = 16;
constexpr std::size_t SIMD_AVX_WIDTH = 32;
constexpr std::size_t SIMD_AVX2_WIDTH = 32;
constexpr std::size_t SIMD_AVX512_WIDTH = 64;
constexpr std::size_t MINIMUM_VECTORISATION_WIDTH = SIMD_SSE42_WIDTH;
constexpr std::size_t LARGEST_VECTORISATION_WIDTH = SIMD_AVX512_WIDTH; // AVX10 not available yet
// VIRTUAL MEMORY PAGE SIZES ARE HANDLED IN os/virtual_memory.h
}
#endif
#ifndef _PAUSE_H_
#define _PAUSE_H_
/*
Intel initially advised using _mm_pause in spin-wait loops in case of hyperthreading
Before Skylake it was about 10 cycles, but with Skylake it becomes 140 cycles and that applies to successor architectures
-> Intel opt manual 2.5.4 "Pause Latency in Skylake Client Microarchitecture"
Later _tpause / _umonitor / _umwait instructions were introduced however not using them for the time being as they are not widespread yet
Pause implementation is instead using nop
*/
inline void pause(uint16_t repeat_count=100)
{
#if defined(__GNUC__)
// rep is for repeating by the no provided in 16 bit cx register
__asm__ __volatile__("mov %0, %%cx\n\trep; nop" : : "r" (repeat_count) : "cx");
#elif defined(_WIN32)
for (uint16_t i = 0; i < repeat_count; ++i)
{
_mm_lfence();
__nop();
_mm_lfence();
}
#endif
}
#endif
// 64BIT ONLY LIVE FUNCTION CODE REPLACEMENT VIA MEMORY MANIPULATION FOR ONLY WINDOWS AS THERE IS NO NEED ON LINUX THANKS TO LD_PRELOAD
#ifndef __TRAMPOLINE_H__
#define __TRAMPOLINE_H__
#ifdef _WIN32
class ScopedReadWriteAccess
{
public:
ScopedReadWriteAccess(void* address)
{
VirtualQuery(address, &m_mbi_thunk, sizeof(MEMORY_BASIC_INFORMATION));
VirtualProtect(m_mbi_thunk.BaseAddress, m_mbi_thunk.RegionSize, PAGE_EXECUTE_READWRITE, &m_mbi_thunk.Protect);
};
~ScopedReadWriteAccess()
{
VirtualProtect(m_mbi_thunk.BaseAddress, m_mbi_thunk.RegionSize, m_mbi_thunk.Protect, &m_mbi_thunk.Protect);
}
private:
MEMORY_BASIC_INFORMATION m_mbi_thunk;
};
class Trampoline // SUPPORTS ONLY 64 BIT
{
public :
static inline constexpr std::size_t INSTRUCTION_SIZE = 14; // 16bits opcode + 32 bits offset + 64 bits address
using Bytes = char[INSTRUCTION_SIZE];
static bool install(void* original_function_address, void* replacement_function_address, Bytes original_bytes)
{
if (is_address_64_bit(original_function_address) == false || is_address_64_bit(replacement_function_address) == false) return false;
ScopedReadWriteAccess scoped_read_write(original_function_address);
builtin_memcpy(original_bytes, original_function_address, INSTRUCTION_SIZE);
auto* target = reinterpret_cast<char*>(original_function_address);
// FIRST 16 BITS - FARJMP opcode 0x25ff
uint16_t farjmp_opcode = 0x25ff;
builtin_memcpy(target, &farjmp_opcode, 2);
// FOLLOWING 32 BITS, OFFSET
uint32_t offset = 0;
builtin_memcpy(target+2, &offset, 4);
// FOLLOWING 64 BITS REPLACEMENT ADDRESS
builtin_memcpy(target+6, &replacement_function_address, 8);
return true;
}
static void uninstall(void* original_function_address, Bytes original_bytes)
{
ScopedReadWriteAccess scoped_read_write(original_function_address);
builtin_memcpy(original_function_address, original_bytes, INSTRUCTION_SIZE);
}
private:
static bool is_address_64_bit(void* address)
{
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(address, &mbi, sizeof(MEMORY_BASIC_INFORMATION));
return mbi.BaseAddress < (void*)0x8000000000000000;
}
};
#endif
#endif
/*
- To work with huge pages , you may need to configure your system :
- Linux : /proc/meminfo should have non-zero "Hugepagesize" & "HugePages_Total/HugePages_Free" attributes
( If HugePages_Total or HugePages_Free is 0
then run "echo 20 | sudo tee /proc/sys/vm/nr_hugepages" to reserve huge pages
Reference : https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt )
( If THP is enabled , we will use madvise. Otherwise we will use HUGE_TLB flag for mmap.
To check if THP enabled : sudo cat /sys/kernel/mm/transparent_hugepage/enabled
To disable THP : echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enable
)
- Windows : SeLockMemoryPrivilege is required.
It can be acquired using gpedit.msc :
Local Computer Policy -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Managements -> Lock pages in memory
- There is NUMA functionality however it is only experimental and not compiled by default. To try NUMA :
You need : #define ENABLE_NUMA
Also if on Linux , you need libnuma ( For ex : on Ubuntu -> sudo apt install libnuma-dev ) and -lnuma for GCC
*/
#ifndef __VIRTUAL_MEMORY_H__
#define __VIRTUAL_MEMORY_H__
#ifdef _WIN32
#pragma warning(disable:6250)
#endif
class VirtualMemory
{
public:
constexpr static std::size_t NO_NUMA = -1;
#ifdef __linux__
constexpr static std::size_t PAGE_ALLOCATION_GRANULARITY = 4096; // In bytes
#elif _WIN32
constexpr static std::size_t PAGE_ALLOCATION_GRANULARITY = 65536; // In bytes , https://devblogs.microsoft.com/oldnewthing/20031008-00/?p=42223
#endif
static std::size_t get_page_size()
{
std::size_t ret{ 0 };
#ifdef __linux__
ret = static_cast<std::size_t>(sysconf(_SC_PAGESIZE)); // TYPICALLY 4096, 2^ 12
#elif _WIN32
// https://learn.microsoft.com/en-gb/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
ret = system_info.dwPageSize; // TYPICALLY 4096, 2^ 12
#endif
return ret;
}
static bool is_huge_page_available()
{
bool ret{ false };
#ifdef __linux__
if (get_huge_page_size() <= 0)
{
ret = false;
}
else
{
if ( get_huge_page_total_count() > 0 )
{
ret = true;
}
}
#elif _WIN32
auto huge_page_size = get_huge_page_size();
if (huge_page_size)
{
HANDLE token = 0;
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token);
if (token)
{
LUID luid;
if (LookupPrivilegeValue(0, SE_LOCK_MEMORY_NAME, &luid))
{
TOKEN_PRIVILEGES token_privileges;
memset(&token_privileges, 0, sizeof(token_privileges));
token_privileges.PrivilegeCount = 1;
token_privileges.Privileges[0].Luid = luid;
token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (AdjustTokenPrivileges(token, FALSE, &token_privileges, 0, 0, 0))
{
auto last_error = GetLastError();
if (last_error == ERROR_SUCCESS)
{
ret = true;
}
}
}
}
}
#endif
return ret;
}
static std::size_t get_huge_page_size()
{
std::size_t ret{ 0 };
#ifdef __linux__
ret = get_proc_mem_info("Hugepagesize", 13) * 1024; // It is in KBs
#elif _WIN32
ret = static_cast<std::size_t>(GetLargePageMinimum());
#endif
return ret;
}
#ifdef __linux__
// Equivalent of /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
static std::size_t get_huge_page_total_count()
{
auto ret = get_proc_mem_info("HugePages_Total", 16);
if(ret == 0 )
{
ret = get_proc_mem_info("HugePages_Free", 15);
}
return ret;
}
static std::size_t get_proc_mem_info(const char* attribute, std::size_t attribute_len)
{
// Using syscalls to avoid memory allocations
std::size_t ret = 0;
const char* mem_info_file = "/proc/meminfo";
int fd = open(mem_info_file, O_RDONLY);
if (fd < 0) {
return ret;
}
char buffer[256];
size_t read_bytes;
while ((read_bytes = read(fd, buffer, sizeof(buffer))) > 0)
{
char* pos = strstr(buffer, attribute);
if (pos != nullptr)
{
ret = std::strtoul(pos + attribute_len, nullptr, 10);
break;
}
}
close(fd);
return ret;
}
// THP stands for "transparent huge page". A Linux mechanism
// It affects how we handle allocation of huge pages on Linux
static bool is_thp_enabled()
{
// Using syscalls to avoid memory allocation
const char* thp_enabled_file = "/sys/kernel/mm/transparent_hugepage/enabled";
// Use the access system call to check if the file exists
if (access(thp_enabled_file, F_OK) == 0)
{
return true;
}
return false;
}
#endif
#ifdef ENABLE_NUMA
static std::size_t get_numa_node_count()
{
std::size_t ret{ 0 };
#ifdef __linux__
// Requires -lnuma
ret = static_cast<std::size_t>(numa_num_configured_nodes());
#elif _WIN32
// GetNumaHighestNodeNumber is not guaranteed to be equal to NUMA node count so we need to iterate backwards
ULONG current_numa_node = 0;
GetNumaHighestNodeNumber(¤t_numa_node);
while (current_numa_node > 0)
{
GROUP_AFFINITY affinity;
if ((GetNumaNodeProcessorMaskEx)(static_cast<USHORT>(current_numa_node), &affinity))
{
//If the specified node has no processors configured, the Mask member is zero
if (affinity.Mask != 0)
{
ret++;
}
}
// max node was invalid or had no processor assigned, try again
current_numa_node--;
}
#endif
return ret;
}
static std::size_t get_numa_node_of_caller()
{
std::size_t numa_node = -1;
#ifdef __linux__
// Requires -lnuma
numa_node = static_cast<std::size_t>(numa_node_of_cpu(sched_getcpu()));
#elif _WIN32
USHORT node_number{ 0 };
PROCESSOR_NUMBER processor_number{ 0 };
GetCurrentProcessorNumberEx(&processor_number);
if (GetNumaProcessorNodeEx(&processor_number, &node_number))
{
numa_node = static_cast<std::size_t>(node_number);
}
#endif
return numa_node;
}
#endif
// Note about alignments : Windows always returns page ( typically 4KB ) or huge page ( typially 2MB ) aligned addresses
// On Linux , page sized ( again 4KB) allocations are aligned to 4KB, but the same does not apply to huge page allocations : They are aligned to 4KB but never to 2MB
// Therefore in case of huge page use, there is no guarantee that the allocated address will be huge-page-aligned , so alignment requirements have to be handled by the caller
//
// Note about huge page failures : If huge page allocation fails, for the time being not doing a fallback for a subsequent non huge page allocation
// So library users have to check return values
//
template <bool use_hugepage, std::size_t numa_node=NO_NUMA, bool zero_buffer=false>
static void* allocate(std::size_t size, void* hint_address = nullptr)
{
void* ret = nullptr;
#ifdef __linux__
static bool thp_enabled = is_thp_enabled();
// MAP_ANONYMOUS rather than going thru a file (memory mapped file)
// MAP_PRIVATE rather than shared memory
int flags = MAP_PRIVATE | MAP_ANONYMOUS;
#ifndef ENABLE_NUMA
// MAP_POPULATE forces system to access the just-allocated memory. That helps by creating TLB entries
flags |= MAP_POPULATE;
#endif
if constexpr (use_hugepage)
{
if (!thp_enabled)
{
flags |= MAP_HUGETLB;
}
}
ret = mmap(hint_address, size, PROT_READ | PROT_WRITE, flags, -1, 0);
if (ret == nullptr)
{
return ret;
}
if constexpr (use_hugepage)
{
if (thp_enabled)
{
madvise(ret, size, MADV_HUGEPAGE);
}
}
#ifdef ENABLE_NUMA
auto numa_node_count = get_numa_node_count();
if (numa_node_count > 0 && numa_node != static_cast<std::size_t>(-1))
{
unsigned long nodemask = 1UL << numa_node;
int result = mbind(ret, size, MPOL_BIND, &nodemask, sizeof(nodemask), MPOL_MF_MOVE);
if (result != 0)
{
munmap(ret, size);
ret = nullptr;
}
}
#endif
#elif _WIN32
int flags = MEM_RESERVE | MEM_COMMIT;
if constexpr (use_hugepage)
{
flags |= MEM_LARGE_PAGES;
}
#ifndef ENABLE_NUMA
ret = VirtualAlloc(hint_address, size, flags, PAGE_READWRITE);
#else
auto numa_node_count = get_numa_node_count();
if (numa_node_count > 0 && numa_node != static_cast<std::size_t>(-1))
{
ret = VirtualAllocExNuma(GetCurrentProcess(), hint_address, size, flags, PAGE_READWRITE, static_cast<DWORD>(numa_node));
}
else
{
ret = VirtualAlloc(hint_address, size, flags, PAGE_READWRITE);
}
#endif
#endif
if constexpr (zero_buffer)
{
builtin_memset(ret, 0, size);
}
return ret;
}
static bool deallocate(void* address, std::size_t size)
{
bool ret{ false };
#ifdef __linux__
ret = munmap(address, size) == 0 ? true : false;
#elif _WIN32
ret = VirtualFree(address, size, MEM_RELEASE) ? true : false;
#endif
return ret;
}
static bool lock_all_pages()
{
bool ret{ false };
#ifdef __linux__
ret = mlockall(MCL_CURRENT | MCL_FUTURE) == 0 ? true : false;
#elif _WIN32
ret = false; // No equivalent on Windows , you have to use VirtualLock per individual page
#endif
return ret;
}
// To prevent the system from swapping the pages out to the paging file
static bool lock(void* address, std::size_t size)
{
bool ret{ false };
#ifdef __linux__
ret = mlock(address, size) == 0 ? true : false;
#elif _WIN32
ret = VirtualLock(address, size) ? true : false;
#endif
return ret;
}
static bool unlock(void* address, std::size_t size)
{
bool ret{ false };
#ifdef __linux__
ret = munlock(address, size) == 0 ? true : false;
#elif _WIN32
ret = VirtualUnlock(address, size) ? true : false;
#endif
return ret;
}
private :
};
#endif
/*
Standard C++ thread_local keyword does not allow you to specify thread specific destructors
and also can't be applied to class members
*/
#ifndef _THREAD_LOCAL_STORAGE_
#define _THREAD_LOCAL_STORAGE_
class ThreadLocalStorage
{
public:
static ThreadLocalStorage& get_instance()
{
static ThreadLocalStorage instance;
return instance;
}
// Call it only once for a process
bool create(void(*thread_destructor)(void*) = nullptr)
{
#if __linux__
return pthread_key_create(&m_tls_index, thread_destructor) == 0;
#elif _WIN32
// Using FLSs rather TLS as it is identical + TLSAlloc doesn't support dtor
m_tls_index = FlsAlloc(thread_destructor);
return m_tls_index == FLS_OUT_OF_INDEXES ? false : true;
#endif
}
// Same as create
void destroy()
{
if (m_tls_index)
{
#if __linux__
pthread_key_delete(m_tls_index);
#elif _WIN32
FlsFree(m_tls_index);
#endif
m_tls_index = 0;
}
}
// GUARANTEED TO BE THREAD-SAFE/LOCAL
void* get()
{
#if __linux__
return pthread_getspecific(m_tls_index);
#elif _WIN32
return FlsGetValue(m_tls_index);
#endif
}
void set(void* data_address)
{
#if __linux__
pthread_setspecific(m_tls_index, data_address);
#elif _WIN32
FlsSetValue(m_tls_index, data_address);
#endif
}
// DOES NOT INVOKE SYSCALLS , JUST ACCESSES SEGMENT REGISTERS
// SO IDEAL FOR IDENTIFIYING THREADS THAT USE TLS
static inline uint64_t get_thread_local_storage_id(void)
{
uint64_t result;
#ifdef _WIN32
// GS
result = reinterpret_cast<uint64_t>(NtCurrentTeb());
#elif __linux__
// FS
asm volatile("mov %%fs:0, %0" : "=r"(result));
#endif
return result;
}
private:
#if __linux__
pthread_key_t m_tls_index = 0;
#elif _WIN32
unsigned long m_tls_index = 0;
#endif
ThreadLocalStorage() = default;
~ThreadLocalStorage() = default;
ThreadLocalStorage(const ThreadLocalStorage& other) = delete;
ThreadLocalStorage& operator= (const ThreadLocalStorage& other) = delete;
ThreadLocalStorage(ThreadLocalStorage&& other) = delete;
ThreadLocalStorage& operator=(ThreadLocalStorage&& other) = delete;
};
#endif
/*
Provides :
static unsigned int get_number_of_logical_cores()
static unsigned int get_number_of_physical_cores()
static bool is_hyper_threading()
static inline void yield()
static inline void sleep(unsigned long microseconds)
static int get_current_core_id()
static unsigned long get_current_thread_id()
static int pin_calling_thread_to_cpu_core(int core_id)
static void set_thread_name(unsigned long thread_id, const std::string_view name)
static bool set_priority(ThreadPriority priority)
*/
#ifndef _THREAD_UTILITIES_
#define _THREAD_UTILITIES_
enum class ThreadPriority
{
IDLE,
BELOW_NORMAL,
NORMAL,
ABOVE_NORMAL,
CRITICAL
};
struct ThreadPriorityNode
{
ThreadPriority priority;
int value;
};
const static std::array<ThreadPriorityNode, 5> NATIVE_THREAD_PRIORITIES =
{
//DO POD INITIALISATION
{
#ifdef __linux__
ThreadPriority::IDLE, 19,
ThreadPriority::BELOW_NORMAL, 1,
ThreadPriority::NORMAL, 0,