Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2675 lines
72 KiB

  1. //+-------------------------------------------------------------------
  2. //
  3. // Microsoft Windows
  4. // Copyright (C) Microsoft Corporation, 1992 - 1992.
  5. //
  6. // File: mstream.cxx
  7. //
  8. // Contents: Mstream operations
  9. //
  10. // Classes: None. (defined in mstream.hxx)
  11. //
  12. // History: 18-Jul-91 Philipla Created.
  13. //
  14. //--------------------------------------------------------------------
  15. #include "msfhead.cxx"
  16. #pragma hdrstop
  17. #include <dirfunc.hxx>
  18. #include <sstream.hxx>
  19. #include <difat.hxx>
  20. #include <time.h>
  21. #include <mread.hxx>
  22. #include <docfilep.hxx>
  23. #include <df32.hxx>
  24. #include <smalloc.hxx>
  25. #include <filelkb.hxx>
  26. #if DBG == 1
  27. DECLARE_INFOLEVEL(msf)
  28. #endif
  29. #define MINPAGES 6
  30. #define MAXPAGES 128
  31. #define MINPAGESSCRATCH 2
  32. #define MAXPAGESSCRATCH 16
  33. //#define SECURETEST
  34. const WCHAR wcsContents[] = L"CONTENTS"; //Name of contents stream for
  35. // conversion
  36. const WCHAR wcsRootEntry[] = L"Root Entry"; //Name of root directory
  37. // entry
  38. SCODE ILBFlush(ILockBytes *pilb, BOOL fFlushCache);
  39. //+---------------------------------------------------------------------------
  40. //
  41. // Function: GetBuffer, public
  42. //
  43. // Synopsis: Gets a chunk of memory to use as a buffer
  44. //
  45. // Arguments: [cbMin] - Minimum size for buffer
  46. // [cbMax] - Maximum size for buffer
  47. // [ppb] - Buffer pointer return
  48. // [pcbActual] - Actual buffer size return
  49. //
  50. // Returns: Appropriate status code
  51. //
  52. // Modifies: [ppb]
  53. // [pcbActual]
  54. //
  55. // Algorithm: Attempt to dynamically allocate [cbMax] bytes
  56. // If that fails, halve allocation size and retry
  57. // If allocation size falls below [cbMin], fail
  58. //
  59. // History: 04-Mar-93 DrewB Created
  60. //
  61. // Notes: Buffer should be released with FreeBuffer
  62. //
  63. //----------------------------------------------------------------------------
  64. SCODE GetBuffer(ULONG cbMin, ULONG cbMax, BYTE **ppb, ULONG *pcbActual)
  65. {
  66. ULONG cbSize;
  67. BYTE *pb;
  68. msfDebugOut((DEB_ITRACE, "In GetBuffer(%u, %u, %p, %p)\n",
  69. cbMin, cbMax, ppb, pcbActual));
  70. msfAssert(cbMin > 0);
  71. msfAssert(cbMax >= cbMin);
  72. msfAssert(ppb != NULL);
  73. msfAssert(pcbActual != NULL);
  74. cbSize = cbMax;
  75. for (;;)
  76. {
  77. pb = (BYTE *) DfMemAlloc(cbSize);
  78. if (pb == NULL)
  79. {
  80. cbSize >>= 1;
  81. if (cbSize < cbMin)
  82. break;
  83. }
  84. else
  85. {
  86. *pcbActual = cbSize;
  87. break;
  88. }
  89. }
  90. *ppb = pb;
  91. msfDebugOut((DEB_ITRACE, "Out GetBuffer => %p, %u\n", *ppb, *pcbActual));
  92. return pb == NULL ? STG_E_INSUFFICIENTMEMORY : S_OK;
  93. }
  94. // Define the safe buffer size
  95. //#define SCRATCHBUFFERSIZE SCRATCHSECTORSIZE
  96. BYTE s_bufSafe[SCRATCHBUFFERSIZE];
  97. LONG s_bufSafeRef = 0;
  98. // Critical Section will be initiqalized in the shared memory allocator
  99. // constructor and deleted in the SmAllocator destructor
  100. CRITICAL_SECTION g_csScratchBuffer;
  101. //+---------------------------------------------------------------------------
  102. //
  103. // Function: GetSafeBuffer, public
  104. //
  105. // Synopsis: Gets a buffer by first trying GetBuffer and if that fails,
  106. // returning a pointer to statically allocated storage.
  107. // Guaranteed to return a pointer to some storage.
  108. //
  109. // Arguments: [cbMin] - Minimum buffer size
  110. // [cbMax] - Maximum buffer size
  111. // [ppb] - Buffer pointer return
  112. // [pcbActual] - Actual buffer size return
  113. //
  114. // Modifies: [ppb]
  115. // [pcbActual]
  116. //
  117. // History: 04-Mar-93 DrewB Created
  118. //
  119. //----------------------------------------------------------------------------
  120. void GetSafeBuffer(ULONG cbMin, ULONG cbMax, BYTE **ppb, ULONG *pcbActual)
  121. {
  122. msfAssert(cbMin > 0);
  123. msfAssert(cbMin <= SCRATCHBUFFERSIZE &&
  124. aMsg("Minimum too large for GetSafeBuffer"));
  125. msfAssert(cbMax >= cbMin);
  126. msfAssert(ppb != NULL);
  127. // We want to minimize contention for the
  128. // static buffer so we always try dynamic allocation, regardless
  129. // of the size
  130. if (
  131. FAILED(GetBuffer(cbMin, cbMax, ppb, pcbActual)))
  132. {
  133. EnterCriticalSection(&g_csScratchBuffer);
  134. msfAssert(s_bufSafeRef == 0 &&
  135. aMsg("Tried to use scratch buffer twice"));
  136. s_bufSafeRef = 1;
  137. *ppb = s_bufSafe;
  138. *pcbActual = min(cbMax, SCRATCHBUFFERSIZE);
  139. }
  140. msfAssert(*ppb != NULL);
  141. }
  142. //+---------------------------------------------------------------------------
  143. //
  144. // Function: FreeBuffer, public
  145. //
  146. // Synopsis: Releases a buffer allocated by GetBuffer or GetSafeBuffer
  147. //
  148. // Arguments: [pb] - Buffer
  149. //
  150. // History: 04-Mar-93 DrewB Created
  151. //
  152. //----------------------------------------------------------------------------
  153. void FreeBuffer(BYTE *pb)
  154. {
  155. if (pb == s_bufSafe)
  156. {
  157. msfAssert((s_bufSafeRef == 1) && aMsg("Bad safe buffer ref count"));
  158. s_bufSafeRef = 0;
  159. LeaveCriticalSection(&g_csScratchBuffer);
  160. }
  161. else
  162. DfMemFree(pb);
  163. }
  164. //+-------------------------------------------------------------------------
  165. //
  166. // Method: CMStream::CMStream, public
  167. //
  168. // Synopsis: CMStream constructor
  169. //
  170. // Arguments: [pplstParent] -- Pointer to ILockBytes pointer of parent
  171. // [plGen] -- Pointer to LUID Generator to use.
  172. // Note: May be NULL, in which case a new
  173. // [uSectorShift] -- Sector shift for this MStream
  174. //
  175. // History: 18-Jul-91 PhilipLa Created.
  176. // 05-Sep-95 MikeHill Initialize '_fMaintainFLBModifyTimestamp'.
  177. // 26-Apr-99 RogerCh Removed _fMaintainFLBModifyTimestamp
  178. //
  179. //--------------------------------------------------------------------------
  180. CMStream::CMStream(
  181. IMalloc *pMalloc,
  182. ILockBytes **pplstParent,
  183. BOOL fIsScratch,
  184. #if defined(USE_NOSCRATCH) || defined(USE_NOSNAPSHOT)
  185. DFLAGS df,
  186. #endif
  187. USHORT uSectorShift)
  188. :_uSectorShift(uSectorShift),
  189. _uSectorSize(1 << uSectorShift),
  190. _uSectorMask(_uSectorSize - 1),
  191. _pplstParent(P_TO_BP(CBasedILockBytesPtrPtr, pplstParent)),
  192. _fIsScratch(fIsScratch),
  193. _fIsNoScratch(P_NOSCRATCH(df)),
  194. _pmsScratch(NULL),
  195. _fIsNoSnapshot(P_NOSNAPSHOT(df)),
  196. _hdr(uSectorShift),
  197. _fat(SIDFAT),
  198. _fatMini(SIDMINIFAT),
  199. _pMalloc(pMalloc)
  200. {
  201. _pmsShadow = NULL;
  202. _pCopySectBuf = NULL;
  203. #if DBG == 1
  204. _uBufferRef = 0;
  205. #endif
  206. _fIsShadow = FALSE;
  207. _ulParentSize = 0;
  208. _pdsministream = NULL;
  209. _pmpt = NULL;
  210. _fBlockWrite = _fTruncate = _fBlockHeader = _fNewConvert = FALSE;
  211. }
  212. //+-------------------------------------------------------------------------
  213. //
  214. // Method: CMStream::CMStream, public
  215. //
  216. // Synopsis: CMStream copy constructor
  217. //
  218. // Arguments: [ms] -- MStream to copy
  219. //
  220. // History: 04-Nov-92 PhilipLa Created.
  221. //
  222. //--------------------------------------------------------------------------
  223. CMStream::CMStream(const CMStream *pms)
  224. :_uSectorShift(pms->_uSectorShift),
  225. _uSectorSize(pms->_uSectorSize),
  226. _uSectorMask(pms->_uSectorMask),
  227. _pplstParent(pms->_pplstParent),
  228. _fIsScratch(pms->_fIsScratch),
  229. _hdr(*(CMSFHeader *)&pms->_hdr),
  230. _dir(*(CDirectory *)pms->GetDir()),
  231. _fat(pms->GetFat()),
  232. _fatMini(pms->GetMiniFat()),
  233. _fatDif(pms->GetDIFat()),
  234. _pdsministream(pms->_pdsministream),
  235. _pmpt(pms->_pmpt),
  236. _fBlockWrite(pms->_fBlockWrite),
  237. _fTruncate(pms->_fTruncate),
  238. _fBlockHeader(pms->_fBlockHeader),
  239. _fNewConvert(pms->_fNewConvert),
  240. _pmsShadow(NULL),
  241. _fIsShadow(TRUE),
  242. _pMalloc(pms->_pMalloc)
  243. {
  244. _pCopySectBuf = pms->_pCopySectBuf;
  245. #if DBG == 1
  246. _uBufferRef = pms->_uBufferRef;
  247. #endif
  248. _dir.SetParent(this);
  249. _fat.SetParent(this);
  250. _fatMini.SetParent(this);
  251. _fatDif.SetParent(this);
  252. _ulParentSize = 0;
  253. _pmpt->AddRef();
  254. }
  255. //+-------------------------------------------------------------------------
  256. //
  257. // Method: CMStream::InitCommon, private
  258. //
  259. // Synopsis: Common code for initialization routines.
  260. //
  261. // Arguments: None.
  262. //
  263. // Returns: S_OK if call completed OK.
  264. //
  265. // Algorithm: *Finish This*
  266. //
  267. // History: 20-May-92 PhilipLa Created.
  268. //
  269. //--------------------------------------------------------------------------
  270. SCODE CMStream::InitCommon(VOID)
  271. {
  272. msfDebugOut((DEB_ITRACE,"In CMStream InitCommon()\n"));
  273. SCODE sc = S_OK;
  274. #ifdef SECURE_BUFFER
  275. memset(s_bufSecure, SECURECHAR, MINISTREAMSIZE);
  276. #endif
  277. CMSFPageTable *pmpt;
  278. msfMem(pmpt = new (GetMalloc()) CMSFPageTable(
  279. this,
  280. (_fIsScratch) ? MINPAGESSCRATCH: MINPAGES,
  281. (_fIsScratch) ? MAXPAGESSCRATCH: MAXPAGES));
  282. _pmpt = P_TO_BP(CBasedMSFPageTablePtr, pmpt);
  283. msfChk(pmpt->Init());
  284. if (!_fIsScratch)
  285. {
  286. CMStream *pms;
  287. msfMem(pms = (CMStream *) new (GetMalloc()) CMStream(this));
  288. _pmsShadow = P_TO_BP(CBasedMStreamPtr, pms);
  289. }
  290. _stmcDir.Init(this, SIDDIR, NULL);
  291. _stmcMiniFat.Init(this, SIDMINIFAT, NULL);
  292. msfDebugOut((DEB_ITRACE,"Leaving CMStream InitCommon()\n"));
  293. Err:
  294. return sc;
  295. }
  296. //+---------------------------------------------------------------------------
  297. //
  298. // Member: CMStream::InitCopy, public
  299. //
  300. // Synopsis: Copy the structures from one multistream to yourself
  301. //
  302. // Arguments: [pms] -- Pointer to multistream to copy.
  303. //
  304. // History: 04-Dec-92 PhilipLa Created
  305. //
  306. // Notes:
  307. //
  308. //----------------------------------------------------------------------------
  309. void CMStream::InitCopy(CMStream *pms)
  310. {
  311. _stmcDir.Init(this, SIDDIR, NULL);
  312. _stmcMiniFat.Init(this, SIDMINIFAT, NULL);
  313. _fat.InitCopy(pms->GetFat());
  314. _fatMini.InitCopy(pms->GetMiniFat());
  315. _fatDif.InitCopy(pms->GetDIFat());
  316. _dir.InitCopy(pms->GetDir());
  317. _dir.SetParent(this);
  318. _fat.SetParent(this);
  319. _fatMini.SetParent(this);
  320. _fatDif.SetParent(this);
  321. memcpy(&_hdr, pms->GetHeader(), sizeof(CMSFHeader));
  322. }
  323. //+---------------------------------------------------------------------------
  324. //
  325. // Member: CMStream::Empty, public
  326. //
  327. // Synopsis: Empty all of the control structures of this CMStream
  328. //
  329. // Arguments: None.
  330. //
  331. // Returns: void.
  332. //
  333. // History: 04-Dec-92 PhilipLa Created
  334. //
  335. //----------------------------------------------------------------------------
  336. void CMStream::Empty(void)
  337. {
  338. _fat.Empty();
  339. _fatMini.Empty();
  340. _fatDif.Empty();
  341. _dir.Empty();
  342. }
  343. //+-------------------------------------------------------------------------
  344. //
  345. // Method: CMStream::~CMStream, public
  346. //
  347. // Synopsis: CMStream destructor
  348. //
  349. // History: 18-Jul-91 PhilipLa Created.
  350. // 20-Jul-95 SusiA Modified to eliminate mutex in allocator
  351. // Caller must already have the mutex.
  352. //
  353. //--------------------------------------------------------------------------
  354. CMStream::~CMStream()
  355. {
  356. msfDebugOut((DEB_ITRACE,"In CMStream destructor\n"));
  357. if (_pmsShadow != NULL)
  358. {
  359. _pmsShadow->~CMStream();
  360. _pmsShadow->deleteNoMutex (BP_TO_P(CMStream *, _pmsShadow));
  361. }
  362. #if DBG == 1
  363. msfAssert((_uBufferRef == 0) &&
  364. aMsg("CopySect buffer left with positive refcount."));
  365. #endif
  366. g_smAllocator.FreeNoMutex(BP_TO_P(BYTE *, _pCopySectBuf));
  367. if ((!_fIsShadow) && (_pdsministream != NULL))
  368. {
  369. _pdsministream->Release();
  370. }
  371. if (_pmpt != NULL)
  372. {
  373. _pmpt->Release();
  374. }
  375. msfDebugOut((DEB_ITRACE,"Leaving CMStream destructor\n"));
  376. }
  377. //+-------------------------------------------------------------------------
  378. //
  379. // Member: CMStream::Init, public
  380. //
  381. // Synposis: Set up an mstream instance from an existing stream
  382. //
  383. // Effects: Modifies Fat and Directory
  384. //
  385. // Arguments: void.
  386. //
  387. // Returns: S_OK if call completed OK.
  388. // Error of Fat or Dir setup otherwise.
  389. //
  390. // History: 18-Jul-91 PhilipLa Created.
  391. //
  392. // Notes:
  393. //
  394. //---------------------------------------------------------------------------
  395. SCODE CMStream::Init(VOID)
  396. {
  397. ULONG ulTemp;
  398. SCODE sc;
  399. ULARGE_INTEGER ulOffset;
  400. msfDebugOut((DEB_ITRACE,"In CMStream::Init()\n"));
  401. msfAssert(!_fIsScratch &&
  402. aMsg("Called Init() on scratch multistream."));
  403. ULONG ulSectorSize = HEADERSIZE;
  404. IFileLockBytes *pfl;
  405. if (SUCCEEDED((*_pplstParent)->QueryInterface(IID_IFileLockBytes,
  406. (void**) &pfl)))
  407. {
  408. ulSectorSize = pfl->GetSectorSize();
  409. pfl->Release();
  410. }
  411. ULISet32(ulOffset, 0);
  412. if (ulSectorSize == sizeof(CMSFHeaderData))
  413. {
  414. sc = (*_pplstParent)->ReadAt(ulOffset, (BYTE *)_hdr.GetData(),
  415. sizeof(CMSFHeaderData), &ulTemp);
  416. }
  417. else
  418. {
  419. void *pvBuf = TaskMemAlloc(ulSectorSize);
  420. msfMem(pvBuf);
  421. sc = (*_pplstParent)->ReadAt(ulOffset, pvBuf, ulSectorSize, &ulTemp);
  422. if (SUCCEEDED(sc) && ulTemp >= sizeof(CMSFHeaderData))
  423. memcpy (_hdr.GetData(), pvBuf, sizeof(CMSFHeaderData));
  424. TaskMemFree (pvBuf);
  425. }
  426. if (sc == E_PENDING)
  427. {
  428. sc = STG_E_PENDINGCONTROL;
  429. }
  430. msfChk(sc);
  431. //We need to mark the header as not dirty, since the constructor
  432. // defaults it to the dirty state. This needs to happen before
  433. // any possible failures, otherwise we can end up writing a
  434. // brand new header over an existing file.
  435. _hdr.ResetDirty();
  436. _uSectorShift = _hdr.GetSectorShift();
  437. _uSectorSize = 1 << _uSectorShift;
  438. _uSectorMask = _uSectorSize - 1;
  439. if (ulTemp != ulSectorSize)
  440. {
  441. msfErr(Err,STG_E_INVALIDHEADER);
  442. }
  443. msfChk(_hdr.Validate());
  444. msfChk(InitCommon());
  445. msfChk(_fatDif.Init(this, _hdr.GetDifLength()));
  446. msfChk(_fat.Init(this, _hdr.GetFatLength(), 0));
  447. FSINDEX fsiLen;
  448. if (_uSectorShift > SECTORSHIFT512)
  449. fsiLen = _hdr.GetDirLength ();
  450. else
  451. msfChk(_fat.GetLength(_hdr.GetDirStart(), &fsiLen));
  452. msfChk(_dir.Init(this, fsiLen));
  453. msfChk(_fatMini.Init(this, _hdr.GetMiniFatLength(), 0));
  454. BYTE *pbBuf;
  455. msfMem(pbBuf = (BYTE *) GetMalloc()->Alloc(GetSectorSize()));
  456. _pCopySectBuf = P_TO_BP(CBasedBytePtr, pbBuf);
  457. #ifdef LARGE_STREAMS
  458. ULONGLONG ulSize;
  459. #else
  460. ULONG ulSize;
  461. #endif
  462. msfChk(_dir.GetSize(SIDMINISTREAM, &ulSize));
  463. CDirectStream *pdsTemp;
  464. msfMem(pdsTemp = new(GetMalloc()) CDirectStream(MINISTREAM_LUID));
  465. _pdsministream = P_TO_BP(CBasedDirectStreamPtr, pdsTemp);
  466. _pdsministream->InitSystem(this, SIDMINISTREAM, ulSize);
  467. msfDebugOut((DEB_ITRACE,"Out CMStream::Init()\n"));
  468. Err:
  469. return sc;
  470. }
  471. //+-------------------------------------------------------------------------
  472. //
  473. // Member: CMStream::InitNew, public
  474. //
  475. // Synposis: Set up a brand new mstream instance
  476. //
  477. // Effects: Modifies FAT and Directory
  478. //
  479. // Arguments: [fDelay] -- If TRUE, then the parent LStream
  480. // will be truncated at the time of first
  481. // entrance to COW, and no writes to the
  482. // LStream will happen before then.
  483. //
  484. // Returns: S_OK if call completed OK.
  485. //
  486. // History: 18-Jul-91 PhilipLa Created.
  487. // 12-Jun-92 PhilipLa Added fDelay.
  488. //
  489. //---------------------------------------------------------------------------
  490. SCODE CMStream::InitNew(BOOL fDelay, ULARGE_INTEGER uliSize)
  491. {
  492. SCODE sc;
  493. msfDebugOut((DEB_ITRACE,"In CMStream::InitNew()\n"));
  494. #ifdef LARGE_DOCFILE
  495. ULONGLONG ulParentSize = 0;
  496. #else
  497. ULONG ulParentSize = 0;
  498. #endif
  499. msfChk(InitCommon());
  500. if (!_fIsScratch)
  501. {
  502. #ifdef LARGE_DOCFILE
  503. ulParentSize = uliSize.QuadPart;
  504. #else
  505. msfAssert (ULIGetHigh(uliSize) == 0);
  506. ulParentSize = ULIGetLow(uliSize);
  507. #endif
  508. if (!fDelay && ulParentSize > 0)
  509. {
  510. ULARGE_INTEGER ulTmp;
  511. ULISet32(ulTmp, 0);
  512. (*_pplstParent)->SetSize(ulTmp);
  513. }
  514. }
  515. _fBlockWrite = (ulParentSize == 0) ? FALSE : fDelay;
  516. msfChk(_fatDif.InitNew(this));
  517. msfChk(_fat.InitNew(this));
  518. if (!_fIsScratch || _fIsNoScratch)
  519. {
  520. msfChk(_fatMini.InitNew(this));
  521. }
  522. if (!_fIsScratch)
  523. {
  524. msfChk(_dir.InitNew(this));
  525. BYTE *pbBuf;
  526. msfMem(pbBuf = (BYTE *) GetMalloc()->Alloc(GetSectorSize()));
  527. _pCopySectBuf = P_TO_BP(CBasedBytePtr, pbBuf);
  528. #ifdef LARGE_STREAMS
  529. ULONGLONG ulSize;
  530. #else
  531. ULONG ulSize;
  532. #endif
  533. msfChk(_dir.GetSize(SIDMINISTREAM, &ulSize));
  534. CDirectStream *pdsTemp;
  535. msfMem(pdsTemp = new(GetMalloc()) CDirectStream(MINISTREAM_LUID));
  536. _pdsministream = P_TO_BP(CBasedDirectStreamPtr, pdsTemp);
  537. _pdsministream->InitSystem(this, SIDMINISTREAM, ulSize);
  538. }
  539. //If we have a zero length original file, this will create an
  540. // empty Docfile on the disk. If the original file was
  541. // not zero length, then the Flush operations will be skipped
  542. // by _fBlockWrite and the file will be unmodified.
  543. if (!_fBlockWrite)
  544. {
  545. msfChk(Flush(0));
  546. }
  547. _fTruncate = (ulParentSize != 0);
  548. _fBlockWrite = fDelay;
  549. msfDebugOut((DEB_ITRACE,"Out CMStream::InitNew()\n"));
  550. return S_OK;
  551. Err:
  552. Empty();
  553. return sc;
  554. }
  555. //+---------------------------------------------------------------------------
  556. //
  557. // Member: CMStream::ConvertILB, private
  558. //
  559. // Synopsis: Copy the first sector of the underlying ILockBytes
  560. // out to the end.
  561. //
  562. // Arguments: [sectMax] -- Total number of sectors in the ILockBytes
  563. //
  564. // Returns: Appropriate status code
  565. //
  566. // History: 03-Feb-93 PhilipLa Created
  567. //
  568. //----------------------------------------------------------------------------
  569. SCODE CMStream::ConvertILB(SECT sectMax)
  570. {
  571. SCODE sc;
  572. BYTE *pb;
  573. ULONG cbNull;
  574. GetSafeBuffer(GetSectorSize(), GetSectorSize(), &pb, &cbNull);
  575. ULONG ulTemp;
  576. ULARGE_INTEGER ulTmp;
  577. ULISet32(ulTmp, 0);
  578. msfHChk((*_pplstParent)->ReadAt(ulTmp, pb, GetSectorSize(), &ulTemp));
  579. ULARGE_INTEGER ulNewPos;
  580. #ifdef LARGE_DOCFILE
  581. ulNewPos.QuadPart = (ULONGLONG)(sectMax) << GetSectorShift();
  582. #else
  583. ULISet32(ulNewPos, sectMax << GetSectorShift());
  584. #endif
  585. msfDebugOut((DEB_ITRACE,"Copying first sector out to %lu\n",
  586. ULIGetLow(ulNewPos)));
  587. msfHChk((*_pplstParent)->WriteAt(
  588. ulNewPos,
  589. pb,
  590. GetSectorSize(),
  591. &ulTemp));
  592. Err:
  593. FreeBuffer(pb);
  594. return sc;
  595. }
  596. //+-------------------------------------------------------------------------
  597. //
  598. // Method: CMStream::InitConvert, public
  599. //
  600. // Synopsis: Init function used in conversion of files to multi
  601. // streams.
  602. //
  603. // Arguments: [fDelayConvert] -- If true, the actual file is not
  604. // touched until a BeginCopyOnWrite()
  605. //
  606. // Returns: S_OK if everything completed OK.
  607. //
  608. // Algorithm: *Finish This*
  609. //
  610. // History: 28-May-92 Philipla Created.
  611. //
  612. // Notes: We are allowed to fail here in low memory
  613. //
  614. //--------------------------------------------------------------------------
  615. SCODE CMStream::InitConvert(BOOL fDelayConvert)
  616. {
  617. SCODE sc;
  618. SECT sectMax;
  619. CDfName const dfnContents(wcsContents);
  620. msfAssert(!_fIsScratch &&
  621. aMsg("Called InitConvert on scratch multistream"));
  622. _fBlockWrite = fDelayConvert;
  623. msfAssert(!_fBlockWrite &&
  624. aMsg("Delayed conversion not supported in this release."));
  625. msfChk(InitCommon());
  626. STATSTG stat;
  627. msfChk((*_pplstParent)->Stat(&stat, STATFLAG_NONAME));
  628. msfDebugOut((DEB_ITRACE,"Size is: %lu\n",ULIGetLow(stat.cbSize)));
  629. #ifdef LARGE_DOCFILE
  630. sectMax = (SECT) ((stat.cbSize.QuadPart + GetSectorSize() - 1) >>
  631. GetSectorShift());
  632. #else
  633. sectMax = (ULIGetLow(stat.cbSize) + GetSectorSize() - 1) >>
  634. GetSectorShift();
  635. #endif
  636. SECT sectMaxMini = 0;
  637. BOOL fIsMini;
  638. fIsMini = FALSE;
  639. //If the CONTENTS stream will be in the Minifat, compute
  640. // the number of Minifat sectors needed.
  641. #ifdef LARGE_DOCFILE
  642. if (stat.cbSize.QuadPart < MINISTREAMSIZE)
  643. #else
  644. if (ULIGetLow(stat.cbSize) < MINISTREAMSIZE)
  645. #endif
  646. {
  647. sectMaxMini = (ULIGetLow(stat.cbSize) + MINISECTORSIZE - 1) >>
  648. MINISECTORSHIFT;
  649. fIsMini = TRUE;
  650. }
  651. BYTE *pbBuf;
  652. msfMem(pbBuf = (BYTE *) GetMalloc()->Alloc(GetSectorSize()));
  653. _pCopySectBuf = P_TO_BP(CBasedBytePtr, pbBuf);
  654. msfChk(_fatDif.InitConvert(this, sectMax));
  655. msfChk(_fat.InitConvert(this, sectMax));
  656. msfChk(_dir.InitNew(this));
  657. msfChk(fIsMini ? _fatMini.InitConvert(this, sectMaxMini)
  658. : _fatMini.InitNew(this));
  659. SID sid;
  660. msfChk(CreateEntry(SIDROOT, &dfnContents, STGTY_STREAM, &sid));
  661. #ifdef LARGE_STREAMS
  662. msfChk(_dir.SetSize(sid, stat.cbSize.QuadPart));
  663. #else
  664. msfChk(_dir.SetSize(sid, ULIGetLow(stat.cbSize)));
  665. #endif
  666. if (!fIsMini)
  667. msfChk(_dir.SetStart(sid, sectMax - 1));
  668. else
  669. {
  670. msfChk(_dir.SetStart(sid, 0));
  671. msfChk(_dir.SetStart(SIDMINISTREAM, sectMax - 1));
  672. #ifdef LARGE_STREAMS
  673. msfChk(_dir.SetSize(SIDMINISTREAM, stat.cbSize.QuadPart));
  674. #else
  675. msfChk(_dir.SetSize(SIDMINISTREAM, ULIGetLow(stat.cbSize)));
  676. #endif
  677. }
  678. #ifdef LARGE_STREAMS
  679. ULONGLONG ulMiniSize;
  680. #else
  681. ULONG ulMiniSize;
  682. #endif
  683. msfChk(_dir.GetSize(SIDMINISTREAM, &ulMiniSize));
  684. CDirectStream *pdsTemp;
  685. msfMem(pdsTemp = new(GetMalloc()) CDirectStream(MINISTREAM_LUID));
  686. _pdsministream = P_TO_BP(CBasedDirectStreamPtr, pdsTemp);
  687. _pdsministream->InitSystem(this, SIDMINISTREAM, ulMiniSize);
  688. if (!_fBlockWrite)
  689. {
  690. msfChk(ConvertILB(sectMax));
  691. msfChk(Flush(0));
  692. }
  693. return S_OK;
  694. Err:
  695. Empty();
  696. return sc;
  697. }
  698. //+-------------------------------------------------------------------------
  699. //
  700. // Method: CMStream::FlushHeader, public
  701. //
  702. // Synopsis: Flush the header to the LStream.
  703. //
  704. // Arguments: [uForce] -- Flag to determine if header should be
  705. // flushed while in copy on write mode.
  706. //
  707. // Returns: S_OK if call completed OK.
  708. // S_OK if the MStream is in copy on write mode or
  709. // is Unconverted and the header was not flushed.
  710. //
  711. // Algorithm: Write the complete header out to the 0th position of
  712. // the LStream.
  713. //
  714. // History: 11-Dec-91 PhilipLa Created.
  715. // 18-Feb-92 PhilipLa Added copy on write support.
  716. //
  717. // Notes:
  718. //
  719. //--------------------------------------------------------------------------
  720. SCODE CMStream::FlushHeader(USHORT uForce)
  721. {
  722. ULONG ulTemp;
  723. SCODE sc;
  724. msfDebugOut((DEB_ITRACE,"In CMStream::FlushHeader()\n"));
  725. if (_fIsScratch || _fBlockWrite ||
  726. ((_fBlockHeader) && (!(uForce & HDR_FORCE))))
  727. {
  728. return S_OK;
  729. }
  730. //If the header isn't dirty, we don't flush it unless forced to.
  731. if (!(uForce & HDR_FORCE) && !(_hdr.IsDirty()))
  732. {
  733. return S_OK;
  734. }
  735. ULARGE_INTEGER ulOffset;
  736. ULISet32(ulOffset, 0);
  737. USHORT usSectorSize = GetSectorSize();
  738. if (usSectorSize == HEADERSIZE || _fIsScratch)
  739. {
  740. sc = (*_pplstParent)->WriteAt(ulOffset, (BYTE *)_hdr.GetData(),
  741. sizeof(CMSFHeaderData), &ulTemp);
  742. }
  743. else
  744. {
  745. msfAssert (_pCopySectBuf != NULL);
  746. memset (_pCopySectBuf, 0, usSectorSize);
  747. memcpy (_pCopySectBuf, _hdr.GetData(), sizeof(CMSFHeaderData));
  748. sc = (*_pplstParent)->WriteAt(ulOffset, _pCopySectBuf,
  749. usSectorSize, &ulTemp);
  750. }
  751. if (sc == E_PENDING)
  752. {
  753. sc = STG_E_PENDINGCONTROL;
  754. }
  755. msfDebugOut((DEB_ITRACE,"Out CMStream::FlushHeader()\n"));
  756. if (SUCCEEDED(sc))
  757. {
  758. _hdr.ResetDirty();
  759. }
  760. return sc;
  761. }
  762. //+-------------------------------------------------------------------------
  763. //
  764. // Method: CMStream::BeginCopyOnWrite, public
  765. //
  766. // Synopsis: Switch the multistream into copy on write mode
  767. //
  768. // Effects: Creates new in-core copies of the Fat, Directory, and
  769. // header.
  770. //
  771. // Arguments: None.
  772. //
  773. // Requires: The multistream cannot already be in copy on write
  774. // mode.
  775. //
  776. // Returns: S_OK if the call completed OK.
  777. // STG_E_ACCESSDENIED if multistream was already in COW mode
  778. //
  779. // Algorithm: Retrieve and store size of parent LStream.
  780. // If _fUnconverted & _fTruncate, call SetSize(0)
  781. // on the parent LStream.
  782. // If _fUnconverted, then flush all control structures.
  783. // Copy all control structures, and switch in the shadow
  784. // copies for current use.
  785. // Return S_OK.
  786. //
  787. // History: 18-Feb-92 PhilipLa Created.
  788. // 09-Jun-92 PhilipLa Added support for fUnconverted
  789. //
  790. // Notes:
  791. //
  792. //--------------------------------------------------------------------------
  793. SCODE CMStream::BeginCopyOnWrite(DWORD const dwFlags)
  794. {
  795. msfDebugOut((DEB_ITRACE,"In CMStream::BeginCopyOnWrite()\n"));
  796. SCODE sc;
  797. msfAssert(!_fBlockHeader &&
  798. aMsg("Tried to reenter Copy-on-Write mode."));
  799. msfAssert(!_fIsScratch &&
  800. aMsg("Tried to enter Copy-on-Write mode in scratch."));
  801. msfAssert(!_fIsNoScratch &&
  802. aMsg("Copy-on-Write started for NoScratch."));
  803. //_fBlockWrite is true if we have a delayed conversion or
  804. // truncation.
  805. if (_fBlockWrite)
  806. {
  807. //In the overwrite case, we don't want to release any
  808. // disk space, so we skip this step.
  809. if ((_fTruncate) && !(dwFlags & STGC_OVERWRITE) &&
  810. (_pmsScratch == NULL))
  811. {
  812. ULARGE_INTEGER ulTmp;
  813. ULISet32(ulTmp, 0);
  814. msfHChk((*_pplstParent)->SetSize(ulTmp));
  815. }
  816. if (!(dwFlags & STGC_OVERWRITE))
  817. {
  818. _fBlockHeader = TRUE;
  819. }
  820. _fBlockWrite = FALSE;
  821. msfChk(Flush(0));
  822. _fBlockHeader = FALSE;
  823. _fTruncate = FALSE;
  824. }
  825. STATSTG stat;
  826. msfHChk((*_pplstParent)->Stat(&stat, STATFLAG_NONAME));
  827. #ifdef LARGE_DOCFILE
  828. _ulParentSize = stat.cbSize.QuadPart;
  829. msfDebugOut((DEB_ITRACE,"Parent size at begin is %Lu\n",_ulParentSize));
  830. #else
  831. msfAssert(ULIGetHigh(stat.cbSize) == 0);
  832. _ulParentSize = ULIGetLow(stat.cbSize);
  833. msfDebugOut((DEB_ITRACE,"Parent size at begin is %lu\n",_ulParentSize));
  834. #endif
  835. if (_fIsNoSnapshot)
  836. {
  837. SECT sectNoSnapshot;
  838. #ifdef LARGE_DOCFILE
  839. sectNoSnapshot = (SECT) ((_ulParentSize - GetSectorSize() +
  840. #else
  841. sectNoSnapshot = (SECT) ((_ulParentSize - HEADERSIZE +
  842. #endif
  843. GetSectorSize() - 1) / GetSectorSize());
  844. _fat.SetNoSnapshot(sectNoSnapshot);
  845. }
  846. //We flush out all of our current dirty pages - after this point,
  847. // we know that any dirty pages should be remapped before being
  848. // written out, assuming we aren't in overwrite mode.
  849. msfChk(Flush(0));
  850. if (!(dwFlags & STGC_OVERWRITE))
  851. {
  852. SECT sectTemp;
  853. if (_pmsScratch == NULL)
  854. {
  855. msfChk(_fat.FindMaxSect(&sectTemp));
  856. }
  857. else
  858. {
  859. msfChk(_fat.FindLast(&sectTemp));
  860. }
  861. _pmsShadow->InitCopy(this);
  862. _pmsShadow->_pdsministream = NULL;
  863. _fat.SetCopyOnWrite(_pmsShadow->GetFat(), sectTemp);
  864. _fBlockHeader = TRUE;
  865. msfChk(_fatDif.RemapSelf());
  866. if (_fIsNoSnapshot)
  867. msfChk(_fat.ResizeNoSnapshot());
  868. msfChk(_fatDif.Fixup(BP_TO_P(CMStream *, _pmsShadow)));
  869. if (_fIsNoSnapshot)
  870. _fat.ResetNoSnapshotFree();
  871. #if DBG == 1
  872. _fat.CheckFreeCount();
  873. #endif
  874. }
  875. else
  876. {
  877. _fat.SetCopyOnWrite(NULL, 0);
  878. }
  879. msfDebugOut((DEB_ITRACE,"Out CMStream::BeginCopyOnWrite()\n"));
  880. return S_OK;
  881. Err:
  882. _fBlockHeader = FALSE;
  883. _pmsShadow->Empty();
  884. _fat.ResetCopyOnWrite();
  885. if (_fIsNoSnapshot)
  886. _fat.ResetNoSnapshotFree();
  887. return sc;
  888. }
  889. //+-------------------------------------------------------------------------
  890. //
  891. // Method: CMStream::EndCopyOnWrite, public
  892. //
  893. // Synopsis: End copy on write mode, either by committing the current
  894. // changes (in which case a merge is performed), or by
  895. // aborting the changes, in which case the persistent form
  896. // of the multistream should be identical to its form
  897. // before copy on write mode was entered.
  898. //
  899. // Effects: *Finish This*
  900. //
  901. // Arguments: [df] -- Flags to determine commit or abort status.
  902. //
  903. // Requires: The multistream must be in copy on write mode.
  904. //
  905. // Returns: S_OK if call completed OK.
  906. // STG_E_ACCESSDENIED if MStream was not in COW mode.
  907. //
  908. // Algorithm: If aborting, delete all shadow structures,
  909. // call SetSize() on parent LStream to restore
  910. // original size, and switch active controls back
  911. // to originals.
  912. // If committing, delete all old structures, switch
  913. // shadows into original position.
  914. //
  915. // History: 18-Feb-92 PhilipLa Created.
  916. // 09-Jun-92 Philipla Added support for fUnconverted
  917. //
  918. // Notes:
  919. //
  920. //--------------------------------------------------------------------------
  921. SCODE CMStream::EndCopyOnWrite(
  922. DWORD const dwCommitFlags,
  923. DFLAGS const df)
  924. {
  925. SCODE sc = S_OK;
  926. msfDebugOut((DEB_ITRACE,"In CMStream::EndCopyOnWrite(%lu)\n",df));
  927. BOOL fFlush = FLUSH_CACHE(dwCommitFlags);
  928. if (dwCommitFlags & STGC_OVERWRITE)
  929. {
  930. if (_pmsScratch != NULL)
  931. {
  932. msfChk(_fatDif.Fixup(NULL));
  933. _fat.ResetCopyOnWrite();
  934. }
  935. msfChk(Flush(fFlush));
  936. }
  937. else
  938. {
  939. msfAssert(_fBlockHeader &&
  940. aMsg("Tried to exit copy-on-write mode without entering."));
  941. ULARGE_INTEGER ulParentSize = {0,0};
  942. if (P_ABORT(df))
  943. {
  944. msfDebugOut((DEB_ITRACE,"Aborting Copy On Write mode\n"));
  945. Empty();
  946. InitCopy(BP_TO_P(CMStream *, _pmsShadow));
  947. #ifdef LARGE_DOCFILE
  948. ulParentSize.QuadPart = _ulParentSize;
  949. #else
  950. ULISetLow(ulParentSize, _ulParentSize);
  951. #endif
  952. }
  953. else
  954. {
  955. SECT sectMax;
  956. msfChk(_fatDif.Fixup(BP_TO_P(CMStream *, _pmsShadow)));
  957. msfChk(Flush(fFlush));
  958. _fat.ResetCopyOnWrite();
  959. msfChk(_fat.GetMaxSect(&sectMax));
  960. #ifdef LARGE_DOCFILE
  961. ulParentSize.QuadPart = ConvertSectOffset(sectMax, 0,
  962. GetSectorShift());
  963. #else
  964. ULISetLow(ulParentSize, ConvertSectOffset(sectMax, 0,
  965. GetSectorShift()));
  966. #endif
  967. msfChk(FlushHeader(HDR_FORCE));
  968. msfVerify(SUCCEEDED(ILBFlush(*_pplstParent, fFlush)) &&
  969. aMsg("CMStream::EndCopyOnWrite ILBFLush failed. "
  970. "Non-fatal, hit Ok."));
  971. }
  972. //
  973. // Shrink the file if the size got smaller.
  974. // Don't shrink if we are in NoSnapshot mode, unless the NoSnapshot
  975. // limit has been set to 0 by Consolidate.
  976. //We don't ever expect this SetSize to fail, since it
  977. // should never attempt to enlarge the file.
  978. if (!_fIsNoSnapshot || 0 == _fat.GetNoSnapshot())
  979. {
  980. #ifdef LARGE_DOCFILE
  981. if (ulParentSize.QuadPart < _ulParentSize)
  982. #else
  983. if (ULIGetLow(ulParentSize) < _ulParentSize)
  984. #endif
  985. {
  986. olHVerSucc((*_pplstParent)->SetSize(ulParentSize));
  987. }
  988. }
  989. _pmsShadow->Empty();
  990. _fBlockHeader = FALSE;
  991. _fNewConvert = FALSE;
  992. }
  993. if (_pmsScratch != NULL)
  994. {
  995. //Let the no-scratch fat pick up whatever changed we've made.
  996. _pmsScratch->InitScratch(this, FALSE);
  997. }
  998. if (!_fIsNoSnapshot)
  999. {
  1000. //In no-snapshot mode, we can't let the file shrink, since
  1001. //we might blow away someone else's state.
  1002. _ulParentSize = 0;
  1003. }
  1004. {
  1005. SCODE sc2 = SetSize();
  1006. msfVerify((SUCCEEDED(sc2) || (sc2 == E_PENDING)) &&
  1007. aMsg("SetSize after copy-on-write failed."));
  1008. }
  1009. if (_fIsNoSnapshot)
  1010. {
  1011. _ulParentSize = 0;
  1012. _fat.SetNoSnapshot(0);
  1013. }
  1014. #if DBG == 1
  1015. STATSTG stat;
  1016. msfHChk((*_pplstParent)->Stat(&stat, STATFLAG_NONAME));
  1017. #ifndef LARGE_DOCFILE
  1018. msfAssert(ULIGetHigh(stat.cbSize) == 0);
  1019. #endif
  1020. msfDebugOut((DEB_ITRACE, "Parent size at end is %lu\n",
  1021. ULIGetLow(stat.cbSize)));
  1022. #endif
  1023. msfDebugOut((DEB_ITRACE,"Out CMStream::EndCopyOnWrite()\n"));
  1024. Err:
  1025. return sc;
  1026. }
  1027. //+---------------------------------------------------------------------------
  1028. //
  1029. // Member: CMStream::Consolidate, public
  1030. //
  1031. // Synopsis: Fill in the holes of a file by moving blocks toward the front.
  1032. //
  1033. // Arguments:
  1034. //
  1035. // Returns: Appropriate status code
  1036. //
  1037. // Algorithm: 1) Find a limit that all blocks should be moved below.
  1038. // The limit includes all the data, a new FAT, DIFAT and
  1039. // DirStream, and doesn't disturb the old fat/dif/dir blocks.
  1040. // 2) Move new fat/dif/dir sectors down. We do this with the
  1041. // cache's copy-on-write DIRTY behaviour.
  1042. // 3) Stream by stream move all the high sectors down.
  1043. //
  1044. // History: 11-Feb-1997 BChapman Created
  1045. //
  1046. // Notes: 1) This is called in the contex of Begin/End Copy-on-Write.
  1047. // 2) We assume throughout that the underlying free sector allocator
  1048. // returns the first free sector of the file.
  1049. // 3) The old fat/dif/dir may leave small holes in the finished file.
  1050. //----------------------------------------------------------------------------
  1051. SCODE CMStream::Consolidate(void)
  1052. {
  1053. //
  1054. // We don't support NOSCRATCH and this should have already
  1055. // been checked in the caller.
  1056. //
  1057. msfAssert(_pmsScratch == NULL);
  1058. SCODE sc=S_OK;
  1059. ULONG cAllocatedSects;
  1060. ULONG cDirEntries;
  1061. CDirEntry *pde=NULL;
  1062. SID sid;
  1063. ULONG sectLast = 0; // Last allocated Sector #.
  1064. ULONG csectFree = 0; // #sects that are free.
  1065. SECT sectLimit; // #sects we will try to shrink the file into.
  1066. ULONG csectLowDIF; // #DIF sects below sectLimit.
  1067. ULONG csectLowFAT; // #FAT sects below sectLimit.
  1068. ULONG csectLowControl; // #motion sensitive sects below sectLimit.
  1069. SECT *psectControl; // list of Dir and Mini Fat sectors
  1070. ULONG csectControl; // # of sects in psectControl
  1071. ULONG i;
  1072. SECT sectType;
  1073. //
  1074. // It is quite impossible to consolidate a file when the Snapshot
  1075. // limits are in effect. This routine is only called when we have
  1076. // confirmed there are no other "seperate" writers. So it should be
  1077. // safe to turn off the snapshot limits.
  1078. //
  1079. if(_fIsNoSnapshot)
  1080. {
  1081. _fat.SetNoSnapshot(0);
  1082. _fat.ResetNoSnapshotFree();
  1083. }
  1084. //
  1085. // Compute the Number of allocated sectors in the file.
  1086. // Ignore the header.
  1087. //
  1088. msfChk(_fat.FindLast(&sectLast));
  1089. sectLast--;
  1090. msfChk(_fat.CountSectType(&csectFree, 0, sectLast, FREESECT));
  1091. //
  1092. // Compute the expected size of the consolidated file. We will
  1093. // use this limit to determine when a sector is too high and needs
  1094. // to be copied down.
  1095. //
  1096. sectLimit = sectLast - csectFree;
  1097. //
  1098. // We will move the stream data sectors by copying them to free
  1099. // sectors and releasing the old sector.
  1100. // But, there are a class of sectors (control structures: FAT, DIF,
  1101. // miniFat, Directory Stream) that the old sector cannot be freed until
  1102. // end-copy-on-write.
  1103. // It is possible that the old (original) versions of these sectors
  1104. // could exist below sectLimit and with therefore be taking up "dead"
  1105. // space in the resulting file. So we need to adjust sectLimit.
  1106. //
  1107. // We are in Copy-On-Write mode so any FAT, DIF, Directory Stream, or
  1108. // MiniFat sector that is modified (by moving other sectors) will be
  1109. // copied to a free sector by the cache manager.
  1110. // It is difficult to know ahead of time which Low FAT sectors won't
  1111. // be touched, and therefore can avoid being copied, so we just assume
  1112. // we need to make a complete copy of the FAT, DIF, Directory Stream,
  1113. // and MiniFAT.
  1114. //
  1115. // Count the number of FAT (and DIFat) blocks up to sectLimit.
  1116. //
  1117. msfChk(_fat.CountSectType(&csectLowFAT, 0, sectLimit, FATSECT));
  1118. msfChk(_fat.CountSectType(&csectLowDIF, 0, sectLimit, DIFSECT));
  1119. //
  1120. // Build a list of sectors in the Directory Stream and MiniFat
  1121. //
  1122. msfChk(BuildConsolidationControlSectList(&psectControl, &csectControl));
  1123. //
  1124. // Sum all the copy-on-write control sectors below sectLimit.
  1125. //
  1126. csectLowControl = csectLowFAT + csectLowDIF;
  1127. for(i=0; i<csectControl; i++)
  1128. {
  1129. if(psectControl[i] < sectLimit)
  1130. ++csectLowControl;
  1131. }
  1132. //
  1133. // Now we adjust sectLimit. (see large comment above)
  1134. // We want to increase it by csectLowControl # of sectors.
  1135. // But, advancing over new control sectors doesn't help make space
  1136. // so skip over those.
  1137. // Note: In a well packed file we can hit EOF while doing this.
  1138. //
  1139. for( ; csectLowControl > 0; ++sectLimit)
  1140. {
  1141. if(sectLimit >= sectLast)
  1142. {
  1143. delete [] psectControl;
  1144. return S_OK;
  1145. }
  1146. msfChkTo(Err_FreeList, _fat.GetNext(sectLimit, &sectType));
  1147. if( FATSECT != sectType
  1148. && DIFSECT != sectType
  1149. && (! IsSectorInList(sectLimit, psectControl, csectControl)) )
  1150. {
  1151. --csectLowControl;
  1152. }
  1153. }
  1154. //
  1155. // We are done with the control sector list.
  1156. //
  1157. delete [] psectControl;
  1158. psectControl = NULL;
  1159. //
  1160. // At Last! We begin to move some data.
  1161. // Iterate through the directory.
  1162. // Remapping the sectors of each Stream to below sectLimit.
  1163. //
  1164. cDirEntries = _dir.GetNumDirEntries();
  1165. for(sid=0; sid<cDirEntries; sid++)
  1166. {
  1167. //
  1168. // Always get the directory entry "for-writing".
  1169. // This has the effect of remapping each sector of the directory
  1170. // stream down into the front of the file.
  1171. //
  1172. msfChk(_dir.GetDirEntry(sid, FB_DIRTY, &pde));
  1173. switch(pde->GetFlags())
  1174. {
  1175. case STGTY_LOCKBYTES:
  1176. case STGTY_PROPERTY:
  1177. case STGTY_STORAGE:
  1178. case STGTY_INVALID:
  1179. default:
  1180. break;
  1181. //
  1182. // Remap The Mini-stream
  1183. //
  1184. case STGTY_ROOT:
  1185. msfChkTo(Err_Release, ConsolidateStream(pde, sectLimit));
  1186. GetMiniStream()->EmptyCache();
  1187. break;
  1188. //
  1189. // Remap the regular streams.
  1190. // Don't remap streams in the mini-streams
  1191. //
  1192. case STGTY_STREAM:
  1193. #ifdef LARGE_STREAMS
  1194. if(pde->GetSize(_dir.IsLargeSector()) < MINISTREAMSIZE)
  1195. #else
  1196. if(pde->GetSize() < MINISTREAMSIZE)
  1197. #endif
  1198. break;
  1199. msfChkTo(Err_Release, ConsolidateStream(pde, sectLimit));
  1200. break;
  1201. }
  1202. _dir.ReleaseEntry(sid);
  1203. }
  1204. //
  1205. // If there are any remaining un-remapped FAT blocks, remap them now.
  1206. // (begin-copy-on-write already remapped the DIF).
  1207. //
  1208. msfChk(_fat.DirtyAll());
  1209. msfChk(_fatMini.DirtyAll());
  1210. return sc;
  1211. Err_FreeList:
  1212. delete [] psectControl;
  1213. return sc;
  1214. Err_Release:
  1215. _dir.ReleaseEntry(sid);
  1216. Err:
  1217. return sc;
  1218. }
  1219. //+---------------------------------------------------------------------------
  1220. //
  1221. // Member: CMStream::BuildConsolidationControlSectList, private
  1222. //
  1223. // Synopsis: Makes a list of all the sectors that are copy-on-write
  1224. // for the purpose of computing how much space we need to
  1225. // make to Consolidate a file.
  1226. //
  1227. // Arguments: [ppsectList] -- [out] pointer to a list of sectors.
  1228. // [pcsect] -- [out] count of sectors on the list.
  1229. //
  1230. // Returns: Appropriate status code
  1231. //
  1232. // Modifies:
  1233. //
  1234. // History: 25-feb-1997 BChapman Created
  1235. //
  1236. //----------------------------------------------------------------------------
  1237. SCODE CMStream::BuildConsolidationControlSectList(
  1238. SECT **ppsectList,
  1239. ULONG *pcsect)
  1240. {
  1241. SECT sect;
  1242. SECT *psectList;
  1243. ULONG i, csect;
  1244. SCODE sc;
  1245. csect = _dir.GetNumDirSects() + _hdr.GetMiniFatLength();
  1246. msfMem(psectList = (SECT*) new SECT[csect]);
  1247. i = 0;
  1248. //
  1249. // Walk the Directory Stream FAT chain and record all
  1250. // the sector numbers.
  1251. //
  1252. sect = _hdr.GetDirStart();
  1253. while(sect != ENDOFCHAIN)
  1254. {
  1255. msfAssert(i < csect);
  1256. psectList[i++] = sect;
  1257. msfChkTo(Err_Free, _fat.GetNext(sect, &sect));
  1258. }
  1259. msfAssert(i == _dir.GetNumDirSects());
  1260. //
  1261. // Walk the MiniFat FAT chain and record all
  1262. // the sector numbers.
  1263. //
  1264. sect = _hdr.GetMiniFatStart();
  1265. while(sect != ENDOFCHAIN)
  1266. {
  1267. msfAssert(i < csect);
  1268. psectList[i++] = sect;
  1269. msfChkTo(Err_Free, _fat.GetNext(sect, &sect));
  1270. }
  1271. msfAssert((i == csect) && aMsg("Directory Stream + MiniFat too short\n"));
  1272. *ppsectList = psectList;
  1273. *pcsect = csect;
  1274. return S_OK;
  1275. Err_Free:
  1276. if (psectList != NULL)
  1277. delete [] psectList;
  1278. return sc;
  1279. Err:
  1280. return sc;
  1281. }
  1282. //+---------------------------------------------------------------------------
  1283. //
  1284. // Member: CMStream::IsSectorOnList, private
  1285. //
  1286. // Synopsis: Searches a list of sector values for a given value.
  1287. //
  1288. // Arguments: [sect] -- [in] value to search for.
  1289. // [psectList] -- [in] list of sectors.
  1290. // [csect] -- [in] count of sectors on the list.
  1291. //
  1292. // Returns: TRUE if the sector is on the list, otherwise FALSE.
  1293. //
  1294. // Modifies:
  1295. //
  1296. // History: 25-feb-1997 BChapman Created
  1297. //
  1298. // Notes:
  1299. //
  1300. //----------------------------------------------------------------------------
  1301. BOOL CMStream::IsSectorInList(
  1302. SECT sect,
  1303. SECT *psectList,
  1304. ULONG csectList)
  1305. {
  1306. ULONG i;
  1307. for(i=0; i < csectList; i++)
  1308. {
  1309. if(sect == psectList[i])
  1310. return TRUE;
  1311. }
  1312. return FALSE;
  1313. }
  1314. //+---------------------------------------------------------------------------
  1315. //
  1316. // Member: CMStream::ConsolidateStream, private
  1317. //
  1318. // Synopsis: Scan the stream FAT chain and remap sectors that are
  1319. // above the given limit.
  1320. //
  1321. // Arguments: [pde] -- Directory entry of the stream (DIRTY)
  1322. // [sectLimit] -- sector limit that all sectors should be below
  1323. //
  1324. // Returns: Appropriate status code
  1325. //
  1326. // Modifies:
  1327. //
  1328. // History: 18-feb-1997 BChapman Created
  1329. //
  1330. // Notes:
  1331. //
  1332. //----------------------------------------------------------------------------
  1333. SCODE CMStream::ConsolidateStream(
  1334. CDirEntry *pde, // Current CDirEntry Object (read-only)
  1335. SECT sectLimit) // Move all sectors below this sector#
  1336. {
  1337. SECT sectPrev, sectCurrent, sectNew;
  1338. ULONG cbLength;
  1339. SCODE sc=S_OK;
  1340. //
  1341. // This code should not be used in NOSCRATCH mode.
  1342. //
  1343. msfAssert(_pmsScratch == NULL);
  1344. //
  1345. // Check the first sector of the stream as a special case.
  1346. //
  1347. sectCurrent = pde->GetStart();
  1348. if(ENDOFCHAIN != sectCurrent && sectCurrent > sectLimit)
  1349. {
  1350. msfChk(_fat.GetFree(1, &sectNew, GF_WRITE));
  1351. // This is only here because I don't understand GetFree().
  1352. msfAssert(ENDOFCHAIN != sectNew);
  1353. msfChk(MoveSect(ENDOFCHAIN, sectCurrent, sectNew));
  1354. sectCurrent = sectNew;
  1355. pde->SetStart(sectCurrent);
  1356. }
  1357. //
  1358. // Do the rest of the stream FAT chain.
  1359. //
  1360. sectPrev = sectCurrent;
  1361. while(ENDOFCHAIN != sectPrev)
  1362. {
  1363. msfChk(_fat.GetNext(sectPrev, &sectCurrent));
  1364. if(ENDOFCHAIN != sectCurrent && sectCurrent > sectLimit)
  1365. {
  1366. msfChk(_fat.GetFree(1, &sectNew, GF_WRITE));
  1367. // This is only here because I don't understand GetFree().
  1368. msfAssert(ENDOFCHAIN != sectNew);
  1369. msfChk(MoveSect(sectPrev, sectCurrent, sectNew));
  1370. sectCurrent = sectNew;
  1371. }
  1372. sectPrev = sectCurrent;
  1373. }
  1374. Err:
  1375. return sc;
  1376. }
  1377. //+---------------------------------------------------------------------------
  1378. //
  1379. // Member: CMStream::MoveSect, private
  1380. //
  1381. // Synopsis: Move Data Sector for Consolidation Support.
  1382. //
  1383. // Arguments: [sectPrev] -- Previous sector, so the link can be updated.
  1384. // [sectOld] -- Location to copy from
  1385. // [sectNew] -- Location to copy to
  1386. //
  1387. // Returns: Appropriate status code
  1388. //
  1389. // Modifies:
  1390. //
  1391. // History: 20-Feb-1997 BChapman Created
  1392. //
  1393. // Notes:
  1394. //
  1395. //----------------------------------------------------------------------------
  1396. SCODE CMStream::MoveSect(
  1397. SECT sectPrev,
  1398. SECT sectOld,
  1399. SECT sectNew)
  1400. {
  1401. ULONG cb;
  1402. SCODE sc=S_OK;
  1403. ULARGE_INTEGER ulOff;
  1404. BYTE *pbScratch = BP_TO_P(BYTE HUGEP *, _pCopySectBuf);
  1405. //
  1406. // This code does not expect NOSCRATCH mode.
  1407. //
  1408. msfAssert(_pmsScratch == NULL);
  1409. //
  1410. // Copy the data from the old sector to the new sector.
  1411. //
  1412. ulOff.QuadPart = ConvertSectOffset(sectOld, 0, GetSectorShift());
  1413. msfChk((*_pplstParent)->ReadAt(ulOff,
  1414. pbScratch,
  1415. GetSectorSize(),
  1416. &cb));
  1417. ulOff.QuadPart = ConvertSectOffset(sectNew, 0, GetSectorShift());
  1418. msfChk((*_pplstParent)->WriteAt(ulOff,
  1419. pbScratch,
  1420. GetSectorSize(),
  1421. &cb));
  1422. //
  1423. // Update the previous sector's link (if this isn't the first sector)
  1424. //
  1425. if(ENDOFCHAIN != sectPrev)
  1426. {
  1427. msfChk(_fat.SetNext(sectPrev, sectNew));
  1428. }
  1429. //
  1430. // Update the link to the next sector.
  1431. //
  1432. SECT sectTemp;
  1433. msfChk(_fat.GetNext(sectOld, &sectTemp));
  1434. msfChk(_fat.SetNext(sectNew, sectTemp));
  1435. //
  1436. // Free the old sector.
  1437. //
  1438. msfChk(_fat.SetNext(sectOld, FREESECT));
  1439. Err:
  1440. return sc;
  1441. }
  1442. //+---------------------------------------------------------------------------
  1443. //
  1444. // Member: CMStream::CopySect, private
  1445. //
  1446. // Synopsis: Do a partial sector delta for copy-on-write support
  1447. //
  1448. // Arguments: [sectOld] -- Location to copy from
  1449. // [sectNew] -- Location to copy to
  1450. // [oStart] -- Offset into sector to begin delta
  1451. // [oEnd] -- Offset into sector to end delta
  1452. // [pb] -- Buffer to delta from
  1453. // [pulRetval] -- Return location for number of bytes written
  1454. //
  1455. // Returns: Appropriate status code
  1456. //
  1457. // Modifies:
  1458. //
  1459. // History: 22-Jan-93 PhilipLa Created
  1460. //
  1461. // Notes: [pb] may be unsafe memory
  1462. //
  1463. //----------------------------------------------------------------------------
  1464. //This pragma is to avoid a C7 bug when building RETAIL
  1465. #if _MSC_VER == 700 && DBG == 0
  1466. #pragma function(memcpy)
  1467. #endif
  1468. SCODE CMStream::CopySect(
  1469. SECT sectOld,
  1470. SECT sectNew,
  1471. OFFSET oStart, // First byte of the sector to copy.
  1472. OFFSET oEnd, // Last byte of the sector to copy.
  1473. BYTE const HUGEP *pb,
  1474. ULONG *pulRetval)
  1475. {
  1476. SCODE sc;
  1477. ULONG cb;
  1478. ULARGE_INTEGER ulOff;
  1479. ULISetHigh(ulOff, 0);
  1480. BYTE HUGEP *pbScratch = BP_TO_P(BYTE HUGEP *, _pCopySectBuf);
  1481. #if DBG == 1
  1482. msfAssert((_uBufferRef == 0) &&
  1483. aMsg("Attempted to use CopySect buffer while refcount != 0"));
  1484. AtomicInc(&_uBufferRef);
  1485. #endif
  1486. msfAssert((pbScratch != NULL) && aMsg("No CopySect buffer found."));
  1487. #ifdef LARGE_DOCFILE
  1488. ulOff.QuadPart = ConvertSectOffset(sectOld, 0, GetSectorShift());
  1489. #else
  1490. ULISetLow(ulOff, ConvertSectOffset(sectOld, 0, GetSectorShift()));
  1491. #endif
  1492. msfHChk((*_pplstParent)->ReadAt(
  1493. ulOff,
  1494. pbScratch,
  1495. GetSectorSize(),
  1496. &cb));
  1497. //Now do delta in memory.
  1498. BYTE HUGEP *pstart;
  1499. pstart = pbScratch + oStart;
  1500. USHORT memLength;
  1501. memLength = oEnd - oStart + 1;
  1502. TRY
  1503. {
  1504. memcpy(pstart, pb, memLength);
  1505. }
  1506. CATCH(CException, e)
  1507. {
  1508. UNREFERENCED_PARM(e);
  1509. msfErr(Err, STG_E_INVALIDPOINTER);
  1510. }
  1511. END_CATCH
  1512. #ifdef LARGE_DOCFILE
  1513. ulOff.QuadPart = ConvertSectOffset(sectNew, 0, GetSectorShift());
  1514. #else
  1515. ULISetLow(ulOff, ConvertSectOffset(sectNew, 0, GetSectorShift()));
  1516. #endif
  1517. msfHChk((*_pplstParent)->WriteAt(
  1518. ulOff,
  1519. pbScratch,
  1520. GetSectorSize(),
  1521. &cb));
  1522. *pulRetval = memLength;
  1523. Err:
  1524. #if DBG == 1
  1525. AtomicDec(&_uBufferRef);
  1526. #endif
  1527. return sc;
  1528. }
  1529. //This returns the compiler to the default behavior
  1530. #if _MSC_VER == 700 && DBG == 0
  1531. #pragma intrinsic(memcpy)
  1532. #endif
  1533. //+-------------------------------------------------------------------------
  1534. //
  1535. // Member: CMStream::MWrite, public
  1536. //
  1537. // Synposis: Do multiple sector writes
  1538. //
  1539. // Effects: Causes multiple stream writes. Modifies fat and directory
  1540. //
  1541. // Arguments: [ph] -- Handle of stream doing write
  1542. // [start] -- Starting sector to write
  1543. // [oStart] -- offset into sector to begin write at
  1544. // [end] -- Last sector to write
  1545. // [oEnd] -- offset into last sector to write to
  1546. // [buffer] -- Pointer to buffer into which data will be written
  1547. // [ulRetVal] -- location to return number of bytes written
  1548. //
  1549. // Returns: Error code of any failed call to parent write
  1550. // S_OK if call completed OK.
  1551. //
  1552. // Modifies: ulRetVal returns the number of bytes written
  1553. //
  1554. // Algorithm: Using a segment table, perform writes on parent stream
  1555. // until call is completed.
  1556. //
  1557. // History: 16-Aug-91 PhilipLa Created.
  1558. // 10-Sep-91 PhilipLa Converted to use sector table
  1559. // 11-Sep-91 PhilipLa Modified interface, modified to
  1560. // allow partial sector writes.
  1561. // 07-Jan-92 PhilipLa Converted to use handle.
  1562. // 18-Feb-92 PhilipLa Added copy on write support.
  1563. //
  1564. // Notes: [pvBuffer] may be unsafe memory
  1565. //
  1566. //---------------------------------------------------------------------------
  1567. SCODE CMStream::MWrite(
  1568. SID sid,
  1569. BOOL fIsMini,
  1570. #ifdef LARGE_STREAMS
  1571. ULONGLONG ulOffset,
  1572. #else
  1573. ULONG ulOffset,
  1574. #endif
  1575. VOID const HUGEP *pvBuffer,
  1576. ULONG ulCount,
  1577. CStreamCache *pstmc,
  1578. ULONG *pulRetval)
  1579. {
  1580. SCODE sc;
  1581. BYTE const HUGEP *pbBuffer = (BYTE const HUGEP *) pvBuffer;
  1582. USHORT cbSector = GetSectorSize();
  1583. CFat *pfat = &_fat;
  1584. USHORT uShift = GetSectorShift();
  1585. ULONG ulLastBytes = 0;
  1586. ULARGE_INTEGER ulOff;
  1587. ULISetHigh(ulOff, 0);
  1588. #ifdef LARGE_STREAMS
  1589. ULONGLONG ulOldSize = 0;
  1590. #else
  1591. ULONG ulOldSize = 0;
  1592. #endif
  1593. // Check if it's a small stream and whether this is a real or
  1594. // scratch multistream.
  1595. if ((fIsMini) &&
  1596. (!_fIsScratch) &&
  1597. (SIDMINISTREAM != sid))
  1598. {
  1599. msfAssert(sid <= MAXREGSID &&
  1600. aMsg("Invalid SID in MWrite"));
  1601. // This stream is stored in the ministream
  1602. cbSector = MINISECTORSIZE;
  1603. uShift = MINISECTORSHIFT;
  1604. pfat = GetMiniFat();
  1605. }
  1606. USHORT uMask = cbSector - 1;
  1607. SECT start = (SECT)(ulOffset >> uShift);
  1608. OFFSET oStart = (OFFSET)(ulOffset & uMask);
  1609. SECT end = (SECT)((ulOffset + ulCount - 1) >> uShift);
  1610. OFFSET oEnd = (OFFSET)((ulOffset + ulCount - 1) & uMask);
  1611. msfDebugOut((DEB_ITRACE,"In CMStream::MWrite(%lu,%u,%lu,%u)\n",
  1612. start,oStart,end,oEnd));
  1613. ULONG bytecount;
  1614. ULONG total = 0;
  1615. msfChk(_dir.GetSize(sid, &ulOldSize));
  1616. //BEGIN COPYONWRITE
  1617. // Note that we don't do this for ministreams (the second pass through
  1618. // this code will take care of it).
  1619. msfAssert(!_fBlockWrite &&
  1620. aMsg("Called MWrite on Unconverted multistream"));
  1621. if ((_fBlockHeader) && (GetMiniFat() != pfat))
  1622. {
  1623. msfDebugOut((DEB_ITRACE,"**MWrite preparing for copy-on-write\n"));
  1624. SECT sectOldStart, sectNewStart, sectOldEnd, sectNewEnd;
  1625. SECT sectNew;
  1626. if (start != 0)
  1627. {
  1628. msfChk(pstmc->GetESect(start - 1, &sectNew));
  1629. }
  1630. else
  1631. {
  1632. msfChk(_dir.GetStart(sid, &sectNew));
  1633. }
  1634. msfChk(_fat.Remap(
  1635. sectNew,
  1636. (start == 0) ? 0 : 1,
  1637. (end - start + 1),
  1638. &sectOldStart,
  1639. &sectNewStart,
  1640. &sectOldEnd,
  1641. &sectNewEnd));
  1642. msfAssert(((end != start) || (sectNewStart == sectNewEnd)) &&
  1643. aMsg("Remap postcondition failed."));
  1644. if (sc != S_FALSE)
  1645. {
  1646. msfChk(pstmc->EmptyRegion(start, end));
  1647. }
  1648. if ((start == 0) && (sectNewStart != ENDOFCHAIN))
  1649. {
  1650. msfDebugOut((DEB_ITRACE,
  1651. "*** Remapped first sector. Changing directory.\n"));
  1652. msfChk(_dir.SetStart(sid, sectNewStart));
  1653. }
  1654. #ifdef LARGE_STREAMS
  1655. ULONGLONG ulSize = ulOldSize;
  1656. #else
  1657. ULONG ulSize = ulOldSize;
  1658. #endif
  1659. if (((oStart != 0) ||
  1660. ((end == start) && (ulOffset + ulCount != ulSize)
  1661. && ((USHORT)oEnd != (cbSector - 1)))) &&
  1662. (sectNewStart != ENDOFCHAIN))
  1663. {
  1664. //Partial first sector.
  1665. ULONG ulRetval;
  1666. msfChk(CopySect(
  1667. sectOldStart,
  1668. sectNewStart,
  1669. oStart,
  1670. (OFFSET) (end == start ? oEnd : (cbSector - 1)),
  1671. pbBuffer,
  1672. &ulRetval));
  1673. pbBuffer = pbBuffer + ulRetval;
  1674. total = total + ulRetval;
  1675. start++;
  1676. oStart = 0;
  1677. }
  1678. if (((end >= start) && ((USHORT)oEnd != cbSector - 1) &&
  1679. (ulCount + ulOffset != ulSize)) &&
  1680. (sectNewEnd != ENDOFCHAIN))
  1681. {
  1682. //Partial last sector.
  1683. msfAssert(((end != start) || (oStart == 0)) &&
  1684. aMsg("CopySect precondition failed."));
  1685. msfChk(CopySect(
  1686. sectOldEnd,
  1687. sectNewEnd,
  1688. 0,
  1689. oEnd,
  1690. pbBuffer + ((end - start) << uShift) - oStart,
  1691. &ulLastBytes));
  1692. end--;
  1693. oEnd = cbSector - 1;
  1694. //We don't need to update pbBuffer, since the change
  1695. // is at the end.
  1696. }
  1697. }
  1698. // At this point, the entire block has been moved into the copy-on-write
  1699. // area of the multistream, and all partial writes have been done.
  1700. //END COPYONWRITE
  1701. msfAssert(end != 0xffffffffL);
  1702. if (end < start)
  1703. {
  1704. *pulRetval = total + ulLastBytes;
  1705. goto Err;
  1706. }
  1707. ULONG ulRunLength;
  1708. ulRunLength = end - start + 1;
  1709. USHORT offset;
  1710. offset = oStart;
  1711. while (TRUE)
  1712. {
  1713. SSegment segtab[CSEG + 1];
  1714. ULONG cSeg;
  1715. msfChk(pstmc->Contig(
  1716. start,
  1717. TRUE,
  1718. (SSegment STACKBASED *) segtab,
  1719. ulRunLength,
  1720. &cSeg));
  1721. msfAssert(cSeg <= CSEG);
  1722. USHORT oend = cbSector - 1;
  1723. ULONG i;
  1724. SECT sectStart;
  1725. for (USHORT iseg = 0; iseg < cSeg;)
  1726. {
  1727. sectStart = segtab[iseg].sectStart;
  1728. i = segtab[iseg].cSect;
  1729. if (i > ulRunLength)
  1730. i = ulRunLength;
  1731. ulRunLength -= i;
  1732. start += i;
  1733. iseg++;
  1734. if (ulRunLength == 0)
  1735. oend = oEnd;
  1736. ULONG ulSize = ((i - 1) << uShift) - offset + oend + 1;
  1737. msfDebugOut((
  1738. DEB_ITRACE,
  1739. "Calling lstream WriteAt(%lu,%p,%lu)\n",
  1740. ConvertSectOffset(sectStart,offset,uShift),
  1741. pbBuffer,
  1742. ulSize));
  1743. if (GetMiniFat() == pfat)
  1744. {
  1745. sc = _pdsministream->CDirectStream::WriteAt(
  1746. (sectStart << uShift) + offset,
  1747. pbBuffer, ulSize,
  1748. (ULONG STACKBASED *)&bytecount);
  1749. }
  1750. else
  1751. {
  1752. #ifdef LARGE_DOCFILE
  1753. ulOff.QuadPart = ConvertSectOffset(sectStart, offset, uShift);
  1754. #else
  1755. ULISetLow(ulOff, ConvertSectOffset(sectStart, offset,
  1756. uShift));
  1757. #endif
  1758. sc = DfGetScode((*_pplstParent)->WriteAt(ulOff, pbBuffer,
  1759. ulSize, &bytecount));
  1760. }
  1761. total += bytecount;
  1762. //Check if this write is the last one in the stream,
  1763. // and that the stream ends as a partial sector.
  1764. //If so, fill out the remainder of the sector with
  1765. // something.
  1766. if ((0 == ulRunLength) && (total + ulOffset > ulOldSize) &&
  1767. (((total + ulOffset) & (GetSectorSize() - 1)) != 0))
  1768. {
  1769. //This is the last sector and the stream has grown.
  1770. ULONG csectOld = (ULONG)((ulOldSize + GetSectorSize() - 1) >>
  1771. GetSectorShift());
  1772. ULONG csectNew = (ULONG)((total + ulOffset + GetSectorSize() - 1) >>
  1773. GetSectorShift());
  1774. if (csectNew > csectOld)
  1775. {
  1776. msfAssert(!fIsMini &&
  1777. aMsg("Small stream grew in MWrite"));
  1778. SECT sectLast = sectStart + i - 1;
  1779. msfVerify(SUCCEEDED(SecureSect(
  1780. sectLast,
  1781. total + ulOffset,
  1782. FALSE)));
  1783. }
  1784. }
  1785. if (0 == ulRunLength || FAILED(sc))
  1786. {
  1787. break;
  1788. }
  1789. pbBuffer = pbBuffer + bytecount;
  1790. offset = 0;
  1791. }
  1792. if (0 == ulRunLength || FAILED(sc))
  1793. {
  1794. *pulRetval = total + ulLastBytes;
  1795. msfDebugOut((
  1796. DEB_ITRACE,
  1797. "Out CMStream::MWrite()=>%lu, retval = %lu\n",
  1798. sc,
  1799. total));
  1800. break;
  1801. }
  1802. }
  1803. Err:
  1804. return sc;
  1805. }
  1806. //+---------------------------------------------------------------------------
  1807. //
  1808. // Member: CMStream::Flush, public
  1809. //
  1810. // Synopsis: Flush control structures.
  1811. //
  1812. // Arguments: None.
  1813. //
  1814. // Returns: Appropriate status code
  1815. //
  1816. // History: 16-Dec-92 PhilipLa Created
  1817. //
  1818. //----------------------------------------------------------------------------
  1819. SCODE CMStream::Flush(BOOL fFlushCache)
  1820. {
  1821. SCODE sc = S_OK;
  1822. msfAssert(!_fBlockWrite &&
  1823. aMsg("Flush called on unconverted base."));
  1824. if ((!_fIsScratch) && (*_pplstParent != NULL))
  1825. {
  1826. msfChk(_pmpt->Flush());
  1827. msfChk(FlushHeader(HDR_NOFORCE));
  1828. msfChk(ILBFlush(*_pplstParent, fFlushCache));
  1829. }
  1830. Err:
  1831. return sc;
  1832. }
  1833. //+-------------------------------------------------------------------------
  1834. //
  1835. // Function: ILBFlush
  1836. //
  1837. // Synopsis: Flush as thoroughly as possible
  1838. //
  1839. // Effects: Flushes ILockBytes
  1840. //
  1841. // Arguments: [pilb] - ILockBytes to flush
  1842. // [fFlushCache] - Flush thoroughly iff TRUE
  1843. //
  1844. // Returns: SCODE
  1845. //
  1846. // Algorithm:
  1847. //
  1848. // History: 12-Feb-93 AlexT Created
  1849. //
  1850. //--------------------------------------------------------------------------
  1851. SCODE ILBFlush(ILockBytes *pilb, BOOL fFlushCache)
  1852. {
  1853. // Try to query interface to our own implementation
  1854. IFileLockBytes *pfl;
  1855. SCODE sc;
  1856. msfDebugOut((DEB_ITRACE, "In ILBFlushCache(%p)\n", pilb));
  1857. // Check for FileLockBytes
  1858. if (!fFlushCache ||
  1859. FAILED(DfGetScode(pilb->QueryInterface(IID_IFileLockBytes, (void **)&pfl))))
  1860. {
  1861. // Either we don't have to flush the cache or its not our ILockBytes
  1862. sc = DfGetScode(pilb->Flush());
  1863. }
  1864. else
  1865. {
  1866. // We have to flush the cache and its our ILockBytes
  1867. sc = DfGetScode(pfl->FlushCache());
  1868. pfl->Release();
  1869. }
  1870. msfDebugOut((DEB_ITRACE, "Out ILBFlushCache()\n"));
  1871. return(sc);
  1872. }
  1873. //+---------------------------------------------------------------------------
  1874. //
  1875. // Member: CMStream::SecureSect, public
  1876. //
  1877. // Synopsis: Zero out the unused portion of a sector
  1878. //
  1879. // Arguments: [sect] -- Sector to zero out
  1880. // [ulSize] -- Size of stream
  1881. // [fIsMini] -- TRUE if stream is in ministream
  1882. //
  1883. // Returns: Appropriate status code
  1884. //
  1885. // Modifies:
  1886. //
  1887. // History: 05-Apr-93 PhilipLa Created
  1888. //
  1889. // Notes:
  1890. //
  1891. //----------------------------------------------------------------------------
  1892. SCODE CMStream::SecureSect(
  1893. const SECT sect,
  1894. #ifdef LARGE_STREAMS
  1895. const ULONGLONG ulSize,
  1896. #else
  1897. const ULONG ulSize,
  1898. #endif
  1899. const BOOL fIsMini)
  1900. {
  1901. #ifdef SECURE_TAIL
  1902. SCODE sc = S_OK;
  1903. BYTE *pb = NULL;
  1904. if (!_fIsScratch)
  1905. {
  1906. ULONG cbSect = fIsMini ? MINISECTORSIZE : GetSectorSize();
  1907. msfAssert(ulSize != 0);
  1908. ULONG ulOffset = (ULONG)(((ulSize - 1) % cbSect) + 1);
  1909. ULONG cb = cbSect - ulOffset;
  1910. msfAssert(cb != 0);
  1911. //We can use any initialized block of memory here. The header
  1912. // is available and is the correct size, so we use that.
  1913. #ifdef SECURE_BUFFER
  1914. pb = s_bufSecure;
  1915. #else
  1916. pb = (BYTE *)_hdr.GetData();
  1917. #endif
  1918. #ifdef SECURETEST
  1919. pb = (BYTE *) DfMemAlloc(cb);
  1920. if (pb != NULL)
  1921. memset(pb, 'Y', cb);
  1922. #endif
  1923. ULONG cbWritten;
  1924. if (!fIsMini)
  1925. {
  1926. ULARGE_INTEGER ulOff;
  1927. #ifdef LARGE_DOCFILE
  1928. ulOff.QuadPart = ConvertSectOffset(
  1929. sect,
  1930. (OFFSET)ulOffset,
  1931. GetSectorShift());
  1932. #else
  1933. ULISet32 (ulOff, ConvertSectOffset(
  1934. sect,
  1935. (OFFSET)ulOffset,
  1936. GetSectorShift()));
  1937. #endif
  1938. msfChk(DfGetScode((*_pplstParent)->WriteAt(
  1939. ulOff,
  1940. pb,
  1941. cb,
  1942. &cbWritten)));
  1943. }
  1944. else
  1945. {
  1946. msfChk(_pdsministream->WriteAt(
  1947. (sect << MINISECTORSHIFT) + ulOffset,
  1948. pb,
  1949. cb,
  1950. (ULONG STACKBASED *)&cbWritten));
  1951. }
  1952. if (cbWritten != cb)
  1953. {
  1954. sc = STG_E_WRITEFAULT;
  1955. }
  1956. }
  1957. Err:
  1958. #ifdef SECURETEST
  1959. DfMemFree(pb);
  1960. #endif
  1961. return sc;
  1962. #else
  1963. //On NT, our sectors get zeroed out by the file system, so we don't
  1964. // need this whole rigamarole.
  1965. return S_OK;
  1966. #endif // WIN32 == 200
  1967. }
  1968. //+-------------------------------------------------------------------------
  1969. //
  1970. // Method: CMStream::SetFileLockBytesTime, public
  1971. //
  1972. // Synopsis: Set the IFileLockBytes time.
  1973. //
  1974. // Arguments: [tt] -- Timestamp requested (WT_CREATION, WT_MODIFICATION,
  1975. // WT_ACCESS)
  1976. // [nt] -- New timestamp
  1977. //
  1978. // Returns: S_OK if call completed OK.
  1979. //
  1980. // Algorithm: Query for IFileLockBytes and call its SetTime member.
  1981. //
  1982. // History: 01-Sep-95 MikeHill Created.
  1983. //
  1984. //--------------------------------------------------------------------------
  1985. SCODE CMStream::SetFileLockBytesTime(
  1986. WHICHTIME const tt,
  1987. TIME_T nt)
  1988. {
  1989. SCODE sc = S_OK;
  1990. ILockBytes *pilb = *_pplstParent;
  1991. IFileLockBytes *pfl;
  1992. if (pilb &&
  1993. (SUCCEEDED(pilb->QueryInterface(IID_IFileLockBytes, (void **)&pfl))))
  1994. {
  1995. sc = ((CFileStream *)pfl)->SetTime(tt, nt);
  1996. pfl->Release();
  1997. }
  1998. return sc;
  1999. }
  2000. //+-------------------------------------------------------------------------
  2001. //
  2002. // Method: CMStream::SetAllFileLockBytesTimes, public
  2003. //
  2004. // Synopsis: Set the IFileLockBytes time.
  2005. //
  2006. // Arguments:
  2007. // [atm] -- ACCESS time
  2008. // [mtm] -- MODIFICATION time
  2009. // [ctm] -- CREATION time
  2010. //
  2011. // Returns: S_OK if call completed OK.
  2012. //
  2013. // Algorithm: Query for IFileLockBytes and call its SetAllTimes member.
  2014. //
  2015. // History: 29-Nov-95 SusiA Created.
  2016. //
  2017. //--------------------------------------------------------------------------
  2018. SCODE CMStream::SetAllFileLockBytesTimes(
  2019. TIME_T atm,
  2020. TIME_T mtm,
  2021. TIME_T ctm)
  2022. {
  2023. SCODE sc = S_OK;
  2024. ILockBytes *pilb = *_pplstParent;
  2025. IFileLockBytes *pfl;
  2026. if (SUCCEEDED(pilb->QueryInterface( IID_IFileLockBytes, (void **)&pfl)))
  2027. {
  2028. sc = ((CFileStream *)pfl)->SetAllTimes(atm, mtm, ctm);
  2029. pfl->Release();
  2030. }
  2031. return sc;
  2032. }
  2033. //+-------------------------------------------------------------------------
  2034. //
  2035. // Method: CMStream::SetTime, public
  2036. //
  2037. // Synopsis: Set the time for a given handle
  2038. //
  2039. // Arguments: [sid] -- SID to retrieve time for
  2040. // [tt] -- Timestamp requested (WT_CREATION, WT_MODIFICATION,
  2041. // WT_ACCESS)
  2042. // [nt] -- New timestamp
  2043. //
  2044. // Returns: S_OK if call completed OK.
  2045. //
  2046. // Algorithm: Call through to directory
  2047. //
  2048. // History: 01-Apr-92 PhilipLa Created.
  2049. // 14-Sep-92 PhilipLa inlined.
  2050. // <Missing history>
  2051. // 26-APR-99 RogerCh Removed faulty optimization
  2052. //
  2053. //--------------------------------------------------------------------------
  2054. SCODE CMStream::SetTime(
  2055. SID const sid,
  2056. WHICHTIME const tt,
  2057. TIME_T nt)
  2058. {
  2059. if ( sid == SIDROOT )
  2060. {
  2061. SCODE sc;
  2062. if( FAILED( sc = SetFileLockBytesTime( tt, nt )))
  2063. {
  2064. return sc;
  2065. }
  2066. }// if( sid == SIDROOT)
  2067. return _dir.SetTime(sid, tt, nt);
  2068. }
  2069. //+-------------------------------------------------------------------------
  2070. //
  2071. // Method: CMStream::SetAllTimes, public
  2072. //
  2073. // Synopsis: Set all the times for a given handle
  2074. //
  2075. // Arguments: [sid] -- SID to retrieve time for
  2076. // [atm] -- ACCESS time
  2077. // [mtm] -- MODIFICATION time
  2078. // [ctm] -- CREATION time
  2079. //
  2080. // Returns: S_OK if call completed OK.
  2081. //
  2082. // Algorithm: Call through to directory
  2083. //
  2084. // History: 27-Nov-95 SusiA Created
  2085. //
  2086. //--------------------------------------------------------------------------
  2087. SCODE CMStream::SetAllTimes(
  2088. SID const sid,
  2089. TIME_T atm,
  2090. TIME_T mtm,
  2091. TIME_T ctm)
  2092. {
  2093. if ( sid == SIDROOT )
  2094. {
  2095. SCODE sc;
  2096. if( FAILED( sc = SetAllFileLockBytesTimes(atm, mtm, ctm )))
  2097. {
  2098. return sc;
  2099. }
  2100. }
  2101. return _dir.SetAllTimes(sid, atm, mtm, ctm);
  2102. }
  2103. //+-------------------------------------------------------------------------
  2104. //
  2105. // Method: CMStream::GetTime, public
  2106. //
  2107. // Synopsis: Get the time for a given handle
  2108. //
  2109. // Arguments: [sid] -- SID to retrieve time for
  2110. // [tt] -- Timestamp requested (WT_CREATION, WT_MODIFICATION,
  2111. // WT_ACCESS)
  2112. // [pnt] -- Pointer to return location
  2113. //
  2114. // Returns: S_OK if call completed OK.
  2115. //
  2116. // History: 01-Apr-92 PhilipLa Created.
  2117. // 14-Sep-92 PhilipLa inlined.
  2118. //
  2119. //--------------------------------------------------------------------------
  2120. SCODE CMStream::GetTime(SID const sid,
  2121. WHICHTIME const tt,
  2122. TIME_T *pnt)
  2123. {
  2124. SCODE sc = S_OK;
  2125. if (sid == SIDROOT)
  2126. {
  2127. //Get timestamp from ILockBytes
  2128. STATSTG stat;
  2129. msfChk((*_pplstParent)->Stat(&stat, STATFLAG_NONAME));
  2130. if (tt == WT_CREATION)
  2131. {
  2132. *pnt = stat.ctime;
  2133. }
  2134. else if (tt == WT_MODIFICATION)
  2135. {
  2136. *pnt = stat.mtime;
  2137. }
  2138. else
  2139. {
  2140. *pnt = stat.atime;
  2141. }
  2142. }
  2143. else
  2144. sc = _dir.GetTime(sid, tt, pnt);
  2145. Err:
  2146. return sc;
  2147. }
  2148. //+-------------------------------------------------------------------------
  2149. //
  2150. // Method: CMStream::GetAllTimes, public
  2151. //
  2152. // Synopsis: Get the times for a given handle
  2153. //
  2154. // Arguments: [sid] -- SID to retrieve time for
  2155. // [patm] -- Pointer to the ACCESS time
  2156. // [pmtm] -- Pointer to the MODIFICATION time
  2157. // [pctm] -- Pointer to the CREATION time
  2158. //
  2159. // Returns: S_OK if call completed OK.
  2160. //
  2161. // History: 26-May-95 SusiA Created
  2162. //
  2163. //--------------------------------------------------------------------------
  2164. SCODE CMStream::GetAllTimes(SID const sid,
  2165. TIME_T *patm,
  2166. TIME_T *pmtm,
  2167. TIME_T *pctm)
  2168. {
  2169. SCODE sc = S_OK;
  2170. if (sid == SIDROOT)
  2171. {
  2172. //Get timestamp from ILockBytes
  2173. STATSTG stat;
  2174. msfChk((*_pplstParent)->Stat(&stat, STATFLAG_NONAME));
  2175. *pctm = stat.ctime;
  2176. *pmtm = stat.mtime;
  2177. *patm = stat.atime;
  2178. }
  2179. else
  2180. sc = _dir.GetAllTimes(sid, patm, pmtm, pctm);
  2181. Err:
  2182. return sc;
  2183. }
  2184. //+---------------------------------------------------------------------------
  2185. //
  2186. // Member: CMStream::InitScratch, public
  2187. //
  2188. // Synopsis: Set up a multistream for NoScratch operation
  2189. //
  2190. // Arguments: [pms] -- Pointer to base multistream
  2191. // [fNew] -- True if this is the first time the function has
  2192. // been called (init path), FALSE if merging behavior
  2193. // is required (EndCopyOnWrite)
  2194. //
  2195. // Returns: Appropriate status code
  2196. //
  2197. // Modifies:
  2198. //
  2199. // History: 02-Mar-95 PhilipLa Created
  2200. //
  2201. // Notes:
  2202. //
  2203. //----------------------------------------------------------------------------
  2204. SCODE CMStream::InitScratch(CMStream *pms, BOOL fNew)
  2205. {
  2206. msfDebugOut((DEB_ITRACE, "In CMStream::InitScratch:%p()\n", this));
  2207. msfAssert(GetSectorSize() == SCRATCHSECTORSIZE);
  2208. msfAssert(_fIsNoScratch &&
  2209. aMsg("Called InitScratch on Multistream not in NoScratch mode"));
  2210. return _fatMini.InitScratch(pms->GetFat(), fNew);
  2211. }
  2212. #ifdef MULTIHEAP
  2213. //+--------------------------------------------------------------
  2214. //
  2215. // Member: CMStream::GetMalloc, public
  2216. //
  2217. // Synopsis: Returns the allocator associated with this multistream
  2218. //
  2219. // History: 05-May-93 AlexT Created
  2220. //
  2221. //---------------------------------------------------------------
  2222. IMalloc * CMStream::GetMalloc(VOID) const
  2223. {
  2224. return (IMalloc *) &g_smAllocator;
  2225. }
  2226. #endif