1 # Copyright (C) 2005-2007, 2010-2015 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
70 &findOrCreateSimulatorForIOSDevice
71 &iosSimulatorDeviceByName
74 &prependToEnvironmentVariableList
75 &printHelpAndExitForRunAndDebugWebKitAppIfNeeded
79 &restartIOSSimulatorDevice
85 &setupMacWebKitEnvironment
86 &sharedCommandLineOptions
87 &sharedCommandLineOptionsUsage
88 &shutDownIOSSimulatorDevice
90 &willUseIOSSimulatorSDK
91 SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT
98 use constant USE_OPEN_COMMAND => 1; # Used in runMacWebKitApp().
99 use constant INCLUDE_OPTIONS_FOR_DEBUGGING => 1;
100 use constant SIMULATOR_DEVICE_STATE_SHUTDOWN => "1";
101 use constant SIMULATOR_DEVICE_STATE_BOOTED => "3";
102 use constant SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT => "For WebKit Development";
104 # 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>.
105 use constant IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX => "iPhone Developer: ";
114 my @baseProductDirOption;
117 my $configurationForVisualStudio;
118 my $configurationProductDir;
120 my $currentSVNRevision;
122 my $didLoadIPhoneSimulatorNotification;
132 my $isInspectorFrontend;
133 my $shouldTargetWebProcess;
134 my $shouldUseXPCServiceForWebProcess;
135 my $shouldUseGuardMalloc;
136 my $shouldNotUseNinja;
139 # Variables for Win32 support
140 my $programFilesPath;
143 my $msBuildInstallDir;
145 my $windowsSourceDir;
147 my $willUseVCExpressWhenBuilding = 0;
149 # Defined in VCSUtils.
152 sub findMatchingArguments($$);
155 sub determineSourceDir
157 return if $sourceDir;
158 $sourceDir = $FindBin::Bin;
159 $sourceDir =~ s|/+$||; # Remove trailing '/' as we would die later
161 # walks up path checking each directory to see if it is the main WebKit project dir,
162 # defined by containing Sources, WebCore, and WebKit
163 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")))
165 if ($sourceDir !~ s|/[^/]+$||) {
166 die "Could not find top level webkit directory above source directory using FindBin.\n";
170 $sourceDir = File::Spec->catdir($sourceDir, "OpenSource") if -d File::Spec->catdir($sourceDir, "OpenSource");
173 sub currentPerlPath()
177 $thisPerl .= $Config{_exe} unless $thisPerl =~ m/$Config{_exe}$/i;
182 # used for scripts which are stored in a non-standard location
188 sub determineNinjaVersion
190 chomp(my $ninjaVersion = `ninja --version`);
191 return $ninjaVersion;
194 sub determineXcodeVersion
196 return if defined $xcodeVersion;
197 my $xcodebuildVersionOutput = `xcodebuild -version`;
198 $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : "3.0";
201 sub readXcodeUserDefault($)
203 my ($unprefixedKey) = @_;
205 determineXcodeVersion();
207 my $xcodeDefaultsDomain = (eval "v$xcodeVersion" lt v4) ? "com.apple.Xcode" : "com.apple.dt.Xcode";
208 my $xcodeDefaultsPrefix = (eval "v$xcodeVersion" lt v4) ? "PBX" : "IDE";
209 my $devnull = File::Spec->devnull();
211 my $value = `defaults read $xcodeDefaultsDomain ${xcodeDefaultsPrefix}${unprefixedKey} 2> ${devnull}`;
218 sub determineBaseProductDir
220 return if defined $baseProductDir;
221 determineSourceDir();
223 my $setSharedPrecompsDir;
224 $baseProductDir = $ENV{"WEBKIT_OUTPUTDIR"};
226 if (!defined($baseProductDir) and isAppleMacWebKit()) {
227 # Silently remove ~/Library/Preferences/xcodebuild.plist which can
228 # cause build failure. The presence of
229 # ~/Library/Preferences/xcodebuild.plist can prevent xcodebuild from
230 # respecting global settings such as a custom build products directory
231 # (<rdar://problem/5585899>).
232 my $personalPlistFile = $ENV{HOME} . "/Library/Preferences/xcodebuild.plist";
233 if (-e $personalPlistFile) {
234 unlink($personalPlistFile) || die "Could not delete $personalPlistFile: $!";
237 determineXcodeVersion();
239 if (eval "v$xcodeVersion" ge v4) {
240 my $buildLocationStyle = join '', readXcodeUserDefault("BuildLocationStyle");
241 if ($buildLocationStyle eq "Custom") {
242 my $buildLocationType = join '', readXcodeUserDefault("CustomBuildLocationType");
243 # FIXME: Read CustomBuildIntermediatesPath and set OBJROOT accordingly.
244 $baseProductDir = readXcodeUserDefault("CustomBuildProductsPath") if $buildLocationType eq "Absolute";
247 # DeterminedByTargets corresponds to a setting of "Legacy" in Xcode.
248 # It is the only build location style for which SHARED_PRECOMPS_DIR is not
249 # overridden when building from within Xcode.
250 $setSharedPrecompsDir = 1 if $buildLocationStyle ne "DeterminedByTargets";
253 if (!defined($baseProductDir)) {
254 $baseProductDir = join '', readXcodeUserDefault("ApplicationwideBuildSettings");
255 $baseProductDir = $1 if $baseProductDir =~ /SYMROOT\s*=\s*\"(.*?)\";/s;
258 undef $baseProductDir unless $baseProductDir =~ /^\//;
261 if (!defined($baseProductDir)) { # Port-specific checks failed, use default
262 $baseProductDir = File::Spec->catdir($sourceDir, "WebKitBuild");
265 if (isGit() && isGitBranchBuild()) {
266 my $branch = gitBranch();
267 $baseProductDir = "$baseProductDir/$branch";
270 if (isAppleMacWebKit()) {
271 $baseProductDir =~ s|^\Q$(SRCROOT)/..\E$|$sourceDir|;
272 $baseProductDir =~ s|^\Q$(SRCROOT)/../|$sourceDir/|;
273 $baseProductDir =~ s|^~/|$ENV{HOME}/|;
274 die "Can't handle Xcode product directory with a ~ in it.\n" if $baseProductDir =~ /~/;
275 die "Can't handle Xcode product directory with a variable in it.\n" if $baseProductDir =~ /\$/;
276 @baseProductDirOption = ("SYMROOT=$baseProductDir", "OBJROOT=$baseProductDir");
277 push(@baseProductDirOption, "SHARED_PRECOMPS_DIR=${baseProductDir}/PrecompiledHeaders") if $setSharedPrecompsDir;
281 my $dosBuildPath = `cygpath --windows \"$baseProductDir\"`;
283 $ENV{"WEBKIT_OUTPUTDIR"} = $dosBuildPath;
284 my $unixBuildPath = `cygpath --unix \"$baseProductDir\"`;
285 chomp $unixBuildPath;
286 $baseProductDir = $dosBuildPath;
290 sub setBaseProductDir($)
292 ($baseProductDir) = @_;
295 sub determineConfiguration
297 return if defined $configuration;
298 determineBaseProductDir();
299 if (open CONFIGURATION, "$baseProductDir/Configuration") {
300 $configuration = <CONFIGURATION>;
303 if ($configuration) {
304 chomp $configuration;
305 # compatibility for people who have old Configuration files
306 $configuration = "Release" if $configuration eq "Deployment";
307 $configuration = "Debug" if $configuration eq "Development";
309 $configuration = "Release";
313 sub determineArchitecture
315 return if defined $architecture;
316 # make sure $architecture is defined in all cases
319 determineBaseProductDir();
322 if (isAppleMacWebKit()) {
323 if (open ARCHITECTURE, "$baseProductDir/Architecture") {
324 $architecture = <ARCHITECTURE>;
330 if (not defined $xcodeSDK or $xcodeSDK =~ /^(\/$|macosx)/) {
331 my $supports64Bit = `sysctl -n hw.optional.x86_64`;
332 chomp $supports64Bit;
333 $architecture = 'x86_64' if $supports64Bit;
334 } elsif ($xcodeSDK =~ /^iphonesimulator/) {
335 $architecture = 'x86_64';
336 } elsif ($xcodeSDK =~ /^iphoneos/) {
337 $architecture = 'armv7';
340 } elsif (isCMakeBuild()) {
341 my $host_processor = "";
342 if (open my $cmake_sysinfo, "cmake --system-information |") {
343 while (<$cmake_sysinfo>) {
344 next unless index($_, 'CMAKE_SYSTEM_PROCESSOR') == 0;
345 if (/^CMAKE_SYSTEM_PROCESSOR \"([^"]+)\"/) {
347 $architecture = 'x86_64' if $architecture eq 'amd64';
351 close $cmake_sysinfo;
355 if (!isAnyWindows()) {
356 if (!$architecture) {
357 # Fall back to output of `arch', if it is present.
358 $architecture = `arch`;
362 if (!$architecture) {
363 # Fall back to output of `uname -m', if it is present.
364 $architecture = `uname -m`;
369 $architecture = 'x86_64' if ($architecture =~ /amd64/ && isBSD());
372 sub determineASanIsEnabled
374 return if defined $asanIsEnabled;
375 determineBaseProductDir();
378 my $asanConfigurationValue;
380 if (open ASAN, "$baseProductDir/ASan") {
381 $asanConfigurationValue = <ASAN>;
383 chomp $asanConfigurationValue;
384 $asanIsEnabled = 1 if $asanConfigurationValue eq "YES";
388 sub determineNumberOfCPUs
390 return if defined $numberOfCPUs;
391 if (defined($ENV{NUMBER_OF_PROCESSORS})) {
392 $numberOfCPUs = $ENV{NUMBER_OF_PROCESSORS};
393 } elsif (isLinux()) {
394 # First try the nproc utility, if it exists. If we get no
395 # results fall back to just interpretting /proc directly.
396 chomp($numberOfCPUs = `nproc --all 2> /dev/null`);
397 if ($numberOfCPUs eq "") {
398 $numberOfCPUs = (grep /processor/, `cat /proc/cpuinfo`);
400 } elsif (isWindows() || isCygwin()) {
402 $numberOfCPUs = `ls /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor | wc -w`;
403 } elsif (isDarwin() || isBSD()) {
404 chomp($numberOfCPUs = `sysctl -n hw.ncpu`);
408 sub determineMaxCPULoad
410 return if defined $maxCPULoad;
411 if (defined($ENV{MAX_CPU_LOAD})) {
412 $maxCPULoad = $ENV{MAX_CPU_LOAD};
418 my ($productDir) = @_;
420 $jscName .= "_debug" if configuration() eq "Debug_All";
421 $jscName .= ".exe" if (isWindows() || isCygwin());
422 return "$productDir/$jscName" if -e "$productDir/$jscName";
423 return "$productDir/JavaScriptCore.framework/Resources/$jscName";
426 sub argumentsForConfiguration()
428 determineConfiguration();
429 determineArchitecture();
433 # FIXME: Is it necessary to pass --debug, --release, --32-bit or --64-bit?
434 # These are determined automatically from stored configuration.
435 push(@args, '--debug') if ($configuration =~ "^Debug");
436 push(@args, '--release') if ($configuration =~ "^Release");
437 push(@args, '--device') if (defined $xcodeSDK && $xcodeSDK =~ /^iphoneos/);
438 push(@args, '--ios-simulator') if (defined $xcodeSDK && $xcodeSDK =~ /^iphonesimulator/);
439 push(@args, '--32-bit') if ($architecture ne "x86_64" and !isWin64());
440 push(@args, '--64-bit') if (isWin64());
441 push(@args, '--gtk') if isGtk();
442 push(@args, '--efl') if isEfl();
443 push(@args, '--wincairo') if isWinCairo();
444 push(@args, '--inspector-frontend') if isInspectorFrontend();
448 sub determineXcodeSDK
450 return if defined $xcodeSDK;
452 if (checkForArgumentAndRemoveFromARGVGettingValue("--sdk", \$sdk)) {
455 if (checkForArgumentAndRemoveFromARGV("--device")) {
456 my $hasInternalSDK = exitStatus(system("xcrun --sdk iphoneos.internal --show-sdk-version > /dev/null 2>&1")) == 0;
457 $xcodeSDK ||= $hasInternalSDK ? "iphoneos.internal" : "iphoneos";
459 if (checkForArgumentAndRemoveFromARGV("--ios-simulator")) {
460 $xcodeSDK ||= 'iphonesimulator';
476 sub xcodeSDKPlatformName()
479 return "" if !defined $xcodeSDK;
480 return "iphoneos" if $xcodeSDK =~ /iphoneos/i;
481 return "iphonesimulator" if $xcodeSDK =~ /iphonesimulator/i;
482 return "macosx" if $xcodeSDK =~ /macosx/i;
483 die "Couldn't determine platform name from Xcode SDK";
490 die "Can't find the SDK path because no Xcode SDK was specified" if not $xcodeSDK;
492 my $sdkPath = `xcrun --sdk $xcodeSDK --show-sdk-path` if $xcodeSDK;
493 die 'Failed to get SDK path from xcrun' if $?;
503 die "Can't find the SDK version because no Xcode SDK was specified" if !$xcodeSDK;
505 chomp(my $sdkVersion = `xcrun --sdk $xcodeSDK --show-sdk-version`);
506 die "Failed to get SDK version from xcrun" if exitStatus($?);
513 return $programFilesPath if defined $programFilesPath;
515 $programFilesPath = $ENV{'PROGRAMFILES(X86)'} || $ENV{'PROGRAMFILES'} || "C:\\Program Files";
517 return $programFilesPath;
520 sub visualStudioInstallDir
522 return $vsInstallDir if defined $vsInstallDir;
524 if ($ENV{'VSINSTALLDIR'}) {
525 $vsInstallDir = $ENV{'VSINSTALLDIR'};
526 $vsInstallDir =~ s|[\\/]$||;
528 $vsInstallDir = File::Spec->catdir(programFilesPath(), "Microsoft Visual Studio 14.0");
530 chomp($vsInstallDir = `cygpath "$vsInstallDir"`) if isCygwin();
532 print "Using Visual Studio: $vsInstallDir\n";
533 return $vsInstallDir;
536 sub msBuildInstallDir
538 return $msBuildInstallDir if defined $msBuildInstallDir;
540 $msBuildInstallDir = File::Spec->catdir(programFilesPath(), "MSBuild", "14.0", "Bin");
542 chomp($msBuildInstallDir = `cygpath "$msBuildInstallDir"`) if isCygwin();
544 print "Using MSBuild: $msBuildInstallDir\n";
545 return $msBuildInstallDir;
548 sub visualStudioVersion
550 return $vsVersion if defined $vsVersion;
552 my $installDir = visualStudioInstallDir();
554 $vsVersion = ($installDir =~ /Microsoft Visual Studio ([0-9]+\.[0-9]*)/) ? $1 : "14";
556 print "Using Visual Studio $vsVersion\n";
560 sub determineConfigurationForVisualStudio
562 return if defined $configurationForVisualStudio;
563 determineConfiguration();
564 # FIXME: We should detect when Debug_All or Production has been chosen.
565 $configurationForVisualStudio = "/p:Configuration=" . $configuration;
568 sub usesPerConfigurationBuildDirectory
570 # [Gtk] We don't have Release/Debug configurations in straight
571 # autotool builds (non build-webkit). In this case and if
572 # WEBKIT_OUTPUTDIR exist, use that as our configuration dir. This will
573 # allows us to run run-webkit-tests without using build-webkit.
574 return ($ENV{"WEBKIT_OUTPUTDIR"} && isGtk()) || isAppleWinWebKit();
577 sub determineConfigurationProductDir
579 return if defined $configurationProductDir;
580 determineBaseProductDir();
581 determineConfiguration();
582 if (isAppleWinWebKit() || isWinCairo()) {
583 $configurationProductDir = File::Spec->catdir($baseProductDir, $configuration);
585 if (usesPerConfigurationBuildDirectory()) {
586 $configurationProductDir = "$baseProductDir";
588 $configurationProductDir = "$baseProductDir/$configuration";
589 $configurationProductDir .= "-" . xcodeSDKPlatformName() if isIOSWebKit();
594 sub setConfigurationProductDir($)
596 ($configurationProductDir) = @_;
599 sub determineCurrentSVNRevision
601 # We always update the current SVN revision here, and leave the caching
602 # to currentSVNRevision(), so that changes to the SVN revision while the
603 # script is running can be picked up by calling this function again.
604 determineSourceDir();
605 $currentSVNRevision = svnRevisionForDirectory($sourceDir);
606 return $currentSVNRevision;
612 determineSourceDir();
613 chdir $sourceDir or die;
618 determineBaseProductDir();
619 return $baseProductDir;
624 determineSourceDir();
630 determineConfigurationProductDir();
631 return $configurationProductDir;
634 sub executableProductDir
636 my $productDirectory = productDir();
639 if (isEfl() || isGtk()) {
640 $binaryDirectory = "bin";
641 } elsif (isAnyWindows()) {
642 $binaryDirectory = isWin64() ? "bin64" : "bin32";
644 return $productDirectory;
647 return File::Spec->catdir($productDirectory, $binaryDirectory);
652 return executableProductDir();
657 determineConfiguration();
658 return $configuration;
663 determineASanIsEnabled();
664 return $asanIsEnabled;
667 sub configurationForVisualStudio()
669 determineConfigurationForVisualStudio();
670 return $configurationForVisualStudio;
673 sub currentSVNRevision
675 determineCurrentSVNRevision() if not defined $currentSVNRevision;
676 return $currentSVNRevision;
681 determineGenerateDsym();
682 return $generateDsym;
685 sub determineGenerateDsym()
687 return if defined($generateDsym);
688 $generateDsym = checkForArgumentAndRemoveFromARGV("--dsym");
691 sub hasIOSDevelopmentCertificate()
693 return !exitStatus(system("security find-identity -p codesigning | grep '" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX . "' > /dev/null 2>&1"));
696 sub argumentsForXcode()
699 push @args, "DEBUG_INFORMATION_FORMAT=dwarf-with-dsym" if generateDsym();
705 determineBaseProductDir();
706 determineConfiguration();
707 determineArchitecture();
708 determineASanIsEnabled();
712 push @options, "-UseSanitizedBuildSystemEnvironment=YES";
713 push @options, ("-configuration", $configuration);
714 push @options, ("-xcconfig", sourceDir() . "/Tools/asan/asan.xcconfig", "ASAN_IGNORE=" . sourceDir() . "/Tools/asan/webkit-asan-ignore.txt") if $asanIsEnabled;
715 push @options, @baseProductDirOption;
716 push @options, "ARCHS=$architecture" if $architecture;
717 push @options, "SDKROOT=$xcodeSDK" if $xcodeSDK;
718 if (willUseIOSDeviceSDK()) {
719 push @options, "ENABLE_BITCODE=NO";
720 if (hasIOSDevelopmentCertificate()) {
721 # FIXME: May match more than one installed development certificate.
722 push @options, "CODE_SIGN_IDENTITY=" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX;
724 push @options, "CODE_SIGN_IDENTITY="; # No identity
725 push @options, "CODE_SIGNING_REQUIRED=NO";
728 push @options, argumentsForXcode();
732 sub XcodeOptionString
734 return join " ", XcodeOptions();
737 sub XcodeOptionStringNoConfig
739 return join " ", @baseProductDirOption;
742 sub XcodeCoverageSupportOptions()
744 my @coverageSupportOptions = ();
745 push @coverageSupportOptions, "GCC_GENERATE_TEST_COVERAGE_FILES=YES";
746 push @coverageSupportOptions, "GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES";
747 return @coverageSupportOptions;
750 sub XcodeStaticAnalyzerOption()
752 return "RUN_CLANG_STATIC_ANALYZER=YES";
755 my $passedConfiguration;
756 my $searchedForPassedConfiguration;
757 sub determinePassedConfiguration
759 return if $searchedForPassedConfiguration;
760 $searchedForPassedConfiguration = 1;
761 $passedConfiguration = undef;
763 if (checkForArgumentAndRemoveFromARGV("--debug")) {
764 $passedConfiguration = "Debug";
765 } elsif(checkForArgumentAndRemoveFromARGV("--release")) {
766 $passedConfiguration = "Release";
767 } elsif (checkForArgumentAndRemoveFromARGV("--profile") || checkForArgumentAndRemoveFromARGV("--profiling")) {
768 $passedConfiguration = "Profiling";
772 sub passedConfiguration
774 determinePassedConfiguration();
775 return $passedConfiguration;
782 if (my $config = shift @_) {
783 $configuration = $config;
787 determinePassedConfiguration();
788 $configuration = $passedConfiguration if $passedConfiguration;
792 my $passedArchitecture;
793 my $searchedForPassedArchitecture;
794 sub determinePassedArchitecture
796 return if $searchedForPassedArchitecture;
797 $searchedForPassedArchitecture = 1;
799 $passedArchitecture = undef;
800 if (checkForArgumentAndRemoveFromARGV("--32-bit")) {
801 if (isAppleMacWebKit()) {
802 # PLATFORM_IOS: Don't run `arch` command inside Simulator environment
804 delete $ENV{DYLD_ROOT_PATH};
805 delete $ENV{DYLD_FRAMEWORK_PATH};
807 $passedArchitecture = `arch`;
808 chomp $passedArchitecture;
813 sub passedArchitecture
815 determinePassedArchitecture();
816 return $passedArchitecture;
821 determineArchitecture();
822 return $architecture;
827 determineNumberOfCPUs();
828 return $numberOfCPUs;
833 determineMaxCPULoad();
839 if (my $arch = shift @_) {
840 $architecture = $arch;
844 determinePassedArchitecture();
845 $architecture = $passedArchitecture if $passedArchitecture;
848 sub skipSafariExecutableEntitlementChecks
850 return `defaults read /Library/Preferences/org.webkit.BuildConfiguration SkipSafariExecutableEntitlementChecks 2>/dev/null` eq "1\n";
853 sub executableHasEntitlements
855 my $executablePath = shift;
856 return (`codesign -d --entitlements - $executablePath 2>&1` =~ /<key>/);
859 sub safariPathFromSafariBundle
861 my ($safariBundle) = @_;
863 die "Safari path is only relevant on Apple Mac platform\n" unless isAppleMacWebKit();
865 my $safariPath = "$safariBundle/Contents/MacOS/Safari";
866 return $safariPath if skipSafariExecutableEntitlementChecks();
868 my $safariForWebKitDevelopmentPath = "$safariBundle/Contents/MacOS/SafariForWebKitDevelopment";
869 return $safariForWebKitDevelopmentPath if -f $safariForWebKitDevelopmentPath && executableHasEntitlements($safariPath);
874 sub installedSafariPath
876 return safariPathFromSafariBundle("/Applications/Safari.app");
882 die "Safari path is only relevant on Apple Mac platform\n" unless isAppleMacWebKit();
884 # Use WEBKIT_SAFARI environment variable if present.
885 my $safariBundle = $ENV{WEBKIT_SAFARI};
886 if (!$safariBundle) {
887 determineConfigurationProductDir();
888 # Use Safari.app in product directory if present (good for Safari development team).
889 if (-d "$configurationProductDir/Safari.app") {
890 $safariBundle = "$configurationProductDir/Safari.app";
892 if (!$safariBundle) {
893 return installedSafariPath();
896 my $safariPath = safariPathFromSafariBundle($safariBundle);
897 die "Can't find executable at $safariPath.\n" if !-x $safariPath;
901 sub builtDylibPathForName
903 my $libraryName = shift;
904 determineConfigurationProductDir();
907 my $extension = isDarwin() ? ".dylib" : ".so";
908 return "$configurationProductDir/lib/libwebkit2gtk-4.0" . $extension;
911 return "$configurationProductDir/lib/libewebkit2.so";
914 return "$configurationProductDir/$libraryName.framework/$libraryName";
916 if (isAppleMacWebKit()) {
917 return "$configurationProductDir/$libraryName.framework/Versions/A/$libraryName";
919 if (isAppleWinWebKit()) {
920 if ($libraryName eq "JavaScriptCore") {
921 return "$baseProductDir/lib/$libraryName.lib";
923 return "$baseProductDir/$libraryName.intermediate/$configuration/$libraryName.intermediate/$libraryName.lib";
927 die "Unsupported platform, can't determine built library locations.\nTry `build-webkit --help` for more information.\n";
930 # Check to see that all the frameworks are built.
931 sub checkFrameworks # FIXME: This is a poor name since only the Mac calls built WebCore a Framework.
933 return if isCygwin() || isWindows();
934 my @frameworks = ("JavaScriptCore", "WebCore");
935 push(@frameworks, "WebKit") if isAppleMacWebKit(); # FIXME: This seems wrong, all ports should have a WebKit these days.
936 for my $framework (@frameworks) {
937 my $path = builtDylibPathForName($framework);
938 die "Can't find built framework at \"$path\".\n" unless -e $path;
942 sub isInspectorFrontend()
944 determineIsInspectorFrontend();
945 return $isInspectorFrontend;
948 sub determineIsInspectorFrontend()
950 return if defined($isInspectorFrontend);
951 $isInspectorFrontend = checkForArgumentAndRemoveFromARGV("--inspector-frontend");
957 my $devnull = File::Spec->devnull();
959 if (isAnyWindows()) {
960 return exitStatus(system("where /q $command >$devnull 2>&1")) == 0;
962 return exitStatus(system("which $command >$devnull 2>&1")) == 0;
965 sub checkForArgumentAndRemoveFromARGV($)
967 my $argToCheck = shift;
968 return checkForArgumentAndRemoveFromArrayRef($argToCheck, \@ARGV);
971 sub checkForArgumentAndRemoveFromArrayRefGettingValue($$$)
973 my ($argToCheck, $valueRef, $arrayRef) = @_;
974 my $argumentStartRegEx = qr#^$argToCheck(?:=\S|$)#;
976 for (; $i < @$arrayRef; ++$i) {
977 last if $arrayRef->[$i] =~ $argumentStartRegEx;
979 if ($i >= @$arrayRef) {
980 return $$valueRef = undef;
982 my ($key, $value) = split("=", $arrayRef->[$i]);
983 splice(@$arrayRef, $i, 1);
984 if (defined($value)) {
985 # e.g. --sdk=iphonesimulator
986 return $$valueRef = $value;
988 return $$valueRef = splice(@$arrayRef, $i, 1); # e.g. --sdk iphonesimulator
991 sub checkForArgumentAndRemoveFromARGVGettingValue($$)
993 my ($argToCheck, $valueRef) = @_;
994 return checkForArgumentAndRemoveFromArrayRefGettingValue($argToCheck, $valueRef, \@ARGV);
997 sub findMatchingArguments($$)
999 my ($argToCheck, $arrayRef) = @_;
1000 my @matchingIndices;
1001 foreach my $index (0 .. $#$arrayRef) {
1002 my $opt = $$arrayRef[$index];
1003 if ($opt =~ /^$argToCheck$/i ) {
1004 push(@matchingIndices, $index);
1007 return @matchingIndices;
1012 my ($argToCheck, $arrayRef) = @_;
1013 my @matchingIndices = findMatchingArguments($argToCheck, $arrayRef);
1014 return scalar @matchingIndices > 0;
1017 sub checkForArgumentAndRemoveFromArrayRef
1019 my ($argToCheck, $arrayRef) = @_;
1020 my @indicesToRemove = findMatchingArguments($argToCheck, $arrayRef);
1021 my $removeOffset = 0;
1022 foreach my $index (@indicesToRemove) {
1023 splice(@$arrayRef, $index - $removeOffset++, 1);
1025 return scalar @indicesToRemove > 0;
1028 sub determineIsEfl()
1030 return if defined($isEfl);
1031 $isEfl = checkForArgumentAndRemoveFromARGV("--efl");
1040 sub determineIsGtk()
1042 return if defined($isGtk);
1043 $isGtk = checkForArgumentAndRemoveFromARGV("--gtk");
1052 # Determine if this is debian, ubuntu, linspire, or something similar.
1055 return -e "/etc/debian_version";
1060 return -e "/etc/fedora-release";
1065 determineIsWinCairo();
1069 sub determineIsWinCairo()
1071 return if defined($isWinCairo);
1072 $isWinCairo = checkForArgumentAndRemoveFromARGV("--wincairo");
1081 sub determineIsWin64()
1083 return if defined($isWin64);
1084 $isWin64 = checkForArgumentAndRemoveFromARGV("--64-bit");
1087 sub determineIsWin64FromArchitecture($)
1090 $isWin64 = ($arch eq "x86_64");
1096 return ($^O eq "cygwin") || 0;
1101 return isWindows() || isCygwin();
1104 sub determineWinVersion()
1106 return if $winVersion;
1108 if (!isAnyWindows()) {
1113 my $versionString = `cmd /c ver`;
1114 $versionString =~ /(\d)\.(\d)\.(\d+)/;
1125 determineWinVersion();
1131 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 1 && winVersion()->{build} == 7600;
1134 sub isWindowsVista()
1136 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 0;
1141 return isAnyWindows() && winVersion()->{major} == 5 && winVersion()->{minor} == 1;
1146 return ($^O eq "darwin") || 0;
1151 return ($^O eq "MSWin32") || 0;
1156 return ($^O eq "linux") || 0;
1161 return ($^O eq "freebsd") || ($^O eq "openbsd") || ($^O eq "netbsd") || 0;
1166 return ($Config{archname} =~ /^arm[v\-]/) || ($Config{archname} =~ /^aarch64[v\-]/);
1171 return (architecture() eq "x86_64") || 0;
1174 sub isCrossCompilation()
1177 $compiler = $ENV{'CC'} if (defined($ENV{'CC'}));
1178 if ($compiler =~ /gcc/) {
1179 my $compiler_options = `$compiler -v 2>&1`;
1180 my @host = $compiler_options =~ m/--host=(.*?)\s/;
1181 my @target = $compiler_options =~ m/--target=(.*?)\s/;
1183 return ($host[0] ne "" && $target[0] ne "" && $host[0] ne $target[0]);
1190 return isAppleMacWebKit() || isAppleWinWebKit();
1193 sub isAppleMacWebKit()
1195 return isDarwin() && !isGtk();
1198 sub isAppleWinWebKit()
1200 return (isCygwin() || isWindows()) && !isWinCairo() && !isGtk();
1203 sub iOSSimulatorDevicesPath
1205 return "$ENV{HOME}/Library/Developer/CoreSimulator/Devices";
1208 sub iOSSimulatorDevices
1210 eval "require Foundation";
1211 my $devicesPath = iOSSimulatorDevicesPath();
1212 opendir(DEVICES, $devicesPath);
1214 $_ =~ m/[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}/;
1218 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
1219 # dictionary keys so as to decouple our representation of the plist from the actual structure
1220 # of the plist, which may change.
1222 Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_("$devicesPath/$_/device.plist"));
1228 sub createiOSSimulatorDevice
1231 my $deviceTypeId = shift;
1232 my $runtimeId = shift;
1234 my $created = system("xcrun", "--sdk", "iphonesimulator", "simctl", "create", $name, $deviceTypeId, $runtimeId) == 0;
1235 die "Couldn't create simulator device: $name $deviceTypeId $runtimeId" if not $created;
1237 system("xcrun", "--sdk", "iphonesimulator", "simctl", "list");
1239 print "Waiting for device to be created ...\n";
1241 for (my $tries = 0; $tries < 5; $tries++){
1242 my @devices = iOSSimulatorDevices();
1243 foreach my $device (@devices) {
1244 return $device if $device->{name} eq $name and $device->{deviceType} eq $deviceTypeId and $device->{runtime} eq $runtimeId;
1248 die "Device $name $deviceTypeId $runtimeId wasn't found in " . iOSSimulatorDevicesPath();
1251 sub willUseIOSDeviceSDK()
1253 return xcodeSDKPlatformName() eq "iphoneos";
1256 sub willUseIOSSimulatorSDK()
1258 return xcodeSDKPlatformName() eq "iphonesimulator";
1263 determineXcodeSDK();
1264 return isAppleMacWebKit() && (willUseIOSDeviceSDK() || willUseIOSSimulatorSDK());
1267 sub determineNmPath()
1271 if (isAppleMacWebKit()) {
1272 $nmPath = `xcrun -find nm`;
1275 $nmPath = "nm" if !$nmPath;
1284 sub splitVersionString
1286 my $versionString = shift;
1287 my @splitVersion = split(/\./, $versionString);
1288 @splitVersion >= 2 or die "Invalid version $versionString";
1290 "major" => $splitVersion[0],
1291 "minor" => $splitVersion[1],
1292 "subminor" => (defined($splitVersion[2]) ? $splitVersion[2] : 0),
1296 sub determineOSXVersion()
1298 return if $osXVersion;
1305 my $versionString = `sw_vers -productVersion`;
1306 $osXVersion = splitVersionString($versionString);
1311 determineOSXVersion();
1315 sub determineIOSVersion()
1317 return if $iosVersion;
1319 if (!isIOSWebKit()) {
1324 my $versionString = xcodeSDKVersion();
1325 $iosVersion = splitVersionString($versionString);
1330 determineIOSVersion();
1336 return $ENV{'OS'} eq 'Windows_NT';
1339 sub shouldTargetWebProcess
1341 determineShouldTargetWebProcess();
1342 return $shouldTargetWebProcess;
1345 sub determineShouldTargetWebProcess
1347 return if defined($shouldTargetWebProcess);
1348 $shouldTargetWebProcess = checkForArgumentAndRemoveFromARGV("--target-web-process");
1351 sub shouldUseXPCServiceForWebProcess
1353 determineShouldUseXPCServiceForWebProcess();
1354 return $shouldUseXPCServiceForWebProcess;
1357 sub determineShouldUseXPCServiceForWebProcess
1359 return if defined($shouldUseXPCServiceForWebProcess);
1360 $shouldUseXPCServiceForWebProcess = checkForArgumentAndRemoveFromARGV("--use-web-process-xpc-service");
1365 determineDebugger();
1369 sub determineDebugger
1371 return if defined($debugger);
1373 determineXcodeVersion();
1374 if (eval "v$xcodeVersion" ge v4.5) {
1380 if (checkForArgumentAndRemoveFromARGV("--use-lldb")) {
1384 if (checkForArgumentAndRemoveFromARGV("--use-gdb")) {
1389 sub appendToEnvironmentVariableList($$)
1391 my ($name, $value) = @_;
1393 if (defined($ENV{$name})) {
1394 $ENV{$name} .= $Config{path_sep} . $value;
1396 $ENV{$name} = $value;
1400 sub prependToEnvironmentVariableList($$)
1402 my ($name, $value) = @_;
1404 if (defined($ENV{$name})) {
1405 $ENV{$name} = $value . $Config{path_sep} . $ENV{$name};
1407 $ENV{$name} = $value;
1411 sub sharedCommandLineOptions()
1414 "g|guard-malloc" => \$shouldUseGuardMalloc,
1418 sub sharedCommandLineOptionsUsage
1423 '-g|--guard-malloc' => 'Use guardmalloc when running executable',
1426 my $indent = " " x ($opts{indent} || 2);
1427 my $switchWidth = List::Util::max(int($opts{switchWidth}), List::Util::max(map { length($_) } keys %switches) + ($opts{brackets} ? 2 : 0));
1429 my $result = "Common switches:\n";
1431 for my $switch (keys %switches) {
1432 my $switchName = $opts{brackets} ? "[" . $switch . "]" : $switch;
1433 $result .= sprintf("%s%-" . $switchWidth . "s %s\n", $indent, $switchName, $switches{$switch});
1439 sub setUpGuardMallocIfNeeded
1445 if (!defined($shouldUseGuardMalloc)) {
1446 $shouldUseGuardMalloc = checkForArgumentAndRemoveFromARGV("-g") || checkForArgumentAndRemoveFromARGV("--guard-malloc");
1449 if ($shouldUseGuardMalloc) {
1450 appendToEnvironmentVariableList("DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1454 sub relativeScriptsDir()
1456 my $scriptDir = File::Spec->catpath("", File::Spec->abs2rel($FindBin::Bin, getcwd()), "");
1457 if ($scriptDir eq "") {
1465 my $relativeScriptsPath = relativeScriptsDir();
1466 if (isGtk() || isEfl()) {
1467 return "$relativeScriptsPath/run-minibrowser";
1468 } elsif (isAppleWebKit()) {
1469 return "$relativeScriptsPath/run-safari";
1475 if (isGtk() || isEfl()) {
1476 return "MiniBrowser";
1477 } elsif (isAppleMacWebKit()) {
1479 } elsif (isAppleWinWebKit()) {
1480 return "MiniBrowser";
1484 sub checkRequiredSystemConfig
1487 chomp(my $productVersion = `sw_vers -productVersion`);
1488 if (eval "v$productVersion" lt v10.7.5) {
1489 print "*************************************************************\n";
1490 print "Mac OS X Version 10.7.5 or later is required to build WebKit.\n";
1491 print "You have " . $productVersion . ", thus the build will most likely fail.\n";
1492 print "*************************************************************\n";
1494 my $xcodebuildVersionOutput = `xcodebuild -version`;
1495 my $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : undef;
1496 if (!$xcodeVersion || $xcodeVersion && eval "v$xcodeVersion" lt v4.6) {
1497 print "*************************************************************\n";
1498 print "Xcode Version 4.6 or later is required to build WebKit.\n";
1499 print "You have an earlier version of Xcode, thus the build will\n";
1500 print "most likely fail. The latest Xcode is available from the App Store.\n";
1501 print "*************************************************************\n";
1503 } elsif (isGtk() or isEfl() or isWindows() or isCygwin()) {
1504 my @cmds = qw(bison gperf flex);
1506 my $oldPath = $ENV{PATH};
1507 foreach my $cmd (@cmds) {
1508 push @missing, $cmd if not commandExists($cmd);
1512 my $list = join ", ", @missing;
1513 die "ERROR: $list missing but required to build WebKit.\n";
1516 # Win32 and other platforms may want to check for minimum config
1519 sub determineWindowsSourceDir()
1521 return if $windowsSourceDir;
1522 $windowsSourceDir = sourceDir();
1523 chomp($windowsSourceDir = `cygpath -w '$windowsSourceDir'`) if isCygwin();
1526 sub windowsSourceDir()
1528 determineWindowsSourceDir();
1529 return $windowsSourceDir;
1532 sub windowsSourceSourceDir()
1534 return File::Spec->catdir(windowsSourceDir(), "Source");
1537 sub windowsLibrariesDir()
1539 return File::Spec->catdir(windowsSourceDir(), "WebKitLibraries", "win");
1542 sub windowsOutputDir()
1544 return File::Spec->catdir(windowsSourceDir(), "WebKitBuild");
1550 my $cmd = "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\\" . $font ."\" 2>&1";
1555 sub checkInstalledTools()
1557 # environment variables. Avoid until this is corrected.
1558 my $pythonVer = `python --version 2>&1`;
1559 die "You must have Python installed to build WebKit.\n" if ($?);
1561 # cURL 7.34.0 has a bug that prevents authentication with opensource.apple.com (and other things using SSL3).
1562 my $curlVer = `curl --version 2> NUL`;
1563 if (!$? and $curlVer =~ "(.*curl.*)") {
1565 if ($curlVer =~ /libcurl\/7\.34\.0/) {
1566 print "cURL version 7.34.0 has a bug that prevents authentication with SSL v2 or v3.\n";
1567 print "cURL 7.33.0 is known to work. The cURL projects is preparing an update to\n";
1568 print "correct this problem.\n\n";
1569 die "Please install a working cURL and try again.\n";
1573 # MathML requires fonts that do not ship with Windows (at least through Windows 8). Warn the user if they are missing
1574 my @fonts = qw(STIXGeneral-Regular MathJax_Main-Regular);
1576 foreach my $font (@fonts) {
1577 push @missing, $font if not fontExists($font);
1580 if (scalar @missing > 0) {
1581 print "*************************************************************\n";
1582 print "Mathematical fonts, such as STIX and MathJax, are needed to\n";
1583 print "use the MathML feature. You do not appear to have these fonts\n";
1584 print "on your system.\n\n";
1585 print "You can download a suitable set of fonts from the following URL:\n";
1586 print "https://developer.mozilla.org/Mozilla/MathML_Projects/Fonts\n";
1587 print "*************************************************************\n";
1590 print "Installed tools are correct for the WebKit build.\n";
1593 sub setupAppleWinEnv()
1595 return unless isAppleWinWebKit();
1597 checkInstalledTools();
1599 if (isWindowsNT()) {
1600 my $restartNeeded = 0;
1601 my %variablesToSet = ();
1603 # FIXME: We should remove this explicit version check for cygwin once we stop supporting Cygwin 1.7.9 or older versions.
1604 # https://bugs.webkit.org/show_bug.cgi?id=85791
1605 my $uname_version = (POSIX::uname())[2];
1606 $uname_version =~ s/\(.*\)//; # Remove the trailing cygwin version, if any.
1607 $uname_version =~ s/\-.*$//; # Remove trailing dash-version content, if any
1608 if (version->parse($uname_version) < version->parse("1.7.10")) {
1609 # Setting the environment variable 'CYGWIN' to 'tty' makes cygwin enable extra support (i.e., termios)
1610 # for UNIX-like ttys in the Windows console
1611 $variablesToSet{CYGWIN} = "tty" unless $ENV{CYGWIN};
1614 # Those environment variables must be set to be able to build inside Visual Studio.
1615 $variablesToSet{WEBKIT_LIBRARIES} = windowsLibrariesDir() unless $ENV{WEBKIT_LIBRARIES};
1616 $variablesToSet{WEBKIT_OUTPUTDIR} = windowsOutputDir() unless $ENV{WEBKIT_OUTPUTDIR};
1617 $variablesToSet{MSBUILDDISABLENODEREUSE} = "1" unless $ENV{MSBUILDDISABLENODEREUSE};
1618 $variablesToSet{_IsNativeEnvironment} = "true" unless $ENV{_IsNativeEnvironment};
1619 $variablesToSet{PreferredToolArchitecture} = "x64" unless $ENV{PreferredToolArchitecture};
1621 foreach my $variable (keys %variablesToSet) {
1622 print "Setting the Environment Variable '" . $variable . "' to '" . $variablesToSet{$variable} . "'\n\n";
1623 my $ret = system "setx", $variable, $variablesToSet{$variable};
1625 system qw(regtool -s set), '\\HKEY_CURRENT_USER\\Environment\\' . $variable, $variablesToSet{$variable};
1627 $restartNeeded ||= $variable eq "WEBKIT_LIBRARIES" || $variable eq "WEBKIT_OUTPUTDIR";
1630 if ($restartNeeded) {
1631 print "Please restart your computer before attempting to build inside Visual Studio.\n\n";
1634 if (!defined $ENV{'WEBKIT_LIBRARIES'} || !$ENV{'WEBKIT_LIBRARIES'}) {
1635 print "Warning: You must set the 'WebKit_Libraries' environment variable\n";
1636 print " to be able build WebKit from within Visual Studio 2013 and newer.\n";
1637 print " Make sure that 'WebKit_Libraries' points to the\n";
1638 print " 'WebKitLibraries/win' directory, not the 'WebKitLibraries/' directory.\n\n";
1640 if (!defined $ENV{'WEBKIT_OUTPUTDIR'} || !$ENV{'WEBKIT_OUTPUTDIR'}) {
1641 print "Warning: You must set the 'WebKit_OutputDir' environment variable\n";
1642 print " to be able build WebKit from within Visual Studio 2013 and newer.\n\n";
1644 if (!defined $ENV{'MSBUILDDISABLENODEREUSE'} || !$ENV{'MSBUILDDISABLENODEREUSE'}) {
1645 print "Warning: You should set the 'MSBUILDDISABLENODEREUSE' environment variable to '1'\n";
1646 print " to avoid periodic locked log files when building.\n\n";
1649 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1650 if (isWin64() and !$ENV{'WEBKIT_64_SUPPORT'}) {
1651 print "Warning: You must set the 'WEBKIT_64_SUPPORT' environment variable\n";
1652 print " to be able run WebKit or JavaScriptCore tests.\n\n";
1656 sub setupCygwinEnv()
1658 return if !isCygwin() && !isWindows();
1659 return if $vcBuildPath;
1661 my $programFilesPath = programFilesPath();
1662 my $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE devenv.com));
1663 if (-e $visualStudioPath) {
1664 # Visual Studio is installed;
1665 if (visualStudioVersion() eq "12") {
1666 $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE devenv.exe));
1669 # Visual Studio not found, try VC++ Express
1670 $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE WDExpress.exe));
1671 if (! -e $visualStudioPath) {
1672 print "*************************************************************\n";
1673 print "Cannot find '$visualStudioPath'\n";
1674 print "Please execute the file 'vcvars32.bat' from\n";
1675 print "'$programFilesPath\\Microsoft Visual Studio 14.0\\VC\\bin\\'\n";
1676 print "to setup the necessary environment variables.\n";
1677 print "*************************************************************\n";
1680 $willUseVCExpressWhenBuilding = 1;
1683 print "Building results into: ", baseProductDir(), "\n";
1684 print "WEBKIT_OUTPUTDIR is set to: ", $ENV{"WEBKIT_OUTPUTDIR"}, "\n";
1685 print "WEBKIT_LIBRARIES is set to: ", $ENV{"WEBKIT_LIBRARIES"}, "\n";
1686 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1687 print "WEBKIT_64_SUPPORT is set to: ", $ENV{"WEBKIT_64_SUPPORT"}, "\n" if isWin64();
1689 # We will actually use MSBuild to build WebKit, but we need to find the Visual Studio install (above) to make
1690 # sure we use the right options.
1691 $vcBuildPath = File::Spec->catfile(msBuildInstallDir(), qw(MSBuild.exe));
1692 if (! -e $vcBuildPath) {
1693 print "*************************************************************\n";
1694 print "Cannot find '$vcBuildPath'\n";
1695 print "Please make sure execute that the Microsoft .NET Framework SDK\n";
1696 print "is installed on this machine.\n";
1697 print "*************************************************************\n";
1702 sub dieIfWindowsPlatformSDKNotInstalled
1704 my $registry32Path = "/proc/registry/";
1705 my $registry64Path = "/proc/registry64/";
1706 my @windowsPlatformSDKRegistryEntries = (
1707 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0A",
1708 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0",
1709 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.1A",
1710 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.0A",
1711 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/MicrosoftSDK/InstalledSDKs/D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1",
1714 # FIXME: It would be better to detect whether we are using 32- or 64-bit Windows
1715 # and only check the appropriate entry. But for now we just blindly check both.
1716 my $recommendedPlatformSDK = $windowsPlatformSDKRegistryEntries[0];
1718 while (@windowsPlatformSDKRegistryEntries) {
1719 my $windowsPlatformSDKRegistryEntry = shift @windowsPlatformSDKRegistryEntries;
1720 return if (-e $registry32Path . $windowsPlatformSDKRegistryEntry) || (-e $registry64Path . $windowsPlatformSDKRegistryEntry);
1723 print "*************************************************************\n";
1724 print "Cannot find registry entry '$recommendedPlatformSDK'.\n";
1725 print "Please download and install the Microsoft Windows SDK\n";
1726 print "from <http://www.microsoft.com/en-us/download/details.aspx?id=8279>.\n\n";
1727 print "Then follow step 2 in the Windows section of the \"Installing Developer\n";
1728 print "Tools\" instructions at <http://www.webkit.org/building/tools.html>.\n";
1729 print "*************************************************************\n";
1733 sub buildXCodeProject($$@)
1735 my ($project, $clean, @extraOptions) = @_;
1738 push(@extraOptions, "-alltargets");
1739 push(@extraOptions, "clean");
1742 push(@extraOptions, ("-sdk", xcodeSDK())) if isIOSWebKit();
1744 chomp($ENV{DSYMUTIL_NUM_THREADS} = `sysctl -n hw.activecpu`);
1745 return system "xcodebuild", "-project", "$project.xcodeproj", @extraOptions;
1748 sub usingVisualStudioExpress()
1751 return $willUseVCExpressWhenBuilding;
1754 sub buildVisualStudioProject
1756 my ($project, $clean) = @_;
1759 my $config = configurationForVisualStudio();
1761 dieIfWindowsPlatformSDKNotInstalled() if $willUseVCExpressWhenBuilding;
1763 chomp($project = `cygpath -w "$project"`) if isCygwin();
1765 my $action = "/t:build";
1767 $action = "/t:clean";
1770 my $platform = "/p:Platform=" . (isWin64() ? "x64" : "Win32");
1771 my $logPath = File::Spec->catdir($baseProductDir, $configuration);
1772 make_path($logPath) unless -d $logPath or $logPath eq ".";
1774 my $errorLogFile = File::Spec->catfile($logPath, "webkit_errors.log");
1775 chomp($errorLogFile = `cygpath -w "$errorLogFile"`) if isCygwin();
1776 my $errorLogging = "/flp:LogFile=" . $errorLogFile . ";ErrorsOnly";
1778 my $warningLogFile = File::Spec->catfile($logPath, "webkit_warnings.log");
1779 chomp($warningLogFile = `cygpath -w "$warningLogFile"`) if isCygwin();
1780 my $warningLogging = "/flp1:LogFile=" . $warningLogFile . ";WarningsOnly";
1782 my @command = ($vcBuildPath, "/verbosity:minimal", $project, $action, $config, $platform, "/fl", $errorLogging, "/fl1", $warningLogging);
1783 print join(" ", @command), "\n";
1784 return system @command;
1787 sub getJhbuildPath()
1789 my @jhbuildPath = File::Spec->splitdir(baseProductDir());
1790 if (isGit() && isGitBranchBuild() && gitBranch()) {
1794 push(@jhbuildPath, "DependenciesEFL");
1796 push(@jhbuildPath, "DependenciesGTK");
1798 die "Cannot get JHBuild path for platform that isn't GTK+ or EFL.\n";
1800 return File::Spec->catdir(@jhbuildPath);
1803 sub isCachedArgumentfileOutOfDate($@)
1805 my ($filename, $currentContents) = @_;
1807 if (! -e $filename) {
1811 open(CONTENTS_FILE, $filename);
1812 chomp(my $previousContents = <CONTENTS_FILE>);
1813 close(CONTENTS_FILE);
1815 if ($previousContents ne $currentContents) {
1816 print "Contents for file $filename have changed.\n";
1817 print "Previous contents were: $previousContents\n\n";
1818 print "New contents are: $currentContents\n";
1825 sub wrapperPrefixIfNeeded()
1827 if (isWindows() || isCygwin()) {
1830 if (isAppleMacWebKit()) {
1833 if (-e getJhbuildPath()) {
1834 my @prefix = (File::Spec->catfile(sourceDir(), "Tools", "jhbuild", "jhbuild-wrapper"));
1836 push(@prefix, "--efl");
1838 push(@prefix, "--gtk");
1840 push(@prefix, "run");
1848 sub cmakeCachePath()
1850 return File::Spec->catdir(baseProductDir(), configuration(), "CMakeCache.txt");
1853 sub shouldRemoveCMakeCache(@)
1855 my ($cacheFilePath, @buildArgs) = @_;
1857 # We check this first, because we always want to create this file for a fresh build.
1858 my $productDir = File::Spec->catdir(baseProductDir(), configuration());
1859 my $optionsCache = File::Spec->catdir($productDir, "build-webkit-options.txt");
1860 my $joinedBuildArgs = join(" ", @buildArgs);
1861 if (isCachedArgumentfileOutOfDate($optionsCache, $joinedBuildArgs)) {
1862 File::Path::mkpath($productDir) unless -d $productDir;
1863 open(CACHED_ARGUMENTS, ">", $optionsCache);
1864 print CACHED_ARGUMENTS $joinedBuildArgs;
1865 close(CACHED_ARGUMENTS);
1870 my $cmakeCache = cmakeCachePath();
1871 unless (-e $cmakeCache) {
1875 my $cacheFileModifiedTime = stat($cmakeCache)->mtime;
1876 my $platformConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "Options" . cmakeBasedPortName() . ".cmake");
1877 if ($cacheFileModifiedTime < stat($platformConfiguration)->mtime) {
1881 my $globalConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "OptionsCommon.cmake");
1882 if ($cacheFileModifiedTime < stat($globalConfiguration)->mtime) {
1886 my $inspectorUserInterfaceDircetory = File::Spec->catdir(sourceDir(), "Source", "WebInspectorUI", "UserInterface");
1887 if ($cacheFileModifiedTime < stat($inspectorUserInterfaceDircetory)->mtime) {
1894 sub removeCMakeCache(@)
1896 my (@buildArgs) = @_;
1897 if (shouldRemoveCMakeCache(@buildArgs)) {
1898 my $cmakeCache = cmakeCachePath();
1899 unlink($cmakeCache) if -e $cmakeCache;
1905 if (!defined($shouldNotUseNinja)) {
1906 $shouldNotUseNinja = checkForArgumentAndRemoveFromARGV("--no-ninja");
1909 if ($shouldNotUseNinja) {
1913 # Test both ninja and ninja-build. Fedora uses ninja-build and has patched CMake to also call ninja-build.
1914 return commandExists("ninja") || commandExists("ninja-build");
1917 sub canUseNinjaGenerator(@)
1919 # Check that a Ninja generator is installed
1920 my $devnull = File::Spec->devnull();
1921 return exitStatus(system("cmake -N -G Ninja >$devnull 2>&1")) == 0;
1924 sub canUseEclipseNinjaGenerator(@)
1926 # Check that eclipse and eclipse Ninja generator is installed
1927 my $devnull = File::Spec->devnull();
1928 return commandExists("eclipse") && exitStatus(system("cmake -N -G 'Eclipse CDT4 - Ninja' >$devnull 2>&1")) == 0;
1931 sub cmakeGeneratedBuildfile(@)
1933 my ($willUseNinja) = @_;
1934 if ($willUseNinja) {
1935 return File::Spec->catfile(baseProductDir(), configuration(), "build.ninja")
1936 } elsif (isWindows() || isCygwin()) {
1937 return File::Spec->catfile(baseProductDir(), configuration(), "WebKit.sln")
1939 return File::Spec->catfile(baseProductDir(), configuration(), "Makefile")
1943 sub generateBuildSystemFromCMakeProject
1945 my ($port, $prefixPath, @cmakeArgs, $additionalCMakeArgs) = @_;
1946 my $config = configuration();
1947 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
1948 File::Path::mkpath($buildPath) unless -d $buildPath;
1949 my $originalWorkingDirectory = getcwd();
1950 chdir($buildPath) or die;
1952 # We try to be smart about when to rerun cmake, so that we can have faster incremental builds.
1953 my $willUseNinja = canUseNinja() && canUseNinjaGenerator();
1954 if (-e cmakeCachePath() && -e cmakeGeneratedBuildfile($willUseNinja)) {
1959 push @args, "-DPORT=\"$port\"";
1960 push @args, "-DCMAKE_INSTALL_PREFIX=\"$prefixPath\"" if $prefixPath;
1961 push @args, "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON" if isGtk();
1962 if ($config =~ /release/i) {
1963 push @args, "-DCMAKE_BUILD_TYPE=Release";
1964 } elsif ($config =~ /debug/i) {
1965 push @args, "-DCMAKE_BUILD_TYPE=Debug";
1968 if ($willUseNinja) {
1970 if (canUseEclipseNinjaGenerator()) {
1971 push @args, "'Eclipse CDT4 - Ninja'";
1973 push @args, "Ninja";
1975 } elsif (isAnyWindows() && isWin64()) {
1976 push @args, '-G "Visual Studio 14 2015 Win64"';
1979 # GTK+ has a production mode, but build-webkit should always use developer mode.
1980 push @args, "-DDEVELOPER_MODE=ON" if isEfl() || isGtk();
1982 # Don't warn variables which aren't used by cmake ports.
1983 push @args, "--no-warn-unused-cli";
1984 push @args, @cmakeArgs if @cmakeArgs;
1985 push @args, $additionalCMakeArgs if $additionalCMakeArgs;
1987 my $cmakeSourceDir = isCygwin() ? windowsSourceDir() : sourceDir();
1988 push @args, '"' . $cmakeSourceDir . '"';
1990 # Compiler options to keep floating point values consistent
1991 # between 32-bit and 64-bit architectures.
1992 determineArchitecture();
1993 if ($architecture ne "x86_64" && !isARM() && !isCrossCompilation() && !isWindows() && !isCygwin()) {
1994 $ENV{'CXXFLAGS'} = "-march=pentium4 -msse2 -mfpmath=sse " . ($ENV{'CXXFLAGS'} || "");
1997 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
1998 # parsed for shell metacharacters.
1999 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2000 my $returnCode = system($wrapper . "cmake @args");
2002 chdir($originalWorkingDirectory);
2006 sub buildCMakeGeneratedProject($)
2008 my ($makeArgs) = @_;
2009 my $config = configuration();
2010 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2011 if (! -d $buildPath) {
2012 die "Must call generateBuildSystemFromCMakeProject() before building CMake project.";
2015 my $command = "cmake";
2016 my @args = ("--build", $buildPath, "--config", $config);
2017 push @args, ("--", $makeArgs) if $makeArgs;
2019 # GTK can use a build script to preserve colors and pretty-printing.
2020 if (isGtk() && -e "$buildPath/build.sh") {
2021 chdir "$buildPath" or die;
2022 $command = "$buildPath/build.sh";
2023 @args = ($makeArgs);
2026 if ($ENV{VERBOSE} && canUseNinja()) {
2028 push @args, "-d keeprsp" if (version->parse(determineNinjaVersion()) >= version->parse("1.4.0"));
2031 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2032 # parsed for shell metacharacters. In particular, $makeArgs may contain such metacharacters.
2033 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2034 return system($wrapper . "$command @args");
2037 sub cleanCMakeGeneratedProject()
2039 my $config = configuration();
2040 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2041 if (-d $buildPath) {
2042 return system("cmake", "--build", $buildPath, "--config", $config, "--target", "clean");
2047 sub buildCMakeProjectOrExit($$$$@)
2049 my ($clean, $port, $prefixPath, $makeArgs, @cmakeArgs) = @_;
2052 exit(exitStatus(cleanCMakeGeneratedProject())) if $clean;
2054 if (isEfl() && checkForArgumentAndRemoveFromARGV("--update-efl")) {
2055 system("perl", "$sourceDir/Tools/Scripts/update-webkitefl-libs") == 0 or die $!;
2058 if (isGtk() && checkForArgumentAndRemoveFromARGV("--update-gtk")) {
2059 system("perl", "$sourceDir/Tools/Scripts/update-webkitgtk-libs") == 0 or die $!;
2062 $returnCode = exitStatus(generateBuildSystemFromCMakeProject($port, $prefixPath, @cmakeArgs));
2063 exit($returnCode) if $returnCode;
2065 $returnCode = exitStatus(buildCMakeGeneratedProject($makeArgs));
2066 exit($returnCode) if $returnCode;
2070 sub cmakeBasedPortArguments()
2075 sub cmakeBasedPortName()
2077 return "Efl" if isEfl();
2078 return "GTK" if isGtk();
2079 return "Mac" if isAppleMacWebKit();
2080 return "WinCairo" if isWinCairo();
2081 return "AppleWin" if isAppleWinWebKit();
2085 sub determineIsCMakeBuild()
2087 return if defined($isCMakeBuild);
2088 $isCMakeBuild = checkForArgumentAndRemoveFromARGV("--cmake");
2093 if (isEfl() || isGtk() || isAnyWindows()) {
2096 determineIsCMakeBuild();
2097 return $isCMakeBuild;
2102 my ($prompt, $default) = @_;
2103 my $defaultValue = $default ? "[$default]" : "";
2104 print "$prompt $defaultValue: ";
2105 chomp(my $input = <STDIN>);
2106 return $input ? $input : $default;
2109 sub appleApplicationSupportPath
2111 open INSTALL_DIR, "</proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/Apple\ Inc./Apple\ Application\ Support/InstallDir";
2112 my $path = <INSTALL_DIR>;
2113 $path =~ s/[\r\n\x00].*//;
2116 my $unixPath = `cygpath -u '$path'`;
2121 sub setPathForRunningWebKitApp
2125 if (isAnyWindows()) {
2126 my $productBinaryDir = executableProductDir();
2127 if (isAppleWinWebKit()) {
2128 $env->{PATH} = join(':', $productBinaryDir, appleApplicationSupportPath(), $env->{PATH} || "");
2129 } elsif (isWinCairo()) {
2130 my $winCairoBin = sourceDir() . "/WebKitLibraries/win/" . (isWin64() ? "bin64/" : "bin32/");
2131 my $gstreamerBin = isWin64() ? $ENV{"GSTREAMER_1_0_ROOT_X86_64"} . "bin" : $ENV{"GSTREAMER_1_0_ROOT_X86"} . "bin";
2132 $env->{PATH} = join(':', $productBinaryDir, $winCairoBin, $gstreamerBin, $env->{PATH} || "");
2137 sub printHelpAndExitForRunAndDebugWebKitAppIfNeeded
2139 return unless checkForArgumentAndRemoveFromARGV("--help");
2141 my ($includeOptionsForDebugging) = @_;
2144 Usage: @{[basename($0)]} [options] [args ...]
2145 --help Show this help message
2146 --no-saved-state Launch the application without state restoration (OS X 10.7 and later)
2147 -g|--guard-malloc Enable Guard Malloc (OS X only)
2148 --use-web-process-xpc-service Launch the Web Process as an XPC Service (OS X only)
2151 if ($includeOptionsForDebugging) {
2153 --target-web-process Debug the web process
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 push @args, ("-WebKit2UseXPCServiceForWebProcess", "YES") if shouldUseXPCServiceForWebProcess();
2171 unshift @args, @ARGV;
2176 sub setupMacWebKitEnvironment($)
2178 my ($dyldFrameworkPath) = @_;
2180 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2182 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2183 prependToEnvironmentVariableList("__XPC_DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2184 $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2186 setUpGuardMallocIfNeeded();
2189 sub setupIOSWebKitEnvironment($)
2191 my ($dyldFrameworkPath) = @_;
2192 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2194 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2195 prependToEnvironmentVariableList("DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2197 setUpGuardMallocIfNeeded();
2200 sub iosSimulatorApplicationsPath()
2202 return File::Spec->catdir(XcodeSDKPath(), "Applications");
2205 sub installedMobileSafariBundle()
2207 return File::Spec->catfile(iosSimulatorApplicationsPath(), "MobileSafari.app");
2210 sub mobileSafariBundle()
2212 determineConfigurationProductDir();
2214 # Use MobileSafari.app in product directory if present.
2215 if (isAppleMacWebKit() && -d "$configurationProductDir/MobileSafari.app") {
2216 return "$configurationProductDir/MobileSafari.app";
2218 return installedMobileSafariBundle();
2221 sub plistPathFromBundle($)
2223 my ($appBundle) = @_;
2224 return "$appBundle/Info.plist" if -f "$appBundle/Info.plist"; # iOS app bundle
2225 return "$appBundle/Contents/Info.plist" if -f "$appBundle/Contents/Info.plist"; # Mac app bundle
2229 sub appIdentifierFromBundle($)
2231 my ($appBundle) = @_;
2232 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2233 chomp(my $bundleIdentifier = `defaults read '$plistPath' CFBundleIdentifier 2> /dev/null`);
2234 return $bundleIdentifier;
2237 sub appDisplayNameFromBundle($)
2239 my ($appBundle) = @_;
2240 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2241 chomp(my $bundleDisplayName = `defaults read '$plistPath' CFBundleDisplayName 2> /dev/null`);
2242 return $bundleDisplayName;
2245 sub waitUntilIOSSimulatorDeviceIsInState($$)
2247 my ($deviceUDID, $waitUntilState) = @_;
2248 my $device = iosSimulatorDeviceByUDID($deviceUDID);
2249 while ($device->{state} ne $waitUntilState) {
2250 usleep(500 * 1000); # Waiting 500ms between file system polls does not make script run-safari feel sluggish.
2251 $device = iosSimulatorDeviceByUDID($deviceUDID);
2255 sub shutDownIOSSimulatorDevice($)
2257 my ($simulatorDevice) = @_;
2258 system("xcrun --sdk iphonesimulator simctl shutdown $simulatorDevice->{UDID} > /dev/null 2>&1");
2261 sub restartIOSSimulatorDevice($)
2263 my ($simulatorDevice) = @_;
2264 shutDownIOSSimulatorDevice($simulatorDevice);
2266 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "boot", $simulatorDevice->{UDID})) == 0 or die "Failed to boot simulator device $simulatorDevice->{UDID}";
2269 sub relaunchIOSSimulator($)
2271 my ($simulatedDevice) = @_;
2272 quitIOSSimulator($simulatedDevice->{UDID});
2274 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2275 my $iosSimulatorBundleID = "com.apple.iphonesimulator";
2276 system("open", "-b", $iosSimulatorBundleID, "--args", "-CurrentDeviceUDID", $simulatedDevice->{UDID}) == 0 or die "Failed to open $iosSimulatorBundleID: $!";
2278 waitUntilIOSSimulatorDeviceIsInState($simulatedDevice->{UDID}, SIMULATOR_DEVICE_STATE_BOOTED);
2281 sub quitIOSSimulator(;$)
2283 my ($waitForShutdownOfSimulatedDeviceUDID) = @_;
2284 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2285 exitStatus(system {"osascript"} "osascript", "-e", 'tell application id "com.apple.iphonesimulator" to quit') == 0 or die "Failed to quit iOS Simulator: $!";
2286 if (!defined($waitForShutdownOfSimulatedDeviceUDID)) {
2289 # FIXME: We assume that $waitForShutdownOfSimulatedDeviceUDID was not booted using the simctl command line tool.
2290 # Otherwise we will spin indefinitely since quiting the iOS Simulator will not shutdown this device. We
2291 # should add a maximum time limit to wait for a device to shutdown and either return an error or die()
2292 # on expiration of the time limit.
2293 waitUntilIOSSimulatorDeviceIsInState($waitForShutdownOfSimulatedDeviceUDID, SIMULATOR_DEVICE_STATE_SHUTDOWN);
2296 sub iosSimulatorDeviceByName($)
2298 my ($simulatorName) = @_;
2299 my $simulatorRuntime = iosSimulatorRuntime();
2300 my @devices = iOSSimulatorDevices();
2301 for my $device (@devices) {
2302 if ($device->{name} eq $simulatorName && $device->{runtime} eq $simulatorRuntime) {
2309 sub iosSimulatorDeviceByUDID($)
2311 my ($simulatedDeviceUDID) = @_;
2312 my $devicePlistPath = File::Spec->catfile(iOSSimulatorDevicesPath(), $simulatedDeviceUDID, "device.plist");
2313 if (!-f $devicePlistPath) {
2316 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
2317 # dictionary keys so as to decouple our representation of the plist from the actual structure
2318 # of the plist, which may change.
2319 eval "require Foundation";
2320 return Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_($devicePlistPath));
2323 sub iosSimulatorRuntime()
2325 my $xcodeSDKVersion = xcodeSDKVersion();
2326 $xcodeSDKVersion =~ s/\./-/;
2327 return "com.apple.CoreSimulator.SimRuntime.iOS-$xcodeSDKVersion";
2330 sub findOrCreateSimulatorForIOSDevice($)
2332 my ($simulatorNameSuffix) = @_;
2334 my $simulatorDeviceType;
2335 if (architecture() eq "x86_64") {
2336 $simulatorName = "iPhone 5s " . $simulatorNameSuffix;
2337 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5s";
2339 $simulatorName = "iPhone 5 " . $simulatorNameSuffix;
2340 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5";
2342 my $simulatedDevice = iosSimulatorDeviceByName($simulatorName);
2343 return $simulatedDevice if $simulatedDevice;
2344 return createiOSSimulatorDevice($simulatorName, $simulatorDeviceType, iosSimulatorRuntime());
2347 sub isIOSSimulatorSystemInstalledApp($)
2349 my ($appBundle) = @_;
2350 my $simulatorApplicationsPath = realpath(iosSimulatorApplicationsPath());
2351 return substr(realpath($appBundle), 0, length($simulatorApplicationsPath)) eq $simulatorApplicationsPath;
2354 sub hasUserInstalledAppInSimulatorDevice($$)
2356 my ($appIdentifier, $simulatedDeviceUDID) = @_;
2357 my $userInstalledAppPath = File::Spec->catfile($ENV{HOME}, "Library", "Developer", "CoreSimulator", "Devices", $simulatedDeviceUDID, "data", "Containers", "Bundle", "Application");
2358 if (!-d $userInstalledAppPath) {
2359 return 0; # No user installed apps.
2361 local @::userInstalledAppBundles;
2362 my $wantedFunction = sub {
2365 # Ignore hidden files and directories.
2366 if ($file =~ /^\../) {
2367 $File::Find::prune = 1;
2371 return if !-d $file || $file !~ /\.app$/;
2372 push @::userInstalledAppBundles, $File::Find::name;
2373 $File::Find::prune = 1; # Do not traverse contents of app bundle.
2375 find($wantedFunction, $userInstalledAppPath);
2376 for my $userInstalledAppBundle (@::userInstalledAppBundles) {
2377 if (appIdentifierFromBundle($userInstalledAppBundle) eq $appIdentifier) {
2378 return 1; # Has user installed app.
2381 return 0; # Does not have user installed app.
2384 sub isSimulatorDeviceBooted($)
2386 my ($simulatedDeviceUDID) = @_;
2387 my $device = iosSimulatorDeviceByUDID($simulatedDeviceUDID);
2388 return $device && $device->{state} eq SIMULATOR_DEVICE_STATE_BOOTED;
2391 sub runIOSWebKitAppInSimulator($;$)
2393 my ($appBundle, $simulatorOptions) = @_;
2394 my $productDir = productDir();
2395 my $appDisplayName = appDisplayNameFromBundle($appBundle);
2396 my $appIdentifier = appIdentifierFromBundle($appBundle);
2397 my $simulatedDevice = findOrCreateSimulatorForIOSDevice(SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT);
2398 my $simulatedDeviceUDID = $simulatedDevice->{UDID};
2400 my $willUseSystemInstalledApp = isIOSSimulatorSystemInstalledApp($appBundle);
2401 if ($willUseSystemInstalledApp) {
2402 if (hasUserInstalledAppInSimulatorDevice($appIdentifier, $simulatedDeviceUDID)) {
2403 # Restore the system-installed app in the simulator device corresponding to $appBundle as it
2404 # was previously overwritten with a custom built version of the app.
2405 # FIXME: Only restore the system-installed version of the app instead of erasing all contents and settings.
2406 print "Quitting iOS Simulator...\n";
2407 quitIOSSimulator($simulatedDeviceUDID);
2408 print "Erasing contents and settings for simulator device \"$simulatedDevice->{name}\".\n";
2409 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "erase", $simulatedDeviceUDID)) == 0 or die;
2411 # FIXME: We assume that if $simulatedDeviceUDID is not booted then iOS Simulator is not open. However
2412 # $simulatedDeviceUDID may have been booted using the simctl command line tool. If $simulatedDeviceUDID
2413 # was booted using simctl then we should shutdown the device and launch iOS Simulator to boot it again.
2414 if (!isSimulatorDeviceBooted($simulatedDeviceUDID)) {
2415 print "Launching iOS Simulator...\n";
2416 relaunchIOSSimulator($simulatedDevice);
2419 # FIXME: We should killall(1) any running instances of $appBundle before installing it to ensure
2420 # that simctl launch opens the latest installed version of the app. For now we quit and
2421 # launch the iOS Simulator again to ensure there are no running instances of $appBundle.
2422 print "Quitting and launching iOS Simulator...\n";
2423 relaunchIOSSimulator($simulatedDevice);
2425 print "Installing $appBundle.\n";
2426 # Install custom built app, overwriting an app with the same app identifier if one exists.
2427 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "install", $simulatedDeviceUDID, $appBundle)) == 0 or die;
2431 $simulatorOptions = {} unless $simulatorOptions;
2434 %simulatorENV = %{$simulatorOptions->{applicationEnvironment}} if $simulatorOptions->{applicationEnvironment};
2436 local %ENV; # Shadow global-scope %ENV so that changes to it will not be seen outside of this scope.
2437 setupIOSWebKitEnvironment($productDir);
2438 %simulatorENV = %ENV;
2440 my $applicationArguments = \@ARGV;
2441 $applicationArguments = $simulatorOptions->{applicationArguments} if $simulatorOptions && $simulatorOptions->{applicationArguments};
2443 # Prefix the environment variables with SIMCTL_CHILD_ per `xcrun simctl help launch`.
2444 foreach my $key (keys %simulatorENV) {
2445 $ENV{"SIMCTL_CHILD_$key"} = $simulatorENV{$key};
2448 print "Starting $appDisplayName with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2449 return exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "launch", $simulatedDeviceUDID, $appIdentifier, @$applicationArguments));
2452 sub runIOSWebKitApp($)
2454 my ($appBundle) = @_;
2455 if (willUseIOSDeviceSDK()) {
2456 die "Only running Safari in iOS Simulator is supported now.";
2458 if (willUseIOSSimulatorSDK()) {
2459 return runIOSWebKitAppInSimulator($appBundle);
2461 die "Not using an iOS SDK."
2464 sub runMacWebKitApp($;$)
2466 my ($appPath, $useOpenCommand) = @_;
2467 my $productDir = productDir();
2468 print "Starting @{[basename($appPath)]} with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2471 setupMacWebKitEnvironment($productDir);
2473 if (defined($useOpenCommand) && $useOpenCommand == USE_OPEN_COMMAND) {
2474 return system("open", "-W", "-a", $appPath, "--args", argumentsForRunAndDebugMacWebKitApp());
2476 if (architecture()) {
2477 return system "arch", "-" . architecture(), $appPath, argumentsForRunAndDebugMacWebKitApp();
2479 return system { $appPath } $appPath, argumentsForRunAndDebugMacWebKitApp();
2482 sub execMacWebKitAppForDebugging($)
2485 my $architectureSwitch;
2486 my $argumentsSeparator;
2488 if (debugger() eq "lldb") {
2489 $architectureSwitch = "--arch";
2490 $argumentsSeparator = "--";
2491 } elsif (debugger() eq "gdb") {
2492 $architectureSwitch = "-arch";
2493 $argumentsSeparator = "--args";
2495 die "Unknown debugger $debugger.\n";
2498 my $debuggerPath = `xcrun -find $debugger`;
2499 chomp $debuggerPath;
2500 die "Can't find the $debugger executable.\n" unless -x $debuggerPath;
2502 my $productDir = productDir();
2503 setupMacWebKitEnvironment($productDir);
2505 my @architectureFlags = ($architectureSwitch, architecture());
2506 if (!shouldTargetWebProcess()) {
2507 print "Starting @{[basename($appPath)]} under $debugger with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2508 exec { $debuggerPath } $debuggerPath, @architectureFlags, $argumentsSeparator, $appPath, argumentsForRunAndDebugMacWebKitApp() or die;
2510 if (shouldUseXPCServiceForWebProcess()) {
2511 die "Targeting the Web Process is not compatible with using an XPC Service for the Web Process at this time.";
2514 my $webProcessShimPath = File::Spec->catfile($productDir, "SecItemShim.dylib");
2515 my $webProcessPath = File::Spec->catdir($productDir, "WebProcess.app");
2516 my $webKit2ExecutablePath = File::Spec->catfile($productDir, "WebKit2.framework", "WebKit2");
2518 appendToEnvironmentVariableList("DYLD_INSERT_LIBRARIES", $webProcessShimPath);
2520 print "Starting WebProcess under $debugger with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2521 exec { $debuggerPath } $debuggerPath, @architectureFlags, $argumentsSeparator, $webProcessPath, $webKit2ExecutablePath, "-type", "webprocess", "-client-executable", $appPath or die;
2527 if (isAppleMacWebKit()) {
2529 execMacWebKitAppForDebugging(safariPath());
2532 return 1; # Unsupported platform; can't debug Safari on this platform.
2537 if (isIOSWebKit()) {
2538 return runIOSWebKitApp(mobileSafariBundle());
2541 if (isAppleMacWebKit()) {
2542 return runMacWebKitApp(safariPath());
2545 if (isAppleWinWebKit()) {
2547 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2548 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2551 return 1; # Unsupported platform; can't run Safari on this platform.
2556 if (isAppleMacWebKit()) {
2557 return runMacWebKitApp(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2558 } elsif (isAppleWinWebKit()) {
2560 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2561 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2567 sub debugMiniBrowser
2569 if (isAppleMacWebKit()) {
2570 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2576 sub runWebKitTestRunner
2578 if (isAppleMacWebKit()) {
2579 return runMacWebKitApp(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2585 sub debugWebKitTestRunner
2587 if (isAppleMacWebKit()) {
2588 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2594 sub readRegistryString
2596 my ($valueName) = @_;
2597 chomp(my $string = `regtool --wow32 get "$valueName"`);
2601 sub writeRegistryString
2603 my ($valueName, $string) = @_;
2605 my $error = system "regtool", "--wow32", "set", "-s", $valueName, $string;
2607 # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
2608 # return a successful exit code. So we double-check here that the value we tried to write to the
2609 # registry was really written.
2610 return !$error && readRegistryString($valueName) eq $string;
2613 sub formatBuildTime($)
2615 my ($buildTime) = @_;
2617 my $buildHours = int($buildTime / 3600);
2618 my $buildMins = int(($buildTime - $buildHours * 3600) / 60);
2619 my $buildSecs = $buildTime - $buildHours * 3600 - $buildMins * 60;
2622 return sprintf("%dh:%02dm:%02ds", $buildHours, $buildMins, $buildSecs);
2624 return sprintf("%02dm:%02ds", $buildMins, $buildSecs);
2627 sub runSvnUpdateAndResolveChangeLogs(@)
2629 my @svnOptions = @_;
2630 my $openCommand = "svn update " . join(" ", @svnOptions);
2631 open my $update, "$openCommand |" or die "cannot execute command $openCommand";
2632 my @conflictedChangeLogs;
2633 while (my $line = <$update>) {
2635 $line =~ m/^C\s+(.+?)[\r\n]*$/;
2637 my $filename = normalizePath($1);
2638 push @conflictedChangeLogs, $filename if basename($filename) eq "ChangeLog";
2641 close $update or die;
2643 if (@conflictedChangeLogs) {
2644 print "Attempting to merge conflicted ChangeLogs.\n";
2645 my $resolveChangeLogsPath = File::Spec->catfile(sourceDir(), "Tools", "Scripts", "resolve-ChangeLogs");
2646 (system($resolveChangeLogsPath, "--no-warnings", @conflictedChangeLogs) == 0)
2647 or die "Could not open resolve-ChangeLogs script: $!.\n";
2653 # Doing a git fetch first allows setups with svn-remote.svn.fetch = trunk:refs/remotes/origin/master
2654 # to perform the rebase much much faster.
2655 system("git", "fetch");
2656 if (isGitSVNDirectory(".")) {
2657 system("git", "svn", "rebase") == 0 or die;
2659 # This will die if branch.$BRANCHNAME.merge isn't set, which is
2660 # almost certainly what we want.
2661 system("git", "pull") == 0 or die;