1 // Copyright (c) 2011 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 "content/browser/mach_broker_mac.h"
7 #include <bsm/libbsm.h>
8 #include <servers/bootstrap.h>
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/command_line.h"
13 #include "base/logging.h"
14 #include "base/mac/foundation_util.h"
15 #include "base/mac/scoped_mach_port.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/sys_string_conversions.h"
19 #include "base/threading/platform_thread.h"
20 #include "content/browser/renderer_host/render_process_host_impl.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/child_process_data.h"
23 #include "content/public/browser/notification_service.h"
24 #include "content/public/browser/notification_types.h"
25 #include "content/public/common/content_switches.h"
31 // Prints a string representation of a Mach error code.
32 std::string MachErrorCode(kern_return_t err) {
33 return base::StringPrintf("0x%x %s", err, mach_error_string(err));
36 // Mach message structure used in the child as a sending message.
37 struct MachBroker_ChildSendMsg {
38 mach_msg_header_t header;
40 mach_msg_port_descriptor_t child_task_port;
43 // Complement to the ChildSendMsg, this is used in the parent for receiving
44 // a message. Contains a message trailer with audit information.
45 struct MachBroker_ParentRecvMsg : public MachBroker_ChildSendMsg {
46 mach_msg_audit_trailer_t trailer;
51 class MachListenerThreadDelegate : public base::PlatformThread::Delegate {
53 explicit MachListenerThreadDelegate(MachBroker* broker)
55 server_port_(MACH_PORT_NULL) {
60 DCHECK(server_port_ == MACH_PORT_NULL);
63 kern_return_t kr = mach_port_allocate(mach_task_self(),
64 MACH_PORT_RIGHT_RECEIVE,
66 if (kr != KERN_SUCCESS) {
67 LOG(ERROR) << "Failed to allocate MachBroker server port: "
72 // Allocate a send right for the server port.
73 kr = mach_port_insert_right(
74 mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND);
75 if (kr != KERN_SUCCESS) {
76 LOG(ERROR) << "Failed to insert send right for MachBroker server port: "
81 server_port_.reset(port);
83 // Register the port with the bootstrap server. Because bootstrap_register
84 // is deprecated, this has to be wraped in an ObjC interface.
85 NSPort* ns_port = [NSMachPort portWithMachPort:port
86 options:NSMachPortDeallocateNone];
87 NSString* name = base::SysUTF8ToNSString(broker_->GetMachPortName());
88 return [[NSMachBootstrapServer sharedInstance] registerPort:ns_port
92 // Implement |PlatformThread::Delegate|.
93 virtual void ThreadMain() OVERRIDE {
94 MachBroker_ParentRecvMsg msg;
95 bzero(&msg, sizeof(msg));
96 msg.header.msgh_size = sizeof(msg);
97 msg.header.msgh_local_port = server_port_.get();
101 // Use the kernel audit information to make sure this message is from
102 // a task that this process spawned. The kernel audit token contains the
103 // unspoofable pid of the task that sent the message.
104 mach_msg_option_t options = MACH_RCV_MSG |
105 MACH_RCV_TRAILER_TYPE(MACH_RCV_TRAILER_AUDIT) |
106 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT);
108 kr = mach_msg(&msg.header, options, 0, sizeof(msg), server_port_,
109 MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
110 if (kr == KERN_SUCCESS) {
111 // TODO(rsesek): In the 10.7 SDK, there's audit_token_to_pid().
113 audit_token_to_au32(msg.trailer.msgh_audit,
114 NULL, NULL, NULL, NULL, NULL, &child_pid, NULL, NULL);
116 mach_port_t child_task_port = msg.child_task_port.name;
118 // Take the lock and update the broker information.
119 base::AutoLock lock(broker_->GetLock());
120 broker_->FinalizePid(child_pid, child_task_port);
122 } while (kr == KERN_SUCCESS);
124 LOG(ERROR) << "MachBroker thread exiting; mach_msg() likely failed: "
125 << MachErrorCode(kr);
129 // The MachBroker to use when new child task rights are received. Can be
131 MachBroker* broker_; // weak
133 base::mac::ScopedMachPort server_port_;
135 DISALLOW_COPY_AND_ASSIGN(MachListenerThreadDelegate);
138 bool MachBroker::ChildSendTaskPortToParent() {
139 // Look up the named MachBroker port that's been registered with the
141 mach_port_t bootstrap_port;
142 kern_return_t kr = task_get_bootstrap_port(mach_task_self(), &bootstrap_port);
143 if (kr != KERN_SUCCESS) {
144 LOG(ERROR) << "Failed to look up bootstrap port: " << MachErrorCode(kr);
148 mach_port_t parent_port;
149 kr = bootstrap_look_up(bootstrap_port,
150 const_cast<char*>(GetMachPortName().c_str()), &parent_port);
151 if (kr != KERN_SUCCESS) {
152 LOG(ERROR) << "Failed to look up named parent port: " << MachErrorCode(kr);
156 // Create the check in message. This will copy a send right on this process'
157 // (the child's) task port and send it to the parent.
158 MachBroker_ChildSendMsg msg;
159 bzero(&msg, sizeof(msg));
160 msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND) |
161 MACH_MSGH_BITS_COMPLEX;
162 msg.header.msgh_remote_port = parent_port;
163 msg.header.msgh_size = sizeof(msg);
164 msg.body.msgh_descriptor_count = 1;
165 msg.child_task_port.name = mach_task_self();
166 msg.child_task_port.disposition = MACH_MSG_TYPE_PORT_SEND;
167 msg.child_task_port.type = MACH_MSG_PORT_DESCRIPTOR;
169 kr = mach_msg(&msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(msg),
170 0, MACH_PORT_NULL, 100 /*milliseconds*/, MACH_PORT_NULL);
171 if (kr != KERN_SUCCESS) {
172 LOG(ERROR) << "Failed to send task port to parent: " << MachErrorCode(kr);
179 MachBroker* MachBroker::GetInstance() {
180 return Singleton<MachBroker, LeakySingletonTraits<MachBroker> >::get();
183 base::Lock& MachBroker::GetLock() {
187 void MachBroker::EnsureRunning() {
188 lock_.AssertAcquired();
190 if (!listener_thread_started_) {
191 listener_thread_started_ = true;
193 BrowserThread::PostTask(
194 BrowserThread::UI, FROM_HERE,
195 base::Bind(&MachBroker::RegisterNotifications, base::Unretained(this)));
197 // Intentional leak. This thread is never joined or reaped.
198 MachListenerThreadDelegate* thread = new MachListenerThreadDelegate(this);
199 if (thread->Init()) {
200 base::PlatformThread::CreateNonJoinable(0, thread);
202 LOG(ERROR) << "Failed to initialize the MachListenerThreadDelegate";
207 void MachBroker::AddPlaceholderForPid(base::ProcessHandle pid) {
208 lock_.AssertAcquired();
210 DCHECK_EQ(0u, mach_map_.count(pid));
211 mach_map_[pid] = MACH_PORT_NULL;
214 mach_port_t MachBroker::TaskForPid(base::ProcessHandle pid) const {
215 base::AutoLock lock(lock_);
216 MachBroker::MachMap::const_iterator it = mach_map_.find(pid);
217 if (it == mach_map_.end())
218 return MACH_PORT_NULL;
222 void MachBroker::BrowserChildProcessHostDisconnected(
223 const ChildProcessData& data) {
224 InvalidatePid(data.handle);
227 void MachBroker::BrowserChildProcessCrashed(const ChildProcessData& data) {
228 InvalidatePid(data.handle);
231 void MachBroker::Observe(int type,
232 const NotificationSource& source,
233 const NotificationDetails& details) {
234 // TODO(rohitrao): These notifications do not always carry the proper PIDs,
235 // especially when the renderer is already gone or has crashed. Find a better
236 // way to listen for child process deaths. http://crbug.com/55734
237 base::ProcessHandle handle = 0;
239 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
240 handle = Details<RenderProcessHost::RendererClosedDetails>(
243 case NOTIFICATION_RENDERER_PROCESS_TERMINATED:
244 handle = Source<RenderProcessHost>(source)->GetHandle();
247 NOTREACHED() << "Unexpected notification";
250 InvalidatePid(handle);
253 MachBroker::MachBroker() : listener_thread_started_(false) {
256 MachBroker::~MachBroker() {}
258 void MachBroker::FinalizePid(base::ProcessHandle pid,
259 mach_port_t task_port) {
260 lock_.AssertAcquired();
262 MachMap::iterator it = mach_map_.find(pid);
263 if (it == mach_map_.end()) {
264 // Do nothing for unknown pids.
265 LOG(ERROR) << "Unknown process " << pid << " is sending Mach IPC messages!";
269 DCHECK(it->second == MACH_PORT_NULL);
270 if (it->second == MACH_PORT_NULL)
271 it->second = task_port;
274 void MachBroker::InvalidatePid(base::ProcessHandle pid) {
275 base::AutoLock lock(lock_);
276 MachBroker::MachMap::iterator it = mach_map_.find(pid);
277 if (it == mach_map_.end())
280 kern_return_t kr = mach_port_deallocate(mach_task_self(),
282 LOG_IF(WARNING, kr != KERN_SUCCESS)
283 << "Failed to mach_port_deallocate mach task " << it->second
284 << ", error " << MachErrorCode(kr);
289 std::string MachBroker::GetMachPortName() {
290 const CommandLine* command_line = CommandLine::ForCurrentProcess();
291 const bool is_child = command_line->HasSwitch(switches::kProcessType);
293 // In non-browser (child) processes, use the parent's pid.
294 const pid_t pid = is_child ? getppid() : getpid();
295 return base::StringPrintf("%s.rohitfork.%d", base::mac::BaseBundleID(), pid);
298 void MachBroker::RegisterNotifications() {
299 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
300 NotificationService::AllBrowserContextsAndSources());
301 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_TERMINATED,
302 NotificationService::AllBrowserContextsAndSources());
304 // No corresponding StopObservingBrowserChildProcesses,
305 // we leak this singleton.
306 BrowserChildProcessObserver::Add(this);
309 } // namespace content