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/));
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 constraints engine.
470my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};
471
472#Get the internal stats setting.
473my $InternalStats = $ENV{'CCC_ANALYZER_INTERNAL_STATS'};
474
475# Get the output format.
476my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
477if (!defined $OutputFormat) { $OutputFormat = "html"; }
478
479# Get the config options.
480my $ConfigOptions = $ENV{'CCC_ANALYZER_CONFIG'};
481
482# Determine the level of verbosity.
483my $Verbose = 0;
484if (defined $ENV{'CCC_ANALYZER_VERBOSE'}) { $Verbose = 1; }
485if (defined $ENV{'CCC_ANALYZER_LOG'}) { $Verbose = 2; }
486
487# Get the HTML output directory.
488my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};
489
490# Get force-analyze-debug-code option.
491my $ForceAnalyzeDebugCode = $ENV{'CCC_ANALYZER_FORCE_ANALYZE_DEBUG_CODE'};
492
493my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
494my %ArchsSeen;
495my $HadArch = 0;
496my $HasSDK = 0;
497
498# Process the arguments.
499foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
500  my $Arg = $ARGV[$i];
501  my @ArgParts = split /=/,$Arg,2;
502  my $ArgKey = $ArgParts[0];
503
504  # Be friendly to "" in the argument list.
505  if (!defined($ArgKey)) {
506    next;
507  }
508
509  # Modes ccc-analyzer supports
510  if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; }
511  elsif ($Arg eq '-c') { $Action = 'compile'; }
512  elsif ($Arg =~ /^-print-prog-name/) { exit 0; }
513
514  # Specially handle duplicate cases of -arch
515  if ($Arg eq "-arch") {
516    my $arch = $ARGV[$i+1];
517    # We don't want to process 'ppc' because of Clang's lack of support
518    # for Altivec (also some #defines won't likely be defined correctly, etc.)
519    if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; }
520    $HadArch = 1;
521    ++$i;
522    next;
523  }
524
525  # On OSX/iOS, record if an SDK path was specified.  This
526  # is innocuous for other platforms, so the check just happens.
527  if ($Arg =~ /^-isysroot/) {
528    $HasSDK = 1;
529  }
530
531  # Options with possible arguments that should pass through to compiler.
532  if (defined $CompileOptionMap{$ArgKey}) {
533    my $Cnt = $CompileOptionMap{$ArgKey};
534    push @CompileOpts,$Arg;
535    while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
536    next;
537  }
538  # Handle the case where there isn't a space after -iquote
539  if ($Arg =~ /^-iquote.*/) {
540    push @CompileOpts,$Arg;
541    next;
542  }
543
544  # Options with possible arguments that should pass through to linker.
545  if (defined $LinkerOptionMap{$ArgKey}) {
546    my $Cnt = $LinkerOptionMap{$ArgKey};
547    push @LinkOpts,$Arg;
548    while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
549    next;
550  }
551
552  # Options with possible arguments that should pass through to both compiler
553  # and the linker.
554  if (defined $CompilerLinkerOptionMap{$ArgKey}) {
555    my $Cnt = $CompilerLinkerOptionMap{$ArgKey};
556
557    # Check if this is an option that should have a unique value, and if so
558    # determine if the value was checked before.
559    if ($UniqueOptions{$Arg}) {
560      if (defined $Uniqued{$Arg}) {
561        $i += $Cnt;
562        next;
563      }
564      $Uniqued{$Arg} = 1;
565    }
566
567    push @CompileOpts,$Arg;
568    push @LinkOpts,$Arg;
569
570    if (scalar @ArgParts == 1) {
571      while ($Cnt > 0) {
572        ++$i; --$Cnt;
573        push @CompileOpts, $ARGV[$i];
574        push @LinkOpts, $ARGV[$i];
575      }
576    }
577    next;
578  }
579
580  # Ignored options.
581  if (defined $IgnoredOptionMap{$ArgKey}) {
582    my $Cnt = $IgnoredOptionMap{$ArgKey};
583    while ($Cnt > 0) {
584      ++$i; --$Cnt;
585    }
586    next;
587  }
588
589  # Compile mode flags.
590  if ($Arg =~ /^-(?:[DIU]|isystem)(.*)$/) {
591    my $Tmp = $Arg;
592    if ($1 eq '') {
593      # FIXME: Check if we are going off the end.
594      ++$i;
595      $Tmp = $Arg . $ARGV[$i];
596    }
597    push @CompileOpts,$Tmp;
598    next;
599  }
600
601  if ($Arg =~ /^-m.*/) {
602    push @CompileOpts,$Arg;
603    next;
604  }
605
606  # Language.
607  if ($Arg eq '-x') {
608    $Lang = $ARGV[$i+1];
609    ++$i; next;
610  }
611
612  # Output file.
613  if ($Arg eq '-o') {
614    ++$i;
615    $Output = $ARGV[$i];
616    next;
617  }
618
619  # Get the link mode.
620  if ($Arg =~ /^-[l,L,O]/) {
621    if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
622    elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
623    else { push @LinkOpts,$Arg; }
624
625    # Must pass this along for the __OPTIMIZE__ macro
626    if ($Arg =~ /^-O/) { push @CompileOpts,$Arg; }
627    next;
628  }
629
630  if ($Arg =~ /^-std=/) {
631    push @CompileOpts,$Arg;
632    next;
633  }
634
635  # Get the compiler/link mode.
636  if ($Arg =~ /^-F(.+)$/) {
637    my $Tmp = $Arg;
638    if ($1 eq '') {
639      # FIXME: Check if we are going off the end.
640      ++$i;
641      $Tmp = $Arg . $ARGV[$i];
642    }
643    push @CompileOpts,$Tmp;
644    push @LinkOpts,$Tmp;
645    next;
646  }
647
648  # Input files.
649  if ($Arg eq '-filelist') {
650    # FIXME: Make sure we aren't walking off the end.
651    open(IN, $ARGV[$i+1]);
652    while (<IN>) { s/\015?\012//; push @Files,$_; }
653    close(IN);
654    ++$i;
655    next;
656  }
657
658  if ($Arg =~ /^-f/) {
659    push @CompileOpts,$Arg;
660    push @LinkOpts,$Arg;
661    next;
662  }
663
664  # Handle -Wno-.  We don't care about extra warnings, but
665  # we should suppress ones that we don't want to see.
666  if ($Arg =~ /^-Wno-/) {
667    push @CompileOpts, $Arg;
668    next;
669  }
670
671  # Handle -Xclang some-arg. Add both arguments to the compiler options.
672  if ($Arg =~ /^-Xclang$/) {
673    # FIXME: Check if we are going off the end.
674    ++$i;
675    push @CompileOpts, $Arg;
676    push @CompileOpts, $ARGV[$i];
677    next;
678  }
679
680  if (!($Arg =~ /^-/)) {
681    push @Files, $Arg;
682    next;
683  }
684}
685
686# Forcedly enable debugging if requested by user.
687if ($ForceAnalyzeDebugCode) {
688  push @CompileOpts, '-UNDEBUG';
689}
690
691# If we are on OSX and have an installation where the
692# default SDK is inferred by xcrun use xcrun to infer
693# the SDK.
694if (not $HasSDK and $UseXCRUN) {
695  my $sdk = `/usr/bin/xcrun --show-sdk-path -sdk macosx`;
696  chomp $sdk;
697  push @CompileOpts, "-isysroot", $sdk;
698}
699
700if ($Action eq 'compile' or $Action eq 'link') {
701  my @Archs = keys %ArchsSeen;
702  # Skip the file if we don't support the architectures specified.
703  exit 0 if ($HadArch && scalar(@Archs) == 0);
704
705  foreach my $file (@Files) {
706    # Determine the language for the file.
707    my $FileLang = $Lang;
708
709    if (!defined($FileLang)) {
710      # Infer the language from the extension.
711      if ($file =~ /[.]([^.]+)$/) {
712        $FileLang = $LangMap{$1};
713      }
714    }
715
716    # FileLang still not defined?  Skip the file.
717    next if (!defined $FileLang);
718
719    # Language not accepted?
720    next if (!defined $LangsAccepted{$FileLang});
721
722    my @CmdArgs;
723    my @AnalyzeArgs;
724
725    if ($FileLang ne 'unknown') {
726      push @CmdArgs, '-x', $FileLang;
727    }
728
729    if (defined $ConstraintsModel) {
730      push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel";
731    }
732
733    if (defined $InternalStats) {
734      push @AnalyzeArgs, "-analyzer-stats";
735    }
736
737    if (defined $Analyses) {
738      push @AnalyzeArgs, split '\s+', $Analyses;
739    }
740
741    if (defined $Plugins) {
742      push @AnalyzeArgs, split '\s+', $Plugins;
743    }
744
745    if (defined $OutputFormat) {
746      push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat;
747      if ($OutputFormat =~ /plist/ || $OutputFormat =~ /sarif/) {
748        # Change "Output" to be a file.
749        my $Suffix = $OutputFormat =~ /plist/ ? ".plist" : ".sarif";
750        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => $Suffix,
751                               DIR => $HtmlDir);
752        $ResultFile = $f;
753        # If the HtmlDir is not set, we should clean up the plist files.
754        if (!defined $HtmlDir || $HtmlDir eq "") {
755          $CleanupFile = $f;
756        }
757      }
758    }
759    if (defined $ConfigOptions) {
760      push @AnalyzeArgs, split '\s+', $ConfigOptions;
761    }
762
763    push @CmdArgs, @CompileOpts;
764    push @CmdArgs, $file;
765
766    if (scalar @Archs) {
767      foreach my $arch (@Archs) {
768        my @NewArgs;
769        push @NewArgs, '-arch', $arch;
770        push @NewArgs, @CmdArgs;
771        Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output,
772                $Verbose, $HtmlDir, $file);
773      }
774    }
775    else {
776      Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output,
777              $Verbose, $HtmlDir, $file);
778    }
779  }
780}
781