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 Destroying the old property we must zero its 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 tweak 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 its 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 its 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 * Strategy: This implementation is built this way for simplicity not for speed.
1656 * I always delete the topmost 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 resides in the usage of another
1660 * enumeration strategy 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 its 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 its 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 its 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 (memory only)
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;
3005 * Get a pointer to the big block of data containing the header.
3007 headerBigBlock = StorageImpl_GetROBigBlock(This, -1);
3010 * Extract the information from the header.
3012 if (headerBigBlock!=0)
3015 * Check for the "magic number" signature and return an error if it is not
3018 if (memcmp(headerBigBlock, STORAGE_oldmagic, sizeof(STORAGE_oldmagic))==0)
3020 StorageImpl_ReleaseBigBlock(This, headerBigBlock);
3021 return STG_E_OLDFORMAT;
3024 if (memcmp(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic))!=0)
3026 StorageImpl_ReleaseBigBlock(This, headerBigBlock);
3027 return STG_E_INVALIDHEADER;
3030 StorageUtl_ReadWord(
3032 OFFSET_BIGBLOCKSIZEBITS,
3033 &This->bigBlockSizeBits);
3035 StorageUtl_ReadWord(
3037 OFFSET_SMALLBLOCKSIZEBITS,
3038 &This->smallBlockSizeBits);
3040 StorageUtl_ReadDWord(
3042 OFFSET_BBDEPOTCOUNT,
3043 &This->bigBlockDepotCount);
3045 StorageUtl_ReadDWord(
3047 OFFSET_ROOTSTARTBLOCK,
3048 &This->rootStartBlock);
3050 StorageUtl_ReadDWord(
3052 OFFSET_SBDEPOTSTART,
3053 &This->smallBlockDepotStart);
3055 StorageUtl_ReadDWord(
3057 OFFSET_EXTBBDEPOTSTART,
3058 &This->extBigBlockDepotStart);
3060 StorageUtl_ReadDWord(
3062 OFFSET_EXTBBDEPOTCOUNT,
3063 &This->extBigBlockDepotCount);
3065 for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
3067 StorageUtl_ReadDWord(
3069 OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
3070 &(This->bigBlockDepotStart[index]));
3074 * Make the bitwise arithmetic to get the size of the blocks in bytes.
3078 This->bigBlockSize = 0x000000001 << (DWORD)This->bigBlockSizeBits;
3079 This->smallBlockSize = 0x000000001 << (DWORD)This->smallBlockSizeBits;
3083 This->bigBlockSize = 0x000000001 >> (DWORD)This->bigBlockSizeBits;
3084 This->smallBlockSize = 0x000000001 >> (DWORD)This->smallBlockSizeBits;
3088 * Right now, the code is making some assumptions about the size of the
3089 * blocks, just make sure they are what we're expecting.
3091 if (This->bigBlockSize != DEF_BIG_BLOCK_SIZE ||
3092 This->smallBlockSize != DEF_SMALL_BLOCK_SIZE)
3094 WARN("Broken OLE storage file\n");
3095 hr = STG_E_INVALIDHEADER;
3101 * Release the block.
3103 StorageImpl_ReleaseBigBlock(This, headerBigBlock);
3109 /******************************************************************************
3110 * Storage32Impl_SaveFileHeader
3112 * This method will save to the file the header, i.e. big block -1.
3114 void StorageImpl_SaveFileHeader(
3117 BYTE headerBigBlock[BIG_BLOCK_SIZE];
3122 * Get a pointer to the big block of data containing the header.
3124 success = StorageImpl_ReadBigBlock(This, -1, headerBigBlock);
3127 * If the block read failed, the file is probably new.
3132 * Initialize for all unknown fields.
3134 memset(headerBigBlock, 0, BIG_BLOCK_SIZE);
3137 * Initialize the magic number.
3139 memcpy(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic));
3142 * And a bunch of things we don't know what they mean
3144 StorageUtl_WriteWord(headerBigBlock, 0x18, 0x3b);
3145 StorageUtl_WriteWord(headerBigBlock, 0x1a, 0x3);
3146 StorageUtl_WriteWord(headerBigBlock, 0x1c, (WORD)-2);
3147 StorageUtl_WriteDWord(headerBigBlock, 0x38, (DWORD)0x1000);
3151 * Write the information to the header.
3153 StorageUtl_WriteWord(
3155 OFFSET_BIGBLOCKSIZEBITS,
3156 This->bigBlockSizeBits);
3158 StorageUtl_WriteWord(
3160 OFFSET_SMALLBLOCKSIZEBITS,
3161 This->smallBlockSizeBits);
3163 StorageUtl_WriteDWord(
3165 OFFSET_BBDEPOTCOUNT,
3166 This->bigBlockDepotCount);
3168 StorageUtl_WriteDWord(
3170 OFFSET_ROOTSTARTBLOCK,
3171 This->rootStartBlock);
3173 StorageUtl_WriteDWord(
3175 OFFSET_SBDEPOTSTART,
3176 This->smallBlockDepotStart);
3178 StorageUtl_WriteDWord(
3180 OFFSET_SBDEPOTCOUNT,
3181 This->smallBlockDepotChain ?
3182 BlockChainStream_GetCount(This->smallBlockDepotChain) : 0);
3184 StorageUtl_WriteDWord(
3186 OFFSET_EXTBBDEPOTSTART,
3187 This->extBigBlockDepotStart);
3189 StorageUtl_WriteDWord(
3191 OFFSET_EXTBBDEPOTCOUNT,
3192 This->extBigBlockDepotCount);
3194 for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
3196 StorageUtl_WriteDWord(
3198 OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
3199 (This->bigBlockDepotStart[index]));
3203 * Write the big block back to the file.
3205 StorageImpl_WriteBigBlock(This, -1, headerBigBlock);
3208 /******************************************************************************
3209 * Storage32Impl_ReadProperty
3211 * This method will read the specified property from the property chain.
3213 BOOL StorageImpl_ReadProperty(
3216 StgProperty* buffer)
3218 BYTE currentProperty[PROPSET_BLOCK_SIZE];
3219 ULARGE_INTEGER offsetInPropSet;
3220 BOOL readSuccessful;
3223 offsetInPropSet.u.HighPart = 0;
3224 offsetInPropSet.u.LowPart = index * PROPSET_BLOCK_SIZE;
3226 readSuccessful = BlockChainStream_ReadAt(
3227 This->rootBlockChain,
3235 /* replace the name of root entry (often "Root Entry") by the file name */
3236 WCHAR *propName = (index == This->base.rootPropertySetIndex) ?
3237 This->filename : (WCHAR *)currentProperty+OFFSET_PS_NAME;
3239 memset(buffer->name, 0, sizeof(buffer->name));
3243 PROPERTY_NAME_BUFFER_LEN );
3244 TRACE("storage name: %s\n", debugstr_w(buffer->name));
3246 memcpy(&buffer->propertyType, currentProperty + OFFSET_PS_PROPERTYTYPE, 1);
3248 StorageUtl_ReadWord(
3250 OFFSET_PS_NAMELENGTH,
3251 &buffer->sizeOfNameString);
3253 StorageUtl_ReadDWord(
3255 OFFSET_PS_PREVIOUSPROP,
3256 &buffer->previousProperty);
3258 StorageUtl_ReadDWord(
3261 &buffer->nextProperty);
3263 StorageUtl_ReadDWord(
3266 &buffer->dirProperty);
3268 StorageUtl_ReadGUID(
3271 &buffer->propertyUniqueID);
3273 StorageUtl_ReadDWord(
3276 &buffer->timeStampS1);
3278 StorageUtl_ReadDWord(
3281 &buffer->timeStampD1);
3283 StorageUtl_ReadDWord(
3286 &buffer->timeStampS2);
3288 StorageUtl_ReadDWord(
3291 &buffer->timeStampD2);
3293 StorageUtl_ReadDWord(
3295 OFFSET_PS_STARTBLOCK,
3296 &buffer->startingBlock);
3298 StorageUtl_ReadDWord(
3301 &buffer->size.u.LowPart);
3303 buffer->size.u.HighPart = 0;
3306 return readSuccessful;
3309 /*********************************************************************
3310 * Write the specified property into the property chain
3312 BOOL StorageImpl_WriteProperty(
3315 StgProperty* buffer)
3317 BYTE currentProperty[PROPSET_BLOCK_SIZE];
3318 ULARGE_INTEGER offsetInPropSet;
3319 BOOL writeSuccessful;
3322 offsetInPropSet.u.HighPart = 0;
3323 offsetInPropSet.u.LowPart = index * PROPSET_BLOCK_SIZE;
3325 memset(currentProperty, 0, PROPSET_BLOCK_SIZE);
3328 currentProperty + OFFSET_PS_NAME,
3330 PROPERTY_NAME_BUFFER_LEN );
3332 memcpy(currentProperty + OFFSET_PS_PROPERTYTYPE, &buffer->propertyType, 1);
3334 StorageUtl_WriteWord(
3336 OFFSET_PS_NAMELENGTH,
3337 buffer->sizeOfNameString);
3339 StorageUtl_WriteDWord(
3341 OFFSET_PS_PREVIOUSPROP,
3342 buffer->previousProperty);
3344 StorageUtl_WriteDWord(
3347 buffer->nextProperty);
3349 StorageUtl_WriteDWord(
3352 buffer->dirProperty);
3354 StorageUtl_WriteGUID(
3357 &buffer->propertyUniqueID);
3359 StorageUtl_WriteDWord(
3362 buffer->timeStampS1);
3364 StorageUtl_WriteDWord(
3367 buffer->timeStampD1);
3369 StorageUtl_WriteDWord(
3372 buffer->timeStampS2);
3374 StorageUtl_WriteDWord(
3377 buffer->timeStampD2);
3379 StorageUtl_WriteDWord(
3381 OFFSET_PS_STARTBLOCK,
3382 buffer->startingBlock);
3384 StorageUtl_WriteDWord(
3387 buffer->size.u.LowPart);
3389 writeSuccessful = BlockChainStream_WriteAt(This->rootBlockChain,
3394 return writeSuccessful;
3397 BOOL StorageImpl_ReadBigBlock(
3402 void* bigBlockBuffer;
3404 bigBlockBuffer = StorageImpl_GetROBigBlock(This, blockIndex);
3406 if (bigBlockBuffer!=0)
3408 memcpy(buffer, bigBlockBuffer, This->bigBlockSize);
3410 StorageImpl_ReleaseBigBlock(This, bigBlockBuffer);
3418 BOOL StorageImpl_WriteBigBlock(
3423 void* bigBlockBuffer;
3425 bigBlockBuffer = StorageImpl_GetBigBlock(This, blockIndex);
3427 if (bigBlockBuffer!=0)
3429 memcpy(bigBlockBuffer, buffer, This->bigBlockSize);
3431 StorageImpl_ReleaseBigBlock(This, bigBlockBuffer);
3439 void* StorageImpl_GetROBigBlock(
3443 return BIGBLOCKFILE_GetROBigBlock(This->bigBlockFile, blockIndex);
3446 void* StorageImpl_GetBigBlock(
3450 return BIGBLOCKFILE_GetBigBlock(This->bigBlockFile, blockIndex);
3453 void StorageImpl_ReleaseBigBlock(
3457 BIGBLOCKFILE_ReleaseBigBlock(This->bigBlockFile, pBigBlock);
3460 /******************************************************************************
3461 * Storage32Impl_SmallBlocksToBigBlocks
3463 * This method will convert a small block chain to a big block chain.
3464 * The small block chain will be destroyed.
3466 BlockChainStream* Storage32Impl_SmallBlocksToBigBlocks(
3468 SmallBlockChainStream** ppsbChain)
3470 ULONG bbHeadOfChain = BLOCK_END_OF_CHAIN;
3471 ULARGE_INTEGER size, offset;
3472 ULONG cbRead, cbWritten, cbTotalRead, cbTotalWritten;
3473 ULONG propertyIndex;
3475 HRESULT successRead;
3476 StgProperty chainProperty;
3478 BlockChainStream *bbTempChain = NULL;
3479 BlockChainStream *bigBlockChain = NULL;
3482 * Create a temporary big block chain that doesn't have
3483 * an associated property. This temporary chain will be
3484 * used to copy data from small blocks to big blocks.
3486 bbTempChain = BlockChainStream_Construct(This,
3489 if(!bbTempChain) return NULL;
3491 * Grow the big block chain.
3493 size = SmallBlockChainStream_GetSize(*ppsbChain);
3494 BlockChainStream_SetSize(bbTempChain, size);
3497 * Copy the contents of the small block chain to the big block chain
3498 * by small block size increments.
3500 offset.u.LowPart = 0;
3501 offset.u.HighPart = 0;
3505 buffer = HeapAlloc(GetProcessHeap(),0,DEF_SMALL_BLOCK_SIZE);
3508 successRead = SmallBlockChainStream_ReadAt(*ppsbChain,
3510 DEF_SMALL_BLOCK_SIZE,
3513 if (FAILED(successRead))
3518 cbTotalRead += cbRead;
3520 successWrite = BlockChainStream_WriteAt(bbTempChain,
3529 cbTotalWritten += cbWritten;
3530 offset.u.LowPart += This->smallBlockSize;
3532 } while (cbRead > 0);
3533 HeapFree(GetProcessHeap(),0,buffer);
3535 assert(cbTotalRead == cbTotalWritten);
3538 * Destroy the small block chain.
3540 propertyIndex = (*ppsbChain)->ownerPropertyIndex;
3541 size.u.HighPart = 0;
3543 SmallBlockChainStream_SetSize(*ppsbChain, size);
3544 SmallBlockChainStream_Destroy(*ppsbChain);
3548 * Change the property information. This chain is now a big block chain
3549 * and it doesn't reside in the small blocks chain anymore.
3551 StorageImpl_ReadProperty(This, propertyIndex, &chainProperty);
3553 chainProperty.startingBlock = bbHeadOfChain;
3555 StorageImpl_WriteProperty(This, propertyIndex, &chainProperty);
3558 * Destroy the temporary propertyless big block chain.
3559 * Create a new big block chain associated with this property.
3561 BlockChainStream_Destroy(bbTempChain);
3562 bigBlockChain = BlockChainStream_Construct(This,
3566 return bigBlockChain;
3569 void StorageInternalImpl_Destroy( StorageBaseImpl *iface)
3571 StorageInternalImpl* This = (StorageInternalImpl*) iface;
3573 StorageBaseImpl_Release((IStorage*)This->base.ancestorStorage);
3574 HeapFree(GetProcessHeap(), 0, This);
3577 /******************************************************************************
3579 ** Storage32InternalImpl_Commit
3581 ** The non-root storages cannot be opened in transacted mode thus this function
3584 HRESULT WINAPI StorageInternalImpl_Commit(
3586 DWORD grfCommitFlags) /* [in] */
3591 /******************************************************************************
3593 ** Storage32InternalImpl_Revert
3595 ** The non-root storages cannot be opened in transacted mode thus this function
3598 HRESULT WINAPI StorageInternalImpl_Revert(
3604 void IEnumSTATSTGImpl_Destroy(IEnumSTATSTGImpl* This)
3606 IStorage_Release((IStorage*)This->parentStorage);
3607 HeapFree(GetProcessHeap(), 0, This->stackToVisit);
3608 HeapFree(GetProcessHeap(), 0, This);
3611 HRESULT WINAPI IEnumSTATSTGImpl_QueryInterface(
3612 IEnumSTATSTG* iface,
3616 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3619 * Perform a sanity check on the parameters.
3622 return E_INVALIDARG;
3625 * Initialize the return parameter.
3630 * Compare the riid with the interface IDs implemented by this object.
3632 if (IsEqualGUID(&IID_IUnknown, riid) ||
3633 IsEqualGUID(&IID_IStorage, riid))
3635 *ppvObject = (IEnumSTATSTG*)This;
3636 IEnumSTATSTG_AddRef((IEnumSTATSTG*)This);
3640 return E_NOINTERFACE;
3643 ULONG WINAPI IEnumSTATSTGImpl_AddRef(
3644 IEnumSTATSTG* iface)
3646 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3647 return InterlockedIncrement(&This->ref);
3650 ULONG WINAPI IEnumSTATSTGImpl_Release(
3651 IEnumSTATSTG* iface)
3653 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3657 newRef = InterlockedDecrement(&This->ref);
3660 * If the reference count goes down to 0, perform suicide.
3664 IEnumSTATSTGImpl_Destroy(This);
3670 HRESULT WINAPI IEnumSTATSTGImpl_Next(
3671 IEnumSTATSTG* iface,
3674 ULONG* pceltFetched)
3676 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3678 StgProperty currentProperty;
3679 STATSTG* currentReturnStruct = rgelt;
3680 ULONG objectFetched = 0;
3681 ULONG currentSearchNode;
3684 * Perform a sanity check on the parameters.
3686 if ( (rgelt==0) || ( (celt!=1) && (pceltFetched==0) ) )
3687 return E_INVALIDARG;
3690 * To avoid the special case, get another pointer to a ULONG value if
3691 * the caller didn't supply one.
3693 if (pceltFetched==0)
3694 pceltFetched = &objectFetched;
3697 * Start the iteration, we will iterate until we hit the end of the
3698 * linked list or until we hit the number of items to iterate through
3703 * Start with the node at the top of the stack.
3705 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3707 while ( ( *pceltFetched < celt) &&
3708 ( currentSearchNode!=PROPERTY_NULL) )
3711 * Remove the top node from the stack
3713 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3716 * Read the property from the storage.
3718 StorageImpl_ReadProperty(This->parentStorage,
3723 * Copy the information to the return buffer.
3725 StorageUtl_CopyPropertyToSTATSTG(currentReturnStruct,
3730 * Step to the next item in the iteration
3733 currentReturnStruct++;
3736 * Push the next search node in the search stack.
3738 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty.nextProperty);
3741 * continue the iteration.
3743 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3746 if (*pceltFetched == celt)
3753 HRESULT WINAPI IEnumSTATSTGImpl_Skip(
3754 IEnumSTATSTG* iface,
3757 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3759 StgProperty currentProperty;
3760 ULONG objectFetched = 0;
3761 ULONG currentSearchNode;
3764 * Start with the node at the top of the stack.
3766 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3768 while ( (objectFetched < celt) &&
3769 (currentSearchNode!=PROPERTY_NULL) )
3772 * Remove the top node from the stack
3774 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3777 * Read the property from the storage.
3779 StorageImpl_ReadProperty(This->parentStorage,
3784 * Step to the next item in the iteration
3789 * Push the next search node in the search stack.
3791 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty.nextProperty);
3794 * continue the iteration.
3796 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3799 if (objectFetched == celt)
3805 HRESULT WINAPI IEnumSTATSTGImpl_Reset(
3806 IEnumSTATSTG* iface)
3808 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3810 StgProperty rootProperty;
3811 BOOL readSuccessful;
3814 * Re-initialize the search stack to an empty stack
3816 This->stackSize = 0;
3819 * Read the root property from the storage.
3821 readSuccessful = StorageImpl_ReadProperty(
3822 This->parentStorage,
3823 This->firstPropertyNode,
3828 assert(rootProperty.sizeOfNameString!=0);
3831 * Push the search node in the search stack.
3833 IEnumSTATSTGImpl_PushSearchNode(This, rootProperty.dirProperty);
3839 HRESULT WINAPI IEnumSTATSTGImpl_Clone(
3840 IEnumSTATSTG* iface,
3841 IEnumSTATSTG** ppenum)
3843 IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3845 IEnumSTATSTGImpl* newClone;
3848 * Perform a sanity check on the parameters.
3851 return E_INVALIDARG;
3853 newClone = IEnumSTATSTGImpl_Construct(This->parentStorage,
3854 This->firstPropertyNode);
3858 * The new clone enumeration must point to the same current node as
3861 newClone->stackSize = This->stackSize ;
3862 newClone->stackMaxSize = This->stackMaxSize ;
3863 newClone->stackToVisit =
3864 HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG) * newClone->stackMaxSize);
3867 newClone->stackToVisit,
3869 sizeof(ULONG) * newClone->stackSize);
3871 *ppenum = (IEnumSTATSTG*)newClone;
3874 * Don't forget to nail down a reference to the clone before
3877 IEnumSTATSTGImpl_AddRef(*ppenum);
3882 INT IEnumSTATSTGImpl_FindParentProperty(
3883 IEnumSTATSTGImpl *This,
3884 ULONG childProperty,
3885 StgProperty *currentProperty,
3888 ULONG currentSearchNode;
3892 * To avoid the special case, get another pointer to a ULONG value if
3893 * the caller didn't supply one.
3896 thisNodeId = &foundNode;
3899 * Start with the node at the top of the stack.
3901 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3904 while (currentSearchNode!=PROPERTY_NULL)
3907 * Store the current node in the returned parameters
3909 *thisNodeId = currentSearchNode;
3912 * Remove the top node from the stack
3914 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3917 * Read the property from the storage.
3919 StorageImpl_ReadProperty(
3920 This->parentStorage,
3924 if (currentProperty->previousProperty == childProperty)
3925 return PROPERTY_RELATION_PREVIOUS;
3927 else if (currentProperty->nextProperty == childProperty)
3928 return PROPERTY_RELATION_NEXT;
3930 else if (currentProperty->dirProperty == childProperty)
3931 return PROPERTY_RELATION_DIR;
3934 * Push the next search node in the search stack.
3936 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty->nextProperty);
3939 * continue the iteration.
3941 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3944 return PROPERTY_NULL;
3947 ULONG IEnumSTATSTGImpl_FindProperty(
3948 IEnumSTATSTGImpl* This,
3949 const OLECHAR* lpszPropName,
3950 StgProperty* currentProperty)
3952 ULONG currentSearchNode;
3955 * Start with the node at the top of the stack.
3957 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3959 while (currentSearchNode!=PROPERTY_NULL)
3962 * Remove the top node from the stack
3964 IEnumSTATSTGImpl_PopSearchNode(This, TRUE);
3967 * Read the property from the storage.
3969 StorageImpl_ReadProperty(This->parentStorage,
3973 if ( propertyNameCmp(
3974 (const OLECHAR*)currentProperty->name,
3975 (const OLECHAR*)lpszPropName) == 0)
3976 return currentSearchNode;
3979 * Push the next search node in the search stack.
3981 IEnumSTATSTGImpl_PushSearchNode(This, currentProperty->nextProperty);
3984 * continue the iteration.
3986 currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3989 return PROPERTY_NULL;
3992 void IEnumSTATSTGImpl_PushSearchNode(
3993 IEnumSTATSTGImpl* This,
3996 StgProperty rootProperty;
3997 BOOL readSuccessful;
4000 * First, make sure we're not trying to push an unexisting node.
4002 if (nodeToPush==PROPERTY_NULL)
4006 * First push the node to the stack
4008 if (This->stackSize == This->stackMaxSize)
4010 This->stackMaxSize += ENUMSTATSGT_SIZE_INCREMENT;
4012 This->stackToVisit = HeapReAlloc(
4016 sizeof(ULONG) * This->stackMaxSize);
4019 This->stackToVisit[This->stackSize] = nodeToPush;
4023 * Read the root property from the storage.
4025 readSuccessful = StorageImpl_ReadProperty(
4026 This->parentStorage,
4032 assert(rootProperty.sizeOfNameString!=0);
4035 * Push the previous search node in the search stack.
4037 IEnumSTATSTGImpl_PushSearchNode(This, rootProperty.previousProperty);
4041 ULONG IEnumSTATSTGImpl_PopSearchNode(
4042 IEnumSTATSTGImpl* This,
4047 if (This->stackSize == 0)
4048 return PROPERTY_NULL;
4050 topNode = This->stackToVisit[This->stackSize-1];
4059 * Virtual function table for the IEnumSTATSTGImpl class.
4061 static const IEnumSTATSTGVtbl IEnumSTATSTGImpl_Vtbl =
4063 IEnumSTATSTGImpl_QueryInterface,
4064 IEnumSTATSTGImpl_AddRef,
4065 IEnumSTATSTGImpl_Release,
4066 IEnumSTATSTGImpl_Next,
4067 IEnumSTATSTGImpl_Skip,
4068 IEnumSTATSTGImpl_Reset,
4069 IEnumSTATSTGImpl_Clone
4072 /******************************************************************************
4073 ** IEnumSTATSTGImpl implementation
4076 IEnumSTATSTGImpl* IEnumSTATSTGImpl_Construct(
4077 StorageImpl* parentStorage,
4078 ULONG firstPropertyNode)
4080 IEnumSTATSTGImpl* newEnumeration;
4082 newEnumeration = HeapAlloc(GetProcessHeap(), 0, sizeof(IEnumSTATSTGImpl));
4084 if (newEnumeration!=0)
4087 * Set-up the virtual function table and reference count.
4089 newEnumeration->lpVtbl = &IEnumSTATSTGImpl_Vtbl;
4090 newEnumeration->ref = 0;
4093 * We want to nail-down the reference to the storage in case the
4094 * enumeration out-lives the storage in the client application.
4096 newEnumeration->parentStorage = parentStorage;
4097 IStorage_AddRef((IStorage*)newEnumeration->parentStorage);
4099 newEnumeration->firstPropertyNode = firstPropertyNode;
4102 * Initialize the search stack
4104 newEnumeration->stackSize = 0;
4105 newEnumeration->stackMaxSize = ENUMSTATSGT_SIZE_INCREMENT;
4106 newEnumeration->stackToVisit =
4107 HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG)*ENUMSTATSGT_SIZE_INCREMENT);
4110 * Make sure the current node of the iterator is the first one.
4112 IEnumSTATSTGImpl_Reset((IEnumSTATSTG*)newEnumeration);
4115 return newEnumeration;
4119 * Virtual function table for the Storage32InternalImpl class.
4121 static const IStorageVtbl Storage32InternalImpl_Vtbl =
4123 StorageBaseImpl_QueryInterface,
4124 StorageBaseImpl_AddRef,
4125 StorageBaseImpl_Release,
4126 StorageBaseImpl_CreateStream,
4127 StorageBaseImpl_OpenStream,
4128 StorageImpl_CreateStorage,
4129 StorageBaseImpl_OpenStorage,
4131 StorageImpl_MoveElementTo,
4132 StorageInternalImpl_Commit,
4133 StorageInternalImpl_Revert,
4134 StorageBaseImpl_EnumElements,
4135 StorageImpl_DestroyElement,
4136 StorageBaseImpl_RenameElement,
4137 StorageImpl_SetElementTimes,
4138 StorageBaseImpl_SetClass,
4139 StorageImpl_SetStateBits,
4140 StorageBaseImpl_Stat
4143 /******************************************************************************
4144 ** Storage32InternalImpl implementation
4147 StorageInternalImpl* StorageInternalImpl_Construct(
4148 StorageImpl* ancestorStorage,
4150 ULONG rootPropertyIndex)
4152 StorageInternalImpl* newStorage;
4155 * Allocate space for the new storage object
4157 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageInternalImpl));
4161 memset(newStorage, 0, sizeof(StorageInternalImpl));
4164 * Initialize the stream list
4167 list_init(&newStorage->base.strmHead);
4170 * Initialize the virtual function table.
4172 newStorage->base.lpVtbl = &Storage32InternalImpl_Vtbl;
4173 newStorage->base.v_destructor = &StorageInternalImpl_Destroy;
4174 newStorage->base.openFlags = openFlags;
4177 * Keep the ancestor storage pointer and nail a reference to it.
4179 newStorage->base.ancestorStorage = ancestorStorage;
4180 StorageBaseImpl_AddRef((IStorage*)(newStorage->base.ancestorStorage));
4183 * Keep the index of the root property set for this storage,
4185 newStorage->base.rootPropertySetIndex = rootPropertyIndex;
4193 /******************************************************************************
4194 ** StorageUtl implementation
4197 void StorageUtl_ReadWord(const BYTE* buffer, ULONG offset, WORD* value)
4201 memcpy(&tmp, buffer+offset, sizeof(WORD));
4202 *value = le16toh(tmp);
4205 void StorageUtl_WriteWord(BYTE* buffer, ULONG offset, WORD value)
4207 value = htole16(value);
4208 memcpy(buffer+offset, &value, sizeof(WORD));
4211 void StorageUtl_ReadDWord(const BYTE* buffer, ULONG offset, DWORD* value)
4215 memcpy(&tmp, buffer+offset, sizeof(DWORD));
4216 *value = le32toh(tmp);
4219 void StorageUtl_WriteDWord(BYTE* buffer, ULONG offset, DWORD value)
4221 value = htole32(value);
4222 memcpy(buffer+offset, &value, sizeof(DWORD));
4225 void StorageUtl_ReadULargeInteger(const BYTE* buffer, ULONG offset,
4226 ULARGE_INTEGER* value)
4228 #ifdef WORDS_BIGENDIAN
4231 memcpy(&tmp, buffer + offset, sizeof(ULARGE_INTEGER));
4232 value->u.LowPart = htole32(tmp.u.HighPart);
4233 value->u.HighPart = htole32(tmp.u.LowPart);
4235 memcpy(value, buffer + offset, sizeof(ULARGE_INTEGER));
4239 void StorageUtl_WriteULargeInteger(BYTE* buffer, ULONG offset,
4240 const ULARGE_INTEGER *value)
4242 #ifdef WORDS_BIGENDIAN
4245 tmp.u.LowPart = htole32(value->u.HighPart);
4246 tmp.u.HighPart = htole32(value->u.LowPart);
4247 memcpy(buffer + offset, &tmp, sizeof(ULARGE_INTEGER));
4249 memcpy(buffer + offset, value, sizeof(ULARGE_INTEGER));
4253 void StorageUtl_ReadGUID(const BYTE* buffer, ULONG offset, GUID* value)
4255 StorageUtl_ReadDWord(buffer, offset, &(value->Data1));
4256 StorageUtl_ReadWord(buffer, offset+4, &(value->Data2));
4257 StorageUtl_ReadWord(buffer, offset+6, &(value->Data3));
4259 memcpy(value->Data4, buffer+offset+8, sizeof(value->Data4));
4262 void StorageUtl_WriteGUID(BYTE* buffer, ULONG offset, const GUID* value)
4264 StorageUtl_WriteDWord(buffer, offset, value->Data1);
4265 StorageUtl_WriteWord(buffer, offset+4, value->Data2);
4266 StorageUtl_WriteWord(buffer, offset+6, value->Data3);
4268 memcpy(buffer+offset+8, value->Data4, sizeof(value->Data4));
4271 void StorageUtl_CopyPropertyToSTATSTG(
4272 STATSTG* destination,
4273 StgProperty* source,
4277 * The copy of the string occurs only when the flag is not set
4279 if( ((statFlags & STATFLAG_NONAME) != 0) ||
4280 (source->name == NULL) ||
4281 (source->name[0] == 0) )
4283 destination->pwcsName = 0;
4287 destination->pwcsName =
4288 CoTaskMemAlloc((lstrlenW(source->name)+1)*sizeof(WCHAR));
4290 strcpyW((LPWSTR)destination->pwcsName, source->name);
4293 switch (source->propertyType)
4295 case PROPTYPE_STORAGE:
4297 destination->type = STGTY_STORAGE;
4299 case PROPTYPE_STREAM:
4300 destination->type = STGTY_STREAM;
4303 destination->type = STGTY_STREAM;
4307 destination->cbSize = source->size;
4309 currentReturnStruct->mtime = {0}; TODO
4310 currentReturnStruct->ctime = {0};
4311 currentReturnStruct->atime = {0};
4313 destination->grfMode = 0;
4314 destination->grfLocksSupported = 0;
4315 destination->clsid = source->propertyUniqueID;
4316 destination->grfStateBits = 0;
4317 destination->reserved = 0;
4320 /******************************************************************************
4321 ** BlockChainStream implementation
4324 BlockChainStream* BlockChainStream_Construct(
4325 StorageImpl* parentStorage,
4326 ULONG* headOfStreamPlaceHolder,
4327 ULONG propertyIndex)
4329 BlockChainStream* newStream;
4332 newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(BlockChainStream));
4334 newStream->parentStorage = parentStorage;
4335 newStream->headOfStreamPlaceHolder = headOfStreamPlaceHolder;
4336 newStream->ownerPropertyIndex = propertyIndex;
4337 newStream->lastBlockNoInSequence = 0xFFFFFFFF;
4338 newStream->tailIndex = BLOCK_END_OF_CHAIN;
4339 newStream->numBlocks = 0;
4341 blockIndex = BlockChainStream_GetHeadOfChain(newStream);
4343 while (blockIndex != BLOCK_END_OF_CHAIN)
4345 newStream->numBlocks++;
4346 newStream->tailIndex = blockIndex;
4348 if(FAILED(StorageImpl_GetNextBlockInChain(
4353 HeapFree(GetProcessHeap(), 0, newStream);
4361 void BlockChainStream_Destroy(BlockChainStream* This)
4363 HeapFree(GetProcessHeap(), 0, This);
4366 /******************************************************************************
4367 * BlockChainStream_GetHeadOfChain
4369 * Returns the head of this stream chain.
4370 * Some special chains don't have properties, their heads are kept in
4371 * This->headOfStreamPlaceHolder.
4374 ULONG BlockChainStream_GetHeadOfChain(BlockChainStream* This)
4376 StgProperty chainProperty;
4377 BOOL readSuccessful;
4379 if (This->headOfStreamPlaceHolder != 0)
4380 return *(This->headOfStreamPlaceHolder);
4382 if (This->ownerPropertyIndex != PROPERTY_NULL)
4384 readSuccessful = StorageImpl_ReadProperty(
4385 This->parentStorage,
4386 This->ownerPropertyIndex,
4391 return chainProperty.startingBlock;
4395 return BLOCK_END_OF_CHAIN;
4398 /******************************************************************************
4399 * BlockChainStream_GetCount
4401 * Returns the number of blocks that comprises this chain.
4402 * This is not the size of the stream as the last block may not be full!
4405 ULONG BlockChainStream_GetCount(BlockChainStream* This)
4410 blockIndex = BlockChainStream_GetHeadOfChain(This);
4412 while (blockIndex != BLOCK_END_OF_CHAIN)
4416 if(FAILED(StorageImpl_GetNextBlockInChain(
4417 This->parentStorage,
4426 /******************************************************************************
4427 * BlockChainStream_ReadAt
4429 * Reads a specified number of bytes from this chain at the specified offset.
4430 * bytesRead may be NULL.
4431 * Failure will be returned if the specified number of bytes has not been read.
4433 BOOL BlockChainStream_ReadAt(BlockChainStream* This,
4434 ULARGE_INTEGER offset,
4439 ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
4440 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->bigBlockSize;
4441 ULONG bytesToReadInBuffer;
4444 BYTE* bigBlockBuffer;
4447 * Find the first block in the stream that contains part of the buffer.
4449 if ( (This->lastBlockNoInSequence == 0xFFFFFFFF) ||
4450 (This->lastBlockNoInSequenceIndex == BLOCK_END_OF_CHAIN) ||
4451 (blockNoInSequence < This->lastBlockNoInSequence) )
4453 blockIndex = BlockChainStream_GetHeadOfChain(This);
4454 This->lastBlockNoInSequence = blockNoInSequence;
4458 ULONG temp = blockNoInSequence;
4460 blockIndex = This->lastBlockNoInSequenceIndex;
4461 blockNoInSequence -= This->lastBlockNoInSequence;
4462 This->lastBlockNoInSequence = temp;
4465 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
4467 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex, &blockIndex)))
4469 blockNoInSequence--;
4472 if ((blockNoInSequence > 0) && (blockIndex == BLOCK_END_OF_CHAIN))
4473 return FALSE; /* We failed to find the starting block */
4475 This->lastBlockNoInSequenceIndex = blockIndex;
4478 * Start reading the buffer.
4481 bufferWalker = buffer;
4483 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
4486 * Calculate how many bytes we can copy from this big block.
4488 bytesToReadInBuffer =
4489 min(This->parentStorage->bigBlockSize - offsetInBlock, size);
4492 * Copy those bytes to the buffer
4495 StorageImpl_GetROBigBlock(This->parentStorage, blockIndex);
4497 memcpy(bufferWalker, bigBlockBuffer + offsetInBlock, bytesToReadInBuffer);
4499 StorageImpl_ReleaseBigBlock(This->parentStorage, bigBlockBuffer);
4502 * Step to the next big block.
4504 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex, &blockIndex)))
4507 bufferWalker += bytesToReadInBuffer;
4508 size -= bytesToReadInBuffer;
4509 *bytesRead += bytesToReadInBuffer;
4510 offsetInBlock = 0; /* There is no offset on the next block */
4517 /******************************************************************************
4518 * BlockChainStream_WriteAt
4520 * Writes the specified number of bytes to this chain at the specified offset.
4521 * bytesWritten may be NULL.
4522 * Will fail if not all specified number of bytes have been written.
4524 BOOL BlockChainStream_WriteAt(BlockChainStream* This,
4525 ULARGE_INTEGER offset,
4528 ULONG* bytesWritten)
4530 ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
4531 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->bigBlockSize;
4534 const BYTE* bufferWalker;
4535 BYTE* bigBlockBuffer;
4538 * Find the first block in the stream that contains part of the buffer.
4540 if ( (This->lastBlockNoInSequence == 0xFFFFFFFF) ||
4541 (This->lastBlockNoInSequenceIndex == BLOCK_END_OF_CHAIN) ||
4542 (blockNoInSequence < This->lastBlockNoInSequence) )
4544 blockIndex = BlockChainStream_GetHeadOfChain(This);
4545 This->lastBlockNoInSequence = blockNoInSequence;
4549 ULONG temp = blockNoInSequence;
4551 blockIndex = This->lastBlockNoInSequenceIndex;
4552 blockNoInSequence -= This->lastBlockNoInSequence;
4553 This->lastBlockNoInSequence = temp;
4556 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
4558 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4561 blockNoInSequence--;
4564 This->lastBlockNoInSequenceIndex = blockIndex;
4567 * Here, I'm casting away the constness on the buffer variable
4568 * This is OK since we don't intend to modify that buffer.
4571 bufferWalker = (const BYTE*)buffer;
4573 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
4576 * Calculate how many bytes we can copy from this big block.
4579 min(This->parentStorage->bigBlockSize - offsetInBlock, size);
4582 * Copy those bytes to the buffer
4584 bigBlockBuffer = StorageImpl_GetBigBlock(This->parentStorage, blockIndex);
4586 memcpy(bigBlockBuffer + offsetInBlock, bufferWalker, bytesToWrite);
4588 StorageImpl_ReleaseBigBlock(This->parentStorage, bigBlockBuffer);
4591 * Step to the next big block.
4593 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4596 bufferWalker += bytesToWrite;
4597 size -= bytesToWrite;
4598 *bytesWritten += bytesToWrite;
4599 offsetInBlock = 0; /* There is no offset on the next block */
4605 /******************************************************************************
4606 * BlockChainStream_Shrink
4608 * Shrinks this chain in the big block depot.
4610 BOOL BlockChainStream_Shrink(BlockChainStream* This,
4611 ULARGE_INTEGER newSize)
4613 ULONG blockIndex, extraBlock;
4618 * Reset the last accessed block cache.
4620 This->lastBlockNoInSequence = 0xFFFFFFFF;
4621 This->lastBlockNoInSequenceIndex = BLOCK_END_OF_CHAIN;
4624 * Figure out how many blocks are needed to contain the new size
4626 numBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
4628 if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
4631 blockIndex = BlockChainStream_GetHeadOfChain(This);
4634 * Go to the new end of chain
4636 while (count < numBlocks)
4638 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4644 /* Get the next block before marking the new end */
4645 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4649 /* Mark the new end of chain */
4650 StorageImpl_SetNextBlockInChain(
4651 This->parentStorage,
4653 BLOCK_END_OF_CHAIN);
4655 This->tailIndex = blockIndex;
4656 This->numBlocks = numBlocks;
4659 * Mark the extra blocks as free
4661 while (extraBlock != BLOCK_END_OF_CHAIN)
4663 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, extraBlock,
4666 StorageImpl_FreeBigBlock(This->parentStorage, extraBlock);
4667 extraBlock = blockIndex;
4673 /******************************************************************************
4674 * BlockChainStream_Enlarge
4676 * Grows this chain in the big block depot.
4678 BOOL BlockChainStream_Enlarge(BlockChainStream* This,
4679 ULARGE_INTEGER newSize)
4681 ULONG blockIndex, currentBlock;
4683 ULONG oldNumBlocks = 0;
4685 blockIndex = BlockChainStream_GetHeadOfChain(This);
4688 * Empty chain. Create the head.
4690 if (blockIndex == BLOCK_END_OF_CHAIN)
4692 blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
4693 StorageImpl_SetNextBlockInChain(This->parentStorage,
4695 BLOCK_END_OF_CHAIN);
4697 if (This->headOfStreamPlaceHolder != 0)
4699 *(This->headOfStreamPlaceHolder) = blockIndex;
4703 StgProperty chainProp;
4704 assert(This->ownerPropertyIndex != PROPERTY_NULL);
4706 StorageImpl_ReadProperty(
4707 This->parentStorage,
4708 This->ownerPropertyIndex,
4711 chainProp.startingBlock = blockIndex;
4713 StorageImpl_WriteProperty(
4714 This->parentStorage,
4715 This->ownerPropertyIndex,
4719 This->tailIndex = blockIndex;
4720 This->numBlocks = 1;
4724 * Figure out how many blocks are needed to contain this stream
4726 newNumBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
4728 if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
4732 * Go to the current end of chain
4734 if (This->tailIndex == BLOCK_END_OF_CHAIN)
4736 currentBlock = blockIndex;
4738 while (blockIndex != BLOCK_END_OF_CHAIN)
4741 currentBlock = blockIndex;
4743 if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, currentBlock,
4748 This->tailIndex = currentBlock;
4751 currentBlock = This->tailIndex;
4752 oldNumBlocks = This->numBlocks;
4755 * Add new blocks to the chain
4757 if (oldNumBlocks < newNumBlocks)
4759 while (oldNumBlocks < newNumBlocks)
4761 blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
4763 StorageImpl_SetNextBlockInChain(
4764 This->parentStorage,
4768 StorageImpl_SetNextBlockInChain(
4769 This->parentStorage,
4771 BLOCK_END_OF_CHAIN);
4773 currentBlock = blockIndex;
4777 This->tailIndex = blockIndex;
4778 This->numBlocks = newNumBlocks;
4784 /******************************************************************************
4785 * BlockChainStream_SetSize
4787 * Sets the size of this stream. The big block depot will be updated.
4788 * The file will grow if we grow the chain.
4790 * TODO: Free the actual blocks in the file when we shrink the chain.
4791 * Currently, the blocks are still in the file. So the file size
4792 * doesn't shrink even if we shrink streams.
4794 BOOL BlockChainStream_SetSize(
4795 BlockChainStream* This,
4796 ULARGE_INTEGER newSize)
4798 ULARGE_INTEGER size = BlockChainStream_GetSize(This);
4800 if (newSize.u.LowPart == size.u.LowPart)
4803 if (newSize.u.LowPart < size.u.LowPart)
4805 BlockChainStream_Shrink(This, newSize);
4809 ULARGE_INTEGER fileSize =
4810 BIGBLOCKFILE_GetSize(This->parentStorage->bigBlockFile);
4812 ULONG diff = newSize.u.LowPart - size.u.LowPart;
4815 * Make sure the file stays a multiple of blocksize
4817 if ((diff % This->parentStorage->bigBlockSize) != 0)
4818 diff += (This->parentStorage->bigBlockSize -
4819 (diff % This->parentStorage->bigBlockSize) );
4821 fileSize.u.LowPart += diff;
4822 BIGBLOCKFILE_SetSize(This->parentStorage->bigBlockFile, fileSize);
4824 BlockChainStream_Enlarge(This, newSize);
4830 /******************************************************************************
4831 * BlockChainStream_GetSize
4833 * Returns the size of this chain.
4834 * Will return the block count if this chain doesn't have a property.
4836 ULARGE_INTEGER BlockChainStream_GetSize(BlockChainStream* This)
4838 StgProperty chainProperty;
4840 if(This->headOfStreamPlaceHolder == NULL)
4843 * This chain is a data stream read the property and return
4844 * the appropriate size
4846 StorageImpl_ReadProperty(
4847 This->parentStorage,
4848 This->ownerPropertyIndex,
4851 return chainProperty.size;
4856 * this chain is a chain that does not have a property, figure out the
4857 * size by making the product number of used blocks times the
4860 ULARGE_INTEGER result;
4861 result.u.HighPart = 0;
4864 BlockChainStream_GetCount(This) *
4865 This->parentStorage->bigBlockSize;
4871 /******************************************************************************
4872 ** SmallBlockChainStream implementation
4875 SmallBlockChainStream* SmallBlockChainStream_Construct(
4876 StorageImpl* parentStorage,
4877 ULONG propertyIndex)
4879 SmallBlockChainStream* newStream;
4881 newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(SmallBlockChainStream));
4883 newStream->parentStorage = parentStorage;
4884 newStream->ownerPropertyIndex = propertyIndex;
4889 void SmallBlockChainStream_Destroy(
4890 SmallBlockChainStream* This)
4892 HeapFree(GetProcessHeap(), 0, This);
4895 /******************************************************************************
4896 * SmallBlockChainStream_GetHeadOfChain
4898 * Returns the head of this chain of small blocks.
4900 ULONG SmallBlockChainStream_GetHeadOfChain(
4901 SmallBlockChainStream* This)
4903 StgProperty chainProperty;
4904 BOOL readSuccessful;
4906 if (This->ownerPropertyIndex)
4908 readSuccessful = StorageImpl_ReadProperty(
4909 This->parentStorage,
4910 This->ownerPropertyIndex,
4915 return chainProperty.startingBlock;
4920 return BLOCK_END_OF_CHAIN;
4923 /******************************************************************************
4924 * SmallBlockChainStream_GetNextBlockInChain
4926 * Returns the index of the next small block in this chain.
4929 * - BLOCK_END_OF_CHAIN: end of this chain
4930 * - BLOCK_UNUSED: small block 'blockIndex' is free
4932 HRESULT SmallBlockChainStream_GetNextBlockInChain(
4933 SmallBlockChainStream* This,
4935 ULONG* nextBlockInChain)
4937 ULARGE_INTEGER offsetOfBlockInDepot;
4942 *nextBlockInChain = BLOCK_END_OF_CHAIN;
4944 offsetOfBlockInDepot.u.HighPart = 0;
4945 offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
4948 * Read those bytes in the buffer from the small block file.
4950 success = BlockChainStream_ReadAt(
4951 This->parentStorage->smallBlockDepotChain,
4952 offsetOfBlockInDepot,
4959 StorageUtl_ReadDWord((BYTE *)&buffer, 0, nextBlockInChain);
4963 return STG_E_READFAULT;
4966 /******************************************************************************
4967 * SmallBlockChainStream_SetNextBlockInChain
4969 * Writes the index of the next block of the specified block in the small
4971 * To set the end of chain use BLOCK_END_OF_CHAIN as nextBlock.
4972 * To flag a block as free use BLOCK_UNUSED as nextBlock.
4974 void SmallBlockChainStream_SetNextBlockInChain(
4975 SmallBlockChainStream* This,
4979 ULARGE_INTEGER offsetOfBlockInDepot;
4983 offsetOfBlockInDepot.u.HighPart = 0;
4984 offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
4986 StorageUtl_WriteDWord((BYTE *)&buffer, 0, nextBlock);
4989 * Read those bytes in the buffer from the small block file.
4991 BlockChainStream_WriteAt(
4992 This->parentStorage->smallBlockDepotChain,
4993 offsetOfBlockInDepot,
4999 /******************************************************************************
5000 * SmallBlockChainStream_FreeBlock
5002 * Flag small block 'blockIndex' as free in the small block depot.
5004 void SmallBlockChainStream_FreeBlock(
5005 SmallBlockChainStream* This,
5008 SmallBlockChainStream_SetNextBlockInChain(This, blockIndex, BLOCK_UNUSED);
5011 /******************************************************************************
5012 * SmallBlockChainStream_GetNextFreeBlock
5014 * Returns the index of a free small block. The small block depot will be
5015 * enlarged if necessary. The small block chain will also be enlarged if
5018 ULONG SmallBlockChainStream_GetNextFreeBlock(
5019 SmallBlockChainStream* This)
5021 ULARGE_INTEGER offsetOfBlockInDepot;
5024 ULONG blockIndex = 0;
5025 ULONG nextBlockIndex = BLOCK_END_OF_CHAIN;
5026 BOOL success = TRUE;
5027 ULONG smallBlocksPerBigBlock;
5029 offsetOfBlockInDepot.u.HighPart = 0;
5032 * Scan the small block depot for a free block
5034 while (nextBlockIndex != BLOCK_UNUSED)
5036 offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
5038 success = BlockChainStream_ReadAt(
5039 This->parentStorage->smallBlockDepotChain,
5040 offsetOfBlockInDepot,
5046 * If we run out of space for the small block depot, enlarge it
5050 StorageUtl_ReadDWord((BYTE *)&buffer, 0, &nextBlockIndex);
5052 if (nextBlockIndex != BLOCK_UNUSED)
5058 BlockChainStream_GetCount(This->parentStorage->smallBlockDepotChain);
5060 ULONG sbdIndex = This->parentStorage->smallBlockDepotStart;
5061 ULONG nextBlock, newsbdIndex;
5062 BYTE* smallBlockDepot;
5064 nextBlock = sbdIndex;
5065 while (nextBlock != BLOCK_END_OF_CHAIN)
5067 sbdIndex = nextBlock;
5068 StorageImpl_GetNextBlockInChain(This->parentStorage, sbdIndex, &nextBlock);
5071 newsbdIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
5072 if (sbdIndex != BLOCK_END_OF_CHAIN)
5073 StorageImpl_SetNextBlockInChain(
5074 This->parentStorage,
5078 StorageImpl_SetNextBlockInChain(
5079 This->parentStorage,
5081 BLOCK_END_OF_CHAIN);
5084 * Initialize all the small blocks to free
5087 StorageImpl_GetBigBlock(This->parentStorage, newsbdIndex);
5089 memset(smallBlockDepot, BLOCK_UNUSED, This->parentStorage->bigBlockSize);
5090 StorageImpl_ReleaseBigBlock(This->parentStorage, smallBlockDepot);
5095 * We have just created the small block depot.
5097 StgProperty rootProp;
5101 * Save it in the header
5103 This->parentStorage->smallBlockDepotStart = newsbdIndex;
5104 StorageImpl_SaveFileHeader(This->parentStorage);
5107 * And allocate the first big block that will contain small blocks
5110 StorageImpl_GetNextFreeBigBlock(This->parentStorage);
5112 StorageImpl_SetNextBlockInChain(
5113 This->parentStorage,
5115 BLOCK_END_OF_CHAIN);
5117 StorageImpl_ReadProperty(
5118 This->parentStorage,
5119 This->parentStorage->base.rootPropertySetIndex,
5122 rootProp.startingBlock = sbStartIndex;
5123 rootProp.size.u.HighPart = 0;
5124 rootProp.size.u.LowPart = This->parentStorage->bigBlockSize;
5126 StorageImpl_WriteProperty(
5127 This->parentStorage,
5128 This->parentStorage->base.rootPropertySetIndex,
5134 smallBlocksPerBigBlock =
5135 This->parentStorage->bigBlockSize / This->parentStorage->smallBlockSize;
5138 * Verify if we have to allocate big blocks to contain small blocks
5140 if (blockIndex % smallBlocksPerBigBlock == 0)
5142 StgProperty rootProp;
5143 ULONG blocksRequired = (blockIndex / smallBlocksPerBigBlock) + 1;
5145 StorageImpl_ReadProperty(
5146 This->parentStorage,
5147 This->parentStorage->base.rootPropertySetIndex,
5150 if (rootProp.size.u.LowPart <
5151 (blocksRequired * This->parentStorage->bigBlockSize))
5153 rootProp.size.u.LowPart += This->parentStorage->bigBlockSize;
5155 BlockChainStream_SetSize(
5156 This->parentStorage->smallBlockRootChain,
5159 StorageImpl_WriteProperty(
5160 This->parentStorage,
5161 This->parentStorage->base.rootPropertySetIndex,
5169 /******************************************************************************
5170 * SmallBlockChainStream_ReadAt
5172 * Reads a specified number of bytes from this chain at the specified offset.
5173 * bytesRead may be NULL.
5174 * Failure will be returned if the specified number of bytes has not been read.
5176 HRESULT SmallBlockChainStream_ReadAt(
5177 SmallBlockChainStream* This,
5178 ULARGE_INTEGER offset,
5184 ULARGE_INTEGER offsetInBigBlockFile;
5185 ULONG blockNoInSequence =
5186 offset.u.LowPart / This->parentStorage->smallBlockSize;
5188 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
5189 ULONG bytesToReadInBuffer;
5191 ULONG bytesReadFromBigBlockFile;
5195 * This should never happen on a small block file.
5197 assert(offset.u.HighPart==0);
5200 * Find the first block in the stream that contains part of the buffer.
5202 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5204 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
5206 rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
5209 blockNoInSequence--;
5213 * Start reading the buffer.
5216 bufferWalker = buffer;
5218 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
5221 * Calculate how many bytes we can copy from this small block.
5223 bytesToReadInBuffer =
5224 min(This->parentStorage->smallBlockSize - offsetInBlock, size);
5227 * Calculate the offset of the small block in the small block file.
5229 offsetInBigBlockFile.u.HighPart = 0;
5230 offsetInBigBlockFile.u.LowPart =
5231 blockIndex * This->parentStorage->smallBlockSize;
5233 offsetInBigBlockFile.u.LowPart += offsetInBlock;
5236 * Read those bytes in the buffer from the small block file.
5237 * The small block has already been identified so it shouldn't fail
5238 * unless the file is corrupt.
5240 if (!BlockChainStream_ReadAt(This->parentStorage->smallBlockRootChain,
5241 offsetInBigBlockFile,
5242 bytesToReadInBuffer,
5244 &bytesReadFromBigBlockFile))
5245 return STG_E_DOCFILECORRUPT;
5247 assert(bytesReadFromBigBlockFile == bytesToReadInBuffer);
5250 * Step to the next big block.
5252 rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
5256 bufferWalker += bytesToReadInBuffer;
5257 size -= bytesToReadInBuffer;
5258 *bytesRead += bytesToReadInBuffer;
5259 offsetInBlock = 0; /* There is no offset on the next block */
5265 /******************************************************************************
5266 * SmallBlockChainStream_WriteAt
5268 * Writes the specified number of bytes to this chain at the specified offset.
5269 * bytesWritten may be NULL.
5270 * Will fail if not all specified number of bytes have been written.
5272 BOOL SmallBlockChainStream_WriteAt(
5273 SmallBlockChainStream* This,
5274 ULARGE_INTEGER offset,
5277 ULONG* bytesWritten)
5279 ULARGE_INTEGER offsetInBigBlockFile;
5280 ULONG blockNoInSequence =
5281 offset.u.LowPart / This->parentStorage->smallBlockSize;
5283 ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
5284 ULONG bytesToWriteInBuffer;
5286 ULONG bytesWrittenFromBigBlockFile;
5287 const BYTE* bufferWalker;
5290 * This should never happen on a small block file.
5292 assert(offset.u.HighPart==0);
5295 * Find the first block in the stream that contains part of the buffer.
5297 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5299 while ( (blockNoInSequence > 0) && (blockIndex != BLOCK_END_OF_CHAIN))
5301 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex)))
5303 blockNoInSequence--;
5307 * Start writing the buffer.
5309 * Here, I'm casting away the constness on the buffer variable
5310 * This is OK since we don't intend to modify that buffer.
5313 bufferWalker = (const BYTE*)buffer;
5314 while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
5317 * Calculate how many bytes we can copy to this small block.
5319 bytesToWriteInBuffer =
5320 min(This->parentStorage->smallBlockSize - offsetInBlock, size);
5323 * Calculate the offset of the small block in the small block file.
5325 offsetInBigBlockFile.u.HighPart = 0;
5326 offsetInBigBlockFile.u.LowPart =
5327 blockIndex * This->parentStorage->smallBlockSize;
5329 offsetInBigBlockFile.u.LowPart += offsetInBlock;
5332 * Write those bytes in the buffer to the small block file.
5334 BlockChainStream_WriteAt(This->parentStorage->smallBlockRootChain,
5335 offsetInBigBlockFile,
5336 bytesToWriteInBuffer,
5338 &bytesWrittenFromBigBlockFile);
5340 assert(bytesWrittenFromBigBlockFile == bytesToWriteInBuffer);
5343 * Step to the next big block.
5345 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
5348 bufferWalker += bytesToWriteInBuffer;
5349 size -= bytesToWriteInBuffer;
5350 *bytesWritten += bytesToWriteInBuffer;
5351 offsetInBlock = 0; /* There is no offset on the next block */
5357 /******************************************************************************
5358 * SmallBlockChainStream_Shrink
5360 * Shrinks this chain in the small block depot.
5362 BOOL SmallBlockChainStream_Shrink(
5363 SmallBlockChainStream* This,
5364 ULARGE_INTEGER newSize)
5366 ULONG blockIndex, extraBlock;
5370 numBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
5372 if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
5375 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5378 * Go to the new end of chain
5380 while (count < numBlocks)
5382 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
5389 * If the count is 0, we have a special case, the head of the chain was
5394 StgProperty chainProp;
5396 StorageImpl_ReadProperty(This->parentStorage,
5397 This->ownerPropertyIndex,
5400 chainProp.startingBlock = BLOCK_END_OF_CHAIN;
5402 StorageImpl_WriteProperty(This->parentStorage,
5403 This->ownerPropertyIndex,
5407 * We start freeing the chain at the head block.
5409 extraBlock = blockIndex;
5413 /* Get the next block before marking the new end */
5414 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
5418 /* Mark the new end of chain */
5419 SmallBlockChainStream_SetNextBlockInChain(
5422 BLOCK_END_OF_CHAIN);
5426 * Mark the extra blocks as free
5428 while (extraBlock != BLOCK_END_OF_CHAIN)
5430 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, extraBlock,
5433 SmallBlockChainStream_FreeBlock(This, extraBlock);
5434 extraBlock = blockIndex;
5440 /******************************************************************************
5441 * SmallBlockChainStream_Enlarge
5443 * Grows this chain in the small block depot.
5445 BOOL SmallBlockChainStream_Enlarge(
5446 SmallBlockChainStream* This,
5447 ULARGE_INTEGER newSize)
5449 ULONG blockIndex, currentBlock;
5451 ULONG oldNumBlocks = 0;
5453 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5458 if (blockIndex == BLOCK_END_OF_CHAIN)
5461 StgProperty chainProp;
5463 StorageImpl_ReadProperty(This->parentStorage, This->ownerPropertyIndex,
5466 chainProp.startingBlock = SmallBlockChainStream_GetNextFreeBlock(This);
5468 StorageImpl_WriteProperty(This->parentStorage, This->ownerPropertyIndex,
5471 blockIndex = chainProp.startingBlock;
5472 SmallBlockChainStream_SetNextBlockInChain(
5475 BLOCK_END_OF_CHAIN);
5478 currentBlock = blockIndex;
5481 * Figure out how many blocks are needed to contain this stream
5483 newNumBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
5485 if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
5489 * Go to the current end of chain
5491 while (blockIndex != BLOCK_END_OF_CHAIN)
5494 currentBlock = blockIndex;
5495 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, currentBlock, &blockIndex)))
5500 * Add new blocks to the chain
5502 while (oldNumBlocks < newNumBlocks)
5504 blockIndex = SmallBlockChainStream_GetNextFreeBlock(This);
5505 SmallBlockChainStream_SetNextBlockInChain(This, currentBlock, blockIndex);
5507 SmallBlockChainStream_SetNextBlockInChain(
5510 BLOCK_END_OF_CHAIN);
5512 currentBlock = blockIndex;
5519 /******************************************************************************
5520 * SmallBlockChainStream_GetCount
5522 * Returns the number of blocks that comprises this chain.
5523 * This is not the size of this chain as the last block may not be full!
5525 ULONG SmallBlockChainStream_GetCount(SmallBlockChainStream* This)
5530 blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5532 while (blockIndex != BLOCK_END_OF_CHAIN)
5536 if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex)))
5543 /******************************************************************************
5544 * SmallBlockChainStream_SetSize
5546 * Sets the size of this stream.
5547 * The file will grow if we grow the chain.
5549 * TODO: Free the actual blocks in the file when we shrink the chain.
5550 * Currently, the blocks are still in the file. So the file size
5551 * doesn't shrink even if we shrink streams.
5553 BOOL SmallBlockChainStream_SetSize(
5554 SmallBlockChainStream* This,
5555 ULARGE_INTEGER newSize)
5557 ULARGE_INTEGER size = SmallBlockChainStream_GetSize(This);
5559 if (newSize.u.LowPart == size.u.LowPart)
5562 if (newSize.u.LowPart < size.u.LowPart)
5564 SmallBlockChainStream_Shrink(This, newSize);
5568 SmallBlockChainStream_Enlarge(This, newSize);
5574 /******************************************************************************
5575 * SmallBlockChainStream_GetSize
5577 * Returns the size of this chain.
5579 ULARGE_INTEGER SmallBlockChainStream_GetSize(SmallBlockChainStream* This)
5581 StgProperty chainProperty;
5583 StorageImpl_ReadProperty(
5584 This->parentStorage,
5585 This->ownerPropertyIndex,
5588 return chainProperty.size;
5591 /******************************************************************************
5592 * StgCreateDocfile [OLE32.@]
5593 * Creates a new compound file storage object
5596 * pwcsName [ I] Unicode string with filename (can be relative or NULL)
5597 * grfMode [ I] Access mode for opening the new storage object (see STGM_ constants)
5598 * reserved [ ?] unused?, usually 0
5599 * ppstgOpen [IO] A pointer to IStorage pointer to the new onject
5602 * S_OK if the file was successfully created
5603 * some STG_E_ value if error
5605 * if pwcsName is NULL, create file with new unique name
5606 * the function can returns
5607 * STG_S_CONVERTED if the specified file was successfully converted to storage format
5610 HRESULT WINAPI StgCreateDocfile(
5614 IStorage **ppstgOpen)
5616 StorageImpl* newStorage = 0;
5617 HANDLE hFile = INVALID_HANDLE_VALUE;
5618 HRESULT hr = STG_E_INVALIDFLAG;
5622 DWORD fileAttributes;
5623 WCHAR tempFileName[MAX_PATH];
5625 TRACE("(%s, %lx, %ld, %p)\n",
5626 debugstr_w(pwcsName), grfMode,
5627 reserved, ppstgOpen);
5630 * Validate the parameters
5633 return STG_E_INVALIDPOINTER;
5635 return STG_E_INVALIDPARAMETER;
5638 * Validate the STGM flags
5640 if ( FAILED( validateSTGM(grfMode) ))
5643 /* StgCreateDocFile always opens for write */
5644 switch(STGM_ACCESS_MODE(grfMode))
5647 case STGM_READWRITE:
5653 /* can't share write */
5654 switch(STGM_SHARE_MODE(grfMode))
5656 case STGM_SHARE_EXCLUSIVE:
5657 case STGM_SHARE_DENY_WRITE:
5663 /* shared reading requires transacted mode */
5664 if( STGM_SHARE_MODE(grfMode) == STGM_SHARE_DENY_WRITE &&
5665 !(grfMode&STGM_TRANSACTED) )
5669 * Generate a unique name.
5673 WCHAR tempPath[MAX_PATH];
5674 static const WCHAR prefix[] = { 'S', 'T', 'O', 0 };
5676 if (STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE)
5679 memset(tempPath, 0, sizeof(tempPath));
5680 memset(tempFileName, 0, sizeof(tempFileName));
5682 if ((GetTempPathW(MAX_PATH, tempPath)) == 0 )
5685 if (GetTempFileNameW(tempPath, prefix, 0, tempFileName) != 0)
5686 pwcsName = tempFileName;
5689 hr = STG_E_INSUFFICIENTMEMORY;
5693 creationMode = TRUNCATE_EXISTING;
5697 creationMode = GetCreationModeFromSTGM(grfMode);
5701 * Interpret the STGM value grfMode
5703 shareMode = GetShareModeFromSTGM(grfMode);
5704 accessMode = GetAccessModeFromSTGM(grfMode);
5706 if (grfMode & STGM_DELETEONRELEASE)
5707 fileAttributes = FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_DELETE_ON_CLOSE;
5709 fileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS;
5711 if (grfMode & STGM_TRANSACTED)
5712 FIXME("Transacted mode not implemented.\n");
5715 * Initialize the "out" parameter.
5719 hFile = CreateFileW(pwcsName,
5727 if (hFile == INVALID_HANDLE_VALUE)
5729 if(GetLastError() == ERROR_FILE_EXISTS)
5730 hr = STG_E_FILEALREADYEXISTS;
5737 * Allocate and initialize the new IStorage32object.
5739 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
5741 if (newStorage == 0)
5743 hr = STG_E_INSUFFICIENTMEMORY;
5747 hr = StorageImpl_Construct(
5758 HeapFree(GetProcessHeap(), 0, newStorage);
5763 * Get an "out" pointer for the caller.
5765 hr = StorageBaseImpl_QueryInterface(
5766 (IStorage*)newStorage,
5767 (REFIID)&IID_IStorage,
5770 TRACE("<-- %p r = %08lx\n", *ppstgOpen, hr);
5775 /******************************************************************************
5776 * StgCreateStorageEx [OLE32.@]
5778 HRESULT WINAPI StgCreateStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
5780 TRACE("(%s, %lx, %lx, %lx, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
5781 grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);
5783 if (stgfmt != STGFMT_FILE && grfAttrs != 0)
5785 ERR("grfAttrs must be 0 if stgfmt != STGFMT_FILE\n");
5786 return STG_E_INVALIDPARAMETER;
5789 if (stgfmt != STGFMT_FILE && grfAttrs != 0 && grfAttrs != FILE_FLAG_NO_BUFFERING)
5791 ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_FILE\n");
5792 return STG_E_INVALIDPARAMETER;
5795 if (stgfmt == STGFMT_FILE)
5797 ERR("Cannot use STGFMT_FILE - this is NTFS only\n");
5798 return STG_E_INVALIDPARAMETER;
5801 if (stgfmt == STGFMT_STORAGE || stgfmt == STGFMT_DOCFILE)
5803 FIXME("Stub: calling StgCreateDocfile, but ignoring pStgOptions and grfAttrs\n");
5804 return StgCreateDocfile(pwcsName, grfMode, 0, (IStorage **)ppObjectOpen);
5807 ERR("Invalid stgfmt argument\n");
5808 return STG_E_INVALIDPARAMETER;
5811 /******************************************************************************
5812 * StgCreatePropSetStg [OLE32.@]
5814 HRESULT WINAPI StgCreatePropSetStg(IStorage *pstg, DWORD reserved,
5815 IPropertySetStorage **ppPropSetStg)
5819 TRACE("(%p, 0x%lx, %p)\n", pstg, reserved, ppPropSetStg);
5821 hr = STG_E_INVALIDPARAMETER;
5823 hr = StorageBaseImpl_QueryInterface(pstg, &IID_IPropertySetStorage,
5824 (void**)ppPropSetStg);
5828 /******************************************************************************
5829 * StgOpenStorageEx [OLE32.@]
5831 HRESULT WINAPI StgOpenStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
5833 TRACE("(%s, %lx, %lx, %lx, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
5834 grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);
5836 if (stgfmt != STGFMT_DOCFILE && grfAttrs != 0)
5838 ERR("grfAttrs must be 0 if stgfmt != STGFMT_DOCFILE\n");
5839 return STG_E_INVALIDPARAMETER;
5842 if (stgfmt != STGFMT_DOCFILE && grfAttrs != 0 && grfAttrs != FILE_FLAG_NO_BUFFERING)
5844 ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_DOCFILE\n");
5845 return STG_E_INVALIDPARAMETER;
5848 if (stgfmt == STGFMT_FILE)
5850 ERR("Cannot use STGFMT_FILE - this is NTFS only\n");
5851 return STG_E_INVALIDPARAMETER;
5854 if (stgfmt == STGFMT_STORAGE || stgfmt == STGFMT_DOCFILE || stgfmt == STGFMT_ANY)
5856 if (stgfmt == STGFMT_ANY)
5857 WARN("STGFMT_ANY assuming storage\n");
5858 FIXME("Stub: calling StgOpenStorage, but ignoring pStgOptions and grfAttrs\n");
5859 return StgOpenStorage(pwcsName, NULL, grfMode, (SNB)NULL, 0, (IStorage **)ppObjectOpen);
5862 ERR("Invalid stgfmt argument\n");
5863 return STG_E_INVALIDPARAMETER;
5867 /******************************************************************************
5868 * StgOpenStorage [OLE32.@]
5870 HRESULT WINAPI StgOpenStorage(
5871 const OLECHAR *pwcsName,
5872 IStorage *pstgPriority,
5876 IStorage **ppstgOpen)
5878 StorageImpl* newStorage = 0;
5883 WCHAR fullname[MAX_PATH];
5886 TRACE("(%s, %p, %lx, %p, %ld, %p)\n",
5887 debugstr_w(pwcsName), pstgPriority, grfMode,
5888 snbExclude, reserved, ppstgOpen);
5891 * Perform sanity checks
5895 hr = STG_E_INVALIDNAME;
5901 hr = STG_E_INVALIDPOINTER;
5907 hr = STG_E_INVALIDPARAMETER;
5911 /* STGM_PRIORITY implies exclusive access */
5912 if (grfMode & STGM_PRIORITY)
5914 if (grfMode & (STGM_TRANSACTED|STGM_SIMPLE|STGM_NOSCRATCH|STGM_NOSNAPSHOT))
5915 return STG_E_INVALIDFLAG;
5916 if (grfMode & STGM_DELETEONRELEASE)
5917 return STG_E_INVALIDFUNCTION;
5918 if(STGM_ACCESS_MODE(grfMode) != STGM_READ)
5919 return STG_E_INVALIDFLAG;
5920 grfMode &= ~0xf0; /* remove the existing sharing mode */
5921 grfMode |= STGM_SHARE_DENY_WRITE;
5925 * Validate the sharing mode
5927 if (!(grfMode & STGM_TRANSACTED))
5928 switch(STGM_SHARE_MODE(grfMode))
5930 case STGM_SHARE_EXCLUSIVE:
5931 case STGM_SHARE_DENY_WRITE:
5934 hr = STG_E_INVALIDFLAG;
5939 * Validate the STGM flags
5941 if ( FAILED( validateSTGM(grfMode) ) ||
5942 (grfMode&STGM_CREATE))
5944 hr = STG_E_INVALIDFLAG;
5948 /* shared reading requires transacted mode */
5949 if( STGM_SHARE_MODE(grfMode) == STGM_SHARE_DENY_WRITE &&
5950 STGM_ACCESS_MODE(grfMode) == STGM_READWRITE &&
5951 !(grfMode&STGM_TRANSACTED) )
5953 hr = STG_E_INVALIDFLAG;
5958 * Interpret the STGM value grfMode
5960 shareMode = GetShareModeFromSTGM(grfMode);
5961 accessMode = GetAccessModeFromSTGM(grfMode);
5964 * Initialize the "out" parameter.
5968 hFile = CreateFileW( pwcsName,
5973 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
5976 if (hFile==INVALID_HANDLE_VALUE)
5978 DWORD last_error = GetLastError();
5984 case ERROR_FILE_NOT_FOUND:
5985 hr = STG_E_FILENOTFOUND;
5988 case ERROR_PATH_NOT_FOUND:
5989 hr = STG_E_PATHNOTFOUND;
5992 case ERROR_ACCESS_DENIED:
5993 case ERROR_WRITE_PROTECT:
5994 hr = STG_E_ACCESSDENIED;
5997 case ERROR_SHARING_VIOLATION:
5998 hr = STG_E_SHAREVIOLATION;
6009 * Refuse to open the file if it's too small to be a structured storage file
6010 * FIXME: verify the file when reading instead of here
6012 length = GetFileSize(hFile, NULL);
6016 hr = STG_E_FILEALREADYEXISTS;
6021 * Allocate and initialize the new IStorage32object.
6023 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
6025 if (newStorage == 0)
6027 hr = STG_E_INSUFFICIENTMEMORY;
6031 /* if the file's length was zero, initialize the storage */
6032 hr = StorageImpl_Construct(
6043 HeapFree(GetProcessHeap(), 0, newStorage);
6045 * According to the docs if the file is not a storage, return STG_E_FILEALREADYEXISTS
6047 if(hr == STG_E_INVALIDHEADER)
6048 hr = STG_E_FILEALREADYEXISTS;
6052 /* prepare the file name string given in lieu of the root property name */
6053 GetFullPathNameW(pwcsName, MAX_PATH, fullname, NULL);
6054 memcpy(newStorage->filename, fullname, PROPERTY_NAME_BUFFER_LEN);
6055 newStorage->filename[PROPERTY_NAME_BUFFER_LEN-1] = '\0';
6058 * Get an "out" pointer for the caller.
6060 hr = StorageBaseImpl_QueryInterface(
6061 (IStorage*)newStorage,
6062 (REFIID)&IID_IStorage,
6066 TRACE("<-- %08lx, IStorage %p\n", hr, ppstgOpen ? *ppstgOpen : NULL);
6070 /******************************************************************************
6071 * StgCreateDocfileOnILockBytes [OLE32.@]
6073 HRESULT WINAPI StgCreateDocfileOnILockBytes(
6077 IStorage** ppstgOpen)
6079 StorageImpl* newStorage = 0;
6083 * Validate the parameters
6085 if ((ppstgOpen == 0) || (plkbyt == 0))
6086 return STG_E_INVALIDPOINTER;
6089 * Allocate and initialize the new IStorage object.
6091 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
6093 if (newStorage == 0)
6094 return STG_E_INSUFFICIENTMEMORY;
6096 hr = StorageImpl_Construct(
6107 HeapFree(GetProcessHeap(), 0, newStorage);
6112 * Get an "out" pointer for the caller.
6114 hr = StorageBaseImpl_QueryInterface(
6115 (IStorage*)newStorage,
6116 (REFIID)&IID_IStorage,
6122 /******************************************************************************
6123 * StgOpenStorageOnILockBytes [OLE32.@]
6125 HRESULT WINAPI StgOpenStorageOnILockBytes(
6127 IStorage *pstgPriority,
6131 IStorage **ppstgOpen)
6133 StorageImpl* newStorage = 0;
6137 * Perform a sanity check
6139 if ((plkbyt == 0) || (ppstgOpen == 0))
6140 return STG_E_INVALIDPOINTER;
6143 * Validate the STGM flags
6145 if ( FAILED( validateSTGM(grfMode) ))
6146 return STG_E_INVALIDFLAG;
6149 * Initialize the "out" parameter.
6154 * Allocate and initialize the new IStorage object.
6156 newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
6158 if (newStorage == 0)
6159 return STG_E_INSUFFICIENTMEMORY;
6161 hr = StorageImpl_Construct(
6172 HeapFree(GetProcessHeap(), 0, newStorage);
6177 * Get an "out" pointer for the caller.
6179 hr = StorageBaseImpl_QueryInterface(
6180 (IStorage*)newStorage,
6181 (REFIID)&IID_IStorage,
6187 /******************************************************************************
6188 * StgSetTimes [ole32.@]
6189 * StgSetTimes [OLE32.@]
6193 HRESULT WINAPI StgSetTimes(OLECHAR const *str, FILETIME const *pctime,
6194 FILETIME const *patime, FILETIME const *pmtime)
6196 IStorage *stg = NULL;
6199 TRACE("%s %p %p %p\n", debugstr_w(str), pctime, patime, pmtime);
6201 r = StgOpenStorage(str, NULL, STGM_READWRITE | STGM_SHARE_DENY_WRITE,
6205 r = IStorage_SetElementTimes(stg, NULL, pctime, patime, pmtime);
6206 IStorage_Release(stg);
6212 /******************************************************************************
6213 * StgIsStorageILockBytes [OLE32.@]
6215 * Determines if the ILockBytes contains a storage object.
6217 HRESULT WINAPI StgIsStorageILockBytes(ILockBytes *plkbyt)
6220 ULARGE_INTEGER offset;
6222 offset.u.HighPart = 0;
6223 offset.u.LowPart = 0;
6225 ILockBytes_ReadAt(plkbyt, offset, sig, sizeof(sig), NULL);
6227 if (memcmp(sig, STORAGE_magic, sizeof(STORAGE_magic)) == 0)
6233 /******************************************************************************
6234 * WriteClassStg [OLE32.@]
6236 * This method will store the specified CLSID in the specified storage object
6238 HRESULT WINAPI WriteClassStg(IStorage* pStg, REFCLSID rclsid)
6243 return E_INVALIDARG;
6245 hRes = IStorage_SetClass(pStg, rclsid);
6250 /***********************************************************************
6251 * ReadClassStg (OLE32.@)
6253 * This method reads the CLSID previously written to a storage object with
6254 * the WriteClassStg.
6257 * pstg [I] IStorage pointer
6258 * pclsid [O] Pointer to where the CLSID is written
6262 * Failure: HRESULT code.
6264 HRESULT WINAPI ReadClassStg(IStorage *pstg,CLSID *pclsid){
6269 TRACE("(%p, %p)\n", pstg, pclsid);
6271 if(!pstg || !pclsid)
6272 return E_INVALIDARG;
6275 * read a STATSTG structure (contains the clsid) from the storage
6277 hRes=IStorage_Stat(pstg,&pstatstg,STATFLAG_DEFAULT);
6280 *pclsid=pstatstg.clsid;
6285 /***********************************************************************
6286 * OleLoadFromStream (OLE32.@)
6288 * This function loads an object from stream
6290 HRESULT WINAPI OleLoadFromStream(IStream *pStm,REFIID iidInterface,void** ppvObj)
6294 LPPERSISTSTREAM xstm;
6296 TRACE("(%p,%s,%p)\n",pStm,debugstr_guid(iidInterface),ppvObj);
6298 res=ReadClassStm(pStm,&clsid);
6299 if (!SUCCEEDED(res))
6301 res=CoCreateInstance(&clsid,NULL,CLSCTX_INPROC_SERVER,iidInterface,ppvObj);
6302 if (!SUCCEEDED(res))
6304 res=IUnknown_QueryInterface((IUnknown*)*ppvObj,&IID_IPersistStream,(LPVOID*)&xstm);
6305 if (!SUCCEEDED(res)) {
6306 IUnknown_Release((IUnknown*)*ppvObj);
6309 res=IPersistStream_Load(xstm,pStm);
6310 IPersistStream_Release(xstm);
6311 /* FIXME: all refcounts ok at this point? I think they should be:
6314 * xstm : 0 (released)
6319 /***********************************************************************
6320 * OleSaveToStream (OLE32.@)
6322 * This function saves an object with the IPersistStream interface on it
6323 * to the specified stream.
6325 HRESULT WINAPI OleSaveToStream(IPersistStream *pPStm,IStream *pStm)
6331 TRACE("(%p,%p)\n",pPStm,pStm);
6333 res=IPersistStream_GetClassID(pPStm,&clsid);
6335 if (SUCCEEDED(res)){
6337 res=WriteClassStm(pStm,&clsid);
6341 res=IPersistStream_Save(pPStm,pStm,TRUE);
6344 TRACE("Finished Save\n");
6348 /****************************************************************************
6349 * This method validate a STGM parameter that can contain the values below
6351 * The stgm modes in 0x0000ffff are not bit masks, but distinct 4 bit values.
6352 * The stgm values contained in 0xffff0000 are bitmasks.
6354 * STGM_DIRECT 0x00000000
6355 * STGM_TRANSACTED 0x00010000
6356 * STGM_SIMPLE 0x08000000
6358 * STGM_READ 0x00000000
6359 * STGM_WRITE 0x00000001
6360 * STGM_READWRITE 0x00000002
6362 * STGM_SHARE_DENY_NONE 0x00000040
6363 * STGM_SHARE_DENY_READ 0x00000030
6364 * STGM_SHARE_DENY_WRITE 0x00000020
6365 * STGM_SHARE_EXCLUSIVE 0x00000010
6367 * STGM_PRIORITY 0x00040000
6368 * STGM_DELETEONRELEASE 0x04000000
6370 * STGM_CREATE 0x00001000
6371 * STGM_CONVERT 0x00020000
6372 * STGM_FAILIFTHERE 0x00000000
6374 * STGM_NOSCRATCH 0x00100000
6375 * STGM_NOSNAPSHOT 0x00200000
6377 static HRESULT validateSTGM(DWORD stgm)
6379 DWORD access = STGM_ACCESS_MODE(stgm);
6380 DWORD share = STGM_SHARE_MODE(stgm);
6381 DWORD create = STGM_CREATE_MODE(stgm);
6383 if (stgm&~STGM_KNOWN_FLAGS)
6385 ERR("unknown flags %08lx\n", stgm);
6393 case STGM_READWRITE:
6401 case STGM_SHARE_DENY_NONE:
6402 case STGM_SHARE_DENY_READ:
6403 case STGM_SHARE_DENY_WRITE:
6404 case STGM_SHARE_EXCLUSIVE:
6413 case STGM_FAILIFTHERE:
6420 * STGM_DIRECT | STGM_TRANSACTED | STGM_SIMPLE
6422 if ( (stgm & STGM_TRANSACTED) && (stgm & STGM_SIMPLE) )
6426 * STGM_CREATE | STGM_CONVERT
6427 * if both are false, STGM_FAILIFTHERE is set to TRUE
6429 if ( create == STGM_CREATE && (stgm & STGM_CONVERT) )
6433 * STGM_NOSCRATCH requires STGM_TRANSACTED
6435 if ( (stgm & STGM_NOSCRATCH) && !(stgm & STGM_TRANSACTED) )
6439 * STGM_NOSNAPSHOT requires STGM_TRANSACTED and
6440 * not STGM_SHARE_EXCLUSIVE or STGM_SHARE_DENY_WRITE`
6442 if ( (stgm & STGM_NOSNAPSHOT) &&
6443 (!(stgm & STGM_TRANSACTED) ||
6444 share == STGM_SHARE_EXCLUSIVE ||
6445 share == STGM_SHARE_DENY_WRITE) )
6451 /****************************************************************************
6452 * GetShareModeFromSTGM
6454 * This method will return a share mode flag from a STGM value.
6455 * The STGM value is assumed valid.
6457 static DWORD GetShareModeFromSTGM(DWORD stgm)
6459 switch (STGM_SHARE_MODE(stgm))
6461 case STGM_SHARE_DENY_NONE:
6462 return FILE_SHARE_READ | FILE_SHARE_WRITE;
6463 case STGM_SHARE_DENY_READ:
6464 return FILE_SHARE_WRITE;
6465 case STGM_SHARE_DENY_WRITE:
6466 return FILE_SHARE_READ;
6467 case STGM_SHARE_EXCLUSIVE:
6470 ERR("Invalid share mode!\n");
6475 /****************************************************************************
6476 * GetAccessModeFromSTGM
6478 * This method will return an access mode flag from a STGM value.
6479 * The STGM value is assumed valid.
6481 static DWORD GetAccessModeFromSTGM(DWORD stgm)
6483 switch (STGM_ACCESS_MODE(stgm))
6486 return GENERIC_READ;
6488 case STGM_READWRITE:
6489 return GENERIC_READ | GENERIC_WRITE;
6491 ERR("Invalid access mode!\n");
6496 /****************************************************************************
6497 * GetCreationModeFromSTGM
6499 * This method will return a creation mode flag from a STGM value.
6500 * The STGM value is assumed valid.
6502 static DWORD GetCreationModeFromSTGM(DWORD stgm)
6504 switch(STGM_CREATE_MODE(stgm))
6507 return CREATE_ALWAYS;
6509 FIXME("STGM_CONVERT not implemented!\n");
6511 case STGM_FAILIFTHERE:
6514 ERR("Invalid create mode!\n");
6520 /*************************************************************************
6521 * OLECONVERT_LoadOLE10 [Internal]
6523 * Loads the OLE10 STREAM to memory
6526 * pOleStream [I] The OLESTREAM
6527 * pData [I] Data Structure for the OLESTREAM Data
6531 * Failure: CONVERT10_E_OLESTREAM_GET for invalid Get
6532 * CONVERT10_E_OLESTREAM_FMT if the OLEID is invalide
6535 * This function is used by OleConvertOLESTREAMToIStorage only.
6537 * Memory allocated for pData must be freed by the caller
6539 static HRESULT OLECONVERT_LoadOLE10(LPOLESTREAM pOleStream, OLECONVERT_OLESTREAM_DATA *pData, BOOL bStrem1)
6542 HRESULT hRes = S_OK;
6546 pData->pData = NULL;
6547 pData->pstrOleObjFileName = (CHAR *) NULL;
6549 for( nTryCnt=0;nTryCnt < max_try; nTryCnt++)
6552 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
6553 if(dwSize != sizeof(pData->dwOleID))
6555 hRes = CONVERT10_E_OLESTREAM_GET;
6557 else if(pData->dwOleID != OLESTREAM_ID)
6559 hRes = CONVERT10_E_OLESTREAM_FMT;
6570 /* Get the TypeID...more info needed for this field */
6571 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
6572 if(dwSize != sizeof(pData->dwTypeID))
6574 hRes = CONVERT10_E_OLESTREAM_GET;
6579 if(pData->dwTypeID != 0)
6581 /* Get the length of the OleTypeName */
6582 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *) &(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
6583 if(dwSize != sizeof(pData->dwOleTypeNameLength))
6585 hRes = CONVERT10_E_OLESTREAM_GET;
6590 if(pData->dwOleTypeNameLength > 0)
6592 /* Get the OleTypeName */
6593 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)pData->strOleTypeName, pData->dwOleTypeNameLength);
6594 if(dwSize != pData->dwOleTypeNameLength)
6596 hRes = CONVERT10_E_OLESTREAM_GET;
6602 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleObjFileNameLength), sizeof(pData->dwOleObjFileNameLength));
6603 if(dwSize != sizeof(pData->dwOleObjFileNameLength))
6605 hRes = CONVERT10_E_OLESTREAM_GET;
6609 if(pData->dwOleObjFileNameLength < 1) /* there is no file name exist */
6610 pData->dwOleObjFileNameLength = sizeof(pData->dwOleObjFileNameLength);
6611 pData->pstrOleObjFileName = HeapAlloc(GetProcessHeap(), 0, pData->dwOleObjFileNameLength);
6612 if(pData->pstrOleObjFileName)
6614 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)(pData->pstrOleObjFileName),pData->dwOleObjFileNameLength);
6615 if(dwSize != pData->dwOleObjFileNameLength)
6617 hRes = CONVERT10_E_OLESTREAM_GET;
6621 hRes = CONVERT10_E_OLESTREAM_GET;
6626 /* Get the Width of the Metafile */
6627 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
6628 if(dwSize != sizeof(pData->dwMetaFileWidth))
6630 hRes = CONVERT10_E_OLESTREAM_GET;
6634 /* Get the Height of the Metafile */
6635 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
6636 if(dwSize != sizeof(pData->dwMetaFileHeight))
6638 hRes = CONVERT10_E_OLESTREAM_GET;
6644 /* Get the Length of the Data */
6645 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
6646 if(dwSize != sizeof(pData->dwDataLength))
6648 hRes = CONVERT10_E_OLESTREAM_GET;
6652 if(hRes == S_OK) /* I don't know what is this 8 byts information is we have to figure out */
6654 if(!bStrem1) /* if it is a second OLE stream data */
6656 pData->dwDataLength -= 8;
6657 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)(pData->strUnknown), sizeof(pData->strUnknown));
6658 if(dwSize != sizeof(pData->strUnknown))
6660 hRes = CONVERT10_E_OLESTREAM_GET;
6666 if(pData->dwDataLength > 0)
6668 pData->pData = HeapAlloc(GetProcessHeap(),0,pData->dwDataLength);
6670 /* Get Data (ex. IStorage, Metafile, or BMP) */
6673 dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)pData->pData, pData->dwDataLength);
6674 if(dwSize != pData->dwDataLength)
6676 hRes = CONVERT10_E_OLESTREAM_GET;
6681 hRes = CONVERT10_E_OLESTREAM_GET;
6690 /*************************************************************************
6691 * OLECONVERT_SaveOLE10 [Internal]
6693 * Saves the OLE10 STREAM From memory
6696 * pData [I] Data Structure for the OLESTREAM Data
6697 * pOleStream [I] The OLESTREAM to save
6701 * Failure: CONVERT10_E_OLESTREAM_PUT for invalid Put
6704 * This function is used by OleConvertIStorageToOLESTREAM only.
6707 static HRESULT OLECONVERT_SaveOLE10(OLECONVERT_OLESTREAM_DATA *pData, LPOLESTREAM pOleStream)
6710 HRESULT hRes = S_OK;
6714 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
6715 if(dwSize != sizeof(pData->dwOleID))
6717 hRes = CONVERT10_E_OLESTREAM_PUT;
6722 /* Set the TypeID */
6723 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
6724 if(dwSize != sizeof(pData->dwTypeID))
6726 hRes = CONVERT10_E_OLESTREAM_PUT;
6730 if(pData->dwOleID == OLESTREAM_ID && pData->dwTypeID != 0 && hRes == S_OK)
6732 /* Set the Length of the OleTypeName */
6733 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
6734 if(dwSize != sizeof(pData->dwOleTypeNameLength))
6736 hRes = CONVERT10_E_OLESTREAM_PUT;
6741 if(pData->dwOleTypeNameLength > 0)
6743 /* Set the OleTypeName */
6744 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *) pData->strOleTypeName, pData->dwOleTypeNameLength);
6745 if(dwSize != pData->dwOleTypeNameLength)
6747 hRes = CONVERT10_E_OLESTREAM_PUT;
6754 /* Set the width of the Metafile */
6755 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
6756 if(dwSize != sizeof(pData->dwMetaFileWidth))
6758 hRes = CONVERT10_E_OLESTREAM_PUT;
6764 /* Set the height of the Metafile */
6765 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
6766 if(dwSize != sizeof(pData->dwMetaFileHeight))
6768 hRes = CONVERT10_E_OLESTREAM_PUT;
6774 /* Set the length of the Data */
6775 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
6776 if(dwSize != sizeof(pData->dwDataLength))
6778 hRes = CONVERT10_E_OLESTREAM_PUT;
6784 if(pData->dwDataLength > 0)
6786 /* Set the Data (eg. IStorage, Metafile, Bitmap) */
6787 dwSize = pOleStream->lpstbl->Put(pOleStream, (void *) pData->pData, pData->dwDataLength);
6788 if(dwSize != pData->dwDataLength)
6790 hRes = CONVERT10_E_OLESTREAM_PUT;
6798 /*************************************************************************
6799 * OLECONVERT_GetOLE20FromOLE10[Internal]
6801 * This function copies OLE10 Data (the IStorage in the OLESTREAM) to disk,
6802 * opens it, and copies the content to the dest IStorage for
6803 * OleConvertOLESTREAMToIStorage
6807 * pDestStorage [I] The IStorage to copy the data to
6808 * pBuffer [I] Buffer that contains the IStorage from the OLESTREAM
6809 * nBufferLength [I] The size of the buffer
6818 static void OLECONVERT_GetOLE20FromOLE10(LPSTORAGE pDestStorage, BYTE *pBuffer, DWORD nBufferLength)
6822 IStorage *pTempStorage;
6823 DWORD dwNumOfBytesWritten;
6824 WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
6825 static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
6827 /* Create a temp File */
6828 GetTempPathW(MAX_PATH, wstrTempDir);
6829 GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
6830 hFile = CreateFileW(wstrTempFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
6832 if(hFile != INVALID_HANDLE_VALUE)
6834 /* Write IStorage Data to File */
6835 WriteFile(hFile, pBuffer, nBufferLength, &dwNumOfBytesWritten, NULL);
6838 /* Open and copy temp storage to the Dest Storage */
6839 hRes = StgOpenStorage(wstrTempFile, NULL, STGM_READ, NULL, 0, &pTempStorage);
6842 hRes = StorageImpl_CopyTo(pTempStorage, 0, NULL, NULL, pDestStorage);
6843 StorageBaseImpl_Release(pTempStorage);
6845 DeleteFileW(wstrTempFile);
6850 /*************************************************************************
6851 * OLECONVERT_WriteOLE20ToBuffer [Internal]
6853 * Saves the OLE10 STREAM From memory
6856 * pStorage [I] The Src IStorage to copy
6857 * pData [I] The Dest Memory to write to.
6860 * The size in bytes allocated for pData
6863 * Memory allocated for pData must be freed by the caller
6865 * Used by OleConvertIStorageToOLESTREAM only.
6868 static DWORD OLECONVERT_WriteOLE20ToBuffer(LPSTORAGE pStorage, BYTE **pData)
6872 DWORD nDataLength = 0;
6873 IStorage *pTempStorage;
6874 WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
6875 static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
6879 /* Create temp Storage */
6880 GetTempPathW(MAX_PATH, wstrTempDir);
6881 GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
6882 hRes = StgCreateDocfile(wstrTempFile, STGM_CREATE | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &pTempStorage);
6886 /* Copy Src Storage to the Temp Storage */
6887 StorageImpl_CopyTo(pStorage, 0, NULL, NULL, pTempStorage);
6888 StorageBaseImpl_Release(pTempStorage);
6890 /* Open Temp Storage as a file and copy to memory */
6891 hFile = CreateFileW(wstrTempFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
6892 if(hFile != INVALID_HANDLE_VALUE)
6894 nDataLength = GetFileSize(hFile, NULL);
6895 *pData = HeapAlloc(GetProcessHeap(),0,nDataLength);
6896 ReadFile(hFile, *pData, nDataLength, &nDataLength, 0);
6899 DeleteFileW(wstrTempFile);
6904 /*************************************************************************
6905 * OLECONVERT_CreateOleStream [Internal]
6907 * Creates the "\001OLE" stream in the IStorage if necessary.
6910 * pStorage [I] Dest storage to create the stream in
6916 * This function is used by OleConvertOLESTREAMToIStorage only.
6918 * This stream is still unknown, MS Word seems to have extra data
6919 * but since the data is stored in the OLESTREAM there should be
6920 * no need to recreate the stream. If the stream is manually
6921 * deleted it will create it with this default data.
6924 void OLECONVERT_CreateOleStream(LPSTORAGE pStorage)
6928 static const WCHAR wstrStreamName[] = {1,'O', 'l', 'e', 0};
6929 BYTE pOleStreamHeader [] =
6931 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
6932 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
6933 0x00, 0x00, 0x00, 0x00
6936 /* Create stream if not present */
6937 hRes = IStorage_CreateStream(pStorage, wstrStreamName,
6938 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
6942 /* Write default Data */
6943 hRes = IStream_Write(pStream, pOleStreamHeader, sizeof(pOleStreamHeader), NULL);
6944 IStream_Release(pStream);
6948 /* write a string to a stream, preceded by its length */
6949 static HRESULT STREAM_WriteString( IStream *stm, LPCWSTR string )
6956 len = WideCharToMultiByte( CP_ACP, 0, string, -1, NULL, 0, NULL, NULL);
6957 r = IStream_Write( stm, &len, sizeof(len), NULL);
6962 str = CoTaskMemAlloc( len );
6963 WideCharToMultiByte( CP_ACP, 0, string, -1, str, len, NULL, NULL);
6964 r = IStream_Write( stm, str, len, NULL);
6965 CoTaskMemFree( str );
6969 /* read a string preceded by its length from a stream */
6970 static HRESULT STREAM_ReadString( IStream *stm, LPWSTR *string )
6973 DWORD len, count = 0;
6977 r = IStream_Read( stm, &len, sizeof(len), &count );
6980 if( count != sizeof(len) )
6981 return E_OUTOFMEMORY;
6983 TRACE("%ld bytes\n",len);
6985 str = CoTaskMemAlloc( len );
6987 return E_OUTOFMEMORY;
6989 r = IStream_Read( stm, str, len, &count );
6994 CoTaskMemFree( str );
6995 return E_OUTOFMEMORY;
6998 TRACE("Read string %s\n",debugstr_an(str,len));
7000 len = MultiByteToWideChar( CP_ACP, 0, str, count, NULL, 0 );
7001 wstr = CoTaskMemAlloc( (len + 1)*sizeof (WCHAR) );
7003 MultiByteToWideChar( CP_ACP, 0, str, count, wstr, len );
7004 CoTaskMemFree( str );
7012 static HRESULT STORAGE_WriteCompObj( LPSTORAGE pstg, CLSID *clsid,
7013 LPCWSTR lpszUserType, LPCWSTR szClipName, LPCWSTR szProgIDName )
7017 static const WCHAR szwStreamName[] = {1, 'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7019 static const BYTE unknown1[12] =
7020 { 0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00,
7021 0xFF, 0xFF, 0xFF, 0xFF};
7022 static const BYTE unknown2[16] =
7023 { 0xF4, 0x39, 0xB2, 0x71, 0x00, 0x00, 0x00, 0x00,
7024 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
7026 TRACE("%p %s %s %s %s\n", pstg, debugstr_guid(clsid),
7027 debugstr_w(lpszUserType), debugstr_w(szClipName),
7028 debugstr_w(szProgIDName));
7030 /* Create a CompObj stream if it doesn't exist */
7031 r = IStorage_CreateStream(pstg, szwStreamName,
7032 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pstm );
7036 /* Write CompObj Structure to stream */
7037 r = IStream_Write(pstm, unknown1, sizeof(unknown1), NULL);
7039 if( SUCCEEDED( r ) )
7040 r = WriteClassStm( pstm, clsid );
7042 if( SUCCEEDED( r ) )
7043 r = STREAM_WriteString( pstm, lpszUserType );
7044 if( SUCCEEDED( r ) )
7045 r = STREAM_WriteString( pstm, szClipName );
7046 if( SUCCEEDED( r ) )
7047 r = STREAM_WriteString( pstm, szProgIDName );
7048 if( SUCCEEDED( r ) )
7049 r = IStream_Write(pstm, unknown2, sizeof(unknown2), NULL);
7051 IStream_Release( pstm );
7056 /***********************************************************************
7057 * WriteFmtUserTypeStg (OLE32.@)
7059 HRESULT WINAPI WriteFmtUserTypeStg(
7060 LPSTORAGE pstg, CLIPFORMAT cf, LPOLESTR lpszUserType)
7063 WCHAR szwClipName[0x40];
7064 CLSID clsid = CLSID_NULL;
7065 LPWSTR wstrProgID = NULL;
7068 TRACE("(%p,%x,%s)\n",pstg,cf,debugstr_w(lpszUserType));
7070 /* get the clipboard format name */
7071 n = GetClipboardFormatNameW( cf, szwClipName, sizeof(szwClipName) );
7074 TRACE("Clipboard name is %s\n", debugstr_w(szwClipName));
7076 /* FIXME: There's room to save a CLSID and its ProgID, but
7077 the CLSID is not looked up in the registry and in all the
7078 tests I wrote it was CLSID_NULL. Where does it come from?
7081 /* get the real program ID. This may fail, but that's fine */
7082 ProgIDFromCLSID(&clsid, &wstrProgID);
7084 TRACE("progid is %s\n",debugstr_w(wstrProgID));
7086 r = STORAGE_WriteCompObj( pstg, &clsid,
7087 lpszUserType, szwClipName, wstrProgID );
7089 CoTaskMemFree(wstrProgID);
7095 /******************************************************************************
7096 * ReadFmtUserTypeStg [OLE32.@]
7098 HRESULT WINAPI ReadFmtUserTypeStg (LPSTORAGE pstg, CLIPFORMAT* pcf, LPOLESTR* lplpszUserType)
7102 static const WCHAR szCompObj[] = { 1, 'C','o','m','p','O','b','j', 0 };
7103 unsigned char unknown1[12];
7104 unsigned char unknown2[16];
7106 LPWSTR szProgIDName = NULL, szCLSIDName = NULL, szOleTypeName = NULL;
7109 TRACE("(%p,%p,%p)\n", pstg, pcf, lplpszUserType);
7111 r = IStorage_OpenStream( pstg, szCompObj, NULL,
7112 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
7115 WARN("Failed to open stream r = %08lx\n", r);
7119 /* read the various parts of the structure */
7120 r = IStream_Read( stm, unknown1, sizeof(unknown1), &count );
7121 if( FAILED( r ) || ( count != sizeof(unknown1) ) )
7123 r = ReadClassStm( stm, &clsid );
7127 r = STREAM_ReadString( stm, &szCLSIDName );
7131 r = STREAM_ReadString( stm, &szOleTypeName );
7135 r = STREAM_ReadString( stm, &szProgIDName );
7139 r = IStream_Read( stm, unknown2, sizeof(unknown2), &count );
7140 if( FAILED( r ) || ( count != sizeof(unknown2) ) )
7143 /* ok, success... now we just need to store what we found */
7145 *pcf = RegisterClipboardFormatW( szOleTypeName );
7146 CoTaskMemFree( szOleTypeName );
7148 if( lplpszUserType )
7149 *lplpszUserType = szCLSIDName;
7150 CoTaskMemFree( szProgIDName );
7153 IStream_Release( stm );
7159 /*************************************************************************
7160 * OLECONVERT_CreateCompObjStream [Internal]
7162 * Creates a "\001CompObj" is the destination IStorage if necessary.
7165 * pStorage [I] The dest IStorage to create the CompObj Stream
7167 * strOleTypeName [I] The ProgID
7171 * Failure: REGDB_E_CLASSNOTREG if cannot reconstruct the stream
7174 * This function is used by OleConvertOLESTREAMToIStorage only.
7176 * The stream data is stored in the OLESTREAM and there should be
7177 * no need to recreate the stream. If the stream is manually
7178 * deleted it will attempt to create it by querying the registry.
7182 HRESULT OLECONVERT_CreateCompObjStream(LPSTORAGE pStorage, LPCSTR strOleTypeName)
7185 HRESULT hStorageRes, hRes = S_OK;
7186 OLECONVERT_ISTORAGE_COMPOBJ IStorageCompObj;
7187 static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7188 WCHAR bufferW[OLESTREAM_MAX_STR_LEN];
7190 BYTE pCompObjUnknown1[] = {0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};
7191 BYTE pCompObjUnknown2[] = {0xF4, 0x39, 0xB2, 0x71};
7193 /* Initialize the CompObj structure */
7194 memset(&IStorageCompObj, 0, sizeof(IStorageCompObj));
7195 memcpy(&(IStorageCompObj.byUnknown1), pCompObjUnknown1, sizeof(pCompObjUnknown1));
7196 memcpy(&(IStorageCompObj.byUnknown2), pCompObjUnknown2, sizeof(pCompObjUnknown2));
7199 /* Create a CompObj stream if it doesn't exist */
7200 hStorageRes = IStorage_CreateStream(pStorage, wstrStreamName,
7201 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
7202 if(hStorageRes == S_OK)
7204 /* copy the OleTypeName to the compobj struct */
7205 IStorageCompObj.dwOleTypeNameLength = strlen(strOleTypeName)+1;
7206 strcpy(IStorageCompObj.strOleTypeName, strOleTypeName);
7208 /* copy the OleTypeName to the compobj struct */
7209 /* Note: in the test made, these were Identical */
7210 IStorageCompObj.dwProgIDNameLength = strlen(strOleTypeName)+1;
7211 strcpy(IStorageCompObj.strProgIDName, strOleTypeName);
7214 MultiByteToWideChar( CP_ACP, 0, IStorageCompObj.strProgIDName, -1,
7215 bufferW, OLESTREAM_MAX_STR_LEN );
7216 hRes = CLSIDFromProgID(bufferW, &(IStorageCompObj.clsid));
7222 /* Get the CLSID Default Name from the Registry */
7223 hErr = RegOpenKeyA(HKEY_CLASSES_ROOT, IStorageCompObj.strProgIDName, &hKey);
7224 if(hErr == ERROR_SUCCESS)
7226 char strTemp[OLESTREAM_MAX_STR_LEN];
7227 IStorageCompObj.dwCLSIDNameLength = OLESTREAM_MAX_STR_LEN;
7228 hErr = RegQueryValueA(hKey, NULL, strTemp, (LONG*) &(IStorageCompObj.dwCLSIDNameLength));
7229 if(hErr == ERROR_SUCCESS)
7231 strcpy(IStorageCompObj.strCLSIDName, strTemp);
7237 /* Write CompObj Structure to stream */
7238 hRes = IStream_Write(pStream, IStorageCompObj.byUnknown1, sizeof(IStorageCompObj.byUnknown1), NULL);
7240 WriteClassStm(pStream,&(IStorageCompObj.clsid));
7242 hRes = IStream_Write(pStream, &(IStorageCompObj.dwCLSIDNameLength), sizeof(IStorageCompObj.dwCLSIDNameLength), NULL);
7243 if(IStorageCompObj.dwCLSIDNameLength > 0)
7245 hRes = IStream_Write(pStream, IStorageCompObj.strCLSIDName, IStorageCompObj.dwCLSIDNameLength, NULL);
7247 hRes = IStream_Write(pStream, &(IStorageCompObj.dwOleTypeNameLength) , sizeof(IStorageCompObj.dwOleTypeNameLength), NULL);
7248 if(IStorageCompObj.dwOleTypeNameLength > 0)
7250 hRes = IStream_Write(pStream, IStorageCompObj.strOleTypeName , IStorageCompObj.dwOleTypeNameLength, NULL);
7252 hRes = IStream_Write(pStream, &(IStorageCompObj.dwProgIDNameLength) , sizeof(IStorageCompObj.dwProgIDNameLength), NULL);
7253 if(IStorageCompObj.dwProgIDNameLength > 0)
7255 hRes = IStream_Write(pStream, IStorageCompObj.strProgIDName , IStorageCompObj.dwProgIDNameLength, NULL);
7257 hRes = IStream_Write(pStream, IStorageCompObj.byUnknown2 , sizeof(IStorageCompObj.byUnknown2), NULL);
7258 IStream_Release(pStream);
7264 /*************************************************************************
7265 * OLECONVERT_CreateOlePresStream[Internal]
7267 * Creates the "\002OlePres000" Stream with the Metafile data
7270 * pStorage [I] The dest IStorage to create \002OLEPres000 stream in.
7271 * dwExtentX [I] Width of the Metafile
7272 * dwExtentY [I] Height of the Metafile
7273 * pData [I] Metafile data
7274 * dwDataLength [I] Size of the Metafile data
7278 * Failure: CONVERT10_E_OLESTREAM_PUT for invalid Put
7281 * This function is used by OleConvertOLESTREAMToIStorage only.
7284 static void OLECONVERT_CreateOlePresStream(LPSTORAGE pStorage, DWORD dwExtentX, DWORD dwExtentY , BYTE *pData, DWORD dwDataLength)
7288 static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
7289 BYTE pOlePresStreamHeader [] =
7291 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00,
7292 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
7293 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
7294 0x00, 0x00, 0x00, 0x00
7297 BYTE pOlePresStreamHeaderEmpty [] =
7299 0x00, 0x00, 0x00, 0x00,
7300 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
7301 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
7302 0x00, 0x00, 0x00, 0x00
7305 /* Create the OlePres000 Stream */
7306 hRes = IStorage_CreateStream(pStorage, wstrStreamName,
7307 STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
7312 OLECONVERT_ISTORAGE_OLEPRES OlePres;
7314 memset(&OlePres, 0, sizeof(OlePres));
7315 /* Do we have any metafile data to save */
7316 if(dwDataLength > 0)
7318 memcpy(OlePres.byUnknown1, pOlePresStreamHeader, sizeof(pOlePresStreamHeader));
7319 nHeaderSize = sizeof(pOlePresStreamHeader);
7323 memcpy(OlePres.byUnknown1, pOlePresStreamHeaderEmpty, sizeof(pOlePresStreamHeaderEmpty));
7324 nHeaderSize = sizeof(pOlePresStreamHeaderEmpty);
7326 /* Set width and height of the metafile */
7327 OlePres.dwExtentX = dwExtentX;
7328 OlePres.dwExtentY = -dwExtentY;
7330 /* Set Data and Length */
7331 if(dwDataLength > sizeof(METAFILEPICT16))
7333 OlePres.dwSize = dwDataLength - sizeof(METAFILEPICT16);
7334 OlePres.pData = &(pData[8]);
7336 /* Save OlePres000 Data to Stream */
7337 hRes = IStream_Write(pStream, OlePres.byUnknown1, nHeaderSize, NULL);
7338 hRes = IStream_Write(pStream, &(OlePres.dwExtentX), sizeof(OlePres.dwExtentX), NULL);
7339 hRes = IStream_Write(pStream, &(OlePres.dwExtentY), sizeof(OlePres.dwExtentY), NULL);
7340 hRes = IStream_Write(pStream, &(OlePres.dwSize), sizeof(OlePres.dwSize), NULL);
7341 if(OlePres.dwSize > 0)
7343 hRes = IStream_Write(pStream, OlePres.pData, OlePres.dwSize, NULL);
7345 IStream_Release(pStream);
7349 /*************************************************************************
7350 * OLECONVERT_CreateOle10NativeStream [Internal]
7352 * Creates the "\001Ole10Native" Stream (should contain a BMP)
7355 * pStorage [I] Dest storage to create the stream in
7356 * pData [I] Ole10 Native Data (ex. bmp)
7357 * dwDataLength [I] Size of the Ole10 Native Data
7363 * This function is used by OleConvertOLESTREAMToIStorage only.
7365 * Might need to verify the data and return appropriate error message
7368 static void OLECONVERT_CreateOle10NativeStream(LPSTORAGE pStorage, BYTE *pData, DWORD dwDataLength)
7372 static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7374 /* Create the Ole10Native Stream */
7375 hRes = IStorage_CreateStream(pStorage, wstrStreamName,
7376 STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
7380 /* Write info to stream */
7381 hRes = IStream_Write(pStream, &dwDataLength, sizeof(dwDataLength), NULL);
7382 hRes = IStream_Write(pStream, pData, dwDataLength, NULL);
7383 IStream_Release(pStream);
7388 /*************************************************************************
7389 * OLECONVERT_GetOLE10ProgID [Internal]
7391 * Finds the ProgID (or OleTypeID) from the IStorage
7394 * pStorage [I] The Src IStorage to get the ProgID
7395 * strProgID [I] the ProgID string to get
7396 * dwSize [I] the size of the string
7400 * Failure: REGDB_E_CLASSNOTREG if cannot reconstruct the stream
7403 * This function is used by OleConvertIStorageToOLESTREAM only.
7407 static HRESULT OLECONVERT_GetOLE10ProgID(LPSTORAGE pStorage, char *strProgID, DWORD *dwSize)
7411 LARGE_INTEGER iSeekPos;
7412 OLECONVERT_ISTORAGE_COMPOBJ CompObj;
7413 static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7415 /* Open the CompObj Stream */
7416 hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7417 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream );
7421 /*Get the OleType from the CompObj Stream */
7422 iSeekPos.u.LowPart = sizeof(CompObj.byUnknown1) + sizeof(CompObj.clsid);
7423 iSeekPos.u.HighPart = 0;
7425 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
7426 IStream_Read(pStream, &CompObj.dwCLSIDNameLength, sizeof(CompObj.dwCLSIDNameLength), NULL);
7427 iSeekPos.u.LowPart = CompObj.dwCLSIDNameLength;
7428 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);
7429 IStream_Read(pStream, &CompObj.dwOleTypeNameLength, sizeof(CompObj.dwOleTypeNameLength), NULL);
7430 iSeekPos.u.LowPart = CompObj.dwOleTypeNameLength;
7431 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);
7433 IStream_Read(pStream, dwSize, sizeof(*dwSize), NULL);
7436 IStream_Read(pStream, strProgID, *dwSize, NULL);
7438 IStream_Release(pStream);
7443 LPOLESTR wstrProgID;
7445 /* Get the OleType from the registry */
7446 REFCLSID clsid = &(stat.clsid);
7447 IStorage_Stat(pStorage, &stat, STATFLAG_NONAME);
7448 hRes = ProgIDFromCLSID(clsid, &wstrProgID);
7451 *dwSize = WideCharToMultiByte(CP_ACP, 0, wstrProgID, -1, strProgID, *dwSize, NULL, FALSE);
7458 /*************************************************************************
7459 * OLECONVERT_GetOle10PresData [Internal]
7461 * Converts IStorage "/001Ole10Native" stream to a OLE10 Stream
7464 * pStorage [I] Src IStroage
7465 * pOleStream [I] Dest OleStream Mem Struct
7471 * This function is used by OleConvertIStorageToOLESTREAM only.
7473 * Memory allocated for pData must be freed by the caller
7477 static void OLECONVERT_GetOle10PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
7482 static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7484 /* Initialize Default data for OLESTREAM */
7485 pOleStreamData[0].dwOleID = OLESTREAM_ID;
7486 pOleStreamData[0].dwTypeID = 2;
7487 pOleStreamData[1].dwOleID = OLESTREAM_ID;
7488 pOleStreamData[1].dwTypeID = 0;
7489 pOleStreamData[0].dwMetaFileWidth = 0;
7490 pOleStreamData[0].dwMetaFileHeight = 0;
7491 pOleStreamData[0].pData = NULL;
7492 pOleStreamData[1].pData = NULL;
7494 /* Open Ole10Native Stream */
7495 hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7496 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream );
7500 /* Read Size and Data */
7501 IStream_Read(pStream, &(pOleStreamData->dwDataLength), sizeof(pOleStreamData->dwDataLength), NULL);
7502 if(pOleStreamData->dwDataLength > 0)
7504 pOleStreamData->pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData->dwDataLength);
7505 IStream_Read(pStream, pOleStreamData->pData, pOleStreamData->dwDataLength, NULL);
7507 IStream_Release(pStream);
7513 /*************************************************************************
7514 * OLECONVERT_GetOle20PresData[Internal]
7516 * Converts IStorage "/002OlePres000" stream to a OLE10 Stream
7519 * pStorage [I] Src IStroage
7520 * pOleStreamData [I] Dest OleStream Mem Struct
7526 * This function is used by OleConvertIStorageToOLESTREAM only.
7528 * Memory allocated for pData must be freed by the caller
7530 static void OLECONVERT_GetOle20PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
7534 OLECONVERT_ISTORAGE_OLEPRES olePress;
7535 static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
7537 /* Initialize Default data for OLESTREAM */
7538 pOleStreamData[0].dwOleID = OLESTREAM_ID;
7539 pOleStreamData[0].dwTypeID = 2;
7540 pOleStreamData[0].dwMetaFileWidth = 0;
7541 pOleStreamData[0].dwMetaFileHeight = 0;
7542 pOleStreamData[0].dwDataLength = OLECONVERT_WriteOLE20ToBuffer(pStorage, &(pOleStreamData[0].pData));
7543 pOleStreamData[1].dwOleID = OLESTREAM_ID;
7544 pOleStreamData[1].dwTypeID = 0;
7545 pOleStreamData[1].dwOleTypeNameLength = 0;
7546 pOleStreamData[1].strOleTypeName[0] = 0;
7547 pOleStreamData[1].dwMetaFileWidth = 0;
7548 pOleStreamData[1].dwMetaFileHeight = 0;
7549 pOleStreamData[1].pData = NULL;
7550 pOleStreamData[1].dwDataLength = 0;
7553 /* Open OlePress000 stream */
7554 hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7555 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream );
7558 LARGE_INTEGER iSeekPos;
7559 METAFILEPICT16 MetaFilePict;
7560 static const char strMetafilePictName[] = "METAFILEPICT";
7562 /* Set the TypeID for a Metafile */
7563 pOleStreamData[1].dwTypeID = 5;
7565 /* Set the OleTypeName to Metafile */
7566 pOleStreamData[1].dwOleTypeNameLength = strlen(strMetafilePictName) +1;
7567 strcpy(pOleStreamData[1].strOleTypeName, strMetafilePictName);
7569 iSeekPos.u.HighPart = 0;
7570 iSeekPos.u.LowPart = sizeof(olePress.byUnknown1);
7572 /* Get Presentation Data */
7573 IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
7574 IStream_Read(pStream, &(olePress.dwExtentX), sizeof(olePress.dwExtentX), NULL);
7575 IStream_Read(pStream, &(olePress.dwExtentY), sizeof(olePress.dwExtentY), NULL);
7576 IStream_Read(pStream, &(olePress.dwSize), sizeof(olePress.dwSize), NULL);
7578 /*Set width and Height */
7579 pOleStreamData[1].dwMetaFileWidth = olePress.dwExtentX;
7580 pOleStreamData[1].dwMetaFileHeight = -olePress.dwExtentY;
7581 if(olePress.dwSize > 0)
7584 pOleStreamData[1].dwDataLength = olePress.dwSize + sizeof(METAFILEPICT16);
7586 /* Set MetaFilePict struct */
7587 MetaFilePict.mm = 8;
7588 MetaFilePict.xExt = olePress.dwExtentX;
7589 MetaFilePict.yExt = olePress.dwExtentY;
7590 MetaFilePict.hMF = 0;
7592 /* Get Metafile Data */
7593 pOleStreamData[1].pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData[1].dwDataLength);
7594 memcpy(pOleStreamData[1].pData, &MetaFilePict, sizeof(MetaFilePict));
7595 IStream_Read(pStream, &(pOleStreamData[1].pData[sizeof(MetaFilePict)]), pOleStreamData[1].dwDataLength-sizeof(METAFILEPICT16), NULL);
7597 IStream_Release(pStream);
7601 /*************************************************************************
7602 * OleConvertOLESTREAMToIStorage [OLE32.@]
7607 * DVTARGETDEVICE paramenter is not handled
7608 * Still unsure of some mem fields for OLE 10 Stream
7609 * Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
7610 * and "\001OLE" streams
7613 HRESULT WINAPI OleConvertOLESTREAMToIStorage (
7614 LPOLESTREAM pOleStream,
7616 const DVTARGETDEVICE* ptd)
7620 OLECONVERT_OLESTREAM_DATA pOleStreamData[2];
7622 memset(pOleStreamData, 0, sizeof(pOleStreamData));
7626 FIXME("DVTARGETDEVICE is not NULL, unhandled parameter\n");
7629 if(pstg == NULL || pOleStream == NULL)
7631 hRes = E_INVALIDARG;
7636 /* Load the OLESTREAM to Memory */
7637 hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[0], TRUE);
7642 /* Load the OLESTREAM to Memory (part 2)*/
7643 hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[1], FALSE);
7649 if(pOleStreamData[0].dwDataLength > sizeof(STORAGE_magic))
7651 /* Do we have the IStorage Data in the OLESTREAM */
7652 if(memcmp(pOleStreamData[0].pData, STORAGE_magic, sizeof(STORAGE_magic)) ==0)
7654 OLECONVERT_GetOLE20FromOLE10(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
7655 OLECONVERT_CreateOlePresStream(pstg, pOleStreamData[1].dwMetaFileWidth, pOleStreamData[1].dwMetaFileHeight, pOleStreamData[1].pData, pOleStreamData[1].dwDataLength);
7659 /* It must be an original OLE 1.0 source */
7660 OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
7665 /* It must be an original OLE 1.0 source */
7666 OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
7669 /* Create CompObj Stream if necessary */
7670 hRes = OLECONVERT_CreateCompObjStream(pstg, pOleStreamData[0].strOleTypeName);
7673 /*Create the Ole Stream if necessary */
7674 OLECONVERT_CreateOleStream(pstg);
7679 /* Free allocated memory */
7680 for(i=0; i < 2; i++)
7682 HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
7683 HeapFree(GetProcessHeap(),0,pOleStreamData[i].pstrOleObjFileName);
7684 pOleStreamData[i].pstrOleObjFileName = NULL;
7689 /*************************************************************************
7690 * OleConvertIStorageToOLESTREAM [OLE32.@]
7697 * Still unsure of some mem fields for OLE 10 Stream
7698 * Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
7699 * and "\001OLE" streams.
7702 HRESULT WINAPI OleConvertIStorageToOLESTREAM (
7704 LPOLESTREAM pOleStream)
7707 HRESULT hRes = S_OK;
7709 OLECONVERT_OLESTREAM_DATA pOleStreamData[2];
7710 static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7713 memset(pOleStreamData, 0, sizeof(pOleStreamData));
7715 if(pstg == NULL || pOleStream == NULL)
7717 hRes = E_INVALIDARG;
7721 /* Get the ProgID */
7722 pOleStreamData[0].dwOleTypeNameLength = OLESTREAM_MAX_STR_LEN;
7723 hRes = OLECONVERT_GetOLE10ProgID(pstg, pOleStreamData[0].strOleTypeName, &(pOleStreamData[0].dwOleTypeNameLength));
7727 /* Was it originally Ole10 */
7728 hRes = IStorage_OpenStream(pstg, wstrStreamName, 0, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream);
7731 IStream_Release(pStream);
7732 /* Get Presentation Data for Ole10Native */
7733 OLECONVERT_GetOle10PresData(pstg, pOleStreamData);
7737 /* Get Presentation Data (OLE20) */
7738 OLECONVERT_GetOle20PresData(pstg, pOleStreamData);
7741 /* Save OLESTREAM */
7742 hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[0]), pOleStream);
7745 hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[1]), pOleStream);
7750 /* Free allocated memory */
7751 for(i=0; i < 2; i++)
7753 HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
7759 /***********************************************************************
7760 * GetConvertStg (OLE32.@)
7762 HRESULT WINAPI GetConvertStg(IStorage *stg) {
7763 FIXME("unimplemented stub!\n");
7767 /******************************************************************************
7768 * StgIsStorageFile [OLE32.@]
7769 * Verify if the file contains a storage object
7775 * S_OK if file has magic bytes as a storage object
7776 * S_FALSE if file is not storage
7779 StgIsStorageFile(LPCOLESTR fn)
7785 TRACE("(\'%s\')\n", debugstr_w(fn));
7786 hf = CreateFileW(fn, GENERIC_READ,
7787 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
7788 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
7790 if (hf == INVALID_HANDLE_VALUE)
7791 return STG_E_FILENOTFOUND;
7793 if (!ReadFile(hf, magic, 8, &bytes_read, NULL))
7795 WARN(" unable to read file\n");
7802 if (bytes_read != 8) {
7803 WARN(" too short\n");
7807 if (!memcmp(magic,STORAGE_magic,8)) {
7812 WARN(" -> Invalid header.\n");