gdiplus: Implement GdipGetRegionScans.
[wine] / dlls / ole32 / stg_prop.c
1 /*
2  * Compound Storage (32 bit version)
3  * Storage implementation
4  *
5  * This file contains the compound file implementation
6  * of the storage interface.
7  *
8  * Copyright 1999 Francis Beaudet
9  * Copyright 1999 Sylvain St-Germain
10  * Copyright 1999 Thuy Nguyen
11  * Copyright 2005 Mike McCormack
12  * Copyright 2005 Juan Lang
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  *
28  * TODO:
29  * - I don't honor the maximum property set size.
30  * - Certain bogus files could result in reading past the end of a buffer.
31  * - Mac-generated files won't be read correctly, even if they're little
32  *   endian, because I disregard whether the generator was a Mac.  This means
33  *   strings will probably be munged (as I don't understand Mac scripts.)
34  * - Not all PROPVARIANT types are supported.
35  * - User defined properties are not supported, see comment in
36  *   PropertyStorage_ReadFromStream
37  */
38
39 #include <assert.h>
40 #include <stdarg.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44
45 #define COBJMACROS
46 #define NONAMELESSUNION
47 #define NONAMELESSSTRUCT
48
49 #include "windef.h"
50 #include "winbase.h"
51 #include "winnls.h"
52 #include "winuser.h"
53 #include "wine/unicode.h"
54 #include "wine/debug.h"
55 #include "dictionary.h"
56 #include "storage32.h"
57 #include "enumx.h"
58
59 WINE_DEFAULT_DEBUG_CHANNEL(storage);
60
61 static inline StorageImpl *impl_from_IPropertySetStorage( IPropertySetStorage *iface )
62 {
63     return (StorageImpl *)((char*)iface - FIELD_OFFSET(StorageImpl, base.pssVtbl));
64 }
65
66 /* These are documented in MSDN,
67  * but they don't seem to be in any header file.
68  */
69 #define PROPSETHDR_BYTEORDER_MAGIC      0xfffe
70 #define PROPSETHDR_OSVER_KIND_WIN16     0
71 #define PROPSETHDR_OSVER_KIND_MAC       1
72 #define PROPSETHDR_OSVER_KIND_WIN32     2
73
74 #define CP_UNICODE 1200
75
76 #define MAX_VERSION_0_PROP_NAME_LENGTH 256
77
78 #define CFTAG_WINDOWS   (-1L)
79 #define CFTAG_MACINTOSH (-2L)
80 #define CFTAG_FMTID     (-3L)
81 #define CFTAG_NODATA      0L
82
83 typedef struct tagPROPERTYSETHEADER
84 {
85     WORD  wByteOrder; /* always 0xfffe */
86     WORD  wFormat;    /* can be zero or one */
87     DWORD dwOSVer;    /* OS version of originating system */
88     CLSID clsid;      /* application CLSID */
89     DWORD reserved;   /* always 1 */
90 } PROPERTYSETHEADER;
91
92 typedef struct tagFORMATIDOFFSET
93 {
94     FMTID fmtid;
95     DWORD dwOffset; /* from beginning of stream */
96 } FORMATIDOFFSET;
97
98 typedef struct tagPROPERTYSECTIONHEADER
99 {
100     DWORD cbSection;
101     DWORD cProperties;
102 } PROPERTYSECTIONHEADER;
103
104 typedef struct tagPROPERTYIDOFFSET
105 {
106     DWORD propid;
107     DWORD dwOffset; /* from beginning of section */
108 } PROPERTYIDOFFSET;
109
110 typedef struct tagPropertyStorage_impl PropertyStorage_impl;
111
112 /* Initializes the property storage from the stream (and undoes any uncommitted
113  * changes in the process.)  Returns an error if there is an error reading or
114  * if the stream format doesn't match what's expected.
115  */
116 static HRESULT PropertyStorage_ReadFromStream(PropertyStorage_impl *);
117
118 static HRESULT PropertyStorage_WriteToStream(PropertyStorage_impl *);
119
120 /* Creates the dictionaries used by the property storage.  If successful, all
121  * the dictionaries have been created.  If failed, none has been.  (This makes
122  * it a bit easier to deal with destroying them.)
123  */
124 static HRESULT PropertyStorage_CreateDictionaries(PropertyStorage_impl *);
125
126 static void PropertyStorage_DestroyDictionaries(PropertyStorage_impl *);
127
128 /* Copies from propvar to prop.  If propvar's type is VT_LPSTR, copies the
129  * string using PropertyStorage_StringCopy.
130  */
131 static HRESULT PropertyStorage_PropVariantCopy(PROPVARIANT *prop,
132  const PROPVARIANT *propvar, LCID targetCP, LCID srcCP);
133
134 /* Copies the string src, which is encoded using code page srcCP, and returns
135  * it in *dst, in the code page specified by targetCP.  The returned string is
136  * allocated using CoTaskMemAlloc.
137  * If srcCP is CP_UNICODE, src is in fact an LPCWSTR.  Similarly, if targetCP
138  * is CP_UNICODE, the returned string is in fact an LPWSTR.
139  * Returns S_OK on success, something else on failure.
140  */
141 static HRESULT PropertyStorage_StringCopy(LPCSTR src, LCID srcCP, LPSTR *dst,
142  LCID targetCP);
143
144 static const IPropertyStorageVtbl IPropertyStorage_Vtbl;
145 static const IEnumSTATPROPSETSTGVtbl IEnumSTATPROPSETSTG_Vtbl;
146 static const IEnumSTATPROPSTGVtbl IEnumSTATPROPSTG_Vtbl;
147 static HRESULT create_EnumSTATPROPSETSTG(StorageImpl *, IEnumSTATPROPSETSTG**);
148 static HRESULT create_EnumSTATPROPSTG(PropertyStorage_impl *, IEnumSTATPROPSTG**);
149
150 /***********************************************************************
151  * Implementation of IPropertyStorage
152  */
153 struct tagPropertyStorage_impl
154 {
155     const IPropertyStorageVtbl *vtbl;
156     LONG ref;
157     CRITICAL_SECTION cs;
158     IStream *stm;
159     BOOL  dirty;
160     FMTID fmtid;
161     CLSID clsid;
162     WORD  format;
163     DWORD originatorOS;
164     DWORD grfFlags;
165     DWORD grfMode;
166     UINT  codePage;
167     LCID  locale;
168     PROPID highestProp;
169     struct dictionary *name_to_propid;
170     struct dictionary *propid_to_name;
171     struct dictionary *propid_to_prop;
172 };
173
174 /************************************************************************
175  * IPropertyStorage_fnQueryInterface (IPropertyStorage)
176  */
177 static HRESULT WINAPI IPropertyStorage_fnQueryInterface(
178     IPropertyStorage *iface,
179     REFIID riid,
180     void** ppvObject)
181 {
182     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
183
184     TRACE("(%p, %s, %p)\n", This, debugstr_guid(riid), ppvObject);
185
186     if (!ppvObject)
187         return E_INVALIDARG;
188
189     *ppvObject = 0;
190
191     if (IsEqualGUID(&IID_IUnknown, riid) ||
192         IsEqualGUID(&IID_IPropertyStorage, riid))
193     {
194         IPropertyStorage_AddRef(iface);
195         *ppvObject = iface;
196         return S_OK;
197     }
198
199     return E_NOINTERFACE;
200 }
201
202 /************************************************************************
203  * IPropertyStorage_fnAddRef (IPropertyStorage)
204  */
205 static ULONG WINAPI IPropertyStorage_fnAddRef(
206     IPropertyStorage *iface)
207 {
208     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
209     return InterlockedIncrement(&This->ref);
210 }
211
212 /************************************************************************
213  * IPropertyStorage_fnRelease (IPropertyStorage)
214  */
215 static ULONG WINAPI IPropertyStorage_fnRelease(
216     IPropertyStorage *iface)
217 {
218     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
219     ULONG ref;
220
221     ref = InterlockedDecrement(&This->ref);
222     if (ref == 0)
223     {
224         TRACE("Destroying %p\n", This);
225         if (This->dirty)
226             IPropertyStorage_Commit(iface, STGC_DEFAULT);
227         IStream_Release(This->stm);
228         This->cs.DebugInfo->Spare[0] = 0;
229         DeleteCriticalSection(&This->cs);
230         PropertyStorage_DestroyDictionaries(This);
231         HeapFree(GetProcessHeap(), 0, This);
232     }
233     return ref;
234 }
235
236 static PROPVARIANT *PropertyStorage_FindProperty(PropertyStorage_impl *This,
237  DWORD propid)
238 {
239     PROPVARIANT *ret = NULL;
240
241     dictionary_find(This->propid_to_prop, UlongToPtr(propid), (void **)&ret);
242     TRACE("returning %p\n", ret);
243     return ret;
244 }
245
246 /* Returns NULL if name is NULL. */
247 static PROPVARIANT *PropertyStorage_FindPropertyByName(
248  PropertyStorage_impl *This, LPCWSTR name)
249 {
250     PROPVARIANT *ret = NULL;
251     void *propid;
252
253     if (!name)
254         return NULL;
255     if (This->codePage == CP_UNICODE)
256     {
257         if (dictionary_find(This->name_to_propid, name, &propid))
258             ret = PropertyStorage_FindProperty(This, PtrToUlong(propid));
259     }
260     else
261     {
262         LPSTR ansiName;
263         HRESULT hr = PropertyStorage_StringCopy((LPCSTR)name, CP_UNICODE,
264          &ansiName, This->codePage);
265
266         if (SUCCEEDED(hr))
267         {
268             if (dictionary_find(This->name_to_propid, ansiName, &propid))
269                 ret = PropertyStorage_FindProperty(This, PtrToUlong(propid));
270             CoTaskMemFree(ansiName);
271         }
272     }
273     TRACE("returning %p\n", ret);
274     return ret;
275 }
276
277 static LPWSTR PropertyStorage_FindPropertyNameById(PropertyStorage_impl *This,
278  DWORD propid)
279 {
280     LPWSTR ret = NULL;
281
282     dictionary_find(This->propid_to_name, UlongToPtr(propid), (void **)&ret);
283     TRACE("returning %p\n", ret);
284     return ret;
285 }
286
287 /************************************************************************
288  * IPropertyStorage_fnReadMultiple (IPropertyStorage)
289  */
290 static HRESULT WINAPI IPropertyStorage_fnReadMultiple(
291     IPropertyStorage* iface,
292     ULONG cpspec,
293     const PROPSPEC rgpspec[],
294     PROPVARIANT rgpropvar[])
295 {
296     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
297     HRESULT hr = S_OK;
298     ULONG i;
299
300     TRACE("(%p, %d, %p, %p)\n", iface, cpspec, rgpspec, rgpropvar);
301
302     if (!cpspec)
303         return S_FALSE;
304     if (!rgpspec || !rgpropvar)
305         return E_INVALIDARG;
306     EnterCriticalSection(&This->cs);
307     for (i = 0; i < cpspec; i++)
308     {
309         PropVariantInit(&rgpropvar[i]);
310         if (rgpspec[i].ulKind == PRSPEC_LPWSTR)
311         {
312             PROPVARIANT *prop = PropertyStorage_FindPropertyByName(This,
313              rgpspec[i].u.lpwstr);
314
315             if (prop)
316                 PropertyStorage_PropVariantCopy(&rgpropvar[i], prop, GetACP(),
317                  This->codePage);
318         }
319         else
320         {
321             switch (rgpspec[i].u.propid)
322             {
323                 case PID_CODEPAGE:
324                     rgpropvar[i].vt = VT_I2;
325                     rgpropvar[i].u.iVal = This->codePage;
326                     break;
327                 case PID_LOCALE:
328                     rgpropvar[i].vt = VT_I4;
329                     rgpropvar[i].u.lVal = This->locale;
330                     break;
331                 default:
332                 {
333                     PROPVARIANT *prop = PropertyStorage_FindProperty(This,
334                      rgpspec[i].u.propid);
335
336                     if (prop)
337                         PropertyStorage_PropVariantCopy(&rgpropvar[i], prop,
338                          GetACP(), This->codePage);
339                     else
340                         hr = S_FALSE;
341                 }
342             }
343         }
344     }
345     LeaveCriticalSection(&This->cs);
346     return hr;
347 }
348
349 static HRESULT PropertyStorage_StringCopy(LPCSTR src, LCID srcCP, LPSTR *dst,
350  LCID dstCP)
351 {
352     HRESULT hr = S_OK;
353     int len;
354
355     TRACE("%s, %p, %d, %d\n",
356      srcCP == CP_UNICODE ? debugstr_w((LPCWSTR)src) : debugstr_a(src), dst,
357      dstCP, srcCP);
358     assert(src);
359     assert(dst);
360     *dst = NULL;
361     if (dstCP == srcCP)
362     {
363         size_t len;
364
365         if (dstCP == CP_UNICODE)
366             len = (strlenW((LPCWSTR)src) + 1) * sizeof(WCHAR);
367         else
368             len = strlen(src) + 1;
369         *dst = CoTaskMemAlloc(len * sizeof(WCHAR));
370         if (!*dst)
371             hr = STG_E_INSUFFICIENTMEMORY;
372         else
373             memcpy(*dst, src, len);
374     }
375     else
376     {
377         if (dstCP == CP_UNICODE)
378         {
379             len = MultiByteToWideChar(srcCP, 0, src, -1, NULL, 0);
380             *dst = CoTaskMemAlloc(len * sizeof(WCHAR));
381             if (!*dst)
382                 hr = STG_E_INSUFFICIENTMEMORY;
383             else
384                 MultiByteToWideChar(srcCP, 0, src, -1, (LPWSTR)*dst, len);
385         }
386         else
387         {
388             LPCWSTR wideStr = NULL;
389             LPWSTR wideStr_tmp = NULL;
390
391             if (srcCP == CP_UNICODE)
392                 wideStr = (LPCWSTR)src;
393             else
394             {
395                 len = MultiByteToWideChar(srcCP, 0, src, -1, NULL, 0);
396                 wideStr_tmp = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
397                 if (wideStr_tmp)
398                 {
399                     MultiByteToWideChar(srcCP, 0, src, -1, wideStr_tmp, len);
400                     wideStr = wideStr_tmp;
401                 }
402                 else
403                     hr = STG_E_INSUFFICIENTMEMORY;
404             }
405             if (SUCCEEDED(hr))
406             {
407                 len = WideCharToMultiByte(dstCP, 0, wideStr, -1, NULL, 0,
408                  NULL, NULL);
409                 *dst = CoTaskMemAlloc(len);
410                 if (!*dst)
411                     hr = STG_E_INSUFFICIENTMEMORY;
412                 else
413                 {
414                     BOOL defCharUsed = FALSE;
415
416                     if (WideCharToMultiByte(dstCP, 0, wideStr, -1, *dst, len,
417                      NULL, &defCharUsed) == 0 || defCharUsed)
418                     {
419                         CoTaskMemFree(*dst);
420                         *dst = NULL;
421                         hr = HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION);
422                     }
423                 }
424             }
425             HeapFree(GetProcessHeap(), 0, wideStr_tmp);
426         }
427     }
428     TRACE("returning 0x%08x (%s)\n", hr,
429      dstCP == CP_UNICODE ? debugstr_w((LPCWSTR)*dst) : debugstr_a(*dst));
430     return hr;
431 }
432
433 static HRESULT PropertyStorage_PropVariantCopy(PROPVARIANT *prop,
434  const PROPVARIANT *propvar, LCID targetCP, LCID srcCP)
435 {
436     HRESULT hr = S_OK;
437
438     assert(prop);
439     assert(propvar);
440     if (propvar->vt == VT_LPSTR)
441     {
442         hr = PropertyStorage_StringCopy(propvar->u.pszVal, srcCP,
443          &prop->u.pszVal, targetCP);
444         if (SUCCEEDED(hr))
445             prop->vt = VT_LPSTR;
446     }
447     else
448         PropVariantCopy(prop, propvar);
449     return hr;
450 }
451
452 /* Stores the property with id propid and value propvar into this property
453  * storage.  lcid is ignored if propvar's type is not VT_LPSTR.  If propvar's
454  * type is VT_LPSTR, converts the string using lcid as the source code page
455  * and This->codePage as the target code page before storing.
456  * As a side effect, may change This->format to 1 if the type of propvar is
457  * a version 1-only property.
458  */
459 static HRESULT PropertyStorage_StorePropWithId(PropertyStorage_impl *This,
460  PROPID propid, const PROPVARIANT *propvar, LCID lcid)
461 {
462     HRESULT hr = S_OK;
463     PROPVARIANT *prop = PropertyStorage_FindProperty(This, propid);
464
465     assert(propvar);
466     if (propvar->vt & VT_BYREF || propvar->vt & VT_ARRAY)
467         This->format = 1;
468     switch (propvar->vt)
469     {
470     case VT_DECIMAL:
471     case VT_I1:
472     case VT_INT:
473     case VT_UINT:
474     case VT_VECTOR|VT_I1:
475         This->format = 1;
476     }
477     TRACE("Setting 0x%08x to type %d\n", propid, propvar->vt);
478     if (prop)
479     {
480         PropVariantClear(prop);
481         hr = PropertyStorage_PropVariantCopy(prop, propvar, This->codePage,
482          lcid);
483     }
484     else
485     {
486         prop = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
487          sizeof(PROPVARIANT));
488         if (prop)
489         {
490             hr = PropertyStorage_PropVariantCopy(prop, propvar, This->codePage,
491              lcid);
492             if (SUCCEEDED(hr))
493             {
494                 dictionary_insert(This->propid_to_prop, UlongToPtr(propid), prop);
495                 if (propid > This->highestProp)
496                     This->highestProp = propid;
497             }
498             else
499                 HeapFree(GetProcessHeap(), 0, prop);
500         }
501         else
502             hr = STG_E_INSUFFICIENTMEMORY;
503     }
504     return hr;
505 }
506
507 /* Adds the name srcName to the name dictionaries, mapped to property ID id.
508  * srcName is encoded in code page cp, and is converted to This->codePage.
509  * If cp is CP_UNICODE, srcName is actually a unicode string.
510  * As a side effect, may change This->format to 1 if srcName is too long for
511  * a version 0 property storage.
512  * Doesn't validate id.
513  */
514 static HRESULT PropertyStorage_StoreNameWithId(PropertyStorage_impl *This,
515  LPCSTR srcName, LCID cp, PROPID id)
516 {
517     LPSTR name;
518     HRESULT hr;
519
520     assert(srcName);
521
522     hr = PropertyStorage_StringCopy(srcName, cp, &name, This->codePage);
523     if (SUCCEEDED(hr))
524     {
525         if (This->codePage == CP_UNICODE)
526         {
527             if (lstrlenW((LPWSTR)name) >= MAX_VERSION_0_PROP_NAME_LENGTH)
528                 This->format = 1;
529         }
530         else
531         {
532             if (strlen(name) >= MAX_VERSION_0_PROP_NAME_LENGTH)
533                 This->format = 1;
534         }
535         TRACE("Adding prop name %s, propid %d\n",
536          This->codePage == CP_UNICODE ? debugstr_w((LPCWSTR)name) :
537          debugstr_a(name), id);
538         dictionary_insert(This->name_to_propid, name, UlongToPtr(id));
539         dictionary_insert(This->propid_to_name, UlongToPtr(id), name);
540     }
541     return hr;
542 }
543
544 /************************************************************************
545  * IPropertyStorage_fnWriteMultiple (IPropertyStorage)
546  */
547 static HRESULT WINAPI IPropertyStorage_fnWriteMultiple(
548     IPropertyStorage* iface,
549     ULONG cpspec,
550     const PROPSPEC rgpspec[],
551     const PROPVARIANT rgpropvar[],
552     PROPID propidNameFirst)
553 {
554     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
555     HRESULT hr = S_OK;
556     ULONG i;
557
558     TRACE("(%p, %d, %p, %p)\n", iface, cpspec, rgpspec, rgpropvar);
559
560     if (cpspec && (!rgpspec || !rgpropvar))
561         return E_INVALIDARG;
562     if (!(This->grfMode & STGM_READWRITE))
563         return STG_E_ACCESSDENIED;
564     EnterCriticalSection(&This->cs);
565     This->dirty = TRUE;
566     This->originatorOS = (DWORD)MAKELONG(LOWORD(GetVersion()),
567      PROPSETHDR_OSVER_KIND_WIN32) ;
568     for (i = 0; i < cpspec; i++)
569     {
570         if (rgpspec[i].ulKind == PRSPEC_LPWSTR)
571         {
572             PROPVARIANT *prop = PropertyStorage_FindPropertyByName(This,
573              rgpspec[i].u.lpwstr);
574
575             if (prop)
576                 PropVariantCopy(prop, &rgpropvar[i]);
577             else
578             {
579                 /* Note that I don't do the special cases here that I do below,
580                  * because naming the special PIDs isn't supported.
581                  */
582                 if (propidNameFirst < PID_FIRST_USABLE ||
583                  propidNameFirst >= PID_MIN_READONLY)
584                     hr = STG_E_INVALIDPARAMETER;
585                 else
586                 {
587                     PROPID nextId = max(propidNameFirst, This->highestProp + 1);
588
589                     hr = PropertyStorage_StoreNameWithId(This,
590                      (LPCSTR)rgpspec[i].u.lpwstr, CP_UNICODE, nextId);
591                     if (SUCCEEDED(hr))
592                         hr = PropertyStorage_StorePropWithId(This, nextId,
593                          &rgpropvar[i], GetACP());
594                 }
595             }
596         }
597         else
598         {
599             switch (rgpspec[i].u.propid)
600             {
601             case PID_DICTIONARY:
602                 /* Can't set the dictionary */
603                 hr = STG_E_INVALIDPARAMETER;
604                 break;
605             case PID_CODEPAGE:
606                 /* Can only set the code page if nothing else has been set */
607                 if (dictionary_num_entries(This->propid_to_prop) == 0 &&
608                  rgpropvar[i].vt == VT_I2)
609                 {
610                     This->codePage = rgpropvar[i].u.iVal;
611                     if (This->codePage == CP_UNICODE)
612                         This->grfFlags &= ~PROPSETFLAG_ANSI;
613                     else
614                         This->grfFlags |= PROPSETFLAG_ANSI;
615                 }
616                 else
617                     hr = STG_E_INVALIDPARAMETER;
618                 break;
619             case PID_LOCALE:
620                 /* Can only set the locale if nothing else has been set */
621                 if (dictionary_num_entries(This->propid_to_prop) == 0 &&
622                  rgpropvar[i].vt == VT_I4)
623                     This->locale = rgpropvar[i].u.lVal;
624                 else
625                     hr = STG_E_INVALIDPARAMETER;
626                 break;
627             case PID_ILLEGAL:
628                 /* silently ignore like MSDN says */
629                 break;
630             default:
631                 if (rgpspec[i].u.propid >= PID_MIN_READONLY)
632                     hr = STG_E_INVALIDPARAMETER;
633                 else
634                     hr = PropertyStorage_StorePropWithId(This,
635                      rgpspec[i].u.propid, &rgpropvar[i], GetACP());
636             }
637         }
638     }
639     if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
640         IPropertyStorage_Commit(iface, STGC_DEFAULT);
641     LeaveCriticalSection(&This->cs);
642     return hr;
643 }
644
645 /************************************************************************
646  * IPropertyStorage_fnDeleteMultiple (IPropertyStorage)
647  */
648 static HRESULT WINAPI IPropertyStorage_fnDeleteMultiple(
649     IPropertyStorage* iface,
650     ULONG cpspec,
651     const PROPSPEC rgpspec[])
652 {
653     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
654     ULONG i;
655     HRESULT hr;
656
657     TRACE("(%p, %d, %p)\n", iface, cpspec, rgpspec);
658
659     if (cpspec && !rgpspec)
660         return E_INVALIDARG;
661     if (!(This->grfMode & STGM_READWRITE))
662         return STG_E_ACCESSDENIED;
663     hr = S_OK;
664     EnterCriticalSection(&This->cs);
665     This->dirty = TRUE;
666     for (i = 0; i < cpspec; i++)
667     {
668         if (rgpspec[i].ulKind == PRSPEC_LPWSTR)
669         {
670             void *propid;
671
672             if (dictionary_find(This->name_to_propid, rgpspec[i].u.lpwstr, &propid))
673                 dictionary_remove(This->propid_to_prop, propid);
674         }
675         else
676         {
677             if (rgpspec[i].u.propid >= PID_FIRST_USABLE &&
678              rgpspec[i].u.propid < PID_MIN_READONLY)
679                 dictionary_remove(This->propid_to_prop, UlongToPtr(rgpspec[i].u.propid));
680             else
681                 hr = STG_E_INVALIDPARAMETER;
682         }
683     }
684     if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
685         IPropertyStorage_Commit(iface, STGC_DEFAULT);
686     LeaveCriticalSection(&This->cs);
687     return hr;
688 }
689
690 /************************************************************************
691  * IPropertyStorage_fnReadPropertyNames (IPropertyStorage)
692  */
693 static HRESULT WINAPI IPropertyStorage_fnReadPropertyNames(
694     IPropertyStorage* iface,
695     ULONG cpropid,
696     const PROPID rgpropid[],
697     LPOLESTR rglpwstrName[])
698 {
699     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
700     ULONG i;
701     HRESULT hr = S_FALSE;
702
703     TRACE("(%p, %d, %p, %p)\n", iface, cpropid, rgpropid, rglpwstrName);
704
705     if (cpropid && (!rgpropid || !rglpwstrName))
706         return E_INVALIDARG;
707     EnterCriticalSection(&This->cs);
708     for (i = 0; i < cpropid && SUCCEEDED(hr); i++)
709     {
710         LPWSTR name = PropertyStorage_FindPropertyNameById(This, rgpropid[i]);
711
712         if (name)
713         {
714             size_t len = lstrlenW(name);
715
716             hr = S_OK;
717             rglpwstrName[i] = CoTaskMemAlloc((len + 1) * sizeof(WCHAR));
718             if (rglpwstrName)
719                 memcpy(rglpwstrName, name, (len + 1) * sizeof(WCHAR));
720             else
721                 hr = STG_E_INSUFFICIENTMEMORY;
722         }
723         else
724             rglpwstrName[i] = NULL;
725     }
726     LeaveCriticalSection(&This->cs);
727     return hr;
728 }
729
730 /************************************************************************
731  * IPropertyStorage_fnWritePropertyNames (IPropertyStorage)
732  */
733 static HRESULT WINAPI IPropertyStorage_fnWritePropertyNames(
734     IPropertyStorage* iface,
735     ULONG cpropid,
736     const PROPID rgpropid[],
737     const LPOLESTR rglpwstrName[])
738 {
739     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
740     ULONG i;
741     HRESULT hr;
742
743     TRACE("(%p, %d, %p, %p)\n", iface, cpropid, rgpropid, rglpwstrName);
744
745     if (cpropid && (!rgpropid || !rglpwstrName))
746         return E_INVALIDARG;
747     if (!(This->grfMode & STGM_READWRITE))
748         return STG_E_ACCESSDENIED;
749     hr = S_OK;
750     EnterCriticalSection(&This->cs);
751     This->dirty = TRUE;
752     for (i = 0; SUCCEEDED(hr) && i < cpropid; i++)
753     {
754         if (rgpropid[i] != PID_ILLEGAL)
755             hr = PropertyStorage_StoreNameWithId(This, (LPCSTR)rglpwstrName[i],
756              CP_UNICODE, rgpropid[i]);
757     }
758     if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
759         IPropertyStorage_Commit(iface, STGC_DEFAULT);
760     LeaveCriticalSection(&This->cs);
761     return hr;
762 }
763
764 /************************************************************************
765  * IPropertyStorage_fnDeletePropertyNames (IPropertyStorage)
766  */
767 static HRESULT WINAPI IPropertyStorage_fnDeletePropertyNames(
768     IPropertyStorage* iface,
769     ULONG cpropid,
770     const PROPID rgpropid[])
771 {
772     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
773     ULONG i;
774     HRESULT hr;
775
776     TRACE("(%p, %d, %p)\n", iface, cpropid, rgpropid);
777
778     if (cpropid && !rgpropid)
779         return E_INVALIDARG;
780     if (!(This->grfMode & STGM_READWRITE))
781         return STG_E_ACCESSDENIED;
782     hr = S_OK;
783     EnterCriticalSection(&This->cs);
784     This->dirty = TRUE;
785     for (i = 0; i < cpropid; i++)
786     {
787         LPWSTR name = NULL;
788
789         if (dictionary_find(This->propid_to_name, UlongToPtr(rgpropid[i]), (void **)&name))
790         {
791             dictionary_remove(This->propid_to_name, UlongToPtr(rgpropid[i]));
792             dictionary_remove(This->name_to_propid, name);
793         }
794     }
795     if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
796         IPropertyStorage_Commit(iface, STGC_DEFAULT);
797     LeaveCriticalSection(&This->cs);
798     return hr;
799 }
800
801 /************************************************************************
802  * IPropertyStorage_fnCommit (IPropertyStorage)
803  */
804 static HRESULT WINAPI IPropertyStorage_fnCommit(
805     IPropertyStorage* iface,
806     DWORD grfCommitFlags)
807 {
808     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
809     HRESULT hr;
810
811     TRACE("(%p, 0x%08x)\n", iface, grfCommitFlags);
812
813     if (!(This->grfMode & STGM_READWRITE))
814         return STG_E_ACCESSDENIED;
815     EnterCriticalSection(&This->cs);
816     if (This->dirty)
817         hr = PropertyStorage_WriteToStream(This);
818     else
819         hr = S_OK;
820     LeaveCriticalSection(&This->cs);
821     return hr;
822 }
823
824 /************************************************************************
825  * IPropertyStorage_fnRevert (IPropertyStorage)
826  */
827 static HRESULT WINAPI IPropertyStorage_fnRevert(
828     IPropertyStorage* iface)
829 {
830     HRESULT hr;
831     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
832
833     TRACE("%p\n", iface);
834
835     EnterCriticalSection(&This->cs);
836     if (This->dirty)
837     {
838         PropertyStorage_DestroyDictionaries(This);
839         hr = PropertyStorage_CreateDictionaries(This);
840         if (SUCCEEDED(hr))
841             hr = PropertyStorage_ReadFromStream(This);
842     }
843     else
844         hr = S_OK;
845     LeaveCriticalSection(&This->cs);
846     return hr;
847 }
848
849 /************************************************************************
850  * IPropertyStorage_fnEnum (IPropertyStorage)
851  */
852 static HRESULT WINAPI IPropertyStorage_fnEnum(
853     IPropertyStorage* iface,
854     IEnumSTATPROPSTG** ppenum)
855 {
856     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
857     return create_EnumSTATPROPSTG(This, ppenum);
858 }
859
860 /************************************************************************
861  * IPropertyStorage_fnSetTimes (IPropertyStorage)
862  */
863 static HRESULT WINAPI IPropertyStorage_fnSetTimes(
864     IPropertyStorage* iface,
865     const FILETIME* pctime,
866     const FILETIME* patime,
867     const FILETIME* pmtime)
868 {
869     FIXME("\n");
870     return E_NOTIMPL;
871 }
872
873 /************************************************************************
874  * IPropertyStorage_fnSetClass (IPropertyStorage)
875  */
876 static HRESULT WINAPI IPropertyStorage_fnSetClass(
877     IPropertyStorage* iface,
878     REFCLSID clsid)
879 {
880     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
881
882     TRACE("%p, %s\n", iface, debugstr_guid(clsid));
883
884     if (!clsid)
885         return E_INVALIDARG;
886     if (!(This->grfMode & STGM_READWRITE))
887         return STG_E_ACCESSDENIED;
888     This->clsid = *clsid;
889     This->dirty = TRUE;
890     if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
891         IPropertyStorage_Commit(iface, STGC_DEFAULT);
892     return S_OK;
893 }
894
895 /************************************************************************
896  * IPropertyStorage_fnStat (IPropertyStorage)
897  */
898 static HRESULT WINAPI IPropertyStorage_fnStat(
899     IPropertyStorage* iface,
900     STATPROPSETSTG* statpsstg)
901 {
902     PropertyStorage_impl *This = (PropertyStorage_impl *)iface;
903     STATSTG stat;
904     HRESULT hr;
905
906     TRACE("%p, %p\n", iface, statpsstg);
907
908     if (!statpsstg)
909         return E_INVALIDARG;
910
911     hr = IStream_Stat(This->stm, &stat, STATFLAG_NONAME);
912     if (SUCCEEDED(hr))
913     {
914         statpsstg->fmtid = This->fmtid;
915         statpsstg->clsid = This->clsid;
916         statpsstg->grfFlags = This->grfFlags;
917         statpsstg->mtime = stat.mtime;
918         statpsstg->ctime = stat.ctime;
919         statpsstg->atime = stat.atime;
920         statpsstg->dwOSVersion = This->originatorOS;
921     }
922     return hr;
923 }
924
925 static int PropertyStorage_PropNameCompare(const void *a, const void *b,
926  void *extra)
927 {
928     PropertyStorage_impl *This = extra;
929
930     if (This->codePage == CP_UNICODE)
931     {
932         TRACE("(%s, %s)\n", debugstr_w(a), debugstr_w(b));
933         if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
934             return lstrcmpW(a, b);
935         else
936             return lstrcmpiW(a, b);
937     }
938     else
939     {
940         TRACE("(%s, %s)\n", debugstr_a(a), debugstr_a(b));
941         if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
942             return lstrcmpA(a, b);
943         else
944             return lstrcmpiA(a, b);
945     }
946 }
947
948 static void PropertyStorage_PropNameDestroy(void *k, void *d, void *extra)
949 {
950     CoTaskMemFree(k);
951 }
952
953 static int PropertyStorage_PropCompare(const void *a, const void *b,
954  void *extra)
955 {
956     TRACE("(%d, %d)\n", PtrToUlong(a), PtrToUlong(b));
957     return PtrToUlong(a) - PtrToUlong(b);
958 }
959
960 static void PropertyStorage_PropertyDestroy(void *k, void *d, void *extra)
961 {
962     PropVariantClear(d);
963     HeapFree(GetProcessHeap(), 0, d);
964 }
965
966 #ifdef WORDS_BIGENDIAN
967 /* Swaps each character in str to or from little endian; assumes the conversion
968  * is symmetric, that is, that lendian16toh is equivalent to htole16.
969  */
970 static void PropertyStorage_ByteSwapString(LPWSTR str, size_t len)
971 {
972     DWORD i;
973
974     /* Swap characters to host order.
975      * FIXME: alignment?
976      */
977     for (i = 0; i < len; i++)
978         str[i] = lendian16toh(str[i]);
979 }
980 #else
981 #define PropertyStorage_ByteSwapString(s, l)
982 #endif
983
984 /* Reads the dictionary from the memory buffer beginning at ptr.  Interprets
985  * the entries according to the values of This->codePage and This->locale.
986  * FIXME: there isn't any checking whether the read property extends past the
987  * end of the buffer.
988  */
989 static HRESULT PropertyStorage_ReadDictionary(PropertyStorage_impl *This,
990  BYTE *ptr)
991 {
992     DWORD numEntries, i;
993     HRESULT hr = S_OK;
994
995     assert(This->name_to_propid);
996     assert(This->propid_to_name);
997
998     StorageUtl_ReadDWord(ptr, 0, &numEntries);
999     TRACE("Reading %d entries:\n", numEntries);
1000     ptr += sizeof(DWORD);
1001     for (i = 0; SUCCEEDED(hr) && i < numEntries; i++)
1002     {
1003         PROPID propid;
1004         DWORD cbEntry;
1005
1006         StorageUtl_ReadDWord(ptr, 0, &propid);
1007         ptr += sizeof(PROPID);
1008         StorageUtl_ReadDWord(ptr, 0, &cbEntry);
1009         ptr += sizeof(DWORD);
1010         TRACE("Reading entry with ID 0x%08x, %d bytes\n", propid, cbEntry);
1011         /* Make sure the source string is NULL-terminated */
1012         if (This->codePage != CP_UNICODE)
1013             ptr[cbEntry - 1] = '\0';
1014         else
1015             *((LPWSTR)ptr + cbEntry / sizeof(WCHAR)) = '\0';
1016         hr = PropertyStorage_StoreNameWithId(This, (char*)ptr, This->codePage, propid);
1017         if (This->codePage == CP_UNICODE)
1018         {
1019             /* Unicode entries are padded to DWORD boundaries */
1020             if (cbEntry % sizeof(DWORD))
1021                 ptr += sizeof(DWORD) - (cbEntry % sizeof(DWORD));
1022         }
1023         ptr += sizeof(DWORD) + cbEntry;
1024     }
1025     return hr;
1026 }
1027
1028 /* FIXME: there isn't any checking whether the read property extends past the
1029  * end of the buffer.
1030  */
1031 static HRESULT PropertyStorage_ReadProperty(PropertyStorage_impl *This,
1032  PROPVARIANT *prop, const BYTE *data)
1033 {
1034     HRESULT hr = S_OK;
1035
1036     assert(prop);
1037     assert(data);
1038     StorageUtl_ReadDWord(data, 0, (DWORD *)&prop->vt);
1039     data += sizeof(DWORD);
1040     switch (prop->vt)
1041     {
1042     case VT_EMPTY:
1043     case VT_NULL:
1044         break;
1045     case VT_I1:
1046         prop->u.cVal = *(const char *)data;
1047         TRACE("Read char 0x%x ('%c')\n", prop->u.cVal, prop->u.cVal);
1048         break;
1049     case VT_UI1:
1050         prop->u.bVal = *data;
1051         TRACE("Read byte 0x%x\n", prop->u.bVal);
1052         break;
1053     case VT_I2:
1054         StorageUtl_ReadWord(data, 0, (WORD*)&prop->u.iVal);
1055         TRACE("Read short %d\n", prop->u.iVal);
1056         break;
1057     case VT_UI2:
1058         StorageUtl_ReadWord(data, 0, &prop->u.uiVal);
1059         TRACE("Read ushort %d\n", prop->u.uiVal);
1060         break;
1061     case VT_INT:
1062     case VT_I4:
1063         StorageUtl_ReadDWord(data, 0, (DWORD*)&prop->u.lVal);
1064         TRACE("Read long %d\n", prop->u.lVal);
1065         break;
1066     case VT_UINT:
1067     case VT_UI4:
1068         StorageUtl_ReadDWord(data, 0, &prop->u.ulVal);
1069         TRACE("Read ulong %d\n", prop->u.ulVal);
1070         break;
1071     case VT_LPSTR:
1072     {
1073         DWORD count;
1074        
1075         StorageUtl_ReadDWord(data, 0, &count);
1076         if (This->codePage == CP_UNICODE && count / 2)
1077         {
1078             WARN("Unicode string has odd number of bytes\n");
1079             hr = STG_E_INVALIDHEADER;
1080         }
1081         else
1082         {
1083             prop->u.pszVal = CoTaskMemAlloc(count);
1084             if (prop->u.pszVal)
1085             {
1086                 memcpy(prop->u.pszVal, data + sizeof(DWORD), count);
1087                 /* This is stored in the code page specified in This->codePage.
1088                  * Don't convert it, the caller will just store it as-is.
1089                  */
1090                 if (This->codePage == CP_UNICODE)
1091                 {
1092                     /* Make sure it's NULL-terminated */
1093                     prop->u.pszVal[count / sizeof(WCHAR) - 1] = '\0';
1094                     TRACE("Read string value %s\n",
1095                      debugstr_w(prop->u.pwszVal));
1096                 }
1097                 else
1098                 {
1099                     /* Make sure it's NULL-terminated */
1100                     prop->u.pszVal[count - 1] = '\0';
1101                     TRACE("Read string value %s\n", debugstr_a(prop->u.pszVal));
1102                 }
1103             }
1104             else
1105                 hr = STG_E_INSUFFICIENTMEMORY;
1106         }
1107         break;
1108     }
1109     case VT_LPWSTR:
1110     {
1111         DWORD count;
1112
1113         StorageUtl_ReadDWord(data, 0, &count);
1114         prop->u.pwszVal = CoTaskMemAlloc(count * sizeof(WCHAR));
1115         if (prop->u.pwszVal)
1116         {
1117             memcpy(prop->u.pwszVal, data + sizeof(DWORD),
1118              count * sizeof(WCHAR));
1119             /* make sure string is NULL-terminated */
1120             prop->u.pwszVal[count - 1] = '\0';
1121             PropertyStorage_ByteSwapString(prop->u.pwszVal, count);
1122             TRACE("Read string value %s\n", debugstr_w(prop->u.pwszVal));
1123         }
1124         else
1125             hr = STG_E_INSUFFICIENTMEMORY;
1126         break;
1127     }
1128     case VT_FILETIME:
1129         StorageUtl_ReadULargeInteger(data, 0,
1130          (ULARGE_INTEGER *)&prop->u.filetime);
1131         break;
1132     case VT_CF:
1133         {
1134             DWORD len = 0, tag = 0;
1135
1136             StorageUtl_ReadDWord(data, 0, &len);
1137             StorageUtl_ReadDWord(data, 4, &tag);
1138             if (len > 8)
1139             {
1140                 len -= 8;
1141                 prop->u.pclipdata = CoTaskMemAlloc(sizeof (CLIPDATA));
1142                 prop->u.pclipdata->cbSize = len;
1143                 prop->u.pclipdata->ulClipFmt = tag;
1144                 prop->u.pclipdata->pClipData = CoTaskMemAlloc(len - sizeof(prop->u.pclipdata->ulClipFmt));
1145                 memcpy(prop->u.pclipdata->pClipData, data+8, len - sizeof(prop->u.pclipdata->ulClipFmt));
1146             }
1147             else
1148                 hr = STG_E_INVALIDPARAMETER;
1149         }
1150         break;
1151     default:
1152         FIXME("unsupported type %d\n", prop->vt);
1153         hr = STG_E_INVALIDPARAMETER;
1154     }
1155     return hr;
1156 }
1157
1158 static HRESULT PropertyStorage_ReadHeaderFromStream(IStream *stm,
1159  PROPERTYSETHEADER *hdr)
1160 {
1161     BYTE buf[sizeof(PROPERTYSETHEADER)];
1162     ULONG count = 0;
1163     HRESULT hr;
1164
1165     assert(stm);
1166     assert(hdr);
1167     hr = IStream_Read(stm, buf, sizeof(buf), &count);
1168     if (SUCCEEDED(hr))
1169     {
1170         if (count != sizeof(buf))
1171         {
1172             WARN("read only %d\n", count);
1173             hr = STG_E_INVALIDHEADER;
1174         }
1175         else
1176         {
1177             StorageUtl_ReadWord(buf, offsetof(PROPERTYSETHEADER, wByteOrder),
1178              &hdr->wByteOrder);
1179             StorageUtl_ReadWord(buf, offsetof(PROPERTYSETHEADER, wFormat),
1180              &hdr->wFormat);
1181             StorageUtl_ReadDWord(buf, offsetof(PROPERTYSETHEADER, dwOSVer),
1182              &hdr->dwOSVer);
1183             StorageUtl_ReadGUID(buf, offsetof(PROPERTYSETHEADER, clsid),
1184              &hdr->clsid);
1185             StorageUtl_ReadDWord(buf, offsetof(PROPERTYSETHEADER, reserved),
1186              &hdr->reserved);
1187         }
1188     }
1189     TRACE("returning 0x%08x\n", hr);
1190     return hr;
1191 }
1192
1193 static HRESULT PropertyStorage_ReadFmtIdOffsetFromStream(IStream *stm,
1194  FORMATIDOFFSET *fmt)
1195 {
1196     BYTE buf[sizeof(FORMATIDOFFSET)];
1197     ULONG count = 0;
1198     HRESULT hr;
1199
1200     assert(stm);
1201     assert(fmt);
1202     hr = IStream_Read(stm, buf, sizeof(buf), &count);
1203     if (SUCCEEDED(hr))
1204     {
1205         if (count != sizeof(buf))
1206         {
1207             WARN("read only %d\n", count);
1208             hr = STG_E_INVALIDHEADER;
1209         }
1210         else
1211         {
1212             StorageUtl_ReadGUID(buf, offsetof(FORMATIDOFFSET, fmtid),
1213              &fmt->fmtid);
1214             StorageUtl_ReadDWord(buf, offsetof(FORMATIDOFFSET, dwOffset),
1215              &fmt->dwOffset);
1216         }
1217     }
1218     TRACE("returning 0x%08x\n", hr);
1219     return hr;
1220 }
1221
1222 static HRESULT PropertyStorage_ReadSectionHeaderFromStream(IStream *stm,
1223  PROPERTYSECTIONHEADER *hdr)
1224 {
1225     BYTE buf[sizeof(PROPERTYSECTIONHEADER)];
1226     ULONG count = 0;
1227     HRESULT hr;
1228
1229     assert(stm);
1230     assert(hdr);
1231     hr = IStream_Read(stm, buf, sizeof(buf), &count);
1232     if (SUCCEEDED(hr))
1233     {
1234         if (count != sizeof(buf))
1235         {
1236             WARN("read only %d\n", count);
1237             hr = STG_E_INVALIDHEADER;
1238         }
1239         else
1240         {
1241             StorageUtl_ReadDWord(buf, offsetof(PROPERTYSECTIONHEADER,
1242              cbSection), &hdr->cbSection);
1243             StorageUtl_ReadDWord(buf, offsetof(PROPERTYSECTIONHEADER,
1244              cProperties), &hdr->cProperties);
1245         }
1246     }
1247     TRACE("returning 0x%08x\n", hr);
1248     return hr;
1249 }
1250
1251 static HRESULT PropertyStorage_ReadFromStream(PropertyStorage_impl *This)
1252 {
1253     PROPERTYSETHEADER hdr;
1254     FORMATIDOFFSET fmtOffset;
1255     PROPERTYSECTIONHEADER sectionHdr;
1256     LARGE_INTEGER seek;
1257     ULONG i;
1258     STATSTG stat;
1259     HRESULT hr;
1260     BYTE *buf = NULL;
1261     ULONG count = 0;
1262     DWORD dictOffset = 0;
1263
1264     This->dirty = FALSE;
1265     This->highestProp = 0;
1266     hr = IStream_Stat(This->stm, &stat, STATFLAG_NONAME);
1267     if (FAILED(hr))
1268         goto end;
1269     if (stat.cbSize.u.HighPart)
1270     {
1271         WARN("stream too big\n");
1272         /* maximum size varies, but it can't be this big */
1273         hr = STG_E_INVALIDHEADER;
1274         goto end;
1275     }
1276     if (stat.cbSize.u.LowPart == 0)
1277     {
1278         /* empty stream is okay */
1279         hr = S_OK;
1280         goto end;
1281     }
1282     else if (stat.cbSize.u.LowPart < sizeof(PROPERTYSETHEADER) +
1283      sizeof(FORMATIDOFFSET))
1284     {
1285         WARN("stream too small\n");
1286         hr = STG_E_INVALIDHEADER;
1287         goto end;
1288     }
1289     seek.QuadPart = 0;
1290     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1291     if (FAILED(hr))
1292         goto end;
1293     hr = PropertyStorage_ReadHeaderFromStream(This->stm, &hdr);
1294     /* I've only seen reserved == 1, but the article says I shouldn't disallow
1295      * higher values.
1296      */
1297     if (hdr.wByteOrder != PROPSETHDR_BYTEORDER_MAGIC || hdr.reserved < 1)
1298     {
1299         WARN("bad magic in prop set header\n");
1300         hr = STG_E_INVALIDHEADER;
1301         goto end;
1302     }
1303     if (hdr.wFormat != 0 && hdr.wFormat != 1)
1304     {
1305         WARN("bad format version %d\n", hdr.wFormat);
1306         hr = STG_E_INVALIDHEADER;
1307         goto end;
1308     }
1309     This->format = hdr.wFormat;
1310     This->clsid = hdr.clsid;
1311     This->originatorOS = hdr.dwOSVer;
1312     if (PROPSETHDR_OSVER_KIND(hdr.dwOSVer) == PROPSETHDR_OSVER_KIND_MAC)
1313         WARN("File comes from a Mac, strings will probably be screwed up\n");
1314     hr = PropertyStorage_ReadFmtIdOffsetFromStream(This->stm, &fmtOffset);
1315     if (FAILED(hr))
1316         goto end;
1317     if (!IsEqualGUID(&fmtOffset.fmtid, &FMTID_DocSummaryInformation) &&
1318         !IsEqualGUID(&fmtOffset.fmtid, &FMTID_SummaryInformation))
1319     {
1320         WARN("not reading unknown fmtid %s\n", debugstr_guid(&fmtOffset.fmtid));
1321         hr = S_FALSE;
1322         goto end;
1323     }
1324     if (fmtOffset.dwOffset > stat.cbSize.u.LowPart)
1325     {
1326         WARN("invalid offset %d (stream length is %d)\n", fmtOffset.dwOffset,
1327          stat.cbSize.u.LowPart);
1328         hr = STG_E_INVALIDHEADER;
1329         goto end;
1330     }
1331     /* wackiness alert: if the format ID is FMTID_DocSummaryInformation, there
1332      * follow not one, but two sections.  The first is the standard properties
1333      * for the document summary information, and the second is user-defined
1334      * properties.  This is the only case in which multiple sections are
1335      * allowed.
1336      * Reading the second stream isn't implemented yet.
1337      */
1338     hr = PropertyStorage_ReadSectionHeaderFromStream(This->stm, &sectionHdr);
1339     if (FAILED(hr))
1340         goto end;
1341     /* The section size includes the section header, so check it */
1342     if (sectionHdr.cbSection < sizeof(PROPERTYSECTIONHEADER))
1343     {
1344         WARN("section header too small, got %d\n", sectionHdr.cbSection);
1345         hr = STG_E_INVALIDHEADER;
1346         goto end;
1347     }
1348     buf = HeapAlloc(GetProcessHeap(), 0, sectionHdr.cbSection -
1349      sizeof(PROPERTYSECTIONHEADER));
1350     if (!buf)
1351     {
1352         hr = STG_E_INSUFFICIENTMEMORY;
1353         goto end;
1354     }
1355     hr = IStream_Read(This->stm, buf, sectionHdr.cbSection -
1356      sizeof(PROPERTYSECTIONHEADER), &count);
1357     if (FAILED(hr))
1358         goto end;
1359     TRACE("Reading %d properties:\n", sectionHdr.cProperties);
1360     for (i = 0; SUCCEEDED(hr) && i < sectionHdr.cProperties; i++)
1361     {
1362         PROPERTYIDOFFSET *idOffset = (PROPERTYIDOFFSET *)(buf +
1363          i * sizeof(PROPERTYIDOFFSET));
1364
1365         if (idOffset->dwOffset < sizeof(PROPERTYSECTIONHEADER) ||
1366          idOffset->dwOffset >= sectionHdr.cbSection - sizeof(DWORD))
1367             hr = STG_E_INVALIDPOINTER;
1368         else
1369         {
1370             if (idOffset->propid >= PID_FIRST_USABLE &&
1371              idOffset->propid < PID_MIN_READONLY && idOffset->propid >
1372              This->highestProp)
1373                 This->highestProp = idOffset->propid;
1374             if (idOffset->propid == PID_DICTIONARY)
1375             {
1376                 /* Don't read the dictionary yet, its entries depend on the
1377                  * code page.  Just store the offset so we know to read it
1378                  * later.
1379                  */
1380                 dictOffset = idOffset->dwOffset;
1381                 TRACE("Dictionary offset is %d\n", dictOffset);
1382             }
1383             else
1384             {
1385                 PROPVARIANT prop;
1386
1387                 PropVariantInit(&prop);
1388                 if (SUCCEEDED(PropertyStorage_ReadProperty(This, &prop,
1389                  buf + idOffset->dwOffset - sizeof(PROPERTYSECTIONHEADER))))
1390                 {
1391                     TRACE("Read property with ID 0x%08x, type %d\n",
1392                      idOffset->propid, prop.vt);
1393                     switch(idOffset->propid)
1394                     {
1395                     case PID_CODEPAGE:
1396                         if (prop.vt == VT_I2)
1397                             This->codePage = (UINT)prop.u.iVal;
1398                         break;
1399                     case PID_LOCALE:
1400                         if (prop.vt == VT_I4)
1401                             This->locale = (LCID)prop.u.lVal;
1402                         break;
1403                     case PID_BEHAVIOR:
1404                         if (prop.vt == VT_I4 && prop.u.lVal)
1405                             This->grfFlags |= PROPSETFLAG_CASE_SENSITIVE;
1406                         /* The format should already be 1, but just in case */
1407                         This->format = 1;
1408                         break;
1409                     default:
1410                         hr = PropertyStorage_StorePropWithId(This,
1411                          idOffset->propid, &prop, This->codePage);
1412                     }
1413                 }
1414                 PropVariantClear(&prop);
1415             }
1416         }
1417     }
1418     if (!This->codePage)
1419     {
1420         /* default to Unicode unless told not to, as specified on msdn */
1421         if (This->grfFlags & PROPSETFLAG_ANSI)
1422             This->codePage = GetACP();
1423         else
1424             This->codePage = CP_UNICODE;
1425     }
1426     if (!This->locale)
1427         This->locale = LOCALE_SYSTEM_DEFAULT;
1428     TRACE("Code page is %d, locale is %d\n", This->codePage, This->locale);
1429     if (dictOffset)
1430         hr = PropertyStorage_ReadDictionary(This,
1431          buf + dictOffset - sizeof(PROPERTYSECTIONHEADER));
1432
1433 end:
1434     HeapFree(GetProcessHeap(), 0, buf);
1435     if (FAILED(hr))
1436     {
1437         dictionary_destroy(This->name_to_propid);
1438         This->name_to_propid = NULL;
1439         dictionary_destroy(This->propid_to_name);
1440         This->propid_to_name = NULL;
1441         dictionary_destroy(This->propid_to_prop);
1442         This->propid_to_prop = NULL;
1443     }
1444     return hr;
1445 }
1446
1447 static void PropertyStorage_MakeHeader(PropertyStorage_impl *This,
1448  PROPERTYSETHEADER *hdr)
1449 {
1450     assert(hdr);
1451     StorageUtl_WriteWord((BYTE *)&hdr->wByteOrder, 0,
1452      PROPSETHDR_BYTEORDER_MAGIC);
1453     StorageUtl_WriteWord((BYTE *)&hdr->wFormat, 0, This->format);
1454     StorageUtl_WriteDWord((BYTE *)&hdr->dwOSVer, 0, This->originatorOS);
1455     StorageUtl_WriteGUID((BYTE *)&hdr->clsid, 0, &This->clsid);
1456     StorageUtl_WriteDWord((BYTE *)&hdr->reserved, 0, 1);
1457 }
1458
1459 static void PropertyStorage_MakeFmtIdOffset(PropertyStorage_impl *This,
1460  FORMATIDOFFSET *fmtOffset)
1461 {
1462     assert(fmtOffset);
1463     StorageUtl_WriteGUID((BYTE *)fmtOffset, 0, &This->fmtid);
1464     StorageUtl_WriteDWord((BYTE *)fmtOffset, offsetof(FORMATIDOFFSET, dwOffset),
1465      sizeof(PROPERTYSETHEADER) + sizeof(FORMATIDOFFSET));
1466 }
1467
1468 static void PropertyStorage_MakeSectionHdr(DWORD cbSection, DWORD numProps,
1469  PROPERTYSECTIONHEADER *hdr)
1470 {
1471     assert(hdr);
1472     StorageUtl_WriteDWord((BYTE *)hdr, 0, cbSection);
1473     StorageUtl_WriteDWord((BYTE *)hdr,
1474      offsetof(PROPERTYSECTIONHEADER, cProperties), numProps);
1475 }
1476
1477 static void PropertyStorage_MakePropertyIdOffset(DWORD propid, DWORD dwOffset,
1478  PROPERTYIDOFFSET *propIdOffset)
1479 {
1480     assert(propIdOffset);
1481     StorageUtl_WriteDWord((BYTE *)propIdOffset, 0, propid);
1482     StorageUtl_WriteDWord((BYTE *)propIdOffset,
1483      offsetof(PROPERTYIDOFFSET, dwOffset), dwOffset);
1484 }
1485
1486 static inline HRESULT PropertStorage_WriteWStringToStream(IStream *stm,
1487  LPCWSTR str, DWORD len, DWORD *written)
1488 {
1489 #ifdef WORDS_BIGENDIAN
1490     WCHAR *leStr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1491     HRESULT hr;
1492
1493     if (!leStr)
1494         return E_OUTOFMEMORY;
1495     memcpy(leStr, str, len * sizeof(WCHAR));
1496     PropertyStorage_ByteSwapString(leStr, len);
1497     hr = IStream_Write(stm, leStr, len, written);
1498     HeapFree(GetProcessHeap(), 0, leStr);
1499     return hr;
1500 #else
1501     return IStream_Write(stm, str, len, written);
1502 #endif
1503 }
1504
1505 struct DictionaryClosure
1506 {
1507     HRESULT hr;
1508     DWORD bytesWritten;
1509 };
1510
1511 static BOOL PropertyStorage_DictionaryWriter(const void *key,
1512  const void *value, void *extra, void *closure)
1513 {
1514     PropertyStorage_impl *This = extra;
1515     struct DictionaryClosure *c = closure;
1516     DWORD propid;
1517     ULONG count;
1518
1519     assert(key);
1520     assert(closure);
1521     StorageUtl_WriteDWord((LPBYTE)&propid, 0, PtrToUlong(value));
1522     c->hr = IStream_Write(This->stm, &propid, sizeof(propid), &count);
1523     if (FAILED(c->hr))
1524         goto end;
1525     c->bytesWritten += sizeof(DWORD);
1526     if (This->codePage == CP_UNICODE)
1527     {
1528         DWORD keyLen, pad = 0;
1529
1530         StorageUtl_WriteDWord((LPBYTE)&keyLen, 0,
1531          (lstrlenW((LPCWSTR)key) + 1) * sizeof(WCHAR));
1532         c->hr = IStream_Write(This->stm, &keyLen, sizeof(keyLen), &count);
1533         if (FAILED(c->hr))
1534             goto end;
1535         c->bytesWritten += sizeof(DWORD);
1536         c->hr = PropertStorage_WriteWStringToStream(This->stm, key, keyLen,
1537          &count);
1538         if (FAILED(c->hr))
1539             goto end;
1540         c->bytesWritten += keyLen * sizeof(WCHAR);
1541         if (keyLen % sizeof(DWORD))
1542         {
1543             c->hr = IStream_Write(This->stm, &pad,
1544              sizeof(DWORD) - keyLen % sizeof(DWORD), &count);
1545             if (FAILED(c->hr))
1546                 goto end;
1547             c->bytesWritten += sizeof(DWORD) - keyLen % sizeof(DWORD);
1548         }
1549     }
1550     else
1551     {
1552         DWORD keyLen;
1553
1554         StorageUtl_WriteDWord((LPBYTE)&keyLen, 0, strlen((LPCSTR)key) + 1);
1555         c->hr = IStream_Write(This->stm, &keyLen, sizeof(keyLen), &count);
1556         if (FAILED(c->hr))
1557             goto end;
1558         c->bytesWritten += sizeof(DWORD);
1559         c->hr = IStream_Write(This->stm, key, keyLen, &count);
1560         if (FAILED(c->hr))
1561             goto end;
1562         c->bytesWritten += keyLen;
1563     }
1564 end:
1565     return SUCCEEDED(c->hr);
1566 }
1567
1568 #define SECTIONHEADER_OFFSET sizeof(PROPERTYSETHEADER) + sizeof(FORMATIDOFFSET)
1569
1570 /* Writes the dictionary to the stream.  Assumes without checking that the
1571  * dictionary isn't empty.
1572  */
1573 static HRESULT PropertyStorage_WriteDictionaryToStream(
1574  PropertyStorage_impl *This, DWORD *sectionOffset)
1575 {
1576     HRESULT hr;
1577     LARGE_INTEGER seek;
1578     PROPERTYIDOFFSET propIdOffset;
1579     ULONG count;
1580     DWORD dwTemp;
1581     struct DictionaryClosure closure;
1582
1583     assert(sectionOffset);
1584
1585     /* The dictionary's always the first property written, so seek to its
1586      * spot.
1587      */
1588     seek.QuadPart = SECTIONHEADER_OFFSET + sizeof(PROPERTYSECTIONHEADER);
1589     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1590     if (FAILED(hr))
1591         goto end;
1592     PropertyStorage_MakePropertyIdOffset(PID_DICTIONARY, *sectionOffset,
1593      &propIdOffset);
1594     hr = IStream_Write(This->stm, &propIdOffset, sizeof(propIdOffset), &count);
1595     if (FAILED(hr))
1596         goto end;
1597
1598     seek.QuadPart = SECTIONHEADER_OFFSET + *sectionOffset;
1599     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1600     if (FAILED(hr))
1601         goto end;
1602     StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0,
1603      dictionary_num_entries(This->name_to_propid));
1604     hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
1605     if (FAILED(hr))
1606         goto end;
1607     *sectionOffset += sizeof(dwTemp);
1608
1609     closure.hr = S_OK;
1610     closure.bytesWritten = 0;
1611     dictionary_enumerate(This->name_to_propid, PropertyStorage_DictionaryWriter,
1612      &closure);
1613     hr = closure.hr;
1614     if (FAILED(hr))
1615         goto end;
1616     *sectionOffset += closure.bytesWritten;
1617     if (closure.bytesWritten % sizeof(DWORD))
1618     {
1619         DWORD padding = sizeof(DWORD) - closure.bytesWritten % sizeof(DWORD);
1620         TRACE("adding %d bytes of padding\n", padding);
1621         *sectionOffset += padding;
1622     }
1623
1624 end:
1625     return hr;
1626 }
1627
1628 static HRESULT PropertyStorage_WritePropertyToStream(PropertyStorage_impl *This,
1629  DWORD propNum, DWORD propid, const PROPVARIANT *var, DWORD *sectionOffset)
1630 {
1631     HRESULT hr;
1632     LARGE_INTEGER seek;
1633     PROPERTYIDOFFSET propIdOffset;
1634     ULONG count;
1635     DWORD dwType, bytesWritten;
1636
1637     assert(var);
1638     assert(sectionOffset);
1639
1640     TRACE("%p, %d, 0x%08x, (%d), (%d)\n", This, propNum, propid, var->vt,
1641      *sectionOffset);
1642
1643     seek.QuadPart = SECTIONHEADER_OFFSET + sizeof(PROPERTYSECTIONHEADER) +
1644      propNum * sizeof(PROPERTYIDOFFSET);
1645     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1646     if (FAILED(hr))
1647         goto end;
1648     PropertyStorage_MakePropertyIdOffset(propid, *sectionOffset, &propIdOffset);
1649     hr = IStream_Write(This->stm, &propIdOffset, sizeof(propIdOffset), &count);
1650     if (FAILED(hr))
1651         goto end;
1652
1653     seek.QuadPart = SECTIONHEADER_OFFSET + *sectionOffset;
1654     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1655     if (FAILED(hr))
1656         goto end;
1657     StorageUtl_WriteDWord((LPBYTE)&dwType, 0, var->vt);
1658     hr = IStream_Write(This->stm, &dwType, sizeof(dwType), &count);
1659     if (FAILED(hr))
1660         goto end;
1661     *sectionOffset += sizeof(dwType);
1662
1663     switch (var->vt)
1664     {
1665     case VT_EMPTY:
1666     case VT_NULL:
1667         bytesWritten = 0;
1668         break;
1669     case VT_I1:
1670     case VT_UI1:
1671         hr = IStream_Write(This->stm, &var->u.cVal, sizeof(var->u.cVal),
1672          &count);
1673         bytesWritten = count;
1674         break;
1675     case VT_I2:
1676     case VT_UI2:
1677     {
1678         WORD wTemp;
1679
1680         StorageUtl_WriteWord((LPBYTE)&wTemp, 0, var->u.iVal);
1681         hr = IStream_Write(This->stm, &wTemp, sizeof(wTemp), &count);
1682         bytesWritten = count;
1683         break;
1684     }
1685     case VT_I4:
1686     case VT_UI4:
1687     {
1688         DWORD dwTemp;
1689
1690         StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, var->u.lVal);
1691         hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
1692         bytesWritten = count;
1693         break;
1694     }
1695     case VT_LPSTR:
1696     {
1697         DWORD len, dwTemp;
1698
1699         if (This->codePage == CP_UNICODE)
1700             len = (lstrlenW(var->u.pwszVal) + 1) * sizeof(WCHAR);
1701         else
1702             len = lstrlenA(var->u.pszVal) + 1;
1703         StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, len);
1704         hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
1705         if (FAILED(hr))
1706             goto end;
1707         hr = IStream_Write(This->stm, var->u.pszVal, len, &count);
1708         bytesWritten = count + sizeof(DWORD);
1709         break;
1710     }
1711     case VT_LPWSTR:
1712     {
1713         DWORD len = lstrlenW(var->u.pwszVal) + 1, dwTemp;
1714
1715         StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, len);
1716         hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
1717         if (FAILED(hr))
1718             goto end;
1719         hr = IStream_Write(This->stm, var->u.pwszVal, len * sizeof(WCHAR),
1720          &count);
1721         bytesWritten = count + sizeof(DWORD);
1722         break;
1723     }
1724     case VT_FILETIME:
1725     {
1726         FILETIME temp;
1727
1728         StorageUtl_WriteULargeInteger((BYTE *)&temp, 0,
1729          (const ULARGE_INTEGER *)&var->u.filetime);
1730         hr = IStream_Write(This->stm, &temp, sizeof(FILETIME), &count);
1731         bytesWritten = count;
1732         break;
1733     }
1734     case VT_CF:
1735     {
1736         DWORD cf_hdr[2], len;
1737
1738         len = var->u.pclipdata->cbSize;
1739         StorageUtl_WriteDWord((LPBYTE)&cf_hdr[0], 0, len + 8);
1740         StorageUtl_WriteDWord((LPBYTE)&cf_hdr[1], 0, var->u.pclipdata->ulClipFmt);
1741         hr = IStream_Write(This->stm, cf_hdr, sizeof(cf_hdr), &count);
1742         if (FAILED(hr))
1743             goto end;
1744         hr = IStream_Write(This->stm, var->u.pclipdata->pClipData,
1745                            len - sizeof(var->u.pclipdata->ulClipFmt), &count);
1746         if (FAILED(hr))
1747             goto end;
1748         bytesWritten = count + sizeof cf_hdr;
1749         break;
1750     }
1751     default:
1752         FIXME("unsupported type: %d\n", var->vt);
1753         return STG_E_INVALIDPARAMETER;
1754     }
1755
1756     if (SUCCEEDED(hr))
1757     {
1758         *sectionOffset += bytesWritten;
1759         if (bytesWritten % sizeof(DWORD))
1760         {
1761             DWORD padding = sizeof(DWORD) - bytesWritten % sizeof(DWORD);
1762             TRACE("adding %d bytes of padding\n", padding);
1763             *sectionOffset += padding;
1764         }
1765     }
1766
1767 end:
1768     return hr;
1769 }
1770
1771 struct PropertyClosure
1772 {
1773     HRESULT hr;
1774     DWORD   propNum;
1775     DWORD  *sectionOffset;
1776 };
1777
1778 static BOOL PropertyStorage_PropertiesWriter(const void *key, const void *value,
1779  void *extra, void *closure)
1780 {
1781     PropertyStorage_impl *This = extra;
1782     struct PropertyClosure *c = closure;
1783
1784     assert(key);
1785     assert(value);
1786     assert(extra);
1787     assert(closure);
1788     c->hr = PropertyStorage_WritePropertyToStream(This, c->propNum++,
1789                                                   PtrToUlong(key), value, c->sectionOffset);
1790     return SUCCEEDED(c->hr);
1791 }
1792
1793 static HRESULT PropertyStorage_WritePropertiesToStream(
1794  PropertyStorage_impl *This, DWORD startingPropNum, DWORD *sectionOffset)
1795 {
1796     struct PropertyClosure closure;
1797
1798     assert(sectionOffset);
1799     closure.hr = S_OK;
1800     closure.propNum = startingPropNum;
1801     closure.sectionOffset = sectionOffset;
1802     dictionary_enumerate(This->propid_to_prop, PropertyStorage_PropertiesWriter,
1803      &closure);
1804     return closure.hr;
1805 }
1806
1807 static HRESULT PropertyStorage_WriteHeadersToStream(PropertyStorage_impl *This)
1808 {
1809     HRESULT hr;
1810     ULONG count = 0;
1811     LARGE_INTEGER seek = { {0} };
1812     PROPERTYSETHEADER hdr;
1813     FORMATIDOFFSET fmtOffset;
1814
1815     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1816     if (FAILED(hr))
1817         goto end;
1818     PropertyStorage_MakeHeader(This, &hdr);
1819     hr = IStream_Write(This->stm, &hdr, sizeof(hdr), &count);
1820     if (FAILED(hr))
1821         goto end;
1822     if (count != sizeof(hdr))
1823     {
1824         hr = STG_E_WRITEFAULT;
1825         goto end;
1826     }
1827
1828     PropertyStorage_MakeFmtIdOffset(This, &fmtOffset);
1829     hr = IStream_Write(This->stm, &fmtOffset, sizeof(fmtOffset), &count);
1830     if (FAILED(hr))
1831         goto end;
1832     if (count != sizeof(fmtOffset))
1833     {
1834         hr = STG_E_WRITEFAULT;
1835         goto end;
1836     }
1837     hr = S_OK;
1838
1839 end:
1840     return hr;
1841 }
1842
1843 static HRESULT PropertyStorage_WriteToStream(PropertyStorage_impl *This)
1844 {
1845     PROPERTYSECTIONHEADER sectionHdr;
1846     HRESULT hr;
1847     ULONG count;
1848     LARGE_INTEGER seek;
1849     DWORD numProps, prop, sectionOffset, dwTemp;
1850     PROPVARIANT var;
1851
1852     PropertyStorage_WriteHeadersToStream(This);
1853
1854     /* Count properties.  Always at least one property, the code page */
1855     numProps = 1;
1856     if (dictionary_num_entries(This->name_to_propid))
1857         numProps++;
1858     if (This->locale != LOCALE_SYSTEM_DEFAULT)
1859         numProps++;
1860     if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
1861         numProps++;
1862     numProps += dictionary_num_entries(This->propid_to_prop);
1863
1864     /* Write section header with 0 bytes right now, I'll adjust it after
1865      * writing properties.
1866      */
1867     PropertyStorage_MakeSectionHdr(0, numProps, &sectionHdr);
1868     seek.QuadPart = SECTIONHEADER_OFFSET;
1869     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1870     if (FAILED(hr))
1871         goto end;
1872     hr = IStream_Write(This->stm, &sectionHdr, sizeof(sectionHdr), &count);
1873     if (FAILED(hr))
1874         goto end;
1875
1876     prop = 0;
1877     sectionOffset = sizeof(PROPERTYSECTIONHEADER) +
1878      numProps * sizeof(PROPERTYIDOFFSET);
1879
1880     if (dictionary_num_entries(This->name_to_propid))
1881     {
1882         prop++;
1883         hr = PropertyStorage_WriteDictionaryToStream(This, &sectionOffset);
1884         if (FAILED(hr))
1885             goto end;
1886     }
1887
1888     PropVariantInit(&var);
1889
1890     var.vt = VT_I2;
1891     var.u.iVal = This->codePage;
1892     hr = PropertyStorage_WritePropertyToStream(This, prop++, PID_CODEPAGE,
1893      &var, &sectionOffset);
1894     if (FAILED(hr))
1895         goto end;
1896
1897     if (This->locale != LOCALE_SYSTEM_DEFAULT)
1898     {
1899         var.vt = VT_I4;
1900         var.u.lVal = This->locale;
1901         hr = PropertyStorage_WritePropertyToStream(This, prop++, PID_LOCALE,
1902          &var, &sectionOffset);
1903         if (FAILED(hr))
1904             goto end;
1905     }
1906
1907     if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
1908     {
1909         var.vt = VT_I4;
1910         var.u.lVal = 1;
1911         hr = PropertyStorage_WritePropertyToStream(This, prop++, PID_BEHAVIOR,
1912          &var, &sectionOffset);
1913         if (FAILED(hr))
1914             goto end;
1915     }
1916
1917     hr = PropertyStorage_WritePropertiesToStream(This, prop, &sectionOffset);
1918     if (FAILED(hr))
1919         goto end;
1920
1921     /* Now write the byte count of the section */
1922     seek.QuadPart = SECTIONHEADER_OFFSET;
1923     hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
1924     if (FAILED(hr))
1925         goto end;
1926     StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, sectionOffset);
1927     hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
1928
1929 end:
1930     return hr;
1931 }
1932
1933 /***********************************************************************
1934  * PropertyStorage_Construct
1935  */
1936 static void PropertyStorage_DestroyDictionaries(PropertyStorage_impl *This)
1937 {
1938     dictionary_destroy(This->name_to_propid);
1939     This->name_to_propid = NULL;
1940     dictionary_destroy(This->propid_to_name);
1941     This->propid_to_name = NULL;
1942     dictionary_destroy(This->propid_to_prop);
1943     This->propid_to_prop = NULL;
1944 }
1945
1946 static HRESULT PropertyStorage_CreateDictionaries(PropertyStorage_impl *This)
1947 {
1948     HRESULT hr = S_OK;
1949
1950     This->name_to_propid = dictionary_create(
1951      PropertyStorage_PropNameCompare, PropertyStorage_PropNameDestroy,
1952      This);
1953     if (!This->name_to_propid)
1954     {
1955         hr = STG_E_INSUFFICIENTMEMORY;
1956         goto end;
1957     }
1958     This->propid_to_name = dictionary_create(PropertyStorage_PropCompare,
1959      NULL, This);
1960     if (!This->propid_to_name)
1961     {
1962         hr = STG_E_INSUFFICIENTMEMORY;
1963         goto end;
1964     }
1965     This->propid_to_prop = dictionary_create(PropertyStorage_PropCompare,
1966      PropertyStorage_PropertyDestroy, This);
1967     if (!This->propid_to_prop)
1968     {
1969         hr = STG_E_INSUFFICIENTMEMORY;
1970         goto end;
1971     }
1972 end:
1973     if (FAILED(hr))
1974         PropertyStorage_DestroyDictionaries(This);
1975     return hr;
1976 }
1977
1978 static HRESULT PropertyStorage_BaseConstruct(IStream *stm,
1979  REFFMTID rfmtid, DWORD grfMode, PropertyStorage_impl **pps)
1980 {
1981     HRESULT hr = S_OK;
1982
1983     assert(pps);
1984     assert(rfmtid);
1985     *pps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof **pps);
1986     if (!*pps)
1987         return E_OUTOFMEMORY;
1988
1989     (*pps)->vtbl = &IPropertyStorage_Vtbl;
1990     (*pps)->ref = 1;
1991     InitializeCriticalSection(&(*pps)->cs);
1992     (*pps)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PropertyStorage_impl.cs");
1993     (*pps)->stm = stm;
1994     (*pps)->fmtid = *rfmtid;
1995     (*pps)->grfMode = grfMode;
1996
1997     hr = PropertyStorage_CreateDictionaries(*pps);
1998     if (FAILED(hr))
1999     {
2000         IStream_Release(stm);
2001         (*pps)->cs.DebugInfo->Spare[0] = 0;
2002         DeleteCriticalSection(&(*pps)->cs);
2003         HeapFree(GetProcessHeap(), 0, *pps);
2004         *pps = NULL;
2005     }
2006
2007     return hr;
2008 }
2009
2010 static HRESULT PropertyStorage_ConstructFromStream(IStream *stm,
2011  REFFMTID rfmtid, DWORD grfMode, IPropertyStorage** pps)
2012 {
2013     PropertyStorage_impl *ps;
2014     HRESULT hr;
2015
2016     assert(pps);
2017     hr = PropertyStorage_BaseConstruct(stm, rfmtid, grfMode, &ps);
2018     if (SUCCEEDED(hr))
2019     {
2020         hr = PropertyStorage_ReadFromStream(ps);
2021         if (SUCCEEDED(hr))
2022         {
2023             *pps = (IPropertyStorage *)ps;
2024             TRACE("PropertyStorage %p constructed\n", ps);
2025             hr = S_OK;
2026         }
2027         else
2028         {
2029             PropertyStorage_DestroyDictionaries(ps);
2030             HeapFree(GetProcessHeap(), 0, ps);
2031         }
2032     }
2033     return hr;
2034 }
2035
2036 static HRESULT PropertyStorage_ConstructEmpty(IStream *stm,
2037  REFFMTID rfmtid, DWORD grfFlags, DWORD grfMode, IPropertyStorage** pps)
2038 {
2039     PropertyStorage_impl *ps;
2040     HRESULT hr;
2041
2042     assert(pps);
2043     hr = PropertyStorage_BaseConstruct(stm, rfmtid, grfMode, &ps);
2044     if (SUCCEEDED(hr))
2045     {
2046         ps->format = 0;
2047         ps->grfFlags = grfFlags;
2048         if (ps->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
2049             ps->format = 1;
2050         /* default to Unicode unless told not to, as specified on msdn */
2051         if (ps->grfFlags & PROPSETFLAG_ANSI)
2052             ps->codePage = GetACP();
2053         else
2054             ps->codePage = CP_UNICODE;
2055         ps->locale = LOCALE_SYSTEM_DEFAULT;
2056         TRACE("Code page is %d, locale is %d\n", ps->codePage, ps->locale);
2057         *pps = (IPropertyStorage *)ps;
2058         TRACE("PropertyStorage %p constructed\n", ps);
2059         hr = S_OK;
2060     }
2061     return hr;
2062 }
2063
2064
2065 /***********************************************************************
2066  * Implementation of IPropertySetStorage
2067  */
2068
2069 /************************************************************************
2070  * IPropertySetStorage_fnQueryInterface (IUnknown)
2071  *
2072  *  This method forwards to the common QueryInterface implementation
2073  */
2074 static HRESULT WINAPI IPropertySetStorage_fnQueryInterface(
2075     IPropertySetStorage *ppstg,
2076     REFIID riid,
2077     void** ppvObject)
2078 {
2079     StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2080     return IStorage_QueryInterface( (IStorage*)This, riid, ppvObject );
2081 }
2082
2083 /************************************************************************
2084  * IPropertySetStorage_fnAddRef (IUnknown)
2085  *
2086  *  This method forwards to the common AddRef implementation
2087  */
2088 static ULONG WINAPI IPropertySetStorage_fnAddRef(
2089     IPropertySetStorage *ppstg)
2090 {
2091     StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2092     return IStorage_AddRef( (IStorage*)This );
2093 }
2094
2095 /************************************************************************
2096  * IPropertySetStorage_fnRelease (IUnknown)
2097  *
2098  *  This method forwards to the common Release implementation
2099  */
2100 static ULONG WINAPI IPropertySetStorage_fnRelease(
2101     IPropertySetStorage *ppstg)
2102 {
2103     StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2104     return IStorage_Release( (IStorage*)This );
2105 }
2106
2107 /************************************************************************
2108  * IPropertySetStorage_fnCreate (IPropertySetStorage)
2109  */
2110 static HRESULT WINAPI IPropertySetStorage_fnCreate(
2111     IPropertySetStorage *ppstg,
2112     REFFMTID rfmtid,
2113     const CLSID* pclsid,
2114     DWORD grfFlags,
2115     DWORD grfMode,
2116     IPropertyStorage** ppprstg)
2117 {
2118     StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2119     WCHAR name[CCH_MAX_PROPSTG_NAME];
2120     IStream *stm = NULL;
2121     HRESULT r;
2122
2123     TRACE("%p %s %08x %08x %p\n", This, debugstr_guid(rfmtid), grfFlags,
2124      grfMode, ppprstg);
2125
2126     /* be picky */
2127     if (grfMode != (STGM_CREATE|STGM_READWRITE|STGM_SHARE_EXCLUSIVE))
2128     {
2129         r = STG_E_INVALIDFLAG;
2130         goto end;
2131     }
2132
2133     if (!rfmtid)
2134     {
2135         r = E_INVALIDARG;
2136         goto end;
2137     }
2138
2139     /* FIXME: if (grfFlags & PROPSETFLAG_NONSIMPLE), we need to create a
2140      * storage, not a stream.  For now, disallow it.
2141      */
2142     if (grfFlags & PROPSETFLAG_NONSIMPLE)
2143     {
2144         FIXME("PROPSETFLAG_NONSIMPLE not supported\n");
2145         r = STG_E_INVALIDFLAG;
2146         goto end;
2147     }
2148
2149     r = FmtIdToPropStgName(rfmtid, name);
2150     if (FAILED(r))
2151         goto end;
2152
2153     r = IStorage_CreateStream( (IStorage*)This, name, grfMode, 0, 0, &stm );
2154     if (FAILED(r))
2155         goto end;
2156
2157     r = PropertyStorage_ConstructEmpty(stm, rfmtid, grfFlags, grfMode, ppprstg);
2158
2159 end:
2160     TRACE("returning 0x%08x\n", r);
2161     return r;
2162 }
2163
2164 /************************************************************************
2165  * IPropertySetStorage_fnOpen (IPropertySetStorage)
2166  */
2167 static HRESULT WINAPI IPropertySetStorage_fnOpen(
2168     IPropertySetStorage *ppstg,
2169     REFFMTID rfmtid,
2170     DWORD grfMode,
2171     IPropertyStorage** ppprstg)
2172 {
2173     StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2174     IStream *stm = NULL;
2175     WCHAR name[CCH_MAX_PROPSTG_NAME];
2176     HRESULT r;
2177
2178     TRACE("%p %s %08x %p\n", This, debugstr_guid(rfmtid), grfMode, ppprstg);
2179
2180     /* be picky */
2181     if (grfMode != (STGM_READWRITE|STGM_SHARE_EXCLUSIVE) &&
2182         grfMode != (STGM_READ|STGM_SHARE_EXCLUSIVE))
2183     {
2184         r = STG_E_INVALIDFLAG;
2185         goto end;
2186     }
2187
2188     if (!rfmtid)
2189     {
2190         r = E_INVALIDARG;
2191         goto end;
2192     }
2193
2194     r = FmtIdToPropStgName(rfmtid, name);
2195     if (FAILED(r))
2196         goto end;
2197
2198     r = IStorage_OpenStream((IStorage*) This, name, 0, grfMode, 0, &stm );
2199     if (FAILED(r))
2200         goto end;
2201
2202     r = PropertyStorage_ConstructFromStream(stm, rfmtid, grfMode, ppprstg);
2203
2204 end:
2205     TRACE("returning 0x%08x\n", r);
2206     return r;
2207 }
2208
2209 /************************************************************************
2210  * IPropertySetStorage_fnDelete (IPropertySetStorage)
2211  */
2212 static HRESULT WINAPI IPropertySetStorage_fnDelete(
2213     IPropertySetStorage *ppstg,
2214     REFFMTID rfmtid)
2215 {
2216     StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2217     IStorage *stg = NULL;
2218     WCHAR name[CCH_MAX_PROPSTG_NAME];
2219     HRESULT r;
2220
2221     TRACE("%p %s\n", This, debugstr_guid(rfmtid));
2222
2223     if (!rfmtid)
2224         return E_INVALIDARG;
2225
2226     r = FmtIdToPropStgName(rfmtid, name);
2227     if (FAILED(r))
2228         return r;
2229
2230     stg = (IStorage*) This;
2231     return IStorage_DestroyElement(stg, name);
2232 }
2233
2234 /************************************************************************
2235  * IPropertySetStorage_fnEnum (IPropertySetStorage)
2236  */
2237 static HRESULT WINAPI IPropertySetStorage_fnEnum(
2238     IPropertySetStorage *ppstg,
2239     IEnumSTATPROPSETSTG** ppenum)
2240 {
2241     StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2242     return create_EnumSTATPROPSETSTG(This, ppenum);
2243 }
2244
2245 /************************************************************************
2246  * Implement IEnumSTATPROPSETSTG using enumx
2247  */
2248 static HRESULT WINAPI IEnumSTATPROPSETSTG_fnQueryInterface(
2249     IEnumSTATPROPSETSTG *iface,
2250     REFIID riid,
2251     void** ppvObject)
2252 {
2253     return enumx_QueryInterface((enumx_impl*)iface, riid, ppvObject);
2254 }
2255
2256 static ULONG WINAPI IEnumSTATPROPSETSTG_fnAddRef(
2257     IEnumSTATPROPSETSTG *iface)
2258 {
2259     return enumx_AddRef((enumx_impl*)iface);
2260 }
2261
2262 static ULONG WINAPI IEnumSTATPROPSETSTG_fnRelease(
2263     IEnumSTATPROPSETSTG *iface)
2264 {
2265     return enumx_Release((enumx_impl*)iface);
2266 }
2267
2268 static HRESULT WINAPI IEnumSTATPROPSETSTG_fnNext(
2269     IEnumSTATPROPSETSTG *iface,
2270     ULONG celt,
2271     STATPROPSETSTG *rgelt,
2272     ULONG *pceltFetched)
2273 {
2274     return enumx_Next((enumx_impl*)iface, celt, rgelt, pceltFetched);
2275 }
2276
2277 static HRESULT WINAPI IEnumSTATPROPSETSTG_fnSkip(
2278     IEnumSTATPROPSETSTG *iface,
2279     ULONG celt)
2280 {
2281     return enumx_Skip((enumx_impl*)iface, celt);
2282 }
2283
2284 static HRESULT WINAPI IEnumSTATPROPSETSTG_fnReset(
2285     IEnumSTATPROPSETSTG *iface)
2286 {
2287     return enumx_Reset((enumx_impl*)iface);
2288 }
2289
2290 static HRESULT WINAPI IEnumSTATPROPSETSTG_fnClone(
2291     IEnumSTATPROPSETSTG *iface,
2292     IEnumSTATPROPSETSTG **ppenum)
2293 {
2294     return enumx_Clone((enumx_impl*)iface, (enumx_impl**)ppenum);
2295 }
2296
2297 static HRESULT create_EnumSTATPROPSETSTG(
2298     StorageImpl *This,
2299     IEnumSTATPROPSETSTG** ppenum)
2300 {
2301     IStorage *stg = (IStorage*) &This->base.lpVtbl;
2302     IEnumSTATSTG *penum = NULL;
2303     STATSTG stat;
2304     ULONG count;
2305     HRESULT r;
2306     STATPROPSETSTG statpss;
2307     enumx_impl *enumx;
2308
2309     TRACE("%p %p\n", This, ppenum);
2310
2311     enumx = enumx_allocate(&IID_IEnumSTATPROPSETSTG,
2312                            &IEnumSTATPROPSETSTG_Vtbl,
2313                            sizeof (STATPROPSETSTG));
2314
2315     /* add all the property set elements into a list */
2316     r = IStorage_EnumElements(stg, 0, NULL, 0, &penum);
2317     if (FAILED(r))
2318         return E_OUTOFMEMORY;
2319
2320     while (1)
2321     {
2322         count = 0;
2323         r = IEnumSTATSTG_Next(penum, 1, &stat, &count);
2324         if (FAILED(r))
2325             break;
2326         if (!count)
2327             break;
2328         if (!stat.pwcsName)
2329             continue;
2330         if (stat.pwcsName[0] == 5 && stat.type == STGTY_STREAM)
2331         {
2332             PropStgNameToFmtId(stat.pwcsName, &statpss.fmtid);
2333             TRACE("adding %s (%s)\n", debugstr_w(stat.pwcsName),
2334                   debugstr_guid(&statpss.fmtid));
2335             statpss.mtime = stat.mtime;
2336             statpss.atime = stat.atime;
2337             statpss.ctime = stat.ctime;
2338             statpss.grfFlags = stat.grfMode;
2339             statpss.clsid = stat.clsid;
2340             enumx_add_element(enumx, &statpss);
2341         }
2342         CoTaskMemFree(stat.pwcsName);
2343     }
2344     IEnumSTATSTG_Release(penum);
2345
2346     *ppenum = (IEnumSTATPROPSETSTG*) enumx;
2347
2348     return S_OK;
2349 }
2350
2351 /************************************************************************
2352  * Implement IEnumSTATPROPSTG using enumx
2353  */
2354 static HRESULT WINAPI IEnumSTATPROPSTG_fnQueryInterface(
2355     IEnumSTATPROPSTG *iface,
2356     REFIID riid,
2357     void** ppvObject)
2358 {
2359     return enumx_QueryInterface((enumx_impl*)iface, riid, ppvObject);
2360 }
2361
2362 static ULONG WINAPI IEnumSTATPROPSTG_fnAddRef(
2363     IEnumSTATPROPSTG *iface)
2364 {
2365     return enumx_AddRef((enumx_impl*)iface);
2366 }
2367
2368 static ULONG WINAPI IEnumSTATPROPSTG_fnRelease(
2369     IEnumSTATPROPSTG *iface)
2370 {
2371     return enumx_Release((enumx_impl*)iface);
2372 }
2373
2374 static HRESULT WINAPI IEnumSTATPROPSTG_fnNext(
2375     IEnumSTATPROPSTG *iface,
2376     ULONG celt,
2377     STATPROPSTG *rgelt,
2378     ULONG *pceltFetched)
2379 {
2380     return enumx_Next((enumx_impl*)iface, celt, rgelt, pceltFetched);
2381 }
2382
2383 static HRESULT WINAPI IEnumSTATPROPSTG_fnSkip(
2384     IEnumSTATPROPSTG *iface,
2385     ULONG celt)
2386 {
2387     return enumx_Skip((enumx_impl*)iface, celt);
2388 }
2389
2390 static HRESULT WINAPI IEnumSTATPROPSTG_fnReset(
2391     IEnumSTATPROPSTG *iface)
2392 {
2393     return enumx_Reset((enumx_impl*)iface);
2394 }
2395
2396 static HRESULT WINAPI IEnumSTATPROPSTG_fnClone(
2397     IEnumSTATPROPSTG *iface,
2398     IEnumSTATPROPSTG **ppenum)
2399 {
2400     return enumx_Clone((enumx_impl*)iface, (enumx_impl**)ppenum);
2401 }
2402
2403 static BOOL prop_enum_stat(const void *k, const void *v, void *extra, void *arg)
2404 {
2405     enumx_impl *enumx = arg;
2406     PROPID propid = PtrToUlong(k);
2407     const PROPVARIANT *prop = v;
2408     STATPROPSTG stat;
2409
2410     stat.lpwstrName = NULL;
2411     stat.propid = propid;
2412     stat.vt = prop->vt;
2413
2414     enumx_add_element(enumx, &stat);
2415
2416     return TRUE;
2417 }
2418
2419 static HRESULT create_EnumSTATPROPSTG(
2420     PropertyStorage_impl *This,
2421     IEnumSTATPROPSTG** ppenum)
2422 {
2423     enumx_impl *enumx;
2424
2425     TRACE("%p %p\n", This, ppenum);
2426
2427     enumx = enumx_allocate(&IID_IEnumSTATPROPSTG,
2428                            &IEnumSTATPROPSTG_Vtbl,
2429                            sizeof (STATPROPSTG));
2430
2431     dictionary_enumerate(This->propid_to_prop, prop_enum_stat, enumx);
2432
2433     *ppenum = (IEnumSTATPROPSTG*) enumx;
2434
2435     return S_OK;
2436 }
2437
2438 /***********************************************************************
2439  * vtables
2440  */
2441 const IPropertySetStorageVtbl IPropertySetStorage_Vtbl =
2442 {
2443     IPropertySetStorage_fnQueryInterface,
2444     IPropertySetStorage_fnAddRef,
2445     IPropertySetStorage_fnRelease,
2446     IPropertySetStorage_fnCreate,
2447     IPropertySetStorage_fnOpen,
2448     IPropertySetStorage_fnDelete,
2449     IPropertySetStorage_fnEnum
2450 };
2451
2452 static const IPropertyStorageVtbl IPropertyStorage_Vtbl =
2453 {
2454     IPropertyStorage_fnQueryInterface,
2455     IPropertyStorage_fnAddRef,
2456     IPropertyStorage_fnRelease,
2457     IPropertyStorage_fnReadMultiple,
2458     IPropertyStorage_fnWriteMultiple,
2459     IPropertyStorage_fnDeleteMultiple,
2460     IPropertyStorage_fnReadPropertyNames,
2461     IPropertyStorage_fnWritePropertyNames,
2462     IPropertyStorage_fnDeletePropertyNames,
2463     IPropertyStorage_fnCommit,
2464     IPropertyStorage_fnRevert,
2465     IPropertyStorage_fnEnum,
2466     IPropertyStorage_fnSetTimes,
2467     IPropertyStorage_fnSetClass,
2468     IPropertyStorage_fnStat,
2469 };
2470
2471 static const IEnumSTATPROPSETSTGVtbl IEnumSTATPROPSETSTG_Vtbl =
2472 {
2473     IEnumSTATPROPSETSTG_fnQueryInterface,
2474     IEnumSTATPROPSETSTG_fnAddRef,
2475     IEnumSTATPROPSETSTG_fnRelease,
2476     IEnumSTATPROPSETSTG_fnNext,
2477     IEnumSTATPROPSETSTG_fnSkip,
2478     IEnumSTATPROPSETSTG_fnReset,
2479     IEnumSTATPROPSETSTG_fnClone,
2480 };
2481
2482 static const IEnumSTATPROPSTGVtbl IEnumSTATPROPSTG_Vtbl =
2483 {
2484     IEnumSTATPROPSTG_fnQueryInterface,
2485     IEnumSTATPROPSTG_fnAddRef,
2486     IEnumSTATPROPSTG_fnRelease,
2487     IEnumSTATPROPSTG_fnNext,
2488     IEnumSTATPROPSTG_fnSkip,
2489     IEnumSTATPROPSTG_fnReset,
2490     IEnumSTATPROPSTG_fnClone,
2491 };
2492
2493 /***********************************************************************
2494  * Format ID <-> name conversion
2495  */
2496 static const WCHAR szSummaryInfo[] = { 5,'S','u','m','m','a','r','y',
2497  'I','n','f','o','r','m','a','t','i','o','n',0 };
2498 static const WCHAR szDocSummaryInfo[] = { 5,'D','o','c','u','m','e','n','t',
2499  'S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0 };
2500
2501 #define BITS_PER_BYTE    8
2502 #define CHARMASK         0x1f
2503 #define BITS_IN_CHARMASK 5
2504 #define NUM_ALPHA_CHARS  26
2505
2506 /***********************************************************************
2507  * FmtIdToPropStgName                                   [ole32.@]
2508  * Returns the storage name of the format ID rfmtid.
2509  * PARAMS
2510  *  rfmtid [I] Format ID for which to return a storage name
2511  *  str    [O] Storage name associated with rfmtid.
2512  *
2513  * RETURNS
2514  *  E_INVALIDARG if rfmtid or str i NULL, S_OK otherwise.
2515  *
2516  * NOTES
2517  * str must be at least CCH_MAX_PROPSTG_NAME characters in length.
2518  */
2519 HRESULT WINAPI FmtIdToPropStgName(const FMTID *rfmtid, LPOLESTR str)
2520 {
2521     static const char fmtMap[] = "abcdefghijklmnopqrstuvwxyz012345";
2522
2523     TRACE("%s, %p\n", debugstr_guid(rfmtid), str);
2524
2525     if (!rfmtid) return E_INVALIDARG;
2526     if (!str) return E_INVALIDARG;
2527
2528     if (IsEqualGUID(&FMTID_SummaryInformation, rfmtid))
2529         lstrcpyW(str, szSummaryInfo);
2530     else if (IsEqualGUID(&FMTID_DocSummaryInformation, rfmtid))
2531         lstrcpyW(str, szDocSummaryInfo);
2532     else if (IsEqualGUID(&FMTID_UserDefinedProperties, rfmtid))
2533         lstrcpyW(str, szDocSummaryInfo);
2534     else
2535     {
2536         const BYTE *fmtptr;
2537         WCHAR *pstr = str;
2538         ULONG bitsRemaining = BITS_PER_BYTE;
2539
2540         *pstr++ = 5;
2541         for (fmtptr = (const BYTE *)rfmtid; fmtptr < (const BYTE *)rfmtid + sizeof(FMTID); )
2542         {
2543             ULONG i = *fmtptr >> (BITS_PER_BYTE - bitsRemaining);
2544
2545             if (bitsRemaining >= BITS_IN_CHARMASK)
2546             {
2547                 *pstr = (WCHAR)(fmtMap[i & CHARMASK]);
2548                 if (bitsRemaining == BITS_PER_BYTE && *pstr >= 'a' &&
2549                  *pstr <= 'z')
2550                     *pstr += 'A' - 'a';
2551                 pstr++;
2552                 bitsRemaining -= BITS_IN_CHARMASK;
2553                 if (bitsRemaining == 0)
2554                 {
2555                     fmtptr++;
2556                     bitsRemaining = BITS_PER_BYTE;
2557                 }
2558             }
2559             else
2560             {
2561                 if (++fmtptr < (const BYTE *)rfmtid + sizeof(FMTID))
2562                     i |= *fmtptr << bitsRemaining;
2563                 *pstr++ = (WCHAR)(fmtMap[i & CHARMASK]);
2564                 bitsRemaining += BITS_PER_BYTE - BITS_IN_CHARMASK;
2565             }
2566         }
2567         *pstr = 0;
2568     }
2569     TRACE("returning %s\n", debugstr_w(str));
2570     return S_OK;
2571 }
2572
2573 /***********************************************************************
2574  * PropStgNameToFmtId                                   [ole32.@]
2575  * Returns the format ID corresponding to the given name.
2576  * PARAMS
2577  *  str    [I] Storage name to convert to a format ID.
2578  *  rfmtid [O] Format ID corresponding to str.
2579  *
2580  * RETURNS
2581  *  E_INVALIDARG if rfmtid or str is NULL or if str can't be converted to
2582  *  a format ID, S_OK otherwise.
2583  */
2584 HRESULT WINAPI PropStgNameToFmtId(const LPOLESTR str, FMTID *rfmtid)
2585 {
2586     HRESULT hr = STG_E_INVALIDNAME;
2587
2588     TRACE("%s, %p\n", debugstr_w(str), rfmtid);
2589
2590     if (!rfmtid) return E_INVALIDARG;
2591     if (!str) return STG_E_INVALIDNAME;
2592
2593     if (!lstrcmpiW(str, szDocSummaryInfo))
2594     {
2595         *rfmtid = FMTID_DocSummaryInformation;
2596         hr = S_OK;
2597     }
2598     else if (!lstrcmpiW(str, szSummaryInfo))
2599     {
2600         *rfmtid = FMTID_SummaryInformation;
2601         hr = S_OK;
2602     }
2603     else
2604     {
2605         ULONG bits;
2606         BYTE *fmtptr = (BYTE *)rfmtid - 1;
2607         const WCHAR *pstr = str;
2608
2609         memset(rfmtid, 0, sizeof(*rfmtid));
2610         for (bits = 0; bits < sizeof(FMTID) * BITS_PER_BYTE;
2611          bits += BITS_IN_CHARMASK)
2612         {
2613             ULONG bitsUsed = bits % BITS_PER_BYTE, bitsStored;
2614             WCHAR wc;
2615
2616             if (bitsUsed == 0)
2617                 fmtptr++;
2618             wc = *++pstr - 'A';
2619             if (wc > NUM_ALPHA_CHARS)
2620             {
2621                 wc += 'A' - 'a';
2622                 if (wc > NUM_ALPHA_CHARS)
2623                 {
2624                     wc += 'a' - '0' + NUM_ALPHA_CHARS;
2625                     if (wc > CHARMASK)
2626                     {
2627                         WARN("invalid character (%d)\n", *pstr);
2628                         goto end;
2629                     }
2630                 }
2631             }
2632             *fmtptr |= wc << bitsUsed;
2633             bitsStored = min(BITS_PER_BYTE - bitsUsed, BITS_IN_CHARMASK);
2634             if (bitsStored < BITS_IN_CHARMASK)
2635             {
2636                 wc >>= BITS_PER_BYTE - bitsUsed;
2637                 if (bits + bitsStored == sizeof(FMTID) * BITS_PER_BYTE)
2638                 {
2639                     if (wc != 0)
2640                     {
2641                         WARN("extra bits\n");
2642                         goto end;
2643                     }
2644                     break;
2645                 }
2646                 fmtptr++;
2647                 *fmtptr |= (BYTE)wc;
2648             }
2649         }
2650         hr = S_OK;
2651     }
2652 end:
2653     return hr;
2654 }