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);
46 use Time::HiRes qw(usleep);
51 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
55 &XcodeCoverageSupportOptions
57 &XcodeOptionStringNoConfig
59 &XcodeStaticAnalyzerOption
60 &appDisplayNameFromBundle
61 &appendToEnvironmentVariableList
65 &cmakeBasedPortArguments
69 &findOrCreateSimulatorForIOSDevice
70 &iosSimulatorDeviceByName
73 &prependToEnvironmentVariableList
74 &printHelpAndExitForRunAndDebugWebKitAppIfNeeded
78 &restartIOSSimulatorDevice
84 &setupMacWebKitEnvironment
85 &sharedCommandLineOptions
86 &sharedCommandLineOptionsUsage
87 &shutDownIOSSimulatorDevice
89 &willUseIOSSimulatorSDK
90 SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT
99 AppleWin => "AppleWin",
104 WinCairo => "WinCairo",
108 use constant USE_OPEN_COMMAND => 1; # Used in runMacWebKitApp().
109 use constant INCLUDE_OPTIONS_FOR_DEBUGGING => 1;
110 use constant SIMULATOR_DEVICE_STATE_SHUTDOWN => "1";
111 use constant SIMULATOR_DEVICE_STATE_BOOTED => "3";
112 use constant SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT => "For WebKit Development";
114 # 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>.
115 use constant IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX => "iPhone Developer: ";
124 my @baseProductDirOption;
127 my $configurationForVisualStudio;
128 my $configurationProductDir;
130 my $currentSVNRevision;
132 my $didLoadIPhoneSimulatorNotification;
139 my $isInspectorFrontend;
141 my $shouldUseGuardMalloc;
142 my $shouldNotUseNinja;
145 my $unknownPortProhibited = 0;
147 # Variables for Win32 support
148 my $programFilesPath;
151 my $msBuildInstallDir;
153 my $windowsSourceDir;
155 my $willUseVCExpressWhenBuilding = 0;
157 # Defined in VCSUtils.
160 sub findMatchingArguments($$);
163 sub determineSourceDir
165 return if $sourceDir;
166 $sourceDir = $FindBin::Bin;
167 $sourceDir =~ s|/+$||; # Remove trailing '/' as we would die later
169 # walks up path checking each directory to see if it is the main WebKit project dir,
170 # defined by containing Sources, WebCore, and WebKit
171 until ((-d File::Spec->catdir($sourceDir, "Source") && -d File::Spec->catdir($sourceDir, "Source", "WebCore") && -d File::Spec->catdir($sourceDir, "Source", "WebKit")) || (-d File::Spec->catdir($sourceDir, "Internal") && -d File::Spec->catdir($sourceDir, "OpenSource")))
173 if ($sourceDir !~ s|/[^/]+$||) {
174 die "Could not find top level webkit directory above source directory using FindBin.\n";
178 $sourceDir = File::Spec->catdir($sourceDir, "OpenSource") if -d File::Spec->catdir($sourceDir, "OpenSource");
181 sub currentPerlPath()
185 $thisPerl .= $Config{_exe} unless $thisPerl =~ m/$Config{_exe}$/i;
190 # used for scripts which are stored in a non-standard location
196 sub determineNinjaVersion
198 chomp(my $ninjaVersion = `ninja --version`);
199 return $ninjaVersion;
202 sub determineXcodeVersion
204 return if defined $xcodeVersion;
205 my $xcodebuildVersionOutput = `xcodebuild -version`;
206 $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : "3.0";
209 sub readXcodeUserDefault($)
211 my ($unprefixedKey) = @_;
213 determineXcodeVersion();
215 my $xcodeDefaultsDomain = (eval "v$xcodeVersion" lt v4) ? "com.apple.Xcode" : "com.apple.dt.Xcode";
216 my $xcodeDefaultsPrefix = (eval "v$xcodeVersion" lt v4) ? "PBX" : "IDE";
217 my $devnull = File::Spec->devnull();
219 my $value = `defaults read $xcodeDefaultsDomain ${xcodeDefaultsPrefix}${unprefixedKey} 2> ${devnull}`;
226 sub determineBaseProductDir
228 return if defined $baseProductDir;
229 determineSourceDir();
231 my $setSharedPrecompsDir;
232 $baseProductDir = $ENV{"WEBKIT_OUTPUTDIR"};
234 if (!defined($baseProductDir) and isAppleMacWebKit()) {
235 # Silently remove ~/Library/Preferences/xcodebuild.plist which can
236 # cause build failure. The presence of
237 # ~/Library/Preferences/xcodebuild.plist can prevent xcodebuild from
238 # respecting global settings such as a custom build products directory
239 # (<rdar://problem/5585899>).
240 my $personalPlistFile = $ENV{HOME} . "/Library/Preferences/xcodebuild.plist";
241 if (-e $personalPlistFile) {
242 unlink($personalPlistFile) || die "Could not delete $personalPlistFile: $!";
245 determineXcodeVersion();
247 if (eval "v$xcodeVersion" ge v4) {
248 my $buildLocationStyle = join '', readXcodeUserDefault("BuildLocationStyle");
249 if ($buildLocationStyle eq "Custom") {
250 my $buildLocationType = join '', readXcodeUserDefault("CustomBuildLocationType");
251 # FIXME: Read CustomBuildIntermediatesPath and set OBJROOT accordingly.
252 $baseProductDir = readXcodeUserDefault("CustomBuildProductsPath") if $buildLocationType eq "Absolute";
255 # DeterminedByTargets corresponds to a setting of "Legacy" in Xcode.
256 # It is the only build location style for which SHARED_PRECOMPS_DIR is not
257 # overridden when building from within Xcode.
258 $setSharedPrecompsDir = 1 if $buildLocationStyle ne "DeterminedByTargets";
261 if (!defined($baseProductDir)) {
262 $baseProductDir = join '', readXcodeUserDefault("ApplicationwideBuildSettings");
263 $baseProductDir = $1 if $baseProductDir =~ /SYMROOT\s*=\s*\"(.*?)\";/s;
266 undef $baseProductDir unless $baseProductDir =~ /^\//;
269 if (!defined($baseProductDir)) { # Port-specific checks failed, use default
270 $baseProductDir = File::Spec->catdir($sourceDir, "WebKitBuild");
273 if (isGit() && isGitBranchBuild()) {
274 my $branch = gitBranch();
275 $baseProductDir = "$baseProductDir/$branch";
278 if (isAppleMacWebKit()) {
279 $baseProductDir =~ s|^\Q$(SRCROOT)/..\E$|$sourceDir|;
280 $baseProductDir =~ s|^\Q$(SRCROOT)/../|$sourceDir/|;
281 $baseProductDir =~ s|^~/|$ENV{HOME}/|;
282 die "Can't handle Xcode product directory with a ~ in it.\n" if $baseProductDir =~ /~/;
283 die "Can't handle Xcode product directory with a variable in it.\n" if $baseProductDir =~ /\$/;
284 @baseProductDirOption = ("SYMROOT=$baseProductDir", "OBJROOT=$baseProductDir");
285 push(@baseProductDirOption, "SHARED_PRECOMPS_DIR=${baseProductDir}/PrecompiledHeaders") if $setSharedPrecompsDir;
289 my $dosBuildPath = `cygpath --windows \"$baseProductDir\"`;
291 $ENV{"WEBKIT_OUTPUTDIR"} = $dosBuildPath;
292 my $unixBuildPath = `cygpath --unix \"$baseProductDir\"`;
293 chomp $unixBuildPath;
294 $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 (isAppleMacWebKit()) {
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 = 'armv7';
348 } elsif (isCMakeBuild()) {
349 my $host_processor = "";
350 if (open my $cmake_sysinfo, "cmake --system-information |") {
351 while (<$cmake_sysinfo>) {
352 next unless index($_, 'CMAKE_SYSTEM_PROCESSOR') == 0;
353 if (/^CMAKE_SYSTEM_PROCESSOR \"([^"]+)\"/) {
355 $architecture = 'x86_64' if $architecture eq 'amd64';
359 close $cmake_sysinfo;
363 if (!isAnyWindows()) {
364 if (!$architecture) {
365 # Fall back to output of `arch', if it is present.
366 $architecture = `arch`;
370 if (!$architecture) {
371 # Fall back to output of `uname -m', if it is present.
372 $architecture = `uname -m`;
377 $architecture = 'x86_64' if ($architecture =~ /amd64/ && isBSD());
380 sub determineASanIsEnabled
382 return if defined $asanIsEnabled;
383 determineBaseProductDir();
386 my $asanConfigurationValue;
388 if (open ASAN, "$baseProductDir/ASan") {
389 $asanConfigurationValue = <ASAN>;
391 chomp $asanConfigurationValue;
392 $asanIsEnabled = 1 if $asanConfigurationValue eq "YES";
396 sub determineNumberOfCPUs
398 return if defined $numberOfCPUs;
399 if (defined($ENV{NUMBER_OF_PROCESSORS})) {
400 $numberOfCPUs = $ENV{NUMBER_OF_PROCESSORS};
401 } elsif (isLinux()) {
402 # First try the nproc utility, if it exists. If we get no
403 # results fall back to just interpretting /proc directly.
404 chomp($numberOfCPUs = `nproc --all 2> /dev/null`);
405 if ($numberOfCPUs eq "") {
406 $numberOfCPUs = (grep /processor/, `cat /proc/cpuinfo`);
408 } elsif (isAnyWindows()) {
410 $numberOfCPUs = `ls /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor | wc -w`;
411 } elsif (isDarwin() || isBSD()) {
412 chomp($numberOfCPUs = `sysctl -n hw.ncpu`);
416 sub determineMaxCPULoad
418 return if defined $maxCPULoad;
419 if (defined($ENV{MAX_CPU_LOAD})) {
420 $maxCPULoad = $ENV{MAX_CPU_LOAD};
426 my ($productDir) = @_;
428 $jscName .= "_debug" if configuration() eq "Debug_All";
429 $jscName .= ".exe" if (isAnyWindows());
430 return "$productDir/$jscName" if -e "$productDir/$jscName";
431 return "$productDir/JavaScriptCore.framework/Resources/$jscName";
434 sub argumentsForConfiguration()
436 determineConfiguration();
437 determineArchitecture();
441 # FIXME: Is it necessary to pass --debug, --release, --32-bit or --64-bit?
442 # These are determined automatically from stored configuration.
443 push(@args, '--debug') if ($configuration =~ "^Debug");
444 push(@args, '--release') if ($configuration =~ "^Release");
445 push(@args, '--device') if (defined $xcodeSDK && $xcodeSDK =~ /^iphoneos/);
446 push(@args, '--ios-simulator') if (defined $xcodeSDK && $xcodeSDK =~ /^iphonesimulator/);
447 push(@args, '--32-bit') if ($architecture ne "x86_64" and !isWin64());
448 push(@args, '--64-bit') if (isWin64());
449 push(@args, '--gtk') if isGtk();
450 push(@args, '--efl') if isEfl();
451 push(@args, '--wincairo') if isWinCairo();
452 push(@args, '--inspector-frontend') if isInspectorFrontend();
456 sub determineXcodeSDK
458 return if defined $xcodeSDK;
460 if (checkForArgumentAndRemoveFromARGVGettingValue("--sdk", \$sdk)) {
463 if (checkForArgumentAndRemoveFromARGV("--device")) {
464 my $hasInternalSDK = exitStatus(system("xcrun --sdk iphoneos.internal --show-sdk-version > /dev/null 2>&1")) == 0;
465 $xcodeSDK ||= $hasInternalSDK ? "iphoneos.internal" : "iphoneos";
467 if (checkForArgumentAndRemoveFromARGV("--ios-simulator")) {
468 $xcodeSDK ||= 'iphonesimulator';
484 sub xcodeSDKPlatformName()
487 return "" if !defined $xcodeSDK;
488 return "iphoneos" if $xcodeSDK =~ /iphoneos/i;
489 return "iphonesimulator" if $xcodeSDK =~ /iphonesimulator/i;
490 return "macosx" if $xcodeSDK =~ /macosx/i;
491 die "Couldn't determine platform name from Xcode SDK";
498 die "Can't find the SDK path because no Xcode SDK was specified" if not $xcodeSDK;
500 my $sdkPath = `xcrun --sdk $xcodeSDK --show-sdk-path` if $xcodeSDK;
501 die 'Failed to get SDK path from xcrun' if $?;
511 die "Can't find the SDK version because no Xcode SDK was specified" if !$xcodeSDK;
513 chomp(my $sdkVersion = `xcrun --sdk $xcodeSDK --show-sdk-version`);
514 die "Failed to get SDK version from xcrun" if exitStatus($?);
521 return $programFilesPath if defined $programFilesPath;
523 $programFilesPath = $ENV{'PROGRAMFILES(X86)'} || $ENV{'PROGRAMFILES'} || "C:\\Program Files";
525 return $programFilesPath;
528 sub visualStudioInstallDir
530 return $vsInstallDir if defined $vsInstallDir;
532 if ($ENV{'VSINSTALLDIR'}) {
533 $vsInstallDir = $ENV{'VSINSTALLDIR'};
534 $vsInstallDir =~ s|[\\/]$||;
536 $vsInstallDir = File::Spec->catdir(programFilesPath(), "Microsoft Visual Studio 14.0");
538 chomp($vsInstallDir = `cygpath "$vsInstallDir"`) if isCygwin();
540 print "Using Visual Studio: $vsInstallDir\n";
541 return $vsInstallDir;
544 sub msBuildInstallDir
546 return $msBuildInstallDir if defined $msBuildInstallDir;
548 $msBuildInstallDir = File::Spec->catdir(programFilesPath(), "MSBuild", "14.0", "Bin");
550 chomp($msBuildInstallDir = `cygpath "$msBuildInstallDir"`) if isCygwin();
552 print "Using MSBuild: $msBuildInstallDir\n";
553 return $msBuildInstallDir;
556 sub visualStudioVersion
558 return $vsVersion if defined $vsVersion;
560 my $installDir = visualStudioInstallDir();
562 $vsVersion = ($installDir =~ /Microsoft Visual Studio ([0-9]+\.[0-9]*)/) ? $1 : "14";
564 print "Using Visual Studio $vsVersion\n";
568 sub determineConfigurationForVisualStudio
570 return if defined $configurationForVisualStudio;
571 determineConfiguration();
572 # FIXME: We should detect when Debug_All or Production has been chosen.
573 $configurationForVisualStudio = "/p:Configuration=" . $configuration;
576 sub usesPerConfigurationBuildDirectory
578 # [Gtk] We don't have Release/Debug configurations in straight
579 # autotool builds (non build-webkit). In this case and if
580 # WEBKIT_OUTPUTDIR exist, use that as our configuration dir. This will
581 # allows us to run run-webkit-tests without using build-webkit.
582 return ($ENV{"WEBKIT_OUTPUTDIR"} && isGtk()) || isAppleWinWebKit();
585 sub determineConfigurationProductDir
587 return if defined $configurationProductDir;
588 determineBaseProductDir();
589 determineConfiguration();
590 if (isAppleWinWebKit() || isWinCairo()) {
591 $configurationProductDir = File::Spec->catdir($baseProductDir, $configuration);
593 if (usesPerConfigurationBuildDirectory()) {
594 $configurationProductDir = "$baseProductDir";
596 $configurationProductDir = "$baseProductDir/$configuration";
597 $configurationProductDir .= "-" . xcodeSDKPlatformName() if isIOSWebKit();
602 sub setConfigurationProductDir($)
604 ($configurationProductDir) = @_;
607 sub determineCurrentSVNRevision
609 # We always update the current SVN revision here, and leave the caching
610 # to currentSVNRevision(), so that changes to the SVN revision while the
611 # script is running can be picked up by calling this function again.
612 determineSourceDir();
613 $currentSVNRevision = svnRevisionForDirectory($sourceDir);
614 return $currentSVNRevision;
620 determineSourceDir();
621 chdir $sourceDir or die;
626 determineBaseProductDir();
627 return $baseProductDir;
632 determineSourceDir();
638 determineConfigurationProductDir();
639 return $configurationProductDir;
642 sub executableProductDir
644 my $productDirectory = productDir();
647 if (isEfl() || isGtk()) {
648 $binaryDirectory = "bin";
649 } elsif (isAnyWindows()) {
650 $binaryDirectory = isWin64() ? "bin64" : "bin32";
652 return $productDirectory;
655 return File::Spec->catdir($productDirectory, $binaryDirectory);
660 return executableProductDir();
665 determineConfiguration();
666 return $configuration;
671 determineASanIsEnabled();
672 return $asanIsEnabled;
675 sub configurationForVisualStudio()
677 determineConfigurationForVisualStudio();
678 return $configurationForVisualStudio;
681 sub currentSVNRevision
683 determineCurrentSVNRevision() if not defined $currentSVNRevision;
684 return $currentSVNRevision;
689 determineGenerateDsym();
690 return $generateDsym;
693 sub determineGenerateDsym()
695 return if defined($generateDsym);
696 $generateDsym = checkForArgumentAndRemoveFromARGV("--dsym");
699 sub hasIOSDevelopmentCertificate()
701 return !exitStatus(system("security find-identity -p codesigning | grep '" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX . "' > /dev/null 2>&1"));
704 sub argumentsForXcode()
707 push @args, "DEBUG_INFORMATION_FORMAT=dwarf-with-dsym" if generateDsym();
713 determineBaseProductDir();
714 determineConfiguration();
715 determineArchitecture();
716 determineASanIsEnabled();
720 push @options, "-UseSanitizedBuildSystemEnvironment=YES";
721 push @options, ("-configuration", $configuration);
722 push @options, ("-xcconfig", sourceDir() . "/Tools/asan/asan.xcconfig", "ASAN_IGNORE=" . sourceDir() . "/Tools/asan/webkit-asan-ignore.txt") if $asanIsEnabled;
723 push @options, @baseProductDirOption;
724 push @options, "ARCHS=$architecture" if $architecture;
725 push @options, "SDKROOT=$xcodeSDK" if $xcodeSDK;
726 if (willUseIOSDeviceSDK()) {
727 push @options, "ENABLE_BITCODE=NO";
728 if (hasIOSDevelopmentCertificate()) {
729 # FIXME: May match more than one installed development certificate.
730 push @options, "CODE_SIGN_IDENTITY=" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX;
732 push @options, "CODE_SIGN_IDENTITY="; # No identity
733 push @options, "CODE_SIGNING_REQUIRED=NO";
736 push @options, argumentsForXcode();
740 sub XcodeOptionString
742 return join " ", XcodeOptions();
745 sub XcodeOptionStringNoConfig
747 return join " ", @baseProductDirOption;
750 sub XcodeCoverageSupportOptions()
752 my @coverageSupportOptions = ();
753 push @coverageSupportOptions, "GCC_GENERATE_TEST_COVERAGE_FILES=YES";
754 push @coverageSupportOptions, "GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES";
755 return @coverageSupportOptions;
758 sub XcodeStaticAnalyzerOption()
760 return "RUN_CLANG_STATIC_ANALYZER=YES";
763 my $passedConfiguration;
764 my $searchedForPassedConfiguration;
765 sub determinePassedConfiguration
767 return if $searchedForPassedConfiguration;
768 $searchedForPassedConfiguration = 1;
769 $passedConfiguration = undef;
771 if (checkForArgumentAndRemoveFromARGV("--debug")) {
772 $passedConfiguration = "Debug";
773 } elsif(checkForArgumentAndRemoveFromARGV("--release")) {
774 $passedConfiguration = "Release";
775 } elsif (checkForArgumentAndRemoveFromARGV("--profile") || checkForArgumentAndRemoveFromARGV("--profiling")) {
776 $passedConfiguration = "Profiling";
780 sub passedConfiguration
782 determinePassedConfiguration();
783 return $passedConfiguration;
790 if (my $config = shift @_) {
791 $configuration = $config;
795 determinePassedConfiguration();
796 $configuration = $passedConfiguration if $passedConfiguration;
800 my $passedArchitecture;
801 my $searchedForPassedArchitecture;
802 sub determinePassedArchitecture
804 return if $searchedForPassedArchitecture;
805 $searchedForPassedArchitecture = 1;
807 $passedArchitecture = undef;
808 if (checkForArgumentAndRemoveFromARGV("--32-bit")) {
809 if (isAppleMacWebKit()) {
810 # PLATFORM_IOS: Don't run `arch` command inside Simulator environment
812 delete $ENV{DYLD_ROOT_PATH};
813 delete $ENV{DYLD_FRAMEWORK_PATH};
815 $passedArchitecture = `arch`;
816 chomp $passedArchitecture;
821 sub passedArchitecture
823 determinePassedArchitecture();
824 return $passedArchitecture;
829 determineArchitecture();
830 return $architecture;
835 determineNumberOfCPUs();
836 return $numberOfCPUs;
841 determineMaxCPULoad();
847 if (my $arch = shift @_) {
848 $architecture = $arch;
852 determinePassedArchitecture();
853 $architecture = $passedArchitecture if $passedArchitecture;
856 sub skipSafariExecutableEntitlementChecks
858 return `defaults read /Library/Preferences/org.webkit.BuildConfiguration SkipSafariExecutableEntitlementChecks 2>/dev/null` eq "1\n";
861 sub executableHasEntitlements
863 my $executablePath = shift;
864 return (`codesign -d --entitlements - $executablePath 2>&1` =~ /<key>/);
867 sub safariPathFromSafariBundle
869 my ($safariBundle) = @_;
871 die "Safari path is only relevant on Apple Mac platform\n" unless isAppleMacWebKit();
873 my $safariPath = "$safariBundle/Contents/MacOS/Safari";
874 return $safariPath if skipSafariExecutableEntitlementChecks();
876 my $safariForWebKitDevelopmentPath = "$safariBundle/Contents/MacOS/SafariForWebKitDevelopment";
877 return $safariForWebKitDevelopmentPath if -f $safariForWebKitDevelopmentPath && executableHasEntitlements($safariPath);
882 sub installedSafariPath
884 return safariPathFromSafariBundle("/Applications/Safari.app");
890 die "Safari path is only relevant on Apple Mac platform\n" unless isAppleMacWebKit();
892 # Use WEBKIT_SAFARI environment variable if present.
893 my $safariBundle = $ENV{WEBKIT_SAFARI};
894 if (!$safariBundle) {
895 determineConfigurationProductDir();
896 # Use Safari.app in product directory if present (good for Safari development team).
897 if (-d "$configurationProductDir/Safari.app") {
898 $safariBundle = "$configurationProductDir/Safari.app";
900 if (!$safariBundle) {
901 return installedSafariPath();
904 my $safariPath = safariPathFromSafariBundle($safariBundle);
905 die "Can't find executable at $safariPath.\n" if !-x $safariPath;
909 sub builtDylibPathForName
911 my $libraryName = shift;
912 determineConfigurationProductDir();
915 my $extension = isDarwin() ? ".dylib" : ".so";
916 return "$configurationProductDir/lib/libwebkit2gtk-4.0" . $extension;
919 return "$configurationProductDir/lib/libewebkit2.so";
922 return "$configurationProductDir/$libraryName.framework/$libraryName";
924 if (isAppleMacWebKit()) {
925 return "$configurationProductDir/$libraryName.framework/Versions/A/$libraryName";
927 if (isAppleWinWebKit()) {
928 if ($libraryName eq "JavaScriptCore") {
929 return "$baseProductDir/lib/$libraryName.lib";
931 return "$baseProductDir/$libraryName.intermediate/$configuration/$libraryName.intermediate/$libraryName.lib";
935 die "Unsupported platform, can't determine built library locations.\nTry `build-webkit --help` for more information.\n";
938 # Check to see that all the frameworks are built.
939 sub checkFrameworks # FIXME: This is a poor name since only the Mac calls built WebCore a Framework.
941 return if isAnyWindows();
942 my @frameworks = ("JavaScriptCore", "WebCore");
943 push(@frameworks, "WebKit") if isAppleMacWebKit(); # FIXME: This seems wrong, all ports should have a WebKit these days.
944 for my $framework (@frameworks) {
945 my $path = builtDylibPathForName($framework);
946 die "Can't find built framework at \"$path\".\n" unless -e $path;
950 sub isInspectorFrontend()
952 determineIsInspectorFrontend();
953 return $isInspectorFrontend;
956 sub determineIsInspectorFrontend()
958 return if defined($isInspectorFrontend);
959 $isInspectorFrontend = checkForArgumentAndRemoveFromARGV("--inspector-frontend");
965 my $devnull = File::Spec->devnull();
967 if (isAnyWindows()) {
968 return exitStatus(system("where /q $command >$devnull 2>&1")) == 0;
970 return exitStatus(system("which $command >$devnull 2>&1")) == 0;
973 sub checkForArgumentAndRemoveFromARGV($)
975 my $argToCheck = shift;
976 return checkForArgumentAndRemoveFromArrayRef($argToCheck, \@ARGV);
979 sub checkForArgumentAndRemoveFromArrayRefGettingValue($$$)
981 my ($argToCheck, $valueRef, $arrayRef) = @_;
982 my $argumentStartRegEx = qr#^$argToCheck(?:=\S|$)#;
984 for (; $i < @$arrayRef; ++$i) {
985 last if $arrayRef->[$i] =~ $argumentStartRegEx;
987 if ($i >= @$arrayRef) {
988 return $$valueRef = undef;
990 my ($key, $value) = split("=", $arrayRef->[$i]);
991 splice(@$arrayRef, $i, 1);
992 if (defined($value)) {
993 # e.g. --sdk=iphonesimulator
994 return $$valueRef = $value;
996 return $$valueRef = splice(@$arrayRef, $i, 1); # e.g. --sdk iphonesimulator
999 sub checkForArgumentAndRemoveFromARGVGettingValue($$)
1001 my ($argToCheck, $valueRef) = @_;
1002 return checkForArgumentAndRemoveFromArrayRefGettingValue($argToCheck, $valueRef, \@ARGV);
1005 sub findMatchingArguments($$)
1007 my ($argToCheck, $arrayRef) = @_;
1008 my @matchingIndices;
1009 foreach my $index (0 .. $#$arrayRef) {
1010 my $opt = $$arrayRef[$index];
1011 if ($opt =~ /^$argToCheck$/i ) {
1012 push(@matchingIndices, $index);
1015 return @matchingIndices;
1020 my ($argToCheck, $arrayRef) = @_;
1021 my @matchingIndices = findMatchingArguments($argToCheck, $arrayRef);
1022 return scalar @matchingIndices > 0;
1025 sub checkForArgumentAndRemoveFromArrayRef
1027 my ($argToCheck, $arrayRef) = @_;
1028 my @indicesToRemove = findMatchingArguments($argToCheck, $arrayRef);
1029 my $removeOffset = 0;
1030 foreach my $index (@indicesToRemove) {
1031 splice(@$arrayRef, $index - $removeOffset++, 1);
1033 return scalar @indicesToRemove > 0;
1036 sub prohibitUnknownPort()
1038 $unknownPortProhibited = 1;
1041 sub determinePortName()
1043 return if defined $portName;
1045 my %argToPortName = (
1048 wincairo => WinCairo
1051 for my $arg (sort keys %argToPortName) {
1052 if (checkForArgumentAndRemoveFromARGV("--$arg")) {
1053 die "Argument '--$arg' conflicts with selected port '$portName'\n"
1054 if defined $portName;
1056 $portName = $argToPortName{$arg};
1060 return if defined $portName;
1062 # Port was not selected via command line, use appropriate default value
1064 if (isAnyWindows()) {
1065 $portName = AppleWin;
1066 } elsif (isDarwin()) {
1067 determineXcodeSDK();
1068 if (willUseIOSDeviceSDK() || willUseIOSSimulatorSDK()) {
1074 if ($unknownPortProhibited) {
1075 my $portsChoice = join "\n\t", qw(
1079 die "Please specify which WebKit port to build using one of the following options:"
1080 . "\n\t$portsChoice\n";
1083 # If script is run without arguments we cannot determine port
1084 # TODO: This state should be outlawed
1085 $portName = Unknown;
1091 determinePortName();
1097 return portName() eq Efl;
1102 return portName() eq GTK;
1105 # Determine if this is debian, ubuntu, linspire, or something similar.
1108 return -e "/etc/debian_version";
1113 return -e "/etc/fedora-release";
1118 return portName() eq WinCairo;
1127 sub determineIsWin64()
1129 return if defined($isWin64);
1130 $isWin64 = checkForArgumentAndRemoveFromARGV("--64-bit");
1133 sub determineIsWin64FromArchitecture($)
1136 $isWin64 = ($arch eq "x86_64");
1142 return ($^O eq "cygwin") || 0;
1147 return isWindows() || isCygwin();
1150 sub determineWinVersion()
1152 return if $winVersion;
1154 if (!isAnyWindows()) {
1159 my $versionString = `cmd /c ver`;
1160 $versionString =~ /(\d)\.(\d)\.(\d+)/;
1171 determineWinVersion();
1177 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 1 && winVersion()->{build} == 7600;
1180 sub isWindowsVista()
1182 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 0;
1187 return isAnyWindows() && winVersion()->{major} == 5 && winVersion()->{minor} == 1;
1192 return ($^O eq "darwin") || 0;
1197 return ($^O eq "MSWin32") || 0;
1202 return ($^O eq "linux") || 0;
1207 return ($^O eq "freebsd") || ($^O eq "openbsd") || ($^O eq "netbsd") || 0;
1212 return ($Config{archname} =~ /^arm[v\-]/) || ($Config{archname} =~ /^aarch64[v\-]/);
1217 return (architecture() eq "x86_64") || 0;
1220 sub isCrossCompilation()
1223 $compiler = $ENV{'CC'} if (defined($ENV{'CC'}));
1224 if ($compiler =~ /gcc/) {
1225 my $compiler_options = `$compiler -v 2>&1`;
1226 my @host = $compiler_options =~ m/--host=(.*?)\s/;
1227 my @target = $compiler_options =~ m/--target=(.*?)\s/;
1229 return ($host[0] ne "" && $target[0] ne "" && $host[0] ne $target[0]);
1236 return isAppleMacWebKit() || isAppleWinWebKit();
1239 sub isAppleMacWebKit()
1241 return (portName() eq Mac) || isIOSWebKit();
1244 sub isAppleWinWebKit()
1246 return portName() eq AppleWin;
1249 sub iOSSimulatorDevicesPath
1251 return "$ENV{HOME}/Library/Developer/CoreSimulator/Devices";
1254 sub iOSSimulatorDevices
1256 eval "require Foundation";
1257 my $devicesPath = iOSSimulatorDevicesPath();
1258 opendir(DEVICES, $devicesPath);
1260 $_ =~ m/[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}/;
1264 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
1265 # dictionary keys so as to decouple our representation of the plist from the actual structure
1266 # of the plist, which may change.
1268 Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_("$devicesPath/$_/device.plist"));
1274 sub createiOSSimulatorDevice
1277 my $deviceTypeId = shift;
1278 my $runtimeId = shift;
1280 my $created = system("xcrun", "--sdk", "iphonesimulator", "simctl", "create", $name, $deviceTypeId, $runtimeId) == 0;
1281 die "Couldn't create simulator device: $name $deviceTypeId $runtimeId" if not $created;
1283 system("xcrun", "--sdk", "iphonesimulator", "simctl", "list");
1285 print "Waiting for device to be created ...\n";
1287 for (my $tries = 0; $tries < 5; $tries++){
1288 my @devices = iOSSimulatorDevices();
1289 foreach my $device (@devices) {
1290 return $device if $device->{name} eq $name and $device->{deviceType} eq $deviceTypeId and $device->{runtime} eq $runtimeId;
1294 die "Device $name $deviceTypeId $runtimeId wasn't found in " . iOSSimulatorDevicesPath();
1297 sub willUseIOSDeviceSDK()
1299 return xcodeSDKPlatformName() eq "iphoneos";
1302 sub willUseIOSSimulatorSDK()
1304 return xcodeSDKPlatformName() eq "iphonesimulator";
1309 return portName() eq iOS;
1312 sub determineNmPath()
1316 if (isAppleMacWebKit()) {
1317 $nmPath = `xcrun -find nm`;
1320 $nmPath = "nm" if !$nmPath;
1329 sub splitVersionString
1331 my $versionString = shift;
1332 my @splitVersion = split(/\./, $versionString);
1333 @splitVersion >= 2 or die "Invalid version $versionString";
1335 "major" => $splitVersion[0],
1336 "minor" => $splitVersion[1],
1337 "subminor" => (defined($splitVersion[2]) ? $splitVersion[2] : 0),
1341 sub determineOSXVersion()
1343 return if $osXVersion;
1350 my $versionString = `sw_vers -productVersion`;
1351 $osXVersion = splitVersionString($versionString);
1356 determineOSXVersion();
1360 sub determineIOSVersion()
1362 return if $iosVersion;
1364 if (!isIOSWebKit()) {
1369 my $versionString = xcodeSDKVersion();
1370 $iosVersion = splitVersionString($versionString);
1375 determineIOSVersion();
1381 return $ENV{'OS'} eq 'Windows_NT';
1386 determineDebugger();
1390 sub determineDebugger
1392 return if defined($debugger);
1394 determineXcodeVersion();
1395 if (eval "v$xcodeVersion" ge v4.5) {
1401 if (checkForArgumentAndRemoveFromARGV("--use-lldb")) {
1405 if (checkForArgumentAndRemoveFromARGV("--use-gdb")) {
1410 sub appendToEnvironmentVariableList($$)
1412 my ($name, $value) = @_;
1414 if (defined($ENV{$name})) {
1415 $ENV{$name} .= $Config{path_sep} . $value;
1417 $ENV{$name} = $value;
1421 sub prependToEnvironmentVariableList($$)
1423 my ($name, $value) = @_;
1425 if (defined($ENV{$name})) {
1426 $ENV{$name} = $value . $Config{path_sep} . $ENV{$name};
1428 $ENV{$name} = $value;
1432 sub sharedCommandLineOptions()
1435 "g|guard-malloc" => \$shouldUseGuardMalloc,
1439 sub sharedCommandLineOptionsUsage
1444 '-g|--guard-malloc' => 'Use guardmalloc when running executable',
1447 my $indent = " " x ($opts{indent} || 2);
1448 my $switchWidth = List::Util::max(int($opts{switchWidth}), List::Util::max(map { length($_) } keys %switches) + ($opts{brackets} ? 2 : 0));
1450 my $result = "Common switches:\n";
1452 for my $switch (keys %switches) {
1453 my $switchName = $opts{brackets} ? "[" . $switch . "]" : $switch;
1454 $result .= sprintf("%s%-" . $switchWidth . "s %s\n", $indent, $switchName, $switches{$switch});
1460 sub setUpGuardMallocIfNeeded
1466 if (!defined($shouldUseGuardMalloc)) {
1467 $shouldUseGuardMalloc = checkForArgumentAndRemoveFromARGV("-g") || checkForArgumentAndRemoveFromARGV("--guard-malloc");
1470 if ($shouldUseGuardMalloc) {
1471 appendToEnvironmentVariableList("DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1472 appendToEnvironmentVariableList("__XPC_DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1476 sub relativeScriptsDir()
1478 my $scriptDir = File::Spec->catpath("", File::Spec->abs2rel($FindBin::Bin, getcwd()), "");
1479 if ($scriptDir eq "") {
1487 my $relativeScriptsPath = relativeScriptsDir();
1488 if (isGtk() || isEfl()) {
1489 return "$relativeScriptsPath/run-minibrowser";
1490 } elsif (isAppleWebKit()) {
1491 return "$relativeScriptsPath/run-safari";
1497 if (isGtk() || isEfl()) {
1498 return "MiniBrowser";
1499 } elsif (isAppleMacWebKit()) {
1501 } elsif (isAppleWinWebKit()) {
1502 return "MiniBrowser";
1506 sub checkRequiredSystemConfig
1509 chomp(my $productVersion = `sw_vers -productVersion`);
1510 if (eval "v$productVersion" lt v10.7.5) {
1511 print "*************************************************************\n";
1512 print "Mac OS X Version 10.7.5 or later is required to build WebKit.\n";
1513 print "You have " . $productVersion . ", thus the build will most likely fail.\n";
1514 print "*************************************************************\n";
1516 my $xcodebuildVersionOutput = `xcodebuild -version`;
1517 my $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : undef;
1518 if (!$xcodeVersion || $xcodeVersion && eval "v$xcodeVersion" lt v4.6) {
1519 print "*************************************************************\n";
1520 print "Xcode Version 4.6 or later is required to build WebKit.\n";
1521 print "You have an earlier version of Xcode, thus the build will\n";
1522 print "most likely fail. The latest Xcode is available from the App Store.\n";
1523 print "*************************************************************\n";
1528 sub determineWindowsSourceDir()
1530 return if $windowsSourceDir;
1531 $windowsSourceDir = sourceDir();
1532 chomp($windowsSourceDir = `cygpath -w '$windowsSourceDir'`) if isCygwin();
1535 sub windowsSourceDir()
1537 determineWindowsSourceDir();
1538 return $windowsSourceDir;
1541 sub windowsSourceSourceDir()
1543 return File::Spec->catdir(windowsSourceDir(), "Source");
1546 sub windowsLibrariesDir()
1548 return File::Spec->catdir(windowsSourceDir(), "WebKitLibraries", "win");
1551 sub windowsOutputDir()
1553 return File::Spec->catdir(windowsSourceDir(), "WebKitBuild");
1559 my $cmd = "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\\" . $font ."\" 2>&1";
1564 sub checkInstalledTools()
1566 # environment variables. Avoid until this is corrected.
1567 my $pythonVer = `python --version 2>&1`;
1568 die "You must have Python installed to build WebKit.\n" if ($?);
1570 # cURL 7.34.0 has a bug that prevents authentication with opensource.apple.com (and other things using SSL3).
1571 my $curlVer = `curl --version 2> NUL`;
1572 if (!$? and $curlVer =~ "(.*curl.*)") {
1574 if ($curlVer =~ /libcurl\/7\.34\.0/) {
1575 print "cURL version 7.34.0 has a bug that prevents authentication with SSL v2 or v3.\n";
1576 print "cURL 7.33.0 is known to work. The cURL projects is preparing an update to\n";
1577 print "correct this problem.\n\n";
1578 die "Please install a working cURL and try again.\n";
1582 # MathML requires fonts that do not ship with Windows (at least through Windows 8). Warn the user if they are missing
1583 my @fonts = qw(STIXGeneral-Regular MathJax_Main-Regular);
1585 foreach my $font (@fonts) {
1586 push @missing, $font if not fontExists($font);
1589 if (scalar @missing > 0) {
1590 print "*************************************************************\n";
1591 print "Mathematical fonts, such as STIX and MathJax, are needed to\n";
1592 print "use the MathML feature. You do not appear to have these fonts\n";
1593 print "on your system.\n\n";
1594 print "You can download a suitable set of fonts from the following URL:\n";
1595 print "https://developer.mozilla.org/Mozilla/MathML_Projects/Fonts\n";
1596 print "*************************************************************\n";
1599 print "Installed tools are correct for the WebKit build.\n";
1602 sub setupAppleWinEnv()
1604 return unless isAppleWinWebKit();
1606 checkInstalledTools();
1608 if (isWindowsNT()) {
1609 my $restartNeeded = 0;
1610 my %variablesToSet = ();
1612 # FIXME: We should remove this explicit version check for cygwin once we stop supporting Cygwin 1.7.9 or older versions.
1613 # https://bugs.webkit.org/show_bug.cgi?id=85791
1614 my $uname_version = (POSIX::uname())[2];
1615 $uname_version =~ s/\(.*\)//; # Remove the trailing cygwin version, if any.
1616 $uname_version =~ s/\-.*$//; # Remove trailing dash-version content, if any
1617 if (version->parse($uname_version) < version->parse("1.7.10")) {
1618 # Setting the environment variable 'CYGWIN' to 'tty' makes cygwin enable extra support (i.e., termios)
1619 # for UNIX-like ttys in the Windows console
1620 $variablesToSet{CYGWIN} = "tty" unless $ENV{CYGWIN};
1623 # Those environment variables must be set to be able to build inside Visual Studio.
1624 $variablesToSet{WEBKIT_LIBRARIES} = windowsLibrariesDir() unless $ENV{WEBKIT_LIBRARIES};
1625 $variablesToSet{WEBKIT_OUTPUTDIR} = windowsOutputDir() unless $ENV{WEBKIT_OUTPUTDIR};
1626 $variablesToSet{MSBUILDDISABLENODEREUSE} = "1" unless $ENV{MSBUILDDISABLENODEREUSE};
1627 $variablesToSet{_IsNativeEnvironment} = "true" unless $ENV{_IsNativeEnvironment};
1628 $variablesToSet{PreferredToolArchitecture} = "x64" unless $ENV{PreferredToolArchitecture};
1630 foreach my $variable (keys %variablesToSet) {
1631 print "Setting the Environment Variable '" . $variable . "' to '" . $variablesToSet{$variable} . "'\n\n";
1632 my $ret = system "setx", $variable, $variablesToSet{$variable};
1634 system qw(regtool -s set), '\\HKEY_CURRENT_USER\\Environment\\' . $variable, $variablesToSet{$variable};
1636 $restartNeeded ||= $variable eq "WEBKIT_LIBRARIES" || $variable eq "WEBKIT_OUTPUTDIR";
1639 if ($restartNeeded) {
1640 print "Please restart your computer before attempting to build inside Visual Studio.\n\n";
1643 if (!defined $ENV{'WEBKIT_LIBRARIES'} || !$ENV{'WEBKIT_LIBRARIES'}) {
1644 print "Warning: You must set the 'WebKit_Libraries' environment variable\n";
1645 print " to be able build WebKit from within Visual Studio 2013 and newer.\n";
1646 print " Make sure that 'WebKit_Libraries' points to the\n";
1647 print " 'WebKitLibraries/win' directory, not the 'WebKitLibraries/' directory.\n\n";
1649 if (!defined $ENV{'WEBKIT_OUTPUTDIR'} || !$ENV{'WEBKIT_OUTPUTDIR'}) {
1650 print "Warning: You must set the 'WebKit_OutputDir' environment variable\n";
1651 print " to be able build WebKit from within Visual Studio 2013 and newer.\n\n";
1653 if (!defined $ENV{'MSBUILDDISABLENODEREUSE'} || !$ENV{'MSBUILDDISABLENODEREUSE'}) {
1654 print "Warning: You should set the 'MSBUILDDISABLENODEREUSE' environment variable to '1'\n";
1655 print " to avoid periodic locked log files when building.\n\n";
1658 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1659 if (isWin64() and !$ENV{'WEBKIT_64_SUPPORT'}) {
1660 print "Warning: You must set the 'WEBKIT_64_SUPPORT' environment variable\n";
1661 print " to be able run WebKit or JavaScriptCore tests.\n\n";
1665 sub setupCygwinEnv()
1667 return if !isAnyWindows();
1668 return if $vcBuildPath;
1670 my $programFilesPath = programFilesPath();
1671 my $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE devenv.com));
1672 if (-e $visualStudioPath) {
1673 # Visual Studio is installed;
1674 if (visualStudioVersion() eq "12") {
1675 $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE devenv.exe));
1678 # Visual Studio not found, try VC++ Express
1679 $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE WDExpress.exe));
1680 if (! -e $visualStudioPath) {
1681 print "*************************************************************\n";
1682 print "Cannot find '$visualStudioPath'\n";
1683 print "Please execute the file 'vcvars32.bat' from\n";
1684 print "'$programFilesPath\\Microsoft Visual Studio 14.0\\VC\\bin\\'\n";
1685 print "to setup the necessary environment variables.\n";
1686 print "*************************************************************\n";
1689 $willUseVCExpressWhenBuilding = 1;
1692 print "Building results into: ", baseProductDir(), "\n";
1693 print "WEBKIT_OUTPUTDIR is set to: ", $ENV{"WEBKIT_OUTPUTDIR"}, "\n";
1694 print "WEBKIT_LIBRARIES is set to: ", $ENV{"WEBKIT_LIBRARIES"}, "\n";
1695 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1696 print "WEBKIT_64_SUPPORT is set to: ", $ENV{"WEBKIT_64_SUPPORT"}, "\n" if isWin64();
1698 # We will actually use MSBuild to build WebKit, but we need to find the Visual Studio install (above) to make
1699 # sure we use the right options.
1700 $vcBuildPath = File::Spec->catfile(msBuildInstallDir(), qw(MSBuild.exe));
1701 if (! -e $vcBuildPath) {
1702 print "*************************************************************\n";
1703 print "Cannot find '$vcBuildPath'\n";
1704 print "Please make sure execute that the Microsoft .NET Framework SDK\n";
1705 print "is installed on this machine.\n";
1706 print "*************************************************************\n";
1711 sub dieIfWindowsPlatformSDKNotInstalled
1713 my $registry32Path = "/proc/registry/";
1714 my $registry64Path = "/proc/registry64/";
1715 my @windowsPlatformSDKRegistryEntries = (
1716 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0A",
1717 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0",
1718 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.1A",
1719 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.0A",
1720 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/MicrosoftSDK/InstalledSDKs/D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1",
1723 # FIXME: It would be better to detect whether we are using 32- or 64-bit Windows
1724 # and only check the appropriate entry. But for now we just blindly check both.
1725 my $recommendedPlatformSDK = $windowsPlatformSDKRegistryEntries[0];
1727 while (@windowsPlatformSDKRegistryEntries) {
1728 my $windowsPlatformSDKRegistryEntry = shift @windowsPlatformSDKRegistryEntries;
1729 return if (-e $registry32Path . $windowsPlatformSDKRegistryEntry) || (-e $registry64Path . $windowsPlatformSDKRegistryEntry);
1732 print "*************************************************************\n";
1733 print "Cannot find registry entry '$recommendedPlatformSDK'.\n";
1734 print "Please download and install the Microsoft Windows SDK\n";
1735 print "from <http://www.microsoft.com/en-us/download/details.aspx?id=8279>.\n\n";
1736 print "Then follow step 2 in the Windows section of the \"Installing Developer\n";
1737 print "Tools\" instructions at <http://www.webkit.org/building/tools.html>.\n";
1738 print "*************************************************************\n";
1742 sub buildXCodeProject($$@)
1744 my ($project, $clean, @extraOptions) = @_;
1747 push(@extraOptions, "-alltargets");
1748 push(@extraOptions, "clean");
1751 push(@extraOptions, ("-sdk", xcodeSDK())) if isIOSWebKit();
1753 chomp($ENV{DSYMUTIL_NUM_THREADS} = `sysctl -n hw.activecpu`);
1754 return system "xcodebuild", "-project", "$project.xcodeproj", @extraOptions;
1757 sub usingVisualStudioExpress()
1760 return $willUseVCExpressWhenBuilding;
1763 sub buildVisualStudioProject
1765 my ($project, $clean) = @_;
1768 my $config = configurationForVisualStudio();
1770 dieIfWindowsPlatformSDKNotInstalled() if $willUseVCExpressWhenBuilding;
1772 chomp($project = `cygpath -w "$project"`) if isCygwin();
1774 my $action = "/t:build";
1776 $action = "/t:clean";
1779 my $platform = "/p:Platform=" . (isWin64() ? "x64" : "Win32");
1780 my $logPath = File::Spec->catdir($baseProductDir, $configuration);
1781 make_path($logPath) unless -d $logPath or $logPath eq ".";
1783 my $errorLogFile = File::Spec->catfile($logPath, "webkit_errors.log");
1784 chomp($errorLogFile = `cygpath -w "$errorLogFile"`) if isCygwin();
1785 my $errorLogging = "/flp:LogFile=" . $errorLogFile . ";ErrorsOnly";
1787 my $warningLogFile = File::Spec->catfile($logPath, "webkit_warnings.log");
1788 chomp($warningLogFile = `cygpath -w "$warningLogFile"`) if isCygwin();
1789 my $warningLogging = "/flp1:LogFile=" . $warningLogFile . ";WarningsOnly";
1791 my @command = ($vcBuildPath, "/verbosity:minimal", $project, $action, $config, $platform, "/fl", $errorLogging, "/fl1", $warningLogging);
1792 print join(" ", @command), "\n";
1793 return system @command;
1796 sub getJhbuildPath()
1798 my @jhbuildPath = File::Spec->splitdir(baseProductDir());
1799 if (isGit() && isGitBranchBuild() && gitBranch()) {
1803 push(@jhbuildPath, "DependenciesEFL");
1805 push(@jhbuildPath, "DependenciesGTK");
1807 die "Cannot get JHBuild path for platform that isn't GTK+ or EFL.\n";
1809 return File::Spec->catdir(@jhbuildPath);
1812 sub isCachedArgumentfileOutOfDate($@)
1814 my ($filename, $currentContents) = @_;
1816 if (! -e $filename) {
1820 open(CONTENTS_FILE, $filename);
1821 chomp(my $previousContents = <CONTENTS_FILE>);
1822 close(CONTENTS_FILE);
1824 if ($previousContents ne $currentContents) {
1825 print "Contents for file $filename have changed.\n";
1826 print "Previous contents were: $previousContents\n\n";
1827 print "New contents are: $currentContents\n";
1834 sub wrapperPrefixIfNeeded()
1836 if (isAnyWindows()) {
1839 if (isAppleMacWebKit()) {
1842 if (-e getJhbuildPath()) {
1843 my @prefix = (File::Spec->catfile(sourceDir(), "Tools", "jhbuild", "jhbuild-wrapper"));
1845 push(@prefix, "--efl");
1847 push(@prefix, "--gtk");
1849 push(@prefix, "run");
1857 sub cmakeCachePath()
1859 return File::Spec->catdir(baseProductDir(), configuration(), "CMakeCache.txt");
1862 sub shouldRemoveCMakeCache(@)
1864 my ($cacheFilePath, @buildArgs) = @_;
1866 # We check this first, because we always want to create this file for a fresh build.
1867 my $productDir = File::Spec->catdir(baseProductDir(), configuration());
1868 my $optionsCache = File::Spec->catdir($productDir, "build-webkit-options.txt");
1869 my $joinedBuildArgs = join(" ", @buildArgs);
1870 if (isCachedArgumentfileOutOfDate($optionsCache, $joinedBuildArgs)) {
1871 File::Path::mkpath($productDir) unless -d $productDir;
1872 open(CACHED_ARGUMENTS, ">", $optionsCache);
1873 print CACHED_ARGUMENTS $joinedBuildArgs;
1874 close(CACHED_ARGUMENTS);
1879 my $cmakeCache = cmakeCachePath();
1880 unless (-e $cmakeCache) {
1884 my $cacheFileModifiedTime = stat($cmakeCache)->mtime;
1885 my $platformConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "Options" . cmakeBasedPortName() . ".cmake");
1886 if ($cacheFileModifiedTime < stat($platformConfiguration)->mtime) {
1890 my $globalConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "OptionsCommon.cmake");
1891 if ($cacheFileModifiedTime < stat($globalConfiguration)->mtime) {
1895 my $inspectorUserInterfaceDircetory = File::Spec->catdir(sourceDir(), "Source", "WebInspectorUI", "UserInterface");
1896 if ($cacheFileModifiedTime < stat($inspectorUserInterfaceDircetory)->mtime) {
1903 sub removeCMakeCache(@)
1905 my (@buildArgs) = @_;
1906 if (shouldRemoveCMakeCache(@buildArgs)) {
1907 my $cmakeCache = cmakeCachePath();
1908 unlink($cmakeCache) if -e $cmakeCache;
1914 if (!defined($shouldNotUseNinja)) {
1915 $shouldNotUseNinja = checkForArgumentAndRemoveFromARGV("--no-ninja");
1918 if ($shouldNotUseNinja) {
1922 # Test both ninja and ninja-build. Fedora uses ninja-build and has patched CMake to also call ninja-build.
1923 return commandExists("ninja") || commandExists("ninja-build");
1926 sub canUseNinjaGenerator(@)
1928 # Check that a Ninja generator is installed
1929 my $devnull = File::Spec->devnull();
1930 return exitStatus(system("cmake -N -G Ninja >$devnull 2>&1")) == 0;
1933 sub canUseEclipseNinjaGenerator(@)
1935 # Check that eclipse and eclipse Ninja generator is installed
1936 my $devnull = File::Spec->devnull();
1937 return commandExists("eclipse") && exitStatus(system("cmake -N -G 'Eclipse CDT4 - Ninja' >$devnull 2>&1")) == 0;
1940 sub cmakeGeneratedBuildfile(@)
1942 my ($willUseNinja) = @_;
1943 if ($willUseNinja) {
1944 return File::Spec->catfile(baseProductDir(), configuration(), "build.ninja")
1945 } elsif (isAnyWindows()) {
1946 return File::Spec->catfile(baseProductDir(), configuration(), "WebKit.sln")
1948 return File::Spec->catfile(baseProductDir(), configuration(), "Makefile")
1952 sub generateBuildSystemFromCMakeProject
1954 my ($prefixPath, @cmakeArgs) = @_;
1955 my $config = configuration();
1956 my $port = cmakeBasedPortName();
1957 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
1958 File::Path::mkpath($buildPath) unless -d $buildPath;
1959 my $originalWorkingDirectory = getcwd();
1960 chdir($buildPath) or die;
1962 # We try to be smart about when to rerun cmake, so that we can have faster incremental builds.
1963 my $willUseNinja = canUseNinja() && canUseNinjaGenerator();
1964 if (-e cmakeCachePath() && -e cmakeGeneratedBuildfile($willUseNinja)) {
1969 push @args, "-DPORT=\"$port\"";
1970 push @args, "-DCMAKE_INSTALL_PREFIX=\"$prefixPath\"" if $prefixPath;
1971 push @args, "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON" if isGtk();
1972 if ($config =~ /release/i) {
1973 push @args, "-DCMAKE_BUILD_TYPE=Release";
1974 } elsif ($config =~ /debug/i) {
1975 push @args, "-DCMAKE_BUILD_TYPE=Debug";
1978 if ($willUseNinja) {
1980 if (canUseEclipseNinjaGenerator()) {
1981 push @args, "'Eclipse CDT4 - Ninja'";
1983 push @args, "Ninja";
1985 } elsif (isAnyWindows() && isWin64()) {
1986 push @args, '-G "Visual Studio 14 2015 Win64"';
1989 # GTK+ has a production mode, but build-webkit should always use developer mode.
1990 push @args, "-DDEVELOPER_MODE=ON" if isEfl() || isGtk();
1992 # Don't warn variables which aren't used by cmake ports.
1993 push @args, "--no-warn-unused-cli";
1994 push @args, @cmakeArgs if @cmakeArgs;
1996 my $cmakeSourceDir = isCygwin() ? windowsSourceDir() : sourceDir();
1997 push @args, '"' . $cmakeSourceDir . '"';
1999 # Compiler options to keep floating point values consistent
2000 # between 32-bit and 64-bit architectures.
2001 determineArchitecture();
2002 if ($architecture ne "x86_64" && !isARM() && !isCrossCompilation() && !isAnyWindows()) {
2003 $ENV{'CXXFLAGS'} = "-march=pentium4 -msse2 -mfpmath=sse " . ($ENV{'CXXFLAGS'} || "");
2006 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2007 # parsed for shell metacharacters.
2008 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2009 my $returnCode = system($wrapper . "cmake @args");
2011 chdir($originalWorkingDirectory);
2015 sub buildCMakeGeneratedProject($)
2017 my ($makeArgs) = @_;
2018 my $config = configuration();
2019 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2020 if (! -d $buildPath) {
2021 die "Must call generateBuildSystemFromCMakeProject() before building CMake project.";
2024 my $command = "cmake";
2025 my @args = ("--build", $buildPath, "--config", $config);
2026 push @args, ("--", $makeArgs) if $makeArgs;
2028 # GTK can use a build script to preserve colors and pretty-printing.
2029 if (isGtk() && -e "$buildPath/build.sh") {
2030 chdir "$buildPath" or die;
2031 $command = "$buildPath/build.sh";
2032 @args = ($makeArgs);
2035 if ($ENV{VERBOSE} && canUseNinja()) {
2037 push @args, "-d keeprsp" if (version->parse(determineNinjaVersion()) >= version->parse("1.4.0"));
2040 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2041 # parsed for shell metacharacters. In particular, $makeArgs may contain such metacharacters.
2042 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2043 return system($wrapper . "$command @args");
2046 sub cleanCMakeGeneratedProject()
2048 my $config = configuration();
2049 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2050 if (-d $buildPath) {
2051 return system("cmake", "--build", $buildPath, "--config", $config, "--target", "clean");
2056 sub buildCMakeProjectOrExit($$$@)
2058 my ($clean, $prefixPath, $makeArgs, @cmakeArgs) = @_;
2061 exit(exitStatus(cleanCMakeGeneratedProject())) if $clean;
2063 if (isEfl() && checkForArgumentAndRemoveFromARGV("--update-efl")) {
2064 system("perl", "$sourceDir/Tools/Scripts/update-webkitefl-libs") == 0 or die $!;
2067 if (isGtk() && checkForArgumentAndRemoveFromARGV("--update-gtk")) {
2068 system("perl", "$sourceDir/Tools/Scripts/update-webkitgtk-libs") == 0 or die $!;
2071 $returnCode = exitStatus(generateBuildSystemFromCMakeProject($prefixPath, @cmakeArgs));
2072 exit($returnCode) if $returnCode;
2074 $returnCode = exitStatus(buildCMakeGeneratedProject($makeArgs));
2075 exit($returnCode) if $returnCode;
2079 sub cmakeBasedPortArguments()
2084 sub cmakeBasedPortName()
2086 return ucfirst portName();
2089 sub determineIsCMakeBuild()
2091 return if defined($isCMakeBuild);
2092 $isCMakeBuild = checkForArgumentAndRemoveFromARGV("--cmake");
2097 return 1 unless isAppleMacWebKit();
2098 determineIsCMakeBuild();
2099 return $isCMakeBuild;
2104 my ($prompt, $default) = @_;
2105 my $defaultValue = $default ? "[$default]" : "";
2106 print "$prompt $defaultValue: ";
2107 chomp(my $input = <STDIN>);
2108 return $input ? $input : $default;
2111 sub appleApplicationSupportPath
2113 open INSTALL_DIR, "</proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/Apple\ Inc./Apple\ Application\ Support/InstallDir";
2114 my $path = <INSTALL_DIR>;
2115 $path =~ s/[\r\n\x00].*//;
2118 my $unixPath = `cygpath -u '$path'`;
2123 sub setPathForRunningWebKitApp
2127 if (isAnyWindows()) {
2128 my $productBinaryDir = executableProductDir();
2129 if (isAppleWinWebKit()) {
2130 $env->{PATH} = join(':', $productBinaryDir, appleApplicationSupportPath(), $env->{PATH} || "");
2131 } elsif (isWinCairo()) {
2132 my $winCairoBin = sourceDir() . "/WebKitLibraries/win/" . (isWin64() ? "bin64/" : "bin32/");
2133 my $gstreamerBin = isWin64() ? $ENV{"GSTREAMER_1_0_ROOT_X86_64"} . "bin" : $ENV{"GSTREAMER_1_0_ROOT_X86"} . "bin";
2134 $env->{PATH} = join(':', $productBinaryDir, $winCairoBin, $gstreamerBin, $env->{PATH} || "");
2139 sub printHelpAndExitForRunAndDebugWebKitAppIfNeeded
2141 return unless checkForArgumentAndRemoveFromARGV("--help");
2143 my ($includeOptionsForDebugging) = @_;
2146 Usage: @{[basename($0)]} [options] [args ...]
2147 --help Show this help message
2148 --no-saved-state Launch the application without state restoration (OS X 10.7 and later)
2149 -g|--guard-malloc Enable Guard Malloc (OS X only)
2152 if ($includeOptionsForDebugging) {
2154 --use-gdb Use GDB (this is the default when using Xcode 4.4 or earlier)
2155 --use-lldb Use LLDB (this is the default when using Xcode 4.5 or later)
2162 sub argumentsForRunAndDebugMacWebKitApp()
2165 if (checkForArgumentAndRemoveFromARGV("--no-saved-state")) {
2166 push @args, ("-ApplePersistenceIgnoreStateQuietly", "YES");
2167 # FIXME: Don't set ApplePersistenceIgnoreState once all supported OS versions respect ApplePersistenceIgnoreStateQuietly (rdar://15032886).
2168 push @args, ("-ApplePersistenceIgnoreState", "YES");
2170 unshift @args, @ARGV;
2175 sub setupMacWebKitEnvironment($)
2177 my ($dyldFrameworkPath) = @_;
2179 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2181 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2182 prependToEnvironmentVariableList("__XPC_DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2183 $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2185 setUpGuardMallocIfNeeded();
2188 sub setupIOSWebKitEnvironment($)
2190 my ($dyldFrameworkPath) = @_;
2191 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2193 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2194 prependToEnvironmentVariableList("DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2196 setUpGuardMallocIfNeeded();
2199 sub iosSimulatorApplicationsPath()
2201 return File::Spec->catdir(XcodeSDKPath(), "Applications");
2204 sub installedMobileSafariBundle()
2206 return File::Spec->catfile(iosSimulatorApplicationsPath(), "MobileSafari.app");
2209 sub mobileSafariBundle()
2211 determineConfigurationProductDir();
2213 # Use MobileSafari.app in product directory if present.
2214 if (isAppleMacWebKit() && -d "$configurationProductDir/MobileSafari.app") {
2215 return "$configurationProductDir/MobileSafari.app";
2217 return installedMobileSafariBundle();
2220 sub plistPathFromBundle($)
2222 my ($appBundle) = @_;
2223 return "$appBundle/Info.plist" if -f "$appBundle/Info.plist"; # iOS app bundle
2224 return "$appBundle/Contents/Info.plist" if -f "$appBundle/Contents/Info.plist"; # Mac app bundle
2228 sub appIdentifierFromBundle($)
2230 my ($appBundle) = @_;
2231 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2232 chomp(my $bundleIdentifier = `defaults read '$plistPath' CFBundleIdentifier 2> /dev/null`);
2233 return $bundleIdentifier;
2236 sub appDisplayNameFromBundle($)
2238 my ($appBundle) = @_;
2239 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2240 chomp(my $bundleDisplayName = `defaults read '$plistPath' CFBundleDisplayName 2> /dev/null`);
2241 return $bundleDisplayName;
2244 sub waitUntilIOSSimulatorDeviceIsInState($$)
2246 my ($deviceUDID, $waitUntilState) = @_;
2247 my $device = iosSimulatorDeviceByUDID($deviceUDID);
2248 while ($device->{state} ne $waitUntilState) {
2249 usleep(500 * 1000); # Waiting 500ms between file system polls does not make script run-safari feel sluggish.
2250 $device = iosSimulatorDeviceByUDID($deviceUDID);
2254 sub shutDownIOSSimulatorDevice($)
2256 my ($simulatorDevice) = @_;
2257 system("xcrun --sdk iphonesimulator simctl shutdown $simulatorDevice->{UDID} > /dev/null 2>&1");
2260 sub restartIOSSimulatorDevice($)
2262 my ($simulatorDevice) = @_;
2263 shutDownIOSSimulatorDevice($simulatorDevice);
2265 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "boot", $simulatorDevice->{UDID})) == 0 or die "Failed to boot simulator device $simulatorDevice->{UDID}";
2268 sub relaunchIOSSimulator($)
2270 my ($simulatedDevice) = @_;
2271 quitIOSSimulator($simulatedDevice->{UDID});
2273 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2274 my $iosSimulatorBundleID = "com.apple.iphonesimulator";
2275 system("open", "-b", $iosSimulatorBundleID, "--args", "-CurrentDeviceUDID", $simulatedDevice->{UDID}) == 0 or die "Failed to open $iosSimulatorBundleID: $!";
2277 waitUntilIOSSimulatorDeviceIsInState($simulatedDevice->{UDID}, SIMULATOR_DEVICE_STATE_BOOTED);
2280 sub quitIOSSimulator(;$)
2282 my ($waitForShutdownOfSimulatedDeviceUDID) = @_;
2283 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2284 exitStatus(system {"osascript"} "osascript", "-e", 'tell application id "com.apple.iphonesimulator" to quit') == 0 or die "Failed to quit iOS Simulator: $!";
2285 if (!defined($waitForShutdownOfSimulatedDeviceUDID)) {
2288 # FIXME: We assume that $waitForShutdownOfSimulatedDeviceUDID was not booted using the simctl command line tool.
2289 # Otherwise we will spin indefinitely since quiting the iOS Simulator will not shutdown this device. We
2290 # should add a maximum time limit to wait for a device to shutdown and either return an error or die()
2291 # on expiration of the time limit.
2292 waitUntilIOSSimulatorDeviceIsInState($waitForShutdownOfSimulatedDeviceUDID, SIMULATOR_DEVICE_STATE_SHUTDOWN);
2295 sub iosSimulatorDeviceByName($)
2297 my ($simulatorName) = @_;
2298 my $simulatorRuntime = iosSimulatorRuntime();
2299 my @devices = iOSSimulatorDevices();
2300 for my $device (@devices) {
2301 if ($device->{name} eq $simulatorName && $device->{runtime} eq $simulatorRuntime) {
2308 sub iosSimulatorDeviceByUDID($)
2310 my ($simulatedDeviceUDID) = @_;
2311 my $devicePlistPath = File::Spec->catfile(iOSSimulatorDevicesPath(), $simulatedDeviceUDID, "device.plist");
2312 if (!-f $devicePlistPath) {
2315 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
2316 # dictionary keys so as to decouple our representation of the plist from the actual structure
2317 # of the plist, which may change.
2318 eval "require Foundation";
2319 return Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_($devicePlistPath));
2322 sub iosSimulatorRuntime()
2324 my $xcodeSDKVersion = xcodeSDKVersion();
2325 $xcodeSDKVersion =~ s/\./-/;
2326 return "com.apple.CoreSimulator.SimRuntime.iOS-$xcodeSDKVersion";
2329 sub findOrCreateSimulatorForIOSDevice($)
2331 my ($simulatorNameSuffix) = @_;
2333 my $simulatorDeviceType;
2334 if (architecture() eq "x86_64") {
2335 $simulatorName = "iPhone 5s " . $simulatorNameSuffix;
2336 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5s";
2338 $simulatorName = "iPhone 5 " . $simulatorNameSuffix;
2339 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5";
2341 my $simulatedDevice = iosSimulatorDeviceByName($simulatorName);
2342 return $simulatedDevice if $simulatedDevice;
2343 return createiOSSimulatorDevice($simulatorName, $simulatorDeviceType, iosSimulatorRuntime());
2346 sub isIOSSimulatorSystemInstalledApp($)
2348 my ($appBundle) = @_;
2349 my $simulatorApplicationsPath = realpath(iosSimulatorApplicationsPath());
2350 return substr(realpath($appBundle), 0, length($simulatorApplicationsPath)) eq $simulatorApplicationsPath;
2353 sub hasUserInstalledAppInSimulatorDevice($$)
2355 my ($appIdentifier, $simulatedDeviceUDID) = @_;
2356 my $userInstalledAppPath = File::Spec->catfile($ENV{HOME}, "Library", "Developer", "CoreSimulator", "Devices", $simulatedDeviceUDID, "data", "Containers", "Bundle", "Application");
2357 if (!-d $userInstalledAppPath) {
2358 return 0; # No user installed apps.
2360 local @::userInstalledAppBundles;
2361 my $wantedFunction = sub {
2364 # Ignore hidden files and directories.
2365 if ($file =~ /^\../) {
2366 $File::Find::prune = 1;
2370 return if !-d $file || $file !~ /\.app$/;
2371 push @::userInstalledAppBundles, $File::Find::name;
2372 $File::Find::prune = 1; # Do not traverse contents of app bundle.
2374 find($wantedFunction, $userInstalledAppPath);
2375 for my $userInstalledAppBundle (@::userInstalledAppBundles) {
2376 if (appIdentifierFromBundle($userInstalledAppBundle) eq $appIdentifier) {
2377 return 1; # Has user installed app.
2380 return 0; # Does not have user installed app.
2383 sub isSimulatorDeviceBooted($)
2385 my ($simulatedDeviceUDID) = @_;
2386 my $device = iosSimulatorDeviceByUDID($simulatedDeviceUDID);
2387 return $device && $device->{state} eq SIMULATOR_DEVICE_STATE_BOOTED;
2390 sub runIOSWebKitAppInSimulator($;$)
2392 my ($appBundle, $simulatorOptions) = @_;
2393 my $productDir = productDir();
2394 my $appDisplayName = appDisplayNameFromBundle($appBundle);
2395 my $appIdentifier = appIdentifierFromBundle($appBundle);
2396 my $simulatedDevice = findOrCreateSimulatorForIOSDevice(SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT);
2397 my $simulatedDeviceUDID = $simulatedDevice->{UDID};
2399 my $willUseSystemInstalledApp = isIOSSimulatorSystemInstalledApp($appBundle);
2400 if ($willUseSystemInstalledApp) {
2401 if (hasUserInstalledAppInSimulatorDevice($appIdentifier, $simulatedDeviceUDID)) {
2402 # Restore the system-installed app in the simulator device corresponding to $appBundle as it
2403 # was previously overwritten with a custom built version of the app.
2404 # FIXME: Only restore the system-installed version of the app instead of erasing all contents and settings.
2405 print "Quitting iOS Simulator...\n";
2406 quitIOSSimulator($simulatedDeviceUDID);
2407 print "Erasing contents and settings for simulator device \"$simulatedDevice->{name}\".\n";
2408 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "erase", $simulatedDeviceUDID)) == 0 or die;
2410 # FIXME: We assume that if $simulatedDeviceUDID is not booted then iOS Simulator is not open. However
2411 # $simulatedDeviceUDID may have been booted using the simctl command line tool. If $simulatedDeviceUDID
2412 # was booted using simctl then we should shutdown the device and launch iOS Simulator to boot it again.
2413 if (!isSimulatorDeviceBooted($simulatedDeviceUDID)) {
2414 print "Launching iOS Simulator...\n";
2415 relaunchIOSSimulator($simulatedDevice);
2418 # FIXME: We should killall(1) any running instances of $appBundle before installing it to ensure
2419 # that simctl launch opens the latest installed version of the app. For now we quit and
2420 # launch the iOS Simulator again to ensure there are no running instances of $appBundle.
2421 print "Quitting and launching iOS Simulator...\n";
2422 relaunchIOSSimulator($simulatedDevice);
2424 print "Installing $appBundle.\n";
2425 # Install custom built app, overwriting an app with the same app identifier if one exists.
2426 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "install", $simulatedDeviceUDID, $appBundle)) == 0 or die;
2430 $simulatorOptions = {} unless $simulatorOptions;
2433 %simulatorENV = %{$simulatorOptions->{applicationEnvironment}} if $simulatorOptions->{applicationEnvironment};
2435 local %ENV; # Shadow global-scope %ENV so that changes to it will not be seen outside of this scope.
2436 setupIOSWebKitEnvironment($productDir);
2437 %simulatorENV = %ENV;
2439 my $applicationArguments = \@ARGV;
2440 $applicationArguments = $simulatorOptions->{applicationArguments} if $simulatorOptions && $simulatorOptions->{applicationArguments};
2442 # Prefix the environment variables with SIMCTL_CHILD_ per `xcrun simctl help launch`.
2443 foreach my $key (keys %simulatorENV) {
2444 $ENV{"SIMCTL_CHILD_$key"} = $simulatorENV{$key};
2447 print "Starting $appDisplayName with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2448 return exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "launch", $simulatedDeviceUDID, $appIdentifier, @$applicationArguments));
2451 sub runIOSWebKitApp($)
2453 my ($appBundle) = @_;
2454 if (willUseIOSDeviceSDK()) {
2455 die "Only running Safari in iOS Simulator is supported now.";
2457 if (willUseIOSSimulatorSDK()) {
2458 return runIOSWebKitAppInSimulator($appBundle);
2460 die "Not using an iOS SDK."
2463 sub runMacWebKitApp($;$)
2465 my ($appPath, $useOpenCommand) = @_;
2466 my $productDir = productDir();
2467 print "Starting @{[basename($appPath)]} with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2470 setupMacWebKitEnvironment($productDir);
2472 if (defined($useOpenCommand) && $useOpenCommand == USE_OPEN_COMMAND) {
2473 return system("open", "-W", "-a", $appPath, "--args", argumentsForRunAndDebugMacWebKitApp());
2475 if (architecture()) {
2476 return system "arch", "-" . architecture(), $appPath, argumentsForRunAndDebugMacWebKitApp();
2478 return system { $appPath } $appPath, argumentsForRunAndDebugMacWebKitApp();
2481 sub execMacWebKitAppForDebugging($)
2484 my $architectureSwitch;
2485 my $argumentsSeparator;
2487 if (debugger() eq "lldb") {
2488 $architectureSwitch = "--arch";
2489 $argumentsSeparator = "--";
2490 } elsif (debugger() eq "gdb") {
2491 $architectureSwitch = "-arch";
2492 $argumentsSeparator = "--args";
2494 die "Unknown debugger $debugger.\n";
2497 my $debuggerPath = `xcrun -find $debugger`;
2498 chomp $debuggerPath;
2499 die "Can't find the $debugger executable.\n" unless -x $debuggerPath;
2501 my $productDir = productDir();
2502 setupMacWebKitEnvironment($productDir);
2504 my @architectureFlags = ($architectureSwitch, architecture());
2505 print "Starting @{[basename($appPath)]} under $debugger with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2506 exec { $debuggerPath } $debuggerPath, @architectureFlags, $argumentsSeparator, $appPath, argumentsForRunAndDebugMacWebKitApp() or die;
2511 if (isAppleMacWebKit()) {
2513 execMacWebKitAppForDebugging(safariPath());
2516 return 1; # Unsupported platform; can't debug Safari on this platform.
2521 if (isIOSWebKit()) {
2522 return runIOSWebKitApp(mobileSafariBundle());
2525 if (isAppleMacWebKit()) {
2526 return runMacWebKitApp(safariPath());
2529 if (isAppleWinWebKit()) {
2531 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2532 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2535 return 1; # Unsupported platform; can't run Safari on this platform.
2540 if (isAppleMacWebKit()) {
2541 return runMacWebKitApp(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2542 } elsif (isAppleWinWebKit()) {
2544 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2545 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2551 sub debugMiniBrowser
2553 if (isAppleMacWebKit()) {
2554 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2560 sub runWebKitTestRunner
2562 if (isAppleMacWebKit()) {
2563 return runMacWebKitApp(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2569 sub debugWebKitTestRunner
2571 if (isAppleMacWebKit()) {
2572 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2578 sub readRegistryString
2580 my ($valueName) = @_;
2581 chomp(my $string = `regtool --wow32 get "$valueName"`);
2585 sub writeRegistryString
2587 my ($valueName, $string) = @_;
2589 my $error = system "regtool", "--wow32", "set", "-s", $valueName, $string;
2591 # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
2592 # return a successful exit code. So we double-check here that the value we tried to write to the
2593 # registry was really written.
2594 return !$error && readRegistryString($valueName) eq $string;
2597 sub formatBuildTime($)
2599 my ($buildTime) = @_;
2601 my $buildHours = int($buildTime / 3600);
2602 my $buildMins = int(($buildTime - $buildHours * 3600) / 60);
2603 my $buildSecs = $buildTime - $buildHours * 3600 - $buildMins * 60;
2606 return sprintf("%dh:%02dm:%02ds", $buildHours, $buildMins, $buildSecs);
2608 return sprintf("%02dm:%02ds", $buildMins, $buildSecs);
2611 sub runSvnUpdateAndResolveChangeLogs(@)
2613 my @svnOptions = @_;
2614 my $openCommand = "svn update " . join(" ", @svnOptions);
2615 open my $update, "$openCommand |" or die "cannot execute command $openCommand";
2616 my @conflictedChangeLogs;
2617 while (my $line = <$update>) {
2619 $line =~ m/^C\s+(.+?)[\r\n]*$/;
2621 my $filename = normalizePath($1);
2622 push @conflictedChangeLogs, $filename if basename($filename) eq "ChangeLog";
2625 close $update or die;
2627 if (@conflictedChangeLogs) {
2628 print "Attempting to merge conflicted ChangeLogs.\n";
2629 my $resolveChangeLogsPath = File::Spec->catfile(sourceDir(), "Tools", "Scripts", "resolve-ChangeLogs");
2630 (system($resolveChangeLogsPath, "--no-warnings", @conflictedChangeLogs) == 0)
2631 or die "Could not open resolve-ChangeLogs script: $!.\n";
2637 # Doing a git fetch first allows setups with svn-remote.svn.fetch = trunk:refs/remotes/origin/master
2638 # to perform the rebase much much faster.
2639 system("git", "fetch");
2640 if (isGitSVNDirectory(".")) {
2641 system("git", "svn", "rebase") == 0 or die;
2643 # This will die if branch.$BRANCHNAME.merge isn't set, which is
2644 # almost certainly what we want.
2645 system("git", "pull") == 0 or die;