blob: e6ad18b8219e1c1bff87674cd75e2b9341cf421c [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
Tao Baoc7a6f1e2015-06-23 11:16:05 -070025import re
Ying Wangbd93d422011-10-28 17:02:30 -070026import subprocess
27import sys
Geremy Condrafd6f7512013-06-16 17:26:08 -070028import commands
Baligh Uddin601ddea2015-06-09 15:48:14 -070029import common
Geremy Condrafd6f7512013-06-16 17:26:08 -070030import shutil
Geremy Condra5b5f4952014-05-05 22:19:37 -070031import tempfile
Ying Wangbd93d422011-10-28 17:02:30 -070032
Baligh Uddin601ddea2015-06-09 15:48:14 -070033OPTIONS = common.OPTIONS
34
Geremy Condrae8e982a2014-05-16 19:14:30 -070035FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
Sami Tolvanenf99b5312015-05-20 07:30:57 +010036BLOCK_SIZE = 4096
Geremy Condrae8e982a2014-05-16 19:14:30 -070037
Ying Wang69e9b4d2012-11-26 18:10:23 -080038def RunCommand(cmd):
Tao Baoc7a6f1e2015-06-23 11:16:05 -070039 """Echo and run the given command.
Ying Wang69e9b4d2012-11-26 18:10:23 -080040
41 Args:
42 cmd: the command represented as a list of strings.
43 Returns:
Tao Baoc7a6f1e2015-06-23 11:16:05 -070044 A tuple of the output and the exit code.
Ying Wang69e9b4d2012-11-26 18:10:23 -080045 """
46 print "Running: ", " ".join(cmd)
Tao Baoc7a6f1e2015-06-23 11:16:05 -070047 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
48 output, _ = p.communicate()
49 print "%s" % (output.rstrip(),)
50 return (output, p.returncode)
Ying Wangbd93d422011-10-28 17:02:30 -070051
Sami Tolvanenf99b5312015-05-20 07:30:57 +010052def GetVerityFECSize(partition_size):
53 cmd = "fec -s %d" % partition_size
54 status, output = commands.getstatusoutput(cmd)
55 if status:
56 print output
57 return False, 0
58 return True, int(output)
59
Geremy Condrafd6f7512013-06-16 17:26:08 -070060def GetVerityTreeSize(partition_size):
Colin Cross477cf2b2014-04-16 18:49:56 -070061 cmd = "build_verity_tree -s %d"
Geremy Condrafd6f7512013-06-16 17:26:08 -070062 cmd %= partition_size
63 status, output = commands.getstatusoutput(cmd)
64 if status:
65 print output
66 return False, 0
67 return True, int(output)
68
69def GetVerityMetadataSize(partition_size):
70 cmd = "system/extras/verity/build_verity_metadata.py -s %d"
71 cmd %= partition_size
Baligh Uddin601ddea2015-06-09 15:48:14 -070072
Geremy Condrafd6f7512013-06-16 17:26:08 -070073 status, output = commands.getstatusoutput(cmd)
74 if status:
75 print output
76 return False, 0
77 return True, int(output)
78
Sami Tolvanenf99b5312015-05-20 07:30:57 +010079def GetVeritySize(partition_size, fec_supported):
80 success, verity_tree_size = GetVerityTreeSize(partition_size)
81 if not success:
82 return 0
83 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
84 if not success:
85 return 0
86 verity_size = verity_tree_size + verity_metadata_size
87 if fec_supported:
88 success, fec_size = GetVerityFECSize(partition_size + verity_size)
89 if not success:
90 return 0
91 return verity_size + fec_size
92 return verity_size
93
94def AdjustPartitionSizeForVerity(partition_size, fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -070095 """Modifies the provided partition size to account for the verity metadata.
96
97 This information is used to size the created image appropriately.
98 Args:
99 partition_size: the size of the partition to be verified.
100 Returns:
101 The size of the partition adjusted for verity metadata.
102 """
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100103 key = "%d %d" % (partition_size, fec_supported)
104 if key in AdjustPartitionSizeForVerity.results:
105 return AdjustPartitionSizeForVerity.results[key]
106
107 hi = partition_size
108 if hi % BLOCK_SIZE != 0:
109 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
110
111 # verity tree and fec sizes depend on the partition size, which
112 # means this estimate is always going to be unnecessarily small
113 lo = partition_size - GetVeritySize(hi, fec_supported)
114 result = lo
115
116 # do a binary search for the optimal size
117 while lo < hi:
118 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
119 size = i + GetVeritySize(i, fec_supported)
120 if size <= partition_size:
121 if result < i:
122 result = i
123 lo = i + BLOCK_SIZE
124 else:
125 hi = i
126
127 AdjustPartitionSizeForVerity.results[key] = result
128 return result
129
130AdjustPartitionSizeForVerity.results = {}
131
Sami Tolvanen4a060042015-12-18 15:50:25 +0000132def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path):
133 cmd = "fec -e %s %s %s" % (sparse_image_path, verity_path, verity_fec_path)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100134 print cmd
135 status, output = commands.getstatusoutput(cmd)
136 if status:
137 print "Could not build FEC data! Error: %s" % output
138 return False
139 return True
Geremy Condrafd6f7512013-06-16 17:26:08 -0700140
Colin Cross477cf2b2014-04-16 18:49:56 -0700141def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
Dan Albert8b72aef2015-03-23 19:13:21 -0700142 cmd = "build_verity_tree -A %s %s %s" % (
143 FIXED_SALT, sparse_image_path, verity_image_path)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700144 print cmd
145 status, output = commands.getstatusoutput(cmd)
146 if status:
147 print "Could not build verity tree! Error: %s" % output
148 return False
149 root, salt = output.split()
150 prop_dict["verity_root_hash"] = root
151 prop_dict["verity_salt"] = salt
152 return True
153
154def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
155 block_device, signer_path, key):
Dan Albert8b72aef2015-03-23 19:13:21 -0700156 cmd_template = (
157 "system/extras/verity/build_verity_metadata.py %s %s %s %s %s %s %s")
158 cmd = cmd_template % (image_size, verity_metadata_path, root_hash, salt,
159 block_device, signer_path, key)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700160 print cmd
161 status, output = commands.getstatusoutput(cmd)
162 if status:
163 print "Could not build verity metadata! Error: %s" % output
164 return False
165 return True
166
167def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
168 """Appends the unsparse image to the given sparse image.
169
170 Args:
171 sparse_image_path: the path to the (sparse) image
172 unsparse_image_path: the path to the (unsparse) image
173 Returns:
174 True on success, False on failure.
175 """
176 cmd = "append2simg %s %s"
177 cmd %= (sparse_image_path, unsparse_image_path)
178 print cmd
179 status, output = commands.getstatusoutput(cmd)
180 if status:
181 print "%s: %s" % (error_message, output)
182 return False
183 return True
184
Sami Tolvanenff914f52015-12-18 13:24:56 +0000185def Append(target, file_to_append, error_message):
186 cmd = 'cat %s >> %s' % (file_to_append, target)
187 print cmd
188 status, output = commands.getstatusoutput(cmd)
189 if status:
190 print "%s: %s" % (error_message, output)
191 return False
192 return True
193
Dan Albert8b72aef2015-03-23 19:13:21 -0700194def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000195 verity_metadata_path, verity_fec_path,
196 fec_supported):
Sami Tolvanenff914f52015-12-18 13:24:56 +0000197 if not Append(verity_image_path, verity_metadata_path,
198 "Could not append verity metadata!"):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700199 return False
Sami Tolvanen4a060042015-12-18 15:50:25 +0000200
201 if fec_supported:
202 # build FEC for the entire partition, including metadata
203 if not BuildVerityFEC(data_image_path, verity_image_path,
204 verity_fec_path):
205 return False
206
207 if not Append(verity_image_path, verity_fec_path, "Could not append FEC!"):
208 return False
209
Sami Tolvanenff914f52015-12-18 13:24:56 +0000210 if not Append2Simg(data_image_path, verity_image_path,
211 "Could not append verity data!"):
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100212 return False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700213 return True
214
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800215def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700216 img_dir = os.path.dirname(sparse_image_path)
217 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
218 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
219 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800220 if replace:
221 os.unlink(unsparse_image_path)
222 else:
223 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700224 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700225 (_, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700226 if exit_code != 0:
227 os.remove(unsparse_image_path)
228 return False, None
229 return True, unsparse_image_path
230
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100231def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700232 """Creates an image that is verifiable using dm-verity.
233
234 Args:
235 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700236 prop_dict: a dictionary of properties required for image creation and
237 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700238 Returns:
239 True on success, False otherwise.
240 """
241 # get properties
242 image_size = prop_dict["partition_size"]
Geremy Condrafd6f7512013-06-16 17:26:08 -0700243 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800244 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700245 if OPTIONS.verity_signer_path is not None:
246 signer_path = OPTIONS.verity_signer_path + ' '
247 signer_path += ' '.join(OPTIONS.verity_signer_args)
248 else:
249 signer_path = prop_dict["verity_signer_cmd"]
Geremy Condrafd6f7512013-06-16 17:26:08 -0700250
251 # make a tempdir
Geremy Condra5b5f4952014-05-05 22:19:37 -0700252 tempdir_name = tempfile.mkdtemp(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700253
254 # get partial image paths
255 verity_image_path = os.path.join(tempdir_name, "verity.img")
256 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100257 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700258
259 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700260 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700261 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700262 return False
263
264 # build the metadata blocks
265 root_hash = prop_dict["verity_root_hash"]
266 salt = prop_dict["verity_salt"]
Dan Albert8b72aef2015-03-23 19:13:21 -0700267 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
268 block_dev, signer_path, signer_key):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700269 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700270 return False
271
272 # build the full verified image
273 if not BuildVerifiedImage(out_file,
274 verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000275 verity_metadata_path,
276 verity_fec_path,
277 fec_supported):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700278 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700279 return False
280
Geremy Condra5b5f4952014-05-05 22:19:37 -0700281 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700282 return True
283
Thierry Strudel74a81e62015-07-09 09:54:55 -0700284def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Ying Wangbd93d422011-10-28 17:02:30 -0700285 """Build an image to out_file from in_dir with property prop_dict.
286
287 Args:
288 in_dir: path of input directory.
289 prop_dict: property dictionary.
290 out_file: path of the output image file.
Thierry Strudel74a81e62015-07-09 09:54:55 -0700291 target_out: path of the product out directory to read device specific FS config files.
Ying Wangbd93d422011-10-28 17:02:30 -0700292
293 Returns:
294 True iff the image is built successfully.
295 """
Tao Baof3282b42015-04-01 11:21:55 -0700296 # system_root_image=true: build a system.img that combines the contents of
297 # /system and the ramdisk, and can be mounted at the root of the file system.
Ying Wanga2292c92015-03-24 19:07:40 -0700298 origin_in = in_dir
299 fs_config = prop_dict.get("fs_config")
300 if (prop_dict.get("system_root_image") == "true"
301 and prop_dict["mount_point"] == "system"):
302 in_dir = tempfile.mkdtemp()
303 # Change the mount point to "/"
304 prop_dict["mount_point"] = "/"
305 if fs_config:
306 # We need to merge the fs_config files of system and ramdisk.
307 fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config",
308 suffix=".txt")
309 os.close(fd)
310 with open(merged_fs_config, "w") as fw:
311 if "ramdisk_fs_config" in prop_dict:
312 with open(prop_dict["ramdisk_fs_config"]) as fr:
313 fw.writelines(fr.readlines())
314 with open(fs_config) as fr:
315 fw.writelines(fr.readlines())
316 fs_config = merged_fs_config
317
Ying Wangbd93d422011-10-28 17:02:30 -0700318 build_command = []
319 fs_type = prop_dict.get("fs_type", "")
Ying Wang69e9b4d2012-11-26 18:10:23 -0800320 run_fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700321
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700322 fs_spans_partition = True
323 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700324 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700325
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700326 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700327 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100328 verity_fec_supported = prop_dict.get("verity_fec") == "true"
329
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700330 # Adjust the partition size to make room for the hashes if this is to be
331 # verified.
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700332 if verity_supported and is_verity_partition and fs_spans_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700333 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100334 adjusted_size = AdjustPartitionSizeForVerity(partition_size,
335 verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700336 if not adjusted_size:
337 return False
338 prop_dict["partition_size"] = str(adjusted_size)
339 prop_dict["original_partition_size"] = str(partition_size)
340
Ying Wangbd93d422011-10-28 17:02:30 -0700341 if fs_type.startswith("ext"):
342 build_command = ["mkuserimg.sh"]
343 if "extfs_sparse_flag" in prop_dict:
344 build_command.append(prop_dict["extfs_sparse_flag"])
Ying Wang69e9b4d2012-11-26 18:10:23 -0800345 run_fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700346 build_command.extend([in_dir, out_file, fs_type,
347 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800348 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800349 if "journal_size" in prop_dict:
350 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800351 if "timestamp" in prop_dict:
352 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700353 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700354 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700355 if target_out:
356 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700357 if "block_list" in prop_dict:
358 build_command.extend(["-B", prop_dict["block_list"]])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100359 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wanga2292c92015-03-24 19:07:40 -0700360 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700361 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800362 elif fs_type.startswith("squash"):
363 build_command = ["mksquashfsimage.sh"]
364 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800365 if "squashfs_sparse_flag" in prop_dict:
366 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800367 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700368 if target_out:
369 build_command.extend(["-d", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700370 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800371 build_command.extend(["-c", prop_dict["selinux_fc"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700372 if "squashfs_compressor" in prop_dict:
373 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
374 if "squashfs_compressor_opt" in prop_dict:
375 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700376 elif fs_type.startswith("f2fs"):
377 build_command = ["mkf2fsuserimg.sh"]
378 build_command.extend([out_file, prop_dict["partition_size"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700379 else:
380 build_command = ["mkyaffs2image", "-f"]
381 if prop_dict.get("mkyaffs2_extra_flags", None):
382 build_command.extend(prop_dict["mkyaffs2_extra_flags"].split())
383 build_command.append(in_dir)
384 build_command.append(out_file)
Kenny Rootf32dc712012-04-08 10:42:34 -0700385 if "selinux_fc" in prop_dict:
386 build_command.append(prop_dict["selinux_fc"])
387 build_command.append(prop_dict["mount_point"])
Ying Wangbd93d422011-10-28 17:02:30 -0700388
Ying Wanga2292c92015-03-24 19:07:40 -0700389 if in_dir != origin_in:
390 # Construct a staging directory of the root file system.
391 ramdisk_dir = prop_dict.get("ramdisk_dir")
392 if ramdisk_dir:
393 shutil.rmtree(in_dir)
394 shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
395 staging_system = os.path.join(in_dir, "system")
396 shutil.rmtree(staging_system, ignore_errors=True)
397 shutil.copytree(origin_in, staging_system, symlinks=True)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700398
399 reserved_blocks = prop_dict.get("has_ext4_reserved_blocks") == "true"
400 ext4fs_output = None
401
Ying Wanga2292c92015-03-24 19:07:40 -0700402 try:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700403 if reserved_blocks and fs_type.startswith("ext4"):
404 (ext4fs_output, exit_code) = RunCommand(build_command)
405 else:
406 (_, exit_code) = RunCommand(build_command)
Ying Wanga2292c92015-03-24 19:07:40 -0700407 finally:
408 if in_dir != origin_in:
409 # Clean up temporary directories and files.
410 shutil.rmtree(in_dir, ignore_errors=True)
411 if fs_config:
412 os.remove(fs_config)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800413 if exit_code != 0:
414 return False
415
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700416 # Bug: 21522719, 22023465
417 # There are some reserved blocks on ext4 FS (lesser of 4096 blocks and 2%).
418 # We need to deduct those blocks from the available space, since they are
419 # not writable even with root privilege. It only affects devices using
420 # file-based OTA and a kernel version of 3.10 or greater (currently just
421 # sprout).
422 if reserved_blocks and fs_type.startswith("ext4"):
423 assert ext4fs_output is not None
424 ext4fs_stats = re.compile(
425 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
426 r'(?P<total_blocks>[0-9]+) blocks')
427 m = ext4fs_stats.match(ext4fs_output.strip().split('\n')[-1])
428 used_blocks = int(m.groupdict().get('used_blocks'))
429 total_blocks = int(m.groupdict().get('total_blocks'))
430 reserved_blocks = min(4096, int(total_blocks * 0.02))
431 adjusted_blocks = total_blocks - reserved_blocks
432 if used_blocks > adjusted_blocks:
433 mount_point = prop_dict.get("mount_point")
434 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
435 "reserved: %d blocks, available: %d blocks)" % (
436 mount_point, total_blocks, used_blocks, reserved_blocks,
437 adjusted_blocks))
438 return False
439
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700440 if not fs_spans_partition:
441 mount_point = prop_dict.get("mount_point")
442 partition_size = int(prop_dict.get("partition_size"))
443 image_size = os.stat(out_file).st_size
444 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700445 print("Error: %s image size of %d is larger than partition size of "
446 "%d" % (mount_point, image_size, partition_size))
447 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700448 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100449 if 2 * image_size - AdjustPartitionSizeForVerity(image_size, verity_fec_supported) > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700450 print "Error: No more room on %s to fit verity data" % mount_point
451 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700452 prop_dict["original_partition_size"] = prop_dict["partition_size"]
453 prop_dict["partition_size"] = str(image_size)
454
Geremy Condrafd6f7512013-06-16 17:26:08 -0700455 # create the verified image if this is to be verified
Geremy Condra5b5f4952014-05-05 22:19:37 -0700456 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100457 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700458 return False
459
Ying Wang6a42a252013-02-27 13:54:02 -0800460 if run_fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800461 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700462 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800463 return False
464
465 # Run e2fsck on the inflated image file
466 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700467 (_, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800468
469 os.remove(unsparse_image)
470
471 return exit_code == 0
Ying Wangbd93d422011-10-28 17:02:30 -0700472
473
474def ImagePropFromGlobalDict(glob_dict, mount_point):
475 """Build an image property dictionary from the global dictionary.
476
477 Args:
478 glob_dict: the global dictionary from the build system.
479 mount_point: such as "system", "data" etc.
480 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800481 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700482
Tao Bao822f5842015-09-30 16:01:14 -0700483 if "build.prop" in glob_dict:
484 bp = glob_dict["build.prop"]
485 if "ro.build.date.utc" in bp:
486 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700487
488 def copy_prop(src_p, dest_p):
489 if src_p in glob_dict:
490 d[dest_p] = str(glob_dict[src_p])
491
Ying Wangbd93d422011-10-28 17:02:30 -0700492 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700493 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800494 "squashfs_sparse_flag",
Ying Wangbd93d422011-10-28 17:02:30 -0700495 "mkyaffs2_extra_flags",
Kenny Rootf32dc712012-04-08 10:42:34 -0700496 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800497 "skip_fsck",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700498 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700499 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100500 "verity_signer_cmd",
501 "verity_fec"
Ying Wangbd93d422011-10-28 17:02:30 -0700502 )
503 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700504 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700505
506 d["mount_point"] = mount_point
507 if mount_point == "system":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700508 copy_prop("fs_type", "fs_type")
Dan Albert8b72aef2015-03-23 19:13:21 -0700509 # Copy the generic sysetem fs type first, override with specific one if
510 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800511 copy_prop("system_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700512 copy_prop("system_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800513 copy_prop("system_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700514 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700515 copy_prop("system_root_image", "system_root_image")
516 copy_prop("ramdisk_dir", "ramdisk_dir")
Tao Bao84e75682015-07-19 02:38:53 -0700517 copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700518 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700519 copy_prop("system_squashfs_compressor", "squashfs_compressor")
520 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Ying Wangbd93d422011-10-28 17:02:30 -0700521 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700522 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700523 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700524 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700525 copy_prop("userdata_size", "partition_size")
526 elif mount_point == "cache":
527 copy_prop("cache_fs_type", "fs_type")
528 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700529 elif mount_point == "vendor":
530 copy_prop("vendor_fs_type", "fs_type")
531 copy_prop("vendor_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800532 copy_prop("vendor_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700533 copy_prop("vendor_verity_block_device", "verity_block_device")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700534 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Ying Wangb8888432014-03-11 17:13:27 -0700535 elif mount_point == "oem":
536 copy_prop("fs_type", "fs_type")
537 copy_prop("oem_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800538 copy_prop("oem_journal_size", "journal_size")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700539 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Ying Wangbd93d422011-10-28 17:02:30 -0700540
541 return d
542
543
544def LoadGlobalDict(filename):
545 """Load "name=value" pairs from filename"""
546 d = {}
547 f = open(filename)
548 for line in f:
549 line = line.strip()
550 if not line or line.startswith("#"):
551 continue
552 k, v = line.split("=", 1)
553 d[k] = v
554 f.close()
555 return d
556
557
558def main(argv):
Thierry Strudel74a81e62015-07-09 09:54:55 -0700559 if len(argv) != 4:
Ying Wangbd93d422011-10-28 17:02:30 -0700560 print __doc__
561 sys.exit(1)
562
563 in_dir = argv[0]
564 glob_dict_file = argv[1]
565 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700566 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700567
568 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700569 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700570 # The caller knows the mount point and provides a dictionay needed by
571 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700572 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700573 else:
Ying Wangae61f502015-03-12 18:30:39 -0700574 image_filename = os.path.basename(out_file)
575 mount_point = ""
576 if image_filename == "system.img":
577 mount_point = "system"
578 elif image_filename == "userdata.img":
579 mount_point = "data"
580 elif image_filename == "cache.img":
581 mount_point = "cache"
582 elif image_filename == "vendor.img":
583 mount_point = "vendor"
584 elif image_filename == "oem.img":
585 mount_point = "oem"
586 else:
587 print >> sys.stderr, "error: unknown image file name ", image_filename
588 exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700589
Ying Wangae61f502015-03-12 18:30:39 -0700590 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
591
Thierry Strudel74a81e62015-07-09 09:54:55 -0700592 if not BuildImage(in_dir, image_properties, out_file, target_out):
Dan Albert8b72aef2015-03-23 19:13:21 -0700593 print >> sys.stderr, "error: failed to build %s from %s" % (out_file,
594 in_dir)
Ying Wangbd93d422011-10-28 17:02:30 -0700595 exit(1)
596
597
598if __name__ == '__main__':
599 main(sys.argv[1:])