aboutsummaryrefslogtreecommitdiffstats
path: root/build
diff options
context:
space:
mode:
authorBowgo Tsai2018-02-05 03:41:02 -0600
committerBowgo Tsai2018-02-05 04:22:12 -0600
commit741a70a058cd238e80d514f84ca832a54c6120a8 (patch)
treebe5da1b0f89517ce01616fbcfe6868a9b717e4ad /build
parentafbcf21bfbd7ce303835a4698214cff302ca8c2b (diff)
downloadsystem-sepolicy-741a70a058cd238e80d514f84ca832a54c6120a8.tar.gz
system-sepolicy-741a70a058cd238e80d514f84ca832a54c6120a8.tar.xz
system-sepolicy-741a70a058cd238e80d514f84ca832a54c6120a8.zip
Using a python script to build sepolicy
Current sepolicy CIL files are built by several command-line tools in Android.mk. This change extracts some of the build logic into a python script to relief the effort in Android.mk. The first command is `build_sepolicy build_cil`. It's possible to add more sub-commands under the build_sepolicy script in the future. Bug: 64240127 Test: build bullhead/taimen Change-Id: Ie0ae4fc5256a550c72954cde5d5dd213a22d159a
Diffstat (limited to 'build')
-rw-r--r--build/Android.bp34
-rw-r--r--build/build_sepolicy.py140
-rw-r--r--build/file_utils.py49
3 files changed, 223 insertions, 0 deletions
diff --git a/build/Android.bp b/build/Android.bp
new file mode 100644
index 00000000..d3f1fc36
--- /dev/null
+++ b/build/Android.bp
@@ -0,0 +1,34 @@
1// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15python_binary_host {
16 name: "build_sepolicy",
17 srcs: [
18 "build_sepolicy.py",
19 "file_utils.py",
20 ],
21 required: [
22 "checkpolicy",
23 "secilc",
24 "version_policy",
25 ],
26 version: {
27 py2: {
28 enabled: true,
29 },
30 py3: {
31 enabled: false,
32 },
33 },
34}
diff --git a/build/build_sepolicy.py b/build/build_sepolicy.py
new file mode 100644
index 00000000..ff2ff075
--- /dev/null
+++ b/build/build_sepolicy.py
@@ -0,0 +1,140 @@
1# Copyright 2018 - The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Command-line tool to build SEPolicy files."""
16
17import argparse
18import os
19import subprocess
20import sys
21
22import file_utils
23
24
25# All supported commands in this module.
26# For each command, need to add two functions. Take 'build_cil' for example:
27# - setup_build_cil()
28# - Sets up command parsers and sets default function to do_build_cil().
29# - do_build_cil()
30_SUPPORTED_COMMANDS = ('build_cil',)
31
32
33def run_host_command(args, **kwargs):
34 """Runs a host command and prints output."""
35 if kwargs.get('shell'):
36 command_log = args
37 else:
38 command_log = ' '.join(args) # For args as a sequence.
39
40 try:
41 subprocess.check_call(args, **kwargs)
42 except subprocess.CalledProcessError as err:
43 sys.stderr.write(
44 'build_sepolicy - failed to run command: {!r} (ret:{})\n'.format(
45 command_log, err.returncode))
46 sys.exit(err.returncode)
47
48
49def do_build_cil(args):
50 """Builds a sepolicy CIL (Common Intermediate Language) file.
51
52 This functions invokes some host utils (e.g., secilc, checkpolicy,
53 version_sepolicy) to generate a .cil file.
54
55 Args:
56 args: the parsed command arguments.
57 """
58 # Determines the raw CIL file name.
59 input_file_name = os.path.splitext(args.input_policy_conf)[0]
60 raw_cil_file = input_file_name + '_raw.cil'
61 # Builds the raw CIL.
62 file_utils.make_parent_dirs(raw_cil_file)
63 checkpolicy_cmd = [args.checkpolicy_env]
64 checkpolicy_cmd += [os.path.join(args.android_host_path, 'checkpolicy'),
65 '-C', '-M', '-c', args.policy_vers,
66 '-o', raw_cil_file, args.input_policy_conf]
67 # Using shell=True to setup args.checkpolicy_env variables.
68 run_host_command(' '.join(checkpolicy_cmd), shell=True)
69 file_utils.filter_out([args.reqd_mask], raw_cil_file)
70
71 # Builds the output CIL by versioning the above raw CIL.
72 output_file = args.output_cil
73 if output_file is None:
74 output_file = input_file_name + '.cil'
75 file_utils.make_parent_dirs(output_file)
76
77 run_host_command([os.path.join(args.android_host_path, 'version_policy'),
78 '-b', args.base_policy, '-t', raw_cil_file,
79 '-n', args.treble_sepolicy_vers, '-o', output_file])
80 if args.filter_out_files:
81 file_utils.filter_out(args.filter_out_files, output_file)
82
83 # Tests that the output file can be merged with the given CILs.
84 if args.dependent_cils:
85 merge_cmd = [os.path.join(args.android_host_path, 'secilc'),
86 '-m', '-M', 'true', '-G', '-N', '-c', args.policy_vers]
87 merge_cmd += args.dependent_cils # the give CILs to merge
88 merge_cmd += [output_file, '-o', '/dev/null', '-f', '/dev/null']
89 run_host_command(merge_cmd)
90
91
92def setup_build_cil(subparsers):
93 """Sets up command args for 'build_cil' command."""
94
95 # Required arguments.
96 parser = subparsers.add_parser('build_cil', help='build CIL files')
97 parser.add_argument('-i', '--input_policy_conf', required=True,
98 help='source policy.conf')
99 parser.add_argument('-m', '--reqd_mask', required=True,
100 help='the bare minimum policy.conf to use checkpolicy')
101 parser.add_argument('-b', '--base_policy', required=True,
102 help='base policy for versioning')
103 parser.add_argument('-t', '--treble_sepolicy_vers', required=True,
104 help='the version number to use for Treble-OTA')
105 parser.add_argument('-p', '--policy_vers', required=True,
106 help='SELinux policy version')
107
108 # Optional arguments.
109 parser.add_argument('-c', '--checkpolicy_env',
110 help='environment variables passed to checkpolicy')
111 parser.add_argument('-f', '--filter_out_files', nargs='+',
112 help='the pattern files to filter out the output cil')
113 parser.add_argument('-d', '--dependent_cils', nargs='+',
114 help=('check the output file can be merged with '
115 'the dependent cil files'))
116 parser.add_argument('-o', '--output_cil', help='the output cil file')
117
118 # The function that performs the actual works.
119 parser.set_defaults(func=do_build_cil)
120
121
122def run(argv):
123 """Sets up command parser and execuates sub-command."""
124 parser = argparse.ArgumentParser()
125
126 # Adds top-level arguments.
127 parser.add_argument('-a', '--android_host_path', default='',
128 help='a path to host out executables')
129
130 # Adds subparsers for each COMMAND.
131 subparsers = parser.add_subparsers(title='COMMAND')
132 for command in _SUPPORTED_COMMANDS:
133 globals()['setup_' + command](subparsers)
134
135 args = parser.parse_args(argv[1:])
136 args.func(args)
137
138
139if __name__ == '__main__':
140 run(sys.argv)
diff --git a/build/file_utils.py b/build/file_utils.py
new file mode 100644
index 00000000..1559a9b9
--- /dev/null
+++ b/build/file_utils.py
@@ -0,0 +1,49 @@
1# Copyright 2018 - The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""File-related utilities."""
16
17
18import os
19import shutil
20import tempfile
21
22
23def make_parent_dirs(file_path):
24 """Creates parent directories for the file_path."""
25 if os.path.exists(file_path):
26 return
27
28 parent_dir = os.path.dirname(file_path)
29 if parent_dir and not os.path.exists(parent_dir):
30 os.makedirs(parent_dir)
31
32
33def filter_out(pattern_files, input_file):
34 """"Removes lines in input_file that match any line in pattern_files."""
35
36 # Prepares patterns.
37 patterns = []
38 for f in pattern_files:
39 patterns.extend(open(f).readlines())
40
41 # Copy lines that are not in the pattern.
42 tmp_output = tempfile.NamedTemporaryFile()
43 with open(input_file, 'r') as in_file:
44 tmp_output.writelines(line for line in in_file.readlines()
45 if line not in patterns)
46 tmp_output.flush()
47
48 # Replaces the input_file.
49 shutil.copyfile(tmp_output.name, input_file)