Add ICU message format support
[chromium-blink-merge.git] / sandbox / win / src / sharedmem_ipc_server.cc
blobea1793c9dc4e9eb53a38a58cfb590b07836cd0a7
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"
16 namespace {
17 // This handle must not be closed.
18 volatile HANDLE g_alive_mutex = NULL;
21 namespace sandbox {
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
43 // server dies.
44 if (!g_alive_mutex) {
45 HANDLE mutex = ::CreateMutexW(NULL, TRUE, NULL);
46 if (::InterlockedCompareExchangePointer(&g_alive_mutex, mutex, NULL)) {
47 // We lost the race to create the mutex.
48 ::CloseHandle(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.
57 return;
59 STLDeleteElements(&server_contexts_);
61 if (client_control_)
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) {
69 return false;
71 // The channel size should be aligned.
72 if (0 != (channel_size % 32)) {
73 return false;
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) {
82 return false;
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)) {
106 return false;
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)) {
134 return false;
136 // This last setting indicates to the client all is setup.
137 client_control_->channels_count = channel_count;
138 return true;
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]) {
145 case WCHAR_TYPE: {
146 delete reinterpret_cast<base::string16*>(args[i]);
147 args[i] = NULL;
148 break;
150 case INOUTPTR_TYPE: {
151 delete reinterpret_cast<CountedBuffer*>(args[i]);
152 args[i] = NULL;
153 break;
155 default: break;
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())
164 return false;
166 for (uint32 i = 0; i < params->GetParamsCount(); i++) {
167 uint32 size;
168 ArgType type;
169 args[i] = params->GetRawParameter(i, &size, &type);
170 if (args[i]) {
171 ipc_params->args[i] = type;
172 switch (type) {
173 case WCHAR_TYPE: {
174 scoped_ptr<base::string16> data(new base::string16);
175 if (!params->GetParameterStr(i, data.get())) {
176 args[i] = 0;
177 ReleaseArgs(ipc_params, args);
178 return false;
180 args[i] = data.release();
181 break;
183 case UINT32_TYPE: {
184 uint32 data;
185 if (!params->GetParameter32(i, &data)) {
186 ReleaseArgs(ipc_params, args);
187 return false;
189 IPCInt ipc_int(data);
190 args[i] = ipc_int.AsVoidPtr();
191 break;
193 case VOIDPTR_TYPE : {
194 void* data;
195 if (!params->GetParameterVoidPtr(i, &data)) {
196 ReleaseArgs(ipc_params, args);
197 return false;
199 args[i] = data;
200 break;
202 case INOUTPTR_TYPE: {
203 if (!args[i]) {
204 ReleaseArgs(ipc_params, args);
205 return false;
207 CountedBuffer* buffer = new CountedBuffer(args[i] , size);
208 args[i] = buffer;
209 break;
211 default: break;
215 return true;
218 bool SharedMemIPCServer::InvokeCallback(const ServerControl* service_context,
219 void* ipc_buffer,
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,
230 &output_size));
231 if (!params.get())
232 return false;
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))
241 return false;
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;
247 DCHECK(dispatcher);
248 bool error = true;
249 Dispatcher* handler = NULL;
251 Dispatcher::CallbackGeneric callback_generic;
252 handler = dispatcher->OnMessageReady(&ipc_params, &callback_generic);
253 if (handler) {
254 switch (params->GetParamsCount()) {
255 case 0: {
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))
260 break;
261 error = false;
262 break;
264 case 1: {
265 Dispatcher::Callback1 callback =
266 reinterpret_cast<Dispatcher::Callback1>(callback_generic);
267 if (!(handler->*callback)(&ipc_info, args[0]))
268 break;
269 error = false;
270 break;
272 case 2: {
273 Dispatcher::Callback2 callback =
274 reinterpret_cast<Dispatcher::Callback2>(callback_generic);
275 if (!(handler->*callback)(&ipc_info, args[0], args[1]))
276 break;
277 error = false;
278 break;
280 case 3: {
281 Dispatcher::Callback3 callback =
282 reinterpret_cast<Dispatcher::Callback3>(callback_generic);
283 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2]))
284 break;
285 error = false;
286 break;
288 case 4: {
289 Dispatcher::Callback4 callback =
290 reinterpret_cast<Dispatcher::Callback4>(callback_generic);
291 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2],
292 args[3]))
293 break;
294 error = false;
295 break;
297 case 5: {
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],
301 args[4]))
302 break;
303 error = false;
304 break;
306 case 6: {
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],
310 args[4], args[5]))
311 break;
312 error = false;
313 break;
315 case 7: {
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]))
320 break;
321 error = false;
322 break;
324 case 8: {
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]))
329 break;
330 error = false;
331 break;
333 case 9: {
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]))
338 break;
339 error = false;
340 break;
342 default: {
343 NOTREACHED();
344 break;
349 if (error) {
350 if (handler)
351 SetCallError(SBOX_ERROR_FAILED_IPC, call_result);
352 } else {
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
357 // memory section.
358 memcpy(ipc_buffer, params.get(), output_size);
362 ReleaseArgs(&ipc_params, args);
364 return !error;
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()
369 // call above.
370 void __stdcall SharedMemIPCServer::ThreadPingEventReady(void* context,
371 unsigned char) {
372 if (NULL == context) {
373 DCHECK(false);
374 return;
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.
379 LONG last_state =
380 ::InterlockedCompareExchange(&service_context->channel->state,
381 kAckChannel, kBusyChannel);
382 if (kBusyChannel != last_state) {
383 DCHECK(false);
384 return;
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,
413 0)) {
414 return false;
417 server_pong->Set(::CreateEventW(NULL, FALSE, FALSE, NULL));
418 if (!::DuplicateHandle(::GetCurrentProcess(), server_pong->Get(),
419 target_process_, client_pong, kDesiredAccess, FALSE,
420 0)) {
421 return false;
423 return true;
426 } // namespace sandbox