stg_prop.c 83.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * Compound Storage (32 bit version)
 * Storage implementation
 *
 * This file contains the compound file implementation
 * of the storage interface.
 *
 * Copyright 1999 Francis Beaudet
 * Copyright 1999 Sylvain St-Germain
 * Copyright 1999 Thuy Nguyen
 * Copyright 2005 Mike McCormack
12
 * Copyright 2005 Juan Lang
13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
 *
Juan Lang's avatar
Juan Lang committed
28
 * TODO:
29
 * - I don't honor the maximum property set size.
30 31 32 33 34
 * - Certain bogus files could result in reading past the end of a buffer.
 * - Mac-generated files won't be read correctly, even if they're little
 *   endian, because I disregard whether the generator was a Mac.  This means
 *   strings will probably be munged (as I don't understand Mac scripts.)
 * - Not all PROPVARIANT types are supported.
35 36
 * - User defined properties are not supported, see comment in
 *   PropertyStorage_ReadFromStream
37 38
 */

39 40 41
#include "config.h"
#include "wine/port.h"

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define COBJMACROS
#define NONAMELESSUNION

#include "windef.h"
#include "winbase.h"
#include "winnls.h"
#include "winuser.h"
#include "wine/unicode.h"
#include "wine/debug.h"
57
#include "dictionary.h"
58
#include "storage32.h"
59
#include "enumx.h"
60
#include "oleauto.h"
61 62 63

WINE_DEFAULT_DEBUG_CHANNEL(storage);

64 65
static inline StorageImpl *impl_from_IPropertySetStorage( IPropertySetStorage *iface )
{
66
    return CONTAINING_RECORD(iface, StorageImpl, base.IPropertySetStorage_iface);
67
}
68

69
/* These are documented in MSDN,
70 71 72 73 74 75 76
 * but they don't seem to be in any header file.
 */
#define PROPSETHDR_BYTEORDER_MAGIC      0xfffe
#define PROPSETHDR_OSVER_KIND_WIN16     0
#define PROPSETHDR_OSVER_KIND_MAC       1
#define PROPSETHDR_OSVER_KIND_WIN32     2

77 78
#define CP_UNICODE 1200

79 80
#define MAX_VERSION_0_PROP_NAME_LENGTH 256

81 82 83 84 85
#define CFTAG_WINDOWS   (-1L)
#define CFTAG_MACINTOSH (-2L)
#define CFTAG_FMTID     (-3L)
#define CFTAG_NODATA      0L

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
typedef struct tagPROPERTYSETHEADER
{
    WORD  wByteOrder; /* always 0xfffe */
    WORD  wFormat;    /* can be zero or one */
    DWORD dwOSVer;    /* OS version of originating system */
    CLSID clsid;      /* application CLSID */
    DWORD reserved;   /* always 1 */
} PROPERTYSETHEADER;

typedef struct tagFORMATIDOFFSET
{
    FMTID fmtid;
    DWORD dwOffset; /* from beginning of stream */
} FORMATIDOFFSET;

typedef struct tagPROPERTYSECTIONHEADER
{
    DWORD cbSection;
    DWORD cProperties;
} PROPERTYSECTIONHEADER;

typedef struct tagPROPERTYIDOFFSET
{
    DWORD propid;
110
    DWORD dwOffset; /* from beginning of section */
111 112
} PROPERTYIDOFFSET;

113
typedef struct tagPropertyStorage_impl PropertyStorage_impl;
114

115 116 117 118
/* Initializes the property storage from the stream (and undoes any uncommitted
 * changes in the process.)  Returns an error if there is an error reading or
 * if the stream format doesn't match what's expected.
 */
119
static HRESULT PropertyStorage_ReadFromStream(PropertyStorage_impl *);
120

121
static HRESULT PropertyStorage_WriteToStream(PropertyStorage_impl *);
122 123 124 125 126

/* Creates the dictionaries used by the property storage.  If successful, all
 * the dictionaries have been created.  If failed, none has been.  (This makes
 * it a bit easier to deal with destroying them.)
 */
127
static HRESULT PropertyStorage_CreateDictionaries(PropertyStorage_impl *);
128

129
static void PropertyStorage_DestroyDictionaries(PropertyStorage_impl *);
130

131 132 133 134 135 136 137 138 139 140 141 142 143
/* Copies from propvar to prop.  If propvar's type is VT_LPSTR, copies the
 * string using PropertyStorage_StringCopy.
 */
static HRESULT PropertyStorage_PropVariantCopy(PROPVARIANT *prop,
 const PROPVARIANT *propvar, LCID targetCP, LCID srcCP);

/* Copies the string src, which is encoded using code page srcCP, and returns
 * it in *dst, in the code page specified by targetCP.  The returned string is
 * allocated using CoTaskMemAlloc.
 * If srcCP is CP_UNICODE, src is in fact an LPCWSTR.  Similarly, if targetCP
 * is CP_UNICODE, the returned string is in fact an LPWSTR.
 * Returns S_OK on success, something else on failure.
 */
144 145
static HRESULT PropertyStorage_StringCopy(LPCSTR src, LCID srcCP, LPSTR *dst,
 LCID targetCP);
146

147
static const IPropertyStorageVtbl IPropertyStorage_Vtbl;
148
static const IEnumSTATPROPSETSTGVtbl IEnumSTATPROPSETSTG_Vtbl;
149
static const IEnumSTATPROPSTGVtbl IEnumSTATPROPSTG_Vtbl;
150
static HRESULT create_EnumSTATPROPSETSTG(StorageImpl *, IEnumSTATPROPSETSTG**);
151
static HRESULT create_EnumSTATPROPSTG(PropertyStorage_impl *, IEnumSTATPROPSTG**);
152 153 154 155

/***********************************************************************
 * Implementation of IPropertyStorage
 */
156
struct tagPropertyStorage_impl
157
{
158
    IPropertyStorage IPropertyStorage_iface;
159
    LONG ref;
160
    CRITICAL_SECTION cs;
161
    IStream *stm;
162 163 164
    BOOL  dirty;
    FMTID fmtid;
    CLSID clsid;
165
    WORD  format;
166 167 168 169 170 171 172 173 174
    DWORD originatorOS;
    DWORD grfFlags;
    DWORD grfMode;
    UINT  codePage;
    LCID  locale;
    PROPID highestProp;
    struct dictionary *name_to_propid;
    struct dictionary *propid_to_name;
    struct dictionary *propid_to_prop;
175
};
176

177 178 179 180 181
static inline PropertyStorage_impl *impl_from_IPropertyStorage(IPropertyStorage *iface)
{
    return CONTAINING_RECORD(iface, PropertyStorage_impl, IPropertyStorage_iface);
}

182 183 184 185 186 187 188 189
/************************************************************************
 * IPropertyStorage_fnQueryInterface (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnQueryInterface(
    IPropertyStorage *iface,
    REFIID riid,
    void** ppvObject)
{
190
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
191

192 193 194
    TRACE("(%p, %s, %p)\n", This, debugstr_guid(riid), ppvObject);

    if (!ppvObject)
195 196 197 198 199 200 201 202
        return E_INVALIDARG;

    *ppvObject = 0;

    if (IsEqualGUID(&IID_IUnknown, riid) ||
        IsEqualGUID(&IID_IPropertyStorage, riid))
    {
        IPropertyStorage_AddRef(iface);
203
        *ppvObject = iface;
204 205 206 207 208 209 210 211 212 213 214 215
        return S_OK;
    }

    return E_NOINTERFACE;
}

/************************************************************************
 * IPropertyStorage_fnAddRef (IPropertyStorage)
 */
static ULONG WINAPI IPropertyStorage_fnAddRef(
    IPropertyStorage *iface)
{
216
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
217 218 219 220 221 222 223 224 225
    return InterlockedIncrement(&This->ref);
}

/************************************************************************
 * IPropertyStorage_fnRelease (IPropertyStorage)
 */
static ULONG WINAPI IPropertyStorage_fnRelease(
    IPropertyStorage *iface)
{
226
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
227 228 229 230 231 232
    ULONG ref;

    ref = InterlockedDecrement(&This->ref);
    if (ref == 0)
    {
        TRACE("Destroying %p\n", This);
233 234
        if (This->dirty)
            IPropertyStorage_Commit(iface, STGC_DEFAULT);
235
        IStream_Release(This->stm);
236
        This->cs.DebugInfo->Spare[0] = 0;
237
        DeleteCriticalSection(&This->cs);
238
        PropertyStorage_DestroyDictionaries(This);
239 240 241 242 243
        HeapFree(GetProcessHeap(), 0, This);
    }
    return ref;
}

244 245 246 247 248
static PROPVARIANT *PropertyStorage_FindProperty(PropertyStorage_impl *This,
 DWORD propid)
{
    PROPVARIANT *ret = NULL;

249
    dictionary_find(This->propid_to_prop, UlongToPtr(propid), (void **)&ret);
250
    TRACE("returning %p\n", ret);
251 252 253
    return ret;
}

254
/* Returns NULL if name is NULL. */
255 256 257 258
static PROPVARIANT *PropertyStorage_FindPropertyByName(
 PropertyStorage_impl *This, LPCWSTR name)
{
    PROPVARIANT *ret = NULL;
259
    void *propid;
260

261
    if (!name)
262
        return NULL;
263 264
    if (This->codePage == CP_UNICODE)
    {
265 266
        if (dictionary_find(This->name_to_propid, name, &propid))
            ret = PropertyStorage_FindProperty(This, PtrToUlong(propid));
267 268 269 270
    }
    else
    {
        LPSTR ansiName;
271 272
        HRESULT hr = PropertyStorage_StringCopy((LPCSTR)name, CP_UNICODE,
         &ansiName, This->codePage);
273 274 275

        if (SUCCEEDED(hr))
        {
276 277
            if (dictionary_find(This->name_to_propid, ansiName, &propid))
                ret = PropertyStorage_FindProperty(This, PtrToUlong(propid));
278 279 280
            CoTaskMemFree(ansiName);
        }
    }
281
    TRACE("returning %p\n", ret);
282 283 284 285 286 287 288 289
    return ret;
}

static LPWSTR PropertyStorage_FindPropertyNameById(PropertyStorage_impl *This,
 DWORD propid)
{
    LPWSTR ret = NULL;

290
    dictionary_find(This->propid_to_name, UlongToPtr(propid), (void **)&ret);
291
    TRACE("returning %p\n", ret);
292 293 294
    return ret;
}

295 296 297 298 299 300 301 302 303
/************************************************************************
 * IPropertyStorage_fnReadMultiple (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnReadMultiple(
    IPropertyStorage* iface,
    ULONG cpspec,
    const PROPSPEC rgpspec[],
    PROPVARIANT rgpropvar[])
{
304
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
305
    HRESULT hr = S_OK;
306 307
    ULONG i;

308
    TRACE("(%p, %d, %p, %p)\n", iface, cpspec, rgpspec, rgpropvar);
309

310 311 312
    if (!cpspec)
        return S_FALSE;
    if (!rgpspec || !rgpropvar)
313 314 315 316 317 318 319 320 321 322 323
        return E_INVALIDARG;
    EnterCriticalSection(&This->cs);
    for (i = 0; i < cpspec; i++)
    {
        PropVariantInit(&rgpropvar[i]);
        if (rgpspec[i].ulKind == PRSPEC_LPWSTR)
        {
            PROPVARIANT *prop = PropertyStorage_FindPropertyByName(This,
             rgpspec[i].u.lpwstr);

            if (prop)
324 325
                PropertyStorage_PropVariantCopy(&rgpropvar[i], prop, GetACP(),
                 This->codePage);
326 327 328
        }
        else
        {
329 330 331 332 333 334 335 336 337 338 339 340 341 342
            switch (rgpspec[i].u.propid)
            {
                case PID_CODEPAGE:
                    rgpropvar[i].vt = VT_I2;
                    rgpropvar[i].u.iVal = This->codePage;
                    break;
                case PID_LOCALE:
                    rgpropvar[i].vt = VT_I4;
                    rgpropvar[i].u.lVal = This->locale;
                    break;
                default:
                {
                    PROPVARIANT *prop = PropertyStorage_FindProperty(This,
                     rgpspec[i].u.propid);
343

344 345 346
                    if (prop)
                        PropertyStorage_PropVariantCopy(&rgpropvar[i], prop,
                         GetACP(), This->codePage);
347 348
                    else
                        hr = S_FALSE;
349 350
                }
            }
351 352 353 354 355 356
        }
    }
    LeaveCriticalSection(&This->cs);
    return hr;
}

357 358
static HRESULT PropertyStorage_StringCopy(LPCSTR src, LCID srcCP, LPSTR *dst,
 LCID dstCP)
359 360 361 362
{
    HRESULT hr = S_OK;
    int len;

363
    TRACE("%s, %p, %d, %d\n",
364
     srcCP == CP_UNICODE ? debugstr_w((LPCWSTR)src) : debugstr_a(src), dst,
365
     dstCP, srcCP);
366 367 368
    assert(src);
    assert(dst);
    *dst = NULL;
369
    if (dstCP == srcCP)
370 371 372
    {
        size_t len;

373
        if (dstCP == CP_UNICODE)
374 375 376 377 378 379 380 381 382 383 384
            len = (strlenW((LPCWSTR)src) + 1) * sizeof(WCHAR);
        else
            len = strlen(src) + 1;
        *dst = CoTaskMemAlloc(len * sizeof(WCHAR));
        if (!*dst)
            hr = STG_E_INSUFFICIENTMEMORY;
        else
            memcpy(*dst, src, len);
    }
    else
    {
385
        if (dstCP == CP_UNICODE)
386 387 388 389 390 391 392 393 394 395
        {
            len = MultiByteToWideChar(srcCP, 0, src, -1, NULL, 0);
            *dst = CoTaskMemAlloc(len * sizeof(WCHAR));
            if (!*dst)
                hr = STG_E_INSUFFICIENTMEMORY;
            else
                MultiByteToWideChar(srcCP, 0, src, -1, (LPWSTR)*dst, len);
        }
        else
        {
396 397
            LPCWSTR wideStr = NULL;
            LPWSTR wideStr_tmp = NULL;
398 399

            if (srcCP == CP_UNICODE)
400
                wideStr = (LPCWSTR)src;
401 402 403
            else
            {
                len = MultiByteToWideChar(srcCP, 0, src, -1, NULL, 0);
404 405 406 407 408 409
                wideStr_tmp = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
                if (wideStr_tmp)
                {
                    MultiByteToWideChar(srcCP, 0, src, -1, wideStr_tmp, len);
                    wideStr = wideStr_tmp;
                }
410 411 412 413 414
                else
                    hr = STG_E_INSUFFICIENTMEMORY;
            }
            if (SUCCEEDED(hr))
            {
415
                len = WideCharToMultiByte(dstCP, 0, wideStr, -1, NULL, 0,
416 417 418 419 420 421 422 423
                 NULL, NULL);
                *dst = CoTaskMemAlloc(len);
                if (!*dst)
                    hr = STG_E_INSUFFICIENTMEMORY;
                else
                {
                    BOOL defCharUsed = FALSE;

424 425
                    if (WideCharToMultiByte(dstCP, 0, wideStr, -1, *dst, len,
                     NULL, &defCharUsed) == 0 || defCharUsed)
426 427 428 429 430 431 432
                    {
                        CoTaskMemFree(*dst);
                        *dst = NULL;
                        hr = HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION);
                    }
                }
            }
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 439 440 441 442 443 444 445 446 447 448 449
    return hr;
}

static HRESULT PropertyStorage_PropVariantCopy(PROPVARIANT *prop,
 const PROPVARIANT *propvar, LCID targetCP, LCID srcCP)
{
    HRESULT hr = S_OK;

    assert(prop);
    assert(propvar);
    if (propvar->vt == VT_LPSTR)
    {
450 451
        hr = PropertyStorage_StringCopy(propvar->u.pszVal, srcCP,
         &prop->u.pszVal, targetCP);
452 453 454 455 456 457 458 459 460 461 462 463
        if (SUCCEEDED(hr))
            prop->vt = VT_LPSTR;
    }
    else
        PropVariantCopy(prop, propvar);
    return hr;
}

/* Stores the property with id propid and value propvar into this property
 * storage.  lcid is ignored if propvar's type is not VT_LPSTR.  If propvar's
 * type is VT_LPSTR, converts the string using lcid as the source code page
 * and This->codePage as the target code page before storing.
464 465
 * As a side effect, may change This->format to 1 if the type of propvar is
 * a version 1-only property.
466
 */
467
static HRESULT PropertyStorage_StorePropWithId(PropertyStorage_impl *This,
468
 PROPID propid, const PROPVARIANT *propvar, LCID lcid)
469 470 471 472
{
    HRESULT hr = S_OK;
    PROPVARIANT *prop = PropertyStorage_FindProperty(This, propid);

473
    assert(propvar);
474 475 476 477 478 479 480 481 482 483 484
    if (propvar->vt & VT_BYREF || propvar->vt & VT_ARRAY)
        This->format = 1;
    switch (propvar->vt)
    {
    case VT_DECIMAL:
    case VT_I1:
    case VT_INT:
    case VT_UINT:
    case VT_VECTOR|VT_I1:
        This->format = 1;
    }
485
    TRACE("Setting 0x%08x to type %d\n", propid, propvar->vt);
486 487 488
    if (prop)
    {
        PropVariantClear(prop);
489 490
        hr = PropertyStorage_PropVariantCopy(prop, propvar, This->codePage,
         lcid);
491 492 493 494 495 496 497
    }
    else
    {
        prop = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
         sizeof(PROPVARIANT));
        if (prop)
        {
498 499 500 501
            hr = PropertyStorage_PropVariantCopy(prop, propvar, This->codePage,
             lcid);
            if (SUCCEEDED(hr))
            {
502
                dictionary_insert(This->propid_to_prop, UlongToPtr(propid), prop);
503 504 505 506 507
                if (propid > This->highestProp)
                    This->highestProp = propid;
            }
            else
                HeapFree(GetProcessHeap(), 0, prop);
508 509 510 511 512
        }
        else
            hr = STG_E_INSUFFICIENTMEMORY;
    }
    return hr;
513 514
}

Juan Lang's avatar
Juan Lang committed
515
/* Adds the name srcName to the name dictionaries, mapped to property ID id.
516 517 518 519
 * srcName is encoded in code page cp, and is converted to This->codePage.
 * If cp is CP_UNICODE, srcName is actually a unicode string.
 * As a side effect, may change This->format to 1 if srcName is too long for
 * a version 0 property storage.
Juan Lang's avatar
Juan Lang committed
520 521
 * Doesn't validate id.
 */
522 523
static HRESULT PropertyStorage_StoreNameWithId(PropertyStorage_impl *This,
 LPCSTR srcName, LCID cp, PROPID id)
Juan Lang's avatar
Juan Lang committed
524
{
525
    LPSTR name;
Juan Lang's avatar
Juan Lang committed
526 527 528 529
    HRESULT hr;

    assert(srcName);

530
    hr = PropertyStorage_StringCopy(srcName, cp, &name, This->codePage);
531
    if (SUCCEEDED(hr))
Juan Lang's avatar
Juan Lang committed
532
    {
533 534 535 536 537 538 539 540 541 542
        if (This->codePage == CP_UNICODE)
        {
            if (lstrlenW((LPWSTR)name) >= MAX_VERSION_0_PROP_NAME_LENGTH)
                This->format = 1;
        }
        else
        {
            if (strlen(name) >= MAX_VERSION_0_PROP_NAME_LENGTH)
                This->format = 1;
        }
543
        TRACE("Adding prop name %s, propid %d\n",
544 545
         This->codePage == CP_UNICODE ? debugstr_w((LPCWSTR)name) :
         debugstr_a(name), id);
546 547
        dictionary_insert(This->name_to_propid, name, UlongToPtr(id));
        dictionary_insert(This->propid_to_name, UlongToPtr(id), name);
Juan Lang's avatar
Juan Lang committed
548 549 550 551
    }
    return hr;
}

552 553 554 555 556 557 558 559 560 561
/************************************************************************
 * IPropertyStorage_fnWriteMultiple (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnWriteMultiple(
    IPropertyStorage* iface,
    ULONG cpspec,
    const PROPSPEC rgpspec[],
    const PROPVARIANT rgpropvar[],
    PROPID propidNameFirst)
{
562
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
563 564 565
    HRESULT hr = S_OK;
    ULONG i;

566
    TRACE("(%p, %d, %p, %p)\n", iface, cpspec, rgpspec, rgpropvar);
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    if (cpspec && (!rgpspec || !rgpropvar))
        return E_INVALIDARG;
    if (!(This->grfMode & STGM_READWRITE))
        return STG_E_ACCESSDENIED;
    EnterCriticalSection(&This->cs);
    This->dirty = TRUE;
    This->originatorOS = (DWORD)MAKELONG(LOWORD(GetVersion()),
     PROPSETHDR_OSVER_KIND_WIN32) ;
    for (i = 0; i < cpspec; i++)
    {
        if (rgpspec[i].ulKind == PRSPEC_LPWSTR)
        {
            PROPVARIANT *prop = PropertyStorage_FindPropertyByName(This,
             rgpspec[i].u.lpwstr);

            if (prop)
                PropVariantCopy(prop, &rgpropvar[i]);
            else
            {
587 588 589
                /* Note that I don't do the special cases here that I do below,
                 * because naming the special PIDs isn't supported.
                 */
590 591 592 593 594 595 596
                if (propidNameFirst < PID_FIRST_USABLE ||
                 propidNameFirst >= PID_MIN_READONLY)
                    hr = STG_E_INVALIDPARAMETER;
                else
                {
                    PROPID nextId = max(propidNameFirst, This->highestProp + 1);

597 598
                    hr = PropertyStorage_StoreNameWithId(This,
                     (LPCSTR)rgpspec[i].u.lpwstr, CP_UNICODE, nextId);
Juan Lang's avatar
Juan Lang committed
599
                    if (SUCCEEDED(hr))
600 601
                        hr = PropertyStorage_StorePropWithId(This, nextId,
                         &rgpropvar[i], GetACP());
602 603 604 605 606
                }
            }
        }
        else
        {
607 608 609 610 611 612 613 614 615 616
            switch (rgpspec[i].u.propid)
            {
            case PID_DICTIONARY:
                /* Can't set the dictionary */
                hr = STG_E_INVALIDPARAMETER;
                break;
            case PID_CODEPAGE:
                /* Can only set the code page if nothing else has been set */
                if (dictionary_num_entries(This->propid_to_prop) == 0 &&
                 rgpropvar[i].vt == VT_I2)
Juan Lang's avatar
Juan Lang committed
617
                {
618
                    This->codePage = rgpropvar[i].u.iVal;
Juan Lang's avatar
Juan Lang committed
619 620 621 622 623
                    if (This->codePage == CP_UNICODE)
                        This->grfFlags &= ~PROPSETFLAG_ANSI;
                    else
                        This->grfFlags |= PROPSETFLAG_ANSI;
                }
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
                else
                    hr = STG_E_INVALIDPARAMETER;
                break;
            case PID_LOCALE:
                /* Can only set the locale if nothing else has been set */
                if (dictionary_num_entries(This->propid_to_prop) == 0 &&
                 rgpropvar[i].vt == VT_I4)
                    This->locale = rgpropvar[i].u.lVal;
                else
                    hr = STG_E_INVALIDPARAMETER;
                break;
            case PID_ILLEGAL:
                /* silently ignore like MSDN says */
                break;
            default:
                if (rgpspec[i].u.propid >= PID_MIN_READONLY)
                    hr = STG_E_INVALIDPARAMETER;
                else
                    hr = PropertyStorage_StorePropWithId(This,
643
                     rgpspec[i].u.propid, &rgpropvar[i], GetACP());
644
            }
645 646
        }
    }
647 648
    if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
        IPropertyStorage_Commit(iface, STGC_DEFAULT);
649 650
    LeaveCriticalSection(&This->cs);
    return hr;
651 652 653 654 655 656 657 658 659 660
}

/************************************************************************
 * IPropertyStorage_fnDeleteMultiple (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnDeleteMultiple(
    IPropertyStorage* iface,
    ULONG cpspec,
    const PROPSPEC rgpspec[])
{
661
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
662 663 664
    ULONG i;
    HRESULT hr;

665
    TRACE("(%p, %d, %p)\n", iface, cpspec, rgpspec);
666

667
    if (cpspec && !rgpspec)
668 669 670 671 672
        return E_INVALIDARG;
    if (!(This->grfMode & STGM_READWRITE))
        return STG_E_ACCESSDENIED;
    hr = S_OK;
    EnterCriticalSection(&This->cs);
673
    This->dirty = TRUE;
674 675 676 677
    for (i = 0; i < cpspec; i++)
    {
        if (rgpspec[i].ulKind == PRSPEC_LPWSTR)
        {
678
            void *propid;
679

680 681
            if (dictionary_find(This->name_to_propid, rgpspec[i].u.lpwstr, &propid))
                dictionary_remove(This->propid_to_prop, propid);
682 683 684
        }
        else
        {
685 686
            if (rgpspec[i].u.propid >= PID_FIRST_USABLE &&
             rgpspec[i].u.propid < PID_MIN_READONLY)
687
                dictionary_remove(This->propid_to_prop, UlongToPtr(rgpspec[i].u.propid));
688 689
            else
                hr = STG_E_INVALIDPARAMETER;
690 691
        }
    }
692 693
    if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
        IPropertyStorage_Commit(iface, STGC_DEFAULT);
694 695
    LeaveCriticalSection(&This->cs);
    return hr;
696 697 698 699 700 701 702 703 704 705 706
}

/************************************************************************
 * IPropertyStorage_fnReadPropertyNames (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnReadPropertyNames(
    IPropertyStorage* iface,
    ULONG cpropid,
    const PROPID rgpropid[],
    LPOLESTR rglpwstrName[])
{
707
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
708
    ULONG i;
709
    HRESULT hr = S_FALSE;
710

711
    TRACE("(%p, %d, %p, %p)\n", iface, cpropid, rgpropid, rglpwstrName);
712

713 714 715 716 717 718 719 720 721 722 723 724 725
    if (cpropid && (!rgpropid || !rglpwstrName))
        return E_INVALIDARG;
    EnterCriticalSection(&This->cs);
    for (i = 0; i < cpropid && SUCCEEDED(hr); i++)
    {
        LPWSTR name = PropertyStorage_FindPropertyNameById(This, rgpropid[i]);

        if (name)
        {
            size_t len = lstrlenW(name);

            hr = S_OK;
            rglpwstrName[i] = CoTaskMemAlloc((len + 1) * sizeof(WCHAR));
726 727
            if (rglpwstrName[i])
                memcpy(rglpwstrName[i], name, (len + 1) * sizeof(WCHAR));
728 729 730 731 732 733 734 735
            else
                hr = STG_E_INSUFFICIENTMEMORY;
        }
        else
            rglpwstrName[i] = NULL;
    }
    LeaveCriticalSection(&This->cs);
    return hr;
736 737 738 739 740 741 742 743 744 745 746
}

/************************************************************************
 * IPropertyStorage_fnWritePropertyNames (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnWritePropertyNames(
    IPropertyStorage* iface,
    ULONG cpropid,
    const PROPID rgpropid[],
    const LPOLESTR rglpwstrName[])
{
747
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
748 749 750
    ULONG i;
    HRESULT hr;

751
    TRACE("(%p, %d, %p, %p)\n", iface, cpropid, rgpropid, rglpwstrName);
752

753 754 755 756 757 758
    if (cpropid && (!rgpropid || !rglpwstrName))
        return E_INVALIDARG;
    if (!(This->grfMode & STGM_READWRITE))
        return STG_E_ACCESSDENIED;
    hr = S_OK;
    EnterCriticalSection(&This->cs);
759
    This->dirty = TRUE;
760
    for (i = 0; SUCCEEDED(hr) && i < cpropid; i++)
761 762
    {
        if (rgpropid[i] != PID_ILLEGAL)
763 764
            hr = PropertyStorage_StoreNameWithId(This, (LPCSTR)rglpwstrName[i],
             CP_UNICODE, rgpropid[i]);
765
    }
766 767
    if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
        IPropertyStorage_Commit(iface, STGC_DEFAULT);
768 769
    LeaveCriticalSection(&This->cs);
    return hr;
770 771 772 773 774 775 776 777 778 779
}

/************************************************************************
 * IPropertyStorage_fnDeletePropertyNames (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnDeletePropertyNames(
    IPropertyStorage* iface,
    ULONG cpropid,
    const PROPID rgpropid[])
{
780
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
781 782 783
    ULONG i;
    HRESULT hr;

784
    TRACE("(%p, %d, %p)\n", iface, cpropid, rgpropid);
785

786 787 788 789 790 791
    if (cpropid && !rgpropid)
        return E_INVALIDARG;
    if (!(This->grfMode & STGM_READWRITE))
        return STG_E_ACCESSDENIED;
    hr = S_OK;
    EnterCriticalSection(&This->cs);
792
    This->dirty = TRUE;
793 794 795 796
    for (i = 0; i < cpropid; i++)
    {
        LPWSTR name = NULL;

797
        if (dictionary_find(This->propid_to_name, UlongToPtr(rgpropid[i]), (void **)&name))
798
        {
799
            dictionary_remove(This->propid_to_name, UlongToPtr(rgpropid[i]));
800 801 802
            dictionary_remove(This->name_to_propid, name);
        }
    }
803 804
    if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
        IPropertyStorage_Commit(iface, STGC_DEFAULT);
805 806
    LeaveCriticalSection(&This->cs);
    return hr;
807 808 809 810 811 812 813 814 815
}

/************************************************************************
 * IPropertyStorage_fnCommit (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnCommit(
    IPropertyStorage* iface,
    DWORD grfCommitFlags)
{
816
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
817 818
    HRESULT hr;

819
    TRACE("(%p, 0x%08x)\n", iface, grfCommitFlags);
820

821 822 823 824
    if (!(This->grfMode & STGM_READWRITE))
        return STG_E_ACCESSDENIED;
    EnterCriticalSection(&This->cs);
    if (This->dirty)
825
        hr = PropertyStorage_WriteToStream(This);
826 827 828 829
    else
        hr = S_OK;
    LeaveCriticalSection(&This->cs);
    return hr;
830 831 832 833 834 835 836 837
}

/************************************************************************
 * IPropertyStorage_fnRevert (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnRevert(
    IPropertyStorage* iface)
{
838
    HRESULT hr;
839
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
840 841 842 843 844

    TRACE("%p\n", iface);

    EnterCriticalSection(&This->cs);
    if (This->dirty)
845 846 847 848 849 850
    {
        PropertyStorage_DestroyDictionaries(This);
        hr = PropertyStorage_CreateDictionaries(This);
        if (SUCCEEDED(hr))
            hr = PropertyStorage_ReadFromStream(This);
    }
851 852 853 854
    else
        hr = S_OK;
    LeaveCriticalSection(&This->cs);
    return hr;
855 856 857 858 859 860 861 862 863
}

/************************************************************************
 * IPropertyStorage_fnEnum (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnEnum(
    IPropertyStorage* iface,
    IEnumSTATPROPSTG** ppenum)
{
864
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
865
    return create_EnumSTATPROPSTG(This, ppenum);
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
}

/************************************************************************
 * IPropertyStorage_fnSetTimes (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnSetTimes(
    IPropertyStorage* iface,
    const FILETIME* pctime,
    const FILETIME* patime,
    const FILETIME* pmtime)
{
    FIXME("\n");
    return E_NOTIMPL;
}

/************************************************************************
 * IPropertyStorage_fnSetClass (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnSetClass(
    IPropertyStorage* iface,
    REFCLSID clsid)
{
888
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
889 890

    TRACE("%p, %s\n", iface, debugstr_guid(clsid));
891 892

    if (!clsid)
893 894 895
        return E_INVALIDARG;
    if (!(This->grfMode & STGM_READWRITE))
        return STG_E_ACCESSDENIED;
896
    This->clsid = *clsid;
897
    This->dirty = TRUE;
898 899
    if (This->grfFlags & PROPSETFLAG_UNBUFFERED)
        IPropertyStorage_Commit(iface, STGC_DEFAULT);
900
    return S_OK;
901 902 903 904 905 906 907 908
}

/************************************************************************
 * IPropertyStorage_fnStat (IPropertyStorage)
 */
static HRESULT WINAPI IPropertyStorage_fnStat(
    IPropertyStorage* iface,
    STATPROPSETSTG* statpsstg)
909
{
910
    PropertyStorage_impl *This = impl_from_IPropertyStorage(iface);
911 912 913 914
    STATSTG stat;
    HRESULT hr;

    TRACE("%p, %p\n", iface, statpsstg);
915 916

    if (!statpsstg)
917 918 919 920 921
        return E_INVALIDARG;

    hr = IStream_Stat(This->stm, &stat, STATFLAG_NONAME);
    if (SUCCEEDED(hr))
    {
922 923
        statpsstg->fmtid = This->fmtid;
        statpsstg->clsid = This->clsid;
924
        statpsstg->grfFlags = This->grfFlags;
925 926 927
        statpsstg->mtime = stat.mtime;
        statpsstg->ctime = stat.ctime;
        statpsstg->atime = stat.atime;
928 929 930 931 932 933 934 935
        statpsstg->dwOSVersion = This->originatorOS;
    }
    return hr;
}

static int PropertyStorage_PropNameCompare(const void *a, const void *b,
 void *extra)
{
936
    PropertyStorage_impl *This = extra;
937

938 939 940 941
    if (This->codePage == CP_UNICODE)
    {
        TRACE("(%s, %s)\n", debugstr_w(a), debugstr_w(b));
        if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
942
            return lstrcmpW(a, b);
943
        else
944
            return lstrcmpiW(a, b);
945
    }
946
    else
947 948 949
    {
        TRACE("(%s, %s)\n", debugstr_a(a), debugstr_a(b));
        if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
950
            return lstrcmpA(a, b);
951
        else
952
            return lstrcmpiA(a, b);
953
    }
954 955 956 957
}

static void PropertyStorage_PropNameDestroy(void *k, void *d, void *extra)
{
Juan Lang's avatar
Juan Lang committed
958
    CoTaskMemFree(k);
959 960 961 962 963
}

static int PropertyStorage_PropCompare(const void *a, const void *b,
 void *extra)
{
964 965
    TRACE("(%d, %d)\n", PtrToUlong(a), PtrToUlong(b));
    return PtrToUlong(a) - PtrToUlong(b);
966 967 968 969
}

static void PropertyStorage_PropertyDestroy(void *k, void *d, void *extra)
{
970
    PropVariantClear(d);
971 972 973
    HeapFree(GetProcessHeap(), 0, d);
}

Juan Lang's avatar
Juan Lang committed
974 975
#ifdef WORDS_BIGENDIAN
/* Swaps each character in str to or from little endian; assumes the conversion
976
 * is symmetric, that is, that lendian16toh is equivalent to htole16.
Juan Lang's avatar
Juan Lang committed
977 978 979 980 981 982 983 984 985
 */
static void PropertyStorage_ByteSwapString(LPWSTR str, size_t len)
{
    DWORD i;

    /* Swap characters to host order.
     * FIXME: alignment?
     */
    for (i = 0; i < len; i++)
986
        str[i] = lendian16toh(str[i]);
Juan Lang's avatar
Juan Lang committed
987 988 989 990 991
}
#else
#define PropertyStorage_ByteSwapString(s, l)
#endif

992 993 994 995 996 997 998 999
/* Reads the dictionary from the memory buffer beginning at ptr.  Interprets
 * the entries according to the values of This->codePage and This->locale.
 * FIXME: there isn't any checking whether the read property extends past the
 * end of the buffer.
 */
static HRESULT PropertyStorage_ReadDictionary(PropertyStorage_impl *This,
 BYTE *ptr)
{
1000
    DWORD numEntries, i;
1001 1002
    HRESULT hr = S_OK;

1003 1004 1005 1006
    assert(This->name_to_propid);
    assert(This->propid_to_name);

    StorageUtl_ReadDWord(ptr, 0, &numEntries);
1007
    TRACE("Reading %d entries:\n", numEntries);
1008
    ptr += sizeof(DWORD);
1009
    for (i = 0; SUCCEEDED(hr) && i < numEntries; i++)
1010
    {
1011 1012
        PROPID propid;
        DWORD cbEntry;
1013

1014 1015 1016 1017
        StorageUtl_ReadDWord(ptr, 0, &propid);
        ptr += sizeof(PROPID);
        StorageUtl_ReadDWord(ptr, 0, &cbEntry);
        ptr += sizeof(DWORD);
1018
        TRACE("Reading entry with ID 0x%08x, %d bytes\n", propid, cbEntry);
1019
        /* Make sure the source string is NULL-terminated */
1020
        if (This->codePage != CP_UNICODE)
Juan Lang's avatar
Juan Lang committed
1021
            ptr[cbEntry - 1] = '\0';
1022
        else
Juan Lang's avatar
Juan Lang committed
1023
            *((LPWSTR)ptr + cbEntry / sizeof(WCHAR)) = '\0';
1024
        hr = PropertyStorage_StoreNameWithId(This, (char*)ptr, This->codePage, propid);
1025 1026
        if (This->codePage == CP_UNICODE)
        {
1027 1028 1029
            /* Unicode entries are padded to DWORD boundaries */
            if (cbEntry % sizeof(DWORD))
                ptr += sizeof(DWORD) - (cbEntry % sizeof(DWORD));
1030
        }
1031
        ptr += sizeof(DWORD) + cbEntry;
1032 1033 1034 1035
    }
    return hr;
}

1036
static void* WINAPI Allocate_CoTaskMemAlloc(void *this, ULONG size)
1037 1038 1039 1040
{
    return CoTaskMemAlloc(size);
}

1041 1042 1043
/* FIXME: there isn't any checking whether the read property extends past the
 * end of the buffer.
 */
1044
static HRESULT PropertyStorage_ReadProperty(PROPVARIANT *prop, const BYTE *data,
1045
    UINT codepage, void* (WINAPI *allocate)(void *this, ULONG size), void *allocate_data)
1046 1047 1048
{
    HRESULT hr = S_OK;

1049 1050 1051 1052 1053
    assert(prop);
    assert(data);
    StorageUtl_ReadDWord(data, 0, (DWORD *)&prop->vt);
    data += sizeof(DWORD);
    switch (prop->vt)
1054
    {
1055
    case VT_EMPTY:
1056 1057 1058 1059 1060 1061 1062
    case VT_NULL:
        break;
    case VT_I1:
        prop->u.cVal = *(const char *)data;
        TRACE("Read char 0x%x ('%c')\n", prop->u.cVal, prop->u.cVal);
        break;
    case VT_UI1:
1063
        prop->u.bVal = *data;
1064 1065 1066
        TRACE("Read byte 0x%x\n", prop->u.bVal);
        break;
    case VT_I2:
1067
        StorageUtl_ReadWord(data, 0, (WORD*)&prop->u.iVal);
1068 1069 1070 1071 1072 1073
        TRACE("Read short %d\n", prop->u.iVal);
        break;
    case VT_UI2:
        StorageUtl_ReadWord(data, 0, &prop->u.uiVal);
        TRACE("Read ushort %d\n", prop->u.uiVal);
        break;
1074
    case VT_INT:
1075
    case VT_I4:
1076
        StorageUtl_ReadDWord(data, 0, (DWORD*)&prop->u.lVal);
1077
        TRACE("Read long %d\n", prop->u.lVal);
1078
        break;
1079
    case VT_UINT:
1080 1081
    case VT_UI4:
        StorageUtl_ReadDWord(data, 0, &prop->u.ulVal);
1082
        TRACE("Read ulong %d\n", prop->u.ulVal);
1083 1084 1085
        break;
    case VT_LPSTR:
    {
1086 1087 1088
        DWORD count;
       
        StorageUtl_ReadDWord(data, 0, &count);
Vincent Povirk's avatar
Vincent Povirk committed
1089
        if (codepage == CP_UNICODE && count % 2)
1090
        {
1091 1092
            WARN("Unicode string has odd number of bytes\n");
            hr = STG_E_INVALIDHEADER;
1093 1094
        }
        else
1095
        {
1096
            prop->u.pszVal = allocate(allocate_data, count);
1097 1098 1099
            if (prop->u.pszVal)
            {
                memcpy(prop->u.pszVal, data + sizeof(DWORD), count);
1100
                /* This is stored in the code page specified in codepage.
1101 1102
                 * Don't convert it, the caller will just store it as-is.
                 */
1103
                if (codepage == CP_UNICODE)
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
                {
                    /* Make sure it's NULL-terminated */
                    prop->u.pszVal[count / sizeof(WCHAR) - 1] = '\0';
                    TRACE("Read string value %s\n",
                     debugstr_w(prop->u.pwszVal));
                }
                else
                {
                    /* Make sure it's NULL-terminated */
                    prop->u.pszVal[count - 1] = '\0';
                    TRACE("Read string value %s\n", debugstr_a(prop->u.pszVal));
                }
            }
            else
                hr = STG_E_INSUFFICIENTMEMORY;
        }
1120 1121
        break;
    }
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
    case VT_BSTR:
    {
        DWORD count, wcount;

        StorageUtl_ReadDWord(data, 0, &count);
        if (codepage == CP_UNICODE && count % 2)
        {
            WARN("Unicode string has odd number of bytes\n");
            hr = STG_E_INVALIDHEADER;
        }
        else
        {
            if (codepage == CP_UNICODE)
                wcount = count / 2;
            else
                wcount = MultiByteToWideChar(codepage, 0, (LPCSTR)(data + sizeof(DWORD)), count, NULL, 0);

            prop->u.bstrVal = SysAllocStringLen(NULL, wcount); /* FIXME: use allocator? */

            if (prop->u.bstrVal)
            {
                if (codepage == CP_UNICODE)
                    memcpy(prop->u.bstrVal, data + sizeof(DWORD), count);
                else
                    MultiByteToWideChar(codepage, 0, (LPCSTR)(data + sizeof(DWORD)), count, prop->u.bstrVal, wcount);

                prop->u.bstrVal[wcount - 1] = '\0';
                TRACE("Read string value %s\n", debugstr_w(prop->u.bstrVal));
            }
            else
                hr = STG_E_INSUFFICIENTMEMORY;
        }
        break;
    }
1156 1157 1158 1159 1160 1161
    case VT_BLOB:
    {
        DWORD count;

        StorageUtl_ReadDWord(data, 0, &count);
        prop->u.blob.cbSize = count;
1162
        prop->u.blob.pBlobData = allocate(allocate_data, count);
1163 1164 1165 1166 1167 1168 1169 1170 1171
        if (prop->u.blob.pBlobData)
        {
            memcpy(prop->u.blob.pBlobData, data + sizeof(DWORD), count);
            TRACE("Read blob value of size %d\n", count);
        }
        else
            hr = STG_E_INSUFFICIENTMEMORY;
        break;
    }
1172 1173
    case VT_LPWSTR:
    {
1174
        DWORD count;
1175

1176
        StorageUtl_ReadDWord(data, 0, &count);
1177
        prop->u.pwszVal = allocate(allocate_data, count * sizeof(WCHAR));
1178 1179 1180 1181
        if (prop->u.pwszVal)
        {
            memcpy(prop->u.pwszVal, data + sizeof(DWORD),
             count * sizeof(WCHAR));
Juan Lang's avatar
Juan Lang committed
1182 1183 1184
            /* make sure string is NULL-terminated */
            prop->u.pwszVal[count - 1] = '\0';
            PropertyStorage_ByteSwapString(prop->u.pwszVal, count);
1185 1186 1187 1188 1189 1190 1191
            TRACE("Read string value %s\n", debugstr_w(prop->u.pwszVal));
        }
        else
            hr = STG_E_INSUFFICIENTMEMORY;
        break;
    }
    case VT_FILETIME:
Juan Lang's avatar
Juan Lang committed
1192 1193
        StorageUtl_ReadULargeInteger(data, 0,
         (ULARGE_INTEGER *)&prop->u.filetime);
1194
        break;
1195 1196
    case VT_CF:
        {
1197
            DWORD len = 0, tag = 0;
1198 1199 1200

            StorageUtl_ReadDWord(data, 0, &len);
            StorageUtl_ReadDWord(data, 4, &tag);
1201
            if (len > 8)
1202
            {
1203
                len -= 8;
1204
                prop->u.pclipdata = allocate(allocate_data, sizeof (CLIPDATA));
1205
                prop->u.pclipdata->cbSize = len;
1206
                prop->u.pclipdata->ulClipFmt = tag;
1207
                prop->u.pclipdata->pClipData = allocate(allocate_data, len - sizeof(prop->u.pclipdata->ulClipFmt));
1208
                memcpy(prop->u.pclipdata->pClipData, data+8, len - sizeof(prop->u.pclipdata->ulClipFmt));
1209 1210 1211 1212 1213
            }
            else
                hr = STG_E_INVALIDPARAMETER;
        }
        break;
1214
    default:
1215
        FIXME("unsupported type %d\n", prop->vt);
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        hr = STG_E_INVALIDPARAMETER;
    }
    return hr;
}

static HRESULT PropertyStorage_ReadHeaderFromStream(IStream *stm,
 PROPERTYSETHEADER *hdr)
{
    BYTE buf[sizeof(PROPERTYSETHEADER)];
    ULONG count = 0;
    HRESULT hr;

1228 1229
    assert(stm);
    assert(hdr);
1230 1231 1232 1233 1234
    hr = IStream_Read(stm, buf, sizeof(buf), &count);
    if (SUCCEEDED(hr))
    {
        if (count != sizeof(buf))
        {
1235
            WARN("read only %d\n", count);
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
            hr = STG_E_INVALIDHEADER;
        }
        else
        {
            StorageUtl_ReadWord(buf, offsetof(PROPERTYSETHEADER, wByteOrder),
             &hdr->wByteOrder);
            StorageUtl_ReadWord(buf, offsetof(PROPERTYSETHEADER, wFormat),
             &hdr->wFormat);
            StorageUtl_ReadDWord(buf, offsetof(PROPERTYSETHEADER, dwOSVer),
             &hdr->dwOSVer);
            StorageUtl_ReadGUID(buf, offsetof(PROPERTYSETHEADER, clsid),
             &hdr->clsid);
            StorageUtl_ReadDWord(buf, offsetof(PROPERTYSETHEADER, reserved),
             &hdr->reserved);
        }
    }
1252
    TRACE("returning 0x%08x\n", hr);
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    return hr;
}

static HRESULT PropertyStorage_ReadFmtIdOffsetFromStream(IStream *stm,
 FORMATIDOFFSET *fmt)
{
    BYTE buf[sizeof(FORMATIDOFFSET)];
    ULONG count = 0;
    HRESULT hr;

1263 1264
    assert(stm);
    assert(fmt);
1265 1266 1267 1268 1269
    hr = IStream_Read(stm, buf, sizeof(buf), &count);
    if (SUCCEEDED(hr))
    {
        if (count != sizeof(buf))
        {
1270
            WARN("read only %d\n", count);
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
            hr = STG_E_INVALIDHEADER;
        }
        else
        {
            StorageUtl_ReadGUID(buf, offsetof(FORMATIDOFFSET, fmtid),
             &fmt->fmtid);
            StorageUtl_ReadDWord(buf, offsetof(FORMATIDOFFSET, dwOffset),
             &fmt->dwOffset);
        }
    }
1281
    TRACE("returning 0x%08x\n", hr);
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    return hr;
}

static HRESULT PropertyStorage_ReadSectionHeaderFromStream(IStream *stm,
 PROPERTYSECTIONHEADER *hdr)
{
    BYTE buf[sizeof(PROPERTYSECTIONHEADER)];
    ULONG count = 0;
    HRESULT hr;

1292 1293
    assert(stm);
    assert(hdr);
1294 1295 1296 1297 1298
    hr = IStream_Read(stm, buf, sizeof(buf), &count);
    if (SUCCEEDED(hr))
    {
        if (count != sizeof(buf))
        {
1299
            WARN("read only %d\n", count);
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
            hr = STG_E_INVALIDHEADER;
        }
        else
        {
            StorageUtl_ReadDWord(buf, offsetof(PROPERTYSECTIONHEADER,
             cbSection), &hdr->cbSection);
            StorageUtl_ReadDWord(buf, offsetof(PROPERTYSECTIONHEADER,
             cProperties), &hdr->cProperties);
        }
    }
1310
    TRACE("returning 0x%08x\n", hr);
1311 1312 1313
    return hr;
}

1314
static HRESULT PropertyStorage_ReadFromStream(PropertyStorage_impl *This)
1315 1316 1317 1318
{
    PROPERTYSETHEADER hdr;
    FORMATIDOFFSET fmtOffset;
    PROPERTYSECTIONHEADER sectionHdr;
1319
    LARGE_INTEGER seek;
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    ULONG i;
    STATSTG stat;
    HRESULT hr;
    BYTE *buf = NULL;
    ULONG count = 0;
    DWORD dictOffset = 0;

    This->dirty = FALSE;
    This->highestProp = 0;
    hr = IStream_Stat(This->stm, &stat, STATFLAG_NONAME);
    if (FAILED(hr))
        goto end;
    if (stat.cbSize.u.HighPart)
    {
        WARN("stream too big\n");
        /* maximum size varies, but it can't be this big */
        hr = STG_E_INVALIDHEADER;
        goto end;
    }
    if (stat.cbSize.u.LowPart == 0)
    {
1341
        /* empty stream is okay */
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
        hr = S_OK;
        goto end;
    }
    else if (stat.cbSize.u.LowPart < sizeof(PROPERTYSETHEADER) +
     sizeof(FORMATIDOFFSET))
    {
        WARN("stream too small\n");
        hr = STG_E_INVALIDHEADER;
        goto end;
    }
1352 1353 1354 1355
    seek.QuadPart = 0;
    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
    hr = PropertyStorage_ReadHeaderFromStream(This->stm, &hdr);
    /* I've only seen reserved == 1, but the article says I shouldn't disallow
     * higher values.
     */
    if (hdr.wByteOrder != PROPSETHDR_BYTEORDER_MAGIC || hdr.reserved < 1)
    {
        WARN("bad magic in prop set header\n");
        hr = STG_E_INVALIDHEADER;
        goto end;
    }
    if (hdr.wFormat != 0 && hdr.wFormat != 1)
    {
        WARN("bad format version %d\n", hdr.wFormat);
        hr = STG_E_INVALIDHEADER;
        goto end;
    }
1372
    This->format = hdr.wFormat;
1373
    This->clsid = hdr.clsid;
1374 1375 1376 1377 1378 1379 1380 1381
    This->originatorOS = hdr.dwOSVer;
    if (PROPSETHDR_OSVER_KIND(hdr.dwOSVer) == PROPSETHDR_OSVER_KIND_MAC)
        WARN("File comes from a Mac, strings will probably be screwed up\n");
    hr = PropertyStorage_ReadFmtIdOffsetFromStream(This->stm, &fmtOffset);
    if (FAILED(hr))
        goto end;
    if (fmtOffset.dwOffset > stat.cbSize.u.LowPart)
    {
1382
        WARN("invalid offset %d (stream length is %d)\n", fmtOffset.dwOffset,
1383 1384 1385 1386 1387
         stat.cbSize.u.LowPart);
        hr = STG_E_INVALIDHEADER;
        goto end;
    }
    /* wackiness alert: if the format ID is FMTID_DocSummaryInformation, there
1388 1389
     * follows not one, but two sections.  The first contains the standard properties
     * for the document summary information, and the second consists of user-defined
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
     * properties.  This is the only case in which multiple sections are
     * allowed.
     * Reading the second stream isn't implemented yet.
     */
    hr = PropertyStorage_ReadSectionHeaderFromStream(This->stm, &sectionHdr);
    if (FAILED(hr))
        goto end;
    /* The section size includes the section header, so check it */
    if (sectionHdr.cbSection < sizeof(PROPERTYSECTIONHEADER))
    {
1400
        WARN("section header too small, got %d\n", sectionHdr.cbSection);
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
        hr = STG_E_INVALIDHEADER;
        goto end;
    }
    buf = HeapAlloc(GetProcessHeap(), 0, sectionHdr.cbSection -
     sizeof(PROPERTYSECTIONHEADER));
    if (!buf)
    {
        hr = STG_E_INSUFFICIENTMEMORY;
        goto end;
    }
    hr = IStream_Read(This->stm, buf, sectionHdr.cbSection -
     sizeof(PROPERTYSECTIONHEADER), &count);
    if (FAILED(hr))
        goto end;
1415
    TRACE("Reading %d properties:\n", sectionHdr.cProperties);
1416 1417 1418 1419 1420 1421
    for (i = 0; SUCCEEDED(hr) && i < sectionHdr.cProperties; i++)
    {
        PROPERTYIDOFFSET *idOffset = (PROPERTYIDOFFSET *)(buf +
         i * sizeof(PROPERTYIDOFFSET));

        if (idOffset->dwOffset < sizeof(PROPERTYSECTIONHEADER) ||
1422
         idOffset->dwOffset > sectionHdr.cbSection - sizeof(DWORD))
1423 1424 1425 1426 1427 1428 1429
            hr = STG_E_INVALIDPOINTER;
        else
        {
            if (idOffset->propid >= PID_FIRST_USABLE &&
             idOffset->propid < PID_MIN_READONLY && idOffset->propid >
             This->highestProp)
                This->highestProp = idOffset->propid;
1430
            if (idOffset->propid == PID_DICTIONARY)
1431 1432 1433 1434 1435 1436
            {
                /* Don't read the dictionary yet, its entries depend on the
                 * code page.  Just store the offset so we know to read it
                 * later.
                 */
                dictOffset = idOffset->dwOffset;
1437
                TRACE("Dictionary offset is %d\n", dictOffset);
1438 1439 1440 1441 1442
            }
            else
            {
                PROPVARIANT prop;

1443
                PropVariantInit(&prop);
1444 1445 1446
                if (SUCCEEDED(PropertyStorage_ReadProperty(&prop,
                 buf + idOffset->dwOffset - sizeof(PROPERTYSECTIONHEADER),
                 This->codePage, Allocate_CoTaskMemAlloc, NULL)))
1447
                {
1448
                    TRACE("Read property with ID 0x%08x, type %d\n",
1449
                     idOffset->propid, prop.vt);
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
                    switch(idOffset->propid)
                    {
                    case PID_CODEPAGE:
                        if (prop.vt == VT_I2)
                            This->codePage = (UINT)prop.u.iVal;
                        break;
                    case PID_LOCALE:
                        if (prop.vt == VT_I4)
                            This->locale = (LCID)prop.u.lVal;
                        break;
                    case PID_BEHAVIOR:
                        if (prop.vt == VT_I4 && prop.u.lVal)
                            This->grfFlags |= PROPSETFLAG_CASE_SENSITIVE;
1463 1464
                        /* The format should already be 1, but just in case */
                        This->format = 1;
1465 1466 1467
                        break;
                    default:
                        hr = PropertyStorage_StorePropWithId(This,
1468
                         idOffset->propid, &prop, This->codePage);
1469 1470
                    }
                }
Juan Lang's avatar
Juan Lang committed
1471
                PropVariantClear(&prop);
1472 1473 1474 1475 1476
            }
        }
    }
    if (!This->codePage)
    {
1477
        /* default to Unicode unless told not to, as specified on msdn */
1478 1479 1480
        if (This->grfFlags & PROPSETFLAG_ANSI)
            This->codePage = GetACP();
        else
1481
            This->codePage = CP_UNICODE;
1482 1483 1484
    }
    if (!This->locale)
        This->locale = LOCALE_SYSTEM_DEFAULT;
1485
    TRACE("Code page is %d, locale is %d\n", This->codePage, This->locale);
1486
    if (dictOffset)
1487
        hr = PropertyStorage_ReadDictionary(This,
1488 1489 1490 1491
         buf + dictOffset - sizeof(PROPERTYSECTIONHEADER));

end:
    HeapFree(GetProcessHeap(), 0, buf);
1492 1493 1494 1495 1496 1497 1498 1499 1500
    if (FAILED(hr))
    {
        dictionary_destroy(This->name_to_propid);
        This->name_to_propid = NULL;
        dictionary_destroy(This->propid_to_name);
        This->propid_to_name = NULL;
        dictionary_destroy(This->propid_to_prop);
        This->propid_to_prop = NULL;
    }
1501 1502 1503
    return hr;
}

1504 1505
static void PropertyStorage_MakeHeader(PropertyStorage_impl *This,
 PROPERTYSETHEADER *hdr)
1506
{
1507 1508 1509
    assert(hdr);
    StorageUtl_WriteWord((BYTE *)&hdr->wByteOrder, 0,
     PROPSETHDR_BYTEORDER_MAGIC);
1510
    StorageUtl_WriteWord((BYTE *)&hdr->wFormat, 0, This->format);
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
    StorageUtl_WriteDWord((BYTE *)&hdr->dwOSVer, 0, This->originatorOS);
    StorageUtl_WriteGUID((BYTE *)&hdr->clsid, 0, &This->clsid);
    StorageUtl_WriteDWord((BYTE *)&hdr->reserved, 0, 1);
}

static void PropertyStorage_MakeFmtIdOffset(PropertyStorage_impl *This,
 FORMATIDOFFSET *fmtOffset)
{
    assert(fmtOffset);
    StorageUtl_WriteGUID((BYTE *)fmtOffset, 0, &This->fmtid);
    StorageUtl_WriteDWord((BYTE *)fmtOffset, offsetof(FORMATIDOFFSET, dwOffset),
     sizeof(PROPERTYSETHEADER) + sizeof(FORMATIDOFFSET));
}

static void PropertyStorage_MakeSectionHdr(DWORD cbSection, DWORD numProps,
 PROPERTYSECTIONHEADER *hdr)
{
    assert(hdr);
    StorageUtl_WriteDWord((BYTE *)hdr, 0, cbSection);
    StorageUtl_WriteDWord((BYTE *)hdr,
     offsetof(PROPERTYSECTIONHEADER, cProperties), numProps);
}

static void PropertyStorage_MakePropertyIdOffset(DWORD propid, DWORD dwOffset,
 PROPERTYIDOFFSET *propIdOffset)
{
    assert(propIdOffset);
    StorageUtl_WriteDWord((BYTE *)propIdOffset, 0, propid);
    StorageUtl_WriteDWord((BYTE *)propIdOffset,
     offsetof(PROPERTYIDOFFSET, dwOffset), dwOffset);
}

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
static inline HRESULT PropertStorage_WriteWStringToStream(IStream *stm,
 LPCWSTR str, DWORD len, DWORD *written)
{
#ifdef WORDS_BIGENDIAN
    WCHAR *leStr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
    HRESULT hr;

    if (!leStr)
        return E_OUTOFMEMORY;
    memcpy(leStr, str, len * sizeof(WCHAR));
    PropertyStorage_ByteSwapString(leStr, len);
    hr = IStream_Write(stm, leStr, len, written);
    HeapFree(GetProcessHeap(), 0, leStr);
    return hr;
#else
    return IStream_Write(stm, str, len, written);
#endif
}

1562 1563 1564 1565 1566 1567 1568 1569 1570
struct DictionaryClosure
{
    HRESULT hr;
    DWORD bytesWritten;
};

static BOOL PropertyStorage_DictionaryWriter(const void *key,
 const void *value, void *extra, void *closure)
{
1571 1572
    PropertyStorage_impl *This = extra;
    struct DictionaryClosure *c = closure;
1573 1574 1575 1576 1577
    DWORD propid;
    ULONG count;

    assert(key);
    assert(closure);
1578
    StorageUtl_WriteDWord((LPBYTE)&propid, 0, PtrToUlong(value));
1579 1580 1581 1582 1583 1584 1585 1586 1587
    c->hr = IStream_Write(This->stm, &propid, sizeof(propid), &count);
    if (FAILED(c->hr))
        goto end;
    c->bytesWritten += sizeof(DWORD);
    if (This->codePage == CP_UNICODE)
    {
        DWORD keyLen, pad = 0;

        StorageUtl_WriteDWord((LPBYTE)&keyLen, 0,
1588
         (lstrlenW((LPCWSTR)key) + 1) * sizeof(WCHAR));
1589 1590 1591 1592
        c->hr = IStream_Write(This->stm, &keyLen, sizeof(keyLen), &count);
        if (FAILED(c->hr))
            goto end;
        c->bytesWritten += sizeof(DWORD);
1593 1594
        c->hr = PropertStorage_WriteWStringToStream(This->stm, key, keyLen,
         &count);
1595 1596
        if (FAILED(c->hr))
            goto end;
Juan Lang's avatar
Juan Lang committed
1597
        c->bytesWritten += keyLen * sizeof(WCHAR);
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
        if (keyLen % sizeof(DWORD))
        {
            c->hr = IStream_Write(This->stm, &pad,
             sizeof(DWORD) - keyLen % sizeof(DWORD), &count);
            if (FAILED(c->hr))
                goto end;
            c->bytesWritten += sizeof(DWORD) - keyLen % sizeof(DWORD);
        }
    }
    else
    {
1609
        DWORD keyLen;
1610

1611 1612
        StorageUtl_WriteDWord((LPBYTE)&keyLen, 0, strlen((LPCSTR)key) + 1);
        c->hr = IStream_Write(This->stm, &keyLen, sizeof(keyLen), &count);
1613 1614 1615
        if (FAILED(c->hr))
            goto end;
        c->bytesWritten += sizeof(DWORD);
1616
        c->hr = IStream_Write(This->stm, key, keyLen, &count);
1617 1618
        if (FAILED(c->hr))
            goto end;
1619
        c->bytesWritten += keyLen;
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
    }
end:
    return SUCCEEDED(c->hr);
}

#define SECTIONHEADER_OFFSET sizeof(PROPERTYSETHEADER) + sizeof(FORMATIDOFFSET)

/* Writes the dictionary to the stream.  Assumes without checking that the
 * dictionary isn't empty.
 */
static HRESULT PropertyStorage_WriteDictionaryToStream(
 PropertyStorage_impl *This, DWORD *sectionOffset)
{
    HRESULT hr;
    LARGE_INTEGER seek;
    PROPERTYIDOFFSET propIdOffset;
    ULONG count;
    DWORD dwTemp;
    struct DictionaryClosure closure;

    assert(sectionOffset);

    /* The dictionary's always the first property written, so seek to its
     * spot.
     */
    seek.QuadPart = SECTIONHEADER_OFFSET + sizeof(PROPERTYSECTIONHEADER);
    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
    PropertyStorage_MakePropertyIdOffset(PID_DICTIONARY, *sectionOffset,
     &propIdOffset);
    hr = IStream_Write(This->stm, &propIdOffset, sizeof(propIdOffset), &count);
    if (FAILED(hr))
        goto end;

    seek.QuadPart = SECTIONHEADER_OFFSET + *sectionOffset;
    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
    StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0,
     dictionary_num_entries(This->name_to_propid));
    hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
    if (FAILED(hr))
        goto end;
    *sectionOffset += sizeof(dwTemp);

    closure.hr = S_OK;
    closure.bytesWritten = 0;
    dictionary_enumerate(This->name_to_propid, PropertyStorage_DictionaryWriter,
     &closure);
    hr = closure.hr;
    if (FAILED(hr))
        goto end;
    *sectionOffset += closure.bytesWritten;
    if (closure.bytesWritten % sizeof(DWORD))
    {
1676 1677 1678
        DWORD padding = sizeof(DWORD) - closure.bytesWritten % sizeof(DWORD);
        TRACE("adding %d bytes of padding\n", padding);
        *sectionOffset += padding;
1679 1680 1681 1682 1683 1684 1685
    }

end:
    return hr;
}

static HRESULT PropertyStorage_WritePropertyToStream(PropertyStorage_impl *This,
1686
 DWORD propNum, DWORD propid, const PROPVARIANT *var, DWORD *sectionOffset)
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
{
    HRESULT hr;
    LARGE_INTEGER seek;
    PROPERTYIDOFFSET propIdOffset;
    ULONG count;
    DWORD dwType, bytesWritten;

    assert(var);
    assert(sectionOffset);

1697
    TRACE("%p, %d, 0x%08x, (%d), (%d)\n", This, propNum, propid, var->vt,
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
     *sectionOffset);

    seek.QuadPart = SECTIONHEADER_OFFSET + sizeof(PROPERTYSECTIONHEADER) +
     propNum * sizeof(PROPERTYIDOFFSET);
    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
    PropertyStorage_MakePropertyIdOffset(propid, *sectionOffset, &propIdOffset);
    hr = IStream_Write(This->stm, &propIdOffset, sizeof(propIdOffset), &count);
    if (FAILED(hr))
        goto end;

    seek.QuadPart = SECTIONHEADER_OFFSET + *sectionOffset;
    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
    StorageUtl_WriteDWord((LPBYTE)&dwType, 0, var->vt);
    hr = IStream_Write(This->stm, &dwType, sizeof(dwType), &count);
    if (FAILED(hr))
        goto end;
    *sectionOffset += sizeof(dwType);

    switch (var->vt)
    {
    case VT_EMPTY:
    case VT_NULL:
        bytesWritten = 0;
        break;
    case VT_I1:
    case VT_UI1:
        hr = IStream_Write(This->stm, &var->u.cVal, sizeof(var->u.cVal),
         &count);
        bytesWritten = count;
        break;
    case VT_I2:
    case VT_UI2:
    {
        WORD wTemp;

        StorageUtl_WriteWord((LPBYTE)&wTemp, 0, var->u.iVal);
        hr = IStream_Write(This->stm, &wTemp, sizeof(wTemp), &count);
        bytesWritten = count;
        break;
    }
    case VT_I4:
    case VT_UI4:
    {
        DWORD dwTemp;

        StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, var->u.lVal);
        hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
        bytesWritten = count;
        break;
    }
    case VT_LPSTR:
    {
        DWORD len, dwTemp;

        if (This->codePage == CP_UNICODE)
            len = (lstrlenW(var->u.pwszVal) + 1) * sizeof(WCHAR);
        else
            len = lstrlenA(var->u.pszVal) + 1;
        StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, len);
        hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
        if (FAILED(hr))
            goto end;
        hr = IStream_Write(This->stm, var->u.pszVal, len, &count);
        bytesWritten = count + sizeof(DWORD);
        break;
    }
    case VT_LPWSTR:
    {
        DWORD len = lstrlenW(var->u.pwszVal) + 1, dwTemp;

        StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, len);
        hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);
        if (FAILED(hr))
            goto end;
        hr = IStream_Write(This->stm, var->u.pwszVal, len * sizeof(WCHAR),
         &count);
        bytesWritten = count + sizeof(DWORD);
        break;
    }
Juan Lang's avatar
Juan Lang committed
1781 1782 1783 1784 1785
    case VT_FILETIME:
    {
        FILETIME temp;

        StorageUtl_WriteULargeInteger((BYTE *)&temp, 0,
1786
         (const ULARGE_INTEGER *)&var->u.filetime);
Juan Lang's avatar
Juan Lang committed
1787 1788 1789 1790
        hr = IStream_Write(This->stm, &temp, sizeof(FILETIME), &count);
        bytesWritten = count;
        break;
    }
1791 1792 1793 1794 1795 1796 1797
    case VT_CF:
    {
        DWORD cf_hdr[2], len;

        len = var->u.pclipdata->cbSize;
        StorageUtl_WriteDWord((LPBYTE)&cf_hdr[0], 0, len + 8);
        StorageUtl_WriteDWord((LPBYTE)&cf_hdr[1], 0, var->u.pclipdata->ulClipFmt);
1798
        hr = IStream_Write(This->stm, cf_hdr, sizeof(cf_hdr), &count);
1799 1800
        if (FAILED(hr))
            goto end;
1801 1802
        hr = IStream_Write(This->stm, var->u.pclipdata->pClipData,
                           len - sizeof(var->u.pclipdata->ulClipFmt), &count);
1803 1804 1805 1806 1807
        if (FAILED(hr))
            goto end;
        bytesWritten = count + sizeof cf_hdr;
        break;
    }
1808 1809 1810 1811 1812 1813 1814 1815 1816
    case VT_CLSID:
    {
        CLSID temp;

        StorageUtl_WriteGUID((BYTE *)&temp, 0, var->u.puuid);
        hr = IStream_Write(This->stm, &temp, sizeof(temp), &count);
        bytesWritten = count;
        break;
    }
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
    default:
        FIXME("unsupported type: %d\n", var->vt);
        return STG_E_INVALIDPARAMETER;
    }

    if (SUCCEEDED(hr))
    {
        *sectionOffset += bytesWritten;
        if (bytesWritten % sizeof(DWORD))
        {
1827 1828 1829
            DWORD padding = sizeof(DWORD) - bytesWritten % sizeof(DWORD);
            TRACE("adding %d bytes of padding\n", padding);
            *sectionOffset += padding;
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
        }
    }

end:
    return hr;
}

struct PropertyClosure
{
    HRESULT hr;
    DWORD   propNum;
    DWORD  *sectionOffset;
};

static BOOL PropertyStorage_PropertiesWriter(const void *key, const void *value,
 void *extra, void *closure)
{
1847 1848
    PropertyStorage_impl *This = extra;
    struct PropertyClosure *c = closure;
1849 1850 1851 1852 1853

    assert(key);
    assert(value);
    assert(extra);
    assert(closure);
1854
    c->hr = PropertyStorage_WritePropertyToStream(This, c->propNum++,
1855
                                                  PtrToUlong(key), value, c->sectionOffset);
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
    return SUCCEEDED(c->hr);
}

static HRESULT PropertyStorage_WritePropertiesToStream(
 PropertyStorage_impl *This, DWORD startingPropNum, DWORD *sectionOffset)
{
    struct PropertyClosure closure;

    assert(sectionOffset);
    closure.hr = S_OK;
    closure.propNum = startingPropNum;
    closure.sectionOffset = sectionOffset;
    dictionary_enumerate(This->propid_to_prop, PropertyStorage_PropertiesWriter,
     &closure);
    return closure.hr;
}

static HRESULT PropertyStorage_WriteHeadersToStream(PropertyStorage_impl *This)
{
    HRESULT hr;
    ULONG count = 0;
    LARGE_INTEGER seek = { {0} };
    PROPERTYSETHEADER hdr;
    FORMATIDOFFSET fmtOffset;

    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
    PropertyStorage_MakeHeader(This, &hdr);
    hr = IStream_Write(This->stm, &hdr, sizeof(hdr), &count);
    if (FAILED(hr))
        goto end;
    if (count != sizeof(hdr))
    {
        hr = STG_E_WRITEFAULT;
        goto end;
    }

    PropertyStorage_MakeFmtIdOffset(This, &fmtOffset);
    hr = IStream_Write(This->stm, &fmtOffset, sizeof(fmtOffset), &count);
    if (FAILED(hr))
        goto end;
    if (count != sizeof(fmtOffset))
    {
        hr = STG_E_WRITEFAULT;
        goto end;
    }
    hr = S_OK;

end:
    return hr;
}

static HRESULT PropertyStorage_WriteToStream(PropertyStorage_impl *This)
{
    PROPERTYSECTIONHEADER sectionHdr;
    HRESULT hr;
    ULONG count;
    LARGE_INTEGER seek;
    DWORD numProps, prop, sectionOffset, dwTemp;
    PROPVARIANT var;

    PropertyStorage_WriteHeadersToStream(This);

    /* Count properties.  Always at least one property, the code page */
    numProps = 1;
    if (dictionary_num_entries(This->name_to_propid))
        numProps++;
    if (This->locale != LOCALE_SYSTEM_DEFAULT)
        numProps++;
    if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
        numProps++;
    numProps += dictionary_num_entries(This->propid_to_prop);

    /* Write section header with 0 bytes right now, I'll adjust it after
     * writing properties.
     */
    PropertyStorage_MakeSectionHdr(0, numProps, &sectionHdr);
    seek.QuadPart = SECTIONHEADER_OFFSET;
    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
    hr = IStream_Write(This->stm, &sectionHdr, sizeof(sectionHdr), &count);
    if (FAILED(hr))
        goto end;

    prop = 0;
    sectionOffset = sizeof(PROPERTYSECTIONHEADER) +
     numProps * sizeof(PROPERTYIDOFFSET);

    if (dictionary_num_entries(This->name_to_propid))
    {
        prop++;
        hr = PropertyStorage_WriteDictionaryToStream(This, &sectionOffset);
        if (FAILED(hr))
            goto end;
    }

    PropVariantInit(&var);

    var.vt = VT_I2;
    var.u.iVal = This->codePage;
    hr = PropertyStorage_WritePropertyToStream(This, prop++, PID_CODEPAGE,
     &var, &sectionOffset);
    if (FAILED(hr))
        goto end;

    if (This->locale != LOCALE_SYSTEM_DEFAULT)
    {
        var.vt = VT_I4;
        var.u.lVal = This->locale;
        hr = PropertyStorage_WritePropertyToStream(This, prop++, PID_LOCALE,
         &var, &sectionOffset);
        if (FAILED(hr))
            goto end;
    }

    if (This->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
    {
        var.vt = VT_I4;
        var.u.lVal = 1;
        hr = PropertyStorage_WritePropertyToStream(This, prop++, PID_BEHAVIOR,
         &var, &sectionOffset);
        if (FAILED(hr))
            goto end;
    }

    hr = PropertyStorage_WritePropertiesToStream(This, prop, &sectionOffset);
    if (FAILED(hr))
        goto end;

    /* Now write the byte count of the section */
    seek.QuadPart = SECTIONHEADER_OFFSET;
    hr = IStream_Seek(This->stm, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
        goto end;
    StorageUtl_WriteDWord((LPBYTE)&dwTemp, 0, sectionOffset);
    hr = IStream_Write(This->stm, &dwTemp, sizeof(dwTemp), &count);

end:
    return hr;
1997 1998 1999
}

/***********************************************************************
2000
 * PropertyStorage_Construct
2001
 */
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
static void PropertyStorage_DestroyDictionaries(PropertyStorage_impl *This)
{
    dictionary_destroy(This->name_to_propid);
    This->name_to_propid = NULL;
    dictionary_destroy(This->propid_to_name);
    This->propid_to_name = NULL;
    dictionary_destroy(This->propid_to_prop);
    This->propid_to_prop = NULL;
}

static HRESULT PropertyStorage_CreateDictionaries(PropertyStorage_impl *This)
{
    HRESULT hr = S_OK;

    This->name_to_propid = dictionary_create(
     PropertyStorage_PropNameCompare, PropertyStorage_PropNameDestroy,
     This);
    if (!This->name_to_propid)
    {
        hr = STG_E_INSUFFICIENTMEMORY;
        goto end;
    }
    This->propid_to_name = dictionary_create(PropertyStorage_PropCompare,
     NULL, This);
    if (!This->propid_to_name)
    {
        hr = STG_E_INSUFFICIENTMEMORY;
        goto end;
    }
    This->propid_to_prop = dictionary_create(PropertyStorage_PropCompare,
     PropertyStorage_PropertyDestroy, This);
    if (!This->propid_to_prop)
    {
        hr = STG_E_INSUFFICIENTMEMORY;
        goto end;
    }
end:
    if (FAILED(hr))
        PropertyStorage_DestroyDictionaries(This);
    return hr;
}

static HRESULT PropertyStorage_BaseConstruct(IStream *stm,
 REFFMTID rfmtid, DWORD grfMode, PropertyStorage_impl **pps)
{
    HRESULT hr = S_OK;

    assert(pps);
    assert(rfmtid);
    *pps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof **pps);
2052
    if (!*pps)
2053 2054
        return E_OUTOFMEMORY;

2055
    (*pps)->IPropertyStorage_iface.lpVtbl = &IPropertyStorage_Vtbl;
2056 2057
    (*pps)->ref = 1;
    InitializeCriticalSection(&(*pps)->cs);
2058
    (*pps)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PropertyStorage_impl.cs");
2059
    (*pps)->stm = stm;
2060
    (*pps)->fmtid = *rfmtid;
2061 2062 2063
    (*pps)->grfMode = grfMode;

    hr = PropertyStorage_CreateDictionaries(*pps);
2064 2065
    if (FAILED(hr))
    {
2066
        (*pps)->cs.DebugInfo->Spare[0] = 0;
2067 2068 2069 2070
        DeleteCriticalSection(&(*pps)->cs);
        HeapFree(GetProcessHeap(), 0, *pps);
        *pps = NULL;
    }
2071
    else IStream_AddRef( stm );
2072 2073 2074 2075 2076 2077

    return hr;
}

static HRESULT PropertyStorage_ConstructFromStream(IStream *stm,
 REFFMTID rfmtid, DWORD grfMode, IPropertyStorage** pps)
2078 2079
{
    PropertyStorage_impl *ps;
2080
    HRESULT hr;
2081

2082 2083 2084 2085 2086 2087 2088
    assert(pps);
    hr = PropertyStorage_BaseConstruct(stm, rfmtid, grfMode, &ps);
    if (SUCCEEDED(hr))
    {
        hr = PropertyStorage_ReadFromStream(ps);
        if (SUCCEEDED(hr))
        {
2089
            *pps = &ps->IPropertyStorage_iface;
2090 2091 2092
            TRACE("PropertyStorage %p constructed\n", ps);
            hr = S_OK;
        }
2093
        else IPropertyStorage_Release( &ps->IPropertyStorage_iface );
2094 2095 2096
    }
    return hr;
}
2097

2098 2099 2100 2101 2102
static HRESULT PropertyStorage_ConstructEmpty(IStream *stm,
 REFFMTID rfmtid, DWORD grfFlags, DWORD grfMode, IPropertyStorage** pps)
{
    PropertyStorage_impl *ps;
    HRESULT hr;
2103

2104 2105
    assert(pps);
    hr = PropertyStorage_BaseConstruct(stm, rfmtid, grfMode, &ps);
2106 2107
    if (SUCCEEDED(hr))
    {
2108
        ps->format = 0;
2109
        ps->grfFlags = grfFlags;
2110 2111
        if (ps->grfFlags & PROPSETFLAG_CASE_SENSITIVE)
            ps->format = 1;
Austin English's avatar
Austin English committed
2112
        /* default to Unicode unless told not to, as specified on msdn */
2113 2114 2115 2116 2117
        if (ps->grfFlags & PROPSETFLAG_ANSI)
            ps->codePage = GetACP();
        else
            ps->codePage = CP_UNICODE;
        ps->locale = LOCALE_SYSTEM_DEFAULT;
2118
        TRACE("Code page is %d, locale is %d\n", ps->codePage, ps->locale);
2119
        *pps = &ps->IPropertyStorage_iface;
2120 2121 2122 2123
        TRACE("PropertyStorage %p constructed\n", ps);
        hr = S_OK;
    }
    return hr;
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
}


/***********************************************************************
 * Implementation of IPropertySetStorage
 */

/************************************************************************
 * IPropertySetStorage_fnQueryInterface (IUnknown)
 *
 *  This method forwards to the common QueryInterface implementation
 */
static HRESULT WINAPI IPropertySetStorage_fnQueryInterface(
    IPropertySetStorage *ppstg,
    REFIID riid,
    void** ppvObject)
{
2141
    StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2142
    return IStorage_QueryInterface( &This->base.IStorage_iface, riid, ppvObject );
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
}

/************************************************************************
 * IPropertySetStorage_fnAddRef (IUnknown)
 *
 *  This method forwards to the common AddRef implementation
 */
static ULONG WINAPI IPropertySetStorage_fnAddRef(
    IPropertySetStorage *ppstg)
{
2153
    StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2154
    return IStorage_AddRef( &This->base.IStorage_iface );
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
}

/************************************************************************
 * IPropertySetStorage_fnRelease (IUnknown)
 *
 *  This method forwards to the common Release implementation
 */
static ULONG WINAPI IPropertySetStorage_fnRelease(
    IPropertySetStorage *ppstg)
{
2165
    StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2166
    return IStorage_Release( &This->base.IStorage_iface );
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
}

/************************************************************************
 * IPropertySetStorage_fnCreate (IPropertySetStorage)
 */
static HRESULT WINAPI IPropertySetStorage_fnCreate(
    IPropertySetStorage *ppstg,
    REFFMTID rfmtid,
    const CLSID* pclsid,
    DWORD grfFlags,
    DWORD grfMode,
    IPropertyStorage** ppprstg)
{
2180
    StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2181
    WCHAR name[CCH_MAX_PROPSTG_NAME + 1];
2182 2183 2184
    IStream *stm = NULL;
    HRESULT r;

2185
    TRACE("%p %s %08x %08x %p\n", This, debugstr_guid(rfmtid), grfFlags,
2186
     grfMode, ppprstg);
2187 2188 2189

    /* be picky */
    if (grfMode != (STGM_CREATE|STGM_READWRITE|STGM_SHARE_EXCLUSIVE))
2190 2191 2192 2193
    {
        r = STG_E_INVALIDFLAG;
        goto end;
    }
2194 2195

    if (!rfmtid)
2196 2197 2198 2199
    {
        r = E_INVALIDARG;
        goto end;
    }
2200

2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
    /* FIXME: if (grfFlags & PROPSETFLAG_NONSIMPLE), we need to create a
     * storage, not a stream.  For now, disallow it.
     */
    if (grfFlags & PROPSETFLAG_NONSIMPLE)
    {
        FIXME("PROPSETFLAG_NONSIMPLE not supported\n");
        r = STG_E_INVALIDFLAG;
        goto end;
    }

2211 2212 2213
    r = FmtIdToPropStgName(rfmtid, name);
    if (FAILED(r))
        goto end;
2214

2215
    r = IStorage_CreateStream( &This->base.IStorage_iface, name, grfMode, 0, 0, &stm );
2216
    if (FAILED(r))
2217 2218
        goto end;

2219
    r = PropertyStorage_ConstructEmpty(stm, rfmtid, grfFlags, grfMode, ppprstg);
2220

2221 2222
    IStream_Release( stm );

2223
end:
2224
    TRACE("returning 0x%08x\n", r);
2225
    return r;
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
}

/************************************************************************
 * IPropertySetStorage_fnOpen (IPropertySetStorage)
 */
static HRESULT WINAPI IPropertySetStorage_fnOpen(
    IPropertySetStorage *ppstg,
    REFFMTID rfmtid,
    DWORD grfMode,
    IPropertyStorage** ppprstg)
{
2237
    StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2238
    IStream *stm = NULL;
2239
    WCHAR name[CCH_MAX_PROPSTG_NAME + 1];
2240 2241
    HRESULT r;

2242
    TRACE("%p %s %08x %p\n", This, debugstr_guid(rfmtid), grfMode, ppprstg);
2243 2244 2245 2246

    /* be picky */
    if (grfMode != (STGM_READWRITE|STGM_SHARE_EXCLUSIVE) &&
        grfMode != (STGM_READ|STGM_SHARE_EXCLUSIVE))
2247 2248 2249 2250
    {
        r = STG_E_INVALIDFLAG;
        goto end;
    }
2251 2252

    if (!rfmtid)
2253 2254 2255 2256
    {
        r = E_INVALIDARG;
        goto end;
    }
2257

2258 2259 2260
    r = FmtIdToPropStgName(rfmtid, name);
    if (FAILED(r))
        goto end;
2261

2262
    r = IStorage_OpenStream( &This->base.IStorage_iface, name, 0, grfMode, 0, &stm );
2263
    if (FAILED(r))
2264 2265
        goto end;

2266
    r = PropertyStorage_ConstructFromStream(stm, rfmtid, grfMode, ppprstg);
2267

2268 2269
    IStream_Release( stm );

2270
end:
2271
    TRACE("returning 0x%08x\n", r);
2272
    return r;
2273 2274 2275 2276 2277 2278 2279 2280 2281
}

/************************************************************************
 * IPropertySetStorage_fnDelete (IPropertySetStorage)
 */
static HRESULT WINAPI IPropertySetStorage_fnDelete(
    IPropertySetStorage *ppstg,
    REFFMTID rfmtid)
{
2282
    StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2283
    WCHAR name[CCH_MAX_PROPSTG_NAME + 1];
2284
    HRESULT r;
2285 2286 2287 2288 2289 2290

    TRACE("%p %s\n", This, debugstr_guid(rfmtid));

    if (!rfmtid)
        return E_INVALIDARG;

2291 2292 2293
    r = FmtIdToPropStgName(rfmtid, name);
    if (FAILED(r))
        return r;
2294

2295
    return IStorage_DestroyElement(&This->base.IStorage_iface, name);
2296 2297 2298 2299 2300 2301 2302 2303 2304
}

/************************************************************************
 * IPropertySetStorage_fnEnum (IPropertySetStorage)
 */
static HRESULT WINAPI IPropertySetStorage_fnEnum(
    IPropertySetStorage *ppstg,
    IEnumSTATPROPSETSTG** ppenum)
{
2305
    StorageImpl *This = impl_from_IPropertySetStorage(ppstg);
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    return create_EnumSTATPROPSETSTG(This, ppenum);
}

/************************************************************************
 * Implement IEnumSTATPROPSETSTG using enumx
 */
static HRESULT WINAPI IEnumSTATPROPSETSTG_fnQueryInterface(
    IEnumSTATPROPSETSTG *iface,
    REFIID riid,
    void** ppvObject)
{
    return enumx_QueryInterface((enumx_impl*)iface, riid, ppvObject);
}

static ULONG WINAPI IEnumSTATPROPSETSTG_fnAddRef(
    IEnumSTATPROPSETSTG *iface)
{
    return enumx_AddRef((enumx_impl*)iface);
}

static ULONG WINAPI IEnumSTATPROPSETSTG_fnRelease(
    IEnumSTATPROPSETSTG *iface)
{
    return enumx_Release((enumx_impl*)iface);
}

static HRESULT WINAPI IEnumSTATPROPSETSTG_fnNext(
    IEnumSTATPROPSETSTG *iface,
    ULONG celt,
    STATPROPSETSTG *rgelt,
    ULONG *pceltFetched)
{
    return enumx_Next((enumx_impl*)iface, celt, rgelt, pceltFetched);
}

static HRESULT WINAPI IEnumSTATPROPSETSTG_fnSkip(
    IEnumSTATPROPSETSTG *iface,
    ULONG celt)
{
    return enumx_Skip((enumx_impl*)iface, celt);
2346
}
2347

2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
static HRESULT WINAPI IEnumSTATPROPSETSTG_fnReset(
    IEnumSTATPROPSETSTG *iface)
{
    return enumx_Reset((enumx_impl*)iface);
}

static HRESULT WINAPI IEnumSTATPROPSETSTG_fnClone(
    IEnumSTATPROPSETSTG *iface,
    IEnumSTATPROPSETSTG **ppenum)
{
    return enumx_Clone((enumx_impl*)iface, (enumx_impl**)ppenum);
}

static HRESULT create_EnumSTATPROPSETSTG(
    StorageImpl *This,
    IEnumSTATPROPSETSTG** ppenum)
{
2365
    IStorage *stg = &This->base.IStorage_iface;
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
    IEnumSTATSTG *penum = NULL;
    STATSTG stat;
    ULONG count;
    HRESULT r;
    STATPROPSETSTG statpss;
    enumx_impl *enumx;

    TRACE("%p %p\n", This, ppenum);

    enumx = enumx_allocate(&IID_IEnumSTATPROPSETSTG,
                           &IEnumSTATPROPSETSTG_Vtbl,
                           sizeof (STATPROPSETSTG));

    /* add all the property set elements into a list */
    r = IStorage_EnumElements(stg, 0, NULL, 0, &penum);
    if (FAILED(r))
2382 2383
    {
        enumx_Release(enumx);
2384
        return E_OUTOFMEMORY;
2385
    }
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405

    while (1)
    {
        count = 0;
        r = IEnumSTATSTG_Next(penum, 1, &stat, &count);
        if (FAILED(r))
            break;
        if (!count)
            break;
        if (!stat.pwcsName)
            continue;
        if (stat.pwcsName[0] == 5 && stat.type == STGTY_STREAM)
        {
            PropStgNameToFmtId(stat.pwcsName, &statpss.fmtid);
            TRACE("adding %s (%s)\n", debugstr_w(stat.pwcsName),
                  debugstr_guid(&statpss.fmtid));
            statpss.mtime = stat.mtime;
            statpss.atime = stat.atime;
            statpss.ctime = stat.ctime;
            statpss.grfFlags = stat.grfMode;
2406
            statpss.clsid = stat.clsid;
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
            enumx_add_element(enumx, &statpss);
        }
        CoTaskMemFree(stat.pwcsName);
    }
    IEnumSTATSTG_Release(penum);

    *ppenum = (IEnumSTATPROPSETSTG*) enumx;

    return S_OK;
}
2417

2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
/************************************************************************
 * Implement IEnumSTATPROPSTG using enumx
 */
static HRESULT WINAPI IEnumSTATPROPSTG_fnQueryInterface(
    IEnumSTATPROPSTG *iface,
    REFIID riid,
    void** ppvObject)
{
    return enumx_QueryInterface((enumx_impl*)iface, riid, ppvObject);
}

static ULONG WINAPI IEnumSTATPROPSTG_fnAddRef(
    IEnumSTATPROPSTG *iface)
{
    return enumx_AddRef((enumx_impl*)iface);
}

static ULONG WINAPI IEnumSTATPROPSTG_fnRelease(
    IEnumSTATPROPSTG *iface)
{
    return enumx_Release((enumx_impl*)iface);
}

static HRESULT WINAPI IEnumSTATPROPSTG_fnNext(
    IEnumSTATPROPSTG *iface,
    ULONG celt,
    STATPROPSTG *rgelt,
    ULONG *pceltFetched)
{
    return enumx_Next((enumx_impl*)iface, celt, rgelt, pceltFetched);
}

static HRESULT WINAPI IEnumSTATPROPSTG_fnSkip(
    IEnumSTATPROPSTG *iface,
    ULONG celt)
{
    return enumx_Skip((enumx_impl*)iface, celt);
}

static HRESULT WINAPI IEnumSTATPROPSTG_fnReset(
    IEnumSTATPROPSTG *iface)
{
    return enumx_Reset((enumx_impl*)iface);
}

static HRESULT WINAPI IEnumSTATPROPSTG_fnClone(
    IEnumSTATPROPSTG *iface,
    IEnumSTATPROPSTG **ppenum)
{
    return enumx_Clone((enumx_impl*)iface, (enumx_impl**)ppenum);
}

static BOOL prop_enum_stat(const void *k, const void *v, void *extra, void *arg)
{
    enumx_impl *enumx = arg;
2473
    PROPID propid = PtrToUlong(k);
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
    const PROPVARIANT *prop = v;
    STATPROPSTG stat;

    stat.lpwstrName = NULL;
    stat.propid = propid;
    stat.vt = prop->vt;

    enumx_add_element(enumx, &stat);

    return TRUE;
}

static HRESULT create_EnumSTATPROPSTG(
    PropertyStorage_impl *This,
    IEnumSTATPROPSTG** ppenum)
{
    enumx_impl *enumx;

    TRACE("%p %p\n", This, ppenum);

    enumx = enumx_allocate(&IID_IEnumSTATPROPSTG,
                           &IEnumSTATPROPSTG_Vtbl,
                           sizeof (STATPROPSTG));

    dictionary_enumerate(This->propid_to_prop, prop_enum_stat, enumx);

    *ppenum = (IEnumSTATPROPSTG*) enumx;

    return S_OK;
}

2505 2506 2507
/***********************************************************************
 * vtables
 */
2508
const IPropertySetStorageVtbl IPropertySetStorage_Vtbl =
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
{
    IPropertySetStorage_fnQueryInterface,
    IPropertySetStorage_fnAddRef,
    IPropertySetStorage_fnRelease,
    IPropertySetStorage_fnCreate,
    IPropertySetStorage_fnOpen,
    IPropertySetStorage_fnDelete,
    IPropertySetStorage_fnEnum
};

2519
static const IPropertyStorageVtbl IPropertyStorage_Vtbl =
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
{
    IPropertyStorage_fnQueryInterface,
    IPropertyStorage_fnAddRef,
    IPropertyStorage_fnRelease,
    IPropertyStorage_fnReadMultiple,
    IPropertyStorage_fnWriteMultiple,
    IPropertyStorage_fnDeleteMultiple,
    IPropertyStorage_fnReadPropertyNames,
    IPropertyStorage_fnWritePropertyNames,
    IPropertyStorage_fnDeletePropertyNames,
    IPropertyStorage_fnCommit,
    IPropertyStorage_fnRevert,
    IPropertyStorage_fnEnum,
    IPropertyStorage_fnSetTimes,
    IPropertyStorage_fnSetClass,
    IPropertyStorage_fnStat,
};
2537

2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
static const IEnumSTATPROPSETSTGVtbl IEnumSTATPROPSETSTG_Vtbl =
{
    IEnumSTATPROPSETSTG_fnQueryInterface,
    IEnumSTATPROPSETSTG_fnAddRef,
    IEnumSTATPROPSETSTG_fnRelease,
    IEnumSTATPROPSETSTG_fnNext,
    IEnumSTATPROPSETSTG_fnSkip,
    IEnumSTATPROPSETSTG_fnReset,
    IEnumSTATPROPSETSTG_fnClone,
};

2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
static const IEnumSTATPROPSTGVtbl IEnumSTATPROPSTG_Vtbl =
{
    IEnumSTATPROPSTG_fnQueryInterface,
    IEnumSTATPROPSTG_fnAddRef,
    IEnumSTATPROPSTG_fnRelease,
    IEnumSTATPROPSTG_fnNext,
    IEnumSTATPROPSTG_fnSkip,
    IEnumSTATPROPSTG_fnReset,
    IEnumSTATPROPSTG_fnClone,
};

2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
/***********************************************************************
 * Format ID <-> name conversion
 */
static const WCHAR szSummaryInfo[] = { 5,'S','u','m','m','a','r','y',
 'I','n','f','o','r','m','a','t','i','o','n',0 };
static const WCHAR szDocSummaryInfo[] = { 5,'D','o','c','u','m','e','n','t',
 'S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0 };

#define BITS_PER_BYTE    8
#define CHARMASK         0x1f
#define BITS_IN_CHARMASK 5
#define NUM_ALPHA_CHARS  26

/***********************************************************************
 * FmtIdToPropStgName					[ole32.@]
 * Returns the storage name of the format ID rfmtid.
 * PARAMS
 *  rfmtid [I] Format ID for which to return a storage name
 *  str    [O] Storage name associated with rfmtid.
 *
 * RETURNS
 *  E_INVALIDARG if rfmtid or str i NULL, S_OK otherwise.
 *
 * NOTES
 * str must be at least CCH_MAX_PROPSTG_NAME characters in length.
 */
HRESULT WINAPI FmtIdToPropStgName(const FMTID *rfmtid, LPOLESTR str)
{
    static const char fmtMap[] = "abcdefghijklmnopqrstuvwxyz012345";

    TRACE("%s, %p\n", debugstr_guid(rfmtid), str);

    if (!rfmtid) return E_INVALIDARG;
    if (!str) return E_INVALIDARG;

    if (IsEqualGUID(&FMTID_SummaryInformation, rfmtid))
        lstrcpyW(str, szSummaryInfo);
    else if (IsEqualGUID(&FMTID_DocSummaryInformation, rfmtid))
        lstrcpyW(str, szDocSummaryInfo);
    else if (IsEqualGUID(&FMTID_UserDefinedProperties, rfmtid))
        lstrcpyW(str, szDocSummaryInfo);
    else
    {
2603
        const BYTE *fmtptr;
2604 2605 2606 2607
        WCHAR *pstr = str;
        ULONG bitsRemaining = BITS_PER_BYTE;

        *pstr++ = 5;
2608
        for (fmtptr = (const BYTE *)rfmtid; fmtptr < (const BYTE *)rfmtid + sizeof(FMTID); )
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
        {
            ULONG i = *fmtptr >> (BITS_PER_BYTE - bitsRemaining);

            if (bitsRemaining >= BITS_IN_CHARMASK)
            {
                *pstr = (WCHAR)(fmtMap[i & CHARMASK]);
                if (bitsRemaining == BITS_PER_BYTE && *pstr >= 'a' &&
                 *pstr <= 'z')
                    *pstr += 'A' - 'a';
                pstr++;
                bitsRemaining -= BITS_IN_CHARMASK;
                if (bitsRemaining == 0)
                {
                    fmtptr++;
                    bitsRemaining = BITS_PER_BYTE;
                }
            }
            else
            {
Eric Pouech's avatar
Eric Pouech committed
2628
                if (++fmtptr < (const BYTE *)rfmtid + sizeof(FMTID))
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
                    i |= *fmtptr << bitsRemaining;
                *pstr++ = (WCHAR)(fmtMap[i & CHARMASK]);
                bitsRemaining += BITS_PER_BYTE - BITS_IN_CHARMASK;
            }
        }
        *pstr = 0;
    }
    TRACE("returning %s\n", debugstr_w(str));
    return S_OK;
}

/***********************************************************************
 * PropStgNameToFmtId					[ole32.@]
 * Returns the format ID corresponding to the given name.
 * PARAMS
 *  str    [I] Storage name to convert to a format ID.
 *  rfmtid [O] Format ID corresponding to str.
 *
 * RETURNS
 *  E_INVALIDARG if rfmtid or str is NULL or if str can't be converted to
 *  a format ID, S_OK otherwise.
 */
HRESULT WINAPI PropStgNameToFmtId(const LPOLESTR str, FMTID *rfmtid)
{
2653
    HRESULT hr = STG_E_INVALIDNAME;
2654 2655 2656 2657

    TRACE("%s, %p\n", debugstr_w(str), rfmtid);

    if (!rfmtid) return E_INVALIDARG;
2658
    if (!str) return STG_E_INVALIDNAME;
2659 2660 2661

    if (!lstrcmpiW(str, szDocSummaryInfo))
    {
2662
        *rfmtid = FMTID_DocSummaryInformation;
2663 2664 2665 2666
        hr = S_OK;
    }
    else if (!lstrcmpiW(str, szSummaryInfo))
    {
2667
        *rfmtid = FMTID_SummaryInformation;
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
        hr = S_OK;
    }
    else
    {
        ULONG bits;
        BYTE *fmtptr = (BYTE *)rfmtid - 1;
        const WCHAR *pstr = str;

        memset(rfmtid, 0, sizeof(*rfmtid));
        for (bits = 0; bits < sizeof(FMTID) * BITS_PER_BYTE;
         bits += BITS_IN_CHARMASK)
        {
            ULONG bitsUsed = bits % BITS_PER_BYTE, bitsStored;
            WCHAR wc;

            if (bitsUsed == 0)
                fmtptr++;
            wc = *++pstr - 'A';
            if (wc > NUM_ALPHA_CHARS)
            {
                wc += 'A' - 'a';
                if (wc > NUM_ALPHA_CHARS)
                {
                    wc += 'a' - '0' + NUM_ALPHA_CHARS;
                    if (wc > CHARMASK)
                    {
                        WARN("invalid character (%d)\n", *pstr);
                        goto end;
                    }
                }
            }
            *fmtptr |= wc << bitsUsed;
            bitsStored = min(BITS_PER_BYTE - bitsUsed, BITS_IN_CHARMASK);
            if (bitsStored < BITS_IN_CHARMASK)
            {
                wc >>= BITS_PER_BYTE - bitsUsed;
                if (bits + bitsStored == sizeof(FMTID) * BITS_PER_BYTE)
                {
                    if (wc != 0)
                    {
                        WARN("extra bits\n");
                        goto end;
                    }
                    break;
                }
                fmtptr++;
                *fmtptr |= (BYTE)wc;
            }
        }
        hr = S_OK;
    }
end:
    return hr;
}
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733

#ifdef __i386__  /* thiscall functions are i386-specific */

#define DEFINE_STDCALL_WRAPPER(num,func,args) \
   __ASM_STDCALL_FUNC(func, args, \
                   "popl %eax\n\t" \
                   "popl %ecx\n\t" \
                   "pushl %eax\n\t" \
                   "movl (%ecx), %eax\n\t" \
                   "jmp *(4*(" #num "))(%eax)" )

DEFINE_STDCALL_WRAPPER(0,Allocate_PMemoryAllocator,8)
2734
extern void* WINAPI Allocate_PMemoryAllocator(void *this, ULONG cbSize);
2735 2736 2737

#else

2738
static void* WINAPI Allocate_PMemoryAllocator(void *this, ULONG cbSize)
2739
{
2740
    void* (WINAPI *fn)(void*,ULONG) = **(void***)this;
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
    return fn(this, cbSize);
}

#endif

BOOLEAN WINAPI StgConvertPropertyToVariant(const SERIALIZEDPROPERTYVALUE* prop,
    USHORT CodePage, PROPVARIANT* pvar, void* pma)
{
    HRESULT hr;

    hr = PropertyStorage_ReadProperty(pvar, (const BYTE*)prop, CodePage, Allocate_PMemoryAllocator, pma);

    if (FAILED(hr))
    {
        FIXME("should raise C++ exception on failure\n");
        PropVariantInit(pvar);
    }

2759
    return FALSE;
2760
}
2761 2762 2763 2764 2765 2766 2767 2768 2769

SERIALIZEDPROPERTYVALUE* WINAPI StgConvertVariantToProperty(const PROPVARIANT *pvar,
    USHORT CodePage, SERIALIZEDPROPERTYVALUE *pprop, ULONG *pcb, PROPID pid,
    BOOLEAN fReserved, ULONG *pcIndirect)
{
    FIXME("%p,%d,%p,%p,%d,%d,%p\n", pvar, CodePage, pprop, pcb, pid, fReserved, pcIndirect);

    return NULL;
}
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806

HRESULT WINAPI StgCreatePropStg(IUnknown *unk, REFFMTID fmt, const CLSID *clsid,
                                DWORD flags, DWORD reserved, IPropertyStorage **prop_stg)
{
    IStorage *stg;
    IStream *stm;
    HRESULT r;

    TRACE("%p %s %s %08x %d %p\n", unk, debugstr_guid(fmt), debugstr_guid(clsid), flags, reserved, prop_stg);

    if (!fmt || reserved)
    {
        r = E_INVALIDARG;
        goto end;
    }

    if (flags & PROPSETFLAG_NONSIMPLE)
    {
        r = IUnknown_QueryInterface(unk, &IID_IStorage, (void **)&stg);
        if (FAILED(r))
            goto end;

        /* FIXME: if (flags & PROPSETFLAG_NONSIMPLE), we need to create a
         * storage, not a stream.  For now, disallow it.
         */
        FIXME("PROPSETFLAG_NONSIMPLE not supported\n");
        IStorage_Release(stg);
        r = STG_E_INVALIDFLAG;
    }
    else
    {
        r = IUnknown_QueryInterface(unk, &IID_IStream, (void **)&stm);
        if (FAILED(r))
            goto end;

        r = PropertyStorage_ConstructEmpty(stm, fmt, flags,
                STGM_CREATE|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, prop_stg);
2807 2808

        IStream_Release( stm );
2809 2810 2811 2812 2813 2814
    }

end:
    TRACE("returning 0x%08x\n", r);
    return r;
}
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851

HRESULT WINAPI StgOpenPropStg(IUnknown *unk, REFFMTID fmt, DWORD flags,
                              DWORD reserved, IPropertyStorage **prop_stg)
{
    IStorage *stg;
    IStream *stm;
    HRESULT r;

    TRACE("%p %s %08x %d %p\n", unk, debugstr_guid(fmt), flags, reserved, prop_stg);

    if (!fmt || reserved)
    {
        r = E_INVALIDARG;
        goto end;
    }

    if (flags & PROPSETFLAG_NONSIMPLE)
    {
        r = IUnknown_QueryInterface(unk, &IID_IStorage, (void **)&stg);
        if (FAILED(r))
            goto end;

        /* FIXME: if (flags & PROPSETFLAG_NONSIMPLE), we need to open a
         * storage, not a stream.  For now, disallow it.
         */
        FIXME("PROPSETFLAG_NONSIMPLE not supported\n");
        IStorage_Release(stg);
        r = STG_E_INVALIDFLAG;
    }
    else
    {
        r = IUnknown_QueryInterface(unk, &IID_IStream, (void **)&stm);
        if (FAILED(r))
            goto end;

        r = PropertyStorage_ConstructFromStream(stm, fmt,
                STGM_READWRITE|STGM_SHARE_EXCLUSIVE, prop_stg);
2852 2853

        IStream_Release( stm );
2854 2855 2856 2857 2858 2859
    }

end:
    TRACE("returning 0x%08x\n", r);
    return r;
}