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 libear 7import libscanbuild.intercept as sut 8import unittest 9import os.path 10 11 12class InterceptUtilTest(unittest.TestCase): 13 def test_format_entry_filters_action(self): 14 def test(command): 15 trace = {"command": command, "directory": "/opt/src/project"} 16 return list(sut.format_entry(trace)) 17 18 self.assertTrue(test(["cc", "-c", "file.c", "-o", "file.o"])) 19 self.assertFalse(test(["cc", "-E", "file.c"])) 20 self.assertFalse(test(["cc", "-MM", "file.c"])) 21 self.assertFalse(test(["cc", "this.o", "that.o", "-o", "a.out"])) 22 23 def test_format_entry_normalize_filename(self): 24 parent = os.path.join(os.sep, "home", "me") 25 current = os.path.join(parent, "project") 26 27 def test(filename): 28 trace = {"directory": current, "command": ["cc", "-c", filename]} 29 return list(sut.format_entry(trace))[0]["file"] 30 31 self.assertEqual(os.path.join(current, "file.c"), test("file.c")) 32 self.assertEqual(os.path.join(current, "file.c"), test("./file.c")) 33 self.assertEqual(os.path.join(parent, "file.c"), test("../file.c")) 34 self.assertEqual( 35 os.path.join(current, "file.c"), test(os.path.join(current, "file.c")) 36 ) 37 38 def test_sip(self): 39 def create_status_report(filename, message): 40 content = """#!/usr/bin/env sh 41 echo 'sa-la-la-la' 42 echo 'la-la-la' 43 echo '{0}' 44 echo 'sa-la-la-la' 45 echo 'la-la-la' 46 """.format( 47 message 48 ) 49 lines = [line.strip() for line in content.split("\n")] 50 with open(filename, "w") as handle: 51 handle.write("\n".join(lines)) 52 handle.close() 53 os.chmod(filename, 0x1FF) 54 55 def create_csrutil(dest_dir, status): 56 filename = os.path.join(dest_dir, "csrutil") 57 message = "System Integrity Protection status: {0}".format(status) 58 return create_status_report(filename, message) 59 60 def create_sestatus(dest_dir, status): 61 filename = os.path.join(dest_dir, "sestatus") 62 message = "SELinux status:\t{0}".format(status) 63 return create_status_report(filename, message) 64 65 ENABLED = "enabled" 66 DISABLED = "disabled" 67 68 OSX = "darwin" 69 70 with libear.TemporaryDirectory() as tmpdir: 71 saved = os.environ["PATH"] 72 try: 73 os.environ["PATH"] = tmpdir + ":" + saved 74 75 create_csrutil(tmpdir, ENABLED) 76 self.assertTrue(sut.is_preload_disabled(OSX)) 77 78 create_csrutil(tmpdir, DISABLED) 79 self.assertFalse(sut.is_preload_disabled(OSX)) 80 finally: 81 os.environ["PATH"] = saved 82 83 saved = os.environ["PATH"] 84 try: 85 os.environ["PATH"] = "" 86 # shall be false when it's not in the path 87 self.assertFalse(sut.is_preload_disabled(OSX)) 88 89 self.assertFalse(sut.is_preload_disabled("unix")) 90 finally: 91 os.environ["PATH"] = saved 92