blob: 6517bf347db77697bea1b8f2528b8121029152a7 [file] [log] [blame]
Doug Zongkereef39442009-04-02 12:14:19 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2008 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, produces an OTA package that installs
19that build. An incremental OTA is produced if -i is given, otherwise
20a full OTA is produced.
21
22Usage: ota_from_target_files [flags] input_target_files output_ota_package
23
Doug Zongker25568482014-03-03 10:21:27 -080024 --board_config <file>
Doug Zongkerfdd8e692009-08-03 17:27:48 -070025 Deprecated.
Doug Zongkereef39442009-04-02 12:14:19 -070026
Doug Zongkerafb32ea2011-09-22 10:28:04 -070027 -k (--package_key) <key> Key to use to sign the package (default is
28 the value of default_system_dev_certificate from the input
29 target-files's META/misc_info.txt, or
30 "build/target/product/security/testkey" if that value is not
31 specified).
32
33 For incremental OTAs, the default value is based on the source
34 target-file, not the target build.
Doug Zongkereef39442009-04-02 12:14:19 -070035
36 -i (--incremental_from) <file>
37 Generate an incremental OTA using the given target-files zip as
38 the starting build.
39
Michael Runge63f01de2014-10-28 19:24:19 -070040 -v (--verify)
41 Remount and verify the checksums of the files written to the
42 system and vendor (if used) partitions. Incremental builds only.
43
Michael Runge6e836112014-04-15 17:40:21 -070044 -o (--oem_settings) <file>
45 Use the file to specify the expected OEM-specific properties
46 on the OEM partition of the intended device.
47
Doug Zongkerdbfaae52009-04-21 17:12:54 -070048 -w (--wipe_user_data)
49 Generate an OTA package that will wipe the user data partition
50 when installed.
51
Doug Zongker962069c2009-04-23 11:41:58 -070052 -n (--no_prereq)
53 Omit the timestamp prereq check normally included at the top of
54 the build scripts (used for developer OTA packages which
55 legitimately need to go back and forth).
56
Doug Zongker1c390a22009-05-14 19:06:36 -070057 -e (--extra_script) <file>
58 Insert the contents of file at the end of the update script.
59
Hristo Bojinovdafb0422010-08-26 14:35:16 -070060 -a (--aslr_mode) <on|off>
61 Specify whether to turn on ASLR for the package (on by default).
Stephen Smalley56882bf2012-02-09 13:36:21 -050062
Doug Zongker9b23f2c2013-11-25 14:44:12 -080063 -2 (--two_step)
64 Generate a 'two-step' OTA package, where recovery is updated
65 first, so that any changes made to the system partition are done
66 using the new recovery (new kernel, etc.).
67
Doug Zongker26e66192014-02-20 13:22:07 -080068 --block
69 Generate a block-based OTA if possible. Will fall back to a
70 file-based OTA if the target_files is older and doesn't support
71 block-based OTAs.
72
Doug Zongker25568482014-03-03 10:21:27 -080073 -b (--binary) <file>
74 Use the given binary as the update-binary in the output package,
75 instead of the binary in the build's target_files. Use for
76 development only.
77
Martin Blumenstingl374e1142014-05-31 20:42:55 +020078 -t (--worker_threads) <int>
79 Specifies the number of worker-threads that will be used when
80 generating patches for incremental updates (defaults to 3).
81
Doug Zongkereef39442009-04-02 12:14:19 -070082"""
83
84import sys
85
Doug Zongkercf6d5a92014-02-18 10:57:07 -080086if sys.hexversion < 0x02070000:
87 print >> sys.stderr, "Python 2.7 or newer is required."
Doug Zongkereef39442009-04-02 12:14:19 -070088 sys.exit(1)
89
90import copy
Doug Zongkerc18736b2009-09-30 09:20:32 -070091import errno
Doug Zongkerfc44a512014-08-26 13:10:25 -070092import multiprocessing
Doug Zongkereef39442009-04-02 12:14:19 -070093import os
94import re
Doug Zongkereef39442009-04-02 12:14:19 -070095import subprocess
96import tempfile
97import time
98import zipfile
99
Doug Zongkerfc44a512014-08-26 13:10:25 -0700100from hashlib import sha1 as sha1
davidcad0bb92011-03-15 14:21:38 +0000101
Doug Zongkereef39442009-04-02 12:14:19 -0700102import common
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700103import edify_generator
Geremy Condra36bd3652014-02-06 19:45:10 -0800104import build_image
Doug Zongkerfc44a512014-08-26 13:10:25 -0700105import blockimgdiff
106import sparse_img
Doug Zongkereef39442009-04-02 12:14:19 -0700107
108OPTIONS = common.OPTIONS
Doug Zongkerafb32ea2011-09-22 10:28:04 -0700109OPTIONS.package_key = None
Doug Zongkereef39442009-04-02 12:14:19 -0700110OPTIONS.incremental_source = None
Michael Runge63f01de2014-10-28 19:24:19 -0700111OPTIONS.verify = False
Doug Zongkereef39442009-04-02 12:14:19 -0700112OPTIONS.require_verbatim = set()
113OPTIONS.prohibit_verbatim = set(("system/build.prop",))
114OPTIONS.patch_threshold = 0.95
Doug Zongkerdbfaae52009-04-21 17:12:54 -0700115OPTIONS.wipe_user_data = False
Doug Zongker962069c2009-04-23 11:41:58 -0700116OPTIONS.omit_prereq = False
Doug Zongker1c390a22009-05-14 19:06:36 -0700117OPTIONS.extra_script = None
Hristo Bojinovdafb0422010-08-26 14:35:16 -0700118OPTIONS.aslr_mode = True
Doug Zongkerfc44a512014-08-26 13:10:25 -0700119OPTIONS.worker_threads = multiprocessing.cpu_count() // 2
120if OPTIONS.worker_threads == 0:
121 OPTIONS.worker_threads = 1
Doug Zongker9b23f2c2013-11-25 14:44:12 -0800122OPTIONS.two_step = False
Takeshi Kanemotoe153b342013-11-14 17:20:50 +0900123OPTIONS.no_signing = False
Doug Zongker26e66192014-02-20 13:22:07 -0800124OPTIONS.block_based = False
Doug Zongker25568482014-03-03 10:21:27 -0800125OPTIONS.updater_binary = None
Michael Runge6e836112014-04-15 17:40:21 -0700126OPTIONS.oem_source = None
Doug Zongker62d4f182014-08-04 16:06:43 -0700127OPTIONS.fallback_to_full = True
Doug Zongkereef39442009-04-02 12:14:19 -0700128
129def MostPopularKey(d, default):
130 """Given a dict, return the key corresponding to the largest
131 value. Returns 'default' if the dict is empty."""
132 x = [(v, k) for (k, v) in d.iteritems()]
133 if not x: return default
134 x.sort()
135 return x[-1][1]
136
137
138def IsSymlink(info):
139 """Return true if the zipfile.ZipInfo object passed in represents a
140 symlink."""
141 return (info.external_attr >> 16) == 0120777
142
Hristo Bojinov96be7202010-08-02 10:26:17 -0700143def IsRegular(info):
144 """Return true if the zipfile.ZipInfo object passed in represents a
145 symlink."""
146 return (info.external_attr >> 28) == 010
Doug Zongkereef39442009-04-02 12:14:19 -0700147
Michael Runge4038aa82013-12-13 18:06:28 -0800148def ClosestFileMatch(src, tgtfiles, existing):
149 """Returns the closest file match between a source file and list
150 of potential matches. The exact filename match is preferred,
151 then the sha1 is searched for, and finally a file with the same
152 basename is evaluated. Rename support in the updater-binary is
153 required for the latter checks to be used."""
154
155 result = tgtfiles.get("path:" + src.name)
156 if result is not None:
157 return result
158
159 if not OPTIONS.target_info_dict.get("update_rename_support", False):
160 return None
161
162 if src.size < 1000:
163 return None
164
165 result = tgtfiles.get("sha1:" + src.sha1)
166 if result is not None and existing.get(result.name) is None:
167 return result
168 result = tgtfiles.get("file:" + src.name.split("/")[-1])
169 if result is not None and existing.get(result.name) is None:
170 return result
171 return None
172
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700173class ItemSet:
174 def __init__(self, partition, fs_config):
175 self.partition = partition
176 self.fs_config = fs_config
177 self.ITEMS = {}
Doug Zongkereef39442009-04-02 12:14:19 -0700178
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700179 def Get(self, name, dir=False):
180 if name not in self.ITEMS:
181 self.ITEMS[name] = Item(self, name, dir=dir)
182 return self.ITEMS[name]
Doug Zongkereef39442009-04-02 12:14:19 -0700183
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700184 def GetMetadata(self, input_zip):
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700185 # The target_files contains a record of what the uid,
186 # gid, and mode are supposed to be.
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700187 output = input_zip.read(self.fs_config)
Doug Zongkereef39442009-04-02 12:14:19 -0700188
189 for line in output.split("\n"):
190 if not line: continue
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700191 columns = line.split()
192 name, uid, gid, mode = columns[:4]
193 selabel = None
194 capabilities = None
195
196 # After the first 4 columns, there are a series of key=value
197 # pairs. Extract out the fields we care about.
198 for element in columns[4:]:
199 key, value = element.split("=")
200 if key == "selabel":
201 selabel = value
202 if key == "capabilities":
203 capabilities = value
204
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700205 i = self.ITEMS.get(name, None)
Doug Zongker283e2a12010-03-15 17:52:32 -0700206 if i is not None:
207 i.uid = int(uid)
208 i.gid = int(gid)
209 i.mode = int(mode, 8)
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700210 i.selabel = selabel
211 i.capabilities = capabilities
Doug Zongker283e2a12010-03-15 17:52:32 -0700212 if i.dir:
213 i.children.sort(key=lambda i: i.name)
214
215 # set metadata for the files generated by this script.
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700216 i = self.ITEMS.get("system/recovery-from-boot.p", None)
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700217 if i: i.uid, i.gid, i.mode, i.selabel, i.capabilities = 0, 0, 0644, None, None
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700218 i = self.ITEMS.get("system/etc/install-recovery.sh", None)
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700219 if i: i.uid, i.gid, i.mode, i.selabel, i.capabilities = 0, 0, 0544, None, None
Doug Zongkereef39442009-04-02 12:14:19 -0700220
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700221
222class Item:
223 """Items represent the metadata (user, group, mode) of files and
224 directories in the system image."""
225 def __init__(self, itemset, name, dir=False):
226 self.itemset = itemset
227 self.name = name
228 self.uid = None
229 self.gid = None
230 self.mode = None
231 self.selabel = None
232 self.capabilities = None
233 self.dir = dir
234
235 if name:
236 self.parent = itemset.Get(os.path.dirname(name), dir=True)
237 self.parent.children.append(self)
238 else:
239 self.parent = None
240 if dir:
241 self.children = []
242
243 def Dump(self, indent=0):
244 if self.uid is not None:
245 print "%s%s %d %d %o" % (" "*indent, self.name, self.uid, self.gid, self.mode)
246 else:
247 print "%s%s %s %s %s" % (" "*indent, self.name, self.uid, self.gid, self.mode)
248 if self.dir:
249 print "%s%s" % (" "*indent, self.descendants)
250 print "%s%s" % (" "*indent, self.best_subtree)
251 for i in self.children:
252 i.Dump(indent=indent+1)
253
Doug Zongkereef39442009-04-02 12:14:19 -0700254 def CountChildMetadata(self):
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700255 """Count up the (uid, gid, mode, selabel, capabilities) tuples for
256 all children and determine the best strategy for using set_perm_recursive and
Doug Zongkereef39442009-04-02 12:14:19 -0700257 set_perm to correctly chown/chmod all the files to their desired
258 values. Recursively calls itself for all descendants.
259
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700260 Returns a dict of {(uid, gid, dmode, fmode, selabel, capabilities): count} counting up
Doug Zongkereef39442009-04-02 12:14:19 -0700261 all descendants of this node. (dmode or fmode may be None.) Also
262 sets the best_subtree of each directory Item to the (uid, gid,
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700263 dmode, fmode, selabel, capabilities) tuple that will match the most
264 descendants of that Item.
Doug Zongkereef39442009-04-02 12:14:19 -0700265 """
266
267 assert self.dir
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700268 d = self.descendants = {(self.uid, self.gid, self.mode, None, self.selabel, self.capabilities): 1}
Doug Zongkereef39442009-04-02 12:14:19 -0700269 for i in self.children:
270 if i.dir:
271 for k, v in i.CountChildMetadata().iteritems():
272 d[k] = d.get(k, 0) + v
273 else:
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700274 k = (i.uid, i.gid, None, i.mode, i.selabel, i.capabilities)
Doug Zongkereef39442009-04-02 12:14:19 -0700275 d[k] = d.get(k, 0) + 1
276
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700277 # Find the (uid, gid, dmode, fmode, selabel, capabilities)
278 # tuple that matches the most descendants.
Doug Zongkereef39442009-04-02 12:14:19 -0700279
280 # First, find the (uid, gid) pair that matches the most
281 # descendants.
282 ug = {}
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700283 for (uid, gid, _, _, _, _), count in d.iteritems():
Doug Zongkereef39442009-04-02 12:14:19 -0700284 ug[(uid, gid)] = ug.get((uid, gid), 0) + count
285 ug = MostPopularKey(ug, (0, 0))
286
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700287 # Now find the dmode, fmode, selabel, and capabilities that match
288 # the most descendants with that (uid, gid), and choose those.
Doug Zongkereef39442009-04-02 12:14:19 -0700289 best_dmode = (0, 0755)
290 best_fmode = (0, 0644)
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700291 best_selabel = (0, None)
292 best_capabilities = (0, None)
Doug Zongkereef39442009-04-02 12:14:19 -0700293 for k, count in d.iteritems():
294 if k[:2] != ug: continue
295 if k[2] is not None and count >= best_dmode[0]: best_dmode = (count, k[2])
296 if k[3] is not None and count >= best_fmode[0]: best_fmode = (count, k[3])
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700297 if k[4] is not None and count >= best_selabel[0]: best_selabel = (count, k[4])
298 if k[5] is not None and count >= best_capabilities[0]: best_capabilities = (count, k[5])
299 self.best_subtree = ug + (best_dmode[1], best_fmode[1], best_selabel[1], best_capabilities[1])
Doug Zongkereef39442009-04-02 12:14:19 -0700300
301 return d
302
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700303 def SetPermissions(self, script):
Doug Zongkereef39442009-04-02 12:14:19 -0700304 """Append set_perm/set_perm_recursive commands to 'script' to
305 set all permissions, users, and groups for the tree of files
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700306 rooted at 'self'."""
Doug Zongkereef39442009-04-02 12:14:19 -0700307
308 self.CountChildMetadata()
309
310 def recurse(item, current):
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700311 # current is the (uid, gid, dmode, fmode, selabel, capabilities) tuple that the current
Doug Zongkereef39442009-04-02 12:14:19 -0700312 # item (and all its children) have already been set to. We only
313 # need to issue set_perm/set_perm_recursive commands if we're
314 # supposed to be something different.
315 if item.dir:
316 if current != item.best_subtree:
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700317 script.SetPermissionsRecursive("/"+item.name, *item.best_subtree)
Doug Zongkereef39442009-04-02 12:14:19 -0700318 current = item.best_subtree
319
320 if item.uid != current[0] or item.gid != current[1] or \
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700321 item.mode != current[2] or item.selabel != current[4] or \
322 item.capabilities != current[5]:
323 script.SetPermissions("/"+item.name, item.uid, item.gid,
324 item.mode, item.selabel, item.capabilities)
Doug Zongkereef39442009-04-02 12:14:19 -0700325
326 for i in item.children:
327 recurse(i, current)
328 else:
329 if item.uid != current[0] or item.gid != current[1] or \
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700330 item.mode != current[3] or item.selabel != current[4] or \
331 item.capabilities != current[5]:
332 script.SetPermissions("/"+item.name, item.uid, item.gid,
333 item.mode, item.selabel, item.capabilities)
Doug Zongkereef39442009-04-02 12:14:19 -0700334
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700335 recurse(self, (-1, -1, -1, -1, None, None))
Doug Zongkereef39442009-04-02 12:14:19 -0700336
337
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700338def CopyPartitionFiles(itemset, input_zip, output_zip=None, substitute=None):
339 """Copies files for the partition in the input zip to the output
Doug Zongkereef39442009-04-02 12:14:19 -0700340 zip. Populates the Item class with their metadata, and returns a
Doug Zongker1807e702012-02-28 12:21:08 -0800341 list of symlinks. output_zip may be None, in which case the copy is
342 skipped (but the other side effects still happen). substitute is an
343 optional dict of {output filename: contents} to be output instead of
344 certain input files.
Doug Zongkereef39442009-04-02 12:14:19 -0700345 """
346
347 symlinks = []
348
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700349 partition = itemset.partition
350
Doug Zongkereef39442009-04-02 12:14:19 -0700351 for info in input_zip.infolist():
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700352 if info.filename.startswith(partition.upper() + "/"):
Doug Zongkereef39442009-04-02 12:14:19 -0700353 basefilename = info.filename[7:]
354 if IsSymlink(info):
355 symlinks.append((input_zip.read(info.filename),
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700356 "/" + partition + "/" + basefilename))
Doug Zongkereef39442009-04-02 12:14:19 -0700357 else:
358 info2 = copy.copy(info)
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700359 fn = info2.filename = partition + "/" + basefilename
Doug Zongkereef39442009-04-02 12:14:19 -0700360 if substitute and fn in substitute and substitute[fn] is None:
361 continue
362 if output_zip is not None:
363 if substitute and fn in substitute:
364 data = substitute[fn]
365 else:
366 data = input_zip.read(info.filename)
367 output_zip.writestr(info2, data)
368 if fn.endswith("/"):
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700369 itemset.Get(fn[:-1], dir=True)
Doug Zongkereef39442009-04-02 12:14:19 -0700370 else:
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700371 itemset.Get(fn, dir=False)
Doug Zongkereef39442009-04-02 12:14:19 -0700372
373 symlinks.sort()
Doug Zongker1807e702012-02-28 12:21:08 -0800374 return symlinks
Doug Zongkereef39442009-04-02 12:14:19 -0700375
376
Doug Zongkereef39442009-04-02 12:14:19 -0700377def SignOutput(temp_zip_name, output_zip_name):
378 key_passwords = common.GetKeyPasswords([OPTIONS.package_key])
379 pw = key_passwords[OPTIONS.package_key]
380
Doug Zongker951495f2009-08-14 12:44:19 -0700381 common.SignFile(temp_zip_name, output_zip_name, OPTIONS.package_key, pw,
382 whole_file=True)
Doug Zongkereef39442009-04-02 12:14:19 -0700383
384
Michael Rungec6e3afd2014-05-05 11:55:47 -0700385def AppendAssertions(script, info_dict, oem_dict = None):
Michael Runge6e836112014-04-15 17:40:21 -0700386 oem_props = info_dict.get("oem_fingerprint_properties")
Michael Runge560569a2014-09-18 15:12:45 -0700387 if oem_props is None or len(oem_props) == 0:
Michael Runge6e836112014-04-15 17:40:21 -0700388 device = GetBuildProp("ro.product.device", info_dict)
389 script.AssertDevice(device)
390 else:
391 if oem_dict is None:
392 raise common.ExternalError("No OEM file provided to answer expected assertions")
393 for prop in oem_props.split():
394 if oem_dict.get(prop) is None:
395 raise common.ExternalError("The OEM file is missing the property %s" % prop)
396 script.AssertOemProperty(prop, oem_dict.get(prop))
Doug Zongkereef39442009-04-02 12:14:19 -0700397
Doug Zongkereef39442009-04-02 12:14:19 -0700398
Doug Zongkerc9253822014-02-04 12:17:58 -0800399def HasRecoveryPatch(target_files_zip):
400 try:
401 target_files_zip.getinfo("SYSTEM/recovery-from-boot.p")
402 return True
403 except KeyError:
404 return False
Doug Zongker73ef8252009-07-23 15:12:53 -0700405
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700406def HasVendorPartition(target_files_zip):
407 try:
408 target_files_zip.getinfo("VENDOR/")
409 return True
410 except KeyError:
411 return False
412
Michael Runge6e836112014-04-15 17:40:21 -0700413def GetOemProperty(name, oem_props, oem_dict, info_dict):
414 if oem_props is not None and name in oem_props:
415 return oem_dict[name]
416 return GetBuildProp(name, info_dict)
417
418
419def CalculateFingerprint(oem_props, oem_dict, info_dict):
420 if oem_props is None:
421 return GetBuildProp("ro.build.fingerprint", info_dict)
422 return "%s/%s/%s:%s" % (
423 GetOemProperty("ro.product.brand", oem_props, oem_dict, info_dict),
424 GetOemProperty("ro.product.name", oem_props, oem_dict, info_dict),
425 GetOemProperty("ro.product.device", oem_props, oem_dict, info_dict),
426 GetBuildProp("ro.build.thumbprint", info_dict))
Doug Zongker73ef8252009-07-23 15:12:53 -0700427
Doug Zongkerfc44a512014-08-26 13:10:25 -0700428
Doug Zongker3c84f562014-07-31 11:06:30 -0700429def GetImage(which, tmpdir, info_dict):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700430 # Return an image object (suitable for passing to BlockImageDiff)
431 # for the 'which' partition (most be "system" or "vendor"). If a
432 # prebuilt image and file map are found in tmpdir they are used,
433 # otherwise they are reconstructed from the individual files.
Doug Zongker3c84f562014-07-31 11:06:30 -0700434
435 assert which in ("system", "vendor")
436
437 path = os.path.join(tmpdir, "IMAGES", which + ".img")
Doug Zongkerfc44a512014-08-26 13:10:25 -0700438 mappath = os.path.join(tmpdir, "IMAGES", which + ".map")
439 if os.path.exists(path) and os.path.exists(mappath):
Doug Zongker3c84f562014-07-31 11:06:30 -0700440 print "using %s.img from target-files" % (which,)
Doug Zongker3c84f562014-07-31 11:06:30 -0700441 # This is a 'new' target-files, which already has the image in it.
Doug Zongker3c84f562014-07-31 11:06:30 -0700442
443 else:
444 print "building %s.img from target-files" % (which,)
445
446 # This is an 'old' target-files, which does not contain images
447 # already built. Build them.
448
Doug Zongkerfc44a512014-08-26 13:10:25 -0700449 mappath = tempfile.mkstemp()[1]
450 OPTIONS.tempfiles.append(mappath)
451
Doug Zongker3c84f562014-07-31 11:06:30 -0700452 import add_img_to_target_files
453 if which == "system":
Doug Zongkerfc44a512014-08-26 13:10:25 -0700454 path = add_img_to_target_files.BuildSystem(
455 tmpdir, info_dict, block_list=mappath)
Doug Zongker3c84f562014-07-31 11:06:30 -0700456 elif which == "vendor":
Doug Zongkerfc44a512014-08-26 13:10:25 -0700457 path = add_img_to_target_files.BuildVendor(
458 tmpdir, info_dict, block_list=mappath)
Doug Zongker3c84f562014-07-31 11:06:30 -0700459
Doug Zongkerfc44a512014-08-26 13:10:25 -0700460 return sparse_img.SparseImage(path, mappath)
461
462
Doug Zongkerc77a9ad2010-09-16 11:28:43 -0700463def WriteFullOTAPackage(input_zip, output_zip):
Doug Zongker9ce2ebf2010-04-21 14:08:44 -0700464 # TODO: how to determine this? We don't know what version it will
465 # be installed on top of. For now, we expect the API just won't
466 # change very often.
Doug Zongkerc77a9ad2010-09-16 11:28:43 -0700467 script = edify_generator.EdifyGenerator(3, OPTIONS.info_dict)
Doug Zongkereef39442009-04-02 12:14:19 -0700468
Michael Runge6e836112014-04-15 17:40:21 -0700469 oem_props = OPTIONS.info_dict.get("oem_fingerprint_properties")
Michael Runge7cd99ba2014-10-22 17:21:48 -0700470 recovery_mount_options = OPTIONS.info_dict.get("recovery_mount_options")
Michael Runge6e836112014-04-15 17:40:21 -0700471 oem_dict = None
Michael Runge560569a2014-09-18 15:12:45 -0700472 if oem_props is not None and len(oem_props) > 0:
Michael Runge6e836112014-04-15 17:40:21 -0700473 if OPTIONS.oem_source is None:
474 raise common.ExternalError("OEM source required for this build")
Michael Runge7cd99ba2014-10-22 17:21:48 -0700475 script.Mount("/oem", recovery_mount_options)
Michael Runge6e836112014-04-15 17:40:21 -0700476 oem_dict = common.LoadDictionaryFromLines(open(OPTIONS.oem_source).readlines())
477
478 metadata = {"post-build": CalculateFingerprint(
479 oem_props, oem_dict, OPTIONS.info_dict),
480 "pre-device": GetOemProperty("ro.product.device", oem_props, oem_dict,
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700481 OPTIONS.info_dict),
482 "post-timestamp": GetBuildProp("ro.build.date.utc",
483 OPTIONS.info_dict),
Doug Zongker2ea21062010-04-28 16:05:21 -0700484 }
485
Doug Zongker05d3dea2009-06-22 11:32:31 -0700486 device_specific = common.DeviceSpecificParams(
487 input_zip=input_zip,
Doug Zongker37974732010-09-16 17:44:38 -0700488 input_version=OPTIONS.info_dict["recovery_api_version"],
Doug Zongker05d3dea2009-06-22 11:32:31 -0700489 output_zip=output_zip,
490 script=script,
Doug Zongker2ea21062010-04-28 16:05:21 -0700491 input_tmp=OPTIONS.input_tmp,
Doug Zongker96a57e72010-09-26 14:57:41 -0700492 metadata=metadata,
493 info_dict=OPTIONS.info_dict)
Doug Zongker05d3dea2009-06-22 11:32:31 -0700494
Doug Zongkerc9253822014-02-04 12:17:58 -0800495 has_recovery_patch = HasRecoveryPatch(input_zip)
Doug Zongker26e66192014-02-20 13:22:07 -0800496 block_based = OPTIONS.block_based and has_recovery_patch
Doug Zongkerc9253822014-02-04 12:17:58 -0800497
Doug Zongker962069c2009-04-23 11:41:58 -0700498 if not OPTIONS.omit_prereq:
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700499 ts = GetBuildProp("ro.build.date.utc", OPTIONS.info_dict)
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700500 ts_text = GetBuildProp("ro.build.date", OPTIONS.info_dict)
501 script.AssertOlderBuild(ts, ts_text)
Doug Zongkereef39442009-04-02 12:14:19 -0700502
Michael Runge6e836112014-04-15 17:40:21 -0700503 AppendAssertions(script, OPTIONS.info_dict, oem_dict)
Doug Zongker05d3dea2009-06-22 11:32:31 -0700504 device_specific.FullOTA_Assertions()
Doug Zongker9b23f2c2013-11-25 14:44:12 -0800505
506 # Two-step package strategy (in chronological order, which is *not*
507 # the order in which the generated script has things):
508 #
509 # if stage is not "2/3" or "3/3":
510 # write recovery image to boot partition
511 # set stage to "2/3"
512 # reboot to boot partition and restart recovery
513 # else if stage is "2/3":
514 # write recovery image to recovery partition
515 # set stage to "3/3"
516 # reboot to recovery partition and restart recovery
517 # else:
518 # (stage must be "3/3")
519 # set stage to ""
520 # do normal full package installation:
521 # wipe and install system, boot image, etc.
522 # set up system to update recovery partition on first boot
523 # complete script normally (allow recovery to mark itself finished and reboot)
524
525 recovery_img = common.GetBootableImage("recovery.img", "recovery.img",
526 OPTIONS.input_tmp, "RECOVERY")
527 if OPTIONS.two_step:
528 if not OPTIONS.info_dict.get("multistage_support", None):
529 assert False, "two-step packages not supported by this build"
530 fs = OPTIONS.info_dict["fstab"]["/misc"]
531 assert fs.fs_type.upper() == "EMMC", \
532 "two-step packages only supported on devices with EMMC /misc partitions"
533 bcb_dev = {"bcb_dev": fs.device}
534 common.ZipWriteStr(output_zip, "recovery.img", recovery_img.data)
535 script.AppendExtra("""
Michael Rungefb8886d2014-10-23 13:51:04 -0700536if get_stage("%(bcb_dev)s") == "2/3" then
Doug Zongker9b23f2c2013-11-25 14:44:12 -0800537""" % bcb_dev)
538 script.WriteRawImage("/recovery", "recovery.img")
539 script.AppendExtra("""
540set_stage("%(bcb_dev)s", "3/3");
541reboot_now("%(bcb_dev)s", "recovery");
Michael Rungefb8886d2014-10-23 13:51:04 -0700542else if get_stage("%(bcb_dev)s") == "3/3" then
Doug Zongker9b23f2c2013-11-25 14:44:12 -0800543""" % bcb_dev)
544
Doug Zongkere5ff5902012-01-17 10:55:37 -0800545 device_specific.FullOTA_InstallBegin()
Doug Zongker171f1cd2009-06-15 22:36:37 -0700546
Doug Zongker01ce19c2014-02-04 13:48:15 -0800547 system_progress = 0.75
Doug Zongkereef39442009-04-02 12:14:19 -0700548
Doug Zongkerdbfaae52009-04-21 17:12:54 -0700549 if OPTIONS.wipe_user_data:
Doug Zongker01ce19c2014-02-04 13:48:15 -0800550 system_progress -= 0.1
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700551 if HasVendorPartition(input_zip):
552 system_progress -= 0.1
Doug Zongkerdbfaae52009-04-21 17:12:54 -0700553
Kenny Rootf32dc712012-04-08 10:42:34 -0700554 if "selinux_fc" in OPTIONS.info_dict:
555 WritePolicyConfig(OPTIONS.info_dict["selinux_fc"], output_zip)
Stephen Smalley56882bf2012-02-09 13:36:21 -0500556
Michael Runge7cd99ba2014-10-22 17:21:48 -0700557 recovery_mount_options = OPTIONS.info_dict.get("recovery_mount_options")
558
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700559 system_items = ItemSet("system", "META/filesystem_config.txt")
Doug Zongker4b9596f2014-06-09 14:15:45 -0700560 script.ShowProgress(system_progress, 0)
Jesse Zhao75bcea02015-01-06 10:59:53 -0800561
Doug Zongker26e66192014-02-20 13:22:07 -0800562 if block_based:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700563 # Full OTA is done as an "incremental" against an empty source
564 # image. This has the effect of writing new data from the package
565 # to the entire partition, but lets us reuse the updater code that
566 # writes incrementals to do it.
567 system_tgt = GetImage("system", OPTIONS.input_tmp, OPTIONS.info_dict)
568 system_tgt.ResetFileMap()
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700569 system_diff = common.BlockDifference("system", system_tgt, src=None)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700570 system_diff.WriteScript(script, output_zip)
Doug Zongker01ce19c2014-02-04 13:48:15 -0800571 else:
572 script.FormatPartition("/system")
Michael Runge7cd99ba2014-10-22 17:21:48 -0700573 script.Mount("/system", recovery_mount_options)
Doug Zongker01ce19c2014-02-04 13:48:15 -0800574 if not has_recovery_patch:
575 script.UnpackPackageDir("recovery", "/system")
Doug Zongker26e66192014-02-20 13:22:07 -0800576 script.UnpackPackageDir("system", "/system")
Doug Zongkereef39442009-04-02 12:14:19 -0700577
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700578 symlinks = CopyPartitionFiles(system_items, input_zip, output_zip)
Doug Zongker01ce19c2014-02-04 13:48:15 -0800579 script.MakeSymlinks(symlinks)
Doug Zongkereef39442009-04-02 12:14:19 -0700580
Doug Zongker55d93282011-01-25 17:03:34 -0800581 boot_img = common.GetBootableImage("boot.img", "boot.img",
582 OPTIONS.input_tmp, "BOOT")
Doug Zongkerc9253822014-02-04 12:17:58 -0800583
Doug Zongker91a99c22014-05-09 13:15:01 -0700584 if not block_based:
Doug Zongkerc9253822014-02-04 12:17:58 -0800585 def output_sink(fn, data):
586 common.ZipWriteStr(output_zip, "recovery/" + fn, data)
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700587 system_items.Get("system/" + fn, dir=False)
Doug Zongkerc9253822014-02-04 12:17:58 -0800588
589 common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink,
590 recovery_img, boot_img)
Doug Zongkereef39442009-04-02 12:14:19 -0700591
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700592 system_items.GetMetadata(input_zip)
593 system_items.Get("system").SetPermissions(script)
594
595 if HasVendorPartition(input_zip):
596 vendor_items = ItemSet("vendor", "META/vendor_filesystem_config.txt")
597 script.ShowProgress(0.1, 0)
598
599 if block_based:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700600 vendor_tgt = GetImage("vendor", OPTIONS.input_tmp, OPTIONS.info_dict)
601 vendor_tgt.ResetFileMap()
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700602 vendor_diff = common.BlockDifference("vendor", vendor_tgt)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700603 vendor_diff.WriteScript(script, output_zip)
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700604 else:
605 script.FormatPartition("/vendor")
Michael Runge7cd99ba2014-10-22 17:21:48 -0700606 script.Mount("/vendor", recovery_mount_options)
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700607 script.UnpackPackageDir("vendor", "/vendor")
608
609 symlinks = CopyPartitionFiles(vendor_items, input_zip, output_zip)
610 script.MakeSymlinks(symlinks)
611
612 vendor_items.GetMetadata(input_zip)
613 vendor_items.Get("vendor").SetPermissions(script)
Doug Zongker73ef8252009-07-23 15:12:53 -0700614
Doug Zongker37974732010-09-16 17:44:38 -0700615 common.CheckSize(boot_img.data, "boot.img", OPTIONS.info_dict)
Doug Zongker73ef8252009-07-23 15:12:53 -0700616 common.ZipWriteStr(output_zip, "boot.img", boot_img.data)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700617
Doug Zongker01ce19c2014-02-04 13:48:15 -0800618 script.ShowProgress(0.05, 5)
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700619 script.WriteRawImage("/boot", "boot.img")
Doug Zongker05d3dea2009-06-22 11:32:31 -0700620
Doug Zongker01ce19c2014-02-04 13:48:15 -0800621 script.ShowProgress(0.2, 10)
Doug Zongker05d3dea2009-06-22 11:32:31 -0700622 device_specific.FullOTA_InstallEnd()
Doug Zongkereef39442009-04-02 12:14:19 -0700623
Doug Zongker1c390a22009-05-14 19:06:36 -0700624 if OPTIONS.extra_script is not None:
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700625 script.AppendExtra(OPTIONS.extra_script)
Doug Zongker1c390a22009-05-14 19:06:36 -0700626
Doug Zongker14833602010-02-02 13:12:04 -0800627 script.UnmountAll()
Doug Zongker9b23f2c2013-11-25 14:44:12 -0800628
Doug Zongker922206e2014-03-04 13:16:24 -0800629 if OPTIONS.wipe_user_data:
630 script.ShowProgress(0.1, 10)
631 script.FormatPartition("/data")
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700632
Doug Zongker9b23f2c2013-11-25 14:44:12 -0800633 if OPTIONS.two_step:
634 script.AppendExtra("""
635set_stage("%(bcb_dev)s", "");
636""" % bcb_dev)
637 script.AppendExtra("else\n")
638 script.WriteRawImage("/boot", "recovery.img")
639 script.AppendExtra("""
640set_stage("%(bcb_dev)s", "2/3");
641reboot_now("%(bcb_dev)s", "");
642endif;
643endif;
644""" % bcb_dev)
Doug Zongker25568482014-03-03 10:21:27 -0800645 script.AddToZip(input_zip, output_zip, input_path=OPTIONS.updater_binary)
Doug Zongker2ea21062010-04-28 16:05:21 -0700646 WriteMetadata(metadata, output_zip)
647
Doug Zongkerfc44a512014-08-26 13:10:25 -0700648
Dan Albertcd082d42015-01-27 15:53:15 -0800649def WritePolicyConfig(file_name, output_zip):
650 common.ZipWrite(output_zip, file_name, os.path.basename(file_name))
Stephen Smalley56882bf2012-02-09 13:36:21 -0500651
Doug Zongker2ea21062010-04-28 16:05:21 -0700652
653def WriteMetadata(metadata, output_zip):
654 common.ZipWriteStr(output_zip, "META-INF/com/android/metadata",
655 "".join(["%s=%s\n" % kv
656 for kv in sorted(metadata.iteritems())]))
Doug Zongkereef39442009-04-02 12:14:19 -0700657
Doug Zongkerfc44a512014-08-26 13:10:25 -0700658
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700659def LoadPartitionFiles(z, partition):
660 """Load all the files from the given partition in a given target-files
Doug Zongkereef39442009-04-02 12:14:19 -0700661 ZipFile, and return a dict of {filename: File object}."""
662 out = {}
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700663 prefix = partition.upper() + "/"
Doug Zongkereef39442009-04-02 12:14:19 -0700664 for info in z.infolist():
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700665 if info.filename.startswith(prefix) and not IsSymlink(info):
Hristo Bojinov96be7202010-08-02 10:26:17 -0700666 basefilename = info.filename[7:]
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700667 fn = partition + "/" + basefilename
Doug Zongkereef39442009-04-02 12:14:19 -0700668 data = z.read(info.filename)
Doug Zongkerea5d7a92010-09-12 15:26:16 -0700669 out[fn] = common.File(fn, data)
Doug Zongker1807e702012-02-28 12:21:08 -0800670 return out
Doug Zongkereef39442009-04-02 12:14:19 -0700671
672
Doug Zongker1eb74dd2012-08-16 16:19:00 -0700673def GetBuildProp(prop, info_dict):
674 """Return the fingerprint of the build of a given target-files info_dict."""
675 try:
676 return info_dict.get("build.prop", {})[prop]
677 except KeyError:
Ying Wangc73e4612014-04-15 15:27:43 -0700678 raise common.ExternalError("couldn't find %s in build.prop" % (prop,))
Doug Zongkereef39442009-04-02 12:14:19 -0700679
Doug Zongkerfc44a512014-08-26 13:10:25 -0700680
Michael Runge4038aa82013-12-13 18:06:28 -0800681def AddToKnownPaths(filename, known_paths):
682 if filename[-1] == "/":
683 return
684 dirs = filename.split("/")[:-1]
685 while len(dirs) > 0:
686 path = "/".join(dirs)
687 if path in known_paths:
688 break;
689 known_paths.add(path)
690 dirs.pop()
Doug Zongkereef39442009-04-02 12:14:19 -0700691
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700692
Geremy Condra36bd3652014-02-06 19:45:10 -0800693def WriteBlockIncrementalOTAPackage(target_zip, source_zip, output_zip):
694 source_version = OPTIONS.source_info_dict["recovery_api_version"]
695 target_version = OPTIONS.target_info_dict["recovery_api_version"]
696
697 if source_version == 0:
698 print ("WARNING: generating edify script for a source that "
699 "can't install it.")
700 script = edify_generator.EdifyGenerator(source_version,
701 OPTIONS.target_info_dict)
702
703 metadata = {"pre-device": GetBuildProp("ro.product.device",
704 OPTIONS.source_info_dict),
705 "post-timestamp": GetBuildProp("ro.build.date.utc",
706 OPTIONS.target_info_dict),
707 }
708
709 device_specific = common.DeviceSpecificParams(
710 source_zip=source_zip,
711 source_version=source_version,
712 target_zip=target_zip,
713 target_version=target_version,
714 output_zip=output_zip,
715 script=script,
716 metadata=metadata,
717 info_dict=OPTIONS.info_dict)
718
719 source_fp = GetBuildProp("ro.build.fingerprint", OPTIONS.source_info_dict)
720 target_fp = GetBuildProp("ro.build.fingerprint", OPTIONS.target_info_dict)
721 metadata["pre-build"] = source_fp
722 metadata["post-build"] = target_fp
723
724 source_boot = common.GetBootableImage(
725 "/tmp/boot.img", "boot.img", OPTIONS.source_tmp, "BOOT",
726 OPTIONS.source_info_dict)
727 target_boot = common.GetBootableImage(
728 "/tmp/boot.img", "boot.img", OPTIONS.target_tmp, "BOOT")
729 updating_boot = (not OPTIONS.two_step and
730 (source_boot.data != target_boot.data))
731
732 source_recovery = common.GetBootableImage(
733 "/tmp/recovery.img", "recovery.img", OPTIONS.source_tmp, "RECOVERY",
734 OPTIONS.source_info_dict)
735 target_recovery = common.GetBootableImage(
736 "/tmp/recovery.img", "recovery.img", OPTIONS.target_tmp, "RECOVERY")
737 updating_recovery = (source_recovery.data != target_recovery.data)
738
Doug Zongkerfc44a512014-08-26 13:10:25 -0700739 system_src = GetImage("system", OPTIONS.source_tmp, OPTIONS.source_info_dict)
740 system_tgt = GetImage("system", OPTIONS.target_tmp, OPTIONS.target_info_dict)
Doug Zongkerb34fcce2014-09-11 09:34:56 -0700741 system_diff = common.BlockDifference("system", system_tgt, system_src,
742 check_first_block=True)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700743
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700744 if HasVendorPartition(target_zip):
745 if not HasVendorPartition(source_zip):
746 raise RuntimeError("can't generate incremental that adds /vendor")
Doug Zongkerfc44a512014-08-26 13:10:25 -0700747 vendor_src = GetImage("vendor", OPTIONS.source_tmp, OPTIONS.source_info_dict)
748 vendor_tgt = GetImage("vendor", OPTIONS.target_tmp, OPTIONS.target_info_dict)
Doug Zongkerb34fcce2014-09-11 09:34:56 -0700749 vendor_diff = common.BlockDifference("vendor", vendor_tgt, vendor_src,
750 check_first_block=True)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700751 else:
752 vendor_diff = None
Geremy Condra36bd3652014-02-06 19:45:10 -0800753
Michael Rungec6e3afd2014-05-05 11:55:47 -0700754 oem_props = OPTIONS.target_info_dict.get("oem_fingerprint_properties")
Michael Runge7cd99ba2014-10-22 17:21:48 -0700755 recovery_mount_options = OPTIONS.target_info_dict.get("recovery_mount_options")
Michael Rungec6e3afd2014-05-05 11:55:47 -0700756 oem_dict = None
Michael Runge560569a2014-09-18 15:12:45 -0700757 if oem_props is not None and len(oem_props) > 0:
Michael Rungec6e3afd2014-05-05 11:55:47 -0700758 if OPTIONS.oem_source is None:
759 raise common.ExternalError("OEM source required for this build")
Michael Runge7cd99ba2014-10-22 17:21:48 -0700760 script.Mount("/oem", recovery_mount_options)
Michael Rungec6e3afd2014-05-05 11:55:47 -0700761 oem_dict = common.LoadDictionaryFromLines(open(OPTIONS.oem_source).readlines())
762
763 AppendAssertions(script, OPTIONS.target_info_dict, oem_dict)
Geremy Condra36bd3652014-02-06 19:45:10 -0800764 device_specific.IncrementalOTA_Assertions()
765
766 # Two-step incremental package strategy (in chronological order,
767 # which is *not* the order in which the generated script has
768 # things):
769 #
770 # if stage is not "2/3" or "3/3":
771 # do verification on current system
772 # write recovery image to boot partition
773 # set stage to "2/3"
774 # reboot to boot partition and restart recovery
775 # else if stage is "2/3":
776 # write recovery image to recovery partition
777 # set stage to "3/3"
778 # reboot to recovery partition and restart recovery
779 # else:
780 # (stage must be "3/3")
781 # perform update:
782 # patch system files, etc.
783 # force full install of new boot image
784 # set up system to update recovery partition on first boot
785 # complete script normally (allow recovery to mark itself finished and reboot)
786
787 if OPTIONS.two_step:
788 if not OPTIONS.info_dict.get("multistage_support", None):
789 assert False, "two-step packages not supported by this build"
790 fs = OPTIONS.info_dict["fstab"]["/misc"]
791 assert fs.fs_type.upper() == "EMMC", \
792 "two-step packages only supported on devices with EMMC /misc partitions"
793 bcb_dev = {"bcb_dev": fs.device}
794 common.ZipWriteStr(output_zip, "recovery.img", target_recovery.data)
795 script.AppendExtra("""
Michael Rungefb8886d2014-10-23 13:51:04 -0700796if get_stage("%(bcb_dev)s") == "2/3" then
Geremy Condra36bd3652014-02-06 19:45:10 -0800797""" % bcb_dev)
798 script.AppendExtra("sleep(20);\n");
799 script.WriteRawImage("/recovery", "recovery.img")
800 script.AppendExtra("""
801set_stage("%(bcb_dev)s", "3/3");
802reboot_now("%(bcb_dev)s", "recovery");
Michael Rungefb8886d2014-10-23 13:51:04 -0700803else if get_stage("%(bcb_dev)s") != "3/3" then
Geremy Condra36bd3652014-02-06 19:45:10 -0800804""" % bcb_dev)
805
806 script.Print("Verifying current system...")
807
808 device_specific.IncrementalOTA_VerifyBegin()
809
Michael Rungec6e3afd2014-05-05 11:55:47 -0700810 if oem_props is None:
811 script.AssertSomeFingerprint(source_fp, target_fp)
812 else:
813 script.AssertSomeThumbprint(
814 GetBuildProp("ro.build.thumbprint", OPTIONS.target_info_dict),
815 GetBuildProp("ro.build.thumbprint", OPTIONS.source_info_dict))
Geremy Condra36bd3652014-02-06 19:45:10 -0800816
817 if updating_boot:
Doug Zongkerf8340082014-08-05 10:39:37 -0700818 boot_type, boot_device = common.GetTypeAndDevice("/boot", OPTIONS.info_dict)
Geremy Condra36bd3652014-02-06 19:45:10 -0800819 d = common.Difference(target_boot, source_boot)
820 _, _, d = d.ComputePatch()
Doug Zongkerf8340082014-08-05 10:39:37 -0700821 if d is None:
822 include_full_boot = True
823 common.ZipWriteStr(output_zip, "boot.img", target_boot.data)
824 else:
825 include_full_boot = False
Geremy Condra36bd3652014-02-06 19:45:10 -0800826
Doug Zongkerf8340082014-08-05 10:39:37 -0700827 print "boot target: %d source: %d diff: %d" % (
828 target_boot.size, source_boot.size, len(d))
Geremy Condra36bd3652014-02-06 19:45:10 -0800829
Doug Zongkerf8340082014-08-05 10:39:37 -0700830 common.ZipWriteStr(output_zip, "patch/boot.img.p", d)
Geremy Condra36bd3652014-02-06 19:45:10 -0800831
Doug Zongkerf8340082014-08-05 10:39:37 -0700832 script.PatchCheck("%s:%s:%d:%s:%d:%s" %
833 (boot_type, boot_device,
834 source_boot.size, source_boot.sha1,
835 target_boot.size, target_boot.sha1))
Geremy Condra36bd3652014-02-06 19:45:10 -0800836
837 device_specific.IncrementalOTA_VerifyEnd()
838
839 if OPTIONS.two_step:
840 script.WriteRawImage("/boot", "recovery.img")
841 script.AppendExtra("""
842set_stage("%(bcb_dev)s", "2/3");
843reboot_now("%(bcb_dev)s", "");
844else
845""" % bcb_dev)
846
Jesse Zhao75bcea02015-01-06 10:59:53 -0800847 # Verify the existing partitions.
848 system_diff.WriteVerifyScript(script)
849 if vendor_diff:
850 vendor_diff.WriteVerifyScript(script)
851
Geremy Condra36bd3652014-02-06 19:45:10 -0800852 script.Comment("---- start making changes here ----")
853
854 device_specific.IncrementalOTA_InstallBegin()
855
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700856 system_diff.WriteScript(script, output_zip,
857 progress=0.8 if vendor_diff else 0.9)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700858 if vendor_diff:
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700859 vendor_diff.WriteScript(script, output_zip, progress=0.1)
Geremy Condra36bd3652014-02-06 19:45:10 -0800860
861 if OPTIONS.two_step:
862 common.ZipWriteStr(output_zip, "boot.img", target_boot.data)
863 script.WriteRawImage("/boot", "boot.img")
864 print "writing full boot image (forced by two-step mode)"
865
866 if not OPTIONS.two_step:
867 if updating_boot:
Doug Zongkerf8340082014-08-05 10:39:37 -0700868 if include_full_boot:
869 print "boot image changed; including full."
870 script.Print("Installing boot image...")
871 script.WriteRawImage("/boot", "boot.img")
872 else:
873 # Produce the boot image by applying a patch to the current
874 # contents of the boot partition, and write it back to the
875 # partition.
876 print "boot image changed; including patch."
877 script.Print("Patching boot image...")
878 script.ShowProgress(0.1, 10)
879 script.ApplyPatch("%s:%s:%d:%s:%d:%s"
880 % (boot_type, boot_device,
881 source_boot.size, source_boot.sha1,
882 target_boot.size, target_boot.sha1),
883 "-",
884 target_boot.size, target_boot.sha1,
885 source_boot.sha1, "patch/boot.img.p")
Geremy Condra36bd3652014-02-06 19:45:10 -0800886 else:
887 print "boot image unchanged; skipping."
888
889 # Do device-specific installation (eg, write radio image).
890 device_specific.IncrementalOTA_InstallEnd()
891
892 if OPTIONS.extra_script is not None:
893 script.AppendExtra(OPTIONS.extra_script)
894
Doug Zongker922206e2014-03-04 13:16:24 -0800895 if OPTIONS.wipe_user_data:
896 script.Print("Erasing user data...")
897 script.FormatPartition("/data")
898
Geremy Condra36bd3652014-02-06 19:45:10 -0800899 if OPTIONS.two_step:
900 script.AppendExtra("""
901set_stage("%(bcb_dev)s", "");
902endif;
903endif;
904""" % bcb_dev)
905
906 script.SetProgress(1)
Doug Zongker25568482014-03-03 10:21:27 -0800907 script.AddToZip(target_zip, output_zip, input_path=OPTIONS.updater_binary)
Geremy Condra36bd3652014-02-06 19:45:10 -0800908 WriteMetadata(metadata, output_zip)
909
Doug Zongker32b527d2014-03-04 10:03:02 -0800910
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700911class FileDifference:
912 def __init__(self, partition, source_zip, target_zip, output_zip):
913 print "Loading target..."
914 self.target_data = target_data = LoadPartitionFiles(target_zip, partition)
915 print "Loading source..."
916 self.source_data = source_data = LoadPartitionFiles(source_zip, partition)
917
918 self.verbatim_targets = verbatim_targets = []
919 self.patch_list = patch_list = []
920 diffs = []
921 self.renames = renames = {}
922 known_paths = set()
923 largest_source_size = 0
924
925 matching_file_cache = {}
926 for fn, sf in source_data.items():
927 assert fn == sf.name
928 matching_file_cache["path:" + fn] = sf
929 if fn in target_data.keys():
930 AddToKnownPaths(fn, known_paths)
931 # Only allow eligibility for filename/sha matching
932 # if there isn't a perfect path match.
933 if target_data.get(sf.name) is None:
934 matching_file_cache["file:" + fn.split("/")[-1]] = sf
935 matching_file_cache["sha:" + sf.sha1] = sf
936
937 for fn in sorted(target_data.keys()):
938 tf = target_data[fn]
939 assert fn == tf.name
940 sf = ClosestFileMatch(tf, matching_file_cache, renames)
941 if sf is not None and sf.name != tf.name:
942 print "File has moved from " + sf.name + " to " + tf.name
943 renames[sf.name] = tf
944
945 if sf is None or fn in OPTIONS.require_verbatim:
946 # This file should be included verbatim
947 if fn in OPTIONS.prohibit_verbatim:
948 raise common.ExternalError("\"%s\" must be sent verbatim" % (fn,))
949 print "send", fn, "verbatim"
950 tf.AddToZip(output_zip)
Michael Runge63f01de2014-10-28 19:24:19 -0700951 verbatim_targets.append((fn, tf.size, tf.sha1))
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700952 if fn in target_data.keys():
953 AddToKnownPaths(fn, known_paths)
954 elif tf.sha1 != sf.sha1:
955 # File is different; consider sending as a patch
956 diffs.append(common.Difference(tf, sf))
957 else:
958 # Target file data identical to source (may still be renamed)
959 pass
960
961 common.ComputeDifferences(diffs)
962
963 for diff in diffs:
964 tf, sf, d = diff.GetPatch()
965 path = "/".join(tf.name.split("/")[:-1])
966 if d is None or len(d) > tf.size * OPTIONS.patch_threshold or \
967 path not in known_paths:
968 # patch is almost as big as the file; don't bother patching
969 # or a patch + rename cannot take place due to the target
970 # directory not existing
971 tf.AddToZip(output_zip)
Michael Runge63f01de2014-10-28 19:24:19 -0700972 verbatim_targets.append((tf.name, tf.size, tf.sha1))
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700973 if sf.name in renames:
974 del renames[sf.name]
975 AddToKnownPaths(tf.name, known_paths)
976 else:
977 common.ZipWriteStr(output_zip, "patch/" + sf.name + ".p", d)
978 patch_list.append((tf, sf, tf.size, common.sha1(d).hexdigest()))
979 largest_source_size = max(largest_source_size, sf.size)
980
981 self.largest_source_size = largest_source_size
982
983 def EmitVerification(self, script):
984 so_far = 0
985 for tf, sf, size, patch_sha in self.patch_list:
986 if tf.name != sf.name:
987 script.SkipNextActionIfTargetExists(tf.name, tf.sha1)
988 script.PatchCheck("/"+sf.name, tf.sha1, sf.sha1)
989 so_far += sf.size
990 return so_far
991
Michael Runge63f01de2014-10-28 19:24:19 -0700992 def EmitExplicitTargetVerification(self, script):
993 for fn, size, sha1 in self.verbatim_targets:
994 if (fn[-1] != "/"):
995 script.FileCheck("/"+fn, sha1)
996 for tf, _, _, _ in self.patch_list:
997 script.FileCheck(tf.name, tf.sha1)
998
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700999 def RemoveUnneededFiles(self, script, extras=()):
1000 script.DeleteFiles(["/"+i[0] for i in self.verbatim_targets] +
1001 ["/"+i for i in sorted(self.source_data)
1002 if i not in self.target_data and
1003 i not in self.renames] +
1004 list(extras))
1005
1006 def TotalPatchSize(self):
1007 return sum(i[1].size for i in self.patch_list)
1008
1009 def EmitPatches(self, script, total_patch_size, so_far):
1010 self.deferred_patch_list = deferred_patch_list = []
1011 for item in self.patch_list:
1012 tf, sf, size, _ = item
1013 if tf.name == "system/build.prop":
1014 deferred_patch_list.append(item)
1015 continue
1016 if (sf.name != tf.name):
1017 script.SkipNextActionIfTargetExists(tf.name, tf.sha1)
1018 script.ApplyPatch("/"+sf.name, "-", tf.size, tf.sha1, sf.sha1, "patch/"+sf.name+".p")
1019 so_far += tf.size
1020 script.SetProgress(so_far / total_patch_size)
1021 return so_far
1022
1023 def EmitDeferredPatches(self, script):
1024 for item in self.deferred_patch_list:
1025 tf, sf, size, _ = item
1026 script.ApplyPatch("/"+sf.name, "-", tf.size, tf.sha1, sf.sha1, "patch/"+sf.name+".p")
1027 script.SetPermissions("/system/build.prop", 0, 0, 0644, None, None)
1028
1029 def EmitRenames(self, script):
1030 if len(self.renames) > 0:
1031 script.Print("Renaming files...")
1032 for src, tgt in self.renames.iteritems():
1033 print "Renaming " + src + " to " + tgt.name
1034 script.RenameFile(src, tgt.name)
1035
1036
1037
1038
Doug Zongkerc77a9ad2010-09-16 11:28:43 -07001039def WriteIncrementalOTAPackage(target_zip, source_zip, output_zip):
Geremy Condra36bd3652014-02-06 19:45:10 -08001040 target_has_recovery_patch = HasRecoveryPatch(target_zip)
1041 source_has_recovery_patch = HasRecoveryPatch(source_zip)
1042
Doug Zongker26e66192014-02-20 13:22:07 -08001043 if (OPTIONS.block_based and
1044 target_has_recovery_patch and
1045 source_has_recovery_patch):
Geremy Condra36bd3652014-02-06 19:45:10 -08001046 return WriteBlockIncrementalOTAPackage(target_zip, source_zip, output_zip)
1047
Doug Zongker37974732010-09-16 17:44:38 -07001048 source_version = OPTIONS.source_info_dict["recovery_api_version"]
1049 target_version = OPTIONS.target_info_dict["recovery_api_version"]
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001050
Doug Zongker9ce2ebf2010-04-21 14:08:44 -07001051 if source_version == 0:
1052 print ("WARNING: generating edify script for a source that "
1053 "can't install it.")
Doug Zongker1eb74dd2012-08-16 16:19:00 -07001054 script = edify_generator.EdifyGenerator(source_version,
1055 OPTIONS.target_info_dict)
Doug Zongkereef39442009-04-02 12:14:19 -07001056
Michael Runge6e836112014-04-15 17:40:21 -07001057 oem_props = OPTIONS.info_dict.get("oem_fingerprint_properties")
Michael Runge7cd99ba2014-10-22 17:21:48 -07001058 recovery_mount_options = OPTIONS.info_dict.get("recovery_mount_options")
Michael Runge6e836112014-04-15 17:40:21 -07001059 oem_dict = None
Michael Runge560569a2014-09-18 15:12:45 -07001060 if oem_props is not None and len(oem_props) > 0:
Michael Runge6e836112014-04-15 17:40:21 -07001061 if OPTIONS.oem_source is None:
1062 raise common.ExternalError("OEM source required for this build")
Michael Runge7cd99ba2014-10-22 17:21:48 -07001063 script.Mount("/oem", recovery_mount_options)
Michael Runge6e836112014-04-15 17:40:21 -07001064 oem_dict = common.LoadDictionaryFromLines(open(OPTIONS.oem_source).readlines())
1065
1066 metadata = {"pre-device": GetOemProperty("ro.product.device", oem_props, oem_dict,
Doug Zongker1eb74dd2012-08-16 16:19:00 -07001067 OPTIONS.source_info_dict),
1068 "post-timestamp": GetBuildProp("ro.build.date.utc",
1069 OPTIONS.target_info_dict),
Doug Zongker2ea21062010-04-28 16:05:21 -07001070 }
1071
Doug Zongker05d3dea2009-06-22 11:32:31 -07001072 device_specific = common.DeviceSpecificParams(
1073 source_zip=source_zip,
Doug Zongker14833602010-02-02 13:12:04 -08001074 source_version=source_version,
Doug Zongker05d3dea2009-06-22 11:32:31 -07001075 target_zip=target_zip,
Doug Zongker14833602010-02-02 13:12:04 -08001076 target_version=target_version,
Doug Zongker05d3dea2009-06-22 11:32:31 -07001077 output_zip=output_zip,
Doug Zongker2ea21062010-04-28 16:05:21 -07001078 script=script,
Doug Zongker96a57e72010-09-26 14:57:41 -07001079 metadata=metadata,
1080 info_dict=OPTIONS.info_dict)
Doug Zongker05d3dea2009-06-22 11:32:31 -07001081
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001082 system_diff = FileDifference("system", source_zip, target_zip, output_zip)
Michael Runge7cd99ba2014-10-22 17:21:48 -07001083 script.Mount("/system", recovery_mount_options)
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001084 if HasVendorPartition(target_zip):
1085 vendor_diff = FileDifference("vendor", source_zip, target_zip, output_zip)
Michael Runge7cd99ba2014-10-22 17:21:48 -07001086 script.Mount("/vendor", recovery_mount_options)
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001087 else:
1088 vendor_diff = None
Michael Runge6e836112014-04-15 17:40:21 -07001089
1090 target_fp = CalculateFingerprint(oem_props, oem_dict, OPTIONS.target_info_dict)
1091 source_fp = CalculateFingerprint(oem_props, oem_dict, OPTIONS.source_info_dict)
1092
1093 if oem_props is None:
1094 script.AssertSomeFingerprint(source_fp, target_fp)
1095 else:
1096 script.AssertSomeThumbprint(
1097 GetBuildProp("ro.build.thumbprint", OPTIONS.target_info_dict),
1098 GetBuildProp("ro.build.thumbprint", OPTIONS.source_info_dict))
1099
Doug Zongker2ea21062010-04-28 16:05:21 -07001100 metadata["pre-build"] = source_fp
1101 metadata["post-build"] = target_fp
Doug Zongkereef39442009-04-02 12:14:19 -07001102
Doug Zongker55d93282011-01-25 17:03:34 -08001103 source_boot = common.GetBootableImage(
Doug Zongkerd5131602012-08-02 14:46:42 -07001104 "/tmp/boot.img", "boot.img", OPTIONS.source_tmp, "BOOT",
1105 OPTIONS.source_info_dict)
Doug Zongker55d93282011-01-25 17:03:34 -08001106 target_boot = common.GetBootableImage(
1107 "/tmp/boot.img", "boot.img", OPTIONS.target_tmp, "BOOT")
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001108 updating_boot = (not OPTIONS.two_step and
1109 (source_boot.data != target_boot.data))
Doug Zongkereef39442009-04-02 12:14:19 -07001110
Doug Zongker55d93282011-01-25 17:03:34 -08001111 source_recovery = common.GetBootableImage(
Doug Zongkerd5131602012-08-02 14:46:42 -07001112 "/tmp/recovery.img", "recovery.img", OPTIONS.source_tmp, "RECOVERY",
1113 OPTIONS.source_info_dict)
Doug Zongker55d93282011-01-25 17:03:34 -08001114 target_recovery = common.GetBootableImage(
1115 "/tmp/recovery.img", "recovery.img", OPTIONS.target_tmp, "RECOVERY")
Doug Zongkerf6a8bad2009-05-29 11:41:21 -07001116 updating_recovery = (source_recovery.data != target_recovery.data)
Doug Zongkereef39442009-04-02 12:14:19 -07001117
Doug Zongker881dd402009-09-20 14:03:55 -07001118 # Here's how we divide up the progress bar:
1119 # 0.1 for verifying the start state (PatchCheck calls)
1120 # 0.8 for applying patches (ApplyPatch calls)
1121 # 0.1 for unpacking verbatim files, symlinking, and doing the
1122 # device-specific commands.
Doug Zongkereef39442009-04-02 12:14:19 -07001123
Michael Runge6e836112014-04-15 17:40:21 -07001124 AppendAssertions(script, OPTIONS.target_info_dict, oem_dict)
Doug Zongker05d3dea2009-06-22 11:32:31 -07001125 device_specific.IncrementalOTA_Assertions()
Doug Zongkereef39442009-04-02 12:14:19 -07001126
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001127 # Two-step incremental package strategy (in chronological order,
1128 # which is *not* the order in which the generated script has
1129 # things):
1130 #
1131 # if stage is not "2/3" or "3/3":
1132 # do verification on current system
1133 # write recovery image to boot partition
1134 # set stage to "2/3"
1135 # reboot to boot partition and restart recovery
1136 # else if stage is "2/3":
1137 # write recovery image to recovery partition
1138 # set stage to "3/3"
1139 # reboot to recovery partition and restart recovery
1140 # else:
1141 # (stage must be "3/3")
1142 # perform update:
1143 # patch system files, etc.
1144 # force full install of new boot image
1145 # set up system to update recovery partition on first boot
1146 # complete script normally (allow recovery to mark itself finished and reboot)
1147
1148 if OPTIONS.two_step:
1149 if not OPTIONS.info_dict.get("multistage_support", None):
1150 assert False, "two-step packages not supported by this build"
1151 fs = OPTIONS.info_dict["fstab"]["/misc"]
1152 assert fs.fs_type.upper() == "EMMC", \
1153 "two-step packages only supported on devices with EMMC /misc partitions"
1154 bcb_dev = {"bcb_dev": fs.device}
1155 common.ZipWriteStr(output_zip, "recovery.img", target_recovery.data)
1156 script.AppendExtra("""
Michael Rungefb8886d2014-10-23 13:51:04 -07001157if get_stage("%(bcb_dev)s") == "2/3" then
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001158""" % bcb_dev)
1159 script.AppendExtra("sleep(20);\n");
1160 script.WriteRawImage("/recovery", "recovery.img")
1161 script.AppendExtra("""
1162set_stage("%(bcb_dev)s", "3/3");
1163reboot_now("%(bcb_dev)s", "recovery");
Michael Rungefb8886d2014-10-23 13:51:04 -07001164else if get_stage("%(bcb_dev)s") != "3/3" then
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001165""" % bcb_dev)
1166
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001167 script.Print("Verifying current system...")
1168
Doug Zongkere5ff5902012-01-17 10:55:37 -08001169 device_specific.IncrementalOTA_VerifyBegin()
1170
Doug Zongker881dd402009-09-20 14:03:55 -07001171 script.ShowProgress(0.1, 0)
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001172 so_far = system_diff.EmitVerification(script)
1173 if vendor_diff:
1174 so_far += vendor_diff.EmitVerification(script)
Doug Zongkereef39442009-04-02 12:14:19 -07001175
Doug Zongker5da317e2009-06-02 13:38:17 -07001176 if updating_boot:
Doug Zongkerea5d7a92010-09-12 15:26:16 -07001177 d = common.Difference(target_boot, source_boot)
Doug Zongker761e6422009-09-25 10:45:39 -07001178 _, _, d = d.ComputePatch()
Doug Zongker5da317e2009-06-02 13:38:17 -07001179 print "boot target: %d source: %d diff: %d" % (
1180 target_boot.size, source_boot.size, len(d))
1181
Doug Zongker048e7ca2009-06-15 14:31:53 -07001182 common.ZipWriteStr(output_zip, "patch/boot.img.p", d)
Doug Zongker5da317e2009-06-02 13:38:17 -07001183
Doug Zongker96a57e72010-09-26 14:57:41 -07001184 boot_type, boot_device = common.GetTypeAndDevice("/boot", OPTIONS.info_dict)
Doug Zongkerf2ab2902010-09-22 10:12:54 -07001185
1186 script.PatchCheck("%s:%s:%d:%s:%d:%s" %
1187 (boot_type, boot_device,
Doug Zongker67369982010-07-07 13:53:32 -07001188 source_boot.size, source_boot.sha1,
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001189 target_boot.size, target_boot.sha1))
Doug Zongker881dd402009-09-20 14:03:55 -07001190 so_far += source_boot.size
Doug Zongker5da317e2009-06-02 13:38:17 -07001191
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001192 size = []
1193 if system_diff.patch_list: size.append(system_diff.largest_source_size)
1194 if vendor_diff:
1195 if vendor_diff.patch_list: size.append(vendor_diff.largest_source_size)
1196 if size or updating_recovery or updating_boot:
1197 script.CacheFreeSpaceCheck(max(size))
Doug Zongker5a482092010-02-17 16:09:18 -08001198
Doug Zongker05d3dea2009-06-22 11:32:31 -07001199 device_specific.IncrementalOTA_VerifyEnd()
1200
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001201 if OPTIONS.two_step:
1202 script.WriteRawImage("/boot", "recovery.img")
1203 script.AppendExtra("""
1204set_stage("%(bcb_dev)s", "2/3");
1205reboot_now("%(bcb_dev)s", "");
1206else
1207""" % bcb_dev)
1208
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001209 script.Comment("---- start making changes here ----")
Doug Zongkereef39442009-04-02 12:14:19 -07001210
Doug Zongkere5ff5902012-01-17 10:55:37 -08001211 device_specific.IncrementalOTA_InstallBegin()
1212
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001213 if OPTIONS.two_step:
1214 common.ZipWriteStr(output_zip, "boot.img", target_boot.data)
1215 script.WriteRawImage("/boot", "boot.img")
1216 print "writing full boot image (forced by two-step mode)"
1217
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001218 script.Print("Removing unneeded files...")
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001219 system_diff.RemoveUnneededFiles(script, ("/system/recovery.img",))
1220 if vendor_diff:
1221 vendor_diff.RemoveUnneededFiles(script)
Doug Zongkereef39442009-04-02 12:14:19 -07001222
Doug Zongker881dd402009-09-20 14:03:55 -07001223 script.ShowProgress(0.8, 0)
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001224 total_patch_size = 1.0 + system_diff.TotalPatchSize()
1225 if vendor_diff:
1226 total_patch_size += vendor_diff.TotalPatchSize()
Doug Zongker881dd402009-09-20 14:03:55 -07001227 if updating_boot:
1228 total_patch_size += target_boot.size
Doug Zongker881dd402009-09-20 14:03:55 -07001229
1230 script.Print("Patching system files...")
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001231 so_far = system_diff.EmitPatches(script, total_patch_size, 0)
1232 if vendor_diff:
1233 script.Print("Patching vendor files...")
1234 so_far = vendor_diff.EmitPatches(script, total_patch_size, so_far)
Doug Zongker881dd402009-09-20 14:03:55 -07001235
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001236 if not OPTIONS.two_step:
1237 if updating_boot:
1238 # Produce the boot image by applying a patch to the current
1239 # contents of the boot partition, and write it back to the
1240 # partition.
1241 script.Print("Patching boot image...")
1242 script.ApplyPatch("%s:%s:%d:%s:%d:%s"
1243 % (boot_type, boot_device,
1244 source_boot.size, source_boot.sha1,
1245 target_boot.size, target_boot.sha1),
1246 "-",
1247 target_boot.size, target_boot.sha1,
1248 source_boot.sha1, "patch/boot.img.p")
1249 so_far += target_boot.size
1250 script.SetProgress(so_far / total_patch_size)
1251 print "boot image changed; including."
1252 else:
1253 print "boot image unchanged; skipping."
Doug Zongkereef39442009-04-02 12:14:19 -07001254
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001255 system_items = ItemSet("system", "META/filesystem_config.txt")
1256 if vendor_diff:
1257 vendor_items = ItemSet("vendor", "META/vendor_filesystem_config.txt")
1258
Doug Zongkereef39442009-04-02 12:14:19 -07001259 if updating_recovery:
Doug Zongkerb32161a2012-08-21 10:33:44 -07001260 # Recovery is generated as a patch using both the boot image
1261 # (which contains the same linux kernel as recovery) and the file
1262 # /system/etc/recovery-resource.dat (which contains all the images
1263 # used in the recovery UI) as sources. This lets us minimize the
1264 # size of the patch, which must be included in every OTA package.
Doug Zongker73ef8252009-07-23 15:12:53 -07001265 #
Doug Zongkerb32161a2012-08-21 10:33:44 -07001266 # For older builds where recovery-resource.dat is not present, we
1267 # use only the boot image as the source.
1268
Doug Zongkerc9253822014-02-04 12:17:58 -08001269 if not target_has_recovery_patch:
1270 def output_sink(fn, data):
1271 common.ZipWriteStr(output_zip, "recovery/" + fn, data)
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001272 system_items.Get("system/" + fn, dir=False)
Doug Zongkerc9253822014-02-04 12:17:58 -08001273
1274 common.MakeRecoveryPatch(OPTIONS.target_tmp, output_sink,
1275 target_recovery, target_boot)
1276 script.DeleteFiles(["/system/recovery-from-boot.p",
1277 "/system/etc/install-recovery.sh"])
Doug Zongker73ef8252009-07-23 15:12:53 -07001278 print "recovery image changed; including as patch from boot."
Doug Zongkereef39442009-04-02 12:14:19 -07001279 else:
1280 print "recovery image unchanged; skipping."
1281
Doug Zongker881dd402009-09-20 14:03:55 -07001282 script.ShowProgress(0.1, 10)
Doug Zongkereef39442009-04-02 12:14:19 -07001283
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001284 target_symlinks = CopyPartitionFiles(system_items, target_zip, None)
1285 if vendor_diff:
1286 target_symlinks.extend(CopyPartitionFiles(vendor_items, target_zip, None))
1287
1288 temp_script = script.MakeTemporary()
1289 system_items.GetMetadata(target_zip)
1290 system_items.Get("system").SetPermissions(temp_script)
1291 if vendor_diff:
1292 vendor_items.GetMetadata(target_zip)
1293 vendor_items.Get("vendor").SetPermissions(temp_script)
1294
1295 # Note that this call will mess up the trees of Items, so make sure
1296 # we're done with them.
1297 source_symlinks = CopyPartitionFiles(system_items, source_zip, None)
1298 if vendor_diff:
1299 source_symlinks.extend(CopyPartitionFiles(vendor_items, source_zip, None))
Doug Zongkereef39442009-04-02 12:14:19 -07001300
1301 target_symlinks_d = dict([(i[1], i[0]) for i in target_symlinks])
Doug Zongkereef39442009-04-02 12:14:19 -07001302 source_symlinks_d = dict([(i[1], i[0]) for i in source_symlinks])
1303
1304 # Delete all the symlinks in source that aren't in target. This
1305 # needs to happen before verbatim files are unpacked, in case a
1306 # symlink in the source is replaced by a real file in the target.
1307 to_delete = []
1308 for dest, link in source_symlinks:
1309 if link not in target_symlinks_d:
1310 to_delete.append(link)
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001311 script.DeleteFiles(to_delete)
Doug Zongkereef39442009-04-02 12:14:19 -07001312
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001313 if system_diff.verbatim_targets:
1314 script.Print("Unpacking new system files...")
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001315 script.UnpackPackageDir("system", "/system")
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001316 if vendor_diff and vendor_diff.verbatim_targets:
1317 script.Print("Unpacking new vendor files...")
1318 script.UnpackPackageDir("vendor", "/vendor")
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001319
Doug Zongkerc9253822014-02-04 12:17:58 -08001320 if updating_recovery and not target_has_recovery_patch:
Doug Zongker42265392010-02-12 10:21:00 -08001321 script.Print("Unpacking new recovery...")
1322 script.UnpackPackageDir("recovery", "/system")
1323
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001324 system_diff.EmitRenames(script)
1325 if vendor_diff:
1326 vendor_diff.EmitRenames(script)
Michael Runge4038aa82013-12-13 18:06:28 -08001327
Doug Zongker05d3dea2009-06-22 11:32:31 -07001328 script.Print("Symlinks and permissions...")
Doug Zongkereef39442009-04-02 12:14:19 -07001329
1330 # Create all the symlinks that don't already exist, or point to
1331 # somewhere different than what we want. Delete each symlink before
1332 # creating it, since the 'symlink' command won't overwrite.
1333 to_create = []
1334 for dest, link in target_symlinks:
1335 if link in source_symlinks_d:
1336 if dest != source_symlinks_d[link]:
1337 to_create.append((dest, link))
1338 else:
1339 to_create.append((dest, link))
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001340 script.DeleteFiles([i[1] for i in to_create])
1341 script.MakeSymlinks(to_create)
Doug Zongkereef39442009-04-02 12:14:19 -07001342
1343 # Now that the symlinks are created, we can set all the
1344 # permissions.
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001345 script.AppendScript(temp_script)
Doug Zongkereef39442009-04-02 12:14:19 -07001346
Doug Zongker881dd402009-09-20 14:03:55 -07001347 # Do device-specific installation (eg, write radio image).
Doug Zongker05d3dea2009-06-22 11:32:31 -07001348 device_specific.IncrementalOTA_InstallEnd()
1349
Doug Zongker1c390a22009-05-14 19:06:36 -07001350 if OPTIONS.extra_script is not None:
Doug Zongker67369982010-07-07 13:53:32 -07001351 script.AppendExtra(OPTIONS.extra_script)
Doug Zongker1c390a22009-05-14 19:06:36 -07001352
Doug Zongkere92f15a2011-08-26 13:46:40 -07001353 # Patch the build.prop file last, so if something fails but the
1354 # device can still come up, it appears to be the old build and will
1355 # get set the OTA package again to retry.
1356 script.Print("Patching remaining system files...")
Doug Zongkerc8b4e842014-06-16 15:16:31 -07001357 system_diff.EmitDeferredPatches(script)
Doug Zongkere92f15a2011-08-26 13:46:40 -07001358
Doug Zongker922206e2014-03-04 13:16:24 -08001359 if OPTIONS.wipe_user_data:
1360 script.Print("Erasing user data...")
1361 script.FormatPartition("/data")
1362
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001363 if OPTIONS.two_step:
1364 script.AppendExtra("""
1365set_stage("%(bcb_dev)s", "");
1366endif;
1367endif;
1368""" % bcb_dev)
1369
Michael Runge63f01de2014-10-28 19:24:19 -07001370 if OPTIONS.verify and system_diff:
1371 script.Print("Remounting and verifying system partition files...")
1372 script.Unmount("/system")
1373 script.Mount("/system")
1374 system_diff.EmitExplicitTargetVerification(script)
1375
1376 if OPTIONS.verify and vendor_diff:
1377 script.Print("Remounting and verifying vendor partition files...")
1378 script.Unmount("/vendor")
1379 script.Mount("/vendor")
1380 vendor_diff.EmitExplicitTargetVerification(script)
Doug Zongker25568482014-03-03 10:21:27 -08001381 script.AddToZip(target_zip, output_zip, input_path=OPTIONS.updater_binary)
Michael Runge63f01de2014-10-28 19:24:19 -07001382
Doug Zongker2ea21062010-04-28 16:05:21 -07001383 WriteMetadata(metadata, output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -07001384
1385
1386def main(argv):
1387
1388 def option_handler(o, a):
Doug Zongker25568482014-03-03 10:21:27 -08001389 if o == "--board_config":
Doug Zongkerfdd8e692009-08-03 17:27:48 -07001390 pass # deprecated
Doug Zongkereef39442009-04-02 12:14:19 -07001391 elif o in ("-k", "--package_key"):
1392 OPTIONS.package_key = a
Doug Zongkereef39442009-04-02 12:14:19 -07001393 elif o in ("-i", "--incremental_from"):
1394 OPTIONS.incremental_source = a
Doug Zongkerdbfaae52009-04-21 17:12:54 -07001395 elif o in ("-w", "--wipe_user_data"):
1396 OPTIONS.wipe_user_data = True
Doug Zongker962069c2009-04-23 11:41:58 -07001397 elif o in ("-n", "--no_prereq"):
1398 OPTIONS.omit_prereq = True
Michael Runge6e836112014-04-15 17:40:21 -07001399 elif o in ("-o", "--oem_settings"):
1400 OPTIONS.oem_source = a
Doug Zongker1c390a22009-05-14 19:06:36 -07001401 elif o in ("-e", "--extra_script"):
1402 OPTIONS.extra_script = a
Hristo Bojinovdafb0422010-08-26 14:35:16 -07001403 elif o in ("-a", "--aslr_mode"):
1404 if a in ("on", "On", "true", "True", "yes", "Yes"):
1405 OPTIONS.aslr_mode = True
1406 else:
1407 OPTIONS.aslr_mode = False
Martin Blumenstingl374e1142014-05-31 20:42:55 +02001408 elif o in ("-t", "--worker_threads"):
1409 if a.isdigit():
1410 OPTIONS.worker_threads = int(a)
1411 else:
1412 raise ValueError("Cannot parse value %r for option %r - only "
1413 "integers are allowed." % (a, o))
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001414 elif o in ("-2", "--two_step"):
1415 OPTIONS.two_step = True
Doug Zongker26e66192014-02-20 13:22:07 -08001416 elif o == "--no_signing":
Takeshi Kanemotoe153b342013-11-14 17:20:50 +09001417 OPTIONS.no_signing = True
Michael Runge63f01de2014-10-28 19:24:19 -07001418 elif o in ("--verify"):
1419 OPTIONS.verify = True
Doug Zongker26e66192014-02-20 13:22:07 -08001420 elif o == "--block":
1421 OPTIONS.block_based = True
Doug Zongker25568482014-03-03 10:21:27 -08001422 elif o in ("-b", "--binary"):
1423 OPTIONS.updater_binary = a
Doug Zongker62d4f182014-08-04 16:06:43 -07001424 elif o in ("--no_fallback_to_full",):
1425 OPTIONS.fallback_to_full = False
Doug Zongkereef39442009-04-02 12:14:19 -07001426 else:
1427 return False
Doug Zongkerdbfaae52009-04-21 17:12:54 -07001428 return True
Doug Zongkereef39442009-04-02 12:14:19 -07001429
1430 args = common.ParseOptions(argv, __doc__,
Ying Wangf5770d72014-06-19 10:32:35 -07001431 extra_opts="b:k:i:d:wne:t:a:2o:",
Doug Zongkereef39442009-04-02 12:14:19 -07001432 extra_long_opts=["board_config=",
1433 "package_key=",
Doug Zongkerdbfaae52009-04-21 17:12:54 -07001434 "incremental_from=",
Doug Zongker962069c2009-04-23 11:41:58 -07001435 "wipe_user_data",
Doug Zongker1c390a22009-05-14 19:06:36 -07001436 "no_prereq",
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001437 "extra_script=",
Hristo Bojinov96be7202010-08-02 10:26:17 -07001438 "worker_threads=",
Doug Zongkerc60c1ba2010-09-03 13:22:38 -07001439 "aslr_mode=",
Doug Zongker9b23f2c2013-11-25 14:44:12 -08001440 "two_step",
Takeshi Kanemotoe153b342013-11-14 17:20:50 +09001441 "no_signing",
Doug Zongker26e66192014-02-20 13:22:07 -08001442 "block",
Doug Zongker25568482014-03-03 10:21:27 -08001443 "binary=",
Michael Runge6e836112014-04-15 17:40:21 -07001444 "oem_settings=",
Michael Runge63f01de2014-10-28 19:24:19 -07001445 "verify",
Doug Zongker62d4f182014-08-04 16:06:43 -07001446 "no_fallback_to_full",
Doug Zongkerc60c1ba2010-09-03 13:22:38 -07001447 ],
Doug Zongkereef39442009-04-02 12:14:19 -07001448 extra_option_handler=option_handler)
1449
1450 if len(args) != 2:
1451 common.Usage(__doc__)
1452 sys.exit(1)
1453
Doug Zongker1c390a22009-05-14 19:06:36 -07001454 if OPTIONS.extra_script is not None:
1455 OPTIONS.extra_script = open(OPTIONS.extra_script).read()
1456
Doug Zongkereef39442009-04-02 12:14:19 -07001457 print "unzipping target target-files..."
Doug Zongker55d93282011-01-25 17:03:34 -08001458 OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])
Doug Zongkerfdd8e692009-08-03 17:27:48 -07001459
Doug Zongkereef39442009-04-02 12:14:19 -07001460 OPTIONS.target_tmp = OPTIONS.input_tmp
Doug Zongker37974732010-09-16 17:44:38 -07001461 OPTIONS.info_dict = common.LoadInfoDict(input_zip)
Kenny Roote2e9f612013-05-29 12:59:35 -07001462
1463 # If this image was originally labelled with SELinux contexts, make sure we
1464 # also apply the labels in our new image. During building, the "file_contexts"
1465 # is in the out/ directory tree, but for repacking from target-files.zip it's
1466 # in the root directory of the ramdisk.
1467 if "selinux_fc" in OPTIONS.info_dict:
1468 OPTIONS.info_dict["selinux_fc"] = os.path.join(OPTIONS.input_tmp, "BOOT", "RAMDISK",
1469 "file_contexts")
1470
Doug Zongker37974732010-09-16 17:44:38 -07001471 if OPTIONS.verbose:
1472 print "--- target info ---"
1473 common.DumpInfoDict(OPTIONS.info_dict)
1474
Doug Zongkereb0a78a2014-01-27 10:01:06 -08001475 # If the caller explicitly specified the device-specific extensions
1476 # path via -s/--device_specific, use that. Otherwise, use
1477 # META/releasetools.py if it is present in the target target_files.
1478 # Otherwise, take the path of the file from 'tool_extensions' in the
1479 # info dict and look for that in the local filesystem, relative to
1480 # the current directory.
1481
Doug Zongker37974732010-09-16 17:44:38 -07001482 if OPTIONS.device_specific is None:
Doug Zongkereb0a78a2014-01-27 10:01:06 -08001483 from_input = os.path.join(OPTIONS.input_tmp, "META", "releasetools.py")
1484 if os.path.exists(from_input):
1485 print "(using device-specific extensions from target_files)"
1486 OPTIONS.device_specific = from_input
1487 else:
1488 OPTIONS.device_specific = OPTIONS.info_dict.get("tool_extensions", None)
1489
Doug Zongker37974732010-09-16 17:44:38 -07001490 if OPTIONS.device_specific is not None:
Doug Zongkereb0a78a2014-01-27 10:01:06 -08001491 OPTIONS.device_specific = os.path.abspath(OPTIONS.device_specific)
Doug Zongker37974732010-09-16 17:44:38 -07001492
Doug Zongker62d4f182014-08-04 16:06:43 -07001493 while True:
Doug Zongkereef39442009-04-02 12:14:19 -07001494
Doug Zongker62d4f182014-08-04 16:06:43 -07001495 if OPTIONS.no_signing:
1496 if os.path.exists(args[1]): os.unlink(args[1])
1497 output_zip = zipfile.ZipFile(args[1], "w", compression=zipfile.ZIP_DEFLATED)
1498 else:
1499 temp_zip_file = tempfile.NamedTemporaryFile()
1500 output_zip = zipfile.ZipFile(temp_zip_file, "w",
1501 compression=zipfile.ZIP_DEFLATED)
1502
1503 if OPTIONS.incremental_source is None:
1504 WriteFullOTAPackage(input_zip, output_zip)
1505 if OPTIONS.package_key is None:
1506 OPTIONS.package_key = OPTIONS.info_dict.get(
1507 "default_system_dev_certificate",
1508 "build/target/product/security/testkey")
1509 break
1510
1511 else:
1512 print "unzipping source target-files..."
1513 OPTIONS.source_tmp, source_zip = common.UnzipTemp(OPTIONS.incremental_source)
1514 OPTIONS.target_info_dict = OPTIONS.info_dict
1515 OPTIONS.source_info_dict = common.LoadInfoDict(source_zip)
1516 if "selinux_fc" in OPTIONS.source_info_dict:
1517 OPTIONS.source_info_dict["selinux_fc"] = os.path.join(OPTIONS.source_tmp, "BOOT", "RAMDISK",
1518 "file_contexts")
1519 if OPTIONS.package_key is None:
1520 OPTIONS.package_key = OPTIONS.source_info_dict.get(
1521 "default_system_dev_certificate",
1522 "build/target/product/security/testkey")
1523 if OPTIONS.verbose:
1524 print "--- source info ---"
1525 common.DumpInfoDict(OPTIONS.source_info_dict)
1526 try:
1527 WriteIncrementalOTAPackage(input_zip, source_zip, output_zip)
1528 break
1529 except ValueError:
1530 if not OPTIONS.fallback_to_full: raise
1531 print "--- failed to build incremental; falling back to full ---"
1532 OPTIONS.incremental_source = None
1533 output_zip.close()
Doug Zongkereef39442009-04-02 12:14:19 -07001534
1535 output_zip.close()
Doug Zongkerafb32ea2011-09-22 10:28:04 -07001536
Takeshi Kanemotoe153b342013-11-14 17:20:50 +09001537 if not OPTIONS.no_signing:
1538 SignOutput(temp_zip_file.name, args[1])
1539 temp_zip_file.close()
Doug Zongkereef39442009-04-02 12:14:19 -07001540
Doug Zongkereef39442009-04-02 12:14:19 -07001541 print "done."
1542
1543
1544if __name__ == '__main__':
1545 try:
Ying Wang7e6d4e42010-12-13 16:25:36 -08001546 common.CloseInheritedPipes()
Doug Zongkereef39442009-04-02 12:14:19 -07001547 main(sys.argv[1:])
1548 except common.ExternalError, e:
1549 print
1550 print " ERROR: %s" % (e,)
1551 print
1552 sys.exit(1)
Doug Zongkerfc44a512014-08-26 13:10:25 -07001553 finally:
1554 common.Cleanup()