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