PRBool noRestart = PR_FALSE;
int xre_main(int argc, char* argv[], const nsXREAppData* aAppData){  nsresult rv;  NS_TIMELINE_MARK("enter main");#if defined(DEBUG) && defined(XP_WIN32)  // Disable small heap allocator to get heapwalk() giving us  // accurate heap numbers. Win2k non-debug does not use small heap allocator.  // Win2k debug seems to be still using it.  // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt__set_sbh_threshold.asp  _set_sbh_threshold(0);#endif#if defined(XP_UNIX) || defined(XP_BEOS)  InstallUnixSignalHandlers(argv[0]);#endif  // Unbuffer stdout, needed for tinderbox tests.  setbuf(stdout, 0);#if defined(FREEBSD)  // Disable all SIGFPE's on FreeBSD, as it has non-IEEE-conformant fp  // trap behavior that trips up on floating-point tests performed by  // the JS engine.  See bugzilla bug 9967 details.  fpsetmask(0);#endif#if defined(XP_UNIX) && !defined(XP_MACOSX)  if (!GetBinaryPath(argv[0]))    return 1;#endif  gArgc = argc;  gArgv = argv;  NS_ASSERTION(aAppData, "must specify XUL app data");  gAppData = aAppData;  gRestartArgc = argc;  gRestartArgv = (char**) malloc(sizeof(char*) * (argc + 1));  if (!gRestartArgv) return 1;  int i;  for (i = 0; i < argc; ++i) {    gRestartArgv[i] = argv[i];  }  gRestartArgv[argc] = nsnull;#if defined(XP_OS2)  PRBool StartOS2App(int aArgc, char **aArgv);  if (!StartOS2App(gArgc, gArgv))    return 1;  ScopedFPHandler handler();#endif /* XP_OS2 */#if defined(XP_BEOS)  if (NS_OK != InitializeBeOSApp())    return 1;#endif#ifdef _BUILD_STATIC_BIN  // Initialize XPCOM's module info table  NSGetStaticModuleInfo = app_getModuleInfo;#endif  // Handle -help and -version command line arguments.  // They should return quickly, so we deal with them here.  if (CheckArg("h") || CheckArg("help") || CheckArg("?")) {    DumpHelp();    return 0;  }  if (CheckArg("v") || CheckArg("version")) {    DumpVersion();    return 0;  }    #ifdef NS_TRACE_MALLOC  gArgc = argc = NS_TraceMallocStartupArgs(argc, argv);#endif  nsXREDirProvider dirProvider;  {    nsCOMPtr<nsIFile> xulAppDir;    const char *appDataFile;    if (CheckArg("app", &appDataFile) == ARG_FOUND) {      nsCOMPtr<nsILocalFile> lf;      NS_GetFileFromPath(appDataFile, getter_AddRefs(lf));      lf->GetParent(getter_AddRefs(xulAppDir));    }    rv = dirProvider.Initialize(xulAppDir);    if (NS_FAILED(rv))      return 1;  }  // Check for -register, which registers chrome and then exits immediately.  if (CheckArg("register")) {    ScopedXPCOMStartup xpcom;    rv = xpcom.Initialize();    NS_ENSURE_SUCCESS(rv, 1);    {      nsCOMPtr<nsIChromeRegistry> chromeReg        (do_GetService("@mozilla.org/chrome/chrome-registry;1"));      NS_ENSURE_TRUE(chromeReg, 1);      chromeReg->CheckForNewChrome();      if (gAppData->flags & NS_XRE_ENABLE_EXTENSION_MANAGER) {        nsCOMPtr<nsIExtensionManager> em          (do_GetService("@mozilla.org/extensions/manager;1"));        NS_ENSURE_TRUE(em, 1);        em->Register();      }    }    return 0;  }#if defined(MOZ_WIDGET_GTK) || defined(MOZ_WIDGET_GTK2)  // setup for private colormap.  Ideally we'd like to do this  // in nsAppShell::Create, but we need to get in before gtk  // has been initialized to make sure everything is running  // consistently.  if (CheckArg("install"))    gdk_rgb_set_install(TRUE);  // Initialize GTK+1/2 here for splash#if defined(MOZ_WIDGET_GTK)  gtk_set_locale();#endif  gtk_init(&gArgc, &gArgv);  gtk_widget_set_default_visual(gdk_rgb_get_visual());  gtk_widget_set_default_colormap(gdk_rgb_get_cmap());#endif /* MOZ_WIDGET_GTK || MOZ_WIDGET_GTK2 */#if defined(MOZ_WIDGET_QT)  QApplication qapp(argc, argv);#endif// #if defined(MOZ_WIDGET_XLIB)// XXXtimeless fix me! How do we get a Display from here to nsAppShell.cpp ?// #endif      // Call the code to install our handler#ifdef MOZ_JPROF  setupProfilingStuff();#endif  // Try to allocate "native app support."  nsCOMPtr<nsINativeAppSupport> nativeApp;  rv = NS_CreateNativeAppSupport(getter_AddRefs(nativeApp));  if (NS_FAILED(rv))    return 1;  PRBool canRun = PR_FALSE;  rv = nativeApp->Start(&canRun);  if (NS_FAILED(rv) || !canRun) {    return 1;  }  //----------------------------------------------------------------  // We need to check if a previous installation occured and  // if so, make sure it finished and cleaned up correctly.  //  // If there is an xpicleanup.dat file left around, that means the  // previous installation did not finish correctly. We must cleanup  // before a valid mozilla can run.  //  // Show the user a platform-specific Alert message, then spawn the  // xpicleanup utility, then exit.  //----------------------------------------------------------------  nsCOMPtr<nsIFile> registryFile;  rv = dirProvider.GetAppDir()->Clone(getter_AddRefs(registryFile));  if (NS_SUCCEEDED(rv)) {    registryFile->AppendNative(CLEANUP_REGISTRY);    PRBool exists;    rv = registryFile->Exists(&exists);    if (NS_SUCCEEDED(rv) && exists) {      return VerifyInstallation(dirProvider.GetAppDir());    }  }#ifdef MOZ_ENABLE_XREMOTE  // handle -remote now that xpcom is fired up  const char* xremotearg;  ArgResult ar = CheckArg("remote", &xremotearg);  if (ar == ARG_BAD) {    PR_fprintf(PR_STDERR, "Error: -remote requires an argument\n");    return 1;  }  if (ar) {    return HandleRemoteArgument(xremotearg);  }#endif  nsCOMPtr<nsIProfileLock> profileLock;  PRBool startOffline = PR_FALSE;  rv = SelectProfile(getter_AddRefs(profileLock), nativeApp, &startOffline);  if (rv == NS_ERROR_LAUNCHED_CHILD_PROCESS ||      rv == NS_ERROR_ABORT) return 0;  if (NS_FAILED(rv)) return 1;  nsCOMPtr<nsILocalFile> lf;  rv = profileLock->GetDirectory(getter_AddRefs(lf));  NS_ENSURE_SUCCESS(rv, 1);  rv = dirProvider.SetProfileDir(lf);  NS_ENSURE_SUCCESS(rv, 1);  //////////////////////// NOW WE HAVE A PROFILE ////////////////////////  PRBool upgraded = PR_FALSE;  PRBool componentsListChanged = PR_FALSE;  // Check for version compatibility with the last version of the app this   // profile was started with.  The format of the version stamp is defined  // by the BuildVersion function.  char lastVersion[MAXPATHLEN];  GetVersion(lf, lastVersion, MAXPATHLEN);  // Build the version stamp for the running application.  nsCAutoString version;  BuildVersion(version);  // Every time a profile is loaded by a build with a different version,  // it updates the compatibility.ini file saying what version last wrote  // the compreg.dat.  On subsequent launches if the version matches,   // there is no need for re-registration.  If the user loads the same  // profile in different builds the component registry must be  // re-generated to prevent mysterious component loading failures.  //   if (version.Equals(lastVersion)) {    componentsListChanged = ComponentsListChanged(lf);    if (componentsListChanged) {      // Remove compreg.dat and xpti.dat, forcing component re-registration,      // with the new list of additional components directories specified      // in "components.ini" which we have just discovered changed since the      // last time the application was run.       RemoveComponentRegistries(lf);    }    // Nothing need be done for the normal startup case.  }  else {    // Remove compreg.dat and xpti.dat, forcing component re-registration    // with the default set of components (this disables any potentially    // troublesome incompatible XPCOM components).     RemoveComponentRegistries(lf);    // Tell the Extension Manager it should check for incompatible     // Extensions and re-write the Components manifest ("components.ini")    // with a list of XPCOM components for compatible extensions    upgraded = PR_TRUE;    // Write out version    WriteVersion(lf, version);  }  PRBool needsRestart = PR_FALSE;  // Allows the user to forcefully bypass the restart process at their  // own risk. Useful for debugging or for tinderboxes where child   // processes can be problematic.  PRBool noRestart = PR_FALSE;  {    // Start the real application    ScopedXPCOMStartup xpcom;    rv = xpcom.Initialize();    NS_ENSURE_SUCCESS(rv, 1);     rv = xpcom.DoAutoreg();    rv |= xpcom.InitEventQueue();    rv |= xpcom.SetWindowCreator(nativeApp);    NS_ENSURE_SUCCESS(rv, 1);    {      if (startOffline) {        nsCOMPtr<nsIIOService> io (do_GetService("@mozilla.org/network/io-service;1"));        NS_ENSURE_TRUE(io, 1);        io->SetOffline(PR_TRUE);      }      {        NS_TIMELINE_ENTER("startupNotifier");        nsCOMPtr<nsIObserver> startupNotifier          (do_CreateInstance(NS_APPSTARTUPNOTIFIER_CONTRACTID, &rv));        NS_ENSURE_SUCCESS(rv, 1);        startupNotifier->Observe(nsnull, APPSTARTUP_TOPIC, nsnull);        NS_TIMELINE_LEAVE("startupNotifier");      }      nsCOMPtr<nsIAppStartup> appStartup        (do_GetService(NS_APPSTARTUP_CONTRACTID));      NS_ENSURE_TRUE(appStartup, 1);      // So we can open and close windows during startup      appStartup->EnterLastWindowClosingSurvivalArea();      // Profile Migration      if (gAppData->flags & NS_XRE_ENABLE_PROFILE_MIGRATOR && gDoMigration) {        gDoMigration = PR_FALSE;        nsCOMPtr<nsIProfileMigrator> pm          (do_CreateInstance(NS_PROFILEMIGRATOR_CONTRACTID));        if (pm)          pm->Migrate(&dirProvider);      }      dirProvider.DoStartup();      nsCOMPtr<nsICommandLineRunner> cmdLine        (do_CreateInstance("@mozilla.org/toolkit/command-line;1"));      NS_ENSURE_TRUE(cmdLine, 1);      nsCOMPtr<nsIFile> workingDir;      rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));      NS_ENSURE_SUCCESS(rv, 1);      rv = cmdLine->Init(gArgc, gArgv,                         workingDir, nsICommandLine::STATE_INITIAL_LAUNCH);      NS_ENSURE_SUCCESS(rv, 1);      /* Special-case services that need early access to the command         line. */      nsCOMPtr<nsIObserver> chromeObserver        (do_GetService("@mozilla.org/chrome/chrome-registry;1"));      if (chromeObserver) {        chromeObserver->Observe(cmdLine, "command-line-startup", nsnull);      }      NS_TIMELINE_ENTER("appStartup->CreateHiddenWindow");      rv = appStartup->CreateHiddenWindow();      NS_TIMELINE_LEAVE("appStartup->CreateHiddenWindow");      NS_ENSURE_SUCCESS(rv, 1);      // Extension Compatibility Checking and Startup      if (gAppData->flags & NS_XRE_ENABLE_EXTENSION_MANAGER) {        nsCOMPtr<nsIExtensionManager> em(do_GetService("@mozilla.org/extensions/manager;1"));        NS_ENSURE_TRUE(em, 1);        if (CheckArg("install-global-extension") ||             CheckArg("install-global-theme") || CheckArg("list-global-items") ||             CheckArg("lock-item") || CheckArg("unlock-item")) {          // Do the required processing and then shut down.          em->HandleCommandLineArgs(cmdLine);          return 0;        }        char* noEMRestart = PR_GetEnv("NO_EM_RESTART");        noRestart = noEMRestart && !strcmp("1", noEMRestart);        if (!noRestart && upgraded) {          rv = em->CheckForMismatches(&needsRestart);          NS_ASSERTION(NS_SUCCEEDED(rv), "Oops, looks like you have a extensions.rdf file generated by a buggy nightly build. Please remove it!");          if (NS_FAILED(rv)) {            needsRestart = PR_FALSE;            upgraded = PR_FALSE;          }        }        if (noRestart || (!upgraded || !needsRestart))          em->Start(cmdLine, componentsListChanged, &needsRestart);      }      if (noRestart || (!upgraded && !needsRestart)) {        // clear out any environment variables which may have been set         // during the relaunch process now that we know we won't be relaunching.        PR_SetEnv("XRE_PROFILE_PATH=");        PR_SetEnv("XRE_START_OFFLINE=");        PR_SetEnv("XRE_IMPORT_PROFILES=");        #ifdef XP_MACOSX        // we re-initialize the command-line service and do appleevents munging        // after we are sure that we're not restarting        cmdLine = do_CreateInstance("@mozilla.org/toolkit/command-line;1");        NS_ENSURE_TRUE(cmdLine, 1);        rv = InitializeMacCommandLine(gArgc, gArgv);        NS_ENSURE_SUCCESS(rv, 1);        rv = cmdLine->Init(gArgc, gArgv,                           workingDir, nsICommandLine::STATE_INITIAL_LAUNCH);        NS_ENSURE_SUCCESS(rv, 1);        // Kick off the prebinding update now that we know we won't be        // relaunching.        UpdatePrebinding();#endif        rv = cmdLine->Run();        NS_ENSURE_SUCCESS(rv, 1);        nsCOMPtr<nsIWindowMediator> windowMediator          (do_GetService(NS_WINDOWMEDIATOR_CONTRACTID, &rv));        NS_ENSURE_SUCCESS(rv, 1);        // Make sure there exists at least 1 window.        nsCOMPtr<nsISimpleEnumerator> windowEnumerator;        rv = windowMediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));        NS_ENSURE_SUCCESS(rv, 1);        PRBool more;        windowEnumerator->HasMoreElements(&more);        if (more) {#ifndef XP_MACOSX          appStartup->ExitLastWindowClosingSurvivalArea();#endif#ifdef MOZ_ENABLE_XREMOTE          // if we have X remote support and we have our one window up and          // running start listening for requests on the proxy window.          nsCOMPtr<nsIXRemoteService> remoteService;          remoteService = do_GetService(NS_IXREMOTESERVICE_CONTRACTID);          if (remoteService)            remoteService->Startup(aAppData->appName);#endif /* MOZ_ENABLE_XREMOTE */          // enable win32 DDE responses and Mac appleevents responses          nativeApp->Enable();          // Start main event loop          NS_TIMELINE_ENTER("appStartup->Run");          rv = appStartup->Run();          NS_TIMELINE_LEAVE("appStartup->Run");          NS_ASSERTION(NS_SUCCEEDED(rv), "failed to run appstartup");#ifdef MOZ_ENABLE_XREMOTE          // shut down the x remote proxy window          if (remoteService)            remoteService->Shutdown();#endif /* MOZ_ENABLE_XREMOTE */        }#ifdef MOZ_TIMELINE        // Make sure we print this out even if timeline is runtime disabled        if (NS_FAILED(NS_TIMELINE_LEAVE("main1")))          NS_TimelineForceMark("...main1");#endif      }      else {        // Upgrade condition (build id changes), but the restart hint was         // not set by the Extension Manager. This is because the compatibility        // resolution for Extensions is different than for the component         // registry - major milestone vs. build id.         needsRestart = PR_TRUE;      }    }    profileLock->Unlock();  }  // Restart the app after XPCOM has been shut down cleanly.   if (!noRestart && needsRestart) {    nsCAutoString path;    lf->GetNativePath(path);    static char kEnvVar[MAXPATHLEN];    sprintf(kEnvVar, "XRE_PROFILE_PATH=%s", path.get());    PR_SetEnv(kEnvVar);    return LaunchChild(nativeApp) == NS_ERROR_LAUNCHED_CHILD_PROCESS ? 0 : 1;  }  return NS_FAILED(rv) ? 1 : 0;}