blob: 9f7119412217eafde5d8a695a4c0c3c26f9bf96c [file] [log] [blame]
Ying Wangbd93d422011-10-28 17:02:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2011 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Build image output_image_file from input_directory and properties_file.
19
20Usage: build_image input_directory properties_file output_image_file
21
22"""
23import os
Ying Wang69e9b4d2012-11-26 18:10:23 -080024import os.path
Ying Wangbd93d422011-10-28 17:02:30 -070025import subprocess
26import sys
Geremy Condrafd6f7512013-06-16 17:26:08 -070027import commands
28import shutil
Ying Wangbd93d422011-10-28 17:02:30 -070029
Ying Wang69e9b4d2012-11-26 18:10:23 -080030def RunCommand(cmd):
31 """ Echo and run the given command
32
33 Args:
34 cmd: the command represented as a list of strings.
35 Returns:
36 The exit code.
37 """
38 print "Running: ", " ".join(cmd)
39 p = subprocess.Popen(cmd)
40 p.communicate()
41 return p.returncode
Ying Wangbd93d422011-10-28 17:02:30 -070042
Geremy Condrafd6f7512013-06-16 17:26:08 -070043def GetVerityTreeSize(partition_size):
44 cmd = "system/extras/verity/build_verity_tree.py -s %d"
45 cmd %= partition_size
46 status, output = commands.getstatusoutput(cmd)
47 if status:
48 print output
49 return False, 0
50 return True, int(output)
51
52def GetVerityMetadataSize(partition_size):
53 cmd = "system/extras/verity/build_verity_metadata.py -s %d"
54 cmd %= partition_size
55 status, output = commands.getstatusoutput(cmd)
56 if status:
57 print output
58 return False, 0
59 return True, int(output)
60
61def AdjustPartitionSizeForVerity(partition_size):
62 """Modifies the provided partition size to account for the verity metadata.
63
64 This information is used to size the created image appropriately.
65 Args:
66 partition_size: the size of the partition to be verified.
67 Returns:
68 The size of the partition adjusted for verity metadata.
69 """
70 success, verity_tree_size = GetVerityTreeSize(partition_size)
71 if not success:
72 return 0;
73 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
74 if not success:
75 return 0
76 return partition_size - verity_tree_size - verity_metadata_size
77
78def BuildVerityTree(unsparse_image_path, verity_image_path, partition_size, prop_dict):
79 cmd = ("system/extras/verity/build_verity_tree.py %s %s %d" %
80 (unsparse_image_path, verity_image_path, partition_size))
81 print cmd
82 status, output = commands.getstatusoutput(cmd)
83 if status:
84 print "Could not build verity tree! Error: %s" % output
85 return False
86 root, salt = output.split()
87 prop_dict["verity_root_hash"] = root
88 prop_dict["verity_salt"] = salt
89 return True
90
91def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
92 block_device, signer_path, key):
93 cmd = ("system/extras/verity/build_verity_metadata.py %s %s %s %s %s %s %s" %
94 (image_size,
95 verity_metadata_path,
96 root_hash,
97 salt,
98 block_device,
99 signer_path,
100 key))
101 print cmd
102 status, output = commands.getstatusoutput(cmd)
103 if status:
104 print "Could not build verity metadata! Error: %s" % output
105 return False
106 return True
107
108def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
109 """Appends the unsparse image to the given sparse image.
110
111 Args:
112 sparse_image_path: the path to the (sparse) image
113 unsparse_image_path: the path to the (unsparse) image
114 Returns:
115 True on success, False on failure.
116 """
117 cmd = "append2simg %s %s"
118 cmd %= (sparse_image_path, unsparse_image_path)
119 print cmd
120 status, output = commands.getstatusoutput(cmd)
121 if status:
122 print "%s: %s" % (error_message, output)
123 return False
124 return True
125
126def BuildVerifiedImage(data_image_path, verity_image_path, verity_metadata_path):
127 if not Append2Simg(data_image_path, verity_metadata_path, "Could not append verity metadata!"):
128 return False
129 if not Append2Simg(data_image_path, verity_image_path, "Could not append verity tree!"):
130 return False
131 return True
132
133def UnsparseImage(sparse_image_path):
134 img_dir = os.path.dirname(sparse_image_path)
135 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
136 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
137 if os.path.exists(unsparse_image_path):
138 return True, unsparse_image_path
139 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
140 exit_code = RunCommand(inflate_command)
141 if exit_code != 0:
142 os.remove(unsparse_image_path)
143 return False, None
144 return True, unsparse_image_path
145
146def MakeVerityEnabledImage(out_file, prop_dict):
147 """Creates an image that is verifiable using dm-verity.
148
149 Args:
150 out_file: the location to write the verifiable image at
151 prop_dict: a dictionary of properties required for image creation and verification
152 Returns:
153 True on success, False otherwise.
154 """
155 # get properties
156 image_size = prop_dict["partition_size"]
157 part_size = int(prop_dict["original_partition_size"])
158 block_dev = prop_dict["verity_block_device"]
159 signer_key = prop_dict["verity_key"]
160 signer_path = prop_dict["verity_signer_cmd"]
161
162 # make a tempdir
163 tempdir_name = os.path.join(os.path.dirname(out_file), "verity_images")
164 if os.path.exists(tempdir_name):
165 shutil.rmtree(tempdir_name)
166 os.mkdir(tempdir_name)
167
168 # get partial image paths
169 verity_image_path = os.path.join(tempdir_name, "verity.img")
170 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
171 success, unsparse_image_path = UnsparseImage(out_file)
172 if not success:
173 shutil.rmtree(tempdir_name)
174 return False
175
176 # build the verity tree and get the root hash and salt
177 if not BuildVerityTree(unsparse_image_path, verity_image_path, part_size, prop_dict):
178 shutil.rmtree(tempdir_name)
179 return False
180
181 # build the metadata blocks
182 root_hash = prop_dict["verity_root_hash"]
183 salt = prop_dict["verity_salt"]
184 if not BuildVerityMetadata(image_size,
185 verity_metadata_path,
186 root_hash,
187 salt,
188 block_dev,
189 signer_path,
190 signer_key):
191 shutil.rmtree(tempdir_name)
192 return False
193
194 # build the full verified image
195 if not BuildVerifiedImage(out_file,
196 verity_image_path,
197 verity_metadata_path):
198 shutil.rmtree(tempdir_name)
199 return False
200
201 shutil.rmtree(tempdir_name)
202 return True
203
Ying Wangbd93d422011-10-28 17:02:30 -0700204def BuildImage(in_dir, prop_dict, out_file):
205 """Build an image to out_file from in_dir with property prop_dict.
206
207 Args:
208 in_dir: path of input directory.
209 prop_dict: property dictionary.
210 out_file: path of the output image file.
211
212 Returns:
213 True iff the image is built successfully.
214 """
215 build_command = []
216 fs_type = prop_dict.get("fs_type", "")
Ying Wang69e9b4d2012-11-26 18:10:23 -0800217 run_fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700218
219 # adjust the partition size to make room for the hashes if this is to be verified
220 if prop_dict.get("verity") == "true":
221 partition_size = int(prop_dict.get("partition_size"))
222 adjusted_size = AdjustPartitionSizeForVerity(partition_size)
223 if not adjusted_size:
224 return False
225 prop_dict["partition_size"] = str(adjusted_size)
226 prop_dict["original_partition_size"] = str(partition_size)
227
Ying Wangbd93d422011-10-28 17:02:30 -0700228 if fs_type.startswith("ext"):
229 build_command = ["mkuserimg.sh"]
230 if "extfs_sparse_flag" in prop_dict:
231 build_command.append(prop_dict["extfs_sparse_flag"])
Ying Wang69e9b4d2012-11-26 18:10:23 -0800232 run_fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700233 build_command.extend([in_dir, out_file, fs_type,
234 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800235 build_command.append(prop_dict["partition_size"])
236 if "timestamp" in prop_dict:
237 build_command.extend(["-T", str(prop_dict["timestamp"])])
Kenny Rootf32dc712012-04-08 10:42:34 -0700238 if "selinux_fc" in prop_dict:
239 build_command.append(prop_dict["selinux_fc"])
Ying Wangbd93d422011-10-28 17:02:30 -0700240 else:
241 build_command = ["mkyaffs2image", "-f"]
242 if prop_dict.get("mkyaffs2_extra_flags", None):
243 build_command.extend(prop_dict["mkyaffs2_extra_flags"].split())
244 build_command.append(in_dir)
245 build_command.append(out_file)
Kenny Rootf32dc712012-04-08 10:42:34 -0700246 if "selinux_fc" in prop_dict:
247 build_command.append(prop_dict["selinux_fc"])
248 build_command.append(prop_dict["mount_point"])
Ying Wangbd93d422011-10-28 17:02:30 -0700249
Ying Wang69e9b4d2012-11-26 18:10:23 -0800250 exit_code = RunCommand(build_command)
251 if exit_code != 0:
252 return False
253
Geremy Condrafd6f7512013-06-16 17:26:08 -0700254 # create the verified image if this is to be verified
255 if prop_dict.get("verity") == "true":
256 if not MakeVerityEnabledImage(out_file, prop_dict):
257 return False
258
Ying Wang6a42a252013-02-27 13:54:02 -0800259 if run_fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra1f504002013-11-17 18:10:55 -0800260 success, unsparse_image = UnsparseImage(out_file)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700261 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800262 return False
263
264 # Run e2fsck on the inflated image file
265 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
266 exit_code = RunCommand(e2fsck_command)
267
268 os.remove(unsparse_image)
269
270 return exit_code == 0
Ying Wangbd93d422011-10-28 17:02:30 -0700271
272
273def ImagePropFromGlobalDict(glob_dict, mount_point):
274 """Build an image property dictionary from the global dictionary.
275
276 Args:
277 glob_dict: the global dictionary from the build system.
278 mount_point: such as "system", "data" etc.
279 """
Doug Zongker850b8072013-12-05 15:54:55 -0800280 d = {"timestamp": glob_dict["build.prop"].get("ro.build.date.utc", -1)}
Ying Wang9f8e8db2011-11-04 11:37:01 -0700281
282 def copy_prop(src_p, dest_p):
283 if src_p in glob_dict:
284 d[dest_p] = str(glob_dict[src_p])
285
Ying Wangbd93d422011-10-28 17:02:30 -0700286 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700287 "extfs_sparse_flag",
288 "mkyaffs2_extra_flags",
Kenny Rootf32dc712012-04-08 10:42:34 -0700289 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800290 "skip_fsck",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700291 "verity",
292 "verity_block_device",
293 "verity_key",
294 "verity_signer_cmd"
Ying Wangbd93d422011-10-28 17:02:30 -0700295 )
296 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700297 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700298
299 d["mount_point"] = mount_point
300 if mount_point == "system":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700301 copy_prop("fs_type", "fs_type")
302 copy_prop("system_size", "partition_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700303 elif mount_point == "data":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700304 copy_prop("fs_type", "fs_type")
305 copy_prop("userdata_size", "partition_size")
306 elif mount_point == "cache":
307 copy_prop("cache_fs_type", "fs_type")
308 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700309 elif mount_point == "vendor":
310 copy_prop("vendor_fs_type", "fs_type")
311 copy_prop("vendor_size", "partition_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700312
313 return d
314
315
316def LoadGlobalDict(filename):
317 """Load "name=value" pairs from filename"""
318 d = {}
319 f = open(filename)
320 for line in f:
321 line = line.strip()
322 if not line or line.startswith("#"):
323 continue
324 k, v = line.split("=", 1)
325 d[k] = v
326 f.close()
327 return d
328
329
330def main(argv):
331 if len(argv) != 3:
332 print __doc__
333 sys.exit(1)
334
335 in_dir = argv[0]
336 glob_dict_file = argv[1]
337 out_file = argv[2]
338
339 glob_dict = LoadGlobalDict(glob_dict_file)
340 image_filename = os.path.basename(out_file)
341 mount_point = ""
342 if image_filename == "system.img":
343 mount_point = "system"
344 elif image_filename == "userdata.img":
345 mount_point = "data"
Ying Wang9f8e8db2011-11-04 11:37:01 -0700346 elif image_filename == "cache.img":
347 mount_point = "cache"
Ying Wanga0febe52013-03-20 11:02:05 -0700348 elif image_filename == "vendor.img":
349 mount_point = "vendor"
Ying Wang9f8e8db2011-11-04 11:37:01 -0700350 else:
351 print >> sys.stderr, "error: unknown image file name ", image_filename
352 exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700353
354 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
355 if not BuildImage(in_dir, image_properties, out_file):
356 print >> sys.stderr, "error: failed to build %s from %s" % (out_file, in_dir)
357 exit(1)
358
359
360if __name__ == '__main__':
361 main(sys.argv[1:])