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  '-include' => 1,
365  '-idirafter' => 1,
366  '-imacros' => 1,
367  '-iprefix' => 1,
368  '-iquote' => 1,
369  '-iwithprefix' => 1,
370  '-iwithprefixbefore' => 1
371);
372
373my %LinkerOptionMap = (
374  '-framework' => 1,
375  '-fobjc-link-runtime' => 0
376);
377
378my %CompilerLinkerOptionMap = (
379  '-Wwrite-strings' => 0,
380  '-ftrapv-handler' => 1, # specifically call out separated -f flag
381  '-mios-simulator-version-min' => 0, # This really has 1 argument, but always has '='
382  '-isysroot' => 1,
383  '-arch' => 1,
384  '-m32' => 0,
385  '-m64' => 0,
386  '-stdlib' => 0, # This is really a 1 argument, but always has '='
387  '--sysroot' => 1,
388  '-target' => 1,
389  '-v' => 0,
390  '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
391  '-miphoneos-version-min' => 0, # This is really a 1 argument, but always has '='
392  '--target' => 0
393);
394
395my %IgnoredOptionMap = (
396  '-MT' => 1,  # Ignore these preprocessor options.
397  '-MF' => 1,
398
399  '-fsyntax-only' => 0,
400  '-save-temps' => 0,
401  '-install_name' => 1,
402  '-exported_symbols_list' => 1,
403  '-current_version' => 1,
404  '-compatibility_version' => 1,
405  '-init' => 1,
406  '-e' => 1,
407  '-seg1addr' => 1,
408  '-bundle_loader' => 1,
409  '-multiply_defined' => 1,
410  '-sectorder' => 3,
411  '--param' => 1,
412  '-u' => 1,
413  '--serialize-diagnostics' => 1
414);
415
416my %LangMap = (
417  'c'   => $IsCXX ? 'c++' : 'c',
418  'cp'  => 'c++',
419  'cpp' => 'c++',
420  'cxx' => 'c++',
421  'txx' => 'c++',
422  'cc'  => 'c++',
423  'C'   => 'c++',
424  'ii'  => 'c++-cpp-output',
425  'i'   => $IsCXX ? 'c++-cpp-output' : 'cpp-output',
426  'm'   => 'objective-c',
427  'mi'  => 'objective-c-cpp-output',
428  'mm'  => 'objective-c++',
429  'mii' => 'objective-c++-cpp-output',
430);
431
432my %UniqueOptions = (
433  '-isysroot' => 0
434);
435
436##----------------------------------------------------------------------------##
437# Languages accepted.
438##----------------------------------------------------------------------------##
439
440my %LangsAccepted = (
441  "objective-c" => 1,
442  "c" => 1,
443  "c++" => 1,
444  "objective-c++" => 1,
445  "cpp-output" => 1,
446  "objective-c-cpp-output" => 1,
447  "c++-cpp-output" => 1
448);
449
450##----------------------------------------------------------------------------##
451#  Main Logic.
452##----------------------------------------------------------------------------##
453
454my $Action = 'link';
455my @CompileOpts;
456my @LinkOpts;
457my @Files;
458my $Lang;
459my $Output;
460my %Uniqued;
461
462# Forward arguments to gcc.
463my $Status = system($Compiler,@ARGV);
464if (defined $ENV{'CCC_ANALYZER_LOG'}) {
465  print STDERR "$Compiler @ARGV\n";
466}
467if ($Status) { exit($Status >> 8); }
468
469# Get the analysis options.
470my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};
471
472# Get the plugins to load.
473my $Plugins = $ENV{'CCC_ANALYZER_PLUGINS'};
474
475# Get the constraints engine.
476my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};
477
478#Get the internal stats setting.
479my $InternalStats = $ENV{'CCC_ANALYZER_INTERNAL_STATS'};
480
481# Get the output format.
482my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
483if (!defined $OutputFormat) { $OutputFormat = "html"; }
484
485# Get the config options.
486my $ConfigOptions = $ENV{'CCC_ANALYZER_CONFIG'};
487
488# Determine the level of verbosity.
489my $Verbose = 0;
490if (defined $ENV{'CCC_ANALYZER_VERBOSE'}) { $Verbose = 1; }
491if (defined $ENV{'CCC_ANALYZER_LOG'}) { $Verbose = 2; }
492
493# Get the HTML output directory.
494my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};
495
496# Get force-analyze-debug-code option.
497my $ForceAnalyzeDebugCode = $ENV{'CCC_ANALYZER_FORCE_ANALYZE_DEBUG_CODE'};
498
499my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
500my %ArchsSeen;
501my $HadArch = 0;
502my $HasSDK = 0;
503
504# Process the arguments.
505foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
506  my $Arg = $ARGV[$i];
507  my @ArgParts = split /=/,$Arg,2;
508  my $ArgKey = $ArgParts[0];
509
510  # Be friendly to "" in the argument list.
511  if (!defined($ArgKey)) {
512    next;
513  }
514
515  # Modes ccc-analyzer supports
516  if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; }
517  elsif ($Arg eq '-c') { $Action = 'compile'; }
518  elsif ($Arg =~ /^-print-prog-name/) { exit 0; }
519
520  # Specially handle duplicate cases of -arch
521  if ($Arg eq "-arch") {
522    my $arch = $ARGV[$i+1];
523    # We don't want to process 'ppc' because of Clang's lack of support
524    # for Altivec (also some #defines won't likely be defined correctly, etc.)
525    if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; }
526    $HadArch = 1;
527    ++$i;
528    next;
529  }
530
531  # On OSX/iOS, record if an SDK path was specified.  This
532  # is innocuous for other platforms, so the check just happens.
533  if ($Arg =~ /^-isysroot/) {
534    $HasSDK = 1;
535  }
536
537  # Options with possible arguments that should pass through to compiler.
538  if (defined $CompileOptionMap{$ArgKey}) {
539    my $Cnt = $CompileOptionMap{$ArgKey};
540    push @CompileOpts,$Arg;
541    while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
542    next;
543  }
544  # Handle the case where there isn't a space after -iquote
545  if ($Arg =~ /^-iquote.*/) {
546    push @CompileOpts,$Arg;
547    next;
548  }
549
550  # Options with possible arguments that should pass through to linker.
551  if (defined $LinkerOptionMap{$ArgKey}) {
552    my $Cnt = $LinkerOptionMap{$ArgKey};
553    push @LinkOpts,$Arg;
554    while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
555    next;
556  }
557
558  # Options with possible arguments that should pass through to both compiler
559  # and the linker.
560  if (defined $CompilerLinkerOptionMap{$ArgKey}) {
561    my $Cnt = $CompilerLinkerOptionMap{$ArgKey};
562
563    # Check if this is an option that should have a unique value, and if so
564    # determine if the value was checked before.
565    if ($UniqueOptions{$Arg}) {
566      if (defined $Uniqued{$Arg}) {
567        $i += $Cnt;
568        next;
569      }
570      $Uniqued{$Arg} = 1;
571    }
572
573    push @CompileOpts,$Arg;
574    push @LinkOpts,$Arg;
575
576    if (scalar @ArgParts == 1) {
577      while ($Cnt > 0) {
578        ++$i; --$Cnt;
579        push @CompileOpts, $ARGV[$i];
580        push @LinkOpts, $ARGV[$i];
581      }
582    }
583    next;
584  }
585
586  # Ignored options.
587  if (defined $IgnoredOptionMap{$ArgKey}) {
588    my $Cnt = $IgnoredOptionMap{$ArgKey};
589    while ($Cnt > 0) {
590      ++$i; --$Cnt;
591    }
592    next;
593  }
594
595  # Compile mode flags.
596  if ($Arg =~ /^-(?:[DIU]|isystem)(.*)$/) {
597    my $Tmp = $Arg;
598    if ($1 eq '') {
599      # FIXME: Check if we are going off the end.
600      ++$i;
601      $Tmp = $Arg . $ARGV[$i];
602    }
603    push @CompileOpts,$Tmp;
604    next;
605  }
606
607  if ($Arg =~ /^-m.*/) {
608    push @CompileOpts,$Arg;
609    next;
610  }
611
612  # Language.
613  if ($Arg eq '-x') {
614    $Lang = $ARGV[$i+1];
615    ++$i; next;
616  }
617
618  # Output file.
619  if ($Arg eq '-o') {
620    ++$i;
621    $Output = $ARGV[$i];
622    next;
623  }
624
625  # Get the link mode.
626  if ($Arg =~ /^-[l,L,O]/) {
627    if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
628    elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
629    else { push @LinkOpts,$Arg; }
630
631    # Must pass this along for the __OPTIMIZE__ macro
632    if ($Arg =~ /^-O/) { push @CompileOpts,$Arg; }
633    next;
634  }
635
636  if ($Arg =~ /^-std=/) {
637    push @CompileOpts,$Arg;
638    next;
639  }
640
641  # Get the compiler/link mode.
642  if ($Arg =~ /^-F(.+)$/) {
643    my $Tmp = $Arg;
644    if ($1 eq '') {
645      # FIXME: Check if we are going off the end.
646      ++$i;
647      $Tmp = $Arg . $ARGV[$i];
648    }
649    push @CompileOpts,$Tmp;
650    push @LinkOpts,$Tmp;
651    next;
652  }
653
654  # Input files.
655  if ($Arg eq '-filelist') {
656    # FIXME: Make sure we aren't walking off the end.
657    open(IN, $ARGV[$i+1]);
658    while (<IN>) { s/\015?\012//; push @Files,$_; }
659    close(IN);
660    ++$i;
661    next;
662  }
663
664  if ($Arg =~ /^-f/) {
665    push @CompileOpts,$Arg;
666    push @LinkOpts,$Arg;
667    next;
668  }
669
670  # Handle -Wno-.  We don't care about extra warnings, but
671  # we should suppress ones that we don't want to see.
672  if ($Arg =~ /^-Wno-/) {
673    push @CompileOpts, $Arg;
674    next;
675  }
676
677  # Handle -Xclang some-arg. Add both arguments to the compiler options.
678  if ($Arg =~ /^-Xclang$/) {
679    # FIXME: Check if we are going off the end.
680    ++$i;
681    push @CompileOpts, $Arg;
682    push @CompileOpts, $ARGV[$i];
683    next;
684  }
685
686  if (!($Arg =~ /^-/)) {
687    push @Files, $Arg;
688    next;
689  }
690}
691
692# Forcedly enable debugging if requested by user.
693if ($ForceAnalyzeDebugCode) {
694  push @CompileOpts, '-UNDEBUG';
695}
696
697# If we are on OSX and have an installation where the
698# default SDK is inferred by xcrun use xcrun to infer
699# the SDK.
700if (not $HasSDK and $UseXCRUN) {
701  my $sdk = `/usr/bin/xcrun --show-sdk-path -sdk macosx`;
702  chomp $sdk;
703  push @CompileOpts, "-isysroot", $sdk;
704}
705
706if ($Action eq 'compile' or $Action eq 'link') {
707  my @Archs = keys %ArchsSeen;
708  # Skip the file if we don't support the architectures specified.
709  exit 0 if ($HadArch && scalar(@Archs) == 0);
710
711  foreach my $file (@Files) {
712    # Determine the language for the file.
713    my $FileLang = $Lang;
714
715    if (!defined($FileLang)) {
716      # Infer the language from the extension.
717      if ($file =~ /[.]([^.]+)$/) {
718        $FileLang = $LangMap{$1};
719      }
720    }
721
722    # FileLang still not defined?  Skip the file.
723    next if (!defined $FileLang);
724
725    # Language not accepted?
726    next if (!defined $LangsAccepted{$FileLang});
727
728    my @CmdArgs;
729    my @AnalyzeArgs;
730
731    if ($FileLang ne 'unknown') {
732      push @CmdArgs, '-x', $FileLang;
733    }
734
735    if (defined $ConstraintsModel) {
736      push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel";
737    }
738
739    if (defined $InternalStats) {
740      push @AnalyzeArgs, "-analyzer-stats";
741    }
742
743    if (defined $Analyses) {
744      push @AnalyzeArgs, split '\s+', $Analyses;
745    }
746
747    if (defined $Plugins) {
748      push @AnalyzeArgs, split '\s+', $Plugins;
749    }
750
751    if (defined $OutputFormat) {
752      push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat;
753      if ($OutputFormat =~ /plist/ || $OutputFormat =~ /sarif/) {
754        # Change "Output" to be a file.
755        my $Suffix = $OutputFormat =~ /plist/ ? ".plist" : ".sarif";
756        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => $Suffix,
757                               DIR => $HtmlDir);
758        $ResultFile = $f;
759        # If the HtmlDir is not set, we should clean up the plist files.
760        if (!defined $HtmlDir || $HtmlDir eq "") {
761          $CleanupFile = $f;
762        }
763      }
764    }
765    if (defined $ConfigOptions) {
766      push @AnalyzeArgs, split '\s+', $ConfigOptions;
767    }
768
769    push @CmdArgs, @CompileOpts;
770    push @CmdArgs, $file;
771
772    if (scalar @Archs) {
773      foreach my $arch (@Archs) {
774        my @NewArgs;
775        push @NewArgs, '-arch', $arch;
776        push @NewArgs, @CmdArgs;
777        Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output,
778                $Verbose, $HtmlDir, $file);
779      }
780    }
781    else {
782      Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output,
783              $Verbose, $HtmlDir, $file);
784    }
785  }
786}
787