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 -a` =~ 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 -a` =~ 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/));
205  return \@items;
206}
207
208sub Analyze {
209  my ($Clang, $OriginalArgs, $AnalyzeArgs, $Lang, $Output, $Verbose, $HtmlDir,
210      $file) = @_;
211
212  my @Args = @$OriginalArgs;
213  my $Cmd;
214  my @CmdArgs;
215  my @CmdArgsSansAnalyses;
216
217  if ($Lang =~ /header/) {
218    exit 0 if (!defined ($Output));
219    $Cmd = 'cp';
220    push @CmdArgs, $file;
221    # Remove the PCH extension.
222    $Output =~ s/[.]gch$//;
223    push @CmdArgs, $Output;
224    @CmdArgsSansAnalyses = @CmdArgs;
225  }
226  else {
227    $Cmd = $Clang;
228
229    # Create arguments for doing regular parsing.
230    my $SyntaxArgs = GetCCArgs($HtmlDir, "-fsyntax-only", \@Args);
231    @CmdArgsSansAnalyses = @$SyntaxArgs;
232
233    # Create arguments for doing static analysis.
234    if (defined $ResultFile) {
235      push @Args, '-o', $ResultFile;
236    }
237    elsif (defined $HtmlDir) {
238      push @Args, '-o', $HtmlDir;
239    }
240    if ($Verbose) {
241      push @Args, "-Xclang", "-analyzer-display-progress";
242    }
243
244    foreach my $arg (@$AnalyzeArgs) {
245      push @Args, "-Xclang", $arg;
246    }
247
248    if (defined $AnalyzerTarget) {
249      push @Args, "-target", $AnalyzerTarget;
250    }
251
252    my $AnalysisArgs = GetCCArgs($HtmlDir, "--analyze", \@Args);
253    @CmdArgs = @$AnalysisArgs;
254  }
255
256  my @PrintArgs;
257  my $dir;
258
259  if ($Verbose) {
260    $dir = getcwd();
261    print STDERR "\n[LOCATION]: $dir\n";
262    push @PrintArgs,"'$Cmd'";
263    foreach my $arg (@CmdArgs) {
264        push @PrintArgs,"\'$arg\'";
265    }
266  }
267  if ($Verbose == 1) {
268    # We MUST print to stderr.  Some clients use the stdout output of
269    # gcc for various purposes.
270    print STDERR join(' ', @PrintArgs);
271    print STDERR "\n";
272  }
273  elsif ($Verbose == 2) {
274    print STDERR "#SHELL (cd '$dir' && @PrintArgs)\n";
275  }
276
277  # Save STDOUT and STDERR of clang to a temporary file and reroute
278  # all clang output to ccc-analyzer's STDERR.
279  # We save the output file in the 'crashes' directory if clang encounters
280  # any problems with the file.
281  my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);
282
283  my $OutputStream = silent_system($HtmlDir, $Cmd, @CmdArgs);
284  while ( <$OutputStream> ) {
285    print $ofh $_;
286    print STDERR $_;
287  }
288  my $Result = $?;
289  close $ofh;
290
291  # Did the command die because of a signal?
292  if ($ReportFailures) {
293    if ($Result & 127 and $Cmd eq $Clang and defined $HtmlDir) {
294      ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
295                          $HtmlDir, "Crash", $ofile);
296    }
297    elsif ($Result) {
298      if ($IncludeParserRejects && !($file =~/conftest/)) {
299        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
300                            $HtmlDir, $ParserRejects, $ofile);
301      } else {
302        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
303                            $HtmlDir, $OtherError, $ofile);
304      }
305    }
306    else {
307      # Check if there were any unhandled attributes.
308      if (open(CHILD, $ofile)) {
309        my %attributes_not_handled;
310
311        # Don't flag warnings about the following attributes that we
312        # know are currently not supported by Clang.
313        $attributes_not_handled{"cdecl"} = 1;
314
315        my $ppfile;
316        while (<CHILD>) {
317          next if (! /warning: '([^\']+)' attribute ignored/);
318
319          # Have we already spotted this unhandled attribute?
320          next if (defined $attributes_not_handled{$1});
321          $attributes_not_handled{$1} = 1;
322
323          # Get the name of the attribute file.
324          my $dir = "$HtmlDir/failures";
325          my $afile = "$dir/attribute_ignored_$1.txt";
326
327          # Only create another preprocessed file if the attribute file
328          # doesn't exist yet.
329          next if (-e $afile);
330
331          # Add this file to the list of files that contained this attribute.
332          # Generate a preprocessed file if we haven't already.
333          if (!(defined $ppfile)) {
334            $ppfile = ProcessClangFailure($Clang, $Lang, $file,
335                                          \@CmdArgsSansAnalyses,
336                                          $HtmlDir, $AttributeIgnored, $ofile);
337          }
338
339          mkpath $dir;
340          open(AFILE, ">$afile");
341          print AFILE "$ppfile\n";
342          close(AFILE);
343        }
344        close CHILD;
345      }
346    }
347  }
348
349  unlink($ofile);
350}
351
352##----------------------------------------------------------------------------##
353#  Lookup tables.
354##----------------------------------------------------------------------------##
355
356my %CompileOptionMap = (
357  '-nostdinc' => 0,
358  '-include' => 1,
359  '-idirafter' => 1,
360  '-imacros' => 1,
361  '-iprefix' => 1,
362  '-iquote' => 1,
363  '-iwithprefix' => 1,
364  '-iwithprefixbefore' => 1
365);
366
367my %LinkerOptionMap = (
368  '-framework' => 1,
369  '-fobjc-link-runtime' => 0
370);
371
372my %CompilerLinkerOptionMap = (
373  '-Wwrite-strings' => 0,
374  '-ftrapv-handler' => 1, # specifically call out separated -f flag
375  '-mios-simulator-version-min' => 0, # This really has 1 argument, but always has '='
376  '-isysroot' => 1,
377  '-arch' => 1,
378  '-m32' => 0,
379  '-m64' => 0,
380  '-stdlib' => 0, # This is really a 1 argument, but always has '='
381  '--sysroot' => 1,
382  '-target' => 1,
383  '-v' => 0,
384  '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
385  '-miphoneos-version-min' => 0, # This is really a 1 argument, but always has '='
386  '--target' => 0
387);
388
389my %IgnoredOptionMap = (
390  '-MT' => 1,  # Ignore these preprocessor options.
391  '-MF' => 1,
392
393  '-fsyntax-only' => 0,
394  '-save-temps' => 0,
395  '-install_name' => 1,
396  '-exported_symbols_list' => 1,
397  '-current_version' => 1,
398  '-compatibility_version' => 1,
399  '-init' => 1,
400  '-e' => 1,
401  '-seg1addr' => 1,
402  '-bundle_loader' => 1,
403  '-multiply_defined' => 1,
404  '-sectorder' => 3,
405  '--param' => 1,
406  '-u' => 1,
407  '--serialize-diagnostics' => 1
408);
409
410my %LangMap = (
411  'c'   => $IsCXX ? 'c++' : 'c',
412  'cp'  => 'c++',
413  'cpp' => 'c++',
414  'cxx' => 'c++',
415  'txx' => 'c++',
416  'cc'  => 'c++',
417  'C'   => 'c++',
418  'ii'  => 'c++-cpp-output',
419  'i'   => $IsCXX ? 'c++-cpp-output' : 'cpp-output',
420  'm'   => 'objective-c',
421  'mi'  => 'objective-c-cpp-output',
422  'mm'  => 'objective-c++',
423  'mii' => 'objective-c++-cpp-output',
424);
425
426my %UniqueOptions = (
427  '-isysroot' => 0
428);
429
430##----------------------------------------------------------------------------##
431# Languages accepted.
432##----------------------------------------------------------------------------##
433
434my %LangsAccepted = (
435  "objective-c" => 1,
436  "c" => 1,
437  "c++" => 1,
438  "objective-c++" => 1,
439  "cpp-output" => 1,
440  "objective-c-cpp-output" => 1,
441  "c++-cpp-output" => 1
442);
443
444##----------------------------------------------------------------------------##
445#  Main Logic.
446##----------------------------------------------------------------------------##
447
448my $Action = 'link';
449my @CompileOpts;
450my @LinkOpts;
451my @Files;
452my $Lang;
453my $Output;
454my %Uniqued;
455
456# Forward arguments to gcc.
457my $Status = system($Compiler,@ARGV);
458if (defined $ENV{'CCC_ANALYZER_LOG'}) {
459  print STDERR "$Compiler @ARGV\n";
460}
461if ($Status) { exit($Status >> 8); }
462
463# Get the analysis options.
464my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};
465
466# Get the plugins to load.
467my $Plugins = $ENV{'CCC_ANALYZER_PLUGINS'};
468
469# Get the store model.
470my $StoreModel = $ENV{'CCC_ANALYZER_STORE_MODEL'};
471
472# Get the constraints engine.
473my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};
474
475#Get the internal stats setting.
476my $InternalStats = $ENV{'CCC_ANALYZER_INTERNAL_STATS'};
477
478# Get the output format.
479my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
480if (!defined $OutputFormat) { $OutputFormat = "html"; }
481
482# Get the config options.
483my $ConfigOptions = $ENV{'CCC_ANALYZER_CONFIG'};
484
485# Determine the level of verbosity.
486my $Verbose = 0;
487if (defined $ENV{'CCC_ANALYZER_VERBOSE'}) { $Verbose = 1; }
488if (defined $ENV{'CCC_ANALYZER_LOG'}) { $Verbose = 2; }
489
490# Get the HTML output directory.
491my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};
492
493# Get force-analyze-debug-code option.
494my $ForceAnalyzeDebugCode = $ENV{'CCC_ANALYZER_FORCE_ANALYZE_DEBUG_CODE'};
495
496my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
497my %ArchsSeen;
498my $HadArch = 0;
499my $HasSDK = 0;
500
501# Process the arguments.
502foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
503  my $Arg = $ARGV[$i];
504  my @ArgParts = split /=/,$Arg,2;
505  my $ArgKey = $ArgParts[0];
506
507  # Be friendly to "" in the argument list.
508  if (!defined($ArgKey)) {
509    next;
510  }
511
512  # Modes ccc-analyzer supports
513  if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; }
514  elsif ($Arg eq '-c') { $Action = 'compile'; }
515  elsif ($Arg =~ /^-print-prog-name/) { exit 0; }
516
517  # Specially handle duplicate cases of -arch
518  if ($Arg eq "-arch") {
519    my $arch = $ARGV[$i+1];
520    # We don't want to process 'ppc' because of Clang's lack of support
521    # for Altivec (also some #defines won't likely be defined correctly, etc.)
522    if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; }
523    $HadArch = 1;
524    ++$i;
525    next;
526  }
527
528  # On OSX/iOS, record if an SDK path was specified.  This
529  # is innocuous for other platforms, so the check just happens.
530  if ($Arg =~ /^-isysroot/) {
531    $HasSDK = 1;
532  }
533
534  # Options with possible arguments that should pass through to compiler.
535  if (defined $CompileOptionMap{$ArgKey}) {
536    my $Cnt = $CompileOptionMap{$ArgKey};
537    push @CompileOpts,$Arg;
538    while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
539    next;
540  }
541  # Handle the case where there isn't a space after -iquote
542  if ($Arg =~ /^-iquote.*/) {
543    push @CompileOpts,$Arg;
544    next;
545  }
546
547  # Options with possible arguments that should pass through to linker.
548  if (defined $LinkerOptionMap{$ArgKey}) {
549    my $Cnt = $LinkerOptionMap{$ArgKey};
550    push @LinkOpts,$Arg;
551    while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
552    next;
553  }
554
555  # Options with possible arguments that should pass through to both compiler
556  # and the linker.
557  if (defined $CompilerLinkerOptionMap{$ArgKey}) {
558    my $Cnt = $CompilerLinkerOptionMap{$ArgKey};
559
560    # Check if this is an option that should have a unique value, and if so
561    # determine if the value was checked before.
562    if ($UniqueOptions{$Arg}) {
563      if (defined $Uniqued{$Arg}) {
564        $i += $Cnt;
565        next;
566      }
567      $Uniqued{$Arg} = 1;
568    }
569
570    push @CompileOpts,$Arg;
571    push @LinkOpts,$Arg;
572
573    if (scalar @ArgParts == 1) {
574      while ($Cnt > 0) {
575        ++$i; --$Cnt;
576        push @CompileOpts, $ARGV[$i];
577        push @LinkOpts, $ARGV[$i];
578      }
579    }
580    next;
581  }
582
583  # Ignored options.
584  if (defined $IgnoredOptionMap{$ArgKey}) {
585    my $Cnt = $IgnoredOptionMap{$ArgKey};
586    while ($Cnt > 0) {
587      ++$i; --$Cnt;
588    }
589    next;
590  }
591
592  # Compile mode flags.
593  if ($Arg =~ /^-(?:[DIU]|isystem)(.*)$/) {
594    my $Tmp = $Arg;
595    if ($1 eq '') {
596      # FIXME: Check if we are going off the end.
597      ++$i;
598      $Tmp = $Arg . $ARGV[$i];
599    }
600    push @CompileOpts,$Tmp;
601    next;
602  }
603
604  if ($Arg =~ /^-m.*/) {
605    push @CompileOpts,$Arg;
606    next;
607  }
608
609  # Language.
610  if ($Arg eq '-x') {
611    $Lang = $ARGV[$i+1];
612    ++$i; next;
613  }
614
615  # Output file.
616  if ($Arg eq '-o') {
617    ++$i;
618    $Output = $ARGV[$i];
619    next;
620  }
621
622  # Get the link mode.
623  if ($Arg =~ /^-[l,L,O]/) {
624    if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
625    elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
626    else { push @LinkOpts,$Arg; }
627
628    # Must pass this along for the __OPTIMIZE__ macro
629    if ($Arg =~ /^-O/) { push @CompileOpts,$Arg; }
630    next;
631  }
632
633  if ($Arg =~ /^-std=/) {
634    push @CompileOpts,$Arg;
635    next;
636  }
637
638  # Get the compiler/link mode.
639  if ($Arg =~ /^-F(.+)$/) {
640    my $Tmp = $Arg;
641    if ($1 eq '') {
642      # FIXME: Check if we are going off the end.
643      ++$i;
644      $Tmp = $Arg . $ARGV[$i];
645    }
646    push @CompileOpts,$Tmp;
647    push @LinkOpts,$Tmp;
648    next;
649  }
650
651  # Input files.
652  if ($Arg eq '-filelist') {
653    # FIXME: Make sure we aren't walking off the end.
654    open(IN, $ARGV[$i+1]);
655    while (<IN>) { s/\015?\012//; push @Files,$_; }
656    close(IN);
657    ++$i;
658    next;
659  }
660
661  if ($Arg =~ /^-f/) {
662    push @CompileOpts,$Arg;
663    push @LinkOpts,$Arg;
664    next;
665  }
666
667  # Handle -Wno-.  We don't care about extra warnings, but
668  # we should suppress ones that we don't want to see.
669  if ($Arg =~ /^-Wno-/) {
670    push @CompileOpts, $Arg;
671    next;
672  }
673
674  # Handle -Xclang some-arg. Add both arguments to the compiler options.
675  if ($Arg =~ /^-Xclang$/) {
676    # FIXME: Check if we are going off the end.
677    ++$i;
678    push @CompileOpts, $Arg;
679    push @CompileOpts, $ARGV[$i];
680    next;
681  }
682
683  if (!($Arg =~ /^-/)) {
684    push @Files, $Arg;
685    next;
686  }
687}
688
689# Forcedly enable debugging if requested by user.
690if ($ForceAnalyzeDebugCode) {
691  push @CompileOpts, '-UNDEBUG';
692}
693
694# If we are on OSX and have an installation where the
695# default SDK is inferred by xcrun use xcrun to infer
696# the SDK.
697if (not $HasSDK and $UseXCRUN) {
698  my $sdk = `/usr/bin/xcrun --show-sdk-path -sdk macosx`;
699  chomp $sdk;
700  push @CompileOpts, "-isysroot", $sdk;
701}
702
703if ($Action eq 'compile' or $Action eq 'link') {
704  my @Archs = keys %ArchsSeen;
705  # Skip the file if we don't support the architectures specified.
706  exit 0 if ($HadArch && scalar(@Archs) == 0);
707
708  foreach my $file (@Files) {
709    # Determine the language for the file.
710    my $FileLang = $Lang;
711
712    if (!defined($FileLang)) {
713      # Infer the language from the extension.
714      if ($file =~ /[.]([^.]+)$/) {
715        $FileLang = $LangMap{$1};
716      }
717    }
718
719    # FileLang still not defined?  Skip the file.
720    next if (!defined $FileLang);
721
722    # Language not accepted?
723    next if (!defined $LangsAccepted{$FileLang});
724
725    my @CmdArgs;
726    my @AnalyzeArgs;
727
728    if ($FileLang ne 'unknown') {
729      push @CmdArgs, '-x', $FileLang;
730    }
731
732    if (defined $StoreModel) {
733      push @AnalyzeArgs, "-analyzer-store=$StoreModel";
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