summaryrefslogtreecommitdiffstats
path: root/content/browser/browser_io_surface_manager_mac.cc
blob: 01225b911f5cb1635363e930879b2fd2bfea0cc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/browser_io_surface_manager_mac.h"

#include <servers/bootstrap.h>

#include <string>

#include "base/logging.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mach_logging.h"
#include "base/strings/stringprintf.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"

namespace content {
namespace {

// Returns the Mach port name to use when sending or receiving messages. |pid|
// is the process ID of the service.
std::string GetMachPortName(pid_t pid) {
  return base::StringPrintf("%s.iosurfacemgr.%d", base::mac::BaseBundleID(),
                            pid);
}

// Amount of time to wait before giving up when sending a reply message.
const int kSendReplyTimeoutMs = 100;

}  // namespace

// static
BrowserIOSurfaceManager* BrowserIOSurfaceManager::GetInstance() {
  return Singleton<BrowserIOSurfaceManager,
                   LeakySingletonTraits<BrowserIOSurfaceManager>>::get();
}

// static
base::mac::ScopedMachSendRight BrowserIOSurfaceManager::LookupServicePort(
    pid_t pid) {
  // Look up the named IOSurfaceManager port that's been registered with
  // the bootstrap server.
  mach_port_t port;
  kern_return_t kr =
      bootstrap_look_up(bootstrap_port, GetMachPortName(pid).c_str(), &port);
  if (kr != KERN_SUCCESS) {
    BOOTSTRAP_LOG(ERROR, kr) << "bootstrap_look_up";
    return base::mac::ScopedMachSendRight();
  }

  return base::mac::ScopedMachSendRight(port);
}

bool BrowserIOSurfaceManager::RegisterIOSurface(int io_surface_id,
                                                int client_id,
                                                IOSurfaceRef io_surface) {
  base::AutoLock lock(lock_);

  IOSurfaceMapKey key(io_surface_id, client_id);
  DCHECK(io_surfaces_.find(key) == io_surfaces_.end());
  io_surfaces_.add(key, make_scoped_ptr(new base::mac::ScopedMachSendRight(
                            IOSurfaceCreateMachPort(io_surface))));
  return true;
}

void BrowserIOSurfaceManager::UnregisterIOSurface(int io_surface_id,
                                                  int client_id) {
  base::AutoLock lock(lock_);

  IOSurfaceMapKey key(io_surface_id, client_id);
  DCHECK(io_surfaces_.find(key) != io_surfaces_.end());
  io_surfaces_.erase(key);
}

IOSurfaceRef BrowserIOSurfaceManager::AcquireIOSurface(int io_surface_id) {
  base::AutoLock lock(lock_);

  IOSurfaceMapKey key(
      io_surface_id,
      BrowserGpuChannelHostFactory::instance()->GetGpuChannelId());
  auto it = io_surfaces_.find(key);
  if (it == io_surfaces_.end()) {
    LOG(ERROR) << "Invalid Id for IOSurface " << io_surface_id;
    return nullptr;
  }

  return IOSurfaceLookupFromMachPort(it->second->get());
}

void BrowserIOSurfaceManager::EnsureRunning() {
  base::AutoLock lock(lock_);

  if (initialized_)
    return;

  // Do not attempt to reinitialize in the event of failure.
  initialized_ = true;

  if (!Initialize()) {
    LOG(ERROR) << "Failed to initialize the BrowserIOSurfaceManager";
  }
}

IOSurfaceManagerToken BrowserIOSurfaceManager::GetGpuProcessToken() const {
  return gpu_process_token_;
}

IOSurfaceManagerToken BrowserIOSurfaceManager::GenerateChildProcessToken(
    int child_process_id) {
  base::AutoLock lock(lock_);

  IOSurfaceManagerToken token = IOSurfaceManagerToken::Generate();
  DCHECK(token.Verify());
  child_process_ids_[token] = child_process_id;
  return token;
}

void BrowserIOSurfaceManager::InvalidateChildProcessToken(
    const IOSurfaceManagerToken& token) {
  base::AutoLock lock(lock_);

  DCHECK(child_process_ids_.find(token) != child_process_ids_.end());
  child_process_ids_.erase(token);
}

BrowserIOSurfaceManager::BrowserIOSurfaceManager()
    : initialized_(false),
      gpu_process_token_(IOSurfaceManagerToken::Generate()) {
  DCHECK(gpu_process_token_.Verify());
}

BrowserIOSurfaceManager::~BrowserIOSurfaceManager() {
}

bool BrowserIOSurfaceManager::Initialize() {
  lock_.AssertAcquired();
  DCHECK(!server_port_.is_valid());

  // Check in with launchd and publish the service name.
  mach_port_t port;
  kern_return_t kr = bootstrap_check_in(
      bootstrap_port, GetMachPortName(getpid()).c_str(), &port);
  if (kr != KERN_SUCCESS) {
    BOOTSTRAP_LOG(ERROR, kr) << "bootstrap_check_in";
    return false;
  }
  server_port_.reset(port);

  // Start the dispatch source.
  std::string queue_name =
      base::StringPrintf("%s.IOSurfaceManager", base::mac::BaseBundleID());
  dispatch_source_.reset(
      new base::DispatchSourceMach(queue_name.c_str(), server_port_.get(), ^{
        HandleRequest();
      }));
  dispatch_source_->Resume();

  return true;
}

void BrowserIOSurfaceManager::HandleRequest() {
  struct {
    union {
      mach_msg_header_t header;
      IOSurfaceManagerHostMsg_RegisterIOSurface register_io_surface;
      IOSurfaceManagerHostMsg_UnregisterIOSurface unregister_io_surface;
      IOSurfaceManagerHostMsg_AcquireIOSurface acquire_io_surface;
    } msg;
    mach_msg_trailer_t trailer;
  } request = {{{0}}};
  request.msg.header.msgh_size = sizeof(request);
  request.msg.header.msgh_local_port = server_port_.get();

  kern_return_t kr =
      mach_msg(&request.msg.header, MACH_RCV_MSG, 0, sizeof(request),
               server_port_, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  if (kr != KERN_SUCCESS) {
    MACH_LOG(ERROR, kr) << "mach_msg";
    return;
  }

  union {
    mach_msg_header_t header;
    IOSurfaceManagerMsg_RegisterIOSurfaceReply register_io_surface;
    IOSurfaceManagerMsg_AcquireIOSurfaceReply acquire_io_surface;
  } reply = {{0}};

  switch (request.msg.header.msgh_id) {
    case IOSurfaceManagerHostMsg_RegisterIOSurface::ID:
      if (!HandleRegisterIOSurfaceRequest(request.msg.register_io_surface,
                                          &reply.register_io_surface)) {
        return;
      }
      break;
    case IOSurfaceManagerHostMsg_UnregisterIOSurface::ID:
      HandleUnregisterIOSurfaceRequest(request.msg.unregister_io_surface);
      // Unregister requests are asynchronous and do not require a reply as
      // there is no guarantee for how quickly an IO surface is removed from
      // the IOSurfaceManager instance after it has been deleted by a child
      // process.
      return;
    case IOSurfaceManagerHostMsg_AcquireIOSurface::ID:
      if (!HandleAcquireIOSurfaceRequest(request.msg.acquire_io_surface,
                                         &reply.acquire_io_surface)) {
        return;
      }
      break;
    default:
      LOG(ERROR) << "Unknown message received!";
      return;
  }

  kr = mach_msg(&reply.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT,
                reply.header.msgh_size, 0, MACH_PORT_NULL, kSendReplyTimeoutMs,
                MACH_PORT_NULL);
  if (kr != KERN_SUCCESS) {
    MACH_LOG(ERROR, kr) << "mach_msg";
  }
}

bool BrowserIOSurfaceManager::HandleRegisterIOSurfaceRequest(
    const IOSurfaceManagerHostMsg_RegisterIOSurface& request,
    IOSurfaceManagerMsg_RegisterIOSurfaceReply* reply) {
  base::AutoLock lock(lock_);

  IOSurfaceManagerToken token;
  static_assert(sizeof(request.token_name) == sizeof(token.name),
                "Mach message token size doesn't match expectation.");
  token.SetName(request.token_name);
  if (token != gpu_process_token_) {
    LOG(ERROR) << "Illegal message from non-GPU process!";
    return false;
  }

  IOSurfaceMapKey key(request.io_surface_id, request.client_id);
  io_surfaces_.add(key, make_scoped_ptr(new base::mac::ScopedMachSendRight(
                            request.io_surface_port.name)));

  reply->header.msgh_bits = MACH_MSGH_BITS_REMOTE(request.header.msgh_bits);
  reply->header.msgh_remote_port = request.header.msgh_remote_port;
  reply->header.msgh_size = sizeof(*reply);
  reply->result = true;
  return true;
}

bool BrowserIOSurfaceManager::HandleUnregisterIOSurfaceRequest(
    const IOSurfaceManagerHostMsg_UnregisterIOSurface& request) {
  base::AutoLock lock(lock_);

  IOSurfaceManagerToken token;
  static_assert(sizeof(request.token_name) == sizeof(token.name),
                "Mach message token size doesn't match expectation.");
  token.SetName(request.token_name);
  if (token != gpu_process_token_) {
    LOG(ERROR) << "Illegal message from non-GPU process!";
    return false;
  }

  IOSurfaceMapKey key(request.io_surface_id, request.client_id);
  io_surfaces_.erase(key);
  return true;
}

bool BrowserIOSurfaceManager::HandleAcquireIOSurfaceRequest(
    const IOSurfaceManagerHostMsg_AcquireIOSurface& request,
    IOSurfaceManagerMsg_AcquireIOSurfaceReply* reply) {
  base::AutoLock lock(lock_);

  IOSurfaceManagerToken token;
  static_assert(sizeof(request.token_name) == sizeof(token.name),
                "Mach message token size doesn't match expectation.");
  token.SetName(request.token_name);
  auto child_process_id_it = child_process_ids_.find(token);
  if (child_process_id_it == child_process_ids_.end()) {
    LOG(ERROR) << "Illegal message from non-child process!";
    return false;
  }

  IOSurfaceMapKey key(request.io_surface_id, child_process_id_it->second);
  auto it = io_surfaces_.find(key);
  if (it == io_surfaces_.end()) {
    LOG(ERROR) << "Invalid Id for IOSurface " << request.io_surface_id;
    return false;
  }

  reply->header.msgh_bits =
      MACH_MSGH_BITS_REMOTE(request.header.msgh_bits) | MACH_MSGH_BITS_COMPLEX;
  reply->header.msgh_remote_port = request.header.msgh_remote_port;
  reply->header.msgh_size = sizeof(*reply);
  reply->body.msgh_descriptor_count = 1;
  reply->io_surface_port.name = it->second->get();
  reply->io_surface_port.disposition = MACH_MSG_TYPE_COPY_SEND;
  reply->io_surface_port.type = MACH_MSG_PORT_DESCRIPTOR;
  return true;
}

}  // namespace content