blob: 390c26fe81eceb7c8c92d21f6a0aacde61087b19 [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"""
Maria Bornski885dbb52015-09-04 11:13:16 -070018Build image output_image_file from input_directory, properties_file, and target_out_dir
Ying Wangbd93d422011-10-28 17:02:30 -070019
Maria Bornski885dbb52015-09-04 11:13:16 -070020Usage: build_image input_directory properties_file output_image_file target_out_dir
Ying Wangbd93d422011-10-28 17:02:30 -070021
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
Sami Tolvanen405e71d2016-02-09 12:28:58 -080031import sparse_img
Geremy Condra5b5f4952014-05-05 22:19:37 -070032import tempfile
Ying Wangbd93d422011-10-28 17:02:30 -070033
Baligh Uddin601ddea2015-06-09 15:48:14 -070034OPTIONS = common.OPTIONS
35
Geremy Condrae8e982a2014-05-16 19:14:30 -070036FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
Sami Tolvanenf99b5312015-05-20 07:30:57 +010037BLOCK_SIZE = 4096
Geremy Condrae8e982a2014-05-16 19:14:30 -070038
Ying Wang69e9b4d2012-11-26 18:10:23 -080039def RunCommand(cmd):
Tao Baoc7a6f1e2015-06-23 11:16:05 -070040 """Echo and run the given command.
Ying Wang69e9b4d2012-11-26 18:10:23 -080041
42 Args:
43 cmd: the command represented as a list of strings.
44 Returns:
Tao Baoc7a6f1e2015-06-23 11:16:05 -070045 A tuple of the output and the exit code.
Ying Wang69e9b4d2012-11-26 18:10:23 -080046 """
47 print "Running: ", " ".join(cmd)
Tao Baoc7a6f1e2015-06-23 11:16:05 -070048 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
49 output, _ = p.communicate()
50 print "%s" % (output.rstrip(),)
51 return (output, p.returncode)
Ying Wangbd93d422011-10-28 17:02:30 -070052
Sami Tolvanenf99b5312015-05-20 07:30:57 +010053def GetVerityFECSize(partition_size):
54 cmd = "fec -s %d" % partition_size
55 status, output = commands.getstatusoutput(cmd)
56 if status:
57 print output
58 return False, 0
59 return True, int(output)
60
Geremy Condrafd6f7512013-06-16 17:26:08 -070061def GetVerityTreeSize(partition_size):
Colin Cross477cf2b2014-04-16 18:49:56 -070062 cmd = "build_verity_tree -s %d"
Geremy Condrafd6f7512013-06-16 17:26:08 -070063 cmd %= partition_size
64 status, output = commands.getstatusoutput(cmd)
65 if status:
66 print output
67 return False, 0
68 return True, int(output)
69
70def GetVerityMetadataSize(partition_size):
71 cmd = "system/extras/verity/build_verity_metadata.py -s %d"
72 cmd %= partition_size
Baligh Uddin601ddea2015-06-09 15:48:14 -070073
Geremy Condrafd6f7512013-06-16 17:26:08 -070074 status, output = commands.getstatusoutput(cmd)
75 if status:
76 print output
77 return False, 0
78 return True, int(output)
79
Sami Tolvanenf99b5312015-05-20 07:30:57 +010080def GetVeritySize(partition_size, fec_supported):
81 success, verity_tree_size = GetVerityTreeSize(partition_size)
82 if not success:
83 return 0
84 success, verity_metadata_size = GetVerityMetadataSize(partition_size)
85 if not success:
86 return 0
87 verity_size = verity_tree_size + verity_metadata_size
88 if fec_supported:
89 success, fec_size = GetVerityFECSize(partition_size + verity_size)
90 if not success:
91 return 0
92 return verity_size + fec_size
93 return verity_size
94
Sami Tolvanen405e71d2016-02-09 12:28:58 -080095def GetSimgSize(image_file):
96 simg = sparse_img.SparseImage(image_file, build_map=False)
97 return simg.blocksize * simg.total_blocks
98
99def ZeroPadSimg(image_file, pad_size):
100 blocks = pad_size // BLOCK_SIZE
101 print("Padding %d blocks (%d bytes)" % (blocks, pad_size))
102 simg = sparse_img.SparseImage(image_file, mode="r+b", build_map=False)
103 simg.AppendFillChunk(0, blocks)
104
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100105def AdjustPartitionSizeForVerity(partition_size, fec_supported):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700106 """Modifies the provided partition size to account for the verity metadata.
107
108 This information is used to size the created image appropriately.
109 Args:
110 partition_size: the size of the partition to be verified.
111 Returns:
Sami Tolvanen433905f2016-09-01 15:58:35 -0700112 A tuple of the size of the partition adjusted for verity metadata, and
113 the size of verity metadata.
Geremy Condrafd6f7512013-06-16 17:26:08 -0700114 """
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100115 key = "%d %d" % (partition_size, fec_supported)
116 if key in AdjustPartitionSizeForVerity.results:
117 return AdjustPartitionSizeForVerity.results[key]
118
119 hi = partition_size
120 if hi % BLOCK_SIZE != 0:
121 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
122
123 # verity tree and fec sizes depend on the partition size, which
124 # means this estimate is always going to be unnecessarily small
Sami Tolvanen433905f2016-09-01 15:58:35 -0700125 verity_size = GetVeritySize(hi, fec_supported)
126 lo = partition_size - verity_size
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100127 result = lo
128
129 # do a binary search for the optimal size
130 while lo < hi:
131 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
Sami Tolvanen433905f2016-09-01 15:58:35 -0700132 v = GetVeritySize(i, fec_supported)
133 if i + v <= partition_size:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100134 if result < i:
135 result = i
Sami Tolvanen433905f2016-09-01 15:58:35 -0700136 verity_size = v
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100137 lo = i + BLOCK_SIZE
138 else:
139 hi = i
140
Sami Tolvanen433905f2016-09-01 15:58:35 -0700141 AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
142 return (result, verity_size)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100143
144AdjustPartitionSizeForVerity.results = {}
145
Sami Tolvanen433905f2016-09-01 15:58:35 -0700146def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
147 padding_size):
148 cmd = "fec -e -p %d %s %s %s" % (padding_size, sparse_image_path,
149 verity_path, verity_fec_path)
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100150 print cmd
151 status, output = commands.getstatusoutput(cmd)
152 if status:
153 print "Could not build FEC data! Error: %s" % output
154 return False
155 return True
Geremy Condrafd6f7512013-06-16 17:26:08 -0700156
Colin Cross477cf2b2014-04-16 18:49:56 -0700157def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
Dan Albert8b72aef2015-03-23 19:13:21 -0700158 cmd = "build_verity_tree -A %s %s %s" % (
159 FIXED_SALT, sparse_image_path, verity_image_path)
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 tree! Error: %s" % output
164 return False
165 root, salt = output.split()
166 prop_dict["verity_root_hash"] = root
167 prop_dict["verity_salt"] = salt
168 return True
169
170def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
171 block_device, signer_path, key):
Dan Albert8b72aef2015-03-23 19:13:21 -0700172 cmd_template = (
173 "system/extras/verity/build_verity_metadata.py %s %s %s %s %s %s %s")
174 cmd = cmd_template % (image_size, verity_metadata_path, root_hash, salt,
175 block_device, signer_path, key)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700176 print cmd
177 status, output = commands.getstatusoutput(cmd)
178 if status:
179 print "Could not build verity metadata! Error: %s" % output
180 return False
181 return True
182
183def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
184 """Appends the unsparse image to the given sparse image.
185
186 Args:
187 sparse_image_path: the path to the (sparse) image
188 unsparse_image_path: the path to the (unsparse) image
189 Returns:
190 True on success, False on failure.
191 """
192 cmd = "append2simg %s %s"
193 cmd %= (sparse_image_path, unsparse_image_path)
194 print cmd
195 status, output = commands.getstatusoutput(cmd)
196 if status:
197 print "%s: %s" % (error_message, output)
198 return False
199 return True
200
Sami Tolvanenff914f52015-12-18 13:24:56 +0000201def Append(target, file_to_append, error_message):
202 cmd = 'cat %s >> %s' % (file_to_append, target)
203 print cmd
204 status, output = commands.getstatusoutput(cmd)
205 if status:
206 print "%s: %s" % (error_message, output)
207 return False
208 return True
209
Dan Albert8b72aef2015-03-23 19:13:21 -0700210def BuildVerifiedImage(data_image_path, verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000211 verity_metadata_path, verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700212 padding_size, fec_supported):
Sami Tolvanenff914f52015-12-18 13:24:56 +0000213 if not Append(verity_image_path, verity_metadata_path,
214 "Could not append verity metadata!"):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700215 return False
Sami Tolvanen4a060042015-12-18 15:50:25 +0000216
217 if fec_supported:
218 # build FEC for the entire partition, including metadata
219 if not BuildVerityFEC(data_image_path, verity_image_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700220 verity_fec_path, padding_size):
Sami Tolvanen4a060042015-12-18 15:50:25 +0000221 return False
222
223 if not Append(verity_image_path, verity_fec_path, "Could not append FEC!"):
224 return False
225
Sami Tolvanenff914f52015-12-18 13:24:56 +0000226 if not Append2Simg(data_image_path, verity_image_path,
227 "Could not append verity data!"):
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100228 return False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700229 return True
230
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800231def UnsparseImage(sparse_image_path, replace=True):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700232 img_dir = os.path.dirname(sparse_image_path)
233 unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
234 unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
235 if os.path.exists(unsparse_image_path):
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800236 if replace:
237 os.unlink(unsparse_image_path)
238 else:
239 return True, unsparse_image_path
Geremy Condrafd6f7512013-06-16 17:26:08 -0700240 inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700241 (_, exit_code) = RunCommand(inflate_command)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700242 if exit_code != 0:
243 os.remove(unsparse_image_path)
244 return False, None
245 return True, unsparse_image_path
246
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100247def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700248 """Creates an image that is verifiable using dm-verity.
249
250 Args:
251 out_file: the location to write the verifiable image at
Dan Albert8b72aef2015-03-23 19:13:21 -0700252 prop_dict: a dictionary of properties required for image creation and
253 verification
Geremy Condrafd6f7512013-06-16 17:26:08 -0700254 Returns:
255 True on success, False otherwise.
256 """
257 # get properties
Sami Tolvanen433905f2016-09-01 15:58:35 -0700258 image_size = int(prop_dict["partition_size"])
Geremy Condrafd6f7512013-06-16 17:26:08 -0700259 block_dev = prop_dict["verity_block_device"]
Paul Lawrencea37b2bb2014-11-13 17:54:30 -0800260 signer_key = prop_dict["verity_key"] + ".pk8"
Baligh Uddin601ddea2015-06-09 15:48:14 -0700261 if OPTIONS.verity_signer_path is not None:
262 signer_path = OPTIONS.verity_signer_path + ' '
263 signer_path += ' '.join(OPTIONS.verity_signer_args)
264 else:
265 signer_path = prop_dict["verity_signer_cmd"]
Geremy Condrafd6f7512013-06-16 17:26:08 -0700266
267 # make a tempdir
Geremy Condra5b5f4952014-05-05 22:19:37 -0700268 tempdir_name = tempfile.mkdtemp(suffix="_verity_images")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700269
270 # get partial image paths
271 verity_image_path = os.path.join(tempdir_name, "verity.img")
272 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100273 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
Geremy Condrafd6f7512013-06-16 17:26:08 -0700274
275 # build the verity tree and get the root hash and salt
Colin Cross477cf2b2014-04-16 18:49:56 -0700276 if not BuildVerityTree(out_file, verity_image_path, prop_dict):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700277 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700278 return False
279
280 # build the metadata blocks
281 root_hash = prop_dict["verity_root_hash"]
282 salt = prop_dict["verity_salt"]
Dan Albert8b72aef2015-03-23 19:13:21 -0700283 if not BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
284 block_dev, signer_path, signer_key):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700285 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700286 return False
287
288 # build the full verified image
Sami Tolvanen433905f2016-09-01 15:58:35 -0700289 target_size = int(prop_dict["original_partition_size"])
290 verity_size = int(prop_dict["verity_size"])
291
292 padding_size = target_size - image_size - verity_size
293 assert padding_size >= 0
294
Geremy Condrafd6f7512013-06-16 17:26:08 -0700295 if not BuildVerifiedImage(out_file,
296 verity_image_path,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000297 verity_metadata_path,
298 verity_fec_path,
Sami Tolvanen433905f2016-09-01 15:58:35 -0700299 padding_size,
Sami Tolvanen4a060042015-12-18 15:50:25 +0000300 fec_supported):
Geremy Condra5b5f4952014-05-05 22:19:37 -0700301 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700302 return False
303
Geremy Condra5b5f4952014-05-05 22:19:37 -0700304 shutil.rmtree(tempdir_name, ignore_errors=True)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700305 return True
306
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800307def ConvertBlockMapToBaseFs(block_map_file):
308 fd, base_fs_file = tempfile.mkstemp(prefix="script_gen_",
309 suffix=".base_fs")
310 os.close(fd)
311
312 convert_command = ["blk_alloc_to_base_fs", block_map_file, base_fs_file]
313 (_, exit_code) = RunCommand(convert_command)
314 if exit_code != 0:
315 os.remove(base_fs_file)
316 return None
317 return base_fs_file
318
Thierry Strudel74a81e62015-07-09 09:54:55 -0700319def BuildImage(in_dir, prop_dict, out_file, target_out=None):
Ying Wangbd93d422011-10-28 17:02:30 -0700320 """Build an image to out_file from in_dir with property prop_dict.
321
322 Args:
323 in_dir: path of input directory.
324 prop_dict: property dictionary.
325 out_file: path of the output image file.
Thierry Strudel74a81e62015-07-09 09:54:55 -0700326 target_out: path of the product out directory to read device specific FS config files.
Ying Wangbd93d422011-10-28 17:02:30 -0700327
328 Returns:
329 True iff the image is built successfully.
330 """
Tao Baof3282b42015-04-01 11:21:55 -0700331 # system_root_image=true: build a system.img that combines the contents of
332 # /system and the ramdisk, and can be mounted at the root of the file system.
Ying Wanga2292c92015-03-24 19:07:40 -0700333 origin_in = in_dir
334 fs_config = prop_dict.get("fs_config")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800335 base_fs_file = None
Ying Wanga2292c92015-03-24 19:07:40 -0700336 if (prop_dict.get("system_root_image") == "true"
337 and prop_dict["mount_point"] == "system"):
338 in_dir = tempfile.mkdtemp()
339 # Change the mount point to "/"
340 prop_dict["mount_point"] = "/"
341 if fs_config:
342 # We need to merge the fs_config files of system and ramdisk.
343 fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config",
344 suffix=".txt")
345 os.close(fd)
346 with open(merged_fs_config, "w") as fw:
347 if "ramdisk_fs_config" in prop_dict:
348 with open(prop_dict["ramdisk_fs_config"]) as fr:
349 fw.writelines(fr.readlines())
350 with open(fs_config) as fr:
351 fw.writelines(fr.readlines())
352 fs_config = merged_fs_config
353
Ying Wangbd93d422011-10-28 17:02:30 -0700354 build_command = []
355 fs_type = prop_dict.get("fs_type", "")
Ying Wang69e9b4d2012-11-26 18:10:23 -0800356 run_fsck = False
Geremy Condrafd6f7512013-06-16 17:26:08 -0700357
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700358 fs_spans_partition = True
359 if fs_type.startswith("squash"):
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700360 fs_spans_partition = False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700361
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700362 is_verity_partition = "verity_block_device" in prop_dict
Geremy Condra5b5f4952014-05-05 22:19:37 -0700363 verity_supported = prop_dict.get("verity") == "true"
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100364 verity_fec_supported = prop_dict.get("verity_fec") == "true"
365
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700366 # Adjust the partition size to make room for the hashes if this is to be
367 # verified.
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800368 if verity_supported and is_verity_partition:
Geremy Condrafd6f7512013-06-16 17:26:08 -0700369 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen433905f2016-09-01 15:58:35 -0700370 (adjusted_size, verity_size) = AdjustPartitionSizeForVerity(partition_size,
371 verity_fec_supported)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700372 if not adjusted_size:
373 return False
374 prop_dict["partition_size"] = str(adjusted_size)
375 prop_dict["original_partition_size"] = str(partition_size)
Sami Tolvanen433905f2016-09-01 15:58:35 -0700376 prop_dict["verity_size"] = str(verity_size)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700377
Ying Wangbd93d422011-10-28 17:02:30 -0700378 if fs_type.startswith("ext"):
379 build_command = ["mkuserimg.sh"]
380 if "extfs_sparse_flag" in prop_dict:
381 build_command.append(prop_dict["extfs_sparse_flag"])
Ying Wang69e9b4d2012-11-26 18:10:23 -0800382 run_fsck = True
Ying Wangbd93d422011-10-28 17:02:30 -0700383 build_command.extend([in_dir, out_file, fs_type,
384 prop_dict["mount_point"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800385 build_command.append(prop_dict["partition_size"])
Ying Wangf3b86352014-11-18 18:03:13 -0800386 if "journal_size" in prop_dict:
387 build_command.extend(["-j", prop_dict["journal_size"]])
Doug Zongker850b8072013-12-05 15:54:55 -0800388 if "timestamp" in prop_dict:
389 build_command.extend(["-T", str(prop_dict["timestamp"])])
Ying Wanga2292c92015-03-24 19:07:40 -0700390 if fs_config:
Doug Zongker82822822014-06-16 09:10:55 -0700391 build_command.extend(["-C", fs_config])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700392 if target_out:
393 build_command.extend(["-D", target_out])
Ying Wanga2292c92015-03-24 19:07:40 -0700394 if "block_list" in prop_dict:
395 build_command.extend(["-B", prop_dict["block_list"]])
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800396 if "base_fs_file" in prop_dict:
397 base_fs_file = ConvertBlockMapToBaseFs(prop_dict["base_fs_file"])
398 if base_fs_file is None:
399 return False
400 build_command.extend(["-d", base_fs_file])
Christoffer Dall8ed01f32014-12-17 21:34:12 +0100401 build_command.extend(["-L", prop_dict["mount_point"]])
Ying Wanga2292c92015-03-24 19:07:40 -0700402 if "selinux_fc" in prop_dict:
Kenny Rootf32dc712012-04-08 10:42:34 -0700403 build_command.append(prop_dict["selinux_fc"])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800404 elif fs_type.startswith("squash"):
405 build_command = ["mksquashfsimage.sh"]
406 build_command.extend([in_dir, out_file])
Todd Poynorb2a555e2015-12-15 18:00:14 -0800407 if "squashfs_sparse_flag" in prop_dict:
408 build_command.extend([prop_dict["squashfs_sparse_flag"]])
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800409 build_command.extend(["-m", prop_dict["mount_point"]])
Thierry Strudel74a81e62015-07-09 09:54:55 -0700410 if target_out:
411 build_command.extend(["-d", target_out])
Mohamad Ayyash88378822016-04-07 22:10:51 -0700412 if fs_config:
413 build_command.extend(["-C", fs_config])
Ying Wanga2292c92015-03-24 19:07:40 -0700414 if "selinux_fc" in prop_dict:
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800415 build_command.extend(["-c", prop_dict["selinux_fc"]])
Mohamad Ayyashc3484f72016-06-13 09:46:58 -0700416 if "block_list" in prop_dict:
417 build_command.extend(["-B", prop_dict["block_list"]])
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700418 if "squashfs_compressor" in prop_dict:
419 build_command.extend(["-z", prop_dict["squashfs_compressor"]])
420 if "squashfs_compressor_opt" in prop_dict:
421 build_command.extend(["-zo", prop_dict["squashfs_compressor_opt"]])
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700422 if "squashfs_block_size" in prop_dict:
423 build_command.extend(["-b", prop_dict["squashfs_block_size"]])
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700424 if "squashfs_disable_4k_align" in prop_dict and prop_dict.get("squashfs_disable_4k_align") == "true":
425 build_command.extend(["-a"])
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700426 elif fs_type.startswith("f2fs"):
427 build_command = ["mkf2fsuserimg.sh"]
428 build_command.extend([out_file, prop_dict["partition_size"]])
Ying Wangbd93d422011-10-28 17:02:30 -0700429 else:
Elliott Hughes305b0882016-06-15 17:04:54 -0700430 print("Error: unknown filesystem type '%s'" % (fs_type))
431 return False
Ying Wangbd93d422011-10-28 17:02:30 -0700432
Ying Wanga2292c92015-03-24 19:07:40 -0700433 if in_dir != origin_in:
434 # Construct a staging directory of the root file system.
435 ramdisk_dir = prop_dict.get("ramdisk_dir")
436 if ramdisk_dir:
437 shutil.rmtree(in_dir)
438 shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
439 staging_system = os.path.join(in_dir, "system")
440 shutil.rmtree(staging_system, ignore_errors=True)
441 shutil.copytree(origin_in, staging_system, symlinks=True)
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700442
443 reserved_blocks = prop_dict.get("has_ext4_reserved_blocks") == "true"
444 ext4fs_output = None
445
Ying Wanga2292c92015-03-24 19:07:40 -0700446 try:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700447 if reserved_blocks and fs_type.startswith("ext4"):
448 (ext4fs_output, exit_code) = RunCommand(build_command)
449 else:
450 (_, exit_code) = RunCommand(build_command)
Ying Wanga2292c92015-03-24 19:07:40 -0700451 finally:
452 if in_dir != origin_in:
453 # Clean up temporary directories and files.
454 shutil.rmtree(in_dir, ignore_errors=True)
455 if fs_config:
456 os.remove(fs_config)
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800457 if base_fs_file is not None:
458 os.remove(base_fs_file)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800459 if exit_code != 0:
460 return False
461
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700462 # Bug: 21522719, 22023465
463 # There are some reserved blocks on ext4 FS (lesser of 4096 blocks and 2%).
464 # We need to deduct those blocks from the available space, since they are
465 # not writable even with root privilege. It only affects devices using
466 # file-based OTA and a kernel version of 3.10 or greater (currently just
467 # sprout).
468 if reserved_blocks and fs_type.startswith("ext4"):
469 assert ext4fs_output is not None
470 ext4fs_stats = re.compile(
471 r'Created filesystem with .* (?P<used_blocks>[0-9]+)/'
472 r'(?P<total_blocks>[0-9]+) blocks')
473 m = ext4fs_stats.match(ext4fs_output.strip().split('\n')[-1])
474 used_blocks = int(m.groupdict().get('used_blocks'))
475 total_blocks = int(m.groupdict().get('total_blocks'))
476 reserved_blocks = min(4096, int(total_blocks * 0.02))
477 adjusted_blocks = total_blocks - reserved_blocks
478 if used_blocks > adjusted_blocks:
479 mount_point = prop_dict.get("mount_point")
480 print("Error: Not enough room on %s (total: %d blocks, used: %d blocks, "
481 "reserved: %d blocks, available: %d blocks)" % (
482 mount_point, total_blocks, used_blocks, reserved_blocks,
483 adjusted_blocks))
484 return False
485
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700486 if not fs_spans_partition:
487 mount_point = prop_dict.get("mount_point")
488 partition_size = int(prop_dict.get("partition_size"))
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800489 image_size = GetSimgSize(out_file)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700490 if image_size > partition_size:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700491 print("Error: %s image size of %d is larger than partition size of "
492 "%d" % (mount_point, image_size, partition_size))
493 return False
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700494 if verity_supported and is_verity_partition:
Sami Tolvanen405e71d2016-02-09 12:28:58 -0800495 ZeroPadSimg(out_file, partition_size - image_size)
Mohamad Ayyashdd063522015-03-24 12:42:03 -0700496
Geremy Condrafd6f7512013-06-16 17:26:08 -0700497 # create the verified image if this is to be verified
Geremy Condra5b5f4952014-05-05 22:19:37 -0700498 if verity_supported and is_verity_partition:
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100499 if not MakeVerityEnabledImage(out_file, verity_fec_supported, prop_dict):
Geremy Condrafd6f7512013-06-16 17:26:08 -0700500 return False
501
Ying Wang6a42a252013-02-27 13:54:02 -0800502 if run_fsck and prop_dict.get("skip_fsck") != "true":
Geremy Condra6e8f53c2013-12-05 17:09:18 -0800503 success, unsparse_image = UnsparseImage(out_file, replace=False)
Geremy Condrafd6f7512013-06-16 17:26:08 -0700504 if not success:
Ying Wang69e9b4d2012-11-26 18:10:23 -0800505 return False
506
507 # Run e2fsck on the inflated image file
508 e2fsck_command = ["e2fsck", "-f", "-n", unsparse_image]
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700509 (_, exit_code) = RunCommand(e2fsck_command)
Ying Wang69e9b4d2012-11-26 18:10:23 -0800510
511 os.remove(unsparse_image)
512
513 return exit_code == 0
Ying Wangbd93d422011-10-28 17:02:30 -0700514
515
516def ImagePropFromGlobalDict(glob_dict, mount_point):
517 """Build an image property dictionary from the global dictionary.
518
519 Args:
520 glob_dict: the global dictionary from the build system.
521 mount_point: such as "system", "data" etc.
522 """
Doug Zongker1ad7ade2013-12-06 11:53:27 -0800523 d = {}
Tao Bao052ae352015-09-28 13:44:13 -0700524
Tao Bao822f5842015-09-30 16:01:14 -0700525 if "build.prop" in glob_dict:
526 bp = glob_dict["build.prop"]
527 if "ro.build.date.utc" in bp:
528 d["timestamp"] = bp["ro.build.date.utc"]
Ying Wang9f8e8db2011-11-04 11:37:01 -0700529
530 def copy_prop(src_p, dest_p):
531 if src_p in glob_dict:
532 d[dest_p] = str(glob_dict[src_p])
533
Ying Wangbd93d422011-10-28 17:02:30 -0700534 common_props = (
Ying Wangbd93d422011-10-28 17:02:30 -0700535 "extfs_sparse_flag",
Todd Poynorb2a555e2015-12-15 18:00:14 -0800536 "squashfs_sparse_flag",
Kenny Rootf32dc712012-04-08 10:42:34 -0700537 "selinux_fc",
Ying Wang6a42a252013-02-27 13:54:02 -0800538 "skip_fsck",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700539 "verity",
Geremy Condrafd6f7512013-06-16 17:26:08 -0700540 "verity_key",
Sami Tolvanenf99b5312015-05-20 07:30:57 +0100541 "verity_signer_cmd",
542 "verity_fec"
Ying Wangbd93d422011-10-28 17:02:30 -0700543 )
544 for p in common_props:
Ying Wang9f8e8db2011-11-04 11:37:01 -0700545 copy_prop(p, p)
Ying Wangbd93d422011-10-28 17:02:30 -0700546
547 d["mount_point"] = mount_point
548 if mount_point == "system":
Ying Wang9f8e8db2011-11-04 11:37:01 -0700549 copy_prop("fs_type", "fs_type")
Dan Albert8b72aef2015-03-23 19:13:21 -0700550 # Copy the generic sysetem fs type first, override with specific one if
551 # available.
Mohamad Ayyashb97746e2015-03-03 12:30:37 -0800552 copy_prop("system_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700553 copy_prop("system_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800554 copy_prop("system_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700555 copy_prop("system_verity_block_device", "verity_block_device")
Tao Baof3282b42015-04-01 11:21:55 -0700556 copy_prop("system_root_image", "system_root_image")
557 copy_prop("ramdisk_dir", "ramdisk_dir")
Tao Bao84e75682015-07-19 02:38:53 -0700558 copy_prop("ramdisk_fs_config", "ramdisk_fs_config")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700559 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Simon Wilsonf86e7ee2015-06-17 12:35:15 -0700560 copy_prop("system_squashfs_compressor", "squashfs_compressor")
561 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700562 copy_prop("system_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700563 copy_prop("system_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800564 copy_prop("system_base_fs_file", "base_fs_file")
Alex Light4e358ab2016-06-16 14:47:10 -0700565 elif mount_point == "system_other":
566 # We inherit the selinux policies of /system since we contain some of its files.
567 d["mount_point"] = "system"
568 copy_prop("fs_type", "fs_type")
569 copy_prop("system_fs_type", "fs_type")
570 copy_prop("system_size", "partition_size")
571 copy_prop("system_journal_size", "journal_size")
572 copy_prop("system_verity_block_device", "verity_block_device")
573 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
574 copy_prop("system_squashfs_compressor", "squashfs_compressor")
575 copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
576 copy_prop("system_squashfs_block_size", "squashfs_block_size")
577 copy_prop("system_base_fs_file", "base_fs_file")
Ying Wangbd93d422011-10-28 17:02:30 -0700578 elif mount_point == "data":
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700579 # Copy the generic fs type first, override with specific one if available.
Ying Wang9f8e8db2011-11-04 11:37:01 -0700580 copy_prop("fs_type", "fs_type")
JP Abgrall5bfed5a2014-06-16 14:17:40 -0700581 copy_prop("userdata_fs_type", "fs_type")
Ying Wang9f8e8db2011-11-04 11:37:01 -0700582 copy_prop("userdata_size", "partition_size")
583 elif mount_point == "cache":
584 copy_prop("cache_fs_type", "fs_type")
585 copy_prop("cache_size", "partition_size")
Ying Wanga0febe52013-03-20 11:02:05 -0700586 elif mount_point == "vendor":
587 copy_prop("vendor_fs_type", "fs_type")
588 copy_prop("vendor_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800589 copy_prop("vendor_journal_size", "journal_size")
Daniel Rosenbergf4eabc32014-07-10 15:42:38 -0700590 copy_prop("vendor_verity_block_device", "verity_block_device")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700591 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Patrick Tjine11aa502016-02-09 15:40:38 -0800592 copy_prop("vendor_squashfs_compressor", "squashfs_compressor")
593 copy_prop("vendor_squashfs_compressor_opt", "squashfs_compressor_opt")
Mohamad Ayyashdfec8152016-05-24 12:59:30 -0700594 copy_prop("vendor_squashfs_block_size", "squashfs_block_size")
Mohamad Ayyash1b6d3482016-06-15 15:53:07 -0700595 copy_prop("vendor_squashfs_disable_4k_align", "squashfs_disable_4k_align")
Mohamad Ayyashf8765552016-03-02 21:07:23 -0800596 copy_prop("vendor_base_fs_file", "base_fs_file")
Ying Wangb8888432014-03-11 17:13:27 -0700597 elif mount_point == "oem":
598 copy_prop("fs_type", "fs_type")
599 copy_prop("oem_size", "partition_size")
Ying Wangf3b86352014-11-18 18:03:13 -0800600 copy_prop("oem_journal_size", "journal_size")
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700601 copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
Ying Wangbd93d422011-10-28 17:02:30 -0700602
603 return d
604
605
606def LoadGlobalDict(filename):
607 """Load "name=value" pairs from filename"""
608 d = {}
609 f = open(filename)
610 for line in f:
611 line = line.strip()
612 if not line or line.startswith("#"):
613 continue
614 k, v = line.split("=", 1)
615 d[k] = v
616 f.close()
617 return d
618
619
620def main(argv):
Thierry Strudel74a81e62015-07-09 09:54:55 -0700621 if len(argv) != 4:
Ying Wangbd93d422011-10-28 17:02:30 -0700622 print __doc__
623 sys.exit(1)
624
625 in_dir = argv[0]
626 glob_dict_file = argv[1]
627 out_file = argv[2]
Thierry Strudel74a81e62015-07-09 09:54:55 -0700628 target_out = argv[3]
Ying Wangbd93d422011-10-28 17:02:30 -0700629
630 glob_dict = LoadGlobalDict(glob_dict_file)
Ying Wangae61f502015-03-12 18:30:39 -0700631 if "mount_point" in glob_dict:
Tao Baoc7a6f1e2015-06-23 11:16:05 -0700632 # The caller knows the mount point and provides a dictionay needed by
633 # BuildImage().
Ying Wangae61f502015-03-12 18:30:39 -0700634 image_properties = glob_dict
Ying Wang9f8e8db2011-11-04 11:37:01 -0700635 else:
Ying Wangae61f502015-03-12 18:30:39 -0700636 image_filename = os.path.basename(out_file)
637 mount_point = ""
638 if image_filename == "system.img":
639 mount_point = "system"
Alex Light4e358ab2016-06-16 14:47:10 -0700640 elif image_filename == "system_other.img":
641 mount_point = "system_other"
Ying Wangae61f502015-03-12 18:30:39 -0700642 elif image_filename == "userdata.img":
643 mount_point = "data"
644 elif image_filename == "cache.img":
645 mount_point = "cache"
646 elif image_filename == "vendor.img":
647 mount_point = "vendor"
648 elif image_filename == "oem.img":
649 mount_point = "oem"
650 else:
651 print >> sys.stderr, "error: unknown image file name ", image_filename
652 exit(1)
Ying Wangbd93d422011-10-28 17:02:30 -0700653
Ying Wangae61f502015-03-12 18:30:39 -0700654 image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
655
Thierry Strudel74a81e62015-07-09 09:54:55 -0700656 if not BuildImage(in_dir, image_properties, out_file, target_out):
Dan Albert8b72aef2015-03-23 19:13:21 -0700657 print >> sys.stderr, "error: failed to build %s from %s" % (out_file,
658 in_dir)
Ying Wangbd93d422011-10-28 17:02:30 -0700659 exit(1)
660
661
662if __name__ == '__main__':
663 main(sys.argv[1:])