-
Notifications
You must be signed in to change notification settings - Fork 3
/
memlive.h
2903 lines (2383 loc) · 92.4 KB
/
memlive.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
/*
MEMLIVE 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 __MEMLIVE__
#define __MEMLIVE__
// STD C
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cassert>
#include <malloc.h>
#include <new>
// CPU INTRINSICS
#include <immintrin.h>
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__GNUC__)
#include <emmintrin.h>
#endif
// STD
#include <string>
#include <string_view>
#include <algorithm>
#include <array>
#include <vector>
#include <unordered_map>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <thread>
#include <atomic>
#include <memory>
#include <mutex> // For std::lock_guard
#include <type_traits>
#ifdef __linux__
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <sys/epoll.h>
#include <sys/sysinfo.h>
#include <sys/mman.h>
#endif
#ifdef _WIN32
#include <Ws2tcpip.h>
// WINDOWS , WE WANT IT AFTER LIVE PROFILER INCLUDES AS WINDOWS.H CAN'T BE INCLUDED BEFORE Ws2tcpip.h
#include <windows.h>
#endif
namespace memlive
{
#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_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 _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 _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
#ifndef _SOCKET_
#define _SOCKET_
#ifdef __linux__
#elif _WIN32
#pragma comment(lib,"Ws2_32.lib")
#pragma warning(disable:4996)
#endif
enum class SocketType
{
TCP,
UDP
};
enum class SocketOption
{
GET_ERROR_AND_CLEAR,
REUSE_ADDRESS,
REUSE_PORT,
KEEP_ALIVE,
EXCLUSIVE_ADDRESS,
RECEIVE_BUFFER_SIZE,
RECEIVE_BUFFER_TIMEOUT,
SEND_BUFFER_SIZE,
SEND_BUFFER_TIMEOUT,
TCP_ENABLE_CORK,
TCP_ENABLE_QUICKACK, // Applies only to Linux , even Nagle is turned off , delayed can cause time loss due in case of lost packages
TCP_DISABLE_NAGLE, // Send packets as soon as possible , no need to wait for ACKs or to reach a certain amount of buffer size
POLLING_INTERVAL, // SO_BUSY_POLL , specifies time to wait for select to query kernel to know if new data received
SOCKET_PRIORITY
};
enum class SocketState
{
DISCONNECTED,
BOUND,
CONNECTED,
LISTENING,
ACCEPTED
};
class SocketAddress
{
public:
void initialise(const std::string_view& address, int port)
{
m_port = port;
m_address = address;
auto addr = &m_socket_address_struct;
memset(addr, 0, sizeof(sockaddr_in));
addr->sin_family = PF_INET;
addr->sin_port = htons(port);
if (m_address.size() > 0)
{
if (get_address_info(m_address.c_str(), &(addr->sin_addr)) != 0)
{
inet_pton(PF_INET, m_address.c_str(), &(addr->sin_addr));
}
}
else
{
addr->sin_addr.s_addr = INADDR_ANY;
}
}
void initialise(struct sockaddr_in* socket_address_struct)
{
char ip[50];
#ifdef __linux__
inet_ntop(PF_INET, (struct in_addr*)&(socket_address_struct->sin_addr.s_addr), ip, sizeof(ip) - 1);
#elif _WIN32
InetNtopA(PF_INET, (struct in_addr*)&(socket_address_struct->sin_addr.s_addr), ip, sizeof(ip) - 1);
#endif
m_address = ip;
m_port = ntohs(socket_address_struct->sin_port);
}
const std::string& get_address() const
{
return m_address;
}
int get_port() const
{
return m_port;
}
struct sockaddr_in* get_socket_address_struct()
{
return &m_socket_address_struct;
}
private:
int m_port = 0;
std::string m_address;
struct sockaddr_in m_socket_address_struct;
static int get_address_info(const char* hostname, struct in_addr* socketAddress)
{
struct addrinfo *res{ nullptr };
int result = getaddrinfo(hostname, nullptr, nullptr, &res);
if (result == 0)
{
memcpy(socketAddress, &((struct sockaddr_in *) res->ai_addr)->sin_addr, sizeof(struct in_addr));
freeaddrinfo(res);
}
return result;
}
};
template <SocketType socket_type = SocketType::TCP>
class Socket
{
public :
// 2 static methods needs to be called at the beginning and end of a program
static void socket_library_initialise()
{
#ifdef _WIN32
WORD version = MAKEWORD(2, 2);
WSADATA data;
WSAStartup(version, &data);
#endif
}
static void socket_library_uninitialise()
{
#ifdef _WIN32
WSACleanup();
#endif
}
Socket():m_socket_descriptor{0}, m_state{ SocketState::DISCONNECTED }, m_pending_connections_queue_size{0}
{
socket_library_initialise();
}
~Socket()
{
close();
socket_library_uninitialise();
}
bool create()
{
if constexpr(socket_type == SocketType::TCP)
{
m_socket_descriptor = static_cast<int>(socket(PF_INET, SOCK_STREAM, 0));
}
else if constexpr (socket_type == SocketType::UDP)
{
m_socket_descriptor = static_cast<int>(socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP));
}
if (m_socket_descriptor < 0)
{
return false;
}
return true;
}
void close()
{
if (m_state != SocketState::DISCONNECTED)
{
if (m_socket_descriptor > 0)
{
#ifdef __linux__
::close(m_socket_descriptor);
#elif _WIN32
::closesocket(m_socket_descriptor);
#endif
}
m_state = SocketState::DISCONNECTED;
}
}
bool bind(const std::string_view& address, int port)
{
m_address.initialise(address, port);
int result = ::bind(m_socket_descriptor, (struct sockaddr*)m_address.get_socket_address_struct(), sizeof(struct sockaddr_in));
if (result != 0)
{
return false;
}
m_state = SocketState::BOUND;
return true;
}
bool connect(const std::string_view& address, int port)
{
m_address.initialise(address, port);
if (::connect(m_socket_descriptor, (struct sockaddr*)m_address.get_socket_address_struct(), sizeof(struct sockaddr_in)) != 0)
{
return false;
}
m_state = SocketState::CONNECTED;
return true;
}
bool connect(const std::string_view& address, int port, int timeout)
{
auto blocking_mode_before_the_call = is_in_blocking_mode();
set_blocking_mode(false);
bool success{ false };
success = connect(address, port);
if (success == false)
{
success = select(true, true, timeout);
}
set_blocking_mode(blocking_mode_before_the_call);
if (success == false)
{
return false;
}
return true;
}
Socket* accept(int timeout)
{
if (m_state != SocketState::LISTENING && m_state != SocketState::ACCEPTED)
{
return nullptr;
}
auto blocking_mode_before_the_call = is_in_blocking_mode();
set_blocking_mode(false);
bool success{ true };
int connector_socket_desc{ -1 };
struct sockaddr_in address;
socklen_t len = sizeof(address);
memset(&address, 0, sizeof(address));
success = select(true, false, timeout);
if (success)
{
connector_socket_desc = static_cast<int>( ::accept(m_socket_descriptor, (struct sockaddr*)&address, &len) );
if (connector_socket_desc < 0)
{
success = false;
}
}
set_blocking_mode(blocking_mode_before_the_call);
if (!success)
{
return nullptr;
}
// It is caller`s responsibility to delete it
Socket* connector_socket{ nullptr };
connector_socket = new Socket;
connector_socket->initialise(connector_socket_desc, &address);
connector_socket->m_state = SocketState::CONNECTED;
m_state = SocketState::ACCEPTED;
return connector_socket;
}
void set_pending_connections_queue_size(int value)
{
m_pending_connections_queue_size = value;
}
void set_blocking_mode(bool blocking_mode)
{
#if __linux__
long arg = fcntl(m_socket_descriptor, F_GETFL, NULL);
if (blocking_mode)
{
arg &= (~O_NONBLOCK);
}
else
{
arg |= O_NONBLOCK;
}
fcntl(m_socket_descriptor, F_SETFL, arg);
#elif _WIN32
u_long mode{ 0 };
if (!blocking_mode)
{
mode = 1;
}
ioctlsocket(m_socket_descriptor, FIONBIO, &mode);
#endif
m_in_blocking_mode = blocking_mode;
}
void set_socket_option(SocketOption option, int value)
{
int actual_option = get_socket_option_value(option);
if (!actual_option)
{
// Even though called ,not supported on this system, for ex QUICK_ACK for Windows
return;
}
int actual_value = value;
#if __linux
setsockopt(m_socket_descriptor, SOL_SOCKET, actual_option, &actual_value, sizeof actual_value);
#elif _WIN32
setsockopt(m_socket_descriptor, SOL_SOCKET, actual_option, (char*)&actual_value, sizeof actual_value);
#endif
}
void set_ttl(int ttl)
{
#if __linux
setsockopt(m_socket_descriptor, IPPROTO_IP, IP_TTL, reinterpret_cast<void*>(&ttl), sizeof(ttl));
#elif _WIN32
setsockopt(m_socket_descriptor, IPPROTO_IP, IP_TTL, (const char*)&ttl, sizeof(ttl));
#endif
}
bool listen()
{
int result = ::listen(m_socket_descriptor, m_pending_connections_queue_size);
if (result != 0)
{
return false;
}
m_state = SocketState::LISTENING;
return true;
}
int get_socket_option(SocketOption option)
{
int actual_option = get_socket_option_value(option);
int ret{ 0 };
socklen_t len{ 0 };
#ifdef __linux__
getsockopt(m_socket_descriptor, SOL_SOCKET, actual_option, (void*)(&ret), &len);
#elif _WIN32
getsockopt(m_socket_descriptor, SOL_SOCKET, actual_option, (char*)(&ret), &len);
#endif
return ret;
}
int get_last_socket_error()
{
return get_socket_option(SocketOption::GET_ERROR_AND_CLEAR);
}
static int get_current_thread_last_socket_error()
{
int ret{ -1 };
#ifdef __linux__
ret = errno;
#elif _WIN32
ret = WSAGetLastError();
#endif
return ret;
}
static std::string get_socket_error_as_string(int error_code)
{
std::string ret;
#ifdef __linux__
ret = strerror(error_code);
#elif _WIN32
HMODULE lib = ::LoadLibraryA("WSock32.dll");
char* temp_string = nullptr;
FormatMessageA(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
(LPCVOID)lib, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&temp_string, 0, NULL);
if (temp_string)
{
ret = temp_string;
LocalFree(temp_string);
}
if (lib)
{
::FreeLibrary(lib);
}
#endif
return ret;
}
bool is_connection_lost(int error_code, std::size_t receive_result, bool is_caller_async)
{
bool ret{ false };
#ifdef __linux__
if (error_code >= 100 && error_code <= 104)
{
ret = true;
}
#elif _WIN32
if (error_code == WSAECONNRESET || error_code == WSAECONNABORTED)
{
ret = true;
}
#endif
else if(is_caller_async && !receive_result)
{
// In case the caller is doing async io with select/poll/epoll/ioring/iouring
ret = true;
}
if (ret == true)
{
m_state = SocketState::DISCONNECTED;
}
return ret;
}
SocketState get_state() const
{
return m_state;
}
int get_port() const
{
return m_address.get_port();
}
std::string get_address() const
{
return m_address.get_address();
}
int get_socket_descriptor() const
{
return m_socket_descriptor;
}
int receive(char* buffer, std::size_t len, int timeout = 0)
{
if (timeout > 0)
{
if (select(true, false, timeout) == false)
{
return 0;
}
}
auto result = ::recv(m_socket_descriptor, buffer, static_cast<int>(len), static_cast<int>(0));
return result;
}
int send(const std::string_view& buffer, int timeout = 0)
{
return send(buffer.data(), buffer.length(), timeout);
}
int send(const char* buffer, std::size_t len, int timeout = 0)
{
if (timeout > 0)
{
if (select(false, true, timeout) == false)
{
return 0;
}
}
auto result = ::send(m_socket_descriptor, buffer, static_cast<int>(len), static_cast<int>(0)) ;
return result;
}
bool is_in_blocking_mode() const { return m_in_blocking_mode; }
protected:
// Needed for operations that need timeout
bool select(bool read, bool write, long timeout)
{
fd_set write_set;
fd_set read_set;
fd_set* read_set_ptr{ nullptr };
fd_set* write_set_ptr{ nullptr };
if (write)
{
FD_ZERO(&write_set);
FD_SET(m_socket_descriptor, &write_set);
write_set_ptr = &write_set;
}
if (read)
{
FD_ZERO(&read_set);
FD_SET(m_socket_descriptor, &read_set);
read_set_ptr = &read_set;
}
struct timeval tv;
tv.tv_sec = timeout;
tv.tv_usec = 0;
// First arg ignored in Windows
if (::select(m_socket_descriptor + 1, read_set_ptr, write_set_ptr, nullptr, &tv) <= 0)
{
return false;
}
return true;
}
private:
int m_socket_descriptor;
SocketState m_state;
bool m_in_blocking_mode = true;
int m_pending_connections_queue_size;
SocketAddress m_address;
// Move ctor deletion
Socket(Socket&& other) = delete;
// Move assignment operator deletion
Socket& operator=(Socket&& other) = delete;
void initialise(int socket_descriptor, struct sockaddr_in* socket_address)
{
m_socket_descriptor = socket_descriptor;
m_address.initialise(socket_address);
}
int get_socket_option_value(SocketOption option)
{
int ret{ 0 };
switch (option)
{
case SocketOption::GET_ERROR_AND_CLEAR:
ret = SO_ERROR;
break;
case SocketOption::REUSE_ADDRESS:
ret = SO_REUSEADDR;
break;
case SocketOption::KEEP_ALIVE:
ret = SO_KEEPALIVE;
break;
case SocketOption::EXCLUSIVE_ADDRESS:
ret = SO_REUSEADDR;
break;
case SocketOption::REUSE_PORT:
#ifdef SO_REUSEPORT
ret = SO_REUSEPORT;
#endif
break;
case SocketOption::RECEIVE_BUFFER_SIZE:
ret = SO_RCVBUF;
break;
case SocketOption::RECEIVE_BUFFER_TIMEOUT:
ret = SO_RCVTIMEO;
break;
case SocketOption::SEND_BUFFER_SIZE:
ret = SO_SNDBUF;
break;
case SocketOption::SEND_BUFFER_TIMEOUT:
ret = SO_SNDTIMEO;
break;
case SocketOption::TCP_DISABLE_NAGLE:
ret = TCP_NODELAY;
break;
case SocketOption::TCP_ENABLE_QUICKACK:
#ifdef TCP_QUICKACK
ret = TCP_QUICKACK;
#endif
break;
case SocketOption::TCP_ENABLE_CORK:
#ifdef TCP_CORK
ret = TCP_CORK;
#endif
break;
case SocketOption::SOCKET_PRIORITY:
#ifdef SO_PRIORITY
ret = SO_PRIORITY;
#endif
break;
case SocketOption::POLLING_INTERVAL:
#ifdef SO_BUSY_POLL
ret = SO_BUSY_POLL;
#endif
break;
default:
break;
}
return ret;
}
};
#endif
/*
Uses epoll on Linux and select on Windows
Could use iouring on Linux and ioring on Windows however only latest OSs support them
so sticking with what is widely available
*/
#ifndef _ASYNC_IO_
#define _ASYNC_IO_
static constexpr std::size_t DEFAULT_MAX_DESCRIPTOR_COUNT = 64;
#ifdef __linux__
enum class EpollMode
{
LEVEL_TRIGGERED,
EDGE_TRIGGERED
};
template<std::size_t MAX_DESCRIPTOR_COUNT = DEFAULT_MAX_DESCRIPTOR_COUNT>
class AsyncIO
{
public:
AsyncIO()
{
}
~AsyncIO()
{
stop();
}
static constexpr bool polls_per_socket()
{
return false;
}