[WTF] Add environment variable helpers
authorross.kirsling@sony.com <ross.kirsling@sony.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 15 Feb 2019 22:47:26 +0000 (22:47 +0000)
committerross.kirsling@sony.com <ross.kirsling@sony.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 15 Feb 2019 22:47:26 +0000 (22:47 +0000)
https://bugs.webkit.org/show_bug.cgi?id=192405

Reviewed by Michael Catanzaro.

Source/JavaScriptCore:

* inspector/remote/glib/RemoteInspectorGlib.cpp:
(Inspector::RemoteInspector::RemoteInspector):
(Inspector::RemoteInspector::start):
* jsc.cpp:
(startTimeoutThreadIfNeeded):
* runtime/Options.cpp:
(JSC::overrideOptionWithHeuristic):
(JSC::Options::overrideAliasedOptionWithHeuristic):
(JSC::Options::initialize):
* runtime/VM.cpp:
(JSC::enableAssembler):
(JSC::VM::VM):
* tools/CodeProfiling.cpp:
(JSC::CodeProfiling::notifyAllocator):
Utilize WTF::Environment where possible.

Source/WebCore:

* platform/NotImplemented.h:
* platform/cocoa/SystemVersion.mm:
(WebCore::createSystemMarketingVersion):
* platform/graphics/gstreamer/GStreamerCommon.cpp:
(WebCore::initializeGStreamer):
* platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp:
(WebCore::MediaPlayerPrivateGStreamer::createGSTPlayBin):
* platform/graphics/nicosia/NicosiaPaintingEngine.cpp:
(Nicosia::PaintingEngine::create):
* platform/graphics/texmap/TextureMapperFPSCounter.cpp:
(WebCore::TextureMapperFPSCounter::TextureMapperFPSCounter):
* platform/graphics/x11/PlatformDisplayX11.cpp:
(WebCore::PlatformDisplayX11::create):
* platform/gtk/RenderThemeWidget.cpp:
(WebCore::RenderThemeScrollbar::RenderThemeScrollbar):
* platform/gtk/ScrollbarThemeGtk.cpp:
(WebCore::ScrollbarThemeGtk::ScrollbarThemeGtk):
* platform/network/curl/CurlContext.cpp:
(WebCore::CurlContext::CurlContext):
(WebCore::EnvironmentVariableReader::read): Deleted.
(WebCore::EnvironmentVariableReader::defined): Deleted.
(WebCore::EnvironmentVariableReader::readAs): Deleted.
(WebCore::EnvironmentVariableReader::sscanTemplate): Deleted.
(WebCore::EnvironmentVariableReader::sscanTemplate<signed>): Deleted.
(WebCore::EnvironmentVariableReader::sscanTemplate<unsigned>): Deleted.
* platform/network/curl/NetworkStorageSessionCurl.cpp:
(WebCore::defaultCookieJarPath):
* platform/network/playstation/CurlSSLHandlePlayStation.cpp:
(WebCore::getCACertPathEnv):
* platform/network/win/CurlSSLHandleWin.cpp:
(WebCore::getCACertPathEnv):
* platform/text/hyphen/HyphenationLibHyphen.cpp:
(WebCore::topLevelPath):
(WebCore::webkitBuildDirectory):
* platform/unix/LoggingUnix.cpp:
(WebCore::logLevelString):
* platform/win/LoggingWin.cpp:
(WebCore::logLevelString):
Utilize WTF::Environment where possible.

Source/WebCore/PAL:

* pal/unix/LoggingUnix.cpp:
(PAL::logLevelString):
* pal/win/LoggingWin.cpp:
(PAL::logLevelString):
Utilize WTF::Environment where possible.

Source/WebKit:

* NetworkProcess/EntryPoint/unix/NetworkProcessMain.cpp:
(main):
* Platform/unix/LoggingUnix.cpp:
(WebKit::logLevelString):
* Platform/win/LoggingWin.cpp:
(WebKit::logLevelString):
* PluginProcess/mac/PluginProcessMac.mm:
(WebKit::shouldCallRealDebugger):
* Shared/Plugins/unix/PluginSearchPath.cpp:
(WebKit::pluginsDirectories):
* Shared/glib/ProcessExecutablePathGLib.cpp:
(WebKit::findWebKitProcess):
* UIProcess/API/glib/WebKitSettings.cpp:
(webKitSettingsConstructed):
(webKitSettingsSetProperty):
* UIProcess/API/glib/WebKitWebContext.cpp:
(injectedBundleDirectory):
(webkitWebContextConstructed):
* UIProcess/API/gtk/WebKitWebViewGtk.cpp:
(webkitWebViewMaximizeWindow):
(webkitWebViewRestoreWindow):
* UIProcess/API/wpe/WPEView.cpp:
(WKWPE::m_backend):
* UIProcess/AuxiliaryProcessProxy.cpp:
(WebKit::AuxiliaryProcessProxy::getLaunchOptions):
* UIProcess/Launcher/glib/BubblewrapLauncher.cpp:
(WebKit::XDGDBusProxyLauncher::launch):
(WebKit::bindDBusSession):
(WebKit::bindX11):
(WebKit::bindWayland):
(WebKit::bindPulse):
(WebKit::bindPathVar):
(WebKit::bindGStreamerData):
(WebKit::bubblewrapSpawn):
* UIProcess/Launcher/glib/ProcessLauncherGLib.cpp:
(WebKit::ProcessLauncher::launchProcess):
* UIProcess/Launcher/mac/ProcessLauncherMac.mm:
(WebKit::systemDirectoryPath):
(WebKit::ProcessLauncher::launchProcess):
* UIProcess/glib/WebProcessPoolGLib.cpp:
(WebKit::memoryPressureMonitorDisabled):
(WebKit::WebProcessPool::platformInitialize):
(WebKit::WebProcessPool::platformInitializeWebProcess):
* UIProcess/gtk/HardwareAccelerationManager.cpp:
(WebKit::HardwareAccelerationManager::HardwareAccelerationManager):
* WebProcess/EntryPoint/unix/WebProcessMain.cpp:
(main):
* WebProcess/gtk/WebProcessMainGtk.cpp:
* WebProcess/wpe/WebProcessMainWPE.cpp:
Utilize WTF::Environment where possible.

Source/WebKitLegacy/ios:

* Misc/WebUIKitSupport.mm:
(WebKitPlatformSystemRootDirectory):
Utilize WTF::Environment where possible.

Source/WebKitLegacy/mac:

* WebView/WebView.mm:
(-[WebView _initWithFrame:frameName:groupName:]):
Utilize WTF::Environment where possible.

Source/WTF:

Create a new Environment API as a platform-independent, thread-safe(r)
way to get and set environment variables.

* WTF.xcodeproj/project.pbxproj:
* wtf/CMakeLists.txt:
* wtf/Environment.h: Added.
* wtf/PlatformGTK.cmake:
* wtf/PlatformJSCOnly.cmake:
* wtf/PlatformMac.cmake:
* wtf/PlatformPlayStation.cmake:
* wtf/PlatformWPE.cmake:
* wtf/PlatformWin.cmake:
* wtf/posix/EnvironmentPOSIX.cpp: Added.
* wtf/win/EnvironmentWin.cpp: Added.
Introduce WTF::Environment.

* wtf/Threading.cpp:
(WTF::threadingIsInitialized):
(WTF::initializeThreading):
* wtf/Threading.h:
Introduce WTF::threadingIsInitialized() so that we can ASSERT that it's
false before setting an environment variable through the new API.

* wtf/DataLog.cpp:
(WTF::initializeLogFileOnce):
* wtf/NumberOfCores.cpp:
(WTF::numberOfProcessorCores):
* wtf/posix/FileSystemPOSIX.cpp:
(WTF::FileSystemImpl::openTemporaryFile):
Utilize WTF::Environment where possible.

Tools:

* DumpRenderTree/mac/DumpRenderTree.mm:
(libraryPathForDumpRenderTree):
* DumpRenderTree/win/DumpRenderTree.cpp:
(libraryPathForDumpRenderTree):
* TestRunnerShared/IOSLayoutTestCommunication.cpp:
(setUpIOSLayoutTestCommunication):
* TestWebKitAPI/Tests/WebKitGLib/TestAutomationSession.cpp:
(beforeAll):
* TestWebKitAPI/glib/WebKitGLib/TestMain.cpp:
(main):
* TestWebKitAPI/glib/WebKitGLib/WebKitTestBus.cpp:
(WebKitTestBus::run):
* WebKitTestRunner/InjectedBundle/gtk/ActivateFontsGtk.cpp:
(WTR::getOutputDir):
(WTR::initializeFontConfigSetting):
* WebKitTestRunner/InjectedBundle/gtk/InjectedBundleGtk.cpp:
(WTR::InjectedBundle::platformInitialize):
* WebKitTestRunner/InjectedBundle/gtk/InjectedBundleUtilities.cpp:
(WTR::topLevelPath):
* WebKitTestRunner/InjectedBundle/wpe/ActivateFontsWPE.cpp:
(WTR::topLevelPath):
(WTR::getOutputDir):
(WTR::activateFonts):
* WebKitTestRunner/TestController.cpp:
(WTR::TestController::libraryPathForTesting):
(WTR::TestController::generateContextConfiguration const):
(WTR::TestController::generatePageConfiguration):
(WTR::TestController::decideDestinationWithSuggestedFilename):
(WTR::TestController::platformAdjustContext):
* WebKitTestRunner/TestController.h:
* WebKitTestRunner/cocoa/TestControllerCocoa.mm:
(WTR::TestController::cocoaPlatformInitialize):
(WTR::TestController::platformAdjustContext):
* WebKitTestRunner/gtk/main.cpp:
(main):
* WebKitTestRunner/mac/TestControllerMac.mm:
(WTR::TestController::configureContentExtensionForTest):
* WebKitTestRunner/wpe/main.cpp:
(main):
Utilize WTF::Environment where possible.

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@241620 268f45cc-cd09-0410-ab3c-d52691b4dbfc

84 files changed:
Source/JavaScriptCore/ChangeLog
Source/JavaScriptCore/inspector/remote/glib/RemoteInspectorGlib.cpp
Source/JavaScriptCore/jsc.cpp
Source/JavaScriptCore/runtime/Options.cpp
Source/JavaScriptCore/runtime/VM.cpp
Source/JavaScriptCore/tools/CodeProfiling.cpp
Source/WTF/ChangeLog
Source/WTF/WTF.xcodeproj/project.pbxproj
Source/WTF/wtf/CMakeLists.txt
Source/WTF/wtf/DataLog.cpp
Source/WTF/wtf/Environment.h [new file with mode: 0644]
Source/WTF/wtf/NumberOfCores.cpp
Source/WTF/wtf/PlatformGTK.cmake
Source/WTF/wtf/PlatformJSCOnly.cmake
Source/WTF/wtf/PlatformMac.cmake
Source/WTF/wtf/PlatformPlayStation.cmake
Source/WTF/wtf/PlatformWPE.cmake
Source/WTF/wtf/PlatformWin.cmake
Source/WTF/wtf/Threading.cpp
Source/WTF/wtf/Threading.h
Source/WTF/wtf/posix/EnvironmentPOSIX.cpp [new file with mode: 0644]
Source/WTF/wtf/posix/FileSystemPOSIX.cpp
Source/WTF/wtf/win/EnvironmentWin.cpp [new file with mode: 0644]
Source/WebCore/ChangeLog
Source/WebCore/PAL/ChangeLog
Source/WebCore/PAL/pal/unix/LoggingUnix.cpp
Source/WebCore/PAL/pal/win/LoggingWin.cpp
Source/WebCore/platform/NotImplemented.h
Source/WebCore/platform/cocoa/SystemVersion.mm
Source/WebCore/platform/graphics/gstreamer/GStreamerCommon.cpp
Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp
Source/WebCore/platform/graphics/nicosia/NicosiaPaintingEngine.cpp
Source/WebCore/platform/graphics/texmap/TextureMapperFPSCounter.cpp
Source/WebCore/platform/graphics/x11/PlatformDisplayX11.cpp
Source/WebCore/platform/gtk/RenderThemeWidget.cpp
Source/WebCore/platform/gtk/ScrollbarThemeGtk.cpp
Source/WebCore/platform/network/curl/CurlContext.cpp
Source/WebCore/platform/network/curl/NetworkStorageSessionCurl.cpp
Source/WebCore/platform/network/playstation/CurlSSLHandlePlayStation.cpp
Source/WebCore/platform/network/win/CurlSSLHandleWin.cpp
Source/WebCore/platform/text/hyphen/HyphenationLibHyphen.cpp
Source/WebCore/platform/unix/LoggingUnix.cpp
Source/WebCore/platform/win/LoggingWin.cpp
Source/WebKit/ChangeLog
Source/WebKit/NetworkProcess/EntryPoint/unix/NetworkProcessMain.cpp
Source/WebKit/Platform/unix/LoggingUnix.cpp
Source/WebKit/Platform/win/LoggingWin.cpp
Source/WebKit/PluginProcess/mac/PluginProcessMac.mm
Source/WebKit/Shared/Plugins/unix/PluginSearchPath.cpp
Source/WebKit/Shared/glib/ProcessExecutablePathGLib.cpp
Source/WebKit/UIProcess/API/glib/WebKitSettings.cpp
Source/WebKit/UIProcess/API/glib/WebKitWebContext.cpp
Source/WebKit/UIProcess/API/gtk/WebKitWebViewGtk.cpp
Source/WebKit/UIProcess/API/wpe/WPEView.cpp
Source/WebKit/UIProcess/AuxiliaryProcessProxy.cpp
Source/WebKit/UIProcess/Launcher/glib/BubblewrapLauncher.cpp
Source/WebKit/UIProcess/Launcher/glib/ProcessLauncherGLib.cpp
Source/WebKit/UIProcess/Launcher/mac/ProcessLauncherMac.mm
Source/WebKit/UIProcess/glib/WebProcessPoolGLib.cpp
Source/WebKit/UIProcess/gtk/HardwareAccelerationManager.cpp
Source/WebKit/WebProcess/EntryPoint/unix/WebProcessMain.cpp
Source/WebKit/WebProcess/gtk/WebProcessMainGtk.cpp
Source/WebKit/WebProcess/wpe/WebProcessMainWPE.cpp
Source/WebKitLegacy/ios/ChangeLog
Source/WebKitLegacy/ios/Misc/WebUIKitSupport.mm
Source/WebKitLegacy/mac/ChangeLog
Source/WebKitLegacy/mac/WebView/WebView.mm
Tools/ChangeLog
Tools/DumpRenderTree/mac/DumpRenderTree.mm
Tools/DumpRenderTree/win/DumpRenderTree.cpp
Tools/TestRunnerShared/IOSLayoutTestCommunication.cpp
Tools/TestWebKitAPI/Tests/WebKitGLib/TestAutomationSession.cpp
Tools/TestWebKitAPI/glib/WebKitGLib/TestMain.cpp
Tools/TestWebKitAPI/glib/WebKitGLib/WebKitTestBus.cpp
Tools/WebKitTestRunner/InjectedBundle/gtk/ActivateFontsGtk.cpp
Tools/WebKitTestRunner/InjectedBundle/gtk/InjectedBundleGtk.cpp
Tools/WebKitTestRunner/InjectedBundle/gtk/InjectedBundleUtilities.cpp
Tools/WebKitTestRunner/InjectedBundle/wpe/ActivateFontsWPE.cpp
Tools/WebKitTestRunner/TestController.cpp
Tools/WebKitTestRunner/TestController.h
Tools/WebKitTestRunner/cocoa/TestControllerCocoa.mm
Tools/WebKitTestRunner/gtk/main.cpp
Tools/WebKitTestRunner/mac/TestControllerMac.mm
Tools/WebKitTestRunner/wpe/main.cpp

index b45a448..afbce2c 100644 (file)
@@ -1,3 +1,26 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        * inspector/remote/glib/RemoteInspectorGlib.cpp:
+        (Inspector::RemoteInspector::RemoteInspector):
+        (Inspector::RemoteInspector::start):
+        * jsc.cpp:
+        (startTimeoutThreadIfNeeded):
+        * runtime/Options.cpp:
+        (JSC::overrideOptionWithHeuristic):
+        (JSC::Options::overrideAliasedOptionWithHeuristic):
+        (JSC::Options::initialize):
+        * runtime/VM.cpp:
+        (JSC::enableAssembler):
+        (JSC::VM::VM):
+        * tools/CodeProfiling.cpp:
+        (JSC::CodeProfiling::notifyAllocator):
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Mark Lam  <mark.lam@apple.com>
 
         SamplingProfiler::stackTracesAsJSON() should escape strings.
index c075698..629d2e9 100644 (file)
@@ -32,6 +32,7 @@
 #include "RemoteConnectionToTarget.h"
 #include "RemoteInspectionTarget.h"
 #include <gio/gio.h>
+#include <wtf/Environment.h>
 #include <wtf/NeverDestroyed.h>
 #include <wtf/RunLoop.h>
 #include <wtf/glib/GUniquePtr.h>
@@ -51,7 +52,7 @@ RemoteInspector& RemoteInspector::singleton()
 
 RemoteInspector::RemoteInspector()
 {
-    if (g_getenv("WEBKIT_INSPECTOR_SERVER"))
+    if (Environment::get("WEBKIT_INSPECTOR_SERVER"))
         start();
 }
 
@@ -65,7 +66,7 @@ void RemoteInspector::start()
     m_enabled = true;
     m_cancellable = adoptGRef(g_cancellable_new());
 
-    GUniquePtr<char> inspectorAddress(g_strdup(g_getenv("WEBKIT_INSPECTOR_SERVER")));
+    GUniquePtr<char> inspectorAddress(g_strdup(Environment::getRaw("WEBKIT_INSPECTOR_SERVER")));
     char* portPtr = g_strrstr(inspectorAddress.get(), ":");
     ASSERT(portPtr);
     *portPtr = '\0';
@@ -79,7 +80,7 @@ void RemoteInspector::start()
             if (GRefPtr<GDBusConnection> connection = adoptGRef(g_dbus_connection_new_for_address_finish(result, &error.outPtr())))
                 inspector->setupConnection(WTFMove(connection));
             else if (!g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
-                g_warning("RemoteInspector failed to connect to inspector server at: %s: %s", g_getenv("WEBKIT_INSPECTOR_SERVER"), error->message);
+                g_warning("RemoteInspector failed to connect to inspector server at: %s: %s", Environment::getRaw("WEBKIT_INSPECTOR_SERVER"), error->message);
     }, this);
 }
 
index 84440dc..37ff1d7 100644 (file)
@@ -83,6 +83,7 @@
 #include <type_traits>
 #include <wtf/Box.h>
 #include <wtf/CommaPrinter.h>
+#include <wtf/Environment.h>
 #include <wtf/MainThread.h>
 #include <wtf/MemoryPressureHandler.h>
 #include <wtf/MonotonicTime.h>
@@ -2348,9 +2349,11 @@ static double s_timeoutMultiplier = 1.0;
 
 static void startTimeoutThreadIfNeeded()
 {
-    if (char* timeoutString = getenv("JSCTEST_timeout")) {
-        if (sscanf(timeoutString, "%lf", &s_desiredTimeout) != 1) {
-            dataLog("WARNING: timeout string is malformed, got ", timeoutString,
+    if (auto timeoutString = Environment::get("JSCTEST_timeout")) {
+        bool ok;
+        s_desiredTimeout = timeoutString->toDouble(&ok);
+        if (!ok) {
+            dataLog("WARNING: timeout string is malformed, got ", *timeoutString,
                 " but expected a number. Not using a timeout.\n");
         } else {
             Thread::create("jsc Timeout Thread", [] () {
index 84d7326..84e8bb1 100644 (file)
@@ -39,6 +39,7 @@
 #include <wtf/ASCIICType.h>
 #include <wtf/Compiler.h>
 #include <wtf/DataLog.h>
+#include <wtf/Environment.h>
 #include <wtf/NumberOfCores.h>
 #include <wtf/PointerPreparations.h>
 #include <wtf/StdLibExtras.h>
@@ -176,7 +177,7 @@ bool overrideOptionWithHeuristic(T& variable, Options::ID id, const char* name,
     bool available = (availability == Options::Availability::Normal)
         || Options::isAvailable(id, availability);
 
-    const char* stringValue = getenv(name);
+    const char* stringValue = Environment::getRaw(name);
     if (!stringValue)
         return false;
     
@@ -189,12 +190,11 @@ bool overrideOptionWithHeuristic(T& variable, Options::ID id, const char* name,
 
 bool Options::overrideAliasedOptionWithHeuristic(const char* name)
 {
-    const char* stringValue = getenv(name);
+    const char* stringValue = Environment::getRaw(name);
     if (!stringValue)
         return false;
 
-    String aliasedOption;
-    aliasedOption = String(&name[4]) + "=" + stringValue;
+    auto aliasedOption = makeString(&name[4], "=", stringValue);
     if (Options::setOption(aliasedOption.utf8().data()))
         return true;
 
@@ -597,9 +597,9 @@ void Options::initialize()
 
 #if ASAN_ENABLED && OS(LINUX) && ENABLE(WEBASSEMBLY_FAST_MEMORY)
             if (Options::useWebAssemblyFastMemory()) {
-                const char* asanOptions = getenv("ASAN_OPTIONS");
+                auto asanOptions = Environment::get("ASAN_OPTIONS");
                 bool okToUseWebAssemblyFastMemory = asanOptions
-                    && (strstr(asanOptions, "allow_user_segv_handler=1") || strstr(asanOptions, "handle_segv=0"));
+                    && asanOptions->contains("allow_user_segv_handler=1") || asanOptions->contains("handle_segv=0");
                 if (!okToUseWebAssemblyFastMemory) {
                     dataLogLn("WARNING: ASAN interferes with JSC signal handlers; useWebAssemblyFastMemory will be disabled.");
                     Options::useWebAssemblyFastMemory() = false;
index 87ea244..79022d6 100644 (file)
 #include "WeakGCMapInlines.h"
 #include "WebAssemblyFunction.h"
 #include "WebAssemblyWrapperFunction.h"
+#include <wtf/Environment.h>
 #include <wtf/ProcessID.h>
 #include <wtf/ReadWriteLock.h>
 #include <wtf/SimpleStats.h>
@@ -197,8 +198,7 @@ static bool enableAssembler(ExecutableAllocator& executableAllocator)
         return false;
     }
 
-    char* canUseJITString = getenv("JavaScriptCoreUseJIT");
-    return !canUseJITString || atoi(canUseJITString);
+    return !Environment::hasValue("JavaScriptCoreUseJIT", "0");
 }
 #endif // ENABLE(!ASSEMBLER)
 
@@ -428,8 +428,7 @@ VM::VM(VMType vmType, HeapType heapType)
         m_perBytecodeProfiler = std::make_unique<Profiler::Database>(*this);
 
         StringPrintStream pathOut;
-        const char* profilerPath = getenv("JSC_PROFILER_PATH");
-        if (profilerPath)
+        if (const char* profilerPath = Environment::getRaw("JSC_PROFILER_PATH"))
             pathOut.print(profilerPath, "/");
         pathOut.print("JSCProfile-", getCurrentProcessID(), "-", m_perBytecodeProfiler->databaseID(), ".json");
         m_perBytecodeProfiler->registerToSaveAtExit(pathOut.toCString().data());
index 94ebe8e..f8ea799 100644 (file)
@@ -28,6 +28,7 @@
 
 #include "CodeProfile.h"
 #include "MachineContext.h"
+#include <wtf/Environment.h>
 #include <wtf/MetaAllocator.h>
 
 #if HAVE(SIGNAL_H)
@@ -85,21 +86,19 @@ void CodeProfiling::sample(void* pc, void** framePointer)
 void CodeProfiling::notifyAllocator(WTF::MetaAllocator* allocator)
 {
     // Check for JSC_CODE_PROFILING.
-    const char* codeProfilingMode = getenv("JSC_CODE_PROFILING");
+    auto codeProfilingMode = Environment::getUInt("JSC_CODE_PROFILING");
     if (!codeProfilingMode)
         return;
 
-    // Check for a valid mode, currently "1", "2", or "3".
-    if (!codeProfilingMode[0] || codeProfilingMode[1])
-        return;
+    // Check for a valid mode, currently 1, 2, or 3.
     switch (*codeProfilingMode) {
-    case '1':
+    case 1:
         s_mode = Enabled;
         break;
-    case '2':
+    case 2:
         s_mode = Verbose;
         break;
-    case '3':
+    case 3:
         s_mode = VeryVerbose;
         break;
     default:
index e182763..af99322 100644 (file)
@@ -1,3 +1,41 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        Create a new Environment API as a platform-independent, thread-safe(r)
+        way to get and set environment variables.
+
+        * WTF.xcodeproj/project.pbxproj:
+        * wtf/CMakeLists.txt:
+        * wtf/Environment.h: Added.
+        * wtf/PlatformGTK.cmake:
+        * wtf/PlatformJSCOnly.cmake:
+        * wtf/PlatformMac.cmake:
+        * wtf/PlatformPlayStation.cmake:
+        * wtf/PlatformWPE.cmake:
+        * wtf/PlatformWin.cmake:
+        * wtf/posix/EnvironmentPOSIX.cpp: Added.
+        * wtf/win/EnvironmentWin.cpp: Added.
+        Introduce WTF::Environment.
+
+        * wtf/Threading.cpp:
+        (WTF::threadingIsInitialized):
+        (WTF::initializeThreading):
+        * wtf/Threading.h:
+        Introduce WTF::threadingIsInitialized() so that we can ASSERT that it's
+        false before setting an environment variable through the new API.
+
+        * wtf/DataLog.cpp:
+        (WTF::initializeLogFileOnce):
+        * wtf/NumberOfCores.cpp:
+        (WTF::numberOfProcessorCores):
+        * wtf/posix/FileSystemPOSIX.cpp:
+        (WTF::FileSystemImpl::openTemporaryFile):
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Brian Burg  <bburg@apple.com>
 
         [Mac] WebInspectorUI.framework does not need to be soft-linked anymore
index e54641d..7e5ae22 100644 (file)
@@ -89,6 +89,7 @@
                93934BD518A1F16900D0D6A1 /* StringViewCF.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93934BD418A1F16900D0D6A1 /* StringViewCF.cpp */; };
                93F1993E19D7958D00C2390B /* StringView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 93F1993D19D7958D00C2390B /* StringView.cpp */; };
                9BC70F05176C379D00101DEC /* AtomicStringTable.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9BC70F04176C379D00101DEC /* AtomicStringTable.cpp */; };
+               A307FD29220CB4350021B62C /* EnvironmentPOSIX.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A307FD28220CB4350021B62C /* EnvironmentPOSIX.cpp */; };
                A32D8FA521FFFAB400780662 /* ThreadingPOSIX.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A32D8FA421FFFAB400780662 /* ThreadingPOSIX.cpp */; };
                A331D95B21F24992009F02AA /* FileSystem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A331D95A21F24992009F02AA /* FileSystem.cpp */; };
                A331D95D21F249E4009F02AA /* FileSystemCF.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A331D95C21F249E4009F02AA /* FileSystemCF.cpp */; };
                9BC70F04176C379D00101DEC /* AtomicStringTable.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AtomicStringTable.cpp; sourceTree = "<group>"; };
                9BD8F40A176C2AD80002D865 /* AtomicStringTable.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AtomicStringTable.h; sourceTree = "<group>"; };
                9C67C542589348E285B49699 /* IndexedContainerIterator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IndexedContainerIterator.h; sourceTree = "<group>"; };
+               A307FD28220CB4350021B62C /* EnvironmentPOSIX.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = EnvironmentPOSIX.cpp; sourceTree = "<group>"; };
+               A307FD2A220CB4490021B62C /* Environment.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Environment.h; sourceTree = "<group>"; };
                A30D412C1F0DE0BA00B71954 /* SoftLinking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SoftLinking.h; sourceTree = "<group>"; };
                A30D412D1F0DE13F00B71954 /* SoftLinking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SoftLinking.h; sourceTree = "<group>"; };
                A32D8FA421FFFAB400780662 /* ThreadingPOSIX.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ThreadingPOSIX.cpp; sourceTree = "<group>"; };
                A331D96321F24A2E009F02AA /* posix */ = {
                        isa = PBXGroup;
                        children = (
+                               A307FD28220CB4350021B62C /* EnvironmentPOSIX.cpp */,
                                A331D96621F24ABD009F02AA /* FileSystemPOSIX.cpp */,
                                A3EE5C3921FFAC5E00FABD61 /* OSAllocatorPOSIX.cpp */,
                                A32D8FA421FFFAB400780662 /* ThreadingPOSIX.cpp */,
                                FE05FAE61FDB214300093230 /* DumbPtrTraits.h */,
                                AD653DA82006B6C200D820D7 /* DumbValueTraits.h */,
                                1AEA88E11D6BBCF400E5AD64 /* EnumTraits.h */,
+                               A307FD2A220CB4490021B62C /* Environment.h */,
                                AD7C434A1DD2A4A70026888B /* Expected.h */,
                                A8A4729F151A825A004123FF /* ExportMacros.h */,
                                0F7C5FB51D885CF20044F5E2 /* FastBitVector.cpp */,
                                A8A472CE151A825B004123FF /* MetaAllocator.h */,
                                A8A472CF151A825B004123FF /* MetaAllocatorHandle.h */,
                                FE7497ED209163060003565B /* MetaAllocatorPtr.h */,
-                               5FAD3AE121B9636600BEE178 /* URLHelpers.cpp */,
-                               5FAD3AE021B9636600BEE178 /* URLHelpers.h */,
                                0F66B2821DC97BAB004A1D3F /* MonotonicTime.cpp */,
                                0F66B2831DC97BAB004A1D3F /* MonotonicTime.h */,
                                FE8225301B2A1E5B00BA68FD /* NakedPtr.h */,
                                5CC0EE7121629F1800A1A842 /* URL.h */,
                                5C1F0597216439940039302C /* URLHash.h */,
                                5CC0EE772162A01000A1A842 /* URLHash.h */,
+                               5FAD3AE121B9636600BEE178 /* URLHelpers.cpp */,
+                               5FAD3AE021B9636600BEE178 /* URLHelpers.h */,
                                5CC0EE7321629F1900A1A842 /* URLParser.cpp */,
                                5CC0EE7221629F1900A1A842 /* URLParser.h */,
                                7AFEC6B01EB22B5900DADE36 /* UUID.cpp */,
                                A8A473B0151A825B004123FF /* double-conversion.cc in Sources */,
                                A8A473BA151A825B004123FF /* dtoa.cpp in Sources */,
                                143DDE9620C8BC37007F76FA /* Entitlements.mm in Sources */,
+                               A307FD29220CB4350021B62C /* EnvironmentPOSIX.cpp in Sources */,
                                50DE35F5215BB01500B979C7 /* ExternalStringImpl.cpp in Sources */,
                                A8A473B3151A825B004123FF /* fast-dtoa.cc in Sources */,
                                0F7C5FB61D885CF20044F5E2 /* FastBitVector.cpp in Sources */,
                                5CC0EE8A2162BC2200A1A842 /* NSURLExtras.mm in Sources */,
                                A8A473F4151A825B004123FF /* NumberOfCores.cpp in Sources */,
                                8348BA0E21FBC0D500FD3054 /* ObjectIdentifier.cpp in Sources */,
-                               5FAD3AE221B9636600BEE178 /* URLHelpers.cpp in Sources */,
                                A3EE5C3A21FFAC5F00FABD61 /* OSAllocatorPOSIX.cpp in Sources */,
                                A8A473F9151A825B004123FF /* OSRandomSource.cpp in Sources */,
                                A8A47402151A825B004123FF /* PageBlock.cpp in Sources */,
                                5CC0EE7621629F1900A1A842 /* URL.cpp in Sources */,
                                5C1F0595216437B30039302C /* URLCF.cpp in Sources */,
                                5CC0EE892162BC2200A1A842 /* URLCocoa.mm in Sources */,
+                               5FAD3AE221B9636600BEE178 /* URLHelpers.cpp in Sources */,
                                5CC0EE7521629F1900A1A842 /* URLParser.cpp in Sources */,
                                1C181C8F1D307AB800F5FA16 /* UTextProvider.cpp in Sources */,
                                1C181C911D307AB800F5FA16 /* UTextProviderLatin1.cpp in Sources */,
index 1f12b79..8104da3 100644 (file)
@@ -55,6 +55,7 @@ set(WTF_PUBLIC_HEADERS
     DumbPtrTraits.h
     DumbValueTraits.h
     EnumTraits.h
+    Environment.h
     Expected.h
     ExportMacros.h
     FastBitVector.h
index 57f9eb2..3bcdd1a 100644 (file)
 #include "config.h"
 #include <wtf/DataLog.h>
 
+#include <mutex>
 #include <stdarg.h>
 #include <string.h>
+#include <thread>
+#include <wtf/Environment.h>
 #include <wtf/FilePrintStream.h>
 #include <wtf/LockedPrintStream.h>
 #include <wtf/ProcessID.h>
 #include <wtf/Threading.h>
-#include <mutex>
-#include <thread>
 
 #if OS(UNIX) || OS(DARWIN)
 #include <unistd.h>
@@ -93,7 +94,7 @@ static void initializeLogFileOnce()
 #elif defined(DATA_LOG_FILENAME)
     filename = DATA_LOG_FILENAME;
 #else
-    filename = getenv("WTF_DATA_LOG_FILENAME");
+    filename = Environment::getRaw("WTF_DATA_LOG_FILENAME");
 #endif
     char actualFilename[maxPathLength + 1];
 
diff --git a/Source/WTF/wtf/Environment.h b/Source/WTF/wtf/Environment.h
new file mode 100644 (file)
index 0000000..bb9e5be
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2019 Sony Interactive Entertainment Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <wtf/Optional.h>
+#include <wtf/text/WTFString.h>
+
+namespace WTF {
+namespace EnvironmentImpl {
+
+WTF_EXPORT_PRIVATE Optional<String> get(const String&);
+
+inline const char* getRaw(const String& variable)
+{
+    auto string = get(variable);
+    return string ? string->utf8().data() : nullptr;
+}
+
+inline Optional<int> getInt(const String& variable)
+{
+    auto string = get(variable);
+    if (!string)
+        return WTF::nullopt;
+
+    bool ok;
+    auto value = string->toIntStrict(&ok);
+    return ok ? makeOptional(value) : WTF::nullopt;
+}
+
+inline Optional<unsigned> getUInt(const String& variable)
+{
+    auto string = get(variable);
+    if (!string)
+        return WTF::nullopt;
+
+    bool ok;
+    auto value = string->toUIntStrict(&ok);
+    return ok ? makeOptional(value) : WTF::nullopt;
+}
+
+inline bool hasValue(const String& variable, const String& expected)
+{
+    auto actual = get(variable);
+    return actual && *actual == expected;
+}
+
+inline bool hasValueOtherThan(const String& variable, const String& expected)
+{
+    auto actual = get(variable);
+    return actual && *actual != expected;
+}
+
+WTF_EXPORT_PRIVATE void set(const String& variable, const String& value);
+WTF_EXPORT_PRIVATE void setIfNotDefined(const String& variable, const String& value);
+
+WTF_EXPORT_PRIVATE void remove(const String&);
+
+} // namespace EnvironmentImpl
+} // namespace WTF
+
+namespace Environment = WTF::EnvironmentImpl;
index 62fa65a..48a9cf2 100644 (file)
@@ -27,6 +27,7 @@
 #include <wtf/NumberOfCores.h>
 
 #include <cstdio>
+#include <wtf/Environment.h>
 
 #if OS(DARWIN)
 #include <sys/param.h>
@@ -49,14 +50,16 @@ int numberOfProcessorCores()
 
     if (s_numberOfCores > 0)
         return s_numberOfCores;
-    
-    if (const char* coresEnv = getenv("WTF_numberOfProcessorCores")) {
-        unsigned numberOfCores;
-        if (sscanf(coresEnv, "%u", &numberOfCores) == 1) {
+
+    if (auto coresEnv = Environment::get("WTF_numberOfProcessorCores")) {
+        bool ok;
+        auto numberOfCores = coresEnv->toUIntStrict(&ok);
+        if (ok) {
             s_numberOfCores = numberOfCores;
             return s_numberOfCores;
-        } else
-            fprintf(stderr, "WARNING: failed to parse WTF_numberOfProcessorCores=%s\n", coresEnv);
+        }
+
+        fprintf(stderr, "WARNING: failed to parse WTF_numberOfProcessorCores=%s\n", coresEnv->utf8().data());
     }
 
 #if OS(DARWIN)
index 297d0fa..b55d0ec 100644 (file)
@@ -28,6 +28,7 @@ list(APPEND WTF_SOURCES
     glib/RunLoopGLib.cpp
     glib/URLGLib.cpp
 
+    posix/EnvironmentPOSIX.cpp
     posix/OSAllocatorPOSIX.cpp
     posix/ThreadingPOSIX.cpp
 
index 3542fef..1932a7f 100644 (file)
@@ -8,6 +8,7 @@ if (WIN32)
 
         win/CPUTimeWin.cpp
         win/DbgHelperWin.cpp
+        win/EnvironmentWin.cpp
         win/FileSystemWin.cpp
         win/LanguageWin.cpp
         win/MainThreadWin.cpp
@@ -33,6 +34,7 @@ else ()
 
         generic/MainThreadGeneric.cpp
 
+        posix/EnvironmentPOSIX.cpp
         posix/FileSystemPOSIX.cpp
         posix/OSAllocatorPOSIX.cpp
         posix/ThreadingPOSIX.cpp
index 9a1f510..339f2bb 100644 (file)
@@ -64,6 +64,7 @@ list(APPEND WTF_SOURCES
     mac/FileSystemMac.mm
     mac/SchedulePairMac.mm
 
+    posix/EnvironmentPOSIX.cpp
     posix/FileSystemPOSIX.cpp
     posix/OSAllocatorPOSIX.cpp
     posix/ThreadingPOSIX.cpp
index 4b69190..fc4a29f 100644 (file)
@@ -5,6 +5,7 @@ list(APPEND WTF_SOURCES
     generic/RunLoopGeneric.cpp
     generic/WorkQueueGeneric.cpp
 
+    posix/EnvironmentPOSIX.cpp
     posix/FileSystemPOSIX.cpp
     posix/OSAllocatorPOSIX.cpp
     posix/ThreadingPOSIX.cpp
index 38e632c..eb5f739 100644 (file)
@@ -26,6 +26,7 @@ list(APPEND WTF_SOURCES
     linux/MemoryFootprintLinux.cpp
     linux/MemoryPressureHandlerLinux.cpp
 
+    posix/EnvironmentPOSIX.cpp
     posix/OSAllocatorPOSIX.cpp
     posix/ThreadingPOSIX.cpp
 
index 2c34022..f65e121 100644 (file)
@@ -12,6 +12,7 @@ list(APPEND WTF_SOURCES
 
     win/CPUTimeWin.cpp
     win/DbgHelperWin.cpp
+    win/EnvironmentWin.cpp
     win/FileSystemWin.cpp
     win/LanguageWin.cpp
     win/MainThreadWin.cpp
index 31e4ddc..a54575c 100644 (file)
@@ -285,10 +285,18 @@ void Thread::dump(PrintStream& out) const
 ThreadSpecificKey Thread::s_key = InvalidThreadSpecificKey;
 #endif
 
+static bool initialized = false;
+
+bool threadingIsInitialized()
+{
+    return initialized;
+}
+
 void initializeThreading()
 {
     static std::once_flag onceKey;
     std::call_once(onceKey, [] {
+        initialized = true;
         initializeRandomNumberGenerator();
 #if !HAVE(FAST_TLS)
         Thread::initializeTLSKey();
index 2d9242c..eee53ae 100644 (file)
@@ -61,6 +61,8 @@ enum class ThreadGroupAddResult;
 class ThreadGroup;
 class PrintStream;
 
+WTF_EXPORT_PRIVATE bool threadingIsInitialized();
+
 // This function can be called from any threads.
 WTF_EXPORT_PRIVATE void initializeThreading();
 
diff --git a/Source/WTF/wtf/posix/EnvironmentPOSIX.cpp b/Source/WTF/wtf/posix/EnvironmentPOSIX.cpp
new file mode 100644 (file)
index 0000000..35e7275
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2019 Sony Interactive Entertainment Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include <wtf/Environment.h>
+
+#include <cstdlib>
+#include <wtf/Assertions.h>
+#include <wtf/Threading.h>
+
+namespace WTF {
+namespace EnvironmentImpl {
+
+Optional<String> get(const String& variable)
+{
+    auto value = getenv(variable.utf8().data());
+    return value ? makeOptional(String::fromUTF8(value)) : WTF::nullopt;
+}
+
+void set(const String& variable, const String& value)
+{
+    ASSERT(!WTF::threadingIsInitialized());
+    setenv(variable.utf8().data(), value.utf8().data(), 1);
+}
+
+void setIfNotDefined(const String& variable, const String& value)
+{
+    ASSERT(!WTF::threadingIsInitialized());
+    setenv(variable.utf8().data(), value.utf8().data(), 0);
+}
+
+void remove(const String& variable)
+{
+    ASSERT(!WTF::threadingIsInitialized());
+    unsetenv(variable.utf8().data());
+}
+
+} // namespace EnvironmentImpl
+} // namespace WTF
index 70d2f98..dce9b37 100644 (file)
@@ -40,6 +40,7 @@
 #include <sys/types.h>
 #include <unistd.h>
 #include <wtf/EnumTraits.h>
+#include <wtf/Environment.h>
 #include <wtf/FileMetadata.h>
 #include <wtf/text/CString.h>
 #include <wtf/text/StringBuilder.h>
@@ -424,8 +425,8 @@ bool getVolumeFreeSpace(const String& path, uint64_t& freeSpace)
 String openTemporaryFile(const String& prefix, PlatformFileHandle& handle)
 {
     char buffer[PATH_MAX];
-    const char* tmpDir = getenv("TMPDIR");
 
+    const char* tmpDir = Environment::getRaw("TMPDIR");
     if (!tmpDir)
         tmpDir = "/tmp";
 
diff --git a/Source/WTF/wtf/win/EnvironmentWin.cpp b/Source/WTF/wtf/win/EnvironmentWin.cpp
new file mode 100644 (file)
index 0000000..a36b966
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2019 Sony Interactive Entertainment Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include <wtf/Environment.h>
+
+#include <windows.h>
+#include <wtf/Assertions.h>
+#include <wtf/Threading.h>
+#include <wtf/Vector.h>
+
+namespace WTF {
+namespace EnvironmentImpl {
+
+Optional<String> get(const String& variable)
+{
+    auto rawVariable = variable.charactersWithNullTermination().data();
+    auto length = ::GetEnvironmentVariableW(rawVariable, nullptr, 0);
+    if (!length)
+        return WTF::nullopt;
+
+    Vector<UChar> buffer(length);
+    return ::GetEnvironmentVariableW(rawVariable, buffer.data(), length) ? makeOptional(String(buffer.data())) : WTF::nullopt;
+}
+
+void set(const String& variable, const String& value)
+{
+    ASSERT(!WTF::threadingIsInitialized());
+    ::SetEnvironmentVariableW(variable.charactersWithNullTermination().data(), value.charactersWithNullTermination().data());
+}
+
+void setIfNotDefined(const String& variable, const String& value)
+{
+    ASSERT(!WTF::threadingIsInitialized());
+    if (get(variable))
+        return;
+
+    set(variable, value);
+}
+
+void remove(const String& variable)
+{
+    ASSERT(!WTF::threadingIsInitialized());
+    ::SetEnvironmentVariableW(variable.charactersWithNullTermination().data(), nullptr);
+}
+
+} // namespace EnvironmentImpl
+} // namespace WTF
index c4b5bc8..9258ebe 100644 (file)
@@ -1,3 +1,50 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        * platform/NotImplemented.h:
+        * platform/cocoa/SystemVersion.mm:
+        (WebCore::createSystemMarketingVersion):
+        * platform/graphics/gstreamer/GStreamerCommon.cpp:
+        (WebCore::initializeGStreamer):
+        * platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp:
+        (WebCore::MediaPlayerPrivateGStreamer::createGSTPlayBin):
+        * platform/graphics/nicosia/NicosiaPaintingEngine.cpp:
+        (Nicosia::PaintingEngine::create):
+        * platform/graphics/texmap/TextureMapperFPSCounter.cpp:
+        (WebCore::TextureMapperFPSCounter::TextureMapperFPSCounter):
+        * platform/graphics/x11/PlatformDisplayX11.cpp:
+        (WebCore::PlatformDisplayX11::create):
+        * platform/gtk/RenderThemeWidget.cpp:
+        (WebCore::RenderThemeScrollbar::RenderThemeScrollbar):
+        * platform/gtk/ScrollbarThemeGtk.cpp:
+        (WebCore::ScrollbarThemeGtk::ScrollbarThemeGtk):
+        * platform/network/curl/CurlContext.cpp:
+        (WebCore::CurlContext::CurlContext):
+        (WebCore::EnvironmentVariableReader::read): Deleted.
+        (WebCore::EnvironmentVariableReader::defined): Deleted.
+        (WebCore::EnvironmentVariableReader::readAs): Deleted.
+        (WebCore::EnvironmentVariableReader::sscanTemplate): Deleted.
+        (WebCore::EnvironmentVariableReader::sscanTemplate<signed>): Deleted.
+        (WebCore::EnvironmentVariableReader::sscanTemplate<unsigned>): Deleted.
+        * platform/network/curl/NetworkStorageSessionCurl.cpp:
+        (WebCore::defaultCookieJarPath):
+        * platform/network/playstation/CurlSSLHandlePlayStation.cpp:
+        (WebCore::getCACertPathEnv):
+        * platform/network/win/CurlSSLHandleWin.cpp:
+        (WebCore::getCACertPathEnv):
+        * platform/text/hyphen/HyphenationLibHyphen.cpp:
+        (WebCore::topLevelPath):
+        (WebCore::webkitBuildDirectory):
+        * platform/unix/LoggingUnix.cpp:
+        (WebCore::logLevelString):
+        * platform/win/LoggingWin.cpp:
+        (WebCore::logLevelString):
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Antoine Quint  <graouts@apple.com>
 
         Add a method to dispatch a PointerEvent based on a PlatformTouchEvent
index 73e3c9f..cb28b2c 100644 (file)
@@ -1,3 +1,16 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        * pal/unix/LoggingUnix.cpp:
+        (PAL::logLevelString):
+        * pal/win/LoggingWin.cpp:
+        (PAL::logLevelString):
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Commit Queue  <commit-queue@webkit.org>
 
         Unreviewed, rolling out r241559 and r241566.
index 24734f9..a432bf7 100644 (file)
 #include "config.h"
 #include "Logging.h"
 
-#include <wtf/text/WTFString.h>
-
 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
 
+#include <wtf/Environment.h>
+#include <wtf/text/WTFString.h>
+
 namespace PAL {
 
 String logLevelString()
 {
 #if !LOG_DISABLED
-    if (char* logEnv = getenv("WEBKIT_DEBUG")) {
+    auto logEnv = Environment::get("WEBKIT_DEBUG");
+    if (!logEnv)
+        return emptyString();
 
 #if defined(NDEBUG)
-        WTFLogAlways("WEBCORE_DEBUG is not empty, but this is a release build. Notice that many log messages will only appear in a debug build.");
+    WTFLogAlways("WEBKIT_DEBUG is not empty, but this is a release build. Notice that many log messages will only appear in a debug build.");
 #endif
 
-        // To disable logging notImplemented set the DISABLE_NI_WARNING environment variable to 1.
-        return makeString("NotYetImplemented,"_s, logEnv);
-    }
-#endif
+    // To disable logging notImplemented set the DISABLE_NI_WARNING environment variable to 1.
+    return makeString("NotYetImplemented,", *logEnv);
+#else
     return String();
+#endif
 }
 
 } // namespace PAL
index 6b232c4..b68cc94 100644 (file)
@@ -29,7 +29,7 @@
 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
 
 #include <windows.h>
-#include <wtf/StdLibExtras.h>
+#include <wtf/Environment.h>
 #include <wtf/text/WTFString.h>
 
 namespace PAL {
@@ -37,17 +37,7 @@ namespace PAL {
 String logLevelString()
 {
 #if !LOG_DISABLED
-    static char* const loggingEnvironmentVariable = "WebCoreLogging";
-    DWORD length = GetEnvironmentVariableA(loggingEnvironmentVariable, 0, 0);
-    if (!length)
-        return emptyString();
-
-    Vector<char> buffer(length);
-
-    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.data(), length))
-        return emptyString();
-
-    return String(buffer.data());
+    return Environment::get("WebCoreLogging").valueOr(emptyString());
 #else
     return String();
 #endif
index 72af706..250d433 100644 (file)
 #define NotImplemented_h
 
 #include <wtf/Assertions.h>
+#include <wtf/Environment.h>
 
 #if PLATFORM(GTK)
-    #define suppressNotImplementedWarning() getenv("DISABLE_NI_WARNING")
+#define suppressNotImplementedWarning() Environment::get("DISABLE_NI_WARNING")
 #else
-    #define suppressNotImplementedWarning() false
+#define suppressNotImplementedWarning() false
 #endif
 
 #if LOG_DISABLED
-    #define notImplemented() ((void)0)
+#define notImplemented() ((void)0)
 #else
 
 namespace WebCore {
index d4c4f5a..3fac83d 100644 (file)
@@ -25,6 +25,8 @@
 #include "config.h"
 #include "SystemVersion.h"
 
+#include <wtf/Environment.h>
+
 namespace WebCore {
 
 static NSString *createSystemMarketingVersion()
@@ -32,7 +34,7 @@ static NSString *createSystemMarketingVersion()
     // Can't use -[NSProcessInfo operatingSystemVersionString] because it has too much stuff we don't want.
     NSString *systemLibraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSSystemDomainMask, YES) objectAtIndex:0];
 #if PLATFORM(IOS_FAMILY_SIMULATOR)
-    if (char *simulatorRoot = getenv("SIMULATOR_ROOT"))
+    if (const char* simulatorRoot = Environment::getRaw("SIMULATOR_ROOT"))
         systemLibraryPath = [NSString stringWithFormat:@"%s/%@", simulatorRoot, systemLibraryPath];
 #endif
     NSString *systemVersionPlistPath = [systemLibraryPath stringByAppendingPathComponent:@"CoreServices/SystemVersion.plist"];
index 1fa4c4c..29f23ba 100644 (file)
@@ -29,6 +29,7 @@
 #include <gst/audio/audio-info.h>
 #include <gst/gst.h>
 #include <mutex>
+#include <wtf/Environment.h>
 #include <wtf/glib/GLibUtilities.h>
 #include <wtf/glib/GUniquePtr.h>
 #include <wtf/glib/RunLoopSourcePriority.h>
@@ -237,8 +238,7 @@ bool initializeGStreamer(Optional<Vector<String>>&& options)
         g_strfreev(argv);
 
         if (isFastMallocEnabled()) {
-            const char* disableFastMalloc = getenv("WEBKIT_GST_DISABLE_FAST_MALLOC");
-            if (!disableFastMalloc || !strcmp(disableFastMalloc, "0"))
+            if (!Environment::hasValue("WEBKIT_GST_DISABLE_FAST_MALLOC", "0"))
                 gst_allocator_set_default(GST_ALLOCATOR(g_object_new(gst_allocator_fast_malloc_get_type(), nullptr)));
         }
 
index d458f1a..9e50cdc 100644 (file)
@@ -42,6 +42,7 @@
 #include <gst/gst.h>
 #include <gst/pbutils/missing-plugins.h>
 #include <limits>
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/HexNumber.h>
 #include <wtf/MediaTime.h>
@@ -2417,7 +2418,7 @@ void MediaPlayerPrivateGStreamer::createGSTPlayBin(const gchar* playbinName, con
     ASSERT(!m_pipeline);
 
 #if GST_CHECK_VERSION(1, 10, 0)
-    if (g_getenv("USE_PLAYBIN3"))
+    if (Environment::get("USE_PLAYBIN3"))
         playbinName = "playbin3";
 #else
     playbinName = "playbin";
index 07ae7a2..6263266 100644 (file)
 
 #include "NicosiaPaintingEngineBasic.h"
 #include "NicosiaPaintingEngineThreaded.h"
+#include <wtf/Environment.h>
 
 namespace Nicosia {
 
 std::unique_ptr<PaintingEngine> PaintingEngine::create()
 {
 #if ENABLE(DEVELOPER_MODE) && PLATFORM(WPE)
-    if (const char* numThreadsEnv = getenv("WEBKIT_NICOSIA_PAINTING_THREADS")) {
-        unsigned numThreads = 0;
-        if (sscanf(numThreadsEnv, "%u", &numThreads) == 1) {
+    if (auto numThreadsEnv = Environment::get("WEBKIT_NICOSIA_PAINTING_THREADS")) {
+        bool ok;
+        auto numThreads = numThreadsEnv->toIntStrict(&ok);
+        if (ok) {
             if (numThreads < 1 || numThreads > 8) {
                 WTFLogAlways("The number of Nicosia painting threads is not between 1 and 8. Using the default value 4\n");
                 numThreads = 4;
index c8cac48..6e51984 100644 (file)
 */
 
 #include "config.h"
-
 #include "TextureMapperFPSCounter.h"
 
 #include "TextureMapper.h"
+#include <wtf/Environment.h>
 #include <wtf/text/WTFString.h>
 
 namespace WebCore {
@@ -34,12 +34,13 @@ TextureMapperFPSCounter::TextureMapperFPSCounter()
     , m_lastFPS(0)
     , m_frameCount(0)
 {
-    String showFPSEnvironment = getenv("WEBKIT_SHOW_FPS");
-    bool ok = false;
-    m_fpsInterval = Seconds(showFPSEnvironment.toDouble(&ok));
-    if (ok && m_fpsInterval) {
-        m_isShowingFPS = true;
-        m_fpsTimestamp = MonotonicTime::now();
+    if (auto showFPSEnvironment = Environment::get("WEBKIT_SHOW_FPS")) {
+        bool ok;
+        m_fpsInterval = Seconds(showFPSEnvironment->toDouble(&ok));
+        if (ok && m_fpsInterval) {
+            m_isShowingFPS = true;
+            m_fpsTimestamp = MonotonicTime::now();
+        }
     }
 }
 
index 8c81119..86a0652 100644 (file)
@@ -27,6 +27,7 @@
 #include "PlatformDisplayX11.h"
 
 #include "GLContext.h"
+#include <wtf/Environment.h>
 
 #if PLATFORM(X11)
 #include <X11/Xlib.h>
@@ -44,7 +45,7 @@ namespace WebCore {
 
 std::unique_ptr<PlatformDisplay> PlatformDisplayX11::create()
 {
-    Display* display = XOpenDisplay(getenv("DISPLAY"));
+    Display* display = XOpenDisplay(Environment::getRaw("DISPLAY"));
     if (!display)
         return nullptr;
 
index b72c107..d85dca1 100644 (file)
@@ -28,6 +28,7 @@
 
 #if GTK_CHECK_VERSION(3, 20, 0)
 
+#include <wtf/Environment.h>
 #include <wtf/HashMap.h>
 #include <wtf/NeverDestroyed.h>
 
@@ -109,7 +110,7 @@ RenderThemeScrollbar::RenderThemeScrollbar(GtkOrientation orientation, Mode mode
         info.classList.append("horizontal");
         info.classList.append("bottom");
     }
-    static bool usesOverlayScrollbars = g_strcmp0(g_getenv("GTK_OVERLAY_SCROLLING"), "0");
+    static bool usesOverlayScrollbars = !Environment::hasValue("GTK_OVERLAY_SCROLLING", "0");
     if (usesOverlayScrollbars)
         info.classList.append("overlay-indicator");
     if (mode == Mode::Full)
index 209af7b..c3323b5 100644 (file)
@@ -35,6 +35,7 @@
 #include "Scrollbar.h"
 #include <cstdlib>
 #include <gtk/gtk.h>
+#include <wtf/Environment.h>
 
 namespace WebCore {
 
@@ -55,7 +56,7 @@ static void themeChangedCallback()
 ScrollbarThemeGtk::ScrollbarThemeGtk()
 {
 #if GTK_CHECK_VERSION(3, 20, 0)
-    m_usesOverlayScrollbars = g_strcmp0(g_getenv("GTK_OVERLAY_SCROLLING"), "0");
+    m_usesOverlayScrollbars = !Environment::hasValue("GTK_OVERLAY_SCROLLING", "0");
 #endif
     static bool themeMonitorInitialized = false;
     if (!themeMonitorInitialized) {
index 0ce1100..a2b8e8d 100644 (file)
@@ -35,6 +35,7 @@
 #include "HTTPHeaderMap.h"
 #include <NetworkLoadMetrics.h>
 #include <mutex>
+#include <wtf/Environment.h>
 #include <wtf/MainThread.h>
 #include <wtf/NeverDestroyed.h>
 #include <wtf/text/CString.h>
 
 namespace WebCore {
 
-class EnvironmentVariableReader {
-public:
-    const char* read(const char* name) { return ::getenv(name); }
-    bool defined(const char* name) { return read(name) != nullptr; }
-
-    template<typename T> Optional<T> readAs(const char* name)
-    {
-        if (const char* valueStr = read(name)) {
-            T value;
-            if (sscanf(valueStr, sscanTemplate<T>(), &value) == 1)
-                return value;
-        }
-
-        return WTF::nullopt;
-    }
-
-private:
-    template<typename T> const char* sscanTemplate()
-    {
-        ASSERT_NOT_REACHED();
-        return nullptr;
-    }
-};
-
-template<>
-constexpr const char* EnvironmentVariableReader::sscanTemplate<signed>() { return "%d"; }
-
-template<>
-constexpr const char* EnvironmentVariableReader::sscanTemplate<unsigned>() { return "%u"; }
-
 // ALPN Protocol ID (RFC7301) https://tools.ietf.org/html/rfc7301
 static const ASCIILiteral httpVersion10 { "http/1.0"_s };
 static const ASCIILiteral httpVersion11 { "http/1.1"_s };
@@ -94,34 +65,31 @@ CurlContext::CurlContext()
 {
     initShareHandle();
 
-    EnvironmentVariableReader envVar;
-
-    if (auto value = envVar.readAs<unsigned>("WEBKIT_CURL_DNS_CACHE_TIMEOUT"))
+    if (auto value = Environment::getUInt("WEBKIT_CURL_DNS_CACHE_TIMEOUT"))
         m_dnsCacheTimeout = Seconds(*value);
 
-    if (auto value = envVar.readAs<unsigned>("WEBKIT_CURL_CONNECT_TIMEOUT"))
+    if (auto value = Environment::getUInt("WEBKIT_CURL_CONNECT_TIMEOUT"))
         m_connectTimeout = Seconds(*value);
 
     long maxConnects { CurlDefaultMaxConnects };
     long maxTotalConnections { CurlDefaultMaxTotalConnections };
     long maxHostConnections { CurlDefaultMaxHostConnections };
 
-    if (auto value = envVar.readAs<signed>("WEBKIT_CURL_MAXCONNECTS"))
+    if (auto value = Environment::getInt("WEBKIT_CURL_MAXCONNECTS"))
         maxConnects = *value;
 
-    if (auto value = envVar.readAs<signed>("WEBKIT_CURL_MAX_TOTAL_CONNECTIONS"))
+    if (auto value = Environment::getInt("WEBKIT_CURL_MAX_TOTAL_CONNECTIONS"))
         maxTotalConnections = *value;
 
-    if (auto value = envVar.readAs<signed>("WEBKIT_CURL_MAX_HOST_CONNECTIONS"))
+    if (auto value = Environment::getInt("WEBKIT_CURL_MAX_HOST_CONNECTIONS"))
         maxHostConnections = *value;
 
     m_scheduler = std::make_unique<CurlRequestScheduler>(maxConnects, maxTotalConnections, maxHostConnections);
 
 #ifndef NDEBUG
-    m_verbose = envVar.defined("DEBUG_CURL");
+    m_verbose = !!Environment::get("DEBUG_CURL");
 
-    auto logFile = envVar.read("CURL_LOG_FILE");
-    if (logFile)
+    if (const char* logFile = Environment::getRaw("CURL_LOG_FILE"))
         m_logFile = fopen(logFile, "a");
 #endif
 }
index 1ac4e02..c33e922 100644 (file)
@@ -35,6 +35,7 @@
 #include "CurlContext.h"
 #include "NetworkingContext.h"
 #include "ResourceHandle.h"
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/MainThread.h>
 #include <wtf/NeverDestroyed.h>
@@ -46,9 +47,8 @@ namespace WebCore {
 static String defaultCookieJarPath()
 {
     static const char* defaultFileName = "cookie.jar.db";
-    char* cookieJarPath = getenv("CURL_COOKIE_JAR_PATH");
-    if (cookieJarPath)
-        return cookieJarPath;
+    if (auto cookieJarPath = Environment::get("CURL_COOKIE_JAR_PATH"))
+        return *cookieJarPath;
 
 #if PLATFORM(WIN)
     return FileSystem::pathByAppendingComponent(FileSystem::localUserSpecificStorageDirectory(), defaultFileName);
index 3e1e287..844aa66 100644 (file)
 #include "config.h"
 #include "CurlSSLHandle.h"
 
+#include <wtf/Environment.h>
+
 namespace WebCore {
 
 static String getCACertPathEnv()
 {
-    char* envPath = getenv("CURL_CA_BUNDLE_PATH");
-    if (envPath)
-        return { envPath };
-
-    return emptyString();
+    return Environment::get("CURL_CA_BUNDLE_PATH").valueOr(emptyString());
 }
 
 void CurlSSLHandle::platformInitialize()
index 47c88ba..395093f 100644 (file)
@@ -26,6 +26,8 @@
 #include "config.h"
 #include "CurlSSLHandle.h"
 
+#include <wtf/Environment.h>
+
 #if USE(CF)
 #if OS(WINDOWS)
 #include "WebCoreBundleWin.h"
@@ -38,9 +40,8 @@ namespace WebCore {
 
 static String getCACertPathEnv()
 {
-    char* envPath = getenv("CURL_CA_BUNDLE_PATH");
-    if (envPath)
-        return String(envPath);
+    if (auto envPath = Environment::get("CURL_CA_BUNDLE_PATH"))
+        return *envPath;
 
 #if USE(CF)
     CFBundleRef webKitBundleRef = webKitBundle();
index 5eeb9bf..5650df4 100644 (file)
@@ -32,6 +32,7 @@
 #include <hyphen.h>
 #include <limits>
 #include <stdlib.h>
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/HashMap.h>
 #include <wtf/NeverDestroyed.h>
@@ -87,8 +88,8 @@ static void scanDirectoryForDictionaries(const char* directoryPath, HashMap<Atom
 #if ENABLE(DEVELOPER_MODE)
 static CString topLevelPath()
 {
-    if (const char* topLevelDirectory = g_getenv("WEBKIT_TOP_LEVEL"))
-        return topLevelDirectory;
+    if (auto topLevelDirectory = Environment::get("WEBKIT_TOP_LEVEL"))
+        return topLevelDirectory->utf8();
 
     // If the environment variable wasn't provided then assume we were built into
     // WebKitBuild/Debug or WebKitBuild/Release. Obviously this will fail if the build
@@ -101,9 +102,8 @@ static CString topLevelPath()
 
 static CString webkitBuildDirectory()
 {
-    const char* webkitOutputDir = g_getenv("WEBKIT_OUTPUTDIR");
-    if (webkitOutputDir)
-        return webkitOutputDir;
+    if (auto webkitOutputDir = Environment::get("WEBKIT_OUTPUTDIR"))
+        return webkitOutputDir->utf8();
 
     GUniquePtr<char> outputDir(g_build_filename(topLevelPath().data(), "WebKitBuild", nullptr));
     return outputDir.get();
index b72ad23..0d1e5a0 100644 (file)
@@ -24,7 +24,7 @@
 
 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
 
-#include <string.h>
+#include <wtf/Environment.h>
 #include <wtf/text/WTFString.h>
 
 namespace WebCore {
@@ -32,7 +32,7 @@ namespace WebCore {
 String logLevelString()
 {
 #if !LOG_DISABLED
-    char* logEnv = getenv("WEBKIT_DEBUG");
+    auto logEnv = Environment::get("WEBKIT_DEBUG");
     if (!logEnv)
         return emptyString();
 
@@ -42,7 +42,7 @@ String logLevelString()
 #endif
 
     // To disable logging notImplemented set the DISABLE_NI_WARNING environment variable to 1.
-    return String("NotYetImplemented,") + logEnv;
+    return makeString("NotYetImplemented,", *logEnv);
 #else
     return String();
 #endif
index e6c444e..c158ed7 100644 (file)
@@ -29,7 +29,7 @@
 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
 
 #include <windows.h>
-#include <wtf/StdLibExtras.h>
+#include <wtf/Environment.h>
 #include <wtf/text/WTFString.h>
 
 namespace WebCore {
@@ -37,17 +37,7 @@ namespace WebCore {
 String logLevelString()
 {
 #if !LOG_DISABLED
-    static char* const loggingEnvironmentVariable = "WebCoreLogging";
-    DWORD length = GetEnvironmentVariableA(loggingEnvironmentVariable, 0, 0);
-    if (!length)
-        return emptyString();
-
-    Vector<char> buffer(length);
-
-    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.data(), length))
-        return emptyString();
-
-    return String(buffer.data());
+    return Environment::get("WebCoreLogging").valueOr(emptyString());
 #else
     return String();
 #endif
index 4d1d051..ffcd4b2 100644 (file)
@@ -1,3 +1,61 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        * NetworkProcess/EntryPoint/unix/NetworkProcessMain.cpp:
+        (main):
+        * Platform/unix/LoggingUnix.cpp:
+        (WebKit::logLevelString):
+        * Platform/win/LoggingWin.cpp:
+        (WebKit::logLevelString):
+        * PluginProcess/mac/PluginProcessMac.mm:
+        (WebKit::shouldCallRealDebugger):
+        * Shared/Plugins/unix/PluginSearchPath.cpp:
+        (WebKit::pluginsDirectories):
+        * Shared/glib/ProcessExecutablePathGLib.cpp:
+        (WebKit::findWebKitProcess):
+        * UIProcess/API/glib/WebKitSettings.cpp:
+        (webKitSettingsConstructed):
+        (webKitSettingsSetProperty):
+        * UIProcess/API/glib/WebKitWebContext.cpp:
+        (injectedBundleDirectory):
+        (webkitWebContextConstructed):
+        * UIProcess/API/gtk/WebKitWebViewGtk.cpp:
+        (webkitWebViewMaximizeWindow):
+        (webkitWebViewRestoreWindow):
+        * UIProcess/API/wpe/WPEView.cpp:
+        (WKWPE::m_backend):
+        * UIProcess/AuxiliaryProcessProxy.cpp:
+        (WebKit::AuxiliaryProcessProxy::getLaunchOptions):
+        * UIProcess/Launcher/glib/BubblewrapLauncher.cpp:
+        (WebKit::XDGDBusProxyLauncher::launch):
+        (WebKit::bindDBusSession):
+        (WebKit::bindX11):
+        (WebKit::bindWayland):
+        (WebKit::bindPulse):
+        (WebKit::bindPathVar):
+        (WebKit::bindGStreamerData):
+        (WebKit::bubblewrapSpawn):
+        * UIProcess/Launcher/glib/ProcessLauncherGLib.cpp:
+        (WebKit::ProcessLauncher::launchProcess):
+        * UIProcess/Launcher/mac/ProcessLauncherMac.mm:
+        (WebKit::systemDirectoryPath):
+        (WebKit::ProcessLauncher::launchProcess):
+        * UIProcess/glib/WebProcessPoolGLib.cpp:
+        (WebKit::memoryPressureMonitorDisabled):
+        (WebKit::WebProcessPool::platformInitialize):
+        (WebKit::WebProcessPool::platformInitializeWebProcess):
+        * UIProcess/gtk/HardwareAccelerationManager.cpp:
+        (WebKit::HardwareAccelerationManager::HardwareAccelerationManager):
+        * WebProcess/EntryPoint/unix/WebProcessMain.cpp:
+        (main):
+        * WebProcess/gtk/WebProcessMainGtk.cpp:
+        * WebProcess/wpe/WebProcessMainWPE.cpp:
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Alex Christensen  <achristensen@webkit.org>
 
         Add SPI version of WKPreferences.safeBrowsingEnabled
index 736c017..95f9f6b 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "config.h"
 #include "NetworkProcessMainUnix.h"
 
-#include <cstdlib>
+#include <wtf/Environment.h>
 
 #if USE(GCRYPT)
 #include <pal/crypto/gcrypt/Initialization.h>
@@ -43,7 +44,7 @@ int main(int argc, char** argv)
     // overwrite this priority string if it's already set by the user.
     // https://bugzilla.gnome.org/show_bug.cgi?id=738633
     // WARNING: This needs to be KEPT IN SYNC with WebProcessMain.cpp.
-    setenv("G_TLS_GNUTLS_PRIORITY", "NORMAL:%COMPAT:!VERS-SSL3.0:!ARCFOUR-128", 0);
+    Environment::setIfNotDefined("G_TLS_GNUTLS_PRIORITY", "NORMAL:%COMPAT:!VERS-SSL3.0:!ARCFOUR-128");
 
 #if USE(GCRYPT)
     PAL::GCrypt::initialize();
index 5b17b3b..09c1fca 100644 (file)
 #include "config.h"
 #include "Logging.h"
 
-namespace WebKit {
-
 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
 
+#include <wtf/Environment.h>
+#include <wtf/text/WTFString.h>
+
+namespace WebKit {
+
 String logLevelString()
 {
 #if !LOG_DISABLED
-    return getenv("WEBKIT_DEBUG");
+    return Environment::get("WEBKIT_DEBUG").valueOr(emptyString());
 #else
     return String();
 #endif
 }
 
-#endif // !LOG_DISABLED || !RELEASE_LOG_DISABLED
+} // namespace WebKit
 
-}
+#endif // !LOG_DISABLED || !RELEASE_LOG_DISABLED
index 69b0a5c..31fd1be 100644 (file)
@@ -30,7 +30,7 @@
 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
 
 #include <windows.h>
-#include <wtf/StdLibExtras.h>
+#include <wtf/Environment.h>
 #include <wtf/text/WTFString.h>
 
 namespace WebKit {
@@ -38,18 +38,7 @@ namespace WebKit {
 String logLevelString()
 {
 #if !LOG_DISABLED
-    static char* const loggingEnvironmentVariable = "WebKitLogging";
-
-    DWORD length = GetEnvironmentVariableA(loggingEnvironmentVariable, 0, 0);
-    if (!length)
-        return emptyString();
-
-    Vector<char> buffer(length);
-
-    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.data(), length))
-        return emptyString();
-
-    return String(buffer.data());
+    return Environment::get("WebKitLogging").valueOr(emptyString());
 #else
     return String();
 #endif
index 1054e43..8d14144 100644 (file)
@@ -53,6 +53,7 @@
 #import <pal/spi/mac/NSApplicationSPI.h>
 #import <pal/spi/mac/NSWindowSPI.h>
 #import <sysexits.h>
+#import <wtf/Environment.h>
 #import <wtf/HashSet.h>
 #import <wtf/NeverDestroyed.h>
 
@@ -168,10 +169,8 @@ static bool shouldCallRealDebugger()
     static bool isUserbreakSet = false;
     static dispatch_once_t flag;
     dispatch_once(&flag, ^{
-        char* var = getenv("USERBREAK");
-
-        if (var)
-            isUserbreakSet = atoi(var);
+        if (auto var = Environment::getInt("USERBREAK"))
+            isUserbreakSet = *var;
     });
     
     return isUserbreakSet;
index 2bd549a..3db3fd1 100644 (file)
@@ -26,6 +26,7 @@
 #include "config.h"
 #include "PluginSearchPath.h"
 
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 
 namespace WebKit {
@@ -36,15 +37,15 @@ Vector<String> pluginsDirectories()
     Vector<String> result;
 
 #if ENABLE(NETSCAPE_PLUGIN_API)
-    String mozillaPaths(getenv("MOZ_PLUGIN_PATH"));
-    if (!mozillaPaths.isEmpty()) {
-        Vector<String> paths = mozillaPaths.split(':');
+    auto mozillaPaths = Environment::get("MOZ_PLUGIN_PATH");
+    if (mozillaPaths && !mozillaPaths->isEmpty()) {
+        Vector<String> paths = mozillaPaths->split(':');
         result.appendVector(paths);
     }
 
-    String mozillaHome(getenv("MOZILLA_HOME"));
-    if (!mozillaHome.isEmpty())
-        result.append(mozillaHome + "/plugins");
+    auto mozillaHome = Environment::get("MOZILLA_HOME");
+    if (mozillaHome && !mozillaHome->isEmpty())
+        result.append(*mozillaHome + "/plugins");
 
     result.append(FileSystem::homeDirectoryPath() + "/.mozilla/plugins");
     result.append(FileSystem::homeDirectoryPath() + "/.netscape/plugins");
index 4ff35d3..a29cd02 100644 (file)
@@ -28,6 +28,7 @@
 #include "ProcessExecutablePath.h"
 
 #include <glib.h>
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/glib/GLibUtilities.h>
 
@@ -46,9 +47,9 @@ static String getExecutablePath()
 static String findWebKitProcess(const char* processName)
 {
 #if ENABLE(DEVELOPER_MODE)
-    static const char* execDirectory = g_getenv("WEBKIT_EXEC_PATH");
+    static auto execDirectory = Environment::get("WEBKIT_EXEC_PATH");
     if (execDirectory) {
-        String processPath = FileSystem::pathByAppendingComponent(FileSystem::stringFromFileSystemRepresentation(execDirectory), processName);
+        String processPath = FileSystem::pathByAppendingComponent(FileSystem::stringFromFileSystemRepresentation(execDirectory->utf8().data()), processName);
         if (FileSystem::fileExists(processPath))
             return processPath;
     }
index 03654dd..a4119f0 100644 (file)
@@ -40,6 +40,7 @@
 #include <WebCore/UserAgent.h>
 #include <cmath>
 #include <glib/gi18n-lib.h>
+#include <wtf/Environment.h>
 #include <wtf/glib/WTFGType.h>
 #include <wtf/text/CString.h>
 
@@ -183,7 +184,7 @@ static void webKitSettingsConstructed(GObject* object)
     WebPreferences* prefs = settings->priv->preferences.get();
     prefs->setShouldRespectImageOrientation(true);
 
-    if (g_getenv("WEBKIT_WEBRTC_DISABLE_UNIFIED_PLAN"))
+    if (Environment::get("WEBKIT_WEBRTC_DISABLE_UNIFIED_PLAN"))
         prefs->setWebRTCUnifiedPlanEnabled(FALSE);
 
     bool mediaStreamEnabled = prefs->mediaStreamEnabled();
@@ -335,8 +336,7 @@ static void webKitSettingsSetProperty(GObject* object, guint propId, const GValu
         if (g_value_get_boolean(value))
             webkit_settings_set_draw_compositing_indicators(settings, g_value_get_boolean(value));
         else {
-            char* debugVisualsEnvironment = getenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS");
-            bool showDebugVisuals = debugVisualsEnvironment && !strcmp(debugVisualsEnvironment, "1");
+            auto showDebugVisuals = Environment::hasValue("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS", "1");
             webkit_settings_set_draw_compositing_indicators(settings, showDebugVisuals);
         }
         break;
index 1ecbf38..7c62d4c 100644 (file)
@@ -57,6 +57,7 @@
 #include <glib/gi18n-lib.h>
 #include <libintl.h>
 #include <memory>
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/HashMap.h>
 #include <wtf/Language.h>
@@ -261,7 +262,7 @@ WEBKIT_DEFINE_TYPE(WebKitWebContext, webkit_web_context, G_TYPE_OBJECT)
 static const char* injectedBundleDirectory()
 {
 #if ENABLE(DEVELOPER_MODE)
-    const char* bundleDirectory = g_getenv("WEBKIT_INJECTED_BUNDLE_PATH");
+    const char* bundleDirectory = Environment::getRaw("WEBKIT_INJECTED_BUNDLE_PATH");
     if (bundleDirectory && g_file_test(bundleDirectory, G_FILE_TEST_IS_DIR))
         return bundleDirectory;
 #endif
@@ -359,7 +360,7 @@ static void webkitWebContextConstructed(GObject* object)
     priv->processPool->setIgnoreTLSErrors(false);
 
 #if ENABLE(MEMORY_SAMPLER)
-    if (getenv("WEBKIT_SAMPLE_MEMORY"))
+    if (Environment::get("WEBKIT_SAMPLE_MEMORY"))
         priv->processPool->startMemorySampler(0);
 #endif
 
index 8cafc7b..e9de041 100644 (file)
@@ -29,6 +29,7 @@
 #include <WebCore/PlatformScreen.h>
 #include <glib/gi18n-lib.h>
 #include <gtk/gtk.h>
+#include <wtf/Environment.h>
 
 gboolean webkitWebViewAuthenticate(WebKitWebView* webView, WebKitAuthenticationRequest* request)
 {
@@ -194,8 +195,7 @@ void webkitWebViewMaximizeWindow(WebKitWebView* view, CompletionHandler<void()>&
 #if ENABLE(DEVELOPER_MODE)
     // Xvfb doesn't support maximize, so we resize the window to the screen size.
     if (WebCore::PlatformDisplay::sharedDisplay().type() == WebCore::PlatformDisplay::Type::X11) {
-        const char* underXvfb = g_getenv("UNDER_XVFB");
-        if (!g_strcmp0(underXvfb, "yes")) {
+        if (Environment::hasValue("UNDER_XVFB", "yes")) {
             auto screenRect = WebCore::screenAvailableRect(nullptr);
             gtk_window_move(window, screenRect.x(), screenRect.y());
             gtk_window_resize(window, screenRect.width(), screenRect.height());
@@ -247,8 +247,7 @@ void webkitWebViewRestoreWindow(WebKitWebView* view, CompletionHandler<void()>&&
 #if ENABLE(DEVELOPER_MODE)
     // Xvfb doesn't support maximize, so we resize the window to the default size.
     if (WebCore::PlatformDisplay::sharedDisplay().type() == WebCore::PlatformDisplay::Type::X11) {
-        const char* underXvfb = g_getenv("UNDER_XVFB");
-        if (!g_strcmp0(underXvfb, "yes")) {
+        if (Environment::hasValue("UNDER_XVFB", "yes")) {
             int x, y;
             gtk_window_get_default_size(window, &x, &y);
             gtk_window_resize(window, x, y);
index eb13b43..d39eb77 100644 (file)
@@ -36,6 +36,7 @@
 #include "WebPageGroup.h"
 #include "WebProcessPool.h"
 #include <wpe/wpe.h>
+#include <wtf/Environment.h>
 
 using namespace WebKit;
 
@@ -70,7 +71,7 @@ View::View(struct wpe_view_backend* backend, const API::PageConfiguration& baseC
     m_pageProxy = pool->createWebPage(*m_pageClient, WTFMove(configuration));
 
 #if ENABLE(MEMORY_SAMPLER)
-    if (getenv("WEBKIT_SAMPLE_MEMORY"))
+    if (Environment::get("WEBKIT_SAMPLE_MEMORY"))
         pool->startMemorySampler(0);
 #endif
 
index ca3789d..ffa034a 100644 (file)
@@ -27,6 +27,7 @@
 #include "AuxiliaryProcessProxy.h"
 
 #include "AuxiliaryProcessMessages.h"
+#include <wtf/Environment.h>
 #include <wtf/RunLoop.h>
 
 namespace WebKit {
@@ -51,8 +52,8 @@ void AuxiliaryProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& lau
 {
     launchOptions.processIdentifier = m_processIdentifier;
 
-    if (const char* userDirectorySuffix = getenv("DIRHELPER_USER_DIR_SUFFIX"))
-        launchOptions.extraInitializationData.add("user-directory-suffix"_s, userDirectorySuffix);
+    if (auto userDirectorySuffix = Environment::get("DIRHELPER_USER_DIR_SUFFIX"))
+        launchOptions.extraInitializationData.add("user-directory-suffix"_s, *userDirectorySuffix);
 
     if (m_alwaysRunsAtBackgroundPriority)
         launchOptions.extraInitializationData.add("always-runs-at-background-priority"_s, "true");
@@ -76,9 +77,9 @@ void AuxiliaryProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& lau
         ASSERT_NOT_REACHED();
         break;
     }
-    const char* processCmdPrefix = getenv(varname);
-    if (processCmdPrefix && *processCmdPrefix)
-        launchOptions.processCmdPrefix = String::fromUTF8(processCmdPrefix);
+    auto processCmdPrefix = Environment::get(varname);
+    if (processCmdPrefix && !processCmdPrefix->isEmpty())
+        launchOptions.processCmdPrefix = *processCmdPrefix;
 #endif // ENABLE(DEVELOPER_MODE) && (PLATFORM(GTK) || PLATFORM(WPE))
 
     platformGetLaunchOptions(launchOptions);
index f8b102a..4f8a466 100644 (file)
@@ -25,6 +25,7 @@
 #include <glib.h>
 #include <seccomp.h>
 #include <sys/ioctl.h>
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/glib/GLibUtilities.h>
 #include <wtf/glib/GRefPtr.h>
@@ -165,7 +166,7 @@ public:
             syncFdStr.get(),
         };
 
-        if (!g_strcmp0(g_getenv("WEBKIT_ENABLE_DBUS_PROXY_LOGGING"), "1"))
+        if (Environment::hasValue("WEBKIT_ENABLE_DBUS_PROXY_LOGGING", "1"))
             proxyArgs.append("--log");
 
         proxyArgs.appendVector(m_permissions);
@@ -282,7 +283,7 @@ static void bindIfExists(Vector<CString>& args, const char* path, BindFlags bind
 static void bindDBusSession(Vector<CString>& args, XDGDBusProxyLauncher& proxy)
 {
     if (!proxy.isRunning())
-        proxy.setAddress(g_getenv("DBUS_SESSION_BUS_ADDRESS"), DBusAddressType::Normal);
+        proxy.setAddress(Environment::getRaw("DBUS_SESSION_BUS_ADDRESS"), DBusAddressType::Normal);
 
     if (proxy.proxyPath().data()) {
         args.appendVector(Vector<CString>({
@@ -293,25 +294,25 @@ static void bindDBusSession(Vector<CString>& args, XDGDBusProxyLauncher& proxy)
 
 static void bindX11(Vector<CString>& args)
 {
-    const char* display = g_getenv("DISPLAY");
+    const char* display = Environment::getRaw("DISPLAY");
     if (!display || display[0] != ':' || !g_ascii_isdigit(const_cast<char*>(display)[1]))
         display = ":0";
     GUniquePtr<char> x11File(g_strdup_printf("/tmp/.X11-unix/X%s", display + 1));
     bindIfExists(args, x11File.get(), BindFlags::ReadWrite);
 
-    const char* xauth = g_getenv("XAUTHORITY");
-    if (!xauth) {
+    if (const char* xauth = Environment::getRaw("XAUTHORITY"))
+        bindIfExists(args, xauth);
+    else {
         const char* homeDir = g_get_home_dir();
         GUniquePtr<char> xauthFile(g_build_filename(homeDir, ".Xauthority", nullptr));
         bindIfExists(args, xauthFile.get());
-    } else
-        bindIfExists(args, xauth);
+    }
 }
 
 #if PLATFORM(WAYLAND) && USE(EGL)
 static void bindWayland(Vector<CString>& args)
 {
-    const char* display = g_getenv("WAYLAND_DISPLAY");
+    const char* display = Environment::getRaw("WAYLAND_DISPLAY");
     if (!display)
         display = "wayland-0";
 
@@ -325,8 +326,7 @@ static void bindPulse(Vector<CString>& args)
 {
     // FIXME: The server can be defined in config files we'd have to parse.
     // They can also be set as X11 props but that is getting a bit ridiculous.
-    const char* pulseServer = g_getenv("PULSE_SERVER");
-    if (pulseServer) {
+    if (const char* pulseServer = Environment::getRaw("PULSE_SERVER")) {
         if (g_str_has_prefix(pulseServer, "unix:"))
             bindIfExists(args, pulseServer + 5, BindFlags::ReadWrite);
         // else it uses tcp
@@ -336,8 +336,7 @@ static void bindPulse(Vector<CString>& args)
         bindIfExists(args, pulseRuntimeDir.get(), BindFlags::ReadWrite);
     }
 
-    const char* pulseConfig = g_getenv("PULSE_CLIENTCONFIG");
-    if (pulseConfig)
+    if (const char* pulseConfig = Environment::getRaw("PULSE_CLIENTCONFIG"))
         bindIfExists(args, pulseConfig);
 
     const char* configDir = g_get_user_config_dir();
@@ -450,7 +449,7 @@ static void bindA11y(Vector<CString>& args)
 
 static bool bindPathVar(Vector<CString>& args, const char* varname)
 {
-    const char* pathValue = g_getenv(varname);
+    const char* pathValue = Environment::getRaw(varname);
     if (!pathValue)
         return false;
 
@@ -477,8 +476,8 @@ static void bindGStreamerData(Vector<CString>& args)
     bindIfExists(args, gstCache.get(), BindFlags::ReadWrite);
 
     // /usr/lib is already added so this is only requried for other dirs
-    const char* scannerPath = g_getenv("GST_PLUGIN_SCANNER") ?: "/usr/libexec/gstreamer-1.0/gst-plugin-scanner";
-    const char* helperPath = g_getenv("GST_INSTALL_PLUGINS_HELPER ") ?: "/usr/libexec/gst-install-plugins-helper";
+    const char* scannerPath = Environment::getRaw("GST_PLUGIN_SCANNER") ?: "/usr/libexec/gstreamer-1.0/gst-plugin-scanner";
+    const char* helperPath = Environment::getRaw("GST_INSTALL_PLUGINS_HELPER ") ?: "/usr/libexec/gst-install-plugins-helper";
 
     bindIfExists(args, scannerPath);
     bindIfExists(args, helperPath);
@@ -720,12 +719,12 @@ GRefPtr<GSubprocess> bubblewrapSpawn(GSubprocessLauncher* launcher, const Proces
     // We would have to parse ld config files for more info.
     bindPathVar(sandboxArgs, "LD_LIBRARY_PATH");
 
-    const char* libraryPath = g_getenv("LD_LIBRARY_PATH");
-    if (libraryPath && libraryPath[0]) {
+    auto libraryPath = Environment::get("LD_LIBRARY_PATH");
+    if (libraryPath && !libraryPath->isEmpty()) {
         // On distros using a suid bwrap it drops this env var
         // so we have to pass it through to the children.
         sandboxArgs.appendVector(Vector<CString>({
-            "--setenv", "LD_LIBRARY_PATH", libraryPath,
+            "--setenv", "LD_LIBRARY_PATH", libraryPath->utf8(),
         }));
     }
 
@@ -804,9 +803,8 @@ GRefPtr<GSubprocess> bubblewrapSpawn(GSubprocessLauncher* launcher, const Proces
     }
 
 #if ENABLE(DEVELOPER_MODE)
-    const char* execDirectory = g_getenv("WEBKIT_EXEC_PATH");
-    if (execDirectory) {
-        String parentDir = FileSystem::directoryName(FileSystem::stringFromFileSystemRepresentation(execDirectory));
+    if (auto execDirectory = Environment::get("WEBKIT_EXEC_PATH")) {
+        auto parentDir = FileSystem::directoryName(FileSystem::stringFromFileSystemRepresentation(execDirectory->utf8().data()));
         bindIfExists(sandboxArgs, parentDir.utf8().data());
     }
 
index 0c39073..58022e1 100644 (file)
@@ -34,6 +34,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <glib.h>
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/RunLoop.h>
 #include <wtf/UniStdExtras.h>
@@ -165,11 +166,10 @@ void ProcessLauncher::launchProcess()
     GUniqueOutPtr<GError> error;
     GRefPtr<GSubprocess> process;
 #if OS(LINUX)
-    const char* sandboxEnv = g_getenv("WEBKIT_FORCE_SANDBOX");
     bool sandboxEnabled = m_launchOptions.extraInitializationData.get("enable-sandbox") == "true";
 
-    if (sandboxEnv)
-        sandboxEnabled = !strcmp(sandboxEnv, "1");
+    if (auto sandboxEnv = Environment::get("WEBKIT_FORCE_SANDBOX"))
+        sandboxEnabled = *sandboxEnv == "1";
 
     if (sandboxEnabled && isInsideFlatpak())
         process = flatpakSpawn(launcher.get(), m_launchOptions, argv, socketPair.client, &error.outPtr());
index 8964df3..933f522 100644 (file)
@@ -34,6 +34,7 @@
 #import <spawn.h>
 #import <sys/param.h>
 #import <sys/stat.h>
+#import <wtf/Environment.h>
 #import <wtf/MachSendRight.h>
 #import <wtf/RunLoop.h>
 #import <wtf/SoftLinking.h>
@@ -84,7 +85,7 @@ static NSString *systemDirectoryPath()
 {
     static NSString *path = [^{
 #if PLATFORM(IOS_FAMILY_SIMULATOR)
-        char *simulatorRoot = getenv("SIMULATOR_ROOT");
+        const char* simulatorRoot = Environment::getRaw("SIMULATOR_ROOT");
         return simulatorRoot ? [NSString stringWithFormat:@"%s/System/", simulatorRoot] : @"/System/";
 #else
         return @"/System/";
@@ -118,11 +119,11 @@ void ProcessLauncher::launchProcess()
 #if PLATFORM(IOS_FAMILY)
     // Clients that set these environment variables explicitly do not have the values automatically forwarded by libxpc.
     auto containerEnvironmentVariables = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
-    if (const char* environmentHOME = getenv("HOME"))
+    if (const char* environmentHOME = Environment::getRaw("HOME"))
         xpc_dictionary_set_string(containerEnvironmentVariables.get(), "HOME", environmentHOME);
-    if (const char* environmentCFFIXED_USER_HOME = getenv("CFFIXED_USER_HOME"))
+    if (const char* environmentCFFIXED_USER_HOME = Environment::getRaw("CFFIXED_USER_HOME"))
         xpc_dictionary_set_string(containerEnvironmentVariables.get(), "CFFIXED_USER_HOME", environmentCFFIXED_USER_HOME);
-    if (const char* environmentTMPDIR = getenv("TMPDIR"))
+    if (const char* environmentTMPDIR = Environment::getRaw("TMPDIR"))
         xpc_dictionary_set_string(containerEnvironmentVariables.get(), "TMPDIR", environmentTMPDIR);
     xpc_dictionary_set_value(initializationMessage.get(), "ContainerEnvironmentVariables", containerEnvironmentVariables.get());
 #endif
index a2a160b..8cc3c96 100644 (file)
@@ -32,6 +32,7 @@
 #include "WebProcessCreationParameters.h"
 #include <JavaScriptCore/RemoteInspectorServer.h>
 #include <WebCore/GStreamerCommon.h>
+#include <wtf/Environment.h>
 #include <wtf/glib/GUniquePtr.h>
 
 namespace WebKit {
@@ -62,14 +63,13 @@ static void initializeRemoteInspectorServer(const char* address)
 
 static bool memoryPressureMonitorDisabled()
 {
-    static const char* disableMemoryPressureMonitor = getenv("WEBKIT_DISABLE_MEMORY_PRESSURE_MONITOR");
-    return disableMemoryPressureMonitor && !strcmp(disableMemoryPressureMonitor, "1");
+    return Environment::hasValue("WEBKIT_DISABLE_MEMORY_PRESSURE_MONITOR", "1");
 }
 
 void WebProcessPool::platformInitialize()
 {
 #if ENABLE(REMOTE_INSPECTOR)
-    if (const char* address = g_getenv("WEBKIT_INSPECTOR_SERVER"))
+    if (const char* address = Environment::getRaw("WEBKIT_INSPECTOR_SERVER"))
         initializeRemoteInspectorServer(address);
 #endif
 
@@ -89,8 +89,7 @@ void WebProcessPool::platformInitializeWebProcess(WebProcessCreationParameters&
 #if PLATFORM(GTK)
     // This is misnamed. It can only be used to disable complex text.
     parameters.shouldAlwaysUseComplexTextCodePath = true;
-    const char* forceComplexText = getenv("WEBKIT_FORCE_COMPLEX_TEXT");
-    if (forceComplexText && !strcmp(forceComplexText, "0"))
+    if (Environment::hasValue("WEBKIT_FORCE_COMPLEX_TEXT", "0"))
         parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath;
 #endif
 
index 45760ee..7366ea3 100644 (file)
@@ -29,6 +29,7 @@
 #include "WaylandCompositor.h"
 #include <WebCore/NotImplemented.h>
 #include <WebCore/PlatformDisplay.h>
+#include <wtf/Environment.h>
 
 #if USE(REDIRECTED_XCOMPOSITE_WINDOW)
 #include <WebCore/PlatformDisplayX11.h>
@@ -52,8 +53,7 @@ HardwareAccelerationManager::HardwareAccelerationManager()
     return;
 #endif
 
-    const char* disableCompositing = getenv("WEBKIT_DISABLE_COMPOSITING_MODE");
-    if (disableCompositing && strcmp(disableCompositing, "0")) {
+    if (Environment::hasValueOtherThan("WEBKIT_DISABLE_COMPOSITING_MODE", "0")) {
         m_canUseHardwareAcceleration = false;
         return;
     }
@@ -78,8 +78,7 @@ HardwareAccelerationManager::HardwareAccelerationManager()
     }
 #endif
 
-    const char* forceCompositing = getenv("WEBKIT_FORCE_COMPOSITING_MODE");
-    if (forceCompositing && strcmp(forceCompositing, "0"))
+    if (Environment::hasValueOtherThan("WEBKIT_FORCE_COMPOSITING_MODE", "0"))
         m_forceHardwareAcceleration = true;
 }
 
index eedd442..1d9bafe 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "config.h"
 #include "WebProcessMainUnix.h"
 
-#include <cstdlib>
+#include <wtf/Environment.h>
 
 #if USE(GCRYPT)
 #include <pal/crypto/gcrypt/Initialization.h>
@@ -42,8 +43,8 @@ int main(int argc, char** argv)
     // GnuTLS or simply stops parsing this variable. We intentionally do not
     // overwrite this priority string if it's already set by the user.
     // https://bugzilla.gnome.org/show_bug.cgi?id=738633
-    // WARNING: This needs to be KEPT IN SYNC with WebProcessMain.cpp.
-    setenv("G_TLS_GNUTLS_PRIORITY", "NORMAL:%COMPAT:!VERS-SSL3.0:!ARCFOUR-128", 0);
+    // WARNING: This needs to be KEPT IN SYNC with NetworkProcessMain.cpp.
+    Environment::setIfNotDefined("G_TLS_GNUTLS_PRIORITY", "NORMAL:%COMPAT:!VERS-SSL3.0:!ARCFOUR-128");
 
 #if USE(GCRYPT)
     PAL::GCrypt::initialize();
index b5f7ac4..10dccbb 100644 (file)
@@ -33,6 +33,7 @@
 #include <gtk/gtk.h>
 #include <libintl.h>
 #include <libsoup/soup.h>
+#include <wtf/Environment.h>
 
 #if PLATFORM(X11)
 #include <X11/Xlib.h>
@@ -46,7 +47,7 @@ public:
     bool platformInitialize() override
     {
 #ifndef NDEBUG
-        if (g_getenv("WEBKIT2_PAUSE_WEB_PROCESS_ON_LAUNCH"))
+        if (Environment::get("WEBKIT2_PAUSE_WEB_PROCESS_ON_LAUNCH"))
             g_usleep(30 * G_USEC_PER_SEC);
 #endif
 
index 13192b4..ef4dfdb 100644 (file)
@@ -34,6 +34,7 @@
 #include <iostream>
 #include <libsoup/soup.h>
 #include <wpe/wpe.h>
+#include <wtf/Environment.h>
 
 namespace WebKit {
 using namespace WebCore;
@@ -43,7 +44,7 @@ public:
     bool platformInitialize() override
     {
 #if ENABLE(DEVELOPER_MODE)
-        if (g_getenv("WEBKIT2_PAUSE_WEB_PROCESS_ON_LAUNCH"))
+        if (Environment::get("WEBKIT2_PAUSE_WEB_PROCESS_ON_LAUNCH"))
             WTF::sleep(30_s);
 #endif
 
index 65f2a4c..a5457c3 100644 (file)
@@ -1,3 +1,14 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        * Misc/WebUIKitSupport.mm:
+        (WebKitPlatformSystemRootDirectory):
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Commit Queue  <commit-queue@webkit.org>
 
         Unreviewed, rolling out r241559 and r241566.
index ad6fe54..61fbab9 100644 (file)
@@ -38,6 +38,7 @@
 #import <WebCore/Settings.h>
 #import <WebCore/WebBackgroundTaskController.h>
 #import <WebCore/WebCoreThreadSystemInterface.h>
+#import <wtf/Environment.h>
 #import <wtf/spi/darwin/dyldSPI.h>
 
 using namespace WebCore;
@@ -106,7 +107,7 @@ const char *WebKitPlatformSystemRootDirectory(void)
 #if PLATFORM(IOS_FAMILY_SIMULATOR)
     static const char *platformSystemRootDirectory = nil;
     if (!platformSystemRootDirectory) {
-        char *simulatorRoot = getenv("IPHONE_SIMULATOR_ROOT");
+        const char* simulatorRoot = Environment::getRaw("IPHONE_SIMULATOR_ROOT");
         platformSystemRootDirectory = simulatorRoot ? simulatorRoot : "/";
     }
     return platformSystemRootDirectory;
index a484822..727c4de 100644 (file)
@@ -1,3 +1,14 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        * WebView/WebView.mm:
+        (-[WebView _initWithFrame:frameName:groupName:]):
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Brian Burg  <bburg@apple.com>
 
         [Mac] WebInspectorUI.framework does not need to be soft-linked anymore
index 480f885..3e8d6b5 100644 (file)
 #import <pal/spi/mac/NSSpellCheckerSPI.h>
 #import <pal/spi/mac/NSWindowSPI.h>
 #import <wtf/Assertions.h>
+#import <wtf/Environment.h>
 #import <wtf/FileSystem.h>
 #import <wtf/HashTraits.h>
 #import <wtf/MainThread.h>
@@ -1606,7 +1607,7 @@ static void WebKitInitializeGamepadProviderIfNecessary()
     // need for Safari to unset it to prevent it from being passed to applications it launches.
     // Unsetting it when a WebView is first created is as good a place as any.
     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
-    if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
+    if (Environment::get("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
         unsetenv("DYLD_FRAMEWORK_PATH");
         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
     }
index 2d87ca1..ea06af9 100644 (file)
@@ -1,3 +1,51 @@
+2019-02-15  Ross Kirsling  <ross.kirsling@sony.com>
+
+        [WTF] Add environment variable helpers
+        https://bugs.webkit.org/show_bug.cgi?id=192405
+
+        Reviewed by Michael Catanzaro.
+
+        * DumpRenderTree/mac/DumpRenderTree.mm:
+        (libraryPathForDumpRenderTree):
+        * DumpRenderTree/win/DumpRenderTree.cpp:
+        (libraryPathForDumpRenderTree):
+        * TestRunnerShared/IOSLayoutTestCommunication.cpp:
+        (setUpIOSLayoutTestCommunication):
+        * TestWebKitAPI/Tests/WebKitGLib/TestAutomationSession.cpp:
+        (beforeAll):
+        * TestWebKitAPI/glib/WebKitGLib/TestMain.cpp:
+        (main):
+        * TestWebKitAPI/glib/WebKitGLib/WebKitTestBus.cpp:
+        (WebKitTestBus::run):
+        * WebKitTestRunner/InjectedBundle/gtk/ActivateFontsGtk.cpp:
+        (WTR::getOutputDir):
+        (WTR::initializeFontConfigSetting):
+        * WebKitTestRunner/InjectedBundle/gtk/InjectedBundleGtk.cpp:
+        (WTR::InjectedBundle::platformInitialize):
+        * WebKitTestRunner/InjectedBundle/gtk/InjectedBundleUtilities.cpp:
+        (WTR::topLevelPath):
+        * WebKitTestRunner/InjectedBundle/wpe/ActivateFontsWPE.cpp:
+        (WTR::topLevelPath):
+        (WTR::getOutputDir):
+        (WTR::activateFonts):
+        * WebKitTestRunner/TestController.cpp:
+        (WTR::TestController::libraryPathForTesting):
+        (WTR::TestController::generateContextConfiguration const):
+        (WTR::TestController::generatePageConfiguration):
+        (WTR::TestController::decideDestinationWithSuggestedFilename):
+        (WTR::TestController::platformAdjustContext):
+        * WebKitTestRunner/TestController.h:
+        * WebKitTestRunner/cocoa/TestControllerCocoa.mm:
+        (WTR::TestController::cocoaPlatformInitialize):
+        (WTR::TestController::platformAdjustContext):
+        * WebKitTestRunner/gtk/main.cpp:
+        (main):
+        * WebKitTestRunner/mac/TestControllerMac.mm:
+        (WTR::TestController::configureContentExtensionForTest):
+        * WebKitTestRunner/wpe/main.cpp:
+        (main):
+        Utilize WTF::Environment where possible.
+
 2019-02-15  Wenson Hsieh  <wenson_hsieh@apple.com>
 
         [iOS] WKWebView callout bar is missing Change Writing Direction item
index b052412..d79ecb3 100644 (file)
@@ -91,6 +91,7 @@
 #import <WebKit/WebViewPrivate.h>
 #import <getopt.h>
 #import <wtf/Assertions.h>
+#import <wtf/Environment.h>
 #import <wtf/FastMalloc.h>
 #import <wtf/LoggingAccumulator.h>
 #import <wtf/ObjCRuntimeExtras.h>
@@ -843,11 +844,10 @@ static void destroyWebViewAndOffscreenWindow(WebView *webView)
 
 static NSString *libraryPathForDumpRenderTree()
 {
-    char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
-    if (dumpRenderTreeTemp)
+    if (const char* dumpRenderTreeTemp = Environment::getRaw("DUMPRENDERTREE_TEMP"))
         return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
-    else
-        return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
+
+    return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
 }
 
 static void enableExperimentalFeatures(WebPreferences* preferences)
index 3764fcd..107ad0c 100644 (file)
@@ -59,6 +59,7 @@
 #include <shlwapi.h>
 #include <tchar.h>
 #include <windows.h>
+#include <wtf/Environment.h>
 #include <wtf/FileSystem.h>
 #include <wtf/HashSet.h>
 #include <wtf/NeverDestroyed.h>
@@ -214,16 +215,14 @@ static string toUTF8(const wchar_t* wideString, size_t length)
 #if USE(CF)
 static String libraryPathForDumpRenderTree()
 {
-    DWORD size = ::GetEnvironmentVariable(dumpRenderTreeTemp, 0, 0);
-    Vector<TCHAR> buffer(size);
-    if (::GetEnvironmentVariable(dumpRenderTreeTemp, buffer.data(), buffer.size())) {
-        wstring path = buffer.data();
-        if (!path.empty() && (path[path.length() - 1] != L'\\'))
-            path.append(L"\\");
-        return String (path.data(), path.length());
-    }
+    auto path = Environment::get(dumpRenderTreeTemp);
+    if (!path || path->isEmpty())
+        return FileSystem::localUserSpecificStorageDirectory();
+
+    if (!path->endsWith('\\'))
+        path->append('\\');
 
-    return FileSystem::localUserSpecificStorageDirectory();
+    return *path;
 }
 #endif
 
index bc312bf..e2e6517 100644 (file)
@@ -32,6 +32,7 @@
 #include <sys/types.h>
 #include <unistd.h>
 #include <wtf/Assertions.h>
+#include <wtf/Environment.h>
 
 static int stdinSocket;
 static int stdoutSocket;
@@ -48,11 +49,10 @@ static int connectToServer(sockaddr_in& serverAddress)
 
 void setUpIOSLayoutTestCommunication()
 {
-    char* portFromEnvironment = getenv("PORT");
-    if (!portFromEnvironment)
+    auto port = Environment::getInt("PORT");
+    if (!port)
         return;
-    int port = atoi(portFromEnvironment);
-    RELEASE_ASSERT(port > 0);
+    RELEASE_ASSERT(*port > 0);
     isUsingTCP = true;
 
     struct hostent* host = gethostbyname("127.0.0.1");
@@ -63,7 +63,7 @@ void setUpIOSLayoutTestCommunication()
         (char*)&serverAddress.sin_addr.s_addr,
         (char*)host->h_addr,
         host->h_length);
-    serverAddress.sin_port = htons(port);
+    serverAddress.sin_port = htons(*port);
     
     // This order matches the server side listener in Tools/Scripts/webkitpy/port/simulator_process.py SimulatorProcess._start()
     stdinSocket = connectToServer(serverAddress);
index 998ab2f..13f20e2 100644 (file)
@@ -21,6 +21,7 @@
 
 #include "TestMain.h"
 #include <gio/gio.h>
+#include <wtf/Environment.h>
 #include <wtf/UUID.h>
 #include <wtf/text/StringBuilder.h>
 
@@ -343,7 +344,7 @@ static void testAutomationSessionApplicationInfo(Test* test, gconstpointer)
 
 void beforeAll()
 {
-    g_setenv("WEBKIT_INSPECTOR_SERVER", "127.0.0.1:2229", TRUE);
+    Environment::set("WEBKIT_INSPECTOR_SERVER", "127.0.0.1:2229");
 
     AutomationTest::add("WebKitAutomationSession", "request-session", testAutomationSessionRequestSession);
     Test::add("WebKitAutomationSession", "application-info", testAutomationSessionApplicationInfo);
index a155a51..dd60b51 100644 (file)
@@ -21,6 +21,7 @@
 #include "TestMain.h"
 
 #include <glib/gstdio.h>
+#include <wtf/Environment.h>
 
 #if PLATFORM(GTK)
 #include <gtk/gtk.h>
@@ -66,19 +67,19 @@ static void removeNonEmptyDirectory(const char* directoryPath)
 
 int main(int argc, char** argv)
 {
-    g_unsetenv("DBUS_SESSION_BUS_ADDRESS");
+    Environment::remove("DBUS_SESSION_BUS_ADDRESS");
 #if PLATFORM(GTK)
     gtk_test_init(&argc, &argv, nullptr);
 #else
     g_test_init(&argc, &argv, nullptr);
 #endif
-    g_setenv("WEBKIT_EXEC_PATH", WEBKIT_EXEC_PATH, FALSE);
-    g_setenv("WEBKIT_INJECTED_BUNDLE_PATH", WEBKIT_INJECTED_BUNDLE_PATH, FALSE);
-    g_setenv("LC_ALL", "C", TRUE);
-    g_setenv("GIO_USE_VFS", "local", TRUE);
-    g_setenv("GSETTINGS_BACKEND", "memory", TRUE);
+    Environment::setIfNotDefined("WEBKIT_EXEC_PATH", WEBKIT_EXEC_PATH);
+    Environment::setIfNotDefined("WEBKIT_INJECTED_BUNDLE_PATH", WEBKIT_INJECTED_BUNDLE_PATH);
+    Environment::set("LC_ALL", "C");
+    Environment::set("GIO_USE_VFS", "local");
+    Environment::set("GSETTINGS_BACKEND", "memory");
     // Get rid of runtime warnings about deprecated properties and signals, since they break the tests.
-    g_setenv("G_ENABLE_DIAGNOSTIC", "0", TRUE);
+    Environment::set("G_ENABLE_DIAGNOSTIC", "0");
     g_test_bug_base("https://bugs.webkit.org/");
 
     registerGResource();
index ba6476c..5a3d5c4 100644 (file)
@@ -20,6 +20,8 @@
 #include "config.h"
 #include "WebKitTestBus.h"
 
+#include <wtf/Environment.h>
+
 WebKitTestBus::WebKitTestBus()
     : m_bus(adoptGRef(g_test_dbus_new(G_TEST_DBUS_NONE)))
 {
@@ -32,14 +34,14 @@ WebKitTestBus::~WebKitTestBus()
 
 bool WebKitTestBus::run()
 {
-    CString display = g_getenv("DISPLAY");
-    CString runtimeDir = g_getenv("XDG_RUNTIME_DIR");
+    auto display = Environment::get("DISPLAY");
+    auto runtimeDir = Environment::get("XDG_RUNTIME_DIR");
     g_test_dbus_up(m_bus.get());
     m_address = g_test_dbus_get_bus_address(m_bus.get());
-    if (!display.isNull())
-        g_setenv("DISPLAY", display.data(), FALSE);
-    if (!runtimeDir.isNull())
-        g_setenv("XDG_RUNTIME_DIR", runtimeDir.data(), FALSE);
+    if (display)
+        Environment::setIfNotDefined("DISPLAY", *display);
+    if (runtimeDir)
+        Environment::setIfNotDefined("XDG_RUNTIME_DIR", *runtimeDir);
     return !m_address.isNull();
 }
 
index 3f8e244..5e8c69a 100644 (file)
@@ -34,6 +34,7 @@
 #include "InjectedBundleUtilities.h"
 #include <fontconfig/fontconfig.h>
 #include <gtk/gtk.h>
+#include <wtf/Environment.h>
 #include <wtf/glib/GLibUtilities.h>
 #include <wtf/glib/GUniquePtr.h>
 
@@ -54,9 +55,8 @@ void initializeGtkSettings()
 
 CString getOutputDir()
 {
-    const char* webkitOutputDir = g_getenv("WEBKIT_OUTPUTDIR");
-    if (webkitOutputDir)
-        return webkitOutputDir;
+    if (auto webkitOutputDir = Environment::get("WEBKIT_OUTPUTDIR"))
+        return webkitOutputDir->utf8();
 
     CString topLevelPath = WTR::topLevelPath();
     GUniquePtr<char> outputDir(g_build_filename(topLevelPath.data(), "WebKitBuild", nullptr));
@@ -80,7 +80,7 @@ static CString getFontsPath()
 
 void initializeFontConfigSetting()
 {
-    if (g_getenv("WEBKIT_SKIP_WEBKITTESTRUNNER_FONTCONFIG_INITIALIZATION"))
+    if (Environment::get("WEBKIT_SKIP_WEBKITTESTRUNNER_FONTCONFIG_INITIALIZATION"))
         return;
 
     FcInit();
index ba08431..249812f 100644 (file)
@@ -45,8 +45,7 @@ void InjectedBundle::platformInitialize(WKTypeRef)
     // messages sent to the logger.
     g_log_set_default_handler(logHandler, 0);
 
-    if (!g_getenv("WEBKIT_TOP_LEVEL"))
-        g_setenv("WEBKIT_TOP_LEVEL", TOP_LEVEL_DIR, FALSE);
+    g_setenv("WEBKIT_TOP_LEVEL", TOP_LEVEL_DIR, FALSE);
 }
 
 } // namespace WTR
index afbd3f7..9277766 100644 (file)
@@ -30,6 +30,7 @@
 #include "InjectedBundleUtilities.h"
 
 #include <gtk/gtk.h>
+#include <wtf/Environment.h>
 #include <wtf/glib/GLibUtilities.h>
 #include <wtf/glib/GUniquePtr.h>
 
@@ -37,8 +38,8 @@ namespace WTR {
 
 CString topLevelPath()
 {
-    if (const char* topLevelDirectory = g_getenv("WEBKIT_TOP_LEVEL"))
-        return topLevelDirectory;
+    if (auto topLevelDirectory = Environment::get("WEBKIT_TOP_LEVEL"))
+        return topLevelDirectory->utf8();
 
     // If the environment variable wasn't provided then assume we were built into
     // WebKitBuild/Debug or WebKitBuild/Release. Obviously this will fail if the build
index a49c7a2..9d1ed80 100644 (file)
@@ -27,6 +27,7 @@
 #include "ActivateFonts.h"
 
 #include <fontconfig/fontconfig.h>
+#include <wtf/Environment.h>
 #include <wtf/glib/GLibUtilities.h>
 #include <wtf/glib/GUniquePtr.h>
 
@@ -34,8 +35,8 @@ namespace WTR {
 
 CString topLevelPath()
 {
-    if (const char* topLevelDirectory = g_getenv("WEBKIT_TOP_LEVEL"))
-        return topLevelDirectory;
+    if (auto topLevelDirectory = Environment::get("WEBKIT_TOP_LEVEL"))
+        return topLevelDirectory->utf8();
 
     // If the environment variable wasn't provided then assume we were built into
     // WebKitBuild/Debug or WebKitBuild/Release. Obviously this will fail if the build
@@ -48,9 +49,8 @@ CString topLevelPath()
 
 CString getOutputDir()
 {
-    const char* webkitOutputDir = g_getenv("WEBKIT_OUTPUTDIR");
-    if (webkitOutputDir)
-        return webkitOutputDir;
+    if (auto webkitOutputDir = Environment::get("WEBKIT_OUTPUTDIR"))
+        return webkitOutputDir->utf8();
 
     GUniquePtr<char> outputDir(g_build_filename(topLevelPath().data(), "WebKitBuild", nullptr));
     return outputDir.get();
@@ -73,7 +73,7 @@ static CString getFontsPath()
 
 void activateFonts()
 {
-    if (g_getenv("WEBKIT_SKIP_WEBKITTESTRUNNER_FONTCONFIG_INITIALIZATION"))
+    if (Environment::get("WEBKIT_SKIP_WEBKITTESTRUNNER_FONTCONFIG_INITIALIZATION"))
         return;
 
     FcInit();
index 10aebcf..aa89f2a 100644 (file)
@@ -72,6 +72,7 @@
 #include <string>
 #include <wtf/AutodrainedPool.h>
 #include <wtf/CryptographicallyRandomNumber.h>
+#include <wtf/Environment.h>
 #include <wtf/MainThread.h>
 #include <wtf/ProcessPrivilege.h>
 #include <wtf/RefCounted.h>
@@ -386,15 +387,15 @@ WKPageRef TestController::createOtherPage(PlatformWebView* parentView, WKPageCon
     return newPage;
 }
 
-const char* TestController::libraryPathForTesting()
+String TestController::libraryPathForTesting()
 {
     // FIXME: This may not be sufficient to prevent interactions/crashes
     // when running more than one copy of DumpRenderTree.
     // See https://bugs.webkit.org/show_bug.cgi?id=10906
-    char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
-    if (dumpRenderTreeTemp)
-        return dumpRenderTreeTemp;
-    return platformLibraryPathForTesting();
+    if (auto dumpRenderTreeTemp = Environment::get("DUMPRENDERTREE_TEMP"))
+        return *dumpRenderTreeTemp;
+
+    return String::fromUTF8(platformLibraryPathForTesting());
 }
 
 void TestController::initialize(int argc, const char* argv[])
@@ -461,9 +462,8 @@ WKRetainPtr<WKContextConfigurationRef> TestController::generateContextConfigurat
     WKContextConfigurationSetFullySynchronousModeIsAllowedForTesting(configuration.get(), true);
     WKContextConfigurationSetIgnoreSynchronousMessagingTimeoutsForTesting(configuration.get(), options.ignoreSynchronousMessagingTimeouts);
 
-    if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
-        String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
-
+    auto temporaryFolder = libraryPathForTesting();
+    if (!!temporaryFolder) {
         WKContextConfigurationSetApplicationCacheDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "ApplicationCache").get());
         WKContextConfigurationSetDiskCacheDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "Cache").get());
         WKContextConfigurationSetIndexedDBDatabaseDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "Databases" + pathSeparator + "IndexedDB").get());
@@ -481,9 +481,8 @@ WKRetainPtr<WKPageConfigurationRef> TestController::generatePageConfiguration(WK
 
     m_geolocationProvider = std::make_unique<GeolocationProviderMock>(m_context.get());
 
-    if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
-        String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
-
+    auto temporaryFolder = libraryPathForTesting();
+    if (!!temporaryFolder) {
         // FIXME: This should be migrated to WKContextConfigurationRef.
         // Disable icon database to avoid fetching <http://127.0.0.1:8000/favicon.ico> and making tests flaky.
         // Invividual tests can enable it using testRunner.setIconDatabaseEnabled, although it's not currently supported in WebKitTestRunner.
@@ -1381,7 +1380,7 @@ static std::string contentExtensionJSONPath(WKURLRef url)
 #if ENABLE(CONTENT_EXTENSIONS)
 void TestController::configureContentExtensionForTest(const TestInvocation& test)
 {
-    const char* contentExtensionsPath = libraryPathForTesting();
+    auto contentExtensionsPath = libraryPathForTesting();
     if (!contentExtensionsPath)
         contentExtensionsPath = "/tmp/wktr-contentextensions";
 
@@ -1400,7 +1399,7 @@ void TestController::configureContentExtensionForTest(const TestInvocation& test
     std::string jsonFileContents {std::istreambuf_iterator<char>(jsonFile), std::istreambuf_iterator<char>()};
     auto jsonSource = adoptWK(WKStringCreateWithUTF8CString(jsonFileContents.c_str()));
 
-    auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath));
+    auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath.utf8().data()));
     auto extensionStore = adoptWK(WKUserContentExtensionStoreCreate(storePath.get()));
     ASSERT(extensionStore);
 
@@ -1423,13 +1422,13 @@ void TestController::resetContentExtensions()
 
     WKPageSetUserContentExtensionsEnabled(mainWebView()->page(), false);
 
-    const char* contentExtensionsPath = libraryPathForTesting();
+    auto contentExtensionsPath = libraryPathForTesting();
     if (!contentExtensionsPath)
         return;
 
     WKUserContentControllerRemoveAllUserContentFilters(userContentController());
 
-    auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath));
+    auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath.utf8().data()));
     auto extensionStore = adoptWK(WKUserContentExtensionStoreCreate(storePath.get()));
     ASSERT(extensionStore);
 
@@ -2279,12 +2278,11 @@ WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef,
         m_currentInvocation->outputText(builder.toString());
     }
 
-    const char* dumpRenderTreeTemp = libraryPathForTesting();
-    if (!dumpRenderTreeTemp)
+    auto temporaryFolder = libraryPathForTesting();
+    if (!temporaryFolder)
         return nullptr;
 
     *allowOverwrite = true;
-    String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
     if (suggestedFilename.isEmpty())
         suggestedFilename = "Unknown";
 
@@ -2828,11 +2826,9 @@ WKContextRef TestController::platformAdjustContext(WKContextRef context, WKConte
     auto* dataStore = WKContextGetWebsiteDataStore(context);
     WKWebsiteDataStoreSetResourceLoadStatisticsEnabled(dataStore, true);
 
-    if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
-        String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
-
+    auto temporaryFolder = libraryPathForTesting();
+    if (!!temporaryFolder)
         WKWebsiteDataStoreSetServiceWorkerRegistrationDirectory(dataStore, toWK(temporaryFolder + pathSeparator + "ServiceWorkers").get());
-    }
 
     return context;
 }
index b43c55c..74cb069 100644 (file)
@@ -37,6 +37,7 @@
 #include <wtf/Seconds.h>
 #include <wtf/Vector.h>
 #include <wtf/text/StringHash.h>
+#include <wtf/text/WTFString.h>
 
 #if PLATFORM(COCOA)
 #include "ClassMethodSwizzler.h"
@@ -444,7 +445,7 @@ private:
     static void runModal(WKPageRef, const void* clientInfo);
     static void runModal(PlatformWebView*);
 
-    static const char* libraryPathForTesting();
+    static String libraryPathForTesting();
     static const char* platformLibraryPathForTesting();
 
     std::unique_ptr<TestInvocation> m_currentInvocation;
index fe3bd6e..2765f6a 100644 (file)
@@ -108,11 +108,11 @@ void initializeWebViewConfiguration(const char* libraryPath, WKStringRef injecte
 
 void TestController::cocoaPlatformInitialize()
 {
-    const char* dumpRenderTreeTemp = libraryPathForTesting();
+    auto dumpRenderTreeTemp = libraryPathForTesting();
     if (!dumpRenderTreeTemp)
         return;
 
-    String resourceLoadStatisticsFolder = String(dumpRenderTreeTemp) + '/' + "ResourceLoadStatistics";
+    auto resourceLoadStatisticsFolder = makeString(dumpRenderTreeTemp, "/ResourceLoadStatistics");
     [[NSFileManager defaultManager] createDirectoryAtPath:resourceLoadStatisticsFolder withIntermediateDirectories:YES attributes:nil error: nil];
     String fullBrowsingSessionResourceLog = resourceLoadStatisticsFolder + '/' + "full_browsing_session_resourceLog.plist";
     NSDictionary *resourceLogPlist = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:1], @"version", nil];
@@ -207,7 +207,7 @@ PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parent
 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
 {
 #if WK_API_ENABLED
-    initializeWebViewConfiguration(libraryPathForTesting(), injectedBundlePath(), context, contextConfiguration);
+    initializeWebViewConfiguration(libraryPathForTesting().utf8().data(), injectedBundlePath(), context, contextConfiguration);
     return (__bridge WKContextRef)globalWebViewConfiguration.processPool;
 #else
     return nullptr;
index a203956..a4d18b3 100644 (file)
 #include "TestController.h"
 #include <WebKit/WKTextCheckerGtk.h>
 #include <gtk/gtk.h>
+#include <wtf/Environment.h>
 #include <wtf/glib/GRefPtr.h>
 
 int main(int argc, char** argv)
 {
-    g_setenv("WEBKIT_DISABLE_MEMORY_PRESSURE_MONITOR", "1", FALSE);
+    Environment::setIfNotDefined("WEBKIT_DISABLE_MEMORY_PRESSURE_MONITOR", "1");
 
     gtk_init(&argc, &argv);
 
index 3e773bc..6db4b25 100644 (file)
@@ -135,10 +135,10 @@ void TestController::configureContentExtensionForTest(const TestInvocation& test
     __block bool doneCompiling = false;
 
     NSURL *tempDir;
-    if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
-        String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
+    auto temporaryFolder = libraryPathForTesting();
+    if (!!temporaryFolder)
         tempDir = [NSURL fileURLWithPath:[(NSString*)temporaryFolder stringByAppendingPathComponent:@"ContentExtensions"] isDirectory:YES];
-    else
+    else
         tempDir = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"ContentExtensions"] isDirectory:YES];
 
     [[_WKUserContentExtensionStore storeWithURL:tempDir] compileContentExtensionForIdentifier:@"TestContentExtensions" encodedContentExtension:contentExtensionString completionHandler:^(_WKUserContentFilter *filter, NSError *error)
index d62269d..135bd25 100644 (file)
 
 #include "TestController.h"
 #include <glib.h>
+#include <wtf/Environment.h>
 
 int main(int argc, char** argv)
 {
-    g_setenv("WEBKIT_DISABLE_MEMORY_PRESSURE_MONITOR", "1", FALSE);
+    Environment::setIfNotDefined("WEBKIT_DISABLE_MEMORY_PRESSURE_MONITOR", "1");
 
     WTR::TestController controller(argc, const_cast<const char**>(argv));
     return 0;