blob: 7cb907260337f097f6ae6292c9de576055176114 [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
81def AddVendor(output_zip, prefix="IMAGES/"):
82 """Turn the contents of VENDOR into a vendor image and store in it
83 output_zip."""
Michael Runge2e0d8fc2014-11-13 21:41:08 -080084
85 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "vendor.img")
86 if os.path.exists(prebuilt_path):
87 print "vendor.img already exists in %s, no need to rebuild..." % (prefix,)
88 return
89
Doug Zongkerfc44a512014-08-26 13:10:25 -070090 block_list = common.MakeTempFile(prefix="vendor-blocklist-", suffix=".map")
91 imgname = BuildVendor(OPTIONS.input_tmp, OPTIONS.info_dict,
Dan Albert8b72aef2015-03-23 19:13:21 -070092 block_list=block_list)
Dan Albert8e0178d2015-01-27 15:53:15 -080093 common.ZipWrite(output_zip, imgname, prefix + "vendor.img")
94 common.ZipWrite(output_zip, block_list, prefix + "vendor.map")
Doug Zongker3c84f562014-07-31 11:06:30 -070095
96
Doug Zongkerfc44a512014-08-26 13:10:25 -070097def BuildVendor(input_dir, info_dict, block_list=None):
98 """Build the (sparse) vendor image and return the name of a temp
99 file containing it."""
100 return CreateImage(input_dir, info_dict, "vendor", block_list=block_list)
101
102
103def CreateImage(input_dir, info_dict, what, block_list=None):
Doug Zongker3c84f562014-07-31 11:06:30 -0700104 print "creating " + what + ".img..."
105
Doug Zongkerfc44a512014-08-26 13:10:25 -0700106 img = common.MakeTempFile(prefix=what + "-", suffix=".img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700107
108 # The name of the directory it is making an image out of matters to
109 # mkyaffs2image. It wants "system" but we have a directory named
110 # "SYSTEM", so create a symlink.
111 try:
112 os.symlink(os.path.join(input_dir, what.upper()),
113 os.path.join(input_dir, what))
Dan Albert8b72aef2015-03-23 19:13:21 -0700114 except OSError as e:
115 # bogus error on my mac version?
116 # File "./build/tools/releasetools/img_from_target_files"
117 # os.path.join(OPTIONS.input_tmp, "system"))
118 # OSError: [Errno 17] File exists
119 if e.errno == errno.EEXIST:
Doug Zongker3c84f562014-07-31 11:06:30 -0700120 pass
121
122 image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
123 fstab = info_dict["fstab"]
124 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700125 image_props["fs_type"] = fstab["/" + what].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700126
Tao Bao822f5842015-09-30 16:01:14 -0700127 # Use a fixed timestamp (01/01/2009) when packaging the image.
128 # Bug: 24377993
129 epoch = datetime.datetime.fromtimestamp(0)
130 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
131 image_props["timestamp"] = int(timestamp)
132
Doug Zongker3c84f562014-07-31 11:06:30 -0700133 if what == "system":
134 fs_config_prefix = ""
135 else:
136 fs_config_prefix = what + "_"
137
138 fs_config = os.path.join(
139 input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
Dan Albert8b72aef2015-03-23 19:13:21 -0700140 if not os.path.exists(fs_config):
141 fs_config = None
Doug Zongker3c84f562014-07-31 11:06:30 -0700142
Ying Wanga2292c92015-03-24 19:07:40 -0700143 # Override values loaded from info_dict.
144 if fs_config:
145 image_props["fs_config"] = fs_config
Ying Wanga2292c92015-03-24 19:07:40 -0700146 if block_list:
147 image_props["block_list"] = block_list
Ying Wanga2292c92015-03-24 19:07:40 -0700148
Doug Zongker3c84f562014-07-31 11:06:30 -0700149 succ = build_image.BuildImage(os.path.join(input_dir, what),
Ying Wanga2292c92015-03-24 19:07:40 -0700150 image_props, img)
Doug Zongker3c84f562014-07-31 11:06:30 -0700151 assert succ, "build " + what + ".img image failed"
152
Doug Zongkerfc44a512014-08-26 13:10:25 -0700153 return img
Doug Zongker3c84f562014-07-31 11:06:30 -0700154
155
156def AddUserdata(output_zip, prefix="IMAGES/"):
Ying Wang2a048392015-06-25 13:56:53 -0700157 """Create a userdata image and store it in output_zip.
158
159 In most case we just create and store an empty userdata.img;
160 But the invoker can also request to create userdata.img with real
161 data from the target files, by setting "userdata_img_with_data=true"
162 in OPTIONS.info_dict.
163 """
Doug Zongker3c84f562014-07-31 11:06:30 -0700164
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800165 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "userdata.img")
166 if os.path.exists(prebuilt_path):
167 print "userdata.img already exists in %s, no need to rebuild..." % (prefix,)
168 return
169
Tao Bao2c15d9e2015-07-09 11:51:16 -0700170 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "data")
Doug Zongker3c84f562014-07-31 11:06:30 -0700171 # We only allow yaffs to have a 0/missing partition_size.
172 # Extfs, f2fs must have a size. Skip userdata.img if no size.
173 if (not image_props.get("fs_type", "").startswith("yaffs") and
174 not image_props.get("partition_size")):
175 return
176
177 print "creating userdata.img..."
178
Tao Bao822f5842015-09-30 16:01:14 -0700179 # Use a fixed timestamp (01/01/2009) when packaging the image.
180 # Bug: 24377993
181 epoch = datetime.datetime.fromtimestamp(0)
182 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
183 image_props["timestamp"] = int(timestamp)
184
Doug Zongker3c84f562014-07-31 11:06:30 -0700185 # The name of the directory it is making an image out of matters to
186 # mkyaffs2image. So we create a temp dir, and within it we create an
Ying Wang2a048392015-06-25 13:56:53 -0700187 # empty dir named "data", or a symlink to the DATA dir,
188 # and build the image from that.
Doug Zongker3c84f562014-07-31 11:06:30 -0700189 temp_dir = tempfile.mkdtemp()
190 user_dir = os.path.join(temp_dir, "data")
Ying Wang2a048392015-06-25 13:56:53 -0700191 empty = (OPTIONS.info_dict.get("userdata_img_with_data") != "true")
192 if empty:
193 # Create an empty dir.
194 os.mkdir(user_dir)
195 else:
196 # Symlink to the DATA dir.
197 os.symlink(os.path.join(OPTIONS.input_tmp, "DATA"),
198 user_dir)
199
Doug Zongker3c84f562014-07-31 11:06:30 -0700200 img = tempfile.NamedTemporaryFile()
201
202 fstab = OPTIONS.info_dict["fstab"]
203 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700204 image_props["fs_type"] = fstab["/data"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700205 succ = build_image.BuildImage(user_dir, image_props, img.name)
206 assert succ, "build userdata.img image failed"
207
208 common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700209 common.ZipWrite(output_zip, img.name, prefix + "userdata.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700210 img.close()
Ying Wang2a048392015-06-25 13:56:53 -0700211 shutil.rmtree(temp_dir)
Doug Zongker3c84f562014-07-31 11:06:30 -0700212
213
214def AddCache(output_zip, prefix="IMAGES/"):
215 """Create an empty cache image and store it in output_zip."""
216
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800217 prebuilt_path = os.path.join(OPTIONS.input_tmp, prefix, "cache.img")
218 if os.path.exists(prebuilt_path):
219 print "cache.img already exists in %s, no need to rebuild..." % (prefix,)
220 return
221
Tao Bao2c15d9e2015-07-09 11:51:16 -0700222 image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict, "cache")
Doug Zongker3c84f562014-07-31 11:06:30 -0700223 # The build system has to explicitly request for cache.img.
224 if "fs_type" not in image_props:
225 return
226
227 print "creating cache.img..."
228
Tao Bao822f5842015-09-30 16:01:14 -0700229 # Use a fixed timestamp (01/01/2009) when packaging the image.
230 # Bug: 24377993
231 epoch = datetime.datetime.fromtimestamp(0)
232 timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
233 image_props["timestamp"] = int(timestamp)
234
Doug Zongker3c84f562014-07-31 11:06:30 -0700235 # The name of the directory it is making an image out of matters to
236 # mkyaffs2image. So we create a temp dir, and within it we create an
237 # empty dir named "cache", and build the image from that.
238 temp_dir = tempfile.mkdtemp()
239 user_dir = os.path.join(temp_dir, "cache")
240 os.mkdir(user_dir)
241 img = tempfile.NamedTemporaryFile()
242
243 fstab = OPTIONS.info_dict["fstab"]
244 if fstab:
Dan Albert8b72aef2015-03-23 19:13:21 -0700245 image_props["fs_type"] = fstab["/cache"].fs_type
Doug Zongker3c84f562014-07-31 11:06:30 -0700246 succ = build_image.BuildImage(user_dir, image_props, img.name)
247 assert succ, "build cache.img image failed"
248
249 common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
Tao Bao2ed665a2015-04-01 11:21:55 -0700250 common.ZipWrite(output_zip, img.name, prefix + "cache.img")
Doug Zongker3c84f562014-07-31 11:06:30 -0700251 img.close()
252 os.rmdir(user_dir)
253 os.rmdir(temp_dir)
254
255
256def AddImagesToTargetFiles(filename):
257 OPTIONS.input_tmp, input_zip = common.UnzipTemp(filename)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700258
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800259 if not OPTIONS.add_missing:
260 for n in input_zip.namelist():
261 if n.startswith("IMAGES/"):
262 print "target_files appears to already contain images."
263 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700264
Doug Zongker3c84f562014-07-31 11:06:30 -0700265 try:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700266 input_zip.getinfo("VENDOR/")
267 has_vendor = True
268 except KeyError:
269 has_vendor = False
Doug Zongker3c84f562014-07-31 11:06:30 -0700270
Tao Bao2c15d9e2015-07-09 11:51:16 -0700271 OPTIONS.info_dict = common.LoadInfoDict(input_zip, OPTIONS.input_tmp)
Doug Zongker3c84f562014-07-31 11:06:30 -0700272
Tao Bao2ed665a2015-04-01 11:21:55 -0700273 common.ZipClose(input_zip)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700274 output_zip = zipfile.ZipFile(filename, "a",
275 compression=zipfile.ZIP_DEFLATED)
Doug Zongker3c84f562014-07-31 11:06:30 -0700276
Tao Baodb45efa2015-10-27 19:25:18 -0700277 has_recovery = (OPTIONS.info_dict.get("no_recovery") != "true")
278
Doug Zongkerfc44a512014-08-26 13:10:25 -0700279 def banner(s):
280 print "\n\n++++ " + s + " ++++\n\n"
Doug Zongker3c84f562014-07-31 11:06:30 -0700281
Doug Zongkerfc44a512014-08-26 13:10:25 -0700282 banner("boot")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800283 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "boot.img")
284 boot_image = None
285 if os.path.exists(prebuilt_path):
286 print "boot.img already exists in IMAGES/, no need to rebuild..."
287 if OPTIONS.rebuild_recovery:
288 boot_image = common.GetBootableImage(
289 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
290 else:
291 boot_image = common.GetBootableImage(
292 "IMAGES/boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
293 if boot_image:
294 boot_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700295
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800296 recovery_image = None
Tao Baodb45efa2015-10-27 19:25:18 -0700297 if has_recovery:
298 banner("recovery")
299 prebuilt_path = os.path.join(OPTIONS.input_tmp, "IMAGES", "recovery.img")
300 if os.path.exists(prebuilt_path):
301 print "recovery.img already exists in IMAGES/, no need to rebuild..."
302 if OPTIONS.rebuild_recovery:
303 recovery_image = common.GetBootableImage(
304 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp,
305 "RECOVERY")
306 else:
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800307 recovery_image = common.GetBootableImage(
308 "IMAGES/recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
Tao Baodb45efa2015-10-27 19:25:18 -0700309 if recovery_image:
310 recovery_image.AddToZip(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700311
Doug Zongkerfc44a512014-08-26 13:10:25 -0700312 banner("system")
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800313 AddSystem(output_zip, recovery_img=recovery_image, boot_img=boot_image)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700314 if has_vendor:
315 banner("vendor")
316 AddVendor(output_zip)
317 banner("userdata")
318 AddUserdata(output_zip)
319 banner("cache")
320 AddCache(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700321
Tao Baoa0421cd2015-11-16 16:32:27 -0800322 # For devices using A/B update, copy over images from RADIO/ to IMAGES/ and
323 # make sure we have all the needed images ready under IMAGES/.
324 ab_partitions = os.path.join(OPTIONS.input_tmp, "META", "ab_partitions.txt")
325 if os.path.exists(ab_partitions):
326 with open(ab_partitions, 'r') as f:
327 lines = f.readlines()
328 for line in lines:
329 img_name = line.strip() + ".img"
330 img_radio_path = os.path.join(OPTIONS.input_tmp, "RADIO", img_name)
331 if os.path.exists(img_radio_path):
332 common.ZipWrite(output_zip, img_radio_path,
333 os.path.join("IMAGES", img_name))
334
335 # Zip spec says: All slashes MUST be forward slashes.
336 img_path = 'IMAGES/' + img_name
337 assert img_path in output_zip.namelist(), "cannot find " + img_name
338
Tao Bao2ed665a2015-04-01 11:21:55 -0700339 common.ZipClose(output_zip)
Doug Zongker3c84f562014-07-31 11:06:30 -0700340
Doug Zongker3c84f562014-07-31 11:06:30 -0700341def main(argv):
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700342 def option_handler(o, a):
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800343 if o in ("-a", "--add_missing"):
344 OPTIONS.add_missing = True
345 elif o in ("-r", "--rebuild_recovery",):
346 OPTIONS.rebuild_recovery = True
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700347 elif o == "--replace_verity_private_key":
348 OPTIONS.replace_verity_private_key = (True, a)
349 elif o == "--replace_verity_public_key":
350 OPTIONS.replace_verity_public_key = (True, a)
351 elif o == "--verity_signer_path":
352 OPTIONS.verity_signer_path = a
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800353 else:
354 return False
355 return True
356
Dan Albert8b72aef2015-03-23 19:13:21 -0700357 args = common.ParseOptions(
358 argv, __doc__, extra_opts="ar",
Baligh Uddin59f4ff12015-09-16 21:20:30 -0700359 extra_long_opts=["add_missing", "rebuild_recovery",
360 "replace_verity_public_key=",
361 "replace_verity_private_key=",
362 "verity_signer_path="],
Dan Albert8b72aef2015-03-23 19:13:21 -0700363 extra_option_handler=option_handler)
Michael Runge2e0d8fc2014-11-13 21:41:08 -0800364
Doug Zongker3c84f562014-07-31 11:06:30 -0700365
366 if len(args) != 1:
367 common.Usage(__doc__)
368 sys.exit(1)
369
370 AddImagesToTargetFiles(args[0])
371 print "done."
372
373if __name__ == '__main__':
374 try:
375 common.CloseInheritedPipes()
376 main(sys.argv[1:])
Dan Albert8b72aef2015-03-23 19:13:21 -0700377 except common.ExternalError as e:
Doug Zongker3c84f562014-07-31 11:06:30 -0700378 print
379 print " ERROR: %s" % (e,)
380 print
381 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700382 finally:
383 common.Cleanup()