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