michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- michael@0: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "GeckoChildProcessHost.h" michael@0: michael@0: #if defined(XP_WIN) && defined(MOZ_CONTENT_SANDBOX) michael@0: #include "sandboxBroker.h" michael@0: #endif michael@0: michael@0: #include "base/command_line.h" michael@0: #include "base/path_service.h" michael@0: #include "base/string_util.h" michael@0: #include "chrome/common/chrome_switches.h" michael@0: #include "chrome/common/process_watcher.h" michael@0: #ifdef MOZ_WIDGET_COCOA michael@0: #include "chrome/common/mach_ipc_mac.h" michael@0: #include "base/rand_util.h" michael@0: #include "nsILocalFileMac.h" michael@0: #endif michael@0: michael@0: #include "MainThreadUtils.h" michael@0: #include "prprf.h" michael@0: #include "prenv.h" michael@0: michael@0: #include "nsExceptionHandler.h" michael@0: michael@0: #include "nsDirectoryServiceDefs.h" michael@0: #include "nsIFile.h" michael@0: michael@0: #include "mozilla/ClearOnShutdown.h" michael@0: #include "mozilla/ipc/BrowserProcessSubThread.h" michael@0: #include "mozilla/Omnijar.h" michael@0: #include michael@0: michael@0: #ifdef XP_WIN michael@0: #include "nsIWinTaskbar.h" michael@0: #define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1" michael@0: #endif michael@0: michael@0: #include "nsTArray.h" michael@0: #include "nsClassHashtable.h" michael@0: #include "nsHashKeys.h" michael@0: michael@0: using mozilla::MonitorAutoLock; michael@0: using mozilla::ipc::GeckoChildProcessHost; michael@0: michael@0: #ifdef ANDROID michael@0: // Like its predecessor in nsExceptionHandler.cpp, this is michael@0: // the magic number of a file descriptor remapping we must michael@0: // preserve for the child process. michael@0: static const int kMagicAndroidSystemPropFd = 5; michael@0: #endif michael@0: michael@0: static const bool kLowRightsSubprocesses = michael@0: // We currently only attempt to drop privileges on gonk, because we michael@0: // have no plugins or extensions to worry about breaking. michael@0: #ifdef MOZ_WIDGET_GONK michael@0: true michael@0: #else michael@0: false michael@0: #endif michael@0: ; michael@0: michael@0: mozilla::StaticRefPtr GeckoChildProcessHost::sGreDir; michael@0: mozilla::DebugOnly GeckoChildProcessHost::sGreDirCached; michael@0: michael@0: static bool michael@0: ShouldHaveDirectoryService() michael@0: { michael@0: return GeckoProcessType_Default == XRE_GetProcessType(); michael@0: } michael@0: michael@0: template<> michael@0: struct RunnableMethodTraits michael@0: { michael@0: static void RetainCallee(GeckoChildProcessHost* obj) { } michael@0: static void ReleaseCallee(GeckoChildProcessHost* obj) { } michael@0: }; michael@0: michael@0: /*static*/ michael@0: base::ChildPrivileges michael@0: GeckoChildProcessHost::DefaultChildPrivileges() michael@0: { michael@0: return (kLowRightsSubprocesses ? michael@0: base::PRIVILEGES_UNPRIVILEGED : base::PRIVILEGES_INHERIT); michael@0: } michael@0: michael@0: GeckoChildProcessHost::GeckoChildProcessHost(GeckoProcessType aProcessType, michael@0: ChildPrivileges aPrivileges) michael@0: : ChildProcessHost(RENDER_PROCESS), // FIXME/cjones: we should own this enum michael@0: mProcessType(aProcessType), michael@0: mSandboxEnabled(true), michael@0: mPrivileges(aPrivileges), michael@0: mMonitor("mozilla.ipc.GeckChildProcessHost.mMonitor"), michael@0: mProcessState(CREATING_CHANNEL), michael@0: mDelegate(nullptr), michael@0: mChildProcessHandle(0) michael@0: #if defined(MOZ_WIDGET_COCOA) michael@0: , mChildTask(MACH_PORT_NULL) michael@0: #endif michael@0: { michael@0: MOZ_COUNT_CTOR(GeckoChildProcessHost); michael@0: } michael@0: michael@0: GeckoChildProcessHost::~GeckoChildProcessHost() michael@0: michael@0: { michael@0: AssertIOThread(); michael@0: michael@0: MOZ_COUNT_DTOR(GeckoChildProcessHost); michael@0: michael@0: if (mChildProcessHandle > 0) michael@0: ProcessWatcher::EnsureProcessTerminated(mChildProcessHandle michael@0: #if defined(NS_BUILD_REFCNT_LOGGING) michael@0: , false // don't "force" michael@0: #endif michael@0: ); michael@0: michael@0: #if defined(MOZ_WIDGET_COCOA) michael@0: if (mChildTask != MACH_PORT_NULL) michael@0: mach_port_deallocate(mach_task_self(), mChildTask); michael@0: #endif michael@0: } michael@0: michael@0: //static michael@0: void michael@0: GeckoChildProcessHost::GetPathToBinary(FilePath& exePath) michael@0: { michael@0: if (ShouldHaveDirectoryService()) { michael@0: MOZ_ASSERT(sGreDirCached); michael@0: if (sGreDir) { michael@0: #ifdef OS_WIN michael@0: nsString path; michael@0: MOZ_ALWAYS_TRUE(NS_SUCCEEDED(sGreDir->GetPath(path))); michael@0: #else michael@0: nsCString path; michael@0: MOZ_ALWAYS_TRUE(NS_SUCCEEDED(sGreDir->GetNativePath(path))); michael@0: #endif michael@0: exePath = FilePath(path.get()); michael@0: #ifdef MOZ_WIDGET_COCOA michael@0: // We need to use an App Bundle on OS X so that we can hide michael@0: // the dock icon. See Bug 557225. michael@0: exePath = exePath.AppendASCII(MOZ_CHILD_PROCESS_BUNDLE); michael@0: #endif michael@0: } michael@0: } michael@0: michael@0: if (exePath.empty()) { michael@0: #ifdef OS_WIN michael@0: exePath = FilePath::FromWStringHack(CommandLine::ForCurrentProcess()->program()); michael@0: #else michael@0: exePath = FilePath(CommandLine::ForCurrentProcess()->argv()[0]); michael@0: #endif michael@0: exePath = exePath.DirName(); michael@0: } michael@0: michael@0: exePath = exePath.AppendASCII(MOZ_CHILD_PROCESS_NAME); michael@0: } michael@0: michael@0: #ifdef MOZ_WIDGET_COCOA michael@0: class AutoCFTypeObject { michael@0: public: michael@0: AutoCFTypeObject(CFTypeRef object) michael@0: { michael@0: mObject = object; michael@0: } michael@0: ~AutoCFTypeObject() michael@0: { michael@0: ::CFRelease(mObject); michael@0: } michael@0: private: michael@0: CFTypeRef mObject; michael@0: }; michael@0: #endif michael@0: michael@0: nsresult GeckoChildProcessHost::GetArchitecturesForBinary(const char *path, uint32_t *result) michael@0: { michael@0: *result = 0; michael@0: michael@0: #ifdef MOZ_WIDGET_COCOA michael@0: CFURLRef url = ::CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, michael@0: (const UInt8*)path, michael@0: strlen(path), michael@0: false); michael@0: if (!url) { michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: AutoCFTypeObject autoPluginContainerURL(url); michael@0: michael@0: CFArrayRef pluginContainerArchs = ::CFBundleCopyExecutableArchitecturesForURL(url); michael@0: if (!pluginContainerArchs) { michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: AutoCFTypeObject autoPluginContainerArchs(pluginContainerArchs); michael@0: michael@0: CFIndex pluginArchCount = ::CFArrayGetCount(pluginContainerArchs); michael@0: for (CFIndex i = 0; i < pluginArchCount; i++) { michael@0: CFNumberRef currentArch = static_cast(::CFArrayGetValueAtIndex(pluginContainerArchs, i)); michael@0: int currentArchInt = 0; michael@0: if (!::CFNumberGetValue(currentArch, kCFNumberIntType, ¤tArchInt)) { michael@0: continue; michael@0: } michael@0: switch (currentArchInt) { michael@0: case kCFBundleExecutableArchitectureI386: michael@0: *result |= base::PROCESS_ARCH_I386; michael@0: break; michael@0: case kCFBundleExecutableArchitectureX86_64: michael@0: *result |= base::PROCESS_ARCH_X86_64; michael@0: break; michael@0: case kCFBundleExecutableArchitecturePPC: michael@0: *result |= base::PROCESS_ARCH_PPC; michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: } michael@0: michael@0: return (*result ? NS_OK : NS_ERROR_FAILURE); michael@0: #else michael@0: return NS_ERROR_NOT_IMPLEMENTED; michael@0: #endif michael@0: } michael@0: michael@0: uint32_t GeckoChildProcessHost::GetSupportedArchitecturesForProcessType(GeckoProcessType type) michael@0: { michael@0: #ifdef MOZ_WIDGET_COCOA michael@0: if (type == GeckoProcessType_Plugin) { michael@0: michael@0: // Cache this, it shouldn't ever change. michael@0: static uint32_t pluginContainerArchs = 0; michael@0: if (pluginContainerArchs == 0) { michael@0: CacheGreDir(); michael@0: FilePath exePath; michael@0: GetPathToBinary(exePath); michael@0: nsresult rv = GetArchitecturesForBinary(exePath.value().c_str(), &pluginContainerArchs); michael@0: NS_ASSERTION(NS_SUCCEEDED(rv) && pluginContainerArchs != 0, "Getting architecture of plugin container failed!"); michael@0: if (NS_FAILED(rv) || pluginContainerArchs == 0) { michael@0: pluginContainerArchs = base::GetCurrentProcessArchitecture(); michael@0: } michael@0: } michael@0: return pluginContainerArchs; michael@0: } michael@0: #endif michael@0: michael@0: return base::GetCurrentProcessArchitecture(); michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::PrepareLaunch() michael@0: { michael@0: #ifdef MOZ_CRASHREPORTER michael@0: if (CrashReporter::GetEnabled()) { michael@0: CrashReporter::OOPInit(); michael@0: } michael@0: #endif michael@0: michael@0: #ifdef XP_WIN michael@0: InitWindowsGroupID(); michael@0: #endif michael@0: CacheGreDir(); michael@0: } michael@0: michael@0: //static michael@0: void michael@0: GeckoChildProcessHost::CacheGreDir() michael@0: { michael@0: // PerformAysncLaunchInternal/GetPathToBinary may be called on the IO thread, michael@0: // and they want to use the directory service, which needs to happen on the michael@0: // main thread (in the event that its implemented in JS). So we grab michael@0: // NS_GRE_DIR here and stash it. michael@0: michael@0: #ifdef MOZ_WIDGET_GONK michael@0: // Apparently, this ASSERT should be present on all platforms. Currently, michael@0: // this assert causes mochitest failures on the Mac platform if its left in. michael@0: michael@0: // B2G overrides the directory service in JS, so this needs to be called michael@0: // on the main thread. michael@0: MOZ_ASSERT(NS_IsMainThread()); michael@0: #endif michael@0: michael@0: if (ShouldHaveDirectoryService()) { michael@0: nsCOMPtr directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID)); michael@0: MOZ_ASSERT(directoryService, "Expected XPCOM to be available"); michael@0: if (directoryService) { michael@0: // getter_AddRefs doesn't work with StaticRefPtr, so we need to store the michael@0: // result in an nsCOMPtr and copy it over. michael@0: nsCOMPtr greDir; michael@0: nsresult rv = directoryService->Get(NS_GRE_DIR, NS_GET_IID(nsIFile), getter_AddRefs(greDir)); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: sGreDir = greDir; michael@0: mozilla::ClearOnShutdown(&sGreDir); michael@0: } michael@0: } michael@0: } michael@0: sGreDirCached = true; michael@0: } michael@0: michael@0: #ifdef XP_WIN michael@0: void GeckoChildProcessHost::InitWindowsGroupID() michael@0: { michael@0: // On Win7+, pass the application user model to the child, so it can michael@0: // register with it. This insures windows created by the container michael@0: // properly group with the parent app on the Win7 taskbar. michael@0: nsCOMPtr taskbarInfo = michael@0: do_GetService(NS_TASKBAR_CONTRACTID); michael@0: if (taskbarInfo) { michael@0: bool isSupported = false; michael@0: taskbarInfo->GetAvailable(&isSupported); michael@0: nsAutoString appId; michael@0: if (isSupported && NS_SUCCEEDED(taskbarInfo->GetDefaultGroupId(appId))) { michael@0: mGroupId.Append(appId); michael@0: } else { michael@0: mGroupId.AssignLiteral("-"); michael@0: } michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: bool michael@0: GeckoChildProcessHost::SyncLaunch(std::vector aExtraOpts, int aTimeoutMs, base::ProcessArchitecture arch) michael@0: { michael@0: PrepareLaunch(); michael@0: michael@0: PRIntervalTime timeoutTicks = (aTimeoutMs > 0) ? michael@0: PR_MillisecondsToInterval(aTimeoutMs) : PR_INTERVAL_NO_TIMEOUT; michael@0: MessageLoop* ioLoop = XRE_GetIOMessageLoop(); michael@0: NS_ASSERTION(MessageLoop::current() != ioLoop, "sync launch from the IO thread NYI"); michael@0: michael@0: ioLoop->PostTask(FROM_HERE, michael@0: NewRunnableMethod(this, michael@0: &GeckoChildProcessHost::RunPerformAsyncLaunch, michael@0: aExtraOpts, arch)); michael@0: // NB: this uses a different mechanism than the chromium parent michael@0: // class. michael@0: MonitorAutoLock lock(mMonitor); michael@0: PRIntervalTime waitStart = PR_IntervalNow(); michael@0: PRIntervalTime current; michael@0: michael@0: // We'll receive several notifications, we need to exit when we michael@0: // have either successfully launched or have timed out. michael@0: while (mProcessState != PROCESS_CONNECTED) { michael@0: // If there was an error then return it, don't wait out the timeout. michael@0: if (mProcessState == PROCESS_ERROR) { michael@0: break; michael@0: } michael@0: michael@0: lock.Wait(timeoutTicks); michael@0: michael@0: if (timeoutTicks != PR_INTERVAL_NO_TIMEOUT) { michael@0: current = PR_IntervalNow(); michael@0: PRIntervalTime elapsed = current - waitStart; michael@0: if (elapsed > timeoutTicks) { michael@0: break; michael@0: } michael@0: timeoutTicks = timeoutTicks - elapsed; michael@0: waitStart = current; michael@0: } michael@0: } michael@0: michael@0: return mProcessState == PROCESS_CONNECTED; michael@0: } michael@0: michael@0: bool michael@0: GeckoChildProcessHost::AsyncLaunch(std::vector aExtraOpts) michael@0: { michael@0: PrepareLaunch(); michael@0: michael@0: MessageLoop* ioLoop = XRE_GetIOMessageLoop(); michael@0: ioLoop->PostTask(FROM_HERE, michael@0: NewRunnableMethod(this, michael@0: &GeckoChildProcessHost::RunPerformAsyncLaunch, michael@0: aExtraOpts, base::GetCurrentProcessArchitecture())); michael@0: michael@0: // This may look like the sync launch wait, but we only delay as michael@0: // long as it takes to create the channel. michael@0: MonitorAutoLock lock(mMonitor); michael@0: while (mProcessState < CHANNEL_INITIALIZED) { michael@0: lock.Wait(); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: bool michael@0: GeckoChildProcessHost::LaunchAndWaitForProcessHandle(StringVector aExtraOpts) michael@0: { michael@0: PrepareLaunch(); michael@0: michael@0: MessageLoop* ioLoop = XRE_GetIOMessageLoop(); michael@0: ioLoop->PostTask(FROM_HERE, michael@0: NewRunnableMethod(this, michael@0: &GeckoChildProcessHost::RunPerformAsyncLaunch, michael@0: aExtraOpts, base::GetCurrentProcessArchitecture())); michael@0: michael@0: MonitorAutoLock lock(mMonitor); michael@0: while (mProcessState < PROCESS_CREATED) { michael@0: lock.Wait(); michael@0: } michael@0: MOZ_ASSERT(mProcessState == PROCESS_ERROR || mChildProcessHandle); michael@0: michael@0: return mProcessState < PROCESS_ERROR; michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::InitializeChannel() michael@0: { michael@0: CreateChannel(); michael@0: michael@0: MonitorAutoLock lock(mMonitor); michael@0: mProcessState = CHANNEL_INITIALIZED; michael@0: lock.Notify(); michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::Join() michael@0: { michael@0: AssertIOThread(); michael@0: michael@0: if (!mChildProcessHandle) { michael@0: return; michael@0: } michael@0: michael@0: // If this fails, there's nothing we can do. michael@0: base::KillProcess(mChildProcessHandle, 0, /*wait*/true); michael@0: SetAlreadyDead(); michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::SetAlreadyDead() michael@0: { michael@0: mChildProcessHandle = 0; michael@0: } michael@0: michael@0: int32_t GeckoChildProcessHost::mChildCounter = 0; michael@0: michael@0: // michael@0: // Wrapper function for handling GECKO_SEPARATE_NSPR_LOGS michael@0: // michael@0: bool michael@0: GeckoChildProcessHost::PerformAsyncLaunch(std::vector aExtraOpts, base::ProcessArchitecture arch) michael@0: { michael@0: // If NSPR log files are not requested, we're done. michael@0: const char* origLogName = PR_GetEnv("NSPR_LOG_FILE"); michael@0: if (!origLogName) { michael@0: return PerformAsyncLaunchInternal(aExtraOpts, arch); michael@0: } michael@0: michael@0: // We currently have no portable way to launch child with environment michael@0: // different than parent. So temporarily change NSPR_LOG_FILE so child michael@0: // inherits value we want it to have. (NSPR only looks at NSPR_LOG_FILE at michael@0: // startup, so it's 'safe' to play with the parent's environment this way.) michael@0: nsAutoCString setChildLogName("NSPR_LOG_FILE="); michael@0: setChildLogName.Append(origLogName); michael@0: michael@0: // remember original value so we can restore it. michael@0: // - buffer needs to be permanently allocated for PR_SetEnv() michael@0: // - Note: this code is not called re-entrantly, nor are restoreOrigLogName michael@0: // or mChildCounter touched by any other thread, so this is safe. michael@0: static char* restoreOrigLogName = 0; michael@0: if (!restoreOrigLogName) michael@0: restoreOrigLogName = strdup(setChildLogName.get()); michael@0: michael@0: // Append child-specific postfix to name michael@0: setChildLogName.AppendLiteral(".child-"); michael@0: setChildLogName.AppendInt(++mChildCounter); michael@0: michael@0: // Passing temporary to PR_SetEnv is ok here because env gets copied michael@0: // by exec, etc., to permanent storage in child when process launched. michael@0: PR_SetEnv(setChildLogName.get()); michael@0: bool retval = PerformAsyncLaunchInternal(aExtraOpts, arch); michael@0: michael@0: // Revert to original value michael@0: PR_SetEnv(restoreOrigLogName); michael@0: michael@0: return retval; michael@0: } michael@0: michael@0: bool michael@0: GeckoChildProcessHost::RunPerformAsyncLaunch(std::vector aExtraOpts, michael@0: base::ProcessArchitecture aArch) michael@0: { michael@0: InitializeChannel(); michael@0: return PerformAsyncLaunch(aExtraOpts, aArch); michael@0: } michael@0: michael@0: void michael@0: #if defined(XP_WIN) michael@0: AddAppDirToCommandLine(CommandLine& aCmdLine) michael@0: #else michael@0: AddAppDirToCommandLine(std::vector& aCmdLine) michael@0: #endif michael@0: { michael@0: // Content processes need access to application resources, so pass michael@0: // the full application directory path to the child process. michael@0: if (ShouldHaveDirectoryService()) { michael@0: nsCOMPtr directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID)); michael@0: NS_ASSERTION(directoryService, "Expected XPCOM to be available"); michael@0: if (directoryService) { michael@0: nsCOMPtr appDir; michael@0: // NS_XPCOM_CURRENT_PROCESS_DIR really means the app dir, not the michael@0: // current process dir. michael@0: nsresult rv = directoryService->Get(NS_XPCOM_CURRENT_PROCESS_DIR, michael@0: NS_GET_IID(nsIFile), michael@0: getter_AddRefs(appDir)); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: nsAutoCString path; michael@0: MOZ_ALWAYS_TRUE(NS_SUCCEEDED(appDir->GetNativePath(path))); michael@0: #if defined(XP_WIN) michael@0: aCmdLine.AppendLooseValue(UTF8ToWide("-appdir")); michael@0: aCmdLine.AppendLooseValue(UTF8ToWide(path.get())); michael@0: #else michael@0: aCmdLine.push_back("-appdir"); michael@0: aCmdLine.push_back(path.get()); michael@0: #endif michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: bool michael@0: GeckoChildProcessHost::PerformAsyncLaunchInternal(std::vector& aExtraOpts, base::ProcessArchitecture arch) michael@0: { michael@0: // We rely on the fact that InitializeChannel() has already been processed michael@0: // on the IO thread before this point is reached. michael@0: if (!GetChannel()) { michael@0: return false; michael@0: } michael@0: michael@0: base::ProcessHandle process = 0; michael@0: michael@0: // send the child the PID so that it can open a ProcessHandle back to us. michael@0: // probably don't want to do this in the long run michael@0: char pidstring[32]; michael@0: PR_snprintf(pidstring, sizeof(pidstring) - 1, michael@0: "%ld", base::Process::Current().pid()); michael@0: michael@0: const char* const childProcessType = michael@0: XRE_ChildProcessTypeToString(mProcessType); michael@0: michael@0: //-------------------------------------------------- michael@0: #if defined(OS_POSIX) michael@0: // For POSIX, we have to be extremely anal about *not* using michael@0: // std::wstring in code compiled with Mozilla's -fshort-wchar michael@0: // configuration, because chromium is compiled with -fno-short-wchar michael@0: // and passing wstrings from one config to the other is unsafe. So michael@0: // we split the logic here. michael@0: michael@0: #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_BSD) michael@0: base::environment_map newEnvVars; michael@0: ChildPrivileges privs = mPrivileges; michael@0: if (privs == base::PRIVILEGES_DEFAULT) { michael@0: privs = DefaultChildPrivileges(); michael@0: } michael@0: // XPCOM may not be initialized in some subprocesses. We don't want michael@0: // to initialize XPCOM just for the directory service, especially michael@0: // since LD_LIBRARY_PATH is already set correctly in subprocesses michael@0: // (meaning that we don't need to set that up in the environment). michael@0: if (ShouldHaveDirectoryService()) { michael@0: MOZ_ASSERT(sGreDirCached); michael@0: if (sGreDir) { michael@0: nsCString path; michael@0: MOZ_ALWAYS_TRUE(NS_SUCCEEDED(sGreDir->GetNativePath(path))); michael@0: # if defined(OS_LINUX) || defined(OS_BSD) michael@0: # if defined(MOZ_WIDGET_ANDROID) michael@0: path += "/lib"; michael@0: # endif // MOZ_WIDGET_ANDROID michael@0: const char *ld_library_path = PR_GetEnv("LD_LIBRARY_PATH"); michael@0: nsCString new_ld_lib_path; michael@0: if (ld_library_path && *ld_library_path) { michael@0: new_ld_lib_path.Assign(path.get()); michael@0: new_ld_lib_path.AppendLiteral(":"); michael@0: new_ld_lib_path.Append(ld_library_path); michael@0: newEnvVars["LD_LIBRARY_PATH"] = new_ld_lib_path.get(); michael@0: } else { michael@0: newEnvVars["LD_LIBRARY_PATH"] = path.get(); michael@0: } michael@0: # elif OS_MACOSX michael@0: newEnvVars["DYLD_LIBRARY_PATH"] = path.get(); michael@0: // XXX DYLD_INSERT_LIBRARIES should only be set when launching a plugin michael@0: // process, and has no effect on other subprocesses (the hooks in michael@0: // libplugin_child_interpose.dylib become noops). But currently it michael@0: // gets set when launching any kind of subprocess. michael@0: // michael@0: // Trigger "dyld interposing" for the dylib that contains michael@0: // plugin_child_interpose.mm. This allows us to hook OS calls in the michael@0: // plugin process (ones that don't work correctly in a background michael@0: // process). Don't break any other "dyld interposing" that has already michael@0: // been set up by whatever may have launched the browser. michael@0: const char* prevInterpose = PR_GetEnv("DYLD_INSERT_LIBRARIES"); michael@0: nsCString interpose; michael@0: if (prevInterpose) { michael@0: interpose.Assign(prevInterpose); michael@0: interpose.AppendLiteral(":"); michael@0: } michael@0: interpose.Append(path.get()); michael@0: interpose.AppendLiteral("/libplugin_child_interpose.dylib"); michael@0: newEnvVars["DYLD_INSERT_LIBRARIES"] = interpose.get(); michael@0: # endif // OS_LINUX michael@0: } michael@0: } michael@0: #endif // OS_LINUX || OS_MACOSX michael@0: michael@0: FilePath exePath; michael@0: GetPathToBinary(exePath); michael@0: michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: // The java wrapper unpacks this for us but can't make it executable michael@0: chmod(exePath.value().c_str(), 0700); michael@0: #endif // MOZ_WIDGET_ANDROID michael@0: michael@0: #ifdef ANDROID michael@0: // Remap the Android property workspace to a well-known int, michael@0: // and update the environment to reflect the new value for the michael@0: // child process. michael@0: const char *apws = getenv("ANDROID_PROPERTY_WORKSPACE"); michael@0: if (apws) { michael@0: int fd = atoi(apws); michael@0: mFileMap.push_back(std::pair(fd, kMagicAndroidSystemPropFd)); michael@0: michael@0: char buf[32]; michael@0: char *szptr = strchr(apws, ','); michael@0: michael@0: snprintf(buf, sizeof(buf), "%d%s", kMagicAndroidSystemPropFd, szptr); michael@0: newEnvVars["ANDROID_PROPERTY_WORKSPACE"] = buf; michael@0: } michael@0: #endif // ANDROID michael@0: michael@0: #ifdef MOZ_WIDGET_GONK michael@0: if (const char *ldPreloadPath = getenv("LD_PRELOAD")) { michael@0: newEnvVars["LD_PRELOAD"] = ldPreloadPath; michael@0: } michael@0: #endif // MOZ_WIDGET_GONK michael@0: michael@0: // remap the IPC socket fd to a well-known int, as the OS does for michael@0: // STDOUT_FILENO, for example michael@0: int srcChannelFd, dstChannelFd; michael@0: channel().GetClientFileDescriptorMapping(&srcChannelFd, &dstChannelFd); michael@0: mFileMap.push_back(std::pair(srcChannelFd, dstChannelFd)); michael@0: michael@0: // no need for kProcessChannelID, the child process inherits the michael@0: // other end of the socketpair() from us michael@0: michael@0: std::vector childArgv; michael@0: michael@0: childArgv.push_back(exePath.value()); michael@0: michael@0: childArgv.insert(childArgv.end(), aExtraOpts.begin(), aExtraOpts.end()); michael@0: michael@0: if (Omnijar::IsInitialized()) { michael@0: // Make sure that child processes can find the omnijar michael@0: // See XRE_InitCommandLine in nsAppRunner.cpp michael@0: nsAutoCString path; michael@0: nsCOMPtr file = Omnijar::GetPath(Omnijar::GRE); michael@0: if (file && NS_SUCCEEDED(file->GetNativePath(path))) { michael@0: childArgv.push_back("-greomni"); michael@0: childArgv.push_back(path.get()); michael@0: } michael@0: file = Omnijar::GetPath(Omnijar::APP); michael@0: if (file && NS_SUCCEEDED(file->GetNativePath(path))) { michael@0: childArgv.push_back("-appomni"); michael@0: childArgv.push_back(path.get()); michael@0: } michael@0: } michael@0: michael@0: // Add the application directory path (-appdir path) michael@0: AddAppDirToCommandLine(childArgv); michael@0: michael@0: childArgv.push_back(pidstring); michael@0: michael@0: #if defined(MOZ_CRASHREPORTER) michael@0: # if defined(OS_LINUX) || defined(OS_BSD) michael@0: int childCrashFd, childCrashRemapFd; michael@0: if (!CrashReporter::CreateNotificationPipeForChild( michael@0: &childCrashFd, &childCrashRemapFd)) michael@0: return false; michael@0: if (0 <= childCrashFd) { michael@0: mFileMap.push_back(std::pair(childCrashFd, childCrashRemapFd)); michael@0: // "true" == crash reporting enabled michael@0: childArgv.push_back("true"); michael@0: } michael@0: else { michael@0: // "false" == crash reporting disabled michael@0: childArgv.push_back("false"); michael@0: } michael@0: # elif defined(MOZ_WIDGET_COCOA) michael@0: childArgv.push_back(CrashReporter::GetChildNotificationPipe()); michael@0: # endif // OS_LINUX michael@0: #endif michael@0: michael@0: #ifdef MOZ_WIDGET_COCOA michael@0: // Add a mach port to the command line so the child can communicate its michael@0: // 'task_t' back to the parent. michael@0: // michael@0: // Put a random number into the channel name, so that a compromised renderer michael@0: // can't pretend being the child that's forked off. michael@0: std::string mach_connection_name = StringPrintf("org.mozilla.machname.%d", michael@0: base::RandInt(0, std::numeric_limits::max())); michael@0: childArgv.push_back(mach_connection_name.c_str()); michael@0: #endif michael@0: michael@0: childArgv.push_back(childProcessType); michael@0: michael@0: base::LaunchApp(childArgv, mFileMap, michael@0: #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_BSD) michael@0: newEnvVars, privs, michael@0: #endif michael@0: false, &process, arch); michael@0: michael@0: // We're in the parent and the child was launched. Close the child FD in the michael@0: // parent as soon as possible, which will allow the parent to detect when the michael@0: // child closes its FD (either due to normal exit or due to crash). michael@0: GetChannel()->CloseClientFileDescriptor(); michael@0: michael@0: #ifdef MOZ_WIDGET_COCOA michael@0: // Wait for the child process to send us its 'task_t' data. michael@0: const int kTimeoutMs = 10000; michael@0: michael@0: MachReceiveMessage child_message; michael@0: ReceivePort parent_recv_port(mach_connection_name.c_str()); michael@0: kern_return_t err = parent_recv_port.WaitForMessage(&child_message, kTimeoutMs); michael@0: if (err != KERN_SUCCESS) { michael@0: std::string errString = StringPrintf("0x%x %s", err, mach_error_string(err)); michael@0: CHROMIUM_LOG(ERROR) << "parent WaitForMessage() failed: " << errString; michael@0: return false; michael@0: } michael@0: michael@0: task_t child_task = child_message.GetTranslatedPort(0); michael@0: if (child_task == MACH_PORT_NULL) { michael@0: CHROMIUM_LOG(ERROR) << "parent GetTranslatedPort(0) failed."; michael@0: return false; michael@0: } michael@0: michael@0: if (child_message.GetTranslatedPort(1) == MACH_PORT_NULL) { michael@0: CHROMIUM_LOG(ERROR) << "parent GetTranslatedPort(1) failed."; michael@0: return false; michael@0: } michael@0: MachPortSender parent_sender(child_message.GetTranslatedPort(1)); michael@0: michael@0: MachSendMessage parent_message(/* id= */0); michael@0: if (!parent_message.AddDescriptor(bootstrap_port)) { michael@0: CHROMIUM_LOG(ERROR) << "parent AddDescriptor(" << bootstrap_port << ") failed."; michael@0: return false; michael@0: } michael@0: michael@0: err = parent_sender.SendMessage(parent_message, kTimeoutMs); michael@0: if (err != KERN_SUCCESS) { michael@0: std::string errString = StringPrintf("0x%x %s", err, mach_error_string(err)); michael@0: CHROMIUM_LOG(ERROR) << "parent SendMessage() failed: " << errString; michael@0: return false; michael@0: } michael@0: #endif michael@0: michael@0: //-------------------------------------------------- michael@0: #elif defined(OS_WIN) michael@0: michael@0: FilePath exePath; michael@0: GetPathToBinary(exePath); michael@0: michael@0: CommandLine cmdLine(exePath.ToWStringHack()); michael@0: cmdLine.AppendSwitchWithValue(switches::kProcessChannelID, channel_id()); michael@0: michael@0: for (std::vector::iterator it = aExtraOpts.begin(); michael@0: it != aExtraOpts.end(); michael@0: ++it) { michael@0: cmdLine.AppendLooseValue(UTF8ToWide(*it)); michael@0: } michael@0: michael@0: if (Omnijar::IsInitialized()) { michael@0: // Make sure the child process can find the omnijar michael@0: // See XRE_InitCommandLine in nsAppRunner.cpp michael@0: nsAutoString path; michael@0: nsCOMPtr file = Omnijar::GetPath(Omnijar::GRE); michael@0: if (file && NS_SUCCEEDED(file->GetPath(path))) { michael@0: cmdLine.AppendLooseValue(UTF8ToWide("-greomni")); michael@0: cmdLine.AppendLooseValue(path.get()); michael@0: } michael@0: file = Omnijar::GetPath(Omnijar::APP); michael@0: if (file && NS_SUCCEEDED(file->GetPath(path))) { michael@0: cmdLine.AppendLooseValue(UTF8ToWide("-appomni")); michael@0: cmdLine.AppendLooseValue(path.get()); michael@0: } michael@0: } michael@0: michael@0: #if defined(XP_WIN) && defined(MOZ_CONTENT_SANDBOX) michael@0: if (mSandboxEnabled) { michael@0: // Tell the process that it should lower its rights after initialization. michael@0: cmdLine.AppendLooseValue(UTF8ToWide("-sandbox")); michael@0: } michael@0: #endif michael@0: michael@0: // Add the application directory path (-appdir path) michael@0: AddAppDirToCommandLine(cmdLine); michael@0: michael@0: // XXX Command line params past this point are expected to be at michael@0: // the end of the command line string, and in a specific order. michael@0: // See XRE_InitChildProcess in nsEmbedFunction. michael@0: michael@0: // Win app model id michael@0: cmdLine.AppendLooseValue(mGroupId.get()); michael@0: michael@0: // Process id michael@0: cmdLine.AppendLooseValue(UTF8ToWide(pidstring)); michael@0: michael@0: #if defined(MOZ_CRASHREPORTER) michael@0: cmdLine.AppendLooseValue( michael@0: UTF8ToWide(CrashReporter::GetChildNotificationPipe())); michael@0: #endif michael@0: michael@0: // Process type michael@0: cmdLine.AppendLooseValue(UTF8ToWide(childProcessType)); michael@0: michael@0: #if defined(XP_WIN) && defined(MOZ_CONTENT_SANDBOX) michael@0: if (mSandboxEnabled) { michael@0: michael@0: mozilla::SandboxBroker sandboxBroker; michael@0: sandboxBroker.LaunchApp(cmdLine.program().c_str(), michael@0: cmdLine.command_line_string().c_str(), michael@0: &process); michael@0: } else michael@0: #endif michael@0: { michael@0: base::LaunchApp(cmdLine, false, false, &process); michael@0: } michael@0: michael@0: #else michael@0: # error Sorry michael@0: #endif michael@0: michael@0: if (!process) { michael@0: MonitorAutoLock lock(mMonitor); michael@0: mProcessState = PROCESS_ERROR; michael@0: lock.Notify(); michael@0: return false; michael@0: } michael@0: // NB: on OS X, we block much longer than we need to in order to michael@0: // reach this call, waiting for the child process's task_t. The michael@0: // best way to fix that is to refactor this file, hard. michael@0: SetHandle(process); michael@0: #if defined(MOZ_WIDGET_COCOA) michael@0: mChildTask = child_task; michael@0: #endif michael@0: michael@0: OpenPrivilegedHandle(base::GetProcId(process)); michael@0: { michael@0: MonitorAutoLock lock(mMonitor); michael@0: mProcessState = PROCESS_CREATED; michael@0: lock.Notify(); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::OpenPrivilegedHandle(base::ProcessId aPid) michael@0: { michael@0: if (mChildProcessHandle) { michael@0: MOZ_ASSERT(aPid == base::GetProcId(mChildProcessHandle)); michael@0: return; michael@0: } michael@0: if (!base::OpenPrivilegedProcessHandle(aPid, &mChildProcessHandle)) { michael@0: NS_RUNTIMEABORT("can't open handle to child process"); michael@0: } michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::OnChannelConnected(int32_t peer_pid) michael@0: { michael@0: OpenPrivilegedHandle(peer_pid); michael@0: { michael@0: MonitorAutoLock lock(mMonitor); michael@0: mProcessState = PROCESS_CONNECTED; michael@0: lock.Notify(); michael@0: } michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::OnMessageReceived(const IPC::Message& aMsg) michael@0: { michael@0: // We never process messages ourself, just save them up for the next michael@0: // listener. michael@0: mQueue.push(aMsg); michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::OnChannelError() michael@0: { michael@0: // Update the process state to an error state if we have a channel michael@0: // error before we're connected. This fixes certain failures, michael@0: // but does not address the full range of possible issues described michael@0: // in the FIXME comment below. michael@0: MonitorAutoLock lock(mMonitor); michael@0: if (mProcessState < PROCESS_CONNECTED) { michael@0: mProcessState = PROCESS_ERROR; michael@0: lock.Notify(); michael@0: } michael@0: // FIXME/bug 773925: save up this error for the next listener. michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::GetQueuedMessages(std::queue& queue) michael@0: { michael@0: // If this is called off the IO thread, bad things will happen. michael@0: DCHECK(MessageLoopForIO::current()); michael@0: swap(queue, mQueue); michael@0: // We expect the next listener to take over processing of our queue. michael@0: } michael@0: michael@0: void michael@0: GeckoChildProcessHost::OnWaitableEventSignaled(base::WaitableEvent *event) michael@0: { michael@0: if (mDelegate) { michael@0: mDelegate->OnWaitableEventSignaled(event); michael@0: } michael@0: ChildProcessHost::OnWaitableEventSignaled(event); michael@0: } michael@0: michael@0: #ifdef MOZ_NUWA_PROCESS michael@0: michael@0: using mozilla::ipc::GeckoExistingProcessHost; michael@0: using mozilla::ipc::FileDescriptor; michael@0: michael@0: GeckoExistingProcessHost:: michael@0: GeckoExistingProcessHost(GeckoProcessType aProcessType, michael@0: base::ProcessHandle aProcess, michael@0: const FileDescriptor& aFileDescriptor, michael@0: ChildPrivileges aPrivileges) michael@0: : GeckoChildProcessHost(aProcessType, aPrivileges) michael@0: , mExistingProcessHandle(aProcess) michael@0: , mExistingFileDescriptor(aFileDescriptor) michael@0: { michael@0: NS_ASSERTION(aFileDescriptor.IsValid(), michael@0: "Expected file descriptor to be valid"); michael@0: } michael@0: michael@0: GeckoExistingProcessHost::~GeckoExistingProcessHost() michael@0: { michael@0: // Bug 943174: If we don't do this, ~GeckoChildProcessHost will try michael@0: // to wait on a process that isn't a direct child, and bad things michael@0: // will happen. michael@0: SetAlreadyDead(); michael@0: } michael@0: michael@0: bool michael@0: GeckoExistingProcessHost::PerformAsyncLaunch(StringVector aExtraOpts, michael@0: base::ProcessArchitecture aArch) michael@0: { michael@0: SetHandle(mExistingProcessHandle); michael@0: michael@0: OpenPrivilegedHandle(base::GetProcId(mExistingProcessHandle)); michael@0: michael@0: MonitorAutoLock lock(mMonitor); michael@0: mProcessState = PROCESS_CREATED; michael@0: lock.Notify(); michael@0: michael@0: return true; michael@0: } michael@0: michael@0: void michael@0: GeckoExistingProcessHost::InitializeChannel() michael@0: { michael@0: CreateChannel(mExistingFileDescriptor); michael@0: michael@0: MonitorAutoLock lock(mMonitor); michael@0: mProcessState = CHANNEL_INITIALIZED; michael@0: lock.Notify(); michael@0: } michael@0: michael@0: #endif /* MOZ_NUWA_PROCESS */