DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (d1ed7de67f5a)

VCS Links

Line Code
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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=2 autoindent cindent expandtab: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ProcessUtils.h"

#include "nsString.h"

#include <sys/prctl.h>

#ifdef MOZ_B2G_LOADER

#include <sys/types.h>
#include <unistd.h>

#include "nsAutoPtr.h"

#include "mozilla/Assertions.h"
#include "mozilla/ipc/PProcLoaderParent.h"
#include "mozilla/ipc/PProcLoaderChild.h"
#include "mozilla/ipc/Transport.h"
#include "mozilla/ipc/FileDescriptorUtils.h"
#include "mozilla/ipc/IOThreadChild.h"
#include "mozilla/dom/ContentProcess.h"
#include "base/file_descriptor_shuffle.h"
#include "mozilla/BackgroundHangMonitor.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/unused.h"
#include "base/process_util.h"
#include "base/eintr_wrapper.h"

#include "prenv.h"

#include "nsXULAppAPI.h" // export XRE_* functions

#include "nsAppRunner.h"

int content_process_main(int argc, char *argv[]);

typedef mozilla::Vector<int> FdArray;

#endif /* MOZ_B2G_LOADER */

namespace mozilla {

namespace ipc {

void SetThisProcessName(const char *aName)
{
  prctl(PR_SET_NAME, (unsigned long)aName, 0uL, 0uL, 0uL);
}

#ifdef MOZ_B2G_LOADER
/**
 * How does B2G Loader Work?
 *
 *  <<parent process>>      <<child process>>
 *   ProcLoaderParent -----> ProcLoaderChild
 *         ^                       |
 *         | load()                | content_process_main()
 *         |                       V
 *     ProcLoaderClient      Nuwa/plugin-container
 *         ^
 *         | ProcLoaderLoad()
 *        ...
 *     ContentParent
 *
 *
 * B2G loader includes an IPC protocol PProcLoader for communication
 * between client (parent) and server (child).  The b2g process is the
 * client.  It requests the server to load/start the Nuwa process with
 * the given arguments, env variables, and file descriptors.
 *
 * ProcLoaderClientInit() is called by B2G loader to initialize the
 * client side, the b2g process.  Then the b2g_main() is called to
 * start b2g process.
 *
 * ProcLoaderClientGeckoInit() is called by XRE_main() to create the
 * parent actor, |ProcLoaderParent|, of PProcLoader for servicing the
 * request to run Nuwa process later once Gecko has been initialized.
 *
 * ProcLoaderServiceRun() is called by the server process.  It starts
 * an IOThread and event loop to serve the |ProcLoaderChild|
 * implmentation of PProcLoader protocol as the child actor.  Once it
 * recieves a load() request, it stops the IOThread and event loop,
 * then starts running the main function of the content process with
 * the given arguments.
 *
 * NOTE: The server process serves at most one load() request.
 */

using namespace base;
using namespace mozilla::dom;

static bool sProcLoaderClientOnDeinit = false;
static DebugOnly<bool> sProcLoaderClientInitialized = false;
static DebugOnly<bool> sProcLoaderClientGeckoInitialized = false;
static pid_t sProcLoaderPid = 0;
static int sProcLoaderChannelFd = -1;
static PProcLoaderParent *sProcLoaderParent = nullptr;
static MessageLoop *sProcLoaderLoop = nullptr;
static mozilla::UniquePtr<FdArray> sReservedFds;

static void ProcLoaderClientDeinit();

/**
 * Some file descriptors, like the child IPC channel FD, must be opened at
 * specific numbers. To ensure this, we pre-reserve kReservedFileDescriptors FDs
 * starting from kBeginReserveFileDescriptor so that operations like
 * __android_log_print() won't take these magic FDs.
 */
static const int kReservedFileDescriptors = 5;
static const int kBeginReserveFileDescriptor = STDERR_FILENO + 1;

class ProcLoaderParent : public PProcLoaderParent
{
public:
  ProcLoaderParent() {}
  virtual ~ProcLoaderParent() {}

  virtual void ActorDestroy(ActorDestroyReason aWhy) MOZ_OVERRIDE;

  virtual bool RecvLoadComplete(const int32_t &aPid,
                                const int32_t &aCookie) MOZ_OVERRIDE;
};

void
ProcLoaderParent::ActorDestroy(ActorDestroyReason aWhy)
{
  if (aWhy == AbnormalShutdown) {
    NS_WARNING("ProcLoaderParent is destroyed abnormally.");
  }

  if (sProcLoaderClientOnDeinit) {
    // Get error for closing while the channel is already error.
    return;
  }

  // Destroy self asynchronously.
  ProcLoaderClientDeinit();
}

static void
_ProcLoaderParentDestroy(PProcLoaderParent *aLoader)
{
  delete aLoader;
  sProcLoaderClientOnDeinit = false;
}

bool
ProcLoaderParent::RecvLoadComplete(const int32_t &aPid,
                                   const int32_t &aCookie)
{
  return true;
}

static void
CloseFileDescriptors(FdArray& aFds)
{
  for (size_t i = 0; i < aFds.length(); i++) {
    unused << HANDLE_EINTR(close(aFds[i]));
  }
}

/**
 * Initialize the client of B2G loader for loader itself.
 *
 * The initialization of B2G loader are divided into two stages. First
 * stage is to collect child info passed from the main program of the
 * loader.  Second stage is to initialize Gecko according to info from the
 * first stage and make the client of loader service ready.
 *
 * \param aPeerPid is the pid of the child.
 * \param aChannelFd is the file descriptor of the socket used for IPC.
 */
static void
ProcLoaderClientInit(pid_t aPeerPid, int aChannelFd)
{
  MOZ_ASSERT(!sProcLoaderClientInitialized, "call ProcLoaderClientInit() more than once");
  MOZ_ASSERT(aPeerPid != 0 && aChannelFd != -1, "invalid argument");
  sProcLoaderPid = aPeerPid;
  sProcLoaderChannelFd = aChannelFd;
  sProcLoaderClientInitialized = true;
}

/**
 * Initialize the client of B2G loader for Gecko.
 */
void
ProcLoaderClientGeckoInit()
{
  MOZ_ASSERT(sProcLoaderClientInitialized, "call ProcLoaderClientInit() at first");
  MOZ_ASSERT(!sProcLoaderClientGeckoInitialized,
             "call ProcLoaderClientGeckoInit() more than once");

  sProcLoaderClientGeckoInitialized = true;

  TransportDescriptor fd;
  fd.mFd = base::FileDescriptor(sProcLoaderChannelFd, /*auto_close=*/ false);
  sProcLoaderChannelFd = -1;
  Transport *transport = OpenDescriptor(fd, Transport::MODE_CLIENT);
  sProcLoaderParent = new ProcLoaderParent();
  sProcLoaderParent->Open(transport,
                          sProcLoaderPid,
                          XRE_GetIOMessageLoop(),
                          ParentSide);
  sProcLoaderLoop = MessageLoop::current();
}

/**
 * Shutdown and destroy the client of B2G loader service.
 */
static void
ProcLoaderClientDeinit()
{
  MOZ_ASSERT(sProcLoaderClientGeckoInitialized && sProcLoaderClientInitialized);
  sProcLoaderClientGeckoInitialized = false;
  sProcLoaderClientInitialized = false;

  sProcLoaderClientOnDeinit = true;

  MOZ_ASSERT(sProcLoaderParent != nullptr);
  PProcLoaderParent *procLoaderParent = sProcLoaderParent;
  sProcLoaderParent = nullptr;
  sProcLoaderLoop = nullptr;

  MessageLoop::current()->
    PostTask(FROM_HERE,
             NewRunnableFunction(&_ProcLoaderParentDestroy,
                                 procLoaderParent));
}

struct AsyncSendLoadData
{
  nsTArray<nsCString> mArgv;
  nsTArray<nsCString> mEnv;
  nsTArray<FDRemap> mFdsremap;
  ChildPrivileges mPrivs;
  int mCookie;
};

static void
AsyncSendLoad(AsyncSendLoadData *aLoad)
{
  PProcLoaderParent *loader = sProcLoaderParent;
  DebugOnly<bool> ok =
    loader->SendLoad(aLoad->mArgv, aLoad->mEnv, aLoad->mFdsremap,
                     aLoad->mPrivs, aLoad->mCookie);
  MOZ_ASSERT(ok);
  delete aLoad;
}

/**
 * Request the loader service, the server, to load Nuwa.
 */
bool
ProcLoaderLoad(const char *aArgv[],
               const char *aEnvp[],
               const file_handle_mapping_vector &aFdsRemap,
               const ChildPrivileges aPrivs,
               ProcessHandle *aProcessHandle)
{
  static int cookie=0;
  int i;

  if (sProcLoaderParent == nullptr || sProcLoaderPid == 0) {
    return false;
  }

  AsyncSendLoadData *load = new AsyncSendLoadData();
  nsTArray<nsCString> &argv = load->mArgv;
  for (i = 0; aArgv[i] != nullptr; i++) {
    argv.AppendElement(nsCString(aArgv[i]));
  }
  nsTArray<nsCString> &env = load->mEnv;
  for (i = 0; aEnvp[i] != nullptr; i++) {
    env.AppendElement(nsCString(aEnvp[i]));
  }
  nsTArray<FDRemap> &fdsremap = load->mFdsremap;
  for (file_handle_mapping_vector::const_iterator fdmap =
         aFdsRemap.begin();
       fdmap != aFdsRemap.end();
       fdmap++) {
    fdsremap.AppendElement(FDRemap(FileDescriptor(fdmap->first), fdmap->second));
  }
  load->mPrivs = aPrivs;
  load->mCookie = cookie++;

  *aProcessHandle = sProcLoaderPid;
  sProcLoaderPid = 0;

  sProcLoaderLoop->PostTask(FROM_HERE,
                            NewRunnableFunction(AsyncSendLoad, load));
  return true;
}


class ProcLoaderRunnerBase;

static bool sProcLoaderServing = false;
static ProcLoaderRunnerBase *sProcLoaderDispatchedTask = nullptr;

class ProcLoaderRunnerBase
{
public:
  virtual int DoWork() = 0;
  virtual ~ProcLoaderRunnerBase() {}
};


class ProcLoaderNoopRunner : public ProcLoaderRunnerBase {
public:
  virtual int DoWork();
};

int
ProcLoaderNoopRunner::DoWork() {
  return 0;
}

/**
 * The runner to load Nuwa at the current process.
 */
class ProcLoaderLoadRunner : public ProcLoaderRunnerBase {
private:
  const nsTArray<nsCString> mArgv;
  const nsTArray<nsCString> mEnv;
  const nsTArray<FDRemap> mFdsRemap;
  const ChildPrivileges mPrivs;

  void ShuffleFds();

public:
  ProcLoaderLoadRunner(const InfallibleTArray<nsCString>& aArgv,
                       const InfallibleTArray<nsCString>& aEnv,
                       const InfallibleTArray<FDRemap>& aFdsRemap,
                       const ChildPrivileges aPrivs)
    : mArgv(aArgv)
    , mEnv(aEnv)
    , mFdsRemap(aFdsRemap)
    , mPrivs(aPrivs) {}

  int DoWork();
};

void
ProcLoaderLoadRunner::ShuffleFds()
{
  unsigned int i;

  MOZ_ASSERT(mFdsRemap.Length() <= kReservedFileDescriptors);

  InjectiveMultimap fd_shuffle1, fd_shuffle2;
  fd_shuffle1.reserve(mFdsRemap.Length());
  fd_shuffle2.reserve(mFdsRemap.Length());

  for (i = 0; i < mFdsRemap.Length(); i++) {
    const FDRemap *map = &mFdsRemap[i];
    int fd = map->fd().PlatformHandle();
    int tofd = map->mapto();

    fd_shuffle1.push_back(InjectionArc(fd, tofd, false));
    fd_shuffle2.push_back(InjectionArc(fd, tofd, false));

    // Erase from sReservedFds we will use.
    for (int* toErase = sReservedFds->begin();
         toErase < sReservedFds->end();
         toErase++) {
      if (tofd == *toErase) {
        sReservedFds->erase(toErase);
        break;
      }
    }
  }

  DebugOnly<bool> ok = ShuffleFileDescriptors(&fd_shuffle1);

  // Close the FDs that are reserved but not used after
  // ShuffleFileDescriptors().
  MOZ_ASSERT(sReservedFds);
  CloseFileDescriptors(*sReservedFds);
  sReservedFds = nullptr;

  // Note that we don'e call ::base::CloseSuperfluousFds() here, assuming that
  // The file descriptor inherited from the parent are also necessary for us.
}

int
ProcLoaderLoadRunner::DoWork()
{
  unsigned int i;

  ShuffleFds();

  unsigned int argc = mArgv.Length();
  char **argv = new char *[argc + 1];
  for (i = 0; i < argc; i++) {
    argv[i] = ::strdup(mArgv[i].get());
  }
  argv[argc] = nullptr;

  unsigned int envc = mEnv.Length();
  for (i = 0; i < envc; i++) {
    PR_SetEnv(mEnv[i].get());
  }

  SetCurrentProcessPrivileges(mPrivs);

  MOZ_ASSERT(content_process_main != nullptr,
             "content_process_main not found");
  // Start Nuwa (main function)
  int ret = content_process_main(argc, argv);

  for (i = 0; i < argc; i++) {
    free(argv[i]);
  }
  delete[] argv;

  return ret;
}


class ProcLoaderChild : public PProcLoaderChild
{
  pid_t mPeerPid;

public:
  ProcLoaderChild(pid_t aPeerPid) : mPeerPid(aPeerPid) {}

  virtual void ActorDestroy(ActorDestroyReason aWhy) MOZ_OVERRIDE;

  virtual bool RecvLoad(const InfallibleTArray<nsCString>& aArgv,
                        const InfallibleTArray<nsCString>& aEnv,
                        const InfallibleTArray<FDRemap>& aFdsremap,
                        const uint32_t& aPrivs,
                        const int32_t& aCookie);

  virtual void OnChannelError();
};

void
ProcLoaderChild::ActorDestroy(ActorDestroyReason aWhy)
{
}

static void
_ProcLoaderChildDestroy(ProcLoaderChild *aChild)
{
  aChild->Close();
  delete aChild;
  MessageLoop::current()->Quit();
}

bool
ProcLoaderChild::RecvLoad(const InfallibleTArray<nsCString>& aArgv,
                          const InfallibleTArray<nsCString>& aEnv,
                          const InfallibleTArray<FDRemap>& aFdsRemap,
                          const uint32_t& aPrivs,
                          const int32_t& aCookie) {
  if (!sProcLoaderServing) {
    return true;
  }
  sProcLoaderServing = false;

  MOZ_ASSERT(sProcLoaderDispatchedTask == nullptr);
  ChildPrivileges privs = static_cast<ChildPrivileges>(aPrivs);
  sProcLoaderDispatchedTask =
    new ProcLoaderLoadRunner(aArgv, aEnv, aFdsRemap, privs);

  SendLoadComplete(mPeerPid, aCookie);

  MessageLoop::current()->PostTask(FROM_HERE,
                                   NewRunnableFunction(_ProcLoaderChildDestroy,
                                                       this));
  return true;
}

void
ProcLoaderChild::OnChannelError()
{
  if (!sProcLoaderServing) {
    return;
  }
  sProcLoaderServing = false;

  PProcLoaderChild::OnChannelError();

  MOZ_ASSERT(sProcLoaderDispatchedTask == nullptr);
  sProcLoaderDispatchedTask = new ProcLoaderNoopRunner();

  MessageLoop::current()->PostTask(FROM_HERE,
                                   NewRunnableFunction(_ProcLoaderChildDestroy,
                                                       this));
}

/**
 * A helper class which calls NS_LogInit/NS_LogTerm in its scope.
 */
class ScopedLogging
{
public:
  ScopedLogging() { NS_LogInit(); }
  ~ScopedLogging() { NS_LogTerm(); }
};

/**
 * Run service of ProcLoader.
 *
 * \param aPeerPid is the pid of the parent.
 * \param aFd is the file descriptor of the socket for IPC.
 *
 * See the comment near the head of this file.
 */
static int
ProcLoaderServiceRun(pid_t aPeerPid, int aFd,
                     int aArgc, const char *aArgv[],
                     FdArray& aReservedFds)
{
  // Make a copy of aReservedFds. It will be used when we dup() the magic file
  // descriptors when ProcLoaderChild::RecvLoad() runs.
  sReservedFds = MakeUnique<FdArray>(mozilla::Move(aReservedFds));

  ScopedLogging logging;

  char **_argv;
  _argv = new char *[aArgc + 1];
  for (int i = 0; i < aArgc; i++) {
    _argv[i] = ::strdup(aArgv[i]);
    MOZ_ASSERT(_argv[i] != nullptr);
  }
  _argv[aArgc] = nullptr;

  gArgv = _argv;
  gArgc = aArgc;

  {
    nsresult rv = XRE_InitCommandLine(aArgc, _argv);
    if (NS_FAILED(rv)) {
      MOZ_CRASH();
    }

    TransportDescriptor fd;
    fd.mFd = base::FileDescriptor(aFd, /*auto_close =*/false);

    MOZ_ASSERT(!sProcLoaderServing);
    MessageLoop loop;

    nsAutoPtr<ContentProcess> process;
    process = new ContentProcess(aPeerPid);
    ChildThread *iothread = process->child_thread();

    Transport *transport = OpenDescriptor(fd, Transport::MODE_CLIENT);
    ProcLoaderChild *loaderChild = new ProcLoaderChild(aPeerPid);
    // Pass a message loop to initialize (connect) the channel
    // (connection).
    loaderChild->Open(transport, aPeerPid, iothread->message_loop());

    BackgroundHangMonitor::Prohibit();

    sProcLoaderServing = true;
    loop.Run();

    BackgroundHangMonitor::Allow();

    XRE_DeinitCommandLine();
  }

  MOZ_ASSERT(sProcLoaderDispatchedTask != nullptr);
  ProcLoaderRunnerBase *task = sProcLoaderDispatchedTask;
  sProcLoaderDispatchedTask = nullptr;
  int ret = task->DoWork();
  delete task;

  for (int i = 0; i < aArgc; i++) {
    free(_argv[i]);
  }
  delete[] _argv;

  return ret;
}

#endif /* MOZ_B2G_LOADER */

} // namespace ipc
} // namespace mozilla

#ifdef MOZ_B2G_LOADER
void
XRE_ProcLoaderClientInit(pid_t aPeerPid, int aChannelFd, FdArray& aReservedFds)
{
  // We already performed fork(). It's safe to free the "danger zone" of file
  // descriptors .
  mozilla::ipc::CloseFileDescriptors(aReservedFds);

  mozilla::ipc::ProcLoaderClientInit(aPeerPid, aChannelFd);
}

int
XRE_ProcLoaderServiceRun(pid_t aPeerPid, int aFd,
                         int aArgc, const char *aArgv[],
                         FdArray& aReservedFds)
{
  return mozilla::ipc::ProcLoaderServiceRun(aPeerPid, aFd,
                                            aArgc, aArgv,
                                            aReservedFds);
}
#endif /* MOZ_B2G_LOADER */