Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# -*- coding: utf-8 -*-
#                     The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.

import unittest
import re
import os
import os.path
import libear
import libscanbuild.analyze as sut


class ReportDirectoryTest(unittest.TestCase):

    # Test that successive report directory names ascend in lexicographic
    # order. This is required so that report directories from two runs of
    # scan-build can be easily matched up to compare results.
    def test_directory_name_comparison(self):
        with libear.TemporaryDirectory() as tmpdir, \
             sut.report_directory(tmpdir, False) as report_dir1, \
             sut.report_directory(tmpdir, False) as report_dir2, \
             sut.report_directory(tmpdir, False) as report_dir3:
            self.assertLess(report_dir1, report_dir2)
            self.assertLess(report_dir2, report_dir3)


class FilteringFlagsTest(unittest.TestCase):

    def test_language_captured(self):
        def test(flags):
            cmd = ['clang', '-c', 'source.c'] + flags
            opts = sut.classify_parameters(cmd)
            return opts['language']

        self.assertEqual(None, test([]))
        self.assertEqual('c', test(['-x', 'c']))
        self.assertEqual('cpp', test(['-x', 'cpp']))

    def test_arch(self):
        def test(flags):
            cmd = ['clang', '-c', 'source.c'] + flags
            opts = sut.classify_parameters(cmd)
            return opts['arch_list']

        self.assertEqual([], test([]))
        self.assertEqual(['mips'], test(['-arch', 'mips']))
        self.assertEqual(['mips', 'i386'],
                         test(['-arch', 'mips', '-arch', 'i386']))

    def assertFlagsChanged(self, expected, flags):
        cmd = ['clang', '-c', 'source.c'] + flags
        opts = sut.classify_parameters(cmd)
        self.assertEqual(expected, opts['flags'])

    def assertFlagsUnchanged(self, flags):
        self.assertFlagsChanged(flags, flags)

    def assertFlagsFiltered(self, flags):
        self.assertFlagsChanged([], flags)

    def test_optimalizations_pass(self):
        self.assertFlagsUnchanged(['-O'])
        self.assertFlagsUnchanged(['-O1'])
        self.assertFlagsUnchanged(['-Os'])
        self.assertFlagsUnchanged(['-O2'])
        self.assertFlagsUnchanged(['-O3'])

    def test_include_pass(self):
        self.assertFlagsUnchanged([])
        self.assertFlagsUnchanged(['-include', '/usr/local/include'])
        self.assertFlagsUnchanged(['-I.'])
        self.assertFlagsUnchanged(['-I', '.'])
        self.assertFlagsUnchanged(['-I/usr/local/include'])
        self.assertFlagsUnchanged(['-I', '/usr/local/include'])
        self.assertFlagsUnchanged(['-I/opt', '-I', '/opt/otp/include'])
        self.assertFlagsUnchanged(['-isystem', '/path'])
        self.assertFlagsUnchanged(['-isystem=/path'])

    def test_define_pass(self):
        self.assertFlagsUnchanged(['-DNDEBUG'])
        self.assertFlagsUnchanged(['-UNDEBUG'])
        self.assertFlagsUnchanged(['-Dvar1=val1', '-Dvar2=val2'])
        self.assertFlagsUnchanged(['-Dvar="val ues"'])

    def test_output_filtered(self):
        self.assertFlagsFiltered(['-o', 'source.o'])

    def test_some_warning_filtered(self):
        self.assertFlagsFiltered(['-Wall'])
        self.assertFlagsFiltered(['-Wnoexcept'])
        self.assertFlagsFiltered(['-Wreorder', '-Wunused', '-Wundef'])
        self.assertFlagsUnchanged(['-Wno-reorder', '-Wno-unused'])

    def test_compile_only_flags_pass(self):
        self.assertFlagsUnchanged(['-std=C99'])
        self.assertFlagsUnchanged(['-nostdinc'])
        self.assertFlagsUnchanged(['-isystem', '/image/debian'])
        self.assertFlagsUnchanged(['-iprefix', '/usr/local'])
        self.assertFlagsUnchanged(['-iquote=me'])
        self.assertFlagsUnchanged(['-iquote', 'me'])

    def test_compile_and_link_flags_pass(self):
        self.assertFlagsUnchanged(['-fsinged-char'])
        self.assertFlagsUnchanged(['-fPIC'])
        self.assertFlagsUnchanged(['-stdlib=libc++'])
        self.assertFlagsUnchanged(['--sysroot', '/'])
        self.assertFlagsUnchanged(['-isysroot', '/'])

    def test_some_flags_filtered(self):
        self.assertFlagsFiltered(['-g'])
        self.assertFlagsFiltered(['-fsyntax-only'])
        self.assertFlagsFiltered(['-save-temps'])
        self.assertFlagsFiltered(['-init', 'my_init'])
        self.assertFlagsFiltered(['-sectorder', 'a', 'b', 'c'])


class Spy(object):
    def __init__(self):
        self.arg = None
        self.success = 0

    def call(self, params):
        self.arg = params
        return self.success


class RunAnalyzerTest(unittest.TestCase):

    @staticmethod
    def run_analyzer(content, failures_report):
        with libear.TemporaryDirectory() as tmpdir:
            filename = os.path.join(tmpdir, 'test.cpp')
            with open(filename, 'w') as handle:
                handle.write(content)

            opts = {
                'clang': 'clang',
                'directory': os.getcwd(),
                'flags': [],
                'direct_args': [],
                'file': filename,
                'output_dir': tmpdir,
                'output_format': 'plist',
                'output_failures': failures_report
            }
            spy = Spy()
            result = sut.run_analyzer(opts, spy.call)
            return (result, spy.arg)

    def test_run_analyzer(self):
        content = "int div(int n, int d) { return n / d; }"
        (result, fwds) = RunAnalyzerTest.run_analyzer(content, False)
        self.assertEqual(None, fwds)
        self.assertEqual(0, result['exit_code'])

    def test_run_analyzer_crash(self):
        content = "int div(int n, int d) { return n / d }"
        (result, fwds) = RunAnalyzerTest.run_analyzer(content, False)
        self.assertEqual(None, fwds)
        self.assertEqual(1, result['exit_code'])

    def test_run_analyzer_crash_and_forwarded(self):
        content = "int div(int n, int d) { return n / d }"
        (_, fwds) = RunAnalyzerTest.run_analyzer(content, True)
        self.assertEqual(1, fwds['exit_code'])
        self.assertTrue(len(fwds['error_output']) > 0)


class ReportFailureTest(unittest.TestCase):

    def assertUnderFailures(self, path):
        self.assertEqual('failures', os.path.basename(os.path.dirname(path)))

    def test_report_failure_create_files(self):
        with libear.TemporaryDirectory() as tmpdir:
            # create input file
            filename = os.path.join(tmpdir, 'test.c')
            with open(filename, 'w') as handle:
                handle.write('int main() { return 0')
            uname_msg = ' '.join(os.uname()) + os.linesep
            error_msg = 'this is my error output'
            # execute test
            opts = {
                'clang': 'clang',
                'directory': os.getcwd(),
                'flags': [],
                'file': filename,
                'output_dir': tmpdir,
                'language': 'c',
                'error_type': 'other_error',
                'error_output': error_msg,
                'exit_code': 13
            }
            sut.report_failure(opts)
            # verify the result
            result = dict()
            pp_file = None
            for root, _, files in os.walk(tmpdir):
                keys = [os.path.join(root, name) for name in files]
                for key in keys:
                    with open(key, 'r') as handle:
                        result[key] = handle.readlines()
                    if re.match(r'^(.*/)+clang(.*)\.i$', key):
                        pp_file = key

            # prepocessor file generated
            self.assertUnderFailures(pp_file)
            # info file generated and content dumped
            info_file = pp_file + '.info.txt'
            self.assertTrue(info_file in result)
            self.assertEqual('Other Error\n', result[info_file][1])
            self.assertEqual(uname_msg, result[info_file][3])
            # error file generated and content dumped
            error_file = pp_file + '.stderr.txt'
            self.assertTrue(error_file in result)
            self.assertEqual([error_msg], result[error_file])


class AnalyzerTest(unittest.TestCase):

    def test_nodebug_macros_appended(self):
        def test(flags):
            spy = Spy()
            opts = {'flags': flags, 'force_debug': True}
            self.assertEqual(spy.success,
                             sut.filter_debug_flags(opts, spy.call))
            return spy.arg['flags']

        self.assertEqual(['-UNDEBUG'], test([]))
        self.assertEqual(['-DNDEBUG', '-UNDEBUG'], test(['-DNDEBUG']))
        self.assertEqual(['-DSomething', '-UNDEBUG'], test(['-DSomething']))

    def test_set_language_fall_through(self):
        def language(expected, input):
            spy = Spy()
            input.update({'compiler': 'c', 'file': 'test.c'})
            self.assertEqual(spy.success, sut.language_check(input, spy.call))
            self.assertEqual(expected, spy.arg['language'])

        language('c',   {'language': 'c', 'flags': []})
        language('c++', {'language': 'c++', 'flags': []})

    def test_set_language_stops_on_not_supported(self):
        spy = Spy()
        input = {
            'compiler': 'c',
            'flags': [],
            'file': 'test.java',
            'language': 'java'
        }
        self.assertIsNone(sut.language_check(input, spy.call))
        self.assertIsNone(spy.arg)

    def test_set_language_sets_flags(self):
        def flags(expected, input):
            spy = Spy()
            input.update({'compiler': 'c', 'file': 'test.c'})
            self.assertEqual(spy.success, sut.language_check(input, spy.call))
            self.assertEqual(expected, spy.arg['flags'])

        flags(['-x', 'c'],   {'language': 'c', 'flags': []})
        flags(['-x', 'c++'], {'language': 'c++', 'flags': []})

    def test_set_language_from_filename(self):
        def language(expected, input):
            spy = Spy()
            input.update({'language': None, 'flags': []})
            self.assertEqual(spy.success, sut.language_check(input, spy.call))
            self.assertEqual(expected, spy.arg['language'])

        language('c',   {'file': 'file.c',   'compiler': 'c'})
        language('c++', {'file': 'file.c',   'compiler': 'c++'})
        language('c++', {'file': 'file.cxx', 'compiler': 'c'})
        language('c++', {'file': 'file.cxx', 'compiler': 'c++'})
        language('c++', {'file': 'file.cpp', 'compiler': 'c++'})
        language('c-cpp-output',   {'file': 'file.i', 'compiler': 'c'})
        language('c++-cpp-output', {'file': 'file.i', 'compiler': 'c++'})

    def test_arch_loop_sets_flags(self):
        def flags(archs):
            spy = Spy()
            input = {'flags': [], 'arch_list': archs}
            sut.arch_check(input, spy.call)
            return spy.arg['flags']

        self.assertEqual([], flags([]))
        self.assertEqual(['-arch', 'i386'], flags(['i386']))
        self.assertEqual(['-arch', 'i386'], flags(['i386', 'ppc']))
        self.assertEqual(['-arch', 'sparc'], flags(['i386', 'sparc']))

    def test_arch_loop_stops_on_not_supported(self):
        def stop(archs):
            spy = Spy()
            input = {'flags': [], 'arch_list': archs}
            self.assertIsNone(sut.arch_check(input, spy.call))
            self.assertIsNone(spy.arg)

        stop(['ppc'])
        stop(['ppc64'])


@sut.require([])
def method_without_expecteds(opts):
    return 0


@sut.require(['this', 'that'])
def method_with_expecteds(opts):
    return 0


@sut.require([])
def method_exception_from_inside(opts):
    raise Exception('here is one')


class RequireDecoratorTest(unittest.TestCase):

    def test_method_without_expecteds(self):
        self.assertEqual(method_without_expecteds(dict()), 0)
        self.assertEqual(method_without_expecteds({}), 0)
        self.assertEqual(method_without_expecteds({'this': 2}), 0)
        self.assertEqual(method_without_expecteds({'that': 3}), 0)

    def test_method_with_expecteds(self):
        self.assertRaises(KeyError, method_with_expecteds, dict())
        self.assertRaises(KeyError, method_with_expecteds, {})
        self.assertRaises(KeyError, method_with_expecteds, {'this': 2})
        self.assertRaises(KeyError, method_with_expecteds, {'that': 3})
        self.assertEqual(method_with_expecteds({'this': 0, 'that': 3}), 0)

    def test_method_exception_not_caught(self):
        self.assertRaises(Exception, method_exception_from_inside, dict())


class PrefixWithTest(unittest.TestCase):

    def test_gives_empty_on_empty(self):
        res = sut.prefix_with(0, [])
        self.assertFalse(res)

    def test_interleaves_prefix(self):
        res = sut.prefix_with(0, [1, 2, 3])
        self.assertListEqual([0, 1, 0, 2, 0, 3], res)


class MergeCtuMapTest(unittest.TestCase):

    def test_no_map_gives_empty(self):
        pairs = sut.create_global_ctu_function_map([])
        self.assertFalse(pairs)

    def test_multiple_maps_merged(self):
        concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
                      'c:@F@fun2#I# ast/fun2.c.ast',
                      'c:@F@fun3#I# ast/fun3.c.ast']
        pairs = sut.create_global_ctu_function_map(concat_map)
        self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
        self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
        self.assertTrue(('c:@F@fun3#I#', 'ast/fun3.c.ast') in pairs)
        self.assertEqual(3, len(pairs))

    def test_not_unique_func_left_out(self):
        concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
                      'c:@F@fun2#I# ast/fun2.c.ast',
                      'c:@F@fun1#I# ast/fun7.c.ast']
        pairs = sut.create_global_ctu_function_map(concat_map)
        self.assertFalse(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
        self.assertFalse(('c:@F@fun1#I#', 'ast/fun7.c.ast') in pairs)
        self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
        self.assertEqual(1, len(pairs))

    def test_duplicates_are_kept(self):
        concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
                      'c:@F@fun2#I# ast/fun2.c.ast',
                      'c:@F@fun1#I# ast/fun1.c.ast']
        pairs = sut.create_global_ctu_function_map(concat_map)
        self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
        self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
        self.assertEqual(2, len(pairs))

    def test_space_handled_in_source(self):
        concat_map = ['c:@F@fun1#I# ast/f un.c.ast']
        pairs = sut.create_global_ctu_function_map(concat_map)
        self.assertTrue(('c:@F@fun1#I#', 'ast/f un.c.ast') in pairs)
        self.assertEqual(1, len(pairs))


class FuncMapSrcToAstTest(unittest.TestCase):

    def test_empty_gives_empty(self):
        fun_ast_lst = sut.func_map_list_src_to_ast([])
        self.assertFalse(fun_ast_lst)

    def test_sources_to_asts(self):
        fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f1.c'),
                       'c:@F@f2#I# ' + os.path.join(os.sep + 'path', 'f2.c')]
        fun_ast_lst = sut.func_map_list_src_to_ast(fun_src_lst)
        self.assertTrue('c:@F@f1#I# ' +
                        os.path.join('ast', 'path', 'f1.c.ast')
                        in fun_ast_lst)
        self.assertTrue('c:@F@f2#I# ' +
                        os.path.join('ast', 'path', 'f2.c.ast')
                        in fun_ast_lst)
        self.assertEqual(2, len(fun_ast_lst))

    def test_spaces_handled(self):
        fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f 1.c')]
        fun_ast_lst = sut.func_map_list_src_to_ast(fun_src_lst)
        self.assertTrue('c:@F@f1#I# ' +
                        os.path.join('ast', 'path', 'f 1.c.ast')
                        in fun_ast_lst)
        self.assertEqual(1, len(fun_ast_lst))