2 * Compound Storage (32 bit version)
3 * Storage implementation
5 * This file contains the compound file implementation
6 * of the storage interface.
8 * Copyright 1999 Francis Beaudet
9 * Copyright 1999 Sylvain St-Germain
10 * Copyright 1999 Thuy Nguyen
11 * Copyright 2005 Mike McCormack
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2.1 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with this library; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 * The compound file implementation of IStorage used for create
29 * and manage substorages and streams within a storage object
30 * residing in a compound file object.
33 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/stg/stg/istorage_compound_file_implementation.asp
43 #define NONAMELESSUNION
44 #define NONAMELESSSTRUCT
50 #include "wine/unicode.h"
51 #include "wine/debug.h"
53 #include "storage32.h"
54 #include "ole2.h" /* For Write/ReadClassStm */
57 #include "wine/wingdi16.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(storage);
61 /* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
62 #define OLESTREAM_ID 0x501
63 #define OLESTREAM_MAX_STR_LEN 255
65 static const char rootPropertyName[] = "Root Entry";
68 /* OLESTREAM memory structure to use for Get and Put Routines */
69 /* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
74 DWORD dwOleTypeNameLength;
75 CHAR strOleTypeName[OLESTREAM_MAX_STR_LEN];
76 CHAR *pstrOleObjFileName;
77 DWORD dwOleObjFileNameLength;
78 DWORD dwMetaFileWidth;
79 DWORD dwMetaFileHeight;
80 CHAR strUnknown[8]; /* don't know what is this 8 byts information in OLE stream. */
83 }OLECONVERT_OLESTREAM_DATA;
85 /* CompObj Stream structure */
86 /* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
91 DWORD dwCLSIDNameLength;
92 CHAR strCLSIDName[OLESTREAM_MAX_STR_LEN];
93 DWORD dwOleTypeNameLength;
94 CHAR strOleTypeName[OLESTREAM_MAX_STR_LEN];
95 DWORD dwProgIDNameLength;
96 CHAR strProgIDName[OLESTREAM_MAX_STR_LEN];
98 }OLECONVERT_ISTORAGE_COMPOBJ;
101 /* Ole Presention Stream structure */
102 /* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
110 }OLECONVERT_ISTORAGE_OLEPRES;
114 /***********************************************************************
115 * Forward declaration of internal functions used by the method DestroyElement
117 static HRESULT deleteStorageProperty(
118 StorageImpl *parentStorage,
119 ULONG foundPropertyIndexToDelete,
120 StgProperty propertyToDelete);
122 static HRESULT deleteStreamProperty(
123 StorageImpl *parentStorage,
124 ULONG foundPropertyIndexToDelete,
125 StgProperty propertyToDelete);
127 static HRESULT findPlaceholder(
128 StorageImpl *storage,
129 ULONG propertyIndexToStore,
130 ULONG storagePropertyIndex,
133 static HRESULT adjustPropertyChain(
135 StgProperty propertyToDelete,
136 StgProperty parentProperty,
137 ULONG parentPropertyId,
140 /***********************************************************************
141 * Declaration of the functions used to manipulate StgProperty
144 static ULONG getFreeProperty(
145 StorageImpl *storage);
147 static void updatePropertyChain(
148 StorageImpl *storage,
149 ULONG newPropertyIndex,
150 StgProperty newProperty);
152 static LONG propertyNameCmp(
153 const OLECHAR *newProperty,
154 const OLECHAR *currentProperty);
157 /***********************************************************************
158 * Declaration of miscellaneous functions...
160 static HRESULT validateSTGM(DWORD stgmValue);
162 static DWORD GetShareModeFromSTGM(DWORD stgm);
163 static DWORD GetAccessModeFromSTGM(DWORD stgm);
164 static DWORD GetCreationModeFromSTGM(DWORD stgm);
166 extern const IPropertySetStorageVtbl IPropertySetStorage_Vtbl;
170 /************************************************************************
171 ** Storage32BaseImpl implementatiion
174 /************************************************************************
175 * Storage32BaseImpl_QueryInterface (IUnknown)
177 * This method implements the common QueryInterface for all IStorage32
178 * implementations contained in this file.
180 * See Windows documentation for more details on IUnknown methods.
182 HRESULT WINAPI StorageBaseImpl_QueryInterface(
187 StorageBaseImpl *This = (StorageBaseImpl *)iface;
189 * Perform a sanity check on the parameters.
191 if ( (This==0) || (ppvObject==0) )
195 * Initialize the return parameter.
200 * Compare the riid with the interface IDs implemented by this object.
202 if (memcmp(&IID_IUnknown, riid, sizeof(IID_IUnknown)) == 0)
204 *ppvObject = (IStorage*)This;
206 else if (memcmp(&IID_IStorage, riid, sizeof(IID_IStorage)) == 0)
208 *ppvObject = (IStorage*)This;
210 else if (memcmp(&IID_IPropertySetStorage, riid, sizeof(IID_IPropertySetStorage)) == 0)
212 *ppvObject = (IStorage*)&This->pssVtbl;
216 * Check that we obtained an interface.
219 return E_NOINTERFACE;
222 * Query Interface always increases the reference count by one when it is
225 IStorage_AddRef(iface);
230 /************************************************************************
231 * Storage32BaseImpl_AddRef (IUnknown)
233 * This method implements the common AddRef for all IStorage32
234 * implementations contained in this file.
236 * See Windows documentation for more details on IUnknown methods.
238 ULONG WINAPI StorageBaseImpl_AddRef(
241 StorageBaseImpl *This = (StorageBaseImpl *)iface;
242 ULONG ref = InterlockedIncrement(&This->ref);
244 TRACE("(%p) AddRef to %ld\n", This, ref);
249 /************************************************************************
250 * Storage32BaseImpl_Release (IUnknown)
252 * This method implements the common Release for all IStorage32
253 * implementations contained in this file.
255 * See Windows documentation for more details on IUnknown methods.
257 ULONG WINAPI StorageBaseImpl_Release(
260 StorageBaseImpl *This = (StorageBaseImpl *)iface;
262 * Decrease the reference count on this object.
264 ULONG ref = InterlockedDecrement(&This->ref);
266 TRACE("(%p) ReleaseRef to %ld\n", This, ref);
269 * If the reference count goes down to 0, perform suicide.
274 * Since we are using a system of base-classes, we want to call the
275 * destructor of the appropriate derived class. To do this, we are
276 * using virtual functions to implement the destructor.
278 This->v_destructor(This);
284 /************************************************************************
285 * Storage32BaseImpl_OpenStream (IStorage)
287 * This method will open the specified stream object from the current storage.
289 * See Windows documentation for more details on IStorage methods.
291 HRESULT WINAPI StorageBaseImpl_OpenStream(
293 const OLECHAR* pwcsName, /* [string][in] */
294 void* reserved1, /* [unique][in] */
295 DWORD grfMode, /* [in] */
296 DWORD reserved2, /* [in] */
297 IStream** ppstm) /* [out] */
299 StorageBaseImpl *This = (StorageBaseImpl *)iface;
300 IEnumSTATSTGImpl* propertyEnumeration;
301 StgStreamImpl* newStream;
302 StgProperty currentProperty;
303 ULONG foundPropertyIndex;
304 HRESULT res = STG_E_UNKNOWN;
305 DWORD parent_grfMode;
307 TRACE("(%p, %s, %p, %lx, %ld, %p)\n",
308 iface, debugstr_w(pwcsName), reserved1, grfMode, reserved2, ppstm);
311 * Perform a sanity check on the parameters.
313 if ( (pwcsName==NULL) || (ppstm==0) )
320 * Initialize the out parameter
325 * Validate the STGM flags
327 if ( FAILED( validateSTGM(grfMode) ))
329 res = STG_E_INVALIDFLAG;
336 if ( STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE ||
337 (grfMode & STGM_DELETEONRELEASE) ||
338 (grfMode & STGM_TRANSACTED) )
340 res = STG_E_INVALIDFUNCTION;
345 * Check that we're compatible with the parent's storage mode, but
346 * only if we are not in transacted mode
348 parent_grfMode = STGM_ACCESS_MODE( This->ancestorStorage->base.openFlags );
349 if(!(This->ancestorStorage->base.openFlags & STGM_TRANSACTED)) {
350 if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( parent_grfMode ) )
352 res = STG_E_ACCESSDENIED;
358 * Create a property enumeration to search the properties
360 propertyEnumeration = IEnumSTATSTGImpl_Construct(
361 This->ancestorStorage,
362 This->rootPropertySetIndex);
365 * Search the enumeration for the property with the given name
367 foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(
373 * Delete the property enumeration since we don't need it anymore
375 IEnumSTATSTGImpl_Destroy(propertyEnumeration);
378 * If it was found, construct the stream object and return a pointer to it.
380 if ( (foundPropertyIndex!=PROPERTY_NULL) &&
381 (currentProperty.propertyType==PROPTYPE_STREAM) )
383 newStream = StgStreamImpl_Construct(This, grfMode, foundPropertyIndex);
387 newStream->grfMode = grfMode;
388 *ppstm = (IStream*)newStream;
391 * Since we are returning a pointer to the interface, we have to
392 * nail down the reference.
394 IStream_AddRef(*ppstm);
397 * add us to the storage's list of active streams
400 StorageBaseImpl_AddStream(This,newStream);
410 res = STG_E_FILENOTFOUND;
414 TRACE("<-- IStream %p\n", *ppstm);
415 TRACE("<-- %08lx\n", res);
419 /************************************************************************
420 * Storage32BaseImpl_OpenStorage (IStorage)
422 * This method will open a new storage object from the current storage.
424 * See Windows documentation for more details on IStorage methods.
426 HRESULT WINAPI StorageBaseImpl_OpenStorage(
428 const OLECHAR* pwcsName, /* [string][unique][in] */
429 IStorage* pstgPriority, /* [unique][in] */
430 DWORD grfMode, /* [in] */
431 SNB snbExclude, /* [unique][in] */
432 DWORD reserved, /* [in] */
433 IStorage** ppstg) /* [out] */
435 StorageBaseImpl *This = (StorageBaseImpl *)iface;
436 StorageInternalImpl* newStorage;
437 IEnumSTATSTGImpl* propertyEnumeration;
438 StgProperty currentProperty;
439 ULONG foundPropertyIndex;
440 HRESULT res = STG_E_UNKNOWN;
441 DWORD parent_grfMode;
443 TRACE("(%p, %s, %p, %lx, %p, %ld, %p)\n",
444 iface, debugstr_w(pwcsName), pstgPriority,
445 grfMode, snbExclude, reserved, ppstg);
448 * Perform a sanity check on the parameters.
450 if ( (This==0) || (pwcsName==NULL) || (ppstg==0) )
457 if (snbExclude != NULL)
459 res = STG_E_INVALIDPARAMETER;
464 * Validate the STGM flags
466 if ( FAILED( validateSTGM(grfMode) ))
468 res = STG_E_INVALIDFLAG;
475 if ( STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE ||
476 (grfMode & STGM_DELETEONRELEASE) ||
477 (grfMode & STGM_PRIORITY) )
479 res = STG_E_INVALIDFUNCTION;
484 * Check that we're compatible with the parent's storage mode,
485 * but only if we are not transacted
487 parent_grfMode = STGM_ACCESS_MODE( This->ancestorStorage->base.openFlags );
488 if(!(This->ancestorStorage->base.openFlags & STGM_TRANSACTED)) {
489 if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( parent_grfMode ) )
491 res = STG_E_ACCESSDENIED;
497 * Initialize the out parameter
502 * Create a property enumeration to search the properties
504 propertyEnumeration = IEnumSTATSTGImpl_Construct(
505 This->ancestorStorage,
506 This->rootPropertySetIndex);
509 * Search the enumeration for the property with the given name
511 foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(
517 * Delete the property enumeration since we don't need it anymore
519 IEnumSTATSTGImpl_Destroy(propertyEnumeration);
522 * If it was found, construct the stream object and return a pointer to it.
524 if ( (foundPropertyIndex!=PROPERTY_NULL) &&
525 (currentProperty.propertyType==PROPTYPE_STORAGE) )
528 * Construct a new Storage object
530 newStorage = StorageInternalImpl_Construct(
531 This->ancestorStorage,
537 *ppstg = (IStorage*)newStorage;
540 * Since we are returning a pointer to the interface,
541 * we have to nail down the reference.
543 StorageBaseImpl_AddRef(*ppstg);
549 res = STG_E_INSUFFICIENTMEMORY;
553 res = STG_E_FILENOTFOUND;
556 TRACE("<-- %08lx\n", res);
560 /************************************************************************
561 * Storage32BaseImpl_EnumElements (IStorage)
563 * This method will create an enumerator object that can be used to
564 * retrieve informatino about all the properties in the storage object.
566 * See Windows documentation for more details on IStorage methods.
568 HRESULT WINAPI StorageBaseImpl_EnumElements(
570 DWORD reserved1, /* [in] */
571 void* reserved2, /* [size_is][unique][in] */
572 DWORD reserved3, /* [in] */
573 IEnumSTATSTG** ppenum) /* [out] */
575 StorageBaseImpl *This = (StorageBaseImpl *)iface;
576 IEnumSTATSTGImpl* newEnum;
578 TRACE("(%p, %ld, %p, %ld, %p)\n",
579 iface, reserved1, reserved2, reserved3, ppenum);
582 * Perform a sanity check on the parameters.
584 if ( (This==0) || (ppenum==0))
588 * Construct the enumerator.
590 newEnum = IEnumSTATSTGImpl_Construct(
591 This->ancestorStorage,
592 This->rootPropertySetIndex);
596 *ppenum = (IEnumSTATSTG*)newEnum;
599 * Don't forget to nail down a reference to the new object before
602 IEnumSTATSTG_AddRef(*ppenum);
607 return E_OUTOFMEMORY;
610 /************************************************************************
611 * Storage32BaseImpl_Stat (IStorage)
613 * This method will retrieve information about this storage object.
615 * See Windows documentation for more details on IStorage methods.
617 HRESULT WINAPI StorageBaseImpl_Stat(
619 STATSTG* pstatstg, /* [out] */
620 DWORD grfStatFlag) /* [in] */
622 StorageBaseImpl *This = (StorageBaseImpl *)iface;
623 StgProperty curProperty;
625 HRESULT res = STG_E_UNKNOWN;
627 TRACE("(%p, %p, %lx)\n",
628 iface, pstatstg, grfStatFlag);
631 * Perform a sanity check on the parameters.
633 if ( (This==0) || (pstatstg==0))
640 * Read the information from the property.
642 readSuccessful = StorageImpl_ReadProperty(
643 This->ancestorStorage,
644 This->rootPropertySetIndex,
649 StorageUtl_CopyPropertyToSTATSTG(
663 TRACE("<-- STATSTG: pwcsName: %s, type: %ld, cbSize.Low/High: %ld/%ld, grfMode: %08lx, grfLocksSupported: %ld, grfStateBits: %08lx\n", debugstr_w(pstatstg->pwcsName), pstatstg->type, pstatstg->cbSize.u.LowPart, pstatstg->cbSize.u.HighPart, pstatstg->grfMode, pstatstg->grfLocksSupported, pstatstg->grfStateBits);
665 TRACE("<-- %08lx\n", res);
669 /************************************************************************
670 * Storage32BaseImpl_RenameElement (IStorage)
672 * This method will rename the specified element.
674 * See Windows documentation for more details on IStorage methods.
676 * Implementation notes: The method used to rename consists of creating a clone
677 * of the deleted StgProperty object setting it with the new name and to
678 * perform a DestroyElement of the old StgProperty.
680 HRESULT WINAPI StorageBaseImpl_RenameElement(
682 const OLECHAR* pwcsOldName, /* [in] */
683 const OLECHAR* pwcsNewName) /* [in] */
685 StorageBaseImpl *This = (StorageBaseImpl *)iface;
686 IEnumSTATSTGImpl* propertyEnumeration;
687 StgProperty currentProperty;
688 ULONG foundPropertyIndex;
690 TRACE("(%p, %s, %s)\n",
691 iface, debugstr_w(pwcsOldName), debugstr_w(pwcsNewName));
694 * Create a property enumeration to search the properties
696 propertyEnumeration = IEnumSTATSTGImpl_Construct(This->ancestorStorage,
697 This->rootPropertySetIndex);
700 * Search the enumeration for the new property name
702 foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
706 if (foundPropertyIndex != PROPERTY_NULL)
709 * There is already a property with the new name
711 IEnumSTATSTGImpl_Destroy(propertyEnumeration);
712 return STG_E_FILEALREADYEXISTS;
715 IEnumSTATSTG_Reset((IEnumSTATSTG*)propertyEnumeration);
718 * Search the enumeration for the old property name
720 foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
725 * Delete the property enumeration since we don't need it anymore
727 IEnumSTATSTGImpl_Destroy(propertyEnumeration);
729 if (foundPropertyIndex != PROPERTY_NULL)
731 StgProperty renamedProperty;
732 ULONG renamedPropertyIndex;
735 * Setup a new property for the renamed property
737 renamedProperty.sizeOfNameString =
738 ( lstrlenW(pwcsNewName)+1 ) * sizeof(WCHAR);
740 if (renamedProperty.sizeOfNameString > PROPERTY_NAME_BUFFER_LEN)
741 return STG_E_INVALIDNAME;
743 strcpyW(renamedProperty.name, pwcsNewName);
745 renamedProperty.propertyType = currentProperty.propertyType;
746 renamedProperty.startingBlock = currentProperty.startingBlock;
747 renamedProperty.size.u.LowPart = currentProperty.size.u.LowPart;
748 renamedProperty.size.u.HighPart = currentProperty.size.u.HighPart;
750 renamedProperty.previousProperty = PROPERTY_NULL;
751 renamedProperty.nextProperty = PROPERTY_NULL;
754 * Bring the dirProperty link in case it is a storage and in which
755 * case the renamed storage elements don't require to be reorganized.
757 renamedProperty.dirProperty = currentProperty.dirProperty;
759 /* call CoFileTime to get the current time
760 renamedProperty.timeStampS1
761 renamedProperty.timeStampD1
762 renamedProperty.timeStampS2
763 renamedProperty.timeStampD2
764 renamedProperty.propertyUniqueID
768 * Obtain a free property in the property chain
770 renamedPropertyIndex = getFreeProperty(This->ancestorStorage);
773 * Save the new property into the new property spot
775 StorageImpl_WriteProperty(
776 This->ancestorStorage,
777 renamedPropertyIndex,
781 * Find a spot in the property chain for our newly created property.
785 renamedPropertyIndex,
789 * At this point the renamed property has been inserted in the tree,
790 * now, before to Destroy the old property we must zeroed it's dirProperty
791 * otherwise the DestroyProperty below will zap it all and we do not want
793 * Also, we fake that the old property is a storage so the DestroyProperty
794 * will not do a SetSize(0) on the stream data.
796 * This means that we need to tweek the StgProperty if it is a stream or a
799 StorageImpl_ReadProperty(This->ancestorStorage,
803 currentProperty.dirProperty = PROPERTY_NULL;
804 currentProperty.propertyType = PROPTYPE_STORAGE;
805 StorageImpl_WriteProperty(
806 This->ancestorStorage,
811 * Invoke Destroy to get rid of the ole property and automatically redo
812 * the linking of it's previous and next members...
814 IStorage_DestroyElement((IStorage*)This->ancestorStorage, pwcsOldName);
820 * There is no property with the old name
822 return STG_E_FILENOTFOUND;
828 /************************************************************************
829 * Storage32BaseImpl_CreateStream (IStorage)
831 * This method will create a stream object within this storage
833 * See Windows documentation for more details on IStorage methods.
835 HRESULT WINAPI StorageBaseImpl_CreateStream(
837 const OLECHAR* pwcsName, /* [string][in] */
838 DWORD grfMode, /* [in] */
839 DWORD reserved1, /* [in] */
840 DWORD reserved2, /* [in] */
841 IStream** ppstm) /* [out] */
843 StorageBaseImpl *This = (StorageBaseImpl *)iface;
844 IEnumSTATSTGImpl* propertyEnumeration;
845 StgStreamImpl* newStream;
846 StgProperty currentProperty, newStreamProperty;
847 ULONG foundPropertyIndex, newPropertyIndex;
848 DWORD parent_grfMode;
850 TRACE("(%p, %s, %lx, %ld, %ld, %p)\n",
851 iface, debugstr_w(pwcsName), grfMode,
852 reserved1, reserved2, ppstm);
855 * Validate parameters
858 return STG_E_INVALIDPOINTER;
861 return STG_E_INVALIDNAME;
863 if (reserved1 || reserved2)
864 return STG_E_INVALIDPARAMETER;
867 * Validate the STGM flags
869 if ( FAILED( validateSTGM(grfMode) ))
870 return STG_E_INVALIDFLAG;
872 if (STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE)
873 return STG_E_INVALIDFLAG;
878 if ((grfMode & STGM_DELETEONRELEASE) ||
879 (grfMode & STGM_TRANSACTED))
880 return STG_E_INVALIDFUNCTION;
883 * Check that we're compatible with the parent's storage mode
884 * if not in transacted mode
886 parent_grfMode = STGM_ACCESS_MODE( This->ancestorStorage->base.openFlags );
887 if(!(parent_grfMode & STGM_TRANSACTED)) {
888 if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( parent_grfMode ) )
889 return STG_E_ACCESSDENIED;
893 * Initialize the out parameter
898 * Create a property enumeration to search the properties
900 propertyEnumeration = IEnumSTATSTGImpl_Construct(This->ancestorStorage,
901 This->rootPropertySetIndex);
903 foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
907 IEnumSTATSTGImpl_Destroy(propertyEnumeration);
909 if (foundPropertyIndex != PROPERTY_NULL)
912 * An element with this name already exists
914 if (STGM_CREATE_MODE(grfMode) == STGM_CREATE)
916 IStorage_DestroyElement(iface, pwcsName);
919 return STG_E_FILEALREADYEXISTS;
923 * memset the empty property
925 memset(&newStreamProperty, 0, sizeof(StgProperty));
927 newStreamProperty.sizeOfNameString =
928 ( lstrlenW(pwcsName)+1 ) * sizeof(WCHAR);
930 if (newStreamProperty.sizeOfNameString > PROPERTY_NAME_BUFFER_LEN)
931 return STG_E_INVALIDNAME;
933 strcpyW(newStreamProperty.name, pwcsName);
935 newStreamProperty.propertyType = PROPTYPE_STREAM;
936 newStreamProperty.startingBlock = BLOCK_END_OF_CHAIN;
937 newStreamProperty.size.u.LowPart = 0;
938 newStreamProperty.size.u.HighPart = 0;
940 newStreamProperty.previousProperty = PROPERTY_NULL;
941 newStreamProperty.nextProperty = PROPERTY_NULL;
942 newStreamProperty.dirProperty = PROPERTY_NULL;
944 /* call CoFileTime to get the current time
945 newStreamProperty.timeStampS1
946 newStreamProperty.timeStampD1
947 newStreamProperty.timeStampS2
948 newStreamProperty.timeStampD2
951 /* newStreamProperty.propertyUniqueID */
954 * Get a free property or create a new one
956 newPropertyIndex = getFreeProperty(This->ancestorStorage);
959 * Save the new property into the new property spot
961 StorageImpl_WriteProperty(
962 This->ancestorStorage,
967 * Find a spot in the property chain for our newly created property.
975 * Open the stream to return it.
977 newStream = StgStreamImpl_Construct(This, grfMode, newPropertyIndex);
981 *ppstm = (IStream*)newStream;
984 * Since we are returning a pointer to the interface, we have to nail down
987 IStream_AddRef(*ppstm);
989 /* add us to the storage's list of active streams
991 StorageBaseImpl_AddStream(This,newStream);
996 return STG_E_INSUFFICIENTMEMORY;
1002 /************************************************************************
1003 * Storage32BaseImpl_SetClass (IStorage)
1005 * This method will write the specified CLSID in the property of this
1008 * See Windows documentation for more details on IStorage methods.
1010 HRESULT WINAPI StorageBaseImpl_SetClass(
1012 REFCLSID clsid) /* [in] */
1014 StorageBaseImpl *This = (StorageBaseImpl *)iface;
1015 HRESULT hRes = E_FAIL;
1016 StgProperty curProperty;
1019 TRACE("(%p, %p)\n", iface, clsid);
1021 success = StorageImpl_ReadProperty(This->ancestorStorage,
1022 This->rootPropertySetIndex,
1026 curProperty.propertyUniqueID = *clsid;
1028 success = StorageImpl_WriteProperty(This->ancestorStorage,
1029 This->rootPropertySetIndex,
1038 /************************************************************************
1039 ** Storage32Impl implementation
1042 /************************************************************************
1043 * Storage32Impl_CreateStorage (IStorage)
1045 * This method will create the storage object within the provided storage.
1047 * See Windows documentation for more details on IStorage methods.
1049 HRESULT WINAPI StorageImpl_CreateStorage(
1051 const OLECHAR *pwcsName, /* [string][in] */
1052 DWORD grfMode, /* [in] */
1053 DWORD reserved1, /* [in] */
1054 DWORD reserved2, /* [in] */
1055 IStorage **ppstg) /* [out] */
1057 StorageImpl* const This=(StorageImpl*)iface;
1059 IEnumSTATSTGImpl *propertyEnumeration;
1060 StgProperty currentProperty;
1061 StgProperty newProperty;
1062 ULONG foundPropertyIndex;
1063 ULONG newPropertyIndex;
1065 DWORD parent_grfMode;
1067 TRACE("(%p, %s, %lx, %ld, %ld, %p)\n",
1068 iface, debugstr_w(pwcsName), grfMode,
1069 reserved1, reserved2, ppstg);
1072 * Validate parameters
1075 return STG_E_INVALIDPOINTER;
1078 return STG_E_INVALIDNAME;
1081 * Initialize the out parameter
1086 * Validate the STGM flags
1088 if ( FAILED( validateSTGM(grfMode) ) ||
1089 (grfMode & STGM_DELETEONRELEASE) )
1091 WARN("bad grfMode: 0x%lx\n", grfMode);
1092 return STG_E_INVALIDFLAG;
1096 * Check that we're compatible with the parent's storage mode
1098 parent_grfMode = STGM_ACCESS_MODE( This->base.ancestorStorage->base.openFlags );
1099 if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( parent_grfMode ) )
1101 WARN("access denied\n");
1102 return STG_E_ACCESSDENIED;
1106 * Create a property enumeration and search the properties
1108 propertyEnumeration = IEnumSTATSTGImpl_Construct( This->base.ancestorStorage,
1109 This->base.rootPropertySetIndex);
1111 foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
1114 IEnumSTATSTGImpl_Destroy(propertyEnumeration);
1116 if (foundPropertyIndex != PROPERTY_NULL)
1119 * An element with this name already exists
1121 if (STGM_CREATE_MODE(grfMode) == STGM_CREATE)
1122 IStorage_DestroyElement(iface, pwcsName);
1125 WARN("file already exists\n");
1126 return STG_E_FILEALREADYEXISTS;
1131 * memset the empty property
1133 memset(&newProperty, 0, sizeof(StgProperty));
1135 newProperty.sizeOfNameString = (lstrlenW(pwcsName)+1)*sizeof(WCHAR);
1137 if (newProperty.sizeOfNameString > PROPERTY_NAME_BUFFER_LEN)
1139 FIXME("name too long\n");
1140 return STG_E_INVALIDNAME;
1143 strcpyW(newProperty.name, pwcsName);
1145 newProperty.propertyType = PROPTYPE_STORAGE;
1146 newProperty.startingBlock = BLOCK_END_OF_CHAIN;
1147 newProperty.size.u.LowPart = 0;
1148 newProperty.size.u.HighPart = 0;
1150 newProperty.previousProperty = PROPERTY_NULL;
1151 newProperty.nextProperty = PROPERTY_NULL;
1152 newProperty.dirProperty = PROPERTY_NULL;
1154 /* call CoFileTime to get the current time
1155 newProperty.timeStampS1
1156 newProperty.timeStampD1
1157 newProperty.timeStampS2
1158 newProperty.timeStampD2
1161 /* newStorageProperty.propertyUniqueID */
1164 * Obtain a free property in the property chain
1166 newPropertyIndex = getFreeProperty(This->base.ancestorStorage);
1169 * Save the new property into the new property spot
1171 StorageImpl_WriteProperty(
1172 This->base.ancestorStorage,
1177 * Find a spot in the property chain for our newly created property.
1179 updatePropertyChain(
1185 * Open it to get a pointer to return.
1187 hr = IStorage_OpenStorage(
1189 (const OLECHAR*)pwcsName,
1196 if( (hr != S_OK) || (*ppstg == NULL))
1206 /***************************************************************************
1210 * Get a free property or create a new one.
1212 static ULONG getFreeProperty(
1213 StorageImpl *storage)
1215 ULONG currentPropertyIndex = 0;
1216 ULONG newPropertyIndex = PROPERTY_NULL;
1217 BOOL readSuccessful = TRUE;
1218 StgProperty currentProperty;
1223 * Start by reading the root property
1225 readSuccessful = StorageImpl_ReadProperty(storage->base.ancestorStorage,
1226 currentPropertyIndex,
1230 if (currentProperty.sizeOfNameString == 0)
1233 * The property existis and is available, we found it.
1235 newPropertyIndex = currentPropertyIndex;
1241 * We exhausted the property list, we will create more space below
1243 newPropertyIndex = currentPropertyIndex;
1245 currentPropertyIndex++;
1247 } while (newPropertyIndex == PROPERTY_NULL);
1250 * grow the property chain
1252 if (! readSuccessful)
1254 StgProperty emptyProperty;
1255 ULARGE_INTEGER newSize;
1256 ULONG propertyIndex;
1257 ULONG lastProperty = 0;
1258 ULONG blockCount = 0;
1261 * obtain the new count of property blocks
1263 blockCount = BlockChainStream_GetCount(
1264 storage->base.ancestorStorage->rootBlockChain)+1;
1267 * initialize the size used by the property stream
1269 newSize.u.HighPart = 0;
1270 newSize.u.LowPart = storage->bigBlockSize * blockCount;
1273 * add a property block to the property chain
1275 BlockChainStream_SetSize(storage->base.ancestorStorage->rootBlockChain, newSize);
1278 * memset the empty property in order to initialize the unused newly
1281 memset(&emptyProperty, 0, sizeof(StgProperty));
1286 lastProperty = storage->bigBlockSize / PROPSET_BLOCK_SIZE * blockCount;
1289 propertyIndex = newPropertyIndex;
1290 propertyIndex < lastProperty;
1293 StorageImpl_WriteProperty(
1294 storage->base.ancestorStorage,
1300 return newPropertyIndex;
1303 /****************************************************************************
1307 * Case insensitive comparaison of StgProperty.name by first considering
1310 * Returns <0 when newPrpoerty < currentProperty
1311 * >0 when newPrpoerty > currentProperty
1312 * 0 when newPrpoerty == currentProperty
1314 static LONG propertyNameCmp(
1315 const OLECHAR *newProperty,
1316 const OLECHAR *currentProperty)
1318 LONG diff = lstrlenW(newProperty) - lstrlenW(currentProperty);
1323 * We compare the string themselves only when they are of the same length
1325 diff = lstrcmpiW( newProperty, currentProperty);
1331 /****************************************************************************
1335 * Properly link this new element in the property chain.
1337 static void updatePropertyChain(
1338 StorageImpl *storage,
1339 ULONG newPropertyIndex,
1340 StgProperty newProperty)
1342 StgProperty currentProperty;
1345 * Read the root property
1347 StorageImpl_ReadProperty(storage->base.ancestorStorage,
1348 storage->base.rootPropertySetIndex,
1351 if (currentProperty.dirProperty != PROPERTY_NULL)
1354 * The root storage contains some element, therefore, start the research
1355 * for the appropriate location.
1358 ULONG current, next, previous, currentPropertyId;
1361 * Keep the StgProperty sequence number of the storage first property
1363 currentPropertyId = currentProperty.dirProperty;
1368 StorageImpl_ReadProperty(storage->base.ancestorStorage,
1369 currentProperty.dirProperty,
1372 previous = currentProperty.previousProperty;
1373 next = currentProperty.nextProperty;
1374 current = currentPropertyId;
1378 LONG diff = propertyNameCmp( newProperty.name, currentProperty.name);
1382 if (previous != PROPERTY_NULL)
1384 StorageImpl_ReadProperty(storage->base.ancestorStorage,
1391 currentProperty.previousProperty = newPropertyIndex;
1392 StorageImpl_WriteProperty(storage->base.ancestorStorage,
1400 if (next != PROPERTY_NULL)
1402 StorageImpl_ReadProperty(storage->base.ancestorStorage,
1409 currentProperty.nextProperty = newPropertyIndex;
1410 StorageImpl_WriteProperty(storage->base.ancestorStorage,
1419 * Trying to insert an item with the same name in the
1420 * subtree structure.
1425 previous = currentProperty.previousProperty;
1426 next = currentProperty.nextProperty;
1432 * The root storage is empty, link the new property to it's dir property
1434 currentProperty.dirProperty = newPropertyIndex;
1435 StorageImpl_WriteProperty(storage->base.ancestorStorage,
1436 storage->base.rootPropertySetIndex,
1442 /*************************************************************************
1445 HRESULT WINAPI StorageImpl_CopyTo(
1447 DWORD ciidExclude, /* [in] */
1448 const IID* rgiidExclude, /* [size_is][unique][in] */
1449 SNB snbExclude, /* [unique][in] */
1450 IStorage* pstgDest) /* [unique][in] */
1452 IEnumSTATSTG *elements = 0;
1453 STATSTG curElement, strStat;
1455 IStorage *pstgTmp, *pstgChild;
1456 IStream *pstrTmp, *pstrChild;
1458 if ((ciidExclude != 0) || (rgiidExclude != NULL) || (snbExclude != NULL))
1459 FIXME("Exclude option not implemented\n");
1461 TRACE("(%p, %ld, %p, %p, %p)\n",
1462 iface, ciidExclude, rgiidExclude,
1463 snbExclude, pstgDest);
1466 * Perform a sanity check
1468 if ( pstgDest == 0 )
1469 return STG_E_INVALIDPOINTER;
1472 * Enumerate the elements
1474 hr = IStorage_EnumElements( iface, 0, 0, 0, &elements );
1482 IStorage_Stat( iface, &curElement, STATFLAG_NONAME);
1483 IStorage_SetClass( pstgDest, &curElement.clsid );
1488 * Obtain the next element
1490 hr = IEnumSTATSTG_Next( elements, 1, &curElement, NULL );
1492 if ( hr == S_FALSE )
1494 hr = S_OK; /* done, every element has been copied */
1498 if (curElement.type == STGTY_STORAGE)
1501 * open child source storage
1503 hr = IStorage_OpenStorage( iface, curElement.pwcsName, NULL,
1504 STGM_READ|STGM_SHARE_EXCLUSIVE,
1505 NULL, 0, &pstgChild );
1511 * Check if destination storage is not a child of the source
1512 * storage, which will cause an infinite loop
1514 if (pstgChild == pstgDest)
1516 IEnumSTATSTG_Release(elements);
1518 return STG_E_ACCESSDENIED;
1522 * create a new storage in destination storage
1524 hr = IStorage_CreateStorage( pstgDest, curElement.pwcsName,
1525 STGM_FAILIFTHERE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,
1529 * if it already exist, don't create a new one use this one
1531 if (hr == STG_E_FILEALREADYEXISTS)
1533 hr = IStorage_OpenStorage( pstgDest, curElement.pwcsName, NULL,
1534 STGM_WRITE|STGM_SHARE_EXCLUSIVE,
1535 NULL, 0, &pstgTmp );
1543 * do the copy recursively
1545 hr = IStorage_CopyTo( pstgChild, ciidExclude, rgiidExclude,
1546 snbExclude, pstgTmp );
1548 IStorage_Release( pstgTmp );
1549 IStorage_Release( pstgChild );
1551 else if (curElement.type == STGTY_STREAM)
1554 * create a new stream in destination storage. If the stream already
1555 * exist, it will be deleted and a new one will be created.
1557 hr = IStorage_CreateStream( pstgDest, curElement.pwcsName,
1558 STGM_CREATE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,
1565 * open child stream storage
1567 hr = IStorage_OpenStream( iface, curElement.pwcsName, NULL,
1568 STGM_READ|STGM_SHARE_EXCLUSIVE,
1575 * Get the size of the source stream
1577 IStream_Stat( pstrChild, &strStat, STATFLAG_NONAME );
1580 * Set the size of the destination stream.
1582 IStream_SetSize(pstrTmp, strStat.cbSize);
1587 hr = IStream_CopyTo( pstrChild, pstrTmp, strStat.cbSize,
1590 IStream_Release( pstrTmp );
1591 IStream_Release( pstrChild );
1595 WARN("unknown element type: %ld\n", curElement.type);
1598 } while (hr == S_OK);
1603 IEnumSTATSTG_Release(elements);
1608 /*************************************************************************
1609 * MoveElementTo (IStorage)
1611 HRESULT WINAPI StorageImpl_MoveElementTo(
1613 const OLECHAR *pwcsName, /* [string][in] */
1614 IStorage *pstgDest, /* [unique][in] */
1615 const OLECHAR *pwcsNewName,/* [string][in] */
1616 DWORD grfFlags) /* [in] */
1618 FIXME("not implemented!\n");
1622 /*************************************************************************
1625 * Ensures that any changes made to a storage object open in transacted mode
1626 * are reflected in the parent storage
1629 * Wine doesn't implement transacted mode, which seems to be a basic
1630 * optimization, so we can ignore this stub for now.
1632 HRESULT WINAPI StorageImpl_Commit(
1634 DWORD grfCommitFlags)/* [in] */
1636 FIXME("(%ld): stub!\n", grfCommitFlags);
1640 /*************************************************************************
1643 * Discard all changes that have been made since the last commit operation
1645 HRESULT WINAPI StorageImpl_Revert(
1648 FIXME("not implemented!\n");
1652 /*************************************************************************
1653 * DestroyElement (IStorage)
1655 * Stategy: This implementation is build this way for simplicity not for speed.
1656 * I always delete the top most element of the enumeration and adjust
1657 * the deleted element pointer all the time. This takes longer to
1658 * do but allow to reinvoke DestroyElement whenever we encounter a
1659 * storage object. The optimisation reside in the usage of another
1660 * enumeration stategy that would give all the leaves of a storage
1661 * first. (postfix order)
1663 HRESULT WINAPI StorageImpl_DestroyElement(
1665 const OLECHAR *pwcsName)/* [string][in] */
1667 StorageImpl* const This=(StorageImpl*)iface;
1669 IEnumSTATSTGImpl* propertyEnumeration;
1672 StgProperty propertyToDelete;
1673 StgProperty parentProperty;
1674 ULONG foundPropertyIndexToDelete;
1675 ULONG typeOfRelation;
1676 ULONG parentPropertyId;
1679 iface, debugstr_w(pwcsName));
1682 * Perform a sanity check on the parameters.
1685 return STG_E_INVALIDPOINTER;
1688 * Create a property enumeration to search the property with the given name
1690 propertyEnumeration = IEnumSTATSTGImpl_Construct(
1691 This->base.ancestorStorage,
1692 This->base.rootPropertySetIndex);
1694 foundPropertyIndexToDelete = IEnumSTATSTGImpl_FindProperty(
1695 propertyEnumeration,
1699 IEnumSTATSTGImpl_Destroy(propertyEnumeration);
1701 if ( foundPropertyIndexToDelete == PROPERTY_NULL )
1703 return STG_E_FILENOTFOUND;
1707 * Find the parent property of the property to delete (the one that
1708 * link to it). If This->dirProperty == foundPropertyIndexToDelete,
1709 * the parent is This. Otherwise, the parent is one of it's sibling...
1713 * First, read This's StgProperty..
1715 res = StorageImpl_ReadProperty(
1716 This->base.ancestorStorage,
1717 This->base.rootPropertySetIndex,
1723 * Second, check to see if by any chance the actual storage (This) is not
1724 * the parent of the property to delete... We never know...
1726 if ( parentProperty.dirProperty == foundPropertyIndexToDelete )
1729 * Set data as it would have been done in the else part...
1731 typeOfRelation = PROPERTY_RELATION_DIR;
1732 parentPropertyId = This->base.rootPropertySetIndex;
1737 * Create a property enumeration to search the parent properties, and
1738 * delete it once done.
1740 IEnumSTATSTGImpl* propertyEnumeration2;
1742 propertyEnumeration2 = IEnumSTATSTGImpl_Construct(
1743 This->base.ancestorStorage,
1744 This->base.rootPropertySetIndex);
1746 typeOfRelation = IEnumSTATSTGImpl_FindParentProperty(
1747 propertyEnumeration2,
1748 foundPropertyIndexToDelete,
1752 IEnumSTATSTGImpl_Destroy(propertyEnumeration2);
1755 if ( propertyToDelete.propertyType == PROPTYPE_STORAGE )
1757 hr = deleteStorageProperty(
1759 foundPropertyIndexToDelete,
1762 else if ( propertyToDelete.propertyType == PROPTYPE_STREAM )
1764 hr = deleteStreamProperty(
1766 foundPropertyIndexToDelete,
1774 * Adjust the property chain
1776 hr = adjustPropertyChain(
1787 /************************************************************************
1788 * StorageImpl_Stat (IStorage)
1790 * This method will retrieve information about this storage object.
1792 * See Windows documentation for more details on IStorage methods.
1794 HRESULT WINAPI StorageImpl_Stat( IStorage* iface,
1795 STATSTG* pstatstg, /* [out] */
1796 DWORD grfStatFlag) /* [in] */
1798 StorageImpl* const This = (StorageImpl*)iface;
1799 HRESULT result = StorageBaseImpl_Stat( iface, pstatstg, grfStatFlag );
1801 if ( !FAILED(result) && ((grfStatFlag & STATFLAG_NONAME) == 0) && This->pwcsName )
1803 CoTaskMemFree(pstatstg->pwcsName);
1804 pstatstg->pwcsName = CoTaskMemAlloc((lstrlenW(This->pwcsName)+1)*sizeof(WCHAR));
1805 strcpyW(pstatstg->pwcsName, This->pwcsName);
1811 /******************************************************************************
1812 * Internal stream list handlers
1815 void StorageBaseImpl_AddStream(StorageBaseImpl * stg, StgStreamImpl * strm)
1817 TRACE("Stream added (stg=%p strm=%p)\n", stg, strm);
1818 list_add_tail(&stg->strmHead,&strm->StrmListEntry);
1821 void StorageBaseImpl_RemoveStream(StorageBaseImpl * stg, StgStreamImpl * strm)
1823 TRACE("Stream removed (stg=%p strm=%p)\n", stg,strm);
1824 list_remove(&(strm->StrmListEntry));
1827 void StorageBaseImpl_DeleteAll(StorageBaseImpl * stg)
1829 struct list *cur, *cur2;
1830 StgStreamImpl *strm=NULL;
1832 LIST_FOR_EACH_SAFE(cur, cur2, &stg->strmHead) {
1833 strm = LIST_ENTRY(cur,StgStreamImpl,StrmListEntry);
1834 TRACE("Streams deleted (stg=%p strm=%p next=%p prev=%p)\n", stg,strm,cur->next,cur->prev);
1835 strm->parentStorage = NULL;
1841 /*********************************************************************
1845 * Perform the deletion of a complete storage node
1848 static HRESULT deleteStorageProperty(
1849 StorageImpl *parentStorage,
1850 ULONG indexOfPropertyToDelete,
1851 StgProperty propertyToDelete)
1853 IEnumSTATSTG *elements = 0;
1854 IStorage *childStorage = 0;
1855 STATSTG currentElement;
1857 HRESULT destroyHr = S_OK;
1860 * Open the storage and enumerate it
1862 hr = StorageBaseImpl_OpenStorage(
1863 (IStorage*)parentStorage,
1864 propertyToDelete.name,
1866 STGM_SHARE_EXCLUSIVE,
1877 * Enumerate the elements
1879 IStorage_EnumElements( childStorage, 0, 0, 0, &elements);
1884 * Obtain the next element
1886 hr = IEnumSTATSTG_Next(elements, 1, ¤tElement, NULL);
1889 destroyHr = StorageImpl_DestroyElement(
1890 (IStorage*)childStorage,
1891 (OLECHAR*)currentElement.pwcsName);
1893 CoTaskMemFree(currentElement.pwcsName);
1897 * We need to Reset the enumeration every time because we delete elements
1898 * and the enumeration could be invalid
1900 IEnumSTATSTG_Reset(elements);
1902 } while ((hr == S_OK) && (destroyHr == S_OK));
1905 * Invalidate the property by zeroing it's name member.
1907 propertyToDelete.sizeOfNameString = 0;
1909 StorageImpl_WriteProperty(parentStorage->base.ancestorStorage,
1910 indexOfPropertyToDelete,
1913 IStorage_Release(childStorage);
1914 IEnumSTATSTG_Release(elements);
1919 /*********************************************************************
1923 * Perform the deletion of a stream node
1926 static HRESULT deleteStreamProperty(
1927 StorageImpl *parentStorage,
1928 ULONG indexOfPropertyToDelete,
1929 StgProperty propertyToDelete)
1933 ULARGE_INTEGER size;
1935 size.u.HighPart = 0;
1938 hr = StorageBaseImpl_OpenStream(
1939 (IStorage*)parentStorage,
1940 (OLECHAR*)propertyToDelete.name,
1942 STGM_WRITE | STGM_SHARE_EXCLUSIVE,
1954 hr = IStream_SetSize(pis, size);
1962 * Release the stream object.
1964 IStream_Release(pis);
1967 * Invalidate the property by zeroing it's name member.
1969 propertyToDelete.sizeOfNameString = 0;
1972 * Here we should re-read the property so we get the updated pointer
1973 * but since we are here to zap it, I don't do it...
1975 StorageImpl_WriteProperty(
1976 parentStorage->base.ancestorStorage,
1977 indexOfPropertyToDelete,
1983 /*********************************************************************
1987 * Finds a placeholder for the StgProperty within the Storage
1990 static HRESULT findPlaceholder(
1991 StorageImpl *storage,
1992 ULONG propertyIndexToStore,
1993 ULONG storePropertyIndex,
1996 StgProperty storeProperty;
2001 * Read the storage property
2003 res = StorageImpl_ReadProperty(
2004 storage->base.ancestorStorage,
2013 if (typeOfRelation == PROPERTY_RELATION_PREVIOUS)
2015 if (storeProperty.previousProperty != PROPERTY_NULL)
2017 return findPlaceholder(
2019 propertyIndexToStore,
2020 storeProperty.previousProperty,
2025 storeProperty.previousProperty = propertyIndexToStore;
2028 else if (typeOfRelation == PROPERTY_RELATION_NEXT)
2030 if (storeProperty.nextProperty != PROPERTY_NULL)
2032 return findPlaceholder(
2034 propertyIndexToStore,
2035 storeProperty.nextProperty,
2040 storeProperty.nextProperty = propertyIndexToStore;
2043 else if (typeOfRelation == PROPERTY_RELATION_DIR)
2045 if (storeProperty.dirProperty != PROPERTY_NULL)
2047 return findPlaceholder(
2049 propertyIndexToStore,
2050 storeProperty.dirProperty,
2055 storeProperty.dirProperty = propertyIndexToStore;
2059 hr = StorageImpl_WriteProperty(
2060 storage->base.ancestorStorage,
2072 /*************************************************************************
2076 * This method takes the previous and the next property link of a property
2077 * to be deleted and find them a place in the Storage.
2079 static HRESULT adjustPropertyChain(
2081 StgProperty propertyToDelete,
2082 StgProperty parentProperty,
2083 ULONG parentPropertyId,
2086 ULONG newLinkProperty = PROPERTY_NULL;
2087 BOOL needToFindAPlaceholder = FALSE;
2088 ULONG storeNode = PROPERTY_NULL;
2089 ULONG toStoreNode = PROPERTY_NULL;
2090 INT relationType = 0;
2094 if (typeOfRelation == PROPERTY_RELATION_PREVIOUS)
2096 if (propertyToDelete.previousProperty != PROPERTY_NULL)
2099 * Set the parent previous to the property to delete previous
2101 newLinkProperty = propertyToDelete.previousProperty;
2103 if (propertyToDelete.nextProperty != PROPERTY_NULL)
2106 * We also need to find a storage for the other link, setup variables
2107 * to do this at the end...
2109 needToFindAPlaceholder = TRUE;
2110 storeNode = propertyToDelete.previousProperty;
2111 toStoreNode = propertyToDelete.nextProperty;
2112 relationType = PROPERTY_RELATION_NEXT;
2115 else if (propertyToDelete.nextProperty != PROPERTY_NULL)
2118 * Set the parent previous to the property to delete next
2120 newLinkProperty = propertyToDelete.nextProperty;
2124 * Link it for real...
2126 parentProperty.previousProperty = newLinkProperty;
2129 else if (typeOfRelation == PROPERTY_RELATION_NEXT)
2131 if (propertyToDelete.previousProperty != PROPERTY_NULL)
2134 * Set the parent next to the property to delete next previous
2136 newLinkProperty = propertyToDelete.previousProperty;
2138 if (propertyToDelete.nextProperty != PROPERTY_NULL)
2141 * We also need to find a storage for the other link, setup variables
2142 * to do this at the end...
2144 needToFindAPlaceholder = TRUE;
2145 storeNode = propertyToDelete.previousProperty;
2146 toStoreNode = propertyToDelete.nextProperty;
2147 relationType = PROPERTY_RELATION_NEXT;
2150 else if (propertyToDelete.nextProperty != PROPERTY_NULL)
2153 * Set the parent next to the property to delete next
2155 newLinkProperty = propertyToDelete.nextProperty;
2159 * Link it for real...
2161 parentProperty.nextProperty = newLinkProperty;
2163 else /* (typeOfRelation == PROPERTY_RELATION_DIR) */
2165 if (propertyToDelete.previousProperty != PROPERTY_NULL)
2168 * Set the parent dir to the property to delete previous
2170 newLinkProperty = propertyToDelete.previousProperty;
2172 if (propertyToDelete.nextProperty != PROPERTY_NULL)
2175 * We also need to find a storage for the other link, setup variables
2176 * to do this at the end...
2178 needToFindAPlaceholder = TRUE;
2179 storeNode = propertyToDelete.previousProperty;
2180 toStoreNode = propertyToDelete.nextProperty;
2181 relationType = PROPERTY_RELATION_NEXT;
2184 else if (propertyToDelete.nextProperty != PROPERTY_NULL)
2187 * Set the parent dir to the property to delete next
2189 newLinkProperty = propertyToDelete.nextProperty;
2193 * Link it for real...
2195 parentProperty.dirProperty = newLinkProperty;
2199 * Write back the parent property
2201 res = StorageImpl_WriteProperty(
2202 This->base.ancestorStorage,
2211 * If a placeholder is required for the other link, then, find one and
2212 * get out of here...
2214 if (needToFindAPlaceholder)
2216 hr = findPlaceholder(
2227 /******************************************************************************
2228 * SetElementTimes (IStorage)
2230 HRESULT WINAPI StorageImpl_SetElementTimes(
2232 const OLECHAR *pwcsName,/* [string][in] */
2233 const FILETIME *pctime, /* [in] */
2234 const FILETIME *patime, /* [in] */
2235 const FILETIME *pmtime) /* [in] */
2237 FIXME("(%s,...), stub!\n",debugstr_w(pwcsName));
2241 /******************************************************************************
2242 * SetStateBits (IStorage)
2244 HRESULT WINAPI StorageImpl_SetStateBits(
2246 DWORD grfStateBits,/* [in] */
2247 DWORD grfMask) /* [in] */
2249 FIXME("not implemented!\n");
2254 * Virtual function table for the IStorage32Impl class.
2256 static const IStorageVtbl Storage32Impl_Vtbl =
2258 StorageBaseImpl_QueryInterface,
2259 StorageBaseImpl_AddRef,
2260 StorageBaseImpl_Release,
2261 StorageBaseImpl_CreateStream,
2262 StorageBaseImpl_OpenStream,
2263 StorageImpl_CreateStorage,
2264 StorageBaseImpl_OpenStorage,
2266 StorageImpl_MoveElementTo,
2269 StorageBaseImpl_EnumElements,
2270 StorageImpl_DestroyElement,
2271 StorageBaseImpl_RenameElement,
2272 StorageImpl_SetElementTimes,
2273 StorageBaseImpl_SetClass,
2274 StorageImpl_SetStateBits,
2278 HRESULT StorageImpl_Construct(
2288 StgProperty currentProperty;
2289 BOOL readSuccessful;
2290 ULONG currentPropertyIndex;
2292 if ( FAILED( validateSTGM(openFlags) ))
2293 return STG_E_INVALIDFLAG;
2295 memset(This, 0, sizeof(StorageImpl));
2298 * Initialize stream list
2301 list_init(&This->base.strmHead);
2304 * Initialize the virtual function table.
2306 This->base.lpVtbl = &Storage32Impl_Vtbl;
2307 This->base.pssVtbl = &IPropertySetStorage_Vtbl;
2308 This->base.v_destructor = &StorageImpl_Destroy;
2309 This->base.openFlags = openFlags;
2312 * This is the top-level storage so initialize the ancestor pointer
2315 This->base.ancestorStorage = This;
2318 * Initialize the physical support of the storage.
2320 This->hFile = hFile;
2323 * Store copy of file path.
2326 This->pwcsName = HeapAlloc(GetProcessHeap(), 0,
2327 (lstrlenW(pwcsName)+1)*sizeof(WCHAR));
2328 if (!This->pwcsName)
2329 return STG_E_INSUFFICIENTMEMORY;
2330 strcpyW(This->pwcsName, pwcsName);
2334 * Initialize the big block cache.
2336 This->bigBlockSize = DEF_BIG_BLOCK_SIZE;
2337 This->smallBlockSize = DEF_SMALL_BLOCK_SIZE;
2338 This->bigBlockFile = BIGBLOCKFILE_Construct(hFile,
2344 if (This->bigBlockFile == 0)
2349 ULARGE_INTEGER size;
2350 BYTE* bigBlockBuffer;
2353 * Initialize all header variables:
2354 * - The big block depot consists of one block and it is at block 0
2355 * - The properties start at block 1
2356 * - There is no small block depot
2358 memset( This->bigBlockDepotStart,
2360 sizeof(This->bigBlockDepotStart));
2362 This->bigBlockDepotCount = 1;
2363 This->bigBlockDepotStart[0] = 0;
2364 This->rootStartBlock = 1;
2365 This->smallBlockDepotStart = BLOCK_END_OF_CHAIN;
2366 This->bigBlockSizeBits = DEF_BIG_BLOCK_SIZE_BITS;
2367 This->smallBlockSizeBits = DEF_SMALL_BLOCK_SIZE_BITS;
2368 This->extBigBlockDepotStart = BLOCK_END_OF_CHAIN;
2369 This->extBigBlockDepotCount = 0;
2371 StorageImpl_SaveFileHeader(This);
2374 * Add one block for the big block depot and one block for the properties
2376 size.u.HighPart = 0;
2377 size.u.LowPart = This->bigBlockSize * 3;
2378 BIGBLOCKFILE_SetSize(This->bigBlockFile, size);
2381 * Initialize the big block depot
2383 bigBlockBuffer = StorageImpl_GetBigBlock(This, 0);
2384 memset(bigBlockBuffer, BLOCK_UNUSED, This->bigBlockSize);
2385 StorageUtl_WriteDWord(bigBlockBuffer, 0, BLOCK_SPECIAL);
2386 StorageUtl_WriteDWord(bigBlockBuffer, sizeof(ULONG), BLOCK_END_OF_CHAIN);
2387 StorageImpl_ReleaseBigBlock(This, bigBlockBuffer);
2392 * Load the header for the file.
2394 hr = StorageImpl_LoadFileHeader(This);
2398 BIGBLOCKFILE_Destructor(This->bigBlockFile);
2405 * There is no block depot cached yet.
2407 This->indexBlockDepotCached = 0xFFFFFFFF;
2410 * Start searching for free blocks with block 0.
2412 This->prevFreeBlock = 0;
2415 * Create the block chain abstractions.
2417 if(!(This->rootBlockChain =
2418 BlockChainStream_Construct(This, &This->rootStartBlock, PROPERTY_NULL)))
2419 return STG_E_READFAULT;
2421 if(!(This->smallBlockDepotChain =
2422 BlockChainStream_Construct(This, &This->smallBlockDepotStart,
2424 return STG_E_READFAULT;
2427 * Write the root property
2431 StgProperty rootProp;
2433 * Initialize the property chain
2435 memset(&rootProp, 0, sizeof(rootProp));
2436 MultiByteToWideChar( CP_ACP, 0, rootPropertyName, -1, rootProp.name,
2437 sizeof(rootProp.name)/sizeof(WCHAR) );
2438 rootProp.sizeOfNameString = (strlenW(rootProp.name)+1) * sizeof(WCHAR);
2439 rootProp.propertyType = PROPTYPE_ROOT;
2440 rootProp.previousProperty = PROPERTY_NULL;
2441 rootProp.nextProperty = PROPERTY_NULL;
2442 rootProp.dirProperty = PROPERTY_NULL;
2443 rootProp.startingBlock = BLOCK_END_OF_CHAIN;
2444 rootProp.size.u.HighPart = 0;
2445 rootProp.size.u.LowPart = 0;
2447 StorageImpl_WriteProperty(This, 0, &rootProp);
2451 * Find the ID of the root in the property sets.
2453 currentPropertyIndex = 0;
2457 readSuccessful = StorageImpl_ReadProperty(
2459 currentPropertyIndex,
2464 if ( (currentProperty.sizeOfNameString != 0 ) &&
2465 (currentProperty.propertyType == PROPTYPE_ROOT) )
2467 This->base.rootPropertySetIndex = currentPropertyIndex;
2471 currentPropertyIndex++;
2473 } while (readSuccessful && (This->base.rootPropertySetIndex == PROPERTY_NULL) );
2475 if (!readSuccessful)
2478 return STG_E_READFAULT;
2482 * Create the block chain abstraction for the small block root chain.
2484 if(!(This->smallBlockRootChain =
2485 BlockChainStream_Construct(This, NULL, This->base.rootPropertySetIndex)))
2486 return STG_E_READFAULT;
2491 void StorageImpl_Destroy(StorageBaseImpl* iface)
2493 StorageImpl *This = (StorageImpl*) iface;
2494 TRACE("(%p)\n", This);
2496 StorageBaseImpl_DeleteAll(&This->base);
2498 HeapFree(GetProcessHeap(), 0, This->pwcsName);
2500 BlockChainStream_Destroy(This->smallBlockRootChain);
2501 BlockChainStream_Destroy(This->rootBlockChain);
2502 BlockChainStream_Destroy(This->smallBlockDepotChain);
2504 BIGBLOCKFILE_Destructor(This->bigBlockFile);
2505 HeapFree(GetProcessHeap(), 0, This);
2508 /******************************************************************************
2509 * Storage32Impl_GetNextFreeBigBlock
2511 * Returns the index of the next free big block.
2512 * If the big block depot is filled, this method will enlarge it.
2515 ULONG StorageImpl_GetNextFreeBigBlock(
2518 ULONG depotBlockIndexPos;
2520 ULONG depotBlockOffset;
2521 ULONG blocksPerDepot = This->bigBlockSize / sizeof(ULONG);
2522 ULONG nextBlockIndex = BLOCK_SPECIAL;
2524 ULONG freeBlock = BLOCK_UNUSED;
2526 depotIndex = This->prevFreeBlock / blocksPerDepot;
2527 depotBlockOffset = (This->prevFreeBlock % blocksPerDepot) * sizeof(ULONG);
2530 * Scan the entire big block depot until we find a block marked free
2532 while (nextBlockIndex != BLOCK_UNUSED)
2534 if (depotIndex < COUNT_BBDEPOTINHEADER)
2536 depotBlockIndexPos = This->bigBlockDepotStart[depotIndex];
2539 * Grow the primary depot.
2541 if (depotBlockIndexPos == BLOCK_UNUSED)
2543 depotBlockIndexPos = depotIndex*blocksPerDepot;
2546 * Add a block depot.
2548 Storage32Impl_AddBlockDepot(This, depotBlockIndexPos);
2549 This->bigBlockDepotCount++;
2550 This->bigBlockDepotStart[depotIndex] = depotBlockIndexPos;
2553 * Flag it as a block depot.
2555 StorageImpl_SetNextBlockInChain(This,
2559 /* Save new header information.
2561 StorageImpl_SaveFileHeader(This);
2566 depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotIndex);
2568 if (depotBlockIndexPos == BLOCK_UNUSED)
2571 * Grow the extended depot.
2573 ULONG extIndex = BLOCK_UNUSED;
2574 ULONG numExtBlocks = depotIndex - COUNT_BBDEPOTINHEADER;
2575 ULONG extBlockOffset = numExtBlocks % (blocksPerDepot - 1);
2577 if (extBlockOffset == 0)
2579 /* We need an extended block.
2581 extIndex = Storage32Impl_AddExtBlockDepot(This);
2582 This->extBigBlockDepotCount++;
2583 depotBlockIndexPos = extIndex + 1;
2586 depotBlockIndexPos = depotIndex * blocksPerDepot;
2589 * Add a block depot and mark it in the extended block.
2591 Storage32Impl_AddBlockDepot(This, depotBlockIndexPos);
2592 This->bigBlockDepotCount++;
2593 Storage32Impl_SetExtDepotBlock(This, depotIndex, depotBlockIndexPos);
2595 /* Flag the block depot.
2597 StorageImpl_SetNextBlockInChain(This,
2601 /* If necessary, flag the extended depot block.
2603 if (extIndex != BLOCK_UNUSED)
2604 StorageImpl_SetNextBlockInChain(This, extIndex, BLOCK_EXTBBDEPOT);
2606 /* Save header information.
2608 StorageImpl_SaveFileHeader(This);
2612 depotBuffer = StorageImpl_GetROBigBlock(This, depotBlockIndexPos);
2614 if (depotBuffer != 0)
2616 while ( ( (depotBlockOffset/sizeof(ULONG) ) < blocksPerDepot) &&
2617 ( nextBlockIndex != BLOCK_UNUSED))
2619 StorageUtl_ReadDWord(depotBuffer, depotBlockOffset, &nextBlockIndex);
2621 if (nextBlockIndex == BLOCK_UNUSED)
2623 freeBlock = (depotIndex * blocksPerDepot) +
2624 (depotBlockOffset/sizeof(ULONG));
2627 depotBlockOffset += sizeof(ULONG);
2630 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2634 depotBlockOffset = 0;
2637 This->prevFreeBlock = freeBlock;
2642 /******************************************************************************
2643 * Storage32Impl_AddBlockDepot
2645 * This will create a depot block, essentially it is a block initialized
2648 void Storage32Impl_AddBlockDepot(StorageImpl* This, ULONG blockIndex)
2652 blockBuffer = StorageImpl_GetBigBlock(This, blockIndex);
2655 * Initialize blocks as free
2657 memset(blockBuffer, BLOCK_UNUSED, This->bigBlockSize);
2659 StorageImpl_ReleaseBigBlock(This, blockBuffer);
2662 /******************************************************************************
2663 * Storage32Impl_GetExtDepotBlock
2665 * Returns the index of the block that corresponds to the specified depot
2666 * index. This method is only for depot indexes equal or greater than
2667 * COUNT_BBDEPOTINHEADER.
2669 ULONG Storage32Impl_GetExtDepotBlock(StorageImpl* This, ULONG depotIndex)
2671 ULONG depotBlocksPerExtBlock = (This->bigBlockSize / sizeof(ULONG)) - 1;
2672 ULONG numExtBlocks = depotIndex - COUNT_BBDEPOTINHEADER;
2673 ULONG extBlockCount = numExtBlocks / depotBlocksPerExtBlock;
2674 ULONG extBlockOffset = numExtBlocks % depotBlocksPerExtBlock;
2675 ULONG blockIndex = BLOCK_UNUSED;
2676 ULONG extBlockIndex = This->extBigBlockDepotStart;
2678 assert(depotIndex >= COUNT_BBDEPOTINHEADER);
2680 if (This->extBigBlockDepotStart == BLOCK_END_OF_CHAIN)
2681 return BLOCK_UNUSED;
2683 while (extBlockCount > 0)
2685 extBlockIndex = Storage32Impl_GetNextExtendedBlock(This, extBlockIndex);
2689 if (extBlockIndex != BLOCK_UNUSED)
2693 depotBuffer = StorageImpl_GetROBigBlock(This, extBlockIndex);
2695 if (depotBuffer != 0)
2697 StorageUtl_ReadDWord(depotBuffer,
2698 extBlockOffset * sizeof(ULONG),
2701 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2708 /******************************************************************************
2709 * Storage32Impl_SetExtDepotBlock
2711 * Associates the specified block index to the specified depot index.
2712 * This method is only for depot indexes equal or greater than
2713 * COUNT_BBDEPOTINHEADER.
2715 void Storage32Impl_SetExtDepotBlock(StorageImpl* This,
2719 ULONG depotBlocksPerExtBlock = (This->bigBlockSize / sizeof(ULONG)) - 1;
2720 ULONG numExtBlocks = depotIndex - COUNT_BBDEPOTINHEADER;
2721 ULONG extBlockCount = numExtBlocks / depotBlocksPerExtBlock;
2722 ULONG extBlockOffset = numExtBlocks % depotBlocksPerExtBlock;
2723 ULONG extBlockIndex = This->extBigBlockDepotStart;
2725 assert(depotIndex >= COUNT_BBDEPOTINHEADER);
2727 while (extBlockCount > 0)
2729 extBlockIndex = Storage32Impl_GetNextExtendedBlock(This, extBlockIndex);
2733 if (extBlockIndex != BLOCK_UNUSED)
2737 depotBuffer = StorageImpl_GetBigBlock(This, extBlockIndex);
2739 if (depotBuffer != 0)
2741 StorageUtl_WriteDWord(depotBuffer,
2742 extBlockOffset * sizeof(ULONG),
2745 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2750 /******************************************************************************
2751 * Storage32Impl_AddExtBlockDepot
2753 * Creates an extended depot block.
2755 ULONG Storage32Impl_AddExtBlockDepot(StorageImpl* This)
2757 ULONG numExtBlocks = This->extBigBlockDepotCount;
2758 ULONG nextExtBlock = This->extBigBlockDepotStart;
2759 BYTE* depotBuffer = NULL;
2760 ULONG index = BLOCK_UNUSED;
2761 ULONG nextBlockOffset = This->bigBlockSize - sizeof(ULONG);
2762 ULONG blocksPerDepotBlock = This->bigBlockSize / sizeof(ULONG);
2763 ULONG depotBlocksPerExtBlock = blocksPerDepotBlock - 1;
2765 index = (COUNT_BBDEPOTINHEADER + (numExtBlocks * depotBlocksPerExtBlock)) *
2766 blocksPerDepotBlock;
2768 if ((numExtBlocks == 0) && (nextExtBlock == BLOCK_END_OF_CHAIN))
2771 * The first extended block.
2773 This->extBigBlockDepotStart = index;
2779 * Follow the chain to the last one.
2781 for (i = 0; i < (numExtBlocks - 1); i++)
2783 nextExtBlock = Storage32Impl_GetNextExtendedBlock(This, nextExtBlock);
2787 * Add the new extended block to the chain.
2789 depotBuffer = StorageImpl_GetBigBlock(This, nextExtBlock);
2790 StorageUtl_WriteDWord(depotBuffer, nextBlockOffset, index);
2791 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2795 * Initialize this block.
2797 depotBuffer = StorageImpl_GetBigBlock(This, index);
2798 memset(depotBuffer, BLOCK_UNUSED, This->bigBlockSize);
2799 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2804 /******************************************************************************
2805 * Storage32Impl_FreeBigBlock
2807 * This method will flag the specified block as free in the big block depot.
2809 void StorageImpl_FreeBigBlock(
2813 StorageImpl_SetNextBlockInChain(This, blockIndex, BLOCK_UNUSED);
2815 if (blockIndex < This->prevFreeBlock)
2816 This->prevFreeBlock = blockIndex;
2819 /************************************************************************
2820 * Storage32Impl_GetNextBlockInChain
2822 * This method will retrieve the block index of the next big block in
2825 * Params: This - Pointer to the Storage object.
2826 * blockIndex - Index of the block to retrieve the chain
2828 * nextBlockIndex - receives the return value.
2830 * Returns: This method returns the index of the next block in the chain.
2831 * It will return the constants:
2832 * BLOCK_SPECIAL - If the block given was not part of a
2834 * BLOCK_END_OF_CHAIN - If the block given was the last in
2836 * BLOCK_UNUSED - If the block given was not past of a chain
2838 * BLOCK_EXTBBDEPOT - This block is part of the extended
2841 * See Windows documentation for more details on IStorage methods.
2843 HRESULT StorageImpl_GetNextBlockInChain(
2846 ULONG* nextBlockIndex)
2848 ULONG offsetInDepot = blockIndex * sizeof (ULONG);
2849 ULONG depotBlockCount = offsetInDepot / This->bigBlockSize;
2850 ULONG depotBlockOffset = offsetInDepot % This->bigBlockSize;
2852 ULONG depotBlockIndexPos;
2855 *nextBlockIndex = BLOCK_SPECIAL;
2857 if(depotBlockCount >= This->bigBlockDepotCount)
2859 WARN("depotBlockCount %ld, bigBlockDepotCount %ld\n", depotBlockCount,
2860 This->bigBlockDepotCount);
2861 return STG_E_READFAULT;
2865 * Cache the currently accessed depot block.
2867 if (depotBlockCount != This->indexBlockDepotCached)
2869 This->indexBlockDepotCached = depotBlockCount;
2871 if (depotBlockCount < COUNT_BBDEPOTINHEADER)
2873 depotBlockIndexPos = This->bigBlockDepotStart[depotBlockCount];
2878 * We have to look in the extended depot.
2880 depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotBlockCount);
2883 depotBuffer = StorageImpl_GetROBigBlock(This, depotBlockIndexPos);
2886 return STG_E_READFAULT;
2888 for (index = 0; index < NUM_BLOCKS_PER_DEPOT_BLOCK; index++)
2890 StorageUtl_ReadDWord(depotBuffer, index*sizeof(ULONG), nextBlockIndex);
2891 This->blockDepotCached[index] = *nextBlockIndex;
2893 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2896 *nextBlockIndex = This->blockDepotCached[depotBlockOffset/sizeof(ULONG)];
2901 /******************************************************************************
2902 * Storage32Impl_GetNextExtendedBlock
2904 * Given an extended block this method will return the next extended block.
2907 * The last ULONG of an extended block is the block index of the next
2908 * extended block. Extended blocks are marked as BLOCK_EXTBBDEPOT in the
2912 * - The index of the next extended block
2913 * - BLOCK_UNUSED: there is no next extended block.
2914 * - Any other return values denotes failure.
2916 ULONG Storage32Impl_GetNextExtendedBlock(StorageImpl* This, ULONG blockIndex)
2918 ULONG nextBlockIndex = BLOCK_SPECIAL;
2919 ULONG depotBlockOffset = This->bigBlockSize - sizeof(ULONG);
2922 depotBuffer = StorageImpl_GetROBigBlock(This, blockIndex);
2926 StorageUtl_ReadDWord(depotBuffer, depotBlockOffset, &nextBlockIndex);
2928 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2931 return nextBlockIndex;
2934 /******************************************************************************
2935 * Storage32Impl_SetNextBlockInChain
2937 * This method will write the index of the specified block's next block
2938 * in the big block depot.
2940 * For example: to create the chain 3 -> 1 -> 7 -> End of Chain
2943 * Storage32Impl_SetNextBlockInChain(This, 3, 1);
2944 * Storage32Impl_SetNextBlockInChain(This, 1, 7);
2945 * Storage32Impl_SetNextBlockInChain(This, 7, BLOCK_END_OF_CHAIN);
2948 void StorageImpl_SetNextBlockInChain(
2953 ULONG offsetInDepot = blockIndex * sizeof (ULONG);
2954 ULONG depotBlockCount = offsetInDepot / This->bigBlockSize;
2955 ULONG depotBlockOffset = offsetInDepot % This->bigBlockSize;
2956 ULONG depotBlockIndexPos;
2959 assert(depotBlockCount < This->bigBlockDepotCount);
2960 assert(blockIndex != nextBlock);
2962 if (depotBlockCount < COUNT_BBDEPOTINHEADER)
2964 depotBlockIndexPos = This->bigBlockDepotStart[depotBlockCount];
2969 * We have to look in the extended depot.
2971 depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotBlockCount);
2974 depotBuffer = StorageImpl_GetBigBlock(This, depotBlockIndexPos);
2978 StorageUtl_WriteDWord(depotBuffer, depotBlockOffset, nextBlock);
2979 StorageImpl_ReleaseBigBlock(This, depotBuffer);
2983 * Update the cached block depot, if necessary.
2985 if (depotBlockCount == This->indexBlockDepotCached)
2987 This->blockDepotCached[depotBlockOffset/sizeof(ULONG)] = nextBlock;
2991 /******************************************************************************
2992 * Storage32Impl_LoadFileHeader
2994 * This method will read in the file header, i.e. big block index -1.
2996 HRESULT StorageImpl_LoadFileHeader(
2999 HRESULT hr = STG_E_FILENOTFOUND;
3000 void* headerBigBlock = NULL;
3004 * Get a pointer to the big block of data containing the header.
3006 headerBigBlock = StorageImpl_GetROBigBlock(This, -1);
3009 * Extract the information from the header.
3011 if (headerBigBlock!=0)
3014 * Check for the "magic number" signature and return an error if it is not
3017 if (memcmp(headerBigBlock, STORAGE_oldmagic, sizeof(STORAGE_oldmagic))==0)
3019 StorageImpl_ReleaseBigBlock(This, headerBigBlock);
3020 return STG_E_OLDFORMAT;
3023 if (memcmp(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic))!=0)
3025 StorageImpl_ReleaseBigBlock(This, headerBigBlock);
3026 return STG_E_INVALIDHEADER;
3029 StorageUtl_ReadWord(
3031 OFFSET_BIGBLOCKSIZEBITS,
3032 &This->bigBlockSizeBits);
3034 StorageUtl_ReadWord(
3036 OFFSET_SMALLBLOCKSIZEBITS,
3037 &This->smallBlockSizeBits);
3039 StorageUtl_ReadDWord(
3041 OFFSET_BBDEPOTCOUNT,
3042 &This->bigBlockDepotCount);
3044 StorageUtl_ReadDWord(
3046 OFFSET_ROOTSTARTBLOCK,
3047 &This->rootStartBlock);
3049 StorageUtl_ReadDWord(
3051 OFFSET_SBDEPOTSTART,
3052 &This->smallBlockDepotStart);
3054 StorageUtl_ReadDWord(
3056 OFFSET_EXTBBDEPOTSTART,
3057 &This->extBigBlockDepotStart);
3059 StorageUtl_ReadDWord(
3061 OFFSET_EXTBBDEPOTCOUNT,
3062 &This->extBigBlockDepotCount);
3064 for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
3066 StorageUtl_ReadDWord(
3068 OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
3069 &(This->bigBlockDepotStart[index]));
3073 * Make the bitwise arithmetic to get the size of the blocks in bytes.
3077 This->bigBlockSize = 0x000000001 << (DWORD)This->bigBlockSizeBits;
3078 This->smallBlockSize = 0x000000001 << (DWORD)This->smallBlockSizeBits;
3082 This->bigBlockSize = 0x000000001 >> (DWORD)This->bigBlockSizeBits;
3083 This->smallBlockSize = 0x000000001 >> (DWORD)This->smallBlockSizeBits;
3087 * Right now, the code is making some assumptions about the size of the
3088 * blocks, just make sure they are what we're expecting.
3090 if (This->bigBlockSize != DEF_BIG_BLOCK_SIZE ||
3091 This->smallBlockSize != DEF_SMALL_BLOCK_SIZE)
3093 WARN("Broken OLE storage file\n");
3094 hr = STG_E_INVALIDHEADER;
3100 * Release the block.
3102 StorageImpl_ReleaseBigBlock(This, headerBigBlock);
3108 /******************************************************************************
3109 * Storage32Impl_SaveFileHeader
3111 * This method will save to the file the header, i.e. big block -1.
3113 void StorageImpl_SaveFileHeader(
3116 BYTE headerBigBlock[BIG_BLOCK_SIZE];
3121 * Get a pointer to the big block of data containing the header.
3123 success = StorageImpl_ReadBigBlock(This, -1, headerBigBlock);
3126 * If the block read failed, the file is probably new.
3131 * Initialize for all unknown fields.
3133 memset(headerBigBlock, 0, BIG_BLOCK_SIZE);
3136 * Initialize the magic number.
3138 memcpy(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic));
3141 * And a bunch of things we don't know what they mean
3143 StorageUtl_WriteWord(headerBigBlock, 0x18, 0x3b);
3144 StorageUtl_WriteWord(headerBigBlock, 0x1a, 0x3);
3145 StorageUtl_WriteWord(headerBigBlock, 0x1c, (WORD)-2);
3146 StorageUtl_WriteDWord(headerBigBlock, 0x38, (DWORD)0x1000);
3150 * Write the information to the header.
3152 StorageUtl_WriteWord(
3154 OFFSET_BIGBLOCKSIZEBITS,
3155 This->bigBlockSizeBits);
3157 StorageUtl_WriteWord(
3159 OFFSET_SMALLBLOCKSIZEBITS,
3160 This->smallBlockSizeBits);
3162 StorageUtl_WriteDWord(
3164 OFFSET_BBDEPOTCOUNT,
3165 This->bigBlockDepotCount);
3167 StorageUtl_WriteDWord(
3169 OFFSET_ROOTSTARTBLOCK,
3170 This->rootStartBlock);
3172 StorageUtl_WriteDWord(
3174 OFFSET_SBDEPOTSTART,
3175 This->smallBlockDepotStart);
3177 StorageUtl_WriteDWord(
3179 OFFSET_SBDEPOTCOUNT,
3180 This->smallBlockDepotChain ?
3181 BlockChainStream_GetCount(This->smallBlockDepotChain) : 0);
3183 StorageUtl_WriteDWord(
3185 OFFSET_EXTBBDEPOTSTART,
3186 This->extBigBlockDepotStart);
3188 StorageUtl_WriteDWord(
3190 OFFSET_EXTBBDEPOTCOUNT,
3191 This->extBigBlockDepotCount);
3193 for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
3195 StorageUtl_WriteDWord(
3197 OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
3198 (This->bigBlockDepotStart[index]));
3202 * Write the big block back to the file.
3204 StorageImpl_WriteBigBlock(This, -1, headerBigBlock);
3207 /******************************************************************************
3208 * Storage32Impl_ReadProperty
3210 * This method will read the specified property from the property chain.
3212 BOOL StorageImpl_ReadProperty(
3215 StgProperty* buffer)
3217 BYTE currentProperty[PROPSET_BLOCK_SIZE];
3218 ULARGE_INTEGER offsetInPropSet;
3219 BOOL readSuccessful;
3222 offsetInPropSet.u.HighPart = 0;
3223 offsetInPropSet.u.LowPart = index * PROPSET_BLOCK_SIZE;
3225 readSuccessful = BlockChainStream_ReadAt(
3226 This->rootBlockChain,
3234 /* replace the name of root entry (often "Root Entry") by the file name */
3235 WCHAR *propName = (index == This->base.rootPropertySetIndex) ?
3236 This->filename : (WCHAR *)currentProperty+OFFSET_PS_NAME;
3238 memset(buffer->name, 0, sizeof(buffer->name));
3242 PROPERTY_NAME_BUFFER_LEN );
3243 TRACE("storage name: %s\n", debugstr_w(buffer->name));
3245 memcpy(&buffer->propertyType, currentProperty + OFFSET_PS_PROPERTYTYPE, 1);
3247 StorageUtl_ReadWord(
3249 OFFSET_PS_NAMELENGTH,
3250 &buffer->sizeOfNameString);
3252 StorageUtl_ReadDWord(
3254 OFFSET_PS_PREVIOUSPROP,
3255 &buffer->previousProperty);
3257 StorageUtl_ReadDWord(
3260 &buffer->nextProperty);
3262 StorageUtl_ReadDWord(
3265 &buffer->dirProperty);
3267 StorageUtl_ReadGUID(
3270 &buffer->propertyUniqueID);
3272 StorageUtl_ReadDWord(
3275 &buffer->timeStampS1);
3277 StorageUtl_ReadDWord(
3280 &buffer->timeStampD1);
3282 StorageUtl_ReadDWord(
3285 &buffer->timeStampS2);
3287 StorageUtl_ReadDWord(
3290 &buffer->timeStampD2);
3292 StorageUtl_ReadDWord(
3294 OFFSET_PS_STARTBLOCK,
3295 &buffer->startingBlock);
3297 StorageUtl_ReadDWord(
3300 &buffer->size.u.LowPart);
3302 buffer->size.u.HighPart = 0;
3305 return readSuccessful;
3308 /*********************************************************************
3309 * Write the specified property into the property chain
3311 BOOL StorageImpl_WriteProperty(
3314 StgProperty* buffer)
3316 BYTE currentProperty[PROPSET_BLOCK_SIZE];
3317 ULARGE_INTEGER offsetInPropSet;
3318 BOOL writeSuccessful;
3321 offsetInPropSet.u.HighPart = 0;
3322 offsetInPropSet.u.LowPart = index * PROPSET_BLOCK_SIZE;
3324 memset(currentProperty, 0, PROPSET_BLOCK_SIZE);
3327 currentProperty + OFFSET_PS_NAME,
3329 PROPERTY_NAME_BUFFER_LEN );
3331 memcpy(currentProperty + OFFSET_PS_PROPERTYTYPE, &buffer->propertyType, 1);
3333 StorageUtl_WriteWord(
3335 OFFSET_PS_NAMELENGTH,
3336 buffer->sizeOfNameString);
3338 StorageUtl_WriteDWord(
3340 OFFSET_PS_PREVIOUSPROP,
3341 buffer->previousProperty);
3343 StorageUtl_WriteDWord(
3346 buffer->nextProperty);
3348 StorageUtl_WriteDWord(
3351 buffer->dirProperty);
3353 StorageUtl_WriteGUID(
3356 &buffer->propertyUniqueID);
3358 StorageUtl_WriteDWord(
3361 buffer->timeStampS1);
3363 StorageUtl_WriteDWord(
3366 buffer->timeStampD1);
3368 StorageUtl_WriteDWord(
3371 buffer->timeStampS2);
3373 StorageUtl_WriteDWord(
3376 buffer->timeStampD2);
3378 StorageUtl_WriteDWord(
3380 OFFSET_PS_STARTBLOCK,
3381 buffer->startingBlock);
3383 StorageUtl_WriteDWord(
3386 buffer->size.u.LowPart);
3388 writeSuccessful = BlockChainStream_WriteAt(This->rootBlockChain,
3393 return writeSuccessful;
3396 BOOL StorageImpl_ReadBigBlock(
3401 void* bigBlockBuffer;
3403 bigBlockBuffer = StorageImpl_GetROBigBlock(This, blockIndex);
3405 if (bigBlockBuffer!=0)
3407 memcpy(buffer, bigBlockBuffer, This->bigBlockSize);
3409 StorageImpl_ReleaseBigBlock(This, bigBlockBuffer);
3417 BOOL StorageImpl_WriteBigBlock(
3422 void* bigBlockBuffer;
3424 bigBlockBuffer = StorageImpl_GetBigBlock(This, blockIndex);
3426 if (bigBlockBuffer!=0)
3428 memcpy(bigBlockBuffer, buffer, This->bigBlockSize);
3430 StorageImpl_ReleaseBigBlock(This, bigBlockBuffer);
3438 void* StorageImpl_GetROBigBlock(
3442 return BIGBLOCKFILE_GetROBigBlock(This->bigBlockFile, blockIndex);
3445 void* StorageImpl_GetBigBlock(
3449 return BIGBLOCKFILE_GetBigBlock(This->bigBlockFile, blockIndex);
3452 void StorageImpl_ReleaseBigBlock(
3456 BIGBLOCKFILE_ReleaseBigBlock(This->bigBlockFile, pBigBlock);
3459 /******************************************************************************
3460 * Storage32Impl_SmallBlocksToBigBlocks
3462 * This method will convert a small block chain to a big block chain.
3463 * The small block chain will be destroyed.
3465 BlockChainStream* Storage32Impl_SmallBlocksToBigBlocks(
3467 SmallBlockChainStream** ppsbChain)
3469 ULONG bbHeadOfChain = BLOCK_END_OF_CHAIN;
3470 ULARGE_INTEGER size, offset;
3471 ULONG cbRead, cbWritten, cbTotalRead, cbTotalWritten;
3472 ULONG propertyIndex;
3474 HRESULT successRead;
3475 StgProperty chainProperty;
3477 BlockChainStream *bbTempChain = NULL;
3478 BlockChainStream *bigBlockChain = NULL;
3481 * Create a temporary big block chain that doesn't have
3482 * an associated property. This temporary chain will be
3483 * used to copy data from small blocks to big blocks.
3485 bbTempChain = BlockChainStream_Construct(This,
3488 if(!bbTempChain) return NULL;
3490 * Grow the big block chain.
3492 size = SmallBlockChainStream_GetSize(*ppsbChain);
3493 BlockChainStream_SetSize(bbTempChain, size);
3496 * Copy the contents of the small block chain to the big block chain
3497 * by small block size increments.
3499 offset.u.LowPart = 0;
3500 offset.u.HighPart = 0;
3504 buffer = HeapAlloc(GetProcessHeap(),0,DEF_SMALL_BLOCK_SIZE);
3507 successRead = SmallBlockChainStream_ReadAt(*ppsbChain,
3509 DEF_SMALL_BLOCK_SIZE,
3512 if (FAILED(successRead))
3517 cbTotalRead += cbRead;
3519 successWrite = BlockChainStream_WriteAt(bbTempChain,
3528 cbTotalWritten += cbWritten;
3529 offset.u.LowPart += This->smallBlockSize;
3531 } while (cbRead > 0);
3532 HeapFree(GetProcessHeap(),0,buffer);
3534 assert(cbTotalRead == cbTotalWritten);
3537 * Destroy the small block chain.
3539 propertyIndex = (*ppsbChain)->ownerPropertyIndex;
3540 size.u.HighPart = 0;
3542 SmallBlockChainStream_SetSize(*ppsbChain, size);
3543 SmallBlockChainStream_Destroy(*ppsbChain);
3547 * Change the property information. This chain is now a big block chain
3548 * and it doesn't reside in the small blocks chain anymore.
3550 StorageImpl_ReadProperty(This, propertyIndex, &chainProperty);
3552 chainProperty.startingBlock = bbHeadOfChain;
3554 StorageImpl_WriteProperty(This, propertyIndex, &chainProperty);
3557 * Destroy the temporary propertyless big block chain.
3558 * Create a new big block chain associated with this property.
3560 BlockChainStream_Destroy(bbTempChain);
3561 bigBlockChain = BlockChainStream_Construct(This,
3565 return bigBlockChain;
3568 void StorageInternalImpl_Destroy( StorageBaseImpl *iface)
3570 StorageInternalImpl* This = (StorageInternalImpl*) iface;
3572 StorageBaseImpl_Release((IStorage*)This->base.ancestorStorage);
3573 HeapFree(GetProcessHeap(), 0, This);
3576 /******************************************************************************
3578 ** Storage32InternalImpl_Commit
3580 ** The non-root storages cannot be opened in transacted mode thus this function
3583 HRESULT WINAPI StorageInternalImpl_Commit(
3585 DWORD grfCommitFlags) /* [in] */
3590 /******************************************************************************
3592 ** Storage32InternalImpl_Revert
3594 ** The non-root storages cannot be opened in transacted mode thus this function
3597 HRESULT WINAPI StorageInternalImpl_Revert(
3603 void IEnumSTATSTGImpl_Destroy(IEnumSTATSTGImpl* This)
3605 IStorage_Release((IStorage*)This->parentStorage);
3606 HeapFree(GetProcessHeap(), 0, This->stackToVisit);
3607 HeapFree(GetProcessHeap(), 0, This);
3610 HRESULT WINAPI IEnumSTATSTGImpl_QueryInterface(
3611 IEnumSTATSTG* iface,
3615 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3618 * Perform a sanity check on the parameters.
3621 return E_INVALIDARG;
3624 * Initialize the return parameter.
3629 * Compare the riid with the interface IDs implemented by this object.
3631 if (IsEqualGUID(&IID_IUnknown, riid) ||
3632 IsEqualGUID(&IID_IStorage, riid))
3634 *ppvObject = (IEnumSTATSTG*)This;
3635 IEnumSTATSTG_AddRef((IEnumSTATSTG*)This);
3639 return E_NOINTERFACE;
3642 ULONG WINAPI IEnumSTATSTGImpl_AddRef(
3643 IEnumSTATSTG* iface)
3645 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3646 return InterlockedIncrement(&This->ref);
3649 ULONG WINAPI IEnumSTATSTGImpl_Release(
3650 IEnumSTATSTG* iface)
3652 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3656 newRef = InterlockedDecrement(&This->ref);
3659 * If the reference count goes down to 0, perform suicide.
3663 IEnumSTATSTGImpl_Destroy(This);
3669 HRESULT WINAPI IEnumSTATSTGImpl_Next(
3670 IEnumSTATSTG* iface,
3673 ULONG* pceltFetched)
3675 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3677 StgProperty currentProperty;
3678 STATSTG* currentReturnStruct = rgelt;
3679 ULONG objectFetched = 0;
3680 ULONG currentSearchNode;
3683 * Perform a sanity check on the parameters.
3685 if ( (rgelt==0) || ( (celt!=1) && (pceltFetched==0) ) )
3686 return E_INVALIDARG;
3689 * To avoid the special case, get another pointer to a ULONG value if
3690 * the caller didn't supply one.
3692 if (pceltFetched==0)
3693 pceltFetched = &objectFetched;
3696 * Start the iteration, we will iterate until we hit the end of the
3697 * linked list or until we hit the number of items to iterate through
3702 * Start with the node at the top of the stack.
3704 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3706 while ( ( *pceltFetched < celt) &&
3707 ( currentSearchNode!=PROPERTY_NULL) )
3710 * Remove the top node from the stack
3712 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3715 * Read the property from the storage.
3717 StorageImpl_ReadProperty(This->parentStorage,
3722 * Copy the information to the return buffer.
3724 StorageUtl_CopyPropertyToSTATSTG(currentReturnStruct,
3729 * Step to the next item in the iteration
3732 currentReturnStruct++;
3735 * Push the next search node in the search stack.
3737 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty.nextProperty);
3740 * continue the iteration.
3742 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3745 if (*pceltFetched == celt)
3752 HRESULT WINAPI IEnumSTATSTGImpl_Skip(
3753 IEnumSTATSTG* iface,
3756 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3758 StgProperty currentProperty;
3759 ULONG objectFetched = 0;
3760 ULONG currentSearchNode;
3763 * Start with the node at the top of the stack.
3765 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3767 while ( (objectFetched < celt) &&
3768 (currentSearchNode!=PROPERTY_NULL) )
3771 * Remove the top node from the stack
3773 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3776 * Read the property from the storage.
3778 StorageImpl_ReadProperty(This->parentStorage,
3783 * Step to the next item in the iteration
3788 * Push the next search node in the search stack.
3790 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty.nextProperty);
3793 * continue the iteration.
3795 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3798 if (objectFetched == celt)
3804 HRESULT WINAPI IEnumSTATSTGImpl_Reset(
3805 IEnumSTATSTG* iface)
3807 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3809 StgProperty rootProperty;
3810 BOOL readSuccessful;
3813 * Re-initialize the search stack to an empty stack
3815 This->stackSize = 0;
3818 * Read the root property from the storage.
3820 readSuccessful = StorageImpl_ReadProperty(
3821 This->parentStorage,
3822 This->firstPropertyNode,
3827 assert(rootProperty.sizeOfNameString!=0);
3830 * Push the search node in the search stack.
3832 IEnumSTATSTGImpl_PushSearchNode(This, rootProperty.dirProperty);
3838 HRESULT WINAPI IEnumSTATSTGImpl_Clone(
3839 IEnumSTATSTG* iface,
3840 IEnumSTATSTG** ppenum)
3842 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3844 IEnumSTATSTGImpl* newClone;
3847 * Perform a sanity check on the parameters.
3850 return E_INVALIDARG;
3852 newClone = IEnumSTATSTGImpl_Construct(This->parentStorage,
3853 This->firstPropertyNode);
3857 * The new clone enumeration must point to the same current node as
3860 newClone->stackSize = This->stackSize ;
3861 newClone->stackMaxSize = This->stackMaxSize ;
3862 newClone->stackToVisit =
3863 HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG) * newClone->stackMaxSize);
3866 newClone->stackToVisit,
3868 sizeof(ULONG) * newClone->stackSize);
3870 *ppenum = (IEnumSTATSTG*)newClone;
3873 * Don't forget to nail down a reference to the clone before
3876 IEnumSTATSTGImpl_AddRef(*ppenum);
3881 INT IEnumSTATSTGImpl_FindParentProperty(
3882 IEnumSTATSTGImpl *This,
3883 ULONG childProperty,
3884 StgProperty *currentProperty,
3887 ULONG currentSearchNode;
3891 * To avoid the special case, get another pointer to a ULONG value if
3892 * the caller didn't supply one.
3895 thisNodeId = &foundNode;
3898 * Start with the node at the top of the stack.
3900 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3903 while (currentSearchNode!=PROPERTY_NULL)
3906 * Store the current node in the returned parameters
3908 *thisNodeId = currentSearchNode;
3911 * Remove the top node from the stack
3913 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3916 * Read the property from the storage.
3918 StorageImpl_ReadProperty(
3919 This->parentStorage,
3923 if (currentProperty->previousProperty == childProperty)
3924 return PROPERTY_RELATION_PREVIOUS;
3926 else if (currentProperty->nextProperty == childProperty)
3927 return PROPERTY_RELATION_NEXT;
3929 else if (currentProperty->dirProperty == childProperty)
3930 return PROPERTY_RELATION_DIR;
3933 * Push the next search node in the search stack.
3935 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty->nextProperty);
3938 * continue the iteration.
3940 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3943 return PROPERTY_NULL;
3946 ULONG IEnumSTATSTGImpl_FindProperty(
3947 IEnumSTATSTGImpl* This,
3948 const OLECHAR* lpszPropName,
3949 StgProperty* currentProperty)
3951 ULONG currentSearchNode;
3954 * Start with the node at the top of the stack.
3956 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3958 while (currentSearchNode!=PROPERTY_NULL)
3961 * Remove the top node from the stack
3963 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3966 * Read the property from the storage.
3968 StorageImpl_ReadProperty(This->parentStorage,
3972 if ( propertyNameCmp(
3973 (const OLECHAR*)currentProperty->name,
3974 (const OLECHAR*)lpszPropName) == 0)
3975 return currentSearchNode;
3978 * Push the next search node in the search stack.
3980 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty->nextProperty);
3983 * continue the iteration.
3985 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3988 return PROPERTY_NULL;
3991 void IEnumSTATSTGImpl_PushSearchNode(
3992 IEnumSTATSTGImpl* This,
3995 StgProperty rootProperty;
3996 BOOL readSuccessful;
3999 * First, make sure we're not trying to push an unexisting node.
4001 if (nodeToPush==PROPERTY_NULL)
4005 * First push the node to the stack
4007 if (This->stackSize == This->stackMaxSize)
4009 This->stackMaxSize += ENUMSTATSGT_SIZE_INCREMENT;
4011 This->stackToVisit = HeapReAlloc(
4015 sizeof(ULONG) * This->stackMaxSize);
4018 This->stackToVisit[This->stackSize] = nodeToPush;
4022 * Read the root property from the storage.
4024 readSuccessful = StorageImpl_ReadProperty(
4025 This->parentStorage,
4031 assert(rootProperty.sizeOfNameString!=0);
4034 * Push the previous search node in the search stack.
4036 IEnumSTATSTGImpl_PushSearchNode(This, rootProperty.previousProperty);
4040 ULONG IEnumSTATSTGImpl_PopSearchNode(
4041 IEnumSTATSTGImpl* This,
4046 if (This->stackSize == 0)
4047 return PROPERTY_NULL;
4049 topNode = This->stackToVisit[This->stackSize-1];
4058 * Virtual function table for the IEnumSTATSTGImpl class.
4060 static const IEnumSTATSTGVtbl IEnumSTATSTGImpl_Vtbl =
4062 IEnumSTATSTGImpl_QueryInterface,
4063 IEnumSTATSTGImpl_AddRef,
4064 IEnumSTATSTGImpl_Release,
4065 IEnumSTATSTGImpl_Next,
4066 IEnumSTATSTGImpl_Skip,
4067 IEnumSTATSTGImpl_Reset,
4068 IEnumSTATSTGImpl_Clone
4071 /******************************************************************************
4072 ** IEnumSTATSTGImpl implementation
4075 IEnumSTATSTGImpl* IEnumSTATSTGImpl_Construct(
4076 StorageImpl* parentStorage,
4077 ULONG firstPropertyNode)
4079 IEnumSTATSTGImpl* newEnumeration;
4081 newEnumeration = HeapAlloc(GetProcessHeap(), 0, sizeof(IEnumSTATSTGImpl));
4083 if (newEnumeration!=0)
4086 * Set-up the virtual function table and reference count.
4088 newEnumeration->lpVtbl = &IEnumSTATSTGImpl_Vtbl;
4089 newEnumeration->ref = 0;
4092 * We want to nail-down the reference to the storage in case the
4093 * enumeration out-lives the storage in the client application.
4095 newEnumeration->parentStorage = parentStorage;
4096 IStorage_AddRef((IStorage*)newEnumeration->parentStorage);
4098 newEnumeration->firstPropertyNode = firstPropertyNode;
4101 * Initialize the search stack
4103 newEnumeration->stackSize = 0;
4104 newEnumeration->stackMaxSize = ENUMSTATSGT_SIZE_INCREMENT;
4105 newEnumeration->stackToVisit =
4106 HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG)*ENUMSTATSGT_SIZE_INCREMENT);
4109 * Make sure the current node of the iterator is the first one.
4111 IEnumSTATSTGImpl_Reset((IEnumSTATSTG*)newEnumeration);
4114 return newEnumeration;
4118 * Virtual function table for the Storage32InternalImpl class.
4120 static const IStorageVtbl Storage32InternalImpl_Vtbl =
4122 StorageBaseImpl_QueryInterface,
4123 StorageBaseImpl_AddRef,
4124 StorageBaseImpl_Release,
4125 StorageBaseImpl_CreateStream,
4126 StorageBaseImpl_OpenStream,
4127 StorageImpl_CreateStorage,
4128 StorageBaseImpl_OpenStorage,
4130 StorageImpl_MoveElementTo,
4131 StorageInternalImpl_Commit,
4132 StorageInternalImpl_Revert,
4133 StorageBaseImpl_EnumElements,
4134 StorageImpl_DestroyElement,
4135 StorageBaseImpl_RenameElement,
4136 StorageImpl_SetElementTimes,
4137 StorageBaseImpl_SetClass,
4138 StorageImpl_SetStateBits,
4139 StorageBaseImpl_Stat
4142 /******************************************************************************
4143 ** Storage32InternalImpl implementation
4146 StorageInternalImpl* StorageInternalImpl_Construct(
4147 StorageImpl* ancestorStorage,
4149 ULONG rootPropertyIndex)
4151 StorageInternalImpl* newStorage;
4154 * Allocate space for the new storage object
4156 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageInternalImpl));
4160 memset(newStorage, 0, sizeof(StorageInternalImpl));
4163 * Initialize the stream list
4166 list_init(&newStorage->base.strmHead);
4169 * Initialize the virtual function table.
4171 newStorage->base.lpVtbl = &Storage32InternalImpl_Vtbl;
4172 newStorage->base.v_destructor = &StorageInternalImpl_Destroy;
4173 newStorage->base.openFlags = openFlags;
4176 * Keep the ancestor storage pointer and nail a reference to it.
4178 newStorage->base.ancestorStorage = ancestorStorage;
4179 StorageBaseImpl_AddRef((IStorage*)(newStorage->base.ancestorStorage));
4182 * Keep the index of the root property set for this storage,
4184 newStorage->base.rootPropertySetIndex = rootPropertyIndex;
4192 /******************************************************************************
4193 ** StorageUtl implementation
4196 void StorageUtl_ReadWord(const BYTE* buffer, ULONG offset, WORD* value)
4200 memcpy(&tmp, buffer+offset, sizeof(WORD));
4201 *value = le16toh(tmp);
4204 void StorageUtl_WriteWord(BYTE* buffer, ULONG offset, WORD value)
4206 value = htole16(value);
4207 memcpy(buffer+offset, &value, sizeof(WORD));
4210 void StorageUtl_ReadDWord(const BYTE* buffer, ULONG offset, DWORD* value)
4214 memcpy(&tmp, buffer+offset, sizeof(DWORD));
4215 *value = le32toh(tmp);
4218 void StorageUtl_WriteDWord(BYTE* buffer, ULONG offset, DWORD value)
4220 value = htole32(value);
4221 memcpy(buffer+offset, &value, sizeof(DWORD));
4224 void StorageUtl_ReadULargeInteger(const BYTE* buffer, ULONG offset,
4225 ULARGE_INTEGER* value)
4227 #ifdef WORDS_BIGENDIAN
4230 memcpy(&tmp, buffer + offset, sizeof(ULARGE_INTEGER));
4231 value->u.LowPart = htole32(tmp.u.HighPart);
4232 value->u.HighPart = htole32(tmp.u.LowPart);
4234 memcpy(value, buffer + offset, sizeof(ULARGE_INTEGER));
4238 void StorageUtl_WriteULargeInteger(BYTE* buffer, ULONG offset,
4239 const ULARGE_INTEGER *value)
4241 #ifdef WORDS_BIGENDIAN
4244 tmp.u.LowPart = htole32(value->u.HighPart);
4245 tmp.u.HighPart = htole32(value->u.LowPart);
4246 memcpy(buffer + offset, &tmp, sizeof(ULARGE_INTEGER));
4248 memcpy(buffer + offset, value, sizeof(ULARGE_INTEGER));
4252 void StorageUtl_ReadGUID(const BYTE* buffer, ULONG offset, GUID* value)
4254 StorageUtl_ReadDWord(buffer, offset, &(value->Data1));
4255 StorageUtl_ReadWord(buffer, offset+4, &(value->Data2));
4256 StorageUtl_ReadWord(buffer, offset+6, &(value->Data3));
4258 memcpy(value->Data4, buffer+offset+8, sizeof(value->Data4));
4261 void StorageUtl_WriteGUID(BYTE* buffer, ULONG offset, const GUID* value)
4263 StorageUtl_WriteDWord(buffer, offset, value->Data1);
4264 StorageUtl_WriteWord(buffer, offset+4, value->Data2);
4265 StorageUtl_WriteWord(buffer, offset+6, value->Data3);
4267 memcpy(buffer+offset+8, value->Data4, sizeof(value->Data4));
4270 void StorageUtl_CopyPropertyToSTATSTG(
4271 STATSTG* destination,
4272 StgProperty* source,
4276 * The copy of the string occurs only when the flag is not set
4278 if( ((statFlags & STATFLAG_NONAME) != 0) ||
4279 (source->name == NULL) ||
4280 (source->name[0] == 0) )
4282 destination->pwcsName = 0;
4286 destination->pwcsName =
4287 CoTaskMemAlloc((lstrlenW(source->name)+1)*sizeof(WCHAR));
4289 strcpyW((LPWSTR)destination->pwcsName, source->name);
4292 switch (source->propertyType)
4294 case PROPTYPE_STORAGE:
4296 destination->type = STGTY_STORAGE;
4298 case PROPTYPE_STREAM:
4299 destination->type = STGTY_STREAM;
4302 destination->type = STGTY_STREAM;
4306 destination->cbSize = source->size;
4308 currentReturnStruct->mtime = {0}; TODO
4309 currentReturnStruct->ctime = {0};
4310 currentReturnStruct->atime = {0};
4312 destination->grfMode = 0;
4313 destination->grfLocksSupported = 0;
4314 destination->clsid = source->propertyUniqueID;
4315 destination->grfStateBits = 0;
4316 destination->reserved = 0;
4319 /******************************************************************************
4320 ** BlockChainStream implementation
4323 BlockChainStream* BlockChainStream_Construct(
4324 StorageImpl* parentStorage,
4325 ULONG* headOfStreamPlaceHolder,
4326 ULONG propertyIndex)
4328 BlockChainStream* newStream;
4331 newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(BlockChainStream));
4333 newStream->parentStorage = parentStorage;
4334 newStream->headOfStreamPlaceHolder = headOfStreamPlaceHolder;
4335 newStream->ownerPropertyIndex = propertyIndex;
4336 newStream->lastBlockNoInSequence = 0xFFFFFFFF;
4337 newStream->tailIndex = BLOCK_END_OF_CHAIN;
4338 newStream->numBlocks = 0;
4340 blockIndex = BlockChainStream_GetHeadOfChain(newStream);
4342 while (blockIndex != BLOCK_END_OF_CHAIN)
4344 newStream->numBlocks++;
4345 newStream->tailIndex = blockIndex;
4347 if(FAILED(StorageImpl_GetNextBlockInChain(
4352 HeapFree(GetProcessHeap(), 0, newStream);
4360 void BlockChainStream_Destroy(BlockChainStream* This)
4362 HeapFree(GetProcessHeap(), 0, This);
4365 /******************************************************************************
4366 * BlockChainStream_GetHeadOfChain
4368 * Returns the head of this stream chain.
4369 * Some special chains don't have properties, their heads are kept in
4370 * This->headOfStreamPlaceHolder.
4373 ULONG BlockChainStream_GetHeadOfChain(BlockChainStream* This)
4375 StgProperty chainProperty;
4376 BOOL readSuccessful;
4378 if (This->headOfStreamPlaceHolder != 0)
4379 return *(This->headOfStreamPlaceHolder);
4381 if (This->ownerPropertyIndex != PROPERTY_NULL)
4383 readSuccessful = StorageImpl_ReadProperty(
4384 This->parentStorage,
4385 This->ownerPropertyIndex,
4390 return chainProperty.startingBlock;
4394 return BLOCK_END_OF_CHAIN;
4397 /******************************************************************************
4398 * BlockChainStream_GetCount
4400 * Returns the number of blocks that comprises this chain.
4401 * This is not the size of the stream as the last block may not be full!
4404 ULONG BlockChainStream_GetCount(BlockChainStream* This)
4409 blockIndex = BlockChainStream_GetHeadOfChain(This);
4411 while (blockIndex != BLOCK_END_OF_CHAIN)
4415 if(FAILED(StorageImpl_GetNextBlockInChain(
4416 This->parentStorage,
4425 /******************************************************************************
4426 * BlockChainStream_ReadAt
4428 * Reads a specified number of bytes from this chain at the specified offset.
4429 * bytesRead may be NULL.
4430 * Failure will be returned if the specified number of bytes has not been read.
4432 BOOL BlockChainStream_ReadAt(BlockChainStream* This,
4433 ULARGE_INTEGER offset,
4438 ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
4439 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->bigBlockSize;
4440 ULONG bytesToReadInBuffer;
4443 BYTE* bigBlockBuffer;
4446 * Find the first block in the stream that contains part of the buffer.
4448 if ( (This->lastBlockNoInSequence == 0xFFFFFFFF) ||
4449 (This->lastBlockNoInSequenceIndex == BLOCK_END_OF_CHAIN) ||
4450 (blockNoInSequence < This->lastBlockNoInSequence) )
4452 blockIndex = BlockChainStream_GetHeadOfChain(This);
4453 This->lastBlockNoInSequence = blockNoInSequence;
4457 ULONG temp = blockNoInSequence;
4459 blockIndex = This->lastBlockNoInSequenceIndex;
4460 blockNoInSequence -= This->lastBlockNoInSequence;
4461 This->lastBlockNoInSequence = temp;
4464 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
4466 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex, &blockIndex)))
4468 blockNoInSequence--;
4471 if ((blockNoInSequence > 0) && (blockIndex == BLOCK_END_OF_CHAIN))
4472 return FALSE; /* We failed to find the starting block */
4474 This->lastBlockNoInSequenceIndex = blockIndex;
4477 * Start reading the buffer.
4480 bufferWalker = buffer;
4482 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
4485 * Calculate how many bytes we can copy from this big block.
4487 bytesToReadInBuffer =
4488 min(This->parentStorage->bigBlockSize - offsetInBlock, size);
4491 * Copy those bytes to the buffer
4494 StorageImpl_GetROBigBlock(This->parentStorage, blockIndex);
4496 memcpy(bufferWalker, bigBlockBuffer + offsetInBlock, bytesToReadInBuffer);
4498 StorageImpl_ReleaseBigBlock(This->parentStorage, bigBlockBuffer);
4501 * Step to the next big block.
4503 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex, &blockIndex)))
4506 bufferWalker += bytesToReadInBuffer;
4507 size -= bytesToReadInBuffer;
4508 *bytesRead += bytesToReadInBuffer;
4509 offsetInBlock = 0; /* There is no offset on the next block */
4516 /******************************************************************************
4517 * BlockChainStream_WriteAt
4519 * Writes the specified number of bytes to this chain at the specified offset.
4520 * bytesWritten may be NULL.
4521 * Will fail if not all specified number of bytes have been written.
4523 BOOL BlockChainStream_WriteAt(BlockChainStream* This,
4524 ULARGE_INTEGER offset,
4527 ULONG* bytesWritten)
4529 ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
4530 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->bigBlockSize;
4533 const BYTE* bufferWalker;
4534 BYTE* bigBlockBuffer;
4537 * Find the first block in the stream that contains part of the buffer.
4539 if ( (This->lastBlockNoInSequence == 0xFFFFFFFF) ||
4540 (This->lastBlockNoInSequenceIndex == BLOCK_END_OF_CHAIN) ||
4541 (blockNoInSequence < This->lastBlockNoInSequence) )
4543 blockIndex = BlockChainStream_GetHeadOfChain(This);
4544 This->lastBlockNoInSequence = blockNoInSequence;
4548 ULONG temp = blockNoInSequence;
4550 blockIndex = This->lastBlockNoInSequenceIndex;
4551 blockNoInSequence -= This->lastBlockNoInSequence;
4552 This->lastBlockNoInSequence = temp;
4555 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
4557 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4560 blockNoInSequence--;
4563 This->lastBlockNoInSequenceIndex = blockIndex;
4566 * Here, I'm casting away the constness on the buffer variable
4567 * This is OK since we don't intend to modify that buffer.
4570 bufferWalker = (const BYTE*)buffer;
4572 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
4575 * Calculate how many bytes we can copy from this big block.
4578 min(This->parentStorage->bigBlockSize - offsetInBlock, size);
4581 * Copy those bytes to the buffer
4583 bigBlockBuffer = StorageImpl_GetBigBlock(This->parentStorage, blockIndex);
4585 memcpy(bigBlockBuffer + offsetInBlock, bufferWalker, bytesToWrite);
4587 StorageImpl_ReleaseBigBlock(This->parentStorage, bigBlockBuffer);
4590 * Step to the next big block.
4592 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4595 bufferWalker += bytesToWrite;
4596 size -= bytesToWrite;
4597 *bytesWritten += bytesToWrite;
4598 offsetInBlock = 0; /* There is no offset on the next block */
4604 /******************************************************************************
4605 * BlockChainStream_Shrink
4607 * Shrinks this chain in the big block depot.
4609 BOOL BlockChainStream_Shrink(BlockChainStream* This,
4610 ULARGE_INTEGER newSize)
4612 ULONG blockIndex, extraBlock;
4617 * Reset the last accessed block cache.
4619 This->lastBlockNoInSequence = 0xFFFFFFFF;
4620 This->lastBlockNoInSequenceIndex = BLOCK_END_OF_CHAIN;
4623 * Figure out how many blocks are needed to contain the new size
4625 numBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
4627 if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
4630 blockIndex = BlockChainStream_GetHeadOfChain(This);
4633 * Go to the new end of chain
4635 while (count < numBlocks)
4637 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4643 /* Get the next block before marking the new end */
4644 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4648 /* Mark the new end of chain */
4649 StorageImpl_SetNextBlockInChain(
4650 This->parentStorage,
4652 BLOCK_END_OF_CHAIN);
4654 This->tailIndex = blockIndex;
4655 This->numBlocks = numBlocks;
4658 * Mark the extra blocks as free
4660 while (extraBlock != BLOCK_END_OF_CHAIN)
4662 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, extraBlock,
4665 StorageImpl_FreeBigBlock(This->parentStorage, extraBlock);
4666 extraBlock = blockIndex;
4672 /******************************************************************************
4673 * BlockChainStream_Enlarge
4675 * Grows this chain in the big block depot.
4677 BOOL BlockChainStream_Enlarge(BlockChainStream* This,
4678 ULARGE_INTEGER newSize)
4680 ULONG blockIndex, currentBlock;
4682 ULONG oldNumBlocks = 0;
4684 blockIndex = BlockChainStream_GetHeadOfChain(This);
4687 * Empty chain. Create the head.
4689 if (blockIndex == BLOCK_END_OF_CHAIN)
4691 blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
4692 StorageImpl_SetNextBlockInChain(This->parentStorage,
4694 BLOCK_END_OF_CHAIN);
4696 if (This->headOfStreamPlaceHolder != 0)
4698 *(This->headOfStreamPlaceHolder) = blockIndex;
4702 StgProperty chainProp;
4703 assert(This->ownerPropertyIndex != PROPERTY_NULL);
4705 StorageImpl_ReadProperty(
4706 This->parentStorage,
4707 This->ownerPropertyIndex,
4710 chainProp.startingBlock = blockIndex;
4712 StorageImpl_WriteProperty(
4713 This->parentStorage,
4714 This->ownerPropertyIndex,
4718 This->tailIndex = blockIndex;
4719 This->numBlocks = 1;
4723 * Figure out how many blocks are needed to contain this stream
4725 newNumBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
4727 if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
4731 * Go to the current end of chain
4733 if (This->tailIndex == BLOCK_END_OF_CHAIN)
4735 currentBlock = blockIndex;
4737 while (blockIndex != BLOCK_END_OF_CHAIN)
4740 currentBlock = blockIndex;
4742 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, currentBlock,
4747 This->tailIndex = currentBlock;
4750 currentBlock = This->tailIndex;
4751 oldNumBlocks = This->numBlocks;
4754 * Add new blocks to the chain
4756 if (oldNumBlocks < newNumBlocks)
4758 while (oldNumBlocks < newNumBlocks)
4760 blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
4762 StorageImpl_SetNextBlockInChain(
4763 This->parentStorage,
4767 StorageImpl_SetNextBlockInChain(
4768 This->parentStorage,
4770 BLOCK_END_OF_CHAIN);
4772 currentBlock = blockIndex;
4776 This->tailIndex = blockIndex;
4777 This->numBlocks = newNumBlocks;
4783 /******************************************************************************
4784 * BlockChainStream_SetSize
4786 * Sets the size of this stream. The big block depot will be updated.
4787 * The file will grow if we grow the chain.
4789 * TODO: Free the actual blocks in the file when we shrink the chain.
4790 * Currently, the blocks are still in the file. So the file size
4791 * doesn't shrink even if we shrink streams.
4793 BOOL BlockChainStream_SetSize(
4794 BlockChainStream* This,
4795 ULARGE_INTEGER newSize)
4797 ULARGE_INTEGER size = BlockChainStream_GetSize(This);
4799 if (newSize.u.LowPart == size.u.LowPart)
4802 if (newSize.u.LowPart < size.u.LowPart)
4804 BlockChainStream_Shrink(This, newSize);
4808 ULARGE_INTEGER fileSize =
4809 BIGBLOCKFILE_GetSize(This->parentStorage->bigBlockFile);
4811 ULONG diff = newSize.u.LowPart - size.u.LowPart;
4814 * Make sure the file stays a multiple of blocksize
4816 if ((diff % This->parentStorage->bigBlockSize) != 0)
4817 diff += (This->parentStorage->bigBlockSize -
4818 (diff % This->parentStorage->bigBlockSize) );
4820 fileSize.u.LowPart += diff;
4821 BIGBLOCKFILE_SetSize(This->parentStorage->bigBlockFile, fileSize);
4823 BlockChainStream_Enlarge(This, newSize);
4829 /******************************************************************************
4830 * BlockChainStream_GetSize
4832 * Returns the size of this chain.
4833 * Will return the block count if this chain doesn't have a property.
4835 ULARGE_INTEGER BlockChainStream_GetSize(BlockChainStream* This)
4837 StgProperty chainProperty;
4839 if(This->headOfStreamPlaceHolder == NULL)
4842 * This chain is a data stream read the property and return
4843 * the appropriate size
4845 StorageImpl_ReadProperty(
4846 This->parentStorage,
4847 This->ownerPropertyIndex,
4850 return chainProperty.size;
4855 * this chain is a chain that does not have a property, figure out the
4856 * size by making the product number of used blocks times the
4859 ULARGE_INTEGER result;
4860 result.u.HighPart = 0;
4863 BlockChainStream_GetCount(This) *
4864 This->parentStorage->bigBlockSize;
4870 /******************************************************************************
4871 ** SmallBlockChainStream implementation
4874 SmallBlockChainStream* SmallBlockChainStream_Construct(
4875 StorageImpl* parentStorage,
4876 ULONG propertyIndex)
4878 SmallBlockChainStream* newStream;
4880 newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(SmallBlockChainStream));
4882 newStream->parentStorage = parentStorage;
4883 newStream->ownerPropertyIndex = propertyIndex;
4888 void SmallBlockChainStream_Destroy(
4889 SmallBlockChainStream* This)
4891 HeapFree(GetProcessHeap(), 0, This);
4894 /******************************************************************************
4895 * SmallBlockChainStream_GetHeadOfChain
4897 * Returns the head of this chain of small blocks.
4899 ULONG SmallBlockChainStream_GetHeadOfChain(
4900 SmallBlockChainStream* This)
4902 StgProperty chainProperty;
4903 BOOL readSuccessful;
4905 if (This->ownerPropertyIndex)
4907 readSuccessful = StorageImpl_ReadProperty(
4908 This->parentStorage,
4909 This->ownerPropertyIndex,
4914 return chainProperty.startingBlock;
4919 return BLOCK_END_OF_CHAIN;
4922 /******************************************************************************
4923 * SmallBlockChainStream_GetNextBlockInChain
4925 * Returns the index of the next small block in this chain.
4928 * - BLOCK_END_OF_CHAIN: end of this chain
4929 * - BLOCK_UNUSED: small block 'blockIndex' is free
4931 HRESULT SmallBlockChainStream_GetNextBlockInChain(
4932 SmallBlockChainStream* This,
4934 ULONG* nextBlockInChain)
4936 ULARGE_INTEGER offsetOfBlockInDepot;
4941 *nextBlockInChain = BLOCK_END_OF_CHAIN;
4943 offsetOfBlockInDepot.u.HighPart = 0;
4944 offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
4947 * Read those bytes in the buffer from the small block file.
4949 success = BlockChainStream_ReadAt(
4950 This->parentStorage->smallBlockDepotChain,
4951 offsetOfBlockInDepot,
4958 StorageUtl_ReadDWord((BYTE *)&buffer, 0, nextBlockInChain);
4962 return STG_E_READFAULT;
4965 /******************************************************************************
4966 * SmallBlockChainStream_SetNextBlockInChain
4968 * Writes the index of the next block of the specified block in the small
4970 * To set the end of chain use BLOCK_END_OF_CHAIN as nextBlock.
4971 * To flag a block as free use BLOCK_UNUSED as nextBlock.
4973 void SmallBlockChainStream_SetNextBlockInChain(
4974 SmallBlockChainStream* This,
4978 ULARGE_INTEGER offsetOfBlockInDepot;
4982 offsetOfBlockInDepot.u.HighPart = 0;
4983 offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
4985 StorageUtl_WriteDWord((BYTE *)&buffer, 0, nextBlock);
4988 * Read those bytes in the buffer from the small block file.
4990 BlockChainStream_WriteAt(
4991 This->parentStorage->smallBlockDepotChain,
4992 offsetOfBlockInDepot,
4998 /******************************************************************************
4999 * SmallBlockChainStream_FreeBlock
5001 * Flag small block 'blockIndex' as free in the small block depot.
5003 void SmallBlockChainStream_FreeBlock(
5004 SmallBlockChainStream* This,
5007 SmallBlockChainStream_SetNextBlockInChain(This, blockIndex, BLOCK_UNUSED);
5010 /******************************************************************************
5011 * SmallBlockChainStream_GetNextFreeBlock
5013 * Returns the index of a free small block. The small block depot will be
5014 * enlarged if necessary. The small block chain will also be enlarged if
5017 ULONG SmallBlockChainStream_GetNextFreeBlock(
5018 SmallBlockChainStream* This)
5020 ULARGE_INTEGER offsetOfBlockInDepot;
5023 ULONG blockIndex = 0;
5024 ULONG nextBlockIndex = BLOCK_END_OF_CHAIN;
5025 BOOL success = TRUE;
5026 ULONG smallBlocksPerBigBlock;
5028 offsetOfBlockInDepot.u.HighPart = 0;
5031 * Scan the small block depot for a free block
5033 while (nextBlockIndex != BLOCK_UNUSED)
5035 offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
5037 success = BlockChainStream_ReadAt(
5038 This->parentStorage->smallBlockDepotChain,
5039 offsetOfBlockInDepot,
5045 * If we run out of space for the small block depot, enlarge it
5049 StorageUtl_ReadDWord((BYTE *)&buffer, 0, &nextBlockIndex);
5051 if (nextBlockIndex != BLOCK_UNUSED)
5057 BlockChainStream_GetCount(This->parentStorage->smallBlockDepotChain);
5059 ULONG sbdIndex = This->parentStorage->smallBlockDepotStart;
5060 ULONG nextBlock, newsbdIndex;
5061 BYTE* smallBlockDepot;
5063 nextBlock = sbdIndex;
5064 while (nextBlock != BLOCK_END_OF_CHAIN)
5066 sbdIndex = nextBlock;
5067 StorageImpl_GetNextBlockInChain(This->parentStorage, sbdIndex, &nextBlock);
5070 newsbdIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
5071 if (sbdIndex != BLOCK_END_OF_CHAIN)
5072 StorageImpl_SetNextBlockInChain(
5073 This->parentStorage,
5077 StorageImpl_SetNextBlockInChain(
5078 This->parentStorage,
5080 BLOCK_END_OF_CHAIN);
5083 * Initialize all the small blocks to free
5086 StorageImpl_GetBigBlock(This->parentStorage, newsbdIndex);
5088 memset(smallBlockDepot, BLOCK_UNUSED, This->parentStorage->bigBlockSize);
5089 StorageImpl_ReleaseBigBlock(This->parentStorage, smallBlockDepot);
5094 * We have just created the small block depot.
5096 StgProperty rootProp;
5100 * Save it in the header
5102 This->parentStorage->smallBlockDepotStart = newsbdIndex;
5103 StorageImpl_SaveFileHeader(This->parentStorage);
5106 * And allocate the first big block that will contain small blocks
5109 StorageImpl_GetNextFreeBigBlock(This->parentStorage);
5111 StorageImpl_SetNextBlockInChain(
5112 This->parentStorage,
5114 BLOCK_END_OF_CHAIN);
5116 StorageImpl_ReadProperty(
5117 This->parentStorage,
5118 This->parentStorage->base.rootPropertySetIndex,
5121 rootProp.startingBlock = sbStartIndex;
5122 rootProp.size.u.HighPart = 0;
5123 rootProp.size.u.LowPart = This->parentStorage->bigBlockSize;
5125 StorageImpl_WriteProperty(
5126 This->parentStorage,
5127 This->parentStorage->base.rootPropertySetIndex,
5133 smallBlocksPerBigBlock =
5134 This->parentStorage->bigBlockSize / This->parentStorage->smallBlockSize;
5137 * Verify if we have to allocate big blocks to contain small blocks
5139 if (blockIndex % smallBlocksPerBigBlock == 0)
5141 StgProperty rootProp;
5142 ULONG blocksRequired = (blockIndex / smallBlocksPerBigBlock) + 1;
5144 StorageImpl_ReadProperty(
5145 This->parentStorage,
5146 This->parentStorage->base.rootPropertySetIndex,
5149 if (rootProp.size.u.LowPart <
5150 (blocksRequired * This->parentStorage->bigBlockSize))
5152 rootProp.size.u.LowPart += This->parentStorage->bigBlockSize;
5154 BlockChainStream_SetSize(
5155 This->parentStorage->smallBlockRootChain,
5158 StorageImpl_WriteProperty(
5159 This->parentStorage,
5160 This->parentStorage->base.rootPropertySetIndex,
5168 /******************************************************************************
5169 * SmallBlockChainStream_ReadAt
5171 * Reads a specified number of bytes from this chain at the specified offset.
5172 * bytesRead may be NULL.
5173 * Failure will be returned if the specified number of bytes has not been read.
5175 HRESULT SmallBlockChainStream_ReadAt(
5176 SmallBlockChainStream* This,
5177 ULARGE_INTEGER offset,
5183 ULARGE_INTEGER offsetInBigBlockFile;
5184 ULONG blockNoInSequence =
5185 offset.u.LowPart / This->parentStorage->smallBlockSize;
5187 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
5188 ULONG bytesToReadInBuffer;
5190 ULONG bytesReadFromBigBlockFile;
5194 * This should never happen on a small block file.
5196 assert(offset.u.HighPart==0);
5199 * Find the first block in the stream that contains part of the buffer.
5201 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5203 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
5205 rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
5208 blockNoInSequence--;
5212 * Start reading the buffer.
5215 bufferWalker = buffer;
5217 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
5220 * Calculate how many bytes we can copy from this small block.
5222 bytesToReadInBuffer =
5223 min(This->parentStorage->smallBlockSize - offsetInBlock, size);
5226 * Calculate the offset of the small block in the small block file.
5228 offsetInBigBlockFile.u.HighPart = 0;
5229 offsetInBigBlockFile.u.LowPart =
5230 blockIndex * This->parentStorage->smallBlockSize;
5232 offsetInBigBlockFile.u.LowPart += offsetInBlock;
5235 * Read those bytes in the buffer from the small block file.
5236 * The small block has already been identified so it shouldn't fail
5237 * unless the file is corrupt.
5239 if (!BlockChainStream_ReadAt(This->parentStorage->smallBlockRootChain,
5240 offsetInBigBlockFile,
5241 bytesToReadInBuffer,
5243 &bytesReadFromBigBlockFile))
5244 return STG_E_DOCFILECORRUPT;
5246 assert(bytesReadFromBigBlockFile == bytesToReadInBuffer);
5249 * Step to the next big block.
5251 rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
5255 bufferWalker += bytesToReadInBuffer;
5256 size -= bytesToReadInBuffer;
5257 *bytesRead += bytesToReadInBuffer;
5258 offsetInBlock = 0; /* There is no offset on the next block */
5264 /******************************************************************************
5265 * SmallBlockChainStream_WriteAt
5267 * Writes the specified number of bytes to this chain at the specified offset.
5268 * bytesWritten may be NULL.
5269 * Will fail if not all specified number of bytes have been written.
5271 BOOL SmallBlockChainStream_WriteAt(
5272 SmallBlockChainStream* This,
5273 ULARGE_INTEGER offset,
5276 ULONG* bytesWritten)
5278 ULARGE_INTEGER offsetInBigBlockFile;
5279 ULONG blockNoInSequence =
5280 offset.u.LowPart / This->parentStorage->smallBlockSize;
5282 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
5283 ULONG bytesToWriteInBuffer;
5285 ULONG bytesWrittenFromBigBlockFile;
5286 const BYTE* bufferWalker;
5289 * This should never happen on a small block file.
5291 assert(offset.u.HighPart==0);
5294 * Find the first block in the stream that contains part of the buffer.
5296 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5298 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
5300 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex)))
5302 blockNoInSequence--;
5306 * Start writing the buffer.
5308 * Here, I'm casting away the constness on the buffer variable
5309 * This is OK since we don't intend to modify that buffer.
5312 bufferWalker = (const BYTE*)buffer;
5313 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
5316 * Calculate how many bytes we can copy to this small block.
5318 bytesToWriteInBuffer =
5319 min(This->parentStorage->smallBlockSize - offsetInBlock, size);
5322 * Calculate the offset of the small block in the small block file.
5324 offsetInBigBlockFile.u.HighPart = 0;
5325 offsetInBigBlockFile.u.LowPart =
5326 blockIndex * This->parentStorage->smallBlockSize;
5328 offsetInBigBlockFile.u.LowPart += offsetInBlock;
5331 * Write those bytes in the buffer to the small block file.
5333 BlockChainStream_WriteAt(This->parentStorage->smallBlockRootChain,
5334 offsetInBigBlockFile,
5335 bytesToWriteInBuffer,
5337 &bytesWrittenFromBigBlockFile);
5339 assert(bytesWrittenFromBigBlockFile == bytesToWriteInBuffer);
5342 * Step to the next big block.
5344 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
5347 bufferWalker += bytesToWriteInBuffer;
5348 size -= bytesToWriteInBuffer;
5349 *bytesWritten += bytesToWriteInBuffer;
5350 offsetInBlock = 0; /* There is no offset on the next block */
5356 /******************************************************************************
5357 * SmallBlockChainStream_Shrink
5359 * Shrinks this chain in the small block depot.
5361 BOOL SmallBlockChainStream_Shrink(
5362 SmallBlockChainStream* This,
5363 ULARGE_INTEGER newSize)
5365 ULONG blockIndex, extraBlock;
5369 numBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
5371 if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
5374 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5377 * Go to the new end of chain
5379 while (count < numBlocks)
5381 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
5388 * If the count is 0, we have a special case, the head of the chain was
5393 StgProperty chainProp;
5395 StorageImpl_ReadProperty(This->parentStorage,
5396 This->ownerPropertyIndex,
5399 chainProp.startingBlock = BLOCK_END_OF_CHAIN;
5401 StorageImpl_WriteProperty(This->parentStorage,
5402 This->ownerPropertyIndex,
5406 * We start freeing the chain at the head block.
5408 extraBlock = blockIndex;
5412 /* Get the next block before marking the new end */
5413 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
5417 /* Mark the new end of chain */
5418 SmallBlockChainStream_SetNextBlockInChain(
5421 BLOCK_END_OF_CHAIN);
5425 * Mark the extra blocks as free
5427 while (extraBlock != BLOCK_END_OF_CHAIN)
5429 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, extraBlock,
5432 SmallBlockChainStream_FreeBlock(This, extraBlock);
5433 extraBlock = blockIndex;
5439 /******************************************************************************
5440 * SmallBlockChainStream_Enlarge
5442 * Grows this chain in the small block depot.
5444 BOOL SmallBlockChainStream_Enlarge(
5445 SmallBlockChainStream* This,
5446 ULARGE_INTEGER newSize)
5448 ULONG blockIndex, currentBlock;
5450 ULONG oldNumBlocks = 0;
5452 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5457 if (blockIndex == BLOCK_END_OF_CHAIN)
5460 StgProperty chainProp;
5462 StorageImpl_ReadProperty(This->parentStorage, This->ownerPropertyIndex,
5465 chainProp.startingBlock = SmallBlockChainStream_GetNextFreeBlock(This);
5467 StorageImpl_WriteProperty(This->parentStorage, This->ownerPropertyIndex,
5470 blockIndex = chainProp.startingBlock;
5471 SmallBlockChainStream_SetNextBlockInChain(
5474 BLOCK_END_OF_CHAIN);
5477 currentBlock = blockIndex;
5480 * Figure out how many blocks are needed to contain this stream
5482 newNumBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
5484 if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
5488 * Go to the current end of chain
5490 while (blockIndex != BLOCK_END_OF_CHAIN)
5493 currentBlock = blockIndex;
5494 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, currentBlock, &blockIndex)))
5499 * Add new blocks to the chain
5501 while (oldNumBlocks < newNumBlocks)
5503 blockIndex = SmallBlockChainStream_GetNextFreeBlock(This);
5504 SmallBlockChainStream_SetNextBlockInChain(This, currentBlock, blockIndex);
5506 SmallBlockChainStream_SetNextBlockInChain(
5509 BLOCK_END_OF_CHAIN);
5511 currentBlock = blockIndex;
5518 /******************************************************************************
5519 * SmallBlockChainStream_GetCount
5521 * Returns the number of blocks that comprises this chain.
5522 * This is not the size of this chain as the last block may not be full!
5524 ULONG SmallBlockChainStream_GetCount(SmallBlockChainStream* This)
5529 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5531 while (blockIndex != BLOCK_END_OF_CHAIN)
5535 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex)))
5542 /******************************************************************************
5543 * SmallBlockChainStream_SetSize
5545 * Sets the size of this stream.
5546 * The file will grow if we grow the chain.
5548 * TODO: Free the actual blocks in the file when we shrink the chain.
5549 * Currently, the blocks are still in the file. So the file size
5550 * doesn't shrink even if we shrink streams.
5552 BOOL SmallBlockChainStream_SetSize(
5553 SmallBlockChainStream* This,
5554 ULARGE_INTEGER newSize)
5556 ULARGE_INTEGER size = SmallBlockChainStream_GetSize(This);
5558 if (newSize.u.LowPart == size.u.LowPart)
5561 if (newSize.u.LowPart < size.u.LowPart)
5563 SmallBlockChainStream_Shrink(This, newSize);
5567 SmallBlockChainStream_Enlarge(This, newSize);
5573 /******************************************************************************
5574 * SmallBlockChainStream_GetSize
5576 * Returns the size of this chain.
5578 ULARGE_INTEGER SmallBlockChainStream_GetSize(SmallBlockChainStream* This)
5580 StgProperty chainProperty;
5582 StorageImpl_ReadProperty(
5583 This->parentStorage,
5584 This->ownerPropertyIndex,
5587 return chainProperty.size;
5590 /******************************************************************************
5591 * StgCreateDocfile [OLE32.@]
5593 HRESULT WINAPI StgCreateDocfile(
5597 IStorage **ppstgOpen)
5599 StorageImpl* newStorage = 0;
5600 HANDLE hFile = INVALID_HANDLE_VALUE;
5601 HRESULT hr = STG_E_INVALIDFLAG;
5605 DWORD fileAttributes;
5606 WCHAR tempFileName[MAX_PATH];
5608 TRACE("(%s, %lx, %ld, %p)\n",
5609 debugstr_w(pwcsName), grfMode,
5610 reserved, ppstgOpen);
5613 * Validate the parameters
5616 return STG_E_INVALIDPOINTER;
5618 return STG_E_INVALIDPARAMETER;
5621 * Validate the STGM flags
5623 if ( FAILED( validateSTGM(grfMode) ))
5626 /* StgCreateDocFile always opens for write */
5627 switch(STGM_ACCESS_MODE(grfMode))
5630 case STGM_READWRITE:
5636 /* can't share write */
5637 switch(STGM_SHARE_MODE(grfMode))
5639 case STGM_SHARE_EXCLUSIVE:
5640 case STGM_SHARE_DENY_WRITE:
5646 /* shared reading requires transacted mode */
5647 if( STGM_SHARE_MODE(grfMode) == STGM_SHARE_DENY_WRITE &&
5648 !(grfMode&STGM_TRANSACTED) )
5652 * Generate a unique name.
5656 WCHAR tempPath[MAX_PATH];
5657 static const WCHAR prefix[] = { 'S', 'T', 'O', 0 };
5659 if (STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE)
5662 memset(tempPath, 0, sizeof(tempPath));
5663 memset(tempFileName, 0, sizeof(tempFileName));
5665 if ((GetTempPathW(MAX_PATH, tempPath)) == 0 )
5668 if (GetTempFileNameW(tempPath, prefix, 0, tempFileName) != 0)
5669 pwcsName = tempFileName;
5672 hr = STG_E_INSUFFICIENTMEMORY;
5676 creationMode = TRUNCATE_EXISTING;
5680 creationMode = GetCreationModeFromSTGM(grfMode);
5684 * Interpret the STGM value grfMode
5686 shareMode = GetShareModeFromSTGM(grfMode);
5687 accessMode = GetAccessModeFromSTGM(grfMode);
5689 if (grfMode & STGM_DELETEONRELEASE)
5690 fileAttributes = FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_DELETE_ON_CLOSE;
5692 fileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS;
5694 if (grfMode & STGM_TRANSACTED)
5695 FIXME("Transacted mode not implemented.\n");
5698 * Initialize the "out" parameter.
5702 hFile = CreateFileW(pwcsName,
5710 if (hFile == INVALID_HANDLE_VALUE)
5712 if(GetLastError() == ERROR_FILE_EXISTS)
5713 hr = STG_E_FILEALREADYEXISTS;
5720 * Allocate and initialize the new IStorage32object.
5722 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
5724 if (newStorage == 0)
5726 hr = STG_E_INSUFFICIENTMEMORY;
5730 hr = StorageImpl_Construct(
5741 HeapFree(GetProcessHeap(), 0, newStorage);
5746 * Get an "out" pointer for the caller.
5748 hr = StorageBaseImpl_QueryInterface(
5749 (IStorage*)newStorage,
5750 (REFIID)&IID_IStorage,
5753 TRACE("<-- %p r = %08lx\n", *ppstgOpen, hr);
5758 /******************************************************************************
5759 * StgCreateStorageEx [OLE32.@]
5761 HRESULT WINAPI StgCreateStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
5763 TRACE("(%s, %lx, %lx, %lx, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
5764 grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);
5766 if (stgfmt != STGFMT_FILE && grfAttrs != 0)
5768 ERR("grfAttrs must be 0 if stgfmt != STGFMT_FILE\n");
5769 return STG_E_INVALIDPARAMETER;
5772 if (stgfmt != STGFMT_FILE && grfAttrs != 0 && grfAttrs != FILE_FLAG_NO_BUFFERING)
5774 ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_FILE\n");
5775 return STG_E_INVALIDPARAMETER;
5778 if (stgfmt == STGFMT_FILE)
5780 ERR("Cannot use STGFMT_FILE - this is NTFS only\n");
5781 return STG_E_INVALIDPARAMETER;
5784 if (stgfmt == STGFMT_STORAGE || stgfmt == STGFMT_DOCFILE)
5786 FIXME("Stub: calling StgCreateDocfile, but ignoring pStgOptions and grfAttrs\n");
5787 return StgCreateDocfile(pwcsName, grfMode, 0, (IStorage **)ppObjectOpen);
5790 ERR("Invalid stgfmt argument\n");
5791 return STG_E_INVALIDPARAMETER;
5794 /******************************************************************************
5795 * StgCreatePropSetStg [OLE32.@]
5797 HRESULT WINAPI StgCreatePropSetStg(IStorage *pstg, DWORD reserved,
5798 IPropertySetStorage **ppPropSetStg)
5802 TRACE("(%p, 0x%lx, %p)\n", pstg, reserved, ppPropSetStg);
5804 hr = STG_E_INVALIDPARAMETER;
5806 hr = StorageBaseImpl_QueryInterface(pstg, &IID_IPropertySetStorage,
5807 (void**)ppPropSetStg);
5811 /******************************************************************************
5812 * StgOpenStorageEx [OLE32.@]
5814 HRESULT WINAPI StgOpenStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
5816 TRACE("(%s, %lx, %lx, %lx, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
5817 grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);
5819 if (stgfmt != STGFMT_DOCFILE && grfAttrs != 0)
5821 ERR("grfAttrs must be 0 if stgfmt != STGFMT_DOCFILE\n");
5822 return STG_E_INVALIDPARAMETER;
5825 if (stgfmt != STGFMT_DOCFILE && grfAttrs != 0 && grfAttrs != FILE_FLAG_NO_BUFFERING)
5827 ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_DOCFILE\n");
5828 return STG_E_INVALIDPARAMETER;
5831 if (stgfmt == STGFMT_FILE)
5833 ERR("Cannot use STGFMT_FILE - this is NTFS only\n");
5834 return STG_E_INVALIDPARAMETER;
5837 if (stgfmt == STGFMT_STORAGE || stgfmt == STGFMT_DOCFILE || stgfmt == STGFMT_ANY)
5839 if (stgfmt == STGFMT_ANY)
5840 WARN("STGFMT_ANY assuming storage\n");
5841 FIXME("Stub: calling StgOpenStorage, but ignoring pStgOptions and grfAttrs\n");
5842 return StgOpenStorage(pwcsName, NULL, grfMode, (SNB)NULL, 0, (IStorage **)ppObjectOpen);
5845 ERR("Invalid stgfmt argument\n");
5846 return STG_E_INVALIDPARAMETER;
5850 /******************************************************************************
5851 * StgOpenStorage [OLE32.@]
5853 HRESULT WINAPI StgOpenStorage(
5854 const OLECHAR *pwcsName,
5855 IStorage *pstgPriority,
5859 IStorage **ppstgOpen)
5861 StorageImpl* newStorage = 0;
5866 WCHAR fullname[MAX_PATH];
5869 TRACE("(%s, %p, %lx, %p, %ld, %p)\n",
5870 debugstr_w(pwcsName), pstgPriority, grfMode,
5871 snbExclude, reserved, ppstgOpen);
5874 * Perform sanity checks
5878 hr = STG_E_INVALIDNAME;
5884 hr = STG_E_INVALIDPOINTER;
5890 hr = STG_E_INVALIDPARAMETER;
5895 * Validate the sharing mode
5897 if (!(grfMode & STGM_TRANSACTED))
5898 switch(STGM_SHARE_MODE(grfMode))
5900 case STGM_SHARE_EXCLUSIVE:
5901 case STGM_SHARE_DENY_WRITE:
5904 hr = STG_E_INVALIDFLAG;
5909 * Validate the STGM flags
5911 if ( FAILED( validateSTGM(grfMode) ) ||
5912 (grfMode&STGM_CREATE))
5914 hr = STG_E_INVALIDFLAG;
5918 /* shared reading requires transacted mode */
5919 if( STGM_SHARE_MODE(grfMode) == STGM_SHARE_DENY_WRITE &&
5920 STGM_ACCESS_MODE(grfMode) == STGM_READWRITE &&
5921 !(grfMode&STGM_TRANSACTED) )
5923 hr = STG_E_INVALIDFLAG;
5928 * Interpret the STGM value grfMode
5930 shareMode = GetShareModeFromSTGM(grfMode);
5931 accessMode = GetAccessModeFromSTGM(grfMode);
5934 * Initialize the "out" parameter.
5938 hFile = CreateFileW( pwcsName,
5943 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
5946 if (hFile==INVALID_HANDLE_VALUE)
5948 DWORD last_error = GetLastError();
5954 case ERROR_FILE_NOT_FOUND:
5955 hr = STG_E_FILENOTFOUND;
5958 case ERROR_PATH_NOT_FOUND:
5959 hr = STG_E_PATHNOTFOUND;
5962 case ERROR_ACCESS_DENIED:
5963 case ERROR_WRITE_PROTECT:
5964 hr = STG_E_ACCESSDENIED;
5967 case ERROR_SHARING_VIOLATION:
5968 hr = STG_E_SHAREVIOLATION;
5979 * Refuse to open the file if it's too small to be a structured storage file
5980 * FIXME: verify the file when reading instead of here
5982 length = GetFileSize(hFile, NULL);
5986 hr = STG_E_FILEALREADYEXISTS;
5991 * Allocate and initialize the new IStorage32object.
5993 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
5995 if (newStorage == 0)
5997 hr = STG_E_INSUFFICIENTMEMORY;
6001 /* if the file's length was zero, initialize the storage */
6002 hr = StorageImpl_Construct(
6013 HeapFree(GetProcessHeap(), 0, newStorage);
6015 * According to the docs if the file is not a storage, return STG_E_FILEALREADYEXISTS
6017 if(hr == STG_E_INVALIDHEADER)
6018 hr = STG_E_FILEALREADYEXISTS;
6022 /* prepare the file name string given in lieu of the root property name */
6023 GetFullPathNameW(pwcsName, MAX_PATH, fullname, NULL);
6024 memcpy(newStorage->filename, fullname, PROPERTY_NAME_BUFFER_LEN);
6025 newStorage->filename[PROPERTY_NAME_BUFFER_LEN-1] = '\0';
6028 * Get an "out" pointer for the caller.
6030 hr = StorageBaseImpl_QueryInterface(
6031 (IStorage*)newStorage,
6032 (REFIID)&IID_IStorage,
6036 TRACE("<-- %08lx, IStorage %p\n", hr, ppstgOpen ? *ppstgOpen : NULL);
6040 /******************************************************************************
6041 * StgCreateDocfileOnILockBytes [OLE32.@]
6043 HRESULT WINAPI StgCreateDocfileOnILockBytes(
6047 IStorage** ppstgOpen)
6049 StorageImpl* newStorage = 0;
6053 * Validate the parameters
6055 if ((ppstgOpen == 0) || (plkbyt == 0))
6056 return STG_E_INVALIDPOINTER;
6059 * Allocate and initialize the new IStorage object.
6061 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
6063 if (newStorage == 0)
6064 return STG_E_INSUFFICIENTMEMORY;
6066 hr = StorageImpl_Construct(
6077 HeapFree(GetProcessHeap(), 0, newStorage);
6082 * Get an "out" pointer for the caller.
6084 hr = StorageBaseImpl_QueryInterface(
6085 (IStorage*)newStorage,
6086 (REFIID)&IID_IStorage,
6092 /******************************************************************************
6093 * StgOpenStorageOnILockBytes [OLE32.@]
6095 HRESULT WINAPI StgOpenStorageOnILockBytes(
6097 IStorage *pstgPriority,
6101 IStorage **ppstgOpen)
6103 StorageImpl* newStorage = 0;
6107 * Perform a sanity check
6109 if ((plkbyt == 0) || (ppstgOpen == 0))
6110 return STG_E_INVALIDPOINTER;
6113 * Validate the STGM flags
6115 if ( FAILED( validateSTGM(grfMode) ))
6116 return STG_E_INVALIDFLAG;
6119 * Initialize the "out" parameter.
6124 * Allocate and initialize the new IStorage object.
6126 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
6128 if (newStorage == 0)
6129 return STG_E_INSUFFICIENTMEMORY;
6131 hr = StorageImpl_Construct(
6142 HeapFree(GetProcessHeap(), 0, newStorage);
6147 * Get an "out" pointer for the caller.
6149 hr = StorageBaseImpl_QueryInterface(
6150 (IStorage*)newStorage,
6151 (REFIID)&IID_IStorage,
6157 /******************************************************************************
6158 * StgSetTimes [ole32.@]
6159 * StgSetTimes [OLE32.@]
6163 HRESULT WINAPI StgSetTimes(OLECHAR const *str, FILETIME const *pctime,
6164 FILETIME const *patime, FILETIME const *pmtime)
6166 IStorage *stg = NULL;
6169 TRACE("%s %p %p %p\n", debugstr_w(str), pctime, patime, pmtime);
6171 r = StgOpenStorage(str, NULL, STGM_READWRITE | STGM_SHARE_DENY_WRITE,
6175 r = IStorage_SetElementTimes(stg, NULL, pctime, patime, pmtime);
6176 IStorage_Release(stg);
6182 /******************************************************************************
6183 * StgIsStorageILockBytes [OLE32.@]
6185 * Determines if the ILockBytes contains a storage object.
6187 HRESULT WINAPI StgIsStorageILockBytes(ILockBytes *plkbyt)
6190 ULARGE_INTEGER offset;
6192 offset.u.HighPart = 0;
6193 offset.u.LowPart = 0;
6195 ILockBytes_ReadAt(plkbyt, offset, sig, sizeof(sig), NULL);
6197 if (memcmp(sig, STORAGE_magic, sizeof(STORAGE_magic)) == 0)
6203 /******************************************************************************
6204 * WriteClassStg [OLE32.@]
6206 * This method will store the specified CLSID in the specified storage object
6208 HRESULT WINAPI WriteClassStg(IStorage* pStg, REFCLSID rclsid)
6213 return E_INVALIDARG;
6215 hRes = IStorage_SetClass(pStg, rclsid);
6220 /***********************************************************************
6221 * ReadClassStg (OLE32.@)
6223 * This method reads the CLSID previously written to a storage object with
6224 * the WriteClassStg.
6227 * pstg [I] IStorage pointer
6228 * pclsid [O] Pointer to where the CLSID is written
6232 * Failure: HRESULT code.
6234 HRESULT WINAPI ReadClassStg(IStorage *pstg,CLSID *pclsid){
6239 TRACE("(%p, %p)\n", pstg, pclsid);
6241 if(!pstg || !pclsid)
6242 return E_INVALIDARG;
6245 * read a STATSTG structure (contains the clsid) from the storage
6247 hRes=IStorage_Stat(pstg,&pstatstg,STATFLAG_DEFAULT);
6250 *pclsid=pstatstg.clsid;
6255 /***********************************************************************
6256 * OleLoadFromStream (OLE32.@)
6258 * This function loads an object from stream
6260 HRESULT WINAPI OleLoadFromStream(IStream *pStm,REFIID iidInterface,void** ppvObj)
6264 LPPERSISTSTREAM xstm;
6266 TRACE("(%p,%s,%p)\n",pStm,debugstr_guid(iidInterface),ppvObj);
6268 res=ReadClassStm(pStm,&clsid);
6269 if (!SUCCEEDED(res))
6271 res=CoCreateInstance(&clsid,NULL,CLSCTX_INPROC_SERVER,iidInterface,ppvObj);
6272 if (!SUCCEEDED(res))
6274 res=IUnknown_QueryInterface((IUnknown*)*ppvObj,&IID_IPersistStream,(LPVOID*)&xstm);
6275 if (!SUCCEEDED(res)) {
6276 IUnknown_Release((IUnknown*)*ppvObj);
6279 res=IPersistStream_Load(xstm,pStm);
6280 IPersistStream_Release(xstm);
6281 /* FIXME: all refcounts ok at this point? I think they should be:
6284 * xstm : 0 (released)
6289 /***********************************************************************
6290 * OleSaveToStream (OLE32.@)
6292 * This function saves an object with the IPersistStream interface on it
6293 * to the specified stream.
6295 HRESULT WINAPI OleSaveToStream(IPersistStream *pPStm,IStream *pStm)
6301 TRACE("(%p,%p)\n",pPStm,pStm);
6303 res=IPersistStream_GetClassID(pPStm,&clsid);
6305 if (SUCCEEDED(res)){
6307 res=WriteClassStm(pStm,&clsid);
6311 res=IPersistStream_Save(pPStm,pStm,TRUE);
6314 TRACE("Finished Save\n");
6318 /****************************************************************************
6319 * This method validate a STGM parameter that can contain the values below
6321 * The stgm modes in 0x0000ffff are not bit masks, but distinct 4 bit values.
6322 * The stgm values contained in 0xffff0000 are bitmasks.
6324 * STGM_DIRECT 0x00000000
6325 * STGM_TRANSACTED 0x00010000
6326 * STGM_SIMPLE 0x08000000
6328 * STGM_READ 0x00000000
6329 * STGM_WRITE 0x00000001
6330 * STGM_READWRITE 0x00000002
6332 * STGM_SHARE_DENY_NONE 0x00000040
6333 * STGM_SHARE_DENY_READ 0x00000030
6334 * STGM_SHARE_DENY_WRITE 0x00000020
6335 * STGM_SHARE_EXCLUSIVE 0x00000010
6337 * STGM_PRIORITY 0x00040000
6338 * STGM_DELETEONRELEASE 0x04000000
6340 * STGM_CREATE 0x00001000
6341 * STGM_CONVERT 0x00020000
6342 * STGM_FAILIFTHERE 0x00000000
6344 * STGM_NOSCRATCH 0x00100000
6345 * STGM_NOSNAPSHOT 0x00200000
6347 static HRESULT validateSTGM(DWORD stgm)
6349 DWORD access = STGM_ACCESS_MODE(stgm);
6350 DWORD share = STGM_SHARE_MODE(stgm);
6351 DWORD create = STGM_CREATE_MODE(stgm);
6353 if (stgm&~STGM_KNOWN_FLAGS)
6355 ERR("unknown flags %08lx\n", stgm);
6363 case STGM_READWRITE:
6371 case STGM_SHARE_DENY_NONE:
6372 case STGM_SHARE_DENY_READ:
6373 case STGM_SHARE_DENY_WRITE:
6374 case STGM_SHARE_EXCLUSIVE:
6383 case STGM_FAILIFTHERE:
6390 * STGM_DIRECT | STGM_TRANSACTED | STGM_SIMPLE
6392 if ( (stgm & STGM_TRANSACTED) && (stgm & STGM_SIMPLE) )
6396 * STGM_CREATE | STGM_CONVERT
6397 * if both are false, STGM_FAILIFTHERE is set to TRUE
6399 if ( create == STGM_CREATE && (stgm & STGM_CONVERT) )
6403 * STGM_NOSCRATCH requires STGM_TRANSACTED
6405 if ( (stgm & STGM_NOSCRATCH) && !(stgm & STGM_TRANSACTED) )
6409 * STGM_NOSNAPSHOT requires STGM_TRANSACTED and
6410 * not STGM_SHARE_EXCLUSIVE or STGM_SHARE_DENY_WRITE`
6412 if ( (stgm & STGM_NOSNAPSHOT) &&
6413 (!(stgm & STGM_TRANSACTED) ||
6414 share == STGM_SHARE_EXCLUSIVE ||
6415 share == STGM_SHARE_DENY_WRITE) )
6421 /****************************************************************************
6422 * GetShareModeFromSTGM
6424 * This method will return a share mode flag from a STGM value.
6425 * The STGM value is assumed valid.
6427 static DWORD GetShareModeFromSTGM(DWORD stgm)
6429 switch (STGM_SHARE_MODE(stgm))
6431 case STGM_SHARE_DENY_NONE:
6432 return FILE_SHARE_READ | FILE_SHARE_WRITE;
6433 case STGM_SHARE_DENY_READ:
6434 return FILE_SHARE_WRITE;
6435 case STGM_SHARE_DENY_WRITE:
6436 return FILE_SHARE_READ;
6437 case STGM_SHARE_EXCLUSIVE:
6440 ERR("Invalid share mode!\n");
6445 /****************************************************************************
6446 * GetAccessModeFromSTGM
6448 * This method will return an access mode flag from a STGM value.
6449 * The STGM value is assumed valid.
6451 static DWORD GetAccessModeFromSTGM(DWORD stgm)
6453 switch (STGM_ACCESS_MODE(stgm))
6456 return GENERIC_READ;
6458 case STGM_READWRITE:
6459 return GENERIC_READ | GENERIC_WRITE;
6461 ERR("Invalid access mode!\n");
6466 /****************************************************************************
6467 * GetCreationModeFromSTGM
6469 * This method will return a creation mode flag from a STGM value.
6470 * The STGM value is assumed valid.
6472 static DWORD GetCreationModeFromSTGM(DWORD stgm)
6474 switch(STGM_CREATE_MODE(stgm))
6477 return CREATE_ALWAYS;
6479 FIXME("STGM_CONVERT not implemented!\n");
6481 case STGM_FAILIFTHERE:
6484 ERR("Invalid create mode!\n");
6490 /*************************************************************************
6491 * OLECONVERT_LoadOLE10 [Internal]
6493 * Loads the OLE10 STREAM to memory
6496 * pOleStream [I] The OLESTREAM
6497 * pData [I] Data Structure for the OLESTREAM Data
6501 * Failure: CONVERT10_E_OLESTREAM_GET for invalid Get
6502 * CONVERT10_E_OLESTREAM_FMT if the OLEID is invalide
6505 * This function is used by OleConvertOLESTREAMToIStorage only.
6507 * Memory allocated for pData must be freed by the caller
6509 static HRESULT OLECONVERT_LoadOLE10(LPOLESTREAM pOleStream, OLECONVERT_OLESTREAM_DATA *pData, BOOL bStrem1)
6512 HRESULT hRes = S_OK;
6516 pData->pData = NULL;
6517 pData->pstrOleObjFileName = (CHAR *) NULL;
6519 for( nTryCnt=0;nTryCnt < max_try; nTryCnt++)
6522 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
6523 if(dwSize != sizeof(pData->dwOleID))
6525 hRes = CONVERT10_E_OLESTREAM_GET;
6527 else if(pData->dwOleID != OLESTREAM_ID)
6529 hRes = CONVERT10_E_OLESTREAM_FMT;
6540 /* Get the TypeID...more info needed for this field */
6541 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
6542 if(dwSize != sizeof(pData->dwTypeID))
6544 hRes = CONVERT10_E_OLESTREAM_GET;
6549 if(pData->dwTypeID != 0)
6551 /* Get the length of the OleTypeName */
6552 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *) &(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
6553 if(dwSize != sizeof(pData->dwOleTypeNameLength))
6555 hRes = CONVERT10_E_OLESTREAM_GET;
6560 if(pData->dwOleTypeNameLength > 0)
6562 /* Get the OleTypeName */
6563 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)pData->strOleTypeName, pData->dwOleTypeNameLength);
6564 if(dwSize != pData->dwOleTypeNameLength)
6566 hRes = CONVERT10_E_OLESTREAM_GET;
6572 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleObjFileNameLength), sizeof(pData->dwOleObjFileNameLength));
6573 if(dwSize != sizeof(pData->dwOleObjFileNameLength))
6575 hRes = CONVERT10_E_OLESTREAM_GET;
6579 if(pData->dwOleObjFileNameLength < 1) /* there is no file name exist */
6580 pData->dwOleObjFileNameLength = sizeof(pData->dwOleObjFileNameLength);
6581 pData->pstrOleObjFileName = HeapAlloc(GetProcessHeap(), 0, pData->dwOleObjFileNameLength);
6582 if(pData->pstrOleObjFileName)
6584 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)(pData->pstrOleObjFileName),pData->dwOleObjFileNameLength);
6585 if(dwSize != pData->dwOleObjFileNameLength)
6587 hRes = CONVERT10_E_OLESTREAM_GET;
6591 hRes = CONVERT10_E_OLESTREAM_GET;
6596 /* Get the Width of the Metafile */
6597 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
6598 if(dwSize != sizeof(pData->dwMetaFileWidth))
6600 hRes = CONVERT10_E_OLESTREAM_GET;
6604 /* Get the Height of the Metafile */
6605 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
6606 if(dwSize != sizeof(pData->dwMetaFileHeight))
6608 hRes = CONVERT10_E_OLESTREAM_GET;
6614 /* Get the Length of the Data */
6615 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
6616 if(dwSize != sizeof(pData->dwDataLength))
6618 hRes = CONVERT10_E_OLESTREAM_GET;
6622 if(hRes == S_OK) /* I don't know what is this 8 byts information is we have to figure out */
6624 if(!bStrem1) /* if it is a second OLE stream data */
6626 pData->dwDataLength -= 8;
6627 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)(pData->strUnknown), sizeof(pData->strUnknown));
6628 if(dwSize != sizeof(pData->strUnknown))
6630 hRes = CONVERT10_E_OLESTREAM_GET;
6636 if(pData->dwDataLength > 0)
6638 pData->pData = HeapAlloc(GetProcessHeap(),0,pData->dwDataLength);
6640 /* Get Data (ex. IStorage, Metafile, or BMP) */
6643 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)pData->pData, pData->dwDataLength);
6644 if(dwSize != pData->dwDataLength)
6646 hRes = CONVERT10_E_OLESTREAM_GET;
6651 hRes = CONVERT10_E_OLESTREAM_GET;
6660 /*************************************************************************
6661 * OLECONVERT_SaveOLE10 [Internal]
6663 * Saves the OLE10 STREAM From memory
6666 * pData [I] Data Structure for the OLESTREAM Data
6667 * pOleStream [I] The OLESTREAM to save
6671 * Failure: CONVERT10_E_OLESTREAM_PUT for invalid Put
6674 * This function is used by OleConvertIStorageToOLESTREAM only.
6677 static HRESULT OLECONVERT_SaveOLE10(OLECONVERT_OLESTREAM_DATA *pData, LPOLESTREAM pOleStream)
6680 HRESULT hRes = S_OK;
6684 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
6685 if(dwSize != sizeof(pData->dwOleID))
6687 hRes = CONVERT10_E_OLESTREAM_PUT;
6692 /* Set the TypeID */
6693 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
6694 if(dwSize != sizeof(pData->dwTypeID))
6696 hRes = CONVERT10_E_OLESTREAM_PUT;
6700 if(pData->dwOleID == OLESTREAM_ID && pData->dwTypeID != 0 && hRes == S_OK)
6702 /* Set the Length of the OleTypeName */
6703 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
6704 if(dwSize != sizeof(pData->dwOleTypeNameLength))
6706 hRes = CONVERT10_E_OLESTREAM_PUT;
6711 if(pData->dwOleTypeNameLength > 0)
6713 /* Set the OleTypeName */
6714 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *) pData->strOleTypeName, pData->dwOleTypeNameLength);
6715 if(dwSize != pData->dwOleTypeNameLength)
6717 hRes = CONVERT10_E_OLESTREAM_PUT;
6724 /* Set the width of the Metafile */
6725 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
6726 if(dwSize != sizeof(pData->dwMetaFileWidth))
6728 hRes = CONVERT10_E_OLESTREAM_PUT;
6734 /* Set the height of the Metafile */
6735 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
6736 if(dwSize != sizeof(pData->dwMetaFileHeight))
6738 hRes = CONVERT10_E_OLESTREAM_PUT;
6744 /* Set the length of the Data */
6745 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
6746 if(dwSize != sizeof(pData->dwDataLength))
6748 hRes = CONVERT10_E_OLESTREAM_PUT;
6754 if(pData->dwDataLength > 0)
6756 /* Set the Data (eg. IStorage, Metafile, Bitmap) */
6757 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *) pData->pData, pData->dwDataLength);
6758 if(dwSize != pData->dwDataLength)
6760 hRes = CONVERT10_E_OLESTREAM_PUT;
6768 /*************************************************************************
6769 * OLECONVERT_GetOLE20FromOLE10[Internal]
6771 * This function copies OLE10 Data (the IStorage in the OLESTREAM) to disk,
6772 * opens it, and copies the content to the dest IStorage for
6773 * OleConvertOLESTREAMToIStorage
6777 * pDestStorage [I] The IStorage to copy the data to
6778 * pBuffer [I] Buffer that contains the IStorage from the OLESTREAM
6779 * nBufferLength [I] The size of the buffer
6788 static void OLECONVERT_GetOLE20FromOLE10(LPSTORAGE pDestStorage, BYTE *pBuffer, DWORD nBufferLength)
6792 IStorage *pTempStorage;
6793 DWORD dwNumOfBytesWritten;
6794 WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
6795 static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
6797 /* Create a temp File */
6798 GetTempPathW(MAX_PATH, wstrTempDir);
6799 GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
6800 hFile = CreateFileW(wstrTempFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
6802 if(hFile != INVALID_HANDLE_VALUE)
6804 /* Write IStorage Data to File */
6805 WriteFile(hFile, pBuffer, nBufferLength, &dwNumOfBytesWritten, NULL);
6808 /* Open and copy temp storage to the Dest Storage */
6809 hRes = StgOpenStorage(wstrTempFile, NULL, STGM_READ, NULL, 0, &pTempStorage);
6812 hRes = StorageImpl_CopyTo(pTempStorage, 0, NULL, NULL, pDestStorage);
6813 StorageBaseImpl_Release(pTempStorage);
6815 DeleteFileW(wstrTempFile);
6820 /*************************************************************************
6821 * OLECONVERT_WriteOLE20ToBuffer [Internal]
6823 * Saves the OLE10 STREAM From memory
6826 * pStorage [I] The Src IStorage to copy
6827 * pData [I] The Dest Memory to write to.
6830 * The size in bytes allocated for pData
6833 * Memory allocated for pData must be freed by the caller
6835 * Used by OleConvertIStorageToOLESTREAM only.
6838 static DWORD OLECONVERT_WriteOLE20ToBuffer(LPSTORAGE pStorage, BYTE **pData)
6842 DWORD nDataLength = 0;
6843 IStorage *pTempStorage;
6844 WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
6845 static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
6849 /* Create temp Storage */
6850 GetTempPathW(MAX_PATH, wstrTempDir);
6851 GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
6852 hRes = StgCreateDocfile(wstrTempFile, STGM_CREATE | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &pTempStorage);
6856 /* Copy Src Storage to the Temp Storage */
6857 StorageImpl_CopyTo(pStorage, 0, NULL, NULL, pTempStorage);
6858 StorageBaseImpl_Release(pTempStorage);
6860 /* Open Temp Storage as a file and copy to memory */
6861 hFile = CreateFileW(wstrTempFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
6862 if(hFile != INVALID_HANDLE_VALUE)
6864 nDataLength = GetFileSize(hFile, NULL);
6865 *pData = HeapAlloc(GetProcessHeap(),0,nDataLength);
6866 ReadFile(hFile, *pData, nDataLength, &nDataLength, 0);
6869 DeleteFileW(wstrTempFile);
6874 /*************************************************************************
6875 * OLECONVERT_CreateOleStream [Internal]
6877 * Creates the "\001OLE" stream in the IStorage if necessary.
6880 * pStorage [I] Dest storage to create the stream in
6886 * This function is used by OleConvertOLESTREAMToIStorage only.
6888 * This stream is still unknown, MS Word seems to have extra data
6889 * but since the data is stored in the OLESTREAM there should be
6890 * no need to recreate the stream. If the stream is manually
6891 * deleted it will create it with this default data.
6894 void OLECONVERT_CreateOleStream(LPSTORAGE pStorage)
6898 static const WCHAR wstrStreamName[] = {1,'O', 'l', 'e', 0};
6899 BYTE pOleStreamHeader [] =
6901 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
6902 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
6903 0x00, 0x00, 0x00, 0x00
6906 /* Create stream if not present */
6907 hRes = IStorage_CreateStream(pStorage, wstrStreamName,
6908 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
6912 /* Write default Data */
6913 hRes = IStream_Write(pStream, pOleStreamHeader, sizeof(pOleStreamHeader), NULL);
6914 IStream_Release(pStream);
6918 /* write a string to a stream, preceded by its length */
6919 static HRESULT STREAM_WriteString( IStream *stm, LPCWSTR string )
6926 len = WideCharToMultiByte( CP_ACP, 0, string, -1, NULL, 0, NULL, NULL);
6927 r = IStream_Write( stm, &len, sizeof(len), NULL);
6932 str = CoTaskMemAlloc( len );
6933 WideCharToMultiByte( CP_ACP, 0, string, -1, str, len, NULL, NULL);
6934 r = IStream_Write( stm, str, len, NULL);
6935 CoTaskMemFree( str );
6939 /* read a string preceded by its length from a stream */
6940 static HRESULT STREAM_ReadString( IStream *stm, LPWSTR *string )
6943 DWORD len, count = 0;
6947 r = IStream_Read( stm, &len, sizeof(len), &count );
6950 if( count != sizeof(len) )
6951 return E_OUTOFMEMORY;
6953 TRACE("%ld bytes\n",len);
6955 str = CoTaskMemAlloc( len );
6957 return E_OUTOFMEMORY;
6959 r = IStream_Read( stm, str, len, &count );
6964 CoTaskMemFree( str );
6965 return E_OUTOFMEMORY;
6968 TRACE("Read string %s\n",debugstr_an(str,len));
6970 len = MultiByteToWideChar( CP_ACP, 0, str, count, NULL, 0 );
6971 wstr = CoTaskMemAlloc( (len + 1)*sizeof (WCHAR) );
6973 MultiByteToWideChar( CP_ACP, 0, str, count, wstr, len );
6974 CoTaskMemFree( str );
6982 static HRESULT STORAGE_WriteCompObj( LPSTORAGE pstg, CLSID *clsid,
6983 LPCWSTR lpszUserType, LPCWSTR szClipName, LPCWSTR szProgIDName )
6987 static const WCHAR szwStreamName[] = {1, 'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
6989 static const BYTE unknown1[12] =
6990 { 0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00,
6991 0xFF, 0xFF, 0xFF, 0xFF};
6992 static const BYTE unknown2[16] =
6993 { 0xF4, 0x39, 0xB2, 0x71, 0x00, 0x00, 0x00, 0x00,
6994 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
6996 TRACE("%p %s %s %s %s\n", pstg, debugstr_guid(clsid),
6997 debugstr_w(lpszUserType), debugstr_w(szClipName),
6998 debugstr_w(szProgIDName));
7000 /* Create a CompObj stream if it doesn't exist */
7001 r = IStorage_CreateStream(pstg, szwStreamName,
7002 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pstm );
7006 /* Write CompObj Structure to stream */
7007 r = IStream_Write(pstm, unknown1, sizeof(unknown1), NULL);
7009 if( SUCCEEDED( r ) )
7010 r = WriteClassStm( pstm, clsid );
7012 if( SUCCEEDED( r ) )
7013 r = STREAM_WriteString( pstm, lpszUserType );
7014 if( SUCCEEDED( r ) )
7015 r = STREAM_WriteString( pstm, szClipName );
7016 if( SUCCEEDED( r ) )
7017 r = STREAM_WriteString( pstm, szProgIDName );
7018 if( SUCCEEDED( r ) )
7019 r = IStream_Write(pstm, unknown2, sizeof(unknown2), NULL);
7021 IStream_Release( pstm );
7026 /***********************************************************************
7027 * WriteFmtUserTypeStg (OLE32.@)
7029 HRESULT WINAPI WriteFmtUserTypeStg(
7030 LPSTORAGE pstg, CLIPFORMAT cf, LPOLESTR lpszUserType)
7033 WCHAR szwClipName[0x40];
7034 CLSID clsid = CLSID_NULL;
7035 LPWSTR wstrProgID = NULL;
7038 TRACE("(%p,%x,%s)\n",pstg,cf,debugstr_w(lpszUserType));
7040 /* get the clipboard format name */
7041 n = GetClipboardFormatNameW( cf, szwClipName, sizeof(szwClipName) );
7044 TRACE("Clipboard name is %s\n", debugstr_w(szwClipName));
7046 /* FIXME: There's room to save a CLSID and its ProgID, but
7047 the CLSID is not looked up in the registry and in all the
7048 tests I wrote it was CLSID_NULL. Where does it come from?
7051 /* get the real program ID. This may fail, but that's fine */
7052 ProgIDFromCLSID(&clsid, &wstrProgID);
7054 TRACE("progid is %s\n",debugstr_w(wstrProgID));
7056 r = STORAGE_WriteCompObj( pstg, &clsid,
7057 lpszUserType, szwClipName, wstrProgID );
7059 CoTaskMemFree(wstrProgID);
7065 /******************************************************************************
7066 * ReadFmtUserTypeStg [OLE32.@]
7068 HRESULT WINAPI ReadFmtUserTypeStg (LPSTORAGE pstg, CLIPFORMAT* pcf, LPOLESTR* lplpszUserType)
7072 static const WCHAR szCompObj[] = { 1, 'C','o','m','p','O','b','j', 0 };
7073 unsigned char unknown1[12];
7074 unsigned char unknown2[16];
7076 LPWSTR szProgIDName = NULL, szCLSIDName = NULL, szOleTypeName = NULL;
7079 TRACE("(%p,%p,%p)\n", pstg, pcf, lplpszUserType);
7081 r = IStorage_OpenStream( pstg, szCompObj, NULL,
7082 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
7085 WARN("Failed to open stream r = %08lx\n", r);
7089 /* read the various parts of the structure */
7090 r = IStream_Read( stm, unknown1, sizeof(unknown1), &count );
7091 if( FAILED( r ) || ( count != sizeof(unknown1) ) )
7093 r = ReadClassStm( stm, &clsid );
7097 r = STREAM_ReadString( stm, &szCLSIDName );
7101 r = STREAM_ReadString( stm, &szOleTypeName );
7105 r = STREAM_ReadString( stm, &szProgIDName );
7109 r = IStream_Read( stm, unknown2, sizeof(unknown2), &count );
7110 if( FAILED( r ) || ( count != sizeof(unknown2) ) )
7113 /* ok, success... now we just need to store what we found */
7115 *pcf = RegisterClipboardFormatW( szOleTypeName );
7116 CoTaskMemFree( szOleTypeName );
7118 if( lplpszUserType )
7119 *lplpszUserType = szCLSIDName;
7120 CoTaskMemFree( szProgIDName );
7123 IStream_Release( stm );
7129 /*************************************************************************
7130 * OLECONVERT_CreateCompObjStream [Internal]
7132 * Creates a "\001CompObj" is the destination IStorage if necessary.
7135 * pStorage [I] The dest IStorage to create the CompObj Stream
7137 * strOleTypeName [I] The ProgID
7141 * Failure: REGDB_E_CLASSNOTREG if cannot reconstruct the stream
7144 * This function is used by OleConvertOLESTREAMToIStorage only.
7146 * The stream data is stored in the OLESTREAM and there should be
7147 * no need to recreate the stream. If the stream is manually
7148 * deleted it will attempt to create it by querying the registry.
7152 HRESULT OLECONVERT_CreateCompObjStream(LPSTORAGE pStorage, LPCSTR strOleTypeName)
7155 HRESULT hStorageRes, hRes = S_OK;
7156 OLECONVERT_ISTORAGE_COMPOBJ IStorageCompObj;
7157 static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7158 WCHAR bufferW[OLESTREAM_MAX_STR_LEN];
7160 BYTE pCompObjUnknown1[] = {0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};
7161 BYTE pCompObjUnknown2[] = {0xF4, 0x39, 0xB2, 0x71};
7163 /* Initialize the CompObj structure */
7164 memset(&IStorageCompObj, 0, sizeof(IStorageCompObj));
7165 memcpy(&(IStorageCompObj.byUnknown1), pCompObjUnknown1, sizeof(pCompObjUnknown1));
7166 memcpy(&(IStorageCompObj.byUnknown2), pCompObjUnknown2, sizeof(pCompObjUnknown2));
7169 /* Create a CompObj stream if it doesn't exist */
7170 hStorageRes = IStorage_CreateStream(pStorage, wstrStreamName,
7171 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
7172 if(hStorageRes == S_OK)
7174 /* copy the OleTypeName to the compobj struct */
7175 IStorageCompObj.dwOleTypeNameLength = strlen(strOleTypeName)+1;
7176 strcpy(IStorageCompObj.strOleTypeName, strOleTypeName);
7178 /* copy the OleTypeName to the compobj struct */
7179 /* Note: in the test made, these were Identical */
7180 IStorageCompObj.dwProgIDNameLength = strlen(strOleTypeName)+1;
7181 strcpy(IStorageCompObj.strProgIDName, strOleTypeName);
7184 MultiByteToWideChar( CP_ACP, 0, IStorageCompObj.strProgIDName, -1,
7185 bufferW, OLESTREAM_MAX_STR_LEN );
7186 hRes = CLSIDFromProgID(bufferW, &(IStorageCompObj.clsid));
7192 /* Get the CLSID Default Name from the Registry */
7193 hErr = RegOpenKeyA(HKEY_CLASSES_ROOT, IStorageCompObj.strProgIDName, &hKey);
7194 if(hErr == ERROR_SUCCESS)
7196 char strTemp[OLESTREAM_MAX_STR_LEN];
7197 IStorageCompObj.dwCLSIDNameLength = OLESTREAM_MAX_STR_LEN;
7198 hErr = RegQueryValueA(hKey, NULL, strTemp, (LONG*) &(IStorageCompObj.dwCLSIDNameLength));
7199 if(hErr == ERROR_SUCCESS)
7201 strcpy(IStorageCompObj.strCLSIDName, strTemp);
7207 /* Write CompObj Structure to stream */
7208 hRes = IStream_Write(pStream, IStorageCompObj.byUnknown1, sizeof(IStorageCompObj.byUnknown1), NULL);
7210 WriteClassStm(pStream,&(IStorageCompObj.clsid));
7212 hRes = IStream_Write(pStream, &(IStorageCompObj.dwCLSIDNameLength), sizeof(IStorageCompObj.dwCLSIDNameLength), NULL);
7213 if(IStorageCompObj.dwCLSIDNameLength > 0)
7215 hRes = IStream_Write(pStream, IStorageCompObj.strCLSIDName, IStorageCompObj.dwCLSIDNameLength, NULL);
7217 hRes = IStream_Write(pStream, &(IStorageCompObj.dwOleTypeNameLength) , sizeof(IStorageCompObj.dwOleTypeNameLength), NULL);
7218 if(IStorageCompObj.dwOleTypeNameLength > 0)
7220 hRes = IStream_Write(pStream, IStorageCompObj.strOleTypeName , IStorageCompObj.dwOleTypeNameLength, NULL);
7222 hRes = IStream_Write(pStream, &(IStorageCompObj.dwProgIDNameLength) , sizeof(IStorageCompObj.dwProgIDNameLength), NULL);
7223 if(IStorageCompObj.dwProgIDNameLength > 0)
7225 hRes = IStream_Write(pStream, IStorageCompObj.strProgIDName , IStorageCompObj.dwProgIDNameLength, NULL);
7227 hRes = IStream_Write(pStream, IStorageCompObj.byUnknown2 , sizeof(IStorageCompObj.byUnknown2), NULL);
7228 IStream_Release(pStream);
7234 /*************************************************************************
7235 * OLECONVERT_CreateOlePresStream[Internal]
7237 * Creates the "\002OlePres000" Stream with the Metafile data
7240 * pStorage [I] The dest IStorage to create \002OLEPres000 stream in.
7241 * dwExtentX [I] Width of the Metafile
7242 * dwExtentY [I] Height of the Metafile
7243 * pData [I] Metafile data
7244 * dwDataLength [I] Size of the Metafile data
7248 * Failure: CONVERT10_E_OLESTREAM_PUT for invalid Put
7251 * This function is used by OleConvertOLESTREAMToIStorage only.
7254 static void OLECONVERT_CreateOlePresStream(LPSTORAGE pStorage, DWORD dwExtentX, DWORD dwExtentY , BYTE *pData, DWORD dwDataLength)
7258 static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
7259 BYTE pOlePresStreamHeader [] =
7261 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00,
7262 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
7263 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
7264 0x00, 0x00, 0x00, 0x00
7267 BYTE pOlePresStreamHeaderEmpty [] =
7269 0x00, 0x00, 0x00, 0x00,
7270 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
7271 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
7272 0x00, 0x00, 0x00, 0x00
7275 /* Create the OlePres000 Stream */
7276 hRes = IStorage_CreateStream(pStorage, wstrStreamName,
7277 STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
7282 OLECONVERT_ISTORAGE_OLEPRES OlePres;
7284 memset(&OlePres, 0, sizeof(OlePres));
7285 /* Do we have any metafile data to save */
7286 if(dwDataLength > 0)
7288 memcpy(OlePres.byUnknown1, pOlePresStreamHeader, sizeof(pOlePresStreamHeader));
7289 nHeaderSize = sizeof(pOlePresStreamHeader);
7293 memcpy(OlePres.byUnknown1, pOlePresStreamHeaderEmpty, sizeof(pOlePresStreamHeaderEmpty));
7294 nHeaderSize = sizeof(pOlePresStreamHeaderEmpty);
7296 /* Set width and height of the metafile */
7297 OlePres.dwExtentX = dwExtentX;
7298 OlePres.dwExtentY = -dwExtentY;
7300 /* Set Data and Length */
7301 if(dwDataLength > sizeof(METAFILEPICT16))
7303 OlePres.dwSize = dwDataLength - sizeof(METAFILEPICT16);
7304 OlePres.pData = &(pData[8]);
7306 /* Save OlePres000 Data to Stream */
7307 hRes = IStream_Write(pStream, OlePres.byUnknown1, nHeaderSize, NULL);
7308 hRes = IStream_Write(pStream, &(OlePres.dwExtentX), sizeof(OlePres.dwExtentX), NULL);
7309 hRes = IStream_Write(pStream, &(OlePres.dwExtentY), sizeof(OlePres.dwExtentY), NULL);
7310 hRes = IStream_Write(pStream, &(OlePres.dwSize), sizeof(OlePres.dwSize), NULL);
7311 if(OlePres.dwSize > 0)
7313 hRes = IStream_Write(pStream, OlePres.pData, OlePres.dwSize, NULL);
7315 IStream_Release(pStream);
7319 /*************************************************************************
7320 * OLECONVERT_CreateOle10NativeStream [Internal]
7322 * Creates the "\001Ole10Native" Stream (should contain a BMP)
7325 * pStorage [I] Dest storage to create the stream in
7326 * pData [I] Ole10 Native Data (ex. bmp)
7327 * dwDataLength [I] Size of the Ole10 Native Data
7333 * This function is used by OleConvertOLESTREAMToIStorage only.
7335 * Might need to verify the data and return appropriate error message
7338 static void OLECONVERT_CreateOle10NativeStream(LPSTORAGE pStorage, BYTE *pData, DWORD dwDataLength)
7342 static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7344 /* Create the Ole10Native Stream */
7345 hRes = IStorage_CreateStream(pStorage, wstrStreamName,
7346 STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
7350 /* Write info to stream */
7351 hRes = IStream_Write(pStream, &dwDataLength, sizeof(dwDataLength), NULL);
7352 hRes = IStream_Write(pStream, pData, dwDataLength, NULL);
7353 IStream_Release(pStream);
7358 /*************************************************************************
7359 * OLECONVERT_GetOLE10ProgID [Internal]
7361 * Finds the ProgID (or OleTypeID) from the IStorage
7364 * pStorage [I] The Src IStorage to get the ProgID
7365 * strProgID [I] the ProgID string to get
7366 * dwSize [I] the size of the string
7370 * Failure: REGDB_E_CLASSNOTREG if cannot reconstruct the stream
7373 * This function is used by OleConvertIStorageToOLESTREAM only.
7377 static HRESULT OLECONVERT_GetOLE10ProgID(LPSTORAGE pStorage, char *strProgID, DWORD *dwSize)
7381 LARGE_INTEGER iSeekPos;
7382 OLECONVERT_ISTORAGE_COMPOBJ CompObj;
7383 static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7385 /* Open the CompObj Stream */
7386 hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7387 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream );
7391 /*Get the OleType from the CompObj Stream */
7392 iSeekPos.u.LowPart = sizeof(CompObj.byUnknown1) + sizeof(CompObj.clsid);
7393 iSeekPos.u.HighPart = 0;
7395 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
7396 IStream_Read(pStream, &CompObj.dwCLSIDNameLength, sizeof(CompObj.dwCLSIDNameLength), NULL);
7397 iSeekPos.u.LowPart = CompObj.dwCLSIDNameLength;
7398 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);
7399 IStream_Read(pStream, &CompObj.dwOleTypeNameLength, sizeof(CompObj.dwOleTypeNameLength), NULL);
7400 iSeekPos.u.LowPart = CompObj.dwOleTypeNameLength;
7401 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);
7403 IStream_Read(pStream, dwSize, sizeof(*dwSize), NULL);
7406 IStream_Read(pStream, strProgID, *dwSize, NULL);
7408 IStream_Release(pStream);
7413 LPOLESTR wstrProgID;
7415 /* Get the OleType from the registry */
7416 REFCLSID clsid = &(stat.clsid);
7417 IStorage_Stat(pStorage, &stat, STATFLAG_NONAME);
7418 hRes = ProgIDFromCLSID(clsid, &wstrProgID);
7421 *dwSize = WideCharToMultiByte(CP_ACP, 0, wstrProgID, -1, strProgID, *dwSize, NULL, FALSE);
7428 /*************************************************************************
7429 * OLECONVERT_GetOle10PresData [Internal]
7431 * Converts IStorage "/001Ole10Native" stream to a OLE10 Stream
7434 * pStorage [I] Src IStroage
7435 * pOleStream [I] Dest OleStream Mem Struct
7441 * This function is used by OleConvertIStorageToOLESTREAM only.
7443 * Memory allocated for pData must be freed by the caller
7447 static void OLECONVERT_GetOle10PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
7452 static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7454 /* Initialize Default data for OLESTREAM */
7455 pOleStreamData[0].dwOleID = OLESTREAM_ID;
7456 pOleStreamData[0].dwTypeID = 2;
7457 pOleStreamData[1].dwOleID = OLESTREAM_ID;
7458 pOleStreamData[1].dwTypeID = 0;
7459 pOleStreamData[0].dwMetaFileWidth = 0;
7460 pOleStreamData[0].dwMetaFileHeight = 0;
7461 pOleStreamData[0].pData = NULL;
7462 pOleStreamData[1].pData = NULL;
7464 /* Open Ole10Native Stream */
7465 hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7466 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream );
7470 /* Read Size and Data */
7471 IStream_Read(pStream, &(pOleStreamData->dwDataLength), sizeof(pOleStreamData->dwDataLength), NULL);
7472 if(pOleStreamData->dwDataLength > 0)
7474 pOleStreamData->pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData->dwDataLength);
7475 IStream_Read(pStream, pOleStreamData->pData, pOleStreamData->dwDataLength, NULL);
7477 IStream_Release(pStream);
7483 /*************************************************************************
7484 * OLECONVERT_GetOle20PresData[Internal]
7486 * Converts IStorage "/002OlePres000" stream to a OLE10 Stream
7489 * pStorage [I] Src IStroage
7490 * pOleStreamData [I] Dest OleStream Mem Struct
7496 * This function is used by OleConvertIStorageToOLESTREAM only.
7498 * Memory allocated for pData must be freed by the caller
7500 static void OLECONVERT_GetOle20PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
7504 OLECONVERT_ISTORAGE_OLEPRES olePress;
7505 static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
7507 /* Initialize Default data for OLESTREAM */
7508 pOleStreamData[0].dwOleID = OLESTREAM_ID;
7509 pOleStreamData[0].dwTypeID = 2;
7510 pOleStreamData[0].dwMetaFileWidth = 0;
7511 pOleStreamData[0].dwMetaFileHeight = 0;
7512 pOleStreamData[0].dwDataLength = OLECONVERT_WriteOLE20ToBuffer(pStorage, &(pOleStreamData[0].pData));
7513 pOleStreamData[1].dwOleID = OLESTREAM_ID;
7514 pOleStreamData[1].dwTypeID = 0;
7515 pOleStreamData[1].dwOleTypeNameLength = 0;
7516 pOleStreamData[1].strOleTypeName[0] = 0;
7517 pOleStreamData[1].dwMetaFileWidth = 0;
7518 pOleStreamData[1].dwMetaFileHeight = 0;
7519 pOleStreamData[1].pData = NULL;
7520 pOleStreamData[1].dwDataLength = 0;
7523 /* Open OlePress000 stream */
7524 hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7525 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream );
7528 LARGE_INTEGER iSeekPos;
7529 METAFILEPICT16 MetaFilePict;
7530 static const char strMetafilePictName[] = "METAFILEPICT";
7532 /* Set the TypeID for a Metafile */
7533 pOleStreamData[1].dwTypeID = 5;
7535 /* Set the OleTypeName to Metafile */
7536 pOleStreamData[1].dwOleTypeNameLength = strlen(strMetafilePictName) +1;
7537 strcpy(pOleStreamData[1].strOleTypeName, strMetafilePictName);
7539 iSeekPos.u.HighPart = 0;
7540 iSeekPos.u.LowPart = sizeof(olePress.byUnknown1);
7542 /* Get Presentation Data */
7543 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
7544 IStream_Read(pStream, &(olePress.dwExtentX), sizeof(olePress.dwExtentX), NULL);
7545 IStream_Read(pStream, &(olePress.dwExtentY), sizeof(olePress.dwExtentY), NULL);
7546 IStream_Read(pStream, &(olePress.dwSize), sizeof(olePress.dwSize), NULL);
7548 /*Set width and Height */
7549 pOleStreamData[1].dwMetaFileWidth = olePress.dwExtentX;
7550 pOleStreamData[1].dwMetaFileHeight = -olePress.dwExtentY;
7551 if(olePress.dwSize > 0)
7554 pOleStreamData[1].dwDataLength = olePress.dwSize + sizeof(METAFILEPICT16);
7556 /* Set MetaFilePict struct */
7557 MetaFilePict.mm = 8;
7558 MetaFilePict.xExt = olePress.dwExtentX;
7559 MetaFilePict.yExt = olePress.dwExtentY;
7560 MetaFilePict.hMF = 0;
7562 /* Get Metafile Data */
7563 pOleStreamData[1].pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData[1].dwDataLength);
7564 memcpy(pOleStreamData[1].pData, &MetaFilePict, sizeof(MetaFilePict));
7565 IStream_Read(pStream, &(pOleStreamData[1].pData[sizeof(MetaFilePict)]), pOleStreamData[1].dwDataLength-sizeof(METAFILEPICT16), NULL);
7567 IStream_Release(pStream);
7571 /*************************************************************************
7572 * OleConvertOLESTREAMToIStorage [OLE32.@]
7577 * DVTARGETDEVICE paramenter is not handled
7578 * Still unsure of some mem fields for OLE 10 Stream
7579 * Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
7580 * and "\001OLE" streams
7583 HRESULT WINAPI OleConvertOLESTREAMToIStorage (
7584 LPOLESTREAM pOleStream,
7586 const DVTARGETDEVICE* ptd)
7590 OLECONVERT_OLESTREAM_DATA pOleStreamData[2];
7592 memset(pOleStreamData, 0, sizeof(pOleStreamData));
7596 FIXME("DVTARGETDEVICE is not NULL, unhandled parameter\n");
7599 if(pstg == NULL || pOleStream == NULL)
7601 hRes = E_INVALIDARG;
7606 /* Load the OLESTREAM to Memory */
7607 hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[0], TRUE);
7612 /* Load the OLESTREAM to Memory (part 2)*/
7613 hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[1], FALSE);
7619 if(pOleStreamData[0].dwDataLength > sizeof(STORAGE_magic))
7621 /* Do we have the IStorage Data in the OLESTREAM */
7622 if(memcmp(pOleStreamData[0].pData, STORAGE_magic, sizeof(STORAGE_magic)) ==0)
7624 OLECONVERT_GetOLE20FromOLE10(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
7625 OLECONVERT_CreateOlePresStream(pstg, pOleStreamData[1].dwMetaFileWidth, pOleStreamData[1].dwMetaFileHeight, pOleStreamData[1].pData, pOleStreamData[1].dwDataLength);
7629 /* It must be an original OLE 1.0 source */
7630 OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
7635 /* It must be an original OLE 1.0 source */
7636 OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
7639 /* Create CompObj Stream if necessary */
7640 hRes = OLECONVERT_CreateCompObjStream(pstg, pOleStreamData[0].strOleTypeName);
7643 /*Create the Ole Stream if necessary */
7644 OLECONVERT_CreateOleStream(pstg);
7649 /* Free allocated memory */
7650 for(i=0; i < 2; i++)
7652 HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
7653 HeapFree(GetProcessHeap(),0,pOleStreamData[i].pstrOleObjFileName);
7654 pOleStreamData[i].pstrOleObjFileName = NULL;
7659 /*************************************************************************
7660 * OleConvertIStorageToOLESTREAM [OLE32.@]
7667 * Still unsure of some mem fields for OLE 10 Stream
7668 * Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
7669 * and "\001OLE" streams.
7672 HRESULT WINAPI OleConvertIStorageToOLESTREAM (
7674 LPOLESTREAM pOleStream)
7677 HRESULT hRes = S_OK;
7679 OLECONVERT_OLESTREAM_DATA pOleStreamData[2];
7680 static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7683 memset(pOleStreamData, 0, sizeof(pOleStreamData));
7685 if(pstg == NULL || pOleStream == NULL)
7687 hRes = E_INVALIDARG;
7691 /* Get the ProgID */
7692 pOleStreamData[0].dwOleTypeNameLength = OLESTREAM_MAX_STR_LEN;
7693 hRes = OLECONVERT_GetOLE10ProgID(pstg, pOleStreamData[0].strOleTypeName, &(pOleStreamData[0].dwOleTypeNameLength));
7697 /* Was it originally Ole10 */
7698 hRes = IStorage_OpenStream(pstg, wstrStreamName, 0, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream);
7701 IStream_Release(pStream);
7702 /* Get Presentation Data for Ole10Native */
7703 OLECONVERT_GetOle10PresData(pstg, pOleStreamData);
7707 /* Get Presentation Data (OLE20) */
7708 OLECONVERT_GetOle20PresData(pstg, pOleStreamData);
7711 /* Save OLESTREAM */
7712 hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[0]), pOleStream);
7715 hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[1]), pOleStream);
7720 /* Free allocated memory */
7721 for(i=0; i < 2; i++)
7723 HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
7729 /***********************************************************************
7730 * GetConvertStg (OLE32.@)
7732 HRESULT WINAPI GetConvertStg(IStorage *stg) {
7733 FIXME("unimplemented stub!\n");
7737 /******************************************************************************
7738 * StgIsStorageFile [OLE32.@]
7741 StgIsStorageFile(LPCOLESTR fn)
7747 TRACE("(\'%s\')\n", debugstr_w(fn));
7748 hf = CreateFileW(fn, GENERIC_READ,
7749 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
7750 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
7752 if (hf == INVALID_HANDLE_VALUE)
7753 return STG_E_FILENOTFOUND;
7755 if (!ReadFile(hf, magic, 8, &bytes_read, NULL))
7757 WARN(" unable to read file\n");
7764 if (bytes_read != 8) {
7765 WARN(" too short\n");
7769 if (!memcmp(magic,STORAGE_magic,8)) {
7774 WARN(" -> Invalid header.\n");