ole32: Use an iface instead of a vtbl pointer in RemUnknown.
[wine] / dlls / ole32 / stubmanager.c
1 /*
2  * A stub manager is an object that controls interface stubs. It is
3  * identified by an OID (object identifier) and acts as the network
4  * identity of the object. There can be many stub managers in a
5  * process or apartment.
6  *
7  * Copyright 2002 Marcus Meissner
8  * Copyright 2004 Mike Hearn for CodeWeavers
9  * Copyright 2004 Robert Shearman (for CodeWeavers)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #define COBJMACROS
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
29
30 #include <assert.h>
31 #include <stdarg.h>
32 #include <limits.h>
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winuser.h"
37 #include "objbase.h"
38 #include "rpc.h"
39
40 #include "wine/debug.h"
41 #include "compobj_private.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(ole);
44
45
46 /* generates an ipid in the following format (similar to native version):
47  * Data1 = apartment-local ipid counter
48  * Data2 = apartment creator thread ID
49  * Data3 = process ID
50  * Data4 = random value
51  */
52 static inline HRESULT generate_ipid(struct stub_manager *m, IPID *ipid)
53 {
54     HRESULT hr;
55     hr = UuidCreate(ipid);
56     if (FAILED(hr))
57     {
58         ERR("couldn't create IPID for stub manager %p\n", m);
59         UuidCreateNil(ipid);
60         return hr;
61     }
62
63     ipid->Data1 = InterlockedIncrement(&m->apt->ipidc);
64     ipid->Data2 = (USHORT)m->apt->tid;
65     ipid->Data3 = (USHORT)GetCurrentProcessId();
66     return S_OK;
67 }
68
69 /* registers a new interface stub COM object with the stub manager and returns registration record */
70 struct ifstub *stub_manager_new_ifstub(struct stub_manager *m, IRpcStubBuffer *sb, IUnknown *iptr, REFIID iid, MSHLFLAGS flags)
71 {
72     struct ifstub *stub;
73     HRESULT hr;
74
75     TRACE("oid=%s, stubbuffer=%p, iptr=%p, iid=%s\n",
76           wine_dbgstr_longlong(m->oid), sb, iptr, debugstr_guid(iid));
77
78     stub = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct ifstub));
79     if (!stub) return NULL;
80
81     hr = RPC_CreateServerChannel(&stub->chan);
82     if (hr != S_OK)
83     {
84         HeapFree(GetProcessHeap(), 0, stub);
85         return NULL;
86     }
87
88     stub->stubbuffer = sb;
89     if (sb) IRpcStubBuffer_AddRef(sb);
90
91     IUnknown_AddRef(iptr);
92     stub->iface = iptr;
93     stub->flags = flags;
94     stub->iid = *iid;
95
96     /* FIXME: find a cleaner way of identifying that we are creating an ifstub
97      * for the remunknown interface */
98     if (flags & MSHLFLAGSP_REMUNKNOWN)
99         stub->ipid = m->oxid_info.ipidRemUnknown;
100     else
101         generate_ipid(m, &stub->ipid);
102
103     EnterCriticalSection(&m->lock);
104     list_add_head(&m->ifstubs, &stub->entry);
105     /* every normal marshal is counted so we don't allow more than we should */
106     if (flags & MSHLFLAGS_NORMAL) m->norm_refs++;
107     LeaveCriticalSection(&m->lock);
108
109     TRACE("ifstub %p created with ipid %s\n", stub, debugstr_guid(&stub->ipid));
110
111     return stub;
112 }
113
114 static void stub_manager_delete_ifstub(struct stub_manager *m, struct ifstub *ifstub)
115 {
116     TRACE("m=%p, m->oid=%s, ipid=%s\n", m, wine_dbgstr_longlong(m->oid), debugstr_guid(&ifstub->ipid));
117
118     list_remove(&ifstub->entry);
119
120     RPC_UnregisterInterface(&ifstub->iid);
121
122     if (ifstub->stubbuffer) IUnknown_Release(ifstub->stubbuffer);
123     IUnknown_Release(ifstub->iface);
124     IRpcChannelBuffer_Release(ifstub->chan);
125
126     HeapFree(GetProcessHeap(), 0, ifstub);
127 }
128
129 static struct ifstub *stub_manager_ipid_to_ifstub(struct stub_manager *m, const IPID *ipid)
130 {
131     struct list    *cursor;
132     struct ifstub  *result = NULL;
133
134     EnterCriticalSection(&m->lock);
135     LIST_FOR_EACH( cursor, &m->ifstubs )
136     {
137         struct ifstub *ifstub = LIST_ENTRY( cursor, struct ifstub, entry );
138
139         if (IsEqualGUID(ipid, &ifstub->ipid))
140         {
141             result = ifstub;
142             break;
143         }
144     }
145     LeaveCriticalSection(&m->lock);
146
147     return result;
148 }
149
150 struct ifstub *stub_manager_find_ifstub(struct stub_manager *m, REFIID iid, MSHLFLAGS flags)
151 {
152     struct ifstub  *result = NULL;
153     struct ifstub  *ifstub;
154
155     EnterCriticalSection(&m->lock);
156     LIST_FOR_EACH_ENTRY( ifstub, &m->ifstubs, struct ifstub, entry )
157     {
158         if (IsEqualIID(iid, &ifstub->iid) && (ifstub->flags == flags))
159         {
160             result = ifstub;
161             break;
162         }
163     }
164     LeaveCriticalSection(&m->lock);
165
166     return result;
167 }
168
169 /* creates a new stub manager and adds it into the apartment. caller must
170  * release stub manager when it is no longer required. the apartment and
171  * external refs together take one implicit ref */
172 struct stub_manager *new_stub_manager(APARTMENT *apt, IUnknown *object)
173 {
174     struct stub_manager *sm;
175
176     assert( apt );
177     
178     sm = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct stub_manager));
179     if (!sm) return NULL;
180
181     list_init(&sm->ifstubs);
182
183     InitializeCriticalSection(&sm->lock);
184     DEBUG_SET_CRITSEC_NAME(&sm->lock, "stub_manager");
185
186     IUnknown_AddRef(object);
187     sm->object = object;
188     sm->apt    = apt;
189
190     /* start off with 2 references because the stub is in the apartment
191      * and the caller will also hold a reference */
192     sm->refs   = 2;
193     sm->weakrefs = 0;
194
195     sm->oxid_info.dwPid = GetCurrentProcessId();
196     sm->oxid_info.dwTid = GetCurrentThreadId();
197     /*
198      * FIXME: this is a hack for marshalling IRemUnknown. In real
199      * DCOM, the IPID of the IRemUnknown interface is generated like
200      * any other and passed to the OXID resolver which then returns it
201      * when queried. We don't have an OXID resolver yet so instead we
202      * use a magic IPID reserved for IRemUnknown.
203      */
204     sm->oxid_info.ipidRemUnknown.Data1 = 0xffffffff;
205     sm->oxid_info.ipidRemUnknown.Data2 = 0xffff;
206     sm->oxid_info.ipidRemUnknown.Data3 = 0xffff;
207     assert(sizeof(sm->oxid_info.ipidRemUnknown.Data4) == sizeof(apt->oxid));
208     memcpy(sm->oxid_info.ipidRemUnknown.Data4, &apt->oxid, sizeof(OXID));
209     sm->oxid_info.dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
210     sm->oxid_info.psa = NULL /* FIXME */;
211
212     /* Yes, that's right, this starts at zero. that's zero EXTERNAL
213      * refs, i.e., nobody has unmarshalled anything yet. We can't have
214      * negative refs because the stub manager cannot be explicitly
215      * killed, it has to die by somebody unmarshalling then releasing
216      * the marshalled ifptr.
217      */
218     sm->extrefs = 0;
219
220     EnterCriticalSection(&apt->cs);
221     sm->oid = apt->oidc++;
222     list_add_head(&apt->stubmgrs, &sm->entry);
223     LeaveCriticalSection(&apt->cs);
224
225     TRACE("Created new stub manager (oid=%s) at %p for object with IUnknown %p\n", wine_dbgstr_longlong(sm->oid), sm, object);
226     
227     return sm;
228 }
229
230 /* caller must remove stub manager from apartment prior to calling this function */
231 static void stub_manager_delete(struct stub_manager *m)
232 {
233     struct list *cursor;
234
235     TRACE("destroying %p (oid=%s)\n", m, wine_dbgstr_longlong(m->oid));
236
237     /* release every ifstub */
238     while ((cursor = list_head(&m->ifstubs)))
239     {
240         struct ifstub *ifstub = LIST_ENTRY(cursor, struct ifstub, entry);
241         stub_manager_delete_ifstub(m, ifstub);
242     }
243
244     CoTaskMemFree(m->oxid_info.psa);
245     IUnknown_Release(m->object);
246
247     DEBUG_CLEAR_CRITSEC_NAME(&m->lock);
248     DeleteCriticalSection(&m->lock);
249
250     HeapFree(GetProcessHeap(), 0, m);
251 }
252
253 /* increments the internal refcount */
254 static ULONG stub_manager_int_addref(struct stub_manager *This)
255 {
256     ULONG refs;
257
258     EnterCriticalSection(&This->apt->cs);
259     refs = ++This->refs;
260     LeaveCriticalSection(&This->apt->cs);
261
262     TRACE("before %d\n", refs - 1);
263
264     return refs;
265 }
266
267 /* decrements the internal refcount */
268 ULONG stub_manager_int_release(struct stub_manager *This)
269 {
270     ULONG refs;
271     APARTMENT *apt = This->apt;
272
273     EnterCriticalSection(&apt->cs);
274     refs = --This->refs;
275
276     TRACE("after %d\n", refs);
277
278     /* remove from apartment so no other thread can access it... */
279     if (!refs)
280         list_remove(&This->entry);
281
282     LeaveCriticalSection(&apt->cs);
283
284     /* ... so now we can delete it without being inside the apartment critsec */
285     if (!refs)
286         stub_manager_delete(This);
287
288     return refs;
289 }
290
291 /* gets the stub manager associated with an object - caller must have
292  * a reference to the apartment while a reference to the stub manager is held.
293  * it must also call release on the stub manager when it is no longer needed */
294 struct stub_manager *get_stub_manager_from_object(APARTMENT *apt, void *object)
295 {
296     struct stub_manager *result = NULL;
297     struct list         *cursor;
298
299     EnterCriticalSection(&apt->cs);
300     LIST_FOR_EACH( cursor, &apt->stubmgrs )
301     {
302         struct stub_manager *m = LIST_ENTRY( cursor, struct stub_manager, entry );
303
304         if (m->object == object)
305         {
306             result = m;
307             stub_manager_int_addref(result);
308             break;
309         }
310     }
311     LeaveCriticalSection(&apt->cs);
312
313     if (result)
314         TRACE("found %p for object %p\n", result, object);
315     else
316         TRACE("not found for object %p\n", object);
317
318     return result;    
319 }
320
321 /* removes the apartment reference to an object, destroying it when no other
322  * threads have a reference to it */
323 void apartment_disconnectobject(struct apartment *apt, void *object)
324 {
325     int found = FALSE;
326     struct stub_manager *stubmgr;
327
328     EnterCriticalSection(&apt->cs);
329     LIST_FOR_EACH_ENTRY( stubmgr, &apt->stubmgrs, struct stub_manager, entry )
330     {
331         if (stubmgr->object == object)
332         {
333             found = TRUE;
334             stub_manager_int_release(stubmgr);
335             break;
336         }
337     }
338     LeaveCriticalSection(&apt->cs);
339
340     if (found)
341         TRACE("disconnect object %p\n", object);
342     else
343         WARN("couldn't find object %p\n", object);
344 }
345
346 /* gets the stub manager associated with an object id - caller must have
347  * a reference to the apartment while a reference to the stub manager is held.
348  * it must also call release on the stub manager when it is no longer needed */
349 struct stub_manager *get_stub_manager(APARTMENT *apt, OID oid)
350 {
351     struct stub_manager *result = NULL;
352     struct list         *cursor;
353
354     EnterCriticalSection(&apt->cs);
355     LIST_FOR_EACH( cursor, &apt->stubmgrs )
356     {
357         struct stub_manager *m = LIST_ENTRY( cursor, struct stub_manager, entry );
358
359         if (m->oid == oid)
360         {
361             result = m;
362             stub_manager_int_addref(result);
363             break;
364         }
365     }
366     LeaveCriticalSection(&apt->cs);
367
368     if (result)
369         TRACE("found %p for oid %s\n", result, wine_dbgstr_longlong(oid));
370     else
371         TRACE("not found for oid %s\n", wine_dbgstr_longlong(oid));
372
373     return result;
374 }
375
376 /* add some external references (ie from a client that unmarshaled an ifptr) */
377 ULONG stub_manager_ext_addref(struct stub_manager *m, ULONG refs, BOOL tableweak)
378 {
379     ULONG rc;
380
381     EnterCriticalSection(&m->lock);
382
383     /* make sure we don't overflow extrefs */
384     refs = min(refs, (ULONG_MAX-1 - m->extrefs));
385     rc = (m->extrefs += refs);
386
387     if (tableweak)
388         rc += ++m->weakrefs;
389
390     LeaveCriticalSection(&m->lock);
391     
392     TRACE("added %u refs to %p (oid %s), rc is now %u\n", refs, m, wine_dbgstr_longlong(m->oid), rc);
393
394     return rc;
395 }
396
397 /* remove some external references */
398 ULONG stub_manager_ext_release(struct stub_manager *m, ULONG refs, BOOL tableweak, BOOL last_unlock_releases)
399 {
400     ULONG rc;
401
402     EnterCriticalSection(&m->lock);
403
404     /* make sure we don't underflow extrefs */
405     refs = min(refs, m->extrefs);
406     rc = (m->extrefs -= refs);
407
408     if (tableweak)
409         --m->weakrefs;
410     if (!last_unlock_releases)
411         rc += m->weakrefs;
412
413     LeaveCriticalSection(&m->lock);
414     
415     TRACE("removed %u refs from %p (oid %s), rc is now %u\n", refs, m, wine_dbgstr_longlong(m->oid), rc);
416
417     if (rc == 0)
418         stub_manager_int_release(m);
419
420     return rc;
421 }
422
423 /* gets the stub manager associated with an ipid - caller must have
424  * a reference to the apartment while a reference to the stub manager is held.
425  * it must also call release on the stub manager when it is no longer needed */
426 static struct stub_manager *get_stub_manager_from_ipid(APARTMENT *apt, const IPID *ipid)
427 {
428     struct stub_manager *result = NULL;
429     struct list         *cursor;
430
431     EnterCriticalSection(&apt->cs);
432     LIST_FOR_EACH( cursor, &apt->stubmgrs )
433     {
434         struct stub_manager *m = LIST_ENTRY( cursor, struct stub_manager, entry );
435
436         if (stub_manager_ipid_to_ifstub(m, ipid))
437         {
438             result = m;
439             stub_manager_int_addref(result);
440             break;
441         }
442     }
443     LeaveCriticalSection(&apt->cs);
444
445     if (result)
446         TRACE("found %p for ipid %s\n", result, debugstr_guid(ipid));
447     else
448         ERR("not found for ipid %s\n", debugstr_guid(ipid));
449
450     return result;
451 }
452
453 static HRESULT ipid_to_stub_manager(const IPID *ipid, APARTMENT **stub_apt, struct stub_manager **stubmgr_ret)
454 {
455     /* FIXME: hack for IRemUnknown */
456     if (ipid->Data2 == 0xffff)
457         *stub_apt = apartment_findfromoxid(*(const OXID *)ipid->Data4, TRUE);
458     else
459         *stub_apt = apartment_findfromtid(ipid->Data2);
460     if (!*stub_apt)
461     {
462         TRACE("Couldn't find apartment corresponding to TID 0x%04x\n", ipid->Data2);
463         return RPC_E_INVALID_OBJECT;
464     }
465     *stubmgr_ret = get_stub_manager_from_ipid(*stub_apt, ipid);
466     if (!*stubmgr_ret)
467     {
468         apartment_release(*stub_apt);
469         *stub_apt = NULL;
470         return RPC_E_INVALID_OBJECT;
471     }
472     return S_OK;
473 }
474
475 /* gets the apartment, stub and channel of an object. the caller must
476  * release the references to all objects (except iface) if the function
477  * returned success, otherwise no references are returned. */
478 HRESULT ipid_get_dispatch_params(const IPID *ipid, APARTMENT **stub_apt,
479                                  IRpcStubBuffer **stub, IRpcChannelBuffer **chan,
480                                  IID *iid, IUnknown **iface)
481 {
482     struct stub_manager *stubmgr;
483     struct ifstub *ifstub;
484     APARTMENT *apt;
485     HRESULT hr;
486
487     hr = ipid_to_stub_manager(ipid, &apt, &stubmgr);
488     if (hr != S_OK) return RPC_E_DISCONNECTED;
489
490     ifstub = stub_manager_ipid_to_ifstub(stubmgr, ipid);
491     if (ifstub)
492     {
493         *stub = ifstub->stubbuffer;
494         IRpcStubBuffer_AddRef(*stub);
495         *chan = ifstub->chan;
496         IRpcChannelBuffer_AddRef(*chan);
497         *stub_apt = apt;
498         *iid = ifstub->iid;
499         *iface = ifstub->iface;
500
501         stub_manager_int_release(stubmgr);
502         return S_OK;
503     }
504     else
505     {
506         stub_manager_int_release(stubmgr);
507         apartment_release(apt);
508         return RPC_E_DISCONNECTED;
509     }
510 }
511
512 /* returns TRUE if it is possible to unmarshal, FALSE otherwise. */
513 BOOL stub_manager_notify_unmarshal(struct stub_manager *m, const IPID *ipid)
514 {
515     BOOL ret = TRUE;
516     struct ifstub *ifstub;
517
518     if (!(ifstub = stub_manager_ipid_to_ifstub(m, ipid)))
519     {
520         ERR("attempted unmarshal of unknown IPID %s\n", debugstr_guid(ipid));
521         return FALSE;
522     }
523
524     EnterCriticalSection(&m->lock);
525
526     /* track normal marshals so we can enforce rules whilst in-process */
527     if (ifstub->flags & MSHLFLAGS_NORMAL)
528     {
529         if (m->norm_refs)
530             m->norm_refs--;
531         else
532         {
533             ERR("attempted invalid normal unmarshal, norm_refs is zero\n");
534             ret = FALSE;
535         }
536     }
537
538     LeaveCriticalSection(&m->lock);
539
540     return ret;
541 }
542
543 /* handles refcounting for CoReleaseMarshalData */
544 void stub_manager_release_marshal_data(struct stub_manager *m, ULONG refs, const IPID *ipid, BOOL tableweak)
545 {
546     struct ifstub *ifstub;
547  
548     if (!(ifstub = stub_manager_ipid_to_ifstub(m, ipid)))
549         return;
550  
551     if (ifstub->flags & MSHLFLAGS_TABLEWEAK)
552         refs = 0;
553     else if (ifstub->flags & MSHLFLAGS_TABLESTRONG)
554         refs = 1;
555
556     stub_manager_ext_release(m, refs, tableweak, FALSE);
557 }
558
559 /* is an ifstub table marshaled? */
560 BOOL stub_manager_is_table_marshaled(struct stub_manager *m, const IPID *ipid)
561 {
562     struct ifstub *ifstub = stub_manager_ipid_to_ifstub(m, ipid);
563  
564     assert( ifstub );
565     
566     return ifstub->flags & (MSHLFLAGS_TABLESTRONG | MSHLFLAGS_TABLEWEAK);
567 }
568
569
570 /*****************************************************************************
571  *
572  * IRemUnknown implementation
573  *
574  *
575  * Note: this object is not related to the lifetime of a stub_manager, but it
576  * interacts with stub managers.
577  */
578
579 typedef struct rem_unknown
580 {
581     IRemUnknown IRemUnknown_iface;
582     LONG refs;
583 } RemUnknown;
584
585 static const IRemUnknownVtbl RemUnknown_Vtbl;
586
587 static inline RemUnknown *impl_from_IRemUnknown(IRemUnknown *iface)
588 {
589     return CONTAINING_RECORD(iface, RemUnknown, IRemUnknown_iface);
590 }
591
592
593 /* construct an IRemUnknown object with one outstanding reference */
594 static HRESULT RemUnknown_Construct(IRemUnknown **ppRemUnknown)
595 {
596     RemUnknown *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
597
598     if (!This) return E_OUTOFMEMORY;
599
600     This->IRemUnknown_iface.lpVtbl = &RemUnknown_Vtbl;
601     This->refs = 1;
602
603     *ppRemUnknown = &This->IRemUnknown_iface;
604     return S_OK;
605 }
606
607 static HRESULT WINAPI RemUnknown_QueryInterface(IRemUnknown *iface, REFIID riid, void **ppv)
608 {
609     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
610
611     if (IsEqualIID(riid, &IID_IUnknown) ||
612         IsEqualIID(riid, &IID_IRemUnknown))
613     {
614         *ppv = iface;
615         IRemUnknown_AddRef(iface);
616         return S_OK;
617     }
618
619     FIXME("No interface for iid %s\n", debugstr_guid(riid));
620
621     *ppv = NULL;
622     return E_NOINTERFACE;
623 }
624
625 static ULONG WINAPI RemUnknown_AddRef(IRemUnknown *iface)
626 {
627     ULONG refs;
628     RemUnknown *This = impl_from_IRemUnknown(iface);
629
630     refs = InterlockedIncrement(&This->refs);
631
632     TRACE("%p before: %d\n", iface, refs-1);
633     return refs;
634 }
635
636 static ULONG WINAPI RemUnknown_Release(IRemUnknown *iface)
637 {
638     ULONG refs;
639     RemUnknown *This = impl_from_IRemUnknown(iface);
640
641     refs = InterlockedDecrement(&This->refs);
642     if (!refs)
643         HeapFree(GetProcessHeap(), 0, This);
644
645     TRACE("%p after: %d\n", iface, refs);
646     return refs;
647 }
648
649 static HRESULT WINAPI RemUnknown_RemQueryInterface(IRemUnknown *iface,
650     REFIPID ripid, ULONG cRefs, USHORT cIids, IID *iids /* [size_is(cIids)] */,
651     REMQIRESULT **ppQIResults /* [size_is(,cIids)] */)
652 {
653     HRESULT hr;
654     USHORT i;
655     USHORT successful_qis = 0;
656     APARTMENT *apt;
657     struct stub_manager *stubmgr;
658
659     TRACE("(%p)->(%s, %d, %d, %p, %p)\n", iface, debugstr_guid(ripid), cRefs, cIids, iids, ppQIResults);
660
661     hr = ipid_to_stub_manager(ripid, &apt, &stubmgr);
662     if (hr != S_OK) return hr;
663
664     *ppQIResults = CoTaskMemAlloc(sizeof(REMQIRESULT) * cIids);
665
666     for (i = 0; i < cIids; i++)
667     {
668         HRESULT hrobj = marshal_object(apt, &(*ppQIResults)[i].std, &iids[i],
669                                        stubmgr->object, MSHLFLAGS_NORMAL);
670         if (hrobj == S_OK)
671             successful_qis++;
672         (*ppQIResults)[i].hResult = hrobj;
673     }
674
675     stub_manager_int_release(stubmgr);
676     apartment_release(apt);
677
678     if (successful_qis == cIids)
679         return S_OK; /* we got all requested interfaces */
680     else if (successful_qis == 0)
681         return E_NOINTERFACE; /* we didn't get any interfaces */
682     else
683         return S_FALSE; /* we got some interfaces */
684 }
685
686 static HRESULT WINAPI RemUnknown_RemAddRef(IRemUnknown *iface,
687     USHORT cInterfaceRefs,
688     REMINTERFACEREF* InterfaceRefs /* [size_is(cInterfaceRefs)] */,
689     HRESULT *pResults /* [size_is(cInterfaceRefs)] */)
690 {
691     HRESULT hr = S_OK;
692     USHORT i;
693
694     TRACE("(%p)->(%d, %p, %p)\n", iface, cInterfaceRefs, InterfaceRefs, pResults);
695
696     for (i = 0; i < cInterfaceRefs; i++)
697     {
698         APARTMENT *apt;
699         struct stub_manager *stubmgr;
700
701         pResults[i] = ipid_to_stub_manager(&InterfaceRefs[i].ipid, &apt, &stubmgr);
702         if (pResults[i] != S_OK)
703         {
704             hr = S_FALSE;
705             continue;
706         }
707
708         stub_manager_ext_addref(stubmgr, InterfaceRefs[i].cPublicRefs, FALSE);
709         if (InterfaceRefs[i].cPrivateRefs)
710             FIXME("Adding %d refs securely not implemented\n", InterfaceRefs[i].cPrivateRefs);
711
712         stub_manager_int_release(stubmgr);
713         apartment_release(apt);
714     }
715
716     return hr;
717 }
718
719 static HRESULT WINAPI RemUnknown_RemRelease(IRemUnknown *iface,
720     USHORT cInterfaceRefs,
721     REMINTERFACEREF* InterfaceRefs /* [size_is(cInterfaceRefs)] */)
722 {
723     HRESULT hr = S_OK;
724     USHORT i;
725
726     TRACE("(%p)->(%d, %p)\n", iface, cInterfaceRefs, InterfaceRefs);
727
728     for (i = 0; i < cInterfaceRefs; i++)
729     {
730         APARTMENT *apt;
731         struct stub_manager *stubmgr;
732
733         hr = ipid_to_stub_manager(&InterfaceRefs[i].ipid, &apt, &stubmgr);
734         if (hr != S_OK)
735         {
736             hr = E_INVALIDARG;
737             /* FIXME: we should undo any changes already made in this function */
738             break;
739         }
740
741         stub_manager_ext_release(stubmgr, InterfaceRefs[i].cPublicRefs, FALSE, TRUE);
742         if (InterfaceRefs[i].cPrivateRefs)
743             FIXME("Releasing %d refs securely not implemented\n", InterfaceRefs[i].cPrivateRefs);
744
745         stub_manager_int_release(stubmgr);
746         apartment_release(apt);
747     }
748
749     return hr;
750 }
751
752 static const IRemUnknownVtbl RemUnknown_Vtbl =
753 {
754     RemUnknown_QueryInterface,
755     RemUnknown_AddRef,
756     RemUnknown_Release,
757     RemUnknown_RemQueryInterface,
758     RemUnknown_RemAddRef,
759     RemUnknown_RemRelease
760 };
761
762 /* starts the IRemUnknown listener for the current apartment */
763 HRESULT start_apartment_remote_unknown(void)
764 {
765     IRemUnknown *pRemUnknown;
766     HRESULT hr = S_OK;
767     APARTMENT *apt = COM_CurrentApt();
768
769     EnterCriticalSection(&apt->cs);
770     if (!apt->remunk_exported)
771     {
772         /* create the IRemUnknown object */
773         hr = RemUnknown_Construct(&pRemUnknown);
774         if (hr == S_OK)
775         {
776             STDOBJREF stdobjref; /* dummy - not used */
777             /* register it with the stub manager */
778             hr = marshal_object(apt, &stdobjref, &IID_IRemUnknown, (IUnknown *)pRemUnknown, MSHLFLAGS_NORMAL|MSHLFLAGSP_REMUNKNOWN);
779             /* release our reference to the object as the stub manager will manage the life cycle for us */
780             IRemUnknown_Release(pRemUnknown);
781             if (hr == S_OK)
782                 apt->remunk_exported = TRUE;
783         }
784     }
785     LeaveCriticalSection(&apt->cs);
786     return hr;
787 }