コード例 #1
0
int main(int argc, char* argv[])
{
  ScopedLogging log;

  nsCOMPtr<nsILocalFile> appini;
  nsresult rv = XRE_GetBinaryPath(argv[0], getter_AddRefs(appini));
  if (NS_FAILED(rv)) {
    Output("Couldn't calculate the application directory.");
    return 255;
  }
  appini->SetNativeLeafName(NS_LITERAL_CSTRING("application.ini"));

  // Allow firefox.exe to launch XULRunner apps via -app <application.ini>
  // Note that -app must be the *first* argument.
  char *appEnv = nsnull;
  const char *appDataFile = PR_GetEnv("XUL_APP_FILE");
  if (appDataFile && *appDataFile) {
    rv = XRE_GetFileFromPath(appDataFile, getter_AddRefs(appini));
    if (NS_FAILED(rv)) {
      Output("Invalid path found: '%s'", appDataFile);
      return 255;
    }
  }
  else if (argc > 1 && IsArg(argv[1], "app")) {
    if (argc == 2) {
      Output("Incorrect number of arguments passed to -app");
      return 255;
    }

    rv = XRE_GetFileFromPath(argv[2], getter_AddRefs(appini));
    if (NS_FAILED(rv)) {
      Output("application.ini path not recognized: '%s'", argv[2]);
      return 255;
    }

    appEnv = PR_smprintf("XUL_APP_FILE=%s", argv[2]);
    PR_SetEnv(appEnv);
    argv[2] = argv[0];
    argv += 2;
    argc -= 2;
  }

  nsXREAppData *appData;
  rv = XRE_CreateAppData(appini, &appData);
  if (NS_FAILED(rv)) {
    Output("Couldn't read application.ini");
    return 255;
  }

  int result = XRE_main(argc, argv, appData);
  XRE_FreeAppData(appData);
  if (appEnv)
    PR_smprintf_free(appEnv);
  return result;
}
コード例 #2
0
NS_IMETHODIMP
nsApplicationAccessibleWrap::Init()
{
    // XXX following code is copied from widget/src/gtk2/nsWindow.cpp
    // we should put it to somewhere that can be used from both modules
    // see bug 390761

    // check if accessibility enabled/disabled by environment variable
    PRBool isGnomeATEnabled = PR_FALSE;
    const char *envValue = PR_GetEnv(sAccEnv);
    if (envValue) {
        isGnomeATEnabled = !!atoi(envValue);
    } else {
        //check gconf-2 setting
        nsresult rv;
        nsCOMPtr<nsIPrefBranch> sysPrefService =
            do_GetService(sSysPrefService, &rv);
        if (NS_SUCCEEDED(rv) && sysPrefService) {
            sysPrefService->GetBoolPref(sAccessibilityKey, &isGnomeATEnabled);
        }
    }

    if (isGnomeATEnabled) {
        // load and initialize gail library
        nsresult rv = LoadGtkModule(sGail);
        if (NS_SUCCEEDED(rv)) {
            (*sGail.init)();
        }
        else {
            MAI_LOG_DEBUG(("Fail to load lib: %s\n", sGail.libName));
        }

        MAI_LOG_DEBUG(("Mozilla Atk Implementation initializing\n"));
        // Initialize the MAI Utility class
        // it will overwrite gail_util
        g_type_class_unref(g_type_class_ref(MAI_TYPE_UTIL));

        // Init atk-bridge now
        PR_SetEnv("NO_AT_BRIDGE=0");

        // load and initialize atk-bridge library
        rv = LoadGtkModule(sAtkBridge);
        if (NS_SUCCEEDED(rv)) {
            // init atk-bridge
            (*sAtkBridge.init)();
        }
        else
            MAI_LOG_DEBUG(("Fail to load lib: %s\n", sAtkBridge.libName));
    }

    return nsApplicationAccessible::Init();
}
コード例 #3
0
ファイル: nsPrintJobPS.cpp プロジェクト: rn10950/RetroZilla
/**
 * Clear the printer environment variable and release the environment lock.
 */
static void
EnvClear()
{
    if (EnvPrinterString) {
        /* On some systems, setenv("FOO") will remove FOO
         * from the environment.
         */
        PR_SetEnv(EnvPrinterName);
        if (!PR_GetEnv(EnvPrinterName)) {
            /* It must have worked */
            PR_smprintf_free(EnvPrinterString);
            EnvPrinterString = nsnull;
        }
    }
    PR_Unlock(EnvLockObj);
}
コード例 #4
0
bool
EmbedLiteAppThreadParent::RecvInitialized()
{
  LOGT();
  PR_SetEnv("MOZ_USE_OMTC=1");
  mozilla::layers::CompositorParent::StartUpWithExistingThread(MessageLoop::current(), PlatformThread::CurrentId());
  mApp->GetListener()->Initialized();
  bool accel = mApp->IsAccelerated();
  SetBoolPref("layers.acceleration.disabled", !accel);
  SetBoolPref("layers.acceleration.force-enabled", accel);
  SetBoolPref("layers.async-video.enabled", accel && getenv("DISABLE_ASYNC_VIDEO") == 0);
  SetBoolPref("gfx.use_tiled_thebes", accel && getenv("DISABLE_TILED") == 0);
  SetBoolPref("egl.use_backing_surface", accel && getenv("DISABLE_BACKING") == 0);
  SetBoolPref("layers.reuse-invalid-tiles", getenv("DISABLE_REUSE_TILES") != 0);
  return true;
}
コード例 #5
0
ファイル: nsPrintJobPS.cpp プロジェクト: rn10950/RetroZilla
/**
 * Set MOZ_PRINTER_NAME to the specified string.
 * @param aPrinter The value for MOZ_PRINTER_NAME. May be an empty string.
 * @return PR_SUCCESS on success.
 *         PR_FAILURE if memory could not be allocated.
 */
static PRStatus
EnvSetPrinter(nsCString& aPrinter)
{
    /* Construct the new environment string */
    char *newVar = PR_smprintf("%s=%s", EnvPrinterName, aPrinter.get());
    if (!newVar)
        return PR_FAILURE;

    /* Add it to the environment and dispose of any old string */
    PR_SetEnv(newVar);
    if (EnvPrinterString)
        PR_smprintf_free(EnvPrinterString);
    EnvPrinterString = newVar;

    return PR_SUCCESS;
}
コード例 #6
0
nsresult
SetRestartArgs(int argc, char** argv)
{
  if (!gExceptionHandler)
    return NS_OK;

  int i;
  nsCAutoString envVar;
  char *env;
  for (i = 0; i < argc; i++) {
    envVar = "MOZ_CRASHREPORTER_RESTART_ARG_";
    envVar.AppendInt(i);
    envVar += "=";
#if defined(XP_UNIX) && !defined(XP_MACOSX)
    // we'd like to run the script around the binary
    // instead of the binary itself, so remove the -bin
    // if it exists on the first argument
    int arg_len = 0;
    if (i == 0 &&
        (arg_len = strlen(argv[i])) > 4 &&
        strcmp(argv[i] + arg_len - 4, "-bin") == 0) {
      envVar.Append(argv[i], arg_len - 4);
    } else
#endif
    {
      envVar += argv[i];
    }

    // PR_SetEnv() wants the string to be available for the lifetime
    // of the app, so dup it here
    env = ToNewCString(envVar);
    if (!env)
      return NS_ERROR_OUT_OF_MEMORY;

    PR_SetEnv(env);
  }

  // make sure the arg list is terminated
  envVar = "MOZ_CRASHREPORTER_RESTART_ARG_";
  envVar.AppendInt(i);
  envVar += "=";

  // PR_SetEnv() wants the string to be available for the lifetime
  // of the app, so dup it here
  env = ToNewCString(envVar);
  if (!env)
    return NS_ERROR_OUT_OF_MEMORY;

  PR_SetEnv(env);

  // make sure we save the info in XUL_APP_FILE for the reporter
  const char *appfile = PR_GetEnv("XUL_APP_FILE");
  if (appfile && *appfile) {
    envVar = "MOZ_CRASHREPORTER_RESTART_XUL_APP_FILE=";
    envVar += appfile;
    env = ToNewCString(envVar);
    PR_SetEnv(env);
  }

  return NS_OK;
}
コード例 #7
0
ファイル: prenv.c プロジェクト: AbrahamJewowich/FreeSWITCH
PR_IMPLEMENT(PRIntn) PR_PutEnv(const char *string)
{
    return (PR_SetEnv(string) == PR_SUCCESS) ? PR_TRUE : PR_FALSE;
}
コード例 #8
0
bool
GLXLibrary::EnsureInitialized(LibType libType)
{
    if (mInitialized) {
        return true;
    }

    // Don't repeatedly try to initialize.
    if (mTriedInitializing) {
        return false;
    }
    mTriedInitializing = true;

    // Force enabling s3 texture compression. (Bug 774134)
    PR_SetEnv("force_s3tc_enable=true");

    if (!mOGLLibrary) {
        const char* libGLfilename = nullptr;
        bool forceFeatureReport = false;
        switch (libType) {
        case MESA_LLVMPIPE_LIB:
            libGLfilename = "mesallvmpipe.so";
            forceFeatureReport = true;
            break;
        case OPENGL_LIB:
            // see e.g. bug 608526: it is intrinsically interesting to know whether we have dynamically linked to libGL.so.1
            // because at least the NVIDIA implementation requires an executable stack, which causes mprotect calls,
            // which trigger glibc bug http://sourceware.org/bugzilla/show_bug.cgi?id=12225
#ifdef __OpenBSD__
            libGLfilename = "libGL.so";
#else
            libGLfilename = "libGL.so.1";
#endif
            break;
        default:
            MOZ_CRASH("Invalid GLX library type.");
        }

        ScopedGfxFeatureReporter reporter(libGLfilename, forceFeatureReport);
        mOGLLibrary = PR_LoadLibrary(libGLfilename);
        if (!mOGLLibrary) {
            NS_WARNING("Couldn't load OpenGL shared library.");
            return false;
        }
        reporter.SetSuccessful();
    }

    if (PR_GetEnv("MOZ_GLX_DEBUG")) {
        mDebug = true;
    }

    GLLibraryLoader::SymLoadStruct symbols[] = {
        /* functions that were in GLX 1.0 */
        { (PRFuncPtr*) &xDestroyContextInternal, { "glXDestroyContext", nullptr } },
        { (PRFuncPtr*) &xMakeCurrentInternal, { "glXMakeCurrent", nullptr } },
        { (PRFuncPtr*) &xSwapBuffersInternal, { "glXSwapBuffers", nullptr } },
        { (PRFuncPtr*) &xQueryVersionInternal, { "glXQueryVersion", nullptr } },
        { (PRFuncPtr*) &xGetCurrentContextInternal, { "glXGetCurrentContext", nullptr } },
        { (PRFuncPtr*) &xWaitGLInternal, { "glXWaitGL", nullptr } },
        { (PRFuncPtr*) &xWaitXInternal, { "glXWaitX", nullptr } },
        /* functions introduced in GLX 1.1 */
        { (PRFuncPtr*) &xQueryExtensionsStringInternal, { "glXQueryExtensionsString", nullptr } },
        { (PRFuncPtr*) &xGetClientStringInternal, { "glXGetClientString", nullptr } },
        { (PRFuncPtr*) &xQueryServerStringInternal, { "glXQueryServerString", nullptr } },
        { nullptr, { nullptr } }
    };

    GLLibraryLoader::SymLoadStruct symbols13[] = {
        /* functions introduced in GLX 1.3 */
        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfig", nullptr } },
        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttrib", nullptr } },
        // WARNING: xGetFBConfigs not set in symbols13_ext
        { (PRFuncPtr*) &xGetFBConfigsInternal, { "glXGetFBConfigs", nullptr } },
        // WARNING: symbols13_ext sets xCreateGLXPixmapWithConfig instead
        { (PRFuncPtr*) &xCreatePixmapInternal, { "glXCreatePixmap", nullptr } },
        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyPixmap", nullptr } },
        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateNewContext", nullptr } },
        { nullptr, { nullptr } }
    };

    GLLibraryLoader::SymLoadStruct symbols13_ext[] = {
        /* extension equivalents for functions introduced in GLX 1.3 */
        // GLX_SGIX_fbconfig extension
        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfigSGIX", nullptr } },
        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttribSGIX", nullptr } },
        // WARNING: no xGetFBConfigs equivalent in extensions
        // WARNING: different from symbols13:
        { (PRFuncPtr*) &xCreateGLXPixmapWithConfigInternal, { "glXCreateGLXPixmapWithConfigSGIX", nullptr } },
        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyGLXPixmap", nullptr } }, // not from ext
        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateContextWithConfigSGIX", nullptr } },
        { nullptr, { nullptr } }
    };

    GLLibraryLoader::SymLoadStruct symbols14[] = {
        /* functions introduced in GLX 1.4 */
        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddress", nullptr } },
        { nullptr, { nullptr } }
    };

    GLLibraryLoader::SymLoadStruct symbols14_ext[] = {
        /* extension equivalents for functions introduced in GLX 1.4 */
        // GLX_ARB_get_proc_address extension
        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddressARB", nullptr } },
        { nullptr, { nullptr } }
    };

    GLLibraryLoader::SymLoadStruct symbols_texturefrompixmap[] = {
        { (PRFuncPtr*) &xBindTexImageInternal, { "glXBindTexImageEXT", nullptr } },
        { (PRFuncPtr*) &xReleaseTexImageInternal, { "glXReleaseTexImageEXT", nullptr } },
        { nullptr, { nullptr } }
    };

    GLLibraryLoader::SymLoadStruct symbols_robustness[] = {
        { (PRFuncPtr*) &xCreateContextAttribsInternal, { "glXCreateContextAttribsARB", nullptr } },
        { nullptr, { nullptr } }
    };

    if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, &symbols[0])) {
        NS_WARNING("Couldn't find required entry point in OpenGL shared library");
        return false;
    }

    Display *display = DefaultXDisplay();
    int screen = DefaultScreen(display);

    if (!xQueryVersion(display, &mGLXMajorVersion, &mGLXMinorVersion)) {
        mGLXMajorVersion = 0;
        mGLXMinorVersion = 0;
        return false;
    }

    if (!GLXVersionCheck(1, 1))
        // Not possible to query for extensions.
        return false;

    const char *clientVendor = xGetClientString(display, LOCAL_GLX_VENDOR);
    const char *serverVendor = xQueryServerString(display, screen, LOCAL_GLX_VENDOR);
    const char *extensionsStr = xQueryExtensionsString(display, screen);

    GLLibraryLoader::SymLoadStruct *sym13;
    if (!GLXVersionCheck(1, 3)) {
        // Even if we don't have 1.3, we might have equivalent extensions
        // (as on the Intel X server).
        if (!HasExtension(extensionsStr, "GLX_SGIX_fbconfig")) {
            return false;
        }
        sym13 = symbols13_ext;
    } else {
        sym13 = symbols13;
    }
    if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, sym13)) {
        NS_WARNING("Couldn't find required entry point in OpenGL shared library");
        return false;
    }

    GLLibraryLoader::SymLoadStruct *sym14;
    if (!GLXVersionCheck(1, 4)) {
        // Even if we don't have 1.4, we might have equivalent extensions
        // (as on the Intel X server).
        if (!HasExtension(extensionsStr, "GLX_ARB_get_proc_address")) {
            return false;
        }
        sym14 = symbols14_ext;
    } else {
        sym14 = symbols14;
    }
    if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, sym14)) {
        NS_WARNING("Couldn't find required entry point in OpenGL shared library");
        return false;
    }

    if (HasExtension(extensionsStr, "GLX_EXT_texture_from_pixmap") &&
        GLLibraryLoader::LoadSymbols(mOGLLibrary, symbols_texturefrompixmap, 
                                         (GLLibraryLoader::PlatformLookupFunction)&xGetProcAddress))
    {
#ifdef MOZ_WIDGET_GTK
        mUseTextureFromPixmap = gfxPlatformGtk::GetPlatform()->UseXRender();
#else
        mUseTextureFromPixmap = true;
#endif
    } else {
        mUseTextureFromPixmap = false;
        NS_WARNING("Texture from pixmap disabled");
    }

    if (HasExtension(extensionsStr, "GLX_ARB_create_context_robustness") &&
        GLLibraryLoader::LoadSymbols(mOGLLibrary, symbols_robustness)) {
        mHasRobustness = true;
    }

    mIsATI = serverVendor && DoesStringMatch(serverVendor, "ATI");
    mIsNVIDIA = serverVendor && DoesStringMatch(serverVendor, "NVIDIA Corporation");
    mClientIsMesa = clientVendor && DoesStringMatch(clientVendor, "Mesa");

    mInitialized = true;
    mLibType = libType;

    return true;
}
コード例 #9
0
bool
PluginProcessChild::Init()
{
#if defined(XP_MACOSX)
    // Remove the trigger for "dyld interposing" that we added in
    // GeckoChildProcessHost::PerformAsyncLaunchInternal(), in the host
    // process just before we were launched.  Dyld interposing will still
    // happen in our process (the plugin child process).  But we don't want
    // it to happen in any processes that the plugin might launch from our
    // process.
    nsCString interpose(PR_GetEnv("DYLD_INSERT_LIBRARIES"));
    if (!interpose.IsEmpty()) {
        // If we added the path to libplugin_child_interpose.dylib to an
        // existing DYLD_INSERT_LIBRARIES, we appended it to the end, after a
        // ":" path seperator.
        int32_t lastSeparatorPos = interpose.RFind(":");
        int32_t lastTriggerPos = interpose.RFind("libplugin_child_interpose.dylib");
        bool needsReset = false;
        if (lastTriggerPos != -1) {
            if (lastSeparatorPos == -1) {
                interpose.Truncate();
                needsReset = true;
            } else if (lastTriggerPos > lastSeparatorPos) {
                interpose.SetLength(lastSeparatorPos);
                needsReset = true;
            }
        }
        if (needsReset) {
            nsCString setInterpose("DYLD_INSERT_LIBRARIES=");
            if (!interpose.IsEmpty()) {
                setInterpose.Append(interpose);
            }
            // Values passed to PR_SetEnv() must be seperately allocated.
            char* setInterposePtr = strdup(setInterpose.get());
            PR_SetEnv(setInterposePtr);
        }
    }
#endif

#ifdef XP_WIN
    // Drag-and-drop needs OleInitialize to be called, and Silverlight depends
    // on the host calling CoInitialize (which is called by OleInitialize).
    ::OleInitialize(nullptr);
#endif

    // Certain plugins, such as flash, steal the unhandled exception filter
    // thus we never get crash reports when they fault. This call fixes it.
    message_loop()->set_exception_restoration(true);

    std::string pluginFilename;

#if defined(OS_POSIX)
    // NB: need to be very careful in ensuring that the first arg
    // (after the binary name) here is indeed the plugin module path.
    // Keep in sync with dom/plugins/PluginModuleParent.
    std::vector<std::string> values = CommandLine::ForCurrentProcess()->argv();
    NS_ABORT_IF_FALSE(values.size() >= 2, "not enough args");

    pluginFilename = UnmungePluginDsoPath(values[1]);

#elif defined(OS_WIN)
    std::vector<std::wstring> values =
        CommandLine::ForCurrentProcess()->GetLooseValues();
    NS_ABORT_IF_FALSE(values.size() >= 1, "not enough loose args");

    if (ShouldProtectPluginCurrentDirectory(values[0].c_str())) {
        SanitizeEnvironmentVariables();
        SetDllDirectory(L"");
    }

    pluginFilename = WideToUTF8(values[0]);
#else
#  error Sorry
#endif

    if (NS_FAILED(nsRegion::InitStatic())) {
      NS_ERROR("Could not initialize nsRegion");
      return false;
    }

    return mPlugin.Init(pluginFilename, ParentHandle(),
                        IOThreadChild::message_loop(),
                        IOThreadChild::channel());
}
コード例 #10
0
int main(int argc, char* argv[])
{
  if (argc > 1 && (IsArg(argv[1], "h") ||
                   IsArg(argv[1], "help") ||
                   IsArg(argv[1], "?")))
  {
    Usage(argv[0]);
    return 0;
  }

  if (argc == 2 && (IsArg(argv[1], "v") || IsArg(argv[1], "version")))
  {
    nsCAutoString milestone;
    nsCAutoString version;
    GetGREVersion(argv[0], &milestone, &version);
    Output(PR_FALSE, "Mozilla XULRunner %s - %s\n",
           milestone.get(), version.get());
    return 0;
  }

  if (argc > 1) {
    nsCAutoString milestone;
    nsresult rv = GetGREVersion(argv[0], &milestone, nsnull);
    if (NS_FAILED(rv))
      return 2;

    if (IsArg(argv[1], "gre-version")) {
      if (argc != 2) {
        Usage(argv[0]);
        return 1;
      }

      printf("%s\n", milestone.get());
      return 0;
    }

    if (IsArg(argv[1], "install-app")) {
      if (argc < 3 || argc > 5) {
        Usage(argv[0]);
        return 1;
      }

      char *appLocation = argv[2];

      char *installTo = nsnull;
      if (argc > 3) {
        installTo = argv[3];
        if (!*installTo) // left blank?
          installTo = nsnull;
      }

      char *leafName = nsnull;
      if (argc > 4) {
        leafName = argv[4];
        if (!*leafName)
          leafName = nsnull;
      }

      nsCOMPtr<nsIFile> regDir;
      rv = GetXULRunnerDir(argv[0], getter_AddRefs(regDir));
      if (NS_FAILED(rv))
        return 2;

      return InstallXULApp(regDir, appLocation, installTo, leafName);
    }
  }

  const char *appDataFile = PR_GetEnv("XUL_APP_FILE");

  if (!(appDataFile && *appDataFile)) {
    if (argc < 2) {
      Usage(argv[0]);
      return 1;
    }

    if (IsArg(argv[1], "app")) {
      if (argc == 2) {
        Usage(argv[0]);
        return 1;
      }
      argv[1] = argv[0];
      ++argv;
      --argc;
    }

    appDataFile = argv[1];
    argv[1] = argv[0];
    ++argv;
    --argc;

    static char kAppEnv[MAXPATHLEN];
    PR_snprintf(kAppEnv, MAXPATHLEN, "XUL_APP_FILE=%s", appDataFile);
    PR_SetEnv(kAppEnv);
  }

  nsCOMPtr<nsILocalFile> appDataLF;
  nsresult rv = XRE_GetFileFromPath(appDataFile, getter_AddRefs(appDataLF));
  if (NS_FAILED(rv)) {
    Output(PR_TRUE, "Error: unrecognized application.ini path.\n");
    return 2;
  }

  AutoAppData appData(appDataLF);
  if (!appData) {
    Output(PR_TRUE, "Error: couldn't parse application.ini.\n");
    return 2;
  }

  return XRE_main(argc, argv, appData);
}
コード例 #11
0
ファイル: env.c プロジェクト: AbrahamJewowich/FreeSWITCH
PRIntn main(PRIntn argc, char *argv[])
{
    char    *value;
    PRStatus    rc;

    {   /* Get command line options */
        PLOptStatus os;
        PLOptState *opt = PL_CreateOptState(argc, argv, "vd");

	    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
        {
		    if (PL_OPT_BAD == os) continue;
            switch (opt->option)
            {
            case 'd':  /* debug */
                debug = 1;
                break;
            case 'v':  /* verbose */
                verbose = 1;
                break;
             default:
                break;
            }
        }
	    PL_DestroyOptState(opt);
    } /* end block "Get command line options" */

#if 0 
    {
        /*
        ** This uses Windows native environment manipulation
        ** as an experiment. Note the separation of namespace!
        */
        BOOL rv;
        DWORD   size;
        rv = SetEnvironmentVariable( ENVNAME, ENVVALUE );
        if ( rv == 0 )  {
            if (debug) printf("env: Shit! SetEnvironmentVariable() failed\n");
            failedAlready = PR_TRUE;
        }
        if (verbose) printf("env: SetEnvironmentVariable() worked\n");

        size = GetEnvironmentVariable( ENVNAME, envBuf, ENVBUFSIZE );    
        if ( size == 0 )  {
            if (debug) printf("env: Shit! GetEnvironmentVariable() failed. Found: %s\n", envBuf );
            failedAlready = PR_TRUE;
        }
        if (verbose) printf("env: GetEnvironmentVariable() worked. Found: %s\n", envBuf);

        value = PR_GetEnv( ENVNAME );
        if ( (NULL == value ) || (strcmp( value, ENVVALUE)))  {
            if (debug) printf( "env: PR_GetEnv() failed retrieving WinNative. Found: %s\n", value);
            failedAlready = PR_TRUE;
        }
        if (verbose) printf("env: PR_GetEnv() worked. Found: %s\n", value);
    }
#endif

    /* set an environment variable, read it back */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "=" ENVVALUE );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed setting\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() worked.\n");
    }

    value = PR_GetEnv( ENVNAME );
    if ( (NULL == value ) || (strcmp( value, ENVVALUE)))  {
        if (debug) printf( "env: PR_GetEnv() Failed after setting\n" );
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_GetEnv() worked after setting it. Found: %s\n", value );
    }

/* ---------------------------------------------------------------------- */
    /* un-set the variable, using RAW name... should not work */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (verbose) printf( "env: PR_SetEnv() not un-set using RAW name. Good!\n");
    } else {
        if (debug) printf("env: PR_SetEnv() un-set using RAW name. Bad!\n" );
        failedAlready = PR_TRUE;
    }

    value = PR_GetEnv( ENVNAME );
    if ( NULL == value ) {
        if (debug) printf("env: PR_GetEnv() after un-set using RAW name. Bad!\n" );
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf( "env: PR_GetEnv() after RAW un-set found: %s\n", value );
    }
    
/* ---------------------------------------------------------------------- */
    /* set it again ... */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "=" ENVVALUE );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed setting the second time.\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() worked.\n");
    }

    /* un-set the variable using the form name= */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "=" );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed un-setting using name=\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() un-set using name= worked\n" );
    }

    value = PR_GetEnv( ENVNAME );
    if (( NULL == value ) || ( 0x00 == *value )) {
        if (verbose) printf("env: PR_GetEnv() after un-set using name= worked\n" );
    } else {
        if (debug) printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value );
        failedAlready = PR_TRUE;
    }
/* ---------------------------------------------------------------------- */
    /* un-set the variable using the form name= */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "999=" );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed un-setting using name=\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() un-set using name= worked\n" );
    }

    value = PR_GetEnv( ENVNAME "999" );
    if (( NULL == value ) || ( 0x00 == *value )) {
        if (verbose) printf("env: PR_GetEnv() after un-set using name= worked\n" );
    } else {
        if (debug) printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value );
        failedAlready = PR_TRUE;
    }

/* ---------------------------------------------------------------------- */
    if (debug || verbose) printf("\n%s\n", (failedAlready)? "FAILED" : "PASSED" );
    return( (failedAlready)? 1 : 0 );
}  /* main() */
コード例 #12
0
ファイル: nsXULRunnerApp.cpp プロジェクト: rn10950/RetroZilla
int main(int argc, char* argv[])
{
  if (argc > 1 && (IsArg(argv[1], "h") ||
                   IsArg(argv[1], "help") ||
                   IsArg(argv[1], "?")))
  {
    Usage();
    return 0;
  }

  if (argc == 2 && (IsArg(argv[1], "v") || IsArg(argv[1], "version")))
  {
    Output(PR_FALSE, "Mozilla XULRunner %s\n", GRE_BUILD_ID);
    return 0;
  }

  if (argc > 1) {
    PRBool registerGlobal = IsArg(argv[1], "register-global");
    PRBool registerUser   = IsArg(argv[1], "register-user");
    if (registerGlobal || registerUser) {
      if (argc != 2) {
        Usage();
        return 1;
      }

      nsCOMPtr<nsIFile> regDir;
      nsresult rv = GetXULRunnerDir(argv[0], getter_AddRefs(regDir));
      if (NS_FAILED(rv))
        return 2;

      return RegisterXULRunner(registerGlobal, regDir,
                               kGREProperties,
                               NS_ARRAY_LENGTH(kGREProperties)) ? 0 : 2;
    }

    registerGlobal = IsArg(argv[1], "unregister-global");
    registerUser   = IsArg(argv[1], "unregister-user");
    if (registerGlobal || registerUser) {
      if (argc != 2) {
        Usage();
        return 1;
      }

      nsCOMPtr<nsIFile> regDir;
      nsresult rv = GetXULRunnerDir(argv[0], getter_AddRefs(regDir));
      if (NS_FAILED(rv))
        return 2;
      UnregisterXULRunner(registerGlobal, regDir);
      return 0;
    }

    if (IsArg(argv[1], "find-gre")) {
      if (argc != 3) {
        Usage();
        return 1;
      }

      char path[MAXPATHLEN];
      static const GREVersionRange vr = {
        argv[2], PR_TRUE,
        argv[2], PR_TRUE
      };
      static const GREProperty kProperties[] = {
        { "xulrunner", "true" }
      };

      nsresult rv = GRE_GetGREPathWithProperties(&vr, 1, kProperties,
                                                 NS_ARRAY_LENGTH(kProperties),
                                                 path, sizeof(path));
      if (NS_FAILED(rv))
        return 1;

      printf("%s\n", path);
      return 0;
    }

    if (IsArg(argv[1], "gre-version")) {
      if (argc != 2) {
        Usage();
        return 1;
      }

      printf("%s\n", GRE_BUILD_ID);
      return 0;
    }

    if (IsArg(argv[1], "install-app")) {
      if (argc < 3 || argc > 5) {
        Usage();
        return 1;
      }

      char *appLocation = argv[2];

      char *installTo = nsnull;
      if (argc > 3) {
        installTo = argv[3];
        if (!*installTo) // left blank?
          installTo = nsnull;
      }

      char *leafName = nsnull;
      if (argc > 4) {
        leafName = argv[4];
        if (!*leafName)
          leafName = nsnull;
      }

      nsCOMPtr<nsIFile> regDir;
      nsresult rv = GetXULRunnerDir(argv[0], getter_AddRefs(regDir));
      if (NS_FAILED(rv))
        return 2;

      return InstallXULApp(regDir, appLocation, installTo, leafName);
    }
  }

  geckoVersion = ParseVersion(GRE_BUILD_ID);

  const char *appDataFile = PR_GetEnv("XUL_APP_FILE");

  if (!(appDataFile && *appDataFile)) {
    if (argc < 2) {
      Usage();
      return 1;
    }

    if (IsArg(argv[1], "app")) {
      if (argc == 2) {
        Usage();
        return 1;
      }
      argv[1] = argv[0];
      ++argv;
      --argc;
    }

    appDataFile = argv[1];
    argv[1] = argv[0];
    ++argv;
    --argc;

    static char kAppEnv[MAXPATHLEN];
    PR_snprintf(kAppEnv, MAXPATHLEN, "XUL_APP_FILE=%s", appDataFile);
    PR_SetEnv(kAppEnv);
  }

  nsCAutoString vendor, name, version, buildID, appID, copyright;

  nsXREAppData appData = { sizeof(nsXREAppData), 0 };

  int rv = LoadAppData(appDataFile, &appData,
                       vendor, name, version, buildID, appID, copyright);
  if (!rv)
    rv = XRE_main(argc, argv, &appData);

  NS_IF_RELEASE(appData.directory);

  return rv;
}
コード例 #13
0
// Annotate the crash report with a Unique User ID and time
// since install.  Also do some prep work for recording
// time since last crash, which must be calculated at
// crash time.
// If any piece of data doesn't exist, initialize it first.
nsresult SetupExtraData(nsILocalFile* aAppDataDirectory,
                        const nsACString& aBuildID)
{
  nsCOMPtr<nsIFile> dataDirectory;
  nsresult rv = aAppDataDirectory->Clone(getter_AddRefs(dataDirectory));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = dataDirectory->AppendNative(NS_LITERAL_CSTRING("Crash Reports"));
  NS_ENSURE_SUCCESS(rv, rv);

  PRBool exists;
  rv = dataDirectory->Exists(&exists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!exists) {
    rv = dataDirectory->Create(nsIFile::DIRECTORY_TYPE, 0700);
    NS_ENSURE_SUCCESS(rv, rv);
  }

#if defined(XP_WIN32)
  nsAutoString dataDirEnv(NS_LITERAL_STRING("MOZ_CRASHREPORTER_DATA_DIRECTORY="));

  nsAutoString dataDirectoryPath;
  rv = dataDirectory->GetPath(dataDirectoryPath);
  NS_ENSURE_SUCCESS(rv, rv);

  dataDirEnv.Append(dataDirectoryPath);

  _wputenv(dataDirEnv.get());
#else
  // Save this path in the environment for the crash reporter application.
  nsCAutoString dataDirEnv("MOZ_CRASHREPORTER_DATA_DIRECTORY=");

  nsCAutoString dataDirectoryPath;
  rv = dataDirectory->GetNativePath(dataDirectoryPath);
  NS_ENSURE_SUCCESS(rv, rv);

  dataDirEnv.Append(dataDirectoryPath);

  char* env = ToNewCString(dataDirEnv);
  NS_ENSURE_TRUE(env, NS_ERROR_OUT_OF_MEMORY);

  PR_SetEnv(env);
#endif

  nsCAutoString data;
  if(NS_SUCCEEDED(GetOrInit(dataDirectory, NS_LITERAL_CSTRING("UserID"),
                            data, InitUserID)))
    AnnotateCrashReport(NS_LITERAL_CSTRING("UserID"), data);

  if(NS_SUCCEEDED(GetOrInit(dataDirectory,
                            NS_LITERAL_CSTRING("InstallTime") + aBuildID,
                            data, InitInstallTime)))
    AnnotateCrashReport(NS_LITERAL_CSTRING("InstallTime"), data);

  // this is a little different, since we can't init it with anything,
  // since it's stored at crash time, and we can't annotate the
  // crash report with the stored value, since we really want
  // (now - LastCrash), so we just get a value if it exists,
  // and store it in a time_t value.
  if(NS_SUCCEEDED(GetOrInit(dataDirectory, NS_LITERAL_CSTRING("LastCrash"),
                            data, NULL))) {
    lastCrashTime = (time_t)atol(data.get());
  }

  // not really the best place to init this, but I have the path I need here
  nsCOMPtr<nsIFile> lastCrashFile;
  rv = dataDirectory->Clone(getter_AddRefs(lastCrashFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = lastCrashFile->AppendNative(NS_LITERAL_CSTRING("LastCrash"));
  NS_ENSURE_SUCCESS(rv, rv);
  memset(lastCrashTimeFilename, 0, sizeof(lastCrashTimeFilename));

#if defined(XP_WIN32)
  nsAutoString filename;
  rv = lastCrashFile->GetPath(filename);
  NS_ENSURE_SUCCESS(rv, rv);

  if (filename.Length() < XP_PATH_MAX)
    wcsncpy(lastCrashTimeFilename, filename.get(), filename.Length());
#else
  nsCAutoString filename;
  rv = lastCrashFile->GetNativePath(filename);
  NS_ENSURE_SUCCESS(rv, rv);

  if (filename.Length() < XP_PATH_MAX)
    strncpy(lastCrashTimeFilename, filename.get(), filename.Length());
#endif

  return NS_OK;
}
コード例 #14
0
ファイル: env.c プロジェクト: biddyweb/switch-oss
int main(int argc, char **argv)
#endif
{
    char    *value;
    PRStatus    rc;

    {   /* Get command line options */
        PLOptStatus os;
        PLOptState *opt = PL_CreateOptState(argc, argv, "vds");

	    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
        {
		    if (PL_OPT_BAD == os) continue;
            switch (opt->option)
            {
            case 'd':  /* debug */
                debug = 1;
                break;
            case 'v':  /* verbose */
                verbose = 1;
                break;
            case 's':  /* secure / set[ug]id */
                /*
                ** To test PR_GetEnvSecure, make this executable (or a
                ** copy of it) setuid / setgid / otherwise inherently
                ** privileged (e.g., file capabilities) and run it
                ** with this flag.
                */
                secure = 1;
                break;
             default:
                break;
            }
        }
	    PL_DestroyOptState(opt);
    } /* end block "Get command line options" */

#if 0 
    {
        /*
        ** This uses Windows native environment manipulation
        ** as an experiment. Note the separation of namespace!
        */
        BOOL rv;
        DWORD   size;
        rv = SetEnvironmentVariable( ENVNAME, ENVVALUE );
        if ( rv == 0 )  {
            if (debug) printf("env: Shit! SetEnvironmentVariable() failed\n");
            failedAlready = PR_TRUE;
        }
        if (verbose) printf("env: SetEnvironmentVariable() worked\n");

        size = GetEnvironmentVariable( ENVNAME, envBuf, ENVBUFSIZE );    
        if ( size == 0 )  {
            if (debug) printf("env: Shit! GetEnvironmentVariable() failed. Found: %s\n", envBuf );
            failedAlready = PR_TRUE;
        }
        if (verbose) printf("env: GetEnvironmentVariable() worked. Found: %s\n", envBuf);

        value = PR_GetEnv( ENVNAME );
        if ( (NULL == value ) || (strcmp( value, ENVVALUE)))  {
            if (debug) printf( "env: PR_GetEnv() failed retrieving WinNative. Found: %s\n", value);
            failedAlready = PR_TRUE;
        }
        if (verbose) printf("env: PR_GetEnv() worked. Found: %s\n", value);
    }
#endif

    /* set an environment variable, read it back */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "=" ENVVALUE );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed setting\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() worked.\n");
    }

    value = PR_GetEnv( ENVNAME );
    if ( (NULL == value ) || (strcmp( value, ENVVALUE)))  {
        if (debug) printf( "env: PR_GetEnv() Failed after setting\n" );
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_GetEnv() worked after setting it. Found: %s\n", value );
    }

    if ( secure ) {
        /*
        ** In this case we've been run with elevated privileges, so
        ** test that PR_GetEnvSecure *doesn't* find that env var.
        */
        value = PR_GetEnvSecure( ENVNAME );
        if ( NULL != value ) {
            if (debug) printf( "env: PR_GetEnvSecure() failed; expected NULL, found \"%s\"\n", value );
            failedAlready = PR_TRUE;
        } else {
            if (verbose) printf("env: PR_GetEnvSecure() worked\n" );
        }
    } else {
        /*
        ** In this case the program is being run normally, so do the
        ** same check for PR_GetEnvSecure as for PR_GetEnv.
        */
        value = PR_GetEnvSecure( ENVNAME );
        if ( (NULL == value ) || (strcmp( value, ENVVALUE)))  {
            if (debug) printf( "env: PR_GetEnvSecure() Failed after setting\n" );
            failedAlready = PR_TRUE;
        } else {
            if (verbose) printf("env: PR_GetEnvSecure() worked after setting it. Found: %s\n", value );
        }
    }

/* ---------------------------------------------------------------------- */
    /* check that PR_DuplicateEnvironment() agrees with PR_GetEnv() */
    {
#if defined(XP_UNIX) && (!defined(DARWIN) || defined(HAVE_CRT_EXTERNS_H))
        static const PRBool expect_failure = PR_FALSE;
#else
        static const PRBool expect_failure = PR_TRUE;
#endif
        char **i, **dupenv = PR_DuplicateEnvironment();


        if ( NULL == dupenv ) {
            if (expect_failure) {
                if (verbose) printf("env: PR_DuplicateEnvironment failed, "
                                    "as expected on this platform.\n");
            } else {
                if (debug) printf("env: PR_DuplicateEnvironment() failed.\n");
                failedAlready = PR_TRUE;
            }
        } else {
            unsigned found = 0;

            if (expect_failure) {
                if (debug) printf("env: PR_DuplicateEnvironment() succeeded, "
                                  "but failure is expected on this platform.\n");
                failedAlready = PR_TRUE;
            } else {
                if (verbose) printf("env: PR_DuplicateEnvironment() succeeded.\n");
            }
            for (i = dupenv; *i; i++) {
                char *equals = strchr(*i, '=');

                if ( equals == NULL ) {
                    if (debug) printf("env: PR_DuplicateEnvironment() returned a string"
                                      " with no '=': %s\n", *i);
                    failedAlready = PR_TRUE;
                } else {
                    /* We own this string, so we can temporarily alter it */
                    /* *i is the null-terminated name; equals + 1 is the value */
                    *equals = '\0';

                    if ( strcmp(*i, ENVNAME) == 0) {
                        found++;
                        if (verbose) printf("env: PR_DuplicateEnvironment() found " ENVNAME
                                            " (%u so far).\n", found);
                    }

                    /* Multiple values for the same name can't happen, according to POSIX. */
                    value = PR_GetEnv(*i);
                    if ( value == NULL ) {
                        if (debug) printf("env: PR_DuplicateEnvironment() returned a name"
                                          " which PR_GetEnv() failed to find: %s\n", *i);
                        failedAlready = PR_TRUE;
                    } else if ( strcmp(equals + 1, value) != 0) {
                        if (debug) printf("env: PR_DuplicateEnvironment() returned the wrong"
                                          " value for %s: expected %s; found %s\n",
                                          *i, value, equals + 1);
                        failedAlready = PR_TRUE;
                    } else {
                        if (verbose) printf("env: PR_DuplicateEnvironment() agreed with"
                                            " PR_GetEnv() about %s\n", *i);
                    }
                }
                PR_Free(*i);
            }
            PR_Free(dupenv);

            if (found != 1) {
                if (debug) printf("env: PR_DuplicateEnvironment() found %u entries for " ENVNAME
                                  " (expected 1)\n", found);
                failedAlready = PR_TRUE;
            } else {
                if (verbose) printf("env: PR_DuplicateEnvironment() found 1 entry for " ENVNAME "\n");
            }
        }
    }

/* ---------------------------------------------------------------------- */
    /* un-set the variable, using RAW name... should not work */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (verbose) printf( "env: PR_SetEnv() not un-set using RAW name. Good!\n");
    } else {
        if (debug) printf("env: PR_SetEnv() un-set using RAW name. Bad!\n" );
        failedAlready = PR_TRUE;
    }

    value = PR_GetEnv( ENVNAME );
    if ( NULL == value ) {
        if (debug) printf("env: PR_GetEnv() after un-set using RAW name. Bad!\n" );
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf( "env: PR_GetEnv() after RAW un-set found: %s\n", value );
    }
    
/* ---------------------------------------------------------------------- */
    /* set it again ... */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "=" ENVVALUE );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed setting the second time.\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() worked.\n");
    }

    /* un-set the variable using the form name= */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "=" );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed un-setting using name=\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() un-set using name= worked\n" );
    }

    value = PR_GetEnv( ENVNAME );
    if (( NULL == value ) || ( 0x00 == *value )) {
        if (verbose) printf("env: PR_GetEnv() after un-set using name= worked\n" );
    } else {
        if (debug) printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value );
        failedAlready = PR_TRUE;
    }
/* ---------------------------------------------------------------------- */
    /* un-set the variable using the form name= */
    envBuf = NewBuffer( ENVBUFSIZE );
    sprintf( envBuf, ENVNAME "999=" );
    rc = PR_SetEnv( envBuf );
    if ( PR_FAILURE == rc )  {
        if (debug) printf( "env: PR_SetEnv() failed un-setting using name=\n");
        failedAlready = PR_TRUE;
    } else {
        if (verbose) printf("env: PR_SetEnv() un-set using name= worked\n" );
    }

    value = PR_GetEnv( ENVNAME "999" );
    if (( NULL == value ) || ( 0x00 == *value )) {
        if (verbose) printf("env: PR_GetEnv() after un-set using name= worked\n" );
    } else {
        if (debug) printf( "env: PR_GetEnv() after un-set using name=. Found: %s\n", value );
        failedAlready = PR_TRUE;
    }

/* ---------------------------------------------------------------------- */
    if (debug || verbose) printf("\n%s\n", (failedAlready)? "FAILED" : "PASSED" );
    return( (failedAlready)? 1 : 0 );
}  /* main() */
コード例 #15
0
NS_IMETHODIMP
nsAppStartup::Quit(PRUint32 aMode)
{
  PRUint32 ferocity = (aMode & 0xF);

  // Quit the application. We will asynchronously call the appshell's
  // Exit() method via nsAppExitEvent to allow one last pass
  // through any events in the queue. This guarantees a tidy cleanup.
  nsresult rv = NS_OK;
  PRBool postedExitEvent = PR_FALSE;

  if (mShuttingDown)
    return NS_OK;

  // If we're considering quitting, we will only do so if:
  if (ferocity == eConsiderQuit) {
    if (mConsiderQuitStopper == 0) {
      // there are no windows...
      ferocity = eAttemptQuit;
    }
#ifdef XP_MACOSX
    else if (mConsiderQuitStopper == 1) {
      // ... or there is only a hiddenWindow left, and it's useless:
      nsCOMPtr<nsIAppShellService> appShell
        (do_GetService(NS_APPSHELLSERVICE_CONTRACTID));

      // Failure shouldn't be fatal, but will abort quit attempt:
      if (!appShell)
        return NS_OK;

      PRBool usefulHiddenWindow;
      appShell->GetApplicationProvidedHiddenWindow(&usefulHiddenWindow);
      nsCOMPtr<nsIXULWindow> hiddenWindow;
      appShell->GetHiddenWindow(getter_AddRefs(hiddenWindow));
      // If the one window is useful, we won't quit:
      if (!hiddenWindow || usefulHiddenWindow)
        return NS_OK;

      ferocity = eAttemptQuit;
    }
#endif
  }

  nsCOMPtr<nsIObserverService> obsService;
  if (ferocity == eAttemptQuit || ferocity == eForceQuit) {

    nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
    nsCOMPtr<nsIWindowMediator> mediator (do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
    if (mediator) {
      mediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
      if (windowEnumerator) {
        PRBool more;
        while (windowEnumerator->HasMoreElements(&more), more) {
          nsCOMPtr<nsISupports> window;
          windowEnumerator->GetNext(getter_AddRefs(window));
          nsCOMPtr<nsPIDOMWindow> domWindow(do_QueryInterface(window));
          if (domWindow) {
            if (!domWindow->CanClose())
              return NS_OK;
          }
        }
      }
    }

    mShuttingDown = PR_TRUE;
    if (!mRestart) {
      mRestart = (aMode & eRestart) != 0;
      gRestartMode = (aMode & 0xF0);
    }

    if (mRestart) {
      // Firefox-restarts reuse the process. Process start-time isn't a useful indicator of startup time
      PR_SetEnv(PR_smprintf("MOZ_APP_RESTART=%lld", (PRInt64) PR_Now() / PR_USEC_PER_MSEC));
    }

    obsService = mozilla::services::GetObserverService();

    if (!mAttemptingQuit) {
      mAttemptingQuit = PR_TRUE;
#ifdef XP_MACOSX
      // now even the Mac wants to quit when the last window is closed
      ExitLastWindowClosingSurvivalArea();
#endif
      if (obsService)
        obsService->NotifyObservers(nsnull, "quit-application-granted", nsnull);
    }

    /* Enumerate through each open window and close it. It's important to do
       this before we forcequit because this can control whether we really quit
       at all. e.g. if one of these windows has an unload handler that
       opens a new window. Ugh. I know. */
    CloseAllWindows();

    if (mediator) {
      if (ferocity == eAttemptQuit) {
        ferocity = eForceQuit; // assume success

        /* Were we able to immediately close all windows? if not, eAttemptQuit
           failed. This could happen for a variety of reasons; in fact it's
           very likely. Perhaps we're being called from JS and the window->Close
           method hasn't had a chance to wrap itself up yet. So give up.
           We'll return (with eConsiderQuit) as the remaining windows are
           closed. */
        mediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
        if (windowEnumerator) {
          PRBool more;
          while (windowEnumerator->HasMoreElements(&more), more) {
            /* we can't quit immediately. we'll try again as the last window
               finally closes. */
            ferocity = eAttemptQuit;
            nsCOMPtr<nsISupports> window;
            windowEnumerator->GetNext(getter_AddRefs(window));
            nsCOMPtr<nsIDOMWindowInternal> domWindow(do_QueryInterface(window));
            if (domWindow) {
              PRBool closed = PR_FALSE;
              domWindow->GetClosed(&closed);
              if (!closed) {
                rv = NS_ERROR_FAILURE;
                break;
              }
            }
          }
        }
      }
    }
  }

  if (ferocity == eForceQuit) {
    // do it!

    // No chance of the shutdown being cancelled from here on; tell people
    // we're shutting down for sure while all services are still available.
    if (obsService) {
      NS_NAMED_LITERAL_STRING(shutdownStr, "shutdown");
      NS_NAMED_LITERAL_STRING(restartStr, "restart");
      obsService->NotifyObservers(nsnull, "quit-application",
        mRestart ? restartStr.get() : shutdownStr.get());
    }

    if (!mRunning) {
      postedExitEvent = PR_TRUE;
    }
    else {
      // no matter what, make sure we send the exit event.  If
      // worst comes to worst, we'll do a leaky shutdown but we WILL
      // shut down. Well, assuming that all *this* stuff works ;-).
      nsCOMPtr<nsIRunnable> event = new nsAppExitEvent(this);
      rv = NS_DispatchToCurrentThread(event);
      if (NS_SUCCEEDED(rv)) {
        postedExitEvent = PR_TRUE;
      }
      else {
        NS_WARNING("failed to dispatch nsAppExitEvent");
      }
    }
  }

  // turn off the reentrancy check flag, but not if we have
  // more asynchronous work to do still.
  if (!postedExitEvent)
    mShuttingDown = PR_FALSE;
  return rv;
}
コード例 #16
0
ファイル: PluginProcessChild.cpp プロジェクト: 70599/Waterfox
bool
PluginProcessChild::Init()
{
    nsDebugImpl::SetMultiprocessMode("NPAPI");

#if defined(XP_MACOSX)
    // Remove the trigger for "dyld interposing" that we added in
    // GeckoChildProcessHost::PerformAsyncLaunchInternal(), in the host
    // process just before we were launched.  Dyld interposing will still
    // happen in our process (the plugin child process).  But we don't want
    // it to happen in any processes that the plugin might launch from our
    // process.
    nsCString interpose(PR_GetEnv("DYLD_INSERT_LIBRARIES"));
    if (!interpose.IsEmpty()) {
        // If we added the path to libplugin_child_interpose.dylib to an
        // existing DYLD_INSERT_LIBRARIES, we appended it to the end, after a
        // ":" path seperator.
        int32_t lastSeparatorPos = interpose.RFind(":");
        int32_t lastTriggerPos = interpose.RFind("libplugin_child_interpose.dylib");
        bool needsReset = false;
        if (lastTriggerPos != -1) {
            if (lastSeparatorPos == -1) {
                interpose.Truncate();
                needsReset = true;
            } else if (lastTriggerPos > lastSeparatorPos) {
                interpose.SetLength(lastSeparatorPos);
                needsReset = true;
            }
        }
        if (needsReset) {
            nsCString setInterpose("DYLD_INSERT_LIBRARIES=");
            if (!interpose.IsEmpty()) {
                setInterpose.Append(interpose);
            }
            // Values passed to PR_SetEnv() must be seperately allocated.
            char* setInterposePtr = strdup(setInterpose.get());
            PR_SetEnv(setInterposePtr);
        }
    }
#endif

#ifdef XP_WIN
    // Drag-and-drop needs OleInitialize to be called, and Silverlight depends
    // on the host calling CoInitialize (which is called by OleInitialize).
    ::OleInitialize(nullptr);
#endif

    // Certain plugins, such as flash, steal the unhandled exception filter
    // thus we never get crash reports when they fault. This call fixes it.
    message_loop()->set_exception_restoration(true);

    std::string pluginFilename;

#if defined(OS_POSIX)
    // NB: need to be very careful in ensuring that the first arg
    // (after the binary name) here is indeed the plugin module path.
    // Keep in sync with dom/plugins/PluginModuleParent.
    std::vector<std::string> values = CommandLine::ForCurrentProcess()->argv();
    MOZ_ASSERT(values.size() >= 2, "not enough args");

    pluginFilename = UnmungePluginDsoPath(values[1]);

#elif defined(OS_WIN)
    std::vector<std::wstring> values =
        CommandLine::ForCurrentProcess()->GetLooseValues();
    MOZ_ASSERT(values.size() >= 1, "not enough loose args");

    if (ShouldProtectPluginCurrentDirectory(values[0].c_str())) {
        SanitizeEnvironmentVariables();
        SetDllDirectory(L"");
    }

    pluginFilename = WideToUTF8(values[0]);

#if defined(MOZ_SANDBOX)
    // This is probably the earliest we would want to start the sandbox.
    // As we attempt to tighten the sandbox, we may need to consider moving this
    // to later in the plugin initialization.
    mozilla::SandboxTarget::Instance()->StartSandbox();
#endif
#else
#  error Sorry
#endif

    if (NS_FAILED(nsRegion::InitStatic())) {
      NS_ERROR("Could not initialize nsRegion");
      return false;
    }

    bool retval = mPlugin.InitForChrome(pluginFilename, ParentPid(),
                                        IOThreadChild::message_loop(),
                                        IOThreadChild::channel());
#if defined(XP_MACOSX)
    if (nsCocoaFeatures::OnYosemiteOrLater()) {
      // Explicitly turn off CGEvent logging.  This works around bug 1092855.
      // If there are already CGEvents in the log, turning off logging also
      // causes those events to be written to disk.  But at this point no
      // CGEvents have yet been processed.  CGEvents are events (usually
      // input events) pulled from the WindowServer.  An option of 0x80000008
      // turns on CGEvent logging.
      CGSSetDebugOptions(0x80000007);
    }
#endif
    return retval;
}
コード例 #17
0
//----------------------------------------------------------------------------------------
nsresult nsMacCommandLine::AddToEnvironmentVars(const char* inArgText)
//----------------------------------------------------------------------------------------
{
  (void)PR_SetEnv(inArgText);
  return NS_OK;
}
コード例 #18
0
JNIEXPORT void JNICALL 
Java_org_mozilla_webclient_impl_wrapper_1native_WrapperFactoryImpl_nativeAppInitialize(
										JNIEnv *env, jobject obj, jstring verifiedBinDirAbsolutePath, jint nativeWF, jobject nativeEventThread)
{
    const char *nativePath = nsnull;
    NativeWrapperFactory *nativeWrapperFactory = (NativeWrapperFactory *) nativeWF;
    nsresult rv;
    nsCOMPtr<nsILocalFile> binDir;
    
    // PENDING(edburns): We need this for rdf_getChildCount
    PR_SetEnv("XPCOM_CHECK_THREADSAFE=0");

    // 
    // create an nsILocalFile from our argument
    //
    
    PR_LOG(prLogModuleInfo, PR_LOG_DEBUG, 
           ("WrapperFactoryImpl_nativeAppInitialize: entering\n"));

    nativePath = (const char *) ::util_GetStringUTFChars(env, 
                                                   verifiedBinDirAbsolutePath);
    PR_LOG(prLogModuleInfo, PR_LOG_DEBUG, 
           ("WrapperFactoryImpl_nativeAppInitialize: nativeBinDir: %s\n", 
            nativePath));
    
    if (nativePath) {
        rv = NS_NewNativeLocalFile(nsDependentCString(nativePath), 1, 
                                   getter_AddRefs(binDir));
        PR_LOG(prLogModuleInfo, PR_LOG_DEBUG, 
               ("WrapperFactoryImpl_nativeAppInitialize: NS_NewNativeLocalFile rv: %d\n", 
                rv));
        
        if (NS_FAILED(rv)) {
            ::util_ThrowExceptionToJava(env, 
                                  "Can't get nsILocalFile from bin directory");
        }
    }
    ::util_ReleaseStringUTFChars(env, verifiedBinDirAbsolutePath, nativePath);
    
    //
    // Make the all important NS_InitEmbedding call
    // 
    
    rv = NS_InitEmbedding(binDir, nsnull);
    PR_LOG(prLogModuleInfo, PR_LOG_DEBUG, 
          ("WrapperFactoryImpl_nativeAppInitialize: NS_InitEmbedding rv: %d\n",
           rv));

    if (NS_FAILED(rv)) {
        ::util_ThrowExceptionToJava(env, "NS_InitEmbedding() failed.");
    }

    // the rest of the startup tasks are coordinated from the java side.
    PR_LOG(prLogModuleInfo, PR_LOG_DEBUG, 
           ("WrapperFactoryImpl_nativeAppInitialize: exiting\n"));

    char propValue[50];
    ::util_getSystemProperty(env, "native.waitForDebugger", propValue, 50);
    if (nsnull != propValue[0] &&
        0 < nsCRT::strlen(propValue)) {
#ifdef XP_UNIX
        pid_t pid = getpid();
        printf("++++++++++++++++debug: pid is: %d\n", pid);
#endif
#ifdef XP_PC
        printf("++++++++++++++++debug: pid is: %d\n", GetCurrentProcessId());
#endif
        fflush(stdout);
        PR_Sleep(700000);
    }
    
    // Store our pointer to the global vm
    if (nsnull == gVm) { // declared in ../src_share/jni_util.h
        ::util_GetJavaVM(env, &gVm);  // save this vm reference
    }

    util_InitializeShareInitContext(env, &(nativeWrapperFactory->shareContext));
    rv = nativeWrapperFactory->Init(env, nativeEventThread);
    if (NS_FAILED(rv)) {
        ::util_ThrowExceptionToJava(env, 
                                    "Failed to init NativeWrapperFactory");
    }
}
コード例 #19
0
void
TimeStamp::RecordProcessRestart()
{
  PR_SetEnv(PR_smprintf("MOZ_APP_RESTART=%lld", ClockTimeNs()));
  sProcessCreation = TimeStamp();
}