tizen beta release
[framework/web/webkit-efl.git] / Tools / Scripts / webkitdirs.pm
1 # Copyright (C) 2005, 2006, 2007, 2010 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 warnings;
33 use Config;
34 use FindBin;
35 use File::Basename;
36 use File::Path qw(mkpath rmtree);
37 use File::Spec;
38 use File::stat;
39 use POSIX;
40 use VCSUtils;
41
42 BEGIN {
43    use Exporter   ();
44    our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
45    $VERSION     = 1.00;
46    @ISA         = qw(Exporter);
47    @EXPORT      = qw(
48        &XcodeOptionString
49        &XcodeOptionStringNoConfig
50        &XcodeOptions
51        &baseProductDir
52        &blackberryTargetArchitecture
53        &chdirWebKit
54        &checkFrameworks
55        &currentSVNRevision
56        &debugSafari
57        &passedConfiguration
58        &productDir
59        &runMacWebKitApp
60        &safariPath
61        &setConfiguration
62        USE_OPEN_COMMAND
63    );
64    %EXPORT_TAGS = ( );
65    @EXPORT_OK   = ();
66 }
67
68 use constant USE_OPEN_COMMAND => 1; # Used in runMacWebKitApp().
69
70 our @EXPORT_OK;
71
72 my $architecture;
73 my $numberOfCPUs;
74 my $baseProductDir;
75 my @baseProductDirOption;
76 my $configuration;
77 my $configurationForVisualStudio;
78 my $configurationProductDir;
79 my $sourceDir;
80 my $currentSVNRevision;
81 my $osXVersion;
82 my $generateDsym;
83 my $isQt;
84 my $qmakebin = "qmake"; # Allow override of the qmake binary from $PATH
85 my $isGtk;
86 my $isWinCE;
87 my $isWinCairo;
88 my $isWx;
89 my $isEfl;
90 my @wxArgs;
91 my $isBlackBerry;
92 my $isChromium;
93 my $isChromiumAndroid;
94 my $isChromiumMacMake;
95 my $forceChromiumUpdate;
96 my $isInspectorFrontend;
97 my $isWK2;
98
99 # Variables for Win32 support
100 my $vcBuildPath;
101 my $windowsSourceDir;
102 my $winVersion;
103 my $willUseVCExpressWhenBuilding = 0;
104
105 # Defined in VCSUtils.
106 sub exitStatus($);
107
108 sub determineSourceDir
109 {
110     return if $sourceDir;
111     $sourceDir = $FindBin::Bin;
112     $sourceDir =~ s|/+$||; # Remove trailing '/' as we would die later
113
114     # walks up path checking each directory to see if it is the main WebKit project dir, 
115     # defined by containing Sources, WebCore, and WebKit
116     until ((-d "$sourceDir/Source" && -d "$sourceDir/Source/WebCore" && -d "$sourceDir/Source/WebKit") || (-d "$sourceDir/Internal" && -d "$sourceDir/OpenSource"))
117     {
118         if ($sourceDir !~ s|/[^/]+$||) {
119             die "Could not find top level webkit directory above source directory using FindBin.\n";
120         }
121     }
122
123     $sourceDir = "$sourceDir/OpenSource" if -d "$sourceDir/OpenSource";
124 }
125
126 sub currentPerlPath()
127 {
128     my $thisPerl = $^X;
129     if ($^O ne 'VMS') {
130         $thisPerl .= $Config{_exe} unless $thisPerl =~ m/$Config{_exe}$/i;
131     }
132     return $thisPerl;
133 }
134
135 sub setQmakeBinaryPath($)
136 {
137     ($qmakebin) = @_;
138 }
139
140 # used for scripts which are stored in a non-standard location
141 sub setSourceDir($)
142 {
143     ($sourceDir) = @_;
144 }
145
146 sub determineBaseProductDir
147 {
148     return if defined $baseProductDir;
149     determineSourceDir();
150
151     $baseProductDir = $ENV{"WEBKITOUTPUTDIR"};
152
153     if (!defined($baseProductDir) and isAppleMacWebKit()) {
154         # Silently remove ~/Library/Preferences/xcodebuild.plist which can
155         # cause build failure. The presence of
156         # ~/Library/Preferences/xcodebuild.plist can prevent xcodebuild from
157         # respecting global settings such as a custom build products directory
158         # (<rdar://problem/5585899>).
159         my $personalPlistFile = $ENV{HOME} . "/Library/Preferences/xcodebuild.plist";
160         if (-e $personalPlistFile) {
161             unlink($personalPlistFile) || die "Could not delete $personalPlistFile: $!";
162         }
163
164         my $xcodebuildVersionOutput = `xcodebuild -version`;
165         my $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : "3.0";
166         my $xcodeDefaultsDomain = (eval "v$xcodeVersion" lt v4) ? "com.apple.Xcode" : "com.apple.dt.Xcode";
167         my $xcodeDefaultsPrefix = (eval "v$xcodeVersion" lt v4) ? "PBX" : "IDE";
168
169         open PRODUCT, "defaults read $xcodeDefaultsDomain ${xcodeDefaultsPrefix}ApplicationwideBuildSettings 2> " . File::Spec->devnull() . " |" or die;
170         $baseProductDir = join '', <PRODUCT>;
171         close PRODUCT;
172
173         $baseProductDir = $1 if $baseProductDir =~ /SYMROOT\s*=\s*\"(.*?)\";/s;
174         undef $baseProductDir unless $baseProductDir =~ /^\//;
175     } elsif (isChromium()) {
176         if (isLinux() || isChromiumAndroid() || isChromiumMacMake()) {
177             $baseProductDir = "$sourceDir/out";
178         } elsif (isDarwin()) {
179             $baseProductDir = "$sourceDir/Source/WebKit/chromium/xcodebuild";
180         } elsif (isWindows() || isCygwin()) {
181             $baseProductDir = "$sourceDir/Source/WebKit/chromium/build";
182         }
183     }
184
185     if (!defined($baseProductDir)) { # Port-spesific checks failed, use default
186         $baseProductDir = "$sourceDir/WebKitBuild";
187     }
188
189     if (isBlackBerry()) {
190         my %archInfo = blackberryTargetArchitecture();
191         $baseProductDir = "$baseProductDir/" . $archInfo{"cpuDir"};
192     }
193
194     if (isGit() && isGitBranchBuild() && !isChromium()) {
195         my $branch = gitBranch();
196         $baseProductDir = "$baseProductDir/$branch";
197     }
198
199     if (isAppleMacWebKit()) {
200         $baseProductDir =~ s|^\Q$(SRCROOT)/..\E$|$sourceDir|;
201         $baseProductDir =~ s|^\Q$(SRCROOT)/../|$sourceDir/|;
202         $baseProductDir =~ s|^~/|$ENV{HOME}/|;
203         die "Can't handle Xcode product directory with a ~ in it.\n" if $baseProductDir =~ /~/;
204         die "Can't handle Xcode product directory with a variable in it.\n" if $baseProductDir =~ /\$/;
205         @baseProductDirOption = ("SYMROOT=$baseProductDir", "OBJROOT=$baseProductDir");
206     }
207
208     if (isCygwin()) {
209         my $dosBuildPath = `cygpath --windows \"$baseProductDir\"`;
210         chomp $dosBuildPath;
211         $ENV{"WEBKITOUTPUTDIR"} = $dosBuildPath;
212         my $unixBuildPath = `cygpath --unix \"$baseProductDir\"`;
213         chomp $unixBuildPath;
214         $baseProductDir = $unixBuildPath;
215     }
216 }
217
218 sub setBaseProductDir($)
219 {
220     ($baseProductDir) = @_;
221 }
222
223 sub determineConfiguration
224 {
225     return if defined $configuration;
226     determineBaseProductDir();
227     if (open CONFIGURATION, "$baseProductDir/Configuration") {
228         $configuration = <CONFIGURATION>;
229         close CONFIGURATION;
230     }
231     if ($configuration) {
232         chomp $configuration;
233         # compatibility for people who have old Configuration files
234         $configuration = "Release" if $configuration eq "Deployment";
235         $configuration = "Debug" if $configuration eq "Development";
236     } else {
237         $configuration = "Release";
238     }
239
240     if ($configuration && isWinCairo()) {
241         unless ($configuration =~ /_Cairo_CFLite$/) {
242             $configuration .= "_Cairo_CFLite";
243         }
244     }
245 }
246
247 sub determineArchitecture
248 {
249     return if defined $architecture;
250     # make sure $architecture is defined in all cases
251     $architecture = "";
252
253     determineBaseProductDir();
254
255     if (isGtk()) {
256         determineConfigurationProductDir();
257         my $host_triple = `grep -E '^host = ' $configurationProductDir/GNUmakefile`;
258         if ($host_triple =~ m/^host = ([^-]+)-/) {
259             # We have a configured build tree; use it.
260             $architecture = $1;
261         } else {
262             # Fall back to output of `arch', if it is present.
263             $architecture = `arch`;
264             chomp $architecture;
265         }
266     } elsif (isAppleMacWebKit()) {
267         if (open ARCHITECTURE, "$baseProductDir/Architecture") {
268             $architecture = <ARCHITECTURE>;
269             close ARCHITECTURE;
270         }
271         if ($architecture) {
272             chomp $architecture;
273         } else {
274             if (isLeopard()) {
275                 $architecture = `arch`;
276             } else {
277                 my $supports64Bit = `sysctl -n hw.optional.x86_64`;
278                 chomp $supports64Bit;
279                 $architecture = $supports64Bit ? 'x86_64' : `arch`;
280             }
281             chomp $architecture;
282         }
283     }
284 }
285
286 sub determineNumberOfCPUs
287 {
288     return if defined $numberOfCPUs;
289     if (isLinux()) {
290         # First try the nproc utility, if it exists. If we get no
291         # results fall back to just interpretting /proc directly.
292         chomp($numberOfCPUs = `nproc 2> /dev/null`);
293         if ($numberOfCPUs eq "") {
294             $numberOfCPUs = (grep /processor/, `cat /proc/cpuinfo`);
295         }
296     } elsif (isWindows() || isCygwin()) {
297         if (defined($ENV{NUMBER_OF_PROCESSORS})) {
298             $numberOfCPUs = $ENV{NUMBER_OF_PROCESSORS};
299         } else {
300             # Assumes cygwin
301             $numberOfCPUs = `ls /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor | wc -w`;
302         }
303     } elsif (isDarwin()) {
304         chomp($numberOfCPUs = `sysctl -n hw.ncpu`);
305     }
306 }
307
308 sub jscPath($)
309 {
310     my ($productDir) = @_;
311     my $jscName = "jsc";
312     $jscName .= "_debug"  if configurationForVisualStudio() eq "Debug_All";
313     $jscName .= ".exe" if (isWindows() || isCygwin());
314     return "$productDir/$jscName" if -e "$productDir/$jscName";
315     return "$productDir/JavaScriptCore.framework/Resources/$jscName";
316 }
317
318 sub argumentsForConfiguration()
319 {
320     determineConfiguration();
321     determineArchitecture();
322
323     my @args = ();
324     push(@args, '--debug') if $configuration eq "Debug";
325     push(@args, '--release') if $configuration eq "Release";
326     push(@args, '--32-bit') if $architecture ne "x86_64";
327     push(@args, '--qt') if isQt();
328     push(@args, '--gtk') if isGtk();
329     push(@args, '--efl') if isEfl();
330     push(@args, '--wincairo') if isWinCairo();
331     push(@args, '--wince') if isWinCE();
332     push(@args, '--wx') if isWx();
333     push(@args, '--blackberry') if isBlackBerry();
334     push(@args, '--chromium') if isChromium() && !isChromiumAndroid();
335     push(@args, '--chromium-android') if isChromiumAndroid();
336     push(@args, '--inspector-frontend') if isInspectorFrontend();
337     return @args;
338 }
339
340 sub determineConfigurationForVisualStudio
341 {
342     return if defined $configurationForVisualStudio;
343     determineConfiguration();
344     # FIXME: We should detect when Debug_All or Production has been chosen.
345     $configurationForVisualStudio = $configuration;
346 }
347
348 sub usesPerConfigurationBuildDirectory
349 {
350     # [Gtk][Efl] We don't have Release/Debug configurations in straight
351     # autotool builds (non build-webkit). In this case and if
352     # WEBKITOUTPUTDIR exist, use that as our configuration dir. This will
353     # allows us to run run-webkit-tests without using build-webkit.
354     return ($ENV{"WEBKITOUTPUTDIR"} && (isGtk() || isEfl())) || isAppleWinWebKit();
355 }
356
357 sub determineConfigurationProductDir
358 {
359     return if defined $configurationProductDir;
360     determineBaseProductDir();
361     determineConfiguration();
362     if (isAppleWinWebKit() && !isWx()) {
363         $configurationProductDir = File::Spec->catdir($baseProductDir, configurationForVisualStudio(), "bin");
364     } else {
365         if (usesPerConfigurationBuildDirectory()) {
366             $configurationProductDir = "$baseProductDir";
367         } else {
368             $configurationProductDir = "$baseProductDir/$configuration";
369         }
370     }
371 }
372
373 sub setConfigurationProductDir($)
374 {
375     ($configurationProductDir) = @_;
376 }
377
378 sub determineCurrentSVNRevision
379 {
380     return if defined $currentSVNRevision;
381     determineSourceDir();
382     $currentSVNRevision = svnRevisionForDirectory($sourceDir);
383     return $currentSVNRevision;
384 }
385
386
387 sub chdirWebKit
388 {
389     determineSourceDir();
390     chdir $sourceDir or die;
391 }
392
393 sub baseProductDir
394 {
395     determineBaseProductDir();
396     return $baseProductDir;
397 }
398
399 sub sourceDir
400 {
401     determineSourceDir();
402     return $sourceDir;
403 }
404
405 sub productDir
406 {
407     determineConfigurationProductDir();
408     return $configurationProductDir;
409 }
410
411 sub jscProductDir
412 {
413     my $productDir = productDir();
414     $productDir .= "/bin" if isQt();
415     $productDir .= "/Programs" if (isGtk() || isEfl());
416
417     return $productDir;
418 }
419
420 sub configuration()
421 {
422     determineConfiguration();
423     return $configuration;
424 }
425
426 sub configurationForVisualStudio()
427 {
428     determineConfigurationForVisualStudio();
429     return $configurationForVisualStudio;
430 }
431
432 sub currentSVNRevision
433 {
434     determineCurrentSVNRevision();
435     return $currentSVNRevision;
436 }
437
438 sub generateDsym()
439 {
440     determineGenerateDsym();
441     return $generateDsym;
442 }
443
444 sub determineGenerateDsym()
445 {
446     return if defined($generateDsym);
447     $generateDsym = checkForArgumentAndRemoveFromARGV("--dsym");
448 }
449
450 sub argumentsForXcode()
451 {
452     my @args = ();
453     push @args, "DEBUG_INFORMATION_FORMAT=dwarf-with-dsym" if generateDsym();
454     return @args;
455 }
456
457 sub XcodeOptions
458 {
459     determineBaseProductDir();
460     determineConfiguration();
461     determineArchitecture();
462     return (@baseProductDirOption, "-configuration", $configuration, "ARCHS=$architecture", argumentsForXcode());
463 }
464
465 sub XcodeOptionString
466 {
467     return join " ", XcodeOptions();
468 }
469
470 sub XcodeOptionStringNoConfig
471 {
472     return join " ", @baseProductDirOption;
473 }
474
475 sub XcodeCoverageSupportOptions()
476 {
477     my @coverageSupportOptions = ();
478     push @coverageSupportOptions, "GCC_GENERATE_TEST_COVERAGE_FILES=YES";
479     push @coverageSupportOptions, "GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES";
480     push @coverageSupportOptions, "EXTRA_LINK= \$(EXTRA_LINK) -ftest-coverage -fprofile-arcs";
481     push @coverageSupportOptions, "OTHER_CFLAGS= \$(OTHER_CFLAGS) -DCOVERAGE -MD";
482     push @coverageSupportOptions, "OTHER_LDFLAGS=\$(OTHER_LDFLAGS) -ftest-coverage -fprofile-arcs -lgcov";
483     return @coverageSupportOptions;
484 }
485
486 my $passedConfiguration;
487 my $searchedForPassedConfiguration;
488 sub determinePassedConfiguration
489 {
490     return if $searchedForPassedConfiguration;
491     $searchedForPassedConfiguration = 1;
492
493     for my $i (0 .. $#ARGV) {
494         my $opt = $ARGV[$i];
495         if ($opt =~ /^--debug$/i || $opt =~ /^--devel/i) {
496             splice(@ARGV, $i, 1);
497             $passedConfiguration = "Debug";
498             $passedConfiguration .= "_Cairo_CFLite" if (isWinCairo() && isCygwin());
499             return;
500         }
501         if ($opt =~ /^--release$/i || $opt =~ /^--deploy/i) {
502             splice(@ARGV, $i, 1);
503             $passedConfiguration = "Release";
504             $passedConfiguration .= "_Cairo_CFLite" if (isWinCairo() && isCygwin());
505             return;
506         }
507         if ($opt =~ /^--profil(e|ing)$/i) {
508             splice(@ARGV, $i, 1);
509             $passedConfiguration = "Profiling";
510             $passedConfiguration .= "_Cairo_CFLite" if (isWinCairo() && isCygwin());
511             return;
512         }
513     }
514     $passedConfiguration = undef;
515 }
516
517 sub passedConfiguration
518 {
519     determinePassedConfiguration();
520     return $passedConfiguration;
521 }
522
523 sub setConfiguration
524 {
525     setArchitecture();
526
527     if (my $config = shift @_) {
528         $configuration = $config;
529         return;
530     }
531
532     determinePassedConfiguration();
533     $configuration = $passedConfiguration if $passedConfiguration;
534 }
535
536
537 my $passedArchitecture;
538 my $searchedForPassedArchitecture;
539 sub determinePassedArchitecture
540 {
541     return if $searchedForPassedArchitecture;
542     $searchedForPassedArchitecture = 1;
543
544     for my $i (0 .. $#ARGV) {
545         my $opt = $ARGV[$i];
546         if ($opt =~ /^--32-bit$/i) {
547             splice(@ARGV, $i, 1);
548             if (isAppleMacWebKit() || isWx()) {
549                 $passedArchitecture = `arch`;
550                 chomp $passedArchitecture;
551             }
552             return;
553         }
554     }
555     $passedArchitecture = undef;
556 }
557
558 sub passedArchitecture
559 {
560     determinePassedArchitecture();
561     return $passedArchitecture;
562 }
563
564 sub architecture()
565 {
566     determineArchitecture();
567     return $architecture;
568 }
569
570 sub numberOfCPUs()
571 {
572     determineNumberOfCPUs();
573     return $numberOfCPUs;
574 }
575
576 sub setArchitecture
577 {
578     if (my $arch = shift @_) {
579         $architecture = $arch;
580         return;
581     }
582
583     determinePassedArchitecture();
584     $architecture = $passedArchitecture if $passedArchitecture;
585 }
586
587
588 sub safariPathFromSafariBundle
589 {
590     my ($safariBundle) = @_;
591
592     return "$safariBundle/Contents/MacOS/Safari" if isAppleMacWebKit();
593     return $safariBundle if isAppleWinWebKit();
594 }
595
596 sub installedSafariPath
597 {
598     my $safariBundle;
599
600     if (isAppleMacWebKit()) {
601         $safariBundle = "/Applications/Safari.app";
602     } elsif (isAppleWinWebKit()) {
603         $safariBundle = readRegistryString("/HKLM/SOFTWARE/Apple Computer, Inc./Safari/InstallDir");
604         $safariBundle =~ s/[\r\n]+$//;
605         $safariBundle = `cygpath -u '$safariBundle'` if isCygwin();
606         $safariBundle =~ s/[\r\n]+$//;
607         $safariBundle .= "Safari.exe";
608     }
609
610     return safariPathFromSafariBundle($safariBundle);
611 }
612
613 # Locate Safari.
614 sub safariPath
615 {
616     # Use WEBKIT_SAFARI environment variable if present.
617     my $safariBundle = $ENV{WEBKIT_SAFARI};
618     if (!$safariBundle) {
619         determineConfigurationProductDir();
620         # Use Safari.app in product directory if present (good for Safari development team).
621         if (isAppleMacWebKit() && -d "$configurationProductDir/Safari.app") {
622             $safariBundle = "$configurationProductDir/Safari.app";
623         } elsif (isAppleWinWebKit()) {
624             my $path = "$configurationProductDir/Safari.exe";
625             my $debugPath = "$configurationProductDir/Safari_debug.exe";
626
627             if (configurationForVisualStudio() eq "Debug_All" && -x $debugPath) {
628                 $safariBundle = $debugPath;
629             } elsif (-x $path) {
630                 $safariBundle = $path;
631             }
632         }
633         if (!$safariBundle) {
634             return installedSafariPath();
635         }
636     }
637     my $safariPath = safariPathFromSafariBundle($safariBundle);
638     die "Can't find executable at $safariPath.\n" if isAppleMacWebKit() && !-x $safariPath;
639     return $safariPath;
640 }
641
642 sub builtDylibPathForName
643 {
644     my $libraryName = shift;
645     determineConfigurationProductDir();
646     if (isChromium()) {
647         return "$configurationProductDir/$libraryName";
648     }
649     if (isBlackBerry()) {
650         my $libraryExtension = $libraryName =~ /^WebKit$/i ? ".so" : ".a";
651         return "$configurationProductDir/$libraryName/lib" . lc($libraryName) . $libraryExtension;
652     }
653     if (isQt()) {
654         $libraryName = "QtWebKit";
655         if (isDarwin() and -d "$configurationProductDir/lib/$libraryName.framework") {
656             return "$configurationProductDir/lib/$libraryName.framework/$libraryName";
657         } elsif (isDarwin() and -d "$configurationProductDir/lib") {
658             return "$configurationProductDir/lib/lib$libraryName.dylib";
659         } elsif (isWindows()) {
660             if (configuration() eq "Debug") {
661                 # On Windows, there is a "d" suffix to the library name. See <http://trac.webkit.org/changeset/53924/>.
662                 $libraryName .= "d";
663             }
664
665             my $mkspec = `$qmakebin -query QMAKE_MKSPECS`;
666             $mkspec =~ s/[\n|\r]$//g;
667             my $qtMajorVersion = retrieveQMakespecVar("$mkspec/qconfig.pri", "QT_MAJOR_VERSION");
668             if (not $qtMajorVersion) {
669                 $qtMajorVersion = "";
670             }
671             return "$configurationProductDir/lib/$libraryName$qtMajorVersion.dll";
672         } else {
673             return "$configurationProductDir/lib/lib$libraryName.so";
674         }
675     }
676     if (isWx()) {
677         return "$configurationProductDir/libwxwebkit.dylib";
678     }
679     if (isGtk()) {
680         # WebKitGTK+ for GTK2, WebKitGTK+ for GTK3, and WebKit2 respectively.
681         my @libraries = ("libwebkitgtk-1.0", "libwebkitgtk-3.0", "libwebkit2gtk-1.0");
682         my $extension = isDarwin() ? ".dylib" : ".so";
683
684         foreach $libraryName (@libraries) {
685             my $libraryPath = "$configurationProductDir/.libs/" . $libraryName . $extension;
686             return $libraryPath if -e $libraryPath;
687         }
688         return "NotFound";
689     }
690     if (isEfl()) {
691         return "$configurationProductDir/$libraryName/../WebKit/libewebkit.so";
692     }
693     if (isWinCE()) {
694         return "$configurationProductDir/$libraryName";
695     }
696     if (isAppleMacWebKit()) {
697         return "$configurationProductDir/$libraryName.framework/Versions/A/$libraryName";
698     }
699     if (isAppleWinWebKit()) {
700         if ($libraryName eq "JavaScriptCore") {
701             return "$baseProductDir/lib/$libraryName.lib";
702         } else {
703             return "$baseProductDir/$libraryName.intermediate/$configuration/$libraryName.intermediate/$libraryName.lib";
704         }
705     }
706
707     die "Unsupported platform, can't determine built library locations.\nTry `build-webkit --help` for more information.\n";
708 }
709
710 # Check to see that all the frameworks are built.
711 sub checkFrameworks # FIXME: This is a poor name since only the Mac calls built WebCore a Framework.
712 {
713     return if isCygwin() || isWindows();
714     my @frameworks = ("JavaScriptCore", "WebCore");
715     push(@frameworks, "WebKit") if isAppleMacWebKit(); # FIXME: This seems wrong, all ports should have a WebKit these days.
716     for my $framework (@frameworks) {
717         my $path = builtDylibPathForName($framework);
718         die "Can't find built framework at \"$path\".\n" unless -e $path;
719     }
720 }
721
722 sub isInspectorFrontend()
723 {
724     determineIsInspectorFrontend();
725     return $isInspectorFrontend;
726 }
727
728 sub determineIsInspectorFrontend()
729 {
730     return if defined($isInspectorFrontend);
731     $isInspectorFrontend = checkForArgumentAndRemoveFromARGV("--inspector-frontend");
732 }
733
734 sub isQt()
735 {
736     determineIsQt();
737     return $isQt;
738 }
739
740 sub getQtVersion()
741 {
742     my $qtVersion = `$qmakebin --version`;
743     $qtVersion =~ s/^(.*)Qt version (\d\.\d)(.*)/$2/s ;
744     return $qtVersion;
745 }
746
747 sub qtFeatureDefaults
748 {
749     die "ERROR: qmake missing but required to build WebKit.\n" if not commandExists($qmakebin);
750
751     my $qmakepath = File::Spec->catfile(sourceDir(), "Tools", "qmake");
752     my $qmakecommand;
753     if (isWindows()) {
754         $qmakecommand = "(set QMAKEPATH=$qmakepath) && $qmakebin";
755     } else {
756         $qmakecommand = "QMAKEPATH=$qmakepath $qmakebin";
757     }
758
759     my $originalCwd = getcwd();
760
761     my $file;
762     my @buildArgs;
763
764     if (@_) {
765         @buildArgs = (@buildArgs, @{$_[0]});
766         my $dir = File::Spec->catfile(productDir(), "Tools", "qmake");
767         File::Path::mkpath($dir);
768         chdir $dir or die "Failed to cd into " . $dir . "\n";
769         $file = File::Spec->catfile($qmakepath, "configure.pro");
770     } else {
771         # Do a quick check of the features without running the config tests
772         $file = File::Spec->catfile($qmakepath, "mkspecs", "features", "features.prf");
773         push @buildArgs, "CONFIG+=compute_defaults";
774     }
775
776     my $defaults = `$qmakecommand @buildArgs $file 2>&1`;
777
778     my %qtFeatureDefaults;
779     while ($defaults =~ m/(\S+?)=(\S+?)/gi) {
780         $qtFeatureDefaults{$1}=$2;
781     }
782
783     chdir $originalCwd;
784
785     return %qtFeatureDefaults;
786 }
787
788 sub commandExists($)
789 {
790     my $command = shift;
791     my $devnull = File::Spec->devnull();
792     return `$command --version 2> $devnull`;
793 }
794
795 sub checkForArgumentAndRemoveFromARGV
796 {
797     my $argToCheck = shift;
798     return checkForArgumentAndRemoveFromArrayRef($argToCheck, \@ARGV);
799 }
800
801 sub checkForArgumentAndRemoveFromArrayRef
802 {
803     my ($argToCheck, $arrayRef) = @_;
804     my @indicesToRemove;
805     foreach my $index (0 .. $#$arrayRef) {
806         my $opt = $$arrayRef[$index];
807         if ($opt =~ /^$argToCheck$/i ) {
808             push(@indicesToRemove, $index);
809         }
810     }
811     foreach my $index (@indicesToRemove) {
812         splice(@$arrayRef, $index, 1);
813     }
814     return $#indicesToRemove > -1;
815 }
816
817 sub isWK2()
818 {
819     if (defined($isWK2)) {
820         return $isWK2;
821     }
822     if (checkForArgumentAndRemoveFromARGV("-2")) {
823         $isWK2 = 1;
824     } else {
825         $isWK2 = 0;
826     }
827     return $isWK2;
828 }
829
830 sub determineIsQt()
831 {
832     return if defined($isQt);
833
834     # Allow override in case QTDIR is not set.
835     if (checkForArgumentAndRemoveFromARGV("--qt")) {
836         $isQt = 1;
837         return;
838     }
839
840     # The presence of QTDIR only means Qt if --gtk or --wx or --efl or --blackberry are not on the command-line
841     if (isGtk() || isWx() || isEfl() || isBlackBerry()) {
842         $isQt = 0;
843         return;
844     }
845     
846     $isQt = defined($ENV{'QTDIR'});
847 }
848
849 sub isBlackBerry()
850 {
851     determineIsBlackBerry();
852     return $isBlackBerry;
853 }
854
855 sub determineIsBlackBerry()
856 {
857     return if defined($isBlackBerry);
858     $isBlackBerry = checkForArgumentAndRemoveFromARGV("--blackberry");
859 }
860
861 sub blackberryTargetArchitecture()
862 {
863     my $arch = $ENV{"BLACKBERRY_ARCH_TYPE"} ? $ENV{"BLACKBERRY_ARCH_TYPE"} : "arm";
864     my $cpu = $ENV{"BLACKBERRY_ARCH_CPU"} ? $ENV{"BLACKBERRY_ARCH_CPU"} : "";
865     my $cpuDir;
866     my $buSuffix;
867     if (($cpu eq "v7le") || ($cpu eq "a9")) {
868         $cpuDir = $arch . "le-v7";
869         $buSuffix = $arch . "v7";
870     } else {
871         $cpu = $arch;
872         $cpuDir = $arch;
873         $buSuffix = $arch;
874     }
875     return ("arch" => $arch,
876             "cpu" => $cpu,
877             "cpuDir" => $cpuDir,
878             "buSuffix" => $buSuffix);
879 }
880
881 sub determineIsEfl()
882 {
883     return if defined($isEfl);
884     $isEfl = checkForArgumentAndRemoveFromARGV("--efl");
885 }
886
887 sub isEfl()
888 {
889     determineIsEfl();
890     return $isEfl;
891 }
892
893 sub isGtk()
894 {
895     determineIsGtk();
896     return $isGtk;
897 }
898
899 sub determineIsGtk()
900 {
901     return if defined($isGtk);
902     $isGtk = checkForArgumentAndRemoveFromARGV("--gtk");
903 }
904
905 sub isWinCE()
906 {
907     determineIsWinCE();
908     return $isWinCE;
909 }
910
911 sub determineIsWinCE()
912 {
913     return if defined($isWinCE);
914     $isWinCE = checkForArgumentAndRemoveFromARGV("--wince");
915 }
916
917 sub isWx()
918 {
919     determineIsWx();
920     return $isWx;
921 }
922
923 sub determineIsWx()
924 {
925     return if defined($isWx);
926     $isWx = checkForArgumentAndRemoveFromARGV("--wx");
927 }
928
929 sub getWxArgs()
930 {
931     if (!@wxArgs) {
932         @wxArgs = ("");
933         my $rawWxArgs = "";
934         foreach my $opt (@ARGV) {
935             if ($opt =~ /^--wx-args/i ) {
936                 @ARGV = grep(!/^--wx-args/i, @ARGV);
937                 $rawWxArgs = $opt;
938                 $rawWxArgs =~ s/--wx-args=//i;
939             }
940         }
941         @wxArgs = split(/,/, $rawWxArgs);
942     }
943     return @wxArgs;
944 }
945
946 # Determine if this is debian, ubuntu, linspire, or something similar.
947 sub isDebianBased()
948 {
949     return -e "/etc/debian_version";
950 }
951
952 sub isFedoraBased()
953 {
954     return -e "/etc/fedora-release";
955 }
956
957 sub isChromium()
958 {
959     determineIsChromium();
960     determineIsChromiumAndroid();
961     return $isChromium || $isChromiumAndroid;
962 }
963
964 sub determineIsChromium()
965 {
966     return if defined($isChromium);
967     $isChromium = checkForArgumentAndRemoveFromARGV("--chromium");
968     if ($isChromium) {
969         $forceChromiumUpdate = checkForArgumentAndRemoveFromARGV("--force-update");
970     }
971 }
972
973 sub isChromiumAndroid()
974 {
975     determineIsChromiumAndroid();
976     return $isChromiumAndroid;
977 }
978
979 sub determineIsChromiumAndroid()
980 {
981     return if defined($isChromiumAndroid);
982     $isChromiumAndroid = checkForArgumentAndRemoveFromARGV("--chromium-android");
983 }
984
985 sub isChromiumMacMake()
986 {
987     determineIsChromiumMacMake();
988     return $isChromiumMacMake;
989 }
990
991 sub determineIsChromiumMacMake()
992 {
993     return if defined($isChromiumMacMake);
994
995     my $hasUpToDateMakefile = 0;
996     if (-e 'Makefile.chromium') {
997         unless (-e 'Source/WebKit/chromium/WebKit.xcodeproj') {
998             $hasUpToDateMakefile = 1;
999         } else {
1000             $hasUpToDateMakefile = stat('Makefile.chromium')->mtime > stat('Source/WebKit/chromium/WebKit.xcodeproj')->mtime;
1001         }
1002     }
1003     $isChromiumMacMake = isDarwin() && $hasUpToDateMakefile;
1004 }
1005
1006 sub forceChromiumUpdate()
1007 {
1008     determineIsChromium();
1009     return $forceChromiumUpdate;
1010 }
1011
1012 sub isWinCairo()
1013 {
1014     determineIsWinCairo();
1015     return $isWinCairo;
1016 }
1017
1018 sub determineIsWinCairo()
1019 {
1020     return if defined($isWinCairo);
1021     $isWinCairo = checkForArgumentAndRemoveFromARGV("--wincairo");
1022 }
1023
1024 sub isCygwin()
1025 {
1026     return ($^O eq "cygwin") || 0;
1027 }
1028
1029 sub isAnyWindows()
1030 {
1031     return isWindows() || isCygwin() || isMsys();
1032 }
1033
1034 sub determineWinVersion()
1035 {
1036     return if $winVersion;
1037
1038     if (!isAnyWindows()) {
1039         $winVersion = -1;
1040         return;
1041     }
1042
1043     my $versionString = `cmd /c ver`;
1044     $versionString =~ /(\d)\.(\d)\.(\d+)/;
1045
1046     $winVersion = {
1047         major => $1,
1048         minor => $2,
1049         build => $3,
1050     };
1051 }
1052
1053 sub winVersion()
1054 {
1055     determineWinVersion();
1056     return $winVersion;
1057 }
1058
1059 sub isWindows7SP0()
1060 {
1061     return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 1 && winVersion()->{build} == 7600;
1062 }
1063
1064 sub isWindowsVista()
1065 {
1066     return isAnyWindows() && winVersion()->{major} == 6 && winVersion()->{minor} == 0;
1067 }
1068
1069 sub isWindowsXP()
1070 {
1071     return isAnyWindows() && winVersion()->{major} == 5 && winVersion()->{minor} == 1;
1072 }
1073
1074 sub isDarwin()
1075 {
1076     return ($^O eq "darwin") || 0;
1077 }
1078
1079 sub isWindows()
1080 {
1081     return ($^O eq "MSWin32") || 0;
1082 }
1083
1084 sub isMsys()
1085 {
1086     return ($^O eq "msys") || 0;
1087 }
1088
1089 sub isLinux()
1090 {
1091     return ($^O eq "linux") || 0;
1092 }
1093
1094 sub isARM()
1095 {
1096     return $Config{archname} =~ /^arm-/;
1097 }
1098
1099 sub isAppleWebKit()
1100 {
1101     return !(isQt() or isGtk() or isWx() or isChromium() or isEfl() or isWinCE() or isBlackBerry());
1102 }
1103
1104 sub isAppleMacWebKit()
1105 {
1106     return isAppleWebKit() && isDarwin();
1107 }
1108
1109 sub isAppleWinWebKit()
1110 {
1111     return isAppleWebKit() && (isCygwin() || isWindows());
1112 }
1113
1114 sub isPerianInstalled()
1115 {
1116     if (!isAppleWebKit()) {
1117         return 0;
1118     }
1119
1120     if (-d "/Library/QuickTime/Perian.component") {
1121         return 1;
1122     }
1123
1124     if (-d "$ENV{HOME}/Library/QuickTime/Perian.component") {
1125         return 1;
1126     }
1127
1128     return 0;
1129 }
1130
1131 sub determineOSXVersion()
1132 {
1133     return if $osXVersion;
1134
1135     if (!isDarwin()) {
1136         $osXVersion = -1;
1137         return;
1138     }
1139
1140     my $version = `sw_vers -productVersion`;
1141     my @splitVersion = split(/\./, $version);
1142     @splitVersion >= 2 or die "Invalid version $version";
1143     $osXVersion = {
1144             "major" => $splitVersion[0],
1145             "minor" => $splitVersion[1],
1146             "subminor" => (defined($splitVersion[2]) ? $splitVersion[2] : 0),
1147     };
1148 }
1149
1150 sub osXVersion()
1151 {
1152     determineOSXVersion();
1153     return $osXVersion;
1154 }
1155
1156 sub isLeopard()
1157 {
1158     return isDarwin() && osXVersion()->{"minor"} == 5;
1159 }
1160
1161 sub isSnowLeopard()
1162 {
1163     return isDarwin() && osXVersion()->{"minor"} == 6;
1164 }
1165
1166 sub isLion()
1167 {
1168     return isDarwin() && osXVersion()->{"minor"} == 7;
1169 }
1170
1171 sub isWindowsNT()
1172 {
1173     return $ENV{'OS'} eq 'Windows_NT';
1174 }
1175
1176 sub relativeScriptsDir()
1177 {
1178     my $scriptDir = File::Spec->catpath("", File::Spec->abs2rel($FindBin::Bin, getcwd()), "");
1179     if ($scriptDir eq "") {
1180         $scriptDir = ".";
1181     }
1182     return $scriptDir;
1183 }
1184
1185 sub launcherPath()
1186 {
1187     my $relativeScriptsPath = relativeScriptsDir();
1188     if (isGtk() || isQt() || isWx() || isEfl() || isWinCE()) {
1189         return "$relativeScriptsPath/run-launcher";
1190     } elsif (isAppleWebKit()) {
1191         return "$relativeScriptsPath/run-safari";
1192     }
1193 }
1194
1195 sub launcherName()
1196 {
1197     if (isGtk()) {
1198         return "GtkLauncher";
1199     } elsif (isQt()) {
1200         return "QtTestBrowser";
1201     } elsif (isWx()) {
1202         return "wxBrowser";
1203     } elsif (isAppleWebKit()) {
1204         return "Safari";
1205     } elsif (isEfl()) {
1206         return "EWebLauncher";
1207     } elsif (isWinCE()) {
1208         return "WinCELauncher";
1209     }
1210 }
1211
1212 sub checkRequiredSystemConfig
1213 {
1214     if (isDarwin()) {
1215         chomp(my $productVersion = `sw_vers -productVersion`);
1216         if (eval "v$productVersion" lt v10.4) {
1217             print "*************************************************************\n";
1218             print "Mac OS X Version 10.4.0 or later is required to build WebKit.\n";
1219             print "You have " . $productVersion . ", thus the build will most likely fail.\n";
1220             print "*************************************************************\n";
1221         }
1222         my $xcodebuildVersionOutput = `xcodebuild -version`;
1223         my $devToolsCoreVersion = ($xcodebuildVersionOutput =~ /DevToolsCore-(\d+)/) ? $1 : undef;
1224         my $xcodeVersion = ($xcodebuildVersionOutput =~ /Xcode ([0-9](\.[0-9]+)*)/) ? $1 : undef;
1225         if (!$devToolsCoreVersion && !$xcodeVersion
1226             || $devToolsCoreVersion && $devToolsCoreVersion < 747
1227             || $xcodeVersion && eval "v$xcodeVersion" lt v2.3) {
1228             print "*************************************************************\n";
1229             print "Xcode Version 2.3 or later is required to build WebKit.\n";
1230             print "You have an earlier version of Xcode, thus the build will\n";
1231             print "most likely fail.  The latest Xcode is available from the web:\n";
1232             print "http://developer.apple.com/tools/xcode\n";
1233             print "*************************************************************\n";
1234         }
1235     } elsif (isGtk() or isQt() or isWx() or isEfl()) {
1236         my @cmds = qw(flex bison gperf);
1237         my @missing = ();
1238         foreach my $cmd (@cmds) {
1239             push @missing, $cmd if not commandExists($cmd);
1240         }
1241
1242         if (@missing) {
1243             my $list = join ", ", @missing;
1244             die "ERROR: $list missing but required to build WebKit.\n";
1245         }
1246     }
1247     # Win32 and other platforms may want to check for minimum config
1248 }
1249
1250 sub determineWindowsSourceDir()
1251 {
1252     return if $windowsSourceDir;
1253     $windowsSourceDir = sourceDir();
1254     chomp($windowsSourceDir = `cygpath -w '$windowsSourceDir'`) if isCygwin();
1255 }
1256
1257 sub windowsSourceDir()
1258 {
1259     determineWindowsSourceDir();
1260     return $windowsSourceDir;
1261 }
1262
1263 sub windowsLibrariesDir()
1264 {
1265     return windowsSourceDir() . "\\WebKitLibraries\\win";
1266 }
1267
1268 sub windowsOutputDir()
1269 {
1270     return windowsSourceDir() . "\\WebKitBuild";
1271 }
1272
1273 sub setupAppleWinEnv()
1274 {
1275     return unless isAppleWinWebKit();
1276
1277     if (isWindowsNT()) {
1278         my $restartNeeded = 0;
1279         my %variablesToSet = ();
1280
1281         # Setting the environment variable 'CYGWIN' to 'tty' makes cygwin enable extra support (i.e., termios)
1282         # for UNIX-like ttys in the Windows console
1283         $variablesToSet{CYGWIN} = "tty" unless $ENV{CYGWIN};
1284         
1285         # Those environment variables must be set to be able to build inside Visual Studio.
1286         $variablesToSet{WEBKITLIBRARIESDIR} = windowsLibrariesDir() unless $ENV{WEBKITLIBRARIESDIR};
1287         $variablesToSet{WEBKITOUTPUTDIR} = windowsOutputDir() unless $ENV{WEBKITOUTPUTDIR};
1288
1289         foreach my $variable (keys %variablesToSet) {
1290             print "Setting the Environment Variable '" . $variable . "' to '" . $variablesToSet{$variable} . "'\n\n";
1291             system qw(regtool -s set), '\\HKEY_CURRENT_USER\\Environment\\' . $variable, $variablesToSet{$variable};
1292             $restartNeeded ||= $variable eq "WEBKITLIBRARIESDIR" || $variable eq "WEBKITOUTPUTDIR";
1293         }
1294
1295         if ($restartNeeded) {
1296             print "Please restart your computer before attempting to build inside Visual Studio.\n\n";
1297         }
1298     } else {
1299         if (!$ENV{'WEBKITLIBRARIESDIR'}) {
1300             print "Warning: You must set the 'WebKitLibrariesDir' environment variable\n";
1301             print "         to be able build WebKit from within Visual Studio.\n";
1302             print "         Make sure that 'WebKitLibrariesDir' points to the\n";
1303             print "         'WebKitLibraries/win' directory, not the 'WebKitLibraries/' directory.\n\n";
1304         }
1305         if (!$ENV{'WEBKITOUTPUTDIR'}) {
1306             print "Warning: You must set the 'WebKitOutputDir' environment variable\n";
1307             print "         to be able build WebKit from within Visual Studio.\n\n";
1308         }
1309     }
1310 }
1311
1312 sub setupCygwinEnv()
1313 {
1314     return if !isCygwin() && !isWindows();
1315     return if $vcBuildPath;
1316
1317     my $vsInstallDir;
1318     my $programFilesPath = $ENV{'PROGRAMFILES(X86)'} || $ENV{'PROGRAMFILES'} || "C:\\Program Files";
1319     if ($ENV{'VSINSTALLDIR'}) {
1320         $vsInstallDir = $ENV{'VSINSTALLDIR'};
1321     } else {
1322         $vsInstallDir = File::Spec->catdir($programFilesPath, "Microsoft Visual Studio 8");
1323     }
1324     chomp($vsInstallDir = `cygpath "$vsInstallDir"`) if isCygwin();
1325     $vcBuildPath = File::Spec->catfile($vsInstallDir, qw(Common7 IDE devenv.com));
1326     if (-e $vcBuildPath) {
1327         # Visual Studio is installed; we can use pdevenv to build.
1328         # FIXME: Make pdevenv work with non-Cygwin Perl.
1329         $vcBuildPath = File::Spec->catfile(sourceDir(), qw(Tools Scripts pdevenv)) if isCygwin();
1330     } else {
1331         # Visual Studio not found, try VC++ Express
1332         $vcBuildPath = File::Spec->catfile($vsInstallDir, qw(Common7 IDE VCExpress.exe));
1333         if (! -e $vcBuildPath) {
1334             print "*************************************************************\n";
1335             print "Cannot find '$vcBuildPath'\n";
1336             print "Please execute the file 'vcvars32.bat' from\n";
1337             print "'$programFilesPath\\Microsoft Visual Studio 8\\VC\\bin\\'\n";
1338             print "to setup the necessary environment variables.\n";
1339             print "*************************************************************\n";
1340             die;
1341         }
1342         $willUseVCExpressWhenBuilding = 1;
1343     }
1344
1345     my $qtSDKPath = File::Spec->catdir($programFilesPath, "QuickTime SDK");
1346     if (0 && ! -e $qtSDKPath) {
1347         print "*************************************************************\n";
1348         print "Cannot find '$qtSDKPath'\n";
1349         print "Please download the QuickTime SDK for Windows from\n";
1350         print "http://developer.apple.com/quicktime/download/\n";
1351         print "*************************************************************\n";
1352         die;
1353     }
1354     
1355     unless ($ENV{WEBKITLIBRARIESDIR}) {
1356         $ENV{'WEBKITLIBRARIESDIR'} = File::Spec->catdir($sourceDir, "WebKitLibraries", "win");
1357         chomp($ENV{WEBKITLIBRARIESDIR} = `cygpath -wa '$ENV{WEBKITLIBRARIESDIR}'`) if isCygwin();
1358     }
1359
1360     print "Building results into: ", baseProductDir(), "\n";
1361     print "WEBKITOUTPUTDIR is set to: ", $ENV{"WEBKITOUTPUTDIR"}, "\n";
1362     print "WEBKITLIBRARIESDIR is set to: ", $ENV{"WEBKITLIBRARIESDIR"}, "\n";
1363 }
1364
1365 sub dieIfWindowsPlatformSDKNotInstalled
1366 {
1367     my $registry32Path = "/proc/registry/";
1368     my $registry64Path = "/proc/registry64/";
1369     my $windowsPlatformSDKRegistryEntry = "HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/MicrosoftSDK/InstalledSDKs/D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1";
1370
1371     # FIXME: It would be better to detect whether we are using 32- or 64-bit Windows
1372     # and only check the appropriate entry. But for now we just blindly check both.
1373     return if (-e $registry32Path . $windowsPlatformSDKRegistryEntry) || (-e $registry64Path . $windowsPlatformSDKRegistryEntry);
1374
1375     print "*************************************************************\n";
1376     print "Cannot find registry entry '$windowsPlatformSDKRegistryEntry'.\n";
1377     print "Please download and install the Microsoft Windows Server 2003 R2\n";
1378     print "Platform SDK from <http://www.microsoft.com/downloads/details.aspx?\n";
1379     print "familyid=0baf2b35-c656-4969-ace8-e4c0c0716adb&displaylang=en>.\n\n";
1380     print "Then follow step 2 in the Windows section of the \"Installing Developer\n";
1381     print "Tools\" instructions at <http://www.webkit.org/building/tools.html>.\n";
1382     print "*************************************************************\n";
1383     die;
1384 }
1385
1386 sub copyInspectorFrontendFiles
1387 {
1388     my $productDir = productDir();
1389     my $sourceInspectorPath = sourceDir() . "/Source/WebCore/inspector/front-end/";
1390     my $inspectorResourcesDirPath = $ENV{"WEBKITINSPECTORRESOURCESDIR"};
1391
1392     if (!defined($inspectorResourcesDirPath)) {
1393         $inspectorResourcesDirPath = "";
1394     }
1395
1396     if (isAppleMacWebKit()) {
1397         $inspectorResourcesDirPath = $productDir . "/WebCore.framework/Resources/inspector";
1398     } elsif (isAppleWinWebKit()) {
1399         $inspectorResourcesDirPath = $productDir . "/WebKit.resources/inspector";
1400     } elsif (isQt() || isGtk()) {
1401         my $prefix = $ENV{"WebKitInstallationPrefix"};
1402         $inspectorResourcesDirPath = (defined($prefix) ? $prefix : "/usr/share") . "/webkit-1.0/webinspector";
1403     } elsif (isEfl()) {
1404         my $prefix = $ENV{"WebKitInstallationPrefix"};
1405         $inspectorResourcesDirPath = (defined($prefix) ? $prefix : "/usr/share") . "/ewebkit/webinspector";
1406     }
1407
1408     if (! -d $inspectorResourcesDirPath) {
1409         print "*************************************************************\n";
1410         print "Cannot find '$inspectorResourcesDirPath'.\n" if (defined($inspectorResourcesDirPath));
1411         print "Make sure that you have built WebKit first.\n" if (! -d $productDir || defined($inspectorResourcesDirPath));
1412         print "Optionally, set the environment variable 'WebKitInspectorResourcesDir'\n";
1413         print "to point to the directory that contains the WebKit Inspector front-end\n";
1414         print "files for the built WebCore framework.\n";
1415         print "*************************************************************\n";
1416         die;
1417     }
1418
1419     if (isAppleMacWebKit()) {
1420         my $sourceLocalizedStrings = sourceDir() . "/Source/WebCore/English.lproj/localizedStrings.js";
1421         my $destinationLocalizedStrings = $productDir . "/WebCore.framework/Resources/English.lproj/localizedStrings.js";
1422         system "ditto", $sourceLocalizedStrings, $destinationLocalizedStrings;
1423     }
1424
1425     return system "rsync", "-aut", "--exclude=/.DS_Store", "--exclude=*.re2js", "--exclude=.svn/", !isQt() ? "--exclude=/WebKit.qrc" : "", $sourceInspectorPath, $inspectorResourcesDirPath;
1426 }
1427
1428 sub buildXCodeProject($$@)
1429 {
1430     my ($project, $clean, @extraOptions) = @_;
1431
1432     if ($clean) {
1433         push(@extraOptions, "-alltargets");
1434         push(@extraOptions, "clean");
1435     }
1436
1437     return system "xcodebuild", "-project", "$project.xcodeproj", @extraOptions;
1438 }
1439
1440 sub usingVisualStudioExpress()
1441 {
1442     setupCygwinEnv();
1443     return $willUseVCExpressWhenBuilding;
1444 }
1445
1446 sub buildVisualStudioProject
1447 {
1448     my ($project, $clean) = @_;
1449     setupCygwinEnv();
1450
1451     my $config = configurationForVisualStudio();
1452
1453     dieIfWindowsPlatformSDKNotInstalled() if $willUseVCExpressWhenBuilding;
1454
1455     chomp($project = `cygpath -w "$project"`) if isCygwin();
1456     
1457     my $action = "/build";
1458     if ($clean) {
1459         $action = "/clean";
1460     }
1461
1462     my @command = ($vcBuildPath, $project, $action, $config);
1463
1464     print join(" ", @command), "\n";
1465     return system @command;
1466 }
1467
1468 sub downloadWafIfNeeded
1469 {
1470     # get / update waf if needed
1471     my $waf = "$sourceDir/Tools/waf/waf";
1472     my $wafURL = 'http://wxwebkit.kosoftworks.com/downloads/deps/waf';
1473     if (!-f $waf) {
1474         my $result = system "curl -o $waf $wafURL";
1475         chmod 0755, $waf;
1476     }
1477 }
1478
1479 sub buildWafProject
1480 {
1481     my ($project, $shouldClean, @options) = @_;
1482     
1483     # set the PYTHONPATH for waf
1484     my $pythonPath = $ENV{'PYTHONPATH'};
1485     if (!defined($pythonPath)) {
1486         $pythonPath = '';
1487     }
1488     my $sourceDir = sourceDir();
1489     my $newPythonPath = "$sourceDir/Tools/waf/build:$pythonPath";
1490     if (isCygwin()) {
1491         $newPythonPath = `cygpath --mixed --path $newPythonPath`;
1492     }
1493     $ENV{'PYTHONPATH'} = $newPythonPath;
1494     
1495     print "Building $project\n";
1496
1497     my $wafCommand = "$sourceDir/Tools/waf/waf";
1498     if ($ENV{'WXWEBKIT_WAF'}) {
1499         $wafCommand = $ENV{'WXWEBKIT_WAF'};
1500     }
1501     if (isCygwin()) {
1502         $wafCommand = `cygpath --windows "$wafCommand"`;
1503         chomp($wafCommand);
1504     }
1505     if ($shouldClean) {
1506         return system $wafCommand, "uninstall", "clean", "distclean";
1507     }
1508     
1509     return system $wafCommand, 'configure', 'build', 'install', @options;
1510 }
1511
1512 sub retrieveQMakespecVar
1513 {
1514     my $mkspec = $_[0];
1515     my $varname = $_[1];
1516
1517     my $varvalue = undef;
1518     #print "retrieveMakespecVar " . $mkspec . ", " . $varname . "\n";
1519
1520     local *SPEC;
1521     open SPEC, "<$mkspec" or return $varvalue;
1522     while (<SPEC>) {
1523         if ($_ =~ /\s*include\((.+)\)/) {
1524             # open the included mkspec
1525             my $oldcwd = getcwd();
1526             (my $volume, my $directories, my $file) = File::Spec->splitpath($mkspec);
1527             my $newcwd = "$volume$directories";
1528             chdir $newcwd if $newcwd;
1529             $varvalue = retrieveQMakespecVar($1, $varname);
1530             chdir $oldcwd;
1531         } elsif ($_ =~ /$varname\s*=\s*([^\s]+)/) {
1532             $varvalue = $1;
1533             last;
1534         }
1535     }
1536     close SPEC;
1537     return $varvalue;
1538 }
1539
1540 sub qtMakeCommand($)
1541 {
1542     my ($qmakebin) = @_;
1543     chomp(my $mkspec = `$qmakebin -query QMAKE_MKSPECS`);
1544     $mkspec .= "/default";
1545     my $compiler = retrieveQMakespecVar("$mkspec/qmake.conf", "QMAKE_CC");
1546
1547     #print "default spec: " . $mkspec . "\n";
1548     #print "compiler found: " . $compiler . "\n";
1549
1550     if ($compiler && $compiler eq "cl") {
1551         return "nmake";
1552     }
1553
1554     return "make";
1555 }
1556
1557 sub autotoolsFlag($$)
1558 {
1559     my ($flag, $feature) = @_;
1560     my $prefix = $flag ? "--enable" : "--disable";
1561
1562     return $prefix . '-' . $feature;
1563 }
1564
1565 sub runAutogenForAutotoolsProject($@)
1566 {
1567     my ($dir, $prefix, $sourceDir, $saveArguments, $argumentsFile, @buildArgs) = @_;
1568
1569     print "Calling autogen.sh in " . $dir . "\n\n";
1570     print "Installation prefix directory: $prefix\n" if(defined($prefix));
1571
1572     if ($saveArguments) {
1573         # Write autogen.sh arguments to a file so that we can detect
1574         # when they change and automatically re-run it.
1575         open(AUTOTOOLS_ARGUMENTS, ">$argumentsFile");
1576         print AUTOTOOLS_ARGUMENTS join(" ", @buildArgs);
1577         close(AUTOTOOLS_ARGUMENTS);
1578     }
1579
1580     # Make the path relative since it will appear in all -I compiler flags.
1581     # Long argument lists cause bizarre slowdowns in libtool.
1582     my $relSourceDir = File::Spec->abs2rel($sourceDir) || ".";
1583     if (system("$relSourceDir/autogen.sh", @buildArgs) ne 0) {
1584         die "Calling autogen.sh failed!\n";
1585     }
1586 }
1587
1588 sub autogenArgumentsHaveChanged($@)
1589 {
1590     my ($filename, @currentArguments) = @_;
1591
1592     if (! -e $filename) {
1593         return 1;
1594     }
1595
1596     open(AUTOTOOLS_ARGUMENTS, $filename);
1597     chomp(my $previousArguments = <AUTOTOOLS_ARGUMENTS>);
1598     close(AUTOTOOLS_ARGUMENTS);
1599
1600     my $joinedCurrentArguments = join(" ", @currentArguments);
1601     if ($previousArguments ne $joinedCurrentArguments) {
1602         print "Previous autogen arguments were: $previousArguments\n\n";
1603         print "New autogen arguments are: $joinedCurrentArguments\n";
1604         return 1;
1605     }
1606
1607     return 0;
1608 }
1609
1610 sub buildAutotoolsProject($@)
1611 {
1612     my ($project, $clean, $enableWebKit2, @buildParams) = @_;
1613
1614     my $make = 'make';
1615     my $dir = productDir();
1616     my $config = passedConfiguration() || configuration();
1617     my $prefix;
1618
1619     my @buildArgs = ();
1620     my $makeArgs = $ENV{"WebKitMakeArguments"} || "";
1621     for my $i (0 .. $#buildParams) {
1622         my $opt = $buildParams[$i];
1623         if ($opt =~ /^--makeargs=(.*)/i ) {
1624             $makeArgs = $makeArgs . " " . $1;
1625         } elsif ($opt =~ /^--prefix=(.*)/i ) {
1626             $prefix = $1;
1627         } else {
1628             push @buildArgs, $opt;
1629         }
1630     }
1631
1632     # Automatically determine the number of CPUs for make only
1633     # if make arguments haven't already been specified.
1634     if ($makeArgs eq "") {
1635         $makeArgs = "-j" . numberOfCPUs();
1636     }
1637
1638     # WebKit is the default target, so we don't need to specify anything.
1639     if ($project eq "JavaScriptCore") {
1640         $makeArgs .= " jsc";
1641     }
1642
1643     # This is a temporary work-around to enable building WebKit2 on the bots,
1644     # but ensuring that it does not ship until the API is stable.
1645     if ($project eq "WebKit" and isGtk() and $enableWebKit2) {
1646         push @buildArgs, "--enable-webkit2";
1647     }
1648
1649     $prefix = $ENV{"WebKitInstallationPrefix"} if !defined($prefix);
1650     push @buildArgs, "--prefix=" . $prefix if defined($prefix);
1651
1652     # check if configuration is Debug
1653     if ($config =~ m/debug/i) {
1654         push @buildArgs, "--enable-debug";
1655     } else {
1656         push @buildArgs, "--disable-debug";
1657     }
1658
1659     # Use rm to clean the build directory since distclean may miss files
1660     if ($clean && -d $dir) {
1661         system "rm", "-rf", "$dir";
1662     }
1663
1664     if (! -d $dir) {
1665         File::Path::mkpath($dir) or die "Failed to create build directory " . $dir
1666     }
1667     chdir $dir or die "Failed to cd into " . $dir . "\n";
1668
1669     if ($clean) {
1670         return 0;
1671     }
1672
1673     # If GNUmakefile exists, don't run autogen.sh unless its arguments
1674     # have changed. The makefile should be smart enough to track autotools
1675     # dependencies and re-run autogen.sh when build files change.
1676     my $autogenArgumentsFile = "previous-autogen-arguments.txt";
1677     my $saveAutogenArguments = $project eq "WebKit";
1678     if (!(-e "GNUmakefile")) {
1679         runAutogenForAutotoolsProject($dir, $prefix, $sourceDir, $saveAutogenArguments, $autogenArgumentsFile, @buildArgs);
1680     }
1681
1682     if ($saveAutogenArguments and autogenArgumentsHaveChanged($autogenArgumentsFile, @buildArgs)) {
1683         runAutogenForAutotoolsProject($dir, $prefix, $sourceDir, $saveAutogenArguments, $autogenArgumentsFile, @buildArgs);
1684     }
1685
1686     if (system("$make $makeArgs") ne 0) {
1687         die "\nFailed to build WebKit using '$make'!\n";
1688     }
1689
1690     chdir ".." or die;
1691
1692     if (isGtk()) {
1693         my $relativeScriptsPath = relativeScriptsDir();
1694         if (system("$relativeScriptsPath/../gtk/generate-gtkdoc --skip-html")) {
1695             die "\n gtkdoc did not build without warnings\n";
1696         }
1697     }
1698
1699     return 0;
1700 }
1701
1702 sub generateBuildSystemFromCMakeProject
1703 {
1704     my ($port, $prefixPath, @cmakeArgs, $additionalCMakeArgs) = @_;
1705     my $config = configuration();
1706     my $buildPath = File::Spec->catdir(baseProductDir(), $config);
1707     File::Path::mkpath($buildPath) unless -d $buildPath;
1708     my $originalWorkingDirectory = getcwd();
1709     chdir($buildPath) or die;
1710
1711     my @args;
1712     push @args, "-DPORT=\"$port\"";
1713     push @args, "-DCMAKE_INSTALL_PREFIX=\"$prefixPath\"" if $prefixPath;
1714     if ($config =~ /release/i) {
1715         push @args, "-DCMAKE_BUILD_TYPE=Release";
1716     } elsif ($config =~ /debug/i) {
1717         push @args, "-DCMAKE_BUILD_TYPE=Debug";
1718     }
1719     # if ENABLE(TIZEN_WEBKIT_EFL_DRT)
1720     push @args, "-DSHARED_CORE=ON";
1721     # endif
1722     push @args, @cmakeArgs if @cmakeArgs;
1723     push @args, $additionalCMakeArgs if $additionalCMakeArgs;
1724
1725     push @args, '"' . sourceDir() . '"';
1726
1727     # We call system("cmake @args") instead of system("cmake", @args) so that @args is
1728     # parsed for shell metacharacters.
1729     my $returnCode = system("cmake @args");
1730
1731     chdir($originalWorkingDirectory);
1732     return $returnCode;
1733 }
1734
1735 sub buildCMakeGeneratedProject($)
1736 {
1737     my ($makeArgs) = @_;
1738     my $config = configuration();
1739     my $buildPath = File::Spec->catdir(baseProductDir(), $config);
1740     if (! -d $buildPath) {
1741         die "Must call generateBuildSystemFromCMakeProject() before building CMake project.";
1742     }
1743     my @args = ("--build", $buildPath, "--config", $config);
1744     push @args, ("--", $makeArgs) if $makeArgs;
1745
1746     # We call system("cmake @args") instead of system("cmake", @args) so that @args is
1747     # parsed for shell metacharacters. In particular, $makeArgs may contain such metacharacters.
1748     return system("cmake @args");
1749 }
1750
1751 sub cleanCMakeGeneratedProject()
1752 {
1753     my $config = configuration();
1754     my $buildPath = File::Spec->catdir(baseProductDir(), $config);
1755     if (-d $buildPath) {
1756         return system("cmake", "--build", $buildPath, "--config", $config, "--target", "clean");
1757     }
1758     return 0;
1759 }
1760
1761 sub buildCMakeProjectOrExit($$$$@)
1762 {
1763     my ($clean, $port, $prefixPath, $makeArgs, @cmakeArgs) = @_;
1764     my $returnCode;
1765
1766     exit(exitStatus(cleanCMakeGeneratedProject())) if $clean;
1767
1768     $returnCode = exitStatus(generateBuildSystemFromCMakeProject($port, $prefixPath, @cmakeArgs));
1769     exit($returnCode) if $returnCode;
1770     $returnCode = exitStatus(buildCMakeGeneratedProject($makeArgs));
1771     exit($returnCode) if $returnCode;
1772 }
1773
1774 sub promptUser
1775 {
1776     my ($prompt, $default) = @_;
1777     my $defaultValue = $default ? "[$default]" : "";
1778     print "$prompt $defaultValue: ";
1779     chomp(my $input = <STDIN>);
1780     return $input ? $input : $default;
1781 }
1782
1783 sub buildQMakeProject($@)
1784 {
1785     my ($project, $clean, @buildParams) = @_;
1786
1787     my @buildArgs = ();
1788
1789     my $makeargs = "";
1790     my $installHeaders;
1791     my $installLibs;
1792     for my $i (0 .. $#buildParams) {
1793         my $opt = $buildParams[$i];
1794         if ($opt =~ /^--qmake=(.*)/i ) {
1795             $qmakebin = $1;
1796         } elsif ($opt =~ /^--qmakearg=(.*)/i ) {
1797             push @buildArgs, $1;
1798         } elsif ($opt =~ /^--makeargs=(.*)/i ) {
1799             $makeargs = $1;
1800         } elsif ($opt =~ /^--install-headers=(.*)/i ) {
1801             $installHeaders = $1;
1802         } elsif ($opt =~ /^--install-libs=(.*)/i ) {
1803             $installLibs = $1;
1804         } else {
1805             push @buildArgs, $opt;
1806         }
1807     }
1808
1809     my $qmakepath = File::Spec->catfile(sourceDir(), "Tools", "qmake");
1810     my $qmakecommand;
1811     if (isWindows()) {
1812         $qmakecommand = "(set QMAKEPATH=$qmakepath) && $qmakebin";
1813     } else {
1814         $qmakecommand = "QMAKEPATH=$qmakepath $qmakebin";
1815     }
1816
1817     my $make = qtMakeCommand($qmakebin);
1818     my $config = configuration();
1819     push @buildArgs, "INSTALL_HEADERS=" . $installHeaders if defined($installHeaders);
1820     push @buildArgs, "INSTALL_LIBS=" . $installLibs if defined($installLibs);
1821
1822     my $passedConfig = passedConfiguration() || "";
1823     if ($passedConfig =~ m/debug/i) {
1824         push @buildArgs, "CONFIG-=release";
1825         push @buildArgs, "CONFIG+=debug";
1826     } elsif ($passedConfig =~ m/release/i) {
1827         push @buildArgs, "CONFIG+=release";
1828         push @buildArgs, "CONFIG-=debug";
1829     }
1830     push @buildArgs, "CONFIG-=debug_and_release" if ($passedConfig && isDarwin());
1831
1832     my $originalCwd = getcwd();
1833     my $dir = File::Spec->canonpath(productDir());
1834     File::Path::mkpath($dir);
1835     chdir $dir or die "Failed to cd into " . $dir . "\n";
1836
1837     my %defines = qtFeatureDefaults(\@buildArgs);
1838
1839     my $needsCleanBuild = 0;
1840
1841     # Ease transition to new build layout
1842     my $pathToOldDefinesFile = File::Spec->catfile($dir, "defaults.txt");
1843     if (-e $pathToOldDefinesFile) {
1844         print "Old build layout detected";
1845         $needsCleanBuild = 1;
1846     }
1847
1848     my $pathToDefinesCache = File::Spec->catfile($dir, ".webkit.config");
1849     if ($needsCleanBuild || (-e $pathToDefinesCache && open(DEFAULTS, $pathToDefinesCache))) {
1850         if (!$needsCleanBuild) {
1851             while (<DEFAULTS>) {
1852                 if ($_ =~ m/(\S+?)=(\S+?)/gi) {
1853                     if (! exists $defines{$1}) {
1854                         print "Feature $1 was removed";
1855                         $needsCleanBuild = 1;
1856                         last;
1857                     }
1858
1859                     if ($defines{$1} != $2) {
1860                         print "Feature $1 has changed ($2 -> $defines{$1})";
1861                         $needsCleanBuild = 1;
1862                         last;
1863                     }
1864                 }
1865             }
1866             close (DEFAULTS);
1867         }
1868
1869         if ($needsCleanBuild) {
1870             print ", clean build needed!\n";
1871             # FIXME: This STDIN/STDOUT check does not work on the bots. Disable until it does.
1872             # if (! -t STDIN || ( &promptUser("Would you like to clean the build directory?", "yes") eq "yes")) {
1873                 chdir $originalCwd;
1874                 File::Path::rmtree($dir);
1875                 File::Path::mkpath($dir);
1876                 chdir $dir or die "Failed to cd into " . $dir . "\n";
1877             #}
1878         }
1879     }
1880
1881     open(DEFAULTS, ">$pathToDefinesCache");
1882     print DEFAULTS "# These defines were set when building WebKit last time\n";
1883     foreach my $key (sort keys %defines) {
1884         print DEFAULTS "$key=$defines{$key}\n";
1885     }
1886     close(DEFAULTS);
1887
1888     my $result = 0;
1889
1890     my $makefile = File::Spec->catfile($dir, "Makefile");
1891     if (! -e $makefile) {
1892         if ($project) {
1893             push @buildArgs, "-after OVERRIDE_SUBDIRS=" . $project;
1894         }
1895
1896         push @buildArgs, File::Spec->catfile(sourceDir(), "WebKit.pro");
1897         my $command = "$qmakecommand @buildArgs";
1898         print "Calling '$command' in " . $dir . "\n\n";
1899         print "Installation headers directory: $installHeaders\n" if(defined($installHeaders));
1900         print "Installation libraries directory: $installLibs\n" if(defined($installLibs));
1901
1902         $result = system "$command";
1903         if ($result ne 0) {
1904            die "Failed to setup build environment using $qmakebin!\n";
1905         }
1906     } elsif ($project) {
1907         $dir = File::Spec->catfile($dir, "Source", $project);
1908         chdir $dir or die "Failed to cd into " . $dir . "\n";
1909         $make = "$make -f Makefile.$project";
1910     }
1911
1912     my $command = "$make $makeargs";
1913     $command =~ s/\s+$//;
1914
1915     if ($clean) {
1916         $command = "$command distclean";
1917     } else {
1918         $command = "$command incremental";
1919     }
1920
1921     print "Calling '$command' in " . $dir . "\n\n";
1922     $result = system $command;
1923
1924     chdir ".." or die;
1925     return $result;
1926 }
1927
1928 sub buildQMakeQtProject($$@)
1929 {
1930     my ($project, $clean, @buildArgs) = @_;
1931
1932     return buildQMakeProject("", $clean, @buildArgs);
1933 }
1934
1935 sub buildGtkProject
1936 {
1937     my ($project, $clean, $enableWebKit2, @buildArgs) = @_;
1938
1939     if ($project ne "WebKit" and $project ne "JavaScriptCore") {
1940         die "Unsupported project: $project. Supported projects: WebKit, JavaScriptCore\n";
1941     }
1942
1943     return buildAutotoolsProject($project, $clean, $enableWebKit2, @buildArgs);
1944 }
1945
1946 sub buildChromiumMakefile($$@)
1947 {
1948     my ($target, $clean, @options) = @_;
1949     if ($clean) {
1950         return system qw(rm -rf out);
1951     }
1952     my $config = configuration();
1953     my $numCpus = numberOfCPUs();
1954     my $makeArgs;
1955     for (@options) {
1956         $makeArgs = $1 if /^--makeargs=(.*)/i;
1957     }
1958     $makeArgs = "-j$numCpus" if not $makeArgs;
1959     my $command = "";
1960
1961     # Building the WebKit Chromium port for Android requires us to cross-
1962     # compile, which will be set up by Chromium's envsetup.sh. The script itself
1963     # will verify that the installed NDK is indeed available.
1964     if (isChromiumAndroid()) {
1965         $command .= "bash -c \"source " . sourceDir() . "/Source/WebKit/chromium/build/android/envsetup.sh && ";
1966         $ENV{ANDROID_NDK_ROOT} = sourceDir() . "/Source/WebKit/chromium/third_party/android-ndk-r7";
1967         $ENV{WEBKIT_ANDROID_BUILD} = 1;
1968     }
1969
1970     $command .= "make -fMakefile.chromium $makeArgs BUILDTYPE=$config $target";
1971     $command .= "\"" if isChromiumAndroid();
1972
1973     print "$command\n";
1974     return system $command;
1975 }
1976
1977 sub buildChromiumVisualStudioProject($$)
1978 {
1979     my ($projectPath, $clean) = @_;
1980
1981     my $config = configuration();
1982     my $action = "/build";
1983     $action = "/clean" if $clean;
1984
1985     # Find Visual Studio installation.
1986     my $vsInstallDir;
1987     my $programFilesPath = $ENV{'PROGRAMFILES'} || "C:\\Program Files";
1988     if ($ENV{'VSINSTALLDIR'}) {
1989         $vsInstallDir = $ENV{'VSINSTALLDIR'};
1990     } else {
1991         $vsInstallDir = "$programFilesPath/Microsoft Visual Studio 8";
1992     }
1993     $vsInstallDir = `cygpath "$vsInstallDir"` if isCygwin();
1994     chomp $vsInstallDir;
1995     $vcBuildPath = "$vsInstallDir/Common7/IDE/devenv.com";
1996     if (! -e $vcBuildPath) {
1997         # Visual Studio not found, try VC++ Express
1998         $vcBuildPath = "$vsInstallDir/Common7/IDE/VCExpress.exe";
1999         if (! -e $vcBuildPath) {
2000             print "*************************************************************\n";
2001             print "Cannot find '$vcBuildPath'\n";
2002             print "Please execute the file 'vcvars32.bat' from\n";
2003             print "'$programFilesPath\\Microsoft Visual Studio 8\\VC\\bin\\'\n";
2004             print "to setup the necessary environment variables.\n";
2005             print "*************************************************************\n";
2006             die;
2007         }
2008     }
2009
2010     # Create command line and execute it.
2011     my @command = ($vcBuildPath, $projectPath, $action, $config);
2012     print "Building results into: ", baseProductDir(), "\n";
2013     print join(" ", @command), "\n";
2014     return system @command;
2015 }
2016
2017 sub buildChromium($@)
2018 {
2019     my ($clean, @options) = @_;
2020
2021     # We might need to update DEPS or re-run GYP if things have changed.
2022     if (checkForArgumentAndRemoveFromArrayRef("--update-chromium", \@options)) {
2023         system("perl", "Tools/Scripts/update-webkit-chromium", "--force") == 0 or die $!;
2024     }
2025
2026     my $result = 1;
2027     if (isDarwin() && !isChromiumAndroid() && !isChromiumMacMake()) {
2028         # Mac build - builds the root xcode project.
2029         $result = buildXCodeProject("Source/WebKit/chromium/WebKit", $clean, "-configuration", configuration(), @options);
2030     } elsif (isCygwin() || isWindows()) {
2031         # Windows build - builds the root visual studio solution.
2032         $result = buildChromiumVisualStudioProject("Source/WebKit/chromium/WebKit.sln", $clean);
2033     } elsif (isLinux() || isChromiumAndroid() || isChromiumMacMake) {
2034         # Linux build - build using make.
2035         $result = buildChromiumMakefile("all", $clean, @options);
2036     } else {
2037         print STDERR "This platform is not supported by chromium.\n";
2038     }
2039     return $result;
2040 }
2041
2042 sub appleApplicationSupportPath
2043 {
2044     open INSTALL_DIR, "</proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/Apple\ Inc./Apple\ Application\ Support/InstallDir";
2045     my $path = <INSTALL_DIR>;
2046     $path =~ s/[\r\n\x00].*//;
2047     close INSTALL_DIR;
2048
2049     my $unixPath = `cygpath -u '$path'`;
2050     chomp $unixPath;
2051     return $unixPath;
2052 }
2053
2054 sub setPathForRunningWebKitApp
2055 {
2056     my ($env) = @_;
2057
2058     if (isAppleWinWebKit()) {
2059         $env->{PATH} = join(':', productDir(), dirname(installedSafariPath()), appleApplicationSupportPath(), $env->{PATH} || "");
2060     } elsif (isQt()) {
2061         my $qtLibs = `$qmakebin -query QT_INSTALL_LIBS`;
2062         $qtLibs =~ s/[\n|\r]$//g;
2063         $env->{PATH} = join(';', $qtLibs, productDir() . "/lib", $env->{PATH} || "");
2064     }
2065 }
2066
2067 sub runMacWebKitApp($;$)
2068 {
2069     my ($appPath, $useOpenCommand) = @_;
2070     my $productDir = productDir();
2071     print "Starting @{[basename($appPath)]} with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2072     $ENV{DYLD_FRAMEWORK_PATH} = $productDir;
2073     $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2074     if (defined($useOpenCommand) && $useOpenCommand == USE_OPEN_COMMAND) {
2075         return system("open", "-W", "-a", $appPath, "--args", @ARGV);
2076     }
2077     if (architecture()) {
2078         return system "arch", "-" . architecture(), $appPath, @ARGV;
2079     }
2080     return system { $appPath } $appPath, @ARGV;
2081 }
2082
2083 sub execMacWebKitAppForDebugging($)
2084 {
2085     my ($appPath) = @_;
2086
2087     my $gdbPath = "/usr/bin/gdb";
2088     die "Can't find gdb executable. Is gdb installed?\n" unless -x $gdbPath;
2089
2090     my $productDir = productDir();
2091     print "Starting @{[basename($appPath)]} under gdb with DYLD_FRAMEWORK_PATH set to point to built WebKit in $productDir.\n";
2092     $ENV{DYLD_FRAMEWORK_PATH} = $productDir;
2093     $ENV{WEBKIT_UNSET_DYLD_FRAMEWORK_PATH} = "YES";
2094     my @architectureFlags = ("-arch", architecture());
2095     exec { $gdbPath } $gdbPath, @architectureFlags, $appPath or die;
2096 }
2097
2098 sub debugSafari
2099 {
2100     if (isAppleMacWebKit()) {
2101         checkFrameworks();
2102         execMacWebKitAppForDebugging(safariPath());
2103     }
2104
2105     if (isAppleWinWebKit()) {
2106         setupCygwinEnv();
2107         my $productDir = productDir();
2108         chomp($ENV{WEBKITNIGHTLY} = `cygpath -wa "$productDir"`);
2109         my $safariPath = safariPath();
2110         chomp($safariPath = `cygpath -wa "$safariPath"`);
2111         return system { $vcBuildPath } $vcBuildPath, "/debugexe", "\"$safariPath\"", @ARGV;
2112     }
2113
2114     return 1; # Unsupported platform; can't debug Safari on this platform.
2115 }
2116
2117 sub runSafari
2118 {
2119
2120     if (isAppleMacWebKit()) {
2121         return runMacWebKitApp(safariPath());
2122     }
2123
2124     if (isAppleWinWebKit()) {
2125         my $result;
2126         my $productDir = productDir();
2127         my $webKitLauncherPath = File::Spec->catfile(productDir(), "WebKit.exe");
2128         return system { $webKitLauncherPath } $webKitLauncherPath, @ARGV;
2129     }
2130
2131     return 1; # Unsupported platform; can't run Safari on this platform.
2132 }
2133
2134 sub runMiniBrowser
2135 {
2136     if (isAppleMacWebKit()) {
2137         return runMacWebKitApp(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2138     }
2139
2140     return 1;
2141 }
2142
2143 sub debugMiniBrowser
2144 {
2145     if (isAppleMacWebKit()) {
2146         execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "MiniBrowser.app", "Contents", "MacOS", "MiniBrowser"));
2147     }
2148     
2149     return 1;
2150 }
2151
2152 sub runWebKitTestRunner
2153 {
2154     if (isAppleMacWebKit()) {
2155         return runMacWebKitApp(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2156     } elsif (isGtk()) {
2157         my $productDir = productDir();
2158         my $injectedBundlePath = "$productDir/Libraries/.libs/libTestRunnerInjectedBundle";
2159         print "Starting WebKitTestRunner with TEST_RUNNER_INJECTED_BUNDLE_FILENAME set to point to $injectedBundlePath.\n";
2160         $ENV{TEST_RUNNER_INJECTED_BUNDLE_FILENAME} = $injectedBundlePath;
2161         my @args = ("$productDir/Programs/WebKitTestRunner", @ARGV);
2162         return system {$args[0] } @args;
2163     }
2164
2165     return 1;
2166 }
2167
2168 sub debugWebKitTestRunner
2169 {
2170     if (isAppleMacWebKit()) {
2171         execMacWebKitAppForDebugging(File::Spec->catfile(productDir(), "WebKitTestRunner"));
2172     }
2173
2174     return 1;
2175 }
2176
2177 sub runTestWebKitAPI
2178 {
2179     if (isAppleMacWebKit()) {
2180         return runMacWebKitApp(File::Spec->catfile(productDir(), "TestWebKitAPI"));
2181     }
2182
2183     return 1;
2184 }
2185
2186 sub readRegistryString
2187 {
2188     my ($valueName) = @_;
2189     chomp(my $string = `regtool --wow32 get "$valueName"`);
2190     return $string;
2191 }
2192
2193 sub writeRegistryString
2194 {
2195     my ($valueName, $string) = @_;
2196
2197     my $error = system "regtool", "--wow32", "set", "-s", $valueName, $string;
2198
2199     # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
2200     # return a successful exit code. So we double-check here that the value we tried to write to the
2201     # registry was really written.
2202     return !$error && readRegistryString($valueName) eq $string;
2203 }
2204
2205 1;