/toolkit/xre/nsAppRunner.cpp
http://github.com/zpao/v8monkey · C++ · 3783 lines · 2733 code · 617 blank · 433 comment · 477 complexity · 3ceee28c315af9b2508a8db7d645029d MD5 · raw file
Large files are truncated click here to view the full file
- /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
- /* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is Mozilla Communicator client code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
- * Benjamin Smedberg <benjamin@smedbergs.us>
- * Ben Goodger <ben@mozilla.org>
- * Fredrik Holmqvist <thesuckiestemail@yahoo.se>
- * Ben Turner <mozilla@songbirdnest.com>
- * Sergei Dolgov <sergei_d@fi.tartu.ee>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
- #if defined(XP_OS2) && defined(MOZ_OS2_HIGH_MEMORY)
- // os2safe.h has to be included before os2.h, needed for high mem
- #include <os2safe.h>
- #endif
- #define XPCOM_TRANSLATE_NSGM_ENTRY_POINT 1
- #if defined(MOZ_WIDGET_QT)
- #include <QtGui/QApplication>
- #include "nsQAppInstance.h"
- #include <QtGui/QInputContextFactory>
- #include <QtGui/QInputContext>
- #endif // MOZ_WIDGET_QT
- #include "mozilla/dom/ContentParent.h"
- #include "mozilla/dom/ContentChild.h"
- #include "mozilla/Util.h"
- #include "nsAppRunner.h"
- #include "nsUpdateDriver.h"
- #ifdef MOZ_INSTRUMENT_EVENT_LOOP
- #include "EventTracer.h"
- #endif
- #ifdef XP_MACOSX
- #include "nsVersionComparator.h"
- #include "MacLaunchHelper.h"
- #include "MacApplicationDelegate.h"
- #include "MacAutoreleasePool.h"
- // these are needed for sysctl
- #include <sys/types.h>
- #include <sys/sysctl.h>
- #endif
- #ifdef XP_OS2
- #include "private/pprthred.h"
- #endif
- #include "prmem.h"
- #include "prnetdb.h"
- #include "prprf.h"
- #include "prproces.h"
- #include "prenv.h"
- #include "nsIAppShellService.h"
- #include "nsIAppStartup.h"
- #include "nsIAppStartupNotifier.h"
- #include "nsIMutableArray.h"
- #include "nsICategoryManager.h"
- #include "nsIChromeRegistry.h"
- #include "nsICommandLineRunner.h"
- #include "nsIComponentManager.h"
- #include "nsIComponentRegistrar.h"
- #include "nsIContentHandler.h"
- #include "nsIDialogParamBlock.h"
- #include "nsIDOMWindow.h"
- #include "mozilla/ModuleUtils.h"
- #include "nsIIOService2.h"
- #include "nsIObserverService.h"
- #include "nsINativeAppSupport.h"
- #include "nsIProcess.h"
- #include "nsIProfileUnlocker.h"
- #include "nsIPromptService.h"
- #include "nsIServiceManager.h"
- #include "nsIStringBundle.h"
- #include "nsISupportsPrimitives.h"
- #include "nsIToolkitChromeRegistry.h"
- #include "nsIToolkitProfile.h"
- #include "nsIToolkitProfileService.h"
- #include "nsIURI.h"
- #include "nsIWindowCreator.h"
- #include "nsIWindowMediator.h"
- #include "nsIWindowWatcher.h"
- #include "nsIXULAppInfo.h"
- #include "nsIXULRuntime.h"
- #include "nsPIDOMWindow.h"
- #include "nsIBaseWindow.h"
- #include "nsIWidget.h"
- #include "nsIDocShell.h"
- #include "nsAppShellCID.h"
- #include "mozilla/FunctionTimer.h"
- #include "mozilla/unused.h"
- using namespace mozilla;
- using mozilla::unused;
- #ifdef XP_WIN
- #include "nsIWinAppHelper.h"
- #include <windows.h>
- #include "cairo/cairo-features.h"
- #ifndef PROCESS_DEP_ENABLE
- #define PROCESS_DEP_ENABLE 0x1
- #endif
- #endif
- #include "nsCRT.h"
- #include "nsCOMPtr.h"
- #include "nsDirectoryServiceDefs.h"
- #include "nsDirectoryServiceUtils.h"
- #include "nsEmbedCID.h"
- #include "nsNetUtil.h"
- #include "nsReadableUtils.h"
- #include "nsStaticComponents.h"
- #include "nsXPCOM.h"
- #include "nsXPCOMCIDInternal.h"
- #include "nsXPIDLString.h"
- #include "nsVersionComparator.h"
- #include "nsAppDirectoryServiceDefs.h"
- #include "nsXULAppAPI.h"
- #include "nsXREDirProvider.h"
- #include "nsToolkitCompsCID.h"
- #include "nsINIParser.h"
- #include "mozilla/Omnijar.h"
- #include "mozilla/StartupTimeline.h"
- #include <stdlib.h>
- #ifdef XP_UNIX
- #include <sys/stat.h>
- #include <unistd.h>
- #include <pwd.h>
- #endif
- #ifdef XP_WIN
- #include <process.h>
- #include <shlobj.h>
- #include "nsThreadUtils.h"
- #endif
- #ifdef XP_MACOSX
- #include "nsILocalFileMac.h"
- #include "nsCommandLineServiceMac.h"
- #endif
- // for X remote support
- #ifdef MOZ_ENABLE_XREMOTE
- #include "XRemoteClient.h"
- #include "nsIRemoteService.h"
- #endif
- #ifdef NS_TRACE_MALLOC
- #include "nsTraceMalloc.h"
- #endif
- #if defined(DEBUG) && defined(XP_WIN32)
- #include <malloc.h>
- #endif
- #if defined (XP_MACOSX)
- #include <Carbon/Carbon.h>
- #endif
- #ifdef DEBUG
- #include "prlog.h"
- #endif
- #ifdef MOZ_JPROF
- #include "jprof.h"
- #endif
- #ifdef MOZ_CRASHREPORTER
- #include "nsExceptionHandler.h"
- #include "nsICrashReporter.h"
- #define NS_CRASHREPORTER_CONTRACTID "@mozilla.org/toolkit/crash-reporter;1"
- #include "nsIPrefService.h"
- #endif
- #include "base/command_line.h"
- #include "mozilla/FunctionTimer.h"
- #ifdef MOZ_WIDGET_ANDROID
- #include "AndroidBridge.h"
- #endif
- extern PRUint32 gRestartMode;
- extern void InstallSignalHandlers(const char *ProgramName);
- #include "nsX11ErrorHandler.h"
- #define FILE_COMPATIBILITY_INFO NS_LITERAL_CSTRING("compatibility.ini")
- #define FILE_INVALIDATE_CACHES NS_LITERAL_CSTRING(".purgecaches")
- int gArgc;
- char **gArgv;
- static const char gToolkitVersion[] = NS_STRINGIFY(GRE_MILESTONE);
- static const char gToolkitBuildID[] = NS_STRINGIFY(GRE_BUILDID);
- static nsIProfileLock* gProfileLock;
- static int gRestartArgc;
- static char **gRestartArgv;
- #ifdef MOZ_WIDGET_QT
- static int gQtOnlyArgc;
- static char **gQtOnlyArgv;
- #endif
- #if defined(MOZ_WIDGET_GTK2)
- #if defined(DEBUG) || defined(NS_BUILD_REFCNT_LOGGING) \
- || defined(NS_TRACE_MALLOC)
- #define CLEANUP_MEMORY 1
- #define PANGO_ENABLE_BACKEND
- #include <pango/pangofc-fontmap.h>
- #endif
- #include <gtk/gtk.h>
- #ifdef MOZ_X11
- #include <gdk/gdkx.h>
- #endif /* MOZ_X11 */
- #include "nsGTKToolkit.h"
- #endif
- #include "BinaryPath.h"
- using mozilla::dom::ContentParent;
- using mozilla::dom::ContentChild;
- // Save literal putenv string to environment variable.
- static void
- SaveToEnv(const char *putenv)
- {
- char *expr = strdup(putenv);
- if (expr)
- PR_SetEnv(expr);
- // We intentionally leak |expr| here since it is required by PR_SetEnv.
- }
- // Tests that an environment variable exists and has a value
- static bool
- EnvHasValue(const char *name)
- {
- const char *val = PR_GetEnv(name);
- return (val && *val);
- }
- // Save the given word to the specified environment variable.
- static void
- SaveWordToEnv(const char *name, const nsACString & word)
- {
- char *expr = PR_smprintf("%s=%s", name, PromiseFlatCString(word).get());
- if (expr)
- PR_SetEnv(expr);
- // We intentionally leak |expr| here since it is required by PR_SetEnv.
- }
- // Save the path of the given file to the specified environment variable.
- static void
- SaveFileToEnv(const char *name, nsIFile *file)
- {
- #ifdef XP_WIN
- nsAutoString path;
- file->GetPath(path);
- SetEnvironmentVariableW(NS_ConvertASCIItoUTF16(name).get(), path.get());
- #else
- nsCAutoString path;
- file->GetNativePath(path);
- SaveWordToEnv(name, path);
- #endif
- }
- // Load the path of a file saved with SaveFileToEnv
- static already_AddRefed<nsILocalFile>
- GetFileFromEnv(const char *name)
- {
- nsresult rv;
- nsILocalFile *file = nsnull;
- #ifdef XP_WIN
- WCHAR path[_MAX_PATH];
- if (!GetEnvironmentVariableW(NS_ConvertASCIItoUTF16(name).get(),
- path, _MAX_PATH))
- return nsnull;
- rv = NS_NewLocalFile(nsDependentString(path), true, &file);
- if (NS_FAILED(rv))
- return nsnull;
- return file;
- #else
- const char *arg = PR_GetEnv(name);
- if (!arg || !*arg)
- return nsnull;
- rv = NS_NewNativeLocalFile(nsDependentCString(arg), true, &file);
- if (NS_FAILED(rv))
- return nsnull;
- return file;
- #endif
- }
- // Save the path of the given word to the specified environment variable
- // provided the environment variable does not have a value.
- static void
- SaveWordToEnvIfUnset(const char *name, const nsACString & word)
- {
- if (!EnvHasValue(name))
- SaveWordToEnv(name, word);
- }
- // Save the path of the given file to the specified environment variable
- // provided the environment variable does not have a value.
- static void
- SaveFileToEnvIfUnset(const char *name, nsIFile *file)
- {
- if (!EnvHasValue(name))
- SaveFileToEnv(name, file);
- }
- static bool
- strimatch(const char* lowerstr, const char* mixedstr)
- {
- while(*lowerstr) {
- if (!*mixedstr) return false; // mixedstr is shorter
- if (tolower(*mixedstr) != *lowerstr) return false; // no match
- ++lowerstr;
- ++mixedstr;
- }
- if (*mixedstr) return false; // lowerstr is shorter
- return true;
- }
- /**
- * Output a string to the user. This method is really only meant to be used to
- * output last-ditch error messages designed for developers NOT END USERS.
- *
- * @param isError
- * Pass true to indicate severe errors.
- * @param fmt
- * printf-style format string followed by arguments.
- */
- static void Output(bool isError, const char *fmt, ... )
- {
- va_list ap;
- va_start(ap, fmt);
- #if defined(XP_WIN) && !MOZ_WINCONSOLE
- char *msg = PR_vsmprintf(fmt, ap);
- if (msg)
- {
- UINT flags = MB_OK;
- if (isError)
- flags |= MB_ICONERROR;
- else
- flags |= MB_ICONINFORMATION;
- wchar_t wide_msg[1024];
- MultiByteToWideChar(CP_ACP,
- 0,
- msg,
- -1,
- wide_msg,
- sizeof(wide_msg) / sizeof(wchar_t));
- MessageBoxW(NULL, wide_msg, L"XULRunner", flags);
- PR_smprintf_free(msg);
- }
- #else
- vfprintf(stderr, fmt, ap);
- #endif
- va_end(ap);
- }
- enum RemoteResult {
- REMOTE_NOT_FOUND = 0,
- REMOTE_FOUND = 1,
- REMOTE_ARG_BAD = 2
- };
- enum ArgResult {
- ARG_NONE = 0,
- ARG_FOUND = 1,
- ARG_BAD = 2 // you wanted a param, but there isn't one
- };
- static void RemoveArg(char **argv)
- {
- do {
- *argv = *(argv + 1);
- ++argv;
- } while (*argv);
- --gArgc;
- }
- /**
- * Check for a commandline flag. If the flag takes a parameter, the
- * parameter is returned in aParam. Flags may be in the form -arg or
- * --arg (or /arg on win32/OS2).
- *
- * @param aArg the parameter to check. Must be lowercase.
- * @param aCheckOSInt if true returns ARG_BAD if the osint argument is present
- * when aArg is also present.
- * @param if non-null, the -arg <data> will be stored in this pointer. This is *not*
- * allocated, but rather a pointer to the argv data.
- */
- static ArgResult
- CheckArg(const char* aArg, bool aCheckOSInt = false, const char **aParam = nsnull, bool aRemArg = true)
- {
- NS_ABORT_IF_FALSE(gArgv, "gArgv must be initialized before CheckArg()");
- char **curarg = gArgv + 1; // skip argv[0]
- ArgResult ar = ARG_NONE;
- while (*curarg) {
- char *arg = curarg[0];
- if (arg[0] == '-'
- #if defined(XP_WIN) || defined(XP_OS2)
- || *arg == '/'
- #endif
- ) {
- ++arg;
- if (*arg == '-')
- ++arg;
- if (strimatch(aArg, arg)) {
- if (aRemArg)
- RemoveArg(curarg);
- if (!aParam) {
- ar = ARG_FOUND;
- break;
- }
- if (*curarg) {
- if (**curarg == '-'
- #if defined(XP_WIN) || defined(XP_OS2)
- || **curarg == '/'
- #endif
- )
- return ARG_BAD;
- *aParam = *curarg;
- if (aRemArg)
- RemoveArg(curarg);
- ar = ARG_FOUND;
- break;
- }
- return ARG_BAD;
- }
- }
- ++curarg;
- }
- if (aCheckOSInt && ar == ARG_FOUND) {
- ArgResult arOSInt = CheckArg("osint");
- if (arOSInt == ARG_FOUND) {
- ar = ARG_BAD;
- PR_fprintf(PR_STDERR, "Error: argument -osint is invalid\n");
- }
- }
- return ar;
- }
- #if defined(XP_WIN)
- /**
- * Check for a commandline flag from the windows shell and remove it from the
- * argv used when restarting. Flags MUST be in the form -arg.
- *
- * @param aArg the parameter to check. Must be lowercase.
- */
- static ArgResult
- CheckArgShell(const char* aArg)
- {
- char **curarg = gRestartArgv + 1; // skip argv[0]
- while (*curarg) {
- char *arg = curarg[0];
- if (arg[0] == '-') {
- ++arg;
- if (strimatch(aArg, arg)) {
- do {
- *curarg = *(curarg + 1);
- ++curarg;
- } while (*curarg);
- --gRestartArgc;
- return ARG_FOUND;
- }
- }
- ++curarg;
- }
- return ARG_NONE;
- }
- /**
- * Enabled Native App Support to process DDE messages when the app needs to
- * restart and the app has been launched by the Windows shell to open an url.
- * When aWait is false this will process the DDE events manually. This prevents
- * Windows from displaying an error message due to the DDE message not being
- * acknowledged.
- */
- static void
- ProcessDDE(nsINativeAppSupport* aNative, bool aWait)
- {
- // When the app is launched by the windows shell the windows shell
- // expects the app to be available for DDE messages and if it isn't
- // windows displays an error dialog. To prevent the error the DDE server
- // is enabled and pending events are processed when the app needs to
- // restart after it was launched by the shell with the requestpending
- // argument. The requestpending pending argument is removed to
- // differentiate it from being launched when an app restart is not
- // required.
- ArgResult ar;
- ar = CheckArgShell("requestpending");
- if (ar == ARG_FOUND) {
- aNative->Enable(); // enable win32 DDE responses
- if (aWait) {
- nsIThread *thread = NS_GetCurrentThread();
- // This is just a guesstimate based on testing different values.
- // If count is 8 or less windows will display an error dialog.
- PRInt32 count = 20;
- while(--count >= 0) {
- NS_ProcessNextEvent(thread);
- PR_Sleep(PR_MillisecondsToInterval(1));
- }
- }
- }
- }
- #endif
- bool gSafeMode = false;
- /**
- * The nsXULAppInfo object implements nsIFactory so that it can be its own
- * singleton.
- */
- class nsXULAppInfo : public nsIXULAppInfo,
- #ifdef XP_WIN
- public nsIWinAppHelper,
- #endif
- #ifdef MOZ_CRASHREPORTER
- public nsICrashReporter,
- #endif
- public nsIXULRuntime
- {
- public:
- nsXULAppInfo() {}
- NS_DECL_ISUPPORTS_INHERITED
- NS_DECL_NSIXULAPPINFO
- NS_DECL_NSIXULRUNTIME
- #ifdef MOZ_CRASHREPORTER
- NS_DECL_NSICRASHREPORTER
- #endif
- #ifdef XP_WIN
- NS_DECL_NSIWINAPPHELPER
- #endif
- };
- NS_INTERFACE_MAP_BEGIN(nsXULAppInfo)
- NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIXULRuntime)
- NS_INTERFACE_MAP_ENTRY(nsIXULRuntime)
- #ifdef XP_WIN
- NS_INTERFACE_MAP_ENTRY(nsIWinAppHelper)
- #endif
- #ifdef MOZ_CRASHREPORTER
- NS_INTERFACE_MAP_ENTRY(nsICrashReporter)
- #endif
- NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIXULAppInfo, gAppData ||
- XRE_GetProcessType() == GeckoProcessType_Content)
- NS_INTERFACE_MAP_END
- NS_IMETHODIMP_(nsrefcnt)
- nsXULAppInfo::AddRef()
- {
- return 1;
- }
- NS_IMETHODIMP_(nsrefcnt)
- nsXULAppInfo::Release()
- {
- return 1;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetVendor(nsACString& aResult)
- {
- if (XRE_GetProcessType() == GeckoProcessType_Content) {
- NS_WARNING("Attempt to get unavailable information in content process.");
- return NS_ERROR_NOT_AVAILABLE;
- }
- aResult.Assign(gAppData->vendor);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetName(nsACString& aResult)
- {
- if (XRE_GetProcessType() == GeckoProcessType_Content) {
- NS_WARNING("Attempt to get unavailable information in content process.");
- return NS_ERROR_NOT_AVAILABLE;
- }
- aResult.Assign(gAppData->name);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetID(nsACString& aResult)
- {
- if (XRE_GetProcessType() == GeckoProcessType_Content) {
- NS_WARNING("Attempt to get unavailable information in content process.");
- return NS_ERROR_NOT_AVAILABLE;
- }
- aResult.Assign(gAppData->ID);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetVersion(nsACString& aResult)
- {
- if (XRE_GetProcessType() == GeckoProcessType_Content) {
- ContentChild* cc = ContentChild::GetSingleton();
- aResult = cc->GetAppInfo().version;
- return NS_OK;
- }
- aResult.Assign(gAppData->version);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetPlatformVersion(nsACString& aResult)
- {
- aResult.Assign(gToolkitVersion);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetAppBuildID(nsACString& aResult)
- {
- if (XRE_GetProcessType() == GeckoProcessType_Content) {
- ContentChild* cc = ContentChild::GetSingleton();
- aResult = cc->GetAppInfo().buildID;
- return NS_OK;
- }
- aResult.Assign(gAppData->buildID);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetPlatformBuildID(nsACString& aResult)
- {
- aResult.Assign(gToolkitBuildID);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetLogConsoleErrors(bool *aResult)
- {
- *aResult = gLogConsoleErrors;
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::SetLogConsoleErrors(bool aValue)
- {
- gLogConsoleErrors = aValue;
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetInSafeMode(bool *aResult)
- {
- *aResult = gSafeMode;
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetOS(nsACString& aResult)
- {
- aResult.AssignLiteral(OS_TARGET);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetXPCOMABI(nsACString& aResult)
- {
- #ifdef TARGET_XPCOM_ABI
- aResult.AssignLiteral(TARGET_XPCOM_ABI);
- return NS_OK;
- #else
- return NS_ERROR_NOT_AVAILABLE;
- #endif
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetWidgetToolkit(nsACString& aResult)
- {
- aResult.AssignLiteral(MOZ_WIDGET_TOOLKIT);
- return NS_OK;
- }
- // Ensure that the GeckoProcessType enum, defined in xpcom/build/nsXULAppAPI.h,
- // is synchronized with the const unsigned longs defined in
- // xpcom/system/nsIXULRuntime.idl.
- #define SYNC_ENUMS(a,b) \
- PR_STATIC_ASSERT(nsIXULRuntime::PROCESS_TYPE_ ## a == \
- static_cast<int>(GeckoProcessType_ ## b));
- SYNC_ENUMS(DEFAULT, Default)
- SYNC_ENUMS(PLUGIN, Plugin)
- SYNC_ENUMS(CONTENT, Content)
- SYNC_ENUMS(IPDLUNITTEST, IPDLUnitTest)
- // .. and ensure that that is all of them:
- PR_STATIC_ASSERT(GeckoProcessType_IPDLUnitTest + 1 == GeckoProcessType_End);
- NS_IMETHODIMP
- nsXULAppInfo::GetProcessType(PRUint32* aResult)
- {
- NS_ENSURE_ARG_POINTER(aResult);
- *aResult = XRE_GetProcessType();
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::EnsureContentProcess()
- {
- if (XRE_GetProcessType() != GeckoProcessType_Default)
- return NS_ERROR_NOT_AVAILABLE;
- unused << ContentParent::GetNewOrUsed();
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::InvalidateCachesOnRestart()
- {
- nsCOMPtr<nsIFile> file;
- nsresult rv = NS_GetSpecialDirectory(NS_APP_PROFILE_DIR_STARTUP,
- getter_AddRefs(file));
- if (NS_FAILED(rv))
- return rv;
- if (!file)
- return NS_ERROR_NOT_AVAILABLE;
-
- file->AppendNative(FILE_COMPATIBILITY_INFO);
- nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(file));
- nsINIParser parser;
- rv = parser.Init(localFile);
- if (NS_FAILED(rv)) {
- // This fails if compatibility.ini is not there, so we'll
- // flush the caches on the next restart anyways.
- return NS_OK;
- }
-
- nsCAutoString buf;
- rv = parser.GetString("Compatibility", "InvalidateCaches", buf);
-
- if (NS_FAILED(rv)) {
- PRFileDesc *fd = nsnull;
- localFile->OpenNSPRFileDesc(PR_RDWR | PR_APPEND, 0600, &fd);
- if (!fd) {
- NS_ERROR("could not create output stream");
- return NS_ERROR_NOT_AVAILABLE;
- }
- static const char kInvalidationHeader[] = NS_LINEBREAK "InvalidateCaches=1" NS_LINEBREAK;
- rv = PR_Write(fd, kInvalidationHeader, sizeof(kInvalidationHeader) - 1);
- PR_Close(fd);
-
- if (NS_FAILED(rv))
- return rv;
- }
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetReplacedLockTime(PRInt64 *aReplacedLockTime)
- {
- if (!gProfileLock)
- return NS_ERROR_NOT_AVAILABLE;
- gProfileLock->GetReplacedLockTime(aReplacedLockTime);
- return NS_OK;
- }
- #ifdef XP_WIN
- // Matches the enum in WinNT.h for the Vista SDK but renamed so that we can
- // safely build with the Vista SDK and without it.
- typedef enum
- {
- VistaTokenElevationTypeDefault = 1,
- VistaTokenElevationTypeFull,
- VistaTokenElevationTypeLimited
- } VISTA_TOKEN_ELEVATION_TYPE;
- // avoid collision with TokeElevationType enum in WinNT.h
- // of the Vista SDK
- #define VistaTokenElevationType static_cast< TOKEN_INFORMATION_CLASS >( 18 )
- NS_IMETHODIMP
- nsXULAppInfo::GetUserCanElevate(bool *aUserCanElevate)
- {
- HANDLE hToken;
- VISTA_TOKEN_ELEVATION_TYPE elevationType;
- DWORD dwSize;
- if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken) ||
- !GetTokenInformation(hToken, VistaTokenElevationType, &elevationType,
- sizeof(elevationType), &dwSize)) {
- *aUserCanElevate = false;
- }
- else {
- // The possible values returned for elevationType and their meanings are:
- // TokenElevationTypeDefault: The token does not have a linked token
- // (e.g. UAC disabled or a standard user, so they can't be elevated)
- // TokenElevationTypeFull: The token is linked to an elevated token
- // (e.g. UAC is enabled and the user is already elevated so they can't
- // be elevated again)
- // TokenElevationTypeLimited: The token is linked to a limited token
- // (e.g. UAC is enabled and the user is not elevated, so they can be
- // elevated)
- *aUserCanElevate = (elevationType == VistaTokenElevationTypeLimited);
- }
- if (hToken)
- CloseHandle(hToken);
- return NS_OK;
- }
- #endif
- #ifdef MOZ_CRASHREPORTER
- NS_IMETHODIMP
- nsXULAppInfo::GetEnabled(bool *aEnabled)
- {
- *aEnabled = CrashReporter::GetEnabled();
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::SetEnabled(bool aEnabled)
- {
- if (aEnabled) {
- if (CrashReporter::GetEnabled())
- // no point in erroring for double-enabling
- return NS_OK;
- nsCOMPtr<nsILocalFile> xreDirectory;
- if (gAppData) {
- xreDirectory = gAppData->xreDirectory;
- }
- else {
- // We didn't get started through XRE_Main, probably
- nsCOMPtr<nsIFile> greDir;
- NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(greDir));
- if (!greDir)
- return NS_ERROR_FAILURE;
- xreDirectory = do_QueryInterface(greDir);
- if (!xreDirectory)
- return NS_ERROR_FAILURE;
- }
- return CrashReporter::SetExceptionHandler(xreDirectory, true);
- }
- else {
- if (!CrashReporter::GetEnabled())
- // no point in erroring for double-disabling
- return NS_OK;
- return CrashReporter::UnsetExceptionHandler();
- }
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetServerURL(nsIURL** aServerURL)
- {
- if (!CrashReporter::GetEnabled())
- return NS_ERROR_NOT_INITIALIZED;
- nsCAutoString data;
- if (!CrashReporter::GetServerURL(data)) {
- return NS_ERROR_FAILURE;
- }
- nsCOMPtr<nsIURI> uri;
- NS_NewURI(getter_AddRefs(uri), data);
- if (!uri)
- return NS_ERROR_FAILURE;
- nsCOMPtr<nsIURL> url;
- url = do_QueryInterface(uri);
- NS_ADDREF(*aServerURL = url);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::SetServerURL(nsIURL* aServerURL)
- {
- bool schemeOk;
- // only allow https or http URLs
- nsresult rv = aServerURL->SchemeIs("https", &schemeOk);
- NS_ENSURE_SUCCESS(rv, rv);
- if (!schemeOk) {
- rv = aServerURL->SchemeIs("http", &schemeOk);
- NS_ENSURE_SUCCESS(rv, rv);
- if (!schemeOk)
- return NS_ERROR_INVALID_ARG;
- }
- nsCAutoString spec;
- rv = aServerURL->GetSpec(spec);
- NS_ENSURE_SUCCESS(rv, rv);
-
- return CrashReporter::SetServerURL(spec);
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetMinidumpPath(nsILocalFile** aMinidumpPath)
- {
- if (!CrashReporter::GetEnabled())
- return NS_ERROR_NOT_INITIALIZED;
- nsAutoString path;
- if (!CrashReporter::GetMinidumpPath(path))
- return NS_ERROR_FAILURE;
- nsresult rv = NS_NewLocalFile(path, false, aMinidumpPath);
- NS_ENSURE_SUCCESS(rv, rv);
- return NS_OK;
- }
- NS_IMETHODIMP
- nsXULAppInfo::SetMinidumpPath(nsILocalFile* aMinidumpPath)
- {
- nsAutoString path;
- nsresult rv = aMinidumpPath->GetPath(path);
- NS_ENSURE_SUCCESS(rv, rv);
- return CrashReporter::SetMinidumpPath(path);
- }
- NS_IMETHODIMP
- nsXULAppInfo::AnnotateCrashReport(const nsACString& key,
- const nsACString& data)
- {
- return CrashReporter::AnnotateCrashReport(key, data);
- }
- NS_IMETHODIMP
- nsXULAppInfo::AppendAppNotesToCrashReport(const nsACString& data)
- {
- return CrashReporter::AppendAppNotesToCrashReport(data);
- }
- NS_IMETHODIMP
- nsXULAppInfo::RegisterAppMemory(PRUint64 pointer,
- PRUint64 len)
- {
- return CrashReporter::RegisterAppMemory((void *)pointer, len);
- }
- NS_IMETHODIMP
- nsXULAppInfo::WriteMinidumpForException(void* aExceptionInfo)
- {
- #ifdef XP_WIN32
- return CrashReporter::WriteMinidumpForException(static_cast<EXCEPTION_POINTERS*>(aExceptionInfo));
- #else
- return NS_ERROR_NOT_IMPLEMENTED;
- #endif
- }
- NS_IMETHODIMP
- nsXULAppInfo::AppendObjCExceptionInfoToAppNotes(void* aException)
- {
- #ifdef XP_MACOSX
- return CrashReporter::AppendObjCExceptionInfoToAppNotes(aException);
- #else
- return NS_ERROR_NOT_IMPLEMENTED;
- #endif
- }
- NS_IMETHODIMP
- nsXULAppInfo::GetSubmitReports(bool* aEnabled)
- {
- return CrashReporter::GetSubmitReports(aEnabled);
- }
- NS_IMETHODIMP
- nsXULAppInfo::SetSubmitReports(bool aEnabled)
- {
- return CrashReporter::SetSubmitReports(aEnabled);
- }
- #endif
- static const nsXULAppInfo kAppInfo;
- static nsresult AppInfoConstructor(nsISupports* aOuter,
- REFNSIID aIID, void **aResult)
- {
- NS_ENSURE_NO_AGGREGATION(aOuter);
- return const_cast<nsXULAppInfo*>(&kAppInfo)->
- QueryInterface(aIID, aResult);
- }
- bool gLogConsoleErrors
- #ifdef DEBUG
- = true;
- #else
- = false;
- #endif
- #define NS_ENSURE_TRUE_LOG(x, ret) \
- PR_BEGIN_MACRO \
- if (NS_UNLIKELY(!(x))) { \
- NS_WARNING("NS_ENSURE_TRUE(" #x ") failed"); \
- gLogConsoleErrors = true; \
- return ret; \
- } \
- PR_END_MACRO
- #define NS_ENSURE_SUCCESS_LOG(res, ret) \
- NS_ENSURE_TRUE_LOG(NS_SUCCEEDED(res), ret)
- /**
- * Because we're starting/stopping XPCOM several times in different scenarios,
- * this class is a stack-based critter that makes sure that XPCOM is shut down
- * during early returns.
- */
- class ScopedXPCOMStartup
- {
- public:
- ScopedXPCOMStartup() :
- mServiceManager(nsnull) { }
- ~ScopedXPCOMStartup();
- nsresult Initialize();
- nsresult SetWindowCreator(nsINativeAppSupport* native);
- static nsresult CreateAppSupport(nsISupports* aOuter, REFNSIID aIID, void** aResult);
- private:
- nsIServiceManager* mServiceManager;
- static nsINativeAppSupport* gNativeAppSupport;
- };
- ScopedXPCOMStartup::~ScopedXPCOMStartup()
- {
- NS_IF_RELEASE(gNativeAppSupport);
- if (mServiceManager) {
- #ifdef XP_MACOSX
- // On OS X, we need a pool to catch cocoa objects that are autoreleased
- // during teardown.
- mozilla::MacAutoreleasePool pool;
- #endif
- nsCOMPtr<nsIAppStartup> appStartup (do_GetService(NS_APPSTARTUP_CONTRACTID));
- if (appStartup)
- appStartup->DestroyHiddenWindow();
- gDirServiceProvider->DoShutdown();
- WriteConsoleLog();
- NS_ShutdownXPCOM(mServiceManager);
- mServiceManager = nsnull;
- }
- }
- // {95d89e3e-a169-41a3-8e56-719978e15b12}
- #define APPINFO_CID \
- { 0x95d89e3e, 0xa169, 0x41a3, { 0x8e, 0x56, 0x71, 0x99, 0x78, 0xe1, 0x5b, 0x12 } }
- // {0C4A446C-EE82-41f2-8D04-D366D2C7A7D4}
- static const nsCID kNativeAppSupportCID =
- { 0xc4a446c, 0xee82, 0x41f2, { 0x8d, 0x4, 0xd3, 0x66, 0xd2, 0xc7, 0xa7, 0xd4 } };
- // {5F5E59CE-27BC-47eb-9D1F-B09CA9049836}
- static const nsCID kProfileServiceCID =
- { 0x5f5e59ce, 0x27bc, 0x47eb, { 0x9d, 0x1f, 0xb0, 0x9c, 0xa9, 0x4, 0x98, 0x36 } };
- static already_AddRefed<nsIFactory>
- ProfileServiceFactoryConstructor(const mozilla::Module& module, const mozilla::Module::CIDEntry& entry)
- {
- nsCOMPtr<nsIFactory> factory;
- NS_NewToolkitProfileFactory(getter_AddRefs(factory));
- return factory.forget();
- }
- NS_DEFINE_NAMED_CID(APPINFO_CID);
- static const mozilla::Module::CIDEntry kXRECIDs[] = {
- { &kAPPINFO_CID, false, NULL, AppInfoConstructor },
- { &kProfileServiceCID, false, ProfileServiceFactoryConstructor, NULL },
- { &kNativeAppSupportCID, false, NULL, ScopedXPCOMStartup::CreateAppSupport },
- { NULL }
- };
- static const mozilla::Module::ContractIDEntry kXREContracts[] = {
- { XULAPPINFO_SERVICE_CONTRACTID, &kAPPINFO_CID },
- { XULRUNTIME_SERVICE_CONTRACTID, &kAPPINFO_CID },
- #ifdef MOZ_CRASHREPORTER
- { NS_CRASHREPORTER_CONTRACTID, &kAPPINFO_CID },
- #endif
- { NS_PROFILESERVICE_CONTRACTID, &kProfileServiceCID },
- { NS_NATIVEAPPSUPPORT_CONTRACTID, &kNativeAppSupportCID },
- { NULL }
- };
- static const mozilla::Module kXREModule = {
- mozilla::Module::kVersion,
- kXRECIDs,
- kXREContracts
- };
- NSMODULE_DEFN(Apprunner) = &kXREModule;
- nsresult
- ScopedXPCOMStartup::Initialize()
- {
- NS_ASSERTION(gDirServiceProvider, "Should not get here!");
- nsresult rv;
- rv = NS_InitXPCOM2(&mServiceManager, gDirServiceProvider->GetAppDir(),
- gDirServiceProvider);
- if (NS_FAILED(rv)) {
- NS_ERROR("Couldn't start xpcom!");
- mServiceManager = nsnull;
- }
- else {
- nsCOMPtr<nsIComponentRegistrar> reg =
- do_QueryInterface(mServiceManager);
- NS_ASSERTION(reg, "Service Manager doesn't QI to Registrar.");
- }
- return rv;
- }
- /**
- * This is a little factory class that serves as a singleton-service-factory
- * for the nativeappsupport object.
- */
- class nsSingletonFactory : public nsIFactory
- {
- public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIFACTORY
- nsSingletonFactory(nsISupports* aSingleton);
- ~nsSingletonFactory() { }
- private:
- nsCOMPtr<nsISupports> mSingleton;
- };
- nsSingletonFactory::nsSingletonFactory(nsISupports* aSingleton)
- : mSingleton(aSingleton)
- {
- NS_ASSERTION(mSingleton, "Singleton was null!");
- }
- NS_IMPL_ISUPPORTS1(nsSingletonFactory, nsIFactory)
- NS_IMETHODIMP
- nsSingletonFactory::CreateInstance(nsISupports* aOuter,
- const nsIID& aIID,
- void* *aResult)
- {
- NS_ENSURE_NO_AGGREGATION(aOuter);
- return mSingleton->QueryInterface(aIID, aResult);
- }
- NS_IMETHODIMP
- nsSingletonFactory::LockFactory(bool)
- {
- return NS_OK;
- }
- /**
- * Set our windowcreator on the WindowWatcher service.
- */
- nsresult
- ScopedXPCOMStartup::SetWindowCreator(nsINativeAppSupport* native)
- {
- NS_TIME_FUNCTION;
- nsresult rv;
- NS_IF_ADDREF(gNativeAppSupport = native);
- // Inform the chrome registry about OS accessibility
- nsCOMPtr<nsIToolkitChromeRegistry> cr =
- mozilla::services::GetToolkitChromeRegistryService();
- NS_TIME_FUNCTION_MARK("Got ToolkitChromeRegistry service");
- if (cr)
- cr->CheckForOSAccessibility();
- NS_TIME_FUNCTION_MARK("OS Accessibility check");
- nsCOMPtr<nsIWindowCreator> creator (do_GetService(NS_APPSTARTUP_CONTRACTID));
- if (!creator) return NS_ERROR_UNEXPECTED;
- NS_TIME_FUNCTION_MARK("Got AppStartup service");
- nsCOMPtr<nsIWindowWatcher> wwatch
- (do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv));
- NS_ENSURE_SUCCESS(rv, rv);
-
- NS_TIME_FUNCTION_MARK("Got WindowWatcher service");
- return wwatch->SetWindowCreator(creator);
- }
- /* static */ nsresult
- ScopedXPCOMStartup::CreateAppSupport(nsISupports* aOuter, REFNSIID aIID, void** aResult)
- {
- if (aOuter)
- return NS_ERROR_NO_AGGREGATION;
- if (!gNativeAppSupport)
- return NS_ERROR_NOT_INITIALIZED;
- return gNativeAppSupport->QueryInterface(aIID, aResult);
- }
- nsINativeAppSupport* ScopedXPCOMStartup::gNativeAppSupport;
- /**
- * A helper class which calls NS_LogInit/NS_LogTerm in its scope.
- */
- class ScopedLogging
- {
- public:
- ScopedLogging() { NS_LogInit(); }
- ~ScopedLogging() { NS_LogTerm(); }
- };
- static void DumpArbitraryHelp()
- {
- nsresult rv;
- ScopedLogging log;
- {
- ScopedXPCOMStartup xpcom;
- xpcom.Initialize();
- nsCOMPtr<nsICommandLineRunner> cmdline
- (do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
- if (!cmdline)
- return;
- nsCString text;
- rv = cmdline->GetHelpText(text);
- if (NS_SUCCEEDED(rv))
- printf("%s", text.get());
- }
- }
- // English text needs to go into a dtd file.
- // But when this is called we have no components etc. These strings must either be
- // here, or in a native resource file.
- static void
- DumpHelp()
- {
- printf("Usage: %s [ options ... ] [URL]\n"
- " where options include:\n\n", gArgv[0]);
- #ifdef MOZ_X11
- printf("X11 options\n"
- " --display=DISPLAY X display to use\n"
- " --sync Make X calls synchronous\n");
- #endif
- #ifdef XP_UNIX
- printf(" --g-fatal-warnings Make all warnings fatal\n"
- "\n%s options\n", gAppData->name);
- #endif
- printf(" -h or -help Print this message.\n"
- " -v or -version Print %s version.\n"
- " -P <profile> Start with <profile>.\n"
- " -migration Start with migration wizard.\n"
- " -ProfileManager Start with ProfileManager.\n"
- " -no-remote Do not accept or send remote commands; implies -new-instance.\n"
- " -new-instance Open new instance, not a new window in running instance.\n"
- " -UILocale <locale> Start with <locale> resources as UI Locale.\n"
- " -safe-mode Disables extensions and themes for this session.\n", gAppData->name);
- #if defined(XP_WIN) || defined(XP_OS2)
- printf(" -console Start %s with a debugging console.\n", gAppData->name);
- #endif
- // this works, but only after the components have registered. so if you drop in a new command line handler, -help
- // won't not until the second run.
- // out of the bug, because we ship a component.reg file, it works correctly.
- DumpArbitraryHelp();
- }
- #ifdef DEBUG_warren
- #ifdef XP_WIN
- #define _CRTDBG_MAP_ALLOC
- #include <crtdbg.h>
- #endif
- #endif
- #if defined(FREEBSD)
- // pick up fpsetmask prototype.
- #include <ieeefp.h>
- #endif
- static inline void
- DumpVersion()
- {
- printf("%s %s %s",
- gAppData->vendor ? gAppData->vendor : "", gAppData->name, gAppData->version);
- if (gAppData->copyright)
- printf(", %s", gAppData->copyright);
- printf("\n");
- }
- #ifdef MOZ_ENABLE_XREMOTE
- // use int here instead of a PR type since it will be returned
- // from main - just to keep types consistent
- static int
- HandleRemoteArgument(const char* remote, const char* aDesktopStartupID)
- {
- nsresult rv;
- ArgResult ar;
- const char *profile = 0;
- nsCAutoString program(gAppData->name);
- ToLowerCase(program);
- const char *username = getenv("LOGNAME");
- ar = CheckArg("p", false, &profile);
- if (ar == ARG_BAD) {
- PR_fprintf(PR_STDERR, "Error: argument -p requires a profile name\n");
- return 1;
- }
- const char *temp = nsnull;
- ar = CheckArg("a", false, &temp);
- if (ar == ARG_BAD) {
- PR_fprintf(PR_STDERR, "Error: argument -a requires an application name\n");
- return 1;
- } else if (ar == ARG_FOUND) {
- program.Assign(temp);
- }
- ar = CheckArg("u", false, &username);
- if (ar == ARG_BAD) {
- PR_fprintf(PR_STDERR, "Error: argument -u requires a username\n");
- return 1;
- }
- XRemoteClient client;
- rv = client.Init();
- if (NS_FAILED(rv)) {
- PR_fprintf(PR_STDERR, "Error: Failed to connect to X server.\n");
- return 1;
- }
- nsXPIDLCString response;
- bool success = false;
- rv = client.SendCommand(program.get(), username, profile, remote,
- aDesktopStartupID, getter_Copies(response), &success);
- // did the command fail?
- if (NS_FAILED(rv)) {
- PR_fprintf(PR_STDERR, "Error: Failed to send command: %s\n",
- response ? response.get() : "No response included");
- return 1;
- }
- if (!success) {
- PR_fprintf(PR_STDERR, "Error: No running window found\n");
- return 2;
- }
- return 0;
- }
- static RemoteResult
- RemoteCommandLine(const char* aDesktopStartupID)
- {
- nsresult rv;
- ArgResult ar;
- nsCAutoString program(gAppData->name);
- ToLowerCase(program);
- const char *username = getenv("LOGNAME");
- const char *temp = nsnull;
- ar = CheckArg("a", true, &temp);
- if (ar == ARG_BAD) {
- PR_fprintf(PR_STDERR, "Error: argument -a requires an application name\n");
- return REMOTE_ARG_BAD;
- } else if (ar == ARG_FOUND) {
- program.Assign(temp);
- }
- ar = CheckArg("u", true, &username);
- if (ar == ARG_BAD) {
- PR_fprintf(PR_STDERR, "Error: argument -u requires a username\n");
- return REMOTE_ARG_BAD;
- }
- XRemoteClient client;
- rv = client.Init();
- if (NS_FAILED(rv))
- return REMOTE_NOT_FOUND;
-
- nsXPIDLCString response;
- bool success = false;
- rv = client.SendCommandLine(program.get(), username, nsnull,
- gArgc, gArgv, aDesktopStartupID,
- getter_Copies(response), &success);
- // did the command fail?
- if (NS_FAILED(rv) || !success)
- return REMOTE_NOT_FOUND;
- return REMOTE_FOUND;
- }
- #endif // MOZ_ENABLE_XREMOTE
- void
- XRE_InitOmnijar(nsILocalFile* greOmni, nsILocalFile* appOmni)
- {
- mozilla::Omnijar::Init(greOmni, appOmni);
- }
- nsresult
- XRE_GetBinaryPath(const char* argv0, nsILocalFile* *aResult)
- {
- return mozilla::BinaryPath::GetFile(argv0, aResult);
- }
- #define NS_ERROR_LAUNCHED_CHILD_PROCESS NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_PROFILE, 200)
- #ifdef XP_WIN
- #include "nsWindowsRestart.cpp"
- #include <shellapi.h>
- typedef BOOL (WINAPI* SetProcessDEPPolicyFunc)(DWORD dwFlags);
- #endif
- #if defined(XP_OS2) && (__KLIBC__ == 0 && __KLIBC_MINOR__ >= 6) // broken kLibc
- // Copy the environment maintained by the C library into an ASCIIZ array
- // that can be used to pass it on to the OS/2 Dos* APIs (which otherwise
- // don't know anything about the stuff set by PR_SetEnv() or setenv()).
- char *createEnv()
- {
- // just allocate the maximum amount (24 kB = 0x60000 bytes), to be able to
- // copy the existing environment
- char *env = (char *)calloc(0x6000, sizeof(char));
- if (!env) {
- return NULL;
- }
- // walk along the environ string array of the C library and copy
- // everything (that fits) into the output environment array, leaving
- // null bytes between the entries
- char *penv = env; // movable pointer to result environment ASCIIZ array
- int i = 0, space = 0x6000;
- while (environ[i] && environ[i][0]) {
- int len = strlen(environ[i]);
- if (space - len <= 0) {
- break;
- }
- strcpy(penv, environ[i]);
- i++; // next environment variable
- penv += len + 1; // jump to after next null byte
- space -= len - 1; // subtract consumed length from usable space
- }
- return env;
- }
- // OS2LaunchChild() is there to replace _execv() which is broken in the C
- // runtime library that comes with GCC 3.3.5 on OS/2. It uses createEnv()
- // to copy the process environment and add necessary variables
- //
- // returns -1 on failure and 0 on success
- int OS2LaunchChild(const char *aExePath, int aArgc, char **aArgv)
- {
- // find total length of aArgv
- int len = 0;
- for (int i = 0; i < aArgc; i++) {
- len += strlen(aArgv[i]) + 1; // plus space in between
- }
- len++; // leave space for null byte at end
- // allocate enough space for all strings and nulls,
- // calloc helpfully initializes to null
- char *args = (char *)calloc(len, sizeof(char));
- if (!args) {
- return -1;
- }
- char *pargs = args; // extra pointer to after the last argument
- // build argument list in the format the DosStartSession() wants,
- // adding spaces between the arguments
- for (int i = 0; i < aArgc; i++, *pargs++ = ' ') {
- strcpy(pargs, aArgv[i]);
- pargs += strlen(aArgv[i]);
- }
- if (aArgc > 1) {
- *(pargs-1) = '\0'; // replace last space
- }
- *pargs = '\0';
- // make sure that the program is separated by null byte
- pargs = strchr(args, ' ');
- if (pargs) {
- *pargs = '\0';
- }
- char *env = createEnv();
- char error[CCHMAXPATH] = { 0 };
- RESULTCODES crc = { 0 };
- ULONG rc = DosExecPgm(error, sizeof(error), EXEC_ASYNC, args, env,
- &crc, (PSZ)aExePath);
- free(args); // done with the arguments
- if (env) {
- free(env);
- }
- if (rc != NO_ERROR) {
- return -1;
- }
- return 0;
- }
- #endif
- // If aBlankCommandLine is true, then the application will be launched with a
- // blank command line instead of being launched with the same command line that
- // it was initially started with.
- static nsresult LaunchChild(nsINativeAppSupport* aNative,
- bool aBlankCommandLine = false)
- {
- aNative->Quit(); // release DDE mutex, if we're holding it
- // Restart this process by exec'ing it into the current process
- // if supported by the platform. Otherwise, use NSPR.
- #ifdef MOZ_JPROF
- // make sure JPROF doesn't think we're E10s
- unsetenv("JPROF_SLAVE");
- #endif
- if (aBlankCommandLine) {
- #if defined(MOZ_WIDGET_QT)
- // Remove only arguments not given to Qt
- gRestartArgc = gQtOnlyArgc;
- gRestartArgv = gQtOnlyArgv;
- #else
- gRestartArgc = 1;
- gRestartArgv[gRestartArgc] = nsnull;
- #endif
- }
- SaveToEnv("MOZ_LAUNCHED_CHILD=1");
- #if defined(MOZ_WIDGET_ANDROID)
- mozilla::AndroidBridge::Bridge()->ScheduleRestart();
- #else
- #if defined(XP_MACOSX)
- CommandLineServiceMac::SetupMacCommandLine(gRestartArgc, gRestartArgv, true);
- PRUint32 restartMode = 0;
- restartMode = gRestartMode;
- LaunchChildMac(gRestartArgc, gRestartArgv, restartMode);
- #else
- nsCOMPtr<nsILocalFile> lf;
- nsresult rv = XRE_GetBinaryPath(gArgv[0], getter_AddRefs(lf));
- if (NS_FAILED(rv))
- return rv;
- #if defined(XP_WIN)
- nsAutoString exePath;
- rv = lf->GetPath(exePath);
- if (NS_FAILED(rv))
- return rv;
- if (!WinLaunchChild(exePath.get(), gRestartArgc, gRestartArgv))
- return NS_ERROR_FAILURE;
- #else
- nsCAutoString exePath;
- rv = lf->GetNativePath(exePath);
- if (NS_FAILED(rv))
- return rv;
- #if defined(XP_OS2) && (__KLIBC__ == 0 && __KLIBC_MINOR__ >= 6)
- // implementation of _execv() is broken with kLibc 0.6.x and later
- if (OS2LaunchChild(exePath.get(), gRestartArgc, gRestartArgv) == -1)
- return NS_ERROR_FAILURE;
- #elif defined(XP_OS2)
- if (_execv(exePath.get(), gRestartArgv) == -1)
- return NS_ERROR_FAILURE;
- #elif defined(XP_UNIX)
- if (execv(exePath.get(), gRestartArgv) == -1)
- return NS_ERROR_FAILURE;
- #else
- PRProcess* process = PR_CreateProcess(exePath.get(), gRestartArgv,
- nsnull, nsnull);
- if (!process) return NS_ERROR_FAILURE;
- PRInt32 exitCode;
- PRStatus failed = PR_WaitProcess(process, &exitCode);
- if (failed || exitCode)
- return NS_ERROR_FAILURE;
- #endif // XP_OS2 series
- #endif // WP_WIN
- #endif // WP_MACOSX
- #endif // MOZ_WIDGET_ANDROID
- return NS_ERROR_LAUNCHED_CHILD_PROCESS;
- }
- static const char kProfileProperties[] =
- "chrome://mozapps/locale/profile/profileSelection.properties";
- static nsresult
- ProfileLockedDialog(nsILocalFile* aProfileDir, nsILocalFile* aProfileLocalDir,
- nsIProfileUnlocker* aUnlocker,
- nsINativeAppSupport* aNative, nsIProfileLock* *aResult)
- {
- nsresult rv;
- ScopedXPCOMStartup xpcom;
- rv = xpcom.Initialize();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = xpcom.SetWindowCreator(aNative);
- NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
- { //extra scoping is needed so we release these components before xpcom shutdown
- nsCOMPtr<nsIStringBundleService> sbs =
- mozilla::services::GetStringBundleService();
- NS_ENSURE_TRUE(sbs, NS_ERROR_FAILURE);
- nsCOMPtr<nsIStringBundle> sb;
- sbs->CreateBundle(kProfileProperties, getter_AddRefs(sb));
- NS_ENSURE_TRUE_LOG(sbs, NS_ERROR_FAILURE);
- NS_ConvertUTF8toUTF16 appName(gAppData->name);
- const PRUnichar* params[] = {appName.get(), appName.get()};
- nsXPIDLString killMessage;
- #ifndef XP_MACOSX
- static const PRUnichar kRestartNoUnlocker[] = {'r','e','s','t','a','r','t','M','e','s','s','a','g','e','N','o','U','n','l','o','c','k','e','r','\0'}; // "restartMessageNoUnlocker"
- static const PRUnichar kRestartUnlocker[] = {'r','e','s','t','a','r','t','M','e','s','s','a','g','e','U','n','l','o','c','k','e','r','\0'}; // "restartMessageUnlocker"
- #else
- static const PRUnichar kRestartNoUnlocker[] = {'r','e','s','t','a','r','t','M','e','s','s','a','g','e','N','o','U','n','l','o','c','k','e','r','M','a','c','\0'}; // "restartMessageNoUnlockerMac"
- static const PRUnichar kRestartUnlocker[] = {'r','e','s','t','a','r','t','M','e','s','s','a','g','e','U','n','l','o','c','k','e','r','M','a','c','\0'}; // "restartMessageUnlockerMac"
- #endif
- sb->FormatStringFromName(aUnlocker ? kRestartUnlocker : kRestartNoUnlocker,
- params, 2, getter_Copies(killMessage));
- nsXPIDLString killTitle;
- sb->FormatStringFromName(NS_LITERAL_STRING("restartTitle").get(),
- params, 1, getter_Copies(killTitle));
- if (!killMessage || !killTitle)
- return NS_ERROR_FAILURE;
- nsCOMPtr<nsIPromptService> ps
- (do_GetService(NS_PROMPTSERVICE_CONTRACTID));
- NS_ENSURE_TRUE(ps, NS_ERROR_FAILURE);
- if (aUnlocker) {
- const PRUint32 flags =
- (nsIPromptService::BUTTON_TITLE_CANCEL *
- nsIPromptService::BUTTON_POS_0) +
- (nsIPromptService::BUTTON_TITLE_IS_STRING *
- nsIPromptService::BUTTON_POS_1) +
- nsIPromptService::BUTTON_POS_1_DEFAULT;
- PRInt32 button;
- // The actual value is irrelevant but we shouldn't be handing out
- // malformed JSBools to XPConnect.
- bool checkState = false;
- rv = ps->ConfirmEx(nsnull, killTitle, killMessage, flags,
- killTitle, nsnull, nsnull, nsnull,
- &checkState, &button);
- NS_ENSURE_SUCCESS_LOG(rv, rv);
- if (button == 1) {
- rv = aUnlocker->Unlock(nsIProfileUnlocker::FORCE_QUIT);
- if (NS_FAILED(rv))
- return rv;
- return NS_LockProfilePath(aProfileDir, aProfileLocalDir,
- nsnull, aResult);
- }
- } else {
- rv = ps->Alert(nsnull, killTitle, killMessage);
- NS_ENSURE_SUCCESS_LOG(rv, rv);
- }
- return NS_ERROR_ABORT;
- }
- }
- static nsresult
- ProfileMissingDialog(nsINativeAppSupport* aNative)
- {
- nsresult rv;
- ScopedXPCOMStartup xpcom;
- rv = xpcom.Initialize();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = xpcom.SetWindowCreator(aNative);
- NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
- { //extra scoping is needed so we release these components before xpcom shutdown
- nsCOMPtr<nsIStringBundleService> sbs =
- mozilla::services::GetStringBundleService();
- NS_ENSURE_TRUE(sbs, NS_ERROR_FAILURE);
-
- nsCOMPtr<nsIStringBundle> sb;
- sbs->CreateBundle(kProfileProperties, getter_AddRefs(sb));
- NS_ENSURE_TRUE_LOG(sbs, NS_ERROR_FAILURE);
-
- NS_ConvertUTF8toUTF16 appName(gAppData->name);
- const PRUnichar* params[] = {appName.get(), appName.get()};
-
- nsXPIDLString missingMessage;
-
- // profileMissing
- static const PRUnichar kMissing[] = {'p','r','o','f','i','l','e','M','i','s','s','i','n','g','\0'};
- sb->FormatStringFromName(kMissing, params, 2, getter_Copies(missingMessage));
-
- nsXPIDLString missingTitle;
- sb->FormatStringFromName(NS_LITERAL_STRING("profileMissingTitle").get(),
- params, 1, getter_Copies(missingTitle));
-
- if (missingMessage && missingTitle) {
- nsCOMPtr<nsIPromptService> ps
- (do_GetService(NS_PROMPTSERVICE_CONTRACTID));
- NS_ENSURE_TRUE(ps, NS_ERROR_FAILURE);
-
- ps->Alert(nsnull, missingTitle, missingMessage);
- }
- return NS_ERROR_ABORT;
- }
- }
- static const char kProfileManagerURL[] =
- "chrome://mozapps/content/profile/profileSelection.xul";
- static nsresult
- ShowProfileManager(nsIToolkitProfileService* aProfileSvc,
- nsINativeAppSupport* aNative)
- {
- nsresult rv;
- nsCOMPtr<nsILocalFile> profD, profLD;
- PRUnichar* profileNamePtr;
- nsCAutoString profileName;
- {
- ScopedXPCOMStartup xpcom;
- rv = xpcom.Initialize();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = xpcom.SetWindowCreator(aNative);
- NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
- #ifdef XP_MACOSX
- CommandLineServiceMac::SetupMacCommandLine(gRestartArgc, gRestartArgv, true);
- #endif
- #ifdef XP_WIN
- // we don't have to wait here because profile manager window will pump
- // and DDE message will be handled
- ProcessDDE(aNative, false);
- #endif
- { //extra scoping is needed so we release these components before xpcom shutdown
- nsCOMPtr<nsIWindowWatcher> windowWatcher
- (do_GetService(NS_WINDOWWATCHER_CONTRACTID));
- nsCOMPtr<nsIDialogParamBlock> ioParamBlock
- (do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID));
- nsCOMPtr<nsIMutableArray> dlgArray (do_CreateInstance(NS_ARRAY_CONTRACTID));
- NS_ENSURE_TRUE(windowWatcher && ioParamBlock && dlgArray, NS_ERROR_FAILURE);
- ioParamBlock->SetObjects(dlgArray);
- nsCOMPtr<nsIAppStartup> appStartup
- (do_GetService(NS_APPSTARTUP_CONTRACTID));
- NS_ENSURE_TRUE(appStartup, NS_ERROR_FAILURE);
- nsCOMPtr<nsIDOMWindow> newWindow;
- rv = windowWatcher->OpenWindow(nsnull,
- kProfileManagerURL,
- "_blank",
- "centerscreen,chrome,modal,titlebar",
- ioParamBlock,
- getter_AddRefs(newWindow));…