blob: 4ad5bcab41ef26311289956766d4b813f5239be5 [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
Geremy Condra5b5f4952014-05-05 22:19:37 -070029import tempfile
Ying Wangbd93d422011-10-28 17:02:30 -070030
Doug Zongker5fad2032014-02-24 08:13:45 -080031import simg_map
32
Ying Wang69e9b4d2012-11-26 18:10:23 -080033def RunCommand(cmd):
34 """ Echo and run the given command
35
36 Args:
37 cmd: the command represented as a list of strings.
38 Returns:
39 The exit code.
40 """
41 print "Running: ", " ".join(cmd)
42 p = subprocess.Popen(cmd)
43 p.communicate()
44 return p.returncode
Ying Wangbd93d422011-10-28 17:02:30 -070045
Geremy Condrafd6f7512013-06-16 17:26:08 -070046def GetVerityTreeSize(partition_size):
Colin Cross477cf2b2014-04-16 18:49:56 -070047 cmd = "build_verity_tree -s %d"
Geremy Condrafd6f7512013-06-16 17:26:08 -070048 cmd %= partition_size
49 status, output = commands.getstatusoutput(cmd)
50 if status:
51 print output
52 return False, 0
53 return True, int(output)
54
55def GetVerityMetadataSize(partition_size):
56 cmd = "system/extras/verity/build_verity_metadata.py -s %d"
57 cmd %= partition_size
58 status, output = commands.getstatusoutput(cmd)
59 if status:
60 print output
61 return False, 0
62 return True, int(output)
63
64def AdjustPartitionSizeForVerity(partition_size):
65 """Modifies the provided partition size to account for the verity metadata.
66
67 This information is used to size the created image appropriately.
68 Args:
69 partition_size: the size of the partition to be verified.
70 Returns:
71 The size of the partition adjusted for verity metadata.
72 """
73 success, verity_tree_size = GetVerityTreeSize(partition_size)
74 if not success:
75 return 0;
76 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
77 if not success:
78 return 0
79 return partition_size - verity_tree_size - verity_metadata_size
80
Colin Cross477cf2b2014-04-16 18:49:56 -070081def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
82 cmd = ("build_verity_tree %s %s" % (sparse_image_path, verity_image_path))
Geremy Condrafd6f7512013-06-16 17:26:08 -070083 print cmd
84 status, output = commands.getstatusoutput(cmd)
85 if status:
86 print "Could not build verity tree! Error: %s" % output
87 return False
88 root, salt = output.split()
89 prop_dict["verity_root_hash"] = root
90 prop_dict["verity_salt"] = salt
91 return True
92
93def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
94 block_device, signer_path, key):
95 cmd = ("system/extras/verity/build_verity_metadata.py %s %s %s %s %s %s %s" %
96 (image_size,
97 verity_metadata_path,
98 root_hash,
99 salt,
100 block_device,
101 signer_path,
102 key))
103 print cmd
104 status, output = commands.getstatusoutput(cmd)
105 if status:
106 print "Could not build verity metadata! Error: %s" % output
107 return False
108 return True
109
110def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
111 """Appends the unsparse image to the given sparse image.
112
113 Args:
114 sparse_image_path: the path to the (sparse) image
115 unsparse_image_path: the path to the (unsparse) image
116 Returns:
117 True on success, False on failure.
118 """
119 cmd = "append2simg %s %s"
120 cmd %= (sparse_image_path, unsparse_image_path)
121 print cmd
122 status, output = commands.getstatusoutput(cmd)
123 if status:
124 print "%s: %s" % (error_message, output)
125 return False
126 return True
127
128def BuildVerifiedImage(data_image_path, verity_image_path, verity_metadata_path):
129 if not Append2Simg(data_image_path, verity_metadata_path, "Could not append verity metadata!"):
130 return False
131 if not Append2Simg(data_image_path, verity_image_path, "Could not append verity tree!"):
132 return False
133 return True
134
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800135def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700136 img_dir = os.path.dirname(sparse_image_path)
137 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
138 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
139 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800140 if replace:
141 os.unlink(unsparse_image_path)
142 else:
143 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700144 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
145 exit_code = RunCommand(inflate_command)
146 if exit_code != 0:
147 os.remove(unsparse_image_path)
148 return False, None
149 return True, unsparse_image_path
150
Doug Zongker5fad2032014-02-24 08:13:45 -0800151def MappedUnsparseImage(sparse_image_path, unsparse_image_path,
152 map_path, mapped_unsparse_image_path):
153 if simg_map.ComputeMap(sparse_image_path, unsparse_image_path,
154 map_path, mapped_unsparse_image_path):
155 return False
156 return True
157
Geremy Condrafd6f7512013-06-16 17:26:08 -0700158def MakeVerityEnabledImage(out_file, prop_dict):
159 """Creates an image that is verifiable using dm-verity.
160
161 Args:
162 out_file: the location to write the verifiable image at
163 prop_dict: a dictionary of properties required for image creation and verification
164 Returns:
165 True on success, False otherwise.
166 """
167 # get properties
168 image_size = prop_dict["partition_size"]
Geremy Condrafd6f7512013-06-16 17:26:08 -0700169 block_dev = prop_dict["verity_block_device"]
170 signer_key = prop_dict["verity_key"]
171 signer_path = prop_dict["verity_signer_cmd"]
172
173 # make a tempdir
Geremy Condra5b5f4952014-05-05 22:19:37 -0700174 tempdir_name = tempfile.mkdtemp(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700175
176 # get partial image paths
177 verity_image_path = os.path.join(tempdir_name, "verity.img")
178 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700179
180 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700181 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700182 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700183 return False
184
185 # build the metadata blocks
186 root_hash = prop_dict["verity_root_hash"]
187 salt = prop_dict["verity_salt"]
188 if not BuildVerityMetadata(image_size,
189 verity_metadata_path,
190 root_hash,
191 salt,
192 block_dev,
193 signer_path,
194 signer_key):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700195 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700196 return False
197
198 # build the full verified image
199 if not BuildVerifiedImage(out_file,
200 verity_image_path,
201 verity_metadata_path):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700202 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700203 return False
204
Geremy Condra5b5f4952014-05-05 22:19:37 -0700205 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700206 return True
207
Ying Wangbd93d422011-10-28 17:02:30 -0700208def BuildImage(in_dir, prop_dict, out_file):
209 """Build an image to out_file from in_dir with property prop_dict.
210
211 Args:
212 in_dir: path of input directory.
213 prop_dict: property dictionary.
214 out_file: path of the output image file.
215
216 Returns:
217 True iff the image is built successfully.
218 """
219 build_command = []
220 fs_type = prop_dict.get("fs_type", "")
Ying Wang69e9b4d2012-11-26 18:10:23 -0800221 run_fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700222
Geremy Condra5b5f4952014-05-05 22:19:37 -0700223 is_verity_partition = prop_dict.get("mount_point") == prop_dict.get("verity_mountpoint")
224 verity_supported = prop_dict.get("verity") == "true"
Geremy Condrafd6f7512013-06-16 17:26:08 -0700225 # adjust the partition size to make room for the hashes if this is to be verified
Geremy Condra5b5f4952014-05-05 22:19:37 -0700226 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700227 partition_size = int(prop_dict.get("partition_size"))
228 adjusted_size = AdjustPartitionSizeForVerity(partition_size)
229 if not adjusted_size:
230 return False
231 prop_dict["partition_size"] = str(adjusted_size)
232 prop_dict["original_partition_size"] = str(partition_size)
233
Ying Wangbd93d422011-10-28 17:02:30 -0700234 if fs_type.startswith("ext"):
235 build_command = ["mkuserimg.sh"]
236 if "extfs_sparse_flag" in prop_dict:
237 build_command.append(prop_dict["extfs_sparse_flag"])
Ying Wang69e9b4d2012-11-26 18:10:23 -0800238 run_fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700239 build_command.extend([in_dir, out_file, fs_type,
240 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800241 build_command.append(prop_dict["partition_size"])
242 if "timestamp" in prop_dict:
243 build_command.extend(["-T", str(prop_dict["timestamp"])])
Kenny Rootf32dc712012-04-08 10:42:34 -0700244 if "selinux_fc" in prop_dict:
245 build_command.append(prop_dict["selinux_fc"])
Ying Wangbd93d422011-10-28 17:02:30 -0700246 else:
247 build_command = ["mkyaffs2image", "-f"]
248 if prop_dict.get("mkyaffs2_extra_flags", None):
249 build_command.extend(prop_dict["mkyaffs2_extra_flags"].split())
250 build_command.append(in_dir)
251 build_command.append(out_file)
Kenny Rootf32dc712012-04-08 10:42:34 -0700252 if "selinux_fc" in prop_dict:
253 build_command.append(prop_dict["selinux_fc"])
254 build_command.append(prop_dict["mount_point"])
Ying Wangbd93d422011-10-28 17:02:30 -0700255
Ying Wang69e9b4d2012-11-26 18:10:23 -0800256 exit_code = RunCommand(build_command)
257 if exit_code != 0:
258 return False
259
Geremy Condrafd6f7512013-06-16 17:26:08 -0700260 # create the verified image if this is to be verified
Geremy Condra5b5f4952014-05-05 22:19:37 -0700261 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700262 if not MakeVerityEnabledImage(out_file, prop_dict):
263 return False
264
Ying Wang6a42a252013-02-27 13:54:02 -0800265 if run_fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800266 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700267 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800268 return False
269
270 # Run e2fsck on the inflated image file
271 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
272 exit_code = RunCommand(e2fsck_command)
273
274 os.remove(unsparse_image)
275
276 return exit_code == 0
Ying Wangbd93d422011-10-28 17:02:30 -0700277
278
279def ImagePropFromGlobalDict(glob_dict, mount_point):
280 """Build an image property dictionary from the global dictionary.
281
282 Args:
283 glob_dict: the global dictionary from the build system.
284 mount_point: such as "system", "data" etc.
285 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800286 d = {}
287 if "build.prop" in glob_dict:
288 bp = glob_dict["build.prop"]
289 if "ro.build.date.utc" in bp:
290 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700291
292 def copy_prop(src_p, dest_p):
293 if src_p in glob_dict:
294 d[dest_p] = str(glob_dict[src_p])
295
Ying Wangbd93d422011-10-28 17:02:30 -0700296 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700297 "extfs_sparse_flag",
298 "mkyaffs2_extra_flags",
Kenny Rootf32dc712012-04-08 10:42:34 -0700299 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800300 "skip_fsck",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700301 "verity",
302 "verity_block_device",
303 "verity_key",
Geremy Condra5b5f4952014-05-05 22:19:37 -0700304 "verity_signer_cmd",
305 "verity_mountpoint"
Ying Wangbd93d422011-10-28 17:02:30 -0700306 )
307 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700308 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700309
310 d["mount_point"] = mount_point
311 if mount_point == "system":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700312 copy_prop("fs_type", "fs_type")
313 copy_prop("system_size", "partition_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700314 elif mount_point == "data":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700315 copy_prop("fs_type", "fs_type")
316 copy_prop("userdata_size", "partition_size")
317 elif mount_point == "cache":
318 copy_prop("cache_fs_type", "fs_type")
319 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700320 elif mount_point == "vendor":
321 copy_prop("vendor_fs_type", "fs_type")
322 copy_prop("vendor_size", "partition_size")
Ying Wangb8888432014-03-11 17:13:27 -0700323 elif mount_point == "oem":
324 copy_prop("fs_type", "fs_type")
325 copy_prop("oem_size", "partition_size")
Ying Wangbd93d422011-10-28 17:02:30 -0700326
327 return d
328
329
330def LoadGlobalDict(filename):
331 """Load "name=value" pairs from filename"""
332 d = {}
333 f = open(filename)
334 for line in f:
335 line = line.strip()
336 if not line or line.startswith("#"):
337 continue
338 k, v = line.split("=", 1)
339 d[k] = v
340 f.close()
341 return d
342
343
344def main(argv):
345 if len(argv) != 3:
346 print __doc__
347 sys.exit(1)
348
349 in_dir = argv[0]
350 glob_dict_file = argv[1]
351 out_file = argv[2]
352
353 glob_dict = LoadGlobalDict(glob_dict_file)
354 image_filename = os.path.basename(out_file)
355 mount_point = ""
356 if image_filename == "system.img":
357 mount_point = "system"
358 elif image_filename == "userdata.img":
359 mount_point = "data"
Ying Wang9f8e8db2011-11-04 11:37:01 -0700360 elif image_filename == "cache.img":
361 mount_point = "cache"
Ying Wanga0febe52013-03-20 11:02:05 -0700362 elif image_filename == "vendor.img":
363 mount_point = "vendor"
Ying Wangb8888432014-03-11 17:13:27 -0700364 elif image_filename == "oem.img":
365 mount_point = "oem"
Ying Wang9f8e8db2011-11-04 11:37:01 -0700366 else:
367 print >> sys.stderr, "error: unknown image file name ", image_filename
368 exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700369
370 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
371 if not BuildImage(in_dir, image_properties, out_file):
372 print >> sys.stderr, "error: failed to build %s from %s" % (out_file, in_dir)
373 exit(1)
374
375
376if __name__ == '__main__':
377 main(sys.argv[1:])