blob: 2d596a4a03cd7d531b184bf5957996fb2f41a70e [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
Yifan Hong69e0d612019-03-11 15:55:33 -070027 `dump-super-image-info' for details.
Yifan Hong2b891ac2018-11-29 12:06:31 -080028 In addition:
Yifan Hong2b891ac2018-11-29 12:06:31 -080029 - If source images should be included in the output image (for super.img
30 and super split images), a list of "*_image" should be paths of each
31 source images.
32
33output_dir_or_file:
34 If a single super image is built (for super_empty.img, or super.img for
35 launch devices), this argument is the output file.
36 If a collection of split images are built (for retrofit devices), this
37 argument is the output directory.
38"""
39
40from __future__ import print_function
41
42import logging
43import os.path
44import shlex
45import sys
46import zipfile
47
48import common
49import sparse_img
50
51if sys.hexversion < 0x02070000:
52 print("Python 2.7 or newer is required.", file=sys.stderr)
53 sys.exit(1)
54
55logger = logging.getLogger(__name__)
56
57
58UNZIP_PATTERN = ["IMAGES/*", "META/*"]
59
60
61def GetPartitionSizeFromImage(img):
62 try:
63 simg = sparse_img.SparseImage(img)
64 return simg.blocksize * simg.total_blocks
65 except ValueError:
66 return os.path.getsize(img)
67
68
Yifan Hongcc46eae2019-01-02 11:51:19 -080069def GetArgumentsForImage(partition, group, image=None):
70 image_size = GetPartitionSizeFromImage(image) if image else 0
71
72 cmd = ["--partition",
73 "{}:readonly:{}:{}".format(partition, image_size, group)]
74 if image:
75 cmd += ["--image", "{}={}".format(partition, image)]
76
77 return cmd
78
79
Yifan Hong2b891ac2018-11-29 12:06:31 -080080def BuildSuperImageFromDict(info_dict, output):
81
82 cmd = [info_dict["lpmake"],
83 "--metadata-size", "65536",
84 "--super-name", info_dict["super_metadata_device"]]
85
86 ab_update = info_dict.get("ab_update") == "true"
87 retrofit = info_dict.get("dynamic_partition_retrofit") == "true"
88 block_devices = shlex.split(info_dict.get("super_block_devices", "").strip())
89 groups = shlex.split(info_dict.get("super_partition_groups", "").strip())
90
David Anderson212e5df2018-12-17 12:52:25 -080091 if ab_update and retrofit:
Yifan Hong2b891ac2018-11-29 12:06:31 -080092 cmd += ["--metadata-slots", "2"]
David Anderson212e5df2018-12-17 12:52:25 -080093 elif ab_update:
94 cmd += ["--metadata-slots", "3"]
Yifan Hong2b891ac2018-11-29 12:06:31 -080095 else:
David Anderson212e5df2018-12-17 12:52:25 -080096 cmd += ["--metadata-slots", "2"]
Yifan Hong2b891ac2018-11-29 12:06:31 -080097
98 if ab_update and retrofit:
99 cmd.append("--auto-slot-suffixing")
100
101 for device in block_devices:
102 size = info_dict["super_{}_device_size".format(device)]
103 cmd += ["--device", "{}:{}".format(device, size)]
104
105 append_suffix = ab_update and not retrofit
106 has_image = False
107 for group in groups:
108 group_size = info_dict["super_{}_group_size".format(group)]
109 if append_suffix:
110 cmd += ["--group", "{}_a:{}".format(group, group_size),
111 "--group", "{}_b:{}".format(group, group_size)]
112 else:
113 cmd += ["--group", "{}:{}".format(group, group_size)]
114
115 partition_list = shlex.split(
116 info_dict["super_{}_partition_list".format(group)].strip())
117
118 for partition in partition_list:
119 image = info_dict.get("{}_image".format(partition))
Yifan Hong2b891ac2018-11-29 12:06:31 -0800120 if image:
Yifan Hong2b891ac2018-11-29 12:06:31 -0800121 has_image = True
Yifan Hongcc46eae2019-01-02 11:51:19 -0800122
123 if not append_suffix:
124 cmd += GetArgumentsForImage(partition, group, image)
125 continue
126
127 # For A/B devices, super partition always contains sub-partitions in
128 # the _a slot, because this image should only be used for
129 # bootstrapping / initializing the device. When flashing the image,
130 # bootloader fastboot should always mark _a slot as bootable.
131 cmd += GetArgumentsForImage(partition + "_a", group + "_a", image)
132
133 other_image = None
134 if partition == "system" and "system_other_image" in info_dict:
135 other_image = info_dict["system_other_image"]
136 has_image = True
137
138 cmd += GetArgumentsForImage(partition + "_b", group + "_b", other_image)
Yifan Hong2b891ac2018-11-29 12:06:31 -0800139
Yifan Hongc3664702019-04-02 16:29:59 -0700140 if info_dict.get("build_non_sparse_super_partition") != "true":
Yifan Hong2b891ac2018-11-29 12:06:31 -0800141 cmd.append("--sparse")
142
143 cmd += ["--output", output]
144
145 common.RunAndCheckOutput(cmd)
146
147 if retrofit and has_image:
148 logger.info("Done writing images to directory %s", output)
149 else:
150 logger.info("Done writing image %s", output)
151
Yifan Honge98427a2018-12-07 10:08:27 -0800152 return True
153
Yifan Hong2b891ac2018-11-29 12:06:31 -0800154
155def BuildSuperImageFromExtractedTargetFiles(inp, out):
156 info_dict = common.LoadInfoDict(inp)
157 partition_list = shlex.split(
158 info_dict.get("dynamic_partition_list", "").strip())
Yifan Hongcc46eae2019-01-02 11:51:19 -0800159
160 if "system" in partition_list:
161 image_path = os.path.join(inp, "IMAGES", "system_other.img")
162 if os.path.isfile(image_path):
163 info_dict["system_other_image"] = image_path
164
Yifan Honge98427a2018-12-07 10:08:27 -0800165 missing_images = []
Yifan Hong2b891ac2018-11-29 12:06:31 -0800166 for partition in partition_list:
Yifan Honge98427a2018-12-07 10:08:27 -0800167 image_path = os.path.join(inp, "IMAGES", "{}.img".format(partition))
168 if not os.path.isfile(image_path):
169 missing_images.append(image_path)
170 else:
171 info_dict["{}_image".format(partition)] = image_path
172 if missing_images:
173 logger.warning("Skip building super image because the following "
174 "images are missing from target files:\n%s",
175 "\n".join(missing_images))
176 return False
Yifan Hong2b891ac2018-11-29 12:06:31 -0800177 return BuildSuperImageFromDict(info_dict, out)
178
179
180def BuildSuperImageFromTargetFiles(inp, out):
181 input_tmp = common.UnzipTemp(inp, UNZIP_PATTERN)
182 return BuildSuperImageFromExtractedTargetFiles(input_tmp, out)
183
184
185def BuildSuperImage(inp, out):
186
187 if isinstance(inp, dict):
188 logger.info("Building super image from info dict...")
189 return BuildSuperImageFromDict(inp, out)
190
191 if isinstance(inp, str):
192 if os.path.isdir(inp):
193 logger.info("Building super image from extracted target files...")
194 return BuildSuperImageFromExtractedTargetFiles(inp, out)
195
196 if zipfile.is_zipfile(inp):
197 logger.info("Building super image from target files...")
198 return BuildSuperImageFromTargetFiles(inp, out)
199
200 if os.path.isfile(inp):
201 with open(inp) as f:
202 lines = f.read()
203 logger.info("Building super image from info dict...")
204 return BuildSuperImageFromDict(common.LoadDictionaryFromLines(lines.split("\n")), out)
205
206 raise ValueError("{} is not a dictionary or a valid path".format(inp))
207
208
209def main(argv):
210
211 args = common.ParseOptions(argv, __doc__)
212
213 if len(args) != 2:
214 common.Usage(__doc__)
215 sys.exit(1)
216
217 common.InitLogging()
218
219 BuildSuperImage(args[0], args[1])
220
221
222if __name__ == "__main__":
223 try:
224 common.CloseInheritedPipes()
225 main(sys.argv[1:])
226 except common.ExternalError:
227 logger.exception("\n ERROR:\n")
228 sys.exit(1)
229 finally:
230 common.Cleanup()