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/mach_logging.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/sys_string_conversions.h"
19 #include "content/browser/renderer_host/render_process_host_impl.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "content/public/browser/child_process_data.h"
22 #include "content/public/browser/notification_service.h"
23 #include "content/public/browser/notification_types.h"
24 #include "content/public/common/content_switches.h"
30 // Mach message structure used in the child as a sending message.
31 struct MachBroker_ChildSendMsg {
32 mach_msg_header_t header;
34 mach_msg_port_descriptor_t child_task_port;
37 // Complement to the ChildSendMsg, this is used in the parent for receiving
38 // a message. Contains a message trailer with audit information.
39 struct MachBroker_ParentRecvMsg : public MachBroker_ChildSendMsg {
40 mach_msg_audit_trailer_t trailer;
45 bool MachBroker::ChildSendTaskPortToParent() {
46 // Look up the named MachBroker port that's been registered with the
48 mach_port_t parent_port;
49 kern_return_t kr = bootstrap_look_up(bootstrap_port,
50 const_cast<char*>(GetMachPortName().c_str()), &parent_port);
51 if (kr != KERN_SUCCESS) {
52 BOOTSTRAP_LOG(ERROR, kr) << "bootstrap_look_up";
55 base::mac::ScopedMachSendRight scoped_right(parent_port);
57 // Create the check in message. This will copy a send right on this process'
58 // (the child's) task port and send it to the parent.
59 MachBroker_ChildSendMsg msg;
60 bzero(&msg, sizeof(msg));
61 msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND) |
62 MACH_MSGH_BITS_COMPLEX;
63 msg.header.msgh_remote_port = parent_port;
64 msg.header.msgh_size = sizeof(msg);
65 msg.body.msgh_descriptor_count = 1;
66 msg.child_task_port.name = mach_task_self();
67 msg.child_task_port.disposition = MACH_MSG_TYPE_PORT_SEND;
68 msg.child_task_port.type = MACH_MSG_PORT_DESCRIPTOR;
70 kr = mach_msg(&msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(msg),
71 0, MACH_PORT_NULL, 100 /*milliseconds*/, MACH_PORT_NULL);
72 if (kr != KERN_SUCCESS) {
73 MACH_LOG(ERROR, kr) << "mach_msg";
80 MachBroker* MachBroker::GetInstance() {
81 return Singleton<MachBroker, LeakySingletonTraits<MachBroker>>::get();
84 base::Lock& MachBroker::GetLock() {
88 void MachBroker::EnsureRunning() {
89 lock_.AssertAcquired();
94 // Do not attempt to reinitialize in the event of failure.
97 BrowserThread::PostTask(
98 BrowserThread::UI, FROM_HERE,
99 base::Bind(&MachBroker::RegisterNotifications, base::Unretained(this)));
102 LOG(ERROR) << "Failed to initialize the MachListenerThreadDelegate";
106 void MachBroker::AddPlaceholderForPid(base::ProcessHandle pid,
107 int child_process_id) {
108 lock_.AssertAcquired();
110 DCHECK_EQ(0u, mach_map_.count(pid));
111 mach_map_[pid] = MACH_PORT_NULL;
112 child_process_id_map_[child_process_id] = pid;
115 mach_port_t MachBroker::TaskForPid(base::ProcessHandle pid) const {
116 base::AutoLock lock(lock_);
117 MachBroker::MachMap::const_iterator it = mach_map_.find(pid);
118 if (it == mach_map_.end())
119 return MACH_PORT_NULL;
123 void MachBroker::BrowserChildProcessHostDisconnected(
124 const ChildProcessData& data) {
125 InvalidateChildProcessId(data.id);
128 void MachBroker::BrowserChildProcessCrashed(const ChildProcessData& data,
130 InvalidateChildProcessId(data.id);
133 void MachBroker::Observe(int type,
134 const NotificationSource& source,
135 const NotificationDetails& details) {
137 case NOTIFICATION_RENDERER_PROCESS_TERMINATED:
138 case NOTIFICATION_RENDERER_PROCESS_CLOSED: {
139 RenderProcessHost* host = Source<RenderProcessHost>(source).ptr();
140 InvalidateChildProcessId(host->GetID());
144 NOTREACHED() << "Unexpected notification";
149 MachBroker::MachBroker() : initialized_(false) {
152 MachBroker::~MachBroker() {}
154 bool MachBroker::Init() {
155 DCHECK(server_port_.get() == MACH_PORT_NULL);
157 // Check in with launchd and publish the service name.
160 bootstrap_check_in(bootstrap_port, GetMachPortName().c_str(), &port);
161 if (kr != KERN_SUCCESS) {
162 BOOTSTRAP_LOG(ERROR, kr) << "bootstrap_check_in";
165 server_port_.reset(port);
167 // Start the dispatch source.
168 std::string queue_name =
169 base::StringPrintf("%s.MachBroker", base::mac::BaseBundleID());
170 dispatch_source_.reset(new base::DispatchSourceMach(
171 queue_name.c_str(), server_port_.get(), ^{ HandleRequest(); }));
172 dispatch_source_->Resume();
177 void MachBroker::HandleRequest() {
178 MachBroker_ParentRecvMsg msg;
179 bzero(&msg, sizeof(msg));
180 msg.header.msgh_size = sizeof(msg);
181 msg.header.msgh_local_port = server_port_.get();
183 const mach_msg_option_t options = MACH_RCV_MSG |
184 MACH_RCV_TRAILER_TYPE(MACH_RCV_TRAILER_AUDIT) |
185 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT);
187 kern_return_t kr = mach_msg(&msg.header,
192 MACH_MSG_TIMEOUT_NONE,
194 if (kr != KERN_SUCCESS) {
195 MACH_LOG(ERROR, kr) << "mach_msg";
199 // Use the kernel audit information to make sure this message is from
200 // a task that this process spawned. The kernel audit token contains the
201 // unspoofable pid of the task that sent the message.
203 // TODO(rsesek): In the 10.7 SDK, there's audit_token_to_pid().
205 audit_token_to_au32(msg.trailer.msgh_audit,
206 NULL, NULL, NULL, NULL, NULL, &child_pid, NULL, NULL);
208 mach_port_t child_task_port = msg.child_task_port.name;
210 // Take the lock and update the broker information.
211 base::AutoLock lock(GetLock());
212 FinalizePid(child_pid, child_task_port);
215 void MachBroker::FinalizePid(base::ProcessHandle pid,
216 mach_port_t task_port) {
217 lock_.AssertAcquired();
219 MachMap::iterator it = mach_map_.find(pid);
220 if (it == mach_map_.end()) {
221 // Do nothing for unknown pids.
222 LOG(ERROR) << "Unknown process " << pid << " is sending Mach IPC messages!";
226 DCHECK(it->second == MACH_PORT_NULL);
227 if (it->second == MACH_PORT_NULL)
228 it->second = task_port;
231 void MachBroker::InvalidateChildProcessId(int child_process_id) {
232 base::AutoLock lock(lock_);
233 MachBroker::ChildProcessIdMap::iterator it =
234 child_process_id_map_.find(child_process_id);
235 if (it == child_process_id_map_.end())
238 MachMap::iterator mach_it = mach_map_.find(it->second);
239 if (mach_it != mach_map_.end()) {
240 kern_return_t kr = mach_port_deallocate(mach_task_self(),
242 MACH_LOG_IF(WARNING, kr != KERN_SUCCESS, kr) << "mach_port_deallocate";
243 mach_map_.erase(mach_it);
245 child_process_id_map_.erase(it);
249 std::string MachBroker::GetMachPortName() {
250 const base::CommandLine* command_line =
251 base::CommandLine::ForCurrentProcess();
252 const bool is_child = command_line->HasSwitch(switches::kProcessType);
254 // In non-browser (child) processes, use the parent's pid.
255 const pid_t pid = is_child ? getppid() : getpid();
256 return base::StringPrintf("%s.rohitfork.%d", base::mac::BaseBundleID(), pid);
259 void MachBroker::RegisterNotifications() {
260 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
261 NotificationService::AllBrowserContextsAndSources());
262 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_TERMINATED,
263 NotificationService::AllBrowserContextsAndSources());
265 // No corresponding StopObservingBrowserChildProcesses,
266 // we leak this singleton.
267 BrowserChildProcessObserver::Add(this);
270 } // namespace content