marshal.c 67.1 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
 *
 * 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
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 22
 */

23
#include <stdarg.h>
24 25 26
#include <string.h>
#include <assert.h>

27 28
#define COBJMACROS

29
#include "windef.h"
30
#include "winbase.h"
31
#include "winuser.h"
32 33 34 35
#include "objbase.h"
#include "ole2.h"
#include "winerror.h"
#include "wine/unicode.h"
36

37 38
#include "compobj_private.h"

39
#include "wine/debug.h"
40

41
WINE_DEFAULT_DEBUG_CHANNEL(ole);
42

43 44
extern const CLSID CLSID_DfMarshal;

45
/* number of refs given out for normal marshaling */
46
#define NORMALEXTREFS 5
47

48 49 50

/* private flag indicating that the object was marshaled as table-weak */
#define SORFP_TABLEWEAK SORF_OXRES1
51 52
/* private flag indicating that the caller does not want to notify the stub
 * when the proxy disconnects or is destroyed */
53
#define SORFP_NOLIFETIMEMGMT SORF_OXRES2
54

55 56 57
/* imported object / proxy manager */
struct proxy_manager
{
58
  IMultiQI IMultiQI_iface;
59
  IMarshal IMarshal_iface;
60
  IClientSecurity IClientSecurity_iface;
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  struct apartment *parent; /* owning apartment (RO) */
  struct list entry;        /* entry in apartment (CS parent->cs) */
  OXID oxid;                /* object exported ID (RO) */
  OXID_INFO oxid_info;      /* string binding, ipid of rem unknown and other information (RO) */
  OID oid;                  /* object ID (RO) */
  struct list interfaces;   /* imported interfaces (CS cs) */
  LONG refs;                /* proxy reference count (LOCK) */
  CRITICAL_SECTION cs;      /* thread safety for this object and children */
  ULONG sorflags;           /* STDOBJREF flags (RO) */
  IRemUnknown *remunk;      /* proxy to IRemUnknown used for lifecycle management (CS cs) */
  HANDLE remoting_mutex;    /* mutex used for synchronizing access to IRemUnknown */
  MSHCTX dest_context;      /* context used for activating optimisations (LOCK) */
  void *dest_context_data;  /* reserved context value (LOCK) */
};

76 77 78 79 80
static inline struct proxy_manager *impl_from_IMultiQI( IMultiQI *iface )
{
    return CONTAINING_RECORD(iface, struct proxy_manager, IMultiQI_iface);
}

81 82
static inline struct proxy_manager *impl_from_IMarshal( IMarshal *iface )
{
83
    return CONTAINING_RECORD(iface, struct proxy_manager, IMarshal_iface);
84 85 86 87
}

static inline struct proxy_manager *impl_from_IClientSecurity( IClientSecurity *iface )
{
88
    return CONTAINING_RECORD(iface, struct proxy_manager, IClientSecurity_iface);
89 90
}

91 92
static HRESULT unmarshal_object(const STDOBJREF *stdobjref, APARTMENT *apt,
                                MSHCTX dest_context, void *dest_context_data,
93 94
                                REFIID riid, const OXID_INFO *oxid_info,
                                void **object);
95

96
/* Marshalling just passes a unique identifier to the remote client,
97 98 99 100 101
 * that makes it possible to find the passed interface again.
 *
 * So basically we need a set of values that make it unique.
 *
 * Note that the IUnknown_QI(ob,xiid,&ppv) always returns the SAME ppv value!
102
 *
103 104
 * A triple is used: OXID (apt id), OID (stub manager id),
 * IPID (interface ptr/stub id).
105 106 107 108
 *
 * 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
109 110
 */

111
static inline HRESULT get_facbuf_for_iid(REFIID riid, IPSFactoryBuffer **facbuf)
112 113 114
{
    HRESULT       hr;
    CLSID         clsid;
115

116 117
    hr = CoGetPSClsid(riid, &clsid);
    if (hr != S_OK)
118
        return hr;
119 120
    return CoGetClassObject(&clsid, CLSCTX_INPROC_SERVER | WINE_CLSCTX_DONT_HOST,
        NULL, &IID_IPSFactoryBuffer, (LPVOID*)facbuf);
121 122
}

123
/* marshals an object into a STDOBJREF structure */
124 125
HRESULT marshal_object(APARTMENT *apt, STDOBJREF *stdobjref, REFIID riid, IUnknown *object,
    DWORD dest_context, void *dest_context_data, MSHLFLAGS mshlflags)
126
{
127
    struct stub_manager *manager;
128
    struct ifstub       *ifstub;
129
    BOOL                 tablemarshal;
130
    HRESULT              hr;
131

132 133 134 135
    hr = apartment_getoxid(apt, &stdobjref->oxid);
    if (hr != S_OK)
        return hr;

136 137 138 139
    hr = apartment_createwindowifneeded(apt);
    if (hr != S_OK)
        return hr;

140 141 142
    if (!(manager = get_stub_manager_from_object(apt, object, TRUE)))
        return E_OUTOFMEMORY;

143 144 145
    stdobjref->flags = SORF_NULL;
    if (mshlflags & MSHLFLAGS_TABLEWEAK)
        stdobjref->flags |= SORFP_TABLEWEAK;
146
    if (mshlflags & MSHLFLAGS_NOPING)
147
        stdobjref->flags |= SORF_NOPING;
148
    stdobjref->oid = manager->oid;
149

150 151
    tablemarshal = ((mshlflags & MSHLFLAGS_TABLESTRONG) || (mshlflags & MSHLFLAGS_TABLEWEAK));

152 153
    /* make sure ifstub that we are creating is unique */
    ifstub = stub_manager_find_ifstub(manager, riid, mshlflags);
154 155
    if (!ifstub) {
        IRpcStubBuffer *stub = NULL;
156

157 158
        /* IUnknown doesn't require a stub buffer, because it never goes out on
         * the wire */
159
        if (!IsEqualIID(riid, &IID_IUnknown))
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        {
            IPSFactoryBuffer *psfb;

            hr = get_facbuf_for_iid(riid, &psfb);
            if (hr == S_OK) {
                hr = IPSFactoryBuffer_CreateStub(psfb, riid, manager->object, &stub);
                IPSFactoryBuffer_Release(psfb);
                if (hr != S_OK)
                    ERR("Failed to create an IRpcStubBuffer from IPSFactory for %s with error 0x%08x\n",
                        debugstr_guid(riid), hr);
            }else {
                ERR("couldn't get IPSFactory buffer for interface %s\n", debugstr_guid(riid));
                hr = E_NOINTERFACE;
            }

        }

        if (hr == S_OK) {
178
            ifstub = stub_manager_new_ifstub(manager, stub, riid, dest_context, dest_context_data, mshlflags);
179 180 181 182 183 184 185 186 187 188 189 190
            if (!ifstub)
                hr = E_OUTOFMEMORY;
        }
        if (stub) IRpcStubBuffer_Release(stub);

        if (hr != S_OK) {
            stub_manager_int_release(manager);
            /* destroy the stub manager if it has no ifstubs by releasing
             * zero external references */
            stub_manager_ext_release(manager, 0, FALSE, TRUE);
            return hr;
        }
191 192
    }

193
    if (!tablemarshal)
194 195
    {
        stdobjref->cPublicRefs = NORMALEXTREFS;
196
        stub_manager_ext_addref(manager, stdobjref->cPublicRefs, FALSE);
197 198 199 200 201
    }
    else
    {
        stdobjref->cPublicRefs = 0;
        if (mshlflags & MSHLFLAGS_TABLESTRONG)
202 203 204
            stub_manager_ext_addref(manager, 1, FALSE);
        else
            stub_manager_ext_addref(manager, 0, TRUE);
205
    }
206

207 208 209
    /* FIXME: check return value */
    RPC_RegisterInterface(riid);

210
    stdobjref->ipid = ifstub->ipid;
211 212

    stub_manager_int_release(manager);
213
    return S_OK;
214 215
}

216 217


218 219
/* Client-side identity of the server object */

220
static HRESULT proxy_manager_get_remunknown(struct proxy_manager * This, IRemUnknown **remunk);
221 222
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);
223
static HRESULT proxy_manager_query_local_interface(struct proxy_manager * This, REFIID riid, void ** ppv);
224

225
static HRESULT WINAPI ClientIdentity_QueryInterface(IMultiQI * iface, REFIID riid, void ** ppv)
226 227
{
    HRESULT hr;
228
    MULTI_QI mqi;
229 230 231

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

232 233
    mqi.pIID = riid;
    hr = IMultiQI_QueryMultipleInterfaces(iface, 1, &mqi);
234
    *ppv = mqi.pItf;
235

236
    return hr;
237 238
}

239
static ULONG WINAPI ClientIdentity_AddRef(IMultiQI *iface)
240
{
241
    struct proxy_manager *This = impl_from_IMultiQI(iface);
242
    TRACE("%p - before %d\n", iface, This->refs);
243 244 245
    return InterlockedIncrement(&This->refs);
}

246
static ULONG WINAPI ClientIdentity_Release(IMultiQI *iface)
247
{
248
    struct proxy_manager *This = impl_from_IMultiQI(iface);
249
    ULONG refs = InterlockedDecrement(&This->refs);
250
    TRACE("%p - after %d\n", iface, refs);
251 252 253 254 255
    if (!refs)
        proxy_manager_destroy(This);
    return refs;
}

256
static HRESULT WINAPI ClientIdentity_QueryMultipleInterfaces(IMultiQI *iface, ULONG cMQIs, MULTI_QI *pMQIs)
257
{
258
    struct proxy_manager *This = impl_from_IMultiQI(iface);
259 260 261 262 263 264 265 266
    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));

267
    TRACE("cMQIs: %d\n", cMQIs);
268 269 270 271 272

    /* 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++)
    {
273
        TRACE("iid[%d] = %s\n", i, debugstr_guid(pMQIs[i].pIID));
274 275 276 277 278 279 280 281 282 283 284
        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++;
        }
    }

285
    TRACE("%d interfaces not found locally\n", nonlocal_mqis);
286 287 288 289 290 291 292 293 294 295 296 297

    /* 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? */
298
        ipid = &LIST_ENTRY(list_head(&This->interfaces), struct ifproxy, entry)->stdobjref.ipid;
299 300 301 302

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

303
        if (SUCCEEDED(hr))
304 305 306
        {
            hr = IRemUnknown_RemQueryInterface(remunk, ipid, NORMALEXTREFS,
                                               nonlocal_mqis, iids, &qiresults);
307
            IRemUnknown_Release(remunk);
308
            if (FAILED(hr))
309
                ERR("IRemUnknown_RemQueryInterface failed with error 0x%08x\n", hr);
310 311 312 313 314 315 316 317 318 319 320 321
        }

        /* 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)
322
                    hrobj = unmarshal_object(&qiresults[i].std, COM_CurrentApt(),
323 324
                                             This->dest_context,
                                             This->dest_context_data,
325
                                             pMQIs[index].pIID, &This->oxid_info,
326 327 328 329 330 331 332 333 334 335 336 337 338 339
                                             (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);
    }

340
    TRACE("%d/%d successfully queried\n", successful_mqis, cMQIs);
341 342 343 344 345 346 347 348 349 350

    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 */
351 352
}

353
static const IMultiQIVtbl ClientIdentity_Vtbl =
354 355 356 357
{
    ClientIdentity_QueryInterface,
    ClientIdentity_AddRef,
    ClientIdentity_Release,
358
    ClientIdentity_QueryMultipleInterfaces
359 360
};

361 362 363 364 365 366 367
/* FIXME: remove these */
static HRESULT WINAPI StdMarshalImpl_GetUnmarshalClass(LPMARSHAL iface, REFIID riid, void* pv, DWORD dwDestContext, void* pvDestContext, DWORD mshlflags, CLSID* pCid);
static HRESULT WINAPI StdMarshalImpl_GetMarshalSizeMax(LPMARSHAL iface, REFIID riid, void* pv, DWORD dwDestContext, void* pvDestContext, DWORD mshlflags, DWORD* pSize);
static HRESULT WINAPI StdMarshalImpl_UnmarshalInterface(LPMARSHAL iface, IStream *pStm, REFIID riid, void **ppv);
static HRESULT WINAPI StdMarshalImpl_ReleaseMarshalData(LPMARSHAL iface, IStream *pStm);
static HRESULT WINAPI StdMarshalImpl_DisconnectObject(LPMARSHAL iface, DWORD dwReserved);

368 369
static HRESULT WINAPI Proxy_QueryInterface(IMarshal *iface, REFIID riid, void **ppvObject)
{
370
    struct proxy_manager *This = impl_from_IMarshal( iface );
371
    return IMultiQI_QueryInterface(&This->IMultiQI_iface, riid, ppvObject);
372 373 374 375
}

static ULONG WINAPI Proxy_AddRef(IMarshal *iface)
{
376
    struct proxy_manager *This = impl_from_IMarshal( iface );
377
    return IMultiQI_AddRef(&This->IMultiQI_iface);
378 379 380 381
}

static ULONG WINAPI Proxy_Release(IMarshal *iface)
{
382
    struct proxy_manager *This = impl_from_IMarshal( iface );
383
    return IMultiQI_Release(&This->IMultiQI_iface);
384 385 386 387 388 389
}

static HRESULT WINAPI Proxy_MarshalInterface(
    LPMARSHAL iface, IStream *pStm, REFIID riid, void* pv, DWORD dwDestContext,
    void* pvDestContext, DWORD mshlflags)
{
390
    struct proxy_manager *This = impl_from_IMarshal( iface );
391 392 393 394 395 396
    HRESULT hr;
    struct ifproxy *ifproxy;

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

    hr = proxy_manager_find_ifproxy(This, riid, &ifproxy);
397
    if (SUCCEEDED(hr))
398
    {
399
        STDOBJREF stdobjref = ifproxy->stdobjref;
400

401 402 403 404
        stdobjref.cPublicRefs = 0;

        if ((mshlflags != MSHLFLAGS_TABLEWEAK) &&
            (mshlflags != MSHLFLAGS_TABLESTRONG))
405
        {
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
            ULONG cPublicRefs = ifproxy->refs;
            ULONG cPublicRefsOld;
            /* optimization - share out proxy's public references if possible
             * instead of making new proxy do a roundtrip through the server */
            do
            {
                ULONG cPublicRefsNew;
                cPublicRefsOld = cPublicRefs;
                stdobjref.cPublicRefs = cPublicRefs / 2;
                cPublicRefsNew = cPublicRefs - stdobjref.cPublicRefs;
                cPublicRefs = InterlockedCompareExchange(
                    (LONG *)&ifproxy->refs, cPublicRefsNew, cPublicRefsOld);
            } while (cPublicRefs != cPublicRefsOld);
        }

        /* normal and table-strong marshaling need at least one reference */
        if (!stdobjref.cPublicRefs && (mshlflags != MSHLFLAGS_TABLEWEAK))
423 424 425 426 427 428 429 430
        {
            IRemUnknown *remunk;
            hr = proxy_manager_get_remunknown(This, &remunk);
            if (hr == S_OK)
            {
                HRESULT hrref = S_OK;
                REMINTERFACEREF rif;
                rif.ipid = ifproxy->stdobjref.ipid;
431
                rif.cPublicRefs = (mshlflags == MSHLFLAGS_TABLESTRONG) ? 1 : NORMALEXTREFS;
432 433
                rif.cPrivateRefs = 0;
                hr = IRemUnknown_RemAddRef(remunk, 1, &rif, &hrref);
434
                IRemUnknown_Release(remunk);
435
                if (hr == S_OK && hrref == S_OK)
436 437 438 439 440 441
                {
                    /* table-strong marshaling doesn't give the refs to the
                     * client that unmarshals the STDOBJREF */
                    if (mshlflags != MSHLFLAGS_TABLESTRONG)
                        stdobjref.cPublicRefs = rif.cPublicRefs;
                }
442
                else
443
                    ERR("IRemUnknown_RemAddRef returned with 0x%08x, hrref = 0x%08x\n", hr, hrref);
444 445
            }
        }
446

447 448
        if (SUCCEEDED(hr))
        {
449
            TRACE("writing stdobjref: flags = %04x cPublicRefs = %d oxid = %s oid = %s ipid = %s\n",
450 451 452 453 454 455
                stdobjref.flags, stdobjref.cPublicRefs,
                wine_dbgstr_longlong(stdobjref.oxid),
                wine_dbgstr_longlong(stdobjref.oid),
                debugstr_guid(&stdobjref.ipid));
            hr = IStream_Write(pStm, &stdobjref, sizeof(stdobjref), NULL);
        }
456
    }
457 458 459 460 461 462 463 464 465 466 467 468 469
    else
    {
        /* we don't have the interface already unmarshaled so we have to
         * request the object from the server */
        IRemUnknown *remunk;
        IPID *ipid;
        REMQIRESULT *qiresults = NULL;
        IID iid = *riid;

        /* 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)->stdobjref.ipid;
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
        /* 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,
                                               1, &iid, &qiresults);
            if (SUCCEEDED(hr))
            {
                hr = IStream_Write(pStm, &qiresults->std, sizeof(qiresults->std), NULL);
                if (FAILED(hr))
                {
                    REMINTERFACEREF rif;
                    rif.ipid = qiresults->std.ipid;
                    rif.cPublicRefs = qiresults->std.cPublicRefs;
                    rif.cPrivateRefs = 0;
                    IRemUnknown_RemRelease(remunk, 1, &rif);
                }
                CoTaskMemFree(qiresults);
            }
            else
492
                ERR("IRemUnknown_RemQueryInterface failed with error 0x%08x\n", hr);
493
            IRemUnknown_Release(remunk);
494 495
        }
    }
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

    return hr;
}

static const IMarshalVtbl ProxyMarshal_Vtbl =
{
    Proxy_QueryInterface,
    Proxy_AddRef,
    Proxy_Release,
    StdMarshalImpl_GetUnmarshalClass,
    StdMarshalImpl_GetMarshalSizeMax,
    Proxy_MarshalInterface,
    StdMarshalImpl_UnmarshalInterface,
    StdMarshalImpl_ReleaseMarshalData,
    StdMarshalImpl_DisconnectObject
};

513 514
static HRESULT WINAPI ProxyCliSec_QueryInterface(IClientSecurity *iface, REFIID riid, void **ppvObject)
{
515
    struct proxy_manager *This = impl_from_IClientSecurity( iface );
516
    return IMultiQI_QueryInterface(&This->IMultiQI_iface, riid, ppvObject);
517 518 519 520
}

static ULONG WINAPI ProxyCliSec_AddRef(IClientSecurity *iface)
{
521
    struct proxy_manager *This = impl_from_IClientSecurity( iface );
522
    return IMultiQI_AddRef(&This->IMultiQI_iface);
523 524 525 526
}

static ULONG WINAPI ProxyCliSec_Release(IClientSecurity *iface)
{
527
    struct proxy_manager *This = impl_from_IClientSecurity( iface );
528
    return IMultiQI_Release(&This->IMultiQI_iface);
529 530 531 532 533 534
}

static HRESULT WINAPI ProxyCliSec_QueryBlanket(IClientSecurity *iface,
                                               IUnknown *pProxy,
                                               DWORD *pAuthnSvc,
                                               DWORD *pAuthzSvc,
535
                                               OLECHAR **ppServerPrincName,
536 537 538 539 540 541
                                               DWORD *pAuthnLevel,
                                               DWORD *pImpLevel,
                                               void **pAuthInfo,
                                               DWORD *pCapabilities)
{
    FIXME("(%p, %p, %p, %p, %p, %p, %p, %p): stub\n", pProxy, pAuthnSvc,
542
          pAuthzSvc, ppServerPrincName, pAuthnLevel, pImpLevel, pAuthInfo,
543
          pCapabilities);
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

    if (pAuthnSvc)
        *pAuthnSvc = 0;
    if (pAuthzSvc)
        *pAuthzSvc = 0;
    if (ppServerPrincName)
        *ppServerPrincName = NULL;
    if (pAuthnLevel)
        *pAuthnLevel = RPC_C_AUTHN_LEVEL_DEFAULT;
    if (pImpLevel)
        *pImpLevel = RPC_C_IMP_LEVEL_DEFAULT;
    if (pAuthInfo)
        *pAuthInfo = NULL;
    if (pCapabilities)
        *pCapabilities = EOAC_NONE;

560 561 562 563 564 565 566 567 568 569 570
    return E_NOTIMPL;
}

static HRESULT WINAPI ProxyCliSec_SetBlanket(IClientSecurity *iface,
                                             IUnknown *pProxy, DWORD AuthnSvc,
                                             DWORD AuthzSvc,
                                             OLECHAR *pServerPrincName,
                                             DWORD AuthnLevel, DWORD ImpLevel,
                                             void *pAuthInfo,
                                             DWORD Capabilities)
{
571
    FIXME("(%p, %d, %d, %s, %d, %d, %p, 0x%x): stub\n", pProxy, AuthnSvc, AuthzSvc,
572
          pServerPrincName == COLE_DEFAULT_PRINCIPAL ? "<default principal>" : debugstr_w(pServerPrincName),
573
          AuthnLevel, ImpLevel, pAuthInfo, Capabilities);
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    return E_NOTIMPL;
}

static HRESULT WINAPI ProxyCliSec_CopyProxy(IClientSecurity *iface,
                                            IUnknown *pProxy, IUnknown **ppCopy)
{
    FIXME("(%p, %p): stub\n", pProxy, ppCopy);
    *ppCopy = NULL;
    return E_NOTIMPL;
}

static const IClientSecurityVtbl ProxyCliSec_Vtbl =
{
    ProxyCliSec_QueryInterface,
    ProxyCliSec_AddRef,
    ProxyCliSec_Release,
    ProxyCliSec_QueryBlanket,
    ProxyCliSec_SetBlanket,
    ProxyCliSec_CopyProxy
};

595 596
static HRESULT ifproxy_get_public_ref(struct ifproxy * This)
{
597
    HRESULT hr = S_OK;
598 599 600 601 602 603 604

    if (WAIT_OBJECT_0 != WaitForSingleObject(This->parent->remoting_mutex, INFINITE))
    {
        ERR("Wait failed for ifproxy %p\n", This);
        return E_UNEXPECTED;
    }

605 606
    if (This->refs == 0)
    {
607
        IRemUnknown *remunk = NULL;
608 609 610

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

611 612
        hr = proxy_manager_get_remunknown(This->parent, &remunk);
        if (hr == S_OK)
613
        {
614
            HRESULT hrref = S_OK;
615
            REMINTERFACEREF rif;
616
            rif.ipid = This->stdobjref.ipid;
617 618 619
            rif.cPublicRefs = NORMALEXTREFS;
            rif.cPrivateRefs = 0;
            hr = IRemUnknown_RemAddRef(remunk, 1, &rif, &hrref);
620
            IRemUnknown_Release(remunk);
621
            if (hr == S_OK && hrref == S_OK)
622
                InterlockedExchangeAdd((LONG *)&This->refs, NORMALEXTREFS);
623
            else
624
                ERR("IRemUnknown_RemAddRef returned with 0x%08x, hrref = 0x%08x\n", hr, hrref);
625 626
        }
    }
627
    ReleaseMutex(This->parent->remoting_mutex);
628

629
    return hr;
630 631
}

632 633
static HRESULT ifproxy_release_public_refs(struct ifproxy * This)
{
634
    HRESULT hr = S_OK;
635
    LONG public_refs;
636

637 638 639 640 641 642
    if (WAIT_OBJECT_0 != WaitForSingleObject(This->parent->remoting_mutex, INFINITE))
    {
        ERR("Wait failed for ifproxy %p\n", This);
        return E_UNEXPECTED;
    }

643 644
    public_refs = This->refs;
    if (public_refs > 0)
645
    {
646 647
        IRemUnknown *remunk = NULL;

648
        TRACE("releasing %d refs\n", public_refs);
649 650 651 652 653

        hr = proxy_manager_get_remunknown(This->parent, &remunk);
        if (hr == S_OK)
        {
            REMINTERFACEREF rif;
654
            rif.ipid = This->stdobjref.ipid;
655
            rif.cPublicRefs = public_refs;
656 657
            rif.cPrivateRefs = 0;
            hr = IRemUnknown_RemRelease(remunk, 1, &rif);
658
            IRemUnknown_Release(remunk);
659
            if (hr == S_OK)
660
                InterlockedExchangeAdd((LONG *)&This->refs, -public_refs);
661 662 663 664 665
            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));
666
            else
667
                ERR("IRemUnknown_RemRelease failed with error 0x%08x\n", hr);
668
        }
669
    }
670
    ReleaseMutex(This->parent->remoting_mutex);
671 672

    return hr;
673 674
}

675
/* should be called inside This->parent->cs critical section */
676 677
static void ifproxy_disconnect(struct ifproxy * This)
{
678
    ifproxy_release_public_refs(This);
679
    if (This->proxy) IRpcProxyBuffer_Disconnect(This->proxy);
680 681 682

    IRpcChannelBuffer_Release(This->chan);
    This->chan = NULL;
683 684
}

685
/* should be called in This->parent->cs critical section if it is an entry in parent's list */
686 687
static void ifproxy_destroy(struct ifproxy * This)
{
688 689
    TRACE("%p\n", This);

690 691 692 693 694 695
    /* 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);

696 697 698 699 700 701
    if (This->chan)
    {
        IRpcChannelBuffer_Release(This->chan);
        This->chan = NULL;
    }

702
    if (This->proxy) IRpcProxyBuffer_Release(This->proxy);
703

704 705 706
    HeapFree(GetProcessHeap(), 0, This);
}

707 708
static HRESULT proxy_manager_construct(
    APARTMENT * apt, ULONG sorflags, OXID oxid, OID oid,
709
    const OXID_INFO *oxid_info, struct proxy_manager ** proxy_manager)
710 711 712 713
{
    struct proxy_manager * This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
    if (!This) return E_OUTOFMEMORY;

714 715 716 717 718 719 720
    This->remoting_mutex = CreateMutexW(NULL, FALSE, NULL);
    if (!This->remoting_mutex)
    {
        HeapFree(GetProcessHeap(), 0, This);
        return HRESULT_FROM_WIN32(GetLastError());
    }

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    if (oxid_info)
    {
        This->oxid_info.dwPid = oxid_info->dwPid;
        This->oxid_info.dwTid = oxid_info->dwTid;
        This->oxid_info.ipidRemUnknown = oxid_info->ipidRemUnknown;
        This->oxid_info.dwAuthnHint = oxid_info->dwAuthnHint;
        This->oxid_info.psa = NULL /* FIXME: copy from oxid_info */;
    }
    else
    {
        HRESULT hr = RPC_ResolveOxid(oxid, &This->oxid_info);
        if (FAILED(hr))
        {
            CloseHandle(This->remoting_mutex);
            HeapFree(GetProcessHeap(), 0, This);
            return hr;
        }
    }

740
    This->IMultiQI_iface.lpVtbl = &ClientIdentity_Vtbl;
741
    This->IMarshal_iface.lpVtbl = &ProxyMarshal_Vtbl;
742
    This->IClientSecurity_iface.lpVtbl = &ProxyCliSec_Vtbl;
743 744 745 746 747

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

    InitializeCriticalSection(&This->cs);
748
    DEBUG_SET_CRITSEC_NAME(&This->cs, "proxy_manager");
749 750 751 752 753 754 755 756

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

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

757
    This->refs = 1;
758

759 760
    /* the DCOM draft specification states that the SORF_NOPING flag is
     * proxy manager specific, not ifproxy specific, so this implies that we
761
     * should store the STDOBJREF flags here in the proxy manager. */
762 763 764 765 766
    This->sorflags = sorflags;

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

767 768 769 770 771
    /* initialise these values to the weakest values and they will be
     * overwritten in proxy_manager_set_context */
    This->dest_context = MSHCTX_INPROC;
    This->dest_context_data = NULL;

772
    EnterCriticalSection(&apt->cs);
Robert Shearman's avatar
Robert Shearman committed
773
    /* FIXME: we are dependent on the ordering in here to make sure a proxy's
774
     * IRemUnknown proxy doesn't get destroyed before the regular proxy does
Robert Shearman's avatar
Robert Shearman committed
775 776 777 778
     * 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);
779 780
    LeaveCriticalSection(&apt->cs);

781 782 783
    TRACE("%p created for OXID %s, OID %s\n", This,
        wine_dbgstr_longlong(oxid), wine_dbgstr_longlong(oid));

784 785 786 787
    *proxy_manager = This;
    return S_OK;
}

788 789
static inline void proxy_manager_set_context(struct proxy_manager *This, MSHCTX dest_context, void *dest_context_data)
{
790
    MSHCTX old_dest_context;
791 792 793 794
    MSHCTX new_dest_context;

    do
    {
795
        old_dest_context = This->dest_context;
796 797 798 799 800 801 802 803 804 805 806 807 808 809 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
        new_dest_context = old_dest_context;
        /* "stronger" values overwrite "weaker" values. stronger values are
         * ones that disable more optimisations */
        switch (old_dest_context)
        {
        case MSHCTX_INPROC:
            new_dest_context = dest_context;
            break;
        case MSHCTX_CROSSCTX:
            switch (dest_context)
            {
            case MSHCTX_INPROC:
                break;
            default:
                new_dest_context = dest_context;
            }
            break;
        case MSHCTX_LOCAL:
            switch (dest_context)
            {
            case MSHCTX_INPROC:
            case MSHCTX_CROSSCTX:
                break;
            default:
                new_dest_context = dest_context;
            }
            break;
        case MSHCTX_NOSHAREDMEM:
            switch (dest_context)
            {
            case MSHCTX_DIFFERENTMACHINE:
                new_dest_context = dest_context;
                break;
            default:
                break;
            }
            break;
        default:
            break;
        }

        if (old_dest_context == new_dest_context) break;

839
        new_dest_context = InterlockedCompareExchange((PLONG)&This->dest_context, new_dest_context, old_dest_context);
840 841 842 843 844 845
    } while (new_dest_context != old_dest_context);

    if (dest_context_data)
        InterlockedExchangePointer(&This->dest_context_data, dest_context_data);
}

846 847 848 849 850 851 852 853 854 855
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))
    {
856 857
        *ppv = &This->IMultiQI_iface;
        IMultiQI_AddRef(&This->IMultiQI_iface);
858 859
        return S_OK;
    }
860 861
    if (IsEqualIID(riid, &IID_IMarshal))
    {
862 863
        *ppv = &This->IMarshal_iface;
        IMarshal_AddRef(&This->IMarshal_iface);
864 865 866 867
        return S_OK;
    }
    if (IsEqualIID(riid, &IID_IClientSecurity))
    {
868 869
        *ppv = &This->IClientSecurity_iface;
        IClientSecurity_AddRef(&This->IClientSecurity_iface);
870
        return S_OK;
871
    }
872 873 874 875 876 877 878 879 880 881 882 883 884

    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;
}

885
static HRESULT proxy_manager_create_ifproxy(
886
    struct proxy_manager * This, const STDOBJREF *stdobjref, REFIID riid,
887
    IRpcChannelBuffer * channel, struct ifproxy ** iif_out)
888 889 890 891 892 893 894 895
{
    HRESULT hr;
    IPSFactoryBuffer * psfb;
    struct ifproxy * ifproxy = HeapAlloc(GetProcessHeap(), 0, sizeof(*ifproxy));
    if (!ifproxy) return E_OUTOFMEMORY;

    list_init(&ifproxy->entry);

896
    ifproxy->parent = This;
897
    ifproxy->stdobjref = *stdobjref;
898
    ifproxy->iid = *riid;
899
    ifproxy->refs = 0;
900 901
    ifproxy->proxy = NULL;

902 903 904
    assert(channel);
    ifproxy->chan = channel; /* FIXME: we should take the binding strings and construct the channel in this function */

905
    /* the IUnknown interface is special because it does not have a
906 907
     * proxy associated with the ifproxy as we handle IUnknown ourselves */
    if (IsEqualIID(riid, &IID_IUnknown))
908
    {
909 910
        ifproxy->iface = &This->IMultiQI_iface;
        IMultiQI_AddRef(&This->IMultiQI_iface);
911
        hr = S_OK;
912
    }
913
    else
914 915 916 917 918 919 920 921
    {
        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 */
922
            hr = IPSFactoryBuffer_CreateProxy(psfb, (IUnknown*)&This->IMultiQI_iface, riid,
923 924 925
                                              &ifproxy->proxy, &ifproxy->iface);
            IPSFactoryBuffer_Release(psfb);
            if (hr != S_OK)
926
                ERR("Could not create proxy for interface %s, error 0x%08x\n",
927 928 929
                    debugstr_guid(riid), hr);
        }
        else
930
            ERR("Could not get IPSFactoryBuffer for interface %s, error 0x%08x\n",
931
                debugstr_guid(riid), hr);
932

933
        if (hr == S_OK)
934
            hr = IRpcProxyBuffer_Connect(ifproxy->proxy, ifproxy->chan);
935
    }
936 937 938 939 940 941 942 943

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

        *iif_out = ifproxy;
944
        TRACE("ifproxy %p created for IPID %s, interface %s with %u public refs\n",
945
              ifproxy, debugstr_guid(&stdobjref->ipid), debugstr_guid(riid), stdobjref->cPublicRefs);
946 947
    }
    else
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
        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;

978 979
    TRACE("oxid = %s, oid = %s\n", wine_dbgstr_longlong(This->oxid),
        wine_dbgstr_longlong(This->oid));
980

981 982
    EnterCriticalSection(&This->cs);

983 984 985 986
    /* SORFP_NOLIFTIMEMGMT proxies (for IRemUnknown) shouldn't be
     * disconnected - it won't do anything anyway, except cause
     * problems for other objects that depend on this proxy always
     * working */
987
    if (!(This->sorflags & SORFP_NOLIFETIMEMGMT))
988
    {
989 990 991 992 993
        LIST_FOR_EACH(cursor, &This->interfaces)
        {
            struct ifproxy * ifproxy = LIST_ENTRY(cursor, struct ifproxy, entry);
            ifproxy_disconnect(ifproxy);
        }
994 995 996 997 998 999 1000 1001
    }

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

    LeaveCriticalSection(&This->cs);
}

1002 1003 1004
static HRESULT proxy_manager_get_remunknown(struct proxy_manager * This, IRemUnknown **remunk)
{
    HRESULT hr = S_OK;
1005 1006
    struct apartment *apt;
    BOOL called_in_original_apt;
1007 1008 1009 1010 1011 1012

    /* 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;

1013 1014 1015 1016 1017 1018
    apt = COM_CurrentApt();
    if (!apt)
        return CO_E_NOTINITIALIZED;

    called_in_original_apt = This->parent && (This->parent->oxid == apt->oxid);

1019
    EnterCriticalSection(&This->cs);
1020 1021 1022 1023
    /* only return the cached object if called from the original apartment.
     * in future, we might want to make the IRemUnknown proxy callable from any
     * apartment to avoid these checks */
    if (This->remunk && called_in_original_apt)
1024
    {
1025 1026
        /* already created - return existing object */
        *remunk = This->remunk;
1027 1028
        IRemUnknown_AddRef(*remunk);
    }
1029
    else if (!This->parent)
1030
    {
1031
        /* disconnected - we can't create IRemUnknown */
1032
        *remunk = NULL;
1033
        hr = S_FALSE;
1034
    }
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    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;
1046 1047
        stdobjref.ipid = This->oxid_info.ipidRemUnknown;

1048
        /* do the unmarshal */
1049
        hr = unmarshal_object(&stdobjref, COM_CurrentApt(), This->dest_context,
1050
                              This->dest_context_data, &IID_IRemUnknown,
1051
                              &This->oxid_info, (void**)remunk);
1052
        if (hr == S_OK && called_in_original_apt)
1053 1054 1055 1056
        {
            This->remunk = *remunk;
            IRemUnknown_AddRef(This->remunk);
        }
1057 1058 1059
    }
    LeaveCriticalSection(&This->cs);

1060
    TRACE("got IRemUnknown* pointer %p, hr = 0x%08x\n", *remunk, hr);
1061 1062 1063 1064 1065 1066 1067 1068

    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. */
1069 1070 1071 1072
static void proxy_manager_destroy(struct proxy_manager * This)
{
    struct list * cursor;

1073 1074 1075
    TRACE("oxid = %s, oid = %s\n", wine_dbgstr_longlong(This->oxid),
        wine_dbgstr_longlong(This->oid));

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    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 */
1094
    while ((cursor = list_head(&This->interfaces)))
1095 1096 1097 1098 1099
    {
        struct ifproxy * ifproxy = LIST_ENTRY(cursor, struct ifproxy, entry);
        ifproxy_destroy(ifproxy);
    }

1100
    if (This->remunk) IRemUnknown_Release(This->remunk);
1101
    CoTaskMemFree(This->oxid_info.psa);
1102

1103
    DEBUG_CLEAR_CRITSEC_NAME(&This->cs);
1104 1105
    DeleteCriticalSection(&This->cs);

1106 1107
    CloseHandle(This->remoting_mutex);

1108 1109 1110
    HeapFree(GetProcessHeap(), 0, This);
}

1111 1112 1113
/* 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. */
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
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))
        {
1125 1126 1127
            /* be careful of a race with ClientIdentity_Release, which would
             * cause us to return a proxy which is in the process of being
             * destroyed */
1128
            if (IMultiQI_AddRef(&proxy->IMultiQI_iface) != 0)
1129 1130 1131 1132 1133
            {
                *proxy_found = proxy;
                found = TRUE;
                break;
            }
1134 1135 1136 1137 1138 1139
        }
    }
    LeaveCriticalSection(&apt->cs);
    return found;
}

1140
HRESULT apartment_disconnectproxies(struct apartment *apt)
1141 1142 1143 1144 1145 1146 1147 1148 1149
{
    struct list * cursor;

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

1150 1151 1152 1153
    return S_OK;
}

/********************** StdMarshal implementation ****************************/
1154 1155
typedef struct _StdMarshalImpl
{
1156 1157 1158 1159
    IMarshal IMarshal_iface;
    LONG     ref;
    DWORD    dest_context;
    void    *dest_context_data;
1160 1161
} StdMarshalImpl;

1162 1163 1164 1165 1166
static inline StdMarshalImpl *impl_from_StdMarshal(IMarshal *iface)
{
    return CONTAINING_RECORD(iface, StdMarshalImpl, IMarshal_iface);
}

1167
static HRESULT WINAPI 
1168
StdMarshalImpl_QueryInterface(IMarshal *iface, REFIID riid, void **ppv)
1169 1170 1171 1172 1173
{
    *ppv = NULL;
    if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IMarshal, riid))
    {
        *ppv = iface;
1174
        IMarshal_AddRef(iface);
1175 1176 1177 1178
        return S_OK;
    }
    FIXME("No interface for %s.\n", debugstr_guid(riid));
    return E_NOINTERFACE;
1179 1180
}

1181
static ULONG WINAPI
1182
StdMarshalImpl_AddRef(IMarshal *iface)
1183
{
1184
    StdMarshalImpl *This = impl_from_StdMarshal(iface);
1185
    return InterlockedIncrement(&This->ref);
1186 1187
}

1188
static ULONG WINAPI
1189
StdMarshalImpl_Release(IMarshal *iface)
1190
{
1191
    StdMarshalImpl *This = impl_from_StdMarshal(iface);
1192
    ULONG ref = InterlockedDecrement(&This->ref);
1193

1194 1195
    if (!ref) HeapFree(GetProcessHeap(),0,This);
    return ref;
1196 1197
}

1198
static HRESULT WINAPI
1199
StdMarshalImpl_GetUnmarshalClass(
1200
    IMarshal *iface, REFIID riid, void* pv, DWORD dwDestContext,
1201 1202 1203 1204
    void* pvDestContext, DWORD mshlflags, CLSID* pCid)
{
    *pCid = CLSID_DfMarshal;
    return S_OK;
1205 1206
}

1207
static HRESULT WINAPI
1208
StdMarshalImpl_GetMarshalSizeMax(
1209
    IMarshal *iface, REFIID riid, void* pv, DWORD dwDestContext,
1210
    void* pvDestContext, DWORD mshlflags, DWORD* pSize)
1211 1212 1213
{
    *pSize = sizeof(STDOBJREF);
    return S_OK;
1214 1215
}

1216
static HRESULT WINAPI
1217
StdMarshalImpl_MarshalInterface(
1218
    IMarshal *iface, IStream *pStm,REFIID riid, void* pv, DWORD dest_context,
1219
    void* dest_context_data, DWORD mshlflags)
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
{
    STDOBJREF             stdobjref;
    ULONG                 res;
    HRESULT               hres;
    APARTMENT            *apt = COM_CurrentApt();

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

    if (!apt)
    {
        ERR("Apartment not initialized\n");
        return CO_E_NOTINITIALIZED;
    }

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

1237
    hres = marshal_object(apt, &stdobjref, riid, pv, dest_context, dest_context_data, mshlflags);
1238
    if (hres != S_OK)
1239
    {
1240
        ERR("Failed to create ifstub, hres=0x%x\n", hres);
1241 1242
        return hres;
    }
1243

1244
    return IStream_Write(pStm, &stdobjref, sizeof(stdobjref), &res);
1245 1246
}

1247 1248 1249
/* helper for StdMarshalImpl_UnmarshalInterface - does the unmarshaling with
 * no questions asked about the rules surrounding same-apartment unmarshals
 * and table marshaling */
1250 1251
static HRESULT unmarshal_object(const STDOBJREF *stdobjref, APARTMENT *apt,
                                MSHCTX dest_context, void *dest_context_data,
1252 1253
                                REFIID riid, const OXID_INFO *oxid_info,
                                void **object)
1254 1255 1256 1257
{
    struct proxy_manager *proxy_manager = NULL;
    HRESULT hr = S_OK;

1258 1259
    assert(apt);

1260
    TRACE("stdobjref: flags = %04x cPublicRefs = %d oxid = %s oid = %s ipid = %s\n",
1261 1262 1263 1264 1265
        stdobjref->flags, stdobjref->cPublicRefs,
        wine_dbgstr_longlong(stdobjref->oxid),
        wine_dbgstr_longlong(stdobjref->oid),
        debugstr_guid(&stdobjref->ipid));

1266
    /* create a new proxy manager if one doesn't already exist for the
1267 1268 1269
     * object */
    if (!find_proxy_manager(apt, stdobjref->oxid, stdobjref->oid, &proxy_manager))
    {
1270
        hr = proxy_manager_construct(apt, stdobjref->flags,
1271
                                     stdobjref->oxid, stdobjref->oid, oxid_info,
1272
                                     &proxy_manager);
1273
    }
1274 1275
    else
        TRACE("proxy manager already created, using\n");
1276 1277 1278

    if (hr == S_OK)
    {
1279
        struct ifproxy * ifproxy;
1280 1281 1282

        proxy_manager_set_context(proxy_manager, dest_context, dest_context_data);

1283 1284
        hr = proxy_manager_find_ifproxy(proxy_manager, riid, &ifproxy);
        if (hr == E_NOINTERFACE)
1285 1286
        {
            IRpcChannelBuffer *chanbuf;
1287
            hr = RPC_CreateClientChannel(&stdobjref->oxid, &stdobjref->ipid,
1288
                                         &proxy_manager->oxid_info,
1289 1290 1291
                                         proxy_manager->dest_context,
                                         proxy_manager->dest_context_data,
                                         &chanbuf);
1292
            if (hr == S_OK)
1293 1294
                hr = proxy_manager_create_ifproxy(proxy_manager, stdobjref,
                                                  riid, chanbuf, &ifproxy);
1295
        }
1296 1297
        else
            IUnknown_AddRef((IUnknown *)ifproxy->iface);
1298

1299 1300 1301 1302 1303 1304 1305 1306 1307
        if (hr == S_OK)
        {
            InterlockedExchangeAdd((LONG *)&ifproxy->refs, stdobjref->cPublicRefs);
            /* get at least one external reference to the object to keep it alive */
            hr = ifproxy_get_public_ref(ifproxy);
            if (FAILED(hr))
                ifproxy_destroy(ifproxy);
        }

1308 1309
        if (hr == S_OK)
            *object = ifproxy->iface;
1310 1311 1312 1313
    }

    /* release our reference to the proxy manager - the client/apartment
     * will hold on to the remaining reference for us */
1314
    if (proxy_manager) IMultiQI_Release(&proxy_manager->IMultiQI_iface);
1315 1316 1317 1318

    return hr;
}

1319
static HRESULT WINAPI
1320
StdMarshalImpl_UnmarshalInterface(IMarshal *iface, IStream *pStm, REFIID riid, void **ppv)
1321
{
1322
    StdMarshalImpl *This = impl_from_StdMarshal(iface);
1323
    struct stub_manager *stubmgr = NULL;
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    STDOBJREF stdobjref;
    ULONG res;
    HRESULT hres;
    APARTMENT *apt = COM_CurrentApt();
    APARTMENT *stub_apt;
    OXID oxid;

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

    /* we need an apartment to unmarshal into */
    if (!apt)
    {
        ERR("Apartment not initialized\n");
        return CO_E_NOTINITIALIZED;
    }

    /* read STDOBJREF from wire */
    hres = IStream_Read(pStm, &stdobjref, sizeof(stdobjref), &res);
1342
    if (hres != S_OK) return STG_E_READFAULT;
1343 1344

    hres = apartment_getoxid(apt, &oxid);
1345
    if (hres != S_OK) return hres;
1346 1347 1348 1349 1350 1351

    /* check if we're marshalling back to ourselves */
    if ((oxid == stdobjref.oxid) && (stubmgr = get_stub_manager(apt, stdobjref.oid)))
    {
        TRACE("Unmarshalling object marshalled in same apartment for iid %s, "
              "returning original object %p\n", debugstr_guid(riid), stubmgr->object);
1352
    
1353
        hres = IUnknown_QueryInterface(stubmgr->object, riid, ppv);
1354
      
1355
        /* unref the ifstub. FIXME: only do this on success? */
1356
        if (!stub_manager_is_table_marshaled(stubmgr, &stdobjref.ipid))
1357
            stub_manager_ext_release(stubmgr, stdobjref.cPublicRefs, stdobjref.flags & SORFP_TABLEWEAK, FALSE);
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371

        stub_manager_int_release(stubmgr);
        return hres;
    }

    /* 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. */
    if ((stub_apt = apartment_findfromoxid(stdobjref.oxid, TRUE)))
    {
        if ((stubmgr = get_stub_manager(stub_apt, stdobjref.oid)))
        {
1372
            if (!stub_manager_notify_unmarshal(stubmgr, &stdobjref.ipid))
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
                hres = CO_E_OBJNOTCONNECTED;
        }
        else
        {
            WARN("Couldn't find object for OXID %s, OID %s, assuming disconnected\n",
                wine_dbgstr_longlong(stdobjref.oxid),
                wine_dbgstr_longlong(stdobjref.oid));
            hres = CO_E_OBJNOTCONNECTED;
        }
    }
    else
        TRACE("Treating unmarshal from OXID %s as inter-process\n",
1385
            wine_dbgstr_longlong(stdobjref.oxid));
1386

1387
    if (hres == S_OK)
1388 1389
        hres = unmarshal_object(&stdobjref, apt, This->dest_context,
                                This->dest_context_data, riid,
1390 1391 1392 1393
                                stubmgr ? &stubmgr->oxid_info : NULL, ppv);

    if (stubmgr) stub_manager_int_release(stubmgr);
    if (stub_apt) apartment_release(stub_apt);
1394

1395
    if (hres != S_OK) WARN("Failed with error 0x%08x\n", hres);
1396
    else TRACE("Successfully created proxy %p\n", *ppv);
1397

1398
    return hres;
1399 1400
}

1401
static HRESULT WINAPI
1402
StdMarshalImpl_ReleaseMarshalData(IMarshal *iface, IStream *pStm)
1403
{
1404
    STDOBJREF            stdobjref;
1405 1406 1407
    ULONG                res;
    HRESULT              hres;
    struct stub_manager *stubmgr;
1408
    APARTMENT           *apt;
1409

1410 1411
    TRACE("iface=%p, pStm=%p\n", iface, pStm);
    
1412
    hres = IStream_Read(pStm, &stdobjref, sizeof(stdobjref), &res);
1413
    if (hres != S_OK) return STG_E_READFAULT;
1414

1415 1416 1417 1418 1419
    TRACE("oxid = %s, oid = %s, ipid = %s\n",
        wine_dbgstr_longlong(stdobjref.oxid),
        wine_dbgstr_longlong(stdobjref.oid),
        wine_dbgstr_guid(&stdobjref.ipid));

1420
    if (!(apt = apartment_findfromoxid(stdobjref.oxid, TRUE)))
1421
    {
1422 1423
        WARN("Could not map OXID %s to apartment object\n",
            wine_dbgstr_longlong(stdobjref.oxid));
1424 1425 1426
        return RPC_E_INVALID_OBJREF;
    }

1427
    if (!(stubmgr = get_stub_manager(apt, stdobjref.oid)))
1428
    {
1429
        apartment_release(apt);
1430
        ERR("could not map object ID to stub manager, oxid=%s, oid=%s\n",
1431
            wine_dbgstr_longlong(stdobjref.oxid), wine_dbgstr_longlong(stdobjref.oid));
1432 1433
        return RPC_E_INVALID_OBJREF;
    }
1434

1435
    stub_manager_release_marshal_data(stubmgr, stdobjref.cPublicRefs, &stdobjref.ipid, stdobjref.flags & SORFP_TABLEWEAK);
1436 1437

    stub_manager_int_release(stubmgr);
1438
    apartment_release(apt);
1439

1440
    return S_OK;
1441 1442
}

1443
static HRESULT WINAPI
1444
StdMarshalImpl_DisconnectObject(IMarshal *iface, DWORD dwReserved)
1445 1446 1447
{
    FIXME("(), stub!\n");
    return S_OK;
1448 1449
}

1450
static const IMarshalVtbl StdMarshalVtbl =
1451
{
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    StdMarshalImpl_QueryInterface,
    StdMarshalImpl_AddRef,
    StdMarshalImpl_Release,
    StdMarshalImpl_GetUnmarshalClass,
    StdMarshalImpl_GetMarshalSizeMax,
    StdMarshalImpl_MarshalInterface,
    StdMarshalImpl_UnmarshalInterface,
    StdMarshalImpl_ReleaseMarshalData,
    StdMarshalImpl_DisconnectObject
};

1463
static HRESULT StdMarshalImpl_Construct(REFIID riid, DWORD dest_context, void *dest_context_data, void** ppvObject)
1464
{
1465 1466 1467
    HRESULT hr;

    StdMarshalImpl *pStdMarshal = HeapAlloc(GetProcessHeap(), 0, sizeof(StdMarshalImpl));
1468 1469
    if (!pStdMarshal)
        return E_OUTOFMEMORY;
1470

1471
    pStdMarshal->IMarshal_iface.lpVtbl = &StdMarshalVtbl;
1472
    pStdMarshal->ref = 0;
1473 1474 1475 1476 1477 1478 1479 1480
    pStdMarshal->dest_context = dest_context;
    pStdMarshal->dest_context_data = dest_context_data;

    hr = IMarshal_QueryInterface(&pStdMarshal->IMarshal_iface, riid, ppvObject);
    if (FAILED(hr))
        HeapFree(GetProcessHeap(), 0, pStdMarshal);

    return hr;
1481 1482
}

1483
/***********************************************************************
1484
 *		CoGetStandardMarshal	[OLE32.@]
1485
 *
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
 * 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.
1505
 */
1506 1507 1508 1509
HRESULT WINAPI CoGetStandardMarshal(REFIID riid, IUnknown *pUnk,
                                    DWORD dwDestContext, LPVOID pvDestContext,
                                    DWORD mshlflags, LPMARSHAL *ppMarshal)
{
1510 1511
    if (pUnk == NULL)
    {
1512
        FIXME("(%s,NULL,%x,%p,%x,%p), unimplemented yet.\n",
1513 1514 1515
            debugstr_guid(riid),dwDestContext,pvDestContext,mshlflags,ppMarshal);
        return E_NOTIMPL;
    }
1516
    TRACE("(%s,%p,%x,%p,%x,%p)\n",
1517
        debugstr_guid(riid),pUnk,dwDestContext,pvDestContext,mshlflags,ppMarshal);
1518

1519
    return StdMarshalImpl_Construct(&IID_IMarshal, dwDestContext, pvDestContext, (void**)ppMarshal);
1520 1521
}

1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
/***********************************************************************
 *		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;
1532

1533 1534 1535
    if (!pUnk)
        return E_POINTER;
    hr = IUnknown_QueryInterface(pUnk, &IID_IMarshal, (LPVOID*)pMarshal);
1536
    if (hr != S_OK)
1537 1538 1539
        hr = CoGetStandardMarshal(riid, pUnk, dwDestContext, pvDestContext,
                                  mshlFlags, pMarshal);
    return hr;
1540 1541
}

1542 1543 1544 1545 1546 1547 1548
/***********************************************************************
 *		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.
 */
1549
static HRESULT get_unmarshaler_from_stream(IStream *stream, IMarshal **marshal, IID *iid)
1550 1551 1552 1553 1554 1555 1556
{
    HRESULT hr;
    ULONG res;
    OBJREF objref;

    /* read common OBJREF header */
    hr = IStream_Read(stream, &objref, FIELD_OFFSET(OBJREF, u_objref), &res);
1557
    if (hr != S_OK || (res != FIELD_OFFSET(OBJREF, u_objref)))
1558
    {
1559
        ERR("Failed to read common OBJREF header, 0x%08x\n", hr);
1560 1561 1562 1563 1564 1565
        return STG_E_READFAULT;
    }

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

1570 1571
    if (iid) *iid = objref.iid;

1572 1573 1574 1575
    /* FIXME: handler marshaling */
    if (objref.flags & OBJREF_STANDARD)
    {
        TRACE("Using standard unmarshaling\n");
1576
        hr = StdMarshalImpl_Construct(&IID_IMarshal, 0, NULL, (LPVOID*)marshal);
1577 1578 1579
    }
    else if (objref.flags & OBJREF_CUSTOM)
    {
1580
        ULONG custom_header_size = FIELD_OFFSET(OBJREF, u_objref.u_custom.pData) - 
1581 1582 1583 1584 1585
                                   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);
1586
        if (hr != S_OK || (res != custom_header_size))
1587
        {
1588
            ERR("Failed to read OR_CUSTOM header, 0x%08x\n", hr);
1589 1590 1591 1592 1593 1594 1595 1596 1597
            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
    {
1598
        FIXME("Invalid or unimplemented marshaling type specified: %x\n",
1599 1600 1601 1602
            objref.flags);
        return RPC_E_INVALID_OBJREF;
    }

1603
    if (hr != S_OK)
1604
        ERR("Failed to create marshal, 0x%08x\n", hr);
1605 1606 1607 1608

    return hr;
}

1609
/***********************************************************************
1610
 *		CoGetMarshalSizeMax	[OLE32.@]
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
 *
 * 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().
1628
 */
1629 1630 1631 1632 1633 1634 1635 1636
HRESULT WINAPI CoGetMarshalSizeMax(ULONG *pulSize, REFIID riid, IUnknown *pUnk,
                                   DWORD dwDestContext, void *pvDestContext,
                                   DWORD mshlFlags)
{
    HRESULT hr;
    LPMARSHAL pMarshal;
    CLSID marshaler_clsid;

1637
    hr = get_marshaler(riid, pUnk, dwDestContext, pvDestContext, mshlFlags, &pMarshal);
1638
    if (hr != S_OK)
1639 1640 1641 1642
        return hr;

    hr = IMarshal_GetUnmarshalClass(pMarshal, riid, pUnk, dwDestContext,
                                    pvDestContext, mshlFlags, &marshaler_clsid);
1643
    if (hr != S_OK)
1644
    {
1645
        ERR("IMarshal::GetUnmarshalClass failed, 0x%08x\n", hr);
1646 1647 1648
        IMarshal_Release(pMarshal);
        return hr;
    }
1649

1650 1651
    hr = IMarshal_GetMarshalSizeMax(pMarshal, riid, pUnk, dwDestContext,
                                    pvDestContext, mshlFlags, pulSize);
1652 1653 1654 1655 1656 1657 1658
    if (IsEqualCLSID(&marshaler_clsid, &CLSID_DfMarshal))
        /* add on the size of the common header */
        *pulSize += FIELD_OFFSET(OBJREF, u_objref);
    else
        /* custom marshaling: add on the size of the whole OBJREF structure
         * like native does */
        *pulSize += sizeof(OBJREF);
1659 1660 1661

    IMarshal_Release(pMarshal);
    return hr;
1662 1663 1664
}


1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
static void dump_MSHLFLAGS(MSHLFLAGS flags)
{
    if (flags & MSHLFLAGS_TABLESTRONG)
        TRACE(" MSHLFLAGS_TABLESTRONG");
    if (flags & MSHLFLAGS_TABLEWEAK)
        TRACE(" MSHLFLAGS_TABLEWEAK");
    if (!(flags & (MSHLFLAGS_TABLESTRONG|MSHLFLAGS_TABLEWEAK)))
        TRACE(" MSHLFLAGS_NORMAL");
    if (flags & MSHLFLAGS_NOPING)
        TRACE(" MSHLFLAGS_NOPING");
}

1677
/***********************************************************************
1678
 *		CoMarshalInterface	[OLE32.@]
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
 *
 * 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().
1708
 */
1709 1710 1711 1712 1713 1714 1715 1716 1717
HRESULT WINAPI CoMarshalInterface(IStream *pStream, REFIID riid, IUnknown *pUnk,
                                  DWORD dwDestContext, void *pvDestContext,
                                  DWORD mshlFlags)
{
    HRESULT	hr;
    CLSID marshaler_clsid;
    OBJREF objref;
    LPMARSHAL pMarshal;

1718
    TRACE("(%p, %s, %p, %x, %p, ", pStream, debugstr_guid(riid), pUnk,
1719 1720 1721
        dwDestContext, pvDestContext);
    dump_MSHLFLAGS(mshlFlags);
    TRACE(")\n");
1722

1723
    if (!pUnk || !pStream)
1724 1725 1726 1727 1728 1729
        return E_INVALIDARG;

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

    /* get the marshaler for the specified interface */
1730
    hr = get_marshaler(riid, pUnk, dwDestContext, pvDestContext, mshlFlags, &pMarshal);
1731
    if (hr != S_OK)
1732
    {
1733
        ERR("Failed to get marshaller, 0x%08x\n", hr);
1734 1735
        return hr;
    }
1736

1737 1738
    hr = IMarshal_GetUnmarshalClass(pMarshal, riid, pUnk, dwDestContext,
                                    pvDestContext, mshlFlags, &marshaler_clsid);
1739
    if (hr != S_OK)
1740
    {
1741
        ERR("IMarshal::GetUnmarshalClass failed, 0x%08x\n", hr);
1742 1743
        goto cleanup;
    }
1744

1745 1746 1747 1748 1749
    /* FIXME: implement handler marshaling too */
    if (IsEqualCLSID(&marshaler_clsid, &CLSID_DfMarshal))
    {
        TRACE("Using standard marshaling\n");
        objref.flags = OBJREF_STANDARD;
1750 1751 1752

        /* write the common OBJREF header to the stream */
        hr = IStream_Write(pStream, &objref, FIELD_OFFSET(OBJREF, u_objref), NULL);
1753
        if (hr != S_OK)
1754
        {
1755
            ERR("Failed to write OBJREF header to stream, 0x%08x\n", hr);
1756 1757
            goto cleanup;
        }
1758 1759 1760 1761 1762
    }
    else
    {
        TRACE("Using custom marshaling\n");
        objref.flags = OBJREF_CUSTOM;
1763 1764 1765 1766 1767 1768
        objref.u_objref.u_custom.clsid = marshaler_clsid;
        objref.u_objref.u_custom.cbExtension = 0;
        objref.u_objref.u_custom.size = 0;
        hr = IMarshal_GetMarshalSizeMax(pMarshal, riid, pUnk, dwDestContext,
                                        pvDestContext, mshlFlags,
                                        &objref.u_objref.u_custom.size);
1769
        if (hr != S_OK)
1770
        {
1771
            ERR("Failed to get max size of marshal data, error 0x%08x\n", hr);
1772 1773 1774 1775 1776
            goto cleanup;
        }
        /* write constant sized common header and OR_CUSTOM data into stream */
        hr = IStream_Write(pStream, &objref,
                          FIELD_OFFSET(OBJREF, u_objref.u_custom.pData), NULL);
1777
        if (hr != S_OK)
1778
        {
1779
            ERR("Failed to write OR_CUSTOM header to stream with 0x%08x\n", hr);
1780 1781 1782
            goto cleanup;
        }
    }
1783

1784
    TRACE("Calling IMarshal::MarshalInterface\n");
1785
    /* call helper object to do the actual marshaling */
1786
    hr = IMarshal_MarshalInterface(pMarshal, pStream, riid, pUnk, dwDestContext,
1787
                                   pvDestContext, mshlFlags);
1788

1789
    if (hr != S_OK)
1790
    {
1791
        ERR("Failed to marshal the interface %s, %x\n", debugstr_guid(riid), hr);
1792 1793 1794 1795 1796
        goto cleanup;
    }

cleanup:
    IMarshal_Release(pMarshal);
1797

1798
    TRACE("completed with hr 0x%08x\n", hr);
1799
    
1800 1801
    return hr;
}
1802 1803

/***********************************************************************
1804
 *		CoUnmarshalInterface	[OLE32.@]
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
 *
 * 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().
1822
 */
1823 1824
HRESULT WINAPI CoUnmarshalInterface(IStream *pStream, REFIID riid, LPVOID *ppv)
{
1825
    HRESULT hr;
1826
    LPMARSHAL pMarshal;
1827 1828
    IID iid;
    IUnknown *object;
1829

1830
    TRACE("(%p, %s, %p)\n", pStream, debugstr_guid(riid), ppv);
1831

1832 1833 1834
    if (!pStream || !ppv)
        return E_INVALIDARG;

1835
    hr = get_unmarshaler_from_stream(pStream, &pMarshal, &iid);
1836 1837 1838 1839
    if (hr != S_OK)
        return hr;

    /* call the helper object to do the actual unmarshaling */
1840
    hr = IMarshal_UnmarshalInterface(pMarshal, pStream, &iid, (LPVOID*)&object);
1841
    if (hr != S_OK)
1842
        ERR("IMarshal::UnmarshalInterface failed, 0x%08x\n", hr);
1843

1844 1845
    if (hr == S_OK)
    {
1846 1847
        /* IID_NULL means use the interface ID of the marshaled object */
        if (!IsEqualIID(riid, &IID_NULL) && !IsEqualIID(riid, &iid))
1848 1849
        {
            TRACE("requested interface != marshalled interface, additional QI needed\n");
1850
            hr = IUnknown_QueryInterface(object, riid, ppv);
1851
            if (hr != S_OK)
1852
                ERR("Couldn't query for interface %s, hr = 0x%08x\n",
1853 1854 1855 1856 1857 1858 1859
                    debugstr_guid(riid), hr);
            IUnknown_Release(object);
        }
        else
        {
            *ppv = object;
        }
1860 1861
    }

1862
    IMarshal_Release(pMarshal);
1863

1864
    TRACE("completed with hr 0x%x\n", hr);
1865
    
1866
    return hr;
1867 1868
}

1869 1870
/***********************************************************************
 *		CoReleaseMarshalData	[OLE32.@]
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
 *
 * 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().
1891
 */
1892 1893 1894 1895
HRESULT WINAPI CoReleaseMarshalData(IStream *pStream)
{
    HRESULT	hr;
    LPMARSHAL pMarshal;
1896

1897
    TRACE("(%p)\n", pStream);
1898

1899
    hr = get_unmarshaler_from_stream(pStream, &pMarshal, NULL);
1900 1901 1902 1903 1904
    if (hr != S_OK)
        return hr;

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

    IMarshal_Release(pMarshal);
    return hr;
1910 1911 1912
}


1913
/***********************************************************************
1914
 *		CoMarshalInterThreadInterfaceInStream	[OLE32.@]
1915
 *
1916 1917 1918 1919 1920
 * 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.
Huw Davies's avatar
Huw Davies committed
1921
 *  ppStm [O] Pointer to IStream object that is created and then used to store the marshalled interface.
1922 1923 1924 1925 1926
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: E_OUTOFMEMORY and other COM error codes
 *
1927
 * SEE ALSO
1928
 *   CoMarshalInterface(), CoUnmarshalInterface() and CoGetInterfaceAndReleaseStream()
1929
 */
1930 1931
HRESULT WINAPI CoMarshalInterThreadInterfaceInStream(
    REFIID riid, LPUNKNOWN pUnk, LPSTREAM * ppStm)
1932 1933 1934 1935
{
    ULARGE_INTEGER	xpos;
    LARGE_INTEGER		seekto;
    HRESULT		hres;
1936

1937 1938
    TRACE("(%s, %p, %p)\n",debugstr_guid(riid), pUnk, ppStm);

1939
    hres = CreateStreamOnHGlobal(NULL, TRUE, ppStm);
1940 1941 1942
    if (FAILED(hres)) return hres;
    hres = CoMarshalInterface(*ppStm, riid, pUnk, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);

1943 1944 1945
    if (SUCCEEDED(hres))
    {
        memset(&seekto, 0, sizeof(seekto));
1946
        IStream_Seek(*ppStm, seekto, STREAM_SEEK_SET, &xpos);
1947 1948 1949 1950 1951 1952
    }
    else
    {
        IStream_Release(*ppStm);
        *ppStm = NULL;
    }
1953 1954

    return hres;
1955 1956 1957
}

/***********************************************************************
1958
 *		CoGetInterfaceAndReleaseStream	[OLE32.@]
1959
 *
Huw Davies's avatar
Huw Davies committed
1960
 * Unmarshalls an interface from a stream and then releases the stream.
1961 1962
 *
 * PARAMS
Huw Davies's avatar
Huw Davies committed
1963
 *  pStm [I] Stream that contains the marshalled interface.
1964 1965 1966 1967 1968 1969 1970
 *  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
 *
1971
 * SEE ALSO
Huw Davies's avatar
Huw Davies committed
1972
 *  CoMarshalInterThreadInterfaceInStream() and CoUnmarshalInterface()
1973
 */
1974 1975
HRESULT WINAPI CoGetInterfaceAndReleaseStream(LPSTREAM pStm, REFIID riid,
                                              LPVOID *ppv)
1976 1977
{
    HRESULT hres;
1978

1979 1980
    TRACE("(%p, %s, %p)\n", pStm, debugstr_guid(riid), ppv);

1981
    if(!pStm) return E_INVALIDARG;
1982 1983 1984
    hres = CoUnmarshalInterface(pStm, riid, ppv);
    IStream_Release(pStm);
    return hres;
1985 1986
}

1987 1988 1989 1990 1991 1992
static HRESULT WINAPI StdMarshalCF_QueryInterface(LPCLASSFACTORY iface,
                                                  REFIID riid, LPVOID *ppv)
{
    *ppv = NULL;
    if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IClassFactory))
    {
1993
        *ppv = iface;
1994 1995 1996
        return S_OK;
    }
    return E_NOINTERFACE;
1997 1998
}

1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
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)
{
2012
    if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IMarshal))
2013
        return StdMarshalImpl_Construct(riid, 0, NULL, ppv);
2014

2015 2016
    FIXME("(%s), not supported.\n",debugstr_guid(riid));
    return E_NOINTERFACE;
2017 2018
}

2019 2020
static HRESULT WINAPI StdMarshalCF_LockServer(LPCLASSFACTORY iface, BOOL fLock)
{
2021 2022 2023 2024
    FIXME("(%d), stub!\n",fLock);
    return S_OK;
}

2025
static const IClassFactoryVtbl StdMarshalCFVtbl =
2026 2027 2028 2029 2030 2031
{
    StdMarshalCF_QueryInterface,
    StdMarshalCF_AddRef,
    StdMarshalCF_Release,
    StdMarshalCF_CreateInstance,
    StdMarshalCF_LockServer
2032
};
2033
static const IClassFactoryVtbl *StdMarshalCF = &StdMarshalCFVtbl;
2034

2035 2036 2037 2038
HRESULT MARSHAL_GetStandardMarshalCF(LPVOID *ppv)
{
    *ppv = &StdMarshalCF;
    return S_OK;
2039
}
2040 2041 2042 2043 2044 2045 2046

/***********************************************************************
 *		CoMarshalHresult	[OLE32.@]
 *
 * Marshals an HRESULT value into a stream.
 *
 * PARAMS
2047 2048
 *  pStm    [I] Stream that hresult will be marshalled into.
 *  hresult [I] HRESULT to be marshalled.
2049 2050 2051 2052 2053
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: A COM error code
 *
2054
 * SEE ALSO
2055 2056
 *  CoUnmarshalHresult().
 */
2057
HRESULT WINAPI CoMarshalHresult(LPSTREAM pStm, HRESULT hresult)
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
{
    return IStream_Write(pStm, &hresult, sizeof(hresult), NULL);
}

/***********************************************************************
 *		CoUnmarshalHresult	[OLE32.@]
 *
 * Unmarshals an HRESULT value from a stream.
 *
 * PARAMS
2068 2069
 *  pStm     [I] Stream that hresult will be unmarshalled from.
 *  phresult [I] Pointer to HRESULT where the value will be unmarshalled to.
2070 2071 2072 2073 2074
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: A COM error code
 *
2075
 * SEE ALSO
2076 2077
 *  CoMarshalHresult().
 */
2078
HRESULT WINAPI CoUnmarshalHresult(LPSTREAM pStm, HRESULT * phresult)
2079 2080 2081
{
    return IStream_Read(pStm, phresult, sizeof(*phresult), NULL);
}