1# -*- coding: utf-8 -*-
2# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3# See https://llvm.org/LICENSE.txt for license information.
4# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5
6import unittest
7import re
8import os
9import os.path
10import libear
11import libscanbuild.analyze as sut
12
13
14class ReportDirectoryTest(unittest.TestCase):
15
16    # Test that successive report directory names ascend in lexicographic
17    # order. This is required so that report directories from two runs of
18    # scan-build can be easily matched up to compare results.
19    def test_directory_name_comparison(self):
20        with libear.TemporaryDirectory() as tmpdir, \
21             sut.report_directory(tmpdir, False, 'html') as report_dir1, \
22             sut.report_directory(tmpdir, False, 'html') as report_dir2, \
23             sut.report_directory(tmpdir, False, 'html') as report_dir3:
24            self.assertLess(report_dir1, report_dir2)
25            self.assertLess(report_dir2, report_dir3)
26
27
28class FilteringFlagsTest(unittest.TestCase):
29
30    def test_language_captured(self):
31        def test(flags):
32            cmd = ['clang', '-c', 'source.c'] + flags
33            opts = sut.classify_parameters(cmd)
34            return opts['language']
35
36        self.assertEqual(None, test([]))
37        self.assertEqual('c', test(['-x', 'c']))
38        self.assertEqual('cpp', test(['-x', 'cpp']))
39
40    def test_arch(self):
41        def test(flags):
42            cmd = ['clang', '-c', 'source.c'] + flags
43            opts = sut.classify_parameters(cmd)
44            return opts['arch_list']
45
46        self.assertEqual([], test([]))
47        self.assertEqual(['mips'], test(['-arch', 'mips']))
48        self.assertEqual(['mips', 'i386'],
49                         test(['-arch', 'mips', '-arch', 'i386']))
50
51    def assertFlagsChanged(self, expected, flags):
52        cmd = ['clang', '-c', 'source.c'] + flags
53        opts = sut.classify_parameters(cmd)
54        self.assertEqual(expected, opts['flags'])
55
56    def assertFlagsUnchanged(self, flags):
57        self.assertFlagsChanged(flags, flags)
58
59    def assertFlagsFiltered(self, flags):
60        self.assertFlagsChanged([], flags)
61
62    def test_optimalizations_pass(self):
63        self.assertFlagsUnchanged(['-O'])
64        self.assertFlagsUnchanged(['-O1'])
65        self.assertFlagsUnchanged(['-Os'])
66        self.assertFlagsUnchanged(['-O2'])
67        self.assertFlagsUnchanged(['-O3'])
68
69    def test_include_pass(self):
70        self.assertFlagsUnchanged([])
71        self.assertFlagsUnchanged(['-include', '/usr/local/include'])
72        self.assertFlagsUnchanged(['-I.'])
73        self.assertFlagsUnchanged(['-I', '.'])
74        self.assertFlagsUnchanged(['-I/usr/local/include'])
75        self.assertFlagsUnchanged(['-I', '/usr/local/include'])
76        self.assertFlagsUnchanged(['-I/opt', '-I', '/opt/otp/include'])
77        self.assertFlagsUnchanged(['-isystem', '/path'])
78        self.assertFlagsUnchanged(['-isystem=/path'])
79
80    def test_define_pass(self):
81        self.assertFlagsUnchanged(['-DNDEBUG'])
82        self.assertFlagsUnchanged(['-UNDEBUG'])
83        self.assertFlagsUnchanged(['-Dvar1=val1', '-Dvar2=val2'])
84        self.assertFlagsUnchanged(['-Dvar="val ues"'])
85
86    def test_output_filtered(self):
87        self.assertFlagsFiltered(['-o', 'source.o'])
88
89    def test_some_warning_filtered(self):
90        self.assertFlagsFiltered(['-Wall'])
91        self.assertFlagsFiltered(['-Wnoexcept'])
92        self.assertFlagsFiltered(['-Wreorder', '-Wunused', '-Wundef'])
93        self.assertFlagsUnchanged(['-Wno-reorder', '-Wno-unused'])
94
95    def test_compile_only_flags_pass(self):
96        self.assertFlagsUnchanged(['-std=C99'])
97        self.assertFlagsUnchanged(['-nostdinc'])
98        self.assertFlagsUnchanged(['-isystem', '/image/debian'])
99        self.assertFlagsUnchanged(['-iprefix', '/usr/local'])
100        self.assertFlagsUnchanged(['-iquote=me'])
101        self.assertFlagsUnchanged(['-iquote', 'me'])
102
103    def test_compile_and_link_flags_pass(self):
104        self.assertFlagsUnchanged(['-fsinged-char'])
105        self.assertFlagsUnchanged(['-fPIC'])
106        self.assertFlagsUnchanged(['-stdlib=libc++'])
107        self.assertFlagsUnchanged(['--sysroot', '/'])
108        self.assertFlagsUnchanged(['-isysroot', '/'])
109
110    def test_some_flags_filtered(self):
111        self.assertFlagsFiltered(['-g'])
112        self.assertFlagsFiltered(['-fsyntax-only'])
113        self.assertFlagsFiltered(['-save-temps'])
114        self.assertFlagsFiltered(['-init', 'my_init'])
115        self.assertFlagsFiltered(['-sectorder', 'a', 'b', 'c'])
116
117
118class Spy(object):
119    def __init__(self):
120        self.arg = None
121        self.success = 0
122
123    def call(self, params):
124        self.arg = params
125        return self.success
126
127
128class RunAnalyzerTest(unittest.TestCase):
129
130    @staticmethod
131    def run_analyzer(content, failures_report, output_format='plist'):
132        with libear.TemporaryDirectory() as tmpdir:
133            filename = os.path.join(tmpdir, 'test.cpp')
134            with open(filename, 'w') as handle:
135                handle.write(content)
136
137            opts = {
138                'clang': 'clang',
139                'directory': os.getcwd(),
140                'flags': [],
141                'direct_args': [],
142                'file': filename,
143                'output_dir': tmpdir,
144                'output_format': output_format,
145                'output_failures': failures_report
146            }
147            spy = Spy()
148            result = sut.run_analyzer(opts, spy.call)
149            output_files = []
150            for entry in os.listdir(tmpdir):
151                output_files.append(entry)
152            return (result, spy.arg, output_files)
153
154    def test_run_analyzer(self):
155        content = "int div(int n, int d) { return n / d; }"
156        (result, fwds, _) = RunAnalyzerTest.run_analyzer(content, False)
157        self.assertEqual(None, fwds)
158        self.assertEqual(0, result['exit_code'])
159
160    def test_run_analyzer_crash(self):
161        content = "int div(int n, int d) { return n / d }"
162        (result, fwds, _) = RunAnalyzerTest.run_analyzer(content, False)
163        self.assertEqual(None, fwds)
164        self.assertEqual(1, result['exit_code'])
165
166    def test_run_analyzer_crash_and_forwarded(self):
167        content = "int div(int n, int d) { return n / d }"
168        (_, fwds, _) = RunAnalyzerTest.run_analyzer(content, True)
169        self.assertEqual(1, fwds['exit_code'])
170        self.assertTrue(len(fwds['error_output']) > 0)
171
172    def test_run_analyzer_with_sarif(self):
173        content = "int div(int n, int d) { return n / d; }"
174        (result, fwds, output_files) = RunAnalyzerTest.run_analyzer(content, False, output_format='sarif')
175        self.assertEqual(None, fwds)
176        self.assertEqual(0, result['exit_code'])
177
178        pattern = re.compile(r'^result-.+\.sarif$')
179        for f in output_files:
180            if re.match(pattern, f):
181                return
182        self.fail('no result sarif files found in output')
183
184
185class ReportFailureTest(unittest.TestCase):
186
187    def assertUnderFailures(self, path):
188        self.assertEqual('failures', os.path.basename(os.path.dirname(path)))
189
190    def test_report_failure_create_files(self):
191        with libear.TemporaryDirectory() as tmpdir:
192            # create input file
193            filename = os.path.join(tmpdir, 'test.c')
194            with open(filename, 'w') as handle:
195                handle.write('int main() { return 0')
196            uname_msg = ' '.join(os.uname()) + os.linesep
197            error_msg = 'this is my error output'
198            # execute test
199            opts = {
200                'clang': 'clang',
201                'directory': os.getcwd(),
202                'flags': [],
203                'file': filename,
204                'output_dir': tmpdir,
205                'language': 'c',
206                'error_type': 'other_error',
207                'error_output': error_msg,
208                'exit_code': 13
209            }
210            sut.report_failure(opts)
211            # verify the result
212            result = dict()
213            pp_file = None
214            for root, _, files in os.walk(tmpdir):
215                keys = [os.path.join(root, name) for name in files]
216                for key in keys:
217                    with open(key, 'r') as handle:
218                        result[key] = handle.readlines()
219                    if re.match(r'^(.*/)+clang(.*)\.i$', key):
220                        pp_file = key
221
222            # prepocessor file generated
223            self.assertUnderFailures(pp_file)
224            # info file generated and content dumped
225            info_file = pp_file + '.info.txt'
226            self.assertTrue(info_file in result)
227            self.assertEqual('Other Error\n', result[info_file][1])
228            self.assertEqual(uname_msg, result[info_file][3])
229            # error file generated and content dumped
230            error_file = pp_file + '.stderr.txt'
231            self.assertTrue(error_file in result)
232            self.assertEqual([error_msg], result[error_file])
233
234
235class AnalyzerTest(unittest.TestCase):
236
237    def test_nodebug_macros_appended(self):
238        def test(flags):
239            spy = Spy()
240            opts = {'flags': flags, 'force_debug': True}
241            self.assertEqual(spy.success,
242                             sut.filter_debug_flags(opts, spy.call))
243            return spy.arg['flags']
244
245        self.assertEqual(['-UNDEBUG'], test([]))
246        self.assertEqual(['-DNDEBUG', '-UNDEBUG'], test(['-DNDEBUG']))
247        self.assertEqual(['-DSomething', '-UNDEBUG'], test(['-DSomething']))
248
249    def test_set_language_fall_through(self):
250        def language(expected, input):
251            spy = Spy()
252            input.update({'compiler': 'c', 'file': 'test.c'})
253            self.assertEqual(spy.success, sut.language_check(input, spy.call))
254            self.assertEqual(expected, spy.arg['language'])
255
256        language('c',   {'language': 'c', 'flags': []})
257        language('c++', {'language': 'c++', 'flags': []})
258
259    def test_set_language_stops_on_not_supported(self):
260        spy = Spy()
261        input = {
262            'compiler': 'c',
263            'flags': [],
264            'file': 'test.java',
265            'language': 'java'
266        }
267        self.assertIsNone(sut.language_check(input, spy.call))
268        self.assertIsNone(spy.arg)
269
270    def test_set_language_sets_flags(self):
271        def flags(expected, input):
272            spy = Spy()
273            input.update({'compiler': 'c', 'file': 'test.c'})
274            self.assertEqual(spy.success, sut.language_check(input, spy.call))
275            self.assertEqual(expected, spy.arg['flags'])
276
277        flags(['-x', 'c'],   {'language': 'c', 'flags': []})
278        flags(['-x', 'c++'], {'language': 'c++', 'flags': []})
279
280    def test_set_language_from_filename(self):
281        def language(expected, input):
282            spy = Spy()
283            input.update({'language': None, 'flags': []})
284            self.assertEqual(spy.success, sut.language_check(input, spy.call))
285            self.assertEqual(expected, spy.arg['language'])
286
287        language('c',   {'file': 'file.c',   'compiler': 'c'})
288        language('c++', {'file': 'file.c',   'compiler': 'c++'})
289        language('c++', {'file': 'file.cxx', 'compiler': 'c'})
290        language('c++', {'file': 'file.cxx', 'compiler': 'c++'})
291        language('c++', {'file': 'file.cpp', 'compiler': 'c++'})
292        language('c-cpp-output',   {'file': 'file.i', 'compiler': 'c'})
293        language('c++-cpp-output', {'file': 'file.i', 'compiler': 'c++'})
294
295    def test_arch_loop_sets_flags(self):
296        def flags(archs):
297            spy = Spy()
298            input = {'flags': [], 'arch_list': archs}
299            sut.arch_check(input, spy.call)
300            return spy.arg['flags']
301
302        self.assertEqual([], flags([]))
303        self.assertEqual(['-arch', 'i386'], flags(['i386']))
304        self.assertEqual(['-arch', 'i386'], flags(['i386', 'ppc']))
305        self.assertEqual(['-arch', 'sparc'], flags(['i386', 'sparc']))
306
307    def test_arch_loop_stops_on_not_supported(self):
308        def stop(archs):
309            spy = Spy()
310            input = {'flags': [], 'arch_list': archs}
311            self.assertIsNone(sut.arch_check(input, spy.call))
312            self.assertIsNone(spy.arg)
313
314        stop(['ppc'])
315        stop(['ppc64'])
316
317
318@sut.require([])
319def method_without_expecteds(opts):
320    return 0
321
322
323@sut.require(['this', 'that'])
324def method_with_expecteds(opts):
325    return 0
326
327
328@sut.require([])
329def method_exception_from_inside(opts):
330    raise Exception('here is one')
331
332
333class RequireDecoratorTest(unittest.TestCase):
334
335    def test_method_without_expecteds(self):
336        self.assertEqual(method_without_expecteds(dict()), 0)
337        self.assertEqual(method_without_expecteds({}), 0)
338        self.assertEqual(method_without_expecteds({'this': 2}), 0)
339        self.assertEqual(method_without_expecteds({'that': 3}), 0)
340
341    def test_method_with_expecteds(self):
342        self.assertRaises(KeyError, method_with_expecteds, dict())
343        self.assertRaises(KeyError, method_with_expecteds, {})
344        self.assertRaises(KeyError, method_with_expecteds, {'this': 2})
345        self.assertRaises(KeyError, method_with_expecteds, {'that': 3})
346        self.assertEqual(method_with_expecteds({'this': 0, 'that': 3}), 0)
347
348    def test_method_exception_not_caught(self):
349        self.assertRaises(Exception, method_exception_from_inside, dict())
350
351
352class PrefixWithTest(unittest.TestCase):
353
354    def test_gives_empty_on_empty(self):
355        res = sut.prefix_with(0, [])
356        self.assertFalse(res)
357
358    def test_interleaves_prefix(self):
359        res = sut.prefix_with(0, [1, 2, 3])
360        self.assertListEqual([0, 1, 0, 2, 0, 3], res)
361
362
363class MergeCtuMapTest(unittest.TestCase):
364
365    def test_no_map_gives_empty(self):
366        pairs = sut.create_global_ctu_extdef_map([])
367        self.assertFalse(pairs)
368
369    def test_multiple_maps_merged(self):
370        concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
371                      'c:@F@fun2#I# ast/fun2.c.ast',
372                      'c:@F@fun3#I# ast/fun3.c.ast']
373        pairs = sut.create_global_ctu_extdef_map(concat_map)
374        self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
375        self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
376        self.assertTrue(('c:@F@fun3#I#', 'ast/fun3.c.ast') in pairs)
377        self.assertEqual(3, len(pairs))
378
379    def test_not_unique_func_left_out(self):
380        concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
381                      'c:@F@fun2#I# ast/fun2.c.ast',
382                      'c:@F@fun1#I# ast/fun7.c.ast']
383        pairs = sut.create_global_ctu_extdef_map(concat_map)
384        self.assertFalse(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
385        self.assertFalse(('c:@F@fun1#I#', 'ast/fun7.c.ast') in pairs)
386        self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
387        self.assertEqual(1, len(pairs))
388
389    def test_duplicates_are_kept(self):
390        concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
391                      'c:@F@fun2#I# ast/fun2.c.ast',
392                      'c:@F@fun1#I# ast/fun1.c.ast']
393        pairs = sut.create_global_ctu_extdef_map(concat_map)
394        self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
395        self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
396        self.assertEqual(2, len(pairs))
397
398    def test_space_handled_in_source(self):
399        concat_map = ['c:@F@fun1#I# ast/f un.c.ast']
400        pairs = sut.create_global_ctu_extdef_map(concat_map)
401        self.assertTrue(('c:@F@fun1#I#', 'ast/f un.c.ast') in pairs)
402        self.assertEqual(1, len(pairs))
403
404
405class ExtdefMapSrcToAstTest(unittest.TestCase):
406
407    def test_empty_gives_empty(self):
408        fun_ast_lst = sut.extdef_map_list_src_to_ast([])
409        self.assertFalse(fun_ast_lst)
410
411    def test_sources_to_asts(self):
412        fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f1.c'),
413                       'c:@F@f2#I# ' + os.path.join(os.sep + 'path', 'f2.c')]
414        fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst)
415        self.assertTrue('c:@F@f1#I# ' +
416                        os.path.join('ast', 'path', 'f1.c.ast')
417                        in fun_ast_lst)
418        self.assertTrue('c:@F@f2#I# ' +
419                        os.path.join('ast', 'path', 'f2.c.ast')
420                        in fun_ast_lst)
421        self.assertEqual(2, len(fun_ast_lst))
422
423    def test_spaces_handled(self):
424        fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f 1.c')]
425        fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst)
426        self.assertTrue('c:@F@f1#I# ' +
427                        os.path.join('ast', 'path', 'f 1.c.ast')
428                        in fun_ast_lst)
429        self.assertEqual(1, len(fun_ast_lst))
430