-
Notifications
You must be signed in to change notification settings - Fork 8
/
ShMemIPC.hpp
1676 lines (1637 loc) · 74.2 KB
/
ShMemIPC.hpp
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
#pragma once
/*
Copyright (c) 2020 Victor Sheinmann, [email protected]
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.
*/
struct NShMem // TODO: Crossplatform - part of the FRAMEWORK
{
static inline char ObjDirName[] = {"TempNamedObjects"}; // TODO: Generate it
//===========================================================================
// 'Global\HelloWorld' => '\BaseNamedObjects\HelloWorld'
// 'Local\HelloWorld' => '\Sessions\1\BaseNamedObjects\HelloWorld'
//
//----------------------------------------------------------------------------
static void InitObjAttrForBaseNamedObj(OBJECT_ATTRIBUTES* Attr, UNICODE_STRING* UStr, wchar_t* Buf, LPSTR Name, LPSTR ObjDirPath)
{
UINT Length = 0;
if((*Name != '\\')&&(*Name != '/'))
{
char Path[] = {'\\','B','a','s','e','N','a','m','e','d','O','b','j','e','c','t','s','\\',0}; // If static then the sring will be in memory as is
if(!ObjDirPath)ObjDirPath = Path; // wchar_t Path[] = {'\\','T','e','m','p','N','a','m','e','d','O','b','j','e','c','t','s','\\'}; // {'\\','B','a','s','e','N','a','m','e','d','O','b','j','e','c','t','s','\\'};
if((*ObjDirPath != '\\')&&(*ObjDirPath != '/'))Buf[Length++] = '\\';
for(;*ObjDirPath;Length++,ObjDirPath++)Buf[Length] = *ObjDirPath;
if((Buf[Length-1] != '\\')&&(Buf[Length-1] != '/'))Buf[Length++] = '\\';
}
for(;*Name;Name++,Length++)Buf[Length] = *Name;
UStr->Buffer = Buf;
UStr->Length = Length * sizeof(wchar_t);
UStr->MaximumLength = UStr->Length + sizeof(wchar_t);
Attr->Length = sizeof(OBJECT_ATTRIBUTES);
Attr->RootDirectory = NULL;
Attr->ObjectName = UStr;
Attr->Attributes = 0;
Attr->SecurityQualityOfService = NULL;
Attr->SecurityDescriptor = NULL;
// DBGMSG("%u - '%ls'",Length,Buf);
}
//----------------------------------------------------------------------------
static NTSTATUS CreateNtObjDirectory(LPSTR ObjDirName, PHANDLE phDirObj) // Create objects directory with NULL security
{
wchar_t Path[512] = {'\\'};
UNICODE_STRING ObjectNameUS;
SECURITY_DESCRIPTOR sd = {SECURITY_DESCRIPTOR_REVISION, 0, 4}; // NULL security descriptor: InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);
OBJECT_ATTRIBUTES oattr = { sizeof(OBJECT_ATTRIBUTES), 0, &ObjectNameUS, OBJ_CASE_INSENSITIVE|OBJ_OPENIF, &sd };
UINT Length = 1;
for(int idx=0;*ObjDirName;ObjDirName++)Path[Length++] = *ObjDirName;
ObjectNameUS.Buffer = Path;
ObjectNameUS.Length = Length * sizeof(wchar_t);
ObjectNameUS.MaximumLength = ObjectNameUS.Length + sizeof(wchar_t);
return NtCreateDirectoryObject(phDirObj, DIRECTORY_ALL_ACCESS, &oattr);
}
//----------------------------------------------------------------------------
static NTSTATUS MutexCreateA(PHANDLE pHandle, LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPSTR lpName, LPSTR lpObjDir)
{
OBJECT_ATTRIBUTES oattr = {};
UNICODE_STRING ObjPathUS;
wchar_t Path[256];
InitObjAttrForBaseNamedObj(&oattr, &ObjPathUS, Path, lpName, lpObjDir);
if(lpMutexAttributes)
{
oattr.Attributes = lpMutexAttributes->bInheritHandle ? 2 : 0;
oattr.SecurityDescriptor = lpMutexAttributes->lpSecurityDescriptor;
}
oattr.Attributes |= OBJ_OPENIF; // Open if already exist
return NtCreateMutant(pHandle, MUTEX_ALL_ACCESS, &oattr, bInitialOwner);
}
//----------------------------------------------------------------------------
static NTSTATUS EventCreateA(PHANDLE pHandle, LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPSTR lpName, LPSTR lpObjDir)
{
OBJECT_ATTRIBUTES oattr = {};
UNICODE_STRING ObjPathUS;
wchar_t Path[256];
InitObjAttrForBaseNamedObj(&oattr, &ObjPathUS, Path, lpName, lpObjDir);
if(lpEventAttributes)
{
oattr.Attributes = lpEventAttributes->bInheritHandle ? 2 : 0;
oattr.SecurityDescriptor = lpEventAttributes->lpSecurityDescriptor;
}
oattr.Attributes |= OBJ_OPENIF; // Open if already exist
return NtCreateEvent(pHandle, EVENT_ALL_ACCESS, &oattr, bManualReset?NotificationEvent:SynchronizationEvent, bInitialState);
}
//----------------------------------------------------------------------------
static NTSTATUS CreateMemSection(PHANDLE SectionHandle, ACCESS_MASK DesiredAccess, PLARGE_INTEGER MaximumSize, ULONG SectionPageProtection, ULONG AllocationAttributes, LPSTR SecName, LPSTR lpObjDir)
{
OBJECT_ATTRIBUTES oattr = {};
UNICODE_STRING ObjPathUS;
wchar_t Path[256];
InitObjAttrForBaseNamedObj(&oattr, &ObjPathUS, Path, SecName, lpObjDir);
oattr.Attributes |= OBJ_OPENIF; // Open if already exist
return NtCreateSection(SectionHandle, DesiredAccess, &oattr, MaximumSize, SectionPageProtection, AllocationAttributes, NULL);
}
//----------------------------------------------------------------------------
static NTSTATUS OpenMemSection(PHANDLE SectionHandle, ACCESS_MASK DesiredAccess, LPSTR SecName, LPSTR lpObjDir)
{
OBJECT_ATTRIBUTES oattr = {};
UNICODE_STRING ObjPathUS;
wchar_t Path[256];
InitObjAttrForBaseNamedObj(&oattr, &ObjPathUS, Path, SecName, lpObjDir);
return NtOpenSection(SectionHandle, DesiredAccess, &oattr);
}
//----------------------------------------------------------------------------
static inline long WaitForSingle(HANDLE hHandle, DWORD dwMilliseconds)
{
#ifdef _NTDLL_H
LARGE_INTEGER Timeout;
LARGE_INTEGER* Tio;
if(INFINITE != dwMilliseconds){Timeout.QuadPart = -10000i64 * dwMilliseconds; Tio = &Timeout;}
else Tio = NULL;
NTSTATUS status = NtWaitForSingleObject(hHandle, FALSE, Tio);
if((long)status < 0)return WAIT_FAILED;
return status; // If Alerted is FALSE
#else
return WaitForSingleObject(hHandle, dwMilliseconds);
#endif
}
//----------------------------------------------------------------------------
static inline ULONG GetTicksCount(void)
{
#ifdef _NTDLL_H
PBYTE pKiUserSharedData = reinterpret_cast<PBYTE>(0x7FFE0000);
return (((*(PDWORD)pKiUserSharedData)?((UINT64)*(PDWORD)pKiUserSharedData):(*(UINT64*)&pKiUserSharedData[0x320])) * *(PDWORD)&pKiUserSharedData[4]) >> 24; // 'TickCountLow * TickCountMultiplier' or 'TickCount * TickCountMultiplier'
#else
return GetTickCount();
#endif
}
//----------------------------------------------------------------------------
static inline ULONG CurrentThreadID(void)
{
#ifdef _NTDLL_H
return NtCurrentThreadId();
#else
return GetCurrentThreadId();
#endif
}
//----------------------------------------------------------------------------
static inline ULONG CurrentProcessID(void)
{
#ifdef _NTDLL_H
return NtCurrentProcessId();
#else
return GetCurrentProcessId();
#endif
}
//----------------------------------------------------------------------------
static inline long CloseOHandle(HANDLE Hndl)
{
if(((SIZE_T)Hndl + 1) > 1) // Checked for NULL(0) and INVALID_HANDLE_VALUE(-1)
#ifdef _NTDLL_H
return !NtClose(Hndl);
#else
return CloseHandle(Hndl);
#endif
return 0;
}
//----------------------------------------------------------------------------
template<typename A> static ULONG SizeString(A Str)
{
unsigned long idx = 0;
while(Str[idx])idx++;
return idx;
}
//----------------------------------------------------------------------------
template<typename A, typename B> static ULONG CopyString(A DstStr, B SrcStr, unsigned long MaxSize=-1)
{
unsigned long idx = 0;
for(;MaxSize && SrcStr[idx];idx++,MaxSize--)DstStr[idx] = SrcStr[idx];
DstStr[idx] = 0;
return idx;
}
//----------------------------------------------------------------------------
template<typename A, typename B> static ULONG AddString(A DstStr, B SrcStr, unsigned long MaxSize=-1)
{
unsigned long idx = 0;
ULONG DstLen = SizeString(DstStr);
DstStr += DstLen;
for(;MaxSize && SrcStr[idx];idx++,MaxSize--)DstStr[idx] = SrcStr[idx];
DstStr[idx] = 0;
return DstLen + idx;
}
//----------------------------------------------------------------------------
template<typename T, typename O> static O _fastcall UIntToString(T Val, O buf, int* Len) // TODO: Optimize
{
if(Val == 0){if(Len)*Len = 1; *buf = '0'; buf[1] = 0; return buf;}
buf = &buf[20];
*buf = 0;
O end = buf;
for(buf--;Val;buf--)
{
*buf = (Val % 10) + '0';
Val /= 10;
}
buf++;
if(Len)*Len = end-buf;
else buf[end-buf] = 0;
return buf; // Optionally move?
}
//----------------------------------------------------------------------------
template<typename T, typename S> static S UIntToHexString(T Value, int MaxDigits, S NumBuf, bool UpCase, int* Len=0) // TODO: Optimize
{
const int cmax = sizeof(T)*2; // Number of byte halves (Digits)
char HexNums[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; // Must be optimized to PlatLen assignments
UINT Case = UpCase?0:16;
if(Value)
{
if(MaxDigits <= 0) // Auto set max digits
{
MaxDigits = 0;
T tmp = Value; // Counter needed to limit a signed value
for(int ctr=cmax;tmp && ctr;ctr--,MaxDigits++,tmp >>= 4); // for(T tmp = Value;tmp;tmp>>=4,MaxDigits++);
if(MaxDigits & 1)MaxDigits++; // Full bytes
}
S DstPtr = &NumBuf[MaxDigits-1];
for(int Ctr = 0;DstPtr >= NumBuf;DstPtr--) // Start from last digit
{
if(Ctr < cmax)
{
*DstPtr = HexNums[(Value & 0x0000000F)+Case]; // From end of buffer
Value = Value >> 4;
Ctr++;
}
else *DstPtr = '0';
}
}
else // Fast 0
{
if(MaxDigits <= 0)MaxDigits = 2;
for(int ctr=0;ctr < MaxDigits;ctr++)NumBuf[ctr] = '0';
}
if(Len)*Len = MaxDigits;
else NumBuf[MaxDigits] = 0;
return NumBuf;
}
//---------------------------------------------------------------------------
//============================================================================
// Slow Critcal Section :(
//-------------------------------------
// Declare all variables volatile, so that the compiler won't try to optimize something important.
// SRWLock spin count is 1024 if there is more than one processor core (NtCurrentTeb()->ProcessEnvironmentBlock->NumberOfProcessors)
//
//#define _USESYSCRITSEC
template<unsigned long DefSpinCtr=1024, unsigned long DefTimeout=-1> class CCritSectEx // -1 is INFINITE // TODO: Shareable critical section
{
#ifndef _USESYSCRITSEC
volatile HANDLE hSemaphore;
volatile long OwnerThID;
volatile long WaitThCtr;
volatile long RecurCtr;
static inline int CoresCnt = 0;
//----------------------------------------------------------------------------
#else
CRITICAL_SECTION csec;
#endif
public:
#ifndef _USESYSCRITSEC
CCritSectEx(void)
{
memset(this, 0,sizeof(*this));
if(!CoresCnt)
{
#ifdef _NTDLL_H
this->CoresCnt = NtCurrentTeb()->ProcessEnvironmentBlock->NumberOfProcessors;
#else
SYSTEM_INFO stSI;
GetSystemInfo(&stSI);
this->CoresCnt = stSI.dwNumberOfProcessors;
#endif
}
}
~CCritSectEx(){NShMem::CloseOHandle(this->hSemaphore);}
#else
CCritSectEx(void){InitializeCriticalSection(&this->csec);}
~CCritSectEx(){DeleteCriticalSection(&this->csec);}
#endif
//----------------------------------------------------------------------------
bool Lock(ULONG SpinCtr=DefSpinCtr, ULONG WaitTimeout=DefTimeout)
{
#ifndef _USESYSCRITSEC
if(this->TryLock(SpinCtr))return true;
// if(!WaitTimeout)return false; // No waiting time specified!
if(!this->hSemaphore) // && !_InterlockedCompareExchangePointer(&this->hSemaphore, (void*)-1, NULL)) // Ensure that we have the kernel event created
{
#ifdef _NTDLL_H
HANDLE hSemaphore = NULL;
NTSTATUS status = NtCreateSemaphore(&hSemaphore,NULL,NULL,0,0x7FFFFFFF); // 40000000 STATUS_OBJECT_NAME_EXISTS
#else
HANDLE hSemaphore = CreateSemaphoreW(NULL, 0, 0x7FFFFFFF, NULL);
#endif
if(_InterlockedCompareExchangePointer(&this->hSemaphore, hSemaphore, NULL))NShMem::CloseOHandle(hSemaphore); //Close it if someone is already created it
// if(this->TryLock(SpinCtr))return true;
}
bool bWaiter = false;
ULONG ThisThreadId = CurrentThreadID();
for(ULONG InitialTicks = GetTicksCount();;) // TODO: Crossplatform timing
{
if(!bWaiter)_InterlockedIncrement(&this->WaitThCtr);
if(!this->OwnerThID && !_InterlockedCompareExchange(&this->OwnerThID, ThisThreadId, 0)){_InterlockedDecrement(&this->WaitThCtr); ++this->RecurCtr; return true;}
ULONG WaitElapsed;
if((ULONG)-1 != WaitTimeout)
{
WaitElapsed = GetTicksCount() - InitialTicks; // how much time elapsed
if(WaitTimeout <= WaitElapsed){_InterlockedDecrement(&this->WaitThCtr); return false;} // Failed to acquire - TIMEOUT
WaitElapsed = WaitTimeout - WaitElapsed;
}
else WaitElapsed = (ULONG)-1;
switch(NShMem::WaitForSingle(this->hSemaphore, WaitTimeout))
{
case WAIT_OBJECT_0:
case WAIT_ABANDONED: // An previous owner thread just died
bWaiter = false;
break;
case WAIT_TIMEOUT:
// DBGMSG("WAIT_TIMEOUT %u\n", CurrentThreadID());
bWaiter = true;
break;
}
}
#else
EnterCriticalSection(&this->csec);
#endif
return true;
}
//----------------------------------------------------------------------------
bool Unlock(void)
{
#ifndef _USESYSCRITSEC
DWORD ThisThreadId = CurrentThreadID();
if(ThisThreadId != this->OwnerThID)return false; // Inconsistent Unlock!
if(--this->RecurCtr > 0)return false; // Still owned by this thread
//_WriteBarrier(); // changes done to the shared resource are committed.
_InterlockedAnd(&this->OwnerThID, 0); // this->OwnerThID = 0; // Hangs everything without Interlocked write here
//_ReadWriteBarrier(); // The CS is released.
if(this->WaitThCtr > 0) // AFTER it is released we check if there're waiters.
{
_InterlockedDecrement(&this->WaitThCtr);
#ifdef _NTDLL_H
NtReleaseSemaphore(this->hSemaphore, 1, NULL);
#else
ReleaseSemaphore(this->hSemaphore, 1, NULL); // Notify waiters that we are finished // Increase count // The state of a semaphore object is signaled when its count is greater than zero, and nonsignaled when its count is equal to zero.
#endif
}
#else
LeaveCriticalSection(&this->csec);
#endif
return true;
}
//----------------------------------------------------------------------------
bool TryLock(ULONG SpinCtr=DefSpinCtr) // Light lock
{
#ifndef _USESYSCRITSEC
ULONG ThisThreadId = CurrentThreadID();
if(ThisThreadId == this->OwnerThID){++this->RecurCtr; return true;} // Recursion of already acquired
if(this->CoresCnt <= 1)return false;
do
{
if(!this->OwnerThID && !_InterlockedCompareExchange(&this->OwnerThID, ThisThreadId, 0)){++this->RecurCtr; return true;} // Takes ownersip if OwnerThID is 0
YieldProcessor(); // _mm_pause()
}
while(SpinCtr--);
return false;
#else
return TryEnterCriticalSection(&this->csec);
#endif
}
//----------------------------------------------------------------------------
void Release(void) // Emergency release if owner thread has died
{
}
//----------------------------------------------------------------------------
};
//===========================================================================
//
//
//
//---------------------------------------------------------------------------
class CGrowBuf // Size: 16/32 // A helper class to use with IPC procedure call // TODO: A decent allocator
{
static const unsigned int PAGE_SIZE = 0x1000;
static const unsigned int GRAN_SIZE = 0x10000;
static SIZE_T AlignAllocSize(SIZE_T Size){return (Size + (GRAN_SIZE-1)) & ~(GRAN_SIZE-1);}
PBYTE GetLocalBuf(void){return (PBYTE)this + sizeof(CGrowBuf);}
protected:
PBYTE Buff; // May be not NULL but point to a stack buffer in a derived class
SIZE_T DSize; // Size of a valid data
SIZE_T FSize; // Full size of allocated buffer
SIZE_T LSize; // Size of local buffer which may follow after a CGrowBuf instance in a derived class
public:
CGrowBuf(void)
{
this->FSize = this->LSize = this->DSize = 0;
this->Buff = this->GetLocalBuf();
}
~CGrowBuf(){this->Clear();}
//------------------------------------------------------------------------------------
UINT GetLen(void){return this->DSize;}
PVOID GetPtr(void){return this->Buff;}
//------------------------------------------------------------------------------------
static void FreeMem(PVOID Addr, SIZE_T Size)
{
if(!Addr)return;
DBGMSG("Releasing: %p, %p",Addr,Size);
Size = AlignAllocSize(Size);
PBYTE APtr = (PBYTE)Addr;
PBYTE EPtr = &APtr[Size];
while(APtr < EPtr)
{
#ifdef _NTDLL_H
SIZE_T FSize = 0;
if(NtFreeVirtualMemory(NtCurrentProcess,(PVOID*)&APtr,&FSize,MEM_RELEASE))break; // Step by GRAN_SIZE
APtr += FSize;
#else
VirtualFree(APtr,0,MEM_RELEASE);
APtr += GRAN_SIZE; // Fails if blocks were larger until reached a base addr of a next block (Cannot know without VirtualWuery from which blocks this range consists)
#endif
DBGMSG("Released: %p",APtr);
}
DBGMSG("Left: %p",(EPtr-APtr));
}
//------------------------------------------------------------------------------------
// When you allocate less than 64K you end up with a range of wasted pages that can't be reserved or committed. So virtual address space goes to waste.
static PVOID AllocMem(PVOID Addr, SIZE_T* Size) // Fast but wastes some memory!
{
*Size = AlignAllocSize(*Size); // To avoid 64k leftover holes
DBGMSG("Allocating: %p, %p",Addr, *Size);
#ifdef _NTDLL_H
if(NtAllocateVirtualMemory(NtCurrentProcess, &Addr, 0, Size, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE))Addr = NULL; // Commits only a page-aligned FSize
#else
BaseAddress = VirtualAlloc(Addr,*Size,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE); // Untested!
#endif
DBGMSG("Allocated: %p, %p",Addr, *Size);
return Addr;
}
//------------------------------------------------------------------------------------
static PVOID ReAllocMem(PVOID Addr, SIZE_T OldSize, SIZE_T* Size)
{
DBGMSG("Addr=%p, OldSize=%08X, NewSize=%08X",Addr,OldSize,*Size);
if(*Size <= OldSize){*Size = OldSize; DBGMSG("Cannot shrink: %p",Addr); return Addr;}
SIZE_T AOSize = AlignAllocSize(OldSize);
SIZE_T NSize = *Size - OldSize;
PVOID NewAddr = AllocMem((PBYTE)Addr + AOSize, &NSize);
if(NewAddr){*Size = AOSize+NSize; DBGMSG("Expanded: %p to %p, %p",Addr,NewAddr,*Size); return Addr;} // Added an adjacent block
NewAddr = AllocMem(NULL, Size);
DBGMSG("Relocated: %p",NewAddr);
memcpy(NewAddr, Addr, OldSize); // Lets crash if it is NULL :)
FreeMem(Addr, OldSize);
return NewAddr;
}
//------------------------------------------------------------------------------------
void Assign(PVOID Data, SIZE_T DataLen, bool DoCopy=false)
{
this->Clear();
this->DSize = DataLen;
if(DoCopy)
{
if(DataLen > this->LSize)
{
this->FSize = DataLen;
this->Buff = (PBYTE)AllocMem(NULL, &this->FSize);
}
memcpy(this->Buff,Data,DataLen);
}
else // Useful to allow any derived class to process some external buffer as its own (Usually this is done with some Allocator/Stream class)
{
this->Buff = (PBYTE)Data;
this->FSize = 0; // Not owns the buffer
}
// DBGMSG("Assigned: %p, %08X, %u",this->Buff,DataLen,(int)DoCopy);
}
//------------------------------------------------------------------------------------
void GrowFor(SIZE_T Len)
{
if(Len > this->LSize)
{
if(!this->FSize)
{
this->FSize = Len;
PBYTE NewPtr = (PBYTE)AllocMem(NULL, &this->FSize);
memcpy(NewPtr, this->Buff, this->DSize); // Copy local data
this->Buff = NewPtr;
}
else if(Len > this->FSize) // No shrinking supported! // (CGrowBuf should be short lived)
{
this->FSize = Len;
this->Buff = (PBYTE)ReAllocMem(this->Buff, this->DSize, &this->FSize);
}
}
this->DSize = Len;
}
//------------------------------------------------------------------------------------
void Clear(void)
{
if(this->FSize > this->LSize)
{
FreeMem(this->Buff, this->FSize);
this->FSize = 0;
}
// DBGMSG("Cleared: %p",this->Buff);
this->DSize = 0;
this->Buff = this->GetLocalBuf(); // Even if there is none
}
//------------------------------------------------------------------------------------
};
//====================================================================================
template<typename T> class CGrowArrImpl: public CGrowBuf
{
protected:
CGrowArrImpl(void) {} // Prenents direct instantiation
void Resize(size_t Cnt){this->GrowFor(Cnt * sizeof(T));}
public:
operator T*() {return (T*)this->Buff;} // Gives 'Array[idx]' access
UINT Count(void){return (this->DSize / sizeof(T));}
UINT Size(void){return this->DSize;}
T* Add(T* Data, size_t Cnt=1)
{
// DBGMSG("Adding: %p, %u",Data,Cnt);
size_t OIdx = this->Count();
this->Resize(OIdx+Cnt);
if(Data)memcpy(&((T*)this->Buff)[OIdx], Data, Cnt*sizeof(T));
return &((T*)this->Buff)[OIdx];
}
//------------------------------------------------------------------------------------
bool Remove(size_t Idx, size_t Cnt=1)
{
// DBGMSG("Removing: %u, %u",Idx,Cnt);
size_t OIdx = this->Count();
if(Idx >= OIdx)return false;
size_t LIdx = Idx + Cnt;
if(LIdx < OIdx)
{
memmove(&((T*)this->Buff)[Idx], &((T*)this->Buff)[LIdx], (OIdx-LIdx)*sizeof(T));
this->Resize(OIdx-Cnt);
}
else this->Resize(Idx); // At the end of list
return true;
}
//------------------------------------------------------------------------------------
bool Remove(T* Itm, size_t Cnt=1)
{
return this->Remove(size_t(Itm - ((T*)this->Buff)), Cnt);
}
//------------------------------------------------------------------------------------
};
//====================================================================================
template<typename T, UINT Prealloc=32> class CGrowArr: public CGrowArrImpl<T>
{
T Array[Prealloc];
public:
CGrowArr(void){this->LSize = Prealloc * sizeof(T);}
};
//====================================================================================
template<UINT MaxSize=512> class CArgPack: public CGrowBuf // Use this if there are more than one argument IN or OUT
{
BYTE Data[MaxSize];
public:
CArgPack(void){this->LSize = MaxSize;}
//------------------------------------------------------------------------------------
template<typename T> PBYTE PushArgEx(T& Value, char* Name=NULL, UINT Hint=0){return this->PushBlkEx(sizeof(T), &Value, Name, Hint);}
PBYTE PushBlkEx(UINT ValLen, PVOID Value=NULL, char* Name=NULL, UINT Hint=0)
{
UINT Offs = this->GetLen();
this->PushBlk(ValLen, Value); // Pointer is invalidated by ReAlloc
if(Name){this->PushStr(Name); ValLen |= 0x80000000;}
if(Hint){this->PushArg(Hint); ValLen |= 0x40000000;}
this->PushArg(ValLen);
return (PBYTE)this->GetPtr() + Offs;
}
//------------------------------------------------------------------------------------
PBYTE PopBlkEx(UINT* ValLen, char* Name=NULL, UINT* Hint=NULL) // No PopArgEx for this
{
UINT ValSize = 0;
UINT HintVal = 0;
if(!this->PopArg(ValSize))return NULL;
if(ValSize & 0x40000000)this->PopArg(HintVal);
if(ValSize & 0x80000000)this->PopStr(Name, (Hint)?(*Hint):(0));
ValSize &= 0x0FFFFFFF;
if(Hint)*Hint = HintVal;
if(ValLen)*ValLen = ValSize;
return this->PopBlk(ValSize, NULL);
}
//------------------------------------------------------------------------------------
PBYTE GetBlkAt(UINT& Offset=-1)
{
if(Offset == (UINT)-1)Offset = this->DSize;
UINT ValSize = 0;
if(sizeof(ValSize) > Offset)return NULL;
Offset -= sizeof(ValSize);
ValSize = *(UINT*)&this->Buff[Offset];
if(ValSize & 0x40000000)Offset -= sizeof(UINT);
if(ValSize & 0x80000000)
{
UINT StrSize = 0;
if(sizeof(StrSize) > Offset)return NULL;
Offset -= sizeof(StrSize);
StrSize = *(UINT*)&this->Buff[Offset];
if(StrSize > Offset)return NULL;
Offset -= StrSize;
}
ValSize &= 0x0FFFFFFF;
if(ValSize > Offset)return NULL;
Offset -= ValSize;
return &this->Buff[Offset];
}
//------------------------------------------------------------------------------------
template<typename T> PBYTE PushArg(T& Value){return this->PushBlk(sizeof(T), &Value);}
template<typename T> PBYTE PopArg(T& Value){return this->PopBlk(sizeof(T), &Value);}
template<typename T> T PopArg(void){T val; this->PopBlk(sizeof(T), &val); return val;}
//------------------------------------------------------------------------------------
template<typename T> PBYTE PushStr(T Str)
{
UINT Len = 0; // In chars // Not Including Zero
for(int ctr=0;Str[ctr];ctr++,Len++);
this->PushBlk(Len*sizeof(*Str), Str); // Push the string Str
return this->PushArg(Len); // CharCount of string
}
//------------------------------------------------------------------------------------
template<typename T> PBYTE PopStr(T Str, UINT MaxLen=0) // MaxLen in chars includes Zero
{
UINT FullLen = 0;
this->PopArg(FullLen);
if(!MaxLen || (--MaxLen > FullLen))MaxLen = FullLen;
if(MaxLen < FullLen)this->PopBlk((FullLen-MaxLen)*sizeof(*Str), NULL); // Skip end of string
if(Str)Str[MaxLen] = 0;
return this->PopBlk(MaxLen*sizeof(*Str), Str);
}
//------------------------------------------------------------------------------------
PBYTE PushBlk(UINT ValLen, PVOID Value=NULL) // TODO: Optimize allocations // Use an external memory pool
{
// DBGMSG("ValLen: %08X",ValLen);
SIZE_T OldSize = this->DSize;
this->GrowFor(this->DSize + ValLen);
PBYTE DstPtr = &this->Buff[OldSize];
if(Value)memcpy(DstPtr,Value,ValLen);
return DstPtr;
}
//------------------------------------------------------------------------------------
PBYTE PopBlk(UINT ValLen, PVOID Value=NULL)
{
if(ValLen > this->DSize){this->Clear(); return NULL;} // No that much data in buffer
this->DSize -= ValLen; // Just forgetting current block size and resizing it on next PUSH?
PBYTE DstPtr = &this->Buff[this->DSize];
if(Value)memcpy(Value,DstPtr,ValLen);
return DstPtr;
}
//------------------------------------------------------------------------------------
};
//====================================================================================
//
//
//
//------------------------------------------------------------------------------------
template<typename Usr=long> class CSharedMem // TODO: Kernel support (Use same NTAPI?) // TODO: Time of message locking to unlock by timeout even if an owner process is crashed
{
static const int MaxNameSize = 64;
#pragma pack(push,1)
struct SMemDescr: public Usr
{
volatile UINT32 MemFlgs; // Unused for now
volatile UINT32 MemSize; // Size of MemData
volatile BYTE NtfEName[MaxNameSize];
volatile BYTE SynMName[MaxNameSize]; // Name of Mutex
volatile BYTE Data[0]; // Should be aligned to 8
};
#pragma pack(pop)
HANDLE hNotifyEvt; // NOTE: Do not rely on Notification Event when used a multiple observers(Set timeout as low as possible and confirm changes by some other means)
HANDLE hSyncMutex;
HANDLE hMapFile;
HANDLE hDirObj;
SMemDescr* MemDesc; // Shared memory buffer
//---------------------------------------------------------
//---------------------------------------------------------
#ifndef _NTDLL_H
static ULONG GetObjNamespaceStr(char* DstStr)
{
char NameSpace[] = {'G','l','o','b','a','l','\\'}; // NOTE: Incompatible with custom named object directory
return CopyString(DstStr, NameSpace, sizeof(NameSpace));
}
#endif
//---------------------------------------------------------
static void MakeObjName(ULONG_PTR Value, LPSTR CustomPart, LPSTR OutName)
{
char TmpBuf[MaxNameSize];
TmpBuf[0] = 0;
if(CustomPart)
{
int idx = 0;
if(Value)TmpBuf[idx++] = '_';
CopyString(&TmpBuf[idx], CustomPart, sizeof(TmpBuf)-(8+8)); // Global\XXXXXXXX_CustomPart
}
ULONG_PTR NumPart = Value;
#ifndef _NTDLL_H
ULONG Len = GetObjNamespaceStr(OutName);
#else
ULONG Len = 0;
#endif
if(NumPart)
{
NumPart ^= (GetTicksCount() * (CurrentThreadID() * CurrentProcessID())); // Randomized?
int HLen = 0;
char HexBuf[64];
char* ptr = UIntToHexString(NumPart, sizeof(void*)*2, HexBuf, true, &HLen);
Len += CopyString(&OutName[Len], ptr, HLen);
}
CopyString(&OutName[Len], TmpBuf);
}
//---------------------------------------------------------
public:
CSharedMem(void)
{
this->hMapFile = NULL;
this->hNotifyEvt = NULL;
this->hSyncMutex = NULL;
this->MemDesc = NULL;
}
//---------------------------------------------------------
~CSharedMem(void)
{
this->Disconnect();
}
//---------------------------------------------------------
bool IsConnected(void){return (bool)this->hMapFile;}
HANDLE GetMapHandle(void){return this->hMapFile;}
//---------------------------------------------------------
static bool IsMappingExist(LPSTR MapName)
{
char FullPath[256];
#ifndef _NTDLL_H
ULONG Len = GetObjNamespaceStr(FullPath);
#else
ULONG Len = 0;
#endif
Len += CopyString(&FullPath[Len], MapName);
#ifdef _NTDLL_H
HANDLE hMap = NULL;
if(OpenMemSection(&hMap, FILE_MAP_ALL_ACCESS, FullPath, ObjDirName) < 0)return false; // Doesn`t exist or access denied
#else
HANDLE hMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, FullPath);
if(!hMap)return false; // Doesn`t exist or access denied
#endif
CloseOHandle(hMap);
return true;
}
//---------------------------------------------------------
static UINT64 GetMappingSize(LPSTR MapName)
{
char FullPath[256];
UINT64 Size = 0;
#ifndef _NTDLL_H
ULONG Len = GetObjNamespaceStr(FullPath);
#else
ULONG Len = 0;
#endif
Len += CopyString(&FullPath[Len], MapName);
#ifdef _NTDLL_H
HANDLE hMap = NULL;
if(OpenMemSection(&hMap, FILE_MAP_ALL_ACCESS, FullPath, ObjDirName) < 0)return 0; // Doesn`t exist or access denied
#else
HANDLE hMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, FullPath);
if(!hMap)return 0; // Doesn`t exist or access denied
#endif
#ifdef _NTDLL_H
SECTION_BASIC_INFORMATION SectionInfo; // = { 0 };
NTSTATUS res = NtQuerySection(hMap, SectionBasicInformation, &SectionInfo, sizeof(SectionInfo), 0);
if(!res)Size = SectionInfo.MaximumSize.QuadPart;
#else
// No documented way to get mapping size?
#endif
CloseOHandle(hMap);
return Size;
}
//---------------------------------------------------------
int Connect(LPSTR MapName, SIZE_T SizeOfNew) // Creates or opens a Shared Memory
{
BYTE TmpBuf[MaxNameSize];
if(this->hMapFile){if(this->Disconnect() < 0){DBGMSG("Failed to disconnect!"); return -1;}}
SizeOfNew = AlignFrwd(SizeOfNew,8);
MakeObjName(0, MapName, (LPSTR)&TmpBuf);
NTSTATUS status = CreateNtObjDirectory(ObjDirName, &this->hDirObj); // Create objects directory with NULL security
if(status < 0){DBGMSG("CreateNtObjDirectory failed(%08X)", status); return -2;}
/*SECURITY_ATTRIBUTES security;
ZeroMemory(&security, sizeof(security));
security.nLength = sizeof(security);
ConvertStringSecurityDescriptorToSecurityDescriptor(
L"D:P(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;OICI;GWGR;;;IU)",
1,
&security.lpSecurityDescriptor,
NULL);
*/
#ifdef _NTDLL_H
LARGE_INTEGER MaxSize;
MaxSize.QuadPart = SizeOfNew;
status = CreateMemSection(&this->hMapFile, SECTION_ALL_ACCESS, &MaxSize, PAGE_READWRITE, SEC_COMMIT, (LPSTR)&TmpBuf, ObjDirName);
if(status < 0){DBGMSG("CreateMapping failed(%08X): Size=%08X", status, SizeOfNew); return -3;} // HANDLE hSec = CreateFileMappingW(INVALID_HANDLE_VALUE,NULL,PAGE_EXECUTE_READWRITE|SEC_COMMIT,0,ModSize,NULL);
bool CreatedNew = !(STATUS_OBJECT_NAME_EXISTS == status);
PVOID BaseAddr = NULL;
status = NtMapViewOfSection(this->hMapFile,NtCurrentProcess,&BaseAddr,0,SizeOfNew,NULL,&SizeOfNew,ViewShare,0,PAGE_READWRITE);
if(status){DBGMSG("Failed to map memory: %08X", status); CloseOHandle(this->hMapFile); this->hMapFile = NULL; return -4;}
this->MemDesc = (SMemDescr*)BaseAddr;
#else
this->hMapFile = CreateFileMappingA(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,SizeOfNew,(LPSTR)&TmpBuf);
//LocalFree(securityDescriptor.lpSecurityDescriptor);
if(!this->hMapFile){DBGMSG("CreateMapping failed(%u): Size=%08X", GetLastError(), SizeOfNew); return -5;}
bool CreatedNew = !(GetLastError() == ERROR_ALREADY_EXISTS);
this->MemDesc = (SMemDescr*)MapViewOfFile(this->hMapFile,FILE_MAP_ALL_ACCESS,0,0,SizeOfNew); // Real memory pages will be allocated on first access?
if(!this->MemDesc){DBGMSG("Failed to map memory: %u", GetLastError()); CloseOHandle(this->hMapFile); this->hMapFile = NULL; return -6;}
#endif
if(CreatedNew)
{
DBGMSG("Created: Initializing IPC header at %p",this->MemDesc);
// memset(this->MemDesc,0,sizeof(SMemDescr)+sizeof(PVOID));
this->MemDesc->MemSize = SizeOfNew;
MakeObjName((ULONG_PTR)this->hMapFile, "S", (LPSTR)&this->MemDesc->SynMName); // Create a Mutex name
MakeObjName((ULONG_PTR)this->hMapFile, "N", (LPSTR)&this->MemDesc->NtfEName);
}
#ifdef _NTDLL_H
NShMem::MutexCreateA(&this->hSyncMutex, NULL, FALSE, (LPSTR)&this->MemDesc->SynMName, ObjDirName);
NShMem::EventCreateA(&this->hNotifyEvt, NULL, TRUE, FALSE, (LPSTR)&this->MemDesc->NtfEName, ObjDirName);
#else
this->hSyncMutex = CreateMutexA(NULL, FALSE, (LPSTR)&this->MemDesc->SynMName); // Take the names from shared memory
this->hNotifyEvt = CreateEventA(NULL, TRUE, FALSE, (LPSTR)&this->MemDesc->NtfEName);
#endif
if(!this->hSyncMutex || !this->hNotifyEvt){DBGMSG("Failed to create sync objects: hSyncMutex=%p(%s), hNotifyEvt=%p(%s)", this->hSyncMutex, &this->MemDesc->SynMName, this->hNotifyEvt, &this->MemDesc->NtfEName); this->Disconnect(); return -7;}
DBGMSG("CreatedNew=%u, SizeOfNew=%08X, MemDesc=%p, MMapName='%s', SynMName='%s', NtfEName='%s'", CreatedNew, SizeOfNew, this->MemDesc, &TmpBuf, &this->MemDesc->SynMName, &this->MemDesc->NtfEName);
return !CreatedNew; // Created a new shared buffer
}
//---------------------------------------------------------
int Disconnect(void)
{
if(!this->IsConnected())return 0; // Not connected
DBGMSG("Disconnecting...");
this->LockBuffer(9000); // Try to Lock but allow Disconnect in case someone else is hang up
HANDLE hMap = this->hMapFile;
this->hMapFile = NULL;
if(!this->MemDesc)return -2;
if(NTSTATUS stat = NtUnmapViewOfSection(NtCurrentProcess, this->MemDesc)){DBGMSG("Failed to unmap memory: %08X", stat); return -3;}
DBGMSG("MemDesc=%p",this->MemDesc);
this->MemDesc = NULL;
CloseOHandle(hMap);
if(this->hNotifyEvt)CloseOHandle(this->hNotifyEvt);
this->hNotifyEvt = NULL;
this->UnlockBuffer();
if(this->hSyncMutex)CloseOHandle(this->hSyncMutex);
this->hSyncMutex = NULL;
if(this->hDirObj)CloseOHandle(this->hDirObj);
return 0;
}
//---------------------------------------------------------
bool LockBuffer(UINT WaitDelay=5000)
{
// DBGMSG("<<<<<<<<<<<<<<<<: %u",WaitDelay);
// DWORD val = GetTicksCount();
bool res = (NShMem::WaitForSingle(this->hSyncMutex,WaitDelay) != WAIT_TIMEOUT);
// DBGMSG("<<<<<<<<<<<<<<<<: %u = %u",res,GetTicksCount()-val);
if(res && !this->IsConnected()){this->UnlockBuffer(); return false;}
return res;
}
//---------------------------------------------------------
bool UnlockBuffer(void)
{
#ifdef _NTDLL_H
UINT res = NtReleaseMutant(this->hSyncMutex, 0) >= 0;
#else
UINT res = ReleaseMutex(this->hSyncMutex);
#endif
// DBGMSG(">>>>>>>>>>>>>>>>: %u",res);
return res;
}
//---------------------------------------------------------
PBYTE BufferPtr(void)
{
if(!this->IsConnected())return NULL;
return (PBYTE)&this->MemDesc->Data;
}
//---------------------------------------------------------
UINT BufferSize(void)
{
if(!this->IsConnected())return 0;
return (this->MemDesc->MemSize - sizeof(SMemDescr));
}
//---------------------------------------------------------
Usr* UserData(void){return this->MemDesc;}
//---------------------------------------------------------
bool NotifyChange(void)
{
#ifdef _NTDLL_H
return NtSetEvent(this->hNotifyEvt, 0) >= 0;
#else
return SetEvent(this->hNotifyEvt);
#endif
}
//---------------------------------------------------------
bool ResetChange(void)
{
#ifdef _NTDLL_H
return NtClearEvent(this->hNotifyEvt) >= 0;
#else
return ResetEvent(this->hNotifyEvt); // At this point all waiting threads are got the event. They all will call this ResetEvent (That`s not a problem?)
#endif
}
//---------------------------------------------------------
// You must check for a new messages before calling this function because some other thread may already reset the Notify Event after a change
//
bool WaitForChange(UINT WaitDelay=1000)
{
// DBGMSG("++++++++++++++++: %u",WaitDelay);
// DWORD val = GetTickCount();
bool res = (NShMem::WaitForSingle(this->hNotifyEvt,WaitDelay) != WAIT_TIMEOUT);
// DBGMSG("++++++++++++++++: %u = %u",res,GetTickCount()-val);
return res;
}
//---------------------------------------------------------
};
//===========================================================================
// Multi Producer, Multi Consumer
//
// Limitations:
// A data block can`t be split so it will be written at beginning of buffer destroying blocks(and leaving that memory unused until an another block may reclaim it) at its end (where it initially supposed to be written) to keep the data stream circular.
//
//===========================================================================
class CSharedIPC
{
static const int WaitChangeDelMs = 100;
#pragma pack(push,1)
public:
struct SMsgBlk // Size is 32 + Data + ValidMrk2 // Always aligned to 16 bytes
{
volatile UINT32 DataSize;
volatile UINT32 ViewCntr;
volatile UINT32 PrevOffs;
volatile UINT32 NextOffs; // From beginning of buffer // There may be gaps between messages after a wrap overwrites some of them
volatile UINT32 TargetID;
volatile UINT32 SenderID;
volatile UINT32 MsgSeqID; // Incremented for each message
volatile UINT32 ValidMrk; // A Opening marker. An Closing marker is after the data
volatile BYTE Data[0]; // Better to be aligned to 8 bytes
static UINT32 FullSize(UINT32 DSize){
return AlignFrwd(DSize + sizeof(SMsgBlk) + sizeof(UINT32), 16);} // After Hdr+Data, at aligned end is UINT32(~ValidMrk) // Align 16 (SSE compatible)
UINT32 FullSize(void){return FullSize(this->DataSize);} // AlignFrwd(this->DataSize + sizeof(SMsgBlk) + 8,8);} // All data blocks aligned to 8 bytes
bool IsBroadcast(void){return !this->TargetID;}
};
private:
struct SDescr // No message wrapping is supported(), if it is not fits then RD and WR pointers are get updated to beginning of the buffer
{
enum EFlags {flEmpty,flUsed=1};
volatile UINT32 Flags; // 0 if buffer is empty // MessageCtr is useless and too costly to maintain
volatile UINT32 NxtMsgID; // Next MessageID to be used (Used by each instance to exclude a viewed messages from enumeration) // What will happen after overflow?
volatile UINT32 FirstBlk; // Points to oldest available message
volatile UINT32 LastBlk; // Points last added message
};
#pragma pack(pop)
UINT32 SyncDelay;
UINT32 InstanceID;
SMsgBlk* NewMsg; // Temporary ptr, protected by Lock
CSharedMem<SDescr> MBuf;
//---------------------------------------------------------------------------
bool IsValidHdr(SMsgBlk* Blk)
{
PBYTE Ptr = this->MBuf.BufferPtr();
PBYTE End = &Ptr[this->MBuf.BufferSize()];
PBYTE Msg = (PBYTE)Blk;
if((Msg < Ptr)||(Msg >= End)){DBGMSG("MsgBegOutside"); return false;} // Begin is not inside the shared buffer
if((&Msg[sizeof(SMsgBlk)] < Ptr)||(&Msg[sizeof(SMsgBlk)] > End)){DBGMSG("HdrOutside"); return false;} // Hdr is not inside the shared buffer
ULONG Len = Blk->FullSize();
if((&Msg[Len] < Ptr)||(&Msg[Len] > End)){DBGMSG("MsgEndOutside"); return false;} // End is not inside the shared buffer
if(!Blk->SenderID){DBGMSG("Unfinished"); return false;} // Not finished yet
bool res = !(~(*(UINT32*)&Msg[Len-sizeof(UINT32)]) ^ Blk->ValidMrk);