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 "sandbox/win/src/sharedmem_ipc_server.h"
9 #include "sandbox/win/src/sharedmem_ipc_client.h"
10 #include "sandbox/win/src/sandbox.h"
11 #include "sandbox/win/src/sandbox_types.h"
12 #include "sandbox/win/src/crosscall_params.h"
13 #include "sandbox/win/src/crosscall_server.h"
16 // This handle must not be closed.
17 volatile HANDLE g_alive_mutex
= NULL
;
22 SharedMemIPCServer::SharedMemIPCServer(HANDLE target_process
,
23 DWORD target_process_id
,
25 ThreadProvider
* thread_provider
,
26 Dispatcher
* dispatcher
)
27 : client_control_(NULL
),
28 thread_provider_(thread_provider
),
29 target_process_(target_process
),
30 target_process_id_(target_process_id
),
31 target_job_object_(target_job
),
32 call_dispatcher_(dispatcher
) {
33 // We create a initially owned mutex. If the server dies unexpectedly,
34 // the thread that owns it will fail to release the lock and windows will
35 // report to the target (when it tries to acquire it) that the wait was
36 // abandoned. Note: We purposely leak the local handle because we want it to
37 // be closed by Windows itself so it is properly marked as abandoned if the
40 HANDLE mutex
= ::CreateMutexW(NULL
, TRUE
, NULL
);
41 if (::InterlockedCompareExchangePointer(&g_alive_mutex
, mutex
, NULL
)) {
42 // We lost the race to create the mutex.
48 SharedMemIPCServer::~SharedMemIPCServer() {
49 // Free the wait handles associated with the thread pool.
50 if (!thread_provider_
->UnRegisterWaits(this)) {
51 // Better to leak than to crash.
54 // Free the IPC signal events.
55 ServerContexts::iterator it
;
56 for (it
= server_contexts_
.begin(); it
!= server_contexts_
.end(); ++it
) {
57 ServerControl
* context
= (*it
);
58 ::CloseHandle(context
->ping_event
);
59 ::CloseHandle(context
->pong_event
);
64 ::UnmapViewOfFile(client_control_
);
67 bool SharedMemIPCServer::Init(void* shared_mem
, uint32 shared_size
,
68 uint32 channel_size
) {
69 // The shared memory needs to be at least as big as a channel.
70 if (shared_size
< channel_size
) {
73 // The channel size should be aligned.
74 if (0 != (channel_size
% 32)) {
78 // Calculate how many channels we can fit in the shared memory.
79 shared_size
-= offsetof(IPCControl
, channels
);
80 size_t channel_count
= shared_size
/ (sizeof(ChannelControl
) + channel_size
);
82 // If we cannot fit even one channel we bail out.
83 if (0 == channel_count
) {
86 // Calculate the start of the first channel.
87 size_t base_start
= (sizeof(ChannelControl
)* channel_count
) +
88 offsetof(IPCControl
, channels
);
90 client_control_
= reinterpret_cast<IPCControl
*>(shared_mem
);
91 client_control_
->channels_count
= 0;
93 // This is the initialization that we do per-channel. Basically:
94 // 1) make two events (ping & pong)
95 // 2) create handles to the events for the client and the server.
96 // 3) initialize the channel (client_context) with the state.
97 // 4) initialize the server side of the channel (service_context).
98 // 5) call the thread provider RegisterWait to register the ping events.
99 for (size_t ix
= 0; ix
!= channel_count
; ++ix
) {
100 ChannelControl
* client_context
= &client_control_
->channels
[ix
];
101 ServerControl
* service_context
= new ServerControl
;
102 server_contexts_
.push_back(service_context
);
104 if (!MakeEvents(&service_context
->ping_event
,
105 &service_context
->pong_event
,
106 &client_context
->ping_event
,
107 &client_context
->pong_event
)) {
111 client_context
->channel_base
= base_start
;
112 client_context
->state
= kFreeChannel
;
114 // Note that some of these values are available as members of this
115 // object but we put them again into the service_context because we
116 // will be called on a static method (ThreadPingEventReady)
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 service_context
->target_info
.job_object
= target_job_object_
;
126 // Advance to the next channel.
127 base_start
+= channel_size
;
128 // Register the ping event with the threadpool.
129 thread_provider_
->RegisterWait(this, service_context
->ping_event
,
130 ThreadPingEventReady
, service_context
);
132 if (!::DuplicateHandle(::GetCurrentProcess(), g_alive_mutex
,
133 target_process_
, &client_control_
->server_alive
,
134 SYNCHRONIZE
| EVENT_MODIFY_STATE
, FALSE
, 0)) {
137 // This last setting indicates to the client all is setup.
138 client_control_
->channels_count
= channel_count
;
142 // Releases memory allocated for IPC arguments, if needed.
143 void ReleaseArgs(const IPCParams
* ipc_params
, void* args
[kMaxIpcParams
]) {
144 for (size_t i
= 0; i
< kMaxIpcParams
; i
++) {
145 switch (ipc_params
->args
[i
]) {
147 delete reinterpret_cast<base::string16
*>(args
[i
]);
151 case INOUTPTR_TYPE
: {
152 delete reinterpret_cast<CountedBuffer
*>(args
[i
]);
161 // Fills up the list of arguments (args and ipc_params) for an IPC call.
162 bool GetArgs(CrossCallParamsEx
* params
, IPCParams
* ipc_params
,
163 void* args
[kMaxIpcParams
]) {
164 if (kMaxIpcParams
< params
->GetParamsCount())
167 for (uint32 i
= 0; i
< params
->GetParamsCount(); i
++) {
170 args
[i
] = params
->GetRawParameter(i
, &size
, &type
);
172 ipc_params
->args
[i
] = type
;
175 scoped_ptr
<base::string16
> data(new base::string16
);
176 if (!params
->GetParameterStr(i
, data
.get())) {
178 ReleaseArgs(ipc_params
, args
);
181 args
[i
] = data
.release();
186 if (!params
->GetParameter32(i
, &data
)) {
187 ReleaseArgs(ipc_params
, args
);
190 IPCInt
ipc_int(data
);
191 args
[i
] = ipc_int
.AsVoidPtr();
194 case VOIDPTR_TYPE
: {
196 if (!params
->GetParameterVoidPtr(i
, &data
)) {
197 ReleaseArgs(ipc_params
, args
);
203 case INOUTPTR_TYPE
: {
205 ReleaseArgs(ipc_params
, args
);
208 CountedBuffer
* buffer
= new CountedBuffer(args
[i
] , size
);
219 bool SharedMemIPCServer::InvokeCallback(const ServerControl
* service_context
,
221 CrossCallReturn
* call_result
) {
222 // Set the default error code;
223 SetCallError(SBOX_ERROR_INVALID_IPC
, call_result
);
224 uint32 output_size
= 0;
225 // Parse, verify and copy the message. The handler operates on a copy
226 // of the message so the client cannot play dirty tricks by changing the
227 // data in the channel while the IPC is being processed.
228 scoped_ptr
<CrossCallParamsEx
> params(
229 CrossCallParamsEx::CreateFromBuffer(ipc_buffer
,
230 service_context
->channel_size
,
235 uint32 tag
= params
->GetTag();
236 static_assert(0 == INVALID_TYPE
, "incorrect type enum");
237 IPCParams ipc_params
= {0};
238 ipc_params
.ipc_tag
= tag
;
240 void* args
[kMaxIpcParams
];
241 if (!GetArgs(params
.get(), &ipc_params
, args
))
244 IPCInfo ipc_info
= {0};
245 ipc_info
.ipc_tag
= tag
;
246 ipc_info
.client_info
= &service_context
->target_info
;
247 Dispatcher
* dispatcher
= service_context
->dispatcher
;
250 Dispatcher
* handler
= NULL
;
252 Dispatcher::CallbackGeneric callback_generic
;
253 handler
= dispatcher
->OnMessageReady(&ipc_params
, &callback_generic
);
255 switch (params
->GetParamsCount()) {
257 // Ask the IPC dispatcher if she can service this IPC.
258 Dispatcher::Callback0 callback
=
259 reinterpret_cast<Dispatcher::Callback0
>(callback_generic
);
260 if (!(handler
->*callback
)(&ipc_info
))
266 Dispatcher::Callback1 callback
=
267 reinterpret_cast<Dispatcher::Callback1
>(callback_generic
);
268 if (!(handler
->*callback
)(&ipc_info
, args
[0]))
274 Dispatcher::Callback2 callback
=
275 reinterpret_cast<Dispatcher::Callback2
>(callback_generic
);
276 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1]))
282 Dispatcher::Callback3 callback
=
283 reinterpret_cast<Dispatcher::Callback3
>(callback_generic
);
284 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2]))
290 Dispatcher::Callback4 callback
=
291 reinterpret_cast<Dispatcher::Callback4
>(callback_generic
);
292 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2],
299 Dispatcher::Callback5 callback
=
300 reinterpret_cast<Dispatcher::Callback5
>(callback_generic
);
301 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
308 Dispatcher::Callback6 callback
=
309 reinterpret_cast<Dispatcher::Callback6
>(callback_generic
);
310 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
317 Dispatcher::Callback7 callback
=
318 reinterpret_cast<Dispatcher::Callback7
>(callback_generic
);
319 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
320 args
[4], args
[5], args
[6]))
326 Dispatcher::Callback8 callback
=
327 reinterpret_cast<Dispatcher::Callback8
>(callback_generic
);
328 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
329 args
[4], args
[5], args
[6], args
[7]))
335 Dispatcher::Callback9 callback
=
336 reinterpret_cast<Dispatcher::Callback9
>(callback_generic
);
337 if (!(handler
->*callback
)(&ipc_info
, args
[0], args
[1], args
[2], args
[3],
338 args
[4], args
[5], args
[6], args
[7], args
[8]))
352 SetCallError(SBOX_ERROR_FAILED_IPC
, call_result
);
354 memcpy(call_result
, &ipc_info
.return_info
, sizeof(*call_result
));
355 SetCallSuccess(call_result
);
356 if (params
->IsInOut()) {
357 // Maybe the params got changed by the broker. We need to upadte the
359 memcpy(ipc_buffer
, params
.get(), output_size
);
363 ReleaseArgs(&ipc_params
, args
);
368 // This function gets called by a thread from the thread pool when a
369 // ping event fires. The context is the same as passed in the RegisterWait()
371 void __stdcall
SharedMemIPCServer::ThreadPingEventReady(void* context
,
373 if (NULL
== context
) {
377 ServerControl
* service_context
= reinterpret_cast<ServerControl
*>(context
);
378 // Since the event fired, the channel *must* be busy. Change to kAckChannel
379 // while we service it.
381 ::InterlockedCompareExchange(&service_context
->channel
->state
,
382 kAckChannel
, kBusyChannel
);
383 if (kBusyChannel
!= last_state
) {
388 // Prepare the result structure. At this point we will return some result
389 // even if the IPC is invalid, malformed or has no handler.
390 CrossCallReturn call_result
= {0};
391 void* buffer
= service_context
->channel_buffer
;
393 InvokeCallback(service_context
, buffer
, &call_result
);
395 // Copy the answer back into the channel and signal the pong event. This
396 // should wake up the client so he can finish the the ipc cycle.
397 CrossCallParams
* call_params
= reinterpret_cast<CrossCallParams
*>(buffer
);
398 memcpy(call_params
->GetCallReturn(), &call_result
, sizeof(call_result
));
399 ::InterlockedExchange(&service_context
->channel
->state
, kAckChannel
);
400 ::SetEvent(service_context
->pong_event
);
403 bool SharedMemIPCServer::MakeEvents(HANDLE
* server_ping
, HANDLE
* 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
= ::CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
411 if (!::DuplicateHandle(::GetCurrentProcess(), *server_ping
, target_process_
,
412 client_ping
, kDesiredAccess
, FALSE
, 0)) {
415 *server_pong
= ::CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
416 if (!::DuplicateHandle(::GetCurrentProcess(), *server_pong
, target_process_
,
417 client_pong
, kDesiredAccess
, FALSE
, 0)) {
423 } // namespace sandbox