1 # Copyright (C) 2005-2007, 2010-2016 Apple Inc. All rights reserved.
2 # Copyright (C) 2009 Google Inc. All rights reserved.
3 # Copyright (C) 2011 Research In Motion Limited. All rights reserved.
4 # Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies).
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution.
15 # 3. Neither the name of Apple Inc. ("Apple") nor the names of
16 # its contributors may be used to endorse or promote products derived
17 # from this software without specific prior written permission.
19 # THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 # DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 # Module to share code to get to WebKit directories.
37 use Digest::MD5 qw(md5_hex);
41 use File::Path qw(make_path mkpath rmtree);
43 use File::Temp qw(tempdir);
47 use Time::HiRes qw(usleep);
52 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
56 &XcodeCoverageSupportOptions
58 &XcodeOptionStringNoConfig
60 &XcodeStaticAnalyzerOption
61 &appDisplayNameFromBundle
62 &appendToEnvironmentVariableList
63 &archCommandLineArgumentsForRestrictedEnvironmentVariables
68 &cmakeArgsFromFeatures
69 &cmakeBasedPortArguments
73 &extractNonHostConfiguration
74 &findOrCreateSimulatorForIOSDevice
75 &iosSimulatorDeviceByName
79 &prependToEnvironmentVariableList
80 &printHelpAndExitForRunAndDebugWebKitAppIfNeeded
84 &restartIOSSimulatorDevice
91 &setupMacWebKitEnvironment
92 &sharedCommandLineOptions
93 &sharedCommandLineOptionsUsage
94 &shutDownIOSSimulatorDevice
96 &willUseIOSSimulatorSDK
97 DO_NOT_USE_OPEN_COMMAND
98 SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT
107 AppleWin => "AppleWin",
111 watchOS => "watchOS",
113 JSCOnly => "JSCOnly",
114 WinCairo => "WinCairo",
119 use constant USE_OPEN_COMMAND => 1; # Used in runMacWebKitApp().
120 use constant DO_NOT_USE_OPEN_COMMAND => 2;
121 use constant SIMULATOR_DEVICE_STATE_SHUTDOWN => "1";
122 use constant SIMULATOR_DEVICE_STATE_BOOTED => "3";
123 use constant SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT => "For WebKit Development";
125 # 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>.
126 use constant IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX => "iPhone Developer: ";
135 my @baseProductDirOption;
138 my $configurationForVisualStudio;
139 my $configurationProductDir;
141 my $currentSVNRevision;
142 my $didLoadIPhoneSimulatorNotification;
148 my $isGenerateProjectOnly;
149 my $shouldBuild32Bit;
151 my $isInspectorFrontend;
153 my $shouldUseGuardMalloc;
154 my $shouldNotUseNinja;
157 my $unknownPortProhibited = 0;
159 # Variables for Win32 support
160 my $programFilesPath;
163 my $msBuildInstallDir;
165 my $windowsSourceDir;
167 my $willUseVCExpressWhenBuilding = 0;
168 my $vsWhereFoundInstallation;
170 # Defined in VCSUtils.
173 sub findMatchingArguments($$);
179 chomp(my $sdkDirectory = `xcrun --sdk '$sdkName' --show-sdk-path`);
180 die "Failed to get SDK path from xcrun: $!" if exitStatus($?);
181 return $sdkDirectory;
184 sub sdkPlatformDirectory($)
187 chomp(my $sdkPlatformDirectory = `xcrun --sdk '$sdkName' --show-sdk-platform-path`);
188 die "Failed to get SDK platform path from xcrun: $!" if exitStatus($?);
189 return $sdkPlatformDirectory;
192 sub determineSourceDir
194 return if $sourceDir;
195 $sourceDir = $FindBin::Bin;
196 $sourceDir =~ s|/+$||; # Remove trailing '/' as we would die later
198 # walks up path checking each directory to see if it is the main WebKit project dir,
199 # defined by containing Sources, WebCore, and JavaScriptCore.
200 until ((-d File::Spec->catdir($sourceDir, "Source") && -d File::Spec->catdir($sourceDir, "Source", "WebCore") && -d File::Spec->catdir($sourceDir, "Source", "JavaScriptCore")) || (-d File::Spec->catdir($sourceDir, "Internal") && -d File::Spec->catdir($sourceDir, "OpenSource")))
202 if ($sourceDir !~ s|/[^/]+$||) {
203 die "Could not find top level webkit directory above source directory using FindBin.\n";
207 $sourceDir = File::Spec->catdir($sourceDir, "OpenSource") if -d File::Spec->catdir($sourceDir, "OpenSource");
210 sub currentPerlPath()
214 $thisPerl .= $Config{_exe} unless $thisPerl =~ m/$Config{_exe}$/i;
219 # used for scripts which are stored in a non-standard location
225 sub determineNinjaVersion
227 chomp(my $ninjaVersion = `ninja --version`);
228 return $ninjaVersion;
231 sub determineXcodeVersion
233 return if defined $xcodeVersion;
234 my $xcodebuildVersionOutput = `xcodebuild -version`;
235 $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9]+(\.[0-9]+)*)/) ? $1 : "3.0";
238 sub readXcodeUserDefault($)
242 my $devnull = File::Spec->devnull();
244 my $value = `defaults read com.apple.dt.Xcode ${key} 2> ${devnull}`;
251 sub determineBaseProductDir
253 return if defined $baseProductDir;
254 determineSourceDir();
256 my $setSharedPrecompsDir;
257 my $indexDataStoreDir;
258 $baseProductDir = $ENV{"WEBKIT_OUTPUTDIR"};
260 if (!defined($baseProductDir) and isAppleCocoaWebKit()) {
261 # Silently remove ~/Library/Preferences/xcodebuild.plist which can
262 # cause build failure. The presence of
263 # ~/Library/Preferences/xcodebuild.plist can prevent xcodebuild from
264 # respecting global settings such as a custom build products directory
265 # (<rdar://problem/5585899>).
266 my $personalPlistFile = $ENV{HOME} . "/Library/Preferences/xcodebuild.plist";
267 if (-e $personalPlistFile) {
268 unlink($personalPlistFile) || die "Could not delete $personalPlistFile: $!";
271 my $buildLocationStyle = join '', readXcodeUserDefault("IDEBuildLocationStyle");
272 if ($buildLocationStyle eq "Custom") {
273 my $buildLocationType = join '', readXcodeUserDefault("IDECustomBuildLocationType");
274 # FIXME: Read CustomBuildIntermediatesPath and set OBJROOT accordingly.
275 if ($buildLocationType eq "Absolute") {
276 $baseProductDir = readXcodeUserDefault("IDECustomBuildProductsPath");
277 $indexDataStoreDir = readXcodeUserDefault("IDECustomIndexStorePath");
281 # DeterminedByTargets corresponds to a setting of "Legacy" in Xcode.
282 # It is the only build location style for which SHARED_PRECOMPS_DIR is not
283 # overridden when building from within Xcode.
284 $setSharedPrecompsDir = 1 if $buildLocationStyle ne "DeterminedByTargets";
286 if (!defined($baseProductDir)) {
287 $baseProductDir = join '', readXcodeUserDefault("IDEApplicationwideBuildSettings");
288 $baseProductDir = $1 if $baseProductDir =~ /SYMROOT\s*=\s*\"(.*?)\";/s;
291 undef $baseProductDir unless $baseProductDir =~ /^\//;
294 if (!defined($baseProductDir)) { # Port-specific checks failed, use default
295 $baseProductDir = File::Spec->catdir($sourceDir, "WebKitBuild");
298 if (isGit() && isGitBranchBuild()) {
299 my $branch = gitBranch();
300 $baseProductDir = "$baseProductDir/$branch";
303 if (isAppleCocoaWebKit()) {
304 $baseProductDir =~ s|^\Q$(SRCROOT)/..\E$|$sourceDir|;
305 $baseProductDir =~ s|^\Q$(SRCROOT)/../|$sourceDir/|;
306 $baseProductDir =~ s|^~/|$ENV{HOME}/|;
307 die "Can't handle Xcode product directory with a ~ in it.\n" if $baseProductDir =~ /~/;
308 die "Can't handle Xcode product directory with a variable in it.\n" if $baseProductDir =~ /\$/;
309 @baseProductDirOption = ("SYMROOT=$baseProductDir", "OBJROOT=$baseProductDir");
310 push(@baseProductDirOption, "SHARED_PRECOMPS_DIR=${baseProductDir}/PrecompiledHeaders") if $setSharedPrecompsDir;
311 push(@baseProductDirOption, "INDEX_ENABLE_DATA_STORE=YES", "INDEX_DATA_STORE_DIR=${indexDataStoreDir}") if $indexDataStoreDir;
315 my $dosBuildPath = `cygpath --windows \"$baseProductDir\"`;
317 $ENV{"WEBKIT_OUTPUTDIR"} = $dosBuildPath;
318 my $unixBuildPath = `cygpath --unix \"$baseProductDir\"`;
319 chomp $unixBuildPath;
320 $baseProductDir = $dosBuildPath;
329 sub setBaseProductDir($)
331 ($baseProductDir) = @_;
334 sub determineConfiguration
336 return if defined $configuration;
337 determineBaseProductDir();
338 if (open CONFIGURATION, "$baseProductDir/Configuration") {
339 $configuration = <CONFIGURATION>;
342 if ($configuration) {
343 chomp $configuration;
344 # compatibility for people who have old Configuration files
345 $configuration = "Release" if $configuration eq "Deployment";
346 $configuration = "Debug" if $configuration eq "Development";
348 $configuration = "Release";
352 sub determineArchitecture
354 return if defined $architecture;
355 # make sure $architecture is defined in all cases
358 determineBaseProductDir();
361 if (isAppleCocoaWebKit()) {
362 if (open ARCHITECTURE, "$baseProductDir/Architecture") {
363 $architecture = <ARCHITECTURE>;
369 if (not defined $xcodeSDK or $xcodeSDK =~ /^(\/$|macosx)/) {
370 my $supports64Bit = `sysctl -n hw.optional.x86_64`;
371 chomp $supports64Bit;
372 $architecture = 'x86_64' if $supports64Bit;
373 } elsif ($xcodeSDK =~ /^iphonesimulator/) {
374 $architecture = 'x86_64';
375 } elsif ($xcodeSDK =~ /^iphoneos/) {
376 $architecture = 'arm64';
379 } elsif (isCMakeBuild()) {
380 if (isCrossCompilation()) {
381 my $compiler = "gcc";
382 $compiler = $ENV{'CC'} if (defined($ENV{'CC'}));
383 my @compiler_machine = split('-', `$compiler -dumpmachine`);
384 $architecture = $compiler_machine[0];
385 } elsif (open my $cmake_sysinfo, "cmake --system-information |") {
386 while (<$cmake_sysinfo>) {
387 next unless index($_, 'CMAKE_SYSTEM_PROCESSOR') == 0;
388 if (/^CMAKE_SYSTEM_PROCESSOR \"([^"]+)\"/) {
393 close $cmake_sysinfo;
397 if (!isAnyWindows()) {
398 if (!$architecture) {
399 # Fall back to output of `uname -m', if it is present.
400 $architecture = `uname -m`;
405 $architecture = 'x86_64' if $architecture =~ /amd64/i;
406 $architecture = 'arm64' if $architecture =~ /aarch64/i;
409 sub determineASanIsEnabled
411 return if defined $asanIsEnabled;
412 determineBaseProductDir();
415 my $asanConfigurationValue;
417 if (open ASAN, "$baseProductDir/ASan") {
418 $asanConfigurationValue = <ASAN>;
420 chomp $asanConfigurationValue;
421 $asanIsEnabled = 1 if $asanConfigurationValue eq "YES";
425 sub determineNumberOfCPUs
427 return if defined $numberOfCPUs;
428 if (defined($ENV{NUMBER_OF_PROCESSORS})) {
429 $numberOfCPUs = $ENV{NUMBER_OF_PROCESSORS};
430 } elsif (isLinux()) {
431 # First try the nproc utility, if it exists. If we get no
432 # results fall back to just interpretting /proc directly.
433 chomp($numberOfCPUs = `nproc --all 2> /dev/null`);
434 if ($numberOfCPUs eq "") {
435 $numberOfCPUs = (grep /processor/, `cat /proc/cpuinfo`);
437 } elsif (isAnyWindows()) {
439 $numberOfCPUs = `ls /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor | wc -w`;
440 } elsif (isDarwin() || isBSD()) {
441 chomp($numberOfCPUs = `sysctl -n hw.ncpu`);
447 sub determineMaxCPULoad
449 return if defined $maxCPULoad;
450 if (defined($ENV{MAX_CPU_LOAD})) {
451 $maxCPULoad = $ENV{MAX_CPU_LOAD};
457 my ($productDir) = @_;
459 $jscName .= "_debug" if configuration() eq "Debug_All";
460 $jscName .= ".exe" if (isAnyWindows());
461 return "$productDir/$jscName" if -e "$productDir/$jscName";
462 return "$productDir/JavaScriptCore.framework/Resources/$jscName";
465 sub argumentsForConfiguration()
467 determineConfiguration();
468 determineArchitecture();
472 # FIXME: Is it necessary to pass --debug, --release, --32-bit or --64-bit?
473 # These are determined automatically from stored configuration.
474 push(@args, '--debug') if ($configuration =~ "^Debug");
475 push(@args, '--release') if ($configuration =~ "^Release");
476 push(@args, '--ios-device') if (defined $xcodeSDK && $xcodeSDK =~ /^iphoneos/);
477 push(@args, '--ios-simulator') if (defined $xcodeSDK && $xcodeSDK =~ /^iphonesimulator/);
478 push(@args, '--32-bit') if ($architecture ne "x86_64" and !isWin64());
479 push(@args, '--64-bit') if (isWin64());
480 push(@args, '--gtk') if isGtk();
481 push(@args, '--wpe') if isWPE();
482 push(@args, '--jsc-only') if isJSCOnly();
483 push(@args, '--wincairo') if isWinCairo();
484 push(@args, '--inspector-frontend') if isInspectorFrontend();
488 sub extractNonMacOSHostConfiguration
491 my @extract = ('--device', '--gtk', '--ios', '--platform', '--sdk', '--simulator', '--wincairo', 'SDKROOT', 'ARCHS');
496 if (length($line) >= length($_) && substr($line, 0, length($_)) eq $_
497 && index($line, 'i386') == -1 && index($line, 'x86_64') == -1) {
508 # FIXME: Convert to json <rdar://problem/21594308>
509 sub parseAvailableXcodeSDKs($)
511 my @outputToParse = @{$_[0]};
513 foreach my $line (@outputToParse) {
515 # iOS 12.0 -sdk iphoneos12.0
516 # Simulator - iOS 12.0 -sdk iphonesimulator12.0
517 # macOS 10.14 -sdk macosx10.14
518 if ($line =~ /-sdk (\D+)([\d\.]+)(\D*)\n/) {
520 push @result, "$1.$3";
529 sub availableXcodeSDKs
531 my @output = `xcodebuild -showsdks`;
532 return parseAvailableXcodeSDKs(\@output);
535 sub determineXcodeSDK
537 return if defined $xcodeSDK;
540 # The user explicitly specified the sdk, don't assume anything
541 if (checkForArgumentAndRemoveFromARGVGettingValue("--sdk", \$sdk)) {
545 if (checkForArgumentAndRemoveFromARGV("--device") || checkForArgumentAndRemoveFromARGV("--ios-device")) {
546 $xcodeSDK ||= "iphoneos";
548 if (checkForArgumentAndRemoveFromARGV("--simulator") || checkForArgumentAndRemoveFromARGV("--ios-simulator")) {
549 $xcodeSDK ||= 'iphonesimulator';
551 if (checkForArgumentAndRemoveFromARGV("--tvos-device")) {
552 $xcodeSDK ||= "appletvos";
554 if (checkForArgumentAndRemoveFromARGV("--tvos-simulator")) {
555 $xcodeSDK ||= "appletvsimulator";
557 if (checkForArgumentAndRemoveFromARGV("--watchos-device")) {
558 $xcodeSDK ||= "watchos";
560 if (checkForArgumentAndRemoveFromARGV("--watchos-simulator")) {
561 $xcodeSDK ||= "watchsimulator";
563 return if !defined $xcodeSDK;
565 # Prefer the internal version of an sdk, if it exists.
566 my @availableSDKs = availableXcodeSDKs();
568 foreach my $sdk (@availableSDKs) {
569 next if $sdk ne "$xcodeSDK.internal";
587 sub xcodeSDKPlatformName()
590 return "" if !defined $xcodeSDK;
591 return "appletvos" if $xcodeSDK =~ /appletvos/i;
592 return "appletvsimulator" if $xcodeSDK =~ /appletvsimulator/i;
593 return "iphoneos" if $xcodeSDK =~ /iphoneos/i;
594 return "iphonesimulator" if $xcodeSDK =~ /iphonesimulator/i;
595 return "macosx" if $xcodeSDK =~ /macosx/i;
596 return "watchos" if $xcodeSDK =~ /watchos/i;
597 return "watchsimulator" if $xcodeSDK =~ /watchsimulator/i;
598 die "Couldn't determine platform name from Xcode SDK";
605 die "Can't find the SDK path because no Xcode SDK was specified" if not $xcodeSDK;
606 return sdkDirectory($xcodeSDK);
613 die "Can't find the SDK version because no Xcode SDK was specified" if !$xcodeSDK;
615 chomp(my $sdkVersion = `xcrun --sdk $xcodeSDK --show-sdk-version`);
616 die "Failed to get SDK version from xcrun" if exitStatus($?);
623 return $programFilesPath if defined $programFilesPath;
625 $programFilesPath = $ENV{'PROGRAMFILES(X86)'} || $ENV{'PROGRAMFILES'} || "C:\\Program Files";
627 return $programFilesPath;
630 sub programFilesPathX86
632 my $programFilesPathX86 = $ENV{'PROGRAMFILES(X86)'} || "C:\\Program Files (x86)";
634 return $programFilesPathX86;
637 sub requireModulesForVSWhere
640 require Encode::Locale;
644 sub pickCurrentVisualStudioInstallation
646 return $vsWhereFoundInstallation if defined $vsWhereFoundInstallation;
648 requireModulesForVSWhere();
649 determineSourceDir();
651 # Prefer Enterprise, then Professional, then Community, then
652 # anything else that provides MSBuild.
653 foreach my $productType ((
654 'Microsoft.VisualStudio.Product.Enterprise',
655 'Microsoft.VisualStudio.Product.Professional',
656 'Microsoft.VisualStudio.Product.Community',
659 my $command = "$sourceDir/WebKitLibraries/win/tools/vswhere -nologo -latest -format json -requires Microsoft.Component.MSBuild";
660 if (defined $productType) {
661 $command .= " -products $productType";
663 my $vsWhereOut = `$command`;
664 my $installations = [];
666 $installations = JSON::PP::decode_json(Encode::encode('UTF-8' => Encode::decode(console_in => $vsWhereOut)));
668 print "Error getting Visual Studio Location: $@\n" if $@;
671 if (scalar @$installations) {
672 my $installation = $installations->[0];
673 $vsWhereFoundInstallation = $installation;
674 return $installation;
680 sub visualStudioInstallDir
682 return $vsInstallDir if defined $vsInstallDir;
684 if ($ENV{'VSINSTALLDIR'}) {
685 $vsInstallDir = $ENV{'VSINSTALLDIR'};
686 $vsInstallDir =~ s|[\\/]$||;
688 $vsInstallDir = visualStudioInstallDirVSWhere();
689 if (not -e $vsInstallDir) {
690 $vsInstallDir = visualStudioInstallDirFallback();
693 chomp($vsInstallDir = `cygpath "$vsInstallDir"`) if isCygwin();
695 print "Using Visual Studio: $vsInstallDir\n";
696 return $vsInstallDir;
699 sub visualStudioInstallDirVSWhere
701 pickCurrentVisualStudioInstallation();
702 if (defined($vsWhereFoundInstallation)) {
703 return $vsWhereFoundInstallation->{installationPath};
708 sub visualStudioInstallDirFallback
710 foreach my $productType ((
715 my $installdir = File::Spec->catdir(programFilesPathX86(),
716 "Microsoft Visual Studio", "2017", $productType);
717 my $msbuilddir = File::Spec->catdir($installdir,
718 "MSBuild", "15.0", "bin");
719 if (-e $installdir && -e $msbuilddir) {
726 sub msBuildInstallDir
728 return $msBuildInstallDir if defined $msBuildInstallDir;
730 my $installDir = visualStudioInstallDir();
731 $msBuildInstallDir = File::Spec->catdir($installDir,
732 "MSBuild", "15.0", "bin");
734 chomp($msBuildInstallDir = `cygpath "$msBuildInstallDir"`) if isCygwin();
736 print "Using MSBuild: $msBuildInstallDir\n";
737 return $msBuildInstallDir;
740 sub determineConfigurationForVisualStudio
742 return if defined $configurationForVisualStudio;
743 determineConfiguration();
744 # FIXME: We should detect when Debug_All or Production has been chosen.
745 $configurationForVisualStudio = "/p:Configuration=" . $configuration;
748 sub usesPerConfigurationBuildDirectory
750 # [Gtk] We don't have Release/Debug configurations in straight
751 # autotool builds (non build-webkit). In this case and if
752 # WEBKIT_OUTPUTDIR exist, use that as our configuration dir. This will
753 # allows us to run run-webkit-tests without using build-webkit.
754 return ($ENV{"WEBKIT_OUTPUTDIR"} && isGtk()) || isAppleWinWebKit();
757 sub determineConfigurationProductDir
759 return if defined $configurationProductDir;
760 determineBaseProductDir();
761 determineConfiguration();
762 if (isAppleWinWebKit() || isWinCairo()) {
763 $configurationProductDir = File::Spec->catdir($baseProductDir, $configuration);
765 if (usesPerConfigurationBuildDirectory()) {
766 $configurationProductDir = "$baseProductDir";
768 $configurationProductDir = "$baseProductDir/$configuration";
769 $configurationProductDir .= "-" . xcodeSDKPlatformName() if isEmbeddedWebKit();
774 sub setConfigurationProductDir($)
776 ($configurationProductDir) = @_;
779 sub determineCurrentSVNRevision
781 # We always update the current SVN revision here, and leave the caching
782 # to currentSVNRevision(), so that changes to the SVN revision while the
783 # script is running can be picked up by calling this function again.
784 determineSourceDir();
785 $currentSVNRevision = svnRevisionForDirectory($sourceDir);
786 return $currentSVNRevision;
792 determineSourceDir();
793 chdir $sourceDir or die;
798 determineBaseProductDir();
799 return $baseProductDir;
804 determineSourceDir();
810 determineConfigurationProductDir();
811 return $configurationProductDir;
814 sub executableProductDir
816 my $productDirectory = productDir();
819 if (isAnyWindows()) {
820 $binaryDirectory = isWin64() ? "bin64" : "bin32";
821 } elsif (isGtk() || isJSCOnly() || isWPE()) {
822 $binaryDirectory = "bin";
824 return $productDirectory;
827 return File::Spec->catdir($productDirectory, $binaryDirectory);
832 return executableProductDir();
837 determineConfiguration();
838 return $configuration;
843 determineASanIsEnabled();
844 return $asanIsEnabled;
847 sub configurationForVisualStudio()
849 determineConfigurationForVisualStudio();
850 return $configurationForVisualStudio;
853 sub currentSVNRevision
855 determineCurrentSVNRevision() if not defined $currentSVNRevision;
856 return $currentSVNRevision;
861 determineGenerateDsym();
862 return $generateDsym;
865 sub determineGenerateDsym()
867 return if defined($generateDsym);
868 $generateDsym = checkForArgumentAndRemoveFromARGV("--dsym");
871 sub hasIOSDevelopmentCertificate()
873 return !exitStatus(system("security find-identity -p codesigning | grep '" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX . "' > /dev/null 2>&1"));
876 sub argumentsForXcode()
879 push @args, "DEBUG_INFORMATION_FORMAT=dwarf-with-dsym" if generateDsym();
885 determineBaseProductDir();
886 determineConfiguration();
887 determineArchitecture();
888 determineASanIsEnabled();
892 push @options, "-UseNewBuildSystem=NO";
893 push @options, "-UseSanitizedBuildSystemEnvironment=YES";
894 push @options, ("-configuration", $configuration);
895 push @options, ("-xcconfig", sourceDir() . "/Tools/asan/asan.xcconfig", "ASAN_IGNORE=" . sourceDir() . "/Tools/asan/webkit-asan-ignore.txt") if $asanIsEnabled;
896 push @options, @baseProductDirOption;
897 push @options, "ARCHS=$architecture" if $architecture;
898 push @options, "SDKROOT=$xcodeSDK" if $xcodeSDK;
899 if (willUseIOSDeviceSDK()) {
900 push @options, "ENABLE_BITCODE=NO";
901 if (hasIOSDevelopmentCertificate()) {
902 # FIXME: May match more than one installed development certificate.
903 push @options, "CODE_SIGN_IDENTITY=" . IOS_DEVELOPMENT_CERTIFICATE_NAME_PREFIX;
905 push @options, "CODE_SIGN_IDENTITY="; # No identity
906 push @options, "CODE_SIGNING_REQUIRED=NO";
909 push @options, argumentsForXcode();
913 sub XcodeOptionString
915 return join " ", XcodeOptions();
918 sub XcodeOptionStringNoConfig
920 return join " ", @baseProductDirOption;
923 sub XcodeCoverageSupportOptions()
925 my @coverageSupportOptions = ();
926 push @coverageSupportOptions, "GCC_GENERATE_TEST_COVERAGE_FILES=YES";
927 push @coverageSupportOptions, "GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES";
928 return @coverageSupportOptions;
931 sub XcodeStaticAnalyzerOption()
933 return "RUN_CLANG_STATIC_ANALYZER=YES";
936 my $passedConfiguration;
937 my $searchedForPassedConfiguration;
938 sub determinePassedConfiguration
940 return if $searchedForPassedConfiguration;
941 $searchedForPassedConfiguration = 1;
942 $passedConfiguration = undef;
944 if (checkForArgumentAndRemoveFromARGV("--debug")) {
945 $passedConfiguration = "Debug";
946 } elsif(checkForArgumentAndRemoveFromARGV("--release")) {
947 $passedConfiguration = "Release";
948 } elsif (checkForArgumentAndRemoveFromARGV("--profile") || checkForArgumentAndRemoveFromARGV("--profiling")) {
949 $passedConfiguration = "Profiling";
953 sub passedConfiguration
955 determinePassedConfiguration();
956 return $passedConfiguration;
963 if (my $config = shift @_) {
964 $configuration = $config;
968 determinePassedConfiguration();
969 $configuration = $passedConfiguration if $passedConfiguration;
973 my $passedArchitecture;
974 my $searchedForPassedArchitecture;
975 sub determinePassedArchitecture
977 return if $searchedForPassedArchitecture;
978 $searchedForPassedArchitecture = 1;
980 $passedArchitecture = undef;
981 if (shouldBuild32Bit()) {
982 if (isAppleCocoaWebKit()) {
983 # PLATFORM_IOS: Don't run `arch` command inside Simulator environment
985 delete $ENV{DYLD_ROOT_PATH};
986 delete $ENV{DYLD_FRAMEWORK_PATH};
988 $passedArchitecture = `arch`;
989 chomp $passedArchitecture;
994 sub passedArchitecture
996 determinePassedArchitecture();
997 return $passedArchitecture;
1002 determineArchitecture();
1003 return $architecture;
1008 determineNumberOfCPUs();
1009 return $numberOfCPUs;
1014 determineMaxCPULoad();
1020 if (my $arch = shift @_) {
1021 $architecture = $arch;
1025 determinePassedArchitecture();
1026 $architecture = $passedArchitecture if $passedArchitecture;
1032 die "Safari path is only relevant on Apple Mac platform\n" unless isAppleMacWebKit();
1036 # Use WEBKIT_SAFARI environment variable if present.
1037 my $safariBundle = $ENV{WEBKIT_SAFARI};
1038 if (!$safariBundle) {
1039 determineConfigurationProductDir();
1040 # Use Safari.app in product directory if present (good for Safari development team).
1041 if (-d "$configurationProductDir/Safari.app") {
1042 $safariBundle = "$configurationProductDir/Safari.app";
1046 if ($safariBundle) {
1047 $safariPath = "$safariBundle/Contents/MacOS/Safari";
1049 $safariPath = "/Applications/Safari.app/Contents/MacOS/SafariForWebKitDevelopment";
1052 die "Can't find executable at $safariPath.\n" if !-x $safariPath;
1056 sub builtDylibPathForName
1058 my $libraryName = shift;
1059 determineConfigurationProductDir();
1062 my $extension = isDarwin() ? ".dylib" : ".so";
1063 return "$configurationProductDir/lib/libwebkit2gtk-4.0" . $extension;
1065 if (isIOSWebKit()) {
1066 return "$configurationProductDir/$libraryName.framework/$libraryName";
1068 if (isAppleCocoaWebKit()) {
1069 return "$configurationProductDir/$libraryName.framework/Versions/A/$libraryName";
1071 if (isAppleWinWebKit()) {
1072 if ($libraryName eq "JavaScriptCore") {
1073 return "$baseProductDir/lib/$libraryName.lib";
1075 return "$baseProductDir/$libraryName.intermediate/$configuration/$libraryName.intermediate/$libraryName.lib";
1079 return "$configurationProductDir/lib/libWPEWebKit-0.1.so";
1082 die "Unsupported platform, can't determine built library locations.\nTry `build-webkit --help` for more information.\n";
1085 # Check to see that all the frameworks are built.
1086 sub checkFrameworks # FIXME: This is a poor name since only the Mac calls built WebCore a Framework.
1088 return if isAnyWindows();
1089 my @frameworks = ("JavaScriptCore", "WebCore");
1090 push(@frameworks, "WebKit") if isAppleCocoaWebKit(); # FIXME: This seems wrong, all ports should have a WebKit these days.
1091 for my $framework (@frameworks) {
1092 my $path = builtDylibPathForName($framework);
1093 die "Can't find built framework at \"$path\".\n" unless -e $path;
1097 sub isInspectorFrontend()
1099 determineIsInspectorFrontend();
1100 return $isInspectorFrontend;
1103 sub determineIsInspectorFrontend()
1105 return if defined($isInspectorFrontend);
1106 $isInspectorFrontend = checkForArgumentAndRemoveFromARGV("--inspector-frontend");
1109 sub commandExists($)
1111 my $command = shift;
1112 my $devnull = File::Spec->devnull();
1114 if (isAnyWindows()) {
1115 return exitStatus(system("where /q $command >$devnull 2>&1")) == 0;
1117 return exitStatus(system("which $command >$devnull 2>&1")) == 0;
1120 sub checkForArgumentAndRemoveFromARGV($)
1122 my $argToCheck = shift;
1123 return checkForArgumentAndRemoveFromArrayRef($argToCheck, \@ARGV);
1126 sub checkForArgumentAndRemoveFromArrayRefGettingValue($$$)
1128 my ($argToCheck, $valueRef, $arrayRef) = @_;
1129 my $argumentStartRegEx = qr#^$argToCheck(?:=\S|$)#;
1131 for (; $i < @$arrayRef; ++$i) {
1132 last if $arrayRef->[$i] =~ $argumentStartRegEx;
1134 if ($i >= @$arrayRef) {
1135 return $$valueRef = undef;
1137 my ($key, $value) = split("=", $arrayRef->[$i]);
1138 splice(@$arrayRef, $i, 1);
1139 if (defined($value)) {
1140 # e.g. --sdk=iphonesimulator
1141 return $$valueRef = $value;
1143 return $$valueRef = splice(@$arrayRef, $i, 1); # e.g. --sdk iphonesimulator
1146 sub checkForArgumentAndRemoveFromARGVGettingValue($$)
1148 my ($argToCheck, $valueRef) = @_;
1149 return checkForArgumentAndRemoveFromArrayRefGettingValue($argToCheck, $valueRef, \@ARGV);
1152 sub findMatchingArguments($$)
1154 my ($argToCheck, $arrayRef) = @_;
1155 my @matchingIndices;
1156 foreach my $index (0 .. $#$arrayRef) {
1157 my $opt = $$arrayRef[$index];
1158 if ($opt =~ /^$argToCheck$/i ) {
1159 push(@matchingIndices, $index);
1162 return @matchingIndices;
1167 my ($argToCheck, $arrayRef) = @_;
1168 my @matchingIndices = findMatchingArguments($argToCheck, $arrayRef);
1169 return scalar @matchingIndices > 0;
1172 sub checkForArgumentAndRemoveFromArrayRef
1174 my ($argToCheck, $arrayRef) = @_;
1175 my @indicesToRemove = findMatchingArguments($argToCheck, $arrayRef);
1176 my $removeOffset = 0;
1177 foreach my $index (@indicesToRemove) {
1178 splice(@$arrayRef, $index - $removeOffset++, 1);
1180 return scalar @indicesToRemove > 0;
1183 sub prohibitUnknownPort()
1185 $unknownPortProhibited = 1;
1188 sub determinePortName()
1190 return if defined $portName;
1192 my %argToPortName = (
1194 'jsc-only' => JSCOnly,
1195 wincairo => WinCairo,
1199 for my $arg (sort keys %argToPortName) {
1200 if (checkForArgumentAndRemoveFromARGV("--$arg")) {
1201 die "Argument '--$arg' conflicts with selected port '$portName'\n"
1202 if defined $portName;
1204 $portName = $argToPortName{$arg};
1208 return if defined $portName;
1210 # Port was not selected via command line, use appropriate default value
1212 if (isAnyWindows()) {
1213 $portName = AppleWin;
1214 } elsif (isDarwin()) {
1215 determineXcodeSDK();
1216 if (willUseIOSDeviceSDK() || willUseIOSSimulatorSDK()) {
1218 } elsif (willUseAppleTVDeviceSDK() || willUseAppleTVSimulatorSDK()) {
1220 } elsif (willUseWatchDeviceSDK() || willUseWatchSimulatorSDK()) {
1221 $portName = watchOS;
1226 if ($unknownPortProhibited) {
1227 my $portsChoice = join "\n\t", qw(
1232 die "Please specify which WebKit port to build using one of the following options:"
1233 . "\n\t$portsChoice\n";
1236 # If script is run without arguments we cannot determine port
1237 # TODO: This state should be outlawed
1238 $portName = Unknown;
1244 determinePortName();
1250 return portName() eq GTK;
1255 return portName() eq JSCOnly;
1260 return portName() eq WPE;
1263 # Determine if this is debian, ubuntu, linspire, or something similar.
1266 return -e "/etc/debian_version";
1271 return -e "/etc/fedora-release";
1276 return portName() eq WinCairo;
1279 sub shouldBuild32Bit()
1281 determineShouldBuild32Bit();
1282 return $shouldBuild32Bit;
1285 sub determineShouldBuild32Bit()
1287 return if defined($shouldBuild32Bit);
1288 $shouldBuild32Bit = checkForArgumentAndRemoveFromARGV("--32-bit");
1297 sub determineIsWin64()
1299 return if defined($isWin64);
1300 $isWin64 = checkForArgumentAndRemoveFromARGV("--64-bit") || ((isWinCairo() || isJSCOnly()) && !shouldBuild32Bit());
1303 sub determineIsWin64FromArchitecture($)
1306 $isWin64 = ($arch eq "x86_64");
1312 return ($^O eq "cygwin") || 0;
1317 return isWindows() || isCygwin();
1320 sub determineWinVersion()
1322 return if $winVersion;
1324 if (!isAnyWindows()) {
1329 my $versionString = `cmd /c ver`;
1330 $versionString =~ /(\d)\.(\d)\.(\d+)/;
1341 determineWinVersion();
1347 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 1 && winVersion()->{build} == 7600;
1350 sub isWindowsVista()
1352 return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 0;
1357 return isAnyWindows() && winVersion()->{major} == 5 && winVersion()->{minor} == 1;
1362 return ($^O eq "darwin") || 0;
1367 return ($^O eq "MSWin32") || 0;
1372 return ($^O eq "linux") || 0;
1377 return ($^O eq "freebsd") || ($^O eq "openbsd") || ($^O eq "netbsd") || 0;
1382 return (architecture() eq "x86_64") || 0;
1387 return (architecture() eq "arm64") || 0;
1390 sub isCrossCompilation()
1393 $compiler = $ENV{'CC'} if (defined($ENV{'CC'}));
1394 if ($compiler =~ /gcc/) {
1395 my $compilerOptions = `$compiler -v 2>&1`;
1396 my @host = $compilerOptions =~ m/--host=(.*?)\s/;
1397 my @target = $compilerOptions =~ m/--target=(.*?)\s/;
1398 if ($target[0] ne "" && $host[0] ne "") {
1399 return ($host[0] ne $target[0]);
1401 # $tempDir gets automatically deleted when goes out of scope
1402 my $tempDir = File::Temp->newdir();
1403 my $testProgramSourcePath = File::Spec->catfile($tempDir, "testcross.c");
1404 my $testProgramBinaryPath = File::Spec->catfile($tempDir, "testcross");
1405 open(my $testProgramSourceHandler, ">", $testProgramSourcePath);
1406 print $testProgramSourceHandler "int main() { return 0; }\n";
1407 system("$compiler $testProgramSourcePath -o $testProgramBinaryPath > /dev/null 2>&1") == 0 or return 0;
1408 # Crosscompiling if the program fails to run (because it was built for other arch)
1409 system("$testProgramBinaryPath > /dev/null 2>&1") == 0 or return 1;
1418 return portName() eq iOS;
1423 return portName() eq tvOS;
1426 sub isWatchOSWebKit()
1428 return portName() eq watchOS;
1431 sub isEmbeddedWebKit()
1433 return isIOSWebKit() || isTVOSWebKit() || isWatchOSWebKit();
1438 return isAppleCocoaWebKit() || isAppleWinWebKit();
1441 sub isAppleMacWebKit()
1443 return portName() eq Mac;
1446 sub isAppleCocoaWebKit()
1448 return isAppleMacWebKit() || isEmbeddedWebKit();
1451 sub isAppleWinWebKit()
1453 return portName() eq AppleWin;
1456 sub iOSSimulatorDevicesPath
1458 return "$ENV{HOME}/Library/Developer/CoreSimulator/Devices";
1461 sub iOSSimulatorDevices
1463 eval "require Foundation";
1464 my $devicesPath = iOSSimulatorDevicesPath();
1465 opendir(DEVICES, $devicesPath);
1467 $_ =~ m/^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$/;
1471 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
1472 # dictionary keys so as to decouple our representation of the plist from the actual structure
1473 # of the plist, which may change.
1475 Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_("$devicesPath/$_/device.plist"));
1481 sub createiOSSimulatorDevice
1484 my $deviceTypeId = shift;
1485 my $runtimeId = shift;
1487 my $created = system("xcrun", "--sdk", "iphonesimulator", "simctl", "create", $name, $deviceTypeId, $runtimeId) == 0;
1488 die "Couldn't create simulator device: $name $deviceTypeId $runtimeId" if not $created;
1490 system("xcrun", "--sdk", "iphonesimulator", "simctl", "list");
1492 print "Waiting for device to be created ...\n";
1494 for (my $tries = 0; $tries < 5; $tries++){
1495 my @devices = iOSSimulatorDevices();
1496 foreach my $device (@devices) {
1497 return $device if $device->{name} eq $name and $device->{deviceType} eq $deviceTypeId and $device->{runtime} eq $runtimeId;
1501 die "Device $name $deviceTypeId $runtimeId wasn't found in " . iOSSimulatorDevicesPath();
1504 sub willUseIOSDeviceSDK()
1506 return xcodeSDKPlatformName() eq "iphoneos";
1509 sub willUseIOSSimulatorSDK()
1511 return xcodeSDKPlatformName() eq "iphonesimulator";
1514 sub willUseAppleTVDeviceSDK()
1516 return xcodeSDKPlatformName() eq "appletvos";
1519 sub willUseAppleTVSimulatorSDK()
1521 return xcodeSDKPlatformName() eq "appletvsimulator";
1524 sub willUseWatchDeviceSDK()
1526 return xcodeSDKPlatformName() eq "watchos";
1529 sub willUseWatchSimulatorSDK()
1531 return xcodeSDKPlatformName() eq "watchsimulator";
1534 sub determineNmPath()
1538 if (isAppleCocoaWebKit()) {
1539 $nmPath = `xcrun -find nm`;
1542 $nmPath = "nm" if !$nmPath;
1551 sub splitVersionString
1553 my $versionString = shift;
1554 my @splitVersion = split(/\./, $versionString);
1555 @splitVersion >= 2 or die "Invalid version $versionString";
1557 "major" => $splitVersion[0],
1558 "minor" => $splitVersion[1],
1559 "subminor" => (defined($splitVersion[2]) ? $splitVersion[2] : 0),
1563 sub determineOSXVersion()
1565 return if $osXVersion;
1572 my $versionString = `sw_vers -productVersion`;
1573 $osXVersion = splitVersionString($versionString);
1578 determineOSXVersion();
1582 sub determineIOSVersion()
1584 return if $iosVersion;
1586 if (!isIOSWebKit()) {
1591 my $versionString = xcodeSDKVersion();
1592 $iosVersion = splitVersionString($versionString);
1597 determineIOSVersion();
1603 return $ENV{'OS'} eq 'Windows_NT';
1606 sub appendToEnvironmentVariableList($$)
1608 my ($name, $value) = @_;
1610 if (defined($ENV{$name})) {
1611 $ENV{$name} .= $Config{path_sep} . $value;
1613 $ENV{$name} = $value;
1617 sub prependToEnvironmentVariableList($$)
1619 my ($name, $value) = @_;
1621 if (defined($ENV{$name})) {
1622 $ENV{$name} = $value . $Config{path_sep} . $ENV{$name};
1624 $ENV{$name} = $value;
1628 sub sharedCommandLineOptions()
1631 "g|guard-malloc" => \$shouldUseGuardMalloc,
1635 sub sharedCommandLineOptionsUsage
1640 '-g|--guard-malloc' => 'Use guardmalloc when running executable',
1643 my $indent = " " x ($opts{indent} || 2);
1644 my $switchWidth = List::Util::max(int($opts{switchWidth}), List::Util::max(map { length($_) } keys %switches) + ($opts{brackets} ? 2 : 0));
1646 my $result = "Common switches:\n";
1648 for my $switch (keys %switches) {
1649 my $switchName = $opts{brackets} ? "[" . $switch . "]" : $switch;
1650 $result .= sprintf("%s%-" . $switchWidth . "s %s\n", $indent, $switchName, $switches{$switch});
1656 sub setUpGuardMallocIfNeeded
1662 if (!defined($shouldUseGuardMalloc)) {
1663 $shouldUseGuardMalloc = checkForArgumentAndRemoveFromARGV("-g") || checkForArgumentAndRemoveFromARGV("--guard-malloc");
1666 if ($shouldUseGuardMalloc) {
1667 appendToEnvironmentVariableList("DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1668 appendToEnvironmentVariableList("__XPC_DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1672 sub relativeScriptsDir()
1674 my $scriptDir = File::Spec->catpath("", File::Spec->abs2rel($FindBin::Bin, getcwd()), "");
1675 if ($scriptDir eq "") {
1683 my $relativeScriptsPath = relativeScriptsDir();
1684 if (isGtk() || isWPE()) {
1685 if (inFlatpakSandbox()) {
1686 return "Tools/Scripts/run-minibrowser";
1688 return "$relativeScriptsPath/run-minibrowser";
1689 } elsif (isAppleWebKit()) {
1690 return "$relativeScriptsPath/run-safari";
1696 if (isGtk() || isWPE()) {
1697 return "MiniBrowser";
1698 } elsif (isAppleMacWebKit()) {
1700 } elsif (isAppleWinWebKit()) {
1701 return "MiniBrowser";
1705 sub checkRequiredSystemConfig
1708 chomp(my $productVersion = `sw_vers -productVersion`);
1709 if (eval "v$productVersion" lt v10.10.5) {
1710 print "*************************************************************\n";
1711 print "OS X Yosemite v10.10.5 or later is required to build WebKit.\n";
1712 print "You have " . $productVersion . ", thus the build will most likely fail.\n";
1713 print "*************************************************************\n";
1715 determineXcodeVersion();
1716 if (eval "v$xcodeVersion" lt v7.0) {
1717 print "*************************************************************\n";
1718 print "Xcode 7.0 or later is required to build WebKit.\n";
1719 print "You have an earlier version of Xcode, thus the build will\n";
1720 print "most likely fail. The latest Xcode is available from the App Store.\n";
1721 print "*************************************************************\n";
1726 sub determineWindowsSourceDir()
1728 return if $windowsSourceDir;
1729 $windowsSourceDir = sourceDir();
1730 chomp($windowsSourceDir = `cygpath -w '$windowsSourceDir'`) if isCygwin();
1733 sub windowsSourceDir()
1735 determineWindowsSourceDir();
1736 return $windowsSourceDir;
1739 sub windowsSourceSourceDir()
1741 return File::Spec->catdir(windowsSourceDir(), "Source");
1744 sub windowsLibrariesDir()
1746 return File::Spec->catdir(windowsSourceDir(), "WebKitLibraries", "win");
1749 sub windowsOutputDir()
1751 return File::Spec->catdir(windowsSourceDir(), "WebKitBuild");
1757 my $cmd = "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\" /v \"$font\" 2>&1";
1762 sub checkInstalledTools()
1764 # environment variables. Avoid until this is corrected.
1765 my $pythonVer = `python --version 2>&1`;
1766 die "You must have Python installed to build WebKit.\n" if ($?);
1768 # cURL 7.34.0 has a bug that prevents authentication with opensource.apple.com (and other things using SSL3).
1769 my $curlVer = `curl --version 2> NUL`;
1770 if (!$? and $curlVer =~ "(.*curl.*)") {
1772 if ($curlVer =~ /libcurl\/7\.34\.0/) {
1773 print "cURL version 7.34.0 has a bug that prevents authentication with SSL v2 or v3.\n";
1774 print "cURL 7.33.0 is known to work. The cURL projects is preparing an update to\n";
1775 print "correct this problem.\n\n";
1776 die "Please install a working cURL and try again.\n";
1780 # MathML requires fonts that may not ship with Windows.
1781 # Warn the user if they are missing.
1782 my @fonts = ('Cambria & Cambria Math (TrueType)', 'LatinModernMath-Regular (TrueType)', 'STIXMath-Regular (TrueType)');
1784 foreach my $font (@fonts) {
1785 push @missing, $font if not fontExists($font);
1788 if (scalar @missing > 0) {
1789 print "*************************************************************\n";
1790 print "Mathematical fonts, such as Latin Modern Math are needed to\n";
1791 print "use the MathML feature. You do not appear to have these fonts\n";
1792 print "on your system.\n\n";
1793 print "You can download a suitable set of fonts from the following URL:\n";
1794 print "https://trac.webkit.org/wiki/MathML/Fonts\n";
1795 print "*************************************************************\n";
1798 print "Installed tools are correct for the WebKit build.\n";
1801 sub setupAppleWinEnv()
1803 return unless isAppleWinWebKit();
1805 checkInstalledTools();
1807 if (isWindowsNT()) {
1808 my $restartNeeded = 0;
1809 my %variablesToSet = ();
1811 # FIXME: We should remove this explicit version check for cygwin once we stop supporting Cygwin 1.7.9 or older versions.
1812 # https://bugs.webkit.org/show_bug.cgi?id=85791
1813 my $uname_version = (POSIX::uname())[2];
1814 $uname_version =~ s/\(.*\)//; # Remove the trailing cygwin version, if any.
1815 $uname_version =~ s/\-.*$//; # Remove trailing dash-version content, if any
1816 if (version->parse($uname_version) < version->parse("1.7.10")) {
1817 # Setting the environment variable 'CYGWIN' to 'tty' makes cygwin enable extra support (i.e., termios)
1818 # for UNIX-like ttys in the Windows console
1819 $variablesToSet{CYGWIN} = "tty" unless $ENV{CYGWIN};
1822 # Those environment variables must be set to be able to build inside Visual Studio.
1823 $variablesToSet{WEBKIT_LIBRARIES} = windowsLibrariesDir() unless $ENV{WEBKIT_LIBRARIES};
1824 $variablesToSet{WEBKIT_OUTPUTDIR} = windowsOutputDir() unless $ENV{WEBKIT_OUTPUTDIR};
1825 $variablesToSet{MSBUILDDISABLENODEREUSE} = "1" unless $ENV{MSBUILDDISABLENODEREUSE};
1826 $variablesToSet{_IsNativeEnvironment} = "true" unless $ENV{_IsNativeEnvironment};
1827 $variablesToSet{PreferredToolArchitecture} = "x64" unless $ENV{PreferredToolArchitecture};
1829 foreach my $variable (keys %variablesToSet) {
1830 print "Setting the Environment Variable '" . $variable . "' to '" . $variablesToSet{$variable} . "'\n\n";
1831 my $ret = system "setx", $variable, $variablesToSet{$variable};
1833 system qw(regtool -s set), '\\HKEY_CURRENT_USER\\Environment\\' . $variable, $variablesToSet{$variable};
1835 $restartNeeded ||= $variable eq "WEBKIT_LIBRARIES" || $variable eq "WEBKIT_OUTPUTDIR";
1838 if ($restartNeeded) {
1839 print "Please restart your computer before attempting to build inside Visual Studio.\n\n";
1842 if (!defined $ENV{'WEBKIT_LIBRARIES'} || !$ENV{'WEBKIT_LIBRARIES'}) {
1843 print "Warning: You must set the 'WebKit_Libraries' environment variable\n";
1844 print " to be able build WebKit from within Visual Studio 2017 and newer.\n";
1845 print " Make sure that 'WebKit_Libraries' points to the\n";
1846 print " 'WebKitLibraries/win' directory, not the 'WebKitLibraries/' directory.\n\n";
1848 if (!defined $ENV{'WEBKIT_OUTPUTDIR'} || !$ENV{'WEBKIT_OUTPUTDIR'}) {
1849 print "Warning: You must set the 'WebKit_OutputDir' environment variable\n";
1850 print " to be able build WebKit from within Visual Studio 2017 and newer.\n\n";
1852 if (!defined $ENV{'MSBUILDDISABLENODEREUSE'} || !$ENV{'MSBUILDDISABLENODEREUSE'}) {
1853 print "Warning: You should set the 'MSBUILDDISABLENODEREUSE' environment variable to '1'\n";
1854 print " to avoid periodic locked log files when building.\n\n";
1857 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1858 if (isWin64() and !$ENV{'WEBKIT_64_SUPPORT'}) {
1859 print "Warning: You must set the 'WEBKIT_64_SUPPORT' environment variable\n";
1860 print " to be able run WebKit or JavaScriptCore tests.\n\n";
1864 sub setupCygwinEnv()
1866 return if !isAnyWindows();
1867 return if $vcBuildPath;
1869 my $programFilesPath = programFilesPath();
1870 my $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE devenv.com));
1871 if (!-e $visualStudioPath) {
1872 # Visual Studio not found, try VC++ Express
1873 $visualStudioPath = File::Spec->catfile(visualStudioInstallDir(), qw(Common7 IDE WDExpress.exe));
1874 if (! -e $visualStudioPath) {
1875 print "*************************************************************\n";
1876 print "Cannot find '$visualStudioPath'\n";
1877 print "Please execute the file 'vcvars32.bat' from\n";
1878 print "your Visual Studio 2017 installation\n";
1879 print "to setup the necessary environment variables.\n";
1880 print "*************************************************************\n";
1883 $willUseVCExpressWhenBuilding = 1;
1886 print "Building results into: ", baseProductDir(), "\n";
1887 print "WEBKIT_OUTPUTDIR is set to: ", $ENV{"WEBKIT_OUTPUTDIR"}, "\n";
1888 print "WEBKIT_LIBRARIES is set to: ", $ENV{"WEBKIT_LIBRARIES"}, "\n";
1889 # FIXME (125180): Remove the following temporary 64-bit support once official support is available.
1890 print "WEBKIT_64_SUPPORT is set to: ", $ENV{"WEBKIT_64_SUPPORT"}, "\n" if isWin64();
1892 # We will actually use MSBuild to build WebKit, but we need to find the Visual Studio install (above) to make
1893 # sure we use the right options.
1894 $vcBuildPath = File::Spec->catfile(msBuildInstallDir(), qw(MSBuild.exe));
1895 if (! -e $vcBuildPath) {
1896 print "*************************************************************\n";
1897 print "Cannot find '$vcBuildPath'\n";
1898 print "Please make sure execute that the Microsoft .NET Framework SDK\n";
1899 print "is installed on this machine.\n";
1900 print "*************************************************************\n";
1905 sub dieIfWindowsPlatformSDKNotInstalled
1907 my $registry32Path = "/proc/registry/";
1908 my $registry64Path = "/proc/registry64/";
1909 my @windowsPlatformSDKRegistryEntries = (
1910 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0A",
1911 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v8.0",
1912 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.1A",
1913 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Microsoft SDKs/Windows/v7.0A",
1914 "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/MicrosoftSDK/InstalledSDKs/D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1",
1917 # FIXME: It would be better to detect whether we are using 32- or 64-bit Windows
1918 # and only check the appropriate entry. But for now we just blindly check both.
1919 my $recommendedPlatformSDK = $windowsPlatformSDKRegistryEntries[0];
1921 while (@windowsPlatformSDKRegistryEntries) {
1922 my $windowsPlatformSDKRegistryEntry = shift @windowsPlatformSDKRegistryEntries;
1923 return if (-e $registry32Path . $windowsPlatformSDKRegistryEntry) || (-e $registry64Path . $windowsPlatformSDKRegistryEntry);
1926 print "*************************************************************\n";
1927 print "Cannot find registry entry '$recommendedPlatformSDK'.\n";
1928 print "Please download and install the Microsoft Windows SDK\n";
1929 print "from <http://www.microsoft.com/en-us/download/details.aspx?id=8279>.\n\n";
1930 print "Then follow step 2 in the Windows section of the \"Installing Developer\n";
1931 print "Tools\" instructions at <http://www.webkit.org/building/tools.html>.\n";
1932 print "*************************************************************\n";
1936 sub buildXCodeProject($$@)
1938 my ($project, $clean, @extraOptions) = @_;
1941 push(@extraOptions, "-alltargets");
1942 push(@extraOptions, "clean");
1945 chomp($ENV{DSYMUTIL_NUM_THREADS} = `sysctl -n hw.activecpu`);
1946 return system "xcodebuild", "-project", "$project.xcodeproj", @extraOptions;
1949 sub usingVisualStudioExpress()
1952 return $willUseVCExpressWhenBuilding;
1955 sub buildVisualStudioProject
1957 my ($project, $clean) = @_;
1960 my $config = configurationForVisualStudio();
1962 dieIfWindowsPlatformSDKNotInstalled() if $willUseVCExpressWhenBuilding;
1964 chomp($project = `cygpath -w "$project"`) if isCygwin();
1966 my $action = "/t:build";
1968 $action = "/t:clean";
1971 my $platform = "/p:Platform=" . (isWin64() ? "x64" : "Win32");
1972 my $logPath = File::Spec->catdir($baseProductDir, $configuration);
1973 make_path($logPath) unless -d $logPath or $logPath eq ".";
1975 my $errorLogFile = File::Spec->catfile($logPath, "webkit_errors.log");
1976 chomp($errorLogFile = `cygpath -w "$errorLogFile"`) if isCygwin();
1977 my $errorLogging = "/flp:LogFile=" . $errorLogFile . ";ErrorsOnly";
1979 my $warningLogFile = File::Spec->catfile($logPath, "webkit_warnings.log");
1980 chomp($warningLogFile = `cygpath -w "$warningLogFile"`) if isCygwin();
1981 my $warningLogging = "/flp1:LogFile=" . $warningLogFile . ";WarningsOnly";
1983 my $maxCPUCount = '/maxcpucount:' . numberOfCPUs();
1985 my @command = ($vcBuildPath, "/verbosity:minimal", $project, $action, $config, $platform, "/fl", $errorLogging, "/fl1", $warningLogging, $maxCPUCount);
1986 print join(" ", @command), "\n";
1987 return system @command;
1990 sub getJhbuildPath()
1992 my @jhbuildPath = File::Spec->splitdir(baseProductDir());
1993 if (isGit() && isGitBranchBuild() && gitBranch()) {
1997 push(@jhbuildPath, "DependenciesGTK");
1999 push(@jhbuildPath, "DependenciesWPE");
2001 die "Cannot get JHBuild path for platform that isn't GTK+ or WPE.\n";
2003 return File::Spec->catdir(@jhbuildPath);
2006 sub getFlatpakPath()
2008 my @flatpakBuildPath = File::Spec->splitdir(baseProductDir());
2010 push(@flatpakBuildPath, "GTK");
2012 push(@flatpakBuildPath, "WPE");
2014 die "Cannot get Flatpak path for platform that isn't GTK+ or WPE.\n";
2016 my @configuration = configuration();
2017 push(@flatpakBuildPath, "FlatpakTree$configuration");
2019 return File::Spec->catdir(@flatpakBuildPath);
2022 sub isCachedArgumentfileOutOfDate($@)
2024 my ($filename, $currentContents) = @_;
2026 if (! -e $filename) {
2030 open(CONTENTS_FILE, $filename);
2031 chomp(my $previousContents = <CONTENTS_FILE> || "");
2032 close(CONTENTS_FILE);
2034 if ($previousContents ne $currentContents) {
2035 print "Contents for file $filename have changed.\n";
2036 print "Previous contents were: $previousContents\n\n";
2037 print "New contents are: $currentContents\n";
2044 sub inFlatpakSandbox()
2046 if (-f "/usr/manifest.json") {
2056 my @command = (File::Spec->catfile(sourceDir(), "Tools", "Scripts", "webkit-flatpak"));
2057 exec @command, argumentsForConfiguration(), "--command", @_, argumentsForConfiguration(), @ARGV or die;
2060 sub runInFlatpakIfAvalaible(@)
2062 if (inFlatpakSandbox()) {
2066 my @command = (File::Spec->catfile(sourceDir(), "Tools", "Scripts", "webkit-flatpak"));
2067 if (system(@command, "--avalaible") != 0) {
2071 if (! -e getFlatpakPath()) {
2078 sub wrapperPrefixIfNeeded()
2081 if (isAnyWindows() || isJSCOnly()) {
2084 if (isAppleCocoaWebKit()) {
2087 if (-e getJhbuildPath()) {
2088 my @prefix = (File::Spec->catfile(sourceDir(), "Tools", "jhbuild", "jhbuild-wrapper"));
2090 push(@prefix, "--gtk");
2092 push(@prefix, "--wpe");
2094 push(@prefix, "run");
2102 sub shouldUseJhbuild()
2104 return ((isGtk() or isWPE()) and -e getJhbuildPath());
2107 sub shouldUseFlatpak()
2109 return ((isGtk() or isWPE()) and ! inFlatpakSandbox() and -e getFlatpakPath());
2112 sub cmakeCachePath()
2114 return File::Spec->catdir(baseProductDir(), configuration(), "CMakeCache.txt");
2117 sub cmakeFilesPath()
2119 return File::Spec->catdir(baseProductDir(), configuration(), "CMakeFiles");
2122 sub shouldRemoveCMakeCache(@)
2124 my ($cacheFilePath, @buildArgs) = @_;
2126 # We check this first, because we always want to create this file for a fresh build.
2127 my $productDir = File::Spec->catdir(baseProductDir(), configuration());
2128 my $optionsCache = File::Spec->catdir($productDir, "build-webkit-options.txt");
2129 my $joinedBuildArgs = join(" ", @buildArgs);
2130 if (isCachedArgumentfileOutOfDate($optionsCache, $joinedBuildArgs)) {
2131 File::Path::mkpath($productDir) unless -d $productDir;
2132 open(CACHED_ARGUMENTS, ">", $optionsCache);
2133 print CACHED_ARGUMENTS $joinedBuildArgs;
2134 close(CACHED_ARGUMENTS);
2139 my $cmakeCache = cmakeCachePath();
2140 unless (-e $cmakeCache) {
2144 my $cacheFileModifiedTime = stat($cmakeCache)->mtime;
2145 my $platformConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "Options" . cmakeBasedPortName() . ".cmake");
2146 if ($cacheFileModifiedTime < stat($platformConfiguration)->mtime) {
2150 my $globalConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "OptionsCommon.cmake");
2151 if ($cacheFileModifiedTime < stat($globalConfiguration)->mtime) {
2155 # FIXME: This probably does not work as expected, or the next block to
2156 # delete the images subdirectory would not be here. Directory mtime does not
2157 # percolate upwards when files are added or removed from subdirectories.
2158 my $inspectorUserInterfaceDirectory = File::Spec->catdir(sourceDir(), "Source", "WebInspectorUI", "UserInterface");
2159 if ($cacheFileModifiedTime < stat($inspectorUserInterfaceDirectory)->mtime) {
2163 my $inspectorImageDirectory = File::Spec->catdir(sourceDir(), "Source", "WebInspectorUI", "UserInterface", "Images");
2164 if ($cacheFileModifiedTime < stat($inspectorImageDirectory)->mtime) {
2168 if(isAnyWindows()) {
2169 my $winConfiguration = File::Spec->catdir(sourceDir(), "Source", "cmake", "OptionsWin.cmake");
2170 if ($cacheFileModifiedTime < stat($winConfiguration)->mtime) {
2178 sub removeCMakeCache(@)
2180 my (@buildArgs) = @_;
2181 if (shouldRemoveCMakeCache(@buildArgs)) {
2182 my $cmakeCache = cmakeCachePath();
2183 my $cmakeFiles = cmakeFilesPath();
2184 unlink($cmakeCache) if -e $cmakeCache;
2185 rmtree($cmakeFiles) if -d $cmakeFiles;
2191 if (!defined($shouldNotUseNinja)) {
2192 $shouldNotUseNinja = checkForArgumentAndRemoveFromARGV("--no-ninja");
2195 if ($shouldNotUseNinja) {
2199 if (isAppleCocoaWebKit()) {
2200 my $devnull = File::Spec->devnull();
2201 if (exitStatus(system("xcrun -find ninja >$devnull 2>&1")) == 0) {
2206 # Test both ninja and ninja-build. Fedora uses ninja-build and has patched CMake to also call ninja-build.
2207 return commandExists("ninja") || commandExists("ninja-build");
2210 sub canUseEclipseNinjaGenerator(@)
2212 # Check that eclipse and eclipse Ninja generator is installed
2213 my $devnull = File::Spec->devnull();
2214 return commandExists("eclipse") && exitStatus(system("cmake -N -G 'Eclipse CDT4 - Ninja' >$devnull 2>&1")) == 0;
2217 sub cmakeGeneratedBuildfile(@)
2219 my ($willUseNinja) = @_;
2220 if ($willUseNinja) {
2221 return File::Spec->catfile(baseProductDir(), configuration(), "build.ninja")
2222 } elsif (isAnyWindows()) {
2223 return File::Spec->catfile(baseProductDir(), configuration(), "WebKit.sln")
2225 return File::Spec->catfile(baseProductDir(), configuration(), "Makefile")
2229 sub generateBuildSystemFromCMakeProject
2231 my ($prefixPath, @cmakeArgs) = @_;
2232 my $config = configuration();
2233 my $port = cmakeBasedPortName();
2234 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2235 File::Path::mkpath($buildPath) unless -d $buildPath;
2236 my $originalWorkingDirectory = getcwd();
2237 chdir($buildPath) or die;
2239 # We try to be smart about when to rerun cmake, so that we can have faster incremental builds.
2240 my $willUseNinja = canUseNinja();
2241 if (-e cmakeCachePath() && -e cmakeGeneratedBuildfile($willUseNinja)) {
2246 push @args, "-DPORT=\"$port\"";
2247 push @args, "-DCMAKE_INSTALL_PREFIX=\"$prefixPath\"" if $prefixPath;
2248 push @args, "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON";
2249 if ($config =~ /release/i) {
2250 push @args, "-DCMAKE_BUILD_TYPE=Release";
2251 } elsif ($config =~ /debug/i) {
2252 push @args, "-DCMAKE_BUILD_TYPE=Debug";
2255 push @args, "-DENABLE_ADDRESS_SANITIZER=ON" if asanIsEnabled();
2257 if ($willUseNinja) {
2259 if (canUseEclipseNinjaGenerator()) {
2260 push @args, "'Eclipse CDT4 - Ninja'";
2262 push @args, "Ninja";
2264 } elsif (isAnyWindows() && isWin64()) {
2265 push @args, '-G "Visual Studio 15 2017 Win64"';
2266 push @args, '-DCMAKE_GENERATOR_TOOLSET="host=x64"';
2268 # Do not show progress of generating bindings in interactive Ninja build not to leave noisy lines on tty
2269 push @args, '-DSHOW_BINDINGS_GENERATION_PROGRESS=1' unless ($willUseNinja && -t STDOUT);
2271 # Some ports have production mode, but build-webkit should always use developer mode.
2272 push @args, "-DDEVELOPER_MODE=ON" if isGtk() || isJSCOnly() || isWPE();
2274 push @args, @cmakeArgs if @cmakeArgs;
2276 my $cmakeSourceDir = isCygwin() ? windowsSourceDir() : sourceDir();
2277 push @args, '"' . $cmakeSourceDir . '"';
2279 # Compiler options to keep floating point values consistent
2280 # between 32-bit and 64-bit architectures.
2281 determineArchitecture();
2282 if ($architecture eq "i686" && !isCrossCompilation() && !isAnyWindows()) {
2283 $ENV{'CXXFLAGS'} = "-march=pentium4 -msse2 -mfpmath=sse " . ($ENV{'CXXFLAGS'} || "");
2286 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2287 # parsed for shell metacharacters.
2288 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2289 my $returnCode = systemVerbose($wrapper . "cmake @args");
2291 chdir($originalWorkingDirectory);
2295 sub buildCMakeGeneratedProject($)
2297 my (@makeArgs) = @_;
2298 my $config = configuration();
2299 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2300 if (! -d $buildPath) {
2301 die "Must call generateBuildSystemFromCMakeProject() before building CMake project.";
2304 if ($ENV{VERBOSE} && canUseNinja()) {
2305 push @makeArgs, "-v";
2306 push @makeArgs, "-d keeprsp" if (version->parse(determineNinjaVersion()) >= version->parse("1.4.0"));
2309 my $command = "cmake";
2310 my @args = ("--build", $buildPath, "--config", $config);
2311 push @args, ("--", @makeArgs) if @makeArgs;
2313 # GTK and JSCOnly can use a build script to preserve colors and pretty-printing.
2314 if ((isGtk() || isJSCOnly()) && -e "$buildPath/build.sh") {
2315 chdir "$buildPath" or die;
2316 $command = "$buildPath/build.sh";
2317 @args = (@makeArgs);
2320 # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2321 # parsed for shell metacharacters. In particular, @makeArgs may contain such metacharacters.
2322 my $wrapper = join(" ", wrapperPrefixIfNeeded()) . " ";
2323 return systemVerbose($wrapper . "$command @args");
2326 sub cleanCMakeGeneratedProject()
2328 my $config = configuration();
2329 my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2330 if (-d $buildPath) {
2331 return systemVerbose("cmake", "--build", $buildPath, "--config", $config, "--target", "clean");
2336 sub buildCMakeProjectOrExit($$$@)
2338 my ($clean, $prefixPath, $makeArgs, @cmakeArgs) = @_;
2341 exit(exitStatus(cleanCMakeGeneratedProject())) if $clean;
2343 if (isGtk() && checkForArgumentAndRemoveFromARGV("--update-gtk")) {
2344 system("perl", "$sourceDir/Tools/Scripts/update-webkitgtk-libs") == 0 or die $!;
2347 if (isWPE() && checkForArgumentAndRemoveFromARGV("--update-wpe")) {
2348 system("perl", "$sourceDir/Tools/Scripts/update-webkitwpe-libs") == 0 or die $!;
2351 $returnCode = exitStatus(generateBuildSystemFromCMakeProject($prefixPath, @cmakeArgs));
2352 exit($returnCode) if $returnCode;
2353 exit 0 if isGenerateProjectOnly();
2355 $returnCode = exitStatus(buildCMakeGeneratedProject($makeArgs));
2356 exit($returnCode) if $returnCode;
2360 sub cmakeArgsFromFeatures(\@;$)
2362 my ($featuresArrayRef, $enableExperimentalFeatures) = @_;
2365 push @args, "-DENABLE_EXPERIMENTAL_FEATURES=ON" if $enableExperimentalFeatures;
2366 foreach (@$featuresArrayRef) {
2367 my $featureName = $_->{define};
2369 my $featureValue = ${$_->{value}}; # Undef to let the build system use its default.
2370 if (defined($featureValue)) {
2371 my $featureEnabled = $featureValue ? "ON" : "OFF";
2372 push @args, "-D$featureName=$featureEnabled";
2380 sub cmakeBasedPortArguments()
2385 sub cmakeBasedPortName()
2387 return ucfirst portName();
2390 sub determineIsCMakeBuild()
2392 return if defined($isCMakeBuild);
2393 $isCMakeBuild = checkForArgumentAndRemoveFromARGV("--cmake");
2398 return 1 unless isAppleCocoaWebKit();
2399 determineIsCMakeBuild();
2400 return $isCMakeBuild;
2403 sub determineIsGenerateProjectOnly()
2405 return if defined($isGenerateProjectOnly);
2406 $isGenerateProjectOnly = checkForArgumentAndRemoveFromARGV("--generate-project-only");
2409 sub isGenerateProjectOnly()
2411 determineIsGenerateProjectOnly();
2412 return $isGenerateProjectOnly;
2417 my ($prompt, $default) = @_;
2418 my $defaultValue = $default ? "[$default]" : "";
2419 print "$prompt $defaultValue: ";
2420 chomp(my $input = <STDIN>);
2421 return $input ? $input : $default;
2424 sub appleApplicationSupportPath
2426 open INSTALL_DIR, "</proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/Apple\ Inc./Apple\ Application\ Support/InstallDir";
2427 my $path = <INSTALL_DIR>;
2428 $path =~ s/[\r\n\x00].*//;
2431 my $unixPath = `cygpath -u '$path'`;
2436 sub setPathForRunningWebKitApp
2440 if (isAnyWindows()) {
2441 my $productBinaryDir = executableProductDir();
2442 if (isAppleWinWebKit()) {
2443 $env->{PATH} = join(':', $productBinaryDir, appleApplicationSupportPath(), $env->{PATH} || "");
2444 } elsif (isWinCairo()) {
2445 my $winCairoBin = sourceDir() . "/WebKitLibraries/win/" . (isWin64() ? "bin64/" : "bin32/");
2446 my $gstreamerBin = isWin64() ? $ENV{"GSTREAMER_1_0_ROOT_X86_64"} . "bin" : $ENV{"GSTREAMER_1_0_ROOT_X86"} . "bin";
2447 $env->{PATH} = join(':', $productBinaryDir, $winCairoBin, $gstreamerBin, $env->{PATH} || "");
2452 sub printHelpAndExitForRunAndDebugWebKitAppIfNeeded
2454 return unless checkForArgumentAndRemoveFromARGV("--help");
2457 Usage: @{[basename($0)]} [options] [args ...]
2458 --help Show this help message
2459 --no-saved-state Launch the application without state restoration
2461 Options specific to macOS:
2462 -g|--guard-malloc Enable Guard Malloc
2463 --lang=LANGUAGE Use a specific language instead of system language.
2464 This accepts a language name (German) or a language code (de, ar, pt_BR, etc).
2465 --locale=LOCALE Use a specific locale instead of the system region.
2471 sub argumentsForRunAndDebugMacWebKitApp()
2474 if (checkForArgumentAndRemoveFromARGV("--no-saved-state")) {
2475 push @args, ("-ApplePersistenceIgnoreStateQuietly", "YES");
2476 # FIXME: Don't set ApplePersistenceIgnoreState once all supported OS versions respect ApplePersistenceIgnoreStateQuietly (rdar://15032886).
2477 push @args, ("-ApplePersistenceIgnoreState", "YES");
2481 if (checkForArgumentAndRemoveFromARGVGettingValue("--lang", \$lang)) {
2482 push @args, ("-AppleLanguages", "(" . $lang . ")");
2486 if (checkForArgumentAndRemoveFromARGVGettingValue("--locale", \$locale)) {
2487 push @args, ("-AppleLocale", $locale);
2490 unshift @args, @ARGV;
2495 sub setupMacWebKitEnvironment($)
2497 my ($dyldFrameworkPath) = @_;
2499 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2501 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2502 prependToEnvironmentVariableList("__XPC_DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2503 prependToEnvironmentVariableList("DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2504 prependToEnvironmentVariableList("__XPC_DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2505 $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2507 setUpGuardMallocIfNeeded();
2510 sub setupIOSWebKitEnvironment($)
2512 my ($dyldFrameworkPath) = @_;
2513 $dyldFrameworkPath = File::Spec->rel2abs($dyldFrameworkPath);
2515 prependToEnvironmentVariableList("DYLD_FRAMEWORK_PATH", $dyldFrameworkPath);
2516 prependToEnvironmentVariableList("DYLD_LIBRARY_PATH", $dyldFrameworkPath);
2518 setUpGuardMallocIfNeeded();
2521 sub iosSimulatorApplicationsPath()
2523 my $iphoneOSPlatformPath = sdkPlatformDirectory("iphoneos");
2524 return File::Spec->catdir($iphoneOSPlatformPath, "Developer", "Library", "CoreSimulator", "Profiles", "Runtimes", "iOS.simruntime", "Contents", "Resources", "RuntimeRoot", "Applications");
2527 sub installedMobileSafariBundle()
2529 return File::Spec->catfile(iosSimulatorApplicationsPath(), "MobileSafari.app");
2532 sub mobileSafariBundle()
2534 determineConfigurationProductDir();
2536 # Use MobileSafari.app in product directory if present.
2537 if (isIOSWebKit() && -d "$configurationProductDir/MobileSafari.app") {
2538 return "$configurationProductDir/MobileSafari.app";
2540 return installedMobileSafariBundle();
2543 sub plistPathFromBundle($)
2545 my ($appBundle) = @_;
2546 return "$appBundle/Info.plist" if -f "$appBundle/Info.plist"; # iOS app bundle
2547 return "$appBundle/Contents/Info.plist" if -f "$appBundle/Contents/Info.plist"; # Mac app bundle
2551 sub appIdentifierFromBundle($)
2553 my ($appBundle) = @_;
2554 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2555 chomp(my $bundleIdentifier = `defaults read '$plistPath' CFBundleIdentifier 2> /dev/null`);
2556 return $bundleIdentifier;
2559 sub appDisplayNameFromBundle($)
2561 my ($appBundle) = @_;
2562 my $plistPath = File::Spec->rel2abs(plistPathFromBundle($appBundle)); # defaults(1) will complain if the specified path is not absolute.
2563 chomp(my $bundleDisplayName = `defaults read '$plistPath' CFBundleDisplayName 2> /dev/null`);
2564 return $bundleDisplayName;
2567 sub waitUntilIOSSimulatorDeviceIsInState($$)
2569 my ($deviceUDID, $waitUntilState) = @_;
2570 my $device = iosSimulatorDeviceByUDID($deviceUDID);
2571 # FIXME: We should add a maximum time limit to wait here.
2572 while ($device->{state} ne $waitUntilState) {
2573 usleep(500 * 1000); # Waiting 500ms between file system polls does not make script run-safari feel sluggish.
2574 $device = iosSimulatorDeviceByUDID($deviceUDID);
2578 sub waitUntilProcessNotRunning($)
2581 while (system("/bin/ps -eo pid,comm | /usr/bin/grep '$process\$'") == 0) {
2586 sub shutDownIOSSimulatorDevice($)
2588 my ($simulatorDevice) = @_;
2589 system("xcrun --sdk iphonesimulator simctl shutdown $simulatorDevice->{UDID} > /dev/null 2>&1");
2592 sub restartIOSSimulatorDevice($)
2594 my ($simulatorDevice) = @_;
2595 shutDownIOSSimulatorDevice($simulatorDevice);
2597 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "boot", $simulatorDevice->{UDID})) == 0 or die "Failed to boot simulator device $simulatorDevice->{UDID}";
2600 sub relaunchIOSSimulator($)
2602 my ($simulatedDevice) = @_;
2603 quitIOSSimulator($simulatedDevice->{UDID});
2605 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2606 chomp(my $developerDirectory = $ENV{DEVELOPER_DIR} || `xcode-select --print-path`);
2607 my $iosSimulatorPath = File::Spec->catfile($developerDirectory, "Applications", "Simulator.app");
2608 system("open", "-a", $iosSimulatorPath, "--args", "-CurrentDeviceUDID", $simulatedDevice->{UDID}) == 0 or die "Failed to open $iosSimulatorPath: $!";
2610 waitUntilIOSSimulatorDeviceIsInState($simulatedDevice->{UDID}, SIMULATOR_DEVICE_STATE_BOOTED);
2611 waitUntilProcessNotRunning("com.apple.datamigrator");
2614 sub quitIOSSimulator(;$)
2616 my ($waitForShutdownOfSimulatedDeviceUDID) = @_;
2617 # FIXME: <rdar://problem/20916140> Switch to using CoreSimulator.framework for launching and quitting iOS Simulator
2618 if (exitStatus(system {"osascript"} "osascript", "-e", 'tell application id "com.apple.iphonesimulator" to quit')) {
2619 # osascript returns a non-zero exit status if Simulator.app is not registered in LaunchServices.
2623 if (!defined($waitForShutdownOfSimulatedDeviceUDID)) {
2626 # FIXME: We assume that $waitForShutdownOfSimulatedDeviceUDID was not booted using the simctl command line tool.
2627 # Otherwise we will spin indefinitely since quiting the iOS Simulator will not shutdown this device. We
2628 # should add a maximum time limit to wait for a device to shutdown and either return an error or die()
2629 # on expiration of the time limit.
2630 waitUntilIOSSimulatorDeviceIsInState($waitForShutdownOfSimulatedDeviceUDID, SIMULATOR_DEVICE_STATE_SHUTDOWN);
2633 sub iosSimulatorDeviceByName($)
2635 my ($simulatorName) = @_;
2636 my $simulatorRuntime = iosSimulatorRuntime();
2637 my @devices = iOSSimulatorDevices();
2638 for my $device (@devices) {
2639 if ($device->{name} eq $simulatorName && $device->{runtime} eq $simulatorRuntime) {
2646 sub iosSimulatorDeviceByUDID($)
2648 my ($simulatedDeviceUDID) = @_;
2649 my $devicePlistPath = File::Spec->catfile(iOSSimulatorDevicesPath(), $simulatedDeviceUDID, "device.plist");
2650 if (!-f $devicePlistPath) {
2653 # FIXME: We should parse the device.plist file ourself and map the dictionary keys in it to known
2654 # dictionary keys so as to decouple our representation of the plist from the actual structure
2655 # of the plist, which may change.
2656 eval "require Foundation";
2657 return Foundation::perlRefFromObjectRef(NSDictionary->dictionaryWithContentsOfFile_($devicePlistPath));
2660 sub iosSimulatorRuntime()
2662 my $xcodeSDKVersion = xcodeSDKVersion();
2663 $xcodeSDKVersion =~ s/\./-/;
2664 return "com.apple.CoreSimulator.SimRuntime.iOS-$xcodeSDKVersion";
2667 sub findOrCreateSimulatorForIOSDevice($)
2669 my ($simulatorNameSuffix) = @_;
2671 my $simulatorDeviceType;
2672 if (architecture() eq "x86_64") {
2673 $simulatorName = "iPhone 5s " . $simulatorNameSuffix;
2674 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5s";
2676 $simulatorName = "iPhone 5 " . $simulatorNameSuffix;
2677 $simulatorDeviceType = "com.apple.CoreSimulator.SimDeviceType.iPhone-5";
2679 my $simulatedDevice = iosSimulatorDeviceByName($simulatorName);
2680 return $simulatedDevice if $simulatedDevice;
2681 return createiOSSimulatorDevice($simulatorName, $simulatorDeviceType, iosSimulatorRuntime());
2684 sub isIOSSimulatorSystemInstalledApp($)
2686 my ($appBundle) = @_;
2687 my $simulatorApplicationsPath = realpath(iosSimulatorApplicationsPath());
2688 return substr(realpath($appBundle), 0, length($simulatorApplicationsPath)) eq $simulatorApplicationsPath;
2691 sub hasUserInstalledAppInSimulatorDevice($$)
2693 my ($appIdentifier, $simulatedDeviceUDID) = @_;
2694 my $userInstalledAppPath = File::Spec->catfile($ENV{HOME}, "Library", "Developer", "CoreSimulator", "Devices", $simulatedDeviceUDID, "data", "Containers", "Bundle", "Application");
2695 if (!-d $userInstalledAppPath) {
2696 return 0; # No user installed apps.
2698 local @::userInstalledAppBundles;
2699 my $wantedFunction = sub {
2702 # Ignore hidden files and directories.
2703 if ($file =~ /^\../) {
2704 $File::Find::prune = 1;
2708 return if !-d $file || $file !~ /\.app$/;
2709 push @::userInstalledAppBundles, $File::Find::name;
2710 $File::Find::prune = 1; # Do not traverse contents of app bundle.
2712 find($wantedFunction, $userInstalledAppPath);
2713 for my $userInstalledAppBundle (@::userInstalledAppBundles) {
2714 if (appIdentifierFromBundle($userInstalledAppBundle) eq $appIdentifier) {
2715 return 1; # Has user installed app.
2718 return 0; # Does not have user installed app.
2721 sub isSimulatorDeviceBooted($)
2723 my ($simulatedDeviceUDID) = @_;
2724 my $device = iosSimulatorDeviceByUDID($simulatedDeviceUDID);
2725 return $device && $device->{state} eq SIMULATOR_DEVICE_STATE_BOOTED;
2728 sub runIOSWebKitAppInSimulator($;$)
2730 my ($appBundle, $simulatorOptions) = @_;
2731 my $productDir = productDir();
2732 my $appDisplayName = appDisplayNameFromBundle($appBundle);
2733 my $appIdentifier = appIdentifierFromBundle($appBundle);
2734 my $simulatedDevice = findOrCreateSimulatorForIOSDevice(SIMULATOR_DEVICE_SUFFIX_FOR_WEBKIT_DEVELOPMENT);
2735 my $simulatedDeviceUDID = $simulatedDevice->{UDID};
2737 my $willUseSystemInstalledApp = isIOSSimulatorSystemInstalledApp($appBundle);
2738 if ($willUseSystemInstalledApp) {
2739 if (hasUserInstalledAppInSimulatorDevice($appIdentifier, $simulatedDeviceUDID)) {
2740 # Restore the system-installed app in the simulator device corresponding to $appBundle as it
2741 # was previously overwritten with a custom built version of the app.
2742 # FIXME: Only restore the system-installed version of the app instead of erasing all contents and settings.
2743 print "Quitting iOS Simulator...\n";
2744 quitIOSSimulator($simulatedDeviceUDID);
2745 print "Erasing contents and settings for simulator device \"$simulatedDevice->{name}\".\n";
2746 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "erase", $simulatedDeviceUDID)) == 0 or die;
2748 # FIXME: We assume that if $simulatedDeviceUDID is not booted then iOS Simulator is not open. However
2749 # $simulatedDeviceUDID may have been booted using the simctl command line tool. If $simulatedDeviceUDID
2750 # was booted using simctl then we should shutdown the device and launch iOS Simulator to boot it again.
2751 if (!isSimulatorDeviceBooted($simulatedDeviceUDID)) {
2752 print "Launching iOS Simulator...\n";
2753 relaunchIOSSimulator($simulatedDevice);
2756 # FIXME: We should killall(1) any running instances of $appBundle before installing it to ensure
2757 # that simctl launch opens the latest installed version of the app. For now we quit and
2758 # launch the iOS Simulator again to ensure there are no running instances of $appBundle.
2759 print "Quitting and launching iOS Simulator...\n";
2760 relaunchIOSSimulator($simulatedDevice);
2762 print "Installing $appBundle.\n";
2763 # Install custom built app, overwriting an app with the same app identifier if one exists.
2764 exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "install", $simulatedDeviceUDID, $appBundle)) == 0 or die;
2768 $simulatorOptions = {} unless $simulatorOptions;
2771 %simulatorENV = %{$simulatorOptions->{applicationEnvironment}} if $simulatorOptions->{applicationEnvironment};
2773 local %ENV; # Shadow global-scope %ENV so that changes to it will not be seen outside of this scope.
2774 setupIOSWebKitEnvironment($productDir);
2775 %simulatorENV = %ENV;
2777 my $applicationArguments = \@ARGV;
2778 $applicationArguments = $simulatorOptions->{applicationArguments} if $simulatorOptions && $simulatorOptions->{applicationArguments};
2780 # Prefix the environment variables with SIMCTL_CHILD_ per `xcrun simctl help launch`.
2781 foreach my $key (keys %simulatorENV) {
2782 $ENV{"SIMCTL_CHILD_$key"} = $simulatorENV{$key};
2785 print "Starting $appDisplayName with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2786 return exitStatus(system("xcrun", "--sdk", "iphonesimulator", "simctl", "launch", $simulatedDeviceUDID, $appIdentifier, @$applicationArguments));
2789 sub runIOSWebKitApp($)
2791 my ($appBundle) = @_;
2792 if (willUseIOSDeviceSDK()) {
2793 die "Only running Safari in iOS Simulator is supported now.";
2795 if (willUseIOSSimulatorSDK()) {
2796 return runIOSWebKitAppInSimulator($appBundle);
2798 die "Not using an iOS SDK."
2801 sub archCommandLineArgumentsForRestrictedEnvironmentVariables()
2804 foreach my $key (keys(%ENV)) {
2805 if ($key =~ /^DYLD_/) {
2806 push @arguments, "-e", "$key=$ENV{$key}";
2812 sub runMacWebKitApp($;$)
2814 my ($appPath, $useOpenCommand) = @_;
2815 my $productDir = productDir();
2816 print "Starting @{[basename($appPath)]} with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2819 setupMacWebKitEnvironment($productDir);
2821 if (defined($useOpenCommand) && $useOpenCommand == USE_OPEN_COMMAND) {
2822 return system("open", "-W", "-a", $appPath, "--args", argumentsForRunAndDebugMacWebKitApp());
2824 if (architecture()) {
2825 return system "arch", "-" . architecture(), archCommandLineArgumentsForRestrictedEnvironmentVariables(), $appPath, argumentsForRunAndDebugMacWebKitApp();
2827 return system { $appPath } $appPath, argumentsForRunAndDebugMacWebKitApp();
2830 sub execMacWebKitAppForDebugging($)
2833 my $architectureSwitch = "--arch";
2834 my $argumentsSeparator = "--";
2836 my $debuggerPath = `xcrun -find lldb`;
2837 chomp $debuggerPath;
2838 die "Can't find the lldb executable.\n" unless -x $debuggerPath;
2840 my $productDir = productDir();
2841 setupMacWebKitEnvironment($productDir);
2843 my @architectureFlags = ($architectureSwitch, architecture());
2844 print "Starting @{[basename($appPath)]} under lldb with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2845 exec { $debuggerPath } $debuggerPath, @architectureFlags, $argumentsSeparator, $appPath, argumentsForRunAndDebugMacWebKitApp() or die;
2850 if (isAppleMacWebKit()) {
2852 execMacWebKitAppForDebugging(safariPath());
2855 return 1; # Unsupported platform; can't debug Safari on this platform.
2860 if (isIOSWebKit()) {
2861 return runIOSWebKitApp(mobileSafariBundle());
2864 if (isAppleMacWebKit()) {
2865 return runMacWebKitApp(safariPath());
2868 if (isAppleWinWebKit()) {
2870 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2871 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2874 return 1; # Unsupported platform; can't run Safari on this platform.
2879 if (isAppleMacWebKit()) {
2880 return runMacWebKitApp(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2882 if (isAppleWinWebKit()) {
2883 my $webKitLauncherPath = File::Spec->catfile(executableProductDir(), "MiniBrowser.exe");
2884 return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2889 sub debugMiniBrowser
2891 if (isAppleMacWebKit()) {
2892 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2898 sub runWebKitTestRunner
2900 if (isAppleMacWebKit()) {
2901 return runMacWebKitApp(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2907 sub debugWebKitTestRunner
2909 if (isAppleMacWebKit()) {
2910 execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2916 sub readRegistryString
2918 my ($valueName) = @_;
2919 chomp(my $string = `regtool --wow32 get "$valueName"`);
2923 sub writeRegistryString
2925 my ($valueName, $string) = @_;
2927 my $error = system "regtool", "--wow32", "set", "-s", $valueName, $string;
2929 # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
2930 # return a successful exit code. So we double-check here that the value we tried to write to the
2931 # registry was really written.
2932 return !$error && readRegistryString($valueName) eq $string;
2935 sub formatBuildTime($)
2937 my ($buildTime) = @_;
2939 my $buildHours = int($buildTime / 3600);
2940 my $buildMins = int(($buildTime - $buildHours * 3600) / 60);
2941 my $buildSecs = $buildTime - $buildHours * 3600 - $buildMins * 60;
2944 return sprintf("%dh:%02dm:%02ds", $buildHours, $buildMins, $buildSecs);
2946 return sprintf("%02dm:%02ds", $buildMins, $buildSecs);
2949 sub runSvnUpdateAndResolveChangeLogs(@)
2951 my @svnOptions = @_;
2952 my $openCommand = "svn update " . join(" ", @svnOptions);
2953 open my $update, "$openCommand |" or die "cannot execute command $openCommand";
2954 my @conflictedChangeLogs;
2955 while (my $line = <$update>) {
2957 $line =~ m/^C\s+(.+?)[\r\n]*$/;
2959 my $filename = normalizePath($1);
2960 push @conflictedChangeLogs, $filename if basename($filename) eq "ChangeLog";
2963 close $update or die;
2965 if (@conflictedChangeLogs) {
2966 print "Attempting to merge conflicted ChangeLogs.\n";
2967 my $resolveChangeLogsPath = File::Spec->catfile(sourceDir(), "Tools", "Scripts", "resolve-ChangeLogs");
2968 (system($resolveChangeLogsPath, "--no-warnings", @conflictedChangeLogs) == 0)
2969 or die "Could not open resolve-ChangeLogs script: $!.\n";
2975 # Doing a git fetch first allows setups with svn-remote.svn.fetch = trunk:refs/remotes/origin/master
2976 # to perform the rebase much much faster.
2977 system("git", "fetch");
2978 if (isGitSVNDirectory(".")) {
2979 system("git", "svn", "rebase") == 0 or die;
2981 # This will die if branch.$BRANCHNAME.merge isn't set, which is
2982 # almost certainly what we want.
2983 system("git", "pull") == 0 or die;