1 # Copyright (C) 2005-2007, 2010-2016 Apple Inc. All rights reserved.
2 # Copyright (C) 2009 Google Inc. All rights reserved.
3 # Copyright (C) 2011 Research In Motion Limited. All rights reserved.
4 # Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies).
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution.
15 # 3. Neither the name of Apple Inc. ("Apple") nor the names of
16 # its contributors may be used to endorse or promote products derived
17 # from this software without specific prior written permission.
19 # THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 # DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 # Module to share code to get to WebKit directories.
37 use Digest::MD5 qw(md5_hex);
41 use File::Path qw(make_path mkpath rmtree);
43 use File::Temp qw(tempdir);
47 use Time::HiRes qw(usleep);
52 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
56 &XcodeCoverageSupportOptions
58 &XcodeOptionStringNoConfig
60 &XcodeStaticAnalyzerOption
61 &appDisplayNameFromBundle
62 &appendToEnvironmentVariableList
63 &archCommandLineArgumentsForRestrictedEnvironmentVariables
67 &cmakeBasedPortArguments
71 &findOrCreateSimulatorForIOSDevice
72 &iosSimulatorDeviceByName
75 &prependToEnvironmentVariableList
76 &printHelpAndExitForRunAndDebugWebKitAppIfNeeded
80 &restartIOSSimulatorDevice
86 &setupMacWebKitEnvironment
87 &sharedCommandLineOptions
88 &sharedCommandLineOptionsUsage
89 &shutDownIOSSimulatorDevice
91 &willUseIOSSimulatorSDK
92 SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT
101 AppleWin => "AppleWin",
106 watchOS => "watchOS",
108 JSCOnly => "JSCOnly",
109 WinCairo => "WinCairo",
113 use constant USE_OPEN_COMMAND => 1; # Used in runMacWebKitApp().
114 use constant SIMULATOR_DEVICE_STATE_SHUTDOWN => "1";
115 use constant SIMULATOR_DEVICE_STATE_BOOTED => "3";
116 use constant SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT => "For WebKit Development";
118 # See table "Certificate types and names" on <https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html#//apple_ref/doc/uid/TP40012582-CH31-SW41>.
119 use constant IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX => "iPhone Developer: ";
128 my @baseProductDirOption;
131 my $configurationForVisualStudio;
132 my $configurationProductDir;
134 my $currentSVNRevision;
135 my $didLoadIPhoneSimulatorNotification;
142 my $isInspectorFrontend;
144 my $shouldUseGuardMalloc;
145 my $shouldNotUseNinja;
148 my $unknownPortProhibited = 0;
150 # Variables for Win32 support
151 my $programFilesPath;
154 my $msBuildInstallDir;
156 my $windowsSourceDir;
158 my $willUseVCExpressWhenBuilding = 0;
160 # Defined in VCSUtils.
163 sub findMatchingArguments($$);
166 sub determineSourceDir
168 return if $sourceDir;
169 $sourceDir = $FindBin::Bin;
170 $sourceDir =~ s|/+$||; # Remove trailing '/' as we would die later
172 # walks up path checking each directory to see if it is the main WebKit project dir,
173 # defined by containing Sources, WebCore, and JavaScriptCore.
174 until ((-d File::Spec->catdir($sourceDir, "Source") && -d File::Spec->catdir($sourceDir, "Source", "WebCore") && -d File::Spec->catdir($sourceDir, "Source", "JavaScriptCore")) || (-d File::Spec->catdir($sourceDir, "Internal") && -d File::Spec->catdir($sourceDir, "OpenSource")))
176 if ($sourceDir !~ s|/[^/]+$||) {
177 die "Could not find top level webkit directory above source directory using FindBin.\n";
181 $sourceDir = File::Spec->catdir($sourceDir, "OpenSource") if -d File::Spec->catdir($sourceDir, "OpenSource");
184 sub currentPerlPath()
188 $thisPerl .= $Config{_exe} unless $thisPerl =~ m/$Config{_exe}$/i;
193 # used for scripts which are stored in a non-standard location
199 sub determineNinjaVersion
201 chomp(my $ninjaVersion = `ninja --version`);
202 return $ninjaVersion;
205 sub determineXcodeVersion
207 return if defined $xcodeVersion;
208 my $xcodebuildVersionOutput = `xcodebuild -version`;
209 $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : "3.0";
212 sub readXcodeUserDefault($)
216 my $devnull = File::Spec->devnull();
218 my $value = `defaults read com.apple.dt.Xcode ${key} 2> ${devnull}`;
225 sub determineBaseProductDir
227 return if defined $baseProductDir;
228 determineSourceDir();
230 my $setSharedPrecompsDir;
231 $baseProductDir = $ENV{"WEBKIT_OUTPUTDIR"};
233 if (!defined($baseProductDir) and isAppleCocoaWebKit()) {
234 # Silently remove ~/Library/Preferences/xcodebuild.plist which can
235 # cause build failure. The presence of
236 # ~/Library/Preferences/xcodebuild.plist can prevent xcodebuild from
237 # respecting global settings such as a custom build products directory
238 # (<rdar://problem/5585899>).
239 my $personalPlistFile = $ENV{HOME} . "/Library/Preferences/xcodebuild.plist";
240 if (-e $personalPlistFile) {
241 unlink($personalPlistFile) || die "Could not delete $personalPlistFile: $!";
244 my $buildLocationStyle = join '', readXcodeUserDefault("IDEBuildLocationStyle");
245 if ($buildLocationStyle eq "Custom") {
246 my $buildLocationType = join '', readXcodeUserDefault("IDECustomBuildLocationType");
247 # FIXME: Read CustomBuildIntermediatesPath and set OBJROOT accordingly.
248 $baseProductDir = readXcodeUserDefault("IDECustomBuildProductsPath") if $buildLocationType eq "Absolute";
251 # DeterminedByTargets corresponds to a setting of "Legacy" in Xcode.
252 # It is the only build location style for which SHARED_PRECOMPS_DIR is not
253 # overridden when building from within Xcode.
254 $setSharedPrecompsDir = 1 if $buildLocationStyle ne "DeterminedByTargets";
256 if (!defined($baseProductDir)) {
257 $baseProductDir = join '', readXcodeUserDefault("IDEApplicationwideBuildSettings");
258 $baseProductDir = $1 if $baseProductDir =~ /SYMROOT\s*=\s*\"(.*?)\";/s;
261 undef $baseProductDir unless $baseProductDir =~ /^\//;
264 if (!defined($baseProductDir)) { # Port-specific checks failed, use default
265 $baseProductDir = File::Spec->catdir($sourceDir, "WebKitBuild");
268 if (isGit() && isGitBranchBuild()) {
269 my $branch = gitBranch();
270 $baseProductDir = "$baseProductDir/$branch";
273 if (isAppleCocoaWebKit()) {
274 $baseProductDir =~ s|^\Q$(SRCROOT)/..\E$|$sourceDir|;
275 $baseProductDir =~ s|^\Q$(SRCROOT)/../|$sourceDir/|;
276 $baseProductDir =~ s|^~/|$ENV{HOME}/|;
277 die "Can't handle Xcode product directory with a ~ in it.\n" if $baseProductDir =~ /~/;
278 die "Can't handle Xcode product directory with a variable in it.\n" if $baseProductDir =~ /\$/;
279 @baseProductDirOption = ("SYMROOT=$baseProductDir", "OBJROOT=$baseProductDir");
280 push(@baseProductDirOption, "SHARED_PRECOMPS_DIR=${baseProductDir}/PrecompiledHeaders") if $setSharedPrecompsDir;
284 my $dosBuildPath = `cygpath --windows \"$baseProductDir\"`;
286 $ENV{"WEBKIT_OUTPUTDIR"} = $dosBuildPath;
287 my $unixBuildPath = `cygpath --unix \"$baseProductDir\"`;
288 chomp $unixBuildPath;
289 $baseProductDir = $dosBuildPath;
298 sub setBaseProductDir($)
300 ($baseProductDir) = @_;
303 sub determineConfiguration
305 return if defined $configuration;
306 determineBaseProductDir();
307 if (open CONFIGURATION, "$baseProductDir/Configuration") {
308 $configuration = <CONFIGURATION>;
311 if ($configuration) {
312 chomp $configuration;
313 # compatibility for people who have old Configuration files
314 $configuration = "Release" if $configuration eq "Deployment";
315 $configuration = "Debug" if $configuration eq "Development";
317 $configuration = "Release";
321 sub determineArchitecture
323 return if defined $architecture;
324 # make sure $architecture is defined in all cases
327 determineBaseProductDir();
330 if (isAppleCocoaWebKit()) {
331 if (open ARCHITECTURE, "$baseProductDir/Architecture") {
332 $architecture = <ARCHITECTURE>;
338 if (not defined $xcodeSDK or $xcodeSDK =~ /^(\/$|macosx)/) {
339 my $supports64Bit = `sysctl -n hw.optional.x86_64`;
340 chomp $supports64Bit;
341 $architecture = 'x86_64' if $supports64Bit;
342 } elsif ($xcodeSDK =~ /^iphonesimulator/) {
343 $architecture = 'x86_64';
344 } elsif ($xcodeSDK =~ /^iphoneos/) {
345 $architecture = 'arm64';
348 } elsif (isCMakeBuild()) {
349 if (isCrossCompilation()) {
350 my $compiler = "gcc";
351 $compiler = $ENV{'CC'} if (defined($ENV{'CC'}));
352 my @compiler_machine = split('-', `$compiler -dumpmachine`);
353 $architecture = $compiler_machine[0];
354 } elsif (open my $cmake_sysinfo, "cmake --system-information |") {
355 while (<$cmake_sysinfo>) {
356 next unless index($_, 'CMAKE_SYSTEM_PROCESSOR') == 0;
357 if (/^CMAKE_SYSTEM_PROCESSOR \"([^"]+)\"/) {
362 close $cmake_sysinfo;
366 if (!isAnyWindows()) {
367 if (!$architecture) {
368 # Fall back to output of `uname -m', if it is present.
369 $architecture = `uname -m`;
374 $architecture = 'x86_64' if $architecture =~ /amd64/i;
375 $architecture = 'arm64' if $architecture =~ /aarch64/i;
378 sub determineASanIsEnabled
380 return if defined $asanIsEnabled;
381 determineBaseProductDir();
384 my $asanConfigurationValue;
386 if (open ASAN, "$baseProductDir/ASan") {
387 $asanConfigurationValue = <ASAN>;
389 chomp $asanConfigurationValue;
390 $asanIsEnabled = 1 if $asanConfigurationValue eq "YES";
394 sub determineNumberOfCPUs
396 return if defined $numberOfCPUs;
397 if (defined($ENV{NUMBER_OF_PROCESSORS})) {
398 $numberOfCPUs = $ENV{NUMBER_OF_PROCESSORS};
399 } elsif (isLinux()) {
400 # First try the nproc utility, if it exists. If we get no
401 # results fall back to just interpretting /proc directly.
402 chomp($numberOfCPUs = `nproc --all 2> /dev/null`);
403 if ($numberOfCPUs eq "") {
404 $numberOfCPUs = (grep /processor/, `cat /proc/cpuinfo`);
406 } elsif (isAnyWindows()) {
408 $numberOfCPUs = `ls /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor | wc -w`;
409 } elsif (isDarwin() || isBSD()) {
410 chomp($numberOfCPUs = `sysctl -n hw.ncpu`);
414 sub determineMaxCPULoad
416 return if defined $maxCPULoad;
417 if (defined($ENV{MAX_CPU_LOAD})) {
418 $maxCPULoad = $ENV{MAX_CPU_LOAD};
424 my ($productDir) = @_;
426 $jscName .= "_debug" if configuration() eq "Debug_All";
427 $jscName .= ".exe" if (isAnyWindows());
428 return "$productDir/$jscName" if -e "$productDir/$jscName";
429 return "$productDir/JavaScriptCore.framework/Resources/$jscName";
432 sub argumentsForConfiguration()
434 determineConfiguration();
435 determineArchitecture();
439 # FIXME: Is it necessary to pass --debug, --release, --32-bit or --64-bit?
440 # These are determined automatically from stored configuration.
441 push(@args, '--debug') if ($configuration =~ "^Debug");
442 push(@args, '--release') if ($configuration =~ "^Release");
443 push(@args, '--ios-device') if (defined $xcodeSDK && $xcodeSDK =~ /^iphoneos/);
444 push(@args, '--ios-simulator') if (defined $xcodeSDK && $xcodeSDK =~ /^iphonesimulator/);
445 push(@args, '--32-bit') if ($architecture ne "x86_64" and !isWin64());
446 push(@args, '--64-bit') if (isWin64());
447 push(@args, '--gtk') if isGtk();
448 push(@args, '--efl') if isEfl();
449 push(@args, '--jsc-only') if isJSCOnly();
450 push(@args, '--wincairo') if isWinCairo();
451 push(@args, '--inspector-frontend') if isInspectorFrontend();
455 sub determineXcodeSDK
457 return if defined $xcodeSDK;
459 if (checkForArgumentAndRemoveFromARGVGettingValue("--sdk", \$sdk)) {
462 if (checkForArgumentAndRemoveFromARGV("--device") || checkForArgumentAndRemoveFromARGV("--ios-device")) {
463 my $hasInternalSDK = exitStatus(system("xcrun --sdk iphoneos.internal --show-sdk-version > /dev/null 2>&1")) == 0;
464 $xcodeSDK ||= $hasInternalSDK ? "iphoneos.internal" : "iphoneos";
466 if (checkForArgumentAndRemoveFromARGV("--simulator") || checkForArgumentAndRemoveFromARGV("--ios-simulator")) {
467 $xcodeSDK ||= 'iphonesimulator';
469 if (checkForArgumentAndRemoveFromARGV("--tvos-device")) {
470 my $hasInternalSDK = exitStatus(system("xcrun --sdk appletvos.internal --show-sdk-version > /dev/null 2>&1")) == 0;
471 $xcodeSDK ||= $hasInternalSDK ? "appletvos.internal" : "appletvos";
473 if (checkForArgumentAndRemoveFromARGV("--tvos-simulator")) {
474 $xcodeSDK ||= "appletvsimulator";
476 if (checkForArgumentAndRemoveFromARGV("--watchos-device")) {
477 my $hasInternalSDK = exitStatus(system("xcrun --sdk watchos.internal --show-sdk-version > /dev/null 2>&1")) == 0;
478 $xcodeSDK ||= $hasInternalSDK ? "watchos.internal" : "watchos";
480 if (checkForArgumentAndRemoveFromARGV("--watchos-simulator")) {
481 $xcodeSDK ||= "watchsimulator";
497 sub xcodeSDKPlatformName()
500 return "" if !defined $xcodeSDK;
501 return "appletvos" if $xcodeSDK =~ /appletvos/i;
502 return "appletvsimulator" if $xcodeSDK =~ /appletvsimulator/i;
503 return "iphoneos" if $xcodeSDK =~ /iphoneos/i;
504 return "iphonesimulator" if $xcodeSDK =~ /iphonesimulator/i;
505 return "macosx" if $xcodeSDK =~ /macosx/i;
506 return "watchos" if $xcodeSDK =~ /watchos/i;
507 return "watchsimulator" if $xcodeSDK =~ /watchsimulator/i;
508 die "Couldn't determine platform name from Xcode SDK";
515 die "Can't find the SDK path because no Xcode SDK was specified" if not $xcodeSDK;
517 my $sdkPath = `xcrun --sdk $xcodeSDK --show-sdk-path` if $xcodeSDK;
518 die 'Failed to get SDK path from xcrun' if $?;
528 die "Can't find the SDK version because no Xcode SDK was specified" if !$xcodeSDK;
530 chomp(my $sdkVersion = `xcrun --sdk $xcodeSDK --show-sdk-version`);
531 die "Failed to get SDK version from xcrun" if exitStatus($?);
538 return $programFilesPath if defined $programFilesPath;
540 $programFilesPath = $ENV{'PROGRAMFILES(X86)'} || $ENV{'PROGRAMFILES'} || "C:\\Program Files";
542 return $programFilesPath;
545 sub visualStudioInstallDir
547 return $vsInstallDir if defined $vsInstallDir;
549 if ($ENV{'VSINSTALLDIR'}) {
550 $vsInstallDir = $ENV{'VSINSTALLDIR'};
551 $vsInstallDir =~ s|[\\/]$||;
553 $vsInstallDir = File::Spec->catdir(programFilesPath(), "Microsoft Visual Studio 14.0");
555 chomp($vsInstallDir = `cygpath "$vsInstallDir"`) if isCygwin();
557 print "Using Visual Studio: $vsInstallDir\n";
558 return $vsInstallDir;
561 sub msBuildInstallDir
563 return $msBuildInstallDir if defined $msBuildInstallDir;
565 $msBuildInstallDir = File::Spec->catdir(programFilesPath(), "MSBuild", "14.0", "Bin");
567 chomp($msBuildInstallDir = `cygpath "$msBuildInstallDir"`) if isCygwin();
569 print "Using MSBuild: $msBuildInstallDir\n";
570 return $msBuildInstallDir;
573 sub visualStudioVersion
575 return $vsVersion if defined $vsVersion;
577 my $installDir = visualStudioInstallDir();
579 $vsVersion = ($installDir =~ /Microsoft Visual Studio ([0-9]+\.[0-9]*)/) ? $1 : "14";
581 print "Using Visual Studio $vsVersion\n";
585 sub determineConfigurationForVisualStudio
587 return if defined $configurationForVisualStudio;
588 determineConfiguration();
589 # FIXME: We should detect when Debug_All or Production has been chosen.
590 $configurationForVisualStudio = "/p:Configuration=" . $configuration;
593 sub usesPerConfigurationBuildDirectory
595 # [Gtk] We don't have Release/Debug configurations in straight
596 # autotool builds (non build-webkit). In this case and if
597 # WEBKIT_OUTPUTDIR exist, use that as our configuration dir. This will
598 # allows us to run run-webkit-tests without using build-webkit.
599 return ($ENV{"WEBKIT_OUTPUTDIR"} && isGtk()) || isAppleWinWebKit();
602 sub determineConfigurationProductDir
604 return if defined $configurationProductDir;
605 determineBaseProductDir();
606 determineConfiguration();
607 if (isAppleWinWebKit() || isWinCairo()) {
608 $configurationProductDir = File::Spec->catdir($baseProductDir, $configuration);
610 if (usesPerConfigurationBuildDirectory()) {
611 $configurationProductDir = "$baseProductDir";
613 $configurationProductDir = "$baseProductDir/$configuration";
614 $configurationProductDir .= "-" . xcodeSDKPlatformName() if isIOSWebKit();
619 sub setConfigurationProductDir($)
621 ($configurationProductDir) = @_;
624 sub determineCurrentSVNRevision
626 # We always update the current SVN revision here, and leave the caching
627 # to currentSVNRevision(), so that changes to the SVN revision while the
628 # script is running can be picked up by calling this function again.
629 determineSourceDir();
630 $currentSVNRevision = svnRevisionForDirectory($sourceDir);
631 return $currentSVNRevision;
637 determineSourceDir();
638 chdir $sourceDir or die;
643 determineBaseProductDir();
644 return $baseProductDir;
649 determineSourceDir();
655 determineConfigurationProductDir();
656 return $configurationProductDir;
659 sub executableProductDir
661 my $productDirectory = productDir();
664 if (isEfl() || isGtk() || isJSCOnly()) {
665 $binaryDirectory = "bin";
666 } elsif (isAnyWindows()) {
667 $binaryDirectory = isWin64() ? "bin64" : "bin32";
669 return $productDirectory;
672 return File::Spec->catdir($productDirectory, $binaryDirectory);
677 return executableProductDir();
682 determineConfiguration();
683 return $configuration;
688 determineASanIsEnabled();
689 return $asanIsEnabled;
692 sub configurationForVisualStudio()
694 determineConfigurationForVisualStudio();
695 return $configurationForVisualStudio;
698 sub currentSVNRevision
700 determineCurrentSVNRevision() if not defined $currentSVNRevision;
701 return $currentSVNRevision;
706 determineGenerateDsym();
707 return $generateDsym;
710 sub determineGenerateDsym()
712 return if defined($generateDsym);
713 $generateDsym = checkForArgumentAndRemoveFromARGV("--dsym");
716 sub hasIOSDevelopmentCertificate()
718 return !exitStatus(system("security find-identity -p codesigning | grep '" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX . "' > /dev/null 2>&1"));
721 sub argumentsForXcode()
724 push @args, "DEBUG_INFORMATION_FORMAT=dwarf-with-dsym" if generateDsym();
730 determineBaseProductDir();
731 determineConfiguration();
732 determineArchitecture();
733 determineASanIsEnabled();
737 push @options, "-UseSanitizedBuildSystemEnvironment=YES";
738 push @options, ("-configuration", $configuration);
739 push @options, ("-xcconfig", sourceDir() . "/Tools/asan/asan.xcconfig", "ASAN_IGNORE=" . sourceDir() . "/Tools/asan/webkit-asan-ignore.txt") if $asanIsEnabled;
740 push @options, @baseProductDirOption;
741 push @options, "ARCHS=$architecture" if $architecture;
742 push @options, "SDKROOT=$xcodeSDK" if $xcodeSDK;
743 if (willUseIOSDeviceSDK()) {
744 push @options, "ENABLE_BITCODE=NO";
745 if (hasIOSDevelopmentCertificate()) {
746 # FIXME: May match more than one installed development certificate.
747 push @options, "CODE_SIGN_IDENTITY=" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX;
749 push @options, "CODE_SIGN_IDENTITY="; # No identity
750 push @options, "CODE_SIGNING_REQUIRED=NO";
753 push @options, argumentsForXcode();
757 sub XcodeOptionString
759 return join " ", XcodeOptions();
762 sub XcodeOptionStringNoConfig
764 return join " ", @baseProductDirOption;
767 sub XcodeCoverageSupportOptions()
769 my @coverageSupportOptions = ();
770 push @coverageSupportOptions, "GCC_GENERATE_TEST_COVERAGE_FILES=YES";
771 push @coverageSupportOptions, "GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES";
772 return @coverageSupportOptions;
775 sub XcodeStaticAnalyzerOption()
777 return "RUN_CLANG_STATIC_ANALYZER=YES";
780 my $passedConfiguration;
781 my $searchedForPassedConfiguration;
782 sub determinePassedConfiguration
784 return if $searchedForPassedConfiguration;
785 $searchedForPassedConfiguration = 1;
786 $passedConfiguration = undef;
788 if (checkForArgumentAndRemoveFromARGV("--debug")) {
789 $passedConfiguration = "Debug";
790 } elsif(checkForArgumentAndRemoveFromARGV("--release")) {
791 $passedConfiguration = "Release";
792 } elsif (checkForArgumentAndRemoveFromARGV("--profile") || checkForArgumentAndRemoveFromARGV("--profiling")) {
793 $passedConfiguration = "Profiling";
797 sub passedConfiguration
799 determinePassedConfiguration();
800 return $passedConfiguration;
807 if (my $config = shift @_) {
808 $configuration = $config;
812 determinePassedConfiguration();
813 $configuration = $passedConfiguration if $passedConfiguration;
817 my $passedArchitecture;
818 my $searchedForPassedArchitecture;
819 sub determinePassedArchitecture
821 return if $searchedForPassedArchitecture;
822 $searchedForPassedArchitecture = 1;
824 $passedArchitecture = undef;
825 if (checkForArgumentAndRemoveFromARGV("--32-bit")) {
826 if (isAppleCocoaWebKit()) {
827 # PLATFORM_IOS: Don't run `arch` command inside Simulator environment
829 delete $ENV{DYLD_ROOT_PATH};
830 delete $ENV{DYLD_FRAMEWORK_PATH};
832 $passedArchitecture = `arch`;
833 chomp $passedArchitecture;
838 sub passedArchitecture
840 determinePassedArchitecture();
841 return $passedArchitecture;
846 determineArchitecture();
847 return $architecture;
852 determineNumberOfCPUs();
853 return $numberOfCPUs;
858 determineMaxCPULoad();
864 if (my $arch = shift @_) {
865 $architecture = $arch;
869 determinePassedArchitecture();
870 $architecture = $passedArchitecture if $passedArchitecture;
876 die "Safari path is only relevant on Apple Mac platform\n" unless isAppleCocoaWebKit();
880 # Use WEBKIT_SAFARI environment variable if present.
881 my $safariBundle = $ENV{WEBKIT_SAFARI};
882 if (!$safariBundle) {
883 determineConfigurationProductDir();
884 # Use Safari.app in product directory if present (good for Safari development team).
885 if (-d "$configurationProductDir/Safari.app") {
886 $safariBundle = "$configurationProductDir/Safari.app";
891 $safariPath = "$safariBundle/Contents/MacOS/Safari";
893 $safariPath = "/Applications/Safari.app/Contents/MacOS/SafariForWebKitDevelopment";
896 die "Can't find executable at $safariPath.\n" if !-x $safariPath;
900 sub builtDylibPathForName
902 my $libraryName = shift;
903 determineConfigurationProductDir();
906 my $extension = isDarwin() ? ".dylib" : ".so";
907 return "$configurationProductDir/lib/libwebkit2gtk-4.0" . $extension;
910 return "$configurationProductDir/lib/libewebkit2.so";
913 return "$configurationProductDir/$libraryName.framework/$libraryName";
915 if (isAppleCocoaWebKit()) {
916 return "$configurationProductDir/$libraryName.framework/Versions/A/$libraryName";
918 if (isAppleWinWebKit()) {
919 if ($libraryName eq "JavaScriptCore") {
920 return "$baseProductDir/lib/$libraryName.lib";
922 return "$baseProductDir/$libraryName.intermediate/$configuration/$libraryName.intermediate/$libraryName.lib";
926 die "Unsupported platform, can't determine built library locations.\nTry `build-webkit --help` for more information.\n";
929 # Check to see that all the frameworks are built.
930 sub checkFrameworks # FIXME: This is a poor name since only the Mac calls built WebCore a Framework.
932 return if isAnyWindows();
933 my @frameworks = ("JavaScriptCore", "WebCore");
934 push(@frameworks, "WebKit") if isAppleCocoaWebKit(); # FIXME: This seems wrong, all ports should have a WebKit these days.
935 for my $framework (@frameworks) {
936 my $path = builtDylibPathForName($framework);
937 die "Can't find built framework at \"$path\".\n" unless -e $path;
941 sub isInspectorFrontend()
943 determineIsInspectorFrontend();
944 return $isInspectorFrontend;
947 sub determineIsInspectorFrontend()
949 return if defined($isInspectorFrontend);
950 $isInspectorFrontend = checkForArgumentAndRemoveFromARGV("--inspector-frontend");
956 my $devnull = File::Spec->devnull();
958 if (isAnyWindows()) {
959 return exitStatus(system("where /q $command >$devnull 2>&1")) == 0;
961 return exitStatus(system("which $command >$devnull 2>&1")) == 0;
964 sub checkForArgumentAndRemoveFromARGV($)
966 my $argToCheck = shift;
967 return checkForArgumentAndRemoveFromArrayRef($argToCheck, \@ARGV);
970 sub checkForArgumentAndRemoveFromArrayRefGettingValue($$$)
972 my ($argToCheck, $valueRef, $arrayRef) = @_;
973 my $argumentStartRegEx = qr#^$argToCheck(?:=\S|$)#;
975 for (; $i < @$arrayRef; ++$i) {
976 last if $arrayRef->[$i] =~ $argumentStartRegEx;
978 if ($i >= @$arrayRef) {
979 return $$valueRef = undef;
981 my ($key, $value) = split("=", $arrayRef->[$i]);
982 splice(@$arrayRef, $i, 1);
983 if (defined($value)) {
984 # e.g. --sdk=iphonesimulator
985 return $$valueRef = $value;
987 return $$valueRef = splice(@$arrayRef, $i, 1); # e.g. --sdk iphonesimulator
990 sub checkForArgumentAndRemoveFromARGVGettingValue($$)
992 my ($argToCheck, $valueRef) = @_;
993 return checkForArgumentAndRemoveFromArrayRefGettingValue($argToCheck, $valueRef, \@ARGV);
996 sub findMatchingArguments($$)
998 my ($argToCheck, $arrayRef) = @_;
1000 foreach my $index (0 .. $#$arrayRef) {
1001 my $opt = $$arrayRef[$index];
1002 if ($opt =~ /^$argToCheck$/i ) {
1003 push(@matchingIndices, $index);
1006 return @matchingIndices;
1011 my ($argToCheck, $arrayRef) = @_;
1012 my @matchingIndices = findMatchingArguments($argToCheck, $arrayRef);
1013 return scalar @matchingIndices > 0;
1016 sub checkForArgumentAndRemoveFromArrayRef
1018 my ($argToCheck, $arrayRef) = @_;
1019 my @indicesToRemove = findMatchingArguments($argToCheck, $arrayRef);
1020 my $removeOffset = 0;
1021 foreach my $index (@indicesToRemove) {
1022 splice(@$arrayRef, $index - $removeOffset++, 1);
1024 return scalar @indicesToRemove > 0;
1027 sub prohibitUnknownPort()
1029 $unknownPortProhibited = 1;
1032 sub determinePortName()
1034 return if defined $portName;
1036 my %argToPortName = (
1039 'jsc-only' => JSCOnly,
1040 wincairo => WinCairo
1043 for my $arg (sort keys %argToPortName) {
1044 if (checkForArgumentAndRemoveFromARGV("--$arg")) {
1045 die "Argument '--$arg' conflicts with selected port '$portName'\n"
1046 if defined $portName;
1048 $portName = $argToPortName{$arg};
1052 return if defined $portName;
1054 # Port was not selected via command line, use appropriate default value
1056 if (isAnyWindows()) {
1057 $portName = AppleWin;
1058 } elsif (isDarwin()) {
1059 determineXcodeSDK();
1060 if (willUseIOSDeviceSDK() || willUseIOSSimulatorSDK()) {
1062 } elsif (willUseAppleTVDeviceSDK() || willUseAppleTVSimulatorSDK()) {
1064 } elsif (willUseWatchDeviceSDK() || willUseWatchSimulatorSDK()) {
1065 $portName = watchOS;
1070 if ($unknownPortProhibited) {
1071 my $portsChoice = join "\n\t", qw(
1076 die "Please specify which WebKit port to build using one of the following options:"
1077 . "\n\t$portsChoice\n";
1080 # If script is run without arguments we cannot determine port
1081 # TODO: This state should be outlawed
1082 $portName = Unknown;
1088 determinePortName();
1094 return portName() eq Efl;
1099 return portName() eq GTK;
1104 return portName() eq JSCOnly;
1107 # Determine if this is debian, ubuntu, linspire, or something similar.
1110 return -e "/etc/debian_version";
1115 return -e "/etc/fedora-release";
1120 return portName() eq WinCairo;
1129 sub determineIsWin64()
1131 return if defined($isWin64);
1132 $isWin64 = checkForArgumentAndRemoveFromARGV("--64-bit");
1135 sub determineIsWin64FromArchitecture($)
1138 $isWin64 = ($arch eq "x86_64");
1144 return ($^O eq "cygwin") || 0;
1149 return isWindows() || isCygwin();
1152 sub determineWinVersion()
1154 return if $winVersion;
1156 if (!isAnyWindows()) {
1161 my $versionString = `cmd /c ver`;
1162 $versionString =~ /(\d)\.(\d)\.(\d+)/;
1173 determineWinVersion();
1179 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 1 && winVersion()->{build} == 7600;
1182 sub isWindowsVista()
1184 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 0;
1189 return isAnyWindows() && winVersion()->{major} == 5 && winVersion()->{minor} == 1;
1194 return ($^O eq "darwin") || 0;
1199 return ($^O eq "MSWin32") || 0;
1204 return ($^O eq "linux") || 0;
1209 return ($^O eq "freebsd") || ($^O eq "openbsd") || ($^O eq "netbsd") || 0;
1214 return (architecture() eq "x86_64") || 0;
1217 sub isCrossCompilation()
1220 $compiler = $ENV{'CC'} if (defined($ENV{'CC'}));
1221 if ($compiler =~ /gcc/) {
1222 my $compilerOptions = `$compiler -v 2>&1`;
1223 my @host = $compilerOptions =~ m/--host=(.*?)\s/;
1224 my @target = $compilerOptions =~ m/--target=(.*?)\s/;
1225 if ($target[0] ne "" && $host[0] ne "") {
1226 return ($host[0] ne $target[0]);
1228 # $tempDir gets automatically deleted when goes out of scope
1229 my $tempDir = File::Temp->newdir();
1230 my $testProgramSourcePath = File::Spec->catfile($tempDir, "testcross.c");
1231 my $testProgramBinaryPath = File::Spec->catfile($tempDir, "testcross");
1232 open(my $testProgramSourceHandler, ">", $testProgramSourcePath);
1233 print $testProgramSourceHandler "int main() { return 0; }\n";
1234 system("$compiler $testProgramSourcePath -o $testProgramBinaryPath > /dev/null 2>&1") == 0 or return 0;
1235 # Crosscompiling if the program fails to run (because it was built for other arch)
1236 system("$testProgramBinaryPath > /dev/null 2>&1") == 0 or return 1;
1245 return isAppleCocoaWebKit() || isAppleWinWebKit();
1248 sub isAppleCocoaWebKit()
1250 return (portName() eq Mac) || isIOSWebKit() || isTVOSWebKit() || isWatchOSWebKit();
1253 sub isAppleWinWebKit()
1255 return portName() eq AppleWin;
1258 sub iOSSimulatorDevicesPath
1260 return "$ENV{HOME}/Library/Developer/CoreSimulator/Devices";
1263 sub iOSSimulatorDevices
1265 eval "require Foundation";
1266 my $devicesPath = iOSSimulatorDevicesPath();
1267 opendir(DEVICES, $devicesPath);
1269 $_ =~ m/^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$/;
1273 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
1274 # dictionary keys so as to decouple our representation of the plist from the actual structure
1275 # of the plist, which may change.
1277 Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_("$devicesPath/$_/device.plist"));
1283 sub createiOSSimulatorDevice
1286 my $deviceTypeId = shift;
1287 my $runtimeId = shift;
1289 my $created = system("xcrun", "--sdk", "iphonesimulator", "simctl", "create", $name, $deviceTypeId, $runtimeId) == 0;
1290 die "Couldn't create simulator device: $name $deviceTypeId $runtimeId" if not $created;
1292 system("xcrun", "--sdk", "iphonesimulator", "simctl", "list");
1294 print "Waiting for device to be created ...\n";
1296 for (my $tries = 0; $tries < 5; $tries++){
1297 my @devices = iOSSimulatorDevices();
1298 foreach my $device (@devices) {
1299 return $device if $device->{name} eq $name and $device->{deviceType} eq $deviceTypeId and $device->{runtime} eq $runtimeId;
1303 die "Device $name $deviceTypeId $runtimeId wasn't found in " . iOSSimulatorDevicesPath();
1306 sub willUseIOSDeviceSDK()
1308 return xcodeSDKPlatformName() eq "iphoneos";
1311 sub willUseIOSSimulatorSDK()
1313 return xcodeSDKPlatformName() eq "iphonesimulator";
1316 sub willUseAppleTVDeviceSDK()
1318 return xcodeSDKPlatformName() eq "appletvos";
1321 sub willUseAppleTVSimulatorSDK()
1323 return xcodeSDKPlatformName() eq "appletvsimulator";
1326 sub willUseWatchDeviceSDK()
1328 return xcodeSDKPlatformName() eq "watchos";
1331 sub willUseWatchSimulatorSDK()
1333 return xcodeSDKPlatformName() eq "watchsimulator";
1338 return portName() eq iOS;
1343 return portName() eq tvOS;
1346 sub isWatchOSWebKit()
1348 return portName() eq watchOS;
1351 sub isEmbeddedWebKit()
1353 return isIOSWebKit() || isTVOSWebKit() || isWatchOSWebKit();
1356 sub determineNmPath()
1360 if (isAppleCocoaWebKit()) {
1361 $nmPath = `xcrun -find nm`;
1364 $nmPath = "nm" if !$nmPath;
1373 sub splitVersionString
1375 my $versionString = shift;
1376 my @splitVersion = split(/\./, $versionString);
1377 @splitVersion >= 2 or die "Invalid version $versionString";
1379 "major" => $splitVersion[0],
1380 "minor" => $splitVersion[1],
1381 "subminor" => (defined($splitVersion[2]) ? $splitVersion[2] : 0),
1385 sub determineOSXVersion()
1387 return if $osXVersion;
1394 my $versionString = `sw_vers -productVersion`;
1395 $osXVersion = splitVersionString($versionString);
1400 determineOSXVersion();
1404 sub determineIOSVersion()
1406 return if $iosVersion;
1408 if (!isIOSWebKit()) {
1413 my $versionString = xcodeSDKVersion();
1414 $iosVersion = splitVersionString($versionString);
1419 determineIOSVersion();
1425 return $ENV{'OS'} eq 'Windows_NT';
1428 sub appendToEnvironmentVariableList($$)
1430 my ($name, $value) = @_;
1432 if (defined($ENV{$name})) {
1433 $ENV{$name} .= $Config{path_sep} . $value;
1435 $ENV{$name} = $value;
1439 sub prependToEnvironmentVariableList($$)
1441 my ($name, $value) = @_;
1443 if (defined($ENV{$name})) {
1444 $ENV{$name} = $value . $Config{path_sep} . $ENV{$name};
1446 $ENV{$name} = $value;
1450 sub sharedCommandLineOptions()
1453 "g|guard-malloc" => \$shouldUseGuardMalloc,
1457 sub sharedCommandLineOptionsUsage
1462 '-g|--guard-malloc' => 'Use guardmalloc when running executable',
1465 my $indent = " " x ($opts{indent} || 2);
1466 my $switchWidth = List::Util::max(int($opts{switchWidth}), List::Util::max(map { length($_) } keys %switches) + ($opts{brackets} ? 2 : 0));
1468 my $result = "Common switches:\n";
1470 for my $switch (keys %switches) {
1471 my $switchName = $opts{brackets} ? "[" . $switch . "]" : $switch;
1472 $result .= sprintf("%s%-" . $switchWidth . "s %s\n", $indent, $switchName, $switches{$switch});
1478 sub setUpGuardMallocIfNeeded
1484 if (!defined($shouldUseGuardMalloc)) {
1485 $shouldUseGuardMalloc = checkForArgumentAndRemoveFromARGV("-g") || checkForArgumentAndRemoveFromARGV("--guard-malloc");
1488 if ($shouldUseGuardMalloc) {
1489 appendToEnvironmentVariableList("DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1490 appendToEnvironmentVariableList("__XPC_DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1494 sub relativeScriptsDir()
1496 my $scriptDir = File::Spec->catpath("", File::Spec->abs2rel($FindBin::Bin, getcwd()), "");
1497 if ($scriptDir eq "") {
1505 my $relativeScriptsPath = relativeScriptsDir();
1506 if (isGtk() || isEfl()) {
1507 return "$relativeScriptsPath/run-minibrowser";
1508 } elsif (isAppleWebKit()) {
1509 return "$relativeScriptsPath/run-safari";
1515 if (isGtk() || isEfl()) {
1516 return "MiniBrowser";
1517 } elsif (isAppleCocoaWebKit()) {
1519 } elsif (isAppleWinWebKit()) {
1520 return "MiniBrowser";
1524 sub checkRequiredSystemConfig
1527 chomp(my $productVersion = `sw_vers -productVersion`);
1528 if (eval "v$productVersion" lt v10.10.5) {
1529 print "*************************************************************\n";
1530 print "OS X Yosemite v10.10.5 or later is required to build WebKit.\n";
1531 print "You have " . $productVersion . ", thus the build will most likely fail.\n";
1532 print "*************************************************************\n";
1534 determineXcodeVersion();
1535 if (eval "v$xcodeVersion" lt v7.0) {
1536 print "*************************************************************\n";
1537 print "Xcode 7.0 or later is required to build WebKit.\n";
1538 print "You have an earlier version of Xcode, thus the build will\n";
1539 print "most likely fail. The latest Xcode is available from the App Store.\n";
1540 print "*************************************************************\n";
1545 sub determineWindowsSourceDir()
1547 return if $windowsSourceDir;
1548 $windowsSourceDir = sourceDir();
1549 chomp($windowsSourceDir = `cygpath -w '$windowsSourceDir'`) if isCygwin();
1552 sub windowsSourceDir()
1554 determineWindowsSourceDir();
1555 return $windowsSourceDir;
1558 sub windowsSourceSourceDir()
1560 return File::Spec->catdir(windowsSourceDir(), "Source");
1563 sub windowsLibrariesDir()
1565 return File::Spec->catdir(windowsSourceDir(), "WebKitLibraries", "win");
1568 sub windowsOutputDir()
1570 return File::Spec->catdir(windowsSourceDir(), "WebKitBuild");
1576 my $cmd = "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\" /v \"$font\" 2>&1";
1581 sub checkInstalledTools()
1583 # environment variables. Avoid until this is corrected.
1584 my $pythonVer = `python --version 2>&1`;
1585 die "You must have Python installed to build WebKit.\n" if ($?);
1587 # cURL 7.34.0 has a bug that prevents authentication with opensource.apple.com (and other things using SSL3).
1588 my $curlVer = `curl --version 2> NUL`;
1589 if (!$? and $curlVer =~ "(.*curl.*)") {
1591 if ($curlVer =~ /libcurl\/7\.34\.0/) {
1592 print "cURL version 7.34.0 has a bug that prevents authentication with SSL v2 or v3.\n";
1593 print "cURL 7.33.0 is known to work. The cURL projects is preparing an update to\n";
1594 print "correct this problem.\n\n";
1595 die "Please install a working cURL and try again.\n";
1599 # MathML requires fonts that may not ship with Windows.
1600 # Warn the user if they are missing.
1601 my @fonts = ('Cambria & Cambria Math (TrueType)', 'LatinModernMath-Regular (TrueType)', 'STIXMath-Regular (TrueType)');
1603 foreach my $font (@fonts) {
1604 push @missing, $font if not fontExists($font);
1607 if (scalar @missing > 0) {
1608 print "*************************************************************\n";
1609 print "Mathematical fonts, such as Latin Modern Math are needed to\n";
1610 print "use the MathML feature. You do not appear to have these fonts\n";
1611 print "on your system.\n\n";
1612 print "You can download a suitable set of fonts from the following URL:\n";
1613 print "https://trac.webkit.org/wiki/MathML/Fonts\n";
1614 print "*************************************************************\n";
1617 print "Installed tools are correct for the WebKit build.\n";
1620 sub setupAppleWinEnv()
1622 return unless isAppleWinWebKit();
1624 checkInstalledTools();
1626 if (isWindowsNT()) {
1627 my $restartNeeded = 0;
1628 my %variablesToSet = ();
1630 # FIXME: We should remove this explicit version check for cygwin once we stop supporting Cygwin 1.7.9 or older versions.
1631 # https://bugs.webkit.org/show_bug.cgi?id=85791
1632 my $uname_version = (POSIX::uname())[2];
1633 $uname_version =~ s/\(.*\)//; # Remove the trailing cygwin version, if any.
1634 $uname_version =~ s/\-.*$//; # Remove trailing dash-version content, if any
1635 if (version->parse($uname_version) < version->parse("1.7.10")) {
1636 # Setting the environment variable 'CYGWIN' to 'tty' makes cygwin enable extra support (i.e., termios)
1637 # for UNIX-like ttys in the Windows console
1638 $variablesToSet{CYGWIN} = "tty" unless $ENV{CYGWIN};
1641 # Those environment variables must be set to be able to build inside Visual Studio.
1642 $variablesToSet{WEBKIT_LIBRARIES} = windowsLibrariesDir() unless $ENV{WEBKIT_LIBRARIES};
1643 $variablesToSet{WEBKIT_OUTPUTDIR} = windowsOutputDir() unless $ENV{WEBKIT_OUTPUTDIR};
1644 $variablesToSet{MSBUILDDISABLENODEREUSE} = "1" unless $ENV{MSBUILDDISABLENODEREUSE};
1645 $variablesToSet{_IsNativeEnvironment} = "true" unless $ENV{_IsNativeEnvironment};
1646 $variablesToSet{PreferredToolArchitecture} = "x64" unless $ENV{PreferredToolArchitecture};
1648 foreach my $variable (keys %variablesToSet) {
1649 print "Setting the Environment Variable '" . $variable . "' to '" . $variablesToSet{$variable} . "'\n\n";
1650 my $ret = system "setx", $variable, $variablesToSet{$variable};
1652 system qw(regtool -s set), '\\HKEY_CURRENT_USER\\Environment\\' . $variable, $variablesToSet{$variable};
1654 $restartNeeded ||= $variable eq "WEBKIT_LIBRARIES" || $variable eq "WEBKIT_OUTPUTDIR";
1657 if ($restartNeeded) {
1658 print "Please restart your computer before attempting to build inside Visual Studio.\n\n";
1661 if (!defined $ENV{'WEBKIT_LIBRARIES'} || !$ENV{'WEBKIT_LIBRARIES'}) {
1662 print "Warning: You must set the 'WebKit_Libraries' environment variable\n";
1663 print " to be able build WebKit from within Visual Studio 2013 and newer.\n";
1664 print " Make sure that 'WebKit_Libraries' points to the\n";
1665 print " 'WebKitLibraries/win' directory, not the 'WebKitLibraries/' directory.\n\n";
1667 if (!defined $ENV{'WEBKIT_OUTPUTDIR'} || !$ENV{'WEBKIT_OUTPUTDIR'}) {
1668 print "Warning: You must set the 'WebKit_OutputDir' environment variable\n";
1669 print " to be able build WebKit from within Visual Studio 2013 and newer.\n\n";
1671 if (!defined $ENV{'MSBUILDDISABLENODEREUSE'} || !$ENV{'MSBUILDDISABLENODEREUSE'}) {
1672 print "Warning: You should set the 'MSBUILDDISABLENODEREUSE' environment variable to '1'\n";
1673 print " to avoid periodic locked log files when building.\n\n";
1676 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1677 if (isWin64() and !$ENV{'WEBKIT_64_SUPPORT'}) {
1678 print "Warning: You must set the 'WEBKIT_64_SUPPORT' environment variable\n";
1679 print " to be able run WebKit or JavaScriptCore tests.\n\n";
1683 sub setupCygwinEnv()
1685 return if !isAnyWindows();
1686 return if $vcBuildPath;
1688 my $programFilesPath = programFilesPath();
1689 my $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE devenv.com));
1690 if (-e $visualStudioPath) {
1691 # Visual Studio is installed;
1692 if (visualStudioVersion() eq "12") {
1693 $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE devenv.exe));
1696 # Visual Studio not found, try VC++ Express
1697 $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE WDExpress.exe));
1698 if (! -e $visualStudioPath) {
1699 print "*************************************************************\n";
1700 print "Cannot find '$visualStudioPath'\n";
1701 print "Please execute the file 'vcvars32.bat' from\n";
1702 print "'$programFilesPath\\Microsoft Visual Studio 14.0\\VC\\bin\\'\n";
1703 print "to setup the necessary environment variables.\n";
1704 print "*************************************************************\n";
1707 $willUseVCExpressWhenBuilding = 1;
1710 print "Building results into: ", baseProductDir(), "\n";
1711 print "WEBKIT_OUTPUTDIR is set to: ", $ENV{"WEBKIT_OUTPUTDIR"}, "\n";
1712 print "WEBKIT_LIBRARIES is set to: ", $ENV{"WEBKIT_LIBRARIES"}, "\n";
1713 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1714 print "WEBKIT_64_SUPPORT is set to: ", $ENV{"WEBKIT_64_SUPPORT"}, "\n" if isWin64();
1716 # We will actually use MSBuild to build WebKit, but we need to find the Visual Studio install (above) to make
1717 # sure we use the right options.
1718 $vcBuildPath = File::Spec->catfile(msBuildInstallDir(), qw(MSBuild.exe));
1719 if (! -e $vcBuildPath) {
1720 print "*************************************************************\n";
1721 print "Cannot find '$vcBuildPath'\n";
1722 print "Please make sure execute that the Microsoft .NET Framework SDK\n";
1723 print "is installed on this machine.\n";
1724 print "*************************************************************\n";
1729 sub dieIfWindowsPlatformSDKNotInstalled
1731 my $registry32Path = "/proc/registry/";
1732 my $registry64Path = "/proc/registry64/";
1733 my @windowsPlatformSDKRegistryEntries = (
1734 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0A",
1735 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0",
1736 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.1A",
1737 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.0A",
1738 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/MicrosoftSDK/InstalledSDKs/D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1",
1741 # FIXME: It would be better to detect whether we are using 32- or 64-bit Windows
1742 # and only check the appropriate entry. But for now we just blindly check both.
1743 my $recommendedPlatformSDK = $windowsPlatformSDKRegistryEntries[0];
1745 while (@windowsPlatformSDKRegistryEntries) {
1746 my $windowsPlatformSDKRegistryEntry = shift @windowsPlatformSDKRegistryEntries;
1747 return if (-e $registry32Path . $windowsPlatformSDKRegistryEntry) || (-e $registry64Path . $windowsPlatformSDKRegistryEntry);
1750 print "*************************************************************\n";
1751 print "Cannot find registry entry '$recommendedPlatformSDK'.\n";
1752 print "Please download and install the Microsoft Windows SDK\n";
1753 print "from <http://www.microsoft.com/en-us/download/details.aspx?id=8279>.\n\n";
1754 print "Then follow step 2 in the Windows section of the \"Installing Developer\n";
1755 print "Tools\" instructions at <http://www.webkit.org/building/tools.html>.\n";
1756 print "*************************************************************\n";
1760 sub buildXCodeProject($$@)
1762 my ($project, $clean, @extraOptions) = @_;
1765 push(@extraOptions, "-alltargets");
1766 push(@extraOptions, "clean");
1769 chomp($ENV{DSYMUTIL_NUM_THREADS} = `sysctl -n hw.activecpu`);
1770 return system "xcodebuild", "-project", "$project.xcodeproj", @extraOptions;
1773 sub usingVisualStudioExpress()
1776 return $willUseVCExpressWhenBuilding;
1779 sub buildVisualStudioProject
1781 my ($project, $clean) = @_;
1784 my $config = configurationForVisualStudio();
1786 dieIfWindowsPlatformSDKNotInstalled() if $willUseVCExpressWhenBuilding;
1788 chomp($project = `cygpath -w "$project"`) if isCygwin();
1790 my $action = "/t:build";
1792 $action = "/t:clean";
1795 my $platform = "/p:Platform=" . (isWin64() ? "x64" : "Win32");
1796 my $logPath = File::Spec->catdir($baseProductDir, $configuration);
1797 make_path($logPath) unless -d $logPath or $logPath eq ".";
1799 my $errorLogFile = File::Spec->catfile($logPath, "webkit_errors.log");
1800 chomp($errorLogFile = `cygpath -w "$errorLogFile"`) if isCygwin();
1801 my $errorLogging = "/flp:LogFile=" . $errorLogFile . ";ErrorsOnly";
1803 my $warningLogFile = File::Spec->catfile($logPath, "webkit_warnings.log");
1804 chomp($warningLogFile = `cygpath -w "$warningLogFile"`) if isCygwin();
1805 my $warningLogging = "/flp1:LogFile=" . $warningLogFile . ";WarningsOnly";
1807 my @command = ($vcBuildPath, "/verbosity:minimal", $project, $action, $config, $platform, "/fl", $errorLogging, "/fl1", $warningLogging);
1808 print join(" ", @command), "\n";
1809 return system @command;
1812 sub getJhbuildPath()
1814 my @jhbuildPath = File::Spec->splitdir(baseProductDir());
1815 if (isGit() && isGitBranchBuild() && gitBranch()) {
1819 push(@jhbuildPath, "DependenciesEFL");
1821 push(@jhbuildPath, "DependenciesGTK");
1823 die "Cannot get JHBuild path for platform that isn't GTK+ or EFL.\n";
1825 return File::Spec->catdir(@jhbuildPath);
1828 sub isCachedArgumentfileOutOfDate($@)
1830 my ($filename, $currentContents) = @_;
1832 if (! -e $filename) {
1836 open(CONTENTS_FILE, $filename);
1837 chomp(my $previousContents = <CONTENTS_FILE>);
1838 close(CONTENTS_FILE);
1840 if ($previousContents ne $currentContents) {
1841 print "Contents for file $filename have changed.\n";
1842 print "Previous contents were: $previousContents\n\n";
1843 print "New contents are: $currentContents\n";
1850 sub wrapperPrefixIfNeeded()
1852 if (isAnyWindows() || isJSCOnly()) {
1855 if (isAppleCocoaWebKit()) {
1858 if (-e getJhbuildPath()) {
1859 my @prefix = (File::Spec->catfile(sourceDir(), "Tools", "jhbuild", "jhbuild-wrapper"));
1861 push(@prefix, "--efl");
1863 push(@prefix, "--gtk");
1865 push(@prefix, "run");
1873 sub cmakeCachePath()
1875 return File::Spec->catdir(baseProductDir(), configuration(), "CMakeCache.txt");
1878 sub cmakeFilesPath()
1880 return File::Spec->catdir(baseProductDir(), configuration(), "CMakeFiles");
1883 sub shouldRemoveCMakeCache(@)
1885 my ($cacheFilePath, @buildArgs) = @_;
1887 # We check this first, because we always want to create this file for a fresh build.
1888 my $productDir = File::Spec->catdir(baseProductDir(), configuration());
1889 my $optionsCache = File::Spec->catdir($productDir, "build-webkit-options.txt");
1890 my $joinedBuildArgs = join(" ", @buildArgs);
1891 if (isCachedArgumentfileOutOfDate($optionsCache, $joinedBuildArgs)) {
1892 File::Path::mkpath($productDir) unless -d $productDir;
1893 open(CACHED_ARGUMENTS, ">", $optionsCache);
1894 print CACHED_ARGUMENTS $joinedBuildArgs;
1895 close(CACHED_ARGUMENTS);
1900 my $cmakeCache = cmakeCachePath();
1901 unless (-e $cmakeCache) {
1905 my $cacheFileModifiedTime = stat($cmakeCache)->mtime;
1906 my $platformConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "Options" . cmakeBasedPortName() . ".cmake");
1907 if ($cacheFileModifiedTime < stat($platformConfiguration)->mtime) {
1911 my $globalConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "OptionsCommon.cmake");
1912 if ($cacheFileModifiedTime < stat($globalConfiguration)->mtime) {
1916 my $inspectorUserInterfaceDircetory = File::Spec->catdir(sourceDir(), "Source", "WebInspectorUI", "UserInterface");
1917 if ($cacheFileModifiedTime < stat($inspectorUserInterfaceDircetory)->mtime) {
1921 if(isAnyWindows()) {
1922 my $winConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "OptionsWin.cmake");
1923 if ($cacheFileModifiedTime < stat($winConfiguration)->mtime) {
1931 sub removeCMakeCache(@)
1933 my (@buildArgs) = @_;
1934 if (shouldRemoveCMakeCache(@buildArgs)) {
1935 my $cmakeCache = cmakeCachePath();
1936 my $cmakeFiles = cmakeFilesPath();
1937 unlink($cmakeCache) if -e $cmakeCache;
1938 rmtree($cmakeFiles) if -d $cmakeFiles;
1944 if (!defined($shouldNotUseNinja)) {
1945 $shouldNotUseNinja = checkForArgumentAndRemoveFromARGV("--no-ninja");
1948 if ($shouldNotUseNinja) {
1952 # Test both ninja and ninja-build. Fedora uses ninja-build and has patched CMake to also call ninja-build.
1953 return commandExists("ninja") || commandExists("ninja-build");
1956 sub canUseNinjaGenerator(@)
1958 # Check that a Ninja generator is installed
1959 my $devnull = File::Spec->devnull();
1960 return exitStatus(system("cmake -N -G Ninja >$devnull 2>&1")) == 0;
1963 sub canUseEclipseNinjaGenerator(@)
1965 # Check that eclipse and eclipse Ninja generator is installed
1966 my $devnull = File::Spec->devnull();
1967 return commandExists("eclipse") && exitStatus(system("cmake -N -G 'Eclipse CDT4 - Ninja' >$devnull 2>&1")) == 0;
1970 sub cmakeGeneratedBuildfile(@)
1972 my ($willUseNinja) = @_;
1973 if ($willUseNinja) {
1974 return File::Spec->catfile(baseProductDir(), configuration(), "build.ninja")
1975 } elsif (isAnyWindows()) {
1976 return File::Spec->catfile(baseProductDir(), configuration(), "WebKit.sln")
1978 return File::Spec->catfile(baseProductDir(), configuration(), "Makefile")
1982 sub generateBuildSystemFromCMakeProject
1984 my ($prefixPath, @cmakeArgs) = @_;
1985 my $config = configuration();
1986 my $port = cmakeBasedPortName();
1987 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
1988 File::Path::mkpath($buildPath) unless -d $buildPath;
1989 my $originalWorkingDirectory = getcwd();
1990 chdir($buildPath) or die;
1992 # We try to be smart about when to rerun cmake, so that we can have faster incremental builds.
1993 my $willUseNinja = canUseNinja() && canUseNinjaGenerator();
1994 if (-e cmakeCachePath() && -e cmakeGeneratedBuildfile($willUseNinja)) {
1999 push @args, "-DPORT=\"$port\"";
2000 push @args, "-DCMAKE_INSTALL_PREFIX=\"$prefixPath\"" if $prefixPath;
2001 push @args, "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON";
2002 if ($config =~ /release/i) {
2003 push @args, "-DCMAKE_BUILD_TYPE=Release";
2004 } elsif ($config =~ /debug/i) {
2005 push @args, "-DCMAKE_BUILD_TYPE=Debug";
2008 if ($willUseNinja) {
2010 if (canUseEclipseNinjaGenerator()) {
2011 push @args, "'Eclipse CDT4 - Ninja'";
2013 push @args, "Ninja";
2015 } elsif (isAnyWindows() && isWin64()) {
2016 push @args, '-G "Visual Studio 14 2015 Win64"';
2018 # Do not show progress of generating bindings in interactive Ninja build not to leave noisy lines on tty
2019 push @args, '-DSHOW_BINDINGS_GENERATION_PROGRESS=1' unless ($willUseNinja && -t STDOUT);
2021 # Some ports have production mode, but build-webkit should always use developer mode.
2022 push @args, "-DDEVELOPER_MODE=ON" if isEfl() || isGtk() || isJSCOnly();
2024 # Don't warn variables which aren't used by cmake ports.
2025 push @args, "--no-warn-unused-cli";
2026 push @args, @cmakeArgs if @cmakeArgs;
2028 my $cmakeSourceDir = isCygwin() ? windowsSourceDir() : sourceDir();
2029 push @args, '"' . $cmakeSourceDir . '"';
2031 # Compiler options to keep floating point values consistent
2032 # between 32-bit and 64-bit architectures.
2033 determineArchitecture();
2034 if ($architecture eq "i686" && !isCrossCompilation() && !isAnyWindows()) {
2035 $ENV{'CXXFLAGS'} = "-march=pentium4 -msse2 -mfpmath=sse " . ($ENV{'CXXFLAGS'} || "");
2038 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2039 # parsed for shell metacharacters.
2040 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2041 my $returnCode = systemVerbose($wrapper . "cmake @args");
2043 chdir($originalWorkingDirectory);
2047 sub buildCMakeGeneratedProject($)
2049 my ($makeArgs) = @_;
2050 my $config = configuration();
2051 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2052 if (! -d $buildPath) {
2053 die "Must call generateBuildSystemFromCMakeProject() before building CMake project.";
2056 my $command = "cmake";
2057 my @args = ("--build", $buildPath, "--config", $config);
2058 push @args, ("--", $makeArgs) if $makeArgs;
2060 # GTK and JSCOnly can use a build script to preserve colors and pretty-printing.
2061 if ((isGtk() || isJSCOnly()) && -e "$buildPath/build.sh") {
2062 chdir "$buildPath" or die;
2063 $command = "$buildPath/build.sh";
2064 @args = ($makeArgs);
2067 if ($ENV{VERBOSE} && canUseNinja()) {
2069 push @args, "-d keeprsp" if (version->parse(determineNinjaVersion()) >= version->parse("1.4.0"));
2072 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2073 # parsed for shell metacharacters. In particular, $makeArgs may contain such metacharacters.
2074 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2075 return systemVerbose($wrapper . "$command @args");
2078 sub cleanCMakeGeneratedProject()
2080 my $config = configuration();
2081 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2082 if (-d $buildPath) {
2083 return systemVerbose("cmake", "--build", $buildPath, "--config", $config, "--target", "clean");
2088 sub buildCMakeProjectOrExit($$$@)
2090 my ($clean, $prefixPath, $makeArgs, @cmakeArgs) = @_;
2093 exit(exitStatus(cleanCMakeGeneratedProject())) if $clean;
2095 if (isEfl() && checkForArgumentAndRemoveFromARGV("--update-efl")) {
2096 system("perl", "$sourceDir/Tools/Scripts/update-webkitefl-libs") == 0 or die $!;
2099 if (isGtk() && checkForArgumentAndRemoveFromARGV("--update-gtk")) {
2100 system("perl", "$sourceDir/Tools/Scripts/update-webkitgtk-libs") == 0 or die $!;
2103 $returnCode = exitStatus(generateBuildSystemFromCMakeProject($prefixPath, @cmakeArgs));
2104 exit($returnCode) if $returnCode;
2106 $returnCode = exitStatus(buildCMakeGeneratedProject($makeArgs));
2107 exit($returnCode) if $returnCode;
2111 sub cmakeBasedPortArguments()
2116 sub cmakeBasedPortName()
2118 return ucfirst portName();
2121 sub determineIsCMakeBuild()
2123 return if defined($isCMakeBuild);
2124 $isCMakeBuild = checkForArgumentAndRemoveFromARGV("--cmake");
2129 return 1 unless isAppleCocoaWebKit();
2130 determineIsCMakeBuild();
2131 return $isCMakeBuild;
2136 my ($prompt, $default) = @_;
2137 my $defaultValue = $default ? "[$default]" : "";
2138 print "$prompt $defaultValue: ";
2139 chomp(my $input = <STDIN>);
2140 return $input ? $input : $default;
2143 sub appleApplicationSupportPath
2145 open INSTALL_DIR, "</proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/Apple\ Inc./Apple\ Application\ Support/InstallDir";
2146 my $path = <INSTALL_DIR>;
2147 $path =~ s/[\r\n\x00].*//;
2150 my $unixPath = `cygpath -u '$path'`;
2155 sub setPathForRunningWebKitApp
2159 if (isAnyWindows()) {
2160 my $productBinaryDir = executableProductDir();
2161 if (isAppleWinWebKit()) {
2162 $env->{PATH} = join(':', $productBinaryDir, appleApplicationSupportPath(), $env->{PATH} || "");
2163 } elsif (isWinCairo()) {
2164 my $winCairoBin = sourceDir() . "/WebKitLibraries/win/" . (isWin64() ? "bin64/" : "bin32/");
2165 my $gstreamerBin = isWin64() ? $ENV{"GSTREAMER_1_0_ROOT_X86_64"} . "bin" : $ENV{"GSTREAMER_1_0_ROOT_X86"} . "bin";
2166 $env->{PATH} = join(':', $productBinaryDir, $winCairoBin, $gstreamerBin, $env->{PATH} || "");
2171 sub printHelpAndExitForRunAndDebugWebKitAppIfNeeded
2173 return unless checkForArgumentAndRemoveFromARGV("--help");
2176 Usage: @{[basename($0)]} [options] [args ...]
2177 --help Show this help message
2178 --no-saved-state Launch the application without state restoration
2180 Options specific to macOS:
2181 -g|--guard-malloc Enable Guard Malloc
2182 --lang=LANGUAGE Use a specific language instead of system language.
2183 This accepts a language name (German) or a language code (de, ar, pt_BR, etc).
2184 --locale=LOCALE Use a specific locale instead of the system region.
2190 sub argumentsForRunAndDebugMacWebKitApp()
2193 if (checkForArgumentAndRemoveFromARGV("--no-saved-state")) {
2194 push @args, ("-ApplePersistenceIgnoreStateQuietly", "YES");
2195 # FIXME: Don't set ApplePersistenceIgnoreState once all supported OS versions respect ApplePersistenceIgnoreStateQuietly (rdar://15032886).
2196 push @args, ("-ApplePersistenceIgnoreState", "YES");
2200 if (checkForArgumentAndRemoveFromARGVGettingValue("--lang", \$lang)) {
2201 push @args, ("-AppleLanguages", "(" . $lang . ")");
2205 if (checkForArgumentAndRemoveFromARGVGettingValue("--locale", \$locale)) {
2206 push @args, ("-AppleLocale", $locale);
2209 unshift @args, @ARGV;
2214 sub setupMacWebKitEnvironment($)
2216 my ($dyldFrameworkPath) = @_;
2218 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2220 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2221 prependToEnvironmentVariableList("__XPC_DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2222 prependToEnvironmentVariableList("DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2223 prependToEnvironmentVariableList("__XPC_DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2224 $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2226 setUpGuardMallocIfNeeded();
2229 sub setupIOSWebKitEnvironment($)
2231 my ($dyldFrameworkPath) = @_;
2232 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2234 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2235 prependToEnvironmentVariableList("DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2237 setUpGuardMallocIfNeeded();
2240 sub iosSimulatorApplicationsPath()
2242 return File::Spec->catdir(XcodeSDKPath(), "Applications");
2245 sub installedMobileSafariBundle()
2247 return File::Spec->catfile(iosSimulatorApplicationsPath(), "MobileSafari.app");
2250 sub mobileSafariBundle()
2252 determineConfigurationProductDir();
2254 # Use MobileSafari.app in product directory if present.
2255 if (isAppleCocoaWebKit() && -d "$configurationProductDir/MobileSafari.app") {
2256 return "$configurationProductDir/MobileSafari.app";
2258 return installedMobileSafariBundle();
2261 sub plistPathFromBundle($)
2263 my ($appBundle) = @_;
2264 return "$appBundle/Info.plist" if -f "$appBundle/Info.plist"; # iOS app bundle
2265 return "$appBundle/Contents/Info.plist" if -f "$appBundle/Contents/Info.plist"; # Mac app bundle
2269 sub appIdentifierFromBundle($)
2271 my ($appBundle) = @_;
2272 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2273 chomp(my $bundleIdentifier = `defaults read '$plistPath' CFBundleIdentifier 2> /dev/null`);
2274 return $bundleIdentifier;
2277 sub appDisplayNameFromBundle($)
2279 my ($appBundle) = @_;
2280 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2281 chomp(my $bundleDisplayName = `defaults read '$plistPath' CFBundleDisplayName 2> /dev/null`);
2282 return $bundleDisplayName;
2285 sub waitUntilIOSSimulatorDeviceIsInState($$)
2287 my ($deviceUDID, $waitUntilState) = @_;
2288 my $device = iosSimulatorDeviceByUDID($deviceUDID);
2289 # FIXME: We should add a maximum time limit to wait here.
2290 while ($device->{state} ne $waitUntilState) {
2291 usleep(500 * 1000); # Waiting 500ms between file system polls does not make script run-safari feel sluggish.
2292 $device = iosSimulatorDeviceByUDID($deviceUDID);
2296 sub shutDownIOSSimulatorDevice($)
2298 my ($simulatorDevice) = @_;
2299 system("xcrun --sdk iphonesimulator simctl shutdown $simulatorDevice->{UDID} > /dev/null 2>&1");
2302 sub restartIOSSimulatorDevice($)
2304 my ($simulatorDevice) = @_;
2305 shutDownIOSSimulatorDevice($simulatorDevice);
2307 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "boot", $simulatorDevice->{UDID})) == 0 or die "Failed to boot simulator device $simulatorDevice->{UDID}";
2310 sub relaunchIOSSimulator($)
2312 my ($simulatedDevice) = @_;
2313 quitIOSSimulator($simulatedDevice->{UDID});
2315 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2316 chomp(my $developerDirectory = $ENV{DEVELOPER_DIR} || `xcode-select --print-path`);
2317 my $iosSimulatorPath = File::Spec->catfile($developerDirectory, "Applications", "Simulator.app");
2318 system("open", "-a", $iosSimulatorPath, "--args", "-CurrentDeviceUDID", $simulatedDevice->{UDID}) == 0 or die "Failed to open $iosSimulatorPath: $!";
2320 waitUntilIOSSimulatorDeviceIsInState($simulatedDevice->{UDID}, SIMULATOR_DEVICE_STATE_BOOTED);
2323 sub quitIOSSimulator(;$)
2325 my ($waitForShutdownOfSimulatedDeviceUDID) = @_;
2326 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2327 if (exitStatus(system {"osascript"} "osascript", "-e", 'tell application id "com.apple.iphonesimulator" to quit')) {
2328 # osascript returns a non-zero exit status if Simulator.app is not registered in LaunchServices.
2332 if (!defined($waitForShutdownOfSimulatedDeviceUDID)) {
2335 # FIXME: We assume that $waitForShutdownOfSimulatedDeviceUDID was not booted using the simctl command line tool.
2336 # Otherwise we will spin indefinitely since quiting the iOS Simulator will not shutdown this device. We
2337 # should add a maximum time limit to wait for a device to shutdown and either return an error or die()
2338 # on expiration of the time limit.
2339 waitUntilIOSSimulatorDeviceIsInState($waitForShutdownOfSimulatedDeviceUDID, SIMULATOR_DEVICE_STATE_SHUTDOWN);
2342 sub iosSimulatorDeviceByName($)
2344 my ($simulatorName) = @_;
2345 my $simulatorRuntime = iosSimulatorRuntime();
2346 my @devices = iOSSimulatorDevices();
2347 for my $device (@devices) {
2348 if ($device->{name} eq $simulatorName && $device->{runtime} eq $simulatorRuntime) {
2355 sub iosSimulatorDeviceByUDID($)
2357 my ($simulatedDeviceUDID) = @_;
2358 my $devicePlistPath = File::Spec->catfile(iOSSimulatorDevicesPath(), $simulatedDeviceUDID, "device.plist");
2359 if (!-f $devicePlistPath) {
2362 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
2363 # dictionary keys so as to decouple our representation of the plist from the actual structure
2364 # of the plist, which may change.
2365 eval "require Foundation";
2366 return Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_($devicePlistPath));
2369 sub iosSimulatorRuntime()
2371 my $xcodeSDKVersion = xcodeSDKVersion();
2372 $xcodeSDKVersion =~ s/\./-/;
2373 return "com.apple.CoreSimulator.SimRuntime.iOS-$xcodeSDKVersion";
2376 sub findOrCreateSimulatorForIOSDevice($)
2378 my ($simulatorNameSuffix) = @_;
2380 my $simulatorDeviceType;
2381 if (architecture() eq "x86_64") {
2382 $simulatorName = "iPhone 5s " . $simulatorNameSuffix;
2383 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5s";
2385 $simulatorName = "iPhone 5 " . $simulatorNameSuffix;
2386 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5";
2388 my $simulatedDevice = iosSimulatorDeviceByName($simulatorName);
2389 return $simulatedDevice if $simulatedDevice;
2390 return createiOSSimulatorDevice($simulatorName, $simulatorDeviceType, iosSimulatorRuntime());
2393 sub isIOSSimulatorSystemInstalledApp($)
2395 my ($appBundle) = @_;
2396 my $simulatorApplicationsPath = realpath(iosSimulatorApplicationsPath());
2397 return substr(realpath($appBundle), 0, length($simulatorApplicationsPath)) eq $simulatorApplicationsPath;
2400 sub hasUserInstalledAppInSimulatorDevice($$)
2402 my ($appIdentifier, $simulatedDeviceUDID) = @_;
2403 my $userInstalledAppPath = File::Spec->catfile($ENV{HOME}, "Library", "Developer", "CoreSimulator", "Devices", $simulatedDeviceUDID, "data", "Containers", "Bundle", "Application");
2404 if (!-d $userInstalledAppPath) {
2405 return 0; # No user installed apps.
2407 local @::userInstalledAppBundles;
2408 my $wantedFunction = sub {
2411 # Ignore hidden files and directories.
2412 if ($file =~ /^\../) {
2413 $File::Find::prune = 1;
2417 return if !-d $file || $file !~ /\.app$/;
2418 push @::userInstalledAppBundles, $File::Find::name;
2419 $File::Find::prune = 1; # Do not traverse contents of app bundle.
2421 find($wantedFunction, $userInstalledAppPath);
2422 for my $userInstalledAppBundle (@::userInstalledAppBundles) {
2423 if (appIdentifierFromBundle($userInstalledAppBundle) eq $appIdentifier) {
2424 return 1; # Has user installed app.
2427 return 0; # Does not have user installed app.
2430 sub isSimulatorDeviceBooted($)
2432 my ($simulatedDeviceUDID) = @_;
2433 my $device = iosSimulatorDeviceByUDID($simulatedDeviceUDID);
2434 return $device && $device->{state} eq SIMULATOR_DEVICE_STATE_BOOTED;
2437 sub runIOSWebKitAppInSimulator($;$)
2439 my ($appBundle, $simulatorOptions) = @_;
2440 my $productDir = productDir();
2441 my $appDisplayName = appDisplayNameFromBundle($appBundle);
2442 my $appIdentifier = appIdentifierFromBundle($appBundle);
2443 my $simulatedDevice = findOrCreateSimulatorForIOSDevice(SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT);
2444 my $simulatedDeviceUDID = $simulatedDevice->{UDID};
2446 my $willUseSystemInstalledApp = isIOSSimulatorSystemInstalledApp($appBundle);
2447 if ($willUseSystemInstalledApp) {
2448 if (hasUserInstalledAppInSimulatorDevice($appIdentifier, $simulatedDeviceUDID)) {
2449 # Restore the system-installed app in the simulator device corresponding to $appBundle as it
2450 # was previously overwritten with a custom built version of the app.
2451 # FIXME: Only restore the system-installed version of the app instead of erasing all contents and settings.
2452 print "Quitting iOS Simulator...\n";
2453 quitIOSSimulator($simulatedDeviceUDID);
2454 print "Erasing contents and settings for simulator device \"$simulatedDevice->{name}\".\n";
2455 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "erase", $simulatedDeviceUDID)) == 0 or die;
2457 # FIXME: We assume that if $simulatedDeviceUDID is not booted then iOS Simulator is not open. However
2458 # $simulatedDeviceUDID may have been booted using the simctl command line tool. If $simulatedDeviceUDID
2459 # was booted using simctl then we should shutdown the device and launch iOS Simulator to boot it again.
2460 if (!isSimulatorDeviceBooted($simulatedDeviceUDID)) {
2461 print "Launching iOS Simulator...\n";
2462 relaunchIOSSimulator($simulatedDevice);
2465 # FIXME: We should killall(1) any running instances of $appBundle before installing it to ensure
2466 # that simctl launch opens the latest installed version of the app. For now we quit and
2467 # launch the iOS Simulator again to ensure there are no running instances of $appBundle.
2468 print "Quitting and launching iOS Simulator...\n";
2469 relaunchIOSSimulator($simulatedDevice);
2471 print "Installing $appBundle.\n";
2472 # Install custom built app, overwriting an app with the same app identifier if one exists.
2473 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "install", $simulatedDeviceUDID, $appBundle)) == 0 or die;
2477 $simulatorOptions = {} unless $simulatorOptions;
2480 %simulatorENV = %{$simulatorOptions->{applicationEnvironment}} if $simulatorOptions->{applicationEnvironment};
2482 local %ENV; # Shadow global-scope %ENV so that changes to it will not be seen outside of this scope.
2483 setupIOSWebKitEnvironment($productDir);
2484 %simulatorENV = %ENV;
2486 my $applicationArguments = \@ARGV;
2487 $applicationArguments = $simulatorOptions->{applicationArguments} if $simulatorOptions && $simulatorOptions->{applicationArguments};
2489 # Prefix the environment variables with SIMCTL_CHILD_ per `xcrun simctl help launch`.
2490 foreach my $key (keys %simulatorENV) {
2491 $ENV{"SIMCTL_CHILD_$key"} = $simulatorENV{$key};
2494 print "Starting $appDisplayName with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2495 return exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "launch", $simulatedDeviceUDID, $appIdentifier, @$applicationArguments));
2498 sub runIOSWebKitApp($)
2500 my ($appBundle) = @_;
2501 if (willUseIOSDeviceSDK()) {
2502 die "Only running Safari in iOS Simulator is supported now.";
2504 if (willUseIOSSimulatorSDK()) {
2505 return runIOSWebKitAppInSimulator($appBundle);
2507 die "Not using an iOS SDK."
2510 sub archCommandLineArgumentsForRestrictedEnvironmentVariables()
2513 foreach my $key (keys(%ENV)) {
2514 if ($key =~ /^DYLD_/) {
2515 push @arguments, "-e", "$key=$ENV{$key}";
2521 sub runMacWebKitApp($;$)
2523 my ($appPath, $useOpenCommand) = @_;
2524 my $productDir = productDir();
2525 print "Starting @{[basename($appPath)]} with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2528 setupMacWebKitEnvironment($productDir);
2530 if (defined($useOpenCommand) && $useOpenCommand == USE_OPEN_COMMAND) {
2531 return system("open", "-W", "-a", $appPath, "--args", argumentsForRunAndDebugMacWebKitApp());
2533 if (architecture()) {
2534 return system "arch", "-" . architecture(), archCommandLineArgumentsForRestrictedEnvironmentVariables(), $appPath, argumentsForRunAndDebugMacWebKitApp();
2536 return system { $appPath } $appPath, argumentsForRunAndDebugMacWebKitApp();
2539 sub execMacWebKitAppForDebugging($)
2542 my $architectureSwitch = "--arch";
2543 my $argumentsSeparator = "--";
2545 my $debuggerPath = `xcrun -find lldb`;
2546 chomp $debuggerPath;
2547 die "Can't find the lldb executable.\n" unless -x $debuggerPath;
2549 my $productDir = productDir();
2550 setupMacWebKitEnvironment($productDir);
2552 my @architectureFlags = ($architectureSwitch, architecture());
2553 print "Starting @{[basename($appPath)]} under lldb with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2554 exec { $debuggerPath } $debuggerPath, @architectureFlags, $argumentsSeparator, $appPath, argumentsForRunAndDebugMacWebKitApp() or die;
2559 if (isAppleCocoaWebKit()) {
2561 execMacWebKitAppForDebugging(safariPath());
2564 return 1; # Unsupported platform; can't debug Safari on this platform.
2569 if (isIOSWebKit()) {
2570 return runIOSWebKitApp(mobileSafariBundle());
2573 if (isAppleCocoaWebKit()) {
2574 return runMacWebKitApp(safariPath());
2577 if (isAppleWinWebKit()) {
2579 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2580 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2583 return 1; # Unsupported platform; can't run Safari on this platform.
2588 if (isAppleCocoaWebKit()) {
2589 return runMacWebKitApp(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2590 } elsif (isAppleWinWebKit()) {
2592 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2593 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2599 sub debugMiniBrowser
2601 if (isAppleCocoaWebKit()) {
2602 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2608 sub runWebKitTestRunner
2610 if (isAppleCocoaWebKit()) {
2611 return runMacWebKitApp(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2617 sub debugWebKitTestRunner
2619 if (isAppleCocoaWebKit()) {
2620 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2626 sub readRegistryString
2628 my ($valueName) = @_;
2629 chomp(my $string = `regtool --wow32 get "$valueName"`);
2633 sub writeRegistryString
2635 my ($valueName, $string) = @_;
2637 my $error = system "regtool", "--wow32", "set", "-s", $valueName, $string;
2639 # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
2640 # return a successful exit code. So we double-check here that the value we tried to write to the
2641 # registry was really written.
2642 return !$error && readRegistryString($valueName) eq $string;
2645 sub formatBuildTime($)
2647 my ($buildTime) = @_;
2649 my $buildHours = int($buildTime / 3600);
2650 my $buildMins = int(($buildTime - $buildHours * 3600) / 60);
2651 my $buildSecs = $buildTime - $buildHours * 3600 - $buildMins * 60;
2654 return sprintf("%dh:%02dm:%02ds", $buildHours, $buildMins, $buildSecs);
2656 return sprintf("%02dm:%02ds", $buildMins, $buildSecs);
2659 sub runSvnUpdateAndResolveChangeLogs(@)
2661 my @svnOptions = @_;
2662 my $openCommand = "svn update " . join(" ", @svnOptions);
2663 open my $update, "$openCommand |" or die "cannot execute command $openCommand";
2664 my @conflictedChangeLogs;
2665 while (my $line = <$update>) {
2667 $line =~ m/^C\s+(.+?)[\r\n]*$/;
2669 my $filename = normalizePath($1);
2670 push @conflictedChangeLogs, $filename if basename($filename) eq "ChangeLog";
2673 close $update or die;
2675 if (@conflictedChangeLogs) {
2676 print "Attempting to merge conflicted ChangeLogs.\n";
2677 my $resolveChangeLogsPath = File::Spec->catfile(sourceDir(), "Tools", "Scripts", "resolve-ChangeLogs");
2678 (system($resolveChangeLogsPath, "--no-warnings", @conflictedChangeLogs) == 0)
2679 or die "Could not open resolve-ChangeLogs script: $!.\n";
2685 # Doing a git fetch first allows setups with svn-remote.svn.fetch = trunk:refs/remotes/origin/master
2686 # to perform the rebase much much faster.
2687 system("git", "fetch");
2688 if (isGitSVNDirectory(".")) {
2689 system("git", "svn", "rebase") == 0 or die;
2691 # This will die if branch.$BRANCHNAME.merge isn't set, which is
2692 # almost certainly what we want.
2693 system("git", "pull") == 0 or die;