Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(334)

Side by Side Diff: content/browser/mach_broker_mac.mm

Issue 13845008: [Mac] Remove base::LaunchSynchronize and rewrite content::MachBroker. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « content/browser/mach_broker_mac.cc ('k') | content/browser/mach_broker_mac_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/browser/mach_broker_mac.h" 5 #include "content/browser/mach_broker_mac.h"
6 6
7 #include <bsm/libbsm.h>
8 #include <mach/mach.h>
9
7 #include "base/bind.h" 10 #include "base/bind.h"
8 #include "base/bind_helpers.h" 11 #include "base/bind_helpers.h"
9 #include "base/command_line.h" 12 #include "base/command_line.h"
10 #include "base/logging.h" 13 #include "base/logging.h"
11 #include "base/mac/foundation_util.h" 14 #include "base/mac/foundation_util.h"
15 #include "base/mac/scoped_mach_port.h"
12 #include "base/mach_ipc_mac.h" 16 #include "base/mach_ipc_mac.h"
13 #include "base/string_util.h" 17 #include "base/string_util.h"
14 #include "base/stringprintf.h" 18 #include "base/stringprintf.h"
15 #include "base/strings/sys_string_conversions.h" 19 #include "base/strings/sys_string_conversions.h"
16 #include "base/threading/platform_thread.h" 20 #include "base/threading/platform_thread.h"
17 #include "content/browser/renderer_host/render_process_host_impl.h" 21 #include "content/browser/renderer_host/render_process_host_impl.h"
18 #include "content/public/browser/child_process_data.h" 22 #include "content/public/browser/child_process_data.h"
19 #include "content/public/browser/browser_thread.h" 23 #include "content/public/browser/browser_thread.h"
20 #include "content/public/browser/notification_service.h" 24 #include "content/public/browser/notification_service.h"
21 #include "content/public/browser/notification_types.h" 25 #include "content/public/browser/notification_types.h"
22 #include "content/public/common/content_switches.h" 26 #include "content/public/common/content_switches.h"
23 27
24 namespace content { 28 namespace content {
25 29
26 namespace { 30 namespace {
31
27 // Prints a string representation of a Mach error code. 32 // Prints a string representation of a Mach error code.
28 std::string MachErrorCode(kern_return_t err) { 33 std::string MachErrorCode(kern_return_t err) {
29 return base::StringPrintf("0x%x %s", err, mach_error_string(err)); 34 return base::StringPrintf("0x%x %s", err, mach_error_string(err));
30 } 35 }
36
37 // Mach message structure used in the child as a sending message.
38 struct MachBroker_ChildSendMsg {
39 mach_msg_header_t header;
40 mach_msg_body_t body;
41 mach_msg_port_descriptor_t child_task_port;
42 };
43
44 // Complement to the ChildSendMsg, this is use din the parent for receiving
Mark Mentovai 2013/04/10 18:43:51 used in
Robert Sesek 2013/04/10 19:06:33 Done.
45 // a message. Contains a message trailer with audit information.
46 struct MachBroker_ParentRecvMsg : public MachBroker_ChildSendMsg {
47 mach_msg_audit_trailer_t trailer;
48 };
49
31 } // namespace 50 } // namespace
32 51
33 class MachListenerThreadDelegate : public base::PlatformThread::Delegate { 52 class MachListenerThreadDelegate : public base::PlatformThread::Delegate {
34 public: 53 public:
35 MachListenerThreadDelegate(MachBroker* broker) : broker_(broker) { 54 MachListenerThreadDelegate(MachBroker* broker)
Mark Mentovai 2013/04/10 18:43:51 explicit
Robert Sesek 2013/04/10 19:06:33 Done.
55 : broker_(broker),
56 server_port_(MACH_PORT_NULL) {
36 DCHECK(broker_); 57 DCHECK(broker_);
37 std::string port_name = MachBroker::GetMachPortName(); 58 }
38 59
39 // Create the receive port in the constructor, not in ThreadMain(). It is 60 bool Init() {
40 // important to create and register the receive port before starting the 61 mach_port_t port;
Mark Mentovai 2013/04/10 18:43:51 DCHECK that this isn’t called more than once (by c
Robert Sesek 2013/04/10 19:06:33 Done.
41 // thread so that child processes will always have someone who's listening. 62 kern_return_t kr = mach_port_allocate(mach_task_self(),
Mark Mentovai 2013/04/10 18:43:51 Cache mach_task_self() since you use it twice in t
Robert Sesek 2013/04/10 19:06:33 But mach_task_self() is really just a macro to mac
42 receive_port_.reset(new base::ReceivePort(port_name.c_str())); 63 MACH_PORT_RIGHT_RECEIVE,
64 &port);
65 if (kr != KERN_SUCCESS) {
66 LOG(ERROR) << "Failed to allocate MachBroker server port: "
67 << MachErrorCode(kr);
Mark Mentovai 2013/04/10 18:43:51 Alignment.
Robert Sesek 2013/04/10 19:06:33 Done.
68 return false;
69 }
70
71 // Allocate a send right for the server port.
72 kr = mach_port_insert_right(
73 mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND);
74 if (kr != KERN_SUCCESS) {
75 LOG(ERROR) << "Failed to insert send right for MachBroker server port: "
76 << MachErrorCode(kr);
77 return false;
78 }
79
80 server_port_.reset(port);
81
82 // Register the port with the bootstrap server. Because bootstrap_register
83 // is deprecated, this has to be wraped in an ObjC interface.
84 NSPort* ns_port = [NSMachPort portWithMachPort:port
85 options:NSMachPortDeallocateNone];
86 NSString* name = base::SysUTF8ToNSString(broker_->GetMachPortName());
87 return [[NSMachBootstrapServer sharedInstance] registerPort:ns_port
88 name:name];
Mark Mentovai 2013/04/10 18:43:51 Any time you register stuff with the bootstrap ser
Robert Sesek 2013/04/10 19:06:33 Yes. This uses the same thing as mach_ipc_mac, so
43 } 89 }
44 90
45 // Implement |PlatformThread::Delegate|. 91 // Implement |PlatformThread::Delegate|.
46 virtual void ThreadMain() OVERRIDE { 92 virtual void ThreadMain() OVERRIDE {
47 base::MachReceiveMessage message; 93 MachBroker_ParentRecvMsg msg;
48 kern_return_t err; 94 bzero(&msg, sizeof(msg));
Mark Mentovai 2013/04/10 18:43:51 It’s more usual in Chrome code to write msg = { 0
Robert Sesek 2013/04/10 19:06:33 The compiler says: error: no matching constructor
49 while ((err = receive_port_->WaitForMessage(&message, 95 msg.header.msgh_size = sizeof(msg);
50 MACH_MSG_TIMEOUT_NONE)) == 96 msg.header.msgh_local_port = server_port_.get();
51 KERN_SUCCESS) { 97
52 // 0 was the secret message id. Reject any messages that don't have it. 98 kern_return_t kr;
53 if (message.GetMessageID() != 0) { 99 do {
54 LOG(ERROR) << "Received message with incorrect id: " 100 // Use the kernel audit information to make sure this message is from
55 << message.GetMessageID(); 101 // a task that this process spawned. The kernel audit token contains the
56 continue; 102 // unspoofable pid of the task that sent the message.
103 mach_msg_option_t options = MACH_RCV_MSG |
104 MACH_RCV_TRAILER_TYPE(MACH_RCV_TRAILER_AUDIT) |
105 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT);
106
107 kr = mach_msg(&msg.header, options, 0, sizeof(msg), server_port_,
108 MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
109 if (kr == KERN_SUCCESS) {
110 // TODO(rsesek): In the 10.7 SDK, there's audit_token_to_pid().
111 pid_t child_pid;
112 audit_token_to_au32(msg.trailer.msgh_audit,
113 NULL, NULL, NULL, NULL, NULL, &child_pid, NULL, NULL);
114
115 mach_port_t child_task_port = msg.child_task_port.name;
116
117 // Take the lock and update the broker information.
118 base::AutoLock lock(broker_->GetLock());
119 broker_->FinalizePid(child_pid, child_task_port);
57 } 120 }
121 } while (kr == KERN_SUCCESS);
58 122
59 const task_t child_task = message.GetTranslatedPort(0); 123 LOG(ERROR) << "MachBroker thread exiting; mach_msg() likely failed: "
60 if (child_task == MACH_PORT_NULL) { 124 << MachErrorCode(kr);
61 LOG(ERROR) << "parent GetTranslatedPort(0) failed.";
62 continue;
63 }
64
65 // It is possible for the child process to die after the call to
66 // |pid_for_task()| but before the call to |FinalizePid()|. To prevent
67 // leaking MachBroker map entries in this case, lock around both these
68 // calls. If the child dies, the death notification will be processed
69 // after the call to FinalizePid(), ensuring proper cleanup.
70 base::AutoLock lock(broker_->GetLock());
71
72 int pid;
73 err = pid_for_task(child_task, &pid);
74 if (err == KERN_SUCCESS) {
75 broker_->FinalizePid(pid,
76 MachBroker::MachInfo().SetTask(child_task));
77 } else {
78 LOG(ERROR) << "Error getting pid for task " << child_task
79 << ": " << MachErrorCode(err);
80 }
81 }
82
83 LOG(ERROR) << "Mach listener thread exiting; "
84 << "parent WaitForMessage() likely failed: "
85 << MachErrorCode(err);
86 } 125 }
87 126
88 private: 127 private:
89 // The Mach port to listen on. Created on thread startup.
90 scoped_ptr<base::ReceivePort> receive_port_;
91
92 // The MachBroker to use when new child task rights are received. Can be 128 // The MachBroker to use when new child task rights are received. Can be
93 // NULL. 129 // NULL.
94 MachBroker* broker_; // weak 130 MachBroker* broker_; // weak
95 131
132 base::mac::ScopedMachPort server_port_;
133
96 DISALLOW_COPY_AND_ASSIGN(MachListenerThreadDelegate); 134 DISALLOW_COPY_AND_ASSIGN(MachListenerThreadDelegate);
97 }; 135 };
98 136
99 // Returns the global MachBroker. 137 bool MachBroker::ChildSendTaskPortToParent() {
138 // Look up the named MachBroker port that's been registered with the
139 // bootstrap server.
140 mach_port_t bootstrap_port;
141 kern_return_t kr = task_get_bootstrap_port(mach_task_self(), &bootstrap_port);
Mark Mentovai 2013/04/10 18:43:51 Cache mach_task_self in this function too.
Robert Sesek 2013/04/10 19:06:33 Same as above.
142 if (kr != KERN_SUCCESS) {
143 LOG(ERROR) << "Failed to look up bootstrap port: " << MachErrorCode(kr);
144 return false;
145 }
146
147 mach_port_t parent_port;
148 kr = bootstrap_look_up(bootstrap_port,
149 const_cast<char*>(GetMachPortName().c_str()), &parent_port);
150 if (kr != KERN_SUCCESS) {
151 LOG(ERROR) << "Failed to look up named parent port: " << MachErrorCode(kr);
152 return false;
153 }
154
155 // Create the check in message. This will copy a send right on this' (the
Mark Mentovai 2013/04/10 18:43:51 this'?
Robert Sesek 2013/04/10 19:06:33 Done.
156 // child's) task port and send it to the parent.
157 MachBroker_ChildSendMsg msg;
Mark Mentovai 2013/04/10 18:43:51 = {0}
158 bzero(&msg, sizeof(msg));
159 msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND) |
160 MACH_MSGH_BITS_COMPLEX;
161 msg.header.msgh_remote_port = parent_port;
162 msg.header.msgh_size = sizeof(msg);
163 msg.body.msgh_descriptor_count = 1;
164 msg.child_task_port.name = mach_task_self();
165 msg.child_task_port.disposition = MACH_MSG_TYPE_PORT_SEND;
166 msg.child_task_port.type = MACH_MSG_PORT_DESCRIPTOR;
167
168 kr = mach_msg(&msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(msg),
169 0, MACH_PORT_NULL, 100 /*milliseconds*/, MACH_PORT_NULL);
Mark Mentovai 2013/04/10 18:43:51 Why even bother timing out OR why 100ms? You’re go
Robert Sesek 2013/04/10 19:06:33 This is what the old one did. I dunno. Ask Rohit.
170 if (kr != KERN_SUCCESS) {
171 LOG(ERROR) << "Failed to send task port to parent: " << MachErrorCode(kr);
172 return false;
173 }
174
175 return true;
176 }
177
100 MachBroker* MachBroker::GetInstance() { 178 MachBroker* MachBroker::GetInstance() {
101 return Singleton<MachBroker, LeakySingletonTraits<MachBroker> >::get(); 179 return Singleton<MachBroker, LeakySingletonTraits<MachBroker> >::get();
102 } 180 }
103 181
182 base::Lock& MachBroker::GetLock() {
183 return lock_;
184 }
185
104 void MachBroker::EnsureRunning() { 186 void MachBroker::EnsureRunning() {
105 lock_.AssertAcquired(); 187 lock_.AssertAcquired();
106 188
107 if (!listener_thread_started_) { 189 if (!listener_thread_started_) {
108 listener_thread_started_ = true; 190 listener_thread_started_ = true;
109 191
110 BrowserThread::PostTask( 192 BrowserThread::PostTask(
111 BrowserThread::UI, FROM_HERE, 193 BrowserThread::UI, FROM_HERE,
112 base::Bind(&MachBroker::RegisterNotifications, base::Unretained(this))); 194 base::Bind(&MachBroker::RegisterNotifications, base::Unretained(this)));
113 195
114 // Intentional leak. This thread is never joined or reaped. 196 // Intentional leak. This thread is never joined or reaped.
115 base::PlatformThread::CreateNonJoinable( 197 MachListenerThreadDelegate* thread = new MachListenerThreadDelegate(this);
116 0, new MachListenerThreadDelegate(this)); 198 if (thread->Init()) {
199 base::PlatformThread::CreateNonJoinable(0, thread);
200 } else {
201 LOG(ERROR) << "Failed to initialize the MachListenerThreadDelegate";
202 }
117 } 203 }
118 } 204 }
119 205
120 // Adds a placeholder to the map for the given pid with MACH_PORT_NULL.
121 void MachBroker::AddPlaceholderForPid(base::ProcessHandle pid) { 206 void MachBroker::AddPlaceholderForPid(base::ProcessHandle pid) {
122 lock_.AssertAcquired(); 207 lock_.AssertAcquired();
123 208
124 MachInfo mach_info;
125 DCHECK_EQ(0u, mach_map_.count(pid)); 209 DCHECK_EQ(0u, mach_map_.count(pid));
126 mach_map_[pid] = mach_info; 210 mach_map_[pid] = MACH_PORT_NULL;
127 } 211 }
128 212
129 // Updates the mapping for |pid| to include the given |mach_info|.
130 void MachBroker::FinalizePid(base::ProcessHandle pid,
131 const MachInfo& mach_info) {
132 lock_.AssertAcquired();
133
134 const int count = mach_map_.count(pid);
135 if (count == 0) {
136 // Do nothing for unknown pids.
137 LOG(ERROR) << "Unknown process " << pid << " is sending Mach IPC messages!";
138 return;
139 }
140
141 DCHECK_EQ(1, count);
142 DCHECK(mach_map_[pid].mach_task_ == MACH_PORT_NULL);
143 if (mach_map_[pid].mach_task_ == MACH_PORT_NULL)
144 mach_map_[pid] = mach_info;
145 }
146
147 // Removes all mappings belonging to |pid| from the broker.
148 void MachBroker::InvalidatePid(base::ProcessHandle pid) {
149 base::AutoLock lock(lock_);
150 MachBroker::MachMap::iterator it = mach_map_.find(pid);
151 if (it == mach_map_.end())
152 return;
153
154 kern_return_t kr = mach_port_deallocate(mach_task_self(),
155 it->second.mach_task_);
156 LOG_IF(WARNING, kr != KERN_SUCCESS)
157 << "Failed to mach_port_deallocate mach task " << it->second.mach_task_
158 << ", error " << MachErrorCode(kr);
159 mach_map_.erase(it);
160 }
161
162 base::Lock& MachBroker::GetLock() {
163 return lock_;
164 }
165
166 // Returns the mach task belonging to |pid|.
167 mach_port_t MachBroker::TaskForPid(base::ProcessHandle pid) const { 213 mach_port_t MachBroker::TaskForPid(base::ProcessHandle pid) const {
168 base::AutoLock lock(lock_); 214 base::AutoLock lock(lock_);
169 MachBroker::MachMap::const_iterator it = mach_map_.find(pid); 215 MachBroker::MachMap::const_iterator it = mach_map_.find(pid);
170 if (it == mach_map_.end()) 216 if (it == mach_map_.end())
171 return MACH_PORT_NULL; 217 return MACH_PORT_NULL;
172 return it->second.mach_task_; 218 return it->second;
173 } 219 }
174 220
175 void MachBroker::BrowserChildProcessHostDisconnected( 221 void MachBroker::BrowserChildProcessHostDisconnected(
176 const ChildProcessData& data) { 222 const ChildProcessData& data) {
177 InvalidatePid(data.handle); 223 InvalidatePid(data.handle);
178 } 224 }
179 225
180 void MachBroker::BrowserChildProcessCrashed(const ChildProcessData& data) { 226 void MachBroker::BrowserChildProcessCrashed(const ChildProcessData& data) {
181 InvalidatePid(data.handle); 227 InvalidatePid(data.handle);
182 } 228 }
(...skipping 13 matching lines...) Expand all
196 case NOTIFICATION_RENDERER_PROCESS_TERMINATED: 242 case NOTIFICATION_RENDERER_PROCESS_TERMINATED:
197 handle = Source<RenderProcessHost>(source)->GetHandle(); 243 handle = Source<RenderProcessHost>(source)->GetHandle();
198 break; 244 break;
199 default: 245 default:
200 NOTREACHED() << "Unexpected notification"; 246 NOTREACHED() << "Unexpected notification";
201 break; 247 break;
202 } 248 }
203 InvalidatePid(handle); 249 InvalidatePid(handle);
204 } 250 }
205 251
252 MachBroker::MachBroker() : listener_thread_started_(false) {
253 }
254
255 MachBroker::~MachBroker() {}
256
257 void MachBroker::FinalizePid(base::ProcessHandle pid,
258 mach_port_t task_port) {
259 lock_.AssertAcquired();
260
261 MachMap::iterator it = mach_map_.find(pid);
262 if (it == mach_map_.end()) {
263 // Do nothing for unknown pids.
264 LOG(ERROR) << "Unknown process " << pid << " is sending Mach IPC messages!";
265 return;
266 }
267
268 DCHECK(it->second == MACH_PORT_NULL);
269 if (it->second == MACH_PORT_NULL)
270 it->second = task_port;
271 }
272
273 void MachBroker::InvalidatePid(base::ProcessHandle pid) {
274 base::AutoLock lock(lock_);
275 MachBroker::MachMap::iterator it = mach_map_.find(pid);
276 if (it == mach_map_.end())
277 return;
278
279 kern_return_t kr = mach_port_deallocate(mach_task_self(),
280 it->second);
281 LOG_IF(WARNING, kr != KERN_SUCCESS)
282 << "Failed to mach_port_deallocate mach task " << it->second
283 << ", error " << MachErrorCode(kr);
284 mach_map_.erase(it);
285 }
286
206 // static 287 // static
207 std::string MachBroker::GetMachPortName() { 288 std::string MachBroker::GetMachPortName() {
208 const CommandLine* command_line = CommandLine::ForCurrentProcess(); 289 const CommandLine* command_line = CommandLine::ForCurrentProcess();
209 const bool is_child = command_line->HasSwitch(switches::kProcessType); 290 const bool is_child = command_line->HasSwitch(switches::kProcessType);
210 291
211 // In non-browser (child) processes, use the parent's pid. 292 // In non-browser (child) processes, use the parent's pid.
212 const pid_t pid = is_child ? getppid() : getpid(); 293 const pid_t pid = is_child ? getppid() : getpid();
213 return base::StringPrintf("%s.rohitfork.%d", base::mac::BaseBundleID(), pid); 294 return base::StringPrintf("%s.rohitfork.%d", base::mac::BaseBundleID(), pid);
214 } 295 }
215 296
216 MachBroker::MachBroker() : listener_thread_started_(false) {
217 }
218
219 MachBroker::~MachBroker() {}
220
221 void MachBroker::RegisterNotifications() { 297 void MachBroker::RegisterNotifications() {
222 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED, 298 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
223 NotificationService::AllBrowserContextsAndSources()); 299 NotificationService::AllBrowserContextsAndSources());
224 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_TERMINATED, 300 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_TERMINATED,
225 NotificationService::AllBrowserContextsAndSources()); 301 NotificationService::AllBrowserContextsAndSources());
226 302
227 // No corresponding StopObservingBrowserChildProcesses, 303 // No corresponding StopObservingBrowserChildProcesses,
228 // we leak this singleton. 304 // we leak this singleton.
229 BrowserChildProcessObserver::Add(this); 305 BrowserChildProcessObserver::Add(this);
230 } 306 }
231 307
232 } // namespace content 308 } // namespace content
OLDNEW
« no previous file with comments | « content/browser/mach_broker_mac.cc ('k') | content/browser/mach_broker_mac_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698