-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP2PmsgMgr.cpp
More file actions
1688 lines (1570 loc) · 58.6 KB
/
Copy pathP2PmsgMgr.cpp
File metadata and controls
1688 lines (1570 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2005-2010, 2022, 2026 Ivyware Pty Ltd, Khrustal & Mann
// MELBOURNE, VICTORIA, AUSTRALIA, 3000
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//
// P2PmsgMgr definitions and prototypes
//
#include "stdafx.h"
#include "P2PmsgMgr.h"
#include "Msgexception.h"
#include "MsgVBHeap.h"
#include "Kernel32_Ext.h"
#include <ASSERT.h>
#include "Tchar.h"
#define objVBList m_oObject.m_hVBList
#define objVBLock m_oObject.m_uVBLock
///////////////////////////////////////////////////////////////////////
// Generic P2Pmsg manager
// Constructors and destructor
P2PmsgMgr::P2PmsgMgr ( )
: P3PmsgItem ( 0, 0, 0 )
{
RenderThisSafe ( );
m_hMgr = P2PmsgHeap_CreateBSTRio ( VBLock_Addr32, 2024, 0 );
Attacheap ( L"P2PmsgMgr name", P3PmsgData() );
ASSERT(m_hMgr==this->r_Object().m_hVBList);
}
P2PmsgMgr::P2PmsgMgr ( UCHAR uAddrNN, UINT nSizeInitial, UINT nSizeMax )
: P3PmsgItem ( 0, 0, 0 )
{
RenderThisSafe ( );
m_hMgr = P2PmsgHeap_CreateBSTRio ( uAddrNN, nSizeInitial, nSizeMax );
Attacheap ( L"", P3PmsgData() );
ASSERT(m_hMgr==this->r_Object().m_hVBList);
}
P2PmsgMgr::P2PmsgMgr ( const P2PmsgMgr& rhs )
: P3PmsgItem ( 0, 0, 0 )
{
RenderThisSafe ( );
m_hMgr = P2PmsgHeap_CreateBSTRio ( P2PmsgHeap_Addrnn(rhs.m_hMgr), 2024, 0 ); //TODO:LJM +2024 is a fudge
Attacheap ( rhs.c_name(), ((P2PmsgMgr&)rhs).r_data() );
(*this) = rhs;
ASSERT(m_hMgr==this->r_Object().m_hVBList);
}
P2PmsgMgr::P2PmsgMgr ( LPCWSTR lpszFilename )
: P3PmsgItem ( 0, 0, 0 )
{
RenderThisSafe ( );
m_hMgr = P2PmsgHeap_CreateBSTRio ( VBLock_Addr32, 2024, 0 );
Attacheap ( L"", P3PmsgData() );
ASSERT(m_hMgr==this->r_Object().m_hVBList);
Load ( lpszFilename );
}
P2PmsgMgr::~P2PmsgMgr ( )
{
if ( m_hMgr )
P2PmsgHeap_Close ( m_hMgr );
m_hMgr = 0;
if ( m_hFile != INVALID_HANDLE_VALUE )
CloseHandle ( m_hFile );
m_hFile = INVALID_HANDLE_VALUE;
DeleteCriticalSection ( &m_oCSectionMgr );
}
void
P2PmsgMgr::RenderThisSafe ( )
{
//m_hMgr = 0;
//m_hFile = INVALID_HANDLE_VALUE;
m_uiWM_APP_TrigINSERT = WM_P2Pmsg_TrigINSERT;
m_uiWM_APP_TrigUPDATE = WM_P2Pmsg_TrigUPDATE;
m_uiWM_APP_TrigDELETE = WM_P2Pmsg_TrigDELETE;
// Resources
CoCreateGuid ( &m_oGUID );
InitializeCriticalSection ( &m_oCSectionMgr );
}
void
P2PmsgMgr::Nullify ( )
{
if ( m_hMgr )
P2PmsgHeap_Close ( m_hMgr );
m_hMgr = 0;
if ( m_hFile != INVALID_HANDLE_VALUE )
CloseHandle ( m_hFile );
m_hFile = INVALID_HANDLE_VALUE;
__super::Nullify ( );
}
//
// Attaches heap to this P2PmsgMgr
//
// Parameters: LPCTNAME lpszMsgName
// Name allocated to heap
//
// const P3PmsgData& oData
// Top level heap data
//
// Returns: P2PmsgMgr&
// Reference to this P2PmsgMgr
P2PmsgMgr&
P2PmsgMgr::Attacheap ( LPCWSTR lpszMsgName, const P3PmsgData& oData )
{
// Environmental
// NOTES: Create a dummy root item for sizing purposes, then allocate
// a chunk directly from the P2PmsgHeap since its yet to be attached
// to the P2PmsgMgr
ASSERT(oData.VerifyContainment());
UCHAR uVBLaddrnn = P2PmsgHeap_Addrnn ( m_hMgr );
P3PmsgItem oRootItem ( lpszMsgName, oData ); // Dummy root for P2PmsgMgr
VBLsize nSizeofRoot = P2PmsgField_SizeofItem ( uVBLaddrnn, oRootItem, TRUE );
VBLaddr aVBLock = P2PmsgHeap_Alloc ( m_hMgr, VBLock_Item, nSizeofRoot ); //Displaces above line
VBLock *pVBLock = (VBLock *)P2PmsgHeap_Addr2Phys ( m_hMgr, aVBLock );
pVBLock -> oHdr.uVBLockDefs |= VBLock_Linked; //Added later by LJM
VBLockItem_Init ( uVBLaddrnn, VBLock_pItem(pVBLock), VBLock_Field ); // Added later by LJM
VBLockField *pField = VBLock_pField ( pVBLock );
VBLockField_Init ( pField, 0xFF ); //TODO: LJM node to field cutover 0xFF );
VBLockName *pName = VBLockField_pName ( pField );
VBLsize nName_Sizeof = VBLockName_Sizeof ( uVBLaddrnn, P2PmsgObject_pName( oRootItem.r_Object() ) );
nName_Sizeof = max ( nName_Sizeof, VBLockName_Sizeof_Min(uVBLaddrnn) );
VBLockName_Init ( uVBLaddrnn, pName
, VBLockAttr_DEFAULT | VBLockAttr_NULL
, lpszMsgName, nName_Sizeof );
VBLockData *pData = VBLockField_pData ( uVBLaddrnn, pField );
VBLsize nData_Sizeof = VBLockData_Sizeof ( uVBLaddrnn, P2PmsgObject_pData( oRootItem.r_Object() ) );
nData_Sizeof = max ( nData_Sizeof, VBLockData_Sizeof_Min(uVBLaddrnn) );
VBLockData_Init ( VBLockField_pData(m_oObject.m_aVBLock,pField)
, VBLockAttr_DEFAULT, oData.DataType(), nData_Sizeof );
Connect ( m_hMgr, aVBLock, VBLock_Hdr_u_SizeNN(pVBLock) );
r_data() = oData;
ASSERT(VBLock_IsLinked(pVBLock));
ASSERT(VBLock_IsAlloc(pVBLock));
ASSERT(VBLock_IsItem(pVBLock));
return *this;
}
//
// Load and attach an existing P2P message heap from disk
// NOTES: Existing manager/file state is released before loading.
// : Entire file is read into memory, then type-dispatched
// based on heap header identification.
// : Supports BSTRio and IOMAGE heap formats.
// : Files > 4GB are intentionally rejected.
//
BOOL
P2PmsgMgr::Load ( LPCWSTR lpszFilename )
{
BOOL bResult = FALSE;
char *pP2PmsgHeap = nullptr;
try
{
//
// Release existing file handle/state
if ( m_hFile != INVALID_HANDLE_VALUE )
CloseHandle ( m_hFile );
m_hFile = INVALID_HANDLE_VALUE;
m_strFilename.Empty();
//
// Open the existing file READ-ONLY. Load reads the whole file into
// memory (below) and the heap is an in-memory copy, so no write access
// is needed. Sharing READ|WRITE means the open never blocks other
// readers/writers and can even read a store that a live saver still
// holds open.
P2PsafeHANDLE shFile
= CreateFile ( lpszFilename
, GENERIC_READ
, FILE_SHARE_READ | FILE_SHARE_WRITE
, nullptr
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL, nullptr );
if ( shFile == INVALID_HANDLE_VALUE )
EVERR->MODULE
->Message(L"CreateFile(%s) failed", lpszFilename)
->HResult(0)
->Throw();
//
// Validate file size
// NOTES: Reject files > 4GB and obviously invalid files
DWORD dwFileSizeHi = 0;
DWORD dwFileSizeLo = GetFileSize(shFile, &dwFileSizeHi);
if ( dwFileSizeHi ||
dwFileSizeLo < sizeof(VBListBSTRio) )
EVERR->MODULE
->AFP(lpszFilename)
->Message(L"Invalid file size")
->HResult(0)
->Throw();
//
// Load entire file into memory
pP2PmsgHeap = new char[dwFileSizeLo];
DWORD dwBytesRead = 0;
bResult = ReadFile ( shFile
, pP2PmsgHeap
, dwFileSizeLo
,&dwBytesRead, nullptr );
if ( !bResult || dwBytesRead != dwFileSizeLo )
EVERR->MODULE
->Message(L"ReadFile(%s) failed", lpszFilename)
->HResult(0)
->Throw();
//
// Determine heap format and connect manager
Nullify ( );
if ( P2PmsgHeap_IsBSTRio(pP2PmsgHeap) )
{
// dwFileSizeLo is the real extent of the buffer above, and the
// BSTRio branch went without it until finding F1. The IOMAGE branch
// below has passed it since the C4 fix; this arm of the same
// dispatch, reached by a file whose first byte is the BSTRio tag
// rather than by anything the C4 test could produce, did not -- so
// an offset read out of the file became a pointer with nothing in
// between. Both arms now check the same thing against the same
// number.
m_hMgr = P2PmsgHeap_CreateBSTRio(
reinterpret_cast<VBListBSTRio*>(pP2PmsgHeap), dwFileSizeLo);
pP2PmsgHeap = nullptr; // ownership transferred
Connect ( m_hMgr, P2PmsgHeap_ConnectBSTRio(m_hMgr), 0 );
}
else if ( P2PmsgHeap_IsIOMAGE(pP2PmsgHeap) )
{
// THE STORE ACCEPTS A PRE-SENTINEL IMAGE AND THE WIRE DOES NOT,
// and the asymmetry is the decision rather than an oversight
// (Targetcore's versioning note, §6, byte_order.md §4.3).
// A frame is a peer, and a peer can be upgraded; a file is
// data somebody already has, and there is no conversation to
// have with it.
// It is still worth saying out loud. A generation-0 image makes no
// statement about its own layout, so everything below parses it
// under THIS build's rules on the strength of nothing - which is
// exactly the silent misread the generation code exists to end.
// F-S6-4 put WARNING in the default mask, which is what makes
// saying so reach anybody.
if ( P2PmsgHeap_IOMAGEform(pP2PmsgHeap) == VBLockSync_Legacy )
EVWRN->MODULE
->AFP(lpszFilename)
->Message(L"Pre-sentinel message image (layout generation 0)")
->Advice (L"Parsed under this build's layout, unverified")
->Cancel (true); // display once, notify, and DELETE
m_hMgr = P2PmsgHeap_CreateIOMAGE(
reinterpret_cast<VBListIOmage*>(pP2PmsgHeap), dwFileSizeLo);
pP2PmsgHeap = nullptr; // ownership transferred
VBLaddr aVBLock = sizeof(VBListIOmage::oSync);
Connect( m_hMgr, P2PmsgHeap_Connect(m_hMgr), aVBLock );
}
else
EVERR->MODULE
->AFP(lpszFilename)
->Message(L"Unknown or corrupted P2PmsgHeap")
->Throw();
//
// Commit successful load. Do NOT retain the file handle: the heap is
// an in-memory copy, so shFile closes here holding no lock. The
// filename is remembered so a later Save() with no argument reopens the
// file for writing (see Save). m_hFile stays INVALID_HANDLE_VALUE.
m_strFilename = lpszFilename;
return TRUE;
}
//
// Exception handlers
//
catch_pP2Pevent_SetLast
catch_pCException_SetLast
catch_ALL_SetLast
delete[] pP2PmsgHeap;
return FALSE;
}
/*BOOL
P2PmsgMgr::Load ( LPCWSTR lpszFilename )
{
// Locals
BOOL bResult;
char *pP2PmsgHeap = nullptr;
// Because this is problematic
try
{
// Resource recovery
if ( m_hFile != INVALID_HANDLE_VALUE )
CloseHandle ( m_hFile );
m_hFile = INVALID_HANDLE_VALUE;
m_strFilename.Empty();
// Open existing disk file
P2PsafeHANDLE shFile = CreateFile ( lpszFilename
, (GENERIC_READ | GENERIC_WRITE)
, m_dwSharedMode // No shared access
, 0 // No security attributes
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0 ); // No template
if ( shFile == INVALID_HANDLE_VALUE )
EVERR->MODULE
->Message( L"CreateFile(%s) failed", lpszFilename )
->HResult( 0 )->Throw();
// Load file contents
DWORD dwFileSizeHi = 0;
DWORD dwFileSizeLo = GetFileSize ( shFile, &dwFileSizeHi );
if ( dwFileSizeHi ||
dwFileSizeLo < sizeof(VBListBSTRio) )
EVERR->MODULE->AFP(lpszFilename)
->Message( L"GetFileSize(%s) failed", lpszFilename )
->HResult( 0 )->Throw();
pP2PmsgHeap = new char [dwFileSizeLo];
DWORD dwBytesRead = 0;
bResult = ReadFile( shFile, pP2PmsgHeap, dwFileSizeLo, &dwBytesRead, 0 );
if ( !bResult || dwBytesRead != dwFileSizeLo )
EVERR->MODULE
->Message( L"ReadFile(%s) data failed", lpszFilename )
->HResult( 0 )->Throw();
// Application
// TODO:LJM this can be tidied up and made more generic
if ( P2PmsgHeap_IsBSTRio(pP2PmsgHeap) )
{
Nullify ( );
m_hMgr = P2PmsgHeap_CreateBSTRio ( (VBListBSTRio *)pP2PmsgHeap );
pP2PmsgHeap = nullptr;
Connect ( m_hMgr, P2PmsgHeap_ConnectBSTRio(m_hMgr), 0 );
}
else if ( P2PmsgHeap_IsIOMAGE(pP2PmsgHeap) )
{
//VBListIOmage oIOmage;
Nullify ( );
m_hMgr = P2PmsgHeap_CreateIOMAGE ( (VBListIOmage *)pP2PmsgHeap );
pP2PmsgHeap = 0; // Locked in elsewhere now
VBLaddr aVBLock = sizeof(VBListIOmage::oSync); //was sizeof(oIOmage.oSync);
Connect ( m_hMgr, P2PmsgHeap_Connect(m_hMgr), aVBLock );
//Connect ( m_hMgr, sizeof(oIOmage.oSync), aVBLock );
}
else
EVERR->MODULE->AFP(lpszFilename)
->Message( L"Unknown or corrupted P2PmsgHeap" )
->Throw();
m_strFilename = lpszFilename;
m_hFile = shFile.Dereference();
return TRUE;
}
// Exceptions
catch_pP2Pevent_SetLast
catch_pCException_SetLast
catch_ALL_SetLast
// Tidy up, and
delete [] pP2PmsgHeap;
return FALSE;
}*/
// Puts the free-block boundary tags back, whatever happens between the scrub
// and the last byte being written. Save throws from a dozen places in between.
namespace {
struct P2PmsgScrubGuard
{
P2PmsgHANDLE m_h;
explicit P2PmsgScrubGuard ( P2PmsgHANDLE h ) noexcept : m_h(h) {}
~P2PmsgScrubGuard ( ) { P2PmsgHeap_ScrubFoots ( m_h, true ); }
};
}
BOOL
P2PmsgMgr::Save ( LPCWSTR lpszFilename, bool bDefragment )
{
// Locals
BOOL bResult = FALSE;
HANDLE hFile = INVALID_HANDLE_VALUE;
// Problematic
try
{
// Resolve the target file. An explicit filename always wins; otherwise
// fall back to the remembered file (e.g. save-back after a read-only
// Load). An atomic save needs a concrete target name to rename onto.
CString strTarget = ( lpszFilename && wcslen(lpszFilename) > 0 )
? CString(lpszFilename) : m_strFilename;
if ( strTarget.IsEmpty() )
EVERR -> MODULE
-> Message( L"Save() has no target filename" )
-> Throw();
// Release any handle we hold on the target so the rename can replace it.
if ( m_hFile != INVALID_HANDLE_VALUE )
CloseHandle ( m_hFile );
m_hFile = INVALID_HANDLE_VALUE;
// Defragmentation
// NOTES: Can take considerable time with large data stores
if ( bDefragment )
{
ASSERT(m_hMgr==r_Object().m_hVBList);
P2PmsgMgr oMgr = *this;
__super::Nullify ( ); // Only P3PmsgItem base class
P2PmsgHeap_Close ( m_hMgr ); // Drops our current list
m_hMgr = oMgr.m_hMgr; // Copy defragmented handle
P2PmsgHeap_AddRef( m_hMgr ); // Increment reference count
Connect ( m_hMgr, P2PmsgHeap_Connect(m_hMgr), 0 );
ASSERT(m_hMgr==r_Object().m_hVBList);
}
// Capture the heap image to persist.
// Scrubbed of free-block boundary tags first, and re-stamped once the
// bytes are out. The tags are an in-memory accelerator for backward
// coalescing; letting them reach the file would make an image written by
// this build differ from one written before the tags existed, for no
// gain -- nothing ever reads the inside of a free block back.
P2PmsgHeap_ScrubFoots ( m_hMgr, false );
P2PmsgScrubGuard shFoots ( m_hMgr ); // Re-stamps, including on a throw
void *vpIOmage = P2PmsgHeap_pImage ( m_hMgr );
VBLsize dwIOmageSize = P2PmsgHeap_Sizeof ( m_hMgr );
// Serialise concurrent writers to the same store (cross-process). Acquire
// an exclusive lock file beside the target; if another writer holds it,
// back off briefly and retry, then fail cleanly rather than racing. The
// lock is released and its file removed (FILE_FLAG_DELETE_ON_CLOSE) when
// shLock goes out of scope - including on any throw below.
CString strLock = strTarget + L".lock";
HANDLE hLockRaw = INVALID_HANDLE_VALUE;
for ( int i = 0; ; i++ )
{
hLockRaw = CreateFileW ( strLock, GENERIC_WRITE | DELETE, 0, nullptr,
CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, nullptr );
if ( hLockRaw != INVALID_HANDLE_VALUE )
break;
DWORD dwErr = GetLastError();
if ( dwErr != ERROR_SHARING_VIOLATION || i >= 50 ) // ~1s of retries
EVERR -> MODULE -> AFP((LPCWSTR)strTarget)
-> Message( L"Save: could not acquire write lock (concurrent writer?)" )
-> HResult( dwErr )
-> Throw();
Sleep ( 20 );
}
P2PsafeHANDLE shLock = hLockRaw; // RAII: releases lock + deletes lock file
// Atomic save: write the full image to a sibling temp file (same
// directory => same volume), flush it, then replace the target with a
// single rename. A crash before the rename leaves the existing store
// intact; a crash after it leaves the fully-written new store. There is
// no window in which the target is half-written.
CString strTemp;
strTemp.Format ( L"%s.%lu.tmp", (LPCWSTR)strTarget, GetCurrentThreadId() );
hFile = CreateFileW ( strTemp, GENERIC_WRITE, 0, nullptr
, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr );
if ( hFile == INVALID_HANDLE_VALUE )
{
DWORD dwErr = GetLastError();
DeleteFileW ( strTemp );
EVERR -> MODULE -> AFP((LPCWSTR)strTemp)
-> Message( L"CreateFile(temp) failed" )
-> HResult( dwErr )
-> Throw();
}
DWORD dwBytesWritten = 0;
BOOL bWrote = WriteFile ( hFile, vpIOmage, (DWORD)dwIOmageSize, &dwBytesWritten, 0 );
if ( !bWrote || dwBytesWritten != (DWORD)dwIOmageSize )
{
DWORD dwErr = GetLastError();
CloseHandle ( hFile ); hFile = INVALID_HANDLE_VALUE;
DeleteFileW ( strTemp );
EVERR -> MODULE -> AFP((LPCWSTR)strTarget)
-> Message( L"WriteFile(temp) failed" )
-> HResult( dwErr )
-> Throw();
}
FlushFileBuffers ( hFile ); // durable before the rename
CloseHandle ( hFile ); hFile = INVALID_HANDLE_VALUE;
// Atomic replace on the same volume; WRITE_THROUGH flushes the rename.
if ( !MoveFileExW ( strTemp, strTarget
, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH ) )
{
DWORD dwErr = GetLastError();
DeleteFileW ( strTemp );
EVERR -> MODULE -> AFP((LPCWSTR)strTarget)
-> Message( L"MoveFileEx() atomic replace failed" )
-> HResult( dwErr )
-> Throw();
}
m_strFilename = strTarget; // remembered for save-back; no handle retained
P2PmsgHeap_SetDirty ( m_hMgr, FALSE );
bResult = TRUE;
}
// Exceptions
catch_pP2Pevent_Cancel
catch_pCException_Cancel
catch_ALL_Cancel
// Tidy up, and
return bResult;
}
BOOL
P2PmsgMgr::SharedMode ( DWORD dwSharedMode )
{
m_dwSharedMode = dwSharedMode;
return TRUE;
}
BOOL
P2PmsgMgr::Rename ( LPCWSTR lpszNewname )
{
if ( m_strFilename.IsEmpty() || !lpszNewname )
return FALSE;
if ( !MoveFileEx ( m_strFilename, lpszNewname
, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH ) )
return FALSE;
m_strFilename = lpszNewname;
return TRUE;
}
///////////////////////////////////////////////////////////////////////
// Factories
P2PmsgMgr*
P2PmsgMgr::Factory ( LPCWSTR lpszFilename
, UCHAR uAddrNN, UINT nSizeInitial, UINT nSizeMax )
{
// Locals
P2PmsgMgr *pMgr = 0;
P2PsafeHANDLE shFile;
try
{
//
shFile = CreateFile ( lpszFilename
, (GENERIC_READ | GENERIC_WRITE)
, 0 //pMgr->m_dwSharedMode // No shared access
, 0 // No security attributes
, CREATE_NEW
, FILE_ATTRIBUTE_NORMAL
, 0 ); // No template
HRESULT hr = GetLastError(); // Destroyed by subsequent action
if ( shFile == INVALID_HANDLE_VALUE )
EVERR->MODULE
->AFP(lpszFilename)->AFP(uAddrNN)->AFP(nSizeInitial)->AFP(nSizeMax)
->Message( L"CreateFile(%s) failed", lpszFilename )
->HResult( hr )
->Throw();
// Instanciation
pMgr = new P2PmsgMgr ( uAddrNN, nSizeInitial, nSizeMax );
pMgr -> m_strFilename = lpszFilename;
pMgr -> m_hFile = shFile.Dereference();
// Instantiated
return pMgr;
}
// Exceptions
catch_pP2Pevent_SetLast
catch_pCException_SetLast
catch_ALL_SetLast
// Tidy up, and
delete pMgr;
return nullptr;
}
P2PmsgMgr*
P2PmsgMgr::Factory ( LPCWSTR lpszFilename, DWORD dwSharedMode )
{
// Locals
P2PmsgMgr *pMgr = 0;
// Because this is problematic
try
{
// Target
pMgr = new P2PmsgMgr ( );
pMgr -> m_dwSharedMode = dwSharedMode;
if ( !pMgr->Load(lpszFilename) )
ThrowP2Pevent();
return pMgr;
}
// Exceptions
catch_pP2Pevent_SetLast
catch_pCException_SetLast
catch_ALL_SetLast
// Tidy up, and
delete pMgr;
return 0;
}
/////////////////////////////////////////////////
// Paging control etc
//
// Paging callback registrations
//
// Parameters: PINT_PTR nfnP2PageItemCB
// User defined callback data. Usually pointer to
// originating class
//
// P2PageinCBFnc *pP2PageinCBFnc
// Pointer to call back function for page in operations
//
// P2PageoutCBFnc *pP2PageoutCBFnc
// Pointer to call back function for page out operations
//
// Returns: BOOL
// Operation summary
BOOL
P2PmsgMgr::PageRegistration ( PINT_PTR nfnP2PageItemCB
, P2PageinCBFnc pP2PageinCBFnc
, P2PageoutCBFnc pP2PageoutCBFnc ) noexcept
{
// Activate registration
m_nfncP2PageCBKey = nfnP2PageItemCB;
m_pfncP2PageinCB = pP2PageinCBFnc;
m_pfncP2PageoutCB = pP2PageoutCBFnc;
return FALSE;
}
//
// Population callback registrations
//
// Parameters: PINT_PTR nfnP2PopulateItemCB
// User defined callback data. Usually pointer to
// originating class
//
// P2PopulateCBFnc *pP2PopulateCBFnc
// Pointer to call back function for population operations
//
// P2PageoutCBFnc *pP2PageoutCBFnc
// Pointer to call back function for page out operations
//
// Returns: BOOL
// Operation summary
BOOL
P2PmsgMgr::PageRegistration ( PINT_PTR nfnP2PopulateItemCB
, P2PopulateCBFnc pP2PopulateCBFnc ) noexcept
{
// Activate registration
m_nfncP2PopulateCBKey = nfnP2PopulateItemCB;
m_pfncP2PopulateCB = pP2PopulateCBFnc;
return FALSE;
}
//
// Manages OHLCvs data set paging in and out
// NOTES: Implementation via delegated callbacks. Null callbacks
// efectively negates operations
//
// Parameters: P2Pos posItem
// OHLCvs data set index
//
// BOOL bFlush
// Flushes loaded page from memory
//
// Returns: BOOL
// Activity summary
BOOL
P2PmsgMgr::PageDatasetIn ( P2Pos posItem )
{
// Logically only if callback exists
if ( m_nfncP2PageCBKey )
return (*m_pfncP2PageinCB)( m_nfncP2PageCBKey, posItem );
return FALSE;
}
BOOL
P2PmsgMgr::PageDatasetOut ( P2Pos posItem, BOOL bFlush )
{
// Logically only if callback exists
if ( m_nfncP2PageCBKey )
return (*m_pfncP2PageoutCB)( m_nfncP2PageCBKey, posItem, bFlush );
return FALSE;
}
//
// Manages paging summaries
//
// Parameters: P3PmsgField& oItem
// Item for which paging is to be managed
//
// DWORD dwAdditions
//
// DWORD dwRemovals
//
// Returns: DWORD
// Current paging summary
DWORD
P2PmsgMgr::PageSumm ( P3PmsgItem& oItem, DWORD dwAdditions, DWORD dwRemovals )
{
// Logically only if callback exists
if ( m_nfncP2PageCBKey == nullptr ) {
ASSERT(0); return 0; } // Absence is very problematic
P3PmsgItem oPagesumm = oItem.ATTR.DeclareItem(L"$Pagesumm",(DWORD)0).r_Object();
DWORD dwPagesumm = oPagesumm.c_uint();
dwPagesumm |= dwAdditions;
dwPagesumm &= ~dwRemovals;
oPagesumm.c_uint(dwPagesumm);
ASSERT((dwPagesumm&P2Pmsg_PAGESUMM_NOMERGE)==0);
return dwPagesumm;
}
//
// Page registrations push and pop
// NOTE: Single level maximum, must be complimented
//
BOOL
P2PmsgMgr::PageRegistrationPush ( )
{
ASSERT(m_pfncP2PageinCBp==0&&m_pfncP2PageoutCBp==0&&m_nfncP2PageCBKeyp==0);
m_pfncP2PageinCBp = m_pfncP2PageinCB;
m_pfncP2PageoutCBp = m_pfncP2PageoutCB;
m_nfncP2PageCBKeyp = m_nfncP2PageCBKey;
return TRUE;
}
BOOL
P2PmsgMgr::PageRegistrationPop ( )
{
ASSERT(m_pfncP2PageinCBp&&m_pfncP2PageoutCBp&&m_nfncP2PageCBKeyp);
m_pfncP2PageinCB = m_pfncP2PageinCBp; m_pfncP2PageinCBp = nullptr;
m_pfncP2PageoutCB = m_pfncP2PageoutCBp; m_pfncP2PageoutCBp = nullptr;
m_nfncP2PageCBKey = m_nfncP2PageCBKeyp; m_nfncP2PageCBKeyp = 0;
// TRUE, not FALSE. The restore above always succeeds, and every documented
// contract over this call -- Push's own return, and
// msgcore_mgr_page_registration_pop's "returns 1 on success" -- says so.
// Reporting failure after doing the work went unnoticed because the only
// caller in the tree was SafeRegistrationPush's destructor, which cannot
// use a return value. Found 2026-08-15 by MsgFacade's IMsgStore::PopPaging,
// the first caller that reads it.
return TRUE;
}
// Operators
P2PmsgMgr&
P2PmsgMgr::operator = ( const P2PmsgMgr& rhs )
{
(P3PmsgItem&)*this = (P3PmsgItem&)rhs;
return *this;
}
///////////////////////////////////////////////////////////////////////
// Addressing
P3PmsgField
P2PmsgMgr::P2Pos2Field ( P2Pos pos )
{
ASSERT(m_hMgr==this->r_Object().m_hVBList);
return P3PmsgField ( objVBList, pos, P2PmsgHeap_Sizeof(objVBList,pos) );
}
P3PmsgAttr
P2PmsgMgr::P2Pos2Attr ( P2Pos pos )
{
P3PmsgAttr oAttr;
if ( IsField(pos) )
oAttr = P3PmsgItem(objVBList,pos,P2PmsgHeap_Sizeof(objVBList,pos)).r_Attr().r_Object();
//else if ( IsNode(pos) )
// oAttr = P3PmsgNode(objVBList,pos,P2PmsgHeap_Sizeof(objVBList,pos)).r_Attr().r_Object();
return oAttr;
}
P3PmsgObject
P2PmsgMgr::P2Pos2Object ( P2Pos nP2Pos, BOOL bPageIn )
{
P3PmsgObject oObject;
oObject.Connectx(objVBList,nP2Pos,0);
ASSERT(m_hMgr==this->r_Object().m_hVBList);
// Observe Data paging
if ( bPageIn ) {
ASSERT ( oObject.IsField() ); PageDatasetIn ( nP2Pos ); }
return oObject;
}
CString
P2PmsgMgr::P2Pos2Path ( P2Pos pos )
{
// ONE ARM PER BLOCK KIND, and the kind is read off the P3PmsgObject at
// pos rather than from IsField(pos). IsField(pos) answers
// VBLockItem_IsField, which is FALSE for a list and FALSE for a vector,
// so six of the eleven things a P2Pos can name fell through to the
// ASSERT(0) that used to stand here: a list, a vector, and all four
// collections. Every one of them HAS a path. §6 taught
// P3Pmsg_GetPath(const P3PmsgField*) about containers, §12 gave the
// attribute collection an overload and §15 gave the descendant
// collection one -- this was the one place that could still reach none
// of it, so a path P3Pmsg_GetPath would build the manager would not.
if ( pos == 0 )
return CString();
P3PmsgObject oObject = P2Pos2Object ( pos );
if ( oObject.IsVoid() )
return CString();
// THE COLLECTIONS ARE ASKED ABOUT FIRST, and not for tidiness. IsAttr
// and IsDesc read the block header, which every block has. IsField,
// IsList and IsVect go straight to VBLock_pItem and read a VBLockItem's
// fields out of whatever block is actually there -- on a collection
// block that is the ut union misread P2PmsgAttr_GetVBLockParentnn
// already records. Asked in this order, the question is never put to a
// block that cannot answer it.
if ( oObject.IsAttr() || oObject.IsDesc() )
{
// NEITHER OVERLOAD TAKES A P3PmsgObject. Both reach the owner through
// the collection's back-pointer to the field it hangs off -- GetField()
// -- and P3PmsgAttr(const P3PmsgObject&) sets only m_oObject, leaving
// that pointer null. A collection converted straight from an object
// therefore builds a lone '@' or '.' with no owner in front of it,
// which is a string, not a path.
//
// So the owner comes first: GetParent() on a collection block is
// exactly the item the collection hangs off, and r_Attr()/r_Desc()
// install the back-pointer the overloads want.
P3PmsgObject oOwner = oObject.GetParent();
if ( !oOwner.IsField() && !oOwner.IsList() && !oOwner.IsVect() )
return CString(); // Unparented collection; nothing to hang it off
P3PmsgField oField = oOwner;
return oObject.IsAttr() ? P3Pmsg_GetPath ( &oField.r_Attr() )
: P3Pmsg_GetPath ( &oField.r_Desc() );
}
// AN ITEM -- a field, a list or a vector. All three are VBLockItem
// blocks and all three are what the P3PmsgField overload builds a path
// for, because P3PmsgList and P3PmsgVect both derive from P3PmsgField
// (§6). The CONVERTING CONSTRUCTOR takes all three; assignment would
// throw "Invalid overloaded context" for the two that are not fields,
// the same trap RootPath2Object carried until §13.
VBLock *pVBLock = (VBLock *)r_Object().Msg2Phys ( pos );
if ( pVBLock && VBLock_IsItem(pVBLock) )
{
P3PmsgField oField = oObject;
return P3Pmsg_GetPath ( &oField );
}
//else if ( IsNode(pos) )
//{
// P3PmsgNode oNode = P2Pos2Node(pos).r_Object();
// return P3Pmsg_GetPath ( &oNode );
//}
// ANYTHING ELSE -- a name block, a data block, a stack block. None of
// them is an object a path names, and none of them is a caller error
// worth an ASSERT: §9's rule is that what a caller spells is the
// caller's business. The empty string says "no path" the way a void
// P3PmsgObject says "no object", and msgcore_mgr_p2pos2path already
// keeps the two apart -- nullptr when the call threw, the string
// otherwise.
return CString();
}
P3PmsgObject
P2PmsgMgr::Path2Object ( LPCWSTR lpszObjectPath )
{
return P3Pmsg_SelectObject ( &this->r_Object(), lpszObjectPath );
}
// Get P3PmsgObject for full P3PmsgObject path
//
// Parameters: LPCWSTR lpszObjectPath
// Full path for P3PmsgObject to be retrieved.
//
// Returns: P3PmsgObject
// Retrieved object, IsEmpty flags failed search
P3PmsgObject
P2PmsgMgr::RootPath2Object ( LPCWSTR lpszObjectPath )
{
// Introduce locals
CString strRoot;
CList<CString> oCListItems;
// A P3PmsgObject, not a P3PmsgItem. Every step of this walk is
// P3Pmsg_SelectObject, which is a free function over P3PmsgObject and has
// an arm for each kind there is -- an item, a list, a vector, an attribute
// collection, a descendant collection. Nothing about the walk needed a
// field; only the variable did, and holding one meant the assignment that
// carries the walk forward was P3PmsgField::operator=(const
// P3PmsgObject&), which THROWS "Invalid overloaded context" for anything
// that is not a field.
//
// So a list or a vector anywhere but the last position ended the path
// with a raised event: ".Root.Numbers.Leaf" and ".Root.Numbers@Unit" both
// threw, though the object-path spellings of the same two questions have
// answered since §6 taught the selector about containers. An ordinary MISS
// under a list -- ".Root.Numbers.Nobody" -- threw the same event rather
// than "Path to object does not exist", because the walk died on the list
// one step before it ever asked about the name.
P3PmsgObject oParent = r_Object(); // Root becomes parent
// Problematic
try
{
// The verdict is the point of the call. Discarded, a path the splitter
// REFUSED was walked anyway, over whatever components it had collected
// before it gave up -- and since the walk answers the last component it
// managed, a malformed path came back as the object one step up from
// where the refusal happened. A silently wrong object, with nothing to
// distinguish it from a right one.
//
// A missing descendant already throws here ("Path to object does not
// exist"); a path that is not a path is at least as much the caller's
// error, and void is reserved for a search that ran and found nothing.
if ( !P3Pmsg_SplitRootPath ( lpszObjectPath, strRoot, oCListItems ) )
EVERR->MODULE
// L"%ls", never the path as the format itself -- refer the note
// on the throw below.
->Message(L"%ls", lpszObjectPath)
->Message("Malformed object path")
->Throw();
// Process the full Object path
POSITION posItems = oCListItems.GetHeadPosition();
while ( posItems )
{
CString strItem = oCListItems.GetNext(posItems);
LPCWSTR lpszItemName = strItem;
// Only the DESCENDANT delimiters come off, and they have to: a path
// handed to P3Pmsg_SelectObject with a leading '.' means "this
// component names the object you are standing on", and it is matched
// against the PARENT's own name (P2Pmsg.cpp, P3Pmsg_SelectObject), so
// ".Child" asked of the parent matches nothing. Stripped, it is a
// plain name and the field arm looks it up among the descendants,
// which is what a step of this walk means.
//
// '@' and '^' must SURVIVE, because for those two the delimiter IS
// the instruction and the name after it is read somewhere else:
// "@Tag" is the attribute Tag, "^" is the item as it stood before the
// last push, "^Kid" is that item's child. Stripped, all three became
// plain names and were looked up among the descendants -- so an
// attribute or a pushed value was answered with whatever child
// happened to share its name, or, far more often, with nothing.
// Every component of either kind was silently the wrong question.
//
// Spelled out rather than asking P3Pmsg_IsPathDelimiter, which
// answers TRUE for the terminator as well: an empty component
// stepped the pointer PAST its own end.
//
// ONLY WHERE A NAME FOLLOWS IT. A lone '.' names the descendant
// collection (§15), and there the delimiter IS the instruction --
// exactly as it is for '@' and '^', which is why those two were never
// stripped. Stripped anyway, a bare '.' became the empty string, and
// P3Pmsg_SelectObject looked for a descendant with no name.
//
// A NAME, and not merely SOMETHING. The test used to be "not the end of
// the component", which is the same thing only where the component is
// '.' and nothing else. The splitter seeds a component with the
// delimiter that introduces it and absorbs a following '^' (it does the
// same for "@^", §10), so ".Store.BHP.^" arrives here as ".^" -- a bare
// '.' with the stack delimiter after it. Stripped to "^", it selected
// the ITEM's snapshot, where "@^" one line of reasoning away selects the
// attribute COLLECTION's. §9's rule is that '^' commutes with '@' and
// with '.'; "^." already answered the snapshot's descendant collection
// and ".^" answered something else entirely (§17).
if ( !P3Pmsg_IsPathDelimiter ( lpszItemName + 1 ) &&
( lpszItemName[0] == T_DescDelim ||
lpszItemName[0] == T_BackSlash ||
lpszItemName[0] == T_ForeSlash ) )
lpszItemName++;
// Select the current item
// NOTES: Last item in list is the requested item
// : ONE selection per component. P3PmsgItem::Exists is itself
// "!P3Pmsg_SelectObject(...).IsVoid()" (P2Pmsg.cpp), so asking
// it and then selecting ran the whole lookup twice for every
// component of every path. The answer is what the test was
// after; only the populate callback below needs a second look,
// and only when the first one missed.
P3PmsgObject oSelected = P3Pmsg_SelectObject ( &oParent, lpszItemName );
// NOTES: If the requested Item is non-descendant type cannot proceed
// : P2PmsgTreeCtrl's only handle descendant items
if ( oSelected.IsVoid() )
{
// Only the DESCENDANT components throw for a miss, which is
// deliberate and unchanged -- those get the populate callback and
// then "Path to object does not exist". An '@' or a '^' that finds
// nothing is an ordinary answer: an item that was never pushed has
// no snapshot, so the empty object is the answer -- "IsEmpty flags
// failed search", as the contract above says.
//
// And a component that carries NO NAME never throws, whichever
// delimiter introduced it. The paging callback exists for a named
// child that may not be in memory yet; a bare delimiter asks for
// the COLLECTION it introduces (§15), and an item that has never
// had one has no block for it. That is the same fact ".Root.Item@"
// reports as void (§12), and reporting it two different ways
// depending on which collection was asked for would be nothing but