1#!/usr/bin/env perl
2#
3# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4# See https://llvm.org/LICENSE.txt for license information.
5# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6#
7##===----------------------------------------------------------------------===##
8#
9#  A script designed to interpose between the build system and gcc.  It invokes
10#  both gcc and the static analyzer.
11#
12##===----------------------------------------------------------------------===##
13
14use strict;
15use warnings;
16use FindBin;
17use Cwd qw/ getcwd abs_path /;
18use File::Temp qw/ tempfile /;
19use File::Path qw / mkpath /;
20use File::Basename;
21use Text::ParseWords;
22
23##===----------------------------------------------------------------------===##
24# List form 'system' with STDOUT and STDERR captured.
25##===----------------------------------------------------------------------===##
26
27sub silent_system {
28  my $HtmlDir = shift;
29  my $Command = shift;
30
31  # Save STDOUT and STDERR and redirect to a temporary file.
32  open OLDOUT, ">&", \*STDOUT;
33  open OLDERR, ">&", \*STDERR;
34  my ($TmpFH, $TmpFile) = tempfile("temp_buf_XXXXXX",
35                                   DIR => $HtmlDir,
36                                   UNLINK => 1);
37  open(STDOUT, ">$TmpFile");
38  open(STDERR, ">&", \*STDOUT);
39
40  # Invoke 'system', STDOUT and STDERR are output to a temporary file.
41  system $Command, @_;
42
43  # Restore STDOUT and STDERR.
44  open STDOUT, ">&", \*OLDOUT;
45  open STDERR, ">&", \*OLDERR;
46
47  return $TmpFH;
48}
49
50##===----------------------------------------------------------------------===##
51# Compiler command setup.
52##===----------------------------------------------------------------------===##
53
54# Search in the PATH if the compiler exists
55sub SearchInPath {
56    my $file = shift;
57    foreach my $dir (split (':', $ENV{PATH})) {
58        if (-x "$dir/$file") {
59            return 1;
60        }
61    }
62    return 0;
63}
64
65my $Compiler;
66my $Clang;
67my $DefaultCCompiler;
68my $DefaultCXXCompiler;
69my $IsCXX;
70my $AnalyzerTarget;
71
72# If on OSX, use xcrun to determine the SDK root.
73my $UseXCRUN = 0;
74
75if (`uname -s` =~ m/Darwin/) {
76  $DefaultCCompiler = 'clang';
77  $DefaultCXXCompiler = 'clang++';
78  # Older versions of OSX do not have xcrun to
79  # query the SDK location.
80  if (-x "/usr/bin/xcrun") {
81    $UseXCRUN = 1;
82  }
83} elsif (`uname -s` =~ m/(FreeBSD|OpenBSD)/) {
84  $DefaultCCompiler = 'cc';
85  $DefaultCXXCompiler = 'c++';
86} else {
87  $DefaultCCompiler = 'gcc';
88  $DefaultCXXCompiler = 'g++';
89}
90
91if ($FindBin::Script =~ /c\+\+-analyzer/) {
92  $Compiler = $ENV{'CCC_CXX'};
93  if (!defined $Compiler || (! -x $Compiler && ! SearchInPath($Compiler))) { $Compiler = $DefaultCXXCompiler; }
94
95  $Clang = $ENV{'CLANG_CXX'};
96  if (!defined $Clang || ! -x $Clang) { $Clang = 'clang++'; }
97
98  $IsCXX = 1
99}
100else {
101  $Compiler = $ENV{'CCC_CC'};
102  if (!defined $Compiler || (! -x $Compiler && ! SearchInPath($Compiler))) { $Compiler = $DefaultCCompiler; }
103
104  $Clang = $ENV{'CLANG'};
105  if (!defined $Clang || ! -x $Clang) { $Clang = 'clang'; }
106
107  $IsCXX = 0
108}
109
110$AnalyzerTarget = $ENV{'CLANG_ANALYZER_TARGET'};
111
112##===----------------------------------------------------------------------===##
113# Cleanup.
114##===----------------------------------------------------------------------===##
115
116my $ReportFailures = $ENV{'CCC_REPORT_FAILURES'};
117if (!defined $ReportFailures) { $ReportFailures = 1; }
118
119my $CleanupFile;
120my $ResultFile;
121
122# Remove any stale files at exit.
123END {
124  if (defined $ResultFile && -z $ResultFile) {
125    unlink($ResultFile);
126  }
127  if (defined $CleanupFile) {
128    unlink($CleanupFile);
129  }
130}
131
132##----------------------------------------------------------------------------##
133#  Process Clang Crashes.
134##----------------------------------------------------------------------------##
135
136sub GetPPExt {
137  my $Lang = shift;
138  if ($Lang =~ /objective-c\+\+/) { return ".mii" };
139  if ($Lang =~ /objective-c/) { return ".mi"; }
140  if ($Lang =~ /c\+\+/) { return ".ii"; }
141  return ".i";
142}
143
144# Set this to 1 if we want to include 'parser rejects' files.
145my $IncludeParserRejects = 0;
146my $ParserRejects = "Parser Rejects";
147my $AttributeIgnored = "Attribute Ignored";
148my $OtherError = "Other Error";
149
150sub ProcessClangFailure {
151  my ($Clang, $Lang, $file, $Args, $HtmlDir, $ErrorType, $ofile) = @_;
152  my $Dir = "$HtmlDir/failures";
153  mkpath $Dir;
154
155  my $prefix = "clang_crash";
156  if ($ErrorType eq $ParserRejects) {
157    $prefix = "clang_parser_rejects";
158  }
159  elsif ($ErrorType eq $AttributeIgnored) {
160    $prefix = "clang_attribute_ignored";
161  }
162  elsif ($ErrorType eq $OtherError) {
163    $prefix = "clang_other_error";
164  }
165
166  # Generate the preprocessed file with Clang.
167  my ($PPH, $PPFile) = tempfile( $prefix . "_XXXXXX",
168                                 SUFFIX => GetPPExt($Lang),
169                                 DIR => $Dir);
170  close ($PPH);
171  system $Clang, @$Args, "-E", "-o", $PPFile;
172
173  # Create the info file.
174  open (OUT, ">", "$PPFile.info.txt") or die "Cannot open $PPFile.info.txt\n";
175  print OUT abs_path($file), "\n";
176  print OUT "$ErrorType\n";
177  print OUT "@$Args\n";
178  close OUT;
179  `uname -a >> $PPFile.info.txt 2>&1`;
180  `"$Compiler" -v >> $PPFile.info.txt 2>&1`;
181  rename($ofile, "$PPFile.stderr.txt");
182  return (basename $PPFile);
183}
184
185##----------------------------------------------------------------------------##
186#  Running the analyzer.
187##----------------------------------------------------------------------------##
188
189sub GetCCArgs {
190  my $HtmlDir = shift;
191  my $mode = shift;
192  my $Args = shift;
193  my $line;
194  my $OutputStream = silent_system($HtmlDir, $Clang, "-###", $mode, @$Args);
195  while (<$OutputStream>) {
196    next if (!/\s"?-cc1"?\s/);
197    $line = $_;
198  }
199  die "could not find clang line\n" if (!defined $line);
200  # Strip leading and trailing whitespace characters.
201  $line =~ s/^\s+|\s+$//g;
202  my @items = quotewords('\s+', 0, $line);
203  my $cmd = shift @items;
204  die "cannot find 'clang' in 'clang' command\n" if (!($cmd =~ /clang/ || basename($cmd) =~ /llvm/));
205  # If this is the llvm-driver the internal command will look like "llvm clang ...".
206  # Later this will be invoked like "clang clang ...", so skip over it.
207  if (basename($cmd) =~ /llvm/) {
208    die "Expected first arg to llvm driver to be 'clang'" if $items[0] ne "clang";
209    shift @items;
210  }
211  return \@items;
212}
213
214sub Analyze {
215  my ($Clang, $OriginalArgs, $AnalyzeArgs, $Lang, $Output, $Verbose, $HtmlDir,
216      $file) = @_;
217
218  my @Args = @$OriginalArgs;
219  my $Cmd;
220  my @CmdArgs;
221  my @CmdArgsSansAnalyses;
222
223  if ($Lang =~ /header/) {
224    exit 0 if (!defined ($Output));
225    $Cmd = 'cp';
226    push @CmdArgs, $file;
227    # Remove the PCH extension.
228    $Output =~ s/[.]gch$//;
229    push @CmdArgs, $Output;
230    @CmdArgsSansAnalyses = @CmdArgs;
231  }
232  else {
233    $Cmd = $Clang;
234
235    # Create arguments for doing regular parsing.
236    my $SyntaxArgs = GetCCArgs($HtmlDir, "-fsyntax-only", \@Args);
237    @CmdArgsSansAnalyses = @$SyntaxArgs;
238
239    # Create arguments for doing static analysis.
240    if (defined $ResultFile) {
241      push @Args, '-o', $ResultFile;
242    }
243    elsif (defined $HtmlDir) {
244      push @Args, '-o', $HtmlDir;
245    }
246    if ($Verbose) {
247      push @Args, "-Xclang", "-analyzer-display-progress";
248    }
249
250    foreach my $arg (@$AnalyzeArgs) {
251      push @Args, "-Xclang", $arg;
252    }
253
254    if (defined $AnalyzerTarget) {
255      push @Args, "-target", $AnalyzerTarget;
256    }
257
258    my $AnalysisArgs = GetCCArgs($HtmlDir, "--analyze", \@Args);
259    @CmdArgs = @$AnalysisArgs;
260  }
261
262  my @PrintArgs;
263  my $dir;
264
265  if ($Verbose) {
266    $dir = getcwd();
267    print STDERR "\n[LOCATION]: $dir\n";
268    push @PrintArgs,"'$Cmd'";
269    foreach my $arg (@CmdArgs) {
270        push @PrintArgs,"\'$arg\'";
271    }
272  }
273  if ($Verbose == 1) {
274    # We MUST print to stderr.  Some clients use the stdout output of
275    # gcc for various purposes.
276    print STDERR join(' ', @PrintArgs);
277    print STDERR "\n";
278  }
279  elsif ($Verbose == 2) {
280    print STDERR "#SHELL (cd '$dir' && @PrintArgs)\n";
281  }
282
283  # Save STDOUT and STDERR of clang to a temporary file and reroute
284  # all clang output to ccc-analyzer's STDERR.
285  # We save the output file in the 'crashes' directory if clang encounters
286  # any problems with the file.
287  my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);
288
289  my $OutputStream = silent_system($HtmlDir, $Cmd, @CmdArgs);
290  while ( <$OutputStream> ) {
291    print $ofh $_;
292    print STDERR $_;
293  }
294  my $Result = $?;
295  close $ofh;
296
297  # Did the command die because of a signal?
298  if ($ReportFailures) {
299    if ($Result & 127 and $Cmd eq $Clang and defined $HtmlDir) {
300      ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
301                          $HtmlDir, "Crash", $ofile);
302    }
303    elsif ($Result) {
304      if ($IncludeParserRejects && !($file =~/conftest/)) {
305        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
306                            $HtmlDir, $ParserRejects, $ofile);
307      } else {
308        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
309                            $HtmlDir, $OtherError, $ofile);
310      }
311    }
312    else {
313      # Check if there were any unhandled attributes.
314      if (open(CHILD, $ofile)) {
315        my %attributes_not_handled;
316
317        # Don't flag warnings about the following attributes that we
318        # know are currently not supported by Clang.
319        $attributes_not_handled{"cdecl"} = 1;
320
321        my $ppfile;
322        while (<CHILD>) {
323          next if (! /warning: '([^\']+)' attribute ignored/);
324
325          # Have we already spotted this unhandled attribute?
326          next if (defined $attributes_not_handled{$1});
327          $attributes_not_handled{$1} = 1;
328
329          # Get the name of the attribute file.
330          my $dir = "$HtmlDir/failures";
331          my $afile = "$dir/attribute_ignored_$1.txt";
332
333          # Only create another preprocessed file if the attribute file
334          # doesn't exist yet.
335          next if (-e $afile);
336
337          # Add this file to the list of files that contained this attribute.
338          # Generate a preprocessed file if we haven't already.
339          if (!(defined $ppfile)) {
340            $ppfile = ProcessClangFailure($Clang, $Lang, $file,
341                                          \@CmdArgsSansAnalyses,
342                                          $HtmlDir, $AttributeIgnored, $ofile);
343          }
344
345          mkpath $dir;
346          open(AFILE, ">$afile");
347          print AFILE "$ppfile\n";
348          close(AFILE);
349        }
350        close CHILD;
351      }
352    }
353  }
354
355  unlink($ofile);
356}
357
358##----------------------------------------------------------------------------##
359#  Lookup tables.
360##----------------------------------------------------------------------------##
361
362my %CompileOptionMap = (
363  '-nostdinc' => 0,
364  '-nostdlibinc' => 0,
365  '-include' => 1,
366  '-idirafter' => 1,
367  '-imacros' => 1,
368  '-iprefix' => 1,
369  '-iquote' => 1,
370  '-iwithprefix' => 1,
371  '-iwithprefixbefore' => 1
372);
373
374my %LinkerOptionMap = (
375  '-framework' => 1,
376  '-fobjc-link-runtime' => 0
377);
378
379my %CompilerLinkerOptionMap = (
380  '-Wwrite-strings' => 0,
381  '-ftrapv-handler' => 1, # specifically call out separated -f flag
382  '-mios-simulator-version-min' => 0, # This really has 1 argument, but always has '='
383  '-isysroot' => 1,
384  '-arch' => 1,
385  '-m32' => 0,
386  '-m64' => 0,
387  '-stdlib' => 0, # This is really a 1 argument, but always has '='
388  '--sysroot' => 1,
389  '-target' => 1,
390  '-v' => 0,
391  '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
392  '-miphoneos-version-min' => 0, # This is really a 1 argument, but always has '='
393  '--target' => 0
394);
395
396my %IgnoredOptionMap = (
397  '-MT' => 1,  # Ignore these preprocessor options.
398  '-MF' => 1,
399
400  '-fsyntax-only' => 0,
401  '-save-temps' => 0,
402  '-install_name' => 1,
403  '-exported_symbols_list' => 1,
404  '-current_version' => 1,
405  '-compatibility_version' => 1,
406  '-init' => 1,
407  '-e' => 1,
408  '-seg1addr' => 1,
409  '-bundle_loader' => 1,
410  '-multiply_defined' => 1,
411  '-sectorder' => 3,
412  '--param' => 1,
413  '-u' => 1,
414  '--serialize-diagnostics' => 1
415);
416
417my %LangMap = (
418  'c'   => $IsCXX ? 'c++' : 'c',
419  'cp'  => 'c++',
420  'cpp' => 'c++',
421  'cxx' => 'c++',
422  'txx' => 'c++',
423  'cc'  => 'c++',
424  'C'   => 'c++',
425  'ii'  => 'c++-cpp-output',
426  'i'   => $IsCXX ? 'c++-cpp-output' : 'cpp-output',
427  'm'   => 'objective-c',
428  'mi'  => 'objective-c-cpp-output',
429  'mm'  => 'objective-c++',
430  'mii' => 'objective-c++-cpp-output',
431);
432
433my %UniqueOptions = (
434  '-isysroot' => 0
435);
436
437##----------------------------------------------------------------------------##
438# Languages accepted.
439##----------------------------------------------------------------------------##
440
441my %LangsAccepted = (
442  "objective-c" => 1,
443  "c" => 1,
444  "c++" => 1,
445  "objective-c++" => 1,
446  "cpp-output" => 1,
447  "objective-c-cpp-output" => 1,
448  "c++-cpp-output" => 1
449);
450
451##----------------------------------------------------------------------------##
452#  Main Logic.
453##----------------------------------------------------------------------------##
454
455my $Action = 'link';
456my @CompileOpts;
457my @LinkOpts;
458my @Files;
459my $Lang;
460my $Output;
461my %Uniqued;
462
463# Forward arguments to gcc.
464my $Status = system($Compiler,@ARGV);
465if (defined $ENV{'CCC_ANALYZER_LOG'}) {
466  print STDERR "$Compiler @ARGV\n";
467}
468if ($Status) { exit($Status >> 8); }
469
470# Get the analysis options.
471my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};
472
473# Get the plugins to load.
474my $Plugins = $ENV{'CCC_ANALYZER_PLUGINS'};
475
476# Get the constraints engine.
477my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};
478
479#Get the internal stats setting.
480my $InternalStats = $ENV{'CCC_ANALYZER_INTERNAL_STATS'};
481
482# Get the output format.
483my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
484if (!defined $OutputFormat) { $OutputFormat = "html"; }
485
486# Get the config options.
487my $ConfigOptions = $ENV{'CCC_ANALYZER_CONFIG'};
488
489# Determine the level of verbosity.
490my $Verbose = 0;
491if (defined $ENV{'CCC_ANALYZER_VERBOSE'}) { $Verbose = 1; }
492if (defined $ENV{'CCC_ANALYZER_LOG'}) { $Verbose = 2; }
493
494# Get the HTML output directory.
495my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};
496
497# Get force-analyze-debug-code option.
498my $ForceAnalyzeDebugCode = $ENV{'CCC_ANALYZER_FORCE_ANALYZE_DEBUG_CODE'};
499
500my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
501my %ArchsSeen;
502my $HadArch = 0;
503my $HasSDK = 0;
504
505# Process the arguments.
506foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
507  my $Arg = $ARGV[$i];
508  my @ArgParts = split /=/,$Arg,2;
509  my $ArgKey = $ArgParts[0];
510
511  # Be friendly to "" in the argument list.
512  if (!defined($ArgKey)) {
513    next;
514  }
515
516  # Modes ccc-analyzer supports
517  if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; }
518  elsif ($Arg eq '-c') { $Action = 'compile'; }
519  elsif ($Arg =~ /^-print-prog-name/) { exit 0; }
520
521  # Specially handle duplicate cases of -arch
522  if ($Arg eq "-arch") {
523    my $arch = $ARGV[$i+1];
524    # We don't want to process 'ppc' because of Clang's lack of support
525    # for Altivec (also some #defines won't likely be defined correctly, etc.)
526    if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; }
527    $HadArch = 1;
528    ++$i;
529    next;
530  }
531
532  # On OSX/iOS, record if an SDK path was specified.  This
533  # is innocuous for other platforms, so the check just happens.
534  if ($Arg =~ /^-isysroot/) {
535    $HasSDK = 1;
536  }
537
538  # Options with possible arguments that should pass through to compiler.
539  if (defined $CompileOptionMap{$ArgKey}) {
540    my $Cnt = $CompileOptionMap{$ArgKey};
541    push @CompileOpts,$Arg;
542    while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
543    next;
544  }
545  # Handle the case where there isn't a space after -iquote
546  if ($Arg =~ /^-iquote.*/) {
547    push @CompileOpts,$Arg;
548    next;
549  }
550
551  # Options with possible arguments that should pass through to linker.
552  if (defined $LinkerOptionMap{$ArgKey}) {
553    my $Cnt = $LinkerOptionMap{$ArgKey};
554    push @LinkOpts,$Arg;
555    while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
556    next;
557  }
558
559  # Options with possible arguments that should pass through to both compiler
560  # and the linker.
561  if (defined $CompilerLinkerOptionMap{$ArgKey}) {
562    my $Cnt = $CompilerLinkerOptionMap{$ArgKey};
563
564    # Check if this is an option that should have a unique value, and if so
565    # determine if the value was checked before.
566    if ($UniqueOptions{$Arg}) {
567      if (defined $Uniqued{$Arg}) {
568        $i += $Cnt;
569        next;
570      }
571      $Uniqued{$Arg} = 1;
572    }
573
574    push @CompileOpts,$Arg;
575    push @LinkOpts,$Arg;
576
577    if (scalar @ArgParts == 1) {
578      while ($Cnt > 0) {
579        ++$i; --$Cnt;
580        push @CompileOpts, $ARGV[$i];
581        push @LinkOpts, $ARGV[$i];
582      }
583    }
584    next;
585  }
586
587  # Ignored options.
588  if (defined $IgnoredOptionMap{$ArgKey}) {
589    my $Cnt = $IgnoredOptionMap{$ArgKey};
590    while ($Cnt > 0) {
591      ++$i; --$Cnt;
592    }
593    next;
594  }
595
596  # Compile mode flags.
597  if ($Arg =~ /^-(?:[DIU]|isystem)(.*)$/) {
598    my $Tmp = $Arg;
599    if ($1 eq '') {
600      # FIXME: Check if we are going off the end.
601      ++$i;
602      $Tmp = $Arg . $ARGV[$i];
603    }
604    push @CompileOpts,$Tmp;
605    next;
606  }
607
608  if ($Arg =~ /^-m.*/) {
609    push @CompileOpts,$Arg;
610    next;
611  }
612
613  # Language.
614  if ($Arg eq '-x') {
615    $Lang = $ARGV[$i+1];
616    ++$i; next;
617  }
618
619  # Output file.
620  if ($Arg eq '-o') {
621    ++$i;
622    $Output = $ARGV[$i];
623    next;
624  }
625
626  # Get the link mode.
627  if ($Arg =~ /^-[l,L,O]/) {
628    if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
629    elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
630    else { push @LinkOpts,$Arg; }
631
632    # Must pass this along for the __OPTIMIZE__ macro
633    if ($Arg =~ /^-O/) { push @CompileOpts,$Arg; }
634    next;
635  }
636
637  if ($Arg =~ /^-std=/) {
638    push @CompileOpts,$Arg;
639    next;
640  }
641
642  # Get the compiler/link mode.
643  if ($Arg =~ /^-F(.+)$/) {
644    my $Tmp = $Arg;
645    if ($1 eq '') {
646      # FIXME: Check if we are going off the end.
647      ++$i;
648      $Tmp = $Arg . $ARGV[$i];
649    }
650    push @CompileOpts,$Tmp;
651    push @LinkOpts,$Tmp;
652    next;
653  }
654
655  # Input files.
656  if ($Arg eq '-filelist') {
657    # FIXME: Make sure we aren't walking off the end.
658    open(IN, $ARGV[$i+1]);
659    while (<IN>) { s/\015?\012//; push @Files,$_; }
660    close(IN);
661    ++$i;
662    next;
663  }
664
665  if ($Arg =~ /^-f/) {
666    push @CompileOpts,$Arg;
667    push @LinkOpts,$Arg;
668    next;
669  }
670
671  # Handle -Wno-.  We don't care about extra warnings, but
672  # we should suppress ones that we don't want to see.
673  if ($Arg =~ /^-Wno-/) {
674    push @CompileOpts, $Arg;
675    next;
676  }
677
678  # Handle -Xclang some-arg. Add both arguments to the compiler options.
679  if ($Arg =~ /^-Xclang$/) {
680    # FIXME: Check if we are going off the end.
681    ++$i;
682    push @CompileOpts, $Arg;
683    push @CompileOpts, $ARGV[$i];
684    next;
685  }
686
687  if (!($Arg =~ /^-/)) {
688    push @Files, $Arg;
689    next;
690  }
691}
692
693# Forcedly enable debugging if requested by user.
694if ($ForceAnalyzeDebugCode) {
695  push @CompileOpts, '-UNDEBUG';
696}
697
698# If we are on OSX and have an installation where the
699# default SDK is inferred by xcrun use xcrun to infer
700# the SDK.
701if (not $HasSDK and $UseXCRUN) {
702  my $sdk = `/usr/bin/xcrun --show-sdk-path -sdk macosx`;
703  chomp $sdk;
704  push @CompileOpts, "-isysroot", $sdk;
705}
706
707if ($Action eq 'compile' or $Action eq 'link') {
708  my @Archs = keys %ArchsSeen;
709  # Skip the file if we don't support the architectures specified.
710  exit 0 if ($HadArch && scalar(@Archs) == 0);
711
712  foreach my $file (@Files) {
713    # Determine the language for the file.
714    my $FileLang = $Lang;
715
716    if (!defined($FileLang)) {
717      # Infer the language from the extension.
718      if ($file =~ /[.]([^.]+)$/) {
719        $FileLang = $LangMap{$1};
720      }
721    }
722
723    # FileLang still not defined?  Skip the file.
724    next if (!defined $FileLang);
725
726    # Language not accepted?
727    next if (!defined $LangsAccepted{$FileLang});
728
729    my @CmdArgs;
730    my @AnalyzeArgs;
731
732    if ($FileLang ne 'unknown') {
733      push @CmdArgs, '-x', $FileLang;
734    }
735
736    if (defined $ConstraintsModel) {
737      push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel";
738    }
739
740    if (defined $InternalStats) {
741      push @AnalyzeArgs, "-analyzer-stats";
742    }
743
744    if (defined $Analyses) {
745      push @AnalyzeArgs, split '\s+', $Analyses;
746    }
747
748    if (defined $Plugins) {
749      push @AnalyzeArgs, split '\s+', $Plugins;
750    }
751
752    if (defined $OutputFormat) {
753      push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat;
754      if ($OutputFormat =~ /plist/ || $OutputFormat =~ /sarif/) {
755        # Change "Output" to be a file.
756        my $Suffix = $OutputFormat =~ /plist/ ? ".plist" : ".sarif";
757        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => $Suffix,
758                               DIR => $HtmlDir);
759        $ResultFile = $f;
760        # If the HtmlDir is not set, we should clean up the plist files.
761        if (!defined $HtmlDir || $HtmlDir eq "") {
762          $CleanupFile = $f;
763        }
764      }
765    }
766    if (defined $ConfigOptions) {
767      push @AnalyzeArgs, split '\s+', $ConfigOptions;
768    }
769
770    push @CmdArgs, @CompileOpts;
771    push @CmdArgs, $file;
772
773    if (scalar @Archs) {
774      foreach my $arch (@Archs) {
775        my @NewArgs;
776        push @NewArgs, '-arch', $arch;
777        push @NewArgs, @CmdArgs;
778        Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output,
779                $Verbose, $HtmlDir, $file);
780      }
781    }
782    else {
783      Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output,
784              $Verbose, $HtmlDir, $file);
785    }
786  }
787}
788