blob: c82a9eee65f70d10c52e5160998a0cb72c886e77 [file] [log] [blame]
Yifan Hong2b891ac2018-11-29 12:06:31 -08001#!/usr/bin/env python
2#
3# Copyright (C) 2018 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"""
18Usage: build_super_image input_file output_dir_or_file
19
20input_file: one of the following:
21 - directory containing extracted target files. It will load info from
22 META/misc_info.txt and build full super image / split images using source
23 images from IMAGES/.
24 - target files package. Same as above, but extracts the archive before
25 building super image.
26 - a dictionary file containing input arguments to build. Check
27 `dump_dynamic_partitions_info' for details.
28 In addition:
29 - "ab_update" needs to be true for A/B devices.
30 - If source images should be included in the output image (for super.img
31 and super split images), a list of "*_image" should be paths of each
32 source images.
33
34output_dir_or_file:
35 If a single super image is built (for super_empty.img, or super.img for
36 launch devices), this argument is the output file.
37 If a collection of split images are built (for retrofit devices), this
38 argument is the output directory.
39"""
40
41from __future__ import print_function
42
43import logging
44import os.path
45import shlex
46import sys
47import zipfile
48
49import common
50import sparse_img
51
52if sys.hexversion < 0x02070000:
53 print("Python 2.7 or newer is required.", file=sys.stderr)
54 sys.exit(1)
55
56logger = logging.getLogger(__name__)
57
58
59UNZIP_PATTERN = ["IMAGES/*", "META/*"]
60
61
62def GetPartitionSizeFromImage(img):
63 try:
64 simg = sparse_img.SparseImage(img)
65 return simg.blocksize * simg.total_blocks
66 except ValueError:
67 return os.path.getsize(img)
68
69
70def BuildSuperImageFromDict(info_dict, output):
71
72 cmd = [info_dict["lpmake"],
73 "--metadata-size", "65536",
74 "--super-name", info_dict["super_metadata_device"]]
75
76 ab_update = info_dict.get("ab_update") == "true"
77 retrofit = info_dict.get("dynamic_partition_retrofit") == "true"
78 block_devices = shlex.split(info_dict.get("super_block_devices", "").strip())
79 groups = shlex.split(info_dict.get("super_partition_groups", "").strip())
80
David Anderson212e5df2018-12-17 12:52:25 -080081 if ab_update and retrofit:
Yifan Hong2b891ac2018-11-29 12:06:31 -080082 cmd += ["--metadata-slots", "2"]
David Anderson212e5df2018-12-17 12:52:25 -080083 elif ab_update:
84 cmd += ["--metadata-slots", "3"]
Yifan Hong2b891ac2018-11-29 12:06:31 -080085 else:
David Anderson212e5df2018-12-17 12:52:25 -080086 cmd += ["--metadata-slots", "2"]
Yifan Hong2b891ac2018-11-29 12:06:31 -080087
88 if ab_update and retrofit:
89 cmd.append("--auto-slot-suffixing")
90
91 for device in block_devices:
92 size = info_dict["super_{}_device_size".format(device)]
93 cmd += ["--device", "{}:{}".format(device, size)]
94
95 append_suffix = ab_update and not retrofit
96 has_image = False
97 for group in groups:
98 group_size = info_dict["super_{}_group_size".format(group)]
99 if append_suffix:
100 cmd += ["--group", "{}_a:{}".format(group, group_size),
101 "--group", "{}_b:{}".format(group, group_size)]
102 else:
103 cmd += ["--group", "{}:{}".format(group, group_size)]
104
105 partition_list = shlex.split(
106 info_dict["super_{}_partition_list".format(group)].strip())
107
108 for partition in partition_list:
109 image = info_dict.get("{}_image".format(partition))
110 image_size = 0
111 if image:
112 image_size = GetPartitionSizeFromImage(image)
113 has_image = True
114 if append_suffix:
115 cmd += ["--partition",
116 "{}_a:readonly:{}:{}_a".format(partition, image_size, group),
117 "--partition",
118 "{}_b:readonly:0:{}_b".format(partition, group)]
119 if image:
120 # For A/B devices, super partition always contains sub-partitions in
121 # the _a slot, because this image should only be used for
122 # bootstrapping / initializing the device. When flashing the image,
123 # bootloader fastboot should always mark _a slot as bootable.
124 cmd += ["--image", "{}_a={}".format(partition, image)]
125 else:
126 cmd += ["--partition",
127 "{}:readonly:{}:{}".format(partition, image_size, group)]
128 if image:
129 cmd += ["--image", "{}={}".format(partition, image)]
130
131 if has_image:
132 cmd.append("--sparse")
133
134 cmd += ["--output", output]
135
136 common.RunAndCheckOutput(cmd)
137
138 if retrofit and has_image:
139 logger.info("Done writing images to directory %s", output)
140 else:
141 logger.info("Done writing image %s", output)
142
Yifan Honge98427a2018-12-07 10:08:27 -0800143 return True
144
Yifan Hong2b891ac2018-11-29 12:06:31 -0800145
146def BuildSuperImageFromExtractedTargetFiles(inp, out):
147 info_dict = common.LoadInfoDict(inp)
148 partition_list = shlex.split(
149 info_dict.get("dynamic_partition_list", "").strip())
Yifan Honge98427a2018-12-07 10:08:27 -0800150 missing_images = []
Yifan Hong2b891ac2018-11-29 12:06:31 -0800151 for partition in partition_list:
Yifan Honge98427a2018-12-07 10:08:27 -0800152 image_path = os.path.join(inp, "IMAGES", "{}.img".format(partition))
153 if not os.path.isfile(image_path):
154 missing_images.append(image_path)
155 else:
156 info_dict["{}_image".format(partition)] = image_path
157 if missing_images:
158 logger.warning("Skip building super image because the following "
159 "images are missing from target files:\n%s",
160 "\n".join(missing_images))
161 return False
Yifan Hong2b891ac2018-11-29 12:06:31 -0800162 return BuildSuperImageFromDict(info_dict, out)
163
164
165def BuildSuperImageFromTargetFiles(inp, out):
166 input_tmp = common.UnzipTemp(inp, UNZIP_PATTERN)
167 return BuildSuperImageFromExtractedTargetFiles(input_tmp, out)
168
169
170def BuildSuperImage(inp, out):
171
172 if isinstance(inp, dict):
173 logger.info("Building super image from info dict...")
174 return BuildSuperImageFromDict(inp, out)
175
176 if isinstance(inp, str):
177 if os.path.isdir(inp):
178 logger.info("Building super image from extracted target files...")
179 return BuildSuperImageFromExtractedTargetFiles(inp, out)
180
181 if zipfile.is_zipfile(inp):
182 logger.info("Building super image from target files...")
183 return BuildSuperImageFromTargetFiles(inp, out)
184
185 if os.path.isfile(inp):
186 with open(inp) as f:
187 lines = f.read()
188 logger.info("Building super image from info dict...")
189 return BuildSuperImageFromDict(common.LoadDictionaryFromLines(lines.split("\n")), out)
190
191 raise ValueError("{} is not a dictionary or a valid path".format(inp))
192
193
194def main(argv):
195
196 args = common.ParseOptions(argv, __doc__)
197
198 if len(args) != 2:
199 common.Usage(__doc__)
200 sys.exit(1)
201
202 common.InitLogging()
203
204 BuildSuperImage(args[0], args[1])
205
206
207if __name__ == "__main__":
208 try:
209 common.CloseInheritedPipes()
210 main(sys.argv[1:])
211 except common.ExternalError:
212 logger.exception("\n ERROR:\n")
213 sys.exit(1)
214 finally:
215 common.Cleanup()