marshal.c 50.5 KB
Newer Older
1
/*
2
 *	Marshalling library
3
 *
4 5 6
 * Copyright 2002 Marcus Meissner
 * Copyright 2004 Mike Hearn, for CodeWeavers
 * Copyright 2004 Rob Shearman, for CodeWeavers
7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * 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
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 22 23 24 25
 */

#include "config.h"

#include <stdlib.h>
26
#include <stdarg.h>
27 28 29 30
#include <stdio.h>
#include <string.h>
#include <assert.h>

31 32
#define COBJMACROS

33
#include "windef.h"
34
#include "winbase.h"
35
#include "winuser.h"
36 37 38 39 40 41 42
#include "objbase.h"
#include "ole2.h"
#include "rpc.h"
#include "winerror.h"
#include "winreg.h"
#include "wtypes.h"
#include "wine/unicode.h"
43

44 45
#include "compobj_private.h"

46
#include "wine/debug.h"
47

48
WINE_DEFAULT_DEBUG_CHANNEL(ole);
49

50 51
extern const CLSID CLSID_DfMarshal;

52 53 54
/* number of refs given out for normal marshaling */
#define NORMALEXTREFS 1 /* FIXME: this should be 5, but we have to wait for IRemUnknown support first */

55 56 57 58
/* private flag indicating that the caller does not want to notify the stub
 * when the proxy disconnects or is destroyed */
#define SORFP_NOLIFETIMEMGMT SORF_OXRES1

59 60
static HRESULT unmarshal_object(const STDOBJREF *stdobjref, APARTMENT *apt, REFIID riid, void **object);

61
/* Marshalling just passes a unique identifier to the remote client,
62 63 64 65 66 67 68
 * that makes it possible to find the passed interface again.
 *
 * So basically we need a set of values that make it unique.
 *
 * 	Process Identifier, Object IUnknown ptr, IID
 *
 * Note that the IUnknown_QI(ob,xiid,&ppv) always returns the SAME ppv value!
69 70 71 72 73 74 75
 *
 * In Windows, a different triple is used: OXID (apt id), OID (stub
 * manager id), IPID (interface ptr/stub id).
 *
 * OXIDs identify an apartment and are network scoped
 * OIDs identify a stub manager and are apartment scoped
 * IPIDs identify an interface stub and are apartment scoped
76 77
 */

78 79 80 81 82 83 84 85 86 87
inline static HRESULT
get_facbuf_for_iid(REFIID riid,IPSFactoryBuffer **facbuf) {
    HRESULT       hres;
    CLSID         pxclsid;

    if ((hres = CoGetPSClsid(riid,&pxclsid)))
	return hres;
    return CoGetClassObject(&pxclsid,CLSCTX_INPROC_SERVER,NULL,&IID_IPSFactoryBuffer,(LPVOID*)facbuf);
}

88
/* creates a new stub manager */
89
HRESULT register_ifstub(APARTMENT *apt, STDOBJREF *stdobjref, REFIID riid, IUnknown *obj, MSHLFLAGS mshlflags)
90
{
91
    struct stub_manager *manager;
92
    struct ifstub       *ifstub;
93
    BOOL                 tablemarshal;
94 95 96
    IRpcStubBuffer      *stub;
    IPSFactoryBuffer    *psfb;
    HRESULT              hr;
97

98 99
    hr = get_facbuf_for_iid(riid, &psfb);
    if (hr != S_OK)
100
    {
101 102
        ERR("couldn't get IPSFactory buffer for interface %s\n", debugstr_guid(riid));
        return hr;
103
    }
104

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    hr = IPSFactoryBuffer_CreateStub(psfb, riid, obj, &stub);
    IPSFactoryBuffer_Release(psfb);
    if (hr != S_OK)
    {
        ERR("Failed to create an IRpcStubBuffer from IPSFactory for %s\n", debugstr_guid(riid));
        return hr;
    }

    if (mshlflags & MSHLFLAGS_NOPING)
        stdobjref->flags = SORF_NOPING;
    else
        stdobjref->flags = SORF_NULL;

    stdobjref->oxid = apt->oxid;

120 121
    /* FIXME: what happens if we register an interface twice with different
     * marshaling flags? */
122
    if ((manager = get_stub_manager_from_object(apt, obj)))
123 124 125
        TRACE("registering new ifstub on pre-existing manager\n");
    else
    {
126 127
        TRACE("constructing new stub manager\n");

128
        manager = new_stub_manager(apt, obj, mshlflags);
129 130
        if (!manager)
            return E_OUTOFMEMORY;
131
    }
132
    stdobjref->oid = manager->oid;
133

134 135
    tablemarshal = ((mshlflags & MSHLFLAGS_TABLESTRONG) || (mshlflags & MSHLFLAGS_TABLEWEAK));

136
    ifstub = stub_manager_new_ifstub(manager, stub, obj, riid);
137
    if (!ifstub)
138
    {
139
        IRpcStubBuffer_Release(stub);
140 141 142
        stub_manager_int_release(manager);
        /* FIXME: should we do another release to completely destroy the
         * stub manager? */
143
        return E_OUTOFMEMORY;
144 145
    }

146
    if (!tablemarshal)
147 148 149 150 151 152 153 154 155 156
    {
        stdobjref->cPublicRefs = NORMALEXTREFS;
        stub_manager_ext_addref(manager, stdobjref->cPublicRefs);
    }
    else
    {
        stdobjref->cPublicRefs = 0;
        if (mshlflags & MSHLFLAGS_TABLESTRONG)
            stub_manager_ext_addref(manager, 1);
    }
157

158 159 160
    /* FIXME: check return value */
    RPC_RegisterInterface(riid);

161
    stdobjref->ipid = ifstub->ipid;
162 163

    stub_manager_int_release(manager);
164
    return S_OK;
165 166
}

167 168


169 170
/* Client-side identity of the server object */

171
static HRESULT proxy_manager_get_remunknown(struct proxy_manager * This, IRemUnknown **remunk);
172 173
static void proxy_manager_destroy(struct proxy_manager * This);
static HRESULT proxy_manager_find_ifproxy(struct proxy_manager * This, REFIID riid, struct ifproxy ** ifproxy_found);
174
static HRESULT proxy_manager_query_local_interface(struct proxy_manager * This, REFIID riid, void ** ppv);
175

176
static HRESULT WINAPI ClientIdentity_QueryInterface(IMultiQI * iface, REFIID riid, void ** ppv)
177 178
{
    HRESULT hr;
179
    MULTI_QI mqi;
180 181 182

    TRACE("%s\n", debugstr_guid(riid));

183 184 185
    mqi.pIID = riid;
    hr = IMultiQI_QueryMultipleInterfaces(iface, 1, &mqi);
    *ppv = (void *)mqi.pItf;
186

187
    return hr;
188 189
}

190
static ULONG WINAPI ClientIdentity_AddRef(IMultiQI * iface)
191 192
{
    struct proxy_manager * This = (struct proxy_manager *)iface;
193
    TRACE("%p - before %ld\n", iface, This->refs);
194 195 196
    return InterlockedIncrement(&This->refs);
}

197
static ULONG WINAPI ClientIdentity_Release(IMultiQI * iface)
198 199 200
{
    struct proxy_manager * This = (struct proxy_manager *)iface;
    ULONG refs = InterlockedDecrement(&This->refs);
201
    TRACE("%p - after %ld\n", iface, refs);
202 203 204 205 206
    if (!refs)
        proxy_manager_destroy(This);
    return refs;
}

207
static HRESULT WINAPI ClientIdentity_QueryMultipleInterfaces(IMultiQI *iface, ULONG cMQIs, MULTI_QI *pMQIs)
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    struct proxy_manager * This = (struct proxy_manager *)iface;
    REMQIRESULT *qiresults = NULL;
    ULONG nonlocal_mqis = 0;
    ULONG i;
    ULONG successful_mqis = 0;
    IID *iids = HeapAlloc(GetProcessHeap(), 0, cMQIs * sizeof(*iids));
    /* mapping of RemQueryInterface index to QueryMultipleInterfaces index */
    ULONG *mapping = HeapAlloc(GetProcessHeap(), 0, cMQIs * sizeof(*mapping));

    TRACE("cMQIs: %ld\n", cMQIs);

    /* try to get a local interface - this includes already active proxy
     * interfaces and also interfaces exposed by the proxy manager */
    for (i = 0; i < cMQIs; i++)
    {
        TRACE("iid[%ld] = %s\n", i, debugstr_guid(pMQIs[i].pIID));
        pMQIs[i].hr = proxy_manager_query_local_interface(This, pMQIs[i].pIID, (void **)&pMQIs[i].pItf);
        if (pMQIs[i].hr == S_OK)
            successful_mqis++;
        else
        {
            iids[nonlocal_mqis] = *pMQIs[i].pIID;
            mapping[nonlocal_mqis] = i;
            nonlocal_mqis++;
        }
    }

    TRACE("%ld interfaces not found locally\n", nonlocal_mqis);

    /* if we have more than one interface not found locally then we must try
     * to query the remote object for it */
    if (nonlocal_mqis != 0)
    {
        IRemUnknown *remunk;
        HRESULT hr;
        IPID *ipid;

        /* get the ipid of the first entry */
        /* FIXME: should we implement ClientIdentity on the ifproxies instead
         * of the proxy_manager so we use the correct ipid here? */
        ipid = &LIST_ENTRY(list_head(&This->interfaces), struct ifproxy, entry)->ipid;

        /* get IRemUnknown proxy so we can communicate with the remote object */
        hr = proxy_manager_get_remunknown(This, &remunk);

        if (hr == S_OK)
        {
            hr = IRemUnknown_RemQueryInterface(remunk, ipid, NORMALEXTREFS,
                                               nonlocal_mqis, iids, &qiresults);
            if (FAILED(hr))
                ERR("IRemUnknown_RemQueryInterface failed with error 0x%08lx\n", hr);
        }

        /* IRemUnknown_RemQueryInterface can return S_FALSE if only some of
         * the interfaces were returned */
        if (SUCCEEDED(hr))
        {
            /* try to unmarshal each object returned to us */
            for (i = 0; i < nonlocal_mqis; i++)
            {
                ULONG index = mapping[i];
                HRESULT hrobj = qiresults[i].hResult;
                if (hrobj == S_OK)
                    hrobj = unmarshal_object(&qiresults[i].std, This->parent,
                                             pMQIs[index].pIID,
                                             (void **)&pMQIs[index].pItf);

                if (hrobj == S_OK)
                    successful_mqis++;
                else
                    ERR("Failed to get pointer to interface %s\n", debugstr_guid(pMQIs[index].pIID));
                pMQIs[index].hr = hrobj;
            }
        }

        /* free the memory allocated by the proxy */
        CoTaskMemFree(qiresults);
    }

    TRACE("%ld/%ld successfully queried\n", successful_mqis, cMQIs);

    HeapFree(GetProcessHeap(), 0, iids);
    HeapFree(GetProcessHeap(), 0, mapping);

    if (successful_mqis == cMQIs)
        return S_OK; /* we got all requested interfaces */
    else if (successful_mqis == 0)
        return E_NOINTERFACE; /* we didn't get any interfaces */
    else
        return S_FALSE; /* we got some interfaces */
299 300
}

301
static const IMultiQIVtbl ClientIdentity_Vtbl =
302 303 304 305
{
    ClientIdentity_QueryInterface,
    ClientIdentity_AddRef,
    ClientIdentity_Release,
306
    ClientIdentity_QueryMultipleInterfaces
307 308 309 310
};

static HRESULT ifproxy_get_public_ref(struct ifproxy * This)
{
311
    HRESULT hr = S_OK;
312 313 314
    /* FIXME: as this call could possibly be going over the network, we
     * are going to spend a long time in this CS. We might want to replace
     * this with a mutex */
315 316 317
    EnterCriticalSection(&This->parent->cs);
    if (This->refs == 0)
    {
318
        IRemUnknown *remunk = NULL;
319 320 321

        TRACE("getting public ref for ifproxy %p\n", This);

322 323
        hr = proxy_manager_get_remunknown(This->parent, &remunk);
        if (hr == S_OK)
324
        {
325 326 327 328 329 330 331 332 333 334
            HRESULT hrref;
            REMINTERFACEREF rif;
            rif.ipid = This->ipid;
            rif.cPublicRefs = NORMALEXTREFS;
            rif.cPrivateRefs = 0;
            hr = IRemUnknown_RemAddRef(remunk, 1, &rif, &hrref);
            if (hr == S_OK && hrref == S_OK)
                This->refs += NORMALEXTREFS;
            else
                ERR("IRemUnknown_RemAddRef returned with 0x%08lx, hrref = 0x%08lx\n", hr, hrref);
335 336 337 338
        }
    }
    LeaveCriticalSection(&This->parent->cs);

339
    return hr;
340 341
}

342 343
static HRESULT ifproxy_release_public_refs(struct ifproxy * This)
{
344 345 346 347 348
    HRESULT hr = S_OK;

    /* FIXME: as this call could possibly be going over the network, we
     * are going to spend a long time in this CS. We might want to replace
     * this with a mutex */
349 350 351
    EnterCriticalSection(&This->parent->cs);
    if (This->refs > 0)
    {
352 353 354 355 356 357 358 359 360 361 362 363 364 365
        IRemUnknown *remunk = NULL;

        TRACE("releasing %ld refs\n", This->refs);

        hr = proxy_manager_get_remunknown(This->parent, &remunk);
        if (hr == S_OK)
        {
            REMINTERFACEREF rif;
            rif.ipid = This->ipid;
            rif.cPublicRefs = This->refs;
            rif.cPrivateRefs = 0;
            hr = IRemUnknown_RemRelease(remunk, 1, &rif);
            if (hr == S_OK)
                This->refs = 0;
366 367 368 369 370
            else if (hr == RPC_E_DISCONNECTED)
                WARN("couldn't release references because object was "
                     "disconnected: oxid = %s, oid = %s\n",
                     wine_dbgstr_longlong(This->parent->oxid),
                     wine_dbgstr_longlong(This->parent->oid));
371 372 373
            else
                ERR("IRemUnknown_RemRelease failed with error 0x%08lx\n", hr);
        }
374 375
    }
    LeaveCriticalSection(&This->parent->cs);
376 377

    return hr;
378 379 380 381
}

static void ifproxy_disconnect(struct ifproxy * This)
{
382
    ifproxy_release_public_refs(This);
383
    if (This->proxy) IRpcProxyBuffer_Disconnect(This->proxy);
384 385 386 387
}

static void ifproxy_destroy(struct ifproxy * This)
{
388 389
    TRACE("%p\n", This);

390 391 392 393 394 395
    /* release public references to this object so that the stub can know
     * when to destroy itself */
    ifproxy_release_public_refs(This);

    list_remove(&This->entry);

396 397 398 399
    /* note: we don't call Release for This->proxy because its lifetime is
     * controlled by the return value from ClientIdentity_Release, which this
     * function is always called from */

400 401 402
    HeapFree(GetProcessHeap(), 0, This);
}

403 404 405
static HRESULT proxy_manager_construct(
    APARTMENT * apt, ULONG sorflags, OXID oxid, OID oid,
    IRpcChannelBuffer * channel, struct proxy_manager ** proxy_manager)
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
{
    struct proxy_manager * This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
    if (!This) return E_OUTOFMEMORY;

    This->lpVtbl = &ClientIdentity_Vtbl;

    list_init(&This->entry);
    list_init(&This->interfaces);

    InitializeCriticalSection(&This->cs);

    /* the apartment the object was unmarshaled into */
    This->parent = apt;

    /* the source apartment and id of the object */
    This->oxid = oxid;
    This->oid = oid;

424
    This->refs = 1;
425

426 427 428 429 430
    /* the DCOM draft specification states that the SORF_NOPING flag is
     * proxy manager specific, not ifproxy specific, so this implies that we
     * should store the STDOBJREF flags in the proxy manager. */
    This->sorflags = sorflags;

Robert Shearman's avatar
Robert Shearman committed
431
    assert(channel);
432 433
    This->chan = channel; /* FIXME: we should take the binding strings and construct the channel in this function */

434 435 436
    /* we create the IRemUnknown proxy on demand */
    This->remunk = NULL;

437
    EnterCriticalSection(&apt->cs);
Robert Shearman's avatar
Robert Shearman committed
438 439 440 441 442 443
    /* FIXME: we are dependent on the ordering in here to make sure a proxy's
     * IRemUnknown proxy doesn't get destroyed before the regual proxy does
     * because we need the IRemUnknown proxy during the destruction of the
     * regular proxy. Ideally, we should maintain a separate list for the
     * IRemUnknown proxies that need late destruction */
    list_add_tail(&apt->proxies, &This->entry);
444 445
    LeaveCriticalSection(&apt->cs);

446 447 448
    TRACE("%p created for OXID %s, OID %s\n", This,
        wine_dbgstr_longlong(oxid), wine_dbgstr_longlong(oid));

449 450 451 452
    *proxy_manager = This;
    return S_OK;
}

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
static HRESULT proxy_manager_query_local_interface(struct proxy_manager * This, REFIID riid, void ** ppv)
{
    HRESULT hr;
    struct ifproxy * ifproxy;

    TRACE("%s\n", debugstr_guid(riid));

    if (IsEqualIID(riid, &IID_IUnknown) ||
        IsEqualIID(riid, &IID_IMultiQI))
    {
        *ppv = (void *)&This->lpVtbl;
        IMultiQI_AddRef((IMultiQI *)&This->lpVtbl);
        return S_OK;
    }

    hr = proxy_manager_find_ifproxy(This, riid, &ifproxy);
    if (hr == S_OK)
    {
        *ppv = ifproxy->iface;
        IUnknown_AddRef((IUnknown *)*ppv);
        return S_OK;
    }

    *ppv = NULL;
    return E_NOINTERFACE;
}

480
static HRESULT proxy_manager_create_ifproxy(
481
    struct proxy_manager * This, const IPID *ipid, REFIID riid, ULONG cPublicRefs,
482
    struct ifproxy ** iif_out)
483 484 485 486 487 488 489 490
{
    HRESULT hr;
    IPSFactoryBuffer * psfb;
    struct ifproxy * ifproxy = HeapAlloc(GetProcessHeap(), 0, sizeof(*ifproxy));
    if (!ifproxy) return E_OUTOFMEMORY;

    list_init(&ifproxy->entry);

491
    ifproxy->parent = This;
492
    ifproxy->ipid = *ipid;
493 494 495 496
    ifproxy->iid = *riid;
    ifproxy->refs = cPublicRefs;
    ifproxy->proxy = NULL;

497
    /* the IUnknown interface is special because it does not have a
498 499
     * proxy associated with the ifproxy as we handle IUnknown ourselves */
    if (IsEqualIID(riid, &IID_IUnknown))
500
    {
501 502
        ifproxy->iface = (void *)&This->lpVtbl;
        hr = S_OK;
503
    }
504
    else
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    {
        hr = get_facbuf_for_iid(riid, &psfb);
        if (hr == S_OK)
        {
            /* important note: the outer unknown is set to the proxy manager.
             * This ensures the COM identity rules are not violated, by having a
             * one-to-one mapping of objects on the proxy side to objects on the
             * stub side, no matter which interface you view the object through */
            hr = IPSFactoryBuffer_CreateProxy(psfb, (IUnknown *)&This->lpVtbl, riid,
                                              &ifproxy->proxy, &ifproxy->iface);
            IPSFactoryBuffer_Release(psfb);
            if (hr != S_OK)
                ERR("Could not create proxy for interface %s, error 0x%08lx\n",
                    debugstr_guid(riid), hr);
        }
        else
            ERR("Could not get IPSFactoryBuffer for interface %s, error 0x%08lx\n",
                debugstr_guid(riid), hr);
523

524 525 526
        if (hr == S_OK)
            hr = IRpcProxyBuffer_Connect(ifproxy->proxy, This->chan);
    }
527 528 529 530 531 532 533 534 535 536 537 538

    /* get at least one external reference to the object to keep it alive */
    if (hr == S_OK)
        hr = ifproxy_get_public_ref(ifproxy);

    if (hr == S_OK)
    {
        EnterCriticalSection(&This->cs);
        list_add_tail(&This->interfaces, &ifproxy->entry);
        LeaveCriticalSection(&This->cs);

        *iif_out = ifproxy;
539
        TRACE("ifproxy %p created for IPID %s, interface %s with %lu public refs\n",
540
              ifproxy, debugstr_guid(ipid), debugstr_guid(riid), cPublicRefs);
541 542
    }
    else
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
        ifproxy_destroy(ifproxy);

    return hr;
}

static HRESULT proxy_manager_find_ifproxy(struct proxy_manager * This, REFIID riid, struct ifproxy ** ifproxy_found)
{
    HRESULT hr = E_NOINTERFACE; /* assume not found */
    struct list * cursor;

    EnterCriticalSection(&This->cs);
    LIST_FOR_EACH(cursor, &This->interfaces)
    {
        struct ifproxy * ifproxy = LIST_ENTRY(cursor, struct ifproxy, entry);
        if (IsEqualIID(riid, &ifproxy->iid))
        {
            *ifproxy_found = ifproxy;
            hr = S_OK;
            break;
        }
    }
    LeaveCriticalSection(&This->cs);

    return hr;
}

static void proxy_manager_disconnect(struct proxy_manager * This)
{
    struct list * cursor;

573 574
    TRACE("oxid = %s, oid = %s\n", wine_dbgstr_longlong(This->oxid),
        wine_dbgstr_longlong(This->oid));
575

576 577 578 579 580 581 582 583 584 585 586
    EnterCriticalSection(&This->cs);

    LIST_FOR_EACH(cursor, &This->interfaces)
    {
        struct ifproxy * ifproxy = LIST_ENTRY(cursor, struct ifproxy, entry);
        ifproxy_disconnect(ifproxy);
    }

    /* apartment is being destroyed so don't keep a pointer around to it */
    This->parent = NULL;

587 588 589 590 591
    /* FIXME: will this still be necessary if/when we use a real RPC
     * channel? */
    IRpcChannelBuffer_Release(This->chan);
    This->chan = NULL;

592 593 594
    LeaveCriticalSection(&This->cs);
}

595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
static HRESULT proxy_manager_get_remunknown(struct proxy_manager * This, IRemUnknown **remunk)
{
    HRESULT hr = S_OK;

    /* we don't want to try and unmarshal or use IRemUnknown if we don't want
     * lifetime management */
    if (This->sorflags & SORFP_NOLIFETIMEMGMT)
        return S_FALSE;

    EnterCriticalSection(&This->cs);
    if (This->remunk)
        /* already created - return existing object */
        *remunk = This->remunk;
    else if (!This->parent)
        /* disconnected - we can't create IRemUnknown */
        hr = S_FALSE;
    else
    {
        STDOBJREF stdobjref;
        /* Don't want IRemUnknown lifetime management as this is IRemUnknown!
         * We also don't care about whether or not the stub is still alive */
        stdobjref.flags = SORFP_NOLIFETIMEMGMT | SORF_NOPING;
        stdobjref.cPublicRefs = 1;
        /* oxid of destination object */
        stdobjref.oxid = This->oxid;
        /* FIXME: what should be used for the oid? The DCOM draft doesn't say */
        stdobjref.oid = (OID)-1;
        /* FIXME: this is a hack around not having an OXID resolver yet -
         * the OXID resolver should give us the IPID of the IRemUnknown
         * interface */
        stdobjref.ipid.Data1 = 0xffffffff;
        stdobjref.ipid.Data2 = 0xffff;
        stdobjref.ipid.Data3 = 0xffff;
        assert(sizeof(stdobjref.ipid.Data4) == sizeof(stdobjref.oxid));
        memcpy(&stdobjref.ipid.Data4, &stdobjref.oxid, sizeof(OXID));
        
        /* do the unmarshal */
        hr = unmarshal_object(&stdobjref, This->parent, &IID_IRemUnknown, (void**)&This->remunk);
        if (hr == S_OK)
            *remunk = This->remunk;
    }
    LeaveCriticalSection(&This->cs);

    TRACE("got IRemUnknown* pointer %p, hr = 0x%08lx\n", *remunk, hr);

    return hr;
}

/* destroys a proxy manager, freeing the memory it used.
 * Note: this function should not be called from a list iteration in the
 * apartment, due to the fact that it removes itself from the apartment and
 * it could add a proxy to IRemUnknown into the apartment. */
647 648 649 650
static void proxy_manager_destroy(struct proxy_manager * This)
{
    struct list * cursor;

651 652 653
    TRACE("oxid = %s, oid = %s\n", wine_dbgstr_longlong(This->oxid),
        wine_dbgstr_longlong(This->oid));

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    if (This->parent)
    {
        EnterCriticalSection(&This->parent->cs);

        /* remove ourself from the list of proxy objects in the apartment */
        LIST_FOR_EACH(cursor, &This->parent->proxies)
        {
            if (cursor == &This->entry)
            {
                list_remove(&This->entry);
                break;
            }
        }

        LeaveCriticalSection(&This->parent->cs);
    }

    /* destroy all of the interface proxies */
672
    while ((cursor = list_head(&This->interfaces)))
673 674 675 676 677
    {
        struct ifproxy * ifproxy = LIST_ENTRY(cursor, struct ifproxy, entry);
        ifproxy_destroy(ifproxy);
    }

678
    if (This->remunk) IRemUnknown_Release(This->remunk);
679
    if (This->chan) IRpcChannelBuffer_Release(This->chan);
680

681 682 683 684 685
    DeleteCriticalSection(&This->cs);

    HeapFree(GetProcessHeap(), 0, This);
}

686 687 688
/* finds the proxy manager corresponding to a given OXID and OID that has
 * been unmarshaled in the specified apartment. The caller must release the
 * reference to the proxy_manager when the object is no longer used. */
689 690 691 692 693 694 695 696 697 698 699 700
static BOOL find_proxy_manager(APARTMENT * apt, OXID oxid, OID oid, struct proxy_manager ** proxy_found)
{
    BOOL found = FALSE;
    struct list * cursor;

    EnterCriticalSection(&apt->cs);
    LIST_FOR_EACH(cursor, &apt->proxies)
    {
        struct proxy_manager * proxy = LIST_ENTRY(cursor, struct proxy_manager, entry);
        if ((oxid == proxy->oxid) && (oid == proxy->oid))
        {
            *proxy_found = proxy;
701
            ClientIdentity_AddRef((IMultiQI *)&proxy->lpVtbl);
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
            found = TRUE;
            break;
        }
    }
    LeaveCriticalSection(&apt->cs);
    return found;
}

HRESULT MARSHAL_Disconnect_Proxies(APARTMENT *apt)
{
    struct list * cursor;

    EnterCriticalSection(&apt->cs);
    LIST_FOR_EACH(cursor, &apt->proxies)
    {
        struct proxy_manager * proxy = LIST_ENTRY(cursor, struct proxy_manager, entry);
        proxy_manager_disconnect(proxy);
    }
    LeaveCriticalSection(&apt->cs);

722 723 724 725 726
    return S_OK;
}

/********************** StdMarshal implementation ****************************/
typedef struct _StdMarshalImpl {
727
  IMarshalVtbl	*lpvtbl;
728 729 730 731 732 733 734 735
  DWORD			ref;

  IID			iid;
  DWORD			dwDestContext;
  LPVOID		pvDestContext;
  DWORD			mshlflags;
} StdMarshalImpl;

736
static HRESULT WINAPI
737 738 739 740 741 742 743 744 745 746 747
StdMarshalImpl_QueryInterface(LPMARSHAL iface,REFIID riid,LPVOID *ppv) {
  *ppv = NULL;
  if (IsEqualIID(&IID_IUnknown,riid) || IsEqualIID(&IID_IMarshal,riid)) {
    *ppv = iface;
    IUnknown_AddRef(iface);
    return S_OK;
  }
  FIXME("No interface for %s.\n",debugstr_guid(riid));
  return E_NOINTERFACE;
}

748
static ULONG WINAPI
749
StdMarshalImpl_AddRef(LPMARSHAL iface) {
750
  StdMarshalImpl *This = (StdMarshalImpl *)iface;
751
  return InterlockedIncrement(&This->ref);
752 753
}

754
static ULONG WINAPI
755
StdMarshalImpl_Release(LPMARSHAL iface) {
756
  StdMarshalImpl *This = (StdMarshalImpl *)iface;
757
  ULONG ref = InterlockedDecrement(&This->ref);
758

759 760
  if (!ref) HeapFree(GetProcessHeap(),0,This);
  return ref;
761 762
}

763
static HRESULT WINAPI
764 765 766 767 768 769 770 771
StdMarshalImpl_GetUnmarshalClass(
  LPMARSHAL iface, REFIID riid, void* pv, DWORD dwDestContext,
  void* pvDestContext, DWORD mshlflags, CLSID* pCid
) {
  memcpy(pCid,&CLSID_DfMarshal,sizeof(CLSID_DfMarshal));
  return S_OK;
}

772
static HRESULT WINAPI
773 774
StdMarshalImpl_GetMarshalSizeMax(
  LPMARSHAL iface, REFIID riid, void* pv, DWORD dwDestContext,
775 776 777 778
  void* pvDestContext, DWORD mshlflags, DWORD* pSize)
{
    *pSize = sizeof(STDOBJREF);
    return S_OK;
779 780
}

781
static HRESULT WINAPI
782 783 784 785
StdMarshalImpl_MarshalInterface(
  LPMARSHAL iface, IStream *pStm,REFIID riid, void* pv, DWORD dwDestContext,
  void* pvDestContext, DWORD mshlflags
) {
786
  STDOBJREF             stdobjref;
787 788 789
  IUnknown             *pUnk;  
  ULONG                 res;
  HRESULT               hres;
790
  APARTMENT            *apt = COM_CurrentApt();
791
    
792
  TRACE("(...,%s,...)\n",debugstr_guid(riid));
793

794 795 796 797 798 799
  if (!apt)
  {
      ERR("Apartment not initialized\n");
      return CO_E_NOTINITIALIZED;
  }

800 801
  /* make sure this apartment can be reached from other threads / processes */
  RPC_StartRemoting(apt);
802

Robert Shearman's avatar
Robert Shearman committed
803 804 805 806 807 808 809
  hres = IUnknown_QueryInterface((LPUNKNOWN)pv, riid, (LPVOID*)&pUnk);
  if (hres != S_OK)
  {
      ERR("object doesn't expose interface %s, failing with error 0x%08lx\n",
        debugstr_guid(riid), hres);
      return E_NOINTERFACE;
  }
810 811

  hres = register_ifstub(apt, &stdobjref, riid, pUnk, mshlflags);
812
  
813
  IUnknown_Release(pUnk);
814 815 816 817 818 819 820
  
  if (hres)
  {
    FIXME("Failed to create ifstub, hres=0x%lx\n", hres);
    return hres;
  }

821
  hres = IStream_Write(pStm, &stdobjref, sizeof(stdobjref), &res);
822 823
  if (hres) return hres;

824 825 826
  return S_OK;
}

827 828 829 830 831 832 833 834
/* helper for StdMarshalImpl_UnmarshalInterface - does the unmarshaling with
 * no questions asked about the rules surrounding same-apartment unmarshals
 * and table marshaling */
static HRESULT unmarshal_object(const STDOBJREF *stdobjref, APARTMENT *apt, REFIID riid, void **object)
{
    struct proxy_manager *proxy_manager = NULL;
    HRESULT hr = S_OK;

835 836 837 838 839 840 841 842
    assert(apt);

    TRACE("stdobjref:\n\tflags = %04lx\n\tcPublicRefs = %ld\n\toxid = %s\n\toid = %s\n\tipid = %s\n",
        stdobjref->flags, stdobjref->cPublicRefs,
        wine_dbgstr_longlong(stdobjref->oxid),
        wine_dbgstr_longlong(stdobjref->oid),
        debugstr_guid(&stdobjref->ipid));

843 844 845 846 847 848
    /* create an a new proxy manager if one doesn't already exist for the
     * object */
    if (!find_proxy_manager(apt, stdobjref->oxid, stdobjref->oid, &proxy_manager))
    {
        IRpcChannelBuffer *chanbuf;

849
        hr = RPC_CreateClientChannel(&stdobjref->oxid, &stdobjref->ipid, &chanbuf);
850 851 852 853 854
        if (hr == S_OK)
            hr = proxy_manager_construct(apt, stdobjref->flags,
                                         stdobjref->oxid, stdobjref->oid,
                                         chanbuf, &proxy_manager);
    }
855 856
    else
        TRACE("proxy manager already created, using\n");
857 858 859

    if (hr == S_OK)
    {
860 861 862
        struct ifproxy * ifproxy;
        hr = proxy_manager_find_ifproxy(proxy_manager, riid, &ifproxy);
        if (hr == E_NOINTERFACE)
863
            hr = proxy_manager_create_ifproxy(proxy_manager, &stdobjref->ipid,
864 865 866 867
                                              riid, stdobjref->cPublicRefs,
                                              &ifproxy);

        if (hr == S_OK)
868
        {
869
            /* FIXME: push this AddRef inside proxy_manager_find_ifproxy/create_ifproxy? */
870
            ClientIdentity_AddRef((IMultiQI*)&proxy_manager->lpVtbl);
871
            *object = ifproxy->iface;
872 873 874 875 876
        }
    }

    /* release our reference to the proxy manager - the client/apartment
     * will hold on to the remaining reference for us */
877
    if (proxy_manager) ClientIdentity_Release((IMultiQI*)&proxy_manager->lpVtbl);
878 879 880 881

    return hr;
}

882
static HRESULT WINAPI
883 884 885
StdMarshalImpl_UnmarshalInterface(LPMARSHAL iface, IStream *pStm, REFIID riid, void **ppv)
{
  struct stub_manager  *stubmgr;
886
  STDOBJREF stdobjref;
887 888
  ULONG			res;
  HRESULT		hres;
889
  APARTMENT *apt = COM_CurrentApt();
890
  APARTMENT *stub_apt;
891 892

  TRACE("(...,%s,....)\n",debugstr_guid(riid));
893

894
  /* we need an apartment to unmarshal into */
895 896 897 898 899
  if (!apt)
  {
      ERR("Apartment not initialized\n");
      return CO_E_NOTINITIALIZED;
  }
900

901
  /* read STDOBJREF from wire */
902
  hres = IStream_Read(pStm, &stdobjref, sizeof(stdobjref), &res);
903
  if (hres) return hres;
904 905
  
  /* check if we're marshalling back to ourselves */
906
  if ((apt->oxid == stdobjref.oxid) && (stubmgr = get_stub_manager(apt, stdobjref.oid)))
907
  {
908 909
      TRACE("Unmarshalling object marshalled in same apartment for iid %s, "
            "returning original object %p\n", debugstr_guid(riid), stubmgr->object);
910 911 912
    
      hres = IUnknown_QueryInterface(stubmgr->object, riid, ppv);
      
913
      /* unref the ifstub. FIXME: only do this on success? */
914
      if (!stub_manager_is_table_marshaled(stubmgr))
915
          stub_manager_ext_release(stubmgr, 1);
916 917

      stub_manager_int_release(stubmgr);
918
      return hres;
919
  }
920

921 922 923 924 925
  /* notify stub manager about unmarshal if process-local object.
   * note: if the oxid is not found then we and native will quite happily
   * ignore table marshaling and normal marshaling rules regarding number of
   * unmarshals, etc, but if you abuse these rules then your proxy could end
   * up returning RPC_E_DISCONNECTED. */
926
  if ((stub_apt = COM_ApartmentFromOXID(stdobjref.oxid, TRUE)))
927
  {
928
      if ((stubmgr = get_stub_manager(stub_apt, stdobjref.oid)))
929
      {
930
          if (!stub_manager_notify_unmarshal(stubmgr))
931 932 933 934 935 936 937
              hres = CO_E_OBJNOTCONNECTED;

          stub_manager_int_release(stubmgr);
      }
      else
      {
          WARN("Couldn't find object for OXID %s, OID %s, assuming disconnected\n",
938 939
              wine_dbgstr_longlong(stdobjref.oxid),
              wine_dbgstr_longlong(stdobjref.oid));
940 941 942 943 944 945
          hres = CO_E_OBJNOTCONNECTED;
      }

      COM_ApartmentRelease(stub_apt);
  }
  else
946 947
      TRACE("Treating unmarshal from OXID %s as inter-process\n",
            wine_dbgstr_longlong(stdobjref.oxid));
948

949
  if (hres == S_OK)
950
      hres = unmarshal_object(&stdobjref, apt, riid, ppv);
951

952 953
  if (hres) WARN("Failed with error 0x%08lx\n", hres);
  else TRACE("Successfully created proxy %p\n", *ppv);
954

955
  return hres;
956 957
}

958
static HRESULT WINAPI
959
StdMarshalImpl_ReleaseMarshalData(LPMARSHAL iface, IStream *pStm) {
960
    STDOBJREF            stdobjref;
961 962 963
    ULONG                res;
    HRESULT              hres;
    struct stub_manager *stubmgr;
964
    APARTMENT           *apt;
965

966 967
    TRACE("iface=%p, pStm=%p\n", iface, pStm);
    
968
    hres = IStream_Read(pStm, &stdobjref, sizeof(stdobjref), &res);
969 970
    if (hres) return hres;

971
    if (!(apt = COM_ApartmentFromOXID(stdobjref.oxid, TRUE)))
972
    {
973 974
        WARN("Could not map OXID %s to apartment object\n",
            wine_dbgstr_longlong(stdobjref.oxid));
975 976 977
        return RPC_E_INVALID_OBJREF;
    }

978
    if (!(stubmgr = get_stub_manager(apt, stdobjref.oid)))
979 980
    {
        ERR("could not map MID to stub manager, oxid=%s, oid=%s\n",
981
            wine_dbgstr_longlong(stdobjref.oxid), wine_dbgstr_longlong(stdobjref.oid));
982 983
        return RPC_E_INVALID_OBJREF;
    }
984

985
    stub_manager_release_marshal_data(stubmgr, stdobjref.cPublicRefs);
986 987

    stub_manager_int_release(stubmgr);
988
    COM_ApartmentRelease(apt);
989

990
    return S_OK;
991 992
}

993
static HRESULT WINAPI
994 995 996 997 998
StdMarshalImpl_DisconnectObject(LPMARSHAL iface, DWORD dwReserved) {
  FIXME("(), stub!\n");
  return S_OK;
}

999
IMarshalVtbl stdmvtbl = {
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    StdMarshalImpl_QueryInterface,
    StdMarshalImpl_AddRef,
    StdMarshalImpl_Release,
    StdMarshalImpl_GetUnmarshalClass,
    StdMarshalImpl_GetMarshalSizeMax,
    StdMarshalImpl_MarshalInterface,
    StdMarshalImpl_UnmarshalInterface,
    StdMarshalImpl_ReleaseMarshalData,
    StdMarshalImpl_DisconnectObject
};

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
static HRESULT StdMarshalImpl_Construct(REFIID riid, void** ppvObject)
{
    StdMarshalImpl * pStdMarshal = 
        HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(StdMarshalImpl));
    if (!pStdMarshal)
        return E_OUTOFMEMORY;
    pStdMarshal->lpvtbl = &stdmvtbl;
    pStdMarshal->ref = 0;
    return IMarshal_QueryInterface((IMarshal*)pStdMarshal, riid, ppvObject);
}

1022
/***********************************************************************
1023
 *		CoGetStandardMarshal	[OLE32.@]
1024
 *
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
 * Gets or creates a standard marshal object.
 *
 * PARAMS
 *  riid          [I] Interface identifier of the pUnk object.
 *  pUnk          [I] Optional. Object to get the marshal object for.
 *  dwDestContext [I] Destination. Used to enable or disable optimizations.
 *  pvDestContext [I] Reserved. Must be NULL.
 *  mshlflags     [I] Flags affecting the marshaling process.
 *  ppMarshal     [O] Address where marshal object will be stored.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * NOTES
 *
 * The function retrieves the IMarshal object associated with an object if
 * that object is currently an active stub, otherwise a new marshal object is
 * created.
1044
 */
1045 1046 1047 1048
HRESULT WINAPI CoGetStandardMarshal(REFIID riid, IUnknown *pUnk,
                                    DWORD dwDestContext, LPVOID pvDestContext,
                                    DWORD mshlflags, LPMARSHAL *ppMarshal)
{
1049 1050 1051 1052
  StdMarshalImpl *dm;

  if (pUnk == NULL) {
    FIXME("(%s,NULL,%lx,%p,%lx,%p), unimplemented yet.\n",
1053
      debugstr_guid(riid),dwDestContext,pvDestContext,mshlflags,ppMarshal
1054 1055 1056 1057
    );
    return E_FAIL;
  }
  TRACE("(%s,%p,%lx,%p,%lx,%p)\n",
1058
    debugstr_guid(riid),pUnk,dwDestContext,pvDestContext,mshlflags,ppMarshal
1059
  );
1060 1061
  *ppMarshal = HeapAlloc(GetProcessHeap(),0,sizeof(StdMarshalImpl));
  dm = (StdMarshalImpl*) *ppMarshal;
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
  if (!dm) return E_FAIL;
  dm->lpvtbl		= &stdmvtbl;
  dm->ref		= 1;

  memcpy(&dm->iid,riid,sizeof(dm->iid));
  dm->dwDestContext	= dwDestContext;
  dm->pvDestContext	= pvDestContext;
  dm->mshlflags		= mshlflags;
  return S_OK;
}

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
/***********************************************************************
 *		get_marshaler	[internal]
 *
 * Retrieves an IMarshal interface for an object.
 */
static HRESULT get_marshaler(REFIID riid, IUnknown *pUnk, DWORD dwDestContext,
                             void *pvDestContext, DWORD mshlFlags,
                             LPMARSHAL *pMarshal)
{
    HRESULT hr;
1083

1084 1085 1086 1087 1088 1089 1090
    if (!pUnk)
        return E_POINTER;
    hr = IUnknown_QueryInterface(pUnk, &IID_IMarshal, (LPVOID*)pMarshal);
    if (hr)
        hr = CoGetStandardMarshal(riid, pUnk, dwDestContext, pvDestContext,
                                  mshlFlags, pMarshal);
    return hr;
1091 1092
}

1093 1094 1095 1096 1097 1098 1099
/***********************************************************************
 *		get_unmarshaler_from_stream	[internal]
 *
 * Creates an IMarshal* object according to the data marshaled to the stream.
 * The function leaves the stream pointer at the start of the data written
 * to the stream by the IMarshal* object.
 */
1100
static HRESULT get_unmarshaler_from_stream(IStream *stream, IMarshal **marshal, IID *iid)
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
{
    HRESULT hr;
    ULONG res;
    OBJREF objref;

    /* read common OBJREF header */
    hr = IStream_Read(stream, &objref, FIELD_OFFSET(OBJREF, u_objref), &res);
    if (hr || (res != FIELD_OFFSET(OBJREF, u_objref)))
    {
        ERR("Failed to read common OBJREF header, 0x%08lx\n", hr);
        return STG_E_READFAULT;
    }

    /* sanity check on header */
    if (objref.signature != OBJREF_SIGNATURE)
    {
        ERR("Bad OBJREF signature 0x%08lx\n", objref.signature);
        return RPC_E_INVALID_OBJREF;
    }

1121 1122
    if (iid) *iid = objref.iid;

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 1156 1157 1158 1159
    /* FIXME: handler marshaling */
    if (objref.flags & OBJREF_STANDARD)
    {
        TRACE("Using standard unmarshaling\n");
        hr = StdMarshalImpl_Construct(&IID_IMarshal, (LPVOID*)marshal);
    }
    else if (objref.flags & OBJREF_CUSTOM)
    {
        ULONG custom_header_size = FIELD_OFFSET(OBJREF, u_objref.u_custom.size) - 
                                   FIELD_OFFSET(OBJREF, u_objref.u_custom);
        TRACE("Using custom unmarshaling\n");
        /* read constant sized OR_CUSTOM data from stream */
        hr = IStream_Read(stream, &objref.u_objref.u_custom,
                          custom_header_size, &res);
        if (hr || (res != custom_header_size))
        {
            ERR("Failed to read OR_CUSTOM header, 0x%08lx\n", hr);
            return STG_E_READFAULT;
        }
        /* now create the marshaler specified in the stream */
        hr = CoCreateInstance(&objref.u_objref.u_custom.clsid, NULL,
                              CLSCTX_INPROC_SERVER, &IID_IMarshal,
                              (LPVOID*)marshal);
    }
    else
    {
        FIXME("Invalid or unimplemented marshaling type specified: %lx\n",
            objref.flags);
        return RPC_E_INVALID_OBJREF;
    }

    if (hr)
        ERR("Failed to create marshal, 0x%08lx\n", hr);

    return hr;
}

1160
/***********************************************************************
1161
 *		CoGetMarshalSizeMax	[OLE32.@]
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
 *
 * Gets the maximum amount of data that will be needed by a marshal.
 *
 * PARAMS
 *  pulSize       [O] Address where maximum marshal size will be stored.
 *  riid          [I] Identifier of the interface to marshal.
 *  pUnk          [I] Pointer to the object to marshal.
 *  dwDestContext [I] Destination. Used to enable or disable optimizations.
 *  pvDestContext [I] Reserved. Must be NULL.
 *  mshlFlags     [I] Flags that affect the marshaling. See CoMarshalInterface().
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoMarshalInterface().
1179
 */
1180 1181 1182 1183 1184 1185 1186 1187
HRESULT WINAPI CoGetMarshalSizeMax(ULONG *pulSize, REFIID riid, IUnknown *pUnk,
                                   DWORD dwDestContext, void *pvDestContext,
                                   DWORD mshlFlags)
{
    HRESULT hr;
    LPMARSHAL pMarshal;
    CLSID marshaler_clsid;

1188
    hr = get_marshaler(riid, pUnk, dwDestContext, pvDestContext, mshlFlags, &pMarshal);
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    if (hr)
        return hr;

    hr = IMarshal_GetUnmarshalClass(pMarshal, riid, pUnk, dwDestContext,
                                    pvDestContext, mshlFlags, &marshaler_clsid);
    if (hr)
    {
        ERR("IMarshal::GetUnmarshalClass failed, 0x%08lx\n", hr);
        IMarshal_Release(pMarshal);
        return hr;
    }
1200

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    hr = IMarshal_GetMarshalSizeMax(pMarshal, riid, pUnk, dwDestContext,
                                    pvDestContext, mshlFlags, pulSize);
    /* add on the size of the common header */
    *pulSize += FIELD_OFFSET(OBJREF, u_objref);

    /* if custom marshaling, add on size of custom header */
    if (!IsEqualCLSID(&marshaler_clsid, &CLSID_DfMarshal))
        *pulSize += FIELD_OFFSET(OBJREF, u_objref.u_custom.size) - 
                    FIELD_OFFSET(OBJREF, u_objref.u_custom);

    IMarshal_Release(pMarshal);
    return hr;
1213 1214 1215 1216
}


/***********************************************************************
1217
 *		CoMarshalInterface	[OLE32.@]
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
 *
 * Marshals an interface into a stream so that the object can then be
 * unmarshaled from another COM apartment and used remotely.
 *
 * PARAMS
 *  pStream       [I] Stream the object will be marshaled into.
 *  riid          [I] Identifier of the interface to marshal.
 *  pUnk          [I] Pointer to the object to marshal.
 *  dwDestContext [I] Destination. Used to enable or disable optimizations.
 *  pvDestContext [I] Reserved. Must be NULL.
 *  mshlFlags     [I] Flags that affect the marshaling. See notes.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * NOTES
 *
 * The mshlFlags parameter can take one or more of the following flags:
 *| MSHLFLAGS_NORMAL - Unmarshal once, releases stub on last proxy release.
 *| MSHLFLAGS_TABLESTRONG - Unmarshal many, release when CoReleaseMarshalData() called.
 *| MSHLFLAGS_TABLEWEAK - Unmarshal many, releases stub on last proxy release.
 *| MSHLFLAGS_NOPING - No automatic garbage collection (and so reduces network traffic).
 *
 * If a marshaled object is not unmarshaled, then CoReleaseMarshalData() must
 * be called in order to release the resources used in the marshaling.
 *
 * SEE ALSO
 *  CoUnmarshalInterface(), CoReleaseMarshalData().
1247
 */
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
HRESULT WINAPI CoMarshalInterface(IStream *pStream, REFIID riid, IUnknown *pUnk,
                                  DWORD dwDestContext, void *pvDestContext,
                                  DWORD mshlFlags)
{
    HRESULT	hr;
    CLSID marshaler_clsid;
    OBJREF objref;
    IStream * pMarshalStream = NULL;
    LPMARSHAL pMarshal;

    TRACE("(%p, %s, %p, %lx, %p, %lx)\n", pStream, debugstr_guid(riid), pUnk,
        dwDestContext, pvDestContext, mshlFlags);

    if (pUnk == NULL)
        return E_INVALIDARG;

    objref.signature = OBJREF_SIGNATURE;
    objref.iid = *riid;

    /* get the marshaler for the specified interface */
1268
    hr = get_marshaler(riid, pUnk, dwDestContext, pvDestContext, mshlFlags, &pMarshal);
1269 1270 1271 1272 1273
    if (hr)
    {
        ERR("Failed to get marshaller, 0x%08lx\n", hr);
        return hr;
    }
1274

1275 1276 1277 1278 1279 1280 1281
    hr = IMarshal_GetUnmarshalClass(pMarshal, riid, pUnk, dwDestContext,
                                    pvDestContext, mshlFlags, &marshaler_clsid);
    if (hr)
    {
        ERR("IMarshal::GetUnmarshalClass failed, 0x%08lx\n", hr);
        goto cleanup;
    }
1282

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    /* FIXME: implement handler marshaling too */
    if (IsEqualCLSID(&marshaler_clsid, &CLSID_DfMarshal))
    {
        TRACE("Using standard marshaling\n");
        objref.flags = OBJREF_STANDARD;
        pMarshalStream = pStream;
    }
    else
    {
        TRACE("Using custom marshaling\n");
        objref.flags = OBJREF_CUSTOM;
        /* we do custom marshaling into a memory stream so that we know what
         * size to write into the OR_CUSTOM header */
        hr = CreateStreamOnHGlobal(NULL, TRUE, &pMarshalStream);
        if (hr)
        {
            ERR("CreateStreamOnHGLOBAL failed with 0x%08lx\n", hr);
            goto cleanup;
        }
    }
1303

1304 1305 1306 1307 1308 1309 1310
    /* write the common OBJREF header to the stream */
    hr = IStream_Write(pStream, &objref, FIELD_OFFSET(OBJREF, u_objref), NULL);
    if (hr)
    {
        ERR("Failed to write OBJREF header to stream, 0x%08lx\n", hr);
        goto cleanup;
    }
1311

1312 1313 1314 1315
    TRACE("Calling IMarshal::MarshalInterace\n");
    /* call helper object to do the actual marshaling */
    hr = IMarshal_MarshalInterface(pMarshal, pMarshalStream, riid, pUnk, dwDestContext,
                                   pvDestContext, mshlFlags);
1316

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
    if (hr)
    {
        ERR("Failed to marshal the interface %s, %lx\n", debugstr_guid(riid), hr);
        goto cleanup;
    }

    if (objref.flags & OBJREF_CUSTOM)
    {
        ULONG custom_header_size = FIELD_OFFSET(OBJREF, u_objref.u_custom.size) - 
                                   FIELD_OFFSET(OBJREF, u_objref.u_custom);
        HGLOBAL hGlobal;
        LPVOID data;
        hr = GetHGlobalFromStream(pMarshalStream, &hGlobal);
        if (hr)
        {
            ERR("Couldn't get HGLOBAL from stream\n");
            hr = E_UNEXPECTED;
            goto cleanup;
        }
1336
        objref.u_objref.u_custom.clsid = marshaler_clsid;
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        objref.u_objref.u_custom.cbExtension = 0;
        objref.u_objref.u_custom.size = GlobalSize(hGlobal);
        /* write constant sized OR_CUSTOM data into stream */
        hr = IStream_Write(pStream, &objref.u_objref.u_custom,
                          custom_header_size, NULL);
        if (hr)
        {
            ERR("Failed to write OR_CUSTOM header to stream with 0x%08lx\n", hr);
            goto cleanup;
        }

        data = GlobalLock(hGlobal);
        if (!data)
        {
            ERR("GlobalLock failed\n");
            hr = E_UNEXPECTED;
            goto cleanup;
        }
        /* write custom marshal data */
        hr = IStream_Write(pStream, data, objref.u_objref.u_custom.size, NULL);
        if (hr)
        {
            ERR("Failed to write custom marshal data with 0x%08lx\n", hr);
            goto cleanup;
        }
        GlobalUnlock(hGlobal);
1363
    }
1364

1365 1366 1367 1368
cleanup:
    if (pMarshalStream && (objref.flags & OBJREF_CUSTOM))
        IStream_Release(pMarshalStream);
    IMarshal_Release(pMarshal);
1369 1370 1371

    TRACE("completed with hr 0x%08lx\n", hr);
    
1372 1373
    return hr;
}
1374 1375

/***********************************************************************
1376
 *		CoUnmarshalInterface	[OLE32.@]
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
 *
 * Unmarshals an object from a stream by creating a proxy to the remote
 * object, if necessary.
 *
 * PARAMS
 *
 *  pStream [I] Stream containing the marshaled object.
 *  riid    [I] Interface identifier of the object to create a proxy to.
 *  ppv     [O] Address where proxy will be stored.
 *
 * RETURNS
 *
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoMarshalInterface().
1394
 */
1395 1396
HRESULT WINAPI CoUnmarshalInterface(IStream *pStream, REFIID riid, LPVOID *ppv)
{
1397
    HRESULT hr;
1398
    LPMARSHAL pMarshal;
1399 1400
    IID iid;
    IUnknown *object;
1401

1402
    TRACE("(%p, %s, %p)\n", pStream, debugstr_guid(riid), ppv);
1403

1404
    hr = get_unmarshaler_from_stream(pStream, &pMarshal, &iid);
1405 1406 1407 1408
    if (hr != S_OK)
        return hr;

    /* call the helper object to do the actual unmarshaling */
1409
    hr = IMarshal_UnmarshalInterface(pMarshal, pStream, &iid, (LPVOID*)&object);
1410 1411 1412
    if (hr)
        ERR("IMarshal::UnmarshalInterface failed, 0x%08lx\n", hr);

1413 1414 1415 1416 1417 1418
    /* IID_NULL means use the interface ID of the marshaled object */
    if (!IsEqualIID(riid, &IID_NULL))
        iid = *riid;

    if (hr == S_OK)
    {
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        if (!IsEqualIID(riid, &iid))
        {
            TRACE("requested interface != marshalled interface, additional QI needed\n");
            hr = IUnknown_QueryInterface(object, &iid, ppv);
            if (hr)
                ERR("Couldn't query for interface %s, hr = 0x%08lx\n",
                    debugstr_guid(riid), hr);
            IUnknown_Release(object);
        }
        else
        {
            *ppv = object;
        }
1432 1433
    }

1434
    IMarshal_Release(pMarshal);
1435 1436 1437

    TRACE("completed with hr 0x%lx\n", hr);
    
1438
    return hr;
1439 1440
}

1441 1442
/***********************************************************************
 *		CoReleaseMarshalData	[OLE32.@]
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
 *
 * Releases resources associated with an object that has been marshaled into
 * a stream.
 *
 * PARAMS
 *
 *  pStream [I] The stream that the object has been marshaled into.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT error code.
 *
 * NOTES
 * 
 * Call this function to release resources associated with a normal or
 * table-weak marshal that will not be unmarshaled, and all table-strong
 * marshals when they are no longer needed.
 *
 * SEE ALSO
 *  CoMarshalInterface(), CoUnmarshalInterface().
1463
 */
1464 1465 1466 1467
HRESULT WINAPI CoReleaseMarshalData(IStream *pStream)
{
    HRESULT	hr;
    LPMARSHAL pMarshal;
1468

1469
    TRACE("(%p)\n", pStream);
1470

1471
    hr = get_unmarshaler_from_stream(pStream, &pMarshal, NULL);
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    if (hr != S_OK)
        return hr;

    /* call the helper object to do the releasing of marshal data */
    hr = IMarshal_ReleaseMarshalData(pMarshal, pStream);
    if (hr)
        ERR("IMarshal::ReleaseMarshalData failed with error 0x%08lx\n", hr);

    IMarshal_Release(pMarshal);
    return hr;
1482 1483 1484
}


1485
/***********************************************************************
1486
 *		CoMarshalInterThreadInterfaceInStream	[OLE32.@]
1487
 *
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
 * Marshal an interface across threads in the same process.
 *
 * PARAMS
 *  riid  [I] Identifier of the interface to be marshalled.
 *  pUnk  [I] Pointer to IUnknown-derived interface that will be marshalled.
 *  ppStm [O] Pointer to IStream object that is created and then used to store the marshalled inteface.
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: E_OUTOFMEMORY and other COM error codes
 *
1499
 * SEE ALSO
1500
 *   CoMarshalInterface(), CoUnmarshalInterface() and CoGetInterfaceAndReleaseStream()
1501
 */
1502 1503
HRESULT WINAPI CoMarshalInterThreadInterfaceInStream(
    REFIID riid, LPUNKNOWN pUnk, LPSTREAM * ppStm)
1504 1505 1506 1507
{
    ULARGE_INTEGER	xpos;
    LARGE_INTEGER		seekto;
    HRESULT		hres;
1508

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    TRACE("(%s, %p, %p)\n",debugstr_guid(riid), pUnk, ppStm);

    hres = CreateStreamOnHGlobal(0, TRUE, ppStm);
    if (FAILED(hres)) return hres;
    hres = CoMarshalInterface(*ppStm, riid, pUnk, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);

    /* FIXME: is this needed? */
    memset(&seekto,0,sizeof(seekto));
    IStream_Seek(*ppStm,seekto,SEEK_SET,&xpos);

    return hres;
1520 1521 1522
}

/***********************************************************************
1523
 *		CoGetInterfaceAndReleaseStream	[OLE32.@]
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
 *
 * Unmarshalls an inteface from a stream and then releases the stream.
 *
 * PARAMS
 *  pStm [I] Stream that contains the marshalled inteface.
 *  riid [I] Interface identifier of the object to unmarshall.
 *  ppv  [O] Address of pointer where the requested interface object will be stored.
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: A COM error code
 *
1536
 * SEE ALSO
1537
 *  CoMarshalInterThreadInterfaceInStream() and CoUnmarshalInteface()
1538
 */
1539 1540
HRESULT WINAPI CoGetInterfaceAndReleaseStream(LPSTREAM pStm, REFIID riid,
                                              LPVOID *ppv)
1541 1542
{
    HRESULT hres;
1543

1544 1545 1546 1547 1548
    TRACE("(%p, %s, %p)\n", pStm, debugstr_guid(riid), ppv);

    hres = CoUnmarshalInterface(pStm, riid, ppv);
    IStream_Release(pStm);
    return hres;
1549 1550
}

1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
static HRESULT WINAPI StdMarshalCF_QueryInterface(LPCLASSFACTORY iface,
                                                  REFIID riid, LPVOID *ppv)
{
    *ppv = NULL;
    if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IClassFactory))
    {
        *ppv = (LPVOID)iface;
        return S_OK;
    }
    return E_NOINTERFACE;
1561 1562
}

1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
static ULONG WINAPI StdMarshalCF_AddRef(LPCLASSFACTORY iface)
{
    return 2; /* non-heap based object */
}

static ULONG WINAPI StdMarshalCF_Release(LPCLASSFACTORY iface)
{
    return 1; /* non-heap based object */
}

static HRESULT WINAPI StdMarshalCF_CreateInstance(LPCLASSFACTORY iface,
    LPUNKNOWN pUnk, REFIID riid, LPVOID *ppv)
{
1576 1577 1578
  if (IsEqualIID(riid,&IID_IMarshal))
    return StdMarshalImpl_Construct(riid, ppv);

1579 1580 1581 1582
  FIXME("(%s), not supported.\n",debugstr_guid(riid));
  return E_NOINTERFACE;
}

1583 1584
static HRESULT WINAPI StdMarshalCF_LockServer(LPCLASSFACTORY iface, BOOL fLock)
{
1585 1586 1587 1588
    FIXME("(%d), stub!\n",fLock);
    return S_OK;
}

1589 1590 1591 1592 1593 1594 1595
static IClassFactoryVtbl StdMarshalCFVtbl =
{
    StdMarshalCF_QueryInterface,
    StdMarshalCF_AddRef,
    StdMarshalCF_Release,
    StdMarshalCF_CreateInstance,
    StdMarshalCF_LockServer
1596
};
1597
static IClassFactoryVtbl *StdMarshalCF = &StdMarshalCFVtbl;
1598

1599 1600 1601 1602
HRESULT MARSHAL_GetStandardMarshalCF(LPVOID *ppv)
{
    *ppv = &StdMarshalCF;
    return S_OK;
1603
}
1604 1605 1606 1607 1608 1609 1610

/***********************************************************************
 *		CoMarshalHresult	[OLE32.@]
 *
 * Marshals an HRESULT value into a stream.
 *
 * PARAMS
1611 1612
 *  pStm    [I] Stream that hresult will be marshalled into.
 *  hresult [I] HRESULT to be marshalled.
1613 1614 1615 1616 1617
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: A COM error code
 *
1618
 * SEE ALSO
1619 1620
 *  CoUnmarshalHresult().
 */
1621
HRESULT WINAPI CoMarshalHresult(LPSTREAM pStm, HRESULT hresult)
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
{
    return IStream_Write(pStm, &hresult, sizeof(hresult), NULL);
}

/***********************************************************************
 *		CoUnmarshalHresult	[OLE32.@]
 *
 * Unmarshals an HRESULT value from a stream.
 *
 * PARAMS
1632 1633
 *  pStm     [I] Stream that hresult will be unmarshalled from.
 *  phresult [I] Pointer to HRESULT where the value will be unmarshalled to.
1634 1635 1636 1637 1638
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: A COM error code
 *
1639
 * SEE ALSO
1640 1641
 *  CoMarshalHresult().
 */
1642
HRESULT WINAPI CoUnmarshalHresult(LPSTREAM pStm, HRESULT * phresult)
1643 1644 1645
{
    return IStream_Read(pStm, phresult, sizeof(*phresult), NULL);
}