1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/callback.h"
6 #include "base/logging.h"
7 #include "base/memory/scoped_ptr.h"
8 #include "base/stl_util.h"
9 #include "sandbox/win/src/sharedmem_ipc_server.h"
10 #include "sandbox/win/src/sharedmem_ipc_client.h"
11 #include "sandbox/win/src/sandbox.h"
12 #include "sandbox/win/src/sandbox_types.h"
13 #include "sandbox/win/src/crosscall_params.h"
14 #include "sandbox/win/src/crosscall_server.h"
17 // This handle must not be closed.
18 volatile HANDLE g_alive_mutex
= NULL
;
23 SharedMemIPCServer::ServerControl::ServerControl() {
26 SharedMemIPCServer::ServerControl::~ServerControl() {
29 SharedMemIPCServer::SharedMemIPCServer(HANDLE target_process
,
30 DWORD target_process_id
,
31 ThreadProvider
* thread_provider
,
32 Dispatcher
* dispatcher
)
33 : client_control_(NULL
),
34 thread_provider_(thread_provider
),
35 target_process_(target_process
),
36 target_process_id_(target_process_id
),
37 call_dispatcher_(dispatcher
) {
38 // We create a initially owned mutex. If the server dies unexpectedly,
39 // the thread that owns it will fail to release the lock and windows will
40 // report to the target (when it tries to acquire it) that the wait was
41 // abandoned. Note: We purposely leak the local handle because we want it to
42 // be closed by Windows itself so it is properly marked as abandoned if the
45 HANDLE mutex
= ::CreateMutexW(NULL
, TRUE
, NULL
);
46 if (::InterlockedCompareExchangePointer(&g_alive_mutex
, mutex
, NULL
)) {
47 // We lost the race to create the mutex.
53 SharedMemIPCServer::~SharedMemIPCServer() {
54 // Free the wait handles associated with the thread pool.
55 if (!thread_provider_
->UnRegisterWaits(this)) {
56 // Better to leak than to crash.
59 STLDeleteElements(&server_contexts_
);
62 ::UnmapViewOfFile(client_control_
);
65 bool SharedMemIPCServer::Init(void* shared_mem
, uint32 shared_size
,
66 uint32 channel_size
) {
67 // The shared memory needs to be at least as big as a channel.
68 if (shared_size
< channel_size
) {
71 // The channel size should be aligned.
72 if (0 != (channel_size
% 32)) {
76 // Calculate how many channels we can fit in the shared memory.
77 shared_size
-= offsetof(IPCControl
, channels
);
78 size_t channel_count
= shared_size
/ (sizeof(ChannelControl
) + channel_size
);
80 // If we cannot fit even one channel we bail out.
81 if (0 == channel_count
) {
84 // Calculate the start of the first channel.
85 size_t base_start
= (sizeof(ChannelControl
)* channel_count
) +
86 offsetof(IPCControl
, channels
);
88 client_control_
= reinterpret_cast<IPCControl
*>(shared_mem
);
89 client_control_
->channels_count
= 0;
91 // This is the initialization that we do per-channel. Basically:
92 // 1) make two events (ping & pong)
93 // 2) create handles to the events for the client and the server.
94 // 3) initialize the channel (client_context) with the state.
95 // 4) initialize the server side of the channel (service_context).
96 // 5) call the thread provider RegisterWait to register the ping events.
97 for (size_t ix
= 0; ix
!= channel_count
; ++ix
) {
98 ChannelControl
* client_context
= &client_control_
->channels
[ix
];
99 ServerControl
* service_context
= new ServerControl
;
100 server_contexts_
.push_back(service_context
);
102 if (!MakeEvents(&service_context
->ping_event
,
103 &service_context
->pong_event
,
104 &client_context
->ping_event
,
105 &client_context
->pong_event
)) {
109 client_context
->channel_base
= base_start
;
110 client_context
->state
= kFreeChannel
;
112 // Note that some of these values are available as members of this object
113 // but we put them again into the service_context because we will be called
114 // on a static method (ThreadPingEventReady). In particular, target_process_
115 // is a raw handle that is not owned by this object (it's owned by the
116 // owner of this object), and we are storing it in multiple places.
117 service_context
->shared_base
= reinterpret_cast<char*>(shared_mem
);
118 service_context
->channel_size
= channel_size
;
119 service_context
->channel
= client_context
;
120 service_context
->channel_buffer
= service_context
->shared_base
+
121 client_context
->channel_base
;
122 service_context
->dispatcher
= call_dispatcher_
;
123 service_context
->target_info
.process
= target_process_
;
124 service_context
->target_info
.process_id
= target_process_id_
;
125 // Advance to the next channel.
126 base_start
+= channel_size
;
127 // Register the ping event with the threadpool.
128 thread_provider_
->RegisterWait(this, service_context
->ping_event
.Get(),
129 ThreadPingEventReady
, service_context
);
131 if (!::DuplicateHandle(::GetCurrentProcess(), g_alive_mutex
,
132 target_process_
, &client_control_
->server_alive
,
133 SYNCHRONIZE
| EVENT_MODIFY_STATE
, FALSE
, 0)) {
136 // This last setting indicates to the client all is setup.
137 client_control_
->channels_count
= channel_count
;
141 // Releases memory allocated for IPC arguments, if needed.
142 void ReleaseArgs(const IPCParams
* ipc_params
, void* args
[kMaxIpcParams
]) {
143 for (size_t i
= 0; i
< kMaxIpcParams
; i
++) {
144 switch (ipc_params
->args
[i
]) {
146 delete reinterpret_cast<base::string16
*>(args
[i
]);
150 case INOUTPTR_TYPE
: {
151 delete reinterpret_cast<CountedBuffer
*>(args
[i
]);
160 // Fills up the list of arguments (args and ipc_params) for an IPC call.
161 bool GetArgs(CrossCallParamsEx
* params
, IPCParams
* ipc_params
,
162 void* args
[kMaxIpcParams
]) {
163 if (kMaxIpcParams
< params
->GetParamsCount())
166 for (uint32 i
= 0; i
< params
->GetParamsCount(); i
++) {
169 args
[i
] = params
->GetRawParameter(i
, &size
, &type
);
171 ipc_params
->args
[i
] = type
;
174 scoped_ptr
<base::string16
> data(new base::string16
);
175 if (!params
->GetParameterStr(i
, data
.get())) {
177 ReleaseArgs(ipc_params
, args
);
180 args
[i
] = data
.release();
185 if (!params
->GetParameter32(i
, &data
)) {
186 ReleaseArgs(ipc_params
, args
);
189 IPCInt
ipc_int(data
);
190 args
[i
] = ipc_int
.AsVoidPtr();
193 case VOIDPTR_TYPE
: {
195 if (!params
->GetParameterVoidPtr(i
, &data
)) {
196 ReleaseArgs(ipc_params
, args
);
202 case INOUTPTR_TYPE
: {
204 ReleaseArgs(ipc_params
, args
);
207 CountedBuffer
* buffer
= new CountedBuffer(args
[i
] , size
);
218 bool SharedMemIPCServer::InvokeCallback(const ServerControl
* service_context
,
220 CrossCallReturn
* call_result
) {
221 // Set the default error code;
222 SetCallError(SBOX_ERROR_INVALID_IPC
, call_result
);
223 uint32 output_size
= 0;
224 // Parse, verify and copy the message. The handler operates on a copy
225 // of the message so the client cannot play dirty tricks by changing the
226 // data in the channel while the IPC is being processed.
227 scoped_ptr
<CrossCallParamsEx
> params(
228 CrossCallParamsEx::CreateFromBuffer(ipc_buffer
,
229 service_context
->channel_size
,
234 uint32 tag
= params
->GetTag();
235 static_assert(0 == INVALID_TYPE
, "incorrect type enum");
236 IPCParams ipc_params
= {0};
237 ipc_params
.ipc_tag
= tag
;
239 void* args
[kMaxIpcParams
];
240 if (!GetArgs(params
.get(), &ipc_params
, args
))
243 IPCInfo ipc_info
= {0};
244 ipc_info
.ipc_tag
= tag
;
245 ipc_info
.client_info
= &service_context
->target_info
;
246 Dispatcher
* dispatcher
= service_context
->dispatcher
;
249 Dispatcher
* handler
= NULL
;
251 Dispatcher::CallbackGeneric callback_generic
;
252 handler
= dispatcher
->OnMessageReady(&ipc_params
, &callback_generic
);
254 switch (params
->GetParamsCount()) {
256 // Ask the IPC dispatcher if she can service this IPC.
257 Dispatcher::Callback0 callback
=
258 reinterpret_cast<Dispatcher::Callback0
>(callback_generic
);
259 if (!(handler
->*callback
)(&ipc_info
))
265 Dispatcher::Callback1 callback
=
266 reinterpret_cast<Dispatcher::Callback1
>(callback_generic
);
267 if (!(handler
->*callback
)(&ipc_info
, args
[0]))
273 Dispatcher::Callback2 callback
=
274 reinterpret_cast<Dispatcher::Callback2
>(callback_generic
);
275 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1]))
281 Dispatcher::Callback3 callback
=
282 reinterpret_cast<Dispatcher::Callback3
>(callback_generic
);
283 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2]))
289 Dispatcher::Callback4 callback
=
290 reinterpret_cast<Dispatcher::Callback4
>(callback_generic
);
291 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2],
298 Dispatcher::Callback5 callback
=
299 reinterpret_cast<Dispatcher::Callback5
>(callback_generic
);
300 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
307 Dispatcher::Callback6 callback
=
308 reinterpret_cast<Dispatcher::Callback6
>(callback_generic
);
309 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
316 Dispatcher::Callback7 callback
=
317 reinterpret_cast<Dispatcher::Callback7
>(callback_generic
);
318 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
319 args
[4], args
[5], args
[6]))
325 Dispatcher::Callback8 callback
=
326 reinterpret_cast<Dispatcher::Callback8
>(callback_generic
);
327 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
328 args
[4], args
[5], args
[6], args
[7]))
334 Dispatcher::Callback9 callback
=
335 reinterpret_cast<Dispatcher::Callback9
>(callback_generic
);
336 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
337 args
[4], args
[5], args
[6], args
[7], args
[8]))
351 SetCallError(SBOX_ERROR_FAILED_IPC
, call_result
);
353 memcpy(call_result
, &ipc_info
.return_info
, sizeof(*call_result
));
354 SetCallSuccess(call_result
);
355 if (params
->IsInOut()) {
356 // Maybe the params got changed by the broker. We need to upadte the
358 memcpy(ipc_buffer
, params
.get(), output_size
);
362 ReleaseArgs(&ipc_params
, args
);
367 // This function gets called by a thread from the thread pool when a
368 // ping event fires. The context is the same as passed in the RegisterWait()
370 void __stdcall
SharedMemIPCServer::ThreadPingEventReady(void* context
,
372 if (NULL
== context
) {
376 ServerControl
* service_context
= reinterpret_cast<ServerControl
*>(context
);
377 // Since the event fired, the channel *must* be busy. Change to kAckChannel
378 // while we service it.
380 ::InterlockedCompareExchange(&service_context
->channel
->state
,
381 kAckChannel
, kBusyChannel
);
382 if (kBusyChannel
!= last_state
) {
387 // Prepare the result structure. At this point we will return some result
388 // even if the IPC is invalid, malformed or has no handler.
389 CrossCallReturn call_result
= {0};
390 void* buffer
= service_context
->channel_buffer
;
392 InvokeCallback(service_context
, buffer
, &call_result
);
394 // Copy the answer back into the channel and signal the pong event. This
395 // should wake up the client so he can finish the the ipc cycle.
396 CrossCallParams
* call_params
= reinterpret_cast<CrossCallParams
*>(buffer
);
397 memcpy(call_params
->GetCallReturn(), &call_result
, sizeof(call_result
));
398 ::InterlockedExchange(&service_context
->channel
->state
, kAckChannel
);
399 ::SetEvent(service_context
->pong_event
.Get());
402 bool SharedMemIPCServer::MakeEvents(base::win::ScopedHandle
* server_ping
,
403 base::win::ScopedHandle
* server_pong
,
404 HANDLE
* client_ping
, HANDLE
* client_pong
) {
405 // Note that the IPC client has no right to delete the events. That would
406 // cause problems. The server *owns* the events.
407 const DWORD kDesiredAccess
= SYNCHRONIZE
| EVENT_MODIFY_STATE
;
409 // The events are auto reset, and start not signaled.
410 server_ping
->Set(::CreateEventW(NULL
, FALSE
, FALSE
, NULL
));
411 if (!::DuplicateHandle(::GetCurrentProcess(), server_ping
->Get(),
412 target_process_
, client_ping
, kDesiredAccess
, FALSE
,
417 server_pong
->Set(::CreateEventW(NULL
, FALSE
, FALSE
, NULL
));
418 if (!::DuplicateHandle(::GetCurrentProcess(), server_pong
->Get(),
419 target_process_
, client_pong
, kDesiredAccess
, FALSE
,
426 } // namespace sandbox