blob: 2b8d4eefb2439ebc908cdab8fe216a052f3c1b72 [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
132def BuildVerityFEC(sparse_image_path, verity_fec_path, prop_dict):
133 cmd = "fec -e %s %s" % (sparse_image_path, verity_fec_path)
134 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
Dan Albert8b72aef2015-03-23 19:13:21 -0700185def BuildVerifiedImage(data_image_path, verity_image_path,
186 verity_metadata_path):
Dan Albert8b72aef2015-03-23 19:13:21 -0700187 if not Append2Simg(data_image_path, verity_image_path,
188 "Could not append verity tree!"):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700189 return False
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100190 if not Append2Simg(data_image_path, verity_metadata_path,
191 "Could not append verity metadata!"):
192 return False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700193 return True
194
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800195def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700196 img_dir = os.path.dirname(sparse_image_path)
197 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
198 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
199 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800200 if replace:
201 os.unlink(unsparse_image_path)
202 else:
203 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700204 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700205 (_, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700206 if exit_code != 0:
207 os.remove(unsparse_image_path)
208 return False, None
209 return True, unsparse_image_path
210
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100211def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700212 """Creates an image that is verifiable using dm-verity.
213
214 Args:
215 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700216 prop_dict: a dictionary of properties required for image creation and
217 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700218 Returns:
219 True on success, False otherwise.
220 """
221 # get properties
222 image_size = prop_dict["partition_size"]
Geremy Condrafd6f7512013-06-16 17:26:08 -0700223 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800224 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700225 if OPTIONS.verity_signer_path is not None:
226 signer_path = OPTIONS.verity_signer_path + ' '
227 signer_path += ' '.join(OPTIONS.verity_signer_args)
228 else:
229 signer_path = prop_dict["verity_signer_cmd"]
Geremy Condrafd6f7512013-06-16 17:26:08 -0700230
231 # make a tempdir
Geremy Condra5b5f4952014-05-05 22:19:37 -0700232 tempdir_name = tempfile.mkdtemp(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700233
234 # get partial image paths
235 verity_image_path = os.path.join(tempdir_name, "verity.img")
236 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100237 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700238
239 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700240 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700241 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700242 return False
243
244 # build the metadata blocks
245 root_hash = prop_dict["verity_root_hash"]
246 salt = prop_dict["verity_salt"]
Dan Albert8b72aef2015-03-23 19:13:21 -0700247 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
248 block_dev, signer_path, signer_key):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700249 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700250 return False
251
252 # build the full verified image
253 if not BuildVerifiedImage(out_file,
254 verity_image_path,
255 verity_metadata_path):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700256 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700257 return False
258
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100259 if fec_supported:
260 # build FEC for the entire partition, including metadata
261 if not BuildVerityFEC(out_file, verity_fec_path, prop_dict):
262 shutil.rmtree(tempdir_name, ignore_errors=True)
263 return False
264
265 if not Append2Simg(out_file, verity_fec_path, "Could not append FEC!"):
266 shutil.rmtree(tempdir_name, ignore_errors=True)
267 return False
268
Geremy Condra5b5f4952014-05-05 22:19:37 -0700269 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700270 return True
271
Thierry Strudel74a81e62015-07-09 09:54:55 -0700272def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Ying Wangbd93d422011-10-28 17:02:30 -0700273 """Build an image to out_file from in_dir with property prop_dict.
274
275 Args:
276 in_dir: path of input directory.
277 prop_dict: property dictionary.
278 out_file: path of the output image file.
Thierry Strudel74a81e62015-07-09 09:54:55 -0700279 target_out: path of the product out directory to read device specific FS config files.
Ying Wangbd93d422011-10-28 17:02:30 -0700280
281 Returns:
282 True iff the image is built successfully.
283 """
Tao Baof3282b42015-04-01 11:21:55 -0700284 # system_root_image=true: build a system.img that combines the contents of
285 # /system and the ramdisk, and can be mounted at the root of the file system.
Ying Wanga2292c92015-03-24 19:07:40 -0700286 origin_in = in_dir
287 fs_config = prop_dict.get("fs_config")
288 if (prop_dict.get("system_root_image") == "true"
289 and prop_dict["mount_point"] == "system"):
290 in_dir = tempfile.mkdtemp()
291 # Change the mount point to "/"
292 prop_dict["mount_point"] = "/"
293 if fs_config:
294 # We need to merge the fs_config files of system and ramdisk.
295 fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config",
296 suffix=".txt")
297 os.close(fd)
298 with open(merged_fs_config, "w") as fw:
299 if "ramdisk_fs_config" in prop_dict:
300 with open(prop_dict["ramdisk_fs_config"]) as fr:
301 fw.writelines(fr.readlines())
302 with open(fs_config) as fr:
303 fw.writelines(fr.readlines())
304 fs_config = merged_fs_config
305
Ying Wangbd93d422011-10-28 17:02:30 -0700306 build_command = []
307 fs_type = prop_dict.get("fs_type", "")
Ying Wang69e9b4d2012-11-26 18:10:23 -0800308 run_fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700309
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700310 fs_spans_partition = True
311 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700312 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700313
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700314 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700315 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100316 verity_fec_supported = prop_dict.get("verity_fec") == "true"
317
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700318 # Adjust the partition size to make room for the hashes if this is to be
319 # verified.
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700320 if verity_supported and is_verity_partition and fs_spans_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700321 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100322 adjusted_size = AdjustPartitionSizeForVerity(partition_size,
323 verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700324 if not adjusted_size:
325 return False
326 prop_dict["partition_size"] = str(adjusted_size)
327 prop_dict["original_partition_size"] = str(partition_size)
328
Ying Wangbd93d422011-10-28 17:02:30 -0700329 if fs_type.startswith("ext"):
330 build_command = ["mkuserimg.sh"]
331 if "extfs_sparse_flag" in prop_dict:
332 build_command.append(prop_dict["extfs_sparse_flag"])
Ying Wang69e9b4d2012-11-26 18:10:23 -0800333 run_fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700334 build_command.extend([in_dir, out_file, fs_type,
335 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800336 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800337 if "journal_size" in prop_dict:
338 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800339 if "timestamp" in prop_dict:
340 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700341 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700342 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700343 if target_out:
344 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700345 if "block_list" in prop_dict:
346 build_command.extend(["-B", prop_dict["block_list"]])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100347 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wanga2292c92015-03-24 19:07:40 -0700348 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700349 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800350 elif fs_type.startswith("squash"):
351 build_command = ["mksquashfsimage.sh"]
352 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800353 if "squashfs_sparse_flag" in prop_dict:
354 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800355 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700356 if target_out:
357 build_command.extend(["-d", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700358 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800359 build_command.extend(["-c", prop_dict["selinux_fc"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700360 if "squashfs_compressor" in prop_dict:
361 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
362 if "squashfs_compressor_opt" in prop_dict:
363 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700364 elif fs_type.startswith("f2fs"):
365 build_command = ["mkf2fsuserimg.sh"]
366 build_command.extend([out_file, prop_dict["partition_size"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700367 else:
368 build_command = ["mkyaffs2image", "-f"]
369 if prop_dict.get("mkyaffs2_extra_flags", None):
370 build_command.extend(prop_dict["mkyaffs2_extra_flags"].split())
371 build_command.append(in_dir)
372 build_command.append(out_file)
Kenny Rootf32dc712012-04-08 10:42:34 -0700373 if "selinux_fc" in prop_dict:
374 build_command.append(prop_dict["selinux_fc"])
375 build_command.append(prop_dict["mount_point"])
Ying Wangbd93d422011-10-28 17:02:30 -0700376
Ying Wanga2292c92015-03-24 19:07:40 -0700377 if in_dir != origin_in:
378 # Construct a staging directory of the root file system.
379 ramdisk_dir = prop_dict.get("ramdisk_dir")
380 if ramdisk_dir:
381 shutil.rmtree(in_dir)
382 shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
383 staging_system = os.path.join(in_dir, "system")
384 shutil.rmtree(staging_system, ignore_errors=True)
385 shutil.copytree(origin_in, staging_system, symlinks=True)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700386
387 reserved_blocks = prop_dict.get("has_ext4_reserved_blocks") == "true"
388 ext4fs_output = None
389
Ying Wanga2292c92015-03-24 19:07:40 -0700390 try:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700391 if reserved_blocks and fs_type.startswith("ext4"):
392 (ext4fs_output, exit_code) = RunCommand(build_command)
393 else:
394 (_, exit_code) = RunCommand(build_command)
Ying Wanga2292c92015-03-24 19:07:40 -0700395 finally:
396 if in_dir != origin_in:
397 # Clean up temporary directories and files.
398 shutil.rmtree(in_dir, ignore_errors=True)
399 if fs_config:
400 os.remove(fs_config)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800401 if exit_code != 0:
402 return False
403
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700404 # Bug: 21522719, 22023465
405 # There are some reserved blocks on ext4 FS (lesser of 4096 blocks and 2%).
406 # We need to deduct those blocks from the available space, since they are
407 # not writable even with root privilege. It only affects devices using
408 # file-based OTA and a kernel version of 3.10 or greater (currently just
409 # sprout).
410 if reserved_blocks and fs_type.startswith("ext4"):
411 assert ext4fs_output is not None
412 ext4fs_stats = re.compile(
413 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
414 r'(?P<total_blocks>[0-9]+) blocks')
415 m = ext4fs_stats.match(ext4fs_output.strip().split('\n')[-1])
416 used_blocks = int(m.groupdict().get('used_blocks'))
417 total_blocks = int(m.groupdict().get('total_blocks'))
418 reserved_blocks = min(4096, int(total_blocks * 0.02))
419 adjusted_blocks = total_blocks - reserved_blocks
420 if used_blocks > adjusted_blocks:
421 mount_point = prop_dict.get("mount_point")
422 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
423 "reserved: %d blocks, available: %d blocks)" % (
424 mount_point, total_blocks, used_blocks, reserved_blocks,
425 adjusted_blocks))
426 return False
427
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700428 if not fs_spans_partition:
429 mount_point = prop_dict.get("mount_point")
430 partition_size = int(prop_dict.get("partition_size"))
431 image_size = os.stat(out_file).st_size
432 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700433 print("Error: %s image size of %d is larger than partition size of "
434 "%d" % (mount_point, image_size, partition_size))
435 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700436 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100437 if 2 * image_size - AdjustPartitionSizeForVerity(image_size, verity_fec_supported) > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700438 print "Error: No more room on %s to fit verity data" % mount_point
439 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700440 prop_dict["original_partition_size"] = prop_dict["partition_size"]
441 prop_dict["partition_size"] = str(image_size)
442
Geremy Condrafd6f7512013-06-16 17:26:08 -0700443 # create the verified image if this is to be verified
Geremy Condra5b5f4952014-05-05 22:19:37 -0700444 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100445 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700446 return False
447
Ying Wang6a42a252013-02-27 13:54:02 -0800448 if run_fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800449 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700450 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800451 return False
452
453 # Run e2fsck on the inflated image file
454 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700455 (_, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800456
457 os.remove(unsparse_image)
458
459 return exit_code == 0
Ying Wangbd93d422011-10-28 17:02:30 -0700460
461
462def ImagePropFromGlobalDict(glob_dict, mount_point):
463 """Build an image property dictionary from the global dictionary.
464
465 Args:
466 glob_dict: the global dictionary from the build system.
467 mount_point: such as "system", "data" etc.
468 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800469 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700470
Tao Bao822f5842015-09-30 16:01:14 -0700471 if "build.prop" in glob_dict:
472 bp = glob_dict["build.prop"]
473 if "ro.build.date.utc" in bp:
474 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700475
476 def copy_prop(src_p, dest_p):
477 if src_p in glob_dict:
478 d[dest_p] = str(glob_dict[src_p])
479
Ying Wangbd93d422011-10-28 17:02:30 -0700480 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700481 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800482 "squashfs_sparse_flag",
Ying Wangbd93d422011-10-28 17:02:30 -0700483 "mkyaffs2_extra_flags",
Kenny Rootf32dc712012-04-08 10:42:34 -0700484 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800485 "skip_fsck",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700486 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700487 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100488 "verity_signer_cmd",
489 "verity_fec"
Ying Wangbd93d422011-10-28 17:02:30 -0700490 )
491 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700492 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700493
494 d["mount_point"] = mount_point
495 if mount_point == "system":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700496 copy_prop("fs_type", "fs_type")
Dan Albert8b72aef2015-03-23 19:13:21 -0700497 # Copy the generic sysetem fs type first, override with specific one if
498 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800499 copy_prop("system_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700500 copy_prop("system_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800501 copy_prop("system_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700502 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700503 copy_prop("system_root_image", "system_root_image")
504 copy_prop("ramdisk_dir", "ramdisk_dir")
Tao Bao84e75682015-07-19 02:38:53 -0700505 copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700506 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700507 copy_prop("system_squashfs_compressor", "squashfs_compressor")
508 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Ying Wangbd93d422011-10-28 17:02:30 -0700509 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700510 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700511 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700512 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700513 copy_prop("userdata_size", "partition_size")
514 elif mount_point == "cache":
515 copy_prop("cache_fs_type", "fs_type")
516 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700517 elif mount_point == "vendor":
518 copy_prop("vendor_fs_type", "fs_type")
519 copy_prop("vendor_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800520 copy_prop("vendor_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700521 copy_prop("vendor_verity_block_device", "verity_block_device")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700522 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Ying Wangb8888432014-03-11 17:13:27 -0700523 elif mount_point == "oem":
524 copy_prop("fs_type", "fs_type")
525 copy_prop("oem_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800526 copy_prop("oem_journal_size", "journal_size")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700527 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Ying Wangbd93d422011-10-28 17:02:30 -0700528
529 return d
530
531
532def LoadGlobalDict(filename):
533 """Load "name=value" pairs from filename"""
534 d = {}
535 f = open(filename)
536 for line in f:
537 line = line.strip()
538 if not line or line.startswith("#"):
539 continue
540 k, v = line.split("=", 1)
541 d[k] = v
542 f.close()
543 return d
544
545
546def main(argv):
Thierry Strudel74a81e62015-07-09 09:54:55 -0700547 if len(argv) != 4:
Ying Wangbd93d422011-10-28 17:02:30 -0700548 print __doc__
549 sys.exit(1)
550
551 in_dir = argv[0]
552 glob_dict_file = argv[1]
553 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700554 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700555
556 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700557 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700558 # The caller knows the mount point and provides a dictionay needed by
559 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700560 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700561 else:
Ying Wangae61f502015-03-12 18:30:39 -0700562 image_filename = os.path.basename(out_file)
563 mount_point = ""
564 if image_filename == "system.img":
565 mount_point = "system"
566 elif image_filename == "userdata.img":
567 mount_point = "data"
568 elif image_filename == "cache.img":
569 mount_point = "cache"
570 elif image_filename == "vendor.img":
571 mount_point = "vendor"
572 elif image_filename == "oem.img":
573 mount_point = "oem"
574 else:
575 print >> sys.stderr, "error: unknown image file name ", image_filename
576 exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700577
Ying Wangae61f502015-03-12 18:30:39 -0700578 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
579
Thierry Strudel74a81e62015-07-09 09:54:55 -0700580 if not BuildImage(in_dir, image_properties, out_file, target_out):
Dan Albert8b72aef2015-03-23 19:13:21 -0700581 print >> sys.stderr, "error: failed to build %s from %s" % (out_file,
582 in_dir)
Ying Wangbd93d422011-10-28 17:02:30 -0700583 exit(1)
584
585
586if __name__ == '__main__':
587 main(sys.argv[1:])