compobj.c 25.3 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3 4
/*
 *	COMPOBJ library
 *
 *	Copyright 1995	Martin von Loewis
5
 *	Copyright 1998	Justin Bradford
6
 *      Copyright 1999  Francis Beaudet
7 8 9
 *      Copyright 1999  Sylvain St-Germain
 *      Copyright 2002  Marcus Meissner
 *      Copyright 2004  Mike Hearn
10
 *      Copyright 2005-2006 Robert Shearman (for CodeWeavers)
11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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
24
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Mike Hearn's avatar
Mike Hearn committed
25
 *
26 27 28 29
 * Note
 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
 *    Therefore do not test against COINIT_MULTITHREADED
 *
Mike Hearn's avatar
Mike Hearn committed
30 31
 * TODO list:           (items bunched together depend on each other)
 *
32
 *   - Implement the OXID resolver so we don't need magic endpoint names for
Mike Hearn's avatar
Mike Hearn committed
33 34
 *     clients and servers to meet up
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
35 36
 */

37
#include <stdarg.h>
38
#include <stdio.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
39
#include <string.h>
40
#include <assert.h>
41

42
#define COBJMACROS
43 44
#include "ntstatus.h"
#define WIN32_NO_STATUS
45
#include "windef.h"
46
#include "winbase.h"
47 48
#include "winerror.h"
#include "winreg.h"
49
#include "winuser.h"
50
#define USE_COM_CONTEXT_DEF
51 52 53
#include "objbase.h"
#include "ole2.h"
#include "ole2ver.h"
54
#include "ctxtcall.h"
55
#include "dde.h"
56
#include "servprov.h"
57

58
#include "initguid.h"
59
#include "compobj_private.h"
60
#include "moniker.h"
61

62
#include "wine/debug.h"
63

64
WINE_DEFAULT_DEBUG_CHANNEL(ole);
65

66
/****************************************************************************
67
 * This section defines variables internal to the COM module.
68 69
 */

70 71 72 73 74 75 76 77 78
enum comclass_miscfields
{
    MiscStatus          = 1,
    MiscStatusIcon      = 2,
    MiscStatusContent   = 4,
    MiscStatusThumbnail = 8,
    MiscStatusDocPrint  = 16
};

79 80 81
struct comclassredirect_data
{
    ULONG size;
82
    ULONG flags;
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    DWORD model;
    GUID  clsid;
    GUID  alias;
    GUID  clsid2;
    GUID  tlbid;
    ULONG name_len;
    ULONG name_offset;
    ULONG progid_len;
    ULONG progid_offset;
    ULONG clrdata_len;
    ULONG clrdata_offset;
    DWORD miscstatus;
    DWORD miscstatuscontent;
    DWORD miscstatusthumbnail;
    DWORD miscstatusicon;
    DWORD miscstatusdocprint;
};

101 102 103 104 105 106 107 108 109 110 111 112
struct ifacepsredirect_data
{
    ULONG size;
    DWORD mask;
    GUID  iid;
    ULONG nummethods;
    GUID  tlbid;
    GUID  base;
    ULONG name_len;
    ULONG name_offset;
};

113 114 115 116 117 118 119
struct progidredirect_data
{
    ULONG size;
    DWORD reserved;
    ULONG clsid_offset;
};

120 121 122 123 124 125
enum class_reg_data_origin
{
    CLASS_REG_ACTCTX,
    CLASS_REG_REGISTRY,
};

126 127
struct class_reg_data
{
128
    enum class_reg_data_origin origin;
129 130 131 132
    union
    {
        struct
        {
133 134
            const WCHAR *module_name;
            DWORD threading_model;
135 136 137 138 139 140
            HANDLE hactctx;
        } actctx;
        HKEY hkey;
    } u;
};

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
static inline enum comclass_miscfields dvaspect_to_miscfields(DWORD aspect)
{
    switch (aspect)
    {
    case DVASPECT_CONTENT:
        return MiscStatusContent;
    case DVASPECT_THUMBNAIL:
        return MiscStatusThumbnail;
    case DVASPECT_ICON:
        return MiscStatusIcon;
    case DVASPECT_DOCPRINT:
        return MiscStatusDocPrint;
    default:
        return MiscStatus;
    };
}

BOOL actctx_get_miscstatus(const CLSID *clsid, DWORD aspect, DWORD *status)
{
    ACTCTX_SECTION_KEYED_DATA data;

    data.cbSize = sizeof(data);
    if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION,
                              clsid, &data))
    {
        struct comclassredirect_data *comclass = (struct comclassredirect_data*)data.lpData;
        enum comclass_miscfields misc = dvaspect_to_miscfields(aspect);
168
        ULONG miscmask = (comclass->flags >> 8) & 0xff;
169

170
        if (!(miscmask & misc))
171
        {
172
            if (!(miscmask & MiscStatus))
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
            {
                *status = 0;
                return TRUE;
            }
            misc = MiscStatus;
        }

        switch (misc)
        {
        case MiscStatus:
            *status = comclass->miscstatus;
            break;
        case MiscStatusIcon:
            *status = comclass->miscstatusicon;
            break;
        case MiscStatusContent:
            *status = comclass->miscstatuscontent;
            break;
        case MiscStatusThumbnail:
            *status = comclass->miscstatusthumbnail;
            break;
        case MiscStatusDocPrint:
            *status = comclass->miscstatusdocprint;
            break;
        default:
           ;
        };

        return TRUE;
    }
    else
        return FALSE;
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
/* wrapper for NtCreateKey that creates the key recursively if necessary */
static NTSTATUS create_key( HKEY *retkey, ACCESS_MASK access, OBJECT_ATTRIBUTES *attr )
{
    NTSTATUS status = NtCreateKey( (HANDLE *)retkey, access, attr, 0, NULL, 0, NULL );

    if (status == STATUS_OBJECT_NAME_NOT_FOUND)
    {
        HANDLE subkey, root = attr->RootDirectory;
        WCHAR *buffer = attr->ObjectName->Buffer;
        DWORD attrs, pos = 0, i = 0, len = attr->ObjectName->Length / sizeof(WCHAR);
        UNICODE_STRING str;

        while (i < len && buffer[i] != '\\') i++;
        if (i == len) return status;

        attrs = attr->Attributes;
        attr->ObjectName = &str;

        while (i < len)
        {
            str.Buffer = buffer + pos;
            str.Length = (i - pos) * sizeof(WCHAR);
            status = NtCreateKey( &subkey, access, attr, 0, NULL, 0, NULL );
            if (attr->RootDirectory != root) NtClose( attr->RootDirectory );
            if (status) return status;
            attr->RootDirectory = subkey;
            while (i < len && buffer[i] == '\\') i++;
            pos = i;
            while (i < len && buffer[i] != '\\') i++;
        }
        str.Buffer = buffer + pos;
        str.Length = (i - pos) * sizeof(WCHAR);
        attr->Attributes = attrs;
        status = NtCreateKey( (PHANDLE)retkey, access, attr, 0, NULL, 0, NULL );
        if (attr->RootDirectory != root) NtClose( attr->RootDirectory );
    }
    return status;
}

static HKEY classes_root_hkey;

/* create the special HKEY_CLASSES_ROOT key */
249
static HKEY create_classes_root_hkey(DWORD access)
250 251 252
{
    HKEY hkey, ret = 0;
    OBJECT_ATTRIBUTES attr;
253
    UNICODE_STRING name = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\Software\\Classes");
254 255 256 257 258 259 260

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &name;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
261
    if (create_key( &hkey, access, &attr )) return 0;
262 263
    TRACE( "%s -> %p\n", debugstr_w(attr.ObjectName->Buffer), hkey );

264 265 266 267 268 269 270
    if (!(access & KEY_WOW64_64KEY))
    {
        if (!(ret = InterlockedCompareExchangePointer( (void **)&classes_root_hkey, hkey, 0 )))
            ret = hkey;
        else
            NtClose( hkey );  /* somebody beat us to it */
    }
271
    else
272
        ret = hkey;
273 274 275 276
    return ret;
}

/* map the hkey from special root to normal key if necessary */
277
static inline HKEY get_classes_root_hkey( HKEY hkey, REGSAM access )
278 279
{
    HKEY ret = hkey;
280 281
    const BOOL is_win64 = sizeof(void*) > sizeof(int);
    const BOOL force_wow32 = is_win64 && (access & KEY_WOW64_32KEY);
282

283 284 285 286 287 288
    if (hkey == HKEY_CLASSES_ROOT &&
        ((access & KEY_WOW64_64KEY) || !(ret = classes_root_hkey)))
        ret = create_classes_root_hkey(MAXIMUM_ALLOWED | (access & KEY_WOW64_64KEY));
    if (force_wow32 && ret && ret == classes_root_hkey)
    {
        access &= ~KEY_WOW64_32KEY;
289
        if (create_classes_key(classes_root_hkey, L"Wow6432Node", access, &hkey))
290 291 292
            return 0;
        ret = hkey;
    }
293 294 295 296 297 298 299 300 301

    return ret;
}

LSTATUS create_classes_key( HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey )
{
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;

302
    if (!(hkey = get_classes_root_hkey( hkey, access ))) return ERROR_INVALID_HANDLE;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319

    attr.Length = sizeof(attr);
    attr.RootDirectory = hkey;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, name );

    return RtlNtStatusToDosError( create_key( retkey, access, &attr ) );
}

LSTATUS open_classes_key( HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey )
{
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;

320
    if (!(hkey = get_classes_root_hkey( hkey, access ))) return ERROR_INVALID_HANDLE;
321 322 323 324 325 326 327 328 329 330 331 332

    attr.Length = sizeof(attr);
    attr.RootDirectory = hkey;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, name );

    return RtlNtStatusToDosError( NtOpenKey( (HANDLE *)retkey, access, &attr ) );
}

333 334 335 336 337
/******************************************************************************
 * Implementation of the manual reset event object. (CLSID_ManualResetEvent)
 */

typedef struct ManualResetEvent {
338 339
    ISynchronize        ISynchronize_iface;
    ISynchronizeHandle  ISynchronizeHandle_iface;
340 341 342 343 344 345 346 347 348 349 350 351
    LONG ref;
    HANDLE event;
} MREImpl;

static inline MREImpl *impl_from_ISynchronize(ISynchronize *iface)
{
    return CONTAINING_RECORD(iface, MREImpl, ISynchronize_iface);
}

static HRESULT WINAPI ISynchronize_fnQueryInterface(ISynchronize *iface, REFIID riid, void **ppv)
{
    MREImpl *This = impl_from_ISynchronize(iface);
352

353 354
    TRACE("%p (%s, %p)\n", This, debugstr_guid(riid), ppv);

355 356 357 358 359
    if(IsEqualGUID(riid, &IID_IUnknown) || IsEqualGUID(riid, &IID_ISynchronize)) {
        *ppv = &This->ISynchronize_iface;
    }else if(IsEqualGUID(riid, &IID_ISynchronizeHandle)) {
        *ppv = &This->ISynchronizeHandle_iface;
    }else {
360
        ERR("Unknown interface %s requested.\n", debugstr_guid(riid));
361 362
        *ppv = NULL;
        return E_NOINTERFACE;
363 364
    }

365 366
    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
367 368 369 370 371 372
}

static ULONG WINAPI ISynchronize_fnAddRef(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    LONG ref = InterlockedIncrement(&This->ref);
373
    TRACE("%p, refcount %ld.\n", iface, ref);
374 375 376 377 378 379 380 381

    return ref;
}

static ULONG WINAPI ISynchronize_fnRelease(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    LONG ref = InterlockedDecrement(&This->ref);
382
    TRACE("%p, refcount %ld.\n", iface, ref);
383 384 385 386 387 388 389 390 391 392 393 394 395

    if(!ref)
    {
        CloseHandle(This->event);
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

static HRESULT WINAPI ISynchronize_fnWait(ISynchronize *iface, DWORD dwFlags, DWORD dwMilliseconds)
{
    MREImpl *This = impl_from_ISynchronize(iface);
396
    DWORD index;
397
    TRACE("%p, %#lx, %#lx.\n", iface, dwFlags, dwMilliseconds);
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    return CoWaitForMultipleHandles(dwFlags, dwMilliseconds, 1, &This->event, &index);
}

static HRESULT WINAPI ISynchronize_fnSignal(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    TRACE("%p\n", This);
    SetEvent(This->event);
    return S_OK;
}

static HRESULT WINAPI ISynchronize_fnReset(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    TRACE("%p\n", This);
    ResetEvent(This->event);
    return S_OK;
}

static ISynchronizeVtbl vt_ISynchronize = {
    ISynchronize_fnQueryInterface,
    ISynchronize_fnAddRef,
    ISynchronize_fnRelease,
    ISynchronize_fnWait,
    ISynchronize_fnSignal,
    ISynchronize_fnReset
424
};
425

426 427 428 429
static inline MREImpl *impl_from_ISynchronizeHandle(ISynchronizeHandle *iface)
{
    return CONTAINING_RECORD(iface, MREImpl, ISynchronizeHandle_iface);
}
430

431 432 433 434 435
static HRESULT WINAPI SynchronizeHandle_QueryInterface(ISynchronizeHandle *iface, REFIID riid, void **ppv)
{
    MREImpl *This = impl_from_ISynchronizeHandle(iface);
    return ISynchronize_QueryInterface(&This->ISynchronize_iface, riid, ppv);
}
436

437 438 439 440
static ULONG WINAPI SynchronizeHandle_AddRef(ISynchronizeHandle *iface)
{
    MREImpl *This = impl_from_ISynchronizeHandle(iface);
    return ISynchronize_AddRef(&This->ISynchronize_iface);
441 442
}

443
static ULONG WINAPI SynchronizeHandle_Release(ISynchronizeHandle *iface)
444
{
445 446 447
    MREImpl *This = impl_from_ISynchronizeHandle(iface);
    return ISynchronize_Release(&This->ISynchronize_iface);
}
448

449 450 451
static HRESULT WINAPI SynchronizeHandle_GetHandle(ISynchronizeHandle *iface, HANDLE *ph)
{
    MREImpl *This = impl_from_ISynchronizeHandle(iface);
452

453 454 455
    *ph = This->event;
    return S_OK;
}
456

457 458 459 460 461 462
static const ISynchronizeHandleVtbl SynchronizeHandleVtbl = {
    SynchronizeHandle_QueryInterface,
    SynchronizeHandle_AddRef,
    SynchronizeHandle_Release,
    SynchronizeHandle_GetHandle
};
463

464 465 466 467
HRESULT WINAPI ManualResetEvent_CreateInstance(IClassFactory *iface, IUnknown *outer, REFIID iid, void **ppv)
{
    MREImpl *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MREImpl));
    HRESULT hr;
468

469 470
    if (outer)
        FIXME("Aggregation not implemented.\n");
471

472 473 474 475
    This->ref = 1;
    This->ISynchronize_iface.lpVtbl = &vt_ISynchronize;
    This->ISynchronizeHandle_iface.lpVtbl = &SynchronizeHandleVtbl;
    This->event = CreateEventW(NULL, TRUE, FALSE, NULL);
476

477 478
    hr = ISynchronize_QueryInterface(&This->ISynchronize_iface, iid, ppv);
    ISynchronize_Release(&This->ISynchronize_iface);
479 480 481
    return hr;
}

482
/******************************************************************************
483
 *           CoBuildVersion [OLE32.@]
484 485 486 487
 *
 * Gets the build version of the DLL.
 *
 * PARAMS
488 489 490
 *
 * RETURNS
 *	Current build version, hiword is majornumber, loword is minornumber
Alexandre Julliard's avatar
Alexandre Julliard committed
491
 */
492 493 494 495
DWORD WINAPI CoBuildVersion(void)
{
    TRACE("Returning version %d, build %d.\n", rmm, rup);
    return (rmm<<16)+rup;
Alexandre Julliard's avatar
Alexandre Julliard committed
496 497
}

498
/******************************************************************************
499
 *		CoInitialize	[OLE32.@]
500
 *
501 502
 * Initializes the COM libraries by calling CoInitializeEx with
 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
503
 *
504 505 506 507 508 509 510
 * PARAMS
 *  lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
 *
 * RETURNS
 *  Success: S_OK if not already initialized, S_FALSE otherwise.
 *  Failure: HRESULT code.
 *
511 512
 * SEE ALSO
 *   CoInitializeEx
Alexandre Julliard's avatar
Alexandre Julliard committed
513
 */
514
HRESULT WINAPI CoInitialize(LPVOID lpReserved)
515 516 517 518
{
  /*
   * Just delegate to the newer method.
   */
519
  return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
Alexandre Julliard's avatar
Alexandre Julliard committed
520 521
}

522 523
/* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
524
{
525
    WCHAR path[CHARS_IN_GUID + ARRAY_SIZE(L"CLSID\\") - 1];
526 527 528
    LONG res;
    HKEY key;

529 530
    lstrcpyW(path, L"CLSID\\");
    StringFromGUID2(clsid, path + lstrlenW(L"CLSID\\"), CHARS_IN_GUID);
531
    res = open_classes_key(HKEY_CLASSES_ROOT, path, keyname ? KEY_READ : access, &key);
532 533 534 535 536 537 538 539 540 541 542
    if (res == ERROR_FILE_NOT_FOUND)
        return REGDB_E_CLASSNOTREG;
    else if (res != ERROR_SUCCESS)
        return REGDB_E_READREGDB;

    if (!keyname)
    {
        *subkey = key;
        return S_OK;
    }

543
    res = open_classes_key(key, keyname, access, subkey);
544
    RegCloseKey(key);
545 546 547 548 549 550 551 552
    if (res == ERROR_FILE_NOT_FOUND)
        return REGDB_E_KEYMISSING;
    else if (res != ERROR_SUCCESS)
        return REGDB_E_READREGDB;

    return S_OK;
}

Ove Kaaven's avatar
Ove Kaaven committed
553
/***********************************************************************
554
 *           CoLoadLibrary (OLE32.@)
555 556 557 558 559 560 561 562 563 564 565 566 567
 *
 * Loads a library.
 *
 * PARAMS
 *  lpszLibName [I] Path to library.
 *  bAutoFree   [I] Whether the library should automatically be freed.
 *
 * RETURNS
 *  Success: Handle to loaded library.
 *  Failure: NULL.
 *
 * SEE ALSO
 *  CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
Ove Kaaven's avatar
Ove Kaaven committed
568
 */
569
HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
Ove Kaaven's avatar
Ove Kaaven committed
570
{
571
    TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
572

573 574
    return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
}
575

576
/***********************************************************************
577
 *           CoFreeLibrary [OLE32.@]
578
 *
579 580 581 582 583 584 585 586 587 588
 * Unloads a library from memory.
 *
 * PARAMS
 *  hLibrary [I] Handle to library to unload.
 *
 * RETURNS
 *  Nothing
 *
 * SEE ALSO
 *  CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
589 590 591
 */
void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
{
592
    FreeLibrary(hLibrary);
593 594 595 596
}


/***********************************************************************
597
 *           CoFreeAllLibraries [OLE32.@]
598
 *
599 600 601 602 603 604 605
 * Function for backwards compatibility only. Does nothing.
 *
 * RETURNS
 *  Nothing.
 *
 * SEE ALSO
 *  CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
606 607 608
 */
void WINAPI CoFreeAllLibraries(void)
{
609
    /* NOP */
Ove Kaaven's avatar
Ove Kaaven committed
610 611
}

612
/***********************************************************************
613
 *           CoGetState [OLE32.@]
614
 *
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
 * Retrieves the thread state object previously stored by CoSetState().
 *
 * PARAMS
 *  ppv [I] Address where pointer to object will be stored.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: E_OUTOFMEMORY.
 *
 * NOTES
 *  Crashes on all invalid ppv addresses, including NULL.
 *  If the function returns a non-NULL object then the caller must release its
 *  reference on the object when the object is no longer required.
 *
 * SEE ALSO
 *  CoSetState().
631
 */
632
HRESULT WINAPI CoGetState(IUnknown ** ppv)
633
{
634 635
    struct oletls *info = COM_CurrentInfo();
    if (!info) return E_OUTOFMEMORY;
636

637
    *ppv = NULL;
638

639
    if (info->state)
640
    {
641 642 643
        IUnknown_AddRef(info->state);
        *ppv = info->state;
        TRACE("apt->state=%p\n", info->state);
644
    }
645

646
    return S_OK;
647
}
648 649

/***********************************************************************
650
 *           CoSetState [OLE32.@]
651
 *
652 653 654 655 656 657 658 659 660 661 662
 * Sets the thread state object.
 *
 * PARAMS
 *  pv [I] Pointer to state object to be stored.
 *
 * NOTES
 *  The system keeps a reference on the object while the object stored.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: E_OUTOFMEMORY.
663
 */
664
HRESULT WINAPI CoSetState(IUnknown * pv)
665
{
666 667 668
    struct oletls *info = COM_CurrentInfo();
    if (!info) return E_OUTOFMEMORY;

669
    if (pv) IUnknown_AddRef(pv);
670

671
    if (info->state)
672
    {
673 674
        TRACE("-- release %p now\n", info->state);
        IUnknown_Release(info->state);
675
    }
676

677
    info->state = pv;
678

679
    return S_OK;
680
}
681

682

683
/******************************************************************************
684
 *              CoTreatAsClass        [OLE32.@]
685
 *
686 687 688 689 690 691 692 693 694 695 696 697
 * Sets the TreatAs value of a class.
 *
 * PARAMS
 *  clsidOld [I] Class to set TreatAs value on.
 *  clsidNew [I] The class the clsidOld should be treated as.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoGetTreatAsClass
698 699 700
 */
HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
{
701 702
    HKEY hkey = NULL;
    WCHAR szClsidNew[CHARS_IN_GUID];
703
    HRESULT res = S_OK;
704
    WCHAR auto_treat_as[CHARS_IN_GUID];
705 706
    LONG auto_treat_as_size = sizeof(auto_treat_as);
    CLSID id;
707

708 709 710
    res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
    if (FAILED(res))
        goto done;
711 712

    if (IsEqualGUID( clsidOld, clsidNew ))
713
    {
714
       if (!RegQueryValueW(hkey, L"AutoTreatAs", auto_treat_as, &auto_treat_as_size) &&
715
           CLSIDFromString(auto_treat_as, &id) == S_OK)
716
       {
717
           if (RegSetValueW(hkey, L"TreatAs", REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
718 719 720 721 722 723 724
           {
               res = REGDB_E_WRITEREGDB;
               goto done;
           }
       }
       else
       {
725
           if (RegDeleteKeyW(hkey, L"TreatAs"))
726
               res = REGDB_E_WRITEREGDB;
727 728 729
           goto done;
       }
    }
730
    else
731
    {
732
        if(IsEqualGUID(clsidNew, &CLSID_NULL)){
733
           RegDeleteKeyW(hkey, L"TreatAs");
734
        }else{
735
            if(!StringFromGUID2(clsidNew, szClsidNew, ARRAY_SIZE(szClsidNew))){
736 737 738 739 740
                WARN("StringFromGUID2 failed\n");
                res = E_FAIL;
                goto done;
            }

741
            if (RegSetValueW(hkey, L"TreatAs", REG_SZ, szClsidNew, sizeof(szClsidNew)) != ERROR_SUCCESS){
742 743 744 745 746
                WARN("RegSetValue failed\n");
                res = REGDB_E_WRITEREGDB;
                goto done;
            }
        }
747 748 749 750 751
    }

done:
    if (hkey) RegCloseKey(hkey);
    return res;
752
}
753

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
/***********************************************************************
 *           CoIsOle1Class [OLE32.@]
 *
 * Determines whether the specified class an OLE v1 class.
 *
 * PARAMS
 *  clsid [I] Class to test.
 *
 * RETURNS
 *  TRUE if the class is an OLE v1 class, or FALSE otherwise.
 */
BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
{
  FIXME("%s\n", debugstr_guid(clsid));
  return FALSE;
}

771
/***********************************************************************
772
 *           IsEqualGUID [OLE32.@]
773 774 775
 *
 * Compares two Unique Identifiers.
 *
776 777 778 779
 * PARAMS
 *  rguid1 [I] The first GUID to compare.
 *  rguid2 [I] The other GUID to compare.
 *
780 781 782 783 784
 * RETURNS
 *	TRUE if equal
 */
#undef IsEqualGUID
BOOL WINAPI IsEqualGUID(
785 786
     REFGUID rguid1,
     REFGUID rguid2)
787 788 789
{
    return !memcmp(rguid1,rguid2,sizeof(GUID));
}
790

791 792 793 794 795 796 797 798 799
/***********************************************************************
 *           CoAllowSetForegroundWindow [OLE32.@]
 *
 */
HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
{
    FIXME("(%p, %p): stub\n", pUnk, pvReserved);
    return S_OK;
}
800

801 802 803
/***********************************************************************
 *           CoGetObject [OLE32.@]
 *
804
 * Gets the object named by converting the name to a moniker and binding to it.
805 806 807 808
 *
 * PARAMS
 *  pszName      [I] String representing the object.
 *  pBindOptions [I] Parameters affecting the binding to the named object.
809
 *  riid         [I] Interface to bind to on the object.
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
 *  ppv          [O] On output, the interface riid of the object represented
 *                   by pszName.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  MkParseDisplayName.
 */
HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
    REFIID riid, void **ppv)
{
    IBindCtx *pbc;
    HRESULT hr;

    *ppv = NULL;

    hr = CreateBindCtx(0, &pbc);
    if (SUCCEEDED(hr))
    {
        if (pBindOptions)
            hr = IBindCtx_SetBindOptions(pbc, pBindOptions);

        if (SUCCEEDED(hr))
        {
            ULONG chEaten;
            IMoniker *pmk;

            hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
            if (SUCCEEDED(hr))
            {
                hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
                IMoniker_Release(pmk);
            }
        }

        IBindCtx_Release(pbc);
    }
    return hr;
}

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
/* Returns expanded dll path from the registry or activation context. */
static BOOL get_object_dll_path(const struct class_reg_data *regdata, WCHAR *dst, DWORD dstlen)
{
    DWORD ret;

    if (regdata->origin == CLASS_REG_REGISTRY)
    {
	DWORD keytype;
	WCHAR src[MAX_PATH];
	DWORD dwLength = dstlen * sizeof(WCHAR);

        if( (ret = RegQueryValueExW(regdata->u.hkey, NULL, NULL, &keytype, (BYTE*)src, &dwLength)) == ERROR_SUCCESS ) {
            if (keytype == REG_EXPAND_SZ) {
              if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
            } else {
              const WCHAR *quote_start;
              quote_start = wcschr(src, '\"');
              if (quote_start) {
                const WCHAR *quote_end = wcschr(quote_start + 1, '\"');
                if (quote_end) {
                  memmove(src, quote_start + 1,
                          (quote_end - quote_start - 1) * sizeof(WCHAR));
                  src[quote_end - quote_start - 1] = '\0';
                }
              }
              lstrcpynW(dst, src, dstlen);
            }
        }
        return !ret;
    }
    else
    {
        ULONG_PTR cookie;

        *dst = 0;
        ActivateActCtx(regdata->u.actctx.hactctx, &cookie);
888
        ret = SearchPathW(NULL, regdata->u.actctx.module_name, L".dll", dstlen, dst, NULL);
889 890 891 892 893
        DeactivateActCtx(0, cookie);
        return *dst != 0;
    }
}

894 895 896 897 898
HRESULT Handler_DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
    HKEY hkey;
    HRESULT hres;

899
    hres = COM_OpenKeyForCLSID(rclsid, L"InprocHandler32", KEY_READ, &hkey);
900 901
    if (SUCCEEDED(hres))
    {
902
        struct class_reg_data regdata;
903 904
        WCHAR dllpath[MAX_PATH+1];

905
        regdata.u.hkey = hkey;
906
        regdata.origin = CLASS_REG_REGISTRY;
907

908
        if (get_object_dll_path(&regdata, dllpath, ARRAY_SIZE(dllpath)))
909
        {
910
            if (!wcsicmp(dllpath, L"ole32.dll"))
911 912 913 914 915 916 917 918 919 920 921 922
            {
                RegCloseKey(hkey);
                return HandlerCF_Create(rclsid, riid, ppv);
            }
        }
        else
            WARN("not creating object for inproc handler path %s\n", debugstr_w(dllpath));
        RegCloseKey(hkey);
    }

    return CLASS_E_CLASSNOTAVAILABLE;
}
923

924 925 926
/***********************************************************************
 *		DllMain (OLE32.@)
 */
927
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID reserved)
928
{
929
    TRACE("%p, %#lx, %p.\n", hinstDLL, fdwReason, reserved);
930 931 932

    switch(fdwReason) {
    case DLL_PROCESS_ATTACH:
933
        hProxyDll = hinstDLL;
934 935 936
	break;

    case DLL_PROCESS_DETACH:
937
        clipbrd_destroy();
938
        if (reserved) break;
939
        release_std_git();
940
        break;
941 942 943 944
    }
    return TRUE;
}

945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
/***********************************************************************
 *		DllRegisterServer (OLE32.@)
 */
HRESULT WINAPI DllRegisterServer(void)
{
    return OLE32_DllRegisterServer();
}

/***********************************************************************
 *		DllUnregisterServer (OLE32.@)
 */
HRESULT WINAPI DllUnregisterServer(void)
{
    return OLE32_DllUnregisterServer();
}