[CherryPick] Input Method upversion
[framework/web/webkit-efl.git] / Tools / Scripts / webkitdirs.pm
1 # Copyright (C) 2005, 2006, 2007, 2010, 2011, 2012 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 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1.  Redistributions of source code must retain the above copyright
10 #     notice, this list of conditions and the following disclaimer. 
11 # 2.  Redistributions in binary form must reproduce the above copyright
12 #     notice, this list of conditions and the following disclaimer in the
13 #     documentation and/or other materials provided with the distribution. 
14 # 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 #     its contributors may be used to endorse or promote products derived
16 #     from this software without specific prior written permission. 
17 #
18 # THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 # DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 # Module to share code to get to WebKit directories.
30
31 use strict;
32 use version;
33 use warnings;
34 use Config;
35 use Digest::MD5 qw(md5_hex);
36 use FindBin;
37 use File::Basename;
38 use File::Path qw(mkpath rmtree);
39 use File::Spec;
40 use File::stat;
41 use POSIX;
42 use VCSUtils;
43
44 BEGIN {
45    use Exporter   ();
46    our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
47    $VERSION     = 1.00;
48    @ISA         = qw(Exporter);
49    @EXPORT      = qw(
50        &XcodeOptionString
51        &XcodeOptionStringNoConfig
52        &XcodeOptions
53        &baseProductDir
54        &chdirWebKit
55        &checkFrameworks
56        &cmakeBasedPortArguments
57        &cmakeBasedPortName
58        &currentSVNRevision
59        &debugSafari
60        &nmPath
61        &passedConfiguration
62        &printHelpAndExitForRunAndDebugWebKitAppIfNeeded
63        &productDir
64        &runMacWebKitApp
65        &safariPath
66        &setConfiguration
67        USE_OPEN_COMMAND
68    );
69    %EXPORT_TAGS = ( );
70    @EXPORT_OK   = ();
71 }
72
73 use constant USE_OPEN_COMMAND => 1; # Used in runMacWebKitApp().
74 use constant INCLUDE_OPTIONS_FOR_DEBUGGING => 1;
75
76 our @EXPORT_OK;
77
78 my $architecture;
79 my $numberOfCPUs;
80 my $baseProductDir;
81 my @baseProductDirOption;
82 my $configuration;
83 my $configurationForVisualStudio;
84 my $configurationProductDir;
85 my $sourceDir;
86 my $currentSVNRevision;
87 my $debugger;
88 my $nmPath;
89 my $osXVersion;
90 my $generateDsym;
91 my $isQt;
92 my $qmakebin = "qmake"; # Allow override of the qmake binary from $PATH
93 my $isGtk;
94 my $isWinCE;
95 my $isWinCairo;
96 my $isWx;
97 my $isEfl;
98 my @wxArgs;
99 my $isBlackBerry;
100 my $isChromium;
101 my $isChromiumAndroid;
102 my $isChromiumMacMake;
103 my $isChromiumNinja;
104 my $forceChromiumUpdate;
105 my $isInspectorFrontend;
106 my $isWK2;
107 my $shouldTargetWebProcess;
108 my $shouldUseGuardMalloc;
109 my $xcodeVersion;
110
111 # Variables for Win32 support
112 my $vcBuildPath;
113 my $windowsSourceDir;
114 my $winVersion;
115 my $willUseVCExpressWhenBuilding = 0;
116
117 # Defined in VCSUtils.
118 sub exitStatus($);
119
120 sub determineSourceDir
121 {
122     return if $sourceDir;
123     $sourceDir = $FindBin::Bin;
124     $sourceDir =~ s|/+$||; # Remove trailing '/' as we would die later
125
126     # walks up path checking each directory to see if it is the main WebKit project dir, 
127     # defined by containing Sources, WebCore, and WebKit
128     until ((-d "$sourceDir/Source" && -d "$sourceDir/Source/WebCore" && -d "$sourceDir/Source/WebKit") || (-d "$sourceDir/Internal" && -d "$sourceDir/OpenSource"))
129     {
130         if ($sourceDir !~ s|/[^/]+$||) {
131             die "Could not find top level webkit directory above source directory using FindBin.\n";
132         }
133     }
134
135     $sourceDir = "$sourceDir/OpenSource" if -d "$sourceDir/OpenSource";
136 }
137
138 sub currentPerlPath()
139 {
140     my $thisPerl = $^X;
141     if ($^O ne 'VMS') {
142         $thisPerl .= $Config{_exe} unless $thisPerl =~ m/$Config{_exe}$/i;
143     }
144     return $thisPerl;
145 }
146
147 sub setQmakeBinaryPath($)
148 {
149     ($qmakebin) = @_;
150 }
151
152 # used for scripts which are stored in a non-standard location
153 sub setSourceDir($)
154 {
155     ($sourceDir) = @_;
156 }
157
158 sub determineXcodeVersion
159 {
160     return if defined $xcodeVersion;
161     my $xcodebuildVersionOutput = `xcodebuild -version`;
162     $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : "3.0";
163 }
164
165 sub readXcodeUserDefault($)
166 {
167     my ($unprefixedKey) = @_;
168
169     determineXcodeVersion();
170
171     my $xcodeDefaultsDomain = (eval "v$xcodeVersion" lt v4) ? "com.apple.Xcode" : "com.apple.dt.Xcode";
172     my $xcodeDefaultsPrefix = (eval "v$xcodeVersion" lt v4) ? "PBX" : "IDE";
173     my $devnull = File::Spec->devnull();
174
175     my $value = `defaults read $xcodeDefaultsDomain ${xcodeDefaultsPrefix}${unprefixedKey} 2> ${devnull}`;
176     return if $?;
177
178     chomp $value;
179     return $value;
180 }
181
182 sub determineBaseProductDir
183 {
184     return if defined $baseProductDir;
185     determineSourceDir();
186
187     my $setSharedPrecompsDir;
188     $baseProductDir = $ENV{"WEBKITOUTPUTDIR"};
189
190     if (!defined($baseProductDir) and isAppleMacWebKit()) {
191         # Silently remove ~/Library/Preferences/xcodebuild.plist which can
192         # cause build failure. The presence of
193         # ~/Library/Preferences/xcodebuild.plist can prevent xcodebuild from
194         # respecting global settings such as a custom build products directory
195         # (<rdar://problem/5585899>).
196         my $personalPlistFile = $ENV{HOME} . "/Library/Preferences/xcodebuild.plist";
197         if (-e $personalPlistFile) {
198             unlink($personalPlistFile) || die "Could not delete $personalPlistFile: $!";
199         }
200
201         determineXcodeVersion();
202
203         if (eval "v$xcodeVersion" ge v4) {
204             my $buildLocationStyle = join '', readXcodeUserDefault("BuildLocationStyle");
205             if ($buildLocationStyle eq "Custom") {
206                 my $buildLocationType = join '', readXcodeUserDefault("CustomBuildLocationType");
207                 # FIXME: Read CustomBuildIntermediatesPath and set OBJROOT accordingly.
208                 $baseProductDir = readXcodeUserDefault("CustomBuildProductsPath") if $buildLocationType eq "Absolute";
209             }
210
211             # DeterminedByTargets corresponds to a setting of "Legacy" in Xcode.
212             # It is the only build location style for which SHARED_PRECOMPS_DIR is not
213             # overridden when building from within Xcode.
214             $setSharedPrecompsDir = 1 if $buildLocationStyle ne "DeterminedByTargets";
215         }
216
217         if (!defined($baseProductDir)) {
218             $baseProductDir = join '', readXcodeUserDefault("ApplicationwideBuildSettings");
219             $baseProductDir = $1 if $baseProductDir =~ /SYMROOT\s*=\s*\"(.*?)\";/s;
220         }
221
222         undef $baseProductDir unless $baseProductDir =~ /^\//;
223     } elsif (isChromium()) {
224         if (isLinux() || isChromiumAndroid() || isChromiumMacMake()) {
225             $baseProductDir = "$sourceDir/out";
226         } elsif (isDarwin()) {
227             $baseProductDir = "$sourceDir/Source/WebKit/chromium/xcodebuild";
228         } elsif (isWindows() || isCygwin()) {
229             $baseProductDir = "$sourceDir/Source/WebKit/chromium/build";
230         }
231     }
232
233     if (!defined($baseProductDir)) { # Port-specific checks failed, use default
234         $baseProductDir = "$sourceDir/WebKitBuild";
235     }
236
237     if (isBlackBerry()) {
238         my %archInfo = blackberryTargetArchitecture();
239         $baseProductDir = "$baseProductDir/" . $archInfo{"cpuDir"};
240     }
241
242     if (isGit() && isGitBranchBuild() && !isChromium()) {
243         my $branch = gitBranch();
244         $baseProductDir = "$baseProductDir/$branch";
245     }
246
247     if (isAppleMacWebKit()) {
248         $baseProductDir =~ s|^\Q$(SRCROOT)/..\E$|$sourceDir|;
249         $baseProductDir =~ s|^\Q$(SRCROOT)/../|$sourceDir/|;
250         $baseProductDir =~ s|^~/|$ENV{HOME}/|;
251         die "Can't handle Xcode product directory with a ~ in it.\n" if $baseProductDir =~ /~/;
252         die "Can't handle Xcode product directory with a variable in it.\n" if $baseProductDir =~ /\$/;
253         @baseProductDirOption = ("SYMROOT=$baseProductDir", "OBJROOT=$baseProductDir");
254         push(@baseProductDirOption, "SHARED_PRECOMPS_DIR=${baseProductDir}/PrecompiledHeaders") if $setSharedPrecompsDir;
255     }
256
257     if (isCygwin()) {
258         my $dosBuildPath = `cygpath --windows \"$baseProductDir\"`;
259         chomp $dosBuildPath;
260         $ENV{"WEBKITOUTPUTDIR"} = $dosBuildPath;
261         my $unixBuildPath = `cygpath --unix \"$baseProductDir\"`;
262         chomp $unixBuildPath;
263         $baseProductDir = $unixBuildPath;
264     }
265 }
266
267 sub setBaseProductDir($)
268 {
269     ($baseProductDir) = @_;
270 }
271
272 sub determineConfiguration
273 {
274     return if defined $configuration;
275     determineBaseProductDir();
276     if (open CONFIGURATION, "$baseProductDir/Configuration") {
277         $configuration = <CONFIGURATION>;
278         close CONFIGURATION;
279     }
280     if ($configuration) {
281         chomp $configuration;
282         # compatibility for people who have old Configuration files
283         $configuration = "Release" if $configuration eq "Deployment";
284         $configuration = "Debug" if $configuration eq "Development";
285     } else {
286         $configuration = "Release";
287     }
288
289     if ($configuration && isWinCairo()) {
290         unless ($configuration =~ /_Cairo_CFLite$/) {
291             $configuration .= "_Cairo_CFLite";
292         }
293     }
294 }
295
296 sub determineArchitecture
297 {
298     return if defined $architecture;
299     # make sure $architecture is defined in all cases
300     $architecture = "";
301
302     determineBaseProductDir();
303
304     if (isGtk()) {
305         determineConfigurationProductDir();
306         my $host_triple = `grep -E '^host = ' $configurationProductDir/GNUmakefile`;
307         if ($host_triple =~ m/^host = ([^-]+)-/) {
308             # We have a configured build tree; use it.
309             $architecture = $1;
310         }
311     } elsif (isAppleMacWebKit()) {
312         if (open ARCHITECTURE, "$baseProductDir/Architecture") {
313             $architecture = <ARCHITECTURE>;
314             close ARCHITECTURE;
315         }
316         if ($architecture) {
317             chomp $architecture;
318         } else {
319             my $supports64Bit = `sysctl -n hw.optional.x86_64`;
320             chomp $supports64Bit;
321             $architecture = 'x86_64' if $supports64Bit;
322         }
323     } elsif (isEfl()) {
324         my $host_processor = "";
325         $host_processor = `cmake --system-information | grep CMAKE_SYSTEM_PROCESSOR`;
326         if ($host_processor =~ m/^CMAKE_SYSTEM_PROCESSOR \"([^"]+)\"/) {
327             # We have a configured build tree; use it.
328             $architecture = $1;
329             $architecture = 'x86_64' if $architecture eq 'amd64';
330         }
331     }
332
333     if (!$architecture && (isGtk() || isAppleMacWebKit() || isEfl())) {
334         # Fall back to output of `arch', if it is present.
335         $architecture = `arch`;
336         chomp $architecture;
337     }
338
339     if (!$architecture && (isGtk() || isAppleMacWebKit() || isEfl())) {
340         # Fall back to output of `uname -m', if it is present.
341         $architecture = `uname -m`;
342         chomp $architecture;
343     }
344 }
345
346 sub determineNumberOfCPUs
347 {
348     return if defined $numberOfCPUs;
349     if (defined($ENV{NUMBER_OF_PROCESSORS})) {
350         $numberOfCPUs = $ENV{NUMBER_OF_PROCESSORS};
351     } elsif (isLinux()) {
352         # First try the nproc utility, if it exists. If we get no
353         # results fall back to just interpretting /proc directly.
354         chomp($numberOfCPUs = `nproc 2> /dev/null`);
355         if ($numberOfCPUs eq "") {
356             $numberOfCPUs = (grep /processor/, `cat /proc/cpuinfo`);
357         }
358     } elsif (isWindows() || isCygwin()) {
359         # Assumes cygwin
360         $numberOfCPUs = `ls /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor | wc -w`;
361     } elsif (isDarwin() || isFreeBSD()) {
362         chomp($numberOfCPUs = `sysctl -n hw.ncpu`);
363     }
364 }
365
366 sub jscPath($)
367 {
368     my ($productDir) = @_;
369     my $jscName = "jsc";
370     $jscName .= "_debug"  if configurationForVisualStudio() eq "Debug_All";
371     $jscName .= ".exe" if (isWindows() || isCygwin());
372     return "$productDir/$jscName" if -e "$productDir/$jscName";
373     return "$productDir/JavaScriptCore.framework/Resources/$jscName";
374 }
375
376 sub argumentsForConfiguration()
377 {
378     determineConfiguration();
379     determineArchitecture();
380
381     my @args = ();
382     push(@args, '--debug') if $configuration eq "Debug";
383     push(@args, '--release') if $configuration eq "Release";
384     push(@args, '--32-bit') if $architecture ne "x86_64";
385     push(@args, '--qt') if isQt();
386     push(@args, '--gtk') if isGtk();
387     push(@args, '--efl') if isEfl();
388     push(@args, '--wincairo') if isWinCairo();
389     push(@args, '--wince') if isWinCE();
390     push(@args, '--wx') if isWx();
391     push(@args, '--blackberry') if isBlackBerry();
392     push(@args, '--chromium') if isChromium() && !isChromiumAndroid();
393     push(@args, '--chromium-android') if isChromiumAndroid();
394     push(@args, '--inspector-frontend') if isInspectorFrontend();
395     return @args;
396 }
397
398 sub determineConfigurationForVisualStudio
399 {
400     return if defined $configurationForVisualStudio;
401     determineConfiguration();
402     # FIXME: We should detect when Debug_All or Production has been chosen.
403     $configurationForVisualStudio = $configuration;
404 }
405
406 sub usesPerConfigurationBuildDirectory
407 {
408     # [Gtk] We don't have Release/Debug configurations in straight
409     # autotool builds (non build-webkit). In this case and if
410     # WEBKITOUTPUTDIR exist, use that as our configuration dir. This will
411     # allows us to run run-webkit-tests without using build-webkit.
412     return ($ENV{"WEBKITOUTPUTDIR"} && isGtk()) || isAppleWinWebKit();
413 }
414
415 sub determineConfigurationProductDir
416 {
417     return if defined $configurationProductDir;
418     determineBaseProductDir();
419     determineConfiguration();
420     if (isAppleWinWebKit() && !isWx()) {
421         $configurationProductDir = File::Spec->catdir($baseProductDir, configurationForVisualStudio(), "bin");
422     } else {
423         if (usesPerConfigurationBuildDirectory()) {
424             $configurationProductDir = "$baseProductDir";
425         } else {
426             $configurationProductDir = "$baseProductDir/$configuration";
427         }
428     }
429 }
430
431 sub setConfigurationProductDir($)
432 {
433     ($configurationProductDir) = @_;
434 }
435
436 sub determineCurrentSVNRevision
437 {
438     # We always update the current SVN revision here, and leave the caching
439     # to currentSVNRevision(), so that changes to the SVN revision while the
440     # script is running can be picked up by calling this function again.
441     determineSourceDir();
442     $currentSVNRevision = svnRevisionForDirectory($sourceDir);
443     return $currentSVNRevision;
444 }
445
446
447 sub chdirWebKit
448 {
449     determineSourceDir();
450     chdir $sourceDir or die;
451 }
452
453 sub baseProductDir
454 {
455     determineBaseProductDir();
456     return $baseProductDir;
457 }
458
459 sub sourceDir
460 {
461     determineSourceDir();
462     return $sourceDir;
463 }
464
465 sub productDir
466 {
467     determineConfigurationProductDir();
468     return $configurationProductDir;
469 }
470
471 sub jscProductDir
472 {
473     my $productDir = productDir();
474     $productDir .= "/bin" if (isQt() || isEfl());
475     $productDir .= "/Programs" if isGtk();
476
477     return $productDir;
478 }
479
480 sub configuration()
481 {
482     determineConfiguration();
483     return $configuration;
484 }
485
486 sub configurationForVisualStudio()
487 {
488     determineConfigurationForVisualStudio();
489     return $configurationForVisualStudio;
490 }
491
492 sub currentSVNRevision
493 {
494     determineCurrentSVNRevision() if not defined $currentSVNRevision;
495     return $currentSVNRevision;
496 }
497
498 sub generateDsym()
499 {
500     determineGenerateDsym();
501     return $generateDsym;
502 }
503
504 sub determineGenerateDsym()
505 {
506     return if defined($generateDsym);
507     $generateDsym = checkForArgumentAndRemoveFromARGV("--dsym");
508 }
509
510 sub argumentsForXcode()
511 {
512     my @args = ();
513     push @args, "DEBUG_INFORMATION_FORMAT=dwarf-with-dsym" if generateDsym();
514     return @args;
515 }
516
517 sub XcodeOptions
518 {
519     determineBaseProductDir();
520     determineConfiguration();
521     determineArchitecture();
522     return (@baseProductDirOption, "-configuration", $configuration, "ARCHS=$architecture", argumentsForXcode());
523 }
524
525 sub XcodeOptionString
526 {
527     return join " ", XcodeOptions();
528 }
529
530 sub XcodeOptionStringNoConfig
531 {
532     return join " ", @baseProductDirOption;
533 }
534
535 sub XcodeCoverageSupportOptions()
536 {
537     my @coverageSupportOptions = ();
538     push @coverageSupportOptions, "GCC_GENERATE_TEST_COVERAGE_FILES=YES";
539     push @coverageSupportOptions, "GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES";
540     push @coverageSupportOptions, "EXTRA_LINK= \$(EXTRA_LINK) -ftest-coverage -fprofile-arcs";
541     push @coverageSupportOptions, "OTHER_CFLAGS= \$(OTHER_CFLAGS) -DCOVERAGE -MD";
542     push @coverageSupportOptions, "OTHER_LDFLAGS=\$(OTHER_LDFLAGS) -ftest-coverage -fprofile-arcs -lgcov";
543     return @coverageSupportOptions;
544 }
545
546 my $passedConfiguration;
547 my $searchedForPassedConfiguration;
548 sub determinePassedConfiguration
549 {
550     return if $searchedForPassedConfiguration;
551     $searchedForPassedConfiguration = 1;
552
553     for my $i (0 .. $#ARGV) {
554         my $opt = $ARGV[$i];
555         if ($opt =~ /^--debug$/i || $opt =~ /^--devel/i) {
556             splice(@ARGV, $i, 1);
557             $passedConfiguration = "Debug";
558             $passedConfiguration .= "_Cairo_CFLite" if (isWinCairo() && isCygwin());
559             return;
560         }
561         if ($opt =~ /^--release$/i || $opt =~ /^--deploy/i) {
562             splice(@ARGV, $i, 1);
563             $passedConfiguration = "Release";
564             $passedConfiguration .= "_Cairo_CFLite" if (isWinCairo() && isCygwin());
565             return;
566         }
567         if ($opt =~ /^--profil(e|ing)$/i) {
568             splice(@ARGV, $i, 1);
569             $passedConfiguration = "Profiling";
570             $passedConfiguration .= "_Cairo_CFLite" if (isWinCairo() && isCygwin());
571             return;
572         }
573     }
574     $passedConfiguration = undef;
575 }
576
577 sub passedConfiguration
578 {
579     determinePassedConfiguration();
580     return $passedConfiguration;
581 }
582
583 sub setConfiguration
584 {
585     setArchitecture();
586
587     if (my $config = shift @_) {
588         $configuration = $config;
589         return;
590     }
591
592     determinePassedConfiguration();
593     $configuration = $passedConfiguration if $passedConfiguration;
594 }
595
596
597 my $passedArchitecture;
598 my $searchedForPassedArchitecture;
599 sub determinePassedArchitecture
600 {
601     return if $searchedForPassedArchitecture;
602     $searchedForPassedArchitecture = 1;
603
604     for my $i (0 .. $#ARGV) {
605         my $opt = $ARGV[$i];
606         if ($opt =~ /^--32-bit$/i) {
607             splice(@ARGV, $i, 1);
608             if (isAppleMacWebKit() || isWx()) {
609                 $passedArchitecture = `arch`;
610                 chomp $passedArchitecture;
611             }
612             return;
613         }
614     }
615     $passedArchitecture = undef;
616 }
617
618 sub passedArchitecture
619 {
620     determinePassedArchitecture();
621     return $passedArchitecture;
622 }
623
624 sub architecture()
625 {
626     determineArchitecture();
627     return $architecture;
628 }
629
630 sub numberOfCPUs()
631 {
632     determineNumberOfCPUs();
633     return $numberOfCPUs;
634 }
635
636 sub setArchitecture
637 {
638     if (my $arch = shift @_) {
639         $architecture = $arch;
640         return;
641     }
642
643     determinePassedArchitecture();
644     $architecture = $passedArchitecture if $passedArchitecture;
645 }
646
647 sub executableHasEntitlements
648 {
649     my $executablePath = shift;
650     return (`codesign -d --entitlements - $executablePath 2>&1` =~ /<key>/);
651 }
652
653 sub safariPathFromSafariBundle
654 {
655     my ($safariBundle) = @_;
656
657     if (isAppleMacWebKit()) {
658         my $safariPath = "$safariBundle/Contents/MacOS/Safari";
659         my $safariForWebKitDevelopmentPath = "$safariBundle/Contents/MacOS/SafariForWebKitDevelopment";
660         return $safariForWebKitDevelopmentPath if -f $safariForWebKitDevelopmentPath && executableHasEntitlements($safariPath);
661         return $safariPath;
662     }
663     return $safariBundle if isAppleWinWebKit();
664 }
665
666 sub installedSafariPath
667 {
668     my $safariBundle;
669
670     if (isAppleMacWebKit()) {
671         $safariBundle = "/Applications/Safari.app";
672     } elsif (isAppleWinWebKit()) {
673         $safariBundle = readRegistryString("/HKLM/SOFTWARE/Apple Computer, Inc./Safari/InstallDir");
674         $safariBundle =~ s/[\r\n]+$//;
675         $safariBundle = `cygpath -u '$safariBundle'` if isCygwin();
676         $safariBundle =~ s/[\r\n]+$//;
677         $safariBundle .= "Safari.exe";
678     }
679
680     return safariPathFromSafariBundle($safariBundle);
681 }
682
683 # Locate Safari.
684 sub safariPath
685 {
686     # Use WEBKIT_SAFARI environment variable if present.
687     my $safariBundle = $ENV{WEBKIT_SAFARI};
688     if (!$safariBundle) {
689         determineConfigurationProductDir();
690         # Use Safari.app in product directory if present (good for Safari development team).
691         if (isAppleMacWebKit() && -d "$configurationProductDir/Safari.app") {
692             $safariBundle = "$configurationProductDir/Safari.app";
693         } elsif (isAppleWinWebKit()) {
694             my $path = "$configurationProductDir/Safari.exe";
695             my $debugPath = "$configurationProductDir/Safari_debug.exe";
696
697             if (configurationForVisualStudio() eq "Debug_All" && -x $debugPath) {
698                 $safariBundle = $debugPath;
699             } elsif (-x $path) {
700                 $safariBundle = $path;
701             }
702         }
703         if (!$safariBundle) {
704             return installedSafariPath();
705         }
706     }
707     my $safariPath = safariPathFromSafariBundle($safariBundle);
708     die "Can't find executable at $safariPath.\n" if isAppleMacWebKit() && !-x $safariPath;
709     return $safariPath;
710 }
711
712 sub builtDylibPathForName
713 {
714     my $libraryName = shift;
715     determineConfigurationProductDir();
716     if (isChromium()) {
717         return "$configurationProductDir/$libraryName";
718     }
719     if (isBlackBerry()) {
720         my $libraryExtension = $libraryName =~ /^WebKit$/i ? ".so" : ".a";
721         return "$configurationProductDir/$libraryName/lib" . lc($libraryName) . $libraryExtension;
722     }
723     if (isQt()) {
724         my $isSearchingForWebCore = $libraryName =~ "WebCore";
725         $libraryName = "QtWebKit";
726         my $result;
727         if (isDarwin() and -d "$configurationProductDir/lib/$libraryName.framework") {
728             $result = "$configurationProductDir/lib/$libraryName.framework/$libraryName";
729         } elsif (isDarwin() and -d "$configurationProductDir/lib") {
730             $result = "$configurationProductDir/lib/lib$libraryName.dylib";
731         } elsif (isWindows()) {
732             if (configuration() eq "Debug") {
733                 # On Windows, there is a "d" suffix to the library name. See <http://trac.webkit.org/changeset/53924/>.
734                 $libraryName .= "d";
735             }
736
737             my $mkspec = `$qmakebin -query QMAKE_MKSPECS`;
738             $mkspec =~ s/[\n|\r]$//g;
739             my $qtMajorVersion = retrieveQMakespecVar("$mkspec/qconfig.pri", "QT_MAJOR_VERSION");
740             if (not $qtMajorVersion) {
741                 $qtMajorVersion = "";
742             }
743
744             $result = "$configurationProductDir/lib/$libraryName$qtMajorVersion.dll";
745         } else {
746             $result = "$configurationProductDir/lib/lib$libraryName.so";
747         }
748
749         if ($isSearchingForWebCore) {
750             # With CONFIG+=force_static_libs_as_shared we have a shared library for each subdir.
751             # For feature detection to work it is necessary to return the path of the WebCore library here.
752             my $replacedWithWebCore = $result;
753             $replacedWithWebCore =~ s/$libraryName/WebCore/g;
754             if (-e $replacedWithWebCore) {
755                 return $replacedWithWebCore;
756             }
757         }
758
759         return $result;
760     }
761     if (isWx()) {
762         return "$configurationProductDir/libwxwebkit.dylib";
763     }
764     if (isGtk()) {
765         # WebKitGTK+ for GTK2, WebKitGTK+ for GTK3, and WebKit2 respectively.
766         my @libraries = ("libwebkitgtk-1.0", "libwebkitgtk-3.0", "libwebkit2gtk-1.0");
767         my $extension = isDarwin() ? ".dylib" : ".so";
768
769         foreach $libraryName (@libraries) {
770             my $libraryPath = "$configurationProductDir/.libs/" . $libraryName . $extension;
771             return $libraryPath if -e $libraryPath;
772         }
773         return "NotFound";
774     }
775     if (isEfl()) {
776         return "$configurationProductDir/lib/libewebkit.so";
777     }
778     if (isWinCE()) {
779         return "$configurationProductDir/$libraryName";
780     }
781     if (isAppleMacWebKit()) {
782         return "$configurationProductDir/$libraryName.framework/Versions/A/$libraryName";
783     }
784     if (isAppleWinWebKit()) {
785         if ($libraryName eq "JavaScriptCore") {
786             return "$baseProductDir/lib/$libraryName.lib";
787         } else {
788             return "$baseProductDir/$libraryName.intermediate/$configuration/$libraryName.intermediate/$libraryName.lib";
789         }
790     }
791
792     die "Unsupported platform, can't determine built library locations.\nTry `build-webkit --help` for more information.\n";
793 }
794
795 # Check to see that all the frameworks are built.
796 sub checkFrameworks # FIXME: This is a poor name since only the Mac calls built WebCore a Framework.
797 {
798     return if isCygwin() || isWindows();
799     my @frameworks = ("JavaScriptCore", "WebCore");
800     push(@frameworks, "WebKit") if isAppleMacWebKit(); # FIXME: This seems wrong, all ports should have a WebKit these days.
801     for my $framework (@frameworks) {
802         my $path = builtDylibPathForName($framework);
803         die "Can't find built framework at \"$path\".\n" unless -e $path;
804     }
805 }
806
807 sub isInspectorFrontend()
808 {
809     determineIsInspectorFrontend();
810     return $isInspectorFrontend;
811 }
812
813 sub determineIsInspectorFrontend()
814 {
815     return if defined($isInspectorFrontend);
816     $isInspectorFrontend = checkForArgumentAndRemoveFromARGV("--inspector-frontend");
817 }
818
819 sub isQt()
820 {
821     determineIsQt();
822     return $isQt;
823 }
824
825 sub getQtVersion()
826 {
827     my $qtVersion = `$qmakebin --version`;
828     $qtVersion =~ s/^(.*)Qt version (\d\.\d)(.*)/$2/s ;
829     return $qtVersion;
830 }
831
832 sub qtFeatureDefaults
833 {
834     die "ERROR: qmake missing but required to build WebKit.\n" if not commandExists($qmakebin);
835
836     my $qmakepath = File::Spec->catfile(sourceDir(), "Tools", "qmake");
837     my $qmakecommand;
838     if (isWindows()) {
839         $qmakecommand = "(set QMAKEPATH=$qmakepath) && $qmakebin";
840     } else {
841         $qmakecommand = "QMAKEPATH=$qmakepath $qmakebin";
842     }
843
844     my $originalCwd = getcwd();
845
846     my $file = File::Spec->catfile($qmakepath, "configure.pro");
847     my @buildArgs;
848     my $qconfigs;
849
850     if (@_) {
851         @buildArgs = (@buildArgs, @{$_[0]});
852         $qconfigs = $_[1];
853         my $dir = File::Spec->catfile(productDir(), "Tools", "qmake");
854         File::Path::mkpath($dir);
855         chdir $dir or die "Failed to cd into " . $dir . "\n";
856     } else {
857         # Do a quick check of the features without running the config tests
858         push @buildArgs, "CONFIG+=quick_check";
859     }
860
861     my @defaults = `$qmakecommand @buildArgs -nocache $file 2>&1`;
862
863     my %qtFeatureDefaults;
864     for (@defaults) {
865         if (/ DEFINES: /) {
866             while (/(\S+?)=(\S+?)/gi) {
867                 $qtFeatureDefaults{$1}=$2;
868             }
869         } elsif (/ CONFIG:(.*)$/) {
870             if (@_) {
871                 $$qconfigs = $1;
872             }
873         } elsif (/Done computing defaults/) {
874             print "\n";
875             last;
876         } elsif (@_) {
877             print $_;
878         }
879     }
880
881     chdir $originalCwd;
882
883     return %qtFeatureDefaults;
884 }
885
886 sub commandExists($)
887 {
888     my $command = shift;
889     my $devnull = File::Spec->devnull();
890     return `$command --version 2> $devnull`;
891 }
892
893 sub checkForArgumentAndRemoveFromARGV
894 {
895     my $argToCheck = shift;
896     return checkForArgumentAndRemoveFromArrayRef($argToCheck, \@ARGV);
897 }
898
899 sub checkForArgumentAndRemoveFromArrayRef
900 {
901     my ($argToCheck, $arrayRef) = @_;
902     my @indicesToRemove;
903     foreach my $index (0 .. $#$arrayRef) {
904         my $opt = $$arrayRef[$index];
905         if ($opt =~ /^$argToCheck$/i ) {
906             push(@indicesToRemove, $index);
907         }
908     }
909     foreach my $index (@indicesToRemove) {
910         splice(@$arrayRef, $index, 1);
911     }
912     return $#indicesToRemove > -1;
913 }
914
915 sub isWK2()
916 {
917     if (defined($isWK2)) {
918         return $isWK2;
919     }
920     if (checkForArgumentAndRemoveFromARGV("-2")) {
921         $isWK2 = 1;
922     } else {
923         $isWK2 = 0;
924     }
925     return $isWK2;
926 }
927
928 sub determineIsQt()
929 {
930     return if defined($isQt);
931
932     # Allow override in case QTDIR is not set.
933     if (checkForArgumentAndRemoveFromARGV("--qt")) {
934         $isQt = 1;
935         return;
936     }
937
938     # The presence of QTDIR only means Qt if --gtk or --wx or --efl or --blackberry or --chromium or --wincairo are not on the command-line
939     if (isGtk() || isWx() || isEfl() || isBlackBerry() || isChromium() || isWinCairo()) {
940         $isQt = 0;
941         return;
942     }
943
944     $isQt = defined($ENV{'QTDIR'});
945 }
946
947 sub isBlackBerry()
948 {
949     determineIsBlackBerry();
950     return $isBlackBerry;
951 }
952
953 sub determineIsBlackBerry()
954 {
955     return if defined($isBlackBerry);
956     $isBlackBerry = checkForArgumentAndRemoveFromARGV("--blackberry");
957 }
958
959 sub blackberryTargetArchitecture()
960 {
961     my $arch = $ENV{"BLACKBERRY_ARCH_TYPE"} ? $ENV{"BLACKBERRY_ARCH_TYPE"} : "arm";
962     my $cpu = $ENV{"BLACKBERRY_ARCH_CPU"} ? $ENV{"BLACKBERRY_ARCH_CPU"} : "";
963     my $cpuDir;
964     my $buSuffix;
965     if (($cpu eq "v7le") || ($cpu eq "a9")) {
966         $cpuDir = $arch . "le-v7";
967         $buSuffix = $arch . "v7";
968     } else {
969         $cpu = $arch;
970         $cpuDir = $arch;
971         $buSuffix = $arch;
972     }
973     return ("arch" => $arch,
974             "cpu" => $cpu,
975             "cpuDir" => $cpuDir,
976             "buSuffix" => $buSuffix);
977 }
978
979 sub blackberryCMakeArguments()
980 {
981     my %archInfo = blackberryTargetArchitecture();
982     my $arch = $archInfo{"arch"};
983     my $cpu = $archInfo{"cpu"};
984     my $cpuDir = $archInfo{"cpuDir"};
985     my $buSuffix = $archInfo{"buSuffix"};
986
987     my @cmakeExtraOptions;
988     if ($cpu eq "a9") {
989         $cpu = $arch . "v7le";
990         push @cmakeExtraOptions, '-DTARGETING_PLAYBOOK=1';
991     }
992
993     my $stageDir = $ENV{"STAGE_DIR"};
994     my $stageLib = File::Spec->catdir($stageDir, $cpuDir, "lib");
995     my $stageUsrLib = File::Spec->catdir($stageDir, $cpuDir, "usr", "lib");
996     my $stageInc = File::Spec->catdir($stageDir, "usr", "include");
997
998     my $qnxHost = $ENV{"QNX_HOST"};
999     my $ccCommand;
1000     my $cxxCommand;
1001     if ($ENV{"USE_ICECC"}) {
1002         chomp($ccCommand = `which icecc`);
1003         $cxxCommand = $ccCommand;
1004     } else {
1005         $ccCommand = File::Spec->catfile($qnxHost, "usr", "bin", "qcc");
1006         $cxxCommand = $ccCommand;
1007     }
1008
1009     if ($ENV{"CCWRAP"}) {
1010         $ccCommand = $ENV{"CCWRAP"};
1011         push @cmakeExtraOptions, "-DCMAKE_C_COMPILER_ARG1=qcc";
1012         push @cmakeExtraOptions, "-DCMAKE_CXX_COMPILER_ARG1=qcc";
1013     }
1014
1015     push @cmakeExtraOptions, "-DCMAKE_SKIP_RPATH='ON'" if isDarwin();
1016     push @cmakeExtraOptions, "-DPUBLIC_BUILD=1" if $ENV{"PUBLIC_BUILD"};
1017     push @cmakeExtraOptions, "-DENABLE_GLES2=1" unless $ENV{"DISABLE_GLES2"};
1018
1019     my @includeSystemDirectories;
1020     push @includeSystemDirectories, File::Spec->catdir($stageInc, "grskia", "skia");
1021     push @includeSystemDirectories, File::Spec->catdir($stageInc, "grskia");
1022     push @includeSystemDirectories, File::Spec->catdir($stageInc, "harfbuzz");
1023     push @includeSystemDirectories, File::Spec->catdir($stageInc, "imf");
1024     push @includeSystemDirectories, $stageInc;
1025     push @includeSystemDirectories, File::Spec->catdir($stageInc, "browser", "platform");
1026     push @includeSystemDirectories, File::Spec->catdir($stageInc, "browser", "qsk");
1027     push @includeSystemDirectories, File::Spec->catdir($stageInc, "ots");
1028
1029     my @cxxFlags;
1030     push @cxxFlags, "-Wl,-rpath-link,$stageLib";
1031     push @cxxFlags, "-Wl,-rpath-link," . File::Spec->catfile($stageUsrLib, "torch-webkit");
1032     push @cxxFlags, "-Wl,-rpath-link,$stageUsrLib";
1033     push @cxxFlags, "-L$stageLib";
1034     push @cxxFlags, "-L$stageUsrLib";
1035
1036     if ($ENV{"PROFILE"}) {
1037         push @cmakeExtraOptions, "-DPROFILING=1";
1038         push @cxxFlags, "-p";
1039     }
1040
1041     my @cmakeArgs;
1042     push @cmakeArgs, '-DCMAKE_SYSTEM_NAME="QNX"';
1043     push @cmakeArgs, "-DCMAKE_SYSTEM_PROCESSOR=\"$cpuDir\"";
1044     push @cmakeArgs, '-DCMAKE_SYSTEM_VERSION="1"';
1045     push @cmakeArgs, "-DCMAKE_C_COMPILER=\"$ccCommand\"";
1046     push @cmakeArgs, "-DCMAKE_CXX_COMPILER=\"$cxxCommand\"";
1047     push @cmakeArgs, "-DCMAKE_C_FLAGS=\"-Vgcc_nto${cpu} -g @cxxFlags\"";
1048     push @cmakeArgs, "-DCMAKE_CXX_FLAGS=\"-Vgcc_nto${cpu}_cpp-ne -g -lang-c++ @cxxFlags\"";
1049
1050     # We cannot use CMAKE_INCLUDE_PATH since this describes the search path for header files in user directories.
1051     # And the QNX system headers are in user directories on the host OS (i.e. they aren't installed in the host OS's
1052     # system header search path). So, we need to inform g++ that these user directories (@includeSystemDirectories)
1053     # are to be taken as the host OS's system header directories when building our port.
1054     #
1055     # Also, we cannot use CMAKE_SYSTEM_INCLUDE_PATH since that will override the entire system header path.
1056     # So, we define the additional system include paths in ADDITIONAL_SYSTEM_INCLUDE_PATH. This list will
1057     # be processed in OptionsBlackBerry.cmake.
1058     push @cmakeArgs, '-DADDITIONAL_SYSTEM_INCLUDE_PATH="' . join(';', @includeSystemDirectories) . '"';
1059
1060     # FIXME: Make this more general purpose such that we can pass a list of directories and files.
1061     push @cmakeArgs, '-DTHIRD_PARTY_ICU_DIR="' . File::Spec->catdir($stageInc, "unicode") . '"';
1062     push @cmakeArgs, '-DTHIRD_PARTY_UNICODE_FILE="' . File::Spec->catfile($stageInc, "unicode.h") . '"';
1063
1064     push @cmakeArgs, "-DCMAKE_LIBRARY_PATH=\"$stageLib;$stageUsrLib\"";
1065     push @cmakeArgs, '-DCMAKE_AR="' . File::Spec->catfile($qnxHost, "usr", "bin", "nto${buSuffix}-ar") . '"';
1066     push @cmakeArgs, '-DCMAKE_RANLIB="' . File::Spec->catfile($qnxHost, "usr", "bin", "nto${buSuffix}-ranlib") . '"';
1067     push @cmakeArgs, '-DCMAKE_LD="'. File::Spec->catfile($qnxHost, "usr", "bin", "nto${buSuffix}-ld") . '"';
1068     push @cmakeArgs, '-DCMAKE_LINKER="' . File::Spec->catfile($qnxHost, "usr", "bin", "nto${buSuffix}-ld") . '"';
1069     push @cmakeArgs, "-DECLIPSE_CDT4_GENERATE_SOURCE_PROJECT=TRUE";
1070     push @cmakeArgs, '-G"Eclipse CDT4 - Unix Makefiles"';
1071     push @cmakeArgs, @cmakeExtraOptions;
1072     return @cmakeArgs;
1073 }
1074
1075 sub determineIsEfl()
1076 {
1077     return if defined($isEfl);
1078     $isEfl = checkForArgumentAndRemoveFromARGV("--efl");
1079 }
1080
1081 sub isEfl()
1082 {
1083     determineIsEfl();
1084     return $isEfl;
1085 }
1086
1087 sub isGtk()
1088 {
1089     determineIsGtk();
1090     return $isGtk;
1091 }
1092
1093 sub determineIsGtk()
1094 {
1095     return if defined($isGtk);
1096     $isGtk = checkForArgumentAndRemoveFromARGV("--gtk");
1097 }
1098
1099 sub isWinCE()
1100 {
1101     determineIsWinCE();
1102     return $isWinCE;
1103 }
1104
1105 sub determineIsWinCE()
1106 {
1107     return if defined($isWinCE);
1108     $isWinCE = checkForArgumentAndRemoveFromARGV("--wince");
1109 }
1110
1111 sub isWx()
1112 {
1113     determineIsWx();
1114     return $isWx;
1115 }
1116
1117 sub determineIsWx()
1118 {
1119     return if defined($isWx);
1120     $isWx = checkForArgumentAndRemoveFromARGV("--wx");
1121 }
1122
1123 sub getWxArgs()
1124 {
1125     if (!@wxArgs) {
1126         @wxArgs = ("");
1127         my $rawWxArgs = "";
1128         foreach my $opt (@ARGV) {
1129             if ($opt =~ /^--wx-args/i ) {
1130                 @ARGV = grep(!/^--wx-args/i, @ARGV);
1131                 $rawWxArgs = $opt;
1132                 $rawWxArgs =~ s/--wx-args=//i;
1133             }
1134         }
1135         @wxArgs = split(/,/, $rawWxArgs);
1136     }
1137     return @wxArgs;
1138 }
1139
1140 # Determine if this is debian, ubuntu, linspire, or something similar.
1141 sub isDebianBased()
1142 {
1143     return -e "/etc/debian_version";
1144 }
1145
1146 sub isFedoraBased()
1147 {
1148     return -e "/etc/fedora-release";
1149 }
1150
1151 sub isChromium()
1152 {
1153     determineIsChromium();
1154     determineIsChromiumAndroid();
1155     return $isChromium || $isChromiumAndroid;
1156 }
1157
1158 sub determineIsChromium()
1159 {
1160     return if defined($isChromium);
1161     $isChromium = checkForArgumentAndRemoveFromARGV("--chromium");
1162     if ($isChromium) {
1163         $forceChromiumUpdate = checkForArgumentAndRemoveFromARGV("--force-update");
1164     }
1165 }
1166
1167 sub isChromiumAndroid()
1168 {
1169     determineIsChromiumAndroid();
1170     return $isChromiumAndroid;
1171 }
1172
1173 sub determineIsChromiumAndroid()
1174 {
1175     return if defined($isChromiumAndroid);
1176     $isChromiumAndroid = checkForArgumentAndRemoveFromARGV("--chromium-android");
1177 }
1178
1179 sub isChromiumMacMake()
1180 {
1181     determineIsChromiumMacMake();
1182     return $isChromiumMacMake;
1183 }
1184
1185 sub determineIsChromiumMacMake()
1186 {
1187     return if defined($isChromiumMacMake);
1188
1189     my $hasUpToDateMakefile = 0;
1190     if (-e 'Makefile.chromium') {
1191         unless (-e 'Source/WebKit/chromium/WebKit.xcodeproj') {
1192             $hasUpToDateMakefile = 1;
1193         } else {
1194             $hasUpToDateMakefile = stat('Makefile.chromium')->mtime > stat('Source/WebKit/chromium/WebKit.xcodeproj')->mtime;
1195         }
1196     }
1197     $isChromiumMacMake = isDarwin() && $hasUpToDateMakefile;
1198 }
1199
1200 sub isChromiumNinja()
1201 {
1202     determineIsChromiumNinja();
1203     return $isChromiumNinja;
1204 }
1205
1206 sub determineIsChromiumNinja()
1207 {
1208     return if defined($isChromiumNinja);
1209
1210     my $config = configuration();
1211
1212     my $hasUpToDateNinjabuild = 0;
1213     if (-e "out/$config/build.ninja") {
1214         my $statNinja = stat("out/$config/build.ninja")->mtime;
1215
1216         my $statXcode = 0;
1217         if (-e 'Source/WebKit/chromium/WebKit.xcodeproj') {
1218           $statXcode = stat('Source/WebKit/chromium/WebKit.xcodeproj')->mtime;
1219         }
1220
1221         my $statMake = 0;
1222         if (-e 'Makefile.chromium') {
1223           $statMake = stat('Makefile.chromium')->mtime;
1224         }
1225
1226         $hasUpToDateNinjabuild = $statNinja > $statXcode && $statNinja > $statMake;
1227     }
1228     $isChromiumNinja = $hasUpToDateNinjabuild;
1229 }
1230
1231 sub forceChromiumUpdate()
1232 {
1233     determineIsChromium();
1234     return $forceChromiumUpdate;
1235 }
1236
1237 sub isWinCairo()
1238 {
1239     determineIsWinCairo();
1240     return $isWinCairo;
1241 }
1242
1243 sub determineIsWinCairo()
1244 {
1245     return if defined($isWinCairo);
1246     $isWinCairo = checkForArgumentAndRemoveFromARGV("--wincairo");
1247 }
1248
1249 sub isCygwin()
1250 {
1251     return ($^O eq "cygwin") || 0;
1252 }
1253
1254 sub isAnyWindows()
1255 {
1256     return isWindows() || isCygwin() || isMsys();
1257 }
1258
1259 sub determineWinVersion()
1260 {
1261     return if $winVersion;
1262
1263     if (!isAnyWindows()) {
1264         $winVersion = -1;
1265         return;
1266     }
1267
1268     my $versionString = `cmd /c ver`;
1269     $versionString =~ /(\d)\.(\d)\.(\d+)/;
1270
1271     $winVersion = {
1272         major => $1,
1273         minor => $2,
1274         build => $3,
1275     };
1276 }
1277
1278 sub winVersion()
1279 {
1280     determineWinVersion();
1281     return $winVersion;
1282 }
1283
1284 sub isWindows7SP0()
1285 {
1286     return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 1 && winVersion()->{build} == 7600;
1287 }
1288
1289 sub isWindowsVista()
1290 {
1291     return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 0;
1292 }
1293
1294 sub isWindowsXP()
1295 {
1296     return isAnyWindows() && winVersion()->{major} == 5 && winVersion()->{minor} == 1;
1297 }
1298
1299 sub isDarwin()
1300 {
1301     return ($^O eq "darwin") || 0;
1302 }
1303
1304 sub isWindows()
1305 {
1306     return ($^O eq "MSWin32") || 0;
1307 }
1308
1309 sub isMsys()
1310 {
1311     return ($^O eq "msys") || 0;
1312 }
1313
1314 sub isLinux()
1315 {
1316     return ($^O eq "linux") || 0;
1317 }
1318
1319 sub isFreeBSD()
1320 {
1321     return ($^O eq "freebsd") || 0;
1322 }
1323
1324 sub isARM()
1325 {
1326     return $Config{archname} =~ /^arm-/;
1327 }
1328
1329 sub isCrossCompilation()
1330 {
1331   my $compiler = "";
1332   $compiler = $ENV{'CC'} if (defined($ENV{'CC'}));
1333   if ($compiler =~ /gcc/) {
1334       my $compiler_options = `$compiler -v 2>&1`;
1335       my @host = $compiler_options =~ m/--host=(.*?)\s/;
1336       my @target = $compiler_options =~ m/--target=(.*?)\s/;
1337
1338       return ($host[0] ne "" && $target[0] ne "" && $host[0] ne $target[0]);
1339   }
1340   return 0;
1341 }
1342
1343 sub isAppleWebKit()
1344 {
1345     return !(isQt() or isGtk() or isWx() or isChromium() or isEfl() or isWinCE() or isBlackBerry());
1346 }
1347
1348 sub isAppleMacWebKit()
1349 {
1350     return isAppleWebKit() && isDarwin();
1351 }
1352
1353 sub isAppleWinWebKit()
1354 {
1355     return isAppleWebKit() && (isCygwin() || isWindows());
1356 }
1357
1358 sub isPerianInstalled()
1359 {
1360     if (!isAppleWebKit()) {
1361         return 0;
1362     }
1363
1364     if (-d "/Library/QuickTime/Perian.component") {
1365         return 1;
1366     }
1367
1368     if (-d "$ENV{HOME}/Library/QuickTime/Perian.component") {
1369         return 1;
1370     }
1371
1372     return 0;
1373 }
1374
1375 sub determineNmPath()
1376 {
1377     return if $nmPath;
1378
1379     if (isAppleMacWebKit()) {
1380         $nmPath = `xcrun -find nm`;
1381         chomp $nmPath;
1382     }
1383     $nmPath = "nm" if !$nmPath;
1384 }
1385
1386 sub nmPath()
1387 {
1388     determineNmPath();
1389     return $nmPath;
1390 }
1391
1392 sub determineOSXVersion()
1393 {
1394     return if $osXVersion;
1395
1396     if (!isDarwin()) {
1397         $osXVersion = -1;
1398         return;
1399     }
1400
1401     my $version = `sw_vers -productVersion`;
1402     my @splitVersion = split(/\./, $version);
1403     @splitVersion >= 2 or die "Invalid version $version";
1404     $osXVersion = {
1405             "major" => $splitVersion[0],
1406             "minor" => $splitVersion[1],
1407             "subminor" => (defined($splitVersion[2]) ? $splitVersion[2] : 0),
1408     };
1409 }
1410
1411 sub osXVersion()
1412 {
1413     determineOSXVersion();
1414     return $osXVersion;
1415 }
1416
1417 sub isSnowLeopard()
1418 {
1419     return isDarwin() && osXVersion()->{"minor"} == 6;
1420 }
1421
1422 sub isLion()
1423 {
1424     return isDarwin() && osXVersion()->{"minor"} == 7;
1425 }
1426
1427 sub isWindowsNT()
1428 {
1429     return $ENV{'OS'} eq 'Windows_NT';
1430 }
1431
1432 sub shouldTargetWebProcess
1433 {
1434     determineShouldTargetWebProcess();
1435     return $shouldTargetWebProcess;
1436 }
1437
1438 sub determineShouldTargetWebProcess
1439 {
1440     return if defined($shouldTargetWebProcess);
1441     $shouldTargetWebProcess = checkForArgumentAndRemoveFromARGV("--target-web-process");
1442 }
1443
1444 sub debugger
1445 {
1446     determineDebugger();
1447     return $debugger;
1448 }
1449
1450 sub determineDebugger
1451 {
1452     return if defined($debugger);
1453     if (checkForArgumentAndRemoveFromARGV("--use-lldb")) {
1454         $debugger = "lldb";
1455     } else {
1456         $debugger = "gdb";
1457     }
1458 }
1459
1460 sub appendToEnvironmentVariableList
1461 {
1462     my ($environmentVariableName, $value) = @_;
1463
1464     if (defined($ENV{$environmentVariableName})) {
1465         $ENV{$environmentVariableName} .= ":" . $value;
1466     } else {
1467         $ENV{$environmentVariableName} = $value;
1468     }
1469 }
1470
1471 sub setUpGuardMallocIfNeeded
1472 {
1473     if (!isDarwin()) {
1474         return;
1475     }
1476
1477     if (!defined($shouldUseGuardMalloc)) {
1478         $shouldUseGuardMalloc = checkForArgumentAndRemoveFromARGV("--guard-malloc");
1479     }
1480
1481     if ($shouldUseGuardMalloc) {
1482         appendToEnvironmentVariableList("DYLD_INSERT_LIBRARIES", "/usr/lib/libgmalloc.dylib");
1483     }
1484 }
1485
1486 sub relativeScriptsDir()
1487 {
1488     my $scriptDir = File::Spec->catpath("", File::Spec->abs2rel($FindBin::Bin, getcwd()), "");
1489     if ($scriptDir eq "") {
1490         $scriptDir = ".";
1491     }
1492     return $scriptDir;
1493 }
1494
1495 sub launcherPath()
1496 {
1497     my $relativeScriptsPath = relativeScriptsDir();
1498     if (isGtk() || isQt() || isWx() || isEfl() || isWinCE()) {
1499         return "$relativeScriptsPath/run-launcher";
1500     } elsif (isAppleWebKit()) {
1501         return "$relativeScriptsPath/run-safari";
1502     }
1503 }
1504
1505 sub launcherName()
1506 {
1507     if (isGtk()) {
1508         return "GtkLauncher";
1509     } elsif (isQt()) {
1510         return "QtTestBrowser";
1511     } elsif (isWx()) {
1512         return "wxBrowser";
1513     } elsif (isAppleWebKit()) {
1514         return "Safari";
1515     } elsif (isEfl()) {
1516         return "EWebLauncher";
1517     } elsif (isWinCE()) {
1518         return "WinCELauncher";
1519     }
1520 }
1521
1522 sub checkRequiredSystemConfig
1523 {
1524     if (isDarwin()) {
1525         chomp(my $productVersion = `sw_vers -productVersion`);
1526         if (eval "v$productVersion" lt v10.4) {
1527             print "*************************************************************\n";
1528             print "Mac OS X Version 10.4.0 or later is required to build WebKit.\n";
1529             print "You have " . $productVersion . ", thus the build will most likely fail.\n";
1530             print "*************************************************************\n";
1531         }
1532         my $xcodebuildVersionOutput = `xcodebuild -version`;
1533         my $devToolsCoreVersion = ($xcodebuildVersionOutput =~ /DevToolsCore-(\d+)/) ? $1 : undef;
1534         my $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : undef;
1535         if (!$devToolsCoreVersion && !$xcodeVersion
1536             || $devToolsCoreVersion && $devToolsCoreVersion < 747
1537             || $xcodeVersion && eval "v$xcodeVersion" lt v2.3) {
1538             print "*************************************************************\n";
1539             print "Xcode Version 2.3 or later is required to build WebKit.\n";
1540             print "You have an earlier version of Xcode, thus the build will\n";
1541             print "most likely fail.  The latest Xcode is available from the web:\n";
1542             print "http://developer.apple.com/tools/xcode\n";
1543             print "*************************************************************\n";
1544         }
1545     } elsif (isGtk() or isQt() or isWx() or isEfl()) {
1546         my @cmds = qw(flex bison gperf);
1547         my @missing = ();
1548         foreach my $cmd (@cmds) {
1549             push @missing, $cmd if not commandExists($cmd);
1550         }
1551
1552         if (@missing) {
1553             my $list = join ", ", @missing;
1554             die "ERROR: $list missing but required to build WebKit.\n";
1555         }
1556     }
1557     # Win32 and other platforms may want to check for minimum config
1558 }
1559
1560 sub determineWindowsSourceDir()
1561 {
1562     return if $windowsSourceDir;
1563     $windowsSourceDir = sourceDir();
1564     chomp($windowsSourceDir = `cygpath -w '$windowsSourceDir'`) if isCygwin();
1565 }
1566
1567 sub windowsSourceDir()
1568 {
1569     determineWindowsSourceDir();
1570     return $windowsSourceDir;
1571 }
1572
1573 sub windowsLibrariesDir()
1574 {
1575     return windowsSourceDir() . "\\WebKitLibraries\\win";
1576 }
1577
1578 sub windowsOutputDir()
1579 {
1580     return windowsSourceDir() . "\\WebKitBuild";
1581 }
1582
1583 sub setupAppleWinEnv()
1584 {
1585     return unless isAppleWinWebKit();
1586
1587     if (isWindowsNT()) {
1588         my $restartNeeded = 0;
1589         my %variablesToSet = ();
1590
1591         # FIXME: We should remove this explicit version check for cygwin once we stop supporting Cygwin 1.7.9 or older versions. 
1592         # https://bugs.webkit.org/show_bug.cgi?id=85791
1593         my $currentCygwinVersion = version->parse(`uname -r`);
1594         my $firstCygwinVersionWithoutTTYSupport = version->parse("1.7.10");
1595         if ($currentCygwinVersion < $firstCygwinVersionWithoutTTYSupport) {
1596             # Setting the environment variable 'CYGWIN' to 'tty' makes cygwin enable extra support (i.e., termios)
1597             # for UNIX-like ttys in the Windows console
1598             $variablesToSet{CYGWIN} = "tty" unless $ENV{CYGWIN};
1599         }
1600         
1601         # Those environment variables must be set to be able to build inside Visual Studio.
1602         $variablesToSet{WEBKITLIBRARIESDIR} = windowsLibrariesDir() unless $ENV{WEBKITLIBRARIESDIR};
1603         $variablesToSet{WEBKITOUTPUTDIR} = windowsOutputDir() unless $ENV{WEBKITOUTPUTDIR};
1604
1605         foreach my $variable (keys %variablesToSet) {
1606             print "Setting the Environment Variable '" . $variable . "' to '" . $variablesToSet{$variable} . "'\n\n";
1607             system qw(regtool -s set), '\\HKEY_CURRENT_USER\\Environment\\' . $variable, $variablesToSet{$variable};
1608             $restartNeeded ||= $variable eq "WEBKITLIBRARIESDIR" || $variable eq "WEBKITOUTPUTDIR";
1609         }
1610
1611         if ($restartNeeded) {
1612             print "Please restart your computer before attempting to build inside Visual Studio.\n\n";
1613         }
1614     } else {
1615         if (!$ENV{'WEBKITLIBRARIESDIR'}) {
1616             print "Warning: You must set the 'WebKitLibrariesDir' environment variable\n";
1617             print "         to be able build WebKit from within Visual Studio.\n";
1618             print "         Make sure that 'WebKitLibrariesDir' points to the\n";
1619             print "         'WebKitLibraries/win' directory, not the 'WebKitLibraries/' directory.\n\n";
1620         }
1621         if (!$ENV{'WEBKITOUTPUTDIR'}) {
1622             print "Warning: You must set the 'WebKitOutputDir' environment variable\n";
1623             print "         to be able build WebKit from within Visual Studio.\n\n";
1624         }
1625     }
1626 }
1627
1628 sub setupCygwinEnv()
1629 {
1630     return if !isCygwin() && !isWindows();
1631     return if $vcBuildPath;
1632
1633     my $vsInstallDir;
1634     my $programFilesPath = $ENV{'PROGRAMFILES(X86)'} || $ENV{'PROGRAMFILES'} || "C:\\Program Files";
1635     if ($ENV{'VSINSTALLDIR'}) {
1636         $vsInstallDir = $ENV{'VSINSTALLDIR'};
1637     } else {
1638         $vsInstallDir = File::Spec->catdir($programFilesPath, "Microsoft Visual Studio 8");
1639     }
1640     chomp($vsInstallDir = `cygpath "$vsInstallDir"`) if isCygwin();
1641     $vcBuildPath = File::Spec->catfile($vsInstallDir, qw(Common7 IDE devenv.com));
1642     if (-e $vcBuildPath) {
1643         # Visual Studio is installed; we can use pdevenv to build.
1644         # FIXME: Make pdevenv work with non-Cygwin Perl.
1645         $vcBuildPath = File::Spec->catfile(sourceDir(), qw(Tools Scripts pdevenv)) if isCygwin();
1646     } else {
1647         # Visual Studio not found, try VC++ Express
1648         $vcBuildPath = File::Spec->catfile($vsInstallDir, qw(Common7 IDE VCExpress.exe));
1649         if (! -e $vcBuildPath) {
1650             print "*************************************************************\n";
1651             print "Cannot find '$vcBuildPath'\n";
1652             print "Please execute the file 'vcvars32.bat' from\n";
1653             print "'$programFilesPath\\Microsoft Visual Studio 8\\VC\\bin\\'\n";
1654             print "to setup the necessary environment variables.\n";
1655             print "*************************************************************\n";
1656             die;
1657         }
1658         $willUseVCExpressWhenBuilding = 1;
1659     }
1660
1661     my $qtSDKPath = File::Spec->catdir($programFilesPath, "QuickTime SDK");
1662     if (0 && ! -e $qtSDKPath) {
1663         print "*************************************************************\n";
1664         print "Cannot find '$qtSDKPath'\n";
1665         print "Please download the QuickTime SDK for Windows from\n";
1666         print "http://developer.apple.com/quicktime/download/\n";
1667         print "*************************************************************\n";
1668         die;
1669     }
1670     
1671     unless ($ENV{WEBKITLIBRARIESDIR}) {
1672         $ENV{'WEBKITLIBRARIESDIR'} = File::Spec->catdir($sourceDir, "WebKitLibraries", "win");
1673         chomp($ENV{WEBKITLIBRARIESDIR} = `cygpath -wa '$ENV{WEBKITLIBRARIESDIR}'`) if isCygwin();
1674     }
1675
1676     print "Building results into: ", baseProductDir(), "\n";
1677     print "WEBKITOUTPUTDIR is set to: ", $ENV{"WEBKITOUTPUTDIR"}, "\n";
1678     print "WEBKITLIBRARIESDIR is set to: ", $ENV{"WEBKITLIBRARIESDIR"}, "\n";
1679 }
1680
1681 sub dieIfWindowsPlatformSDKNotInstalled
1682 {
1683     my $registry32Path = "/proc/registry/";
1684     my $registry64Path = "/proc/registry64/";
1685     my $windowsPlatformSDKRegistryEntry = "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/MicrosoftSDK/InstalledSDKs/D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1";
1686
1687     # FIXME: It would be better to detect whether we are using 32- or 64-bit Windows
1688     # and only check the appropriate entry. But for now we just blindly check both.
1689     return if (-e $registry32Path . $windowsPlatformSDKRegistryEntry) || (-e $registry64Path . $windowsPlatformSDKRegistryEntry);
1690
1691     print "*************************************************************\n";
1692     print "Cannot find registry entry '$windowsPlatformSDKRegistryEntry'.\n";
1693     print "Please download and install the Microsoft Windows Server 2003 R2\n";
1694     print "Platform SDK from <http://www.microsoft.com/downloads/details.aspx?\n";
1695     print "familyid=0baf2b35-c656-4969-ace8-e4c0c0716adb&displaylang=en>.\n\n";
1696     print "Then follow step 2 in the Windows section of the \"Installing Developer\n";
1697     print "Tools\" instructions at <http://www.webkit.org/building/tools.html>.\n";
1698     print "*************************************************************\n";
1699     die;
1700 }
1701
1702 sub copyInspectorFrontendFiles
1703 {
1704     my $productDir = productDir();
1705     my $sourceInspectorPath = sourceDir() . "/Source/WebCore/inspector/front-end/";
1706     my $inspectorResourcesDirPath = $ENV{"WEBKITINSPECTORRESOURCESDIR"};
1707
1708     if (!defined($inspectorResourcesDirPath)) {
1709         $inspectorResourcesDirPath = "";
1710     }
1711
1712     if (isAppleMacWebKit()) {
1713         $inspectorResourcesDirPath = $productDir . "/WebCore.framework/Resources/inspector";
1714     } elsif (isAppleWinWebKit()) {
1715         $inspectorResourcesDirPath = $productDir . "/WebKit.resources/inspector";
1716     } elsif (isQt() || isGtk()) {
1717         my $prefix = $ENV{"WebKitInstallationPrefix"};
1718         $inspectorResourcesDirPath = (defined($prefix) ? $prefix : "/usr/share") . "/webkit-1.0/webinspector";
1719     } elsif (isEfl()) {
1720         my $prefix = $ENV{"WebKitInstallationPrefix"};
1721         $inspectorResourcesDirPath = (defined($prefix) ? $prefix : "/usr/share") . "/ewebkit/webinspector";
1722     }
1723
1724     if (! -d $inspectorResourcesDirPath) {
1725         print "*************************************************************\n";
1726         print "Cannot find '$inspectorResourcesDirPath'.\n" if (defined($inspectorResourcesDirPath));
1727         print "Make sure that you have built WebKit first.\n" if (! -d $productDir || defined($inspectorResourcesDirPath));
1728         print "Optionally, set the environment variable 'WebKitInspectorResourcesDir'\n";
1729         print "to point to the directory that contains the WebKit Inspector front-end\n";
1730         print "files for the built WebCore framework.\n";
1731         print "*************************************************************\n";
1732         die;
1733     }
1734
1735     if (isAppleMacWebKit()) {
1736         my $sourceLocalizedStrings = sourceDir() . "/Source/WebCore/English.lproj/localizedStrings.js";
1737         my $destinationLocalizedStrings = $productDir . "/WebCore.framework/Resources/English.lproj/localizedStrings.js";
1738         system "ditto", $sourceLocalizedStrings, $destinationLocalizedStrings;
1739     }
1740
1741     return system "rsync", "-aut", "--exclude=/.DS_Store", "--exclude=*.re2js", "--exclude=.svn/", !isQt() ? "--exclude=/WebKit.qrc" : "", $sourceInspectorPath, $inspectorResourcesDirPath;
1742 }
1743
1744 sub buildXCodeProject($$@)
1745 {
1746     my ($project, $clean, @extraOptions) = @_;
1747
1748     if ($clean) {
1749         push(@extraOptions, "-alltargets");
1750         push(@extraOptions, "clean");
1751     }
1752
1753     return system "xcodebuild", "-project", "$project.xcodeproj", @extraOptions;
1754 }
1755
1756 sub usingVisualStudioExpress()
1757 {
1758     setupCygwinEnv();
1759     return $willUseVCExpressWhenBuilding;
1760 }
1761
1762 sub buildVisualStudioProject
1763 {
1764     my ($project, $clean) = @_;
1765     setupCygwinEnv();
1766
1767     my $config = configurationForVisualStudio();
1768
1769     dieIfWindowsPlatformSDKNotInstalled() if $willUseVCExpressWhenBuilding;
1770
1771     chomp($project = `cygpath -w "$project"`) if isCygwin();
1772     
1773     my $action = "/build";
1774     if ($clean) {
1775         $action = "/clean";
1776     }
1777
1778     my @command = ($vcBuildPath, $project, $action, $config);
1779
1780     print join(" ", @command), "\n";
1781     return system @command;
1782 }
1783
1784 sub downloadWafIfNeeded
1785 {
1786     # get / update waf if needed
1787     my $waf = "$sourceDir/Tools/waf/waf";
1788     my $wafURL = 'http://wxwebkit.kosoftworks.com/downloads/deps/waf';
1789     if (!-f $waf) {
1790         my $result = system "curl -o $waf $wafURL";
1791         chmod 0755, $waf;
1792     }
1793 }
1794
1795 sub buildWafProject
1796 {
1797     my ($project, $shouldClean, @options) = @_;
1798     
1799     # set the PYTHONPATH for waf
1800     my $pythonPath = $ENV{'PYTHONPATH'};
1801     if (!defined($pythonPath)) {
1802         $pythonPath = '';
1803     }
1804     my $sourceDir = sourceDir();
1805     my $newPythonPath = "$sourceDir/Tools/waf/build:$pythonPath";
1806     if (isCygwin()) {
1807         $newPythonPath = `cygpath --mixed --path $newPythonPath`;
1808     }
1809     $ENV{'PYTHONPATH'} = $newPythonPath;
1810     
1811     print "Building $project\n";
1812
1813     my $wafCommand = "$sourceDir/Tools/waf/waf";
1814     if ($ENV{'WXWEBKIT_WAF'}) {
1815         $wafCommand = $ENV{'WXWEBKIT_WAF'};
1816     }
1817     if (isCygwin()) {
1818         $wafCommand = `cygpath --windows "$wafCommand"`;
1819         chomp($wafCommand);
1820     }
1821     if ($shouldClean) {
1822         return system $wafCommand, "uninstall", "clean", "distclean";
1823     }
1824     
1825     return system $wafCommand, 'configure', 'build', 'install', @options;
1826 }
1827
1828 sub retrieveQMakespecVar
1829 {
1830     my $mkspec = $_[0];
1831     my $varname = $_[1];
1832
1833     my $varvalue = undef;
1834     #print "retrieveMakespecVar " . $mkspec . ", " . $varname . "\n";
1835
1836     local *SPEC;
1837     open SPEC, "<$mkspec" or return $varvalue;
1838     while (<SPEC>) {
1839         if ($_ =~ /\s*include\((.+)\)/) {
1840             # open the included mkspec
1841             my $oldcwd = getcwd();
1842             (my $volume, my $directories, my $file) = File::Spec->splitpath($mkspec);
1843             my $newcwd = "$volume$directories";
1844             chdir $newcwd if $newcwd;
1845             $varvalue = retrieveQMakespecVar($1, $varname);
1846             chdir $oldcwd;
1847         } elsif ($_ =~ /$varname\s*=\s*([^\s]+)/) {
1848             $varvalue = $1;
1849             last;
1850         }
1851     }
1852     close SPEC;
1853     return $varvalue;
1854 }
1855
1856 sub qtMakeCommand($)
1857 {
1858     my ($qmakebin) = @_;
1859     chomp(my $mkspec = `$qmakebin -query QMAKE_MKSPECS`);
1860     $mkspec .= "/default";
1861     my $compiler = retrieveQMakespecVar("$mkspec/qmake.conf", "QMAKE_CC");
1862
1863     #print "default spec: " . $mkspec . "\n";
1864     #print "compiler found: " . $compiler . "\n";
1865
1866     if ($compiler && $compiler eq "cl") {
1867         return "nmake";
1868     }
1869
1870     return "make";
1871 }
1872
1873 sub autotoolsFlag($$)
1874 {
1875     my ($flag, $feature) = @_;
1876     my $prefix = $flag ? "--enable" : "--disable";
1877
1878     return $prefix . '-' . $feature;
1879 }
1880
1881 sub getMD5HashForFile($)
1882 {
1883     my $file = shift;
1884
1885     open(FILE_CONTENTS, $file);
1886
1887     # Read the whole file.
1888     my $contents = "";
1889     while (<FILE_CONTENTS>) {
1890         $contents .= $_;
1891     }
1892
1893     close(FILE_CONTENTS);
1894
1895     return md5_hex($contents);
1896 }
1897
1898 sub runAutogenForAutotoolsProjectIfNecessary($@)
1899 {
1900     my ($dir, $prefix, $sourceDir, $project, @buildArgs) = @_;
1901
1902     my $argumentsFile = "previous-autogen-arguments.txt";
1903     if (-e "GNUmakefile") {
1904         # Just assume that build-jsc will never be used to reconfigure JSC. Later
1905         # we can go back and make this more complicated if the demand is there.
1906         if ($project ne "WebKit") {
1907             return;
1908         }
1909
1910         # We only run autogen.sh again if the arguments passed have changed.
1911         if (!mustReRunAutogen($sourceDir, $argumentsFile, @buildArgs)) {
1912             return;
1913         }
1914     }
1915
1916     print "Calling autogen.sh in " . $dir . "\n\n";
1917     print "Installation prefix directory: $prefix\n" if(defined($prefix));
1918
1919     # Only for WebKit, write the autogen.sh arguments to a file so that we can detect
1920     # when they change and automatically re-run it.
1921     if ($project eq 'WebKit') {
1922         open(AUTOTOOLS_ARGUMENTS, ">$argumentsFile");
1923         print AUTOTOOLS_ARGUMENTS join(" ", @buildArgs);
1924         close(AUTOTOOLS_ARGUMENTS);
1925     }
1926
1927     # Make the path relative since it will appear in all -I compiler flags.
1928     # Long argument lists cause bizarre slowdowns in libtool.
1929     my $relSourceDir = File::Spec->abs2rel($sourceDir) || ".";
1930
1931     # Compiler options to keep floating point values consistent
1932     # between 32-bit and 64-bit architectures. The options are also
1933     # used on Chromium build.
1934     determineArchitecture();
1935     if ($architecture ne "x86_64" && !isARM()) {
1936         $ENV{'CXXFLAGS'} = "-march=pentium4 -msse2 -mfpmath=sse " . ($ENV{'CXXFLAGS'} || "");
1937     }
1938
1939     # Prefix the command with jhbuild run.
1940     unshift(@buildArgs, "$relSourceDir/autogen.sh");
1941     unshift(@buildArgs, "$sourceDir/Tools/gtk/run-with-jhbuild");
1942     if (system(@buildArgs) ne 0) {
1943         die "Calling autogen.sh failed!\n";
1944     }
1945 }
1946
1947 sub getJhbuildPath()
1948 {
1949     return join('/', baseProductDir(), "Dependencies");
1950 }
1951
1952 sub jhbuildConfigurationChanged()
1953 {
1954     foreach my $file (qw(jhbuildrc.md5sum jhbuild.modules.md5sum)) {
1955         my $path = join('/', getJhbuildPath(), $file);
1956         if (! -e $path) {
1957             return 1;
1958         }
1959
1960         # Get the md5 sum of the file we're testing, look in the right platform directory.
1961         $file =~ m/(.+)\.md5sum/;
1962         my $platformDir = isEfl() ? 'efl' : 'gtk';
1963         my $actualFile = join('/', $sourceDir, 'Tools', $platformDir, $1);
1964         my $currentSum = getMD5HashForFile($actualFile);
1965
1966         # Get our previous record.
1967         open(PREVIOUS_MD5, $path);
1968         chomp(my $previousSum = <PREVIOUS_MD5>);
1969         close(PREVIOUS_MD5);
1970
1971         if ($previousSum ne $currentSum) {
1972             return 1;
1973         }
1974     }
1975 }
1976
1977 sub saveJhbuildMd5() {
1978     my $platform = isEfl() ? 'efl' : 'gtk';
1979     # Save md5sum for jhbuild-related files.
1980     foreach my $file (qw(jhbuildrc jhbuild.modules)) {
1981         my $source = join('/', $sourceDir, "Tools", $platform, $file);
1982         my $destination = join('/', getJhbuildPath(), $file);
1983         open(SUM, ">$destination" . ".md5sum");
1984         print SUM getMD5HashForFile($source);
1985         close(SUM);
1986     }
1987 }
1988
1989 sub cleanJhbuild() {
1990         # If the configuration changed, dependencies may have been removed.
1991         # Since we lack a granular way of uninstalling those we wipe out the
1992         # jhbuild root and start from scratch.
1993         my $jhbuildPath = getJhbuildPath();
1994         if (system("rm -rf $jhbuildPath/Root") ne 0) {
1995             die "Cleaning jhbuild root failed!";
1996         }
1997
1998         my $platform = isEfl() ? 'efl' : 'gtk';
1999         if (system("perl $sourceDir/Tools/jhbuild/jhbuild-wrapper --$platform clean") ne 0) {
2000             die "Cleaning jhbuild modules failed!";
2001         }
2002 }
2003
2004 sub mustReRunAutogen($@)
2005 {
2006     my ($sourceDir, $filename, @currentArguments) = @_;
2007
2008     if (! -e $filename) {
2009         return 1;
2010     }
2011
2012     open(AUTOTOOLS_ARGUMENTS, $filename);
2013     chomp(my $previousArguments = <AUTOTOOLS_ARGUMENTS>);
2014     close(AUTOTOOLS_ARGUMENTS);
2015
2016     # We only care about the WebKit2 argument when we are building WebKit itself.
2017     # build-jsc never passes --enable-webkit2, so if we didn't do this, autogen.sh
2018     # would run for every single build on the bots, since it runs both build-webkit
2019     # and build-jsc.
2020     my $joinedCurrentArguments = join(" ", @currentArguments);
2021     if ($previousArguments ne $joinedCurrentArguments) {
2022         print "Previous autogen arguments were: $previousArguments\n\n";
2023         print "New autogen arguments are: $joinedCurrentArguments\n";
2024         return 1;
2025     }
2026
2027     return 0;
2028 }
2029
2030 sub buildAutotoolsProject($@)
2031 {
2032     my ($project, $clean, @buildParams) = @_;
2033
2034     my $make = 'make';
2035     my $dir = productDir();
2036     my $config = passedConfiguration() || configuration();
2037     my $prefix;
2038
2039     # Use rm to clean the build directory since distclean may miss files
2040     if ($clean && -d $dir) {
2041         system "rm", "-rf", "$dir";
2042     }
2043
2044     if (! -d $dir) {
2045         File::Path::mkpath($dir) or die "Failed to create build directory " . $dir
2046     }
2047     chdir $dir or die "Failed to cd into " . $dir . "\n";
2048
2049     if ($clean) {
2050         return 0;
2051     }
2052
2053     my @buildArgs = ();
2054     my $makeArgs = $ENV{"WebKitMakeArguments"} || "";
2055     for my $i (0 .. $#buildParams) {
2056         my $opt = $buildParams[$i];
2057         if ($opt =~ /^--makeargs=(.*)/i ) {
2058             $makeArgs = $makeArgs . " " . $1;
2059         } elsif ($opt =~ /^--prefix=(.*)/i ) {
2060             $prefix = $1;
2061         } else {
2062             push @buildArgs, $opt;
2063         }
2064     }
2065
2066     # Automatically determine the number of CPUs for make only
2067     # if make arguments haven't already been specified.
2068     if ($makeArgs eq "") {
2069         $makeArgs = "-j" . numberOfCPUs();
2070     }
2071
2072     # WebKit is the default target, so we don't need to specify anything.
2073     if ($project eq "JavaScriptCore") {
2074         $makeArgs .= " jsc";
2075     } elsif ($project eq "WTF") {
2076         $makeArgs .= " libWTF.la";
2077     }
2078
2079     $prefix = $ENV{"WebKitInstallationPrefix"} if !defined($prefix);
2080     push @buildArgs, "--prefix=" . $prefix if defined($prefix);
2081
2082     # Check if configuration is Debug.
2083     my $debug = $config =~ m/debug/i;
2084     if ($debug) {
2085         push @buildArgs, "--enable-debug";
2086     } else {
2087         push @buildArgs, "--disable-debug";
2088     }
2089
2090     # Enable unstable features when building through build-webkit.
2091     push @buildArgs, "--enable-unstable-features";
2092
2093     # We might need to update jhbuild dependencies.
2094     my $needUpdate = 0;
2095     if (jhbuildConfigurationChanged()) {
2096         cleanJhbuild();
2097         $needUpdate = 1;
2098     }
2099
2100     if (checkForArgumentAndRemoveFromArrayRef("--update-gtk", \@buildArgs)) {
2101         $needUpdate = 1;
2102     }
2103
2104     if ($needUpdate) {
2105         # Force autogen to run, to catch the possibly updated libraries.
2106         system("rm -f previous-autogen-arguments.txt");
2107
2108         system("perl", "$sourceDir/Tools/Scripts/update-webkitgtk-libs") == 0 or die $!;
2109     }
2110
2111     saveJhbuildMd5();
2112
2113     # If GNUmakefile exists, don't run autogen.sh unless its arguments
2114     # have changed. The makefile should be smart enough to track autotools
2115     # dependencies and re-run autogen.sh when build files change.
2116     runAutogenForAutotoolsProjectIfNecessary($dir, $prefix, $sourceDir, $project, @buildArgs);
2117
2118     my $gtkScriptsPath = "$sourceDir/Tools/gtk";
2119     my $runWithJhbuild = "$gtkScriptsPath/run-with-jhbuild";
2120     if (system("$runWithJhbuild $make $makeArgs") ne 0) {
2121         die "\nFailed to build WebKit using '$make'!\n";
2122     }
2123
2124     chdir ".." or die;
2125
2126     if ($project eq 'WebKit' && !isCrossCompilation()) {
2127         my @docGenerationOptions = ($runWithJhbuild, "$gtkScriptsPath/generate-gtkdoc", "--skip-html");
2128         push(@docGenerationOptions, productDir());
2129
2130         if (system(@docGenerationOptions)) {
2131             die "\n gtkdoc did not build without warnings\n";
2132         }
2133     }
2134
2135     return 0;
2136 }
2137
2138 sub jhbuildWrapperPrefixIfNeeded()
2139 {
2140     if (isEfl()) {
2141         return File::Spec->catfile(sourceDir(), "Tools", "efl", "run-with-jhbuild");
2142     }
2143     return "";
2144 }
2145
2146 sub removeCMakeCache()
2147 {
2148     my $cacheFilePath = File::Spec->catdir(baseProductDir(), configuration(), "CMakeCache.txt");
2149     unlink($cacheFilePath) if -e $cacheFilePath;
2150 }
2151
2152 sub generateBuildSystemFromCMakeProject
2153 {
2154     my ($port, $prefixPath, @cmakeArgs, $additionalCMakeArgs) = @_;
2155     my $config = configuration();
2156     my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2157     File::Path::mkpath($buildPath) unless -d $buildPath;
2158     my $originalWorkingDirectory = getcwd();
2159     chdir($buildPath) or die;
2160
2161     my @args;
2162     push @args, "-DPORT=\"$port\"";
2163     push @args, "-DCMAKE_INSTALL_PREFIX=\"$prefixPath\"" if $prefixPath;
2164     push @args, "-DSHARED_CORE=ON" if isEfl() && $ENV{"ENABLE_DRT"};
2165     if ($config =~ /release/i) {
2166         push @args, "-DCMAKE_BUILD_TYPE=Release";
2167     } elsif ($config =~ /debug/i) {
2168         push @args, "-DCMAKE_BUILD_TYPE=Debug";
2169     }
2170     # if ENABLE(TIZEN_WEBKIT_EFL_DRT)
2171     push @args, "-DSHARED_CORE=ON";
2172     # endif
2173     push @args, @cmakeArgs if @cmakeArgs;
2174     push @args, $additionalCMakeArgs if $additionalCMakeArgs;
2175
2176     push @args, '"' . sourceDir() . '"';
2177
2178     # Compiler options to keep floating point values consistent
2179     # between 32-bit and 64-bit architectures.
2180     determineArchitecture();
2181     if ($architecture ne "x86_64" && !isARM()) {
2182         $ENV{'CXXFLAGS'} = "-march=pentium4 -msse2 -mfpmath=sse " . ($ENV{'CXXFLAGS'} || "");
2183     }
2184
2185     if (isEfl() && jhbuildConfigurationChanged()) {
2186         cleanJhbuild();
2187         system("perl", "$sourceDir/Tools/Scripts/update-webkitefl-libs") == 0 or die $!;
2188     }
2189
2190     if (isEfl()) {
2191         saveJhbuildMd5();
2192     }
2193
2194     # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2195     # parsed for shell metacharacters.
2196     my $wrapper = jhbuildWrapperPrefixIfNeeded() . " ";
2197     my $returnCode = system($wrapper . "cmake @args");
2198
2199     chdir($originalWorkingDirectory);
2200     return $returnCode;
2201 }
2202
2203 sub buildCMakeGeneratedProject($)
2204 {
2205     my ($makeArgs) = @_;
2206     my $config = configuration();
2207     my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2208     if (! -d $buildPath) {
2209         die "Must call generateBuildSystemFromCMakeProject() before building CMake project.";
2210     }
2211     my @args = ("--build", $buildPath, "--config", $config);
2212     push @args, ("--", $makeArgs) if $makeArgs;
2213
2214     # We call system("cmake @args") instead of system("cmake", @args) so that @args is
2215     # parsed for shell metacharacters. In particular, $makeArgs may contain such metacharacters.
2216     my $wrapper = jhbuildWrapperPrefixIfNeeded() . " ";
2217     return system($wrapper . "cmake @args");
2218 }
2219
2220 sub cleanCMakeGeneratedProject()
2221 {
2222     my $config = configuration();
2223     my $buildPath = File::Spec->catdir(baseProductDir(), $config);
2224     if (-d $buildPath) {
2225         return system("cmake", "--build", $buildPath, "--config", $config, "--target", "clean");
2226     }
2227     return 0;
2228 }
2229
2230 sub buildCMakeProjectOrExit($$$$@)
2231 {
2232     my ($clean, $port, $prefixPath, $makeArgs, @cmakeArgs) = @_;
2233     my $returnCode;
2234
2235     exit(exitStatus(cleanCMakeGeneratedProject())) if $clean;
2236
2237     $returnCode = exitStatus(generateBuildSystemFromCMakeProject($port, $prefixPath, @cmakeArgs));
2238     exit($returnCode) if $returnCode;
2239     $returnCode = exitStatus(buildCMakeGeneratedProject($makeArgs));
2240     exit($returnCode) if $returnCode;
2241     return 0;
2242 }
2243
2244 sub cmakeBasedPortArguments()
2245 {
2246     return blackberryCMakeArguments() if isBlackBerry();
2247     return ('-DCMAKE_WINCE_SDK="STANDARDSDK_500 (ARMV4I)"') if isWinCE();
2248     return ();
2249 }
2250
2251 sub cmakeBasedPortName()
2252 {
2253     return "BlackBerry" if isBlackBerry();
2254     return "Efl" if isEfl();
2255     return "WinCE" if isWinCE();
2256     return "";
2257 }
2258
2259 sub promptUser
2260 {
2261     my ($prompt, $default) = @_;
2262     my $defaultValue = $default ? "[$default]" : "";
2263     print "$prompt $defaultValue: ";
2264     chomp(my $input = <STDIN>);
2265     return $input ? $input : $default;
2266 }
2267
2268 sub buildQMakeProjects
2269 {
2270     my ($projects, $clean, @buildParams) = @_;
2271
2272     my @buildArgs = ();
2273     my $qconfigs = "";
2274
2275     my $make = qtMakeCommand($qmakebin);
2276     my $makeargs = "";
2277     my $installHeaders;
2278     my $installLibs;
2279     for my $i (0 .. $#buildParams) {
2280         my $opt = $buildParams[$i];
2281         if ($opt =~ /^--qmake=(.*)/i ) {
2282             $qmakebin = $1;
2283         } elsif ($opt =~ /^--qmakearg=(.*)/i ) {
2284             push @buildArgs, $1;
2285         } elsif ($opt =~ /^--makeargs=(.*)/i ) {
2286             $makeargs = $1;
2287         } elsif ($opt =~ /^--install-headers=(.*)/i ) {
2288             $installHeaders = $1;
2289         } elsif ($opt =~ /^--install-libs=(.*)/i ) {
2290             $installLibs = $1;
2291         } else {
2292             push @buildArgs, $opt;
2293         }
2294     }
2295
2296     # Automatically determine the number of CPUs for make only if this make argument haven't already been specified.
2297     if ($make eq "make" && $makeargs !~ /-j\s*\d+/i && (!defined $ENV{"MAKEFLAGS"} || ($ENV{"MAKEFLAGS"} !~ /-j\s*\d+/i ))) {
2298         $makeargs .= " -j" . numberOfCPUs();
2299     }
2300
2301     my $qmakepath = File::Spec->catfile(sourceDir(), "Tools", "qmake");
2302     my $qmakecommand;
2303     if (isWindows()) {
2304         $qmakecommand = "(set QMAKEPATH=$qmakepath) && $qmakebin";
2305     } else {
2306         $qmakecommand = "QMAKEPATH=$qmakepath $qmakebin";
2307     }
2308
2309     my $config = configuration();
2310     push @buildArgs, "INSTALL_HEADERS=" . $installHeaders if defined($installHeaders);
2311     push @buildArgs, "INSTALL_LIBS=" . $installLibs if defined($installLibs);
2312
2313     my $passedConfig = passedConfiguration() || "";
2314     if ($passedConfig =~ m/debug/i) {
2315         push @buildArgs, "CONFIG-=release";
2316         push @buildArgs, "CONFIG+=debug";
2317     } elsif ($passedConfig =~ m/release/i) {
2318         push @buildArgs, "CONFIG+=release";
2319         push @buildArgs, "CONFIG-=debug";
2320     } elsif ($passedConfig) {
2321         die "Build type $passedConfig is not supported with --qt.\n";
2322     }
2323     push @buildArgs, "CONFIG-=debug_and_release" if ($passedConfig && isDarwin());
2324
2325     my $originalCwd = getcwd();
2326     my $dir = File::Spec->canonpath(productDir());
2327     File::Path::mkpath($dir);
2328     chdir $dir or die "Failed to cd into " . $dir . "\n";
2329
2330     my %defines = qtFeatureDefaults(\@buildArgs, \$qconfigs);
2331
2332     my $svnRevision = currentSVNRevision();
2333
2334     my $buildHint = "";
2335
2336     my $pathToDefinesCache = File::Spec->catfile($dir, ".webkit.config");
2337     my $pathToOldDefinesFile = File::Spec->catfile($dir, "defaults.txt");
2338
2339     # FIXME: Get rid of .webkit.config and defaults.txt and move all the logic to .qmake.cache
2340
2341     # Ease transition to new build layout
2342     if (-e $pathToOldDefinesFile) {
2343         print "Old build layout detected";
2344         $buildHint = "clean";
2345     } elsif (-e $pathToDefinesCache && open(DEFAULTS, $pathToDefinesCache)) {
2346         my %previousDefines;
2347         while (<DEFAULTS>) {
2348             if ($_ =~ m/(\S+)=(\S+)/gi) {
2349                 $previousDefines{$1} = $2;
2350             }
2351         }
2352         close (DEFAULTS);
2353
2354         $previousDefines{"SVN_REVISION"} = "unknown" if not exists $previousDefines{"SVN_REVISION"};
2355
2356         if ($svnRevision ne $previousDefines{"SVN_REVISION"}) {
2357             print "Last built revision was " . $previousDefines{"SVN_REVISION"} .
2358                 ", now at revision $svnRevision. Full incremental build needed.\n";
2359
2360             $buildHint = "incremental";
2361         }
2362
2363         # Don't confuse the should-we-clean heuristics below
2364         delete($previousDefines{"SVN_REVISION"});
2365
2366         my @uniqueDefineNames = keys %{ +{ map { $_, 1 } (keys %defines, keys %previousDefines) } };
2367         foreach my $define (@uniqueDefineNames) {
2368             if (! exists $previousDefines{$define}) {
2369                 print "Feature $define added";
2370                 $buildHint = "clean";
2371                 last;
2372             }
2373
2374             if (! exists $defines{$define}) {
2375                 print "Feature $define removed";
2376                 $buildHint = "clean";
2377                 last;
2378             }
2379
2380             if ($defines{$define} != $previousDefines{$define}) {
2381                 print "Feature $define changed ($previousDefines{$define} -> $defines{$define})";
2382                 $buildHint = "clean";
2383                 last;
2384             }
2385         }
2386     } else {
2387         # Missing build cache suggests we had a broken build after a clean,
2388         # so we assume we have to do an incremental build just in case.
2389         $buildHint = "incremental";
2390     }
2391
2392     if ($buildHint eq "clean") {
2393         print ", clean build needed!\n";
2394         # FIXME: This STDIN/STDOUT check does not work on the bots. Disable until it does.
2395         # if (! -t STDIN || ( &promptUser("Would you like to clean the build directory?", "yes") eq "yes")) {
2396             chdir $originalCwd;
2397             File::Path::rmtree($dir);
2398             File::Path::mkpath($dir);
2399             chdir $dir or die "Failed to cd into " . $dir . "\n";
2400         #}
2401
2402         # Still trigger an incremental build
2403         $buildHint = "incremental";
2404     }
2405
2406     if ($buildHint eq "incremental") {
2407         my $qmakeDefines = "DEFINES +=";
2408         foreach my $key (sort keys %defines) {
2409             $qmakeDefines .= " \\\n    $key=$defines{$key}";
2410         }
2411         open(QMAKE_CACHE, ">.qmake.cache") or die "Cannot create .qmake.cache!\n";
2412         print QMAKE_CACHE "CONFIG += webkit_configured $qconfigs\n";
2413         print QMAKE_CACHE $qmakeDefines."\n";
2414         close(QMAKE_CACHE);
2415     }
2416
2417     # Save config up-front so we can detect changes to the build config even
2418     # when the user re-configures after aborting the build.
2419     open(DEFAULTS, ">$pathToDefinesCache");
2420     print DEFAULTS "# These defines were set when building WebKit last time\n";
2421     foreach my $key (sort keys %defines) {
2422         print DEFAULTS "$key=$defines{$key}\n";
2423     }
2424     close(DEFAULTS);
2425
2426     my $result = 0;
2427
2428     my $makefile = File::Spec->catfile($dir, "Makefile");
2429     if (! -e $makefile) {
2430         push @buildArgs, "-after OVERRIDE_SUBDIRS=\"@{$projects}\"" if @{$projects};
2431
2432         push @buildArgs, File::Spec->catfile(sourceDir(), "WebKit.pro");
2433         my $command = "$qmakecommand @buildArgs";
2434         print "Calling '$command' in " . $dir . "\n\n";
2435         print "Installation headers directory: $installHeaders\n" if(defined($installHeaders));
2436         print "Installation libraries directory: $installLibs\n" if(defined($installLibs));
2437
2438         $result = system "$command";
2439         if ($result ne 0) {
2440            die "Failed to setup build environment using $qmakebin!\n";
2441         }
2442     }
2443
2444     my $command = "$make $makeargs";
2445     $command =~ s/\s+$//;
2446
2447     if ($clean) {
2448         $command = "$command distclean";
2449     } elsif ($buildHint eq "incremental") {
2450         $command = "$command incremental";
2451     }
2452
2453     print "Calling '$command' in " . $dir . "\n\n";
2454     $result = system $command;
2455
2456     chdir ".." or die;
2457
2458     if ($result eq 0) {
2459         # Now that the build completed successfully we can save the SVN revision
2460         open(DEFAULTS, ">>$pathToDefinesCache");
2461         print DEFAULTS "SVN_REVISION=$svnRevision\n";
2462         close(DEFAULTS);
2463     } elsif ($buildHint eq "" && exitStatus($result)) {
2464         my $exitCode = exitStatus($result);
2465         my $failMessage = <<EOF;
2466
2467 ===== BUILD FAILED ======
2468
2469 The build failed with exit code $exitCode. This may have been because you
2470
2471   - added an #include to a source/header
2472   - added a Q_OBJECT macro to a class
2473   - added a new resource to a qrc file
2474
2475 as dependencies are not automatically re-computed for local developer builds.
2476 You may try computing dependencies manually by running 'make qmake' in:
2477
2478   $dir
2479
2480 or passing --makeargs="qmake" to build-webkit.
2481
2482 =========================
2483
2484 EOF
2485         print "$failMessage";
2486     }
2487
2488     return $result;
2489 }
2490
2491 sub buildGtkProject
2492 {
2493     my ($project, $clean, @buildArgs) = @_;
2494
2495     if ($project ne "WebKit" and $project ne "JavaScriptCore" and $project ne "WTF") {
2496         die "Unsupported project: $project. Supported projects: WebKit, JavaScriptCore, WTF\n";
2497     }
2498
2499     return buildAutotoolsProject($project, $clean, @buildArgs);
2500 }
2501
2502 sub buildChromiumMakefile($$@)
2503 {
2504     my ($target, $clean, @options) = @_;
2505     if ($clean) {
2506         return system qw(rm -rf out);
2507     }
2508     my $config = configuration();
2509     my $numCpus = numberOfCPUs();
2510     my $makeArgs;
2511     for (@options) {
2512         $makeArgs = $1 if /^--makeargs=(.*)/i;
2513     }
2514     $makeArgs = "-j$numCpus" if not $makeArgs;
2515     my $command .= "make -fMakefile.chromium $makeArgs BUILDTYPE=$config $target";
2516
2517     print "$command\n";
2518     return system $command;
2519 }
2520
2521 sub buildChromiumNinja($$@)
2522 {
2523     # rm -rf out requires rerunning gyp, so don't support --clean for now.
2524     my ($target, @options) = @_;
2525     my $config = configuration();
2526     my $makeArgs = "";
2527     for (@options) {
2528         $makeArgs = $1 if /^--makeargs=(.*)/i;
2529     }
2530     my $command = "";
2531
2532     $command .= "ninja -C out/$config $target $makeArgs";
2533
2534     print "$command\n";
2535     return system $command;
2536 }
2537
2538 sub buildChromiumVisualStudioProject($$)
2539 {
2540     my ($projectPath, $clean) = @_;
2541
2542     my $config = configuration();
2543     my $action = "/build";
2544     $action = "/clean" if $clean;
2545
2546     # Find Visual Studio installation.
2547     my $vsInstallDir;
2548     my $programFilesPath = $ENV{'PROGRAMFILES'} || "C:\\Program Files";
2549     if ($ENV{'VSINSTALLDIR'}) {
2550         $vsInstallDir = $ENV{'VSINSTALLDIR'};
2551     } else {
2552         $vsInstallDir = "$programFilesPath/Microsoft Visual Studio 8";
2553     }
2554     $vsInstallDir =~ s,\\,/,g;
2555     $vsInstallDir = `cygpath "$vsInstallDir"` if isCygwin();
2556     chomp $vsInstallDir;
2557     $vcBuildPath = "$vsInstallDir/Common7/IDE/devenv.com";
2558     if (! -e $vcBuildPath) {
2559         # Visual Studio not found, try VC++ Express
2560         $vcBuildPath = "$vsInstallDir/Common7/IDE/VCExpress.exe";
2561         if (! -e $vcBuildPath) {
2562             print "*************************************************************\n";
2563             print "Cannot find '$vcBuildPath'\n";
2564             print "Please execute the file 'vcvars32.bat' from\n";
2565             print "'$programFilesPath\\Microsoft Visual Studio 8\\VC\\bin\\'\n";
2566             print "to setup the necessary environment variables.\n";
2567             print "*************************************************************\n";
2568             die;
2569         }
2570     }
2571
2572     # Create command line and execute it.
2573     my @command = ($vcBuildPath, $projectPath, $action, $config);
2574     print "Building results into: ", baseProductDir(), "\n";
2575     print join(" ", @command), "\n";
2576     return system @command;
2577 }
2578
2579 sub buildChromium($@)
2580 {
2581     my ($clean, @options) = @_;
2582
2583     # We might need to update DEPS or re-run GYP if things have changed.
2584     if (checkForArgumentAndRemoveFromArrayRef("--update-chromium", \@options)) {
2585         system("perl", "Tools/Scripts/update-webkit-chromium", "--force") == 0 or die $!;
2586     }
2587
2588     my $result = 1;
2589     if (isDarwin() && !isChromiumAndroid() && !isChromiumMacMake() && !isChromiumNinja()) {
2590         # Mac build - builds the root xcode project.
2591         $result = buildXCodeProject("Source/WebKit/chromium/All", $clean, "-configuration", configuration(), @options);
2592     } elsif (isCygwin() || isWindows()) {
2593         # Windows build - builds the root visual studio solution.
2594         $result = buildChromiumVisualStudioProject("Source/WebKit/chromium/All.sln", $clean);
2595     } elsif (isChromiumNinja()) {
2596         $result = buildChromiumNinja("all", $clean, @options);
2597     } elsif (isLinux() || isChromiumAndroid() || isChromiumMacMake()) {
2598         # Linux build - build using make.
2599         $result = buildChromiumMakefile("all", $clean, @options);
2600     } else {
2601         print STDERR "This platform is not supported by chromium.\n";
2602     }
2603     return $result;
2604 }
2605
2606 sub chromiumInstall64BitAndroidLinkerIfNeeded
2607 {
2608     my ($androidNdkRoot) = @_;
2609
2610     # Resolve the toolchain version through glob().
2611     my $linkerDirPrefix = glob("$androidNdkRoot/toolchains/arm-linux-androideabi-*/prebuilt/linux-x86");
2612
2613     my $linkerDirname1 = "$linkerDirPrefix/bin";
2614     my $linkerBasename1 = "arm-linux-androideabi-ld";
2615     my $linkerDirname2 = "$linkerDirPrefix/arm-linux-androideabi/bin";
2616     my $linkerBasename2 = "ld";
2617     my $newLinker = "arm-linux-androideabi-ld.e4df3e0a5bb640ccfa2f30ee67fe9b3146b152d6";
2618
2619     # Do not continue if the new linker is not (yet) available.
2620     if (! -e "third_party/aosp/$newLinker") {
2621         return;
2622     }
2623
2624     chromiumReplaceAndroidLinkerIfNeeded($linkerDirname1, $linkerBasename1, $newLinker);
2625     chromiumReplaceAndroidLinkerIfNeeded($linkerDirname2, $linkerBasename2, $newLinker);
2626 }
2627
2628 sub chromiumReplaceAndroidLinkerIfNeeded
2629 {
2630     my ($linkerDirname, $linkerBasename, $newLinker) = @_;
2631
2632     # If the destination directory does not exist, or the linker has already
2633     # been installed, replacing it will not be necessary.
2634     if (! -d "$linkerDirname" || -e "$linkerDirname/$newLinker") {
2635         return;
2636     }
2637
2638     print "Installing 64-bit Android linker in $linkerDirname..\n";
2639     system("cp", "third_party/aosp/$newLinker", "$linkerDirname/$newLinker");
2640     system("mv", "$linkerDirname/$linkerBasename", "$linkerDirname/$linkerBasename.orig");
2641     system("ln", "-s", "$newLinker", "$linkerDirname/$linkerBasename");
2642
2643     if (! -e "$linkerDirname/$newLinker") {
2644         print "Unable to copy the linker.\n";
2645         exit 1;
2646     }
2647 }
2648
2649 sub appleApplicationSupportPath
2650 {
2651     open INSTALL_DIR, "</proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/Apple\ Inc./Apple\ Application\ Support/InstallDir";
2652     my $path = <INSTALL_DIR>;
2653     $path =~ s/[\r\n\x00].*//;
2654     close INSTALL_DIR;
2655
2656     my $unixPath = `cygpath -u '$path'`;
2657     chomp $unixPath;
2658     return $unixPath;
2659 }
2660
2661 sub setPathForRunningWebKitApp
2662 {
2663     my ($env) = @_;
2664
2665     if (isAppleWinWebKit()) {
2666         $env->{PATH} = join(':', productDir(), dirname(installedSafariPath()), appleApplicationSupportPath(), $env->{PATH} || "");
2667     } elsif (isQt()) {
2668         my $qtLibs = `$qmakebin -query QT_INSTALL_LIBS`;
2669         $qtLibs =~ s/[\n|\r]$//g;
2670         $env->{PATH} = join(';', $qtLibs, productDir() . "/lib", $env->{PATH} || "");
2671     }
2672 }
2673
2674 sub printHelpAndExitForRunAndDebugWebKitAppIfNeeded
2675 {
2676     return unless checkForArgumentAndRemoveFromARGV("--help");
2677
2678     my ($includeOptionsForDebugging) = @_;
2679
2680     print STDERR <<EOF;
2681 Usage: @{[basename($0)]} [options] [args ...]
2682   --help                Show this help message
2683   --no-saved-state      Disable application resume for the session on Mac OS 10.7
2684   --guard-malloc        Enable Guard Malloc (Mac OS X only)
2685 EOF
2686
2687     if ($includeOptionsForDebugging) {
2688         print STDERR <<EOF;
2689   --target-web-process  Debug the web process
2690   --use-lldb            Use LLDB
2691 EOF
2692     }
2693
2694     exit(1);
2695 }
2696
2697 sub argumentsForRunAndDebugMacWebKitApp()
2698 {
2699     my @args = @ARGV;
2700     push @args, ("-ApplePersistenceIgnoreState", "YES") if !isSnowLeopard() && checkForArgumentAndRemoveFromArrayRef("--no-saved-state", \@args);
2701     return @args;
2702 }
2703
2704 sub runMacWebKitApp($;$)
2705 {
2706     my ($appPath, $useOpenCommand) = @_;
2707     my $productDir = productDir();
2708     print "Starting @{[basename($appPath)]} with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2709     $ENV{DYLD_FRAMEWORK_PATH} = $productDir;
2710     $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2711
2712     setUpGuardMallocIfNeeded();
2713
2714     if (defined($useOpenCommand) && $useOpenCommand == USE_OPEN_COMMAND) {
2715         return system("open", "-W", "-a", $appPath, "--args", argumentsForRunAndDebugMacWebKitApp());
2716     }
2717     if (architecture()) {
2718         return system "arch", "-" . architecture(), $appPath, argumentsForRunAndDebugMacWebKitApp();
2719     }
2720     return system { $appPath } $appPath, argumentsForRunAndDebugMacWebKitApp();
2721 }
2722
2723 sub execMacWebKitAppForDebugging($)
2724 {
2725     my ($appPath) = @_;
2726     my $architectureSwitch;
2727     my $argumentsSeparator;
2728
2729     if (debugger() eq "lldb") {
2730         $architectureSwitch = "--arch";
2731         $argumentsSeparator = "--";
2732     } elsif (debugger() eq "gdb") {
2733         $architectureSwitch = "-arch";
2734         $argumentsSeparator = "--args";
2735     } else {
2736         die "Unknown debugger $debugger.\n";
2737     }
2738
2739     my $debuggerPath = `xcrun -find $debugger`;
2740     chomp $debuggerPath;
2741     die "Can't find the $debugger executable.\n" unless -x $debuggerPath;
2742
2743     my $productDir = productDir();
2744     $ENV{DYLD_FRAMEWORK_PATH} = $productDir;
2745     $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2746
2747     setUpGuardMallocIfNeeded();
2748
2749     my @architectureFlags = ($architectureSwitch, architecture());
2750     if (!shouldTargetWebProcess()) {
2751         print "Starting @{[basename($appPath)]} under $debugger with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2752         exec { $debuggerPath } $debuggerPath, @architectureFlags, $argumentsSeparator, $appPath, argumentsForRunAndDebugMacWebKitApp() or die;
2753     } else {
2754         my $webProcessShimPath = File::Spec->catfile($productDir, "WebProcessShim.dylib");
2755         my $webProcessPath = File::Spec->catdir($productDir, "WebProcess.app");
2756         my $webKit2ExecutablePath = File::Spec->catfile($productDir, "WebKit2.framework", "WebKit2");
2757
2758         appendToEnvironmentVariableList("DYLD_INSERT_LIBRARIES", $webProcessShimPath);
2759
2760         print "Starting WebProcess under $debugger with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2761         exec { $debuggerPath } $debuggerPath, @architectureFlags, $argumentsSeparator, $webProcessPath, $webKit2ExecutablePath, "-type", "webprocess", "-client-executable", $appPath or die;
2762     }
2763 }
2764
2765 sub debugSafari
2766 {
2767     if (isAppleMacWebKit()) {
2768         checkFrameworks();
2769         execMacWebKitAppForDebugging(safariPath());
2770     }
2771
2772     if (isAppleWinWebKit()) {
2773         setupCygwinEnv();
2774         my $productDir = productDir();
2775         chomp($ENV{WEBKITNIGHTLY} = `cygpath -wa "$productDir"`);
2776         my $safariPath = safariPath();
2777         chomp($safariPath = `cygpath -wa "$safariPath"`);
2778         return system { $vcBuildPath } $vcBuildPath, "/debugexe", "\"$safariPath\"", @ARGV;
2779     }
2780
2781     return 1; # Unsupported platform; can't debug Safari on this platform.
2782 }
2783
2784 sub runSafari
2785 {
2786
2787     if (isAppleMacWebKit()) {
2788         return runMacWebKitApp(safariPath());
2789     }
2790
2791     if (isAppleWinWebKit()) {
2792         my $result;
2793         my $productDir = productDir();
2794         my $webKitLauncherPath = File::Spec->catfile(productDir(), "WebKit.exe");
2795         return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2796     }
2797
2798     return 1; # Unsupported platform; can't run Safari on this platform.
2799 }
2800
2801 sub runMiniBrowser
2802 {
2803     if (isAppleMacWebKit()) {
2804         return runMacWebKitApp(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2805     }
2806
2807     return 1;
2808 }
2809
2810 sub debugMiniBrowser
2811 {
2812     if (isAppleMacWebKit()) {
2813         execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2814     }
2815     
2816     return 1;
2817 }
2818
2819 sub runWebKitTestRunner
2820 {
2821     if (isAppleMacWebKit()) {
2822         return runMacWebKitApp(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2823     } elsif (isGtk()) {
2824         my $productDir = productDir();
2825         my $injectedBundlePath = "$productDir/Libraries/.libs/libTestRunnerInjectedBundle";
2826         print "Starting WebKitTestRunner with TEST_RUNNER_INJECTED_BUNDLE_FILENAME set to point to $injectedBundlePath.\n";
2827         $ENV{TEST_RUNNER_INJECTED_BUNDLE_FILENAME} = $injectedBundlePath;
2828         my @args = ("$productDir/Programs/WebKitTestRunner", @ARGV);
2829         return system {$args[0] } @args;
2830     }
2831
2832     return 1;
2833 }
2834
2835 sub debugWebKitTestRunner
2836 {
2837     if (isAppleMacWebKit()) {
2838         execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2839     }
2840
2841     return 1;
2842 }
2843
2844 sub runTestWebKitAPI
2845 {
2846     if (isAppleMacWebKit()) {
2847         return runMacWebKitApp(File::Spec->catfile(productDir(), "TestWebKitAPI"));
2848     }
2849
2850     return 1;
2851 }
2852
2853 sub readRegistryString
2854 {
2855     my ($valueName) = @_;
2856     chomp(my $string = `regtool --wow32 get "$valueName"`);
2857     return $string;
2858 }
2859
2860 sub writeRegistryString
2861 {
2862     my ($valueName, $string) = @_;
2863
2864     my $error = system "regtool", "--wow32", "set", "-s", $valueName, $string;
2865
2866     # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
2867     # return a successful exit code. So we double-check here that the value we tried to write to the
2868     # registry was really written.
2869     return !$error && readRegistryString($valueName) eq $string;
2870 }
2871
2872 1;