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