storage32.c 253 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 * Compound Storage (32 bit version)
 * Storage implementation
 *
 * This file contains the compound file implementation
 * of the storage interface.
 *
 * Copyright 1999 Francis Beaudet
 * Copyright 1999 Sylvain St-Germain
 * Copyright 1999 Thuy Nguyen
11
 * Copyright 2005 Mike McCormack
12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
25
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 27 28 29 30
 *
 * NOTES
 *  The compound file implementation of IStorage used for create
 *  and manage substorages and streams within a storage object
 *  residing in a compound file object.
31 32 33
 */

#include <assert.h>
34
#include <stdarg.h>
35
#include <stdio.h>
Patrik Stridvall's avatar
Patrik Stridvall committed
36
#include <stdlib.h>
37 38
#include <string.h>

39
#define COBJMACROS
40 41
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
42

43 44
#include "windef.h"
#include "winbase.h"
45
#include "winnls.h"
46
#include "winuser.h"
47
#include "wine/unicode.h"
48
#include "wine/debug.h"
49 50

#include "storage32.h"
51
#include "ole2.h"      /* For Write/ReadClassStm */
52

53 54 55
#include "winreg.h"
#include "wine/wingdi16.h"

56
WINE_DEFAULT_DEBUG_CHANNEL(storage);
57

58 59 60 61
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
#define OLESTREAM_ID 0x501
#define OLESTREAM_MAX_STR_LEN 255

62 63 64 65 66 67
/*
 * These are signatures to detect the type of Document file.
 */
static const BYTE STORAGE_magic[8]    ={0xd0,0xcf,0x11,0xe0,0xa1,0xb1,0x1a,0xe1};
static const BYTE STORAGE_oldmagic[8] ={0xd0,0xcf,0x11,0xe0,0x0e,0x11,0xfc,0x0d};

68
static const char rootEntryName[] = "Root Entry";
69

70 71 72 73 74 75 76 77 78 79
/****************************************************************************
 * Storage32InternalImpl definitions.
 *
 * Definition of the implementation structure for the IStorage32 interface.
 * This one implements the IStorage32 interface for storage that are
 * inside another storage.
 */
struct StorageInternalImpl
{
  struct StorageBaseImpl base;
80

81
  /*
82
   * Entry in the parent's stream tracking list
83
   */
84
  struct list ParentListEntry;
85 86

  StorageBaseImpl *parentStorage;
87 88 89
};
typedef struct StorageInternalImpl StorageInternalImpl;

90 91 92
static const IStorageVtbl TransactedSnapshotImpl_Vtbl;
static const IStorageVtbl Storage32InternalImpl_Vtbl;

93
/* Method definitions for the Storage32InternalImpl class. */
94
static StorageInternalImpl* StorageInternalImpl_Construct(StorageBaseImpl* parentStorage,
95
                                                          DWORD openFlags, DirRef storageDirEntry);
96
static void StorageImpl_Destroy(StorageBaseImpl* iface);
97
static void StorageImpl_Invalidate(StorageBaseImpl* iface);
98
static HRESULT StorageImpl_Flush(StorageBaseImpl* iface);
99
static BOOL StorageImpl_ReadBigBlock(StorageImpl* This, ULONG blockIndex, void* buffer);
100
static BOOL StorageImpl_WriteBigBlock(StorageImpl* This, ULONG blockIndex, const void* buffer);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
static void StorageImpl_SetNextBlockInChain(StorageImpl* This, ULONG blockIndex, ULONG nextBlock);
static HRESULT StorageImpl_LoadFileHeader(StorageImpl* This);
static void StorageImpl_SaveFileHeader(StorageImpl* This);

static void Storage32Impl_AddBlockDepot(StorageImpl* This, ULONG blockIndex);
static ULONG Storage32Impl_AddExtBlockDepot(StorageImpl* This);
static ULONG Storage32Impl_GetNextExtendedBlock(StorageImpl* This, ULONG blockIndex);
static ULONG Storage32Impl_GetExtDepotBlock(StorageImpl* This, ULONG depotIndex);
static void Storage32Impl_SetExtDepotBlock(StorageImpl* This, ULONG depotIndex, ULONG blockIndex);

static ULONG BlockChainStream_GetHeadOfChain(BlockChainStream* This);
static ULARGE_INTEGER BlockChainStream_GetSize(BlockChainStream* This);
static ULONG BlockChainStream_GetCount(BlockChainStream* This);

static ULARGE_INTEGER SmallBlockChainStream_GetSize(SmallBlockChainStream* This);
116
static ULONG SmallBlockChainStream_GetHeadOfChain(SmallBlockChainStream* This);
117 118 119 120
static BOOL StorageImpl_WriteDWordToBigBlock( StorageImpl* This,
    ULONG blockIndex, ULONG offset, DWORD value);
static BOOL StorageImpl_ReadDWordFromBigBlock( StorageImpl*  This,
    ULONG blockIndex, ULONG offset, DWORD* value);
121

122
static BOOL StorageBaseImpl_IsStreamOpen(StorageBaseImpl * stg, DirRef streamEntry);
123
static BOOL StorageBaseImpl_IsStorageOpen(StorageBaseImpl * stg, DirRef storageEntry);
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
typedef struct TransactedDirEntry
{
  /* If applicable, a reference to the original DirEntry in the transacted
   * parent. If this is a newly-created entry, DIRENTRY_NULL. */
  DirRef transactedParentEntry;

  /* True if this entry is being used. */
  int inuse;

  /* True if data is up to date. */
  int read;

  /* True if this entry has been modified. */
  int dirty;

  /* True if this entry's stream has been modified. */
  int stream_dirty;

  /* True if this entry has been deleted in the transacted storage, but the
   * delete has not yet been committed. */
  int deleted;

  /* If this entry's stream has been modified, a reference to where the stream
   * is stored in the snapshot file. */
  DirRef stream_entry;

  /* This directory entry's data, including any changes that have been made. */
  DirEntry data;

  /* A reference to the parent of this node. This is only valid while we are
   * committing changes. */
  DirRef parent;

  /* A reference to a newly-created entry in the transacted parent. This is
   * always equal to transactedParentEntry except when committing changes. */
  DirRef newTransactedParentEntry;
} TransactedDirEntry;

163
/****************************************************************************
164
 * Transacted storage object.
165 166 167 168 169
 */
typedef struct TransactedSnapshotImpl
{
  struct StorageBaseImpl base;

170
  /*
171
   * Modified streams are temporarily saved to the scratch file.
172
   */
173 174 175 176 177 178 179
  StorageBaseImpl *scratch;

  /* The directory structure is kept here, so that we can track how these
   * entries relate to those in the parent storage. */
  TransactedDirEntry *entries;
  ULONG entries_size;
  ULONG firstFreeEntry;
180

181 182 183 184 185 186 187 188 189
  /*
   * Changes are committed to the transacted parent.
   */
  StorageBaseImpl *transactedParent;
} TransactedSnapshotImpl;

/* Generic function to create a transacted wrapper for a direct storage object. */
static HRESULT Storage_ConstructTransacted(StorageBaseImpl* parent, StorageBaseImpl** result);

190 191
/* OLESTREAM memory structure to use for Get and Put Routines */
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
192
typedef struct
193 194 195 196 197
{
    DWORD dwOleID;
    DWORD dwTypeID;
    DWORD dwOleTypeNameLength;
    CHAR  strOleTypeName[OLESTREAM_MAX_STR_LEN];
Alexandre Julliard's avatar
Alexandre Julliard committed
198 199
    CHAR  *pstrOleObjFileName;
    DWORD dwOleObjFileNameLength;
200 201
    DWORD dwMetaFileWidth;
    DWORD dwMetaFileHeight;
Austin English's avatar
Austin English committed
202
    CHAR  strUnknown[8]; /* don't know what this 8 byte information in OLE stream is. */
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    DWORD dwDataLength;
    BYTE *pData;
}OLECONVERT_OLESTREAM_DATA;

/* CompObj Stream structure */
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
typedef struct
{
    BYTE byUnknown1[12];
    CLSID clsid;
    DWORD dwCLSIDNameLength;
    CHAR strCLSIDName[OLESTREAM_MAX_STR_LEN];
    DWORD dwOleTypeNameLength;
    CHAR strOleTypeName[OLESTREAM_MAX_STR_LEN];
    DWORD dwProgIDNameLength;
    CHAR strProgIDName[OLESTREAM_MAX_STR_LEN];
    BYTE byUnknown2[16];
}OLECONVERT_ISTORAGE_COMPOBJ;


Austin English's avatar
Austin English committed
223
/* Ole Presentation Stream structure */
224 225 226 227 228 229
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
typedef struct
{
    BYTE byUnknown1[28];
    DWORD dwExtentX;
    DWORD dwExtentY;
230
    DWORD dwSize;
231 232 233 234 235
    BYTE *pData;
}OLECONVERT_ISTORAGE_OLEPRES;



236 237 238
/***********************************************************************
 * Forward declaration of internal functions used by the method DestroyElement
 */
239
static HRESULT deleteStorageContents(
240
  StorageBaseImpl *parentStorage,
241
  DirRef       indexToDelete,
242
  DirEntry     entryDataToDelete);
243

244
static HRESULT deleteStreamContents(
245
  StorageBaseImpl *parentStorage,
246
  DirRef        indexToDelete,
247
  DirEntry      entryDataToDelete);
248

249
static HRESULT removeFromTree(
250
  StorageBaseImpl *This,
251 252
  DirRef        parentStorageIndex,
  DirRef        deletedIndex);
253 254

/***********************************************************************
255
 * Declaration of the functions used to manipulate DirEntry
256 257
 */

258
static HRESULT insertIntoTree(
259
  StorageBaseImpl *This,
260 261
  DirRef        parentStorageIndex,
  DirRef        newEntryIndex);
262

263 264 265
static LONG entryNameCmp(
    const OLECHAR *name1,
    const OLECHAR *name2);
266

267
static DirRef findElement(
268
    StorageBaseImpl *storage,
269
    DirRef storageEntry,
270
    const OLECHAR *name,
271
    DirEntry *data);
272

273
static HRESULT findTreeParent(
274
    StorageBaseImpl *storage,
275
    DirRef storageEntry,
276
    const OLECHAR *childName,
277
    DirEntry *parentData,
278
    DirRef *parentEntry,
279 280
    ULONG *relation);

281 282 283
/***********************************************************************
 * Declaration of miscellaneous functions...
 */
284
static HRESULT validateSTGM(DWORD stgmValue);
285 286 287 288 289

static DWORD GetShareModeFromSTGM(DWORD stgm);
static DWORD GetAccessModeFromSTGM(DWORD stgm);
static DWORD GetCreationModeFromSTGM(DWORD stgm);

290
extern const IPropertySetStorageVtbl IPropertySetStorage_Vtbl;
291 292


293 294 295 296 297 298 299 300 301
/****************************************************************************
 * IEnumSTATSTGImpl definitions.
 *
 * Definition of the implementation structure for the IEnumSTATSTGImpl interface.
 * This class allows iterating through the content of a storage and to find
 * specific items inside it.
 */
struct IEnumSTATSTGImpl
{
302
  IEnumSTATSTG   IEnumSTATSTG_iface;
303 304

  LONG           ref;                   /* Reference count */
305
  StorageBaseImpl* parentStorage;         /* Reference to the parent storage */
306
  DirRef         storageDirEntry;     /* Directory entry of the storage to enumerate */
307

308
  WCHAR	         name[DIRENTRY_NAME_MAX_LEN]; /* The most recent name visited */
309 310
};

311 312 313 314 315
static inline IEnumSTATSTGImpl *impl_from_IEnumSTATSTG(IEnumSTATSTG *iface)
{
  return CONTAINING_RECORD(iface, IEnumSTATSTGImpl, IEnumSTATSTG_iface);
}

316

317
static IEnumSTATSTGImpl* IEnumSTATSTGImpl_Construct(StorageBaseImpl* This, DirRef storageDirEntry);
318 319
static void IEnumSTATSTGImpl_Destroy(IEnumSTATSTGImpl* This);

320 321 322 323
/************************************************************************
** Block Functions
*/

324
static ULONG StorageImpl_GetBigBlockOffset(StorageImpl* This, ULONG index)
325
{
326
    return (index+1) * This->bigBlockSize;
327
}
328

329
/************************************************************************
Austin English's avatar
Austin English committed
330
** Storage32BaseImpl implementation
331
*/
332 333 334 335 336 337
static HRESULT StorageImpl_ReadAt(StorageImpl* This,
  ULARGE_INTEGER offset,
  void*          buffer,
  ULONG          size,
  ULONG*         bytesRead)
{
338
    return ILockBytes_ReadAt(This->lockBytes,offset,buffer,size,bytesRead);
339 340 341 342
}

static HRESULT StorageImpl_WriteAt(StorageImpl* This,
  ULARGE_INTEGER offset,
343
  const void*    buffer,
344 345 346
  const ULONG    size,
  ULONG*         bytesWritten)
{
347
    return ILockBytes_WriteAt(This->lockBytes,offset,buffer,size,bytesWritten);
348
}
349 350 351 352 353 354

/************************************************************************
 * Storage32BaseImpl_QueryInterface (IUnknown)
 *
 * This method implements the common QueryInterface for all IStorage32
 * implementations contained in this file.
355
 *
356 357
 * See Windows documentation for more details on IUnknown methods.
 */
358
static HRESULT WINAPI StorageBaseImpl_QueryInterface(
359
  IStorage*        iface,
360 361 362
  REFIID             riid,
  void**             ppvObject)
{
363
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
364

365 366
  if ( (This==0) || (ppvObject==0) )
    return E_INVALIDARG;
367

368
  *ppvObject = 0;
369

370 371
  if (IsEqualGUID(&IID_IUnknown, riid) ||
      IsEqualGUID(&IID_IStorage, riid))
372
  {
373
    *ppvObject = This;
374
  }
375
  else if (IsEqualGUID(&IID_IPropertySetStorage, riid))
376
  {
377
    *ppvObject = &This->pssVtbl;
378
  }
379

380 381
  if ((*ppvObject)==0)
    return E_NOINTERFACE;
382

383
  IStorage_AddRef(iface);
384

385
  return S_OK;
386
}
387

388 389 390 391 392
/************************************************************************
 * Storage32BaseImpl_AddRef (IUnknown)
 *
 * This method implements the common AddRef for all IStorage32
 * implementations contained in this file.
393
 *
394 395
 * See Windows documentation for more details on IUnknown methods.
 */
396
static ULONG WINAPI StorageBaseImpl_AddRef(
397
            IStorage* iface)
398
{
399
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
400 401
  ULONG ref = InterlockedIncrement(&This->ref);

402
  TRACE("(%p) AddRef to %d\n", This, ref);
403 404

  return ref;
405
}
406

407 408 409 410 411
/************************************************************************
 * Storage32BaseImpl_Release (IUnknown)
 *
 * This method implements the common Release for all IStorage32
 * implementations contained in this file.
412
 *
413 414
 * See Windows documentation for more details on IUnknown methods.
 */
415
static ULONG WINAPI StorageBaseImpl_Release(
416
      IStorage* iface)
417
{
418
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
419

420
  ULONG ref = InterlockedDecrement(&This->ref);
421

422
  TRACE("(%p) ReleaseRef to %d\n", This, ref);
423

424
  if (ref == 0)
425 426
  {
    /*
427 428
     * Since we are using a system of base-classes, we want to call the
     * destructor of the appropriate derived class. To do this, we are
429 430
     * using virtual functions to implement the destructor.
     */
431
    StorageBaseImpl_Destroy(This);
432
  }
433

434
  return ref;
435 436 437 438 439 440 441 442 443
}

/************************************************************************
 * Storage32BaseImpl_OpenStream (IStorage)
 *
 * This method will open the specified stream object from the current storage.
 *
 * See Windows documentation for more details on IStorage methods.
 */
444
static HRESULT WINAPI StorageBaseImpl_OpenStream(
445 446
  IStorage*        iface,
  const OLECHAR*   pwcsName,  /* [string][in] */
447
  void*            reserved1, /* [unique][in] */
448 449 450
  DWORD            grfMode,   /* [in]  */
  DWORD            reserved2, /* [in]  */
  IStream**        ppstm)     /* [out] */
451
{
452
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
453
  StgStreamImpl*    newStream;
454
  DirEntry          currentEntry;
455
  DirRef            streamEntryRef;
Alexandre Julliard's avatar
Alexandre Julliard committed
456
  HRESULT           res = STG_E_UNKNOWN;
457

458
  TRACE("(%p, %s, %p, %x, %d, %p)\n",
459 460
	iface, debugstr_w(pwcsName), reserved1, grfMode, reserved2, ppstm);

461
  if ( (pwcsName==NULL) || (ppstm==0) )
Alexandre Julliard's avatar
Alexandre Julliard committed
462 463 464 465
  {
    res = E_INVALIDARG;
    goto end;
  }
466

Alexandre Julliard's avatar
Alexandre Julliard committed
467
  *ppstm = NULL;
468

469 470
  if ( FAILED( validateSTGM(grfMode) ) ||
       STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE)
Alexandre Julliard's avatar
Alexandre Julliard committed
471 472 473 474
  {
    res = STG_E_INVALIDFLAG;
    goto end;
  }
475 476 477 478

  /*
   * As documented.
   */
479
  if ( (grfMode & STGM_DELETEONRELEASE) || (grfMode & STGM_TRANSACTED) )
Alexandre Julliard's avatar
Alexandre Julliard committed
480 481 482 483
  {
    res = STG_E_INVALIDFUNCTION;
    goto end;
  }
484

485
  if (This->reverted)
486 487 488 489 490
  {
    res = STG_E_REVERTED;
    goto end;
  }

491
  /*
492 493
   * Check that we're compatible with the parent's storage mode, but
   * only if we are not in transacted mode
494
   */
495
  if(!(This->openFlags & STGM_TRANSACTED)) {
496
    if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->openFlags ) )
497
    {
498
      res = STG_E_INVALIDFLAG;
499 500
      goto end;
    }
501 502
  }

503
  /*
504
   * Search for the element with the given name
505
   */
506
  streamEntryRef = findElement(
507
    This,
508
    This->storageDirEntry,
509
    pwcsName,
510
    &currentEntry);
511

512 513 514
  /*
   * If it was found, construct the stream object and return a pointer to it.
   */
515 516
  if ( (streamEntryRef!=DIRENTRY_NULL) &&
       (currentEntry.stgType==STGTY_STREAM) )
517
  {
518 519 520 521 522 523 524
    if (StorageBaseImpl_IsStreamOpen(This, streamEntryRef))
    {
      /* A single stream cannot be opened a second time. */
      res = STG_E_ACCESSDENIED;
      goto end;
    }

525
    newStream = StgStreamImpl_Construct(This, grfMode, streamEntryRef);
526

527 528
    if (newStream!=0)
    {
529
      newStream->grfMode = grfMode;
530
      *ppstm = (IStream*)newStream;
531

532
      IStream_AddRef(*ppstm);
533

Alexandre Julliard's avatar
Alexandre Julliard committed
534 535
      res = S_OK;
      goto end;
536
    }
537

Alexandre Julliard's avatar
Alexandre Julliard committed
538 539
    res = E_OUTOFMEMORY;
    goto end;
540
  }
541

Alexandre Julliard's avatar
Alexandre Julliard committed
542 543 544 545 546
  res = STG_E_FILENOTFOUND;

end:
  if (res == S_OK)
    TRACE("<-- IStream %p\n", *ppstm);
547
  TRACE("<-- %08x\n", res);
Alexandre Julliard's avatar
Alexandre Julliard committed
548
  return res;
549 550 551 552 553 554
}

/************************************************************************
 * Storage32BaseImpl_OpenStorage (IStorage)
 *
 * This method will open a new storage object from the current storage.
555
 *
556
 * See Windows documentation for more details on IStorage methods.
557
 */
558
static HRESULT WINAPI StorageBaseImpl_OpenStorage(
559
  IStorage*        iface,
560 561 562 563 564 565
  const OLECHAR*   pwcsName,      /* [string][unique][in] */
  IStorage*        pstgPriority,  /* [unique][in] */
  DWORD            grfMode,       /* [in] */
  SNB              snbExclude,    /* [unique][in] */
  DWORD            reserved,      /* [in] */
  IStorage**       ppstg)         /* [out] */
566
{
567
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
568 569
  StorageInternalImpl*   newStorage;
  StorageBaseImpl*       newTransactedStorage;
570
  DirEntry               currentEntry;
571
  DirRef                 storageEntryRef;
Alexandre Julliard's avatar
Alexandre Julliard committed
572
  HRESULT                res = STG_E_UNKNOWN;
573

574
  TRACE("(%p, %s, %p, %x, %p, %d, %p)\n",
575
	iface, debugstr_w(pwcsName), pstgPriority,
576
	grfMode, snbExclude, reserved, ppstg);
577

578
  if ( (This==0) || (pwcsName==NULL) || (ppstg==0) )
Alexandre Julliard's avatar
Alexandre Julliard committed
579 580 581 582
  {
    res = E_INVALIDARG;
    goto end;
  }
583

584 585 586 587 588 589
  if (This->openFlags & STGM_SIMPLE)
  {
    res = STG_E_INVALIDFUNCTION;
    goto end;
  }

Alexandre Julliard's avatar
Alexandre Julliard committed
590 591 592 593 594 595
  /* as documented */
  if (snbExclude != NULL)
  {
    res = STG_E_INVALIDPARAMETER;
    goto end;
  }
596

597
  if ( FAILED( validateSTGM(grfMode) ))
Alexandre Julliard's avatar
Alexandre Julliard committed
598 599 600 601
  {
    res = STG_E_INVALIDFLAG;
    goto end;
  }
602 603 604 605

  /*
   * As documented.
   */
606
  if ( STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE ||
607 608
        (grfMode & STGM_DELETEONRELEASE) ||
        (grfMode & STGM_PRIORITY) )
Alexandre Julliard's avatar
Alexandre Julliard committed
609 610 611 612
  {
    res = STG_E_INVALIDFUNCTION;
    goto end;
  }
613

614
  if (This->reverted)
615 616
    return STG_E_REVERTED;

617
  /*
618 619
   * Check that we're compatible with the parent's storage mode,
   * but only if we are not transacted
620
   */
621
  if(!(This->openFlags & STGM_TRANSACTED)) {
622
    if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->openFlags ) )
623 624 625 626
    {
      res = STG_E_ACCESSDENIED;
      goto end;
    }
627 628
  }

Alexandre Julliard's avatar
Alexandre Julliard committed
629
  *ppstg = NULL;
630

631
  storageEntryRef = findElement(
632
                         This,
633
                         This->storageDirEntry,
634
                         pwcsName,
635
                         &currentEntry);
636

637 638
  if ( (storageEntryRef!=DIRENTRY_NULL) &&
       (currentEntry.stgType==STGTY_STORAGE) )
639
  {
640 641 642 643 644 645 646
    if (StorageBaseImpl_IsStorageOpen(This, storageEntryRef))
    {
      /* A single storage cannot be opened a second time. */
      res = STG_E_ACCESSDENIED;
      goto end;
    }

647
    newStorage = StorageInternalImpl_Construct(
648
                   This,
649
                   grfMode,
650
                   storageEntryRef);
651

652 653
    if (newStorage != 0)
    {
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
      if (grfMode & STGM_TRANSACTED)
      {
        res = Storage_ConstructTransacted(&newStorage->base, &newTransactedStorage);

        if (FAILED(res))
        {
          HeapFree(GetProcessHeap(), 0, newStorage);
          goto end;
        }

        *ppstg = (IStorage*)newTransactedStorage;
      }
      else
      {
        *ppstg = (IStorage*)newStorage;
      }
670

671 672
      list_add_tail(&This->storageHead, &newStorage->ParentListEntry);

Alexandre Julliard's avatar
Alexandre Julliard committed
673 674
      res = S_OK;
      goto end;
675
    }
676

Alexandre Julliard's avatar
Alexandre Julliard committed
677 678
    res = STG_E_INSUFFICIENTMEMORY;
    goto end;
679
  }
680

Alexandre Julliard's avatar
Alexandre Julliard committed
681 682 683
  res = STG_E_FILENOTFOUND;

end:
684
  TRACE("<-- %08x\n", res);
Alexandre Julliard's avatar
Alexandre Julliard committed
685
  return res;
686 687 688 689 690
}

/************************************************************************
 * Storage32BaseImpl_EnumElements (IStorage)
 *
691
 * This method will create an enumerator object that can be used to
692
 * retrieve information about all the elements in the storage object.
693
 *
694
 * See Windows documentation for more details on IStorage methods.
695
 */
696
static HRESULT WINAPI StorageBaseImpl_EnumElements(
697
  IStorage*       iface,
698 699 700 701
  DWORD           reserved1, /* [in] */
  void*           reserved2, /* [size_is][unique][in] */
  DWORD           reserved3, /* [in] */
  IEnumSTATSTG**  ppenum)    /* [out] */
702
{
703
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
704 705
  IEnumSTATSTGImpl* newEnum;

706
  TRACE("(%p, %d, %p, %d, %p)\n",
707 708
	iface, reserved1, reserved2, reserved3, ppenum);

709 710
  if ( (This==0) || (ppenum==0))
    return E_INVALIDARG;
711

712
  if (This->reverted)
713 714
    return STG_E_REVERTED;

715
  newEnum = IEnumSTATSTGImpl_Construct(
716
              This,
717
              This->storageDirEntry);
718 719 720

  if (newEnum!=0)
  {
721
    *ppenum = &newEnum->IEnumSTATSTG_iface;
722

723
    IEnumSTATSTG_AddRef(*ppenum);
724

725 726 727 728 729 730 731 732 733 734
    return S_OK;
  }

  return E_OUTOFMEMORY;
}

/************************************************************************
 * Storage32BaseImpl_Stat (IStorage)
 *
 * This method will retrieve information about this storage object.
735
 *
736
 * See Windows documentation for more details on IStorage methods.
737
 */
738
static HRESULT WINAPI StorageBaseImpl_Stat(
739
  IStorage*        iface,
740 741
  STATSTG*         pstatstg,     /* [out] */
  DWORD            grfStatFlag)  /* [in] */
742
{
743
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
744
  DirEntry       currentEntry;
Alexandre Julliard's avatar
Alexandre Julliard committed
745
  HRESULT        res = STG_E_UNKNOWN;
746

747
  TRACE("(%p, %p, %x)\n",
748 749
	iface, pstatstg, grfStatFlag);

750
  if ( (This==0) || (pstatstg==0))
Alexandre Julliard's avatar
Alexandre Julliard committed
751 752 753 754
  {
    res = E_INVALIDARG;
    goto end;
  }
755

756
  if (This->reverted)
757 758 759 760 761
  {
    res = STG_E_REVERTED;
    goto end;
  }

762 763
  res = StorageBaseImpl_ReadDirEntry(
                    This,
764
                    This->storageDirEntry,
765
                    &currentEntry);
766

767
  if (SUCCEEDED(res))
768
  {
769
    StorageUtl_CopyDirEntryToSTATSTG(
770
      This,
771
      pstatstg,
772
      &currentEntry,
773
      grfStatFlag);
774

775
    pstatstg->grfMode = This->openFlags;
776
    pstatstg->grfStateBits = This->stateBits;
777
  }
778

Alexandre Julliard's avatar
Alexandre Julliard committed
779 780 781
end:
  if (res == S_OK)
  {
782
    TRACE("<-- STATSTG: pwcsName: %s, type: %d, cbSize.Low/High: %d/%d, grfMode: %08x, grfLocksSupported: %d, grfStateBits: %08x\n", debugstr_w(pstatstg->pwcsName), pstatstg->type, pstatstg->cbSize.u.LowPart, pstatstg->cbSize.u.HighPart, pstatstg->grfMode, pstatstg->grfLocksSupported, pstatstg->grfStateBits);
Alexandre Julliard's avatar
Alexandre Julliard committed
783
  }
784
  TRACE("<-- %08x\n", res);
Alexandre Julliard's avatar
Alexandre Julliard committed
785
  return res;
786 787 788 789 790
}

/************************************************************************
 * Storage32BaseImpl_RenameElement (IStorage)
 *
791
 * This method will rename the specified element.
792 793 794
 *
 * See Windows documentation for more details on IStorage methods.
 */
795
static HRESULT WINAPI StorageBaseImpl_RenameElement(
796 797 798
            IStorage*        iface,
            const OLECHAR*   pwcsOldName,  /* [in] */
            const OLECHAR*   pwcsNewName)  /* [in] */
799
{
800
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
801
  DirEntry          currentEntry;
802
  DirRef            currentEntryRef;
803

804
  TRACE("(%p, %s, %s)\n",
805 806
	iface, debugstr_w(pwcsOldName), debugstr_w(pwcsNewName));

807
  if (This->reverted)
808 809
    return STG_E_REVERTED;

810
  currentEntryRef = findElement(This,
811
                                   This->storageDirEntry,
812
                                   pwcsNewName,
813
                                   &currentEntry);
814

815
  if (currentEntryRef != DIRENTRY_NULL)
816 817
  {
    /*
818
     * There is already an element with the new name
819 820 821 822 823
     */
    return STG_E_FILEALREADYEXISTS;
  }

  /*
824
   * Search for the old element name
825
   */
826
  currentEntryRef = findElement(This,
827
                                   This->storageDirEntry,
828
                                   pwcsOldName,
829
                                   &currentEntry);
830

831
  if (currentEntryRef != DIRENTRY_NULL)
832
  {
833 834
    if (StorageBaseImpl_IsStreamOpen(This, currentEntryRef) ||
        StorageBaseImpl_IsStorageOpen(This, currentEntryRef))
835
    {
836
      WARN("Element is already open; cannot rename.\n");
837 838 839
      return STG_E_ACCESSDENIED;
    }

840
    /* Remove the element from its current position in the tree */
841
    removeFromTree(This, This->storageDirEntry,
842
        currentEntryRef);
843

844
    /* Change the name of the element */
845
    strcpyW(currentEntry.name, pwcsNewName);
846

847 848 849 850
    /* Delete any sibling links */
    currentEntry.leftChild = DIRENTRY_NULL;
    currentEntry.rightChild = DIRENTRY_NULL;

851
    StorageBaseImpl_WriteDirEntry(This, currentEntryRef,
852
        &currentEntry);
853

854
    /* Insert the element in a new position in the tree */
855
    insertIntoTree(This, This->storageDirEntry,
856
        currentEntryRef);
857 858 859 860
  }
  else
  {
    /*
861
     * There is no element with the old name
862 863 864 865
     */
    return STG_E_FILENOTFOUND;
  }

866
  return StorageBaseImpl_Flush(This);
867 868 869 870 871
}

/************************************************************************
 * Storage32BaseImpl_CreateStream (IStorage)
 *
872
 * This method will create a stream object within this storage
873 874 875
 *
 * See Windows documentation for more details on IStorage methods.
 */
876
static HRESULT WINAPI StorageBaseImpl_CreateStream(
877 878
            IStorage*        iface,
            const OLECHAR*   pwcsName,  /* [string][in] */
879 880 881
            DWORD            grfMode,   /* [in] */
            DWORD            reserved1, /* [in] */
            DWORD            reserved2, /* [in] */
882
            IStream**        ppstm)     /* [out] */
883
{
884
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
885
  StgStreamImpl*    newStream;
886
  DirEntry          currentEntry, newStreamEntry;
887
  DirRef            currentEntryRef, newStreamEntryRef;
888
  HRESULT hr;
889

890
  TRACE("(%p, %s, %x, %d, %d, %p)\n",
891
	iface, debugstr_w(pwcsName), grfMode,
892 893
	reserved1, reserved2, ppstm);

894 895 896 897 898 899
  if (ppstm == 0)
    return STG_E_INVALIDPOINTER;

  if (pwcsName == 0)
    return STG_E_INVALIDNAME;

900 901 902
  if (reserved1 || reserved2)
    return STG_E_INVALIDPARAMETER;

903 904 905
  if ( FAILED( validateSTGM(grfMode) ))
    return STG_E_INVALIDFLAG;

906
  if (STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE) 
907 908
    return STG_E_INVALIDFLAG;

909
  if (This->reverted)
910 911
    return STG_E_REVERTED;

912 913 914
  /*
   * As documented.
   */
915 916
  if ((grfMode & STGM_DELETEONRELEASE) ||
      (grfMode & STGM_TRANSACTED))
917 918
    return STG_E_INVALIDFUNCTION;

919
  /*
920 921
   * Don't worry about permissions in transacted mode, as we can always write
   * changes; we just can't always commit them.
922
   */
923
  if(!(This->openFlags & STGM_TRANSACTED)) {
924 925 926 927 928
    /* Can't create a stream on read-only storage */
    if ( STGM_ACCESS_MODE( This->openFlags ) == STGM_READ )
      return STG_E_ACCESSDENIED;

    /* Can't create a stream with greater access than the parent. */
929
    if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->openFlags ) )
930 931
      return STG_E_ACCESSDENIED;
  }
932

933
  if(This->openFlags & STGM_SIMPLE)
934 935
    if(grfMode & STGM_CREATE) return STG_E_INVALIDFLAG;

936 937
  *ppstm = 0;

938
  currentEntryRef = findElement(This,
939
                                   This->storageDirEntry,
940
                                   pwcsName,
941
                                   &currentEntry);
942

943
  if (currentEntryRef != DIRENTRY_NULL)
944 945
  {
    /*
946
     * An element with this name already exists
947
     */
948
    if (STGM_CREATE_MODE(grfMode) == STGM_CREATE)
949
    {
950
      IStorage_DestroyElement(iface, pwcsName);
951
    }
952
    else
953 954 955
      return STG_E_FILEALREADYEXISTS;
  }

956
  /*
957
   * memset the empty entry
958
   */
959
  memset(&newStreamEntry, 0, sizeof(DirEntry));
960

961
  newStreamEntry.sizeOfNameString =
962
      ( lstrlenW(pwcsName)+1 ) * sizeof(WCHAR);
963

964
  if (newStreamEntry.sizeOfNameString > DIRENTRY_NAME_BUFFER_LEN)
965 966
    return STG_E_INVALIDNAME;

967
  strcpyW(newStreamEntry.name, pwcsName);
968

969 970 971 972
  newStreamEntry.stgType       = STGTY_STREAM;
  newStreamEntry.startingBlock = BLOCK_END_OF_CHAIN;
  newStreamEntry.size.u.LowPart  = 0;
  newStreamEntry.size.u.HighPart = 0;
973

974 975 976
  newStreamEntry.leftChild        = DIRENTRY_NULL;
  newStreamEntry.rightChild       = DIRENTRY_NULL;
  newStreamEntry.dirRootEntry     = DIRENTRY_NULL;
977

978
  /* call CoFileTime to get the current time
979 980
  newStreamEntry.ctime
  newStreamEntry.mtime
981 982
  */

983
  /*  newStreamEntry.clsid */
984 985

  /*
986
   * Create an entry with the new data
987
   */
988 989 990 991
  hr = StorageBaseImpl_CreateDirEntry(This, &newStreamEntry, &newStreamEntryRef);
  if (FAILED(hr))
    return hr;

992
  /*
993
   * Insert the new entry in the parent storage's tree.
994
   */
995
  hr = insertIntoTree(
996
    This,
997
    This->storageDirEntry,
998
    newStreamEntryRef);
999 1000 1001 1002 1003
  if (FAILED(hr))
  {
    StorageBaseImpl_DestroyDirEntry(This, newStreamEntryRef);
    return hr;
  }
1004

1005
  /*
1006 1007
   * Open the stream to return it.
   */
1008
  newStream = StgStreamImpl_Construct(This, grfMode, newStreamEntryRef);
1009 1010 1011

  if (newStream != 0)
  {
1012
    *ppstm = (IStream*)newStream;
1013

1014
    IStream_AddRef(*ppstm);
1015 1016 1017 1018 1019 1020
  }
  else
  {
    return STG_E_INSUFFICIENTMEMORY;
  }

1021
  return StorageBaseImpl_Flush(This);
1022 1023 1024 1025 1026
}

/************************************************************************
 * Storage32BaseImpl_SetClass (IStorage)
 *
1027
 * This method will write the specified CLSID in the directory entry of this
1028 1029 1030 1031
 * storage.
 *
 * See Windows documentation for more details on IStorage methods.
 */
1032
static HRESULT WINAPI StorageBaseImpl_SetClass(
1033
  IStorage*        iface,
1034
  REFCLSID         clsid) /* [in] */
1035
{
1036
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
1037
  HRESULT hRes;
1038
  DirEntry currentEntry;
1039

1040
  TRACE("(%p, %p)\n", iface, clsid);
1041

1042
  if (This->reverted)
1043 1044
    return STG_E_REVERTED;

1045 1046 1047
  hRes = StorageBaseImpl_ReadDirEntry(This,
                                      This->storageDirEntry,
                                      &currentEntry);
1048
  if (SUCCEEDED(hRes))
1049
  {
1050
    currentEntry.clsid = *clsid;
1051

1052 1053 1054
    hRes = StorageBaseImpl_WriteDirEntry(This,
                                         This->storageDirEntry,
                                         &currentEntry);
1055 1056
  }

1057 1058 1059
  if (SUCCEEDED(hRes))
    hRes = StorageBaseImpl_Flush(This);

1060 1061 1062 1063 1064 1065
  return hRes;
}

/************************************************************************
** Storage32Impl implementation
*/
1066

1067
/************************************************************************
1068
 * Storage32BaseImpl_CreateStorage (IStorage)
1069 1070 1071 1072 1073
 *
 * This method will create the storage object within the provided storage.
 *
 * See Windows documentation for more details on IStorage methods.
 */
1074
static HRESULT WINAPI StorageBaseImpl_CreateStorage(
1075
  IStorage*      iface,
1076 1077 1078 1079 1080
  const OLECHAR  *pwcsName, /* [string][in] */
  DWORD            grfMode,   /* [in] */
  DWORD            reserved1, /* [in] */
  DWORD            reserved2, /* [in] */
  IStorage       **ppstg)   /* [out] */
1081
{
1082
  StorageBaseImpl* const This=(StorageBaseImpl*)iface;
1083

1084 1085
  DirEntry         currentEntry;
  DirEntry         newEntry;
1086 1087
  DirRef           currentEntryRef;
  DirRef           newEntryRef;
1088 1089
  HRESULT          hr;

1090
  TRACE("(%p, %s, %x, %d, %d, %p)\n",
1091
	iface, debugstr_w(pwcsName), grfMode,
1092
	reserved1, reserved2, ppstg);
1093

1094 1095 1096
  if (ppstg == 0)
    return STG_E_INVALIDPOINTER;

1097 1098 1099 1100 1101
  if (This->openFlags & STGM_SIMPLE)
  {
    return STG_E_INVALIDFUNCTION;
  }

1102 1103 1104
  if (pwcsName == 0)
    return STG_E_INVALIDNAME;

1105 1106
  *ppstg = NULL;

1107 1108
  if ( FAILED( validateSTGM(grfMode) ) ||
       (grfMode & STGM_DELETEONRELEASE) )
1109
  {
1110
    WARN("bad grfMode: 0x%x\n", grfMode);
1111
    return STG_E_INVALIDFLAG;
1112
  }
1113

1114
  if (This->reverted)
1115 1116
    return STG_E_REVERTED;

1117 1118 1119
  /*
   * Check that we're compatible with the parent's storage mode
   */
1120 1121
  if ( !(This->openFlags & STGM_TRANSACTED) &&
       STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->openFlags ) )
1122 1123
  {
    WARN("access denied\n");
1124
    return STG_E_ACCESSDENIED;
1125
  }
1126

1127
  currentEntryRef = findElement(This,
1128
                                   This->storageDirEntry,
1129
                                   pwcsName,
1130
                                   &currentEntry);
1131

1132
  if (currentEntryRef != DIRENTRY_NULL)
1133 1134
  {
    /*
1135
     * An element with this name already exists
1136
     */
1137
    if (STGM_CREATE_MODE(grfMode) == STGM_CREATE &&
1138 1139
        ((This->openFlags & STGM_TRANSACTED) ||
         STGM_ACCESS_MODE(This->openFlags) != STGM_READ))
1140 1141 1142 1143 1144
    {
      hr = IStorage_DestroyElement(iface, pwcsName);
      if (FAILED(hr))
        return hr;
    }
1145
    else
1146 1147
    {
      WARN("file already exists\n");
1148
      return STG_E_FILEALREADYEXISTS;
1149
    }
1150
  }
1151 1152
  else if (!(This->openFlags & STGM_TRANSACTED) &&
           STGM_ACCESS_MODE(This->openFlags) == STGM_READ)
1153 1154 1155 1156
  {
    WARN("read-only storage\n");
    return STG_E_ACCESSDENIED;
  }
1157

1158
  memset(&newEntry, 0, sizeof(DirEntry));
1159

1160
  newEntry.sizeOfNameString = (lstrlenW(pwcsName)+1)*sizeof(WCHAR);
1161

1162
  if (newEntry.sizeOfNameString > DIRENTRY_NAME_BUFFER_LEN)
1163 1164
  {
    FIXME("name too long\n");
1165
    return STG_E_INVALIDNAME;
1166
  }
1167

1168
  strcpyW(newEntry.name, pwcsName);
1169

1170 1171 1172 1173
  newEntry.stgType       = STGTY_STORAGE;
  newEntry.startingBlock = BLOCK_END_OF_CHAIN;
  newEntry.size.u.LowPart  = 0;
  newEntry.size.u.HighPart = 0;
1174

1175 1176 1177
  newEntry.leftChild        = DIRENTRY_NULL;
  newEntry.rightChild       = DIRENTRY_NULL;
  newEntry.dirRootEntry     = DIRENTRY_NULL;
1178

1179
  /* call CoFileTime to get the current time
1180 1181
  newEntry.ctime
  newEntry.mtime
1182 1183
  */

1184
  /*  newEntry.clsid */
1185

1186
  /*
1187
   * Create a new directory entry for the storage
1188
   */
1189 1190 1191
  hr = StorageBaseImpl_CreateDirEntry(This, &newEntry, &newEntryRef);
  if (FAILED(hr))
    return hr;
1192

1193
  /*
1194
   * Insert the new directory entry into the parent storage's tree
1195
   */
1196
  hr = insertIntoTree(
1197
    This,
1198
    This->storageDirEntry,
1199
    newEntryRef);
1200 1201 1202 1203 1204
  if (FAILED(hr))
  {
    StorageBaseImpl_DestroyDirEntry(This, newEntryRef);
    return hr;
  }
1205

1206
  /*
1207 1208
   * Open it to get a pointer to return.
   */
1209
  hr = IStorage_OpenStorage(iface, pwcsName, 0, grfMode, 0, 0, ppstg);
1210 1211 1212 1213 1214 1215

  if( (hr != S_OK) || (*ppstg == NULL))
  {
    return hr;
  }

1216 1217
  if (SUCCEEDED(hr))
    hr = StorageBaseImpl_Flush(This);
1218

1219 1220 1221 1222 1223 1224 1225 1226
  return S_OK;
}


/***************************************************************************
 *
 * Internal Method
 *
1227
 * Reserve a directory entry in the file and initialize it.
1228
 */
1229 1230
static HRESULT StorageImpl_CreateDirEntry(
  StorageBaseImpl *base,
1231
  const DirEntry *newData,
1232
  DirRef *index)
1233
{
1234
  StorageImpl *storage = (StorageImpl*)base;
1235 1236
  ULONG       currentEntryIndex    = 0;
  ULONG       newEntryIndex        = DIRENTRY_NULL;
1237
  HRESULT hr = S_OK;
1238
  BYTE currentData[RAW_DIRENTRY_SIZE];
1239
  WORD sizeOfNameString;
1240 1241 1242

  do
  {
1243
    hr = StorageImpl_ReadRawDirEntry(storage,
1244
                                     currentEntryIndex,
1245
                                     currentData);
1246

1247
    if (SUCCEEDED(hr))
1248
    {
1249 1250 1251 1252 1253 1254
      StorageUtl_ReadWord(
        currentData,
        OFFSET_PS_NAMELENGTH,
        &sizeOfNameString);

      if (sizeOfNameString == 0)
1255
      {
1256
        /*
1257
         * The entry exists and is available, we found it.
1258
         */
1259
        newEntryIndex = currentEntryIndex;
1260 1261 1262 1263 1264
      }
    }
    else
    {
      /*
1265
       * We exhausted the directory entries, we will create more space below
1266
       */
1267
      newEntryIndex = currentEntryIndex;
1268
    }
1269
    currentEntryIndex++;
1270

1271
  } while (newEntryIndex == DIRENTRY_NULL);
1272

1273
  /*
1274
   * grow the directory stream
1275
   */
1276
  if (FAILED(hr))
1277
  {
1278
    BYTE           emptyData[RAW_DIRENTRY_SIZE];
1279
    ULARGE_INTEGER newSize;
1280 1281
    ULONG          entryIndex;
    ULONG          lastEntry     = 0;
1282 1283
    ULONG          blockCount    = 0;

1284
    /*
1285
     * obtain the new count of blocks in the directory stream
1286 1287
     */
    blockCount = BlockChainStream_GetCount(
1288
                   storage->rootBlockChain)+1;
1289

1290
    /*
1291
     * initialize the size used by the directory stream
1292
     */
1293 1294
    newSize.u.HighPart = 0;
    newSize.u.LowPart  = storage->bigBlockSize * blockCount;
1295

1296
    /*
1297
     * add a block to the directory stream
1298
     */
1299
    BlockChainStream_SetSize(storage->rootBlockChain, newSize);
1300

1301
    /*
1302 1303
     * memset the empty entry in order to initialize the unused newly
     * created entries
1304
     */
1305
    memset(emptyData, 0, RAW_DIRENTRY_SIZE);
1306

1307
    /*
1308 1309
     * initialize them
     */
1310
    lastEntry = storage->bigBlockSize / RAW_DIRENTRY_SIZE * blockCount;
1311

1312
    for(
1313 1314 1315
      entryIndex = newEntryIndex + 1;
      entryIndex < lastEntry;
      entryIndex++)
1316
    {
1317
      StorageImpl_WriteRawDirEntry(
1318
        storage,
1319
        entryIndex,
1320
        emptyData);
1321
    }
1322 1323

    StorageImpl_SaveFileHeader(storage);
1324 1325
  }

1326 1327
  UpdateRawDirEntry(currentData, newData);

1328
  hr = StorageImpl_WriteRawDirEntry(storage, newEntryIndex, currentData);
1329 1330

  if (SUCCEEDED(hr))
1331
    *index = newEntryIndex;
1332 1333

  return hr;
1334 1335
}

1336 1337 1338 1339 1340 1341
/***************************************************************************
 *
 * Internal Method
 *
 * Mark a directory entry in the file as free.
 */
1342 1343
static HRESULT StorageImpl_DestroyDirEntry(
  StorageBaseImpl *base,
1344
  DirRef index)
1345 1346
{
  HRESULT hr;
1347
  BYTE emptyData[RAW_DIRENTRY_SIZE];
1348
  StorageImpl *storage = (StorageImpl*)base;
1349

1350
  memset(emptyData, 0, RAW_DIRENTRY_SIZE);
1351 1352 1353 1354 1355 1356 1357

  hr = StorageImpl_WriteRawDirEntry(storage, index, emptyData);

  return hr;
}


1358 1359 1360 1361
/****************************************************************************
 *
 * Internal Method
 *
1362
 * Case insensitive comparison of DirEntry.name by first considering
1363 1364
 * their size.
 *
1365 1366 1367
 * Returns <0 when name1 < name2
 *         >0 when name1 > name2
 *          0 when name1 == name2
1368
 */
1369 1370 1371
static LONG entryNameCmp(
    const OLECHAR *name1,
    const OLECHAR *name2)
1372
{
1373
  LONG diff      = lstrlenW(name1) - lstrlenW(name2);
1374

1375
  while (diff == 0 && *name1 != 0)
1376
  {
1377
    /*
Francois Gouget's avatar
Francois Gouget committed
1378
     * We compare the string themselves only when they are of the same length
1379
     */
1380
    diff = toupperW(*name1++) - toupperW(*name2++);
1381 1382
  }

1383
  return diff;
1384 1385 1386 1387 1388 1389
}

/****************************************************************************
 *
 * Internal Method
 *
1390
 * Add a directory entry to a storage
1391
 */
1392
static HRESULT insertIntoTree(
1393
  StorageBaseImpl *This,
1394 1395
  DirRef        parentStorageIndex,
  DirRef        newEntryIndex)
1396
{
1397 1398
  DirEntry currentEntry;
  DirEntry newEntry;
1399 1400

  /*
1401
   * Read the inserted entry
1402
   */
1403 1404 1405
  StorageBaseImpl_ReadDirEntry(This,
                               newEntryIndex,
                               &newEntry);
1406 1407

  /*
1408
   * Read the storage entry
1409
   */
1410 1411 1412
  StorageBaseImpl_ReadDirEntry(This,
                               parentStorageIndex,
                               &currentEntry);
1413

1414
  if (currentEntry.dirRootEntry != DIRENTRY_NULL)
1415
  {
1416
    /*
1417 1418 1419
     * The root storage contains some element, therefore, start the research
     * for the appropriate location.
     */
1420
    BOOL found = 0;
1421
    DirRef current, next, previous, currentEntryId;
1422 1423

    /*
1424
     * Keep a reference to the root of the storage's element tree
1425
     */
1426
    currentEntryId = currentEntry.dirRootEntry;
1427 1428

    /*
1429
     * Read
1430
     */
1431 1432 1433
    StorageBaseImpl_ReadDirEntry(This,
                                 currentEntry.dirRootEntry,
                                 &currentEntry);
1434

1435 1436 1437
    previous = currentEntry.leftChild;
    next     = currentEntry.rightChild;
    current  = currentEntryId;
1438 1439 1440

    while (found == 0)
    {
1441
      LONG diff = entryNameCmp( newEntry.name, currentEntry.name);
1442

1443 1444
      if (diff < 0)
      {
1445
        if (previous != DIRENTRY_NULL)
1446
        {
1447 1448 1449
          StorageBaseImpl_ReadDirEntry(This,
                                       previous,
                                       &currentEntry);
1450 1451 1452 1453
          current = previous;
        }
        else
        {
1454
          currentEntry.leftChild = newEntryIndex;
1455 1456 1457
          StorageBaseImpl_WriteDirEntry(This,
                                        current,
                                        &currentEntry);
1458 1459 1460
          found = 1;
        }
      }
1461
      else if (diff > 0)
1462
      {
1463
        if (next != DIRENTRY_NULL)
1464
        {
1465 1466 1467
          StorageBaseImpl_ReadDirEntry(This,
                                       next,
                                       &currentEntry);
1468 1469 1470 1471
          current = next;
        }
        else
        {
1472
          currentEntry.rightChild = newEntryIndex;
1473 1474 1475
          StorageBaseImpl_WriteDirEntry(This,
                                        current,
                                        &currentEntry);
1476 1477 1478
          found = 1;
        }
      }
1479 1480 1481 1482 1483 1484
      else
      {
	/*
	 * Trying to insert an item with the same name in the
	 * subtree structure.
	 */
1485
	return STG_E_FILEALREADYEXISTS;
1486
      }
1487

1488 1489
      previous = currentEntry.leftChild;
      next     = currentEntry.rightChild;
1490 1491 1492 1493
    }
  }
  else
  {
1494
    /*
1495
     * The storage is empty, make the new entry the root of its element tree
1496
     */
1497
    currentEntry.dirRootEntry = newEntryIndex;
1498 1499 1500
    StorageBaseImpl_WriteDirEntry(This,
                                  parentStorageIndex,
                                  &currentEntry);
1501
  }
1502 1503

  return S_OK;
1504 1505
}

1506 1507 1508 1509 1510 1511
/****************************************************************************
 *
 * Internal Method
 *
 * Find and read the element of a storage with the given name.
 */
1512
static DirRef findElement(StorageBaseImpl *storage, DirRef storageEntry,
1513
    const OLECHAR *name, DirEntry *data)
1514
{
1515
  DirRef currentEntry;
1516 1517

  /* Read the storage entry to find the root of the tree. */
1518
  StorageBaseImpl_ReadDirEntry(storage, storageEntry, data);
1519

1520
  currentEntry = data->dirRootEntry;
1521

1522
  while (currentEntry != DIRENTRY_NULL)
1523 1524 1525
  {
    LONG cmp;

1526
    StorageBaseImpl_ReadDirEntry(storage, currentEntry, data);
1527

1528
    cmp = entryNameCmp(name, data->name);
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

    if (cmp == 0)
      /* found it */
      break;

    else if (cmp < 0)
      currentEntry = data->leftChild;

    else if (cmp > 0)
      currentEntry = data->rightChild;
  }

  return currentEntry;
}

1544 1545 1546 1547 1548 1549 1550 1551 1552
/****************************************************************************
 *
 * Internal Method
 *
 * Find and read the binary tree parent of the element with the given name.
 *
 * If there is no such element, find a place where it could be inserted and
 * return STG_E_FILENOTFOUND.
 */
1553
static HRESULT findTreeParent(StorageBaseImpl *storage, DirRef storageEntry,
1554
    const OLECHAR *childName, DirEntry *parentData, DirRef *parentEntry,
1555 1556
    ULONG *relation)
{
1557
  DirRef childEntry;
1558
  DirEntry childData;
1559 1560

  /* Read the storage entry to find the root of the tree. */
1561
  StorageBaseImpl_ReadDirEntry(storage, storageEntry, parentData);
1562 1563

  *parentEntry = storageEntry;
1564
  *relation = DIRENTRY_RELATION_DIR;
1565

1566
  childEntry = parentData->dirRootEntry;
1567

1568
  while (childEntry != DIRENTRY_NULL)
1569 1570 1571
  {
    LONG cmp;

1572
    StorageBaseImpl_ReadDirEntry(storage, childEntry, &childData);
1573

1574
    cmp = entryNameCmp(childName, childData.name);
1575 1576 1577 1578 1579 1580 1581 1582 1583

    if (cmp == 0)
      /* found it */
      break;

    else if (cmp < 0)
    {
      *parentData = childData;
      *parentEntry = childEntry;
1584
      *relation = DIRENTRY_RELATION_PREVIOUS;
1585 1586 1587 1588 1589 1590 1591 1592

      childEntry = parentData->leftChild;
    }

    else if (cmp > 0)
    {
      *parentData = childData;
      *parentEntry = childEntry;
1593
      *relation = DIRENTRY_RELATION_NEXT;
1594 1595 1596 1597 1598

      childEntry = parentData->rightChild;
    }
  }

1599
  if (childEntry == DIRENTRY_NULL)
1600 1601 1602 1603 1604
    return STG_E_FILENOTFOUND;
  else
    return S_OK;
}

1605

1606 1607 1608
static HRESULT StorageBaseImpl_CopyStorageEntryTo(StorageBaseImpl *This,
    DirRef srcEntry, BOOL skip_storage, BOOL skip_stream,
    SNB snbExclude, IStorage *pstgDest);
1609

1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
static HRESULT StorageBaseImpl_CopyChildEntryTo(StorageBaseImpl *This,
    DirRef srcEntry, BOOL skip_storage, BOOL skip_stream,
    SNB snbExclude, IStorage *pstgDest)
{
  DirEntry data;
  HRESULT hr;
  BOOL skip = FALSE;
  IStorage *pstgTmp;
  IStream *pstrChild, *pstrTmp;
  STATSTG strStat;
1620

1621 1622
  if (srcEntry == DIRENTRY_NULL)
    return S_OK;
1623

1624
  hr = StorageBaseImpl_ReadDirEntry( This, srcEntry, &data );
1625

1626
  if (FAILED(hr))
1627 1628
    return hr;

1629
  if ( snbExclude )
1630
  {
1631
    WCHAR **snb = snbExclude;
1632

1633
    while ( *snb != NULL && !skip )
1634
    {
1635 1636 1637
      if ( lstrcmpW(data.name, *snb) == 0 )
        skip = TRUE;
      ++snb;
1638
    }
1639
  }
1640

1641 1642 1643
  if (!skip)
  {
    if (data.stgType == STGTY_STORAGE && !skip_storage)
1644 1645 1646 1647
    {
      /*
       * create a new storage in destination storage
       */
1648
      hr = IStorage_CreateStorage( pstgDest, data.name,
1649
                                   STGM_FAILIFTHERE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,
1650
                                   0, 0,
1651
                                   &pstgTmp );
1652

1653 1654 1655 1656 1657
      /*
       * if it already exist, don't create a new one use this one
       */
      if (hr == STG_E_FILEALREADYEXISTS)
      {
1658
        hr = IStorage_OpenStorage( pstgDest, data.name, NULL,
1659 1660 1661
                                   STGM_WRITE|STGM_SHARE_EXCLUSIVE,
                                   NULL, 0, &pstgTmp );
      }
1662

1663
      if (SUCCEEDED(hr))
1664
      {
1665 1666
        hr = StorageBaseImpl_CopyStorageEntryTo( This, srcEntry, skip_storage,
                                                 skip_stream, NULL, pstgTmp );
1667

1668
        IStorage_Release(pstgTmp);
1669
      }
1670
    }
1671
    else if (data.stgType == STGTY_STREAM && !skip_stream)
1672 1673 1674 1675 1676
    {
      /*
       * create a new stream in destination storage. If the stream already
       * exist, it will be deleted and a new one will be created.
       */
1677
      hr = IStorage_CreateStream( pstgDest, data.name,
1678 1679 1680 1681
                                  STGM_CREATE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,
                                  0, 0, &pstrTmp );

      /*
1682 1683
       * open child stream storage. This operation must succeed even if the
       * stream is already open, so we use internal functions to do it.
1684
       */
1685 1686
      if (hr == S_OK)
      {
1687
        pstrChild = (IStream*)StgStreamImpl_Construct(This, STGM_READ|STGM_SHARE_EXCLUSIVE, srcEntry);
1688 1689 1690 1691 1692
        if (pstrChild)
          IStream_AddRef(pstrChild);
        else
          hr = E_OUTOFMEMORY;
      }
1693

1694 1695 1696 1697 1698 1699
      if (hr == S_OK)
      {
        /*
         * Get the size of the source stream
         */
        IStream_Stat( pstrChild, &strStat, STATFLAG_NONAME );
1700

1701 1702 1703 1704
        /*
         * Set the size of the destination stream.
         */
        IStream_SetSize(pstrTmp, strStat.cbSize);
1705

1706 1707 1708 1709 1710
        /*
         * do the copy
         */
        hr = IStream_CopyTo( pstrChild, pstrTmp, strStat.cbSize,
                             NULL, NULL );
1711

1712 1713
        IStream_Release( pstrChild );
      }
1714

1715 1716
      IStream_Release( pstrTmp );
    }
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
  }

  /* copy siblings */
  if (SUCCEEDED(hr))
    hr = StorageBaseImpl_CopyChildEntryTo( This, data.leftChild, skip_storage,
                                           skip_stream, snbExclude, pstgDest );

  if (SUCCEEDED(hr))
    hr = StorageBaseImpl_CopyChildEntryTo( This, data.rightChild, skip_storage,
                                           skip_stream, snbExclude, pstgDest );

  return hr;
}

static HRESULT StorageBaseImpl_CopyStorageEntryTo(StorageBaseImpl *This,
    DirRef srcEntry, BOOL skip_storage, BOOL skip_stream,
    SNB snbExclude, IStorage *pstgDest)
{
  DirEntry data;
  HRESULT hr;

  hr = StorageBaseImpl_ReadDirEntry( This, srcEntry, &data );

  if (SUCCEEDED(hr))
    hr = IStorage_SetClass( pstgDest, &data.clsid );

  if (SUCCEEDED(hr))
    hr = StorageBaseImpl_CopyChildEntryTo( This, data.dirRootEntry, skip_storage,
      skip_stream, snbExclude, pstgDest );

  return hr;
}

/*************************************************************************
 * CopyTo (IStorage)
 */
static HRESULT WINAPI StorageBaseImpl_CopyTo(
  IStorage*   iface,
  DWORD       ciidExclude,  /* [in] */
  const IID*  rgiidExclude, /* [size_is][unique][in] */
  SNB         snbExclude,   /* [unique][in] */
  IStorage*   pstgDest)     /* [unique][in] */
{
  StorageBaseImpl* const This=(StorageBaseImpl*)iface;

  BOOL         skip_storage = FALSE, skip_stream = FALSE;
  int          i;

  TRACE("(%p, %d, %p, %p, %p)\n",
	iface, ciidExclude, rgiidExclude,
	snbExclude, pstgDest);

  if ( pstgDest == 0 )
    return STG_E_INVALIDPOINTER;

  for(i = 0; i < ciidExclude; ++i)
  {
    if(IsEqualGUID(&IID_IStorage, &rgiidExclude[i]))
        skip_storage = TRUE;
    else if(IsEqualGUID(&IID_IStream, &rgiidExclude[i]))
        skip_stream = TRUE;
1778
    else
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
        WARN("Unknown excluded GUID: %s\n", debugstr_guid(&rgiidExclude[i]));
  }

  if (!skip_storage)
  {
    /* Give up early if it looks like this would be infinitely recursive.
     * Oddly enough, this includes some cases that aren't really recursive, like
     * copying to a transacted child. */
    IStorage *pstgDestAncestor = pstgDest;
    IStorage *pstgDestAncestorChild = NULL;

    /* Go up the chain from the destination until we find the source storage. */
    while (pstgDestAncestor != iface) {
      pstgDestAncestorChild = pstgDest;

      if (pstgDestAncestor->lpVtbl == &TransactedSnapshotImpl_Vtbl)
      {
        TransactedSnapshotImpl *impl = (TransactedSnapshotImpl*) pstgDestAncestor;

        pstgDestAncestor = (IStorage*)impl->transactedParent;
      }
      else if (pstgDestAncestor->lpVtbl == &Storage32InternalImpl_Vtbl)
      {
        StorageInternalImpl *impl = (StorageInternalImpl*) pstgDestAncestor;

        pstgDestAncestor = (IStorage*)impl->parentStorage;
      }
      else
        break;
1808 1809
    }

1810 1811 1812
    if (pstgDestAncestor == iface)
    {
      BOOL fail = TRUE;
1813

1814 1815 1816 1817 1818
      if (pstgDestAncestorChild && snbExclude)
      {
        StorageBaseImpl *ancestorChildBase = (StorageBaseImpl*)pstgDestAncestorChild;
        DirEntry data;
        WCHAR **snb = snbExclude;
1819

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
        StorageBaseImpl_ReadDirEntry(ancestorChildBase, ancestorChildBase->storageDirEntry, &data);

        while ( *snb != NULL && fail )
        {
          if ( lstrcmpW(data.name, *snb) == 0 )
            fail = FALSE;
          ++snb;
        }
      }

      if (fail)
        return STG_E_ACCESSDENIED;
    }
  }

  return StorageBaseImpl_CopyStorageEntryTo( This, This->storageDirEntry,
    skip_storage, skip_stream, snbExclude, pstgDest );
1837
}
1838

1839 1840 1841
/*************************************************************************
 * MoveElementTo (IStorage)
 */
1842
static HRESULT WINAPI StorageBaseImpl_MoveElementTo(
1843
  IStorage*     iface,
1844 1845 1846 1847
  const OLECHAR *pwcsName,   /* [string][in] */
  IStorage      *pstgDest,   /* [unique][in] */
  const OLECHAR *pwcsNewName,/* [string][in] */
  DWORD           grfFlags)    /* [in] */
1848
{
1849
  FIXME("(%p %s %p %s %u): stub\n", iface,
1850 1851
         debugstr_w(pwcsName), pstgDest,
         debugstr_w(pwcsNewName), grfFlags);
1852 1853
  return E_NOTIMPL;
}
1854

1855 1856
/*************************************************************************
 * Commit (IStorage)
1857 1858 1859 1860
 *
 * Ensures that any changes made to a storage object open in transacted mode
 * are reflected in the parent storage
 *
1861
 * In a non-transacted mode, this ensures all cached writes are completed.
1862
 */
1863
static HRESULT WINAPI StorageImpl_Commit(
1864
  IStorage*   iface,
1865
  DWORD         grfCommitFlags)/* [in] */
1866
{
1867 1868 1869
  StorageBaseImpl* const base=(StorageBaseImpl*)iface;
  TRACE("(%p %d)\n", iface, grfCommitFlags);
  return StorageBaseImpl_Flush(base);
1870
}
1871

1872 1873
/*************************************************************************
 * Revert (IStorage)
1874 1875
 *
 * Discard all changes that have been made since the last commit operation
1876
 */
1877
static HRESULT WINAPI StorageImpl_Revert(
1878
  IStorage* iface)
1879
{
1880 1881
  TRACE("(%p)\n", iface);
  return S_OK;
1882 1883 1884
}

/*************************************************************************
1885
 * DestroyElement (IStorage)
1886
 *
1887 1888
 * Strategy: This implementation is built this way for simplicity not for speed.
 *          I always delete the topmost element of the enumeration and adjust
1889 1890
 *          the deleted element pointer all the time.  This takes longer to
 *          do but allow to reinvoke DestroyElement whenever we encounter a
1891 1892
 *          storage object.  The optimisation resides in the usage of another
 *          enumeration strategy that would give all the leaves of a storage
1893 1894
 *          first. (postfix order)
 */
1895
static HRESULT WINAPI StorageBaseImpl_DestroyElement(
1896
  IStorage*     iface,
1897
  const OLECHAR *pwcsName)/* [string][in] */
1898
{
1899
  StorageBaseImpl* const This=(StorageBaseImpl*)iface;
1900

1901
  HRESULT           hr = S_OK;
1902
  DirEntry          entryToDelete;
1903
  DirRef            entryToDeleteRef;
1904

1905
  TRACE("(%p, %s)\n",
1906 1907
	iface, debugstr_w(pwcsName));

1908
  if (pwcsName==NULL)
1909
    return STG_E_INVALIDPOINTER;
1910

1911
  if (This->reverted)
1912 1913
    return STG_E_REVERTED;

1914 1915
  if ( !(This->openFlags & STGM_TRANSACTED) &&
       STGM_ACCESS_MODE( This->openFlags ) == STGM_READ )
1916 1917
    return STG_E_ACCESSDENIED;

1918
  entryToDeleteRef = findElement(
1919
    This,
1920
    This->storageDirEntry,
1921
    pwcsName,
1922
    &entryToDelete);
1923

1924
  if ( entryToDeleteRef == DIRENTRY_NULL )
1925 1926 1927 1928
  {
    return STG_E_FILENOTFOUND;
  }

1929
  if ( entryToDelete.stgType == STGTY_STORAGE )
1930
  {
1931
    hr = deleteStorageContents(
1932
           This,
1933 1934
           entryToDeleteRef,
           entryToDelete);
1935
  }
1936
  else if ( entryToDelete.stgType == STGTY_STREAM )
1937
  {
1938
    hr = deleteStreamContents(
1939
           This,
1940 1941
           entryToDeleteRef,
           entryToDelete);
1942 1943
  }

1944
  if (hr!=S_OK)
1945 1946 1947
    return hr;

  /*
1948
   * Remove the entry from its parent storage
1949
   */
1950
  hr = removeFromTree(
1951
        This,
1952
        This->storageDirEntry,
1953
        entryToDeleteRef);
1954

1955
  /*
1956
   * Invalidate the entry
1957
   */
1958
  if (SUCCEEDED(hr))
1959
    StorageBaseImpl_DestroyDirEntry(This, entryToDeleteRef);
1960

1961 1962 1963
  if (SUCCEEDED(hr))
    hr = StorageBaseImpl_Flush(This);

1964 1965 1966 1967
  return hr;
}


1968
/******************************************************************************
1969
 * Internal stream list handlers
1970 1971
 */

1972
void StorageBaseImpl_AddStream(StorageBaseImpl * stg, StgStreamImpl * strm)
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
{
  TRACE("Stream added (stg=%p strm=%p)\n", stg, strm);
  list_add_tail(&stg->strmHead,&strm->StrmListEntry);
}

void StorageBaseImpl_RemoveStream(StorageBaseImpl * stg, StgStreamImpl * strm)
{
  TRACE("Stream removed (stg=%p strm=%p)\n", stg,strm);
  list_remove(&(strm->StrmListEntry));
}

1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
static BOOL StorageBaseImpl_IsStreamOpen(StorageBaseImpl * stg, DirRef streamEntry)
{
  StgStreamImpl *strm;

  LIST_FOR_EACH_ENTRY(strm, &stg->strmHead, StgStreamImpl, StrmListEntry)
  {
    if (strm->dirEntry == streamEntry)
    {
      return TRUE;
    }
  }

  return FALSE;
}

1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
static BOOL StorageBaseImpl_IsStorageOpen(StorageBaseImpl * stg, DirRef storageEntry)
{
  StorageInternalImpl *childstg;

  LIST_FOR_EACH_ENTRY(childstg, &stg->storageHead, StorageInternalImpl, ParentListEntry)
  {
    if (childstg->base.storageDirEntry == storageEntry)
    {
      return TRUE;
    }
  }

  return FALSE;
}

2014
static void StorageBaseImpl_DeleteAll(StorageBaseImpl * stg)
2015 2016 2017
{
  struct list *cur, *cur2;
  StgStreamImpl *strm=NULL;
2018
  StorageInternalImpl *childstg=NULL;
2019 2020 2021

  LIST_FOR_EACH_SAFE(cur, cur2, &stg->strmHead) {
    strm = LIST_ENTRY(cur,StgStreamImpl,StrmListEntry);
2022
    TRACE("Streams invalidated (stg=%p strm=%p next=%p prev=%p)\n", stg,strm,cur->next,cur->prev);
2023
    strm->parentStorage = NULL;
2024 2025
    list_remove(cur);
  }
2026 2027 2028

  LIST_FOR_EACH_SAFE(cur, cur2, &stg->storageHead) {
    childstg = LIST_ENTRY(cur,StorageInternalImpl,ParentListEntry);
2029
    StorageBaseImpl_Invalidate( &childstg->base );
2030
  }
2031 2032 2033 2034 2035 2036 2037

  if (stg->transactedChild)
  {
    StorageBaseImpl_Invalidate(stg->transactedChild);

    stg->transactedChild = NULL;
  }
2038
}
2039 2040


2041 2042 2043 2044
/*********************************************************************
 *
 * Internal Method
 *
2045
 * Delete the contents of a storage entry.
2046 2047
 *
 */
2048
static HRESULT deleteStorageContents(
2049
  StorageBaseImpl *parentStorage,
2050
  DirRef       indexToDelete,
2051
  DirEntry     entryDataToDelete)
2052 2053
{
  IEnumSTATSTG *elements     = 0;
2054
  IStorage   *childStorage = 0;
2055 2056 2057
  STATSTG      currentElement;
  HRESULT      hr;
  HRESULT      destroyHr = S_OK;
2058 2059 2060 2061 2062 2063 2064
  StorageInternalImpl *stg, *stg2;

  /* Invalidate any open storage objects. */
  LIST_FOR_EACH_ENTRY_SAFE(stg, stg2, &parentStorage->storageHead, StorageInternalImpl, ParentListEntry)
  {
    if (stg->base.storageDirEntry == indexToDelete)
    {
2065
      StorageBaseImpl_Invalidate(&stg->base);
2066 2067
    }
  }
2068 2069 2070 2071

  /*
   * Open the storage and enumerate it
   */
2072 2073
  hr = StorageBaseImpl_OpenStorage(
        (IStorage*)parentStorage,
2074
        entryDataToDelete.name,
2075
        0,
2076
        STGM_WRITE | STGM_SHARE_EXCLUSIVE,
2077 2078 2079 2080 2081 2082 2083 2084 2085
        0,
        0,
        &childStorage);

  if (hr != S_OK)
  {
    return hr;
  }

2086
  /*
2087 2088
   * Enumerate the elements
   */
2089
  IStorage_EnumElements( childStorage, 0, 0, 0, &elements);
2090 2091 2092 2093 2094 2095 2096 2097 2098

  do
  {
    /*
     * Obtain the next element
     */
    hr = IEnumSTATSTG_Next(elements, 1, &currentElement, NULL);
    if (hr==S_OK)
    {
2099
      destroyHr = IStorage_DestroyElement(childStorage, currentElement.pwcsName);
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111

      CoTaskMemFree(currentElement.pwcsName);
    }

    /*
     * We need to Reset the enumeration every time because we delete elements
     * and the enumeration could be invalid
     */
    IEnumSTATSTG_Reset(elements);

  } while ((hr == S_OK) && (destroyHr == S_OK));

2112
  IStorage_Release(childStorage);
2113
  IEnumSTATSTG_Release(elements);
2114

2115 2116 2117 2118 2119 2120 2121
  return destroyHr;
}

/*********************************************************************
 *
 * Internal Method
 *
2122
 * Perform the deletion of a stream's data
2123 2124
 *
 */
2125
static HRESULT deleteStreamContents(
2126
  StorageBaseImpl *parentStorage,
2127
  DirRef        indexToDelete,
2128
  DirEntry      entryDataToDelete)
2129
{
2130
  IStream      *pis;
2131 2132
  HRESULT        hr;
  ULARGE_INTEGER size;
2133
  StgStreamImpl *strm, *strm2;
2134 2135

  /* Invalidate any open stream objects. */
2136
  LIST_FOR_EACH_ENTRY_SAFE(strm, strm2, &parentStorage->strmHead, StgStreamImpl, StrmListEntry)
2137 2138 2139 2140 2141 2142 2143 2144
  {
    if (strm->dirEntry == indexToDelete)
    {
      TRACE("Stream deleted %p\n", strm);
      strm->parentStorage = NULL;
      list_remove(&strm->StrmListEntry);
    }
  }
2145

2146 2147
  size.u.HighPart = 0;
  size.u.LowPart = 0;
2148

2149
  hr = StorageBaseImpl_OpenStream((IStorage*)parentStorage,
2150
        entryDataToDelete.name, NULL, STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &pis);
2151

2152 2153 2154 2155 2156
  if (hr!=S_OK)
  {
    return(hr);
  }

2157 2158 2159 2160
  /*
   * Zap the stream
   */
  hr = IStream_SetSize(pis, size);
2161 2162 2163 2164 2165 2166

  if(hr != S_OK)
  {
    return hr;
  }

2167 2168 2169 2170 2171
  /*
   * Release the stream object.
   */
  IStream_Release(pis);

2172 2173 2174
  return S_OK;
}

2175
static void setEntryLink(DirEntry *entry, ULONG relation, DirRef new_target)
2176
{
2177
  switch (relation)
2178
  {
2179
    case DIRENTRY_RELATION_PREVIOUS:
2180
      entry->leftChild = new_target;
2181
      break;
2182
    case DIRENTRY_RELATION_NEXT:
2183
      entry->rightChild = new_target;
2184
      break;
2185
    case DIRENTRY_RELATION_DIR:
2186
      entry->dirRootEntry = new_target;
2187 2188 2189
      break;
    default:
      assert(0);
2190 2191 2192 2193 2194 2195 2196
  }
}

/*************************************************************************
 *
 * Internal Method
 *
2197 2198
 * This method removes a directory entry from its parent storage tree without
 * freeing any resources attached to it.
2199
 */
2200
static HRESULT removeFromTree(
2201
  StorageBaseImpl *This,
2202 2203
  DirRef        parentStorageIndex,
  DirRef        deletedIndex)
2204 2205
{
  HRESULT hr                     = S_OK;
2206 2207
  DirEntry   entryToDelete;
  DirEntry   parentEntry;
2208
  DirRef parentEntryRef;
2209 2210
  ULONG typeOfRelation;

2211
  hr = StorageBaseImpl_ReadDirEntry(This, deletedIndex, &entryToDelete);
2212 2213 2214

  if (hr != S_OK)
    return hr;
2215 2216

  /*
2217
   * Find the element that links to the one we want to delete.
2218
   */
2219 2220
  hr = findTreeParent(This, parentStorageIndex, entryToDelete.name,
    &parentEntry, &parentEntryRef, &typeOfRelation);
2221 2222 2223

  if (hr != S_OK)
    return hr;
2224

2225
  if (entryToDelete.leftChild != DIRENTRY_NULL)
2226
  {
2227 2228 2229
    /*
     * Replace the deleted entry with its left child
     */
2230
    setEntryLink(&parentEntry, typeOfRelation, entryToDelete.leftChild);
2231

2232
    hr = StorageBaseImpl_WriteDirEntry(
2233
            This,
2234 2235
            parentEntryRef,
            &parentEntry);
2236
    if(FAILED(hr))
2237
    {
2238
      return hr;
2239
    }
2240

2241
    if (entryToDelete.rightChild != DIRENTRY_NULL)
2242
    {
2243
      /*
2244 2245 2246
       * We need to reinsert the right child somewhere. We already know it and
       * its children are greater than everything in the left tree, so we
       * insert it at the rightmost point in the left tree.
2247
       */
2248
      DirRef newRightChildParent = entryToDelete.leftChild;
2249
      DirEntry newRightChildParentEntry;
2250 2251 2252

      do
      {
2253
        hr = StorageBaseImpl_ReadDirEntry(
2254
                This,
2255
                newRightChildParent,
2256
                &newRightChildParentEntry);
2257
        if (FAILED(hr))
2258
        {
2259
          return hr;
2260 2261
        }

2262 2263 2264
        if (newRightChildParentEntry.rightChild != DIRENTRY_NULL)
          newRightChildParent = newRightChildParentEntry.rightChild;
      } while (newRightChildParentEntry.rightChild != DIRENTRY_NULL);
2265

2266
      newRightChildParentEntry.rightChild = entryToDelete.rightChild;
2267

2268
      hr = StorageBaseImpl_WriteDirEntry(
2269
              This,
2270
              newRightChildParent,
2271
              &newRightChildParentEntry);
2272
      if (FAILED(hr))
2273
      {
2274
        return hr;
2275
      }
2276
    }
2277
  }
2278
  else
2279
  {
2280
    /*
2281
     * Replace the deleted entry with its right child
2282
     */
2283
    setEntryLink(&parentEntry, typeOfRelation, entryToDelete.rightChild);
2284

2285
    hr = StorageBaseImpl_WriteDirEntry(
2286
            This,
2287 2288
            parentEntryRef,
            &parentEntry);
2289
    if(FAILED(hr))
2290
    {
2291
      return hr;
2292
    }
2293 2294 2295 2296 2297 2298
  }

  return hr;
}


2299 2300 2301
/******************************************************************************
 * SetElementTimes (IStorage)
 */
2302
static HRESULT WINAPI StorageBaseImpl_SetElementTimes(
2303
  IStorage*     iface,
2304 2305 2306 2307
  const OLECHAR *pwcsName,/* [string][in] */
  const FILETIME  *pctime,  /* [in] */
  const FILETIME  *patime,  /* [in] */
  const FILETIME  *pmtime)  /* [in] */
2308
{
2309 2310
  FIXME("(%s,...), stub!\n",debugstr_w(pwcsName));
  return S_OK;
2311 2312
}

2313 2314 2315
/******************************************************************************
 * SetStateBits (IStorage)
 */
2316
static HRESULT WINAPI StorageBaseImpl_SetStateBits(
2317
  IStorage*   iface,
2318 2319
  DWORD         grfStateBits,/* [in] */
  DWORD         grfMask)     /* [in] */
2320
{
2321
  StorageBaseImpl* const This = (StorageBaseImpl*)iface;
2322

2323
  if (This->reverted)
2324 2325
    return STG_E_REVERTED;

2326
  This->stateBits = (This->stateBits & ~grfMask) | (grfStateBits & grfMask);
2327
  return S_OK;
2328 2329
}

2330 2331 2332 2333 2334 2335 2336
static HRESULT StorageImpl_BaseWriteDirEntry(StorageBaseImpl *base,
  DirRef index, const DirEntry *data)
{
  StorageImpl *This = (StorageImpl*)base;
  return StorageImpl_WriteDirEntry(This, index, data);
}

2337 2338 2339 2340 2341 2342 2343
static HRESULT StorageImpl_BaseReadDirEntry(StorageBaseImpl *base,
  DirRef index, DirEntry *data)
{
  StorageImpl *This = (StorageImpl*)base;
  return StorageImpl_ReadDirEntry(This, index, data);
}

2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
static BlockChainStream **StorageImpl_GetFreeBlockChainCacheEntry(StorageImpl* This)
{
  int i;

  for (i=0; i<BLOCKCHAIN_CACHE_SIZE; i++)
  {
    if (!This->blockChainCache[i])
    {
      return &This->blockChainCache[i];
    }
  }

  i = This->blockChainToEvict;

  BlockChainStream_Destroy(This->blockChainCache[i]);
  This->blockChainCache[i] = NULL;

  This->blockChainToEvict++;
  if (This->blockChainToEvict == BLOCKCHAIN_CACHE_SIZE)
    This->blockChainToEvict = 0;

  return &This->blockChainCache[i];
}

static BlockChainStream **StorageImpl_GetCachedBlockChainStream(StorageImpl *This,
    DirRef index)
{
  int i, free_index=-1;

  for (i=0; i<BLOCKCHAIN_CACHE_SIZE; i++)
  {
    if (!This->blockChainCache[i])
    {
      if (free_index == -1) free_index = i;
    }
    else if (This->blockChainCache[i]->ownerDirEntry == index)
    {
      return &This->blockChainCache[i];
    }
  }

  if (free_index == -1)
  {
    free_index = This->blockChainToEvict;

    BlockChainStream_Destroy(This->blockChainCache[free_index]);
    This->blockChainCache[free_index] = NULL;

    This->blockChainToEvict++;
    if (This->blockChainToEvict == BLOCKCHAIN_CACHE_SIZE)
      This->blockChainToEvict = 0;
  }

  This->blockChainCache[free_index] = BlockChainStream_Construct(This, NULL, index);
  return &This->blockChainCache[free_index];
}

2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
static void StorageImpl_DeleteCachedBlockChainStream(StorageImpl *This, DirRef index)
{
  int i;

  for (i=0; i<BLOCKCHAIN_CACHE_SIZE; i++)
  {
    if (This->blockChainCache[i] && This->blockChainCache[i]->ownerDirEntry == index)
    {
      BlockChainStream_Destroy(This->blockChainCache[i]);
      This->blockChainCache[i] = NULL;
      return;
    }
  }
}

2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
static HRESULT StorageImpl_StreamReadAt(StorageBaseImpl *base, DirRef index,
  ULARGE_INTEGER offset, ULONG size, void *buffer, ULONG *bytesRead)
{
  StorageImpl *This = (StorageImpl*)base;
  DirEntry data;
  HRESULT hr;
  ULONG bytesToRead;

  hr = StorageImpl_ReadDirEntry(This, index, &data);
  if (FAILED(hr)) return hr;

  if (data.size.QuadPart == 0)
  {
    *bytesRead = 0;
    return S_OK;
  }

  if (offset.QuadPart + size > data.size.QuadPart)
  {
    bytesToRead = data.size.QuadPart - offset.QuadPart;
  }
  else
  {
    bytesToRead = size;
  }

  if (data.size.QuadPart < LIMIT_TO_USE_SMALL_BLOCK)
  {
    SmallBlockChainStream *stream;

    stream = SmallBlockChainStream_Construct(This, NULL, index);
    if (!stream) return E_OUTOFMEMORY;

    hr = SmallBlockChainStream_ReadAt(stream, offset, bytesToRead, buffer, bytesRead);

    SmallBlockChainStream_Destroy(stream);

    return hr;
  }
  else
  {
2457
    BlockChainStream *stream = NULL;
2458

2459
    stream = *StorageImpl_GetCachedBlockChainStream(This, index);
2460 2461 2462 2463 2464 2465 2466 2467
    if (!stream) return E_OUTOFMEMORY;

    hr = BlockChainStream_ReadAt(stream, offset, bytesToRead, buffer, bytesRead);

    return hr;
  }
}

2468 2469 2470 2471 2472 2473 2474
static HRESULT StorageImpl_StreamSetSize(StorageBaseImpl *base, DirRef index,
  ULARGE_INTEGER newsize)
{
  StorageImpl *This = (StorageImpl*)base;
  DirEntry data;
  HRESULT hr;
  SmallBlockChainStream *smallblock=NULL;
2475
  BlockChainStream **pbigblock=NULL, *bigblock=NULL;
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496

  hr = StorageImpl_ReadDirEntry(This, index, &data);
  if (FAILED(hr)) return hr;

  /* In simple mode keep the stream size above the small block limit */
  if (This->base.openFlags & STGM_SIMPLE)
    newsize.QuadPart = max(newsize.QuadPart, LIMIT_TO_USE_SMALL_BLOCK);

  if (data.size.QuadPart == newsize.QuadPart)
    return S_OK;

  /* Create a block chain object of the appropriate type */
  if (data.size.QuadPart == 0)
  {
    if (newsize.QuadPart < LIMIT_TO_USE_SMALL_BLOCK)
    {
      smallblock = SmallBlockChainStream_Construct(This, NULL, index);
      if (!smallblock) return E_OUTOFMEMORY;
    }
    else
    {
2497 2498
      pbigblock = StorageImpl_GetCachedBlockChainStream(This, index);
      bigblock = *pbigblock;
2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
      if (!bigblock) return E_OUTOFMEMORY;
    }
  }
  else if (data.size.QuadPart < LIMIT_TO_USE_SMALL_BLOCK)
  {
    smallblock = SmallBlockChainStream_Construct(This, NULL, index);
    if (!smallblock) return E_OUTOFMEMORY;
  }
  else
  {
2509 2510
    pbigblock = StorageImpl_GetCachedBlockChainStream(This, index);
    bigblock = *pbigblock;
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
    if (!bigblock) return E_OUTOFMEMORY;
  }

  /* Change the block chain type if necessary. */
  if (smallblock && newsize.QuadPart >= LIMIT_TO_USE_SMALL_BLOCK)
  {
    bigblock = Storage32Impl_SmallBlocksToBigBlocks(This, &smallblock);
    if (!bigblock)
    {
      SmallBlockChainStream_Destroy(smallblock);
      return E_FAIL;
    }
2523 2524 2525

    pbigblock = StorageImpl_GetFreeBlockChainCacheEntry(This);
    *pbigblock = bigblock;
2526 2527 2528
  }
  else if (bigblock && newsize.QuadPart < LIMIT_TO_USE_SMALL_BLOCK)
  {
2529
    smallblock = Storage32Impl_BigBlocksToSmallBlocks(This, pbigblock, newsize);
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
    if (!smallblock)
      return E_FAIL;
  }

  /* Set the size of the block chain. */
  if (smallblock)
  {
    SmallBlockChainStream_SetSize(smallblock, newsize);
    SmallBlockChainStream_Destroy(smallblock);
  }
  else
  {
    BlockChainStream_SetSize(bigblock, newsize);
  }

  /* Set the size in the directory entry. */
  hr = StorageImpl_ReadDirEntry(This, index, &data);
  if (SUCCEEDED(hr))
  {
    data.size = newsize;

    hr = StorageImpl_WriteDirEntry(This, index, &data);
  }
  return hr;
}

2556 2557 2558 2559 2560 2561
static HRESULT StorageImpl_StreamWriteAt(StorageBaseImpl *base, DirRef index,
  ULARGE_INTEGER offset, ULONG size, const void *buffer, ULONG *bytesWritten)
{
  StorageImpl *This = (StorageImpl*)base;
  DirEntry data;
  HRESULT hr;
2562
  ULARGE_INTEGER newSize;
2563 2564 2565 2566

  hr = StorageImpl_ReadDirEntry(This, index, &data);
  if (FAILED(hr)) return hr;

2567 2568 2569
  /* Grow the stream if necessary */
  newSize.QuadPart = 0;
  newSize.QuadPart = offset.QuadPart + size;
2570

2571
  if (newSize.QuadPart > data.size.QuadPart)
2572
  {
2573 2574 2575 2576
    hr = StorageImpl_StreamSetSize(base, index, newSize);
    if (FAILED(hr))
      return hr;

2577 2578
    hr = StorageImpl_ReadDirEntry(This, index, &data);
    if (FAILED(hr)) return hr;
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
  }

  if (data.size.QuadPart < LIMIT_TO_USE_SMALL_BLOCK)
  {
    SmallBlockChainStream *stream;

    stream = SmallBlockChainStream_Construct(This, NULL, index);
    if (!stream) return E_OUTOFMEMORY;

    hr = SmallBlockChainStream_WriteAt(stream, offset, size, buffer, bytesWritten);

    SmallBlockChainStream_Destroy(stream);

    return hr;
  }
  else
  {
    BlockChainStream *stream;

2598
    stream = *StorageImpl_GetCachedBlockChainStream(This, index);
2599 2600 2601 2602 2603 2604 2605 2606
    if (!stream) return E_OUTOFMEMORY;

    hr = BlockChainStream_WriteAt(stream, offset, size, buffer, bytesWritten);

    return hr;
  }
}

2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
static HRESULT StorageImpl_StreamLink(StorageBaseImpl *base, DirRef dst,
  DirRef src)
{
  StorageImpl *This = (StorageImpl*)base;
  DirEntry dst_data, src_data;
  HRESULT hr;

  hr = StorageImpl_ReadDirEntry(This, dst, &dst_data);

  if (SUCCEEDED(hr))
    hr = StorageImpl_ReadDirEntry(This, src, &src_data);

  if (SUCCEEDED(hr))
  {
    StorageImpl_DeleteCachedBlockChainStream(This, src);
    dst_data.startingBlock = src_data.startingBlock;
    dst_data.size = src_data.size;

    hr = StorageImpl_WriteDirEntry(This, dst, &dst_data);
  }

  return hr;
}

2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
static HRESULT StorageImpl_GetFilename(StorageBaseImpl* iface, LPWSTR *result)
{
  StorageImpl *This = (StorageImpl*) iface;
  STATSTG statstg;
  HRESULT hr;

  hr = ILockBytes_Stat(This->lockBytes, &statstg, 0);

  *result = statstg.pwcsName;

  return hr;
}

2644 2645 2646
/*
 * Virtual function table for the IStorage32Impl class.
 */
2647
static const IStorageVtbl Storage32Impl_Vtbl =
2648 2649 2650 2651 2652 2653
{
    StorageBaseImpl_QueryInterface,
    StorageBaseImpl_AddRef,
    StorageBaseImpl_Release,
    StorageBaseImpl_CreateStream,
    StorageBaseImpl_OpenStream,
2654
    StorageBaseImpl_CreateStorage,
2655
    StorageBaseImpl_OpenStorage,
2656
    StorageBaseImpl_CopyTo,
2657
    StorageBaseImpl_MoveElementTo,
2658 2659 2660
    StorageImpl_Commit,
    StorageImpl_Revert,
    StorageBaseImpl_EnumElements,
2661
    StorageBaseImpl_DestroyElement,
2662
    StorageBaseImpl_RenameElement,
2663
    StorageBaseImpl_SetElementTimes,
2664
    StorageBaseImpl_SetClass,
2665
    StorageBaseImpl_SetStateBits,
2666
    StorageBaseImpl_Stat
2667 2668
};

2669 2670
static const StorageBaseImplVtbl StorageImpl_BaseVtbl =
{
2671
  StorageImpl_Destroy,
2672
  StorageImpl_Invalidate,
2673
  StorageImpl_Flush,
2674
  StorageImpl_GetFilename,
2675
  StorageImpl_CreateDirEntry,
2676 2677
  StorageImpl_BaseWriteDirEntry,
  StorageImpl_BaseReadDirEntry,
2678
  StorageImpl_DestroyDirEntry,
2679
  StorageImpl_StreamReadAt,
2680
  StorageImpl_StreamWriteAt,
2681 2682
  StorageImpl_StreamSetSize,
  StorageImpl_StreamLink
2683 2684
};

2685
static HRESULT StorageImpl_Construct(
2686
  HANDLE       hFile,
2687
  LPCOLESTR    pwcsName,
2688 2689
  ILockBytes*  pLkbyt,
  DWORD        openFlags,
2690
  BOOL         fileBased,
2691
  BOOL         create,
2692
  ULONG        sector_size,
2693
  StorageImpl** result)
2694
{
2695
  StorageImpl* This;
2696
  HRESULT     hr = S_OK;
2697
  DirEntry currentEntry;
2698
  DirRef      currentEntryRef;
2699

2700 2701 2702
  if ( FAILED( validateSTGM(openFlags) ))
    return STG_E_INVALIDFLAG;

2703 2704 2705 2706
  This = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
  if (!This)
    return E_OUTOFMEMORY;

2707
  memset(This, 0, sizeof(StorageImpl));
2708

2709 2710
  list_init(&This->base.strmHead);

2711 2712
  list_init(&This->base.storageHead);

2713 2714
  This->base.lpVtbl = &Storage32Impl_Vtbl;
  This->base.pssVtbl = &IPropertySetStorage_Vtbl;
2715
  This->base.baseVtbl = &StorageImpl_BaseVtbl;
2716
  This->base.openFlags = (openFlags & ~STGM_CREATE);
2717
  This->base.ref = 1;
2718
  This->base.create = create;
2719

2720 2721
  This->base.reverted = 0;

2722 2723 2724
  /*
   * Initialize the big block cache.
   */
2725
  This->bigBlockSize   = sector_size;
2726
  This->smallBlockSize = DEF_SMALL_BLOCK_SIZE;
2727
  if (hFile)
2728
    hr = FileLockBytesImpl_Construct(hFile, openFlags, pwcsName, &This->lockBytes);
2729
  else
2730
  {
2731 2732
    This->lockBytes = pLkbyt;
    ILockBytes_AddRef(pLkbyt);
2733
  }
2734

2735 2736 2737
  if (FAILED(hr))
    goto end;

2738
  if (create)
2739 2740
  {
    ULARGE_INTEGER size;
2741
    BYTE bigBlockBuffer[MAX_BIG_BLOCK_SIZE];
2742

2743 2744 2745 2746
    /* Discard any existing data. */
    size.QuadPart = 0;
    ILockBytes_SetSize(This->lockBytes, size);

2747 2748 2749
    /*
     * Initialize all header variables:
     * - The big block depot consists of one block and it is at block 0
2750
     * - The directory table starts at block 1
2751 2752
     * - There is no small block depot
     */
2753 2754
    memset( This->bigBlockDepotStart,
            BLOCK_UNUSED,
2755 2756 2757 2758 2759
            sizeof(This->bigBlockDepotStart));

    This->bigBlockDepotCount    = 1;
    This->bigBlockDepotStart[0] = 0;
    This->rootStartBlock        = 1;
2760
    This->smallBlockLimit       = LIMIT_TO_USE_SMALL_BLOCK;
2761
    This->smallBlockDepotStart  = BLOCK_END_OF_CHAIN;
2762 2763 2764 2765
    if (sector_size == 4096)
      This->bigBlockSizeBits      = MAX_BIG_BLOCK_SIZE_BITS;
    else
      This->bigBlockSizeBits      = MIN_BIG_BLOCK_SIZE_BITS;
2766 2767 2768 2769
    This->smallBlockSizeBits    = DEF_SMALL_BLOCK_SIZE_BITS;
    This->extBigBlockDepotStart = BLOCK_END_OF_CHAIN;
    This->extBigBlockDepotCount = 0;

2770
    StorageImpl_SaveFileHeader(This);
2771 2772

    /*
2773
     * Add one block for the big block depot and one block for the directory table
2774
     */
2775 2776
    size.u.HighPart = 0;
    size.u.LowPart  = This->bigBlockSize * 3;
2777
    ILockBytes_SetSize(This->lockBytes, size);
2778 2779 2780 2781 2782 2783 2784

    /*
     * Initialize the big block depot
     */
    memset(bigBlockBuffer, BLOCK_UNUSED, This->bigBlockSize);
    StorageUtl_WriteDWord(bigBlockBuffer, 0, BLOCK_SPECIAL);
    StorageUtl_WriteDWord(bigBlockBuffer, sizeof(ULONG), BLOCK_END_OF_CHAIN);
2785
    StorageImpl_WriteBigBlock(This, 0, bigBlockBuffer);
2786 2787
  }
  else
2788 2789 2790 2791
  {
    /*
     * Load the header for the file.
     */
2792 2793 2794 2795
    hr = StorageImpl_LoadFileHeader(This);

    if (FAILED(hr))
    {
2796
      goto end;
2797
    }
2798 2799 2800 2801 2802 2803
  }

  /*
   * There is no block depot cached yet.
   */
  This->indexBlockDepotCached = 0xFFFFFFFF;
2804
  This->indexExtBlockDepotCached = 0xFFFFFFFF;
2805 2806 2807 2808 2809

  /*
   * Start searching for free blocks with block 0.
   */
  This->prevFreeBlock = 0;
2810

2811 2812
  This->firstFreeSmallBlock = 0;

2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
  /* Read the extended big block depot locations. */
  if (This->extBigBlockDepotCount != 0)
  {
    ULONG current_block = This->extBigBlockDepotStart;
    ULONG cache_size = This->extBigBlockDepotCount * 2;
    int i;

    This->extBigBlockDepotLocations = HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG) * cache_size);
    if (!This->extBigBlockDepotLocations)
    {
      hr = E_OUTOFMEMORY;
      goto end;
    }

    This->extBigBlockDepotLocationsSize = cache_size;

    for (i=0; i<This->extBigBlockDepotCount; i++)
    {
      if (current_block == BLOCK_END_OF_CHAIN)
      {
        WARN("File has too few extended big block depot blocks.\n");
        hr = STG_E_DOCFILECORRUPT;
        goto end;
      }
      This->extBigBlockDepotLocations[i] = current_block;
      current_block = Storage32Impl_GetNextExtendedBlock(This, current_block);
    }
  }
  else
  {
    This->extBigBlockDepotLocations = NULL;
    This->extBigBlockDepotLocationsSize = 0;
  }

2847 2848 2849
  /*
   * Create the block chain abstractions.
   */
2850
  if(!(This->rootBlockChain =
2851
       BlockChainStream_Construct(This, &This->rootStartBlock, DIRENTRY_NULL)))
2852 2853 2854 2855
  {
    hr = STG_E_READFAULT;
    goto end;
  }
2856

2857 2858
  if(!(This->smallBlockDepotChain =
       BlockChainStream_Construct(This, &This->smallBlockDepotStart,
2859
				  DIRENTRY_NULL)))
2860 2861 2862 2863
  {
    hr = STG_E_READFAULT;
    goto end;
  }
2864 2865

  /*
2866
   * Write the root storage entry (memory only)
2867
   */
2868
  if (create)
2869
  {
2870
    DirEntry rootEntry;
2871
    /*
2872
     * Initialize the directory table
2873
     */
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
    memset(&rootEntry, 0, sizeof(rootEntry));
    MultiByteToWideChar( CP_ACP, 0, rootEntryName, -1, rootEntry.name,
                         sizeof(rootEntry.name)/sizeof(WCHAR) );
    rootEntry.sizeOfNameString = (strlenW(rootEntry.name)+1) * sizeof(WCHAR);
    rootEntry.stgType          = STGTY_ROOT;
    rootEntry.leftChild = DIRENTRY_NULL;
    rootEntry.rightChild     = DIRENTRY_NULL;
    rootEntry.dirRootEntry     = DIRENTRY_NULL;
    rootEntry.startingBlock    = BLOCK_END_OF_CHAIN;
    rootEntry.size.u.HighPart    = 0;
    rootEntry.size.u.LowPart     = 0;

    StorageImpl_WriteDirEntry(This, 0, &rootEntry);
2887 2888 2889
  }

  /*
2890
   * Find the ID of the root storage.
2891
   */
2892
  currentEntryRef = 0;
2893

2894 2895
  do
  {
2896
    hr = StorageImpl_ReadDirEntry(
2897
                      This,
2898 2899
                      currentEntryRef,
                      &currentEntry);
2900

2901
    if (SUCCEEDED(hr))
2902
    {
2903 2904
      if ( (currentEntry.sizeOfNameString != 0 ) &&
           (currentEntry.stgType          == STGTY_ROOT) )
2905
      {
2906
        This->base.storageDirEntry = currentEntryRef;
2907 2908 2909
      }
    }

2910
    currentEntryRef++;
2911

2912
  } while (SUCCEEDED(hr) && (This->base.storageDirEntry == DIRENTRY_NULL) );
2913

2914
  if (FAILED(hr))
2915
  {
2916 2917
    hr = STG_E_READFAULT;
    goto end;
2918 2919 2920 2921 2922
  }

  /*
   * Create the block chain abstraction for the small block root chain.
   */
2923
  if(!(This->smallBlockRootChain =
2924
       BlockChainStream_Construct(This, NULL, This->base.storageDirEntry)))
2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
  {
    hr = STG_E_READFAULT;
  }

end:
  if (FAILED(hr))
  {
    IStorage_Release((IStorage*)This);
    *result = NULL;
  }
  else
2936 2937
  {
    StorageImpl_Flush((StorageBaseImpl*)This);
2938
    *result = This;
2939
  }
2940

2941 2942 2943
  return hr;
}

2944 2945 2946 2947 2948 2949 2950 2951 2952
static void StorageImpl_Invalidate(StorageBaseImpl* iface)
{
  StorageImpl *This = (StorageImpl*) iface;

  StorageBaseImpl_DeleteAll(&This->base);

  This->base.reverted = 1;
}

2953
static void StorageImpl_Destroy(StorageBaseImpl* iface)
2954
{
2955
  StorageImpl *This = (StorageImpl*) iface;
2956
  int i;
2957
  TRACE("(%p)\n", This);
2958

2959 2960
  StorageImpl_Flush(iface);

2961
  StorageImpl_Invalidate(iface);
2962

2963 2964
  HeapFree(GetProcessHeap(), 0, This->extBigBlockDepotLocations);

2965 2966 2967 2968
  BlockChainStream_Destroy(This->smallBlockRootChain);
  BlockChainStream_Destroy(This->rootBlockChain);
  BlockChainStream_Destroy(This->smallBlockDepotChain);

2969 2970 2971
  for (i=0; i<BLOCKCHAIN_CACHE_SIZE; i++)
    BlockChainStream_Destroy(This->blockChainCache[i]);

2972 2973
  if (This->lockBytes)
    ILockBytes_Release(This->lockBytes);
2974
  HeapFree(GetProcessHeap(), 0, This);
2975 2976
}

2977 2978 2979
static HRESULT StorageImpl_Flush(StorageBaseImpl* iface)
{
  StorageImpl *This = (StorageImpl*) iface;
2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
  int i;
  HRESULT hr;
  TRACE("(%p)\n", This);

  hr = BlockChainStream_Flush(This->smallBlockRootChain);

  if (SUCCEEDED(hr))
    hr = BlockChainStream_Flush(This->rootBlockChain);

  if (SUCCEEDED(hr))
    hr = BlockChainStream_Flush(This->smallBlockDepotChain);

  for (i=0; SUCCEEDED(hr) && i<BLOCKCHAIN_CACHE_SIZE; i++)
    if (This->blockChainCache[i])
      hr = BlockChainStream_Flush(This->blockChainCache[i]);

  if (SUCCEEDED(hr))
    hr = ILockBytes_Flush(This->lockBytes);
2998

2999
  return hr;
3000 3001
}

3002 3003 3004 3005 3006 3007 3008
/******************************************************************************
 *      Storage32Impl_GetNextFreeBigBlock
 *
 * Returns the index of the next free big block.
 * If the big block depot is filled, this method will enlarge it.
 *
 */
3009
static ULONG StorageImpl_GetNextFreeBigBlock(
3010
  StorageImpl* This)
3011 3012
{
  ULONG depotBlockIndexPos;
3013
  BYTE depotBuffer[MAX_BIG_BLOCK_SIZE];
3014
  BOOL success;
3015 3016 3017 3018
  ULONG depotBlockOffset;
  ULONG blocksPerDepot    = This->bigBlockSize / sizeof(ULONG);
  ULONG nextBlockIndex    = BLOCK_SPECIAL;
  int   depotIndex        = 0;
3019
  ULONG freeBlock         = BLOCK_UNUSED;
3020
  ULARGE_INTEGER neededSize;
3021
  STATSTG statstg;
3022 3023 3024

  depotIndex = This->prevFreeBlock / blocksPerDepot;
  depotBlockOffset = (This->prevFreeBlock % blocksPerDepot) * sizeof(ULONG);
3025 3026 3027 3028

  /*
   * Scan the entire big block depot until we find a block marked free
   */
3029
  while (nextBlockIndex != BLOCK_UNUSED)
3030
  {
3031
    if (depotIndex < COUNT_BBDEPOTINHEADER)
3032
    {
3033 3034
      depotBlockIndexPos = This->bigBlockDepotStart[depotIndex];

3035
      /*
3036
       * Grow the primary depot.
3037
       */
3038 3039 3040
      if (depotBlockIndexPos == BLOCK_UNUSED)
      {
        depotBlockIndexPos = depotIndex*blocksPerDepot;
3041

3042 3043 3044 3045 3046 3047
        /*
         * Add a block depot.
         */
        Storage32Impl_AddBlockDepot(This, depotBlockIndexPos);
        This->bigBlockDepotCount++;
        This->bigBlockDepotStart[depotIndex] = depotBlockIndexPos;
3048

3049 3050 3051
        /*
         * Flag it as a block depot.
         */
3052
        StorageImpl_SetNextBlockInChain(This,
3053 3054
                                          depotBlockIndexPos,
                                          BLOCK_SPECIAL);
3055

3056 3057
        /* Save new header information.
         */
3058
        StorageImpl_SaveFileHeader(This);
3059
      }
3060 3061 3062 3063
    }
    else
    {
      depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotIndex);
3064

3065 3066 3067 3068 3069 3070 3071 3072
      if (depotBlockIndexPos == BLOCK_UNUSED)
      {
        /*
         * Grow the extended depot.
         */
        ULONG extIndex       = BLOCK_UNUSED;
        ULONG numExtBlocks   = depotIndex - COUNT_BBDEPOTINHEADER;
        ULONG extBlockOffset = numExtBlocks % (blocksPerDepot - 1);
3073

3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
        if (extBlockOffset == 0)
        {
          /* We need an extended block.
           */
          extIndex = Storage32Impl_AddExtBlockDepot(This);
          This->extBigBlockDepotCount++;
          depotBlockIndexPos = extIndex + 1;
        }
        else
          depotBlockIndexPos = depotIndex * blocksPerDepot;

        /*
         * Add a block depot and mark it in the extended block.
         */
        Storage32Impl_AddBlockDepot(This, depotBlockIndexPos);
        This->bigBlockDepotCount++;
        Storage32Impl_SetExtDepotBlock(This, depotIndex, depotBlockIndexPos);

        /* Flag the block depot.
         */
3094
        StorageImpl_SetNextBlockInChain(This,
3095 3096 3097 3098 3099 3100
                                          depotBlockIndexPos,
                                          BLOCK_SPECIAL);

        /* If necessary, flag the extended depot block.
         */
        if (extIndex != BLOCK_UNUSED)
3101
          StorageImpl_SetNextBlockInChain(This, extIndex, BLOCK_EXTBBDEPOT);
3102 3103 3104

        /* Save header information.
         */
3105
        StorageImpl_SaveFileHeader(This);
3106
      }
3107 3108
    }

3109
    success = StorageImpl_ReadBigBlock(This, depotBlockIndexPos, depotBuffer);
3110

3111
    if (success)
3112
    {
3113
      while ( ( (depotBlockOffset/sizeof(ULONG) ) < blocksPerDepot) &&
3114 3115 3116 3117
              ( nextBlockIndex != BLOCK_UNUSED))
      {
        StorageUtl_ReadDWord(depotBuffer, depotBlockOffset, &nextBlockIndex);

3118 3119 3120 3121 3122
        if (nextBlockIndex == BLOCK_UNUSED)
        {
          freeBlock = (depotIndex * blocksPerDepot) +
                      (depotBlockOffset/sizeof(ULONG));
        }
3123 3124 3125 3126 3127 3128

        depotBlockOffset += sizeof(ULONG);
      }
    }

    depotIndex++;
3129
    depotBlockOffset = 0;
3130 3131
  }

3132 3133 3134
  /*
   * make sure that the block physically exists before using it
   */
3135
  neededSize.QuadPart = StorageImpl_GetBigBlockOffset(This, freeBlock)+This->bigBlockSize;
3136 3137 3138 3139 3140

  ILockBytes_Stat(This->lockBytes, &statstg, STATFLAG_NONAME);

  if (neededSize.QuadPart > statstg.cbSize.QuadPart)
    ILockBytes_SetSize(This->lockBytes, neededSize);
3141

3142 3143 3144
  This->prevFreeBlock = freeBlock;

  return freeBlock;
3145 3146
}

3147 3148 3149 3150 3151 3152
/******************************************************************************
 *      Storage32Impl_AddBlockDepot
 *
 * This will create a depot block, essentially it is a block initialized
 * to BLOCK_UNUSEDs.
 */
3153
static void Storage32Impl_AddBlockDepot(StorageImpl* This, ULONG blockIndex)
3154
{
3155
  BYTE blockBuffer[MAX_BIG_BLOCK_SIZE];
3156 3157 3158 3159 3160

  /*
   * Initialize blocks as free
   */
  memset(blockBuffer, BLOCK_UNUSED, This->bigBlockSize);
3161
  StorageImpl_WriteBigBlock(This, blockIndex, blockBuffer);
3162 3163 3164 3165 3166 3167 3168 3169 3170
}

/******************************************************************************
 *      Storage32Impl_GetExtDepotBlock
 *
 * Returns the index of the block that corresponds to the specified depot
 * index. This method is only for depot indexes equal or greater than
 * COUNT_BBDEPOTINHEADER.
 */
3171
static ULONG Storage32Impl_GetExtDepotBlock(StorageImpl* This, ULONG depotIndex)
3172 3173 3174 3175 3176 3177
{
  ULONG depotBlocksPerExtBlock = (This->bigBlockSize / sizeof(ULONG)) - 1;
  ULONG numExtBlocks           = depotIndex - COUNT_BBDEPOTINHEADER;
  ULONG extBlockCount          = numExtBlocks / depotBlocksPerExtBlock;
  ULONG extBlockOffset         = numExtBlocks % depotBlocksPerExtBlock;
  ULONG blockIndex             = BLOCK_UNUSED;
3178
  ULONG extBlockIndex;
3179 3180
  BYTE depotBuffer[MAX_BIG_BLOCK_SIZE];
  int index, num_blocks;
3181 3182 3183

  assert(depotIndex >= COUNT_BBDEPOTINHEADER);

3184
  if (extBlockCount >= This->extBigBlockDepotCount)
3185 3186
    return BLOCK_UNUSED;

3187 3188 3189
  if (This->indexExtBlockDepotCached != extBlockCount)
  {
    extBlockIndex = This->extBigBlockDepotLocations[extBlockCount];
3190

3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
    StorageImpl_ReadBigBlock(This, extBlockIndex, depotBuffer);

    num_blocks = This->bigBlockSize / 4;

    for (index = 0; index < num_blocks; index++)
    {
      StorageUtl_ReadDWord(depotBuffer, index*sizeof(ULONG), &blockIndex);
      This->extBlockDepotCached[index] = blockIndex;
    }

    This->indexExtBlockDepotCached = extBlockCount;
  }

  blockIndex = This->extBlockDepotCached[extBlockOffset];
3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215

  return blockIndex;
}

/******************************************************************************
 *      Storage32Impl_SetExtDepotBlock
 *
 * Associates the specified block index to the specified depot index.
 * This method is only for depot indexes equal or greater than
 * COUNT_BBDEPOTINHEADER.
 */
3216
static void Storage32Impl_SetExtDepotBlock(StorageImpl* This, ULONG depotIndex, ULONG blockIndex)
3217 3218 3219 3220 3221
{
  ULONG depotBlocksPerExtBlock = (This->bigBlockSize / sizeof(ULONG)) - 1;
  ULONG numExtBlocks           = depotIndex - COUNT_BBDEPOTINHEADER;
  ULONG extBlockCount          = numExtBlocks / depotBlocksPerExtBlock;
  ULONG extBlockOffset         = numExtBlocks % depotBlocksPerExtBlock;
3222
  ULONG extBlockIndex;
3223 3224 3225

  assert(depotIndex >= COUNT_BBDEPOTINHEADER);

3226 3227 3228
  assert(extBlockCount < This->extBigBlockDepotCount);

  extBlockIndex = This->extBigBlockDepotLocations[extBlockCount];
3229 3230 3231

  if (extBlockIndex != BLOCK_UNUSED)
  {
3232 3233 3234
    StorageImpl_WriteDWordToBigBlock(This, extBlockIndex,
                        extBlockOffset * sizeof(ULONG),
                        blockIndex);
3235
  }
3236 3237 3238 3239 3240

  if (This->indexExtBlockDepotCached == extBlockCount)
  {
    This->extBlockDepotCached[extBlockOffset] = blockIndex;
  }
3241 3242 3243 3244 3245 3246 3247
}

/******************************************************************************
 *      Storage32Impl_AddExtBlockDepot
 *
 * Creates an extended depot block.
 */
3248
static ULONG Storage32Impl_AddExtBlockDepot(StorageImpl* This)
3249 3250 3251
{
  ULONG numExtBlocks           = This->extBigBlockDepotCount;
  ULONG nextExtBlock           = This->extBigBlockDepotStart;
3252
  BYTE  depotBuffer[MAX_BIG_BLOCK_SIZE];
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
  ULONG index                  = BLOCK_UNUSED;
  ULONG nextBlockOffset        = This->bigBlockSize - sizeof(ULONG);
  ULONG blocksPerDepotBlock    = This->bigBlockSize / sizeof(ULONG);
  ULONG depotBlocksPerExtBlock = blocksPerDepotBlock - 1;

  index = (COUNT_BBDEPOTINHEADER + (numExtBlocks * depotBlocksPerExtBlock)) *
          blocksPerDepotBlock;

  if ((numExtBlocks == 0) && (nextExtBlock == BLOCK_END_OF_CHAIN))
  {
    /*
     * The first extended block.
     */
    This->extBigBlockDepotStart = index;
  }
  else
  {
    /*
3271
     * Find the last existing extended block.
3272
     */
3273
    nextExtBlock = This->extBigBlockDepotLocations[This->extBigBlockDepotCount-1];
3274 3275 3276 3277

    /*
     * Add the new extended block to the chain.
     */
3278 3279
    StorageImpl_WriteDWordToBigBlock(This, nextExtBlock, nextBlockOffset,
                                     index);
3280 3281 3282 3283 3284 3285
  }

  /*
   * Initialize this block.
   */
  memset(depotBuffer, BLOCK_UNUSED, This->bigBlockSize);
3286
  StorageImpl_WriteBigBlock(This, index, depotBuffer);
3287

3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301
  /* Add the block to our cache. */
  if (This->extBigBlockDepotLocationsSize == numExtBlocks)
  {
    ULONG new_cache_size = (This->extBigBlockDepotLocationsSize+1)*2;
    ULONG *new_cache = HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG) * new_cache_size);

    memcpy(new_cache, This->extBigBlockDepotLocations, sizeof(ULONG) * This->extBigBlockDepotLocationsSize);
    HeapFree(GetProcessHeap(), 0, This->extBigBlockDepotLocations);

    This->extBigBlockDepotLocations = new_cache;
    This->extBigBlockDepotLocationsSize = new_cache_size;
  }
  This->extBigBlockDepotLocations[numExtBlocks] = index;

3302 3303 3304
  return index;
}

3305 3306 3307 3308 3309
/******************************************************************************
 *      Storage32Impl_FreeBigBlock
 *
 * This method will flag the specified block as free in the big block depot.
 */
3310
static void StorageImpl_FreeBigBlock(
3311
  StorageImpl* This,
3312 3313
  ULONG          blockIndex)
{
3314
  StorageImpl_SetNextBlockInChain(This, blockIndex, BLOCK_UNUSED);
3315 3316 3317

  if (blockIndex < This->prevFreeBlock)
    This->prevFreeBlock = blockIndex;
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
}

/************************************************************************
 * Storage32Impl_GetNextBlockInChain
 *
 * This method will retrieve the block index of the next big block in
 * in the chain.
 *
 * Params:  This       - Pointer to the Storage object.
 *          blockIndex - Index of the block to retrieve the chain
 *                       for.
3329
 *          nextBlockIndex - receives the return value.
3330 3331 3332 3333 3334 3335 3336 3337 3338
 *
 * Returns: This method returns the index of the next block in the chain.
 *          It will return the constants:
 *              BLOCK_SPECIAL - If the block given was not part of a
 *                              chain.
 *              BLOCK_END_OF_CHAIN - If the block given was the last in
 *                                   a chain.
 *              BLOCK_UNUSED - If the block given was not past of a chain
 *                             and is available.
3339 3340 3341
 *              BLOCK_EXTBBDEPOT - This block is part of the extended
 *                                 big block depot.
 *
3342
 * See Windows documentation for more details on IStorage methods.
3343
 */
3344
static HRESULT StorageImpl_GetNextBlockInChain(
3345
  StorageImpl* This,
3346 3347
  ULONG        blockIndex,
  ULONG*       nextBlockIndex)
3348 3349 3350 3351
{
  ULONG offsetInDepot    = blockIndex * sizeof (ULONG);
  ULONG depotBlockCount  = offsetInDepot / This->bigBlockSize;
  ULONG depotBlockOffset = offsetInDepot % This->bigBlockSize;
3352
  BYTE depotBuffer[MAX_BIG_BLOCK_SIZE];
3353
  BOOL success;
3354
  ULONG depotBlockIndexPos;
3355
  int index, num_blocks;
3356

3357 3358 3359 3360
  *nextBlockIndex   = BLOCK_SPECIAL;

  if(depotBlockCount >= This->bigBlockDepotCount)
  {
3361
    WARN("depotBlockCount %d, bigBlockDepotCount %d\n", depotBlockCount,
3362 3363 3364
	 This->bigBlockDepotCount);
    return STG_E_READFAULT;
  }
3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384

  /*
   * Cache the currently accessed depot block.
   */
  if (depotBlockCount != This->indexBlockDepotCached)
  {
    This->indexBlockDepotCached = depotBlockCount;

    if (depotBlockCount < COUNT_BBDEPOTINHEADER)
    {
      depotBlockIndexPos = This->bigBlockDepotStart[depotBlockCount];
    }
    else
    {
      /*
       * We have to look in the extended depot.
       */
      depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotBlockCount);
    }

3385
    success = StorageImpl_ReadBigBlock(This, depotBlockIndexPos, depotBuffer);
3386

3387
    if (!success)
3388
      return STG_E_READFAULT;
3389

3390 3391 3392
    num_blocks = This->bigBlockSize / 4;

    for (index = 0; index < num_blocks; index++)
3393 3394 3395
    {
      StorageUtl_ReadDWord(depotBuffer, index*sizeof(ULONG), nextBlockIndex);
      This->blockDepotCached[index] = *nextBlockIndex;
3396 3397 3398
    }
  }

3399
  *nextBlockIndex = This->blockDepotCached[depotBlockOffset/sizeof(ULONG)];
3400

3401
  return S_OK;
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
}

/******************************************************************************
 *      Storage32Impl_GetNextExtendedBlock
 *
 * Given an extended block this method will return the next extended block.
 *
 * NOTES:
 * The last ULONG of an extended block is the block index of the next
 * extended block. Extended blocks are marked as BLOCK_EXTBBDEPOT in the
 * depot.
 *
 * Return values:
 *    - The index of the next extended block
 *    - BLOCK_UNUSED: there is no next extended block.
 *    - Any other return values denotes failure.
 */
3419
static ULONG Storage32Impl_GetNextExtendedBlock(StorageImpl* This, ULONG blockIndex)
3420 3421 3422
{
  ULONG nextBlockIndex   = BLOCK_SPECIAL;
  ULONG depotBlockOffset = This->bigBlockSize - sizeof(ULONG);
3423

3424 3425
  StorageImpl_ReadDWordFromBigBlock(This, blockIndex, depotBlockOffset,
                        &nextBlockIndex);
3426

3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
  return nextBlockIndex;
}

/******************************************************************************
 *      Storage32Impl_SetNextBlockInChain
 *
 * This method will write the index of the specified block's next block
 * in the big block depot.
 *
 * For example: to create the chain 3 -> 1 -> 7 -> End of Chain
 *              do the following
 *
 * Storage32Impl_SetNextBlockInChain(This, 3, 1);
 * Storage32Impl_SetNextBlockInChain(This, 1, 7);
 * Storage32Impl_SetNextBlockInChain(This, 7, BLOCK_END_OF_CHAIN);
 *
 */
3444
static void StorageImpl_SetNextBlockInChain(
3445
          StorageImpl* This,
3446 3447 3448 3449 3450 3451 3452 3453 3454
          ULONG          blockIndex,
          ULONG          nextBlock)
{
  ULONG offsetInDepot    = blockIndex * sizeof (ULONG);
  ULONG depotBlockCount  = offsetInDepot / This->bigBlockSize;
  ULONG depotBlockOffset = offsetInDepot % This->bigBlockSize;
  ULONG depotBlockIndexPos;

  assert(depotBlockCount < This->bigBlockDepotCount);
Thuy Nguyen's avatar
Thuy Nguyen committed
3455
  assert(blockIndex != nextBlock);
3456

3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
  if (depotBlockCount < COUNT_BBDEPOTINHEADER)
  {
    depotBlockIndexPos = This->bigBlockDepotStart[depotBlockCount];
  }
  else
  {
    /*
     * We have to look in the extended depot.
     */
    depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotBlockCount);
  }
3468

3469 3470
  StorageImpl_WriteDWordToBigBlock(This, depotBlockIndexPos, depotBlockOffset,
                        nextBlock);
3471 3472 3473 3474 3475 3476 3477
  /*
   * Update the cached block depot, if necessary.
   */
  if (depotBlockCount == This->indexBlockDepotCached)
  {
    This->blockDepotCached[depotBlockOffset/sizeof(ULONG)] = nextBlock;
  }
3478 3479 3480 3481 3482
}

/******************************************************************************
 *      Storage32Impl_LoadFileHeader
 *
3483
 * This method will read in the file header
3484
 */
3485
static HRESULT StorageImpl_LoadFileHeader(
3486
          StorageImpl* This)
3487
{
3488 3489
  HRESULT hr;
  BYTE    headerBigBlock[HEADER_SIZE];
3490
  int     index;
3491 3492
  ULARGE_INTEGER offset;
  DWORD bytes_read;
3493

3494
  TRACE("\n");
3495 3496 3497
  /*
   * Get a pointer to the big block of data containing the header.
   */
3498 3499 3500 3501 3502
  offset.u.HighPart = 0;
  offset.u.LowPart = 0;
  hr = StorageImpl_ReadAt(This, offset, headerBigBlock, HEADER_SIZE, &bytes_read);
  if (SUCCEEDED(hr) && bytes_read != HEADER_SIZE)
    hr = STG_E_FILENOTFOUND;
3503 3504 3505 3506

  /*
   * Extract the information from the header.
   */
3507
  if (SUCCEEDED(hr))
3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523
  {
    /*
     * Check for the "magic number" signature and return an error if it is not
     * found.
     */
    if (memcmp(headerBigBlock, STORAGE_oldmagic, sizeof(STORAGE_oldmagic))==0)
    {
      return STG_E_OLDFORMAT;
    }

    if (memcmp(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic))!=0)
    {
      return STG_E_INVALIDHEADER;
    }

    StorageUtl_ReadWord(
3524 3525
      headerBigBlock,
      OFFSET_BIGBLOCKSIZEBITS,
3526 3527 3528
      &This->bigBlockSizeBits);

    StorageUtl_ReadWord(
3529 3530
      headerBigBlock,
      OFFSET_SMALLBLOCKSIZEBITS,
3531 3532 3533
      &This->smallBlockSizeBits);

    StorageUtl_ReadDWord(
3534 3535
      headerBigBlock,
      OFFSET_BBDEPOTCOUNT,
3536 3537 3538
      &This->bigBlockDepotCount);

    StorageUtl_ReadDWord(
3539 3540
      headerBigBlock,
      OFFSET_ROOTSTARTBLOCK,
3541 3542
      &This->rootStartBlock);

3543 3544 3545 3546 3547
    StorageUtl_ReadDWord(
      headerBigBlock,
      OFFSET_SMALLBLOCKLIMIT,
      &This->smallBlockLimit);

3548
    StorageUtl_ReadDWord(
3549 3550
      headerBigBlock,
      OFFSET_SBDEPOTSTART,
3551 3552
      &This->smallBlockDepotStart);

3553 3554 3555
    StorageUtl_ReadDWord(
      headerBigBlock,
      OFFSET_EXTBBDEPOTSTART,
3556 3557 3558
      &This->extBigBlockDepotStart);

    StorageUtl_ReadDWord(
3559 3560
      headerBigBlock,
      OFFSET_EXTBBDEPOTCOUNT,
3561
      &This->extBigBlockDepotCount);
3562

3563 3564 3565
    for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
    {
      StorageUtl_ReadDWord(
3566
        headerBigBlock,
3567 3568 3569
        OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
        &(This->bigBlockDepotStart[index]));
    }
3570

3571 3572 3573
    /*
     * Make the bitwise arithmetic to get the size of the blocks in bytes.
     */
3574 3575
    This->bigBlockSize   = 0x000000001 << (DWORD)This->bigBlockSizeBits;
    This->smallBlockSize = 0x000000001 << (DWORD)This->smallBlockSizeBits;
3576

3577
    /*
3578
     * Right now, the code is making some assumptions about the size of the
3579 3580
     * blocks, just make sure they are what we're expecting.
     */
3581
    if ((This->bigBlockSize != MIN_BIG_BLOCK_SIZE && This->bigBlockSize != MAX_BIG_BLOCK_SIZE) ||
3582 3583
	This->smallBlockSize != DEF_SMALL_BLOCK_SIZE ||
	This->smallBlockLimit != LIMIT_TO_USE_SMALL_BLOCK)
Alexandre Julliard's avatar
Alexandre Julliard committed
3584
    {
3585 3586
	FIXME("Broken OLE storage file? bigblock=0x%x, smallblock=0x%x, sblimit=0x%x\n",
	    This->bigBlockSize, This->smallBlockSize, This->smallBlockLimit);
Alexandre Julliard's avatar
Alexandre Julliard committed
3587 3588 3589 3590
	hr = STG_E_INVALIDHEADER;
    }
    else
	hr = S_OK;
3591
  }
3592

3593 3594 3595 3596 3597 3598
  return hr;
}

/******************************************************************************
 *      Storage32Impl_SaveFileHeader
 *
3599
 * This method will save to the file the header
3600
 */
3601
static void StorageImpl_SaveFileHeader(
3602
          StorageImpl* This)
3603
{
3604
  BYTE   headerBigBlock[HEADER_SIZE];
3605
  int    index;
3606 3607 3608
  HRESULT hr;
  ULARGE_INTEGER offset;
  DWORD bytes_read, bytes_written;
3609
  DWORD major_version, dirsectorcount;
3610 3611 3612 3613

  /*
   * Get a pointer to the big block of data containing the header.
   */
3614 3615 3616 3617 3618
  offset.u.HighPart = 0;
  offset.u.LowPart = 0;
  hr = StorageImpl_ReadAt(This, offset, headerBigBlock, HEADER_SIZE, &bytes_read);
  if (SUCCEEDED(hr) && bytes_read != HEADER_SIZE)
    hr = STG_E_FILENOTFOUND;
3619

3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
  if (This->bigBlockSizeBits == 0x9)
    major_version = 3;
  else if (This->bigBlockSizeBits == 0xc)
    major_version = 4;
  else
  {
    ERR("invalid big block shift 0x%x\n", This->bigBlockSizeBits);
    major_version = 4;
  }

3630 3631 3632
  /*
   * If the block read failed, the file is probably new.
   */
3633
  if (FAILED(hr))
3634 3635 3636 3637
  {
    /*
     * Initialize for all unknown fields.
     */
3638
    memset(headerBigBlock, 0, HEADER_SIZE);
3639

3640 3641 3642 3643 3644
    /*
     * Initialize the magic number.
     */
    memcpy(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic));
  }
3645

3646 3647 3648
  /*
   * Write the information to the header.
   */
3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663
  StorageUtl_WriteWord(
    headerBigBlock,
    OFFSET_MINORVERSION,
    0x3e);

  StorageUtl_WriteWord(
    headerBigBlock,
    OFFSET_MAJORVERSION,
    major_version);

  StorageUtl_WriteWord(
    headerBigBlock,
    OFFSET_BYTEORDERMARKER,
    (WORD)-2);

3664 3665 3666 3667
  StorageUtl_WriteWord(
    headerBigBlock,
    OFFSET_BIGBLOCKSIZEBITS,
    This->bigBlockSizeBits);
3668

3669 3670 3671 3672
  StorageUtl_WriteWord(
    headerBigBlock,
    OFFSET_SMALLBLOCKSIZEBITS,
    This->smallBlockSizeBits);
3673

3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690
  if (major_version >= 4)
  {
    if (This->rootBlockChain)
      dirsectorcount = BlockChainStream_GetCount(This->rootBlockChain);
    else
      /* This file is being created, and it will start out with one block. */
      dirsectorcount = 1;
  }
  else
    /* This field must be 0 in versions older than 4 */
    dirsectorcount = 0;

  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_DIRSECTORCOUNT,
    dirsectorcount);

3691 3692 3693 3694
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_BBDEPOTCOUNT,
    This->bigBlockDepotCount);
3695

3696 3697 3698 3699
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_ROOTSTARTBLOCK,
    This->rootStartBlock);
3700

3701 3702 3703 3704 3705
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_SMALLBLOCKLIMIT,
    This->smallBlockLimit);

3706 3707 3708 3709
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_SBDEPOTSTART,
    This->smallBlockDepotStart);
3710

3711 3712 3713 3714 3715 3716 3717 3718 3719 3720
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_SBDEPOTCOUNT,
    This->smallBlockDepotChain ?
     BlockChainStream_GetCount(This->smallBlockDepotChain) : 0);

  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_EXTBBDEPOTSTART,
    This->extBigBlockDepotStart);
3721

3722 3723 3724 3725 3726 3727 3728
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_EXTBBDEPOTCOUNT,
    This->extBigBlockDepotCount);

  for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
  {
3729
    StorageUtl_WriteDWord(
3730
      headerBigBlock,
3731 3732
      OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
      (This->bigBlockDepotStart[index]));
3733
  }
3734

3735 3736 3737
  /*
   * Write the big block back to the file.
   */
3738
  StorageImpl_WriteAt(This, offset, headerBigBlock, HEADER_SIZE, &bytes_written);
3739 3740
}

3741 3742 3743 3744 3745
/******************************************************************************
 *      StorageImpl_ReadRawDirEntry
 *
 * This method will read the raw data from a directory entry in the file.
 *
3746
 * buffer must be RAW_DIRENTRY_SIZE bytes long.
3747 3748 3749 3750 3751 3752 3753 3754
 */
HRESULT StorageImpl_ReadRawDirEntry(StorageImpl *This, ULONG index, BYTE *buffer)
{
  ULARGE_INTEGER offset;
  HRESULT hr;
  ULONG bytesRead;

  offset.u.HighPart = 0;
3755
  offset.u.LowPart  = index * RAW_DIRENTRY_SIZE;
3756 3757 3758 3759

  hr = BlockChainStream_ReadAt(
                    This->rootBlockChain,
                    offset,
3760
                    RAW_DIRENTRY_SIZE,
3761 3762 3763
                    buffer,
                    &bytesRead);

3764 3765 3766
  if (bytesRead != RAW_DIRENTRY_SIZE)
    return STG_E_READFAULT;

3767 3768 3769
  return hr;
}

3770 3771 3772 3773 3774
/******************************************************************************
 *      StorageImpl_WriteRawDirEntry
 *
 * This method will write the raw data from a directory entry in the file.
 *
3775
 * buffer must be RAW_DIRENTRY_SIZE bytes long.
3776 3777 3778 3779 3780 3781 3782 3783
 */
HRESULT StorageImpl_WriteRawDirEntry(StorageImpl *This, ULONG index, const BYTE *buffer)
{
  ULARGE_INTEGER offset;
  HRESULT hr;
  ULONG bytesRead;

  offset.u.HighPart = 0;
3784
  offset.u.LowPart  = index * RAW_DIRENTRY_SIZE;
3785 3786 3787 3788

  hr = BlockChainStream_WriteAt(
                    This->rootBlockChain,
                    offset,
3789
                    RAW_DIRENTRY_SIZE,
3790 3791 3792 3793 3794 3795
                    buffer,
                    &bytesRead);

  return hr;
}

3796 3797 3798 3799 3800
/******************************************************************************
 *      UpdateRawDirEntry
 *
 * Update raw directory entry data from the fields in newData.
 *
3801
 * buffer must be RAW_DIRENTRY_SIZE bytes long.
3802
 */
3803
void UpdateRawDirEntry(BYTE *buffer, const DirEntry *newData)
3804
{
3805
  memset(buffer, 0, RAW_DIRENTRY_SIZE);
3806 3807 3808 3809

  memcpy(
    buffer + OFFSET_PS_NAME,
    newData->name,
3810
    DIRENTRY_NAME_BUFFER_LEN );
3811

3812
  memcpy(buffer + OFFSET_PS_STGTYPE, &newData->stgType, 1);
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830

  StorageUtl_WriteWord(
    buffer,
      OFFSET_PS_NAMELENGTH,
      newData->sizeOfNameString);

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_LEFTCHILD,
      newData->leftChild);

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_RIGHTCHILD,
      newData->rightChild);

  StorageUtl_WriteDWord(
    buffer,
3831 3832
      OFFSET_PS_DIRROOT,
      newData->dirRootEntry);
3833 3834 3835 3836

  StorageUtl_WriteGUID(
    buffer,
      OFFSET_PS_GUID,
3837
      &newData->clsid);
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_CTIMELOW,
      newData->ctime.dwLowDateTime);

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_CTIMEHIGH,
      newData->ctime.dwHighDateTime);

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_MTIMELOW,
      newData->mtime.dwLowDateTime);

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_MTIMEHIGH,
      newData->ctime.dwHighDateTime);

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_STARTBLOCK,
      newData->startingBlock);

  StorageUtl_WriteDWord(
    buffer,
      OFFSET_PS_SIZE,
      newData->size.u.LowPart);
}

3870
/******************************************************************************
3871
 *      Storage32Impl_ReadDirEntry
3872
 *
3873
 * This method will read the specified directory entry.
3874
 */
3875
HRESULT StorageImpl_ReadDirEntry(
3876
  StorageImpl* This,
3877
  DirRef         index,
3878
  DirEntry*      buffer)
3879
{
3880
  BYTE           currentEntry[RAW_DIRENTRY_SIZE];
3881
  HRESULT        readRes;
Thuy Nguyen's avatar
Thuy Nguyen committed
3882

3883
  readRes = StorageImpl_ReadRawDirEntry(This, index, currentEntry);
Alexandre Julliard's avatar
Alexandre Julliard committed
3884

3885
  if (SUCCEEDED(readRes))
3886 3887 3888
  {
    memset(buffer->name, 0, sizeof(buffer->name));
    memcpy(
3889
      buffer->name,
3890
      (WCHAR *)currentEntry+OFFSET_PS_NAME,
3891
      DIRENTRY_NAME_BUFFER_LEN );
Alexandre Julliard's avatar
Alexandre Julliard committed
3892
    TRACE("storage name: %s\n", debugstr_w(buffer->name));
3893

3894
    memcpy(&buffer->stgType, currentEntry + OFFSET_PS_STGTYPE, 1);
3895

3896
    StorageUtl_ReadWord(
3897
      currentEntry,
3898
      OFFSET_PS_NAMELENGTH,
3899 3900 3901
      &buffer->sizeOfNameString);

    StorageUtl_ReadDWord(
3902
      currentEntry,
3903 3904
      OFFSET_PS_LEFTCHILD,
      &buffer->leftChild);
3905 3906

    StorageUtl_ReadDWord(
3907
      currentEntry,
3908 3909
      OFFSET_PS_RIGHTCHILD,
      &buffer->rightChild);
3910 3911

    StorageUtl_ReadDWord(
3912
      currentEntry,
3913 3914
      OFFSET_PS_DIRROOT,
      &buffer->dirRootEntry);
3915 3916

    StorageUtl_ReadGUID(
3917
      currentEntry,
3918
      OFFSET_PS_GUID,
3919
      &buffer->clsid);
3920 3921

    StorageUtl_ReadDWord(
3922
      currentEntry,
3923 3924
      OFFSET_PS_CTIMELOW,
      &buffer->ctime.dwLowDateTime);
3925 3926

    StorageUtl_ReadDWord(
3927
      currentEntry,
3928 3929
      OFFSET_PS_CTIMEHIGH,
      &buffer->ctime.dwHighDateTime);
3930 3931

    StorageUtl_ReadDWord(
3932
      currentEntry,
3933 3934
      OFFSET_PS_MTIMELOW,
      &buffer->mtime.dwLowDateTime);
3935 3936

    StorageUtl_ReadDWord(
3937
      currentEntry,
3938 3939
      OFFSET_PS_MTIMEHIGH,
      &buffer->mtime.dwHighDateTime);
3940 3941

    StorageUtl_ReadDWord(
3942
      currentEntry,
3943
      OFFSET_PS_STARTBLOCK,
3944 3945 3946
      &buffer->startingBlock);

    StorageUtl_ReadDWord(
3947
      currentEntry,
3948
      OFFSET_PS_SIZE,
3949
      &buffer->size.u.LowPart);
3950

3951
    buffer->size.u.HighPart = 0;
3952 3953
  }

3954
  return readRes;
3955 3956 3957
}

/*********************************************************************
3958
 * Write the specified directory entry to the file
3959
 */
3960
HRESULT StorageImpl_WriteDirEntry(
3961
  StorageImpl*          This,
3962
  DirRef                index,
3963
  const DirEntry*       buffer)
3964
{
3965
  BYTE           currentEntry[RAW_DIRENTRY_SIZE];
3966
  HRESULT        writeRes;
3967

3968
  UpdateRawDirEntry(currentEntry, buffer);
3969

3970
  writeRes = StorageImpl_WriteRawDirEntry(This, index, currentEntry);
3971
  return writeRes;
3972 3973
}

3974
static BOOL StorageImpl_ReadBigBlock(
3975
  StorageImpl* This,
3976 3977 3978
  ULONG          blockIndex,
  void*          buffer)
{
3979
  ULARGE_INTEGER ulOffset;
3980
  DWORD  read=0;
3981

3982
  ulOffset.u.HighPart = 0;
3983
  ulOffset.u.LowPart = StorageImpl_GetBigBlockOffset(This, blockIndex);
3984

3985
  StorageImpl_ReadAt(This, ulOffset, buffer, This->bigBlockSize, &read);
3986 3987 3988 3989 3990 3991 3992 3993

  if (read && read < This->bigBlockSize)
  {
    /* File ends during this block; fill the rest with 0's. */
    memset((LPBYTE)buffer+read, 0, This->bigBlockSize-read);
  }

  return (read != 0);
3994
}
3995

3996 3997 3998 3999 4000 4001 4002 4003 4004
static BOOL StorageImpl_ReadDWordFromBigBlock(
  StorageImpl*  This,
  ULONG         blockIndex,
  ULONG         offset,
  DWORD*        value)
{
  ULARGE_INTEGER ulOffset;
  DWORD  read;
  DWORD  tmp;
4005

4006
  ulOffset.u.HighPart = 0;
4007
  ulOffset.u.LowPart = StorageImpl_GetBigBlockOffset(This, blockIndex);
4008
  ulOffset.u.LowPart += offset;
4009

4010
  StorageImpl_ReadAt(This, ulOffset, &tmp, sizeof(DWORD), &read);
4011
  *value = lendian32toh(tmp);
4012
  return (read == sizeof(DWORD));
4013 4014
}

4015
static BOOL StorageImpl_WriteBigBlock(
4016 4017 4018
  StorageImpl*  This,
  ULONG         blockIndex,
  const void*   buffer)
4019
{
4020 4021
  ULARGE_INTEGER ulOffset;
  DWORD  wrote;
4022

4023
  ulOffset.u.HighPart = 0;
4024
  ulOffset.u.LowPart = StorageImpl_GetBigBlockOffset(This, blockIndex);
4025

4026 4027
  StorageImpl_WriteAt(This, ulOffset, buffer, This->bigBlockSize, &wrote);
  return (wrote == This->bigBlockSize);
4028 4029
}

4030
static BOOL StorageImpl_WriteDWordToBigBlock(
4031
  StorageImpl* This,
4032 4033 4034
  ULONG         blockIndex,
  ULONG         offset,
  DWORD         value)
4035
{
4036 4037
  ULARGE_INTEGER ulOffset;
  DWORD  wrote;
4038

4039
  ulOffset.u.HighPart = 0;
4040
  ulOffset.u.LowPart = StorageImpl_GetBigBlockOffset(This, blockIndex);
4041
  ulOffset.u.LowPart += offset;
4042

4043 4044 4045
  value = htole32(value);
  StorageImpl_WriteAt(This, ulOffset, &value, sizeof(DWORD), &wrote);
  return (wrote == sizeof(DWORD));
4046 4047
}

4048 4049 4050 4051 4052 4053 4054
/******************************************************************************
 *              Storage32Impl_SmallBlocksToBigBlocks
 *
 * This method will convert a small block chain to a big block chain.
 * The small block chain will be destroyed.
 */
BlockChainStream* Storage32Impl_SmallBlocksToBigBlocks(
4055
                      StorageImpl* This,
4056 4057 4058 4059
                      SmallBlockChainStream** ppsbChain)
{
  ULONG bbHeadOfChain = BLOCK_END_OF_CHAIN;
  ULARGE_INTEGER size, offset;
4060 4061
  ULONG cbRead, cbWritten;
  ULARGE_INTEGER cbTotalRead;
4062
  DirRef streamEntryRef;
4063
  HRESULT resWrite = S_OK;
4064
  HRESULT resRead;
4065
  DirEntry streamEntry;
4066
  BYTE *buffer;
4067 4068 4069 4070 4071
  BlockChainStream *bbTempChain = NULL;
  BlockChainStream *bigBlockChain = NULL;

  /*
   * Create a temporary big block chain that doesn't have
4072
   * an associated directory entry. This temporary chain will be
4073 4074 4075 4076
   * used to copy data from small blocks to big blocks.
   */
  bbTempChain = BlockChainStream_Construct(This,
                                           &bbHeadOfChain,
4077
                                           DIRENTRY_NULL);
4078
  if(!bbTempChain) return NULL;
4079 4080 4081 4082 4083 4084 4085 4086 4087 4088
  /*
   * Grow the big block chain.
   */
  size = SmallBlockChainStream_GetSize(*ppsbChain);
  BlockChainStream_SetSize(bbTempChain, size);

  /*
   * Copy the contents of the small block chain to the big block chain
   * by small block size increments.
   */
4089 4090
  offset.u.LowPart = 0;
  offset.u.HighPart = 0;
4091
  cbTotalRead.QuadPart = 0;
4092

4093
  buffer = HeapAlloc(GetProcessHeap(),0,DEF_SMALL_BLOCK_SIZE);
4094 4095
  do
  {
4096 4097
    resRead = SmallBlockChainStream_ReadAt(*ppsbChain,
                                           offset,
4098
                                           min(This->smallBlockSize, size.u.LowPart - offset.u.LowPart),
4099 4100 4101
                                           buffer,
                                           &cbRead);
    if (FAILED(resRead))
4102 4103 4104 4105
        break;

    if (cbRead > 0)
    {
4106
        cbTotalRead.QuadPart += cbRead;
4107

4108
        resWrite = BlockChainStream_WriteAt(bbTempChain,
4109
                                            offset,
4110
                                            cbRead,
4111 4112
                                            buffer,
                                            &cbWritten);
4113

4114
        if (FAILED(resWrite))
4115
            break;
4116

4117
        offset.u.LowPart += cbRead;
4118
    }
4119 4120 4121 4122 4123
    else
    {
        resRead = STG_E_READFAULT;
        break;
    }
4124
  } while (cbTotalRead.QuadPart < size.QuadPart);
4125
  HeapFree(GetProcessHeap(),0,buffer);
4126

4127 4128 4129
  size.u.HighPart = 0;
  size.u.LowPart  = 0;

4130 4131
  if (FAILED(resRead) || FAILED(resWrite))
  {
4132
    ERR("conversion failed: resRead = 0x%08x, resWrite = 0x%08x\n", resRead, resWrite);
4133
    BlockChainStream_SetSize(bbTempChain, size);
4134 4135 4136
    BlockChainStream_Destroy(bbTempChain);
    return NULL;
  }
4137 4138 4139 4140

  /*
   * Destroy the small block chain.
   */
4141
  streamEntryRef = (*ppsbChain)->ownerDirEntry;
4142 4143 4144 4145 4146
  SmallBlockChainStream_SetSize(*ppsbChain, size);
  SmallBlockChainStream_Destroy(*ppsbChain);
  *ppsbChain = 0;

  /*
4147
   * Change the directory entry. This chain is now a big block chain
4148 4149
   * and it doesn't reside in the small blocks chain anymore.
   */
4150
  StorageImpl_ReadDirEntry(This, streamEntryRef, &streamEntry);
4151

4152
  streamEntry.startingBlock = bbHeadOfChain;
4153

4154
  StorageImpl_WriteDirEntry(This, streamEntryRef, &streamEntry);
4155 4156

  /*
4157 4158
   * Destroy the temporary entryless big block chain.
   * Create a new big block chain associated with this entry.
4159 4160 4161 4162
   */
  BlockChainStream_Destroy(bbTempChain);
  bigBlockChain = BlockChainStream_Construct(This,
                                             NULL,
4163
                                             streamEntryRef);
4164 4165 4166 4167

  return bigBlockChain;
}

4168 4169 4170 4171 4172 4173 4174 4175
/******************************************************************************
 *              Storage32Impl_BigBlocksToSmallBlocks
 *
 * This method will convert a big block chain to a small block chain.
 * The big block chain will be destroyed on success.
 */
SmallBlockChainStream* Storage32Impl_BigBlocksToSmallBlocks(
                           StorageImpl* This,
4176 4177
                           BlockChainStream** ppbbChain,
                           ULARGE_INTEGER newSize)
4178 4179
{
    ULARGE_INTEGER size, offset, cbTotalRead;
4180 4181
    ULONG cbRead, cbWritten, sbHeadOfChain = BLOCK_END_OF_CHAIN;
    DirRef streamEntryRef;
4182
    HRESULT resWrite = S_OK, resRead = S_OK;
4183
    DirEntry streamEntry;
4184 4185 4186 4187 4188 4189
    BYTE* buffer;
    SmallBlockChainStream* sbTempChain;

    TRACE("%p %p\n", This, ppbbChain);

    sbTempChain = SmallBlockChainStream_Construct(This, &sbHeadOfChain,
4190
            DIRENTRY_NULL);
4191 4192 4193 4194

    if(!sbTempChain)
        return NULL;

4195
    SmallBlockChainStream_SetSize(sbTempChain, newSize);
4196
    size = BlockChainStream_GetSize(*ppbbChain);
4197
    size.QuadPart = min(size.QuadPart, newSize.QuadPart);
4198 4199 4200 4201 4202

    offset.u.HighPart = 0;
    offset.u.LowPart = 0;
    cbTotalRead.QuadPart = 0;
    buffer = HeapAlloc(GetProcessHeap(), 0, This->bigBlockSize);
4203
    while(cbTotalRead.QuadPart < size.QuadPart)
4204 4205
    {
        resRead = BlockChainStream_ReadAt(*ppbbChain, offset,
4206 4207
                min(This->bigBlockSize, size.u.LowPart - offset.u.LowPart),
                buffer, &cbRead);
4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221

        if(FAILED(resRead))
            break;

        if(cbRead > 0)
        {
            cbTotalRead.QuadPart += cbRead;

            resWrite = SmallBlockChainStream_WriteAt(sbTempChain, offset,
                    cbRead, buffer, &cbWritten);

            if(FAILED(resWrite))
                break;

4222
            offset.u.LowPart += cbRead;
4223
        }
4224 4225 4226 4227 4228
        else
        {
            resRead = STG_E_READFAULT;
            break;
        }
4229
    }
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243
    HeapFree(GetProcessHeap(), 0, buffer);

    size.u.HighPart = 0;
    size.u.LowPart = 0;

    if(FAILED(resRead) || FAILED(resWrite))
    {
        ERR("conversion failed: resRead = 0x%08x, resWrite = 0x%08x\n", resRead, resWrite);
        SmallBlockChainStream_SetSize(sbTempChain, size);
        SmallBlockChainStream_Destroy(sbTempChain);
        return NULL;
    }

    /* destroy the original big block chain */
4244
    streamEntryRef = (*ppbbChain)->ownerDirEntry;
4245 4246 4247 4248
    BlockChainStream_SetSize(*ppbbChain, size);
    BlockChainStream_Destroy(*ppbbChain);
    *ppbbChain = NULL;

4249 4250 4251
    StorageImpl_ReadDirEntry(This, streamEntryRef, &streamEntry);
    streamEntry.startingBlock = sbHeadOfChain;
    StorageImpl_WriteDirEntry(This, streamEntryRef, &streamEntry);
4252 4253

    SmallBlockChainStream_Destroy(sbTempChain);
4254
    return SmallBlockChainStream_Construct(This, NULL, streamEntryRef);
4255 4256
}

4257 4258 4259
static HRESULT StorageBaseImpl_CopyStream(
  StorageBaseImpl *dst, DirRef dst_entry,
  StorageBaseImpl *src, DirRef src_entry)
4260 4261
{
  HRESULT hr;
4262 4263 4264 4265
  BYTE data[4096];
  DirEntry srcdata;
  ULARGE_INTEGER bytes_copied;
  ULONG bytestocopy, bytesread, byteswritten;
4266

4267
  hr = StorageBaseImpl_ReadDirEntry(src, src_entry, &srcdata);
4268 4269 4270

  if (SUCCEEDED(hr))
  {
4271
    hr = StorageBaseImpl_StreamSetSize(dst, dst_entry, srcdata.size);
4272

4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284
    bytes_copied.QuadPart = 0;
    while (bytes_copied.QuadPart < srcdata.size.QuadPart && SUCCEEDED(hr))
    {
      bytestocopy = min(4096, srcdata.size.QuadPart - bytes_copied.QuadPart);

      hr = StorageBaseImpl_StreamReadAt(src, src_entry, bytes_copied, bytestocopy,
        data, &bytesread);
      if (SUCCEEDED(hr) && bytesread != bytestocopy) hr = STG_E_READFAULT;

      if (SUCCEEDED(hr))
        hr = StorageBaseImpl_StreamWriteAt(dst, dst_entry, bytes_copied, bytestocopy,
          data, &byteswritten);
4285 4286 4287 4288 4289
      if (SUCCEEDED(hr))
      {
        if (byteswritten != bytestocopy) hr = STG_E_WRITEFAULT;
        bytes_copied.QuadPart += byteswritten;
      }
4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348
    }
  }

  return hr;
}

static DirRef TransactedSnapshotImpl_FindFreeEntry(TransactedSnapshotImpl *This)
{
  DirRef result=This->firstFreeEntry;

  while (result < This->entries_size && This->entries[result].inuse)
    result++;

  if (result == This->entries_size)
  {
    ULONG new_size = This->entries_size * 2;
    TransactedDirEntry *new_entries;

    new_entries = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(TransactedDirEntry) * new_size);
    if (!new_entries) return DIRENTRY_NULL;

    memcpy(new_entries, This->entries, sizeof(TransactedDirEntry) * This->entries_size);
    HeapFree(GetProcessHeap(), 0, This->entries);

    This->entries = new_entries;
    This->entries_size = new_size;
  }

  This->entries[result].inuse = 1;

  This->firstFreeEntry = result+1;

  return result;
}

static DirRef TransactedSnapshotImpl_CreateStubEntry(
  TransactedSnapshotImpl *This, DirRef parentEntryRef)
{
  DirRef stubEntryRef;
  TransactedDirEntry *entry;

  stubEntryRef = TransactedSnapshotImpl_FindFreeEntry(This);

  if (stubEntryRef != DIRENTRY_NULL)
  {
    entry = &This->entries[stubEntryRef];

    entry->newTransactedParentEntry = entry->transactedParentEntry = parentEntryRef;

    entry->read = 0;
  }

  return stubEntryRef;
}

static HRESULT TransactedSnapshotImpl_EnsureReadEntry(
  TransactedSnapshotImpl *This, DirRef entry)
{
  HRESULT hr=S_OK;
4349
  DirEntry data;
4350 4351 4352 4353 4354

  if (!This->entries[entry].read)
  {
    hr = StorageBaseImpl_ReadDirEntry(This->transactedParent,
        This->entries[entry].transactedParentEntry,
4355
        &data);
4356

4357
    if (SUCCEEDED(hr) && data.leftChild != DIRENTRY_NULL)
4358
    {
4359
      data.leftChild = TransactedSnapshotImpl_CreateStubEntry(This, data.leftChild);
4360

4361
      if (data.leftChild == DIRENTRY_NULL)
4362 4363 4364
        hr = E_OUTOFMEMORY;
    }

4365
    if (SUCCEEDED(hr) && data.rightChild != DIRENTRY_NULL)
4366
    {
4367
      data.rightChild = TransactedSnapshotImpl_CreateStubEntry(This, data.rightChild);
4368

4369
      if (data.rightChild == DIRENTRY_NULL)
4370 4371 4372
        hr = E_OUTOFMEMORY;
    }

4373
    if (SUCCEEDED(hr) && data.dirRootEntry != DIRENTRY_NULL)
4374
    {
4375
      data.dirRootEntry = TransactedSnapshotImpl_CreateStubEntry(This, data.dirRootEntry);
4376

4377
      if (data.dirRootEntry == DIRENTRY_NULL)
4378 4379
        hr = E_OUTOFMEMORY;
    }
4380 4381

    if (SUCCEEDED(hr))
4382 4383
    {
      memcpy(&This->entries[entry].data, &data, sizeof(DirEntry));
4384
      This->entries[entry].read = 1;
4385
    }
4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412
  }

  return hr;
}

static HRESULT TransactedSnapshotImpl_MakeStreamDirty(
  TransactedSnapshotImpl *This, DirRef entry)
{
  HRESULT hr = S_OK;

  if (!This->entries[entry].stream_dirty)
  {
    DirEntry new_entrydata;

    memset(&new_entrydata, 0, sizeof(DirEntry));
    new_entrydata.name[0] = 'S';
    new_entrydata.sizeOfNameString = 1;
    new_entrydata.stgType = STGTY_STREAM;
    new_entrydata.startingBlock = BLOCK_END_OF_CHAIN;
    new_entrydata.leftChild = DIRENTRY_NULL;
    new_entrydata.rightChild = DIRENTRY_NULL;
    new_entrydata.dirRootEntry = DIRENTRY_NULL;

    hr = StorageBaseImpl_CreateDirEntry(This->scratch, &new_entrydata,
      &This->entries[entry].stream_entry);

    if (SUCCEEDED(hr) && This->entries[entry].transactedParentEntry != DIRENTRY_NULL)
4413
    {
4414 4415 4416 4417 4418 4419
      hr = StorageBaseImpl_CopyStream(
        This->scratch, This->entries[entry].stream_entry,
        This->transactedParent, This->entries[entry].transactedParentEntry);

      if (FAILED(hr))
        StorageBaseImpl_DestroyDirEntry(This->scratch, This->entries[entry].stream_entry);
4420 4421 4422
    }

    if (SUCCEEDED(hr))
4423 4424 4425 4426 4427 4428 4429 4430
      This->entries[entry].stream_dirty = 1;

    if (This->entries[entry].transactedParentEntry != DIRENTRY_NULL)
    {
      /* Since this entry is modified, and we aren't using its stream data, we
       * no longer care about the original entry. */
      DirRef delete_ref;
      delete_ref = TransactedSnapshotImpl_CreateStubEntry(This, This->entries[entry].transactedParentEntry);
4431

4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542
      if (delete_ref != DIRENTRY_NULL)
        This->entries[delete_ref].deleted = 1;

      This->entries[entry].transactedParentEntry = This->entries[entry].newTransactedParentEntry = DIRENTRY_NULL;
    }
  }

  return hr;
}

/* Find the first entry in a depth-first traversal. */
static DirRef TransactedSnapshotImpl_FindFirstChild(
  TransactedSnapshotImpl* This, DirRef parent)
{
  DirRef cursor, prev;
  TransactedDirEntry *entry;

  cursor = parent;
  entry = &This->entries[cursor];
  while (entry->read)
  {
    if (entry->data.leftChild != DIRENTRY_NULL)
    {
      prev = cursor;
      cursor = entry->data.leftChild;
      entry = &This->entries[cursor];
      entry->parent = prev;
    }
    else if (entry->data.rightChild != DIRENTRY_NULL)
    {
      prev = cursor;
      cursor = entry->data.rightChild;
      entry = &This->entries[cursor];
      entry->parent = prev;
    }
    else if (entry->data.dirRootEntry != DIRENTRY_NULL)
    {
      prev = cursor;
      cursor = entry->data.dirRootEntry;
      entry = &This->entries[cursor];
      entry->parent = prev;
    }
    else
      break;
  }

  return cursor;
}

/* Find the next entry in a depth-first traversal. */
static DirRef TransactedSnapshotImpl_FindNextChild(
  TransactedSnapshotImpl* This, DirRef current)
{
  DirRef parent;
  TransactedDirEntry *parent_entry;

  parent = This->entries[current].parent;
  parent_entry = &This->entries[parent];

  if (parent != DIRENTRY_NULL && parent_entry->data.dirRootEntry != current)
  {
    if (parent_entry->data.rightChild != current && parent_entry->data.rightChild != DIRENTRY_NULL)
    {
      This->entries[parent_entry->data.rightChild].parent = parent;
      return TransactedSnapshotImpl_FindFirstChild(This, parent_entry->data.rightChild);
    }

    if (parent_entry->data.dirRootEntry != DIRENTRY_NULL)
    {
      This->entries[parent_entry->data.dirRootEntry].parent = parent;
      return TransactedSnapshotImpl_FindFirstChild(This, parent_entry->data.dirRootEntry);
    }
  }

  return parent;
}

/* Return TRUE if we've made a copy of this entry for committing to the parent. */
static inline BOOL TransactedSnapshotImpl_MadeCopy(
  TransactedSnapshotImpl* This, DirRef entry)
{
  return entry != DIRENTRY_NULL &&
    This->entries[entry].newTransactedParentEntry != This->entries[entry].transactedParentEntry;
}

/* Destroy the entries created by CopyTree. */
static void TransactedSnapshotImpl_DestroyTemporaryCopy(
  TransactedSnapshotImpl* This, DirRef stop)
{
  DirRef cursor;
  TransactedDirEntry *entry;
  ULARGE_INTEGER zero;

  zero.QuadPart = 0;

  if (!This->entries[This->base.storageDirEntry].read)
    return;

  cursor = This->entries[This->base.storageDirEntry].data.dirRootEntry;

  if (cursor == DIRENTRY_NULL)
    return;

  cursor = TransactedSnapshotImpl_FindFirstChild(This, cursor);

  while (cursor != DIRENTRY_NULL && cursor != stop)
  {
    if (TransactedSnapshotImpl_MadeCopy(This, cursor))
    {
      entry = &This->entries[cursor];

4543 4544 4545
      if (entry->stream_dirty)
        StorageBaseImpl_StreamSetSize(This->transactedParent,
          entry->newTransactedParentEntry, zero);
4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561

      StorageBaseImpl_DestroyDirEntry(This->transactedParent,
        entry->newTransactedParentEntry);

      entry->newTransactedParentEntry = entry->transactedParentEntry;
    }

    cursor = TransactedSnapshotImpl_FindNextChild(This, cursor);
  }
}

/* Make a copy of our edited tree that we can use in the parent. */
static HRESULT TransactedSnapshotImpl_CopyTree(TransactedSnapshotImpl* This)
{
  DirRef cursor;
  TransactedDirEntry *entry;
4562
  HRESULT hr = S_OK;
4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611

  cursor = This->base.storageDirEntry;
  entry = &This->entries[cursor];
  entry->parent = DIRENTRY_NULL;
  entry->newTransactedParentEntry = entry->transactedParentEntry;

  if (entry->data.dirRootEntry == DIRENTRY_NULL)
    return S_OK;

  This->entries[entry->data.dirRootEntry].parent = DIRENTRY_NULL;

  cursor = TransactedSnapshotImpl_FindFirstChild(This, entry->data.dirRootEntry);
  entry = &This->entries[cursor];

  while (cursor != DIRENTRY_NULL)
  {
    /* Make a copy of this entry in the transacted parent. */
    if (!entry->read ||
        (!entry->dirty && !entry->stream_dirty &&
         !TransactedSnapshotImpl_MadeCopy(This, entry->data.leftChild) &&
         !TransactedSnapshotImpl_MadeCopy(This, entry->data.rightChild) &&
         !TransactedSnapshotImpl_MadeCopy(This, entry->data.dirRootEntry)))
      entry->newTransactedParentEntry = entry->transactedParentEntry;
    else
    {
      DirEntry newData;

      memcpy(&newData, &entry->data, sizeof(DirEntry));

      newData.size.QuadPart = 0;
      newData.startingBlock = BLOCK_END_OF_CHAIN;

      if (newData.leftChild != DIRENTRY_NULL)
        newData.leftChild = This->entries[newData.leftChild].newTransactedParentEntry;

      if (newData.rightChild != DIRENTRY_NULL)
        newData.rightChild = This->entries[newData.rightChild].newTransactedParentEntry;

      if (newData.dirRootEntry != DIRENTRY_NULL)
        newData.dirRootEntry = This->entries[newData.dirRootEntry].newTransactedParentEntry;

      hr = StorageBaseImpl_CreateDirEntry(This->transactedParent, &newData,
        &entry->newTransactedParentEntry);
      if (FAILED(hr))
      {
        TransactedSnapshotImpl_DestroyTemporaryCopy(This, cursor);
        return hr;
      }

4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624
      if (entry->stream_dirty)
      {
        hr = StorageBaseImpl_CopyStream(
          This->transactedParent, entry->newTransactedParentEntry,
          This->scratch, entry->stream_entry);
      }
      else if (entry->data.size.QuadPart)
      {
        hr = StorageBaseImpl_StreamLink(
          This->transactedParent, entry->newTransactedParentEntry,
          entry->transactedParentEntry);
      }

4625 4626 4627 4628 4629 4630 4631 4632 4633 4634
      if (FAILED(hr))
      {
        cursor = TransactedSnapshotImpl_FindNextChild(This, cursor);
        TransactedSnapshotImpl_DestroyTemporaryCopy(This, cursor);
        return hr;
      }
    }

    cursor = TransactedSnapshotImpl_FindNextChild(This, cursor);
    entry = &This->entries[cursor];
4635 4636 4637 4638 4639
  }

  return hr;
}

4640 4641 4642 4643
static HRESULT WINAPI TransactedSnapshotImpl_Commit(
  IStorage*            iface,
  DWORD                  grfCommitFlags)  /* [in] */
{
4644
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) iface;
4645 4646 4647 4648
  TransactedDirEntry *root_entry;
  DirRef i, dir_root_ref;
  DirEntry data;
  ULARGE_INTEGER zero;
4649
  HRESULT hr;
4650 4651

  zero.QuadPart = 0;
4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664

  TRACE("(%p,%x)\n", iface, grfCommitFlags);

  /* Cannot commit a read-only transacted storage */
  if ( STGM_ACCESS_MODE( This->base.openFlags ) == STGM_READ )
    return STG_E_ACCESSDENIED;

  /* To prevent data loss, we create the new structure in the file before we
   * delete the old one, so that in case of errors the old data is intact. We
   * shouldn't do this if STGC_OVERWRITE is set, but that flag should only be
   * needed in the rare situation where we have just enough free disk space to
   * overwrite the existing data. */

4665
  root_entry = &This->entries[This->base.storageDirEntry];
4666

4667 4668
  if (!root_entry->read)
    return S_OK;
4669

4670 4671
  hr = TransactedSnapshotImpl_CopyTree(This);
  if (FAILED(hr)) return hr;
4672

4673 4674
  if (root_entry->data.dirRootEntry == DIRENTRY_NULL)
    dir_root_ref = DIRENTRY_NULL;
4675
  else
4676
    dir_root_ref = This->entries[root_entry->data.dirRootEntry].newTransactedParentEntry;
4677

4678 4679
  hr = StorageBaseImpl_Flush(This->transactedParent);

4680
  /* Update the storage to use the new data in one step. */
4681 4682 4683
  if (SUCCEEDED(hr))
    hr = StorageBaseImpl_ReadDirEntry(This->transactedParent,
      root_entry->transactedParentEntry, &data);
4684 4685 4686

  if (SUCCEEDED(hr))
  {
4687 4688 4689 4690
    data.dirRootEntry = dir_root_ref;
    data.clsid = root_entry->data.clsid;
    data.ctime = root_entry->data.ctime;
    data.mtime = root_entry->data.mtime;
4691 4692

    hr = StorageBaseImpl_WriteDirEntry(This->transactedParent,
4693
      root_entry->transactedParentEntry, &data);
4694 4695
  }

4696 4697 4698 4699 4700
  /* Try to flush after updating the root storage, but if the flush fails, keep
   * going, on the theory that it'll either succeed later or the subsequent
   * writes will fail. */
  StorageBaseImpl_Flush(This->transactedParent);

4701 4702 4703
  if (SUCCEEDED(hr))
  {
    /* Destroy the old now-orphaned data. */
4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733
    for (i=0; i<This->entries_size; i++)
    {
      TransactedDirEntry *entry = &This->entries[i];
      if (entry->inuse)
      {
        if (entry->deleted)
        {
          StorageBaseImpl_StreamSetSize(This->transactedParent,
            entry->transactedParentEntry, zero);
          StorageBaseImpl_DestroyDirEntry(This->transactedParent,
            entry->transactedParentEntry);
          memset(entry, 0, sizeof(TransactedDirEntry));
          This->firstFreeEntry = min(i, This->firstFreeEntry);
        }
        else if (entry->read && entry->transactedParentEntry != entry->newTransactedParentEntry)
        {
          if (entry->transactedParentEntry != DIRENTRY_NULL)
            StorageBaseImpl_DestroyDirEntry(This->transactedParent,
              entry->transactedParentEntry);
          if (entry->stream_dirty)
          {
            StorageBaseImpl_StreamSetSize(This->scratch, entry->stream_entry, zero);
            StorageBaseImpl_DestroyDirEntry(This->scratch, entry->stream_entry);
            entry->stream_dirty = 0;
          }
          entry->dirty = 0;
          entry->transactedParentEntry = entry->newTransactedParentEntry;
        }
      }
    }
4734 4735 4736
  }
  else
  {
4737
    TransactedSnapshotImpl_DestroyTemporaryCopy(This, DIRENTRY_NULL);
4738 4739
  }

4740 4741 4742
  if (SUCCEEDED(hr))
    hr = StorageBaseImpl_Flush(This->transactedParent);

4743
  return hr;
4744 4745 4746 4747 4748
}

static HRESULT WINAPI TransactedSnapshotImpl_Revert(
  IStorage*            iface)
{
4749
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) iface;
4750 4751
  ULARGE_INTEGER zero;
  ULONG i;
4752 4753 4754 4755 4756 4757

  TRACE("(%p)\n", iface);

  /* Destroy the open objects. */
  StorageBaseImpl_DeleteAll(&This->base);

4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774
  /* Clear out the scratch file. */
  zero.QuadPart = 0;
  for (i=0; i<This->entries_size; i++)
  {
    if (This->entries[i].stream_dirty)
    {
      StorageBaseImpl_StreamSetSize(This->scratch, This->entries[i].stream_entry,
        zero);

      StorageBaseImpl_DestroyDirEntry(This->scratch, This->entries[i].stream_entry);
    }
  }

  memset(This->entries, 0, sizeof(TransactedDirEntry) * This->entries_size);

  This->firstFreeEntry = 0;
  This->base.storageDirEntry = TransactedSnapshotImpl_CreateStubEntry(This, This->transactedParent->storageDirEntry);
4775

4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794
  return S_OK;
}

static void TransactedSnapshotImpl_Invalidate(StorageBaseImpl* This)
{
  if (!This->reverted)
  {
    TRACE("Storage invalidated (stg=%p)\n", This);

    This->reverted = 1;

    StorageBaseImpl_DeleteAll(This);
  }
}

static void TransactedSnapshotImpl_Destroy( StorageBaseImpl *iface)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) iface;

4795
  TransactedSnapshotImpl_Revert((IStorage*)iface);
4796 4797 4798

  IStorage_Release((IStorage*)This->transactedParent);

4799 4800 4801
  IStorage_Release((IStorage*)This->scratch);

  HeapFree(GetProcessHeap(), 0, This->entries);
4802

4803 4804 4805
  HeapFree(GetProcessHeap(), 0, This);
}

4806 4807 4808 4809 4810 4811
static HRESULT TransactedSnapshotImpl_Flush(StorageBaseImpl* iface)
{
  /* We only need to flush when committing. */
  return S_OK;
}

4812 4813 4814 4815 4816 4817 4818
static HRESULT TransactedSnapshotImpl_GetFilename(StorageBaseImpl* iface, LPWSTR *result)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) iface;

  return StorageBaseImpl_GetFilename(This->transactedParent, result);
}

4819 4820 4821 4822
static HRESULT TransactedSnapshotImpl_CreateDirEntry(StorageBaseImpl *base,
  const DirEntry *newData, DirRef *index)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;
4823 4824 4825 4826 4827 4828 4829 4830
  DirRef new_ref;
  TransactedDirEntry *new_entry;

  new_ref = TransactedSnapshotImpl_FindFreeEntry(This);
  if (new_ref == DIRENTRY_NULL)
    return E_OUTOFMEMORY;

  new_entry = &This->entries[new_ref];
4831

4832 4833 4834 4835 4836 4837 4838 4839 4840 4841
  new_entry->newTransactedParentEntry = new_entry->transactedParentEntry = DIRENTRY_NULL;
  new_entry->read = 1;
  new_entry->dirty = 1;
  memcpy(&new_entry->data, newData, sizeof(DirEntry));

  *index = new_ref;

  TRACE("%s l=%x r=%x d=%x <-- %x\n", debugstr_w(newData->name), newData->leftChild, newData->rightChild, newData->dirRootEntry, *index);

  return S_OK;
4842 4843 4844 4845 4846 4847
}

static HRESULT TransactedSnapshotImpl_WriteDirEntry(StorageBaseImpl *base,
  DirRef index, const DirEntry *data)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;
4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
  HRESULT hr;

  TRACE("%x %s l=%x r=%x d=%x\n", index, debugstr_w(data->name), data->leftChild, data->rightChild, data->dirRootEntry);

  hr = TransactedSnapshotImpl_EnsureReadEntry(This, index);
  if (FAILED(hr)) return hr;

  memcpy(&This->entries[index].data, data, sizeof(DirEntry));

  if (index != This->base.storageDirEntry)
  {
    This->entries[index].dirty = 1;

    if (data->size.QuadPart == 0 &&
        This->entries[index].transactedParentEntry != DIRENTRY_NULL)
    {
      /* Since this entry is modified, and we aren't using its stream data, we
       * no longer care about the original entry. */
      DirRef delete_ref;
      delete_ref = TransactedSnapshotImpl_CreateStubEntry(This, This->entries[index].transactedParentEntry);

      if (delete_ref != DIRENTRY_NULL)
        This->entries[delete_ref].deleted = 1;

      This->entries[index].transactedParentEntry = This->entries[index].newTransactedParentEntry = DIRENTRY_NULL;
    }
  }
4875

4876
  return S_OK;
4877 4878 4879 4880 4881 4882
}

static HRESULT TransactedSnapshotImpl_ReadDirEntry(StorageBaseImpl *base,
  DirRef index, DirEntry *data)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;
4883 4884 4885 4886 4887 4888 4889 4890
  HRESULT hr;

  hr = TransactedSnapshotImpl_EnsureReadEntry(This, index);
  if (FAILED(hr)) return hr;

  memcpy(data, &This->entries[index].data, sizeof(DirEntry));

  TRACE("%x %s l=%x r=%x d=%x\n", index, debugstr_w(data->name), data->leftChild, data->rightChild, data->dirRootEntry);
4891

4892
  return S_OK;
4893 4894 4895 4896 4897 4898 4899
}

static HRESULT TransactedSnapshotImpl_DestroyDirEntry(StorageBaseImpl *base,
  DirRef index)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;

4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914
  if (This->entries[index].transactedParentEntry == DIRENTRY_NULL ||
      This->entries[index].data.size.QuadPart != 0)
  {
    /* If we deleted this entry while it has stream data. We must have left the
     * data because some other entry is using it, and we need to leave the
     * original entry alone. */
    memset(&This->entries[index], 0, sizeof(TransactedDirEntry));
    This->firstFreeEntry = min(index, This->firstFreeEntry);
  }
  else
  {
    This->entries[index].deleted = 1;
  }

  return S_OK;
4915 4916 4917 4918 4919 4920 4921
}

static HRESULT TransactedSnapshotImpl_StreamReadAt(StorageBaseImpl *base,
  DirRef index, ULARGE_INTEGER offset, ULONG size, void *buffer, ULONG *bytesRead)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;

4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
  if (This->entries[index].stream_dirty)
  {
    return StorageBaseImpl_StreamReadAt(This->scratch,
        This->entries[index].stream_entry, offset, size, buffer, bytesRead);
  }
  else if (This->entries[index].transactedParentEntry == DIRENTRY_NULL)
  {
    /* This stream doesn't live in the parent, and we haven't allocated storage
     * for it yet */
    *bytesRead = 0;
    return S_OK;
  }
  else
  {
    return StorageBaseImpl_StreamReadAt(This->transactedParent,
        This->entries[index].transactedParentEntry, offset, size, buffer, bytesRead);
  }
4939 4940 4941 4942 4943 4944
}

static HRESULT TransactedSnapshotImpl_StreamWriteAt(StorageBaseImpl *base,
  DirRef index, ULARGE_INTEGER offset, ULONG size, const void *buffer, ULONG *bytesWritten)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;
4945 4946 4947 4948 4949 4950 4951
  HRESULT hr;

  hr = TransactedSnapshotImpl_EnsureReadEntry(This, index);
  if (FAILED(hr)) return hr;

  hr = TransactedSnapshotImpl_MakeStreamDirty(This, index);
  if (FAILED(hr)) return hr;
4952

4953 4954 4955 4956 4957 4958 4959 4960 4961
  hr = StorageBaseImpl_StreamWriteAt(This->scratch,
    This->entries[index].stream_entry, offset, size, buffer, bytesWritten);

  if (SUCCEEDED(hr) && size != 0)
    This->entries[index].data.size.QuadPart = max(
        This->entries[index].data.size.QuadPart,
        offset.QuadPart + size);

  return hr;
4962 4963 4964 4965 4966 4967
}

static HRESULT TransactedSnapshotImpl_StreamSetSize(StorageBaseImpl *base,
  DirRef index, ULARGE_INTEGER newsize)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;
4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003
  HRESULT hr;

  hr = TransactedSnapshotImpl_EnsureReadEntry(This, index);
  if (FAILED(hr)) return hr;

  if (This->entries[index].data.size.QuadPart == newsize.QuadPart)
    return S_OK;

  if (newsize.QuadPart == 0)
  {
    /* Destroy any parent references or entries in the scratch file. */
    if (This->entries[index].stream_dirty)
    {
      ULARGE_INTEGER zero;
      zero.QuadPart = 0;
      StorageBaseImpl_StreamSetSize(This->scratch,
        This->entries[index].stream_entry, zero);
      StorageBaseImpl_DestroyDirEntry(This->scratch,
        This->entries[index].stream_entry);
      This->entries[index].stream_dirty = 0;
    }
    else if (This->entries[index].transactedParentEntry != DIRENTRY_NULL)
    {
      DirRef delete_ref;
      delete_ref = TransactedSnapshotImpl_CreateStubEntry(This, This->entries[index].transactedParentEntry);

      if (delete_ref != DIRENTRY_NULL)
        This->entries[delete_ref].deleted = 1;

      This->entries[index].transactedParentEntry = This->entries[index].newTransactedParentEntry = DIRENTRY_NULL;
    }
  }
  else
  {
    hr = TransactedSnapshotImpl_MakeStreamDirty(This, index);
    if (FAILED(hr)) return hr;
5004

5005 5006 5007 5008 5009 5010 5011 5012
    hr = StorageBaseImpl_StreamSetSize(This->scratch,
      This->entries[index].stream_entry, newsize);
  }

  if (SUCCEEDED(hr))
    This->entries[index].data.size = newsize;

  return hr;
5013 5014
}

5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039
static HRESULT TransactedSnapshotImpl_StreamLink(StorageBaseImpl *base,
  DirRef dst, DirRef src)
{
  TransactedSnapshotImpl* This = (TransactedSnapshotImpl*) base;
  HRESULT hr;
  TransactedDirEntry *dst_entry, *src_entry;

  hr = TransactedSnapshotImpl_EnsureReadEntry(This, src);
  if (FAILED(hr)) return hr;

  hr = TransactedSnapshotImpl_EnsureReadEntry(This, dst);
  if (FAILED(hr)) return hr;

  dst_entry = &This->entries[dst];
  src_entry = &This->entries[src];

  dst_entry->stream_dirty = src_entry->stream_dirty;
  dst_entry->stream_entry = src_entry->stream_entry;
  dst_entry->transactedParentEntry = src_entry->transactedParentEntry;
  dst_entry->newTransactedParentEntry = src_entry->newTransactedParentEntry;
  dst_entry->data.size = src_entry->data.size;

  return S_OK;
}

5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065
static const IStorageVtbl TransactedSnapshotImpl_Vtbl =
{
    StorageBaseImpl_QueryInterface,
    StorageBaseImpl_AddRef,
    StorageBaseImpl_Release,
    StorageBaseImpl_CreateStream,
    StorageBaseImpl_OpenStream,
    StorageBaseImpl_CreateStorage,
    StorageBaseImpl_OpenStorage,
    StorageBaseImpl_CopyTo,
    StorageBaseImpl_MoveElementTo,
    TransactedSnapshotImpl_Commit,
    TransactedSnapshotImpl_Revert,
    StorageBaseImpl_EnumElements,
    StorageBaseImpl_DestroyElement,
    StorageBaseImpl_RenameElement,
    StorageBaseImpl_SetElementTimes,
    StorageBaseImpl_SetClass,
    StorageBaseImpl_SetStateBits,
    StorageBaseImpl_Stat
};

static const StorageBaseImplVtbl TransactedSnapshotImpl_BaseVtbl =
{
  TransactedSnapshotImpl_Destroy,
  TransactedSnapshotImpl_Invalidate,
5066
  TransactedSnapshotImpl_Flush,
5067
  TransactedSnapshotImpl_GetFilename,
5068 5069 5070 5071 5072 5073
  TransactedSnapshotImpl_CreateDirEntry,
  TransactedSnapshotImpl_WriteDirEntry,
  TransactedSnapshotImpl_ReadDirEntry,
  TransactedSnapshotImpl_DestroyDirEntry,
  TransactedSnapshotImpl_StreamReadAt,
  TransactedSnapshotImpl_StreamWriteAt,
5074 5075
  TransactedSnapshotImpl_StreamSetSize,
  TransactedSnapshotImpl_StreamLink
5076 5077 5078 5079 5080
};

static HRESULT TransactedSnapshotImpl_Construct(StorageBaseImpl *parentStorage,
  TransactedSnapshotImpl** result)
{
5081 5082
  HRESULT hr;

5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100
  *result = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(TransactedSnapshotImpl));
  if (*result)
  {
    (*result)->base.lpVtbl = &TransactedSnapshotImpl_Vtbl;

    /* This is OK because the property set storage functions use the IStorage functions. */
    (*result)->base.pssVtbl = parentStorage->pssVtbl;

    (*result)->base.baseVtbl = &TransactedSnapshotImpl_BaseVtbl;

    list_init(&(*result)->base.strmHead);

    list_init(&(*result)->base.storageHead);

    (*result)->base.ref = 1;

    (*result)->base.openFlags = parentStorage->openFlags;

5101
    /* Create a new temporary storage to act as the scratch file. */
5102
    hr = StgCreateDocfile(NULL, STGM_READWRITE|STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_DELETEONRELEASE,
5103
        0, (IStorage**)&(*result)->scratch);
5104

5105 5106
    if (SUCCEEDED(hr))
    {
5107
        ULONG num_entries = 20;
5108

5109
        (*result)->entries = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(TransactedDirEntry) * num_entries);
5110

5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129
        (*result)->entries_size = num_entries;

        (*result)->firstFreeEntry = 0;

        if ((*result)->entries)
        {
            /* parentStorage already has 1 reference, which we take over here. */
            (*result)->transactedParent = parentStorage;

            parentStorage->transactedChild = (StorageBaseImpl*)*result;

            (*result)->base.storageDirEntry = TransactedSnapshotImpl_CreateStubEntry(*result, parentStorage->storageDirEntry);
        }
        else
        {
            IStorage_Release((IStorage*)(*result)->scratch);

            hr = E_OUTOFMEMORY;
        }
5130 5131 5132 5133 5134
    }

    if (FAILED(hr)) HeapFree(GetProcessHeap(), 0, (*result));

    return hr;
5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160
  }
  else
    return E_OUTOFMEMORY;
}

static HRESULT Storage_ConstructTransacted(StorageBaseImpl *parentStorage,
  StorageBaseImpl** result)
{
  static int fixme=0;

  if (parentStorage->openFlags & (STGM_NOSCRATCH|STGM_NOSNAPSHOT) && !fixme++)
  {
    FIXME("Unimplemented flags %x\n", parentStorage->openFlags);
  }

  return TransactedSnapshotImpl_Construct(parentStorage,
    (TransactedSnapshotImpl**)result);
}

static HRESULT Storage_Construct(
  HANDLE       hFile,
  LPCOLESTR    pwcsName,
  ILockBytes*  pLkbyt,
  DWORD        openFlags,
  BOOL         fileBased,
  BOOL         create,
5161
  ULONG        sector_size,
5162 5163 5164 5165 5166 5167
  StorageBaseImpl** result)
{
  StorageImpl *newStorage;
  StorageBaseImpl *newTransactedStorage;
  HRESULT hr;

5168
  hr = StorageImpl_Construct(hFile, pwcsName, pLkbyt, openFlags, fileBased, create, sector_size, &newStorage);
5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185
  if (FAILED(hr)) goto end;

  if (openFlags & STGM_TRANSACTED)
  {
    hr = Storage_ConstructTransacted(&newStorage->base, &newTransactedStorage);
    if (FAILED(hr))
      IStorage_Release((IStorage*)newStorage);
    else
      *result = newTransactedStorage;
  }
  else
    *result = &newStorage->base;

end:
  return hr;
}

5186
static void StorageInternalImpl_Invalidate( StorageBaseImpl *base )
5187
{
5188 5189
  StorageInternalImpl* This = (StorageInternalImpl*) base;

5190
  if (!This->base.reverted)
5191 5192 5193
  {
    TRACE("Storage invalidated (stg=%p)\n", This);

5194 5195 5196 5197
    This->base.reverted = 1;

    This->parentStorage = NULL;

5198 5199 5200 5201 5202 5203
    StorageBaseImpl_DeleteAll(&This->base);

    list_remove(&This->ParentListEntry);
  }
}

5204
static void StorageInternalImpl_Destroy( StorageBaseImpl *iface)
5205
{
5206 5207
  StorageInternalImpl* This = (StorageInternalImpl*) iface;

5208
  StorageInternalImpl_Invalidate(&This->base);
5209

5210 5211 5212
  HeapFree(GetProcessHeap(), 0, This);
}

5213 5214 5215 5216 5217 5218 5219
static HRESULT StorageInternalImpl_Flush(StorageBaseImpl* iface)
{
  StorageInternalImpl* This = (StorageInternalImpl*) iface;

  return StorageBaseImpl_Flush(This->parentStorage);
}

5220 5221 5222 5223 5224 5225 5226
static HRESULT StorageInternalImpl_GetFilename(StorageBaseImpl* iface, LPWSTR *result)
{
  StorageInternalImpl* This = (StorageInternalImpl*) iface;

  return StorageBaseImpl_GetFilename(This->parentStorage, result);
}

5227 5228 5229
static HRESULT StorageInternalImpl_CreateDirEntry(StorageBaseImpl *base,
  const DirEntry *newData, DirRef *index)
{
5230 5231 5232
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_CreateDirEntry(This->parentStorage,
5233 5234 5235
    newData, index);
}

5236 5237 5238
static HRESULT StorageInternalImpl_WriteDirEntry(StorageBaseImpl *base,
  DirRef index, const DirEntry *data)
{
5239 5240 5241
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_WriteDirEntry(This->parentStorage,
5242 5243 5244
    index, data);
}

5245 5246 5247
static HRESULT StorageInternalImpl_ReadDirEntry(StorageBaseImpl *base,
  DirRef index, DirEntry *data)
{
5248 5249 5250
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_ReadDirEntry(This->parentStorage,
5251 5252 5253
    index, data);
}

5254 5255 5256
static HRESULT StorageInternalImpl_DestroyDirEntry(StorageBaseImpl *base,
  DirRef index)
{
5257 5258 5259
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_DestroyDirEntry(This->parentStorage,
5260 5261 5262
    index);
}

5263 5264 5265
static HRESULT StorageInternalImpl_StreamReadAt(StorageBaseImpl *base,
  DirRef index, ULARGE_INTEGER offset, ULONG size, void *buffer, ULONG *bytesRead)
{
5266 5267 5268
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_StreamReadAt(This->parentStorage,
5269 5270 5271
    index, offset, size, buffer, bytesRead);
}

5272 5273 5274
static HRESULT StorageInternalImpl_StreamWriteAt(StorageBaseImpl *base,
  DirRef index, ULARGE_INTEGER offset, ULONG size, const void *buffer, ULONG *bytesWritten)
{
5275 5276 5277
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_StreamWriteAt(This->parentStorage,
5278 5279 5280
    index, offset, size, buffer, bytesWritten);
}

5281 5282 5283
static HRESULT StorageInternalImpl_StreamSetSize(StorageBaseImpl *base,
  DirRef index, ULARGE_INTEGER newsize)
{
5284 5285 5286
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_StreamSetSize(This->parentStorage,
5287 5288 5289
    index, newsize);
}

5290 5291 5292 5293 5294 5295 5296 5297 5298
static HRESULT StorageInternalImpl_StreamLink(StorageBaseImpl *base,
  DirRef dst, DirRef src)
{
  StorageInternalImpl* This = (StorageInternalImpl*) base;

  return StorageBaseImpl_StreamLink(This->parentStorage,
    dst, src);
}

5299 5300 5301 5302 5303
/******************************************************************************
**
** Storage32InternalImpl_Commit
**
*/
5304
static HRESULT WINAPI StorageInternalImpl_Commit(
5305
  IStorage*            iface,
5306
  DWORD                  grfCommitFlags)  /* [in] */
5307
{
5308 5309 5310
  StorageBaseImpl* base = (StorageBaseImpl*) iface;
  TRACE("(%p,%x)\n", iface, grfCommitFlags);
  return StorageBaseImpl_Flush(base);
5311
}
5312

5313 5314 5315 5316 5317
/******************************************************************************
**
** Storage32InternalImpl_Revert
**
*/
5318
static HRESULT WINAPI StorageInternalImpl_Revert(
5319
  IStorage*            iface)
5320
{
5321
  FIXME("(%p): stub\n", iface);
5322 5323 5324
  return S_OK;
}

5325
static void IEnumSTATSTGImpl_Destroy(IEnumSTATSTGImpl* This)
5326
{
5327
  IStorage_Release((IStorage*)This->parentStorage);
5328 5329 5330
  HeapFree(GetProcessHeap(), 0, This);
}

5331
static HRESULT WINAPI IEnumSTATSTGImpl_QueryInterface(
5332
  IEnumSTATSTG*     iface,
5333 5334 5335
  REFIID            riid,
  void**            ppvObject)
{
5336
  IEnumSTATSTGImpl* const This = impl_from_IEnumSTATSTG(iface);
5337

5338 5339 5340 5341 5342
  if (ppvObject==0)
    return E_INVALIDARG;

  *ppvObject = 0;

5343
  if (IsEqualGUID(&IID_IUnknown, riid) ||
5344
      IsEqualGUID(&IID_IEnumSTATSTG, riid))
5345
  {
5346
    *ppvObject = This;
5347
    IEnumSTATSTG_AddRef(&This->IEnumSTATSTG_iface);
5348
    return S_OK;
5349 5350
  }

5351
  return E_NOINTERFACE;
5352
}
5353

5354
static ULONG   WINAPI IEnumSTATSTGImpl_AddRef(
5355
  IEnumSTATSTG* iface)
5356
{
5357
  IEnumSTATSTGImpl* const This = impl_from_IEnumSTATSTG(iface);
5358
  return InterlockedIncrement(&This->ref);
5359
}
5360

5361
static ULONG   WINAPI IEnumSTATSTGImpl_Release(
5362
  IEnumSTATSTG* iface)
5363
{
5364
  IEnumSTATSTGImpl* const This = impl_from_IEnumSTATSTG(iface);
5365

5366 5367
  ULONG newRef;

5368
  newRef = InterlockedDecrement(&This->ref);
5369 5370 5371 5372 5373 5374

  if (newRef==0)
  {
    IEnumSTATSTGImpl_Destroy(This);
  }

5375
  return newRef;
5376 5377
}

5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422
static HRESULT IEnumSTATSTGImpl_GetNextRef(
  IEnumSTATSTGImpl* This,
  DirRef *ref)
{
  DirRef result = DIRENTRY_NULL;
  DirRef searchNode;
  DirEntry entry;
  HRESULT hr;
  WCHAR result_name[DIRENTRY_NAME_MAX_LEN];

  hr = StorageBaseImpl_ReadDirEntry(This->parentStorage,
    This->parentStorage->storageDirEntry, &entry);
  searchNode = entry.dirRootEntry;

  while (SUCCEEDED(hr) && searchNode != DIRENTRY_NULL)
  {
    hr = StorageBaseImpl_ReadDirEntry(This->parentStorage, searchNode, &entry);

    if (SUCCEEDED(hr))
    {
      LONG diff = entryNameCmp( entry.name, This->name);

      if (diff <= 0)
      {
        searchNode = entry.rightChild;
      }
      else
      {
        result = searchNode;
        memcpy(result_name, entry.name, sizeof(result_name));
        searchNode = entry.leftChild;
      }
    }
  }

  if (SUCCEEDED(hr))
  {
    *ref = result;
    if (result != DIRENTRY_NULL)
      memcpy(This->name, result_name, sizeof(result_name));
  }

  return hr;
}

5423
static HRESULT WINAPI IEnumSTATSTGImpl_Next(
5424
  IEnumSTATSTG* iface,
5425 5426 5427 5428
  ULONG             celt,
  STATSTG*          rgelt,
  ULONG*            pceltFetched)
{
5429
  IEnumSTATSTGImpl* const This = impl_from_IEnumSTATSTG(iface);
5430

5431
  DirEntry    currentEntry;
5432 5433
  STATSTG*    currentReturnStruct = rgelt;
  ULONG       objectFetched       = 0;
5434
  DirRef      currentSearchNode;
5435
  HRESULT     hr=S_OK;
5436 5437

  if ( (rgelt==0) || ( (celt!=1) && (pceltFetched==0) ) )
5438 5439
    return E_INVALIDARG;

5440 5441 5442
  if (This->parentStorage->reverted)
    return STG_E_REVERTED;

5443 5444 5445 5446 5447 5448
  /*
   * To avoid the special case, get another pointer to a ULONG value if
   * the caller didn't supply one.
   */
  if (pceltFetched==0)
    pceltFetched = &objectFetched;
5449

5450 5451 5452 5453 5454 5455
  /*
   * Start the iteration, we will iterate until we hit the end of the
   * linked list or until we hit the number of items to iterate through
   */
  *pceltFetched = 0;

5456
  while ( *pceltFetched < celt )
5457
  {
5458 5459 5460 5461
    hr = IEnumSTATSTGImpl_GetNextRef(This, &currentSearchNode);

    if (FAILED(hr) || currentSearchNode == DIRENTRY_NULL)
      break;
5462 5463

    /*
5464
     * Read the entry from the storage.
5465
     */
5466
    StorageBaseImpl_ReadDirEntry(This->parentStorage,
5467
      currentSearchNode,
5468
      &currentEntry);
5469 5470 5471 5472

    /*
     * Copy the information to the return buffer.
     */
5473
    StorageUtl_CopyDirEntryToSTATSTG(This->parentStorage,
5474
      currentReturnStruct,
5475
      &currentEntry,
5476
      STATFLAG_DEFAULT);
5477

5478 5479 5480 5481 5482 5483 5484
    /*
     * Step to the next item in the iteration
     */
    (*pceltFetched)++;
    currentReturnStruct++;
  }

5485 5486
  if (SUCCEEDED(hr) && *pceltFetched != celt)
    hr = S_FALSE;
5487

5488
  return hr;
5489 5490
}

5491

5492
static HRESULT WINAPI IEnumSTATSTGImpl_Skip(
5493
  IEnumSTATSTG* iface,
5494 5495
  ULONG             celt)
{
5496
  IEnumSTATSTGImpl* const This = impl_from_IEnumSTATSTG(iface);
5497

5498
  ULONG       objectFetched = 0;
5499
  DirRef      currentSearchNode;
5500
  HRESULT     hr=S_OK;
5501

5502 5503 5504
  if (This->parentStorage->reverted)
    return STG_E_REVERTED;

5505
  while ( (objectFetched < celt) )
5506
  {
5507
    hr = IEnumSTATSTGImpl_GetNextRef(This, &currentSearchNode);
5508

5509 5510
    if (FAILED(hr) || currentSearchNode == DIRENTRY_NULL)
      break;
5511

5512 5513 5514
    objectFetched++;
  }

5515 5516
  if (SUCCEEDED(hr) && objectFetched != celt)
    return S_FALSE;
5517

5518
  return hr;
5519
}
5520

5521
static HRESULT WINAPI IEnumSTATSTGImpl_Reset(
5522
  IEnumSTATSTG* iface)
5523
{
5524
  IEnumSTATSTGImpl* const This = impl_from_IEnumSTATSTG(iface);
5525

5526 5527 5528
  if (This->parentStorage->reverted)
    return STG_E_REVERTED;

5529
  This->name[0] = 0;
5530

5531
  return S_OK;
5532
}
5533

5534
static HRESULT WINAPI IEnumSTATSTGImpl_Clone(
5535
  IEnumSTATSTG* iface,
5536 5537
  IEnumSTATSTG**    ppenum)
{
5538
  IEnumSTATSTGImpl* const This = impl_from_IEnumSTATSTG(iface);
5539

5540 5541
  IEnumSTATSTGImpl* newClone;

5542 5543 5544
  if (This->parentStorage->reverted)
    return STG_E_REVERTED;

5545 5546 5547 5548 5549
  /*
   * Perform a sanity check on the parameters.
   */
  if (ppenum==0)
    return E_INVALIDARG;
5550

5551
  newClone = IEnumSTATSTGImpl_Construct(This->parentStorage,
5552
               This->storageDirEntry);
5553

5554

5555 5556 5557 5558
  /*
   * The new clone enumeration must point to the same current node as
   * the ole one.
   */
5559
  memcpy(newClone->name, This->name, sizeof(newClone->name));
5560

5561
  *ppenum = &newClone->IEnumSTATSTG_iface;
5562

5563 5564 5565 5566
  /*
   * Don't forget to nail down a reference to the clone before
   * returning it.
   */
5567
  IEnumSTATSTGImpl_AddRef(*ppenum);
5568 5569 5570 5571

  return S_OK;
}

5572 5573 5574
/*
 * Virtual function table for the IEnumSTATSTGImpl class.
 */
5575
static const IEnumSTATSTGVtbl IEnumSTATSTGImpl_Vtbl =
5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589
{
    IEnumSTATSTGImpl_QueryInterface,
    IEnumSTATSTGImpl_AddRef,
    IEnumSTATSTGImpl_Release,
    IEnumSTATSTGImpl_Next,
    IEnumSTATSTGImpl_Skip,
    IEnumSTATSTGImpl_Reset,
    IEnumSTATSTGImpl_Clone
};

/******************************************************************************
** IEnumSTATSTGImpl implementation
*/

5590
static IEnumSTATSTGImpl* IEnumSTATSTGImpl_Construct(
5591
  StorageBaseImpl* parentStorage,
5592
  DirRef         storageDirEntry)
5593 5594 5595 5596 5597 5598 5599 5600 5601 5602
{
  IEnumSTATSTGImpl* newEnumeration;

  newEnumeration = HeapAlloc(GetProcessHeap(), 0, sizeof(IEnumSTATSTGImpl));

  if (newEnumeration!=0)
  {
    /*
     * Set-up the virtual function table and reference count.
     */
5603
    newEnumeration->IEnumSTATSTG_iface.lpVtbl = &IEnumSTATSTGImpl_Vtbl;
5604 5605 5606 5607 5608 5609 5610 5611 5612
    newEnumeration->ref       = 0;

    /*
     * We want to nail-down the reference to the storage in case the
     * enumeration out-lives the storage in the client application.
     */
    newEnumeration->parentStorage = parentStorage;
    IStorage_AddRef((IStorage*)newEnumeration->parentStorage);

5613
    newEnumeration->storageDirEntry   = storageDirEntry;
5614 5615 5616 5617

    /*
     * Make sure the current node of the iterator is the first one.
     */
5618
    IEnumSTATSTGImpl_Reset(&newEnumeration->IEnumSTATSTG_iface);
5619 5620 5621 5622 5623 5624 5625 5626
  }

  return newEnumeration;
}

/*
 * Virtual function table for the Storage32InternalImpl class.
 */
5627
static const IStorageVtbl Storage32InternalImpl_Vtbl =
5628 5629 5630 5631 5632 5633
{
    StorageBaseImpl_QueryInterface,
    StorageBaseImpl_AddRef,
    StorageBaseImpl_Release,
    StorageBaseImpl_CreateStream,
    StorageBaseImpl_OpenStream,
5634
    StorageBaseImpl_CreateStorage,
5635
    StorageBaseImpl_OpenStorage,
5636
    StorageBaseImpl_CopyTo,
5637
    StorageBaseImpl_MoveElementTo,
5638 5639 5640
    StorageInternalImpl_Commit,
    StorageInternalImpl_Revert,
    StorageBaseImpl_EnumElements,
5641
    StorageBaseImpl_DestroyElement,
5642
    StorageBaseImpl_RenameElement,
5643
    StorageBaseImpl_SetElementTimes,
5644
    StorageBaseImpl_SetClass,
5645
    StorageBaseImpl_SetStateBits,
5646 5647 5648
    StorageBaseImpl_Stat
};

5649 5650
static const StorageBaseImplVtbl StorageInternalImpl_BaseVtbl =
{
5651
  StorageInternalImpl_Destroy,
5652
  StorageInternalImpl_Invalidate,
5653
  StorageInternalImpl_Flush,
5654
  StorageInternalImpl_GetFilename,
5655
  StorageInternalImpl_CreateDirEntry,
5656
  StorageInternalImpl_WriteDirEntry,
5657
  StorageInternalImpl_ReadDirEntry,
5658
  StorageInternalImpl_DestroyDirEntry,
5659
  StorageInternalImpl_StreamReadAt,
5660
  StorageInternalImpl_StreamWriteAt,
5661 5662
  StorageInternalImpl_StreamSetSize,
  StorageInternalImpl_StreamLink
5663 5664
};

5665 5666 5667 5668
/******************************************************************************
** Storage32InternalImpl implementation
*/

5669
static StorageInternalImpl* StorageInternalImpl_Construct(
5670
  StorageBaseImpl* parentStorage,
5671
  DWORD        openFlags,
5672
  DirRef       storageDirEntry)
5673 5674 5675
{
  StorageInternalImpl* newStorage;

5676
  newStorage = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(StorageInternalImpl));
5677 5678 5679

  if (newStorage!=0)
  {
5680
    list_init(&newStorage->base.strmHead);
5681 5682

    list_init(&newStorage->base.storageHead);
5683

5684 5685 5686 5687
    /*
     * Initialize the virtual function table.
     */
    newStorage->base.lpVtbl = &Storage32InternalImpl_Vtbl;
5688
    newStorage->base.pssVtbl = &IPropertySetStorage_Vtbl;
5689
    newStorage->base.baseVtbl = &StorageInternalImpl_BaseVtbl;
5690
    newStorage->base.openFlags = (openFlags & ~STGM_CREATE);
5691

5692 5693
    newStorage->base.reverted = 0;

5694 5695
    newStorage->base.ref = 1;

5696
    newStorage->parentStorage = parentStorage;
5697 5698

    /*
5699
     * Keep a reference to the directory entry of this storage
5700
     */
5701
    newStorage->base.storageDirEntry = storageDirEntry;
5702

5703 5704
    newStorage->base.create = 0;

5705 5706 5707 5708 5709 5710
    return newStorage;
  }

  return 0;
}

5711 5712 5713 5714
/******************************************************************************
** StorageUtl implementation
*/

5715
void StorageUtl_ReadWord(const BYTE* buffer, ULONG offset, WORD* value)
5716
{
5717 5718 5719
  WORD tmp;

  memcpy(&tmp, buffer+offset, sizeof(WORD));
5720
  *value = lendian16toh(tmp);
5721 5722
}

5723
void StorageUtl_WriteWord(BYTE* buffer, ULONG offset, WORD value)
5724
{
5725
  value = htole16(value);
5726
  memcpy(buffer+offset, &value, sizeof(WORD));
5727 5728
}

5729
void StorageUtl_ReadDWord(const BYTE* buffer, ULONG offset, DWORD* value)
5730
{
5731 5732 5733
  DWORD tmp;

  memcpy(&tmp, buffer+offset, sizeof(DWORD));
5734
  *value = lendian32toh(tmp);
5735 5736
}

5737
void StorageUtl_WriteDWord(BYTE* buffer, ULONG offset, DWORD value)
5738
{
5739
  value = htole32(value);
5740
  memcpy(buffer+offset, &value, sizeof(DWORD));
5741 5742
}

Juan Lang's avatar
Juan Lang committed
5743 5744 5745 5746 5747 5748 5749
void StorageUtl_ReadULargeInteger(const BYTE* buffer, ULONG offset,
 ULARGE_INTEGER* value)
{
#ifdef WORDS_BIGENDIAN
    ULARGE_INTEGER tmp;

    memcpy(&tmp, buffer + offset, sizeof(ULARGE_INTEGER));
5750 5751
    value->u.LowPart = htole32(tmp.u.HighPart);
    value->u.HighPart = htole32(tmp.u.LowPart);
Juan Lang's avatar
Juan Lang committed
5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762
#else
    memcpy(value, buffer + offset, sizeof(ULARGE_INTEGER));
#endif
}

void StorageUtl_WriteULargeInteger(BYTE* buffer, ULONG offset,
 const ULARGE_INTEGER *value)
{
#ifdef WORDS_BIGENDIAN
    ULARGE_INTEGER tmp;

5763 5764
    tmp.u.LowPart = htole32(value->u.HighPart);
    tmp.u.HighPart = htole32(value->u.LowPart);
Juan Lang's avatar
Juan Lang committed
5765 5766 5767 5768 5769 5770
    memcpy(buffer + offset, &tmp, sizeof(ULARGE_INTEGER));
#else
    memcpy(buffer + offset, value, sizeof(ULARGE_INTEGER));
#endif
}

5771
void StorageUtl_ReadGUID(const BYTE* buffer, ULONG offset, GUID* value)
5772 5773 5774 5775 5776
{
  StorageUtl_ReadDWord(buffer, offset,   &(value->Data1));
  StorageUtl_ReadWord(buffer,  offset+4, &(value->Data2));
  StorageUtl_ReadWord(buffer,  offset+6, &(value->Data3));

5777
  memcpy(value->Data4, buffer+offset+8, sizeof(value->Data4));
5778 5779
}

5780
void StorageUtl_WriteGUID(BYTE* buffer, ULONG offset, const GUID* value)
5781 5782 5783 5784 5785
{
  StorageUtl_WriteDWord(buffer, offset,   value->Data1);
  StorageUtl_WriteWord(buffer,  offset+4, value->Data2);
  StorageUtl_WriteWord(buffer,  offset+6, value->Data3);

5786
  memcpy(buffer+offset+8, value->Data4, sizeof(value->Data4));
5787 5788
}

5789
void StorageUtl_CopyDirEntryToSTATSTG(
5790
  StorageBaseImpl*      storage,
5791
  STATSTG*              destination,
5792
  const DirEntry*       source,
5793
  int                   statFlags)
5794 5795 5796 5797
{
  /*
   * The copy of the string occurs only when the flag is not set
   */
5798 5799 5800 5801 5802 5803 5804 5805
  if (!(statFlags & STATFLAG_NONAME) && source->stgType == STGTY_ROOT)
  {
    /* Use the filename for the root storage. */
    destination->pwcsName = 0;
    StorageBaseImpl_GetFilename(storage, &destination->pwcsName);
  }
  else if( ((statFlags & STATFLAG_NONAME) != 0) ||
       (source->name[0] == 0) )
5806 5807 5808 5809 5810
  {
    destination->pwcsName = 0;
  }
  else
  {
5811
    destination->pwcsName =
5812
      CoTaskMemAlloc((lstrlenW(source->name)+1)*sizeof(WCHAR));
5813

5814
    strcpyW(destination->pwcsName, source->name);
5815
  }
5816

5817
  switch (source->stgType)
5818
  {
5819 5820
    case STGTY_STORAGE:
    case STGTY_ROOT:
5821 5822
      destination->type = STGTY_STORAGE;
      break;
5823
    case STGTY_STREAM:
5824 5825 5826 5827
      destination->type = STGTY_STREAM;
      break;
    default:
      destination->type = STGTY_STREAM;
5828
      break;
5829 5830 5831
  }

  destination->cbSize            = source->size;
5832
/*
5833 5834
  currentReturnStruct->mtime     = {0}; TODO
  currentReturnStruct->ctime     = {0};
5835
  currentReturnStruct->atime     = {0};
5836 5837
*/
  destination->grfMode           = 0;
5838
  destination->grfLocksSupported = 0;
5839
  destination->clsid             = source->clsid;
5840 5841
  destination->grfStateBits      = 0;
  destination->reserved          = 0;
5842 5843 5844 5845 5846 5847
}

/******************************************************************************
** BlockChainStream implementation
*/

5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954
/* Read and save the index of all blocks in this stream. */
HRESULT BlockChainStream_UpdateIndexCache(BlockChainStream* This)
{
  ULONG  next_sector, next_offset;
  HRESULT hr;
  struct BlockChainRun *last_run;

  if (This->indexCacheLen == 0)
  {
    last_run = NULL;
    next_offset = 0;
    next_sector = BlockChainStream_GetHeadOfChain(This);
  }
  else
  {
    last_run = &This->indexCache[This->indexCacheLen-1];
    next_offset = last_run->lastOffset+1;
    hr = StorageImpl_GetNextBlockInChain(This->parentStorage,
        last_run->firstSector + last_run->lastOffset - last_run->firstOffset,
        &next_sector);
    if (FAILED(hr)) return hr;
  }

  while (next_sector != BLOCK_END_OF_CHAIN)
  {
    if (!last_run || next_sector != last_run->firstSector + next_offset - last_run->firstOffset)
    {
      /* Add the current block to the cache. */
      if (This->indexCacheSize == 0)
      {
        This->indexCache = HeapAlloc(GetProcessHeap(), 0, sizeof(struct BlockChainRun)*16);
        if (!This->indexCache) return E_OUTOFMEMORY;
        This->indexCacheSize = 16;
      }
      else if (This->indexCacheSize == This->indexCacheLen)
      {
        struct BlockChainRun *new_cache;
        ULONG new_size;

        new_size = This->indexCacheSize * 2;
        new_cache = HeapAlloc(GetProcessHeap(), 0, sizeof(struct BlockChainRun)*new_size);
        if (!new_cache) return E_OUTOFMEMORY;
        memcpy(new_cache, This->indexCache, sizeof(struct BlockChainRun)*This->indexCacheLen);

        HeapFree(GetProcessHeap(), 0, This->indexCache);
        This->indexCache = new_cache;
        This->indexCacheSize = new_size;
      }

      This->indexCacheLen++;
      last_run = &This->indexCache[This->indexCacheLen-1];
      last_run->firstSector = next_sector;
      last_run->firstOffset = next_offset;
    }

    last_run->lastOffset = next_offset;

    /* Find the next block. */
    next_offset++;
    hr = StorageImpl_GetNextBlockInChain(This->parentStorage, next_sector, &next_sector);
    if (FAILED(hr)) return hr;
  }

  if (This->indexCacheLen)
  {
    This->tailIndex = last_run->firstSector + last_run->lastOffset - last_run->firstOffset;
    This->numBlocks = last_run->lastOffset+1;
  }
  else
  {
    This->tailIndex = BLOCK_END_OF_CHAIN;
    This->numBlocks = 0;
  }

  return S_OK;
}

/* Locate the nth block in this stream. */
ULONG BlockChainStream_GetSectorOfOffset(BlockChainStream *This, ULONG offset)
{
  ULONG min_offset = 0, max_offset = This->numBlocks-1;
  ULONG min_run = 0, max_run = This->indexCacheLen-1;

  if (offset >= This->numBlocks)
    return BLOCK_END_OF_CHAIN;

  while (min_run < max_run)
  {
    ULONG run_to_check = min_run + (offset - min_offset) * (max_run - min_run) / (max_offset - min_offset);
    if (offset < This->indexCache[run_to_check].firstOffset)
    {
      max_offset = This->indexCache[run_to_check].firstOffset-1;
      max_run = run_to_check-1;
    }
    else if (offset > This->indexCache[run_to_check].lastOffset)
    {
      min_offset = This->indexCache[run_to_check].lastOffset+1;
      min_run = run_to_check+1;
    }
    else
      /* Block is in this run. */
      min_run = max_run = run_to_check;
  }

  return This->indexCache[min_run].firstSector + offset - This->indexCache[min_run].firstOffset;
}

5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001
HRESULT BlockChainStream_GetBlockAtOffset(BlockChainStream *This,
    ULONG index, BlockChainBlock **block, ULONG *sector, BOOL create)
{
  BlockChainBlock *result=NULL;
  int i;

  for (i=0; i<2; i++)
    if (This->cachedBlocks[i].index == index)
    {
      *sector = This->cachedBlocks[i].sector;
      *block = &This->cachedBlocks[i];
      return S_OK;
    }

  *sector = BlockChainStream_GetSectorOfOffset(This, index);
  if (*sector == BLOCK_END_OF_CHAIN)
    return STG_E_DOCFILECORRUPT;

  if (create)
  {
    if (This->cachedBlocks[0].index == 0xffffffff)
      result = &This->cachedBlocks[0];
    else if (This->cachedBlocks[1].index == 0xffffffff)
      result = &This->cachedBlocks[1];
    else
    {
      result = &This->cachedBlocks[This->blockToEvict++];
      if (This->blockToEvict == 2)
        This->blockToEvict = 0;
    }

    if (result->dirty)
    {
      if (!StorageImpl_WriteBigBlock(This->parentStorage, result->sector, result->data))
        return STG_E_WRITEFAULT;
      result->dirty = 0;
    }

    result->read = 0;
    result->index = index;
    result->sector = *sector;
  }

  *block = result;
  return S_OK;
}

6002
BlockChainStream* BlockChainStream_Construct(
6003
  StorageImpl* parentStorage,
6004
  ULONG*         headOfStreamPlaceHolder,
6005
  DirRef         dirEntry)
6006 6007 6008 6009 6010 6011 6012
{
  BlockChainStream* newStream;

  newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(BlockChainStream));

  newStream->parentStorage           = parentStorage;
  newStream->headOfStreamPlaceHolder = headOfStreamPlaceHolder;
6013
  newStream->ownerDirEntry           = dirEntry;
6014 6015 6016
  newStream->indexCache              = NULL;
  newStream->indexCacheLen           = 0;
  newStream->indexCacheSize          = 0;
6017 6018 6019 6020 6021
  newStream->cachedBlocks[0].index = 0xffffffff;
  newStream->cachedBlocks[0].dirty = 0;
  newStream->cachedBlocks[1].index = 0xffffffff;
  newStream->cachedBlocks[1].dirty = 0;
  newStream->blockToEvict          = 0;
Thuy Nguyen's avatar
Thuy Nguyen committed
6022

6023
  if (FAILED(BlockChainStream_UpdateIndexCache(newStream)))
Thuy Nguyen's avatar
Thuy Nguyen committed
6024
  {
6025 6026 6027
    HeapFree(GetProcessHeap(), 0, newStream->indexCache);
    HeapFree(GetProcessHeap(), 0, newStream);
    return NULL;
Thuy Nguyen's avatar
Thuy Nguyen committed
6028
  }
6029 6030 6031 6032

  return newStream;
}

6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049
HRESULT BlockChainStream_Flush(BlockChainStream* This)
{
  int i;
  if (!This) return S_OK;
  for (i=0; i<2; i++)
  {
    if (This->cachedBlocks[i].dirty)
    {
      if (StorageImpl_WriteBigBlock(This->parentStorage, This->cachedBlocks[i].sector, This->cachedBlocks[i].data))
        This->cachedBlocks[i].dirty = 0;
      else
        return STG_E_WRITEFAULT;
    }
  }
  return S_OK;
}

6050 6051
void BlockChainStream_Destroy(BlockChainStream* This)
{
6052
  if (This)
6053 6054
  {
    BlockChainStream_Flush(This);
6055
    HeapFree(GetProcessHeap(), 0, This->indexCache);
6056
  }
6057 6058 6059 6060 6061 6062 6063
  HeapFree(GetProcessHeap(), 0, This);
}

/******************************************************************************
 *      BlockChainStream_GetHeadOfChain
 *
 * Returns the head of this stream chain.
6064
 * Some special chains don't have directory entries, their heads are kept in
6065 6066 6067
 * This->headOfStreamPlaceHolder.
 *
 */
6068
static ULONG BlockChainStream_GetHeadOfChain(BlockChainStream* This)
6069
{
6070
  DirEntry  chainEntry;
6071
  HRESULT   hr;
6072 6073 6074 6075

  if (This->headOfStreamPlaceHolder != 0)
    return *(This->headOfStreamPlaceHolder);

6076
  if (This->ownerDirEntry != DIRENTRY_NULL)
6077
  {
6078
    hr = StorageImpl_ReadDirEntry(
6079
                      This->parentStorage,
6080
                      This->ownerDirEntry,
6081
                      &chainEntry);
6082

6083
    if (SUCCEEDED(hr))
6084
    {
6085
      return chainEntry.startingBlock;
6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097
    }
  }

  return BLOCK_END_OF_CHAIN;
}

/******************************************************************************
 *       BlockChainStream_GetCount
 *
 * Returns the number of blocks that comprises this chain.
 * This is not the size of the stream as the last block may not be full!
 */
6098
static ULONG BlockChainStream_GetCount(BlockChainStream* This)
6099
{
6100
  return This->numBlocks;
6101 6102 6103
}

/******************************************************************************
6104
 *      BlockChainStream_ReadAt
6105 6106 6107 6108 6109
 *
 * Reads a specified number of bytes from this chain at the specified offset.
 * bytesRead may be NULL.
 * Failure will be returned if the specified number of bytes has not been read.
 */
6110
HRESULT BlockChainStream_ReadAt(BlockChainStream* This,
6111 6112 6113 6114 6115
  ULARGE_INTEGER offset,
  ULONG          size,
  void*          buffer,
  ULONG*         bytesRead)
{
6116 6117
  ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
  ULONG offsetInBlock     = offset.u.LowPart % This->parentStorage->bigBlockSize;
6118 6119 6120
  ULONG bytesToReadInBuffer;
  ULONG blockIndex;
  BYTE* bufferWalker;
6121
  ULARGE_INTEGER stream_size;
6122 6123
  HRESULT hr;
  BlockChainBlock *cachedBlock;
6124 6125

  TRACE("(%p)-> %i %p %i %p\n",This, offset.u.LowPart, buffer, size, bytesRead);
6126 6127 6128 6129

  /*
   * Find the first block in the stream that contains part of the buffer.
   */
6130
  blockIndex = BlockChainStream_GetSectorOfOffset(This, blockNoInSequence);
6131

6132 6133 6134 6135 6136 6137 6138
  *bytesRead   = 0;

  stream_size = BlockChainStream_GetSize(This);
  if (stream_size.QuadPart > offset.QuadPart)
    size = min(stream_size.QuadPart - offset.QuadPart, size);
  else
    return S_OK;
6139

6140 6141 6142 6143
  /*
   * Start reading the buffer.
   */
  bufferWalker = buffer;
6144

6145
  while (size > 0)
6146
  {
6147 6148
    ULARGE_INTEGER ulOffset;
    DWORD bytesReadAt;
6149

6150 6151 6152
    /*
     * Calculate how many bytes we can copy from this big block.
     */
6153
    bytesToReadInBuffer =
6154
      min(This->parentStorage->bigBlockSize - offsetInBlock, size);
6155

6156
    hr = BlockChainStream_GetBlockAtOffset(This, blockNoInSequence, &cachedBlock, &blockIndex, size == bytesToReadInBuffer);
6157

6158 6159
    if (FAILED(hr))
      return hr;
6160

6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188
    if (!cachedBlock)
    {
      /* Not in cache, and we're going to read past the end of the block. */
      ulOffset.u.HighPart = 0;
      ulOffset.u.LowPart = StorageImpl_GetBigBlockOffset(This->parentStorage, blockIndex) +
                               offsetInBlock;

      StorageImpl_ReadAt(This->parentStorage,
           ulOffset,
           bufferWalker,
           bytesToReadInBuffer,
           &bytesReadAt);
    }
    else
    {
      if (!cachedBlock->read)
      {
        if (!StorageImpl_ReadBigBlock(This->parentStorage, cachedBlock->sector, cachedBlock->data))
          return STG_E_READFAULT;

        cachedBlock->read = 1;
      }

      memcpy(bufferWalker, cachedBlock->data+offsetInBlock, bytesToReadInBuffer);
      bytesReadAt = bytesToReadInBuffer;
    }

    blockNoInSequence++;
6189 6190 6191
    bufferWalker += bytesReadAt;
    size         -= bytesReadAt;
    *bytesRead   += bytesReadAt;
6192 6193
    offsetInBlock = 0;  /* There is no offset on the next block */

6194 6195
    if (bytesToReadInBuffer != bytesReadAt)
        break;
6196
  }
6197

6198
  return S_OK;
6199 6200 6201 6202 6203 6204 6205 6206
}

/******************************************************************************
 *      BlockChainStream_WriteAt
 *
 * Writes the specified number of bytes to this chain at the specified offset.
 * Will fail if not all specified number of bytes have been written.
 */
6207
HRESULT BlockChainStream_WriteAt(BlockChainStream* This,
6208 6209 6210 6211 6212
  ULARGE_INTEGER    offset,
  ULONG             size,
  const void*       buffer,
  ULONG*            bytesWritten)
{
6213 6214
  ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
  ULONG offsetInBlock     = offset.u.LowPart % This->parentStorage->bigBlockSize;
6215 6216
  ULONG bytesToWrite;
  ULONG blockIndex;
Eric Pouech's avatar
Eric Pouech committed
6217
  const BYTE* bufferWalker;
6218 6219
  HRESULT hr;
  BlockChainBlock *cachedBlock;
6220

6221
  *bytesWritten   = 0;
6222
  bufferWalker = buffer;
6223

6224
  while (size > 0)
6225
  {
6226 6227
    ULARGE_INTEGER ulOffset;
    DWORD bytesWrittenAt;
6228

6229
    /*
6230
     * Calculate how many bytes we can copy to this big block.
6231
     */
6232
    bytesToWrite =
6233
      min(This->parentStorage->bigBlockSize - offsetInBlock, size);
6234

6235
    hr = BlockChainStream_GetBlockAtOffset(This, blockNoInSequence, &cachedBlock, &blockIndex, size == bytesToWrite);
6236

6237 6238 6239 6240 6241 6242 6243
    /* BlockChainStream_SetSize should have already been called to ensure we have
     * enough blocks in the chain to write into */
    if (FAILED(hr))
    {
      ERR("not enough blocks in chain to write data\n");
      return hr;
    }
6244

6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270
    if (!cachedBlock)
    {
      /* Not in cache, and we're going to write past the end of the block. */
      ulOffset.u.HighPart = 0;
      ulOffset.u.LowPart = StorageImpl_GetBigBlockOffset(This->parentStorage, blockIndex) +
                               offsetInBlock;

      StorageImpl_WriteAt(This->parentStorage,
           ulOffset,
           bufferWalker,
           bytesToWrite,
           &bytesWrittenAt);
    }
    else
    {
      if (!cachedBlock->read && bytesToWrite != This->parentStorage->bigBlockSize)
      {
        if (!StorageImpl_ReadBigBlock(This->parentStorage, cachedBlock->sector, cachedBlock->data))
          return STG_E_READFAULT;
      }

      memcpy(cachedBlock->data+offsetInBlock, bufferWalker, bytesToWrite);
      bytesWrittenAt = bytesToWrite;
      cachedBlock->read = 1;
      cachedBlock->dirty = 1;
    }
6271

6272
    blockNoInSequence++;
6273 6274 6275
    bufferWalker  += bytesWrittenAt;
    size          -= bytesWrittenAt;
    *bytesWritten += bytesWrittenAt;
6276
    offsetInBlock  = 0;      /* There is no offset on the next block */
6277 6278 6279

    if (bytesWrittenAt != bytesToWrite)
      break;
6280
  }
6281

6282
  return (size == 0) ? S_OK : STG_E_WRITEFAULT;
6283 6284 6285 6286 6287 6288 6289
}

/******************************************************************************
 *      BlockChainStream_Shrink
 *
 * Shrinks this chain in the big block depot.
 */
6290 6291
static BOOL BlockChainStream_Shrink(BlockChainStream* This,
                                    ULARGE_INTEGER    newSize)
6292
{
6293
  ULONG blockIndex;
6294
  ULONG numBlocks;
6295
  int i;
6296

6297 6298 6299
  /*
   * Figure out how many blocks are needed to contain the new size
   */
6300
  numBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
6301

6302
  if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
6303 6304
    numBlocks++;

6305
  if (numBlocks)
6306
  {
6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318
    /*
     * Go to the new end of chain
     */
    blockIndex = BlockChainStream_GetSectorOfOffset(This, numBlocks-1);

    /* Mark the new end of chain */
    StorageImpl_SetNextBlockInChain(
      This->parentStorage,
      blockIndex,
      BLOCK_END_OF_CHAIN);

    This->tailIndex = blockIndex;
6319
  }
6320 6321 6322 6323 6324 6325 6326 6327 6328 6329
  else
  {
    if (This->headOfStreamPlaceHolder != 0)
    {
      *This->headOfStreamPlaceHolder = BLOCK_END_OF_CHAIN;
    }
    else
    {
      DirEntry chainEntry;
      assert(This->ownerDirEntry != DIRENTRY_NULL);
6330

6331 6332 6333 6334
      StorageImpl_ReadDirEntry(
        This->parentStorage,
        This->ownerDirEntry,
        &chainEntry);
6335

6336 6337 6338 6339 6340 6341 6342 6343 6344 6345
      chainEntry.startingBlock = BLOCK_END_OF_CHAIN;

      StorageImpl_WriteDirEntry(
        This->parentStorage,
        This->ownerDirEntry,
        &chainEntry);
    }

    This->tailIndex = BLOCK_END_OF_CHAIN;
  }
6346

Thuy Nguyen's avatar
Thuy Nguyen committed
6347 6348
  This->numBlocks = numBlocks;

6349 6350 6351
  /*
   * Mark the extra blocks as free
   */
6352
  while (This->indexCacheLen && This->indexCache[This->indexCacheLen-1].lastOffset >= numBlocks)
6353
  {
6354 6355 6356 6357 6358 6359 6360
    struct BlockChainRun *last_run = &This->indexCache[This->indexCacheLen-1];
    StorageImpl_FreeBigBlock(This->parentStorage,
      last_run->firstSector + last_run->lastOffset - last_run->firstOffset);
    if (last_run->lastOffset == last_run->firstOffset)
      This->indexCacheLen--;
    else
      last_run->lastOffset--;
6361 6362
  }

6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374
  /*
   * Reset the last accessed block cache.
   */
  for (i=0; i<2; i++)
  {
    if (This->cachedBlocks[i].index >= numBlocks)
    {
      This->cachedBlocks[i].index = 0xffffffff;
      This->cachedBlocks[i].dirty = 0;
    }
  }

6375 6376 6377 6378 6379 6380 6381 6382
  return TRUE;
}

/******************************************************************************
 *      BlockChainStream_Enlarge
 *
 * Grows this chain in the big block depot.
 */
6383 6384
static BOOL BlockChainStream_Enlarge(BlockChainStream* This,
                                     ULARGE_INTEGER    newSize)
6385 6386 6387 6388 6389 6390 6391 6392
{
  ULONG blockIndex, currentBlock;
  ULONG newNumBlocks;
  ULONG oldNumBlocks = 0;

  blockIndex = BlockChainStream_GetHeadOfChain(This);

  /*
6393
   * Empty chain. Create the head.
6394 6395 6396
   */
  if (blockIndex == BLOCK_END_OF_CHAIN)
  {
6397 6398
    blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
    StorageImpl_SetNextBlockInChain(This->parentStorage,
6399 6400 6401 6402 6403 6404 6405 6406 6407
                                      blockIndex,
                                      BLOCK_END_OF_CHAIN);

    if (This->headOfStreamPlaceHolder != 0)
    {
      *(This->headOfStreamPlaceHolder) = blockIndex;
    }
    else
    {
6408
      DirEntry chainEntry;
6409
      assert(This->ownerDirEntry != DIRENTRY_NULL);
6410

6411
      StorageImpl_ReadDirEntry(
6412
        This->parentStorage,
6413
        This->ownerDirEntry,
6414
        &chainEntry);
6415

6416
      chainEntry.startingBlock = blockIndex;
6417

6418
      StorageImpl_WriteDirEntry(
6419
        This->parentStorage,
6420
        This->ownerDirEntry,
6421
        &chainEntry);
Thuy Nguyen's avatar
Thuy Nguyen committed
6422
    }
6423

Thuy Nguyen's avatar
Thuy Nguyen committed
6424 6425 6426
    This->tailIndex = blockIndex;
    This->numBlocks = 1;
  }
6427 6428 6429 6430

  /*
   * Figure out how many blocks are needed to contain this stream
   */
6431
  newNumBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
6432

6433
  if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
6434 6435 6436 6437 6438
    newNumBlocks++;

  /*
   * Go to the current end of chain
   */
Thuy Nguyen's avatar
Thuy Nguyen committed
6439
  if (This->tailIndex == BLOCK_END_OF_CHAIN)
6440 6441 6442
  {
    currentBlock = blockIndex;

Thuy Nguyen's avatar
Thuy Nguyen committed
6443 6444 6445 6446 6447
    while (blockIndex != BLOCK_END_OF_CHAIN)
    {
      This->numBlocks++;
      currentBlock = blockIndex;

6448 6449 6450
      if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, currentBlock,
						&blockIndex)))
	return FALSE;
Thuy Nguyen's avatar
Thuy Nguyen committed
6451 6452 6453
    }

    This->tailIndex = currentBlock;
6454 6455
  }

Thuy Nguyen's avatar
Thuy Nguyen committed
6456 6457 6458
  currentBlock = This->tailIndex;
  oldNumBlocks = This->numBlocks;

6459 6460 6461
  /*
   * Add new blocks to the chain
   */
6462
  if (oldNumBlocks < newNumBlocks)
6463
  {
6464 6465 6466
    while (oldNumBlocks < newNumBlocks)
    {
      blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
6467

6468
      StorageImpl_SetNextBlockInChain(
6469 6470
	This->parentStorage,
	currentBlock,
6471
	blockIndex);
6472

6473
      StorageImpl_SetNextBlockInChain(
6474 6475
        This->parentStorage,
	blockIndex,
6476
	BLOCK_END_OF_CHAIN);
6477

6478 6479 6480
      currentBlock = blockIndex;
      oldNumBlocks++;
    }
6481

6482 6483 6484
    This->tailIndex = blockIndex;
    This->numBlocks = newNumBlocks;
  }
Thuy Nguyen's avatar
Thuy Nguyen committed
6485

6486 6487 6488
  if (FAILED(BlockChainStream_UpdateIndexCache(This)))
    return FALSE;

6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499
  return TRUE;
}

/******************************************************************************
 *      BlockChainStream_SetSize
 *
 * Sets the size of this stream. The big block depot will be updated.
 * The file will grow if we grow the chain.
 *
 * TODO: Free the actual blocks in the file when we shrink the chain.
 *       Currently, the blocks are still in the file. So the file size
6500
 *       doesn't shrink even if we shrink streams.
6501
 */
6502
BOOL BlockChainStream_SetSize(
6503 6504 6505 6506 6507
  BlockChainStream* This,
  ULARGE_INTEGER    newSize)
{
  ULARGE_INTEGER size = BlockChainStream_GetSize(This);

6508
  if (newSize.u.LowPart == size.u.LowPart)
6509 6510
    return TRUE;

6511
  if (newSize.u.LowPart < size.u.LowPart)
6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526
  {
    BlockChainStream_Shrink(This, newSize);
  }
  else
  {
    BlockChainStream_Enlarge(This, newSize);
  }

  return TRUE;
}

/******************************************************************************
 *      BlockChainStream_GetSize
 *
 * Returns the size of this chain.
6527
 * Will return the block count if this chain doesn't have a directory entry.
6528
 */
6529
static ULARGE_INTEGER BlockChainStream_GetSize(BlockChainStream* This)
6530
{
6531
  DirEntry chainEntry;
6532 6533 6534

  if(This->headOfStreamPlaceHolder == NULL)
  {
6535
    /*
6536
     * This chain has a directory entry so use the size value from there.
6537
     */
6538
    StorageImpl_ReadDirEntry(
6539
      This->parentStorage,
6540
      This->ownerDirEntry,
6541
      &chainEntry);
6542

6543
    return chainEntry.size;
6544 6545 6546 6547
  }
  else
  {
    /*
6548
     * this chain is a chain that does not have a directory entry, figure out the
6549
     * size by making the product number of used blocks times the
6550 6551 6552
     * size of them
     */
    ULARGE_INTEGER result;
6553
    result.u.HighPart = 0;
6554

6555
    result.u.LowPart  =
6556
      BlockChainStream_GetCount(This) *
6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567
      This->parentStorage->bigBlockSize;

    return result;
  }
}

/******************************************************************************
** SmallBlockChainStream implementation
*/

SmallBlockChainStream* SmallBlockChainStream_Construct(
6568
  StorageImpl* parentStorage,
6569
  ULONG*         headOfStreamPlaceHolder,
6570
  DirRef         dirEntry)
6571 6572 6573 6574 6575 6576
{
  SmallBlockChainStream* newStream;

  newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(SmallBlockChainStream));

  newStream->parentStorage      = parentStorage;
6577
  newStream->headOfStreamPlaceHolder = headOfStreamPlaceHolder;
6578
  newStream->ownerDirEntry      = dirEntry;
6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593

  return newStream;
}

void SmallBlockChainStream_Destroy(
  SmallBlockChainStream* This)
{
  HeapFree(GetProcessHeap(), 0, This);
}

/******************************************************************************
 *      SmallBlockChainStream_GetHeadOfChain
 *
 * Returns the head of this chain of small blocks.
 */
6594
static ULONG SmallBlockChainStream_GetHeadOfChain(
6595 6596
  SmallBlockChainStream* This)
{
6597
  DirEntry  chainEntry;
6598
  HRESULT   hr;
6599

6600 6601 6602
  if (This->headOfStreamPlaceHolder != NULL)
    return *(This->headOfStreamPlaceHolder);

6603
  if (This->ownerDirEntry)
6604
  {
6605
    hr = StorageImpl_ReadDirEntry(
6606
                      This->parentStorage,
6607
                      This->ownerDirEntry,
6608
                      &chainEntry);
6609

6610
    if (SUCCEEDED(hr))
6611
    {
6612
      return chainEntry.startingBlock;
6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623
    }

  }

  return BLOCK_END_OF_CHAIN;
}

/******************************************************************************
 *      SmallBlockChainStream_GetNextBlockInChain
 *
 * Returns the index of the next small block in this chain.
6624
 *
6625 6626 6627 6628
 * Return Values:
 *    - BLOCK_END_OF_CHAIN: end of this chain
 *    - BLOCK_UNUSED: small block 'blockIndex' is free
 */
6629
static HRESULT SmallBlockChainStream_GetNextBlockInChain(
6630
  SmallBlockChainStream* This,
6631 6632
  ULONG                  blockIndex,
  ULONG*                 nextBlockInChain)
6633 6634 6635 6636
{
  ULARGE_INTEGER offsetOfBlockInDepot;
  DWORD  buffer;
  ULONG  bytesRead;
6637
  HRESULT res;
6638

6639 6640
  *nextBlockInChain = BLOCK_END_OF_CHAIN;

6641 6642
  offsetOfBlockInDepot.u.HighPart = 0;
  offsetOfBlockInDepot.u.LowPart  = blockIndex * sizeof(ULONG);
6643 6644 6645 6646

  /*
   * Read those bytes in the buffer from the small block file.
   */
6647
  res = BlockChainStream_ReadAt(
6648 6649 6650 6651 6652 6653
              This->parentStorage->smallBlockDepotChain,
              offsetOfBlockInDepot,
              sizeof(DWORD),
              &buffer,
              &bytesRead);

6654 6655 6656
  if (SUCCEEDED(res) && bytesRead != sizeof(DWORD))
    res = STG_E_READFAULT;

6657
  if (SUCCEEDED(res))
6658
  {
6659
    StorageUtl_ReadDWord((BYTE *)&buffer, 0, nextBlockInChain);
6660
    return S_OK;
6661 6662
  }

6663
  return res;
6664 6665 6666 6667 6668 6669 6670 6671 6672 6673
}

/******************************************************************************
 *       SmallBlockChainStream_SetNextBlockInChain
 *
 * Writes the index of the next block of the specified block in the small
 * block depot.
 * To set the end of chain use BLOCK_END_OF_CHAIN as nextBlock.
 * To flag a block as free use BLOCK_UNUSED as nextBlock.
 */
6674
static void SmallBlockChainStream_SetNextBlockInChain(
6675 6676 6677 6678 6679 6680 6681 6682
  SmallBlockChainStream* This,
  ULONG                  blockIndex,
  ULONG                  nextBlock)
{
  ULARGE_INTEGER offsetOfBlockInDepot;
  DWORD  buffer;
  ULONG  bytesWritten;

6683 6684
  offsetOfBlockInDepot.u.HighPart = 0;
  offsetOfBlockInDepot.u.LowPart  = blockIndex * sizeof(ULONG);
6685

6686
  StorageUtl_WriteDWord((BYTE *)&buffer, 0, nextBlock);
6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703

  /*
   * Read those bytes in the buffer from the small block file.
   */
  BlockChainStream_WriteAt(
    This->parentStorage->smallBlockDepotChain,
    offsetOfBlockInDepot,
    sizeof(DWORD),
    &buffer,
    &bytesWritten);
}

/******************************************************************************
 *      SmallBlockChainStream_FreeBlock
 *
 * Flag small block 'blockIndex' as free in the small block depot.
 */
6704
static void SmallBlockChainStream_FreeBlock(
6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717
  SmallBlockChainStream* This,
  ULONG                  blockIndex)
{
  SmallBlockChainStream_SetNextBlockInChain(This, blockIndex, BLOCK_UNUSED);
}

/******************************************************************************
 *      SmallBlockChainStream_GetNextFreeBlock
 *
 * Returns the index of a free small block. The small block depot will be
 * enlarged if necessary. The small block chain will also be enlarged if
 * necessary.
 */
6718
static ULONG SmallBlockChainStream_GetNextFreeBlock(
6719 6720 6721 6722 6723
  SmallBlockChainStream* This)
{
  ULARGE_INTEGER offsetOfBlockInDepot;
  DWORD buffer;
  ULONG bytesRead;
6724
  ULONG blockIndex = This->parentStorage->firstFreeSmallBlock;
6725
  ULONG nextBlockIndex = BLOCK_END_OF_CHAIN;
6726
  HRESULT res = S_OK;
6727
  ULONG smallBlocksPerBigBlock;
6728 6729 6730
  DirEntry rootEntry;
  ULONG blocksRequired;
  ULARGE_INTEGER old_size, size_required;
6731

6732
  offsetOfBlockInDepot.u.HighPart = 0;
6733 6734 6735 6736 6737 6738

  /*
   * Scan the small block depot for a free block
   */
  while (nextBlockIndex != BLOCK_UNUSED)
  {
6739
    offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
6740

6741
    res = BlockChainStream_ReadAt(
6742 6743 6744 6745 6746 6747 6748 6749 6750
                This->parentStorage->smallBlockDepotChain,
                offsetOfBlockInDepot,
                sizeof(DWORD),
                &buffer,
                &bytesRead);

    /*
     * If we run out of space for the small block depot, enlarge it
     */
6751
    if (SUCCEEDED(res) && bytesRead == sizeof(DWORD))
6752
    {
6753
      StorageUtl_ReadDWord((BYTE *)&buffer, 0, &nextBlockIndex);
6754 6755 6756 6757 6758 6759

      if (nextBlockIndex != BLOCK_UNUSED)
        blockIndex++;
    }
    else
    {
6760
      ULONG count =
6761 6762
        BlockChainStream_GetCount(This->parentStorage->smallBlockDepotChain);

6763
      BYTE smallBlockDepot[MAX_BIG_BLOCK_SIZE];
6764 6765
      ULARGE_INTEGER newSize, offset;
      ULONG bytesWritten;
6766

6767 6768
      newSize.QuadPart = (count + 1) * This->parentStorage->bigBlockSize;
      BlockChainStream_Enlarge(This->parentStorage->smallBlockDepotChain, newSize);
6769 6770 6771 6772 6773

      /*
       * Initialize all the small blocks to free
       */
      memset(smallBlockDepot, BLOCK_UNUSED, This->parentStorage->bigBlockSize);
6774 6775 6776
      offset.QuadPart = count * This->parentStorage->bigBlockSize;
      BlockChainStream_WriteAt(This->parentStorage->smallBlockDepotChain,
        offset, This->parentStorage->bigBlockSize, smallBlockDepot, &bytesWritten);
6777

6778
      StorageImpl_SaveFileHeader(This->parentStorage);
6779 6780 6781
    }
  }

6782 6783
  This->parentStorage->firstFreeSmallBlock = blockIndex+1;

6784
  smallBlocksPerBigBlock =
6785 6786 6787 6788 6789
    This->parentStorage->bigBlockSize / This->parentStorage->smallBlockSize;

  /*
   * Verify if we have to allocate big blocks to contain small blocks
   */
6790
  blocksRequired = (blockIndex / smallBlocksPerBigBlock) + 1;
6791

6792
  size_required.QuadPart = blocksRequired * This->parentStorage->bigBlockSize;
6793

6794
  old_size = BlockChainStream_GetSize(This->parentStorage->smallBlockRootChain);
6795

6796 6797 6798 6799 6800
  if (size_required.QuadPart > old_size.QuadPart)
  {
    BlockChainStream_SetSize(
      This->parentStorage->smallBlockRootChain,
      size_required);
6801

6802 6803 6804 6805
    StorageImpl_ReadDirEntry(
      This->parentStorage,
      This->parentStorage->base.storageDirEntry,
      &rootEntry);
6806

6807
    rootEntry.size = size_required;
6808

6809 6810 6811 6812
    StorageImpl_WriteDirEntry(
      This->parentStorage,
      This->parentStorage->base.storageDirEntry,
      &rootEntry);
6813 6814 6815 6816 6817 6818 6819 6820 6821 6822
  }

  return blockIndex;
}

/******************************************************************************
 *      SmallBlockChainStream_ReadAt
 *
 * Reads a specified number of bytes from this chain at the specified offset.
 * bytesRead may be NULL.
6823
 * Failure will be returned if the specified number of bytes has not been read.
6824
 */
6825
HRESULT SmallBlockChainStream_ReadAt(
6826 6827 6828 6829 6830 6831
  SmallBlockChainStream* This,
  ULARGE_INTEGER         offset,
  ULONG                  size,
  void*                  buffer,
  ULONG*                 bytesRead)
{
6832
  HRESULT rc = S_OK;
6833
  ULARGE_INTEGER offsetInBigBlockFile;
6834
  ULONG blockNoInSequence =
6835
    offset.u.LowPart / This->parentStorage->smallBlockSize;
6836

6837
  ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
6838 6839 6840 6841
  ULONG bytesToReadInBuffer;
  ULONG blockIndex;
  ULONG bytesReadFromBigBlockFile;
  BYTE* bufferWalker;
6842
  ULARGE_INTEGER stream_size;
6843 6844 6845 6846

  /*
   * This should never happen on a small block file.
   */
6847
  assert(offset.u.HighPart==0);
6848

6849 6850 6851 6852 6853 6854 6855 6856
  *bytesRead   = 0;

  stream_size = SmallBlockChainStream_GetSize(This);
  if (stream_size.QuadPart > offset.QuadPart)
    size = min(stream_size.QuadPart - offset.QuadPart, size);
  else
    return S_OK;

6857 6858 6859 6860 6861 6862 6863
  /*
   * Find the first block in the stream that contains part of the buffer.
   */
  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);

  while ( (blockNoInSequence > 0) &&  (blockIndex != BLOCK_END_OF_CHAIN))
  {
6864 6865 6866
    rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
    if(FAILED(rc))
      return rc;
6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879
    blockNoInSequence--;
  }

  /*
   * Start reading the buffer.
   */
  bufferWalker = buffer;

  while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
  {
    /*
     * Calculate how many bytes we can copy from this small block.
     */
6880
    bytesToReadInBuffer =
6881
      min(This->parentStorage->smallBlockSize - offsetInBlock, size);
6882 6883 6884 6885

    /*
     * Calculate the offset of the small block in the small block file.
     */
6886 6887
    offsetInBigBlockFile.u.HighPart  = 0;
    offsetInBigBlockFile.u.LowPart   =
6888 6889
      blockIndex * This->parentStorage->smallBlockSize;

6890
    offsetInBigBlockFile.u.LowPart  += offsetInBlock;
6891 6892 6893

    /*
     * Read those bytes in the buffer from the small block file.
6894 6895
     * The small block has already been identified so it shouldn't fail
     * unless the file is corrupt.
6896
     */
6897
    rc = BlockChainStream_ReadAt(This->parentStorage->smallBlockRootChain,
6898 6899 6900
      offsetInBigBlockFile,
      bytesToReadInBuffer,
      bufferWalker,
6901 6902 6903 6904
      &bytesReadFromBigBlockFile);

    if (FAILED(rc))
      return rc;
6905

6906 6907 6908
    if (!bytesReadFromBigBlockFile)
      return STG_E_DOCFILECORRUPT;

6909 6910 6911
    /*
     * Step to the next big block.
     */
6912 6913
    rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
    if(FAILED(rc))
6914
      return STG_E_DOCFILECORRUPT;
6915

6916 6917 6918 6919
    bufferWalker += bytesReadFromBigBlockFile;
    size         -= bytesReadFromBigBlockFile;
    *bytesRead   += bytesReadFromBigBlockFile;
    offsetInBlock = (offsetInBlock + bytesReadFromBigBlockFile) % This->parentStorage->smallBlockSize;
6920 6921
  }

6922
  return S_OK;
6923 6924 6925 6926 6927 6928 6929 6930
}

/******************************************************************************
 *       SmallBlockChainStream_WriteAt
 *
 * Writes the specified number of bytes to this chain at the specified offset.
 * Will fail if not all specified number of bytes have been written.
 */
6931
HRESULT SmallBlockChainStream_WriteAt(
6932 6933 6934 6935 6936 6937 6938
  SmallBlockChainStream* This,
  ULARGE_INTEGER offset,
  ULONG          size,
  const void*    buffer,
  ULONG*         bytesWritten)
{
  ULARGE_INTEGER offsetInBigBlockFile;
6939
  ULONG blockNoInSequence =
6940
    offset.u.LowPart / This->parentStorage->smallBlockSize;
6941

6942
  ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
6943 6944
  ULONG bytesToWriteInBuffer;
  ULONG blockIndex;
6945
  ULONG bytesWrittenToBigBlockFile;
Eric Pouech's avatar
Eric Pouech committed
6946
  const BYTE* bufferWalker;
6947
  HRESULT res;
6948

6949 6950 6951
  /*
   * This should never happen on a small block file.
   */
6952
  assert(offset.u.HighPart==0);
6953

6954 6955 6956 6957
  /*
   * Find the first block in the stream that contains part of the buffer.
   */
  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
6958

6959 6960
  while ( (blockNoInSequence > 0) &&  (blockIndex != BLOCK_END_OF_CHAIN))
  {
6961
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex)))
6962
      return STG_E_DOCFILECORRUPT;
6963 6964
    blockNoInSequence--;
  }
6965

6966 6967 6968 6969
  /*
   * Start writing the buffer.
   */
  *bytesWritten   = 0;
6970
  bufferWalker = buffer;
6971 6972 6973 6974 6975
  while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
  {
    /*
     * Calculate how many bytes we can copy to this small block.
     */
6976
    bytesToWriteInBuffer =
6977
      min(This->parentStorage->smallBlockSize - offsetInBlock, size);
6978

6979 6980 6981
    /*
     * Calculate the offset of the small block in the small block file.
     */
6982 6983
    offsetInBigBlockFile.u.HighPart  = 0;
    offsetInBigBlockFile.u.LowPart   =
6984 6985
      blockIndex * This->parentStorage->smallBlockSize;

6986
    offsetInBigBlockFile.u.LowPart  += offsetInBlock;
6987

6988 6989 6990
    /*
     * Write those bytes in the buffer to the small block file.
     */
6991 6992
    res = BlockChainStream_WriteAt(
      This->parentStorage->smallBlockRootChain,
6993 6994 6995
      offsetInBigBlockFile,
      bytesToWriteInBuffer,
      bufferWalker,
6996
      &bytesWrittenToBigBlockFile);
6997 6998
    if (FAILED(res))
      return res;
6999

7000 7001 7002
    /*
     * Step to the next big block.
     */
7003 7004 7005
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
							&blockIndex)))
      return FALSE;
7006 7007 7008 7009
    bufferWalker  += bytesWrittenToBigBlockFile;
    size          -= bytesWrittenToBigBlockFile;
    *bytesWritten += bytesWrittenToBigBlockFile;
    offsetInBlock  = (offsetInBlock + bytesWrittenToBigBlockFile) % This->parentStorage->smallBlockSize;
7010
  }
7011

7012
  return (size == 0) ? S_OK : STG_E_WRITEFAULT;
7013 7014 7015 7016 7017
}

/******************************************************************************
 *       SmallBlockChainStream_Shrink
 *
7018
 * Shrinks this chain in the small block depot.
7019
 */
7020
static BOOL SmallBlockChainStream_Shrink(
7021 7022 7023 7024 7025
  SmallBlockChainStream* This,
  ULARGE_INTEGER newSize)
{
  ULONG blockIndex, extraBlock;
  ULONG numBlocks;
7026
  ULONG count = 0;
7027

7028
  numBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
7029

7030
  if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
7031 7032 7033 7034 7035 7036 7037 7038 7039
    numBlocks++;

  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);

  /*
   * Go to the new end of chain
   */
  while (count < numBlocks)
  {
7040 7041 7042
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
							&blockIndex)))
      return FALSE;
7043 7044 7045
    count++;
  }

7046 7047
  /*
   * If the count is 0, we have a special case, the head of the chain was
7048
   * just freed.
7049 7050 7051
   */
  if (count == 0)
  {
7052
    DirEntry chainEntry;
7053

7054
    StorageImpl_ReadDirEntry(This->parentStorage,
7055
			     This->ownerDirEntry,
7056
			     &chainEntry);
7057

7058
    chainEntry.startingBlock = BLOCK_END_OF_CHAIN;
7059

7060
    StorageImpl_WriteDirEntry(This->parentStorage,
7061
			      This->ownerDirEntry,
7062
			      &chainEntry);
7063 7064 7065 7066 7067 7068 7069 7070 7071

    /*
     * We start freeing the chain at the head block.
     */
    extraBlock = blockIndex;
  }
  else
  {
    /* Get the next block before marking the new end */
7072 7073 7074
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
							&extraBlock)))
      return FALSE;
7075 7076 7077

    /* Mark the new end of chain */
    SmallBlockChainStream_SetNextBlockInChain(
7078 7079
      This,
      blockIndex,
7080 7081
      BLOCK_END_OF_CHAIN);
  }
7082 7083 7084 7085 7086 7087

  /*
   * Mark the extra blocks as free
   */
  while (extraBlock != BLOCK_END_OF_CHAIN)
  {
7088 7089 7090
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, extraBlock,
							&blockIndex)))
      return FALSE;
7091
    SmallBlockChainStream_FreeBlock(This, extraBlock);
7092
    This->parentStorage->firstFreeSmallBlock = min(This->parentStorage->firstFreeSmallBlock, extraBlock);
7093 7094 7095
    extraBlock = blockIndex;
  }

7096
  return TRUE;
7097 7098 7099 7100 7101 7102 7103
}

/******************************************************************************
 *      SmallBlockChainStream_Enlarge
 *
 * Grows this chain in the small block depot.
 */
7104
static BOOL SmallBlockChainStream_Enlarge(
7105 7106 7107 7108 7109 7110 7111 7112 7113 7114
  SmallBlockChainStream* This,
  ULARGE_INTEGER newSize)
{
  ULONG blockIndex, currentBlock;
  ULONG newNumBlocks;
  ULONG oldNumBlocks = 0;

  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);

  /*
7115
   * Empty chain. Create the head.
7116 7117 7118
   */
  if (blockIndex == BLOCK_END_OF_CHAIN)
  {
7119 7120 7121 7122 7123
    blockIndex = SmallBlockChainStream_GetNextFreeBlock(This);
    SmallBlockChainStream_SetNextBlockInChain(
        This,
        blockIndex,
        BLOCK_END_OF_CHAIN);
7124

7125 7126 7127 7128 7129 7130
    if (This->headOfStreamPlaceHolder != NULL)
    {
      *(This->headOfStreamPlaceHolder) = blockIndex;
    }
    else
    {
7131
      DirEntry chainEntry;
7132

7133
      StorageImpl_ReadDirEntry(This->parentStorage, This->ownerDirEntry,
7134
                                   &chainEntry);
7135

7136
      chainEntry.startingBlock = blockIndex;
7137

7138
      StorageImpl_WriteDirEntry(This->parentStorage, This->ownerDirEntry,
7139
                                  &chainEntry);
7140
    }
7141 7142 7143 7144 7145 7146 7147
  }

  currentBlock = blockIndex;

  /*
   * Figure out how many blocks are needed to contain this stream
   */
7148
  newNumBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
7149

7150
  if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
7151 7152 7153 7154 7155 7156 7157 7158 7159
    newNumBlocks++;

  /*
   * Go to the current end of chain
   */
  while (blockIndex != BLOCK_END_OF_CHAIN)
  {
    oldNumBlocks++;
    currentBlock = blockIndex;
7160 7161
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, currentBlock, &blockIndex)))
      return FALSE;
7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172
  }

  /*
   * Add new blocks to the chain
   */
  while (oldNumBlocks < newNumBlocks)
  {
    blockIndex = SmallBlockChainStream_GetNextFreeBlock(This);
    SmallBlockChainStream_SetNextBlockInChain(This, currentBlock, blockIndex);

    SmallBlockChainStream_SetNextBlockInChain(
7173 7174
      This,
      blockIndex,
7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191
      BLOCK_END_OF_CHAIN);

    currentBlock = blockIndex;
    oldNumBlocks++;
  }

  return TRUE;
}

/******************************************************************************
 *      SmallBlockChainStream_SetSize
 *
 * Sets the size of this stream.
 * The file will grow if we grow the chain.
 *
 * TODO: Free the actual blocks in the file when we shrink the chain.
 *       Currently, the blocks are still in the file. So the file size
7192
 *       doesn't shrink even if we shrink streams.
7193
 */
7194
BOOL SmallBlockChainStream_SetSize(
7195 7196 7197 7198 7199
                SmallBlockChainStream* This,
                ULARGE_INTEGER    newSize)
{
  ULARGE_INTEGER size = SmallBlockChainStream_GetSize(This);

7200
  if (newSize.u.LowPart == size.u.LowPart)
7201 7202
    return TRUE;

7203
  if (newSize.u.LowPart < size.u.LowPart)
7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214
  {
    SmallBlockChainStream_Shrink(This, newSize);
  }
  else
  {
    SmallBlockChainStream_Enlarge(This, newSize);
  }

  return TRUE;
}

7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240
/******************************************************************************
 *       SmallBlockChainStream_GetCount
 *
 * Returns the number of small blocks that comprises this chain.
 * This is not the size of the stream as the last block may not be full!
 *
 */
static ULONG SmallBlockChainStream_GetCount(SmallBlockChainStream* This)
{
    ULONG blockIndex;
    ULONG count = 0;

    blockIndex = SmallBlockChainStream_GetHeadOfChain(This);

    while(blockIndex != BLOCK_END_OF_CHAIN)
    {
        count++;

        if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This,
                        blockIndex, &blockIndex)))
            return 0;
    }

    return count;
}

7241 7242 7243 7244 7245
/******************************************************************************
 *      SmallBlockChainStream_GetSize
 *
 * Returns the size of this chain.
 */
7246
static ULARGE_INTEGER SmallBlockChainStream_GetSize(SmallBlockChainStream* This)
7247
{
7248
  DirEntry chainEntry;
7249

7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260
  if(This->headOfStreamPlaceHolder != NULL)
  {
    ULARGE_INTEGER result;
    result.u.HighPart = 0;

    result.u.LowPart = SmallBlockChainStream_GetCount(This) *
        This->parentStorage->smallBlockSize;

    return result;
  }

7261
  StorageImpl_ReadDirEntry(
7262
    This->parentStorage,
7263
    This->ownerDirEntry,
7264
    &chainEntry);
7265

7266
  return chainEntry.size;
7267 7268
}

7269
static HRESULT create_storagefile(
7270
  LPCOLESTR pwcsName,
7271
  DWORD       grfMode,
7272 7273 7274 7275
  DWORD       grfAttrs,
  STGOPTIONS* pStgOptions,
  REFIID      riid,
  void**      ppstgOpen)
7276
{
7277
  StorageBaseImpl* newStorage = 0;
7278
  HANDLE       hFile      = INVALID_HANDLE_VALUE;
7279
  HRESULT        hr         = STG_E_INVALIDFLAG;
7280 7281 7282 7283
  DWORD          shareMode;
  DWORD          accessMode;
  DWORD          creationMode;
  DWORD          fileAttributes;
7284
  WCHAR          tempFileName[MAX_PATH];
7285

7286
  if (ppstgOpen == 0)
7287
    return STG_E_INVALIDPOINTER;
7288 7289

  if (pStgOptions->ulSectorSize != MIN_BIG_BLOCK_SIZE && pStgOptions->ulSectorSize != MAX_BIG_BLOCK_SIZE)
7290
    return STG_E_INVALIDPARAMETER;
7291

7292 7293 7294 7295
  /* if no share mode given then DENY_NONE is the default */
  if (STGM_SHARE_MODE(grfMode) == 0)
      grfMode |= STGM_SHARE_DENY_NONE;

7296
  if ( FAILED( validateSTGM(grfMode) ))
7297
    goto end;
7298

7299
  /* StgCreateDocFile seems to refuse readonly access, despite MSDN */
7300 7301 7302 7303 7304 7305
  switch(STGM_ACCESS_MODE(grfMode))
  {
  case STGM_WRITE:
  case STGM_READWRITE:
    break;
  default:
7306
    goto end;
7307
  }
7308

7309 7310
  /* in direct mode, can only use SHARE_EXCLUSIVE */
  if (!(grfMode & STGM_TRANSACTED) && (STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE))
7311
    goto end;
7312

7313 7314
  /* but in transacted mode, any share mode is valid */

7315 7316 7317 7318 7319 7320
  /*
   * Generate a unique name.
   */
  if (pwcsName == 0)
  {
    WCHAR tempPath[MAX_PATH];
7321
    static const WCHAR prefix[] = { 'S', 'T', 'O', 0 };
7322 7323 7324 7325 7326 7327 7328 7329 7330 7331

    memset(tempPath, 0, sizeof(tempPath));
    memset(tempFileName, 0, sizeof(tempFileName));

    if ((GetTempPathW(MAX_PATH, tempPath)) == 0 )
      tempPath[0] = '.';

    if (GetTempFileNameW(tempPath, prefix, 0, tempFileName) != 0)
      pwcsName = tempFileName;
    else
7332 7333 7334 7335
    {
      hr = STG_E_INSUFFICIENTMEMORY;
      goto end;
    }
7336 7337 7338 7339 7340 7341

    creationMode = TRUNCATE_EXISTING;
  }
  else
  {
    creationMode = GetCreationModeFromSTGM(grfMode);
7342 7343
  }

7344
  /*
7345
   * Interpret the STGM value grfMode
7346
   */
7347
  shareMode    = FILE_SHARE_READ | FILE_SHARE_WRITE;
7348 7349 7350 7351 7352 7353 7354
  accessMode   = GetAccessModeFromSTGM(grfMode);

  if (grfMode & STGM_DELETEONRELEASE)
    fileAttributes = FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_DELETE_ON_CLOSE;
  else
    fileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS;

7355
  if (STGM_SHARE_MODE(grfMode) && !(grfMode & STGM_SHARE_DENY_NONE))
7356 7357 7358
  {
    static int fixme;
    if (!fixme++)
7359
      FIXME("Storage share mode not implemented.\n");
7360
  }
7361

7362 7363
  *ppstgOpen = 0;

7364
  hFile = CreateFileW(pwcsName,
7365 7366
                        accessMode,
                        shareMode,
7367
                        NULL,
7368 7369
                        creationMode,
                        fileAttributes,
7370
                        0);
7371

7372
  if (hFile == INVALID_HANDLE_VALUE)
7373
  {
7374
    if(GetLastError() == ERROR_FILE_EXISTS)
7375 7376 7377 7378
      hr = STG_E_FILEALREADYEXISTS;
    else
      hr = E_FAIL;
    goto end;
7379 7380 7381 7382 7383
  }

  /*
   * Allocate and initialize the new IStorage32object.
   */
7384
  hr = Storage_Construct(
7385
         hFile,
7386
        pwcsName,
7387 7388
         NULL,
         grfMode,
7389
         TRUE,
7390
         TRUE,
7391
         pStgOptions->ulSectorSize,
7392
         &newStorage);
7393

7394
  if (FAILED(hr))
7395
  {
7396
    goto end;
7397
  }
7398

7399 7400 7401
  hr = IStorage_QueryInterface((IStorage*)newStorage, riid, ppstgOpen);

  IStorage_Release((IStorage*)newStorage);
7402

7403
end:
7404
  TRACE("<-- %p  r = %08x\n", *ppstgOpen, hr);
7405 7406 7407 7408

  return hr;
}

7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447
/******************************************************************************
 *    StgCreateDocfile  [OLE32.@]
 * Creates a new compound file storage object
 *
 * PARAMS
 *  pwcsName  [ I] Unicode string with filename (can be relative or NULL)
 *  grfMode   [ I] Access mode for opening the new storage object (see STGM_ constants)
 *  reserved  [ ?] unused?, usually 0
 *  ppstgOpen [IO] A pointer to IStorage pointer to the new onject
 *
 * RETURNS
 *  S_OK if the file was successfully created
 *  some STG_E_ value if error
 * NOTES
 *  if pwcsName is NULL, create file with new unique name
 *  the function can returns
 *  STG_S_CONVERTED if the specified file was successfully converted to storage format
 *  (unrealized now)
 */
HRESULT WINAPI StgCreateDocfile(
  LPCOLESTR pwcsName,
  DWORD       grfMode,
  DWORD       reserved,
  IStorage  **ppstgOpen)
{
  STGOPTIONS stgoptions = {1, 0, 512};

  TRACE("(%s, %x, %d, %p)\n",
	debugstr_w(pwcsName), grfMode,
	reserved, ppstgOpen);

  if (ppstgOpen == 0)
    return STG_E_INVALIDPOINTER;
  if (reserved != 0)
    return STG_E_INVALIDPARAMETER;

  return create_storagefile(pwcsName, grfMode, 0, &stgoptions, &IID_IStorage, (void**)ppstgOpen);
}

7448 7449 7450
/******************************************************************************
 *              StgCreateStorageEx        [OLE32.@]
 */
7451 7452
HRESULT WINAPI StgCreateStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
{
7453
    TRACE("(%s, %x, %x, %x, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
7454
          grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);
7455 7456 7457 7458 7459 7460 7461

    if (stgfmt != STGFMT_FILE && grfAttrs != 0)
    {
        ERR("grfAttrs must be 0 if stgfmt != STGFMT_FILE\n");
        return STG_E_INVALIDPARAMETER;  
    }

7462
    if (stgfmt == STGFMT_FILE && grfAttrs != 0 && grfAttrs != FILE_FLAG_NO_BUFFERING)
7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475
    {
        ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_FILE\n");
        return STG_E_INVALIDPARAMETER;  
    }

    if (stgfmt == STGFMT_FILE)
    {
        ERR("Cannot use STGFMT_FILE - this is NTFS only\n");  
        return STG_E_INVALIDPARAMETER;
    }

    if (stgfmt == STGFMT_STORAGE || stgfmt == STGFMT_DOCFILE)
    {
7476 7477 7478
        STGOPTIONS defaultOptions = {1, 0, 512};

        if (!pStgOptions) pStgOptions = &defaultOptions;
7479
        return create_storagefile(pwcsName, grfMode, grfAttrs, pStgOptions, riid, ppObjectOpen);
7480 7481
    }

7482

7483 7484
    ERR("Invalid stgfmt argument\n");
    return STG_E_INVALIDPARAMETER;
7485 7486
}

7487 7488 7489 7490 7491 7492 7493 7494
/******************************************************************************
 *              StgCreatePropSetStg       [OLE32.@]
 */
HRESULT WINAPI StgCreatePropSetStg(IStorage *pstg, DWORD reserved,
 IPropertySetStorage **ppPropSetStg)
{
    HRESULT hr;

7495
    TRACE("(%p, 0x%x, %p)\n", pstg, reserved, ppPropSetStg);
7496 7497 7498 7499 7500 7501 7502 7503
    if (reserved)
        hr = STG_E_INVALIDPARAMETER;
    else
        hr = StorageBaseImpl_QueryInterface(pstg, &IID_IPropertySetStorage,
         (void**)ppPropSetStg);
    return hr;
}

7504 7505 7506 7507 7508
/******************************************************************************
 *              StgOpenStorageEx      [OLE32.@]
 */
HRESULT WINAPI StgOpenStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
{
7509
    TRACE("(%s, %x, %x, %x, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
7510 7511 7512 7513 7514 7515 7516 7517
          grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);

    if (stgfmt != STGFMT_DOCFILE && grfAttrs != 0)
    {
        ERR("grfAttrs must be 0 if stgfmt != STGFMT_DOCFILE\n");
        return STG_E_INVALIDPARAMETER;  
    }

7518
    switch (stgfmt)
7519
    {
7520
    case STGFMT_FILE:
7521 7522
        ERR("Cannot use STGFMT_FILE - this is NTFS only\n");  
        return STG_E_INVALIDPARAMETER;
7523 7524 7525
        
    case STGFMT_STORAGE:
        break;
7526

7527 7528 7529 7530 7531 7532
    case STGFMT_DOCFILE:
        if (grfAttrs && grfAttrs != FILE_FLAG_NO_BUFFERING)
        {
            ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_DOCFILE\n");
            return STG_E_INVALIDPARAMETER;  
        }
7533
        FIXME("Stub: calling StgOpenStorage, but ignoring pStgOptions and grfAttrs\n");
7534 7535 7536 7537 7538 7539 7540 7541
        break;

    case STGFMT_ANY:
        WARN("STGFMT_ANY assuming storage\n");
        break;

    default:
        return STG_E_INVALIDPARAMETER;
7542 7543
    }

7544
    return StgOpenStorage(pwcsName, NULL, grfMode, NULL, 0, (IStorage **)ppObjectOpen);
7545 7546 7547
}


7548
/******************************************************************************
7549
 *              StgOpenStorage        [OLE32.@]
7550
 */
7551 7552 7553
HRESULT WINAPI StgOpenStorage(
  const OLECHAR *pwcsName,
  IStorage      *pstgPriority,
7554 7555 7556 7557
  DWORD          grfMode,
  SNB            snbExclude,
  DWORD          reserved,
  IStorage     **ppstgOpen)
7558
{
7559
  StorageBaseImpl* newStorage = 0;
7560
  HRESULT        hr = S_OK;
7561
  HANDLE         hFile = 0;
7562 7563
  DWORD          shareMode;
  DWORD          accessMode;
7564

7565
  TRACE("(%s, %p, %x, %p, %d, %p)\n",
7566 7567 7568
	debugstr_w(pwcsName), pstgPriority, grfMode,
	snbExclude, reserved, ppstgOpen);

7569 7570 7571 7572 7573 7574 7575
  if (pwcsName == 0)
  {
    hr = STG_E_INVALIDNAME;
    goto end;
  }

  if (ppstgOpen == 0)
Alexandre Julliard's avatar
Alexandre Julliard committed
7576 7577 7578 7579
  {
    hr = STG_E_INVALIDPOINTER;
    goto end;
  }
7580

7581 7582 7583 7584 7585 7586
  if (reserved)
  {
    hr = STG_E_INVALIDPARAMETER;
    goto end;
  }

7587 7588
  if (grfMode & STGM_PRIORITY)
  {
7589 7590 7591 7592 7593 7594
    if (grfMode & (STGM_TRANSACTED|STGM_SIMPLE|STGM_NOSCRATCH|STGM_NOSNAPSHOT))
      return STG_E_INVALIDFLAG;
    if (grfMode & STGM_DELETEONRELEASE)
      return STG_E_INVALIDFUNCTION;
    if(STGM_ACCESS_MODE(grfMode) != STGM_READ)
      return STG_E_INVALIDFLAG;
7595
    grfMode &= ~0xf0; /* remove the existing sharing mode */
7596 7597 7598 7599 7600 7601 7602 7603
    grfMode |= STGM_SHARE_DENY_NONE;

    /* STGM_PRIORITY stops other IStorage objects on the same file from
     * committing until the STGM_PRIORITY IStorage is closed. it also
     * stops non-transacted mode StgOpenStorage calls with write access from
     * succeeding. obviously, both of these cannot be achieved through just
     * file share flags */
    FIXME("STGM_PRIORITY mode not implemented correctly\n");
7604 7605
  }

7606 7607 7608
  /*
   * Validate the sharing mode
   */
7609
  if (!(grfMode & (STGM_TRANSACTED|STGM_PRIORITY)))
7610 7611 7612 7613 7614 7615 7616 7617 7618
    switch(STGM_SHARE_MODE(grfMode))
    {
      case STGM_SHARE_EXCLUSIVE:
      case STGM_SHARE_DENY_WRITE:
        break;
      default:
        hr = STG_E_INVALIDFLAG;
        goto end;
    }
7619 7620 7621

  if ( FAILED( validateSTGM(grfMode) ) ||
       (grfMode&STGM_CREATE))
Alexandre Julliard's avatar
Alexandre Julliard committed
7622 7623 7624 7625
  {
    hr = STG_E_INVALIDFLAG;
    goto end;
  }
7626

7627 7628 7629 7630 7631 7632 7633 7634 7635
  /* shared reading requires transacted mode */
  if( STGM_SHARE_MODE(grfMode) == STGM_SHARE_DENY_WRITE &&
      STGM_ACCESS_MODE(grfMode) == STGM_READWRITE &&
     !(grfMode&STGM_TRANSACTED) )
  {
    hr = STG_E_INVALIDFLAG;
    goto end;
  }

7636 7637 7638 7639 7640 7641
  /*
   * Interpret the STGM value grfMode
   */
  shareMode    = GetShareModeFromSTGM(grfMode);
  accessMode   = GetAccessModeFromSTGM(grfMode);

7642
  *ppstgOpen = 0;
7643

7644 7645 7646 7647 7648 7649 7650
  hFile = CreateFileW( pwcsName,
                       accessMode,
                       shareMode,
                       NULL,
                       OPEN_EXISTING,
                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
                       0);
7651

7652
  if (hFile==INVALID_HANDLE_VALUE)
7653
  {
7654 7655
    DWORD last_error = GetLastError();

Alexandre Julliard's avatar
Alexandre Julliard committed
7656 7657
    hr = E_FAIL;

7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680
    switch (last_error)
    {
      case ERROR_FILE_NOT_FOUND:
        hr = STG_E_FILENOTFOUND;
        break;

      case ERROR_PATH_NOT_FOUND:
        hr = STG_E_PATHNOTFOUND;
        break;

      case ERROR_ACCESS_DENIED:
      case ERROR_WRITE_PROTECT:
        hr = STG_E_ACCESSDENIED;
        break;

      case ERROR_SHARING_VIOLATION:
        hr = STG_E_SHAREVIOLATION;
        break;

      default:
        hr = E_FAIL;
    }

Alexandre Julliard's avatar
Alexandre Julliard committed
7681
    goto end;
7682 7683
  }

7684 7685 7686 7687
  /*
   * Refuse to open the file if it's too small to be a structured storage file
   * FIXME: verify the file when reading instead of here
   */
7688
  if (GetFileSize(hFile, NULL) < 0x100)
7689 7690 7691 7692 7693
  {
    CloseHandle(hFile);
    hr = STG_E_FILEALREADYEXISTS;
    goto end;
  }
7694

7695 7696 7697
  /*
   * Allocate and initialize the new IStorage32object.
   */
7698
  hr = Storage_Construct(
7699
         hFile,
7700
         pwcsName,
7701 7702
         NULL,
         grfMode,
7703
         TRUE,
7704
         FALSE,
7705
         512,
7706
         &newStorage);
7707

7708
  if (FAILED(hr))
7709
  {
7710 7711 7712 7713
    /*
     * According to the docs if the file is not a storage, return STG_E_FILEALREADYEXISTS
     */
    if(hr == STG_E_INVALIDHEADER)
Alexandre Julliard's avatar
Alexandre Julliard committed
7714 7715
	hr = STG_E_FILEALREADYEXISTS;
    goto end;
7716
  }
7717

7718 7719 7720
  /*
   * Get an "out" pointer for the caller.
   */
7721
  *ppstgOpen = (IStorage*)newStorage;
7722

Alexandre Julliard's avatar
Alexandre Julliard committed
7723
end:
7724
  TRACE("<-- %08x, IStorage %p\n", hr, ppstgOpen ? *ppstgOpen : NULL);
7725 7726 7727 7728
  return hr;
}

/******************************************************************************
7729
 *    StgCreateDocfileOnILockBytes    [OLE32.@]
7730 7731 7732 7733 7734 7735 7736
 */
HRESULT WINAPI StgCreateDocfileOnILockBytes(
      ILockBytes *plkbyt,
      DWORD grfMode,
      DWORD reserved,
      IStorage** ppstgOpen)
{
7737
  StorageBaseImpl* newStorage = 0;
7738 7739 7740 7741 7742 7743 7744 7745
  HRESULT        hr         = S_OK;

  if ((ppstgOpen == 0) || (plkbyt == 0))
    return STG_E_INVALIDPOINTER;

  /*
   * Allocate and initialize the new IStorage object.
   */
7746
  hr = Storage_Construct(
7747
         0,
7748
        0,
7749 7750
         plkbyt,
         grfMode,
7751
         FALSE,
7752
         TRUE,
7753
         512,
7754
         &newStorage);
7755 7756 7757 7758 7759 7760 7761 7762 7763

  if (FAILED(hr))
  {
    return hr;
  }

  /*
   * Get an "out" pointer for the caller.
   */
7764
  *ppstgOpen = (IStorage*)newStorage;
7765

7766
  return hr;
7767 7768 7769
}

/******************************************************************************
7770
 *    StgOpenStorageOnILockBytes    [OLE32.@]
7771 7772 7773 7774 7775 7776 7777 7778 7779
 */
HRESULT WINAPI StgOpenStorageOnILockBytes(
      ILockBytes *plkbyt,
      IStorage *pstgPriority,
      DWORD grfMode,
      SNB snbExclude,
      DWORD reserved,
      IStorage **ppstgOpen)
{
7780
  StorageBaseImpl* newStorage = 0;
7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793
  HRESULT        hr = S_OK;

  if ((plkbyt == 0) || (ppstgOpen == 0))
    return STG_E_INVALIDPOINTER;

  if ( FAILED( validateSTGM(grfMode) ))
    return STG_E_INVALIDFLAG;

  *ppstgOpen = 0;

  /*
   * Allocate and initialize the new IStorage object.
   */
7794
  hr = Storage_Construct(
7795
         0,
7796
         0,
7797 7798
         plkbyt,
         grfMode,
7799
         FALSE,
7800
         FALSE,
7801
         512,
7802
         &newStorage);
7803 7804 7805 7806 7807 7808 7809 7810 7811

  if (FAILED(hr))
  {
    return hr;
  }

  /*
   * Get an "out" pointer for the caller.
   */
7812
  *ppstgOpen = (IStorage*)newStorage;
7813 7814 7815 7816

  return hr;
}

Jim Aston's avatar
Jim Aston committed
7817
/******************************************************************************
7818 7819
 *              StgSetTimes [ole32.@]
 *              StgSetTimes [OLE32.@]
Jim Aston's avatar
Jim Aston committed
7820 7821 7822
 *
 *
 */
Mike McCormack's avatar
Mike McCormack committed
7823 7824
HRESULT WINAPI StgSetTimes(OLECHAR const *str, FILETIME const *pctime,
                           FILETIME const *patime, FILETIME const *pmtime)
Jim Aston's avatar
Jim Aston committed
7825
{
Mike McCormack's avatar
Mike McCormack committed
7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839
  IStorage *stg = NULL;
  HRESULT r;
 
  TRACE("%s %p %p %p\n", debugstr_w(str), pctime, patime, pmtime);

  r = StgOpenStorage(str, NULL, STGM_READWRITE | STGM_SHARE_DENY_WRITE,
                     0, 0, &stg);
  if( SUCCEEDED(r) )
  {
    r = IStorage_SetElementTimes(stg, NULL, pctime, patime, pmtime);
    IStorage_Release(stg);
  }

  return r;
Jim Aston's avatar
Jim Aston committed
7840 7841
}

7842
/******************************************************************************
7843
 *              StgIsStorageILockBytes        [OLE32.@]
7844 7845 7846 7847 7848 7849 7850 7851
 *
 * Determines if the ILockBytes contains a storage object.
 */
HRESULT WINAPI StgIsStorageILockBytes(ILockBytes *plkbyt)
{
  BYTE sig[8];
  ULARGE_INTEGER offset;

7852 7853
  offset.u.HighPart = 0;
  offset.u.LowPart  = 0;
7854 7855 7856 7857 7858 7859 7860 7861 7862 7863

  ILockBytes_ReadAt(plkbyt, offset, sig, sizeof(sig), NULL);

  if (memcmp(sig, STORAGE_magic, sizeof(STORAGE_magic)) == 0)
    return S_OK;

  return S_FALSE;
}

/******************************************************************************
7864
 *              WriteClassStg        [OLE32.@]
7865 7866 7867
 *
 * This method will store the specified CLSID in the specified storage object
 */
7868
HRESULT WINAPI WriteClassStg(IStorage* pStg, REFCLSID rclsid)
7869 7870 7871
{
  HRESULT hRes;

7872 7873
  if(!pStg)
    return E_INVALIDARG;
7874

7875 7876 7877
  if(!rclsid)
    return STG_E_INVALIDPOINTER;

7878
  hRes = IStorage_SetClass(pStg, rclsid);
7879 7880 7881 7882

  return hRes;
}

7883
/***********************************************************************
7884
 *    ReadClassStg (OLE32.@)
Noomen Hamza's avatar
Noomen Hamza committed
7885
 *
7886 7887 7888 7889 7890 7891 7892 7893 7894 7895
 * This method reads the CLSID previously written to a storage object with
 * the WriteClassStg.
 *
 * PARAMS
 *  pstg    [I] IStorage pointer
 *  pclsid  [O] Pointer to where the CLSID is written
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
Noomen Hamza's avatar
Noomen Hamza committed
7896 7897 7898 7899 7900
 */
HRESULT WINAPI ReadClassStg(IStorage *pstg,CLSID *pclsid){

    STATSTG pstatstg;
    HRESULT hRes;
7901

7902 7903 7904 7905
    TRACE("(%p, %p)\n", pstg, pclsid);

    if(!pstg || !pclsid)
        return E_INVALIDARG;
Noomen Hamza's avatar
Noomen Hamza committed
7906 7907 7908 7909

   /*
    * read a STATSTG structure (contains the clsid) from the storage
    */
7910
    hRes=IStorage_Stat(pstg,&pstatstg,STATFLAG_NONAME);
Noomen Hamza's avatar
Noomen Hamza committed
7911 7912 7913 7914 7915 7916 7917

    if(SUCCEEDED(hRes))
        *pclsid=pstatstg.clsid;

    return hRes;
}

7918
/***********************************************************************
7919
 *    OleLoadFromStream (OLE32.@)
Noomen Hamza's avatar
Noomen Hamza committed
7920 7921 7922 7923 7924
 *
 * This function loads an object from stream
 */
HRESULT  WINAPI OleLoadFromStream(IStream *pStm,REFIID iidInterface,void** ppvObj)
{
7925 7926 7927
    CLSID	clsid;
    HRESULT	res;
    LPPERSISTSTREAM	xstm;
Noomen Hamza's avatar
Noomen Hamza committed
7928

7929
    TRACE("(%p,%s,%p)\n",pStm,debugstr_guid(iidInterface),ppvObj);
Noomen Hamza's avatar
Noomen Hamza committed
7930 7931

    res=ReadClassStm(pStm,&clsid);
7932
    if (FAILED(res))
7933 7934
	return res;
    res=CoCreateInstance(&clsid,NULL,CLSCTX_INPROC_SERVER,iidInterface,ppvObj);
7935
    if (FAILED(res))
7936
	return res;
7937
    res=IUnknown_QueryInterface((IUnknown*)*ppvObj,&IID_IPersistStream,(LPVOID*)&xstm);
7938
    if (FAILED(res)) {
7939 7940
	IUnknown_Release((IUnknown*)*ppvObj);
	return res;
Noomen Hamza's avatar
Noomen Hamza committed
7941
    }
7942 7943 7944 7945 7946 7947 7948
    res=IPersistStream_Load(xstm,pStm);
    IPersistStream_Release(xstm);
    /* FIXME: all refcounts ok at this point? I think they should be:
     * 		pStm	: unchanged
     *		ppvObj	: 1
     *		xstm	: 0 (released)
     */
Noomen Hamza's avatar
Noomen Hamza committed
7949 7950 7951
    return res;
}

7952
/***********************************************************************
7953
 *    OleSaveToStream (OLE32.@)
Noomen Hamza's avatar
Noomen Hamza committed
7954
 *
7955 7956
 * This function saves an object with the IPersistStream interface on it
 * to the specified stream.
Noomen Hamza's avatar
Noomen Hamza committed
7957 7958 7959 7960 7961 7962
 */
HRESULT  WINAPI OleSaveToStream(IPersistStream *pPStm,IStream *pStm)
{

    CLSID clsid;
    HRESULT res;
7963

7964
    TRACE("(%p,%p)\n",pPStm,pStm);
Noomen Hamza's avatar
Noomen Hamza committed
7965 7966 7967 7968

    res=IPersistStream_GetClassID(pPStm,&clsid);

    if (SUCCEEDED(res)){
7969

Noomen Hamza's avatar
Noomen Hamza committed
7970 7971 7972 7973
        res=WriteClassStm(pStm,&clsid);

        if (SUCCEEDED(res))

7974
            res=IPersistStream_Save(pPStm,pStm,TRUE);
Noomen Hamza's avatar
Noomen Hamza committed
7975 7976
    }

7977
    TRACE("Finished Save\n");
Noomen Hamza's avatar
Noomen Hamza committed
7978 7979
    return res;
}
7980

7981 7982 7983
/****************************************************************************
 * This method validate a STGM parameter that can contain the values below
 *
7984 7985 7986
 * The stgm modes in 0x0000ffff are not bit masks, but distinct 4 bit values.
 * The stgm values contained in 0xffff0000 are bitmasks.
 *
7987 7988 7989
 * STGM_DIRECT               0x00000000
 * STGM_TRANSACTED           0x00010000
 * STGM_SIMPLE               0x08000000
7990
 *
7991 7992 7993
 * STGM_READ                 0x00000000
 * STGM_WRITE                0x00000001
 * STGM_READWRITE            0x00000002
7994
 *
7995 7996 7997 7998
 * STGM_SHARE_DENY_NONE      0x00000040
 * STGM_SHARE_DENY_READ      0x00000030
 * STGM_SHARE_DENY_WRITE     0x00000020
 * STGM_SHARE_EXCLUSIVE      0x00000010
7999
 *
8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011
 * STGM_PRIORITY             0x00040000
 * STGM_DELETEONRELEASE      0x04000000
 *
 * STGM_CREATE               0x00001000
 * STGM_CONVERT              0x00020000
 * STGM_FAILIFTHERE          0x00000000
 *
 * STGM_NOSCRATCH            0x00100000
 * STGM_NOSNAPSHOT           0x00200000
 */
static HRESULT validateSTGM(DWORD stgm)
{
8012 8013 8014
  DWORD access = STGM_ACCESS_MODE(stgm);
  DWORD share  = STGM_SHARE_MODE(stgm);
  DWORD create = STGM_CREATE_MODE(stgm);
8015

8016 8017
  if (stgm&~STGM_KNOWN_FLAGS)
  {
8018
    ERR("unknown flags %08x\n", stgm);
8019 8020
    return E_FAIL;
  }
8021

8022 8023 8024 8025 8026 8027 8028 8029 8030
  switch (access)
  {
  case STGM_READ:
  case STGM_WRITE:
  case STGM_READWRITE:
    break;
  default:
    return E_FAIL;
  }
8031

8032 8033 8034 8035 8036 8037 8038 8039 8040 8041
  switch (share)
  {
  case STGM_SHARE_DENY_NONE:
  case STGM_SHARE_DENY_READ:
  case STGM_SHARE_DENY_WRITE:
  case STGM_SHARE_EXCLUSIVE:
    break;
  default:
    return E_FAIL;
  }
8042

8043 8044 8045 8046 8047 8048 8049 8050
  switch (create)
  {
  case STGM_CREATE:
  case STGM_FAILIFTHERE:
    break;
  default:
    return E_FAIL;
  }
8051

8052
  /*
8053 8054
   * STGM_DIRECT | STGM_TRANSACTED | STGM_SIMPLE
   */
8055
  if ( (stgm & STGM_TRANSACTED) && (stgm & STGM_SIMPLE) )
8056 8057 8058 8059 8060 8061
      return E_FAIL;

  /*
   * STGM_CREATE | STGM_CONVERT
   * if both are false, STGM_FAILIFTHERE is set to TRUE
   */
8062
  if ( create == STGM_CREATE && (stgm & STGM_CONVERT) )
8063 8064 8065 8066 8067
    return E_FAIL;

  /*
   * STGM_NOSCRATCH requires STGM_TRANSACTED
   */
8068
  if ( (stgm & STGM_NOSCRATCH) && !(stgm & STGM_TRANSACTED) )
8069
    return E_FAIL;
8070

8071
  /*
8072
   * STGM_NOSNAPSHOT requires STGM_TRANSACTED and
8073 8074
   * not STGM_SHARE_EXCLUSIVE or STGM_SHARE_DENY_WRITE`
   */
8075 8076 8077 8078
  if ( (stgm & STGM_NOSNAPSHOT) &&
        (!(stgm & STGM_TRANSACTED) ||
         share == STGM_SHARE_EXCLUSIVE ||
         share == STGM_SHARE_DENY_WRITE) )
8079 8080 8081 8082 8083 8084 8085 8086 8087
    return E_FAIL;

  return S_OK;
}

/****************************************************************************
 *      GetShareModeFromSTGM
 *
 * This method will return a share mode flag from a STGM value.
8088
 * The STGM value is assumed valid.
8089 8090 8091
 */
static DWORD GetShareModeFromSTGM(DWORD stgm)
{
8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105
  switch (STGM_SHARE_MODE(stgm))
  {
  case STGM_SHARE_DENY_NONE:
    return FILE_SHARE_READ | FILE_SHARE_WRITE;
  case STGM_SHARE_DENY_READ:
    return FILE_SHARE_WRITE;
  case STGM_SHARE_DENY_WRITE:
    return FILE_SHARE_READ;
  case STGM_SHARE_EXCLUSIVE:
    return 0;
  }
  ERR("Invalid share mode!\n");
  assert(0);
  return 0;
8106 8107 8108 8109 8110 8111 8112 8113 8114 8115
}

/****************************************************************************
 *      GetAccessModeFromSTGM
 *
 * This method will return an access mode flag from a STGM value.
 * The STGM value is assumed valid.
 */
static DWORD GetAccessModeFromSTGM(DWORD stgm)
{
8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126
  switch (STGM_ACCESS_MODE(stgm))
  {
  case STGM_READ:
    return GENERIC_READ;
  case STGM_WRITE:
  case STGM_READWRITE:
    return GENERIC_READ | GENERIC_WRITE;
  }
  ERR("Invalid access mode!\n");
  assert(0);
  return 0;
8127 8128 8129 8130 8131 8132 8133 8134 8135 8136
}

/****************************************************************************
 *      GetCreationModeFromSTGM
 *
 * This method will return a creation mode flag from a STGM value.
 * The STGM value is assumed valid.
 */
static DWORD GetCreationModeFromSTGM(DWORD stgm)
{
8137 8138 8139
  switch(STGM_CREATE_MODE(stgm))
  {
  case STGM_CREATE:
8140
    return CREATE_ALWAYS;
8141
  case STGM_CONVERT:
8142
    FIXME("STGM_CONVERT not implemented!\n");
8143
    return CREATE_NEW;
8144 8145
  case STGM_FAILIFTHERE:
    return CREATE_NEW;
8146
  }
8147 8148 8149
  ERR("Invalid create mode!\n");
  assert(0);
  return 0;
8150
}
8151 8152 8153


/*************************************************************************
8154
 * OLECONVERT_LoadOLE10 [Internal]
8155
 *
8156
 * Loads the OLE10 STREAM to memory
8157 8158 8159 8160 8161 8162 8163 8164
 *
 * PARAMS
 *     pOleStream   [I] The OLESTREAM
 *     pData        [I] Data Structure for the OLESTREAM Data
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  CONVERT10_E_OLESTREAM_GET for invalid Get
Austin English's avatar
Austin English committed
8165
 *               CONVERT10_E_OLESTREAM_FMT if the OLEID is invalid
8166 8167 8168
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
8169
 *
8170 8171
 *     Memory allocated for pData must be freed by the caller
 */
8172
static HRESULT OLECONVERT_LoadOLE10(LPOLESTREAM pOleStream, OLECONVERT_OLESTREAM_DATA *pData, BOOL bStrem1)
8173 8174 8175
{
	DWORD dwSize;
	HRESULT hRes = S_OK;
Alexandre Julliard's avatar
Alexandre Julliard committed
8176 8177 8178
	int nTryCnt=0;
	int max_try = 6;

8179
	pData->pData = NULL;
8180
	pData->pstrOleObjFileName = NULL;
8181

Alexandre Julliard's avatar
Alexandre Julliard committed
8182 8183
	for( nTryCnt=0;nTryCnt < max_try; nTryCnt++)
	{
8184 8185 8186 8187 8188 8189 8190 8191 8192 8193
	/* Get the OleID */
	dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
	if(dwSize != sizeof(pData->dwOleID))
	{
		hRes = CONVERT10_E_OLESTREAM_GET;
	}
	else if(pData->dwOleID != OLESTREAM_ID)
	{
		hRes = CONVERT10_E_OLESTREAM_FMT;
	}
Alexandre Julliard's avatar
Alexandre Julliard committed
8194 8195 8196 8197 8198 8199
		else
		{
			hRes = S_OK;
			break;
		}
	}
8200 8201 8202

	if(hRes == S_OK)
	{
8203
		/* Get the TypeID... more info needed for this field */
8204 8205 8206 8207 8208 8209 8210 8211 8212 8213
		dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
		if(dwSize != sizeof(pData->dwTypeID))
		{
			hRes = CONVERT10_E_OLESTREAM_GET;
		}
	}
	if(hRes == S_OK)
	{
		if(pData->dwTypeID != 0)
		{
Francois Gouget's avatar
Francois Gouget committed
8214
			/* Get the length of the OleTypeName */
8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225
			dwSize = pOleStream->lpstbl->Get(pOleStream, (void *) &(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
			if(dwSize != sizeof(pData->dwOleTypeNameLength))
			{
				hRes = CONVERT10_E_OLESTREAM_GET;
			}

			if(hRes == S_OK)
			{
				if(pData->dwOleTypeNameLength > 0)
				{
					/* Get the OleTypeName */
8226
					dwSize = pOleStream->lpstbl->Get(pOleStream, pData->strOleTypeName, pData->dwOleTypeNameLength);
8227 8228 8229 8230 8231 8232
					if(dwSize != pData->dwOleTypeNameLength)
					{
						hRes = CONVERT10_E_OLESTREAM_GET;
					}
				}
			}
Alexandre Julliard's avatar
Alexandre Julliard committed
8233 8234 8235 8236 8237 8238 8239
			if(bStrem1)
			{
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleObjFileNameLength), sizeof(pData->dwOleObjFileNameLength));
				if(dwSize != sizeof(pData->dwOleObjFileNameLength))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
8240
			if(hRes == S_OK)
Alexandre Julliard's avatar
Alexandre Julliard committed
8241
			{
8242
					if(pData->dwOleObjFileNameLength < 1) /* there is no file name exist */
Alexandre Julliard's avatar
Alexandre Julliard committed
8243
						pData->dwOleObjFileNameLength = sizeof(pData->dwOleObjFileNameLength);
8244
					pData->pstrOleObjFileName = HeapAlloc(GetProcessHeap(), 0, pData->dwOleObjFileNameLength);
Alexandre Julliard's avatar
Alexandre Julliard committed
8245 8246
					if(pData->pstrOleObjFileName)
					{
8247
						dwSize = pOleStream->lpstbl->Get(pOleStream, pData->pstrOleObjFileName, pData->dwOleObjFileNameLength);
Alexandre Julliard's avatar
Alexandre Julliard committed
8248 8249 8250 8251 8252 8253 8254 8255 8256 8257
						if(dwSize != pData->dwOleObjFileNameLength)
						{
							hRes = CONVERT10_E_OLESTREAM_GET;
						}
					}
					else
						hRes = CONVERT10_E_OLESTREAM_GET;
				}
			}
			else
8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273
			{
				/* Get the Width of the Metafile */
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
				if(dwSize != sizeof(pData->dwMetaFileWidth))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
			if(hRes == S_OK)
			{
				/* Get the Height of the Metafile */
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
				if(dwSize != sizeof(pData->dwMetaFileHeight))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
			}
Alexandre Julliard's avatar
Alexandre Julliard committed
8274
			}
8275 8276
			if(hRes == S_OK)
			{
Francois Gouget's avatar
Francois Gouget committed
8277
				/* Get the Length of the Data */
8278 8279 8280 8281 8282 8283 8284
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
				if(dwSize != sizeof(pData->dwDataLength))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
			}

Austin English's avatar
Austin English committed
8285
			if(hRes == S_OK) /* I don't know what this 8 byte information is. We have to figure out */
Alexandre Julliard's avatar
Alexandre Julliard committed
8286
			{
8287
				if(!bStrem1) /* if it is a second OLE stream data */
Alexandre Julliard's avatar
Alexandre Julliard committed
8288 8289
				{
					pData->dwDataLength -= 8;
8290
					dwSize = pOleStream->lpstbl->Get(pOleStream, pData->strUnknown, sizeof(pData->strUnknown));
Alexandre Julliard's avatar
Alexandre Julliard committed
8291 8292 8293 8294 8295 8296
					if(dwSize != sizeof(pData->strUnknown))
					{
						hRes = CONVERT10_E_OLESTREAM_GET;
					}
				}
			}
8297 8298 8299 8300
			if(hRes == S_OK)
			{
				if(pData->dwDataLength > 0)
				{
8301
					pData->pData = HeapAlloc(GetProcessHeap(),0,pData->dwDataLength);
8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323

					/* Get Data (ex. IStorage, Metafile, or BMP) */
					if(pData->pData)
					{
						dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)pData->pData, pData->dwDataLength);
						if(dwSize != pData->dwDataLength)
						{
							hRes = CONVERT10_E_OLESTREAM_GET;
						}
					}
					else
					{
						hRes = CONVERT10_E_OLESTREAM_GET;
					}
				}
			}
		}
	}
	return hRes;
}

/*************************************************************************
8324
 * OLECONVERT_SaveOLE10 [Internal]
8325
 *
8326
 * Saves the OLE10 STREAM From memory
8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337
 *
 * PARAMS
 *     pData        [I] Data Structure for the OLESTREAM Data
 *     pOleStream   [I] The OLESTREAM to save
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  CONVERT10_E_OLESTREAM_PUT for invalid Put
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
8338
 *
8339
 */
8340
static HRESULT OLECONVERT_SaveOLE10(OLECONVERT_OLESTREAM_DATA *pData, LPOLESTREAM pOleStream)
8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364
{
    DWORD dwSize;
    HRESULT hRes = S_OK;


   /* Set the OleID */
    dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
    if(dwSize != sizeof(pData->dwOleID))
    {
        hRes = CONVERT10_E_OLESTREAM_PUT;
    }

    if(hRes == S_OK)
    {
        /* Set the TypeID */
        dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
        if(dwSize != sizeof(pData->dwTypeID))
        {
            hRes = CONVERT10_E_OLESTREAM_PUT;
        }
    }

    if(pData->dwOleID == OLESTREAM_ID && pData->dwTypeID != 0 && hRes == S_OK)
    {
Francois Gouget's avatar
Francois Gouget committed
8365
        /* Set the Length of the OleTypeName */
8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376
        dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
        if(dwSize != sizeof(pData->dwOleTypeNameLength))
        {
            hRes = CONVERT10_E_OLESTREAM_PUT;
        }

        if(hRes == S_OK)
        {
            if(pData->dwOleTypeNameLength > 0)
            {
                /* Set the OleTypeName */
8377
                dwSize = pOleStream->lpstbl->Put(pOleStream, pData->strOleTypeName, pData->dwOleTypeNameLength);
8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406
                if(dwSize != pData->dwOleTypeNameLength)
                {
                    hRes = CONVERT10_E_OLESTREAM_PUT;
                }
            }
        }

        if(hRes == S_OK)
        {
            /* Set the width of the Metafile */
            dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
            if(dwSize != sizeof(pData->dwMetaFileWidth))
            {
                hRes = CONVERT10_E_OLESTREAM_PUT;
            }
        }

        if(hRes == S_OK)
        {
            /* Set the height of the Metafile */
            dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
            if(dwSize != sizeof(pData->dwMetaFileHeight))
            {
                hRes = CONVERT10_E_OLESTREAM_PUT;
            }
        }

        if(hRes == S_OK)
        {
Francois Gouget's avatar
Francois Gouget committed
8407
            /* Set the length of the Data */
8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431
            dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
            if(dwSize != sizeof(pData->dwDataLength))
            {
                hRes = CONVERT10_E_OLESTREAM_PUT;
            }
        }

        if(hRes == S_OK)
        {
            if(pData->dwDataLength > 0)
            {
                /* Set the Data (eg. IStorage, Metafile, Bitmap) */
                dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)  pData->pData, pData->dwDataLength);
                if(dwSize != pData->dwDataLength)
                {
                    hRes = CONVERT10_E_OLESTREAM_PUT;
                }
            }
        }
    }
    return hRes;
}

/*************************************************************************
8432
 * OLECONVERT_GetOLE20FromOLE10[Internal]
8433 8434
 *
 * This function copies OLE10 Data (the IStorage in the OLESTREAM) to disk,
8435
 * opens it, and copies the content to the dest IStorage for
8436
 * OleConvertOLESTREAMToIStorage
8437
 *
8438 8439 8440 8441 8442 8443 8444 8445 8446 8447
 *
 * PARAMS
 *     pDestStorage  [I] The IStorage to copy the data to
 *     pBuffer       [I] Buffer that contains the IStorage from the OLESTREAM
 *     nBufferLength [I] The size of the buffer
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
8448 8449
 *
 *
8450
 */
8451
static void OLECONVERT_GetOLE20FromOLE10(LPSTORAGE pDestStorage, const BYTE *pBuffer, DWORD nBufferLength)
8452 8453 8454 8455 8456 8457
{
    HRESULT hRes;
    HANDLE hFile;
    IStorage *pTempStorage;
    DWORD dwNumOfBytesWritten;
    WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
8458
    static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
8459 8460 8461 8462

    /* Create a temp File */
    GetTempPathW(MAX_PATH, wstrTempDir);
    GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
Patrik Stridvall's avatar
Patrik Stridvall committed
8463
    hFile = CreateFileW(wstrTempFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474

    if(hFile != INVALID_HANDLE_VALUE)
    {
        /* Write IStorage Data to File */
        WriteFile(hFile, pBuffer, nBufferLength, &dwNumOfBytesWritten, NULL);
        CloseHandle(hFile);

        /* Open and copy temp storage to the Dest Storage */
        hRes = StgOpenStorage(wstrTempFile, NULL, STGM_READ, NULL, 0, &pTempStorage);
        if(hRes == S_OK)
        {
8475 8476
            hRes = IStorage_CopyTo(pTempStorage, 0, NULL, NULL, pDestStorage);
            IStorage_Release(pTempStorage);
8477 8478 8479 8480 8481 8482 8483
        }
        DeleteFileW(wstrTempFile);
    }
}


/*************************************************************************
8484
 * OLECONVERT_WriteOLE20ToBuffer [Internal]
8485
 *
8486
 * Saves the OLE10 STREAM From memory
8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498
 *
 * PARAMS
 *     pStorage  [I] The Src IStorage to copy
 *     pData     [I] The Dest Memory to write to.
 *
 * RETURNS
 *     The size in bytes allocated for pData
 *
 * NOTES
 *     Memory allocated for pData must be freed by the caller
 *
 *     Used by OleConvertIStorageToOLESTREAM only.
8499
 *
8500
 */
8501
static DWORD OLECONVERT_WriteOLE20ToBuffer(LPSTORAGE pStorage, BYTE **pData)
8502 8503 8504 8505 8506 8507
{
    HANDLE hFile;
    HRESULT hRes;
    DWORD nDataLength = 0;
    IStorage *pTempStorage;
    WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
8508
    static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
8509 8510

    *pData = NULL;
8511

8512 8513 8514
    /* Create temp Storage */
    GetTempPathW(MAX_PATH, wstrTempDir);
    GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
Patrik Stridvall's avatar
Patrik Stridvall committed
8515
    hRes = StgCreateDocfile(wstrTempFile, STGM_CREATE | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &pTempStorage);
8516 8517 8518 8519

    if(hRes == S_OK)
    {
        /* Copy Src Storage to the Temp Storage */
8520 8521
        IStorage_CopyTo(pStorage, 0, NULL, NULL, pTempStorage);
        IStorage_Release(pTempStorage);
8522 8523

        /* Open Temp Storage as a file and copy to memory */
Patrik Stridvall's avatar
Patrik Stridvall committed
8524
        hFile = CreateFileW(wstrTempFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
8525 8526 8527
        if(hFile != INVALID_HANDLE_VALUE)
        {
            nDataLength = GetFileSize(hFile, NULL);
8528
            *pData = HeapAlloc(GetProcessHeap(),0,nDataLength);
8529 8530 8531 8532 8533 8534 8535 8536 8537
            ReadFile(hFile, *pData, nDataLength, &nDataLength, 0);
            CloseHandle(hFile);
        }
        DeleteFileW(wstrTempFile);
    }
    return nDataLength;
}

/*************************************************************************
8538
 * OLECONVERT_CreateOleStream [Internal]
8539
 *
8540
 * Creates the "\001OLE" stream in the IStorage if necessary.
8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552
 *
 * PARAMS
 *     pStorage     [I] Dest storage to create the stream in
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
 *
 *     This stream is still unknown, MS Word seems to have extra data
 *     but since the data is stored in the OLESTREAM there should be
8553
 *     no need to recreate the stream.  If the stream is manually
8554
 *     deleted it will create it with this default data.
8555
 *
8556 8557 8558 8559 8560
 */
void OLECONVERT_CreateOleStream(LPSTORAGE pStorage)
{
    HRESULT hRes;
    IStream *pStream;
8561
    static const WCHAR wstrStreamName[] = {1,'O', 'l', 'e', 0};
8562
    BYTE pOleStreamHeader [] =
8563
    {
8564 8565 8566
        0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00
8567
    };
8568

8569
    /* Create stream if not present */
8570
    hRes = IStorage_CreateStream(pStorage, wstrStreamName,
8571 8572 8573 8574 8575 8576 8577 8578 8579 8580
        STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );

    if(hRes == S_OK)
    {
        /* Write default Data */
        hRes = IStream_Write(pStream, pOleStreamHeader, sizeof(pOleStreamHeader), NULL);
        IStream_Release(pStream);
    }
}

8581 8582 8583 8584 8585 8586 8587 8588 8589
/* write a string to a stream, preceded by its length */
static HRESULT STREAM_WriteString( IStream *stm, LPCWSTR string )
{
    HRESULT r;
    LPSTR str;
    DWORD len = 0;

    if( string )
        len = WideCharToMultiByte( CP_ACP, 0, string, -1, NULL, 0, NULL, NULL);
8590
    r = IStream_Write( stm, &len, sizeof(len), NULL);
8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609
    if( FAILED( r ) )
        return r;
    if(len == 0)
        return r;
    str = CoTaskMemAlloc( len );
    WideCharToMultiByte( CP_ACP, 0, string, -1, str, len, NULL, NULL);
    r = IStream_Write( stm, str, len, NULL);
    CoTaskMemFree( str );
    return r;
}

/* read a string preceded by its length from a stream */
static HRESULT STREAM_ReadString( IStream *stm, LPWSTR *string )
{
    HRESULT r;
    DWORD len, count = 0;
    LPSTR str;
    LPWSTR wstr;

8610
    r = IStream_Read( stm, &len, sizeof(len), &count );
8611 8612
    if( FAILED( r ) )
        return r;
8613
    if( count != sizeof(len) )
8614 8615
        return E_OUTOFMEMORY;

8616
    TRACE("%d bytes\n",len);
8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649
    
    str = CoTaskMemAlloc( len );
    if( !str )
        return E_OUTOFMEMORY;
    count = 0;
    r = IStream_Read( stm, str, len, &count );
    if( FAILED( r ) )
        return r;
    if( count != len )
    {
        CoTaskMemFree( str );
        return E_OUTOFMEMORY;
    }

    TRACE("Read string %s\n",debugstr_an(str,len));

    len = MultiByteToWideChar( CP_ACP, 0, str, count, NULL, 0 );
    wstr = CoTaskMemAlloc( (len + 1)*sizeof (WCHAR) );
    if( wstr )
         MultiByteToWideChar( CP_ACP, 0, str, count, wstr, len );
    CoTaskMemFree( str );

    *string = wstr;

    return r;
}


static HRESULT STORAGE_WriteCompObj( LPSTORAGE pstg, CLSID *clsid,
    LPCWSTR lpszUserType, LPCWSTR szClipName, LPCWSTR szProgIDName )
{
    IStream *pstm;
    HRESULT r = S_OK;
8650
    static const WCHAR szwStreamName[] = {1, 'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662

    static const BYTE unknown1[12] =
       { 0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00,
         0xFF, 0xFF, 0xFF, 0xFF};
    static const BYTE unknown2[16] =
       { 0xF4, 0x39, 0xB2, 0x71, 0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

    TRACE("%p %s %s %s %s\n", pstg, debugstr_guid(clsid),
           debugstr_w(lpszUserType), debugstr_w(szClipName),
           debugstr_w(szProgIDName));

8663
    /*  Create a CompObj stream */
8664
    r = IStorage_CreateStream(pstg, szwStreamName,
8665
        STGM_CREATE | STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pstm );
8666 8667 8668 8669
    if( FAILED (r) )
        return r;

    /* Write CompObj Structure to stream */
8670
    r = IStream_Write(pstm, unknown1, sizeof(unknown1), NULL);
8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681

    if( SUCCEEDED( r ) )
        r = WriteClassStm( pstm, clsid );

    if( SUCCEEDED( r ) )
        r = STREAM_WriteString( pstm, lpszUserType );
    if( SUCCEEDED( r ) )
        r = STREAM_WriteString( pstm, szClipName );
    if( SUCCEEDED( r ) )
        r = STREAM_WriteString( pstm, szProgIDName );
    if( SUCCEEDED( r ) )
8682
        r = IStream_Write(pstm, unknown2, sizeof(unknown2), NULL);
8683 8684 8685 8686 8687 8688 8689

    IStream_Release( pstm );

    return r;
}

/***********************************************************************
8690
 *               WriteFmtUserTypeStg (OLE32.@)
8691 8692 8693 8694 8695 8696
 */
HRESULT WINAPI WriteFmtUserTypeStg(
	  LPSTORAGE pstg, CLIPFORMAT cf, LPOLESTR lpszUserType)
{
    HRESULT r;
    WCHAR szwClipName[0x40];
8697 8698
    CLSID clsid = CLSID_NULL;
    LPWSTR wstrProgID = NULL;
8699 8700 8701 8702 8703
    DWORD n;

    TRACE("(%p,%x,%s)\n",pstg,cf,debugstr_w(lpszUserType));

    /* get the clipboard format name */
8704
    n = GetClipboardFormatNameW( cf, szwClipName, sizeof(szwClipName)/sizeof(szwClipName[0]) );
8705 8706 8707 8708
    szwClipName[n]=0;

    TRACE("Clipboard name is %s\n", debugstr_w(szwClipName));

8709 8710 8711 8712
    /* FIXME: There's room to save a CLSID and its ProgID, but
       the CLSID is not looked up in the registry and in all the
       tests I wrote it was CLSID_NULL.  Where does it come from?
    */
8713

8714 8715
    /* get the real program ID.  This may fail, but that's fine */
    ProgIDFromCLSID(&clsid, &wstrProgID);
8716 8717 8718

    TRACE("progid is %s\n",debugstr_w(wstrProgID));

8719 8720
    r = STORAGE_WriteCompObj( pstg, &clsid, 
                              lpszUserType, szwClipName, wstrProgID );
8721

8722
    CoTaskMemFree(wstrProgID);
8723 8724 8725 8726 8727 8728

    return r;
}


/******************************************************************************
8729
 *              ReadFmtUserTypeStg        [OLE32.@]
8730 8731 8732 8733 8734
 */
HRESULT WINAPI ReadFmtUserTypeStg (LPSTORAGE pstg, CLIPFORMAT* pcf, LPOLESTR* lplpszUserType)
{
    HRESULT r;
    IStream *stm = 0;
8735
    static const WCHAR szCompObj[] = { 1, 'C','o','m','p','O','b','j', 0 };
8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747
    unsigned char unknown1[12];
    unsigned char unknown2[16];
    DWORD count;
    LPWSTR szProgIDName = NULL, szCLSIDName = NULL, szOleTypeName = NULL;
    CLSID clsid;

    TRACE("(%p,%p,%p)\n", pstg, pcf, lplpszUserType);

    r = IStorage_OpenStream( pstg, szCompObj, NULL, 
                    STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
    if( FAILED ( r ) )
    {
8748
        WARN("Failed to open stream r = %08x\n", r);
8749 8750 8751 8752
        return r;
    }

    /* read the various parts of the structure */
8753 8754
    r = IStream_Read( stm, unknown1, sizeof(unknown1), &count );
    if( FAILED( r ) || ( count != sizeof(unknown1) ) )
8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771
        goto end;
    r = ReadClassStm( stm, &clsid );
    if( FAILED( r ) )
        goto end;

    r = STREAM_ReadString( stm, &szCLSIDName );
    if( FAILED( r ) )
        goto end;

    r = STREAM_ReadString( stm, &szOleTypeName );
    if( FAILED( r ) )
        goto end;

    r = STREAM_ReadString( stm, &szProgIDName );
    if( FAILED( r ) )
        goto end;

8772 8773
    r = IStream_Read( stm, unknown2, sizeof(unknown2), &count );
    if( FAILED( r ) || ( count != sizeof(unknown2) ) )
8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790
        goto end;

    /* ok, success... now we just need to store what we found */
    if( pcf )
        *pcf = RegisterClipboardFormatW( szOleTypeName );
    CoTaskMemFree( szOleTypeName );

    if( lplpszUserType )
        *lplpszUserType = szCLSIDName;
    CoTaskMemFree( szProgIDName );

end:
    IStream_Release( stm );

    return r;
}

8791 8792

/*************************************************************************
8793
 * OLECONVERT_CreateCompObjStream [Internal]
8794 8795 8796 8797
 *
 * Creates a "\001CompObj" is the destination IStorage if necessary.
 *
 * PARAMS
8798
 *     pStorage       [I] The dest IStorage to create the CompObj Stream
8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809
 *                        if necessary.
 *     strOleTypeName [I] The ProgID
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  REGDB_E_CLASSNOTREG if cannot reconstruct the stream
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
 *
 *     The stream data is stored in the OLESTREAM and there should be
8810
 *     no need to recreate the stream.  If the stream is manually
8811 8812
 *     deleted it will attempt to create it by querying the registry.
 *
8813
 *
8814 8815 8816 8817 8818 8819
 */
HRESULT OLECONVERT_CreateCompObjStream(LPSTORAGE pStorage, LPCSTR strOleTypeName)
{
    IStream *pStream;
    HRESULT hStorageRes, hRes = S_OK;
    OLECONVERT_ISTORAGE_COMPOBJ IStorageCompObj;
8820
    static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
8821
    WCHAR bufferW[OLESTREAM_MAX_STR_LEN];
8822 8823 8824 8825 8826 8827

    BYTE pCompObjUnknown1[] = {0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};
    BYTE pCompObjUnknown2[] = {0xF4, 0x39, 0xB2, 0x71};

    /* Initialize the CompObj structure */
    memset(&IStorageCompObj, 0, sizeof(IStorageCompObj));
8828 8829
    memcpy(IStorageCompObj.byUnknown1, pCompObjUnknown1, sizeof(pCompObjUnknown1));
    memcpy(IStorageCompObj.byUnknown2, pCompObjUnknown2, sizeof(pCompObjUnknown2));
8830 8831 8832


    /*  Create a CompObj stream if it doesn't exist */
8833
    hStorageRes = IStorage_CreateStream(pStorage, wstrStreamName,
8834 8835 8836 8837 8838 8839 8840 8841
        STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
    if(hStorageRes == S_OK)
    {
        /* copy the OleTypeName to the compobj struct */
        IStorageCompObj.dwOleTypeNameLength = strlen(strOleTypeName)+1;
        strcpy(IStorageCompObj.strOleTypeName, strOleTypeName);

        /* copy the OleTypeName to the compobj struct */
8842
        /* Note: in the test made, these were Identical      */
8843 8844 8845 8846
        IStorageCompObj.dwProgIDNameLength = strlen(strOleTypeName)+1;
        strcpy(IStorageCompObj.strProgIDName, strOleTypeName);

        /* Get the CLSID */
8847 8848 8849
        MultiByteToWideChar( CP_ACP, 0, IStorageCompObj.strProgIDName, -1,
                             bufferW, OLESTREAM_MAX_STR_LEN );
        hRes = CLSIDFromProgID(bufferW, &(IStorageCompObj.clsid));
8850

8851
        if(hRes == S_OK)
8852 8853 8854 8855
        {
            HKEY hKey;
            LONG hErr;
            /* Get the CLSID Default Name from the Registry */
8856
            hErr = RegOpenKeyA(HKEY_CLASSES_ROOT, IStorageCompObj.strProgIDName, &hKey);
8857 8858 8859 8860
            if(hErr == ERROR_SUCCESS)
            {
                char strTemp[OLESTREAM_MAX_STR_LEN];
                IStorageCompObj.dwCLSIDNameLength = OLESTREAM_MAX_STR_LEN;
8861
                hErr = RegQueryValueA(hKey, NULL, strTemp, (LONG*) &(IStorageCompObj.dwCLSIDNameLength));
8862 8863 8864 8865 8866 8867 8868 8869
                if(hErr == ERROR_SUCCESS)
                {
                    strcpy(IStorageCompObj.strCLSIDName, strTemp);
                }
                RegCloseKey(hKey);
            }
        }

8870 8871 8872 8873 8874 8875 8876
        /* Write CompObj Structure to stream */
        hRes = IStream_Write(pStream, IStorageCompObj.byUnknown1, sizeof(IStorageCompObj.byUnknown1), NULL);

        WriteClassStm(pStream,&(IStorageCompObj.clsid));

        hRes = IStream_Write(pStream, &(IStorageCompObj.dwCLSIDNameLength), sizeof(IStorageCompObj.dwCLSIDNameLength), NULL);
        if(IStorageCompObj.dwCLSIDNameLength > 0)
8877
        {
8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888
            hRes = IStream_Write(pStream, IStorageCompObj.strCLSIDName, IStorageCompObj.dwCLSIDNameLength, NULL);
        }
        hRes = IStream_Write(pStream, &(IStorageCompObj.dwOleTypeNameLength) , sizeof(IStorageCompObj.dwOleTypeNameLength), NULL);
        if(IStorageCompObj.dwOleTypeNameLength > 0)
        {
            hRes = IStream_Write(pStream, IStorageCompObj.strOleTypeName , IStorageCompObj.dwOleTypeNameLength, NULL);
        }
        hRes = IStream_Write(pStream, &(IStorageCompObj.dwProgIDNameLength) , sizeof(IStorageCompObj.dwProgIDNameLength), NULL);
        if(IStorageCompObj.dwProgIDNameLength > 0)
        {
            hRes = IStream_Write(pStream, IStorageCompObj.strProgIDName , IStorageCompObj.dwProgIDNameLength, NULL);
8889
        }
8890
        hRes = IStream_Write(pStream, IStorageCompObj.byUnknown2 , sizeof(IStorageCompObj.byUnknown2), NULL);
8891 8892 8893 8894 8895 8896 8897
        IStream_Release(pStream);
    }
    return hRes;
}


/*************************************************************************
8898
 * OLECONVERT_CreateOlePresStream[Internal]
8899 8900 8901 8902 8903 8904
 *
 * Creates the "\002OlePres000" Stream with the Metafile data
 *
 * PARAMS
 *     pStorage     [I] The dest IStorage to create \002OLEPres000 stream in.
 *     dwExtentX    [I] Width of the Metafile
8905
 *     dwExtentY    [I] Height of the Metafile
8906 8907 8908 8909 8910 8911 8912 8913 8914
 *     pData        [I] Metafile data
 *     dwDataLength [I] Size of the Metafile data
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  CONVERT10_E_OLESTREAM_PUT for invalid Put
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
8915
 *
8916
 */
8917
static void OLECONVERT_CreateOlePresStream(LPSTORAGE pStorage, DWORD dwExtentX, DWORD dwExtentY , BYTE *pData, DWORD dwDataLength)
8918 8919 8920
{
    HRESULT hRes;
    IStream *pStream;
8921
    static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
8922
    BYTE pOlePresStreamHeader [] =
8923
    {
8924 8925
        0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00,
        0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
8926 8927 8928 8929
        0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00
    };

8930
    BYTE pOlePresStreamHeaderEmpty [] =
8931
    {
8932 8933
        0x00, 0x00, 0x00, 0x00,
        0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
8934 8935 8936
        0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00
    };
8937

8938
    /* Create the OlePres000 Stream */
8939
    hRes = IStorage_CreateStream(pStorage, wstrStreamName,
8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962
        STGM_CREATE | STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );

    if(hRes == S_OK)
    {
        DWORD nHeaderSize;
        OLECONVERT_ISTORAGE_OLEPRES OlePres;

        memset(&OlePres, 0, sizeof(OlePres));
        /* Do we have any metafile data to save */
        if(dwDataLength > 0)
        {
            memcpy(OlePres.byUnknown1, pOlePresStreamHeader, sizeof(pOlePresStreamHeader));
            nHeaderSize = sizeof(pOlePresStreamHeader);
        }
        else
        {
            memcpy(OlePres.byUnknown1, pOlePresStreamHeaderEmpty, sizeof(pOlePresStreamHeaderEmpty));
            nHeaderSize = sizeof(pOlePresStreamHeaderEmpty);
        }
        /* Set width and height of the metafile */
        OlePres.dwExtentX = dwExtentX;
        OlePres.dwExtentY = -dwExtentY;

Francois Gouget's avatar
Francois Gouget committed
8963
        /* Set Data and Length */
8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982
        if(dwDataLength > sizeof(METAFILEPICT16))
        {
            OlePres.dwSize = dwDataLength - sizeof(METAFILEPICT16);
            OlePres.pData = &(pData[8]);
        }
        /* Save OlePres000 Data to Stream */
        hRes = IStream_Write(pStream, OlePres.byUnknown1, nHeaderSize, NULL);
        hRes = IStream_Write(pStream, &(OlePres.dwExtentX), sizeof(OlePres.dwExtentX), NULL);
        hRes = IStream_Write(pStream, &(OlePres.dwExtentY), sizeof(OlePres.dwExtentY), NULL);
        hRes = IStream_Write(pStream, &(OlePres.dwSize), sizeof(OlePres.dwSize), NULL);
        if(OlePres.dwSize > 0)
        {
            hRes = IStream_Write(pStream, OlePres.pData, OlePres.dwSize, NULL);
        }
        IStream_Release(pStream);
    }
}

/*************************************************************************
8983
 * OLECONVERT_CreateOle10NativeStream [Internal]
8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998
 *
 * Creates the "\001Ole10Native" Stream (should contain a BMP)
 *
 * PARAMS
 *     pStorage     [I] Dest storage to create the stream in
 *     pData        [I] Ole10 Native Data (ex. bmp)
 *     dwDataLength [I] Size of the Ole10 Native Data
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
 *
 *     Might need to verify the data and return appropriate error message
8999
 *
9000
 */
9001
static void OLECONVERT_CreateOle10NativeStream(LPSTORAGE pStorage, const BYTE *pData, DWORD dwDataLength)
9002 9003 9004
{
    HRESULT hRes;
    IStream *pStream;
9005
    static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
9006

9007
    /* Create the Ole10Native Stream */
9008
    hRes = IStorage_CreateStream(pStorage, wstrStreamName,
9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021
        STGM_CREATE | STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );

    if(hRes == S_OK)
    {
        /* Write info to stream */
        hRes = IStream_Write(pStream, &dwDataLength, sizeof(dwDataLength), NULL);
        hRes = IStream_Write(pStream, pData, dwDataLength, NULL);
        IStream_Release(pStream);
    }

}

/*************************************************************************
9022
 * OLECONVERT_GetOLE10ProgID [Internal]
9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037
 *
 * Finds the ProgID (or OleTypeID) from the IStorage
 *
 * PARAMS
 *     pStorage        [I] The Src IStorage to get the ProgID
 *     strProgID       [I] the ProgID string to get
 *     dwSize          [I] the size of the string
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  REGDB_E_CLASSNOTREG if cannot reconstruct the stream
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
 *
9038
 *
9039
 */
9040
static HRESULT OLECONVERT_GetOLE10ProgID(LPSTORAGE pStorage, char *strProgID, DWORD *dwSize)
9041 9042 9043 9044 9045
{
    HRESULT hRes;
    IStream *pStream;
    LARGE_INTEGER iSeekPos;
    OLECONVERT_ISTORAGE_COMPOBJ CompObj;
9046
    static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
9047 9048

    /* Open the CompObj Stream */
9049
    hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
9050 9051 9052 9053 9054
        STGM_READ  | STGM_SHARE_EXCLUSIVE, 0, &pStream );
    if(hRes == S_OK)
    {

        /*Get the OleType from the CompObj Stream */
9055 9056
        iSeekPos.u.LowPart = sizeof(CompObj.byUnknown1) + sizeof(CompObj.clsid);
        iSeekPos.u.HighPart = 0;
9057 9058 9059

        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
        IStream_Read(pStream, &CompObj.dwCLSIDNameLength, sizeof(CompObj.dwCLSIDNameLength), NULL);
9060
        iSeekPos.u.LowPart = CompObj.dwCLSIDNameLength;
9061 9062
        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);
        IStream_Read(pStream, &CompObj.dwOleTypeNameLength, sizeof(CompObj.dwOleTypeNameLength), NULL);
9063
        iSeekPos.u.LowPart = CompObj.dwOleTypeNameLength;
9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085
        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);

        IStream_Read(pStream, dwSize, sizeof(*dwSize), NULL);
        if(*dwSize > 0)
        {
            IStream_Read(pStream, strProgID, *dwSize, NULL);
        }
        IStream_Release(pStream);
    }
    else
    {
        STATSTG stat;
        LPOLESTR wstrProgID;

        /* Get the OleType from the registry */
        REFCLSID clsid = &(stat.clsid);
        IStorage_Stat(pStorage, &stat, STATFLAG_NONAME);
        hRes = ProgIDFromCLSID(clsid, &wstrProgID);
        if(hRes == S_OK)
        {
            *dwSize = WideCharToMultiByte(CP_ACP, 0, wstrProgID, -1, strProgID, *dwSize, NULL, FALSE);
        }
9086

9087 9088 9089 9090 9091
    }
    return hRes;
}

/*************************************************************************
9092
 * OLECONVERT_GetOle10PresData [Internal]
9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106
 *
 * Converts IStorage "/001Ole10Native" stream to a OLE10 Stream
 *
 * PARAMS
 *     pStorage     [I] Src IStroage
 *     pOleStream   [I] Dest OleStream Mem Struct
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
 *
 *     Memory allocated for pData must be freed by the caller
9107 9108
 *
 *
9109
 */
9110
static void OLECONVERT_GetOle10PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
9111 9112 9113 9114
{

    HRESULT hRes;
    IStream *pStream;
9115
    static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127

    /* Initialize Default data for OLESTREAM */
    pOleStreamData[0].dwOleID = OLESTREAM_ID;
    pOleStreamData[0].dwTypeID = 2;
    pOleStreamData[1].dwOleID = OLESTREAM_ID;
    pOleStreamData[1].dwTypeID = 0;
    pOleStreamData[0].dwMetaFileWidth = 0;
    pOleStreamData[0].dwMetaFileHeight = 0;
    pOleStreamData[0].pData = NULL;
    pOleStreamData[1].pData = NULL;

    /* Open Ole10Native Stream */
9128
    hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
9129 9130 9131 9132 9133 9134 9135 9136
        STGM_READ  | STGM_SHARE_EXCLUSIVE, 0, &pStream );
    if(hRes == S_OK)
    {

        /* Read Size and Data */
        IStream_Read(pStream, &(pOleStreamData->dwDataLength), sizeof(pOleStreamData->dwDataLength), NULL);
        if(pOleStreamData->dwDataLength > 0)
        {
9137
            pOleStreamData->pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData->dwDataLength);
9138 9139 9140 9141 9142 9143 9144 9145 9146
            IStream_Read(pStream, pOleStreamData->pData, pOleStreamData->dwDataLength, NULL);
        }
        IStream_Release(pStream);
    }

}


/*************************************************************************
9147
 * OLECONVERT_GetOle20PresData[Internal]
9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159
 *
 * Converts IStorage "/002OlePres000" stream to a OLE10 Stream
 *
 * PARAMS
 *     pStorage         [I] Src IStroage
 *     pOleStreamData   [I] Dest OleStream Mem Struct
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
9160
 *
9161 9162
 *     Memory allocated for pData must be freed by the caller
 */
9163
static void OLECONVERT_GetOle20PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
9164 9165 9166 9167
{
    HRESULT hRes;
    IStream *pStream;
    OLECONVERT_ISTORAGE_OLEPRES olePress;
9168
    static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186

    /* Initialize Default data for OLESTREAM */
    pOleStreamData[0].dwOleID = OLESTREAM_ID;
    pOleStreamData[0].dwTypeID = 2;
    pOleStreamData[0].dwMetaFileWidth = 0;
    pOleStreamData[0].dwMetaFileHeight = 0;
    pOleStreamData[0].dwDataLength = OLECONVERT_WriteOLE20ToBuffer(pStorage, &(pOleStreamData[0].pData));
    pOleStreamData[1].dwOleID = OLESTREAM_ID;
    pOleStreamData[1].dwTypeID = 0;
    pOleStreamData[1].dwOleTypeNameLength = 0;
    pOleStreamData[1].strOleTypeName[0] = 0;
    pOleStreamData[1].dwMetaFileWidth = 0;
    pOleStreamData[1].dwMetaFileHeight = 0;
    pOleStreamData[1].pData = NULL;
    pOleStreamData[1].dwDataLength = 0;


    /* Open OlePress000 stream */
9187
    hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
9188 9189 9190 9191 9192
        STGM_READ  | STGM_SHARE_EXCLUSIVE, 0, &pStream );
    if(hRes == S_OK)
    {
        LARGE_INTEGER iSeekPos;
        METAFILEPICT16 MetaFilePict;
9193
        static const char strMetafilePictName[] = "METAFILEPICT";
9194 9195 9196 9197 9198 9199 9200 9201

        /* Set the TypeID for a Metafile */
        pOleStreamData[1].dwTypeID = 5;

        /* Set the OleTypeName to Metafile */
        pOleStreamData[1].dwOleTypeNameLength = strlen(strMetafilePictName) +1;
        strcpy(pOleStreamData[1].strOleTypeName, strMetafilePictName);

9202 9203
        iSeekPos.u.HighPart = 0;
        iSeekPos.u.LowPart = sizeof(olePress.byUnknown1);
9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225

        /* Get Presentation Data */
        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
        IStream_Read(pStream, &(olePress.dwExtentX), sizeof(olePress.dwExtentX), NULL);
        IStream_Read(pStream, &(olePress.dwExtentY), sizeof(olePress.dwExtentY), NULL);
        IStream_Read(pStream, &(olePress.dwSize), sizeof(olePress.dwSize), NULL);

        /*Set width and Height */
        pOleStreamData[1].dwMetaFileWidth = olePress.dwExtentX;
        pOleStreamData[1].dwMetaFileHeight = -olePress.dwExtentY;
        if(olePress.dwSize > 0)
        {
            /* Set Length */
            pOleStreamData[1].dwDataLength  = olePress.dwSize + sizeof(METAFILEPICT16);

            /* Set MetaFilePict struct */
            MetaFilePict.mm = 8;
            MetaFilePict.xExt = olePress.dwExtentX;
            MetaFilePict.yExt = olePress.dwExtentY;
            MetaFilePict.hMF = 0;

            /* Get Metafile Data */
9226
            pOleStreamData[1].pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData[1].dwDataLength);
9227 9228 9229 9230 9231 9232 9233 9234
            memcpy(pOleStreamData[1].pData, &MetaFilePict, sizeof(MetaFilePict));
            IStream_Read(pStream, &(pOleStreamData[1].pData[sizeof(MetaFilePict)]), pOleStreamData[1].dwDataLength-sizeof(METAFILEPICT16), NULL);
        }
        IStream_Release(pStream);
    }
}

/*************************************************************************
9235
 * OleConvertOLESTREAMToIStorage [OLE32.@]
9236 9237 9238 9239
 *
 * Read info on MSDN
 *
 * TODO
Austin English's avatar
Austin English committed
9240
 *      DVTARGETDEVICE parameter is not handled
9241 9242 9243
 *      Still unsure of some mem fields for OLE 10 Stream
 *      Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
 *      and "\001OLE" streams
9244
 *
9245 9246
 */
HRESULT WINAPI OleConvertOLESTREAMToIStorage (
9247 9248
    LPOLESTREAM pOleStream,
    LPSTORAGE pstg,
9249 9250 9251 9252 9253 9254
    const DVTARGETDEVICE* ptd)
{
    int i;
    HRESULT hRes=S_OK;
    OLECONVERT_OLESTREAM_DATA pOleStreamData[2];

9255 9256
    TRACE("%p %p %p\n", pOleStream, pstg, ptd);

9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271
    memset(pOleStreamData, 0, sizeof(pOleStreamData));

    if(ptd != NULL)
    {
        FIXME("DVTARGETDEVICE is not NULL, unhandled parameter\n");
    }

    if(pstg == NULL || pOleStream == NULL)
    {
        hRes = E_INVALIDARG;
    }

    if(hRes == S_OK)
    {
        /* Load the OLESTREAM to Memory */
Alexandre Julliard's avatar
Alexandre Julliard committed
9272
        hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[0], TRUE);
9273 9274 9275 9276 9277
    }

    if(hRes == S_OK)
    {
        /* Load the OLESTREAM to Memory (part 2)*/
Alexandre Julliard's avatar
Alexandre Julliard committed
9278
        hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[1], FALSE);
9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316
    }

    if(hRes == S_OK)
    {

        if(pOleStreamData[0].dwDataLength > sizeof(STORAGE_magic))
        {
            /* Do we have the IStorage Data in the OLESTREAM */
            if(memcmp(pOleStreamData[0].pData, STORAGE_magic, sizeof(STORAGE_magic)) ==0)
            {
                OLECONVERT_GetOLE20FromOLE10(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
                OLECONVERT_CreateOlePresStream(pstg, pOleStreamData[1].dwMetaFileWidth, pOleStreamData[1].dwMetaFileHeight, pOleStreamData[1].pData, pOleStreamData[1].dwDataLength);
            }
            else
            {
                /* It must be an original OLE 1.0 source */
                OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
            }
        }
        else
        {
            /* It must be an original OLE 1.0 source */
            OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
        }

        /* Create CompObj Stream if necessary */
        hRes = OLECONVERT_CreateCompObjStream(pstg, pOleStreamData[0].strOleTypeName);
        if(hRes == S_OK)
        {
            /*Create the Ole Stream if necessary */
            OLECONVERT_CreateOleStream(pstg);
        }
    }


    /* Free allocated memory */
    for(i=0; i < 2; i++)
    {
9317 9318 9319
        HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
        HeapFree(GetProcessHeap(),0,pOleStreamData[i].pstrOleObjFileName);
        pOleStreamData[i].pstrOleObjFileName = NULL;
9320 9321 9322 9323 9324
    }
    return hRes;
}

/*************************************************************************
9325
 * OleConvertIStorageToOLESTREAM [OLE32.@]
9326 9327 9328 9329 9330 9331 9332 9333 9334
 *
 * Read info on MSDN
 *
 * Read info on MSDN
 *
 * TODO
 *      Still unsure of some mem fields for OLE 10 Stream
 *      Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
 *      and "\001OLE" streams.
9335
 *
9336 9337
 */
HRESULT WINAPI OleConvertIStorageToOLESTREAM (
9338
    LPSTORAGE pstg,
9339 9340 9341 9342 9343 9344
    LPOLESTREAM pOleStream)
{
    int i;
    HRESULT hRes = S_OK;
    IStream *pStream;
    OLECONVERT_OLESTREAM_DATA pOleStreamData[2];
9345
    static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
9346

9347
    TRACE("%p %p\n", pstg, pOleStream);
9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362

    memset(pOleStreamData, 0, sizeof(pOleStreamData));

    if(pstg == NULL || pOleStream == NULL)
    {
        hRes = E_INVALIDARG;
    }
    if(hRes == S_OK)
    {
        /* Get the ProgID */
        pOleStreamData[0].dwOleTypeNameLength = OLESTREAM_MAX_STR_LEN;
        hRes = OLECONVERT_GetOLE10ProgID(pstg, pOleStreamData[0].strOleTypeName, &(pOleStreamData[0].dwOleTypeNameLength));
    }
    if(hRes == S_OK)
    {
Alexandre Julliard's avatar
Alexandre Julliard committed
9363
        /* Was it originally Ole10 */
9364
        hRes = IStorage_OpenStream(pstg, wstrStreamName, 0, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream);
9365 9366 9367
        if(hRes == S_OK)
        {
            IStream_Release(pStream);
Alexandre Julliard's avatar
Alexandre Julliard committed
9368
            /* Get Presentation Data for Ole10Native */
9369 9370 9371 9372
            OLECONVERT_GetOle10PresData(pstg, pOleStreamData);
        }
        else
        {
Alexandre Julliard's avatar
Alexandre Julliard committed
9373
            /* Get Presentation Data (OLE20) */
9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388
            OLECONVERT_GetOle20PresData(pstg, pOleStreamData);
        }

        /* Save OLESTREAM */
        hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[0]), pOleStream);
        if(hRes == S_OK)
        {
            hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[1]), pOleStream);
        }

    }

    /* Free allocated memory */
    for(i=0; i < 2; i++)
    {
9389
        HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
9390 9391 9392 9393
    }

    return hRes;
}
9394

9395
/***********************************************************************
9396
 *		GetConvertStg (OLE32.@)
9397
 */
9398 9399
HRESULT WINAPI GetConvertStg(IStorage *stg) {
    FIXME("unimplemented stub!\n");
9400 9401
    return E_FAIL;
}
9402 9403

/******************************************************************************
9404
 * StgIsStorageFile [OLE32.@]
9405 9406 9407 9408 9409 9410 9411 9412
 * Verify if the file contains a storage object
 *
 * PARAMS
 *  fn      [ I] Filename
 *
 * RETURNS
 *  S_OK    if file has magic bytes as a storage object
 *  S_FALSE if file is not storage
9413 9414 9415 9416 9417 9418 9419 9420
 */
HRESULT WINAPI
StgIsStorageFile(LPCOLESTR fn)
{
	HANDLE		hf;
	BYTE		magic[8];
	DWORD		bytes_read;

9421
	TRACE("%s\n", debugstr_w(fn));
9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438
	hf = CreateFileW(fn, GENERIC_READ,
	                 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
	                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

	if (hf == INVALID_HANDLE_VALUE)
		return STG_E_FILENOTFOUND;

	if (!ReadFile(hf, magic, 8, &bytes_read, NULL))
	{
		WARN(" unable to read file\n");
		CloseHandle(hf);
		return S_FALSE;
	}

	CloseHandle(hf);

	if (bytes_read != 8) {
9439
		TRACE(" too short\n");
9440 9441 9442 9443
		return S_FALSE;
	}

	if (!memcmp(magic,STORAGE_magic,8)) {
9444
		TRACE(" -> YES\n");
9445 9446 9447
		return S_OK;
	}

9448
	TRACE(" -> Invalid header.\n");
9449 9450
	return S_FALSE;
}
9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468

/***********************************************************************
 *		WriteClassStm (OLE32.@)
 *
 * Writes a CLSID to a stream.
 *
 * PARAMS
 *  pStm   [I] Stream to write to.
 *  rclsid [I] CLSID to write.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI WriteClassStm(IStream *pStm,REFCLSID rclsid)
{
    TRACE("(%p,%p)\n",pStm,rclsid);

9469
    if (!pStm || !rclsid)
9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494
        return E_INVALIDARG;

    return IStream_Write(pStm,rclsid,sizeof(CLSID),NULL);
}

/***********************************************************************
 *		ReadClassStm (OLE32.@)
 *
 * Reads a CLSID from a stream.
 *
 * PARAMS
 *  pStm   [I] Stream to read from.
 *  rclsid [O] CLSID to read.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI ReadClassStm(IStream *pStm,CLSID *pclsid)
{
    ULONG nbByte;
    HRESULT res;

    TRACE("(%p,%p)\n",pStm,pclsid);

9495
    if (!pStm || !pclsid)
9496 9497
        return E_INVALIDARG;

9498
    /* clear the output args */
9499
    *pclsid = CLSID_NULL;
9500

9501 9502 9503 9504 9505 9506
    res = IStream_Read(pStm,(void*)pclsid,sizeof(CLSID),&nbByte);

    if (FAILED(res))
        return res;

    if (nbByte != sizeof(CLSID))
9507
        return STG_E_READFAULT;
9508 9509 9510
    else
        return S_OK;
}