The Mechanics of COM+
Atoms are complicated things, and the atoms of COM+ are no exception. This is particularly true of context, the mechanics of which are more complex than they appear at first glance. If you want to apply COM+ successfully, you need to know more about how contexts work. You need to understand the relationship between contexts and references to objects, that is, interface pointers. This association is integral to the correct behavior of the COM+ plumbing. You need to manage interface pointers properly for interception to work correctly. If you do not, interception will not work, and neither will any of the runtime services COM+ provides. You also need to understand the relationship between contexts and objects themselves. By default, every instance of every configured class gets a brand-new context of its own. This implies a nontrivial amount of overhead in both time (for interception) and space (for context data structures). Although you get runtime services in return, you should not simply accept these costs. You can reduce runtime overhead by creating multiple objects in a single context, but you need to know how to configure classes to exhibit this behavior. This chapter deals with these basic mechanical topics.
Context Relativity
COM+ does a lot of work to make sure new objects live in contexts configured to meet their needs. The goal, of course, is to make sure that when an object's method is invoked, it executes in an appropriate environment that provides the services the object requires. The details are handled by the interception plumbing, which "does the right thing" when a causality crosses a context boundary to do work against an object. While COM+ makes sure an object's environment is initially correct, you bear some responsibility for making sure it remains correct. To make sure the interception plumbing always works correctly, you have to treat interface pointers as context-relative resources that cannot be used outside the context where they were initially acquired. In general this is not a burden; however, in some rare circumstances it requires some extra work on your part.
The Problem
First, let me explain the problem. Remember that when a new object is created, the SCM has to decide whether it should exist in the same context as its creator or in a brand-new context of its own. In the former case CoCreateInstance[Ex] returns a raw interface pointer that refers to the new object directly. In the latter case it returns an interface pointer to a proxy set up to intercept each method call and provide whatever additional runtime services the new object requires.
Assume that the SCM decides a new object can exist in its creator's context and returns a raw reference to it, as shown in Figure 3-1. What would happen if the raw reference to the new object, A' in the diagram, were handed to an object in another context? Figure 3-2 depicts this situation. If the object in the foreign context, object B, were to call a method of object A' directly, no interception would occur. The method of object A' would execute in object B's environment, using whatever runtime services context B was configured to use. If the method of object A' attempted to access object context, the call to CoGetObjectContext would succeed, but it would return a reference to an object representing B's world. That is not at all what object A' expects. If object A' expects a declarative transaction, it might not get one or it might get object B's. Neither of these situations is good; in fact, either result could be catastrophic.
What happens if the SCM decides a new object needs to live in a new context and CoCreateInstance[Ex] returns a reference to a proxy, as shown in Figure 3-3? Does the same problem exist in this case? Can a reference to a proxy safely be handed to other contexts? The answers are yes, the problem remains, and no, the proxy cannot be used from other contexts. To understand why, you have to know a little bit more about the COM+ interception plumbing.
In Chapter 2, I explained that COM+ uses proxies to intercept cross-context calls and to "do the right thing" to provide the services' objects in the target context expect. Proxies, however, are just one part of the picture. The interception plumbing's logical model has three separate pieces, shown in Figure 3-4.
A proxy represents an object in a foreign context. Proxies convert method calls into messages that can be sent through a channel. A channel is a conection to a foreign context, a pipe. Channels move messages from one context to another. A stub represents an object from a channel's point of view. Stubs convert messages back into method invocations on real objects. The physical structure of the interception plumbing differs depending on the distance between the two contexts it connects. Specifically, channels that move calls to other threads are more complex than channels that do not. Channels that do not move calls to other threads do not use full-blown stubs. Instead, the stub is merged with the channel. For simplicity's sake, the rest of this book focuses on the logical model of the interception plumbing and assumes there is always a stub.
COM+ runtime services are implemented in the stub side of the channel, where they can expose functionality as part of an object's context. (In some cases, such as just-in-time activation, the stub gets involved, too.) For example, if a declarative transaction is going to be made available as part of an object's environment, it makes no sense to try to do that on the proxy side. The declarative transaction has to be available to the real object, where it lives, not where the caller (and proxy) live. This architecture is shown in Figure 3-5.
COM+ gains great flexibility by invoking runtime services in the channel instead of the stub. Each channel represents a connection to a stub from a particular proxy; there can be as many channels to a stub and object as required. Each proxy is permanently affixed to its channel when it is created. Stubs, on the other hand, are simply handed a channel long enough to process an inbound call. Within the scope of each call, the stub uses the channel to allocate memory for out parameters and to optimize their marshaling based on how far away the proxy is. COM+ tunes each channel's behavior so that it does the minimum amount of work necessary to bridge the difference between the proxy's context and the real object's context.
As Figure 3-6 illustrates, each channel is tuned to bridge the specific differences between its proxy's context and the real object's context. It might be, for instance, that calling from context A to context B mandates a security check and initiates a new declarative transaction, while calling from context C to context B initiates a new declarative transaction but does nothing in terms of security.
What would happen if a reference to a proxy were handed to an object in another context, as shown in Figure 3-7? In this case, object C in context C holds a reference to the proxy in context A. Calls through the proxy will be intercepted, but because the proxy was created in context A, its channel cannot do the right thing. The channel's behavior is specifically optimized to deal with the difference between context A and context B. It knows nothing about context C. If calls from object C were allowed to go through, the results would be hard to predict and might be disastrous. So the channel does not let the call go through.
Channels actively enforce the context relativity of their proxies. The proxy side of the channel records the context it is initially created in. As each call comes in, the channel examines the current context ID, which is available as part of object context (remember IObjectContextInfo::GetContextId). If its original context ID and the current context ID match, the channel processes the call. If the IDs do not match, the channel returns a standard error code, RPC_E_WRONGTHREAD. COM+ inherited this constant from classic COM and uses it to indicate that a proxy is being used from a context other than its own, even if the problem has nothing to do with which thread is making the call. You should think of it as RPC_E_WRONGCONTEXT, which is what it really means.
You have to treat interface pointers as context-relative resources, or the interception plumbing will not work correctly. If you use a raw pointer to a real object in any context other than the one the object was created in, no interception will occur. If you use a pointer to a proxy in any context other than the one the proxy was created in, the channel will reject the call because it knows the right interception cannot occur. In either case, the resulting behavior is undesirable. In the former case, it is probably dangerous as well. All this leads to an inevitable question: How can you pass interface pointers to real objects or proxies from one context to another safely?
Marshaling Interface Pointers
Obviously COM+ has to provide a way to translate an interface pointer that is valid in one context into one that is valid in another context. If a pointer to a real object is passed to another context, it should be converted to a pointer to a proxy that is appropriate for that context and can forward calls back to the real object. If a pointer to a proxy is passed to another context, it should also be converted to a proxy appropriate for that context, with one exception. If a pointer to a proxy is passed to the context where the real object it refers to lives, the pointer to the proxy should be converted to a pointer to the real object instead.
COM+ enables all this functionality through an API it inherited from classic COM, CoMarshalInterface. CoMarshalInterface is one of a set of APIs designed to facilitate moving interface pointers from one context to another. CoMarshalInterface translates, or marshals, interface pointers into context-neutral byte streams called OBJREFs. An OBJREF contains the addressing information necessary to make calls back to an object. If you pass a pointer to a real object to CoMarshalInterface, it will create a stub for the object (if one does not already exist) and return an OBJREF identifying where the object lives. If you pass a pointer to a proxy to CoMarshalInterface, it will not create a stub, and it will return an OBJREF identifying where the real object the proxy refers to lives.
Once you have an OBJREF, you can take it to any context anywhere in the world and then convert it back into an interface pointer by calling CoUnmarshalInterface. CoUnmarshalInterface interprets, or unmarshals, the contents of an OBJREF and returns a pointer either to a proxy or to a real object if you happen to be in the context where the object the OBJREF refers to lives. If CoUnmarshalInterface returns a pointer to a proxy, the proxy is attached to a channel that is specifically tuned for the difference between the proxy's context and the real object's context.1
The context relativity of interface pointers is not a burden in general. You do not have to call these low-level plumbing APIs on a regular basis. Whenever you pass interface pointers to or receive them from the methods of COM interfaces or system APIs, you do not have to worry about marshaling; the plumbing takes care of all the details as needed. If you call CoCreateInstance[Ex] and the SCM decides the new object being created needs to live in a new context of its own, CoMarshalInterface and CoUnmarshalInterface are called automatically. If you pass an interface pointer through an existing proxy/stub connection, the proxy and stub call CoMarshalInterface and CoUnmarshal Interface on your behalf again. If you pass an interface pointer directly to an object in your own context, nothing happens because no translation is necessary. As long as you always pass interface pointers from one context to another using one of these techniquesCOM APIs or the methods of COM interfacesyou never have to worry about marshaling interface pointers.
There are, however, two situations where you may want to pass interface pointers between contexts without using either a system API or a COM method call. First, you may want to put an interface pointer into a global variable that is accessible from multiple contexts in your process. Second, you may want to pass an interface pointer to a new thread you are starting. These are the rare circumstances where you have to do some extra work. In both these cases, you are responsible for making sure interface pointers are marshaled correctly.
The Global Interface Table
Even when you are responsible for marshaling interface pointers by hand, you do not have to use the low-level marshaling APIs. Most application developers use the Global Interface Table (GIT) instead. The GIT is a processwide lookup table that maps back and forth between context-relative interface pointers and context-neutral cookies. The GIT is implemented in OLE32.DLL. You can instantiate it by calling CoCreateInstance[Ex] and passing CLSID_Std GlobalInterfaceTable. A reference to the GIT is implicitly context neutral. It can be cached in a global variable and safely accessed from any context. This is a special exception to the context-relativity rule that does not apply in the general case. Figure 3-8 shows the architecture of the GIT.
The Global Interface Table implements a standard interface called GlobalInterfaceTable.
interface IGlobalInterfaceTable : IUnknown { HRESULT RegisterInterfaceInGlobal([in] IUnknown *pUnk, [in] REFIID riid, [out] DWORD *pdwCookie); HRESULT RevokeInterfaceFromGlobal([in] DWORD dwCookie); HRESULT GetInterfaceFromGlobal([in] DWORD dwCookie, [in] REFIID riid, [out, iid_is(riid)] void **ppv); };
RegisterInterfaceInGlobal inserts an interface pointer into the GIT and returns a context-neutral cookie to represent it. The cookie is a DWORD that is guaranteed not to be 0 (the null cookie, like a null pointer, is never valid). A GIT cookie can be passed to another context using any technique you like, including via a global variable or as an argument to a new thread. GetInterfaceFromGlobal converts a valid cookie into an interface pointer that is appropriate for the current context. A cookie remains valid until the interface pointer it refers to is removed from the GIT by a call to RevokeInterfaceFromGlobal. This explicit clean-up mechanism allows the GIT to easily support a "marshal-once/unmarshal-many times" scheme, which is preferred if you're going to store a GIT cookie in a global variable. It also means that the GIT holds a reference to a registered object until it is explicitly revoked. If you fail to revoke a reference held by the GIT, the object it refers to will remain in memory until the GIT releases it when the process shuts down.
Here is an example demonstrating how the GIT can be used to pass an interface pointer to a new thread. The StartSomething function creates a new object and passes it as input to a new thread. It uses the GIT to marshal the interface pointer.
// Global GIT reference initialized elsewhere extern IGlobalInterfaceTable *g_pGIT; // Declaration of thread proc implemented below DWORD WINAPI DoSomething(void *pv); // Function that starts a new thread HRESULT StartSomething(void) { // Create new object CComPtr<IObject> spObj; HRESULT hr = spObj.CoCreateInstance(__uuidof(SomeObject)); if (FAILED(hr)) return hr; // Put reference to object into GIT DWORD cookie = 0; hr = g_pGIT->RegisterInterfaceInGlobal(spObj, __uuidof(spObj), &cookie); if (FAILED(hr)) return hr; // Start new thread, passing cookie as argument HANDLE thread = CreateThread(0, 0, &DoSomething, (void*)cookie, 0, 0); // If CreateThread fails, remove reference from GIT if (thread == 0) { g_pGIT->RevokeInterfaceFromGlobal(dwCookie); return E_FAIL; } CloseHandle(thread); return hr; }
Notice that this function removes the interface pointer from the GIT if CreateThread fails. Here is the implementation of the thread function, DoSomething. It uses the cookie that StartSomething passed as an input argument to retrieve an interface pointer to the object from the GIT.
// implementation of thread proc DWORD WINAPI DoSomething(void *pv) { // initialize COM HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hr)) return hr; // retrieve reference from GIT DWORD cookie = (DWORD) pv; CComPtr<IObject> spObj; hr = g_pGIT->GetInterfaceFromGlobal(cookie, __uuidof(spObj), (void**)&spObj); // remove reference from GIT g_pGIT->RevokeInterfaceFromGlobal(cookie); // if attempt to get reference failed, exit if (FAILED(hr)) return hr; ... // use object // clean things up spObj.Release(); CoUninitialize(); return hr; }
This function retrieves an interface pointer to the object and then removes it from the GIT. When this thread function completes, the object is released.
Context Relativity in Day-to-Day Life
Although you have to be aware of context relativity and the importance of marshaling interface pointers between contexts, you typically do not have to spend much time worrying about these issues in your day-to-day development work. None of the code in Chapter 1 had to worry about context relativity at all. COM+ designs are based on the object-per-client model (remember Rule 1.1), so it is unlikely that you will need to put an interface pointer into a global variable. Similarly COM+-based classes typically rely on the thread pool provided by the runtime and do not create their own threads. Still, there may be cases where you want to share an interface pointer using one of these techniques, especially if you are building some relatively low-level plumbing of your own, an efficient middle-tier cache, for example. There may also be situations where you violate context relativity accidentally and need to be able to figure out why your code is not working correctly. Just remember that context relativity boils down to one simple, tremendously important guideline, Rule 3.1. If you do not follow this rule, the interception plumbing and, therefore, the context programming model will not work correctly.
Rule 3.1
Do not pass interface pointers from one context to another without using a system-provided facility (e.g., system API, COM interface method, the Global Interface Table) to translate the reference to work in the destination context.
Footnotes
1. My coverage of this topic is purposefully brief because, although this aspect of the plumbing is important to understand, the details are not relevant to this story and have been copiously documented elsewhere. For more information on these APIs and the contents of OBJREFs, see the COM Specification and the DCOM Protocol Internet Draft, available from MSDN or online at http://www.microsoft.com/com/, or Essential COM by Box.