blob: ddc0d0b29b5bf3b9915dc290483f95fe454fa3f1 [file] [log] [blame]
Doug Zongker3c84f562014-07-31 11:06:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2014 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"""
18Given a target-files zipfile that does not contain images (ie, does
19not have an IMAGES/ top-level subdirectory), produce the images and
20add them to the zipfile.
21
22Usage: add_img_to_target_files target_files
23"""
24
25import sys
26
27if sys.hexversion < 0x02070000:
28 print >> sys.stderr, "Python 2.7 or newer is required."
29 sys.exit(1)
30
Tao Bao822f5842015-09-30 16:01:14 -070031import datetime
Doug Zongker3c84f562014-07-31 11:06:30 -070032import errno
33import os
Ying Wang2a048392015-06-25 13:56:53 -070034import shutil
Doug Zongker3c84f562014-07-31 11:06:30 -070035import tempfile
36import zipfile
37
Doug Zongker3c84f562014-07-31 11:06:30 -070038import build_image
39import common
40
41OPTIONS = common.OPTIONS
42
Michael Runge2e0d8fc2014-11-13 21:41:08 -080043OPTIONS.add_missing = False
44OPTIONS.rebuild_recovery = False
Baligh Uddin59f4ff12015-09-16 21:20:30 -070045OPTIONS.replace_verity_public_key = False
46OPTIONS.replace_verity_private_key = False
47OPTIONS.verity_signer_path = None
Doug Zongker3c84f562014-07-31 11:06:30 -070048
Michael Runge2e0d8fc2014-11-13 21:41:08 -080049def AddSystem(output_zip, prefix="IMAGES/", recovery_img=None, boot_img=None):
Doug Zongker3c84f562014-07-31 11:06:30 -070050 """Turn the contents of SYSTEM into a system image and store it in
51 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -080052
53 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system.img")
54 if os.path.exists(prebuilt_path):
55 print "system.img already exists in %s, no need to rebuild..." % (prefix,)
56 return
57
58 def output_sink(fn, data):
Dan Albert8b72aef2015-03-23 19:13:21 -070059 ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
60 ofile.write(data)
61 ofile.close()
Michael Runge2e0d8fc2014-11-13 21:41:08 -080062
63 if OPTIONS.rebuild_recovery:
Dan Albert8b72aef2015-03-23 19:13:21 -070064 print "Building new recovery patch"
65 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink, recovery_img,
66 boot_img, info_dict=OPTIONS.info_dict)
Michael Runge2e0d8fc2014-11-13 21:41:08 -080067
Doug Zongkerfc44a512014-08-26 13:10:25 -070068 block_list = common.MakeTempFile(prefix="system-blocklist-", suffix=".map")
69 imgname = BuildSystem(OPTIONS.input_tmp, OPTIONS.info_dict,
70 block_list=block_list)
Dan Albert8e0178d2015-01-27 15:53:15 -080071 common.ZipWrite(output_zip, imgname, prefix + "system.img")
72 common.ZipWrite(output_zip, block_list, prefix + "system.map")
Doug Zongkerfc44a512014-08-26 13:10:25 -070073
74
75def BuildSystem(input_dir, info_dict, block_list=None):
76 """Build the (sparse) system image and return the name of a temp
77 file containing it."""
78 return CreateImage(input_dir, info_dict, "system", block_list=block_list)
79
80
Alex Light4e358ab2016-06-16 14:47:10 -070081def AddSystemOther(output_zip, prefix="IMAGES/"):
82 """Turn the contents of SYSTEM_OTHER into a system_other image
83 and store it in output_zip."""
84
85 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "system_other.img")
86 if os.path.exists(prebuilt_path):
87 print "system_other.img already exists in %s, no need to rebuild..." % (prefix,)
88 return
89
90 imgname = BuildSystemOther(OPTIONS.input_tmp, OPTIONS.info_dict)
91 common.ZipWrite(output_zip, imgname, prefix + "system_other.img")
92
93def BuildSystemOther(input_dir, info_dict):
94 """Build the (sparse) system_other image and return the name of a temp
95 file containing it."""
96 return CreateImage(input_dir, info_dict, "system_other", block_list=None)
97
98
Doug Zongkerfc44a512014-08-26 13:10:25 -070099def AddVendor(output_zip, prefix="IMAGES/"):
100 """Turn the contents of VENDOR into a vendor image and store in it
101 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800102
103 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "vendor.img")
104 if os.path.exists(prebuilt_path):
105 print "vendor.img already exists in %s, no need to rebuild..." % (prefix,)
106 return
107
Doug Zongkerfc44a512014-08-26 13:10:25 -0700108 block_list = common.MakeTempFile(prefix="vendor-blocklist-", suffix=".map")
109 imgname = BuildVendor(OPTIONS.input_tmp, OPTIONS.info_dict,
Dan Albert8b72aef2015-03-23 19:13:21 -0700110 block_list=block_list)
Dan Albert8e0178d2015-01-27 15:53:15 -0800111 common.ZipWrite(output_zip, imgname, prefix + "vendor.img")
112 common.ZipWrite(output_zip, block_list, prefix + "vendor.map")
Doug Zongker3c84f562014-07-31 11:06:30 -0700113
114
Doug Zongkerfc44a512014-08-26 13:10:25 -0700115def BuildVendor(input_dir, info_dict, block_list=None):
116 """Build the (sparse) vendor image and return the name of a temp
117 file containing it."""
118 return CreateImage(input_dir, info_dict, "vendor", block_list=block_list)
119
120
121def CreateImage(input_dir, info_dict, what, block_list=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700122 print "creating " + what + ".img..."
123
Doug Zongkerfc44a512014-08-26 13:10:25 -0700124 img = common.MakeTempFile(prefix=what + "-", suffix=".img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700125
126 # The name of the directory it is making an image out of matters to
127 # mkyaffs2image. It wants "system" but we have a directory named
128 # "SYSTEM", so create a symlink.
129 try:
130 os.symlink(os.path.join(input_dir, what.upper()),
131 os.path.join(input_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700132 except OSError as e:
133 # bogus error on my mac version?
134 # File "./build/tools/releasetools/img_from_target_files"
135 # os.path.join(OPTIONS.input_tmp, "system"))
136 # OSError: [Errno 17] File exists
137 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700138 pass
139
140 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
141 fstab = info_dict["fstab"]
142 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700143 image_props["fs_type"] = fstab["/" + what].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700144
Tao Bao822f5842015-09-30 16:01:14 -0700145 # Use a fixed timestamp (01/01/2009) when packaging the image.
146 # Bug: 24377993
147 epoch = datetime.datetime.fromtimestamp(0)
148 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
149 image_props["timestamp"] = int(timestamp)
150
Doug Zongker3c84f562014-07-31 11:06:30 -0700151 if what == "system":
152 fs_config_prefix = ""
153 else:
154 fs_config_prefix = what + "_"
155
156 fs_config = os.path.join(
157 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700158 if not os.path.exists(fs_config):
159 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700160
Ying Wanga2292c92015-03-24 19:07:40 -0700161 # Override values loaded from info_dict.
162 if fs_config:
163 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700164 if block_list:
165 image_props["block_list"] = block_list
Ying Wanga2292c92015-03-24 19:07:40 -0700166
Doug Zongker3c84f562014-07-31 11:06:30 -0700167 succ = build_image.BuildImage(os.path.join(input_dir, what),
Ying Wanga2292c92015-03-24 19:07:40 -0700168 image_props, img)
Doug Zongker3c84f562014-07-31 11:06:30 -0700169 assert succ, "build " + what + ".img image failed"
170
Doug Zongkerfc44a512014-08-26 13:10:25 -0700171 return img
Doug Zongker3c84f562014-07-31 11:06:30 -0700172
173
174def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700175 """Create a userdata image and store it in output_zip.
176
177 In most case we just create and store an empty userdata.img;
178 But the invoker can also request to create userdata.img with real
179 data from the target files, by setting "userdata_img_with_data=true"
180 in OPTIONS.info_dict.
181 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700182
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800183 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "userdata.img")
184 if os.path.exists(prebuilt_path):
185 print "userdata.img already exists in %s, no need to rebuild..." % (prefix,)
186 return
187
Tao Bao2c15d9e2015-07-09 11:51:16 -0700188 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Doug Zongker3c84f562014-07-31 11:06:30 -0700189 # We only allow yaffs to have a 0/missing partition_size.
190 # Extfs, f2fs must have a size. Skip userdata.img if no size.
191 if (not image_props.get("fs_type", "").startswith("yaffs") and
192 not image_props.get("partition_size")):
193 return
194
195 print "creating userdata.img..."
196
Tao Bao822f5842015-09-30 16:01:14 -0700197 # Use a fixed timestamp (01/01/2009) when packaging the image.
198 # Bug: 24377993
199 epoch = datetime.datetime.fromtimestamp(0)
200 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
201 image_props["timestamp"] = int(timestamp)
202
Doug Zongker3c84f562014-07-31 11:06:30 -0700203 # The name of the directory it is making an image out of matters to
204 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700205 # empty dir named "data", or a symlink to the DATA dir,
206 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700207 temp_dir = tempfile.mkdtemp()
208 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700209 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
210 if empty:
211 # Create an empty dir.
212 os.mkdir(user_dir)
213 else:
214 # Symlink to the DATA dir.
215 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
216 user_dir)
217
Doug Zongker3c84f562014-07-31 11:06:30 -0700218 img = tempfile.NamedTemporaryFile()
219
220 fstab = OPTIONS.info_dict["fstab"]
221 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700222 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700223 succ = build_image.BuildImage(user_dir, image_props, img.name)
224 assert succ, "build userdata.img image failed"
225
226 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700227 common.ZipWrite(output_zip, img.name, prefix + "userdata.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700228 img.close()
Ying Wang2a048392015-06-25 13:56:53 -0700229 shutil.rmtree(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700230
231
232def AddCache(output_zip, prefix="IMAGES/"):
233 """Create an empty cache image and store it in output_zip."""
234
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800235 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "cache.img")
236 if os.path.exists(prebuilt_path):
237 print "cache.img already exists in %s, no need to rebuild..." % (prefix,)
238 return
239
Tao Bao2c15d9e2015-07-09 11:51:16 -0700240 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700241 # The build system has to explicitly request for cache.img.
242 if "fs_type" not in image_props:
243 return
244
245 print "creating cache.img..."
246
Tao Bao822f5842015-09-30 16:01:14 -0700247 # Use a fixed timestamp (01/01/2009) when packaging the image.
248 # Bug: 24377993
249 epoch = datetime.datetime.fromtimestamp(0)
250 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
251 image_props["timestamp"] = int(timestamp)
252
Doug Zongker3c84f562014-07-31 11:06:30 -0700253 # The name of the directory it is making an image out of matters to
254 # mkyaffs2image. So we create a temp dir, and within it we create an
255 # empty dir named "cache", and build the image from that.
256 temp_dir = tempfile.mkdtemp()
257 user_dir = os.path.join(temp_dir, "cache")
258 os.mkdir(user_dir)
259 img = tempfile.NamedTemporaryFile()
260
261 fstab = OPTIONS.info_dict["fstab"]
262 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700263 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700264 succ = build_image.BuildImage(user_dir, image_props, img.name)
265 assert succ, "build cache.img image failed"
266
267 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700268 common.ZipWrite(output_zip, img.name, prefix + "cache.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700269 img.close()
270 os.rmdir(user_dir)
271 os.rmdir(temp_dir)
272
273
274def AddImagesToTargetFiles(filename):
275 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700276
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800277 if not OPTIONS.add_missing:
278 for n in input_zip.namelist():
279 if n.startswith("IMAGES/"):
280 print "target_files appears to already contain images."
281 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700282
Doug Zongker3c84f562014-07-31 11:06:30 -0700283 try:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700284 input_zip.getinfo("VENDOR/")
285 has_vendor = True
286 except KeyError:
287 has_vendor = False
Doug Zongker3c84f562014-07-31 11:06:30 -0700288
Alex Light4e358ab2016-06-16 14:47:10 -0700289 has_system_other = "SYSTEM_OTHER/" in input_zip.namelist()
290
Tao Bao2c15d9e2015-07-09 11:51:16 -0700291 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700292
Tao Bao2ed665a2015-04-01 11:21:55 -0700293 common.ZipClose(input_zip)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700294 output_zip = zipfile.ZipFile(filename, "a",
295 compression=zipfile.ZIP_DEFLATED)
Doug Zongker3c84f562014-07-31 11:06:30 -0700296
Tao Baodb45efa2015-10-27 19:25:18 -0700297 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
298
Doug Zongkerfc44a512014-08-26 13:10:25 -0700299 def banner(s):
300 print "\n\n++++ " + s + " ++++\n\n"
Doug Zongker3c84f562014-07-31 11:06:30 -0700301
Doug Zongkerfc44a512014-08-26 13:10:25 -0700302 banner("boot")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800303 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
304 boot_image = None
305 if os.path.exists(prebuilt_path):
306 print "boot.img already exists in IMAGES/, no need to rebuild..."
307 if OPTIONS.rebuild_recovery:
308 boot_image = common.GetBootableImage(
309 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
310 else:
311 boot_image = common.GetBootableImage(
312 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
313 if boot_image:
314 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700315
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800316 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700317 if has_recovery:
318 banner("recovery")
319 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
320 if os.path.exists(prebuilt_path):
321 print "recovery.img already exists in IMAGES/, no need to rebuild..."
322 if OPTIONS.rebuild_recovery:
323 recovery_image = common.GetBootableImage(
324 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
325 "RECOVERY")
326 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800327 recovery_image = common.GetBootableImage(
328 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700329 if recovery_image:
330 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700331
Doug Zongkerfc44a512014-08-26 13:10:25 -0700332 banner("system")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800333 AddSystem(output_zip, recovery_img=recovery_image, boot_img=boot_image)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700334 if has_vendor:
335 banner("vendor")
336 AddVendor(output_zip)
Alex Light4e358ab2016-06-16 14:47:10 -0700337 if has_system_other:
338 banner("system_other")
339 AddSystemOther(output_zip)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700340 banner("userdata")
341 AddUserdata(output_zip)
342 banner("cache")
343 AddCache(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700344
Tao Baoa0421cd2015-11-16 16:32:27 -0800345 # For devices using A/B update, copy over images from RADIO/ to IMAGES/ and
346 # make sure we have all the needed images ready under IMAGES/.
347 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
348 if os.path.exists(ab_partitions):
349 with open(ab_partitions, 'r') as f:
350 lines = f.readlines()
351 for line in lines:
352 img_name = line.strip() + ".img"
353 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
354 if os.path.exists(img_radio_path):
355 common.ZipWrite(output_zip, img_radio_path,
356 os.path.join("IMAGES", img_name))
357
358 # Zip spec says: All slashes MUST be forward slashes.
359 img_path = 'IMAGES/' + img_name
360 assert img_path in output_zip.namelist(), "cannot find " + img_name
361
Tao Bao2ed665a2015-04-01 11:21:55 -0700362 common.ZipClose(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700363
Doug Zongker3c84f562014-07-31 11:06:30 -0700364def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700365 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800366 if o in ("-a", "--add_missing"):
367 OPTIONS.add_missing = True
368 elif o in ("-r", "--rebuild_recovery",):
369 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700370 elif o == "--replace_verity_private_key":
371 OPTIONS.replace_verity_private_key = (True, a)
372 elif o == "--replace_verity_public_key":
373 OPTIONS.replace_verity_public_key = (True, a)
374 elif o == "--verity_signer_path":
375 OPTIONS.verity_signer_path = a
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800376 else:
377 return False
378 return True
379
Dan Albert8b72aef2015-03-23 19:13:21 -0700380 args = common.ParseOptions(
381 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700382 extra_long_opts=["add_missing", "rebuild_recovery",
383 "replace_verity_public_key=",
384 "replace_verity_private_key=",
385 "verity_signer_path="],
Dan Albert8b72aef2015-03-23 19:13:21 -0700386 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800387
Doug Zongker3c84f562014-07-31 11:06:30 -0700388
389 if len(args) != 1:
390 common.Usage(__doc__)
391 sys.exit(1)
392
393 AddImagesToTargetFiles(args[0])
394 print "done."
395
396if __name__ == '__main__':
397 try:
398 common.CloseInheritedPipes()
399 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700400 except common.ExternalError as e:
Doug Zongker3c84f562014-07-31 11:06:30 -0700401 print
402 print " ERROR: %s" % (e,)
403 print
404 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700405 finally:
406 common.Cleanup()