]>
git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_utilities/lib/unixchild.cpp
2 * Copyright (c) 2000-2001,2003-2004,2011,2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 // unixchild - low-level UNIX process child management.
28 // Note that the map-of-children (mChildren) only holds children presumed to
29 // be alive. Neither unborn nor dead children are included. This is important
30 // for how children are reaped and death notifications dispatched, and should
31 // not be changed without prior deep contemplation.
34 // All Child objects in this subsystem are mutated under control of a single
35 // lock (mChildren). This means that children will not step on each other.
36 // However, death callbacks (Child::dying) are made outside the lock's scope
37 // to avoid deadlock scenarios with outside locking hierarchies. When Child::dying
38 // is called, the child has already transitioned to "dead" state and is no longer
39 // in the (live) children map.
41 #include "unixchild.h"
42 #include <security_utilities/debugging.h>
48 namespace UnixPlusPlus
{
52 // All our globals are in a ModuleNexus, for that special lazy-init goodness
54 ModuleNexus
<Child::Children
> Child::mChildren
;
58 // Make and break Children
61 : mState(unborn
), mPid(0), mStatus(0)
68 assert(mState
!= alive
); // not allowed by protocol
73 // Take a Child object that is not alive (i.e. is either unborn or dead),
74 // and reset it to unborn, so you can fork() it again.
75 // This call forgets everything about the previous process.
81 assert(false); // bad boy; can't do that
85 secinfo("unixchild", "%p reset (from state %d)", this, mState
);
95 // Global inquiries and setup
97 void Child::sharedChildren(bool s
)
99 StLock
<Mutex
> _(mChildren());
100 mChildren().shared
= s
;
103 bool Child::sharedChildren()
105 StLock
<Mutex
> _(mChildren());
106 return mChildren().shared
;
111 // Check status for one Child
113 Child::State
Child::check()
118 StLock
<Mutex
> _(mChildren());
122 reaped
= checkStatus(WNOHANG
);
135 // Wait for a particular child to be dead.
136 // This call cannot wait for multiple children; you'll have
137 // to program that yourself using whatever event loop you're using.
143 StLock
<Mutex
> _(mChildren());
146 reaped
= checkStatus(0); // wait for it
149 assert(false); // don't do that
161 // Requires caller to hold mChildren() lock.
163 void Child::tryKill(int signal
)
165 assert(mState
== alive
); // ... or don't bother us
166 secinfo("unixchild", "%p (pid %d) sending signal(%d)", this, pid(), signal
);
167 if (::kill(pid(), signal
))
169 case ESRCH
: // someone else reaped ths child; or things are just wacky
170 secinfo("unixchild", "%p (pid %d) has disappeared!", this, pid());
172 mChildren().erase(pid());
175 UnixError::throwMe();
181 // Send a signal to the Child.
182 // This will succeed (and do nothing) if the Child is not alive.
184 void Child::kill(int signal
)
186 StLock
<Mutex
> _(mChildren());
190 secinfo("unixchild", "%p (pid %d) not alive; cannot send signal %d",
191 this, pid(), signal
);
196 // Kill with prejudice.
197 // This will make a serious attempt to *synchronously* kill the process before
198 // returning. If that doesn't work for some reason, abandon the child.
199 // This is one thing you can do in the destructor of your subclass to legally
200 // dispose of your Child's process.
204 // note that we mustn't hold the lock across these calls
205 switch (this->state()) {
207 if (this->state() == alive
) {
208 this->kill(SIGTERM
); // shoot it once
209 checkChildren(); // check for quick death
210 if (this->state() == alive
) {
211 usleep(200000); // give it some time to die
212 if (this->state() == alive
) { // could have been reaped by another thread
213 checkChildren(); // check again
214 if (this->state() == alive
) { // it... just... won't... die...
215 this->kill(SIGKILL
); // take THAT!
217 if (this->state() == alive
) // stuck zombie
218 this->abandon(); // leave the body behind
225 secinfo("unixchild", "%p (pid %d) already dead; ignoring kill request", this, pid());
228 secinfo("unixchild", "%p state %d; ignoring kill request", this, this->state());
235 // Take a living child and cut it loose. This sets its state to abandoned
236 // and removes it from the child registry.
237 // This is one thing you can do in the destructor of your subclass to legally
238 // dispose of your child's process.
240 void Child::abandon()
242 StLock
<Mutex
> _(mChildren());
243 if (mState
== alive
) {
244 secinfo("unixchild", "%p (pid %d) abandoned", this, pid());
246 mChildren().erase(pid());
248 secinfo("unixchild", "%p (pid %d) is not alive; abandon() ignored",
255 // Forensic examination of the Child's cadaver.
256 // Not interlocked because you have to check for state() == dead first,
257 // and these values are const ever after.
259 int Child::waitStatus() const
261 assert(mState
== dead
);
265 bool Child::bySignal() const
267 assert(mState
== dead
);
268 return WIFSIGNALED(mStatus
);
271 int Child::exitCode() const
273 assert(mState
== dead
);
274 assert(WIFEXITED(mStatus
));
275 return WEXITSTATUS(mStatus
);
278 int Child::exitSignal() const
280 assert(mState
== dead
);
281 assert(WIFSIGNALED(mStatus
));
282 return WTERMSIG(mStatus
);
285 bool Child::coreDumped() const
287 assert(mState
== dead
);
288 assert(WIFSIGNALED(mStatus
));
289 return WCOREDUMP(mStatus
);
294 // Find a child in the child map, by pid
295 // This will only find live children, and return NULL for all others.
297 Child
*Child::findGeneric(pid_t pid
)
299 StLock
<Mutex
> _(mChildren());
300 Children::iterator it
= mChildren().find(pid
);
301 if (it
== mChildren().end())
309 // Do the actual fork job.
310 // At this layer, the client side does nothing but run childAction(). Any plumbing
311 // or cleanup is up to that function (which runs in the child) and the caller (after
312 // fork() returns). If childAction() returns at all, we will call exit(1) to get
317 static const unsigned maxDelay
= 30; // seconds increment, i.e. 5 retries
319 assert(mState
== unborn
);
320 for (unsigned delay
= 1; ;) {
321 switch (pid_t pid
= ::fork()) {
322 case -1: // fork failed
325 secinfo("unixchild", "%p fork EINTR; retrying", this);
326 continue; // no problem
328 if (delay
< maxDelay
) {
329 secinfo("unixchild", "%p fork EAGAIN; delaying %d seconds",
337 UnixError::throwMe();
339 assert(false); // unreached
342 //@@@ bother to clean child map?
351 StLock
<Mutex
> _(mChildren());
354 mChildren().insert(make_pair(pid
, this));
356 secinfo("unixchild", "%p (parent) running parent action", this);
357 this->parentAction();
366 // Check the status of this child by explicitly probing it.
367 // Caller must hold master lock.
369 bool Child::checkStatus(int options
)
371 assert(state() == alive
);
372 secinfo("unixchild", "checking %p (pid %d)", this, this->pid());
375 switch (pid_t pid
= ::wait4(this->pid(), &status
, options
, NULL
)) {
381 secinfo("unixchild", "%p (pid=%d) unknown to kernel", this, this->pid());
383 mChildren().erase(this->pid());
386 UnixError::throwMe();
389 return false; // child not ready (do nothing)
391 assert(pid
== this->pid());
399 // Perform an idempotent check for dead children, as per the UNIX wait() system calls.
400 // This can be called at any time, and will reap all children that have died since
401 // last time. The obvious time to call this is after a SIGCHLD has been received;
402 // however signal dispatch is so - uh, interesting - in UNIX that we don't even try
403 // to deal with it at this level. Suffice to say that calling checkChildren directly
404 // from within a signal handler is NOT generally safe due to locking constraints.
406 // If the shared() flag is on, we explicitly poll each child known to be recently
407 // alive. That is less efficient than reaping any and all, but leaves any children
408 // alone that someone else may have created without our knowledge. The default is
409 // not shared(), which will reap (and discard) any unrelated children without letting
410 // the caller know about it.
412 void Child::checkChildren()
416 StLock
<Mutex
> _(mChildren());
417 if (mChildren().shared
) {
418 for (Children::iterator it
= mChildren().begin(); it
!= mChildren().end(); it
++)
419 if (it
->second
->checkStatus(WNOHANG
))
420 casualties
.add(it
->second
);
421 } else if (!mChildren().empty()) {
423 while (pid_t pid
= ::wait4(0, &status
, WNOHANG
, NULL
)) {
425 os
<< "universal child check (" << mChildren().size() << " children known alive)";
426 secinfo("unixchild", "%s", os
.str().c_str());
431 secinfo("unixchild", "EINTR on wait4; retrying");
432 continue; // benign, but retry the wait()
434 // Should not normally happen (there *is* a child around),
435 // but gets returned anyway if the child is stopped in the debugger.
436 // Treat like a zero return (no children ready to be buried).
437 secinfo("unixchild", "ECHILD with filled nursery (ignored)");
440 UnixError::throwMe();
443 if (Child
*child
= mChildren()[pid
]) {
445 casualties
.add(child
);
447 secinfo("unixchild", "reaping feral child pid=%d", pid
);
448 if (mChildren().empty())
449 goto no_more
; // none left
455 secinfo("unixchild", "spurious checkChildren (the nursery is empty)");
457 } // release master lock
463 // Perform the canonical last rites for a formerly alive child.
464 // Requires master lock held throughout.
466 void Child::bury(int status
)
468 assert(mState
== alive
);
471 mChildren().erase(mPid
);
474 secinfo("unixchild", "%p (pid %d) died by signal %d%s",
475 this, mPid
, exitSignal(),
476 coreDumped() ? " and dumped core" : "");
478 secinfo("unixchild", "%p (pid %d) died by exit(%d)",
479 this, mPid
, exitCode());
487 void Child::parentAction()
497 void Child::Bier::notify()
499 for (const_iterator it
= begin(); it
!= end(); ++it
)
504 } // end namespace IPPlusPlus
505 } // end namespace Security