blob: 3d0da88fe5424e5ff22adcf934517c7e7b59e132 [file] [log] [blame]
Doug Zongkerc494d7c2009-06-18 08:43:44 -07001# Copyright (C) 2009 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Doug Zongkerc494d7c2009-06-18 08:43:44 -070015import re
16
17import common
18
19class EdifyGenerator(object):
20 """Class to generate scripts in the 'edify' recovery script language
21 used from donut onwards."""
22
Doug Zongkerb4c7d322010-07-01 15:30:11 -070023 def __init__(self, version, info):
Doug Zongkerc494d7c2009-06-18 08:43:44 -070024 self.script = []
25 self.mounts = set()
26 self.version = version
Doug Zongkerb4c7d322010-07-01 15:30:11 -070027 self.info = info
Doug Zongkerc494d7c2009-06-18 08:43:44 -070028
29 def MakeTemporary(self):
30 """Make a temporary script object whose commands can latter be
31 appended to the parent script with AppendScript(). Used when the
32 caller wants to generate script commands out-of-order."""
Doug Zongker67369982010-07-07 13:53:32 -070033 x = EdifyGenerator(self.version, self.info)
Doug Zongkerc494d7c2009-06-18 08:43:44 -070034 x.mounts = self.mounts
35 return x
36
37 @staticmethod
Dan Albert8b72aef2015-03-23 19:13:21 -070038 def WordWrap(cmd, linelen=80):
Doug Zongkerc494d7c2009-06-18 08:43:44 -070039 """'cmd' should be a function call with null characters after each
40 parameter (eg, "somefun(foo,\0bar,\0baz)"). This function wraps cmd
41 to a given line length, replacing nulls with spaces and/or newlines
42 to format it nicely."""
43 indent = cmd.index("(")+1
44 out = []
45 first = True
46 x = re.compile("^(.{,%d})\0" % (linelen-indent,))
47 while True:
48 if not first:
49 out.append(" " * indent)
50 first = False
51 m = x.search(cmd)
52 if not m:
53 parts = cmd.split("\0", 1)
54 out.append(parts[0]+"\n")
55 if len(parts) == 1:
56 break
57 else:
58 cmd = parts[1]
59 continue
60 out.append(m.group(1)+"\n")
61 cmd = cmd[m.end():]
62
63 return "".join(out).replace("\0", " ").rstrip("\n")
64
65 def AppendScript(self, other):
66 """Append the contents of another script (which should be created
67 with temporary=True) to this one."""
68 self.script.extend(other.script)
69
Michael Runge6e836112014-04-15 17:40:21 -070070 def AssertOemProperty(self, name, value):
71 """Assert that a property on the OEM paritition matches a value."""
72 if not name:
73 raise ValueError("must specify an OEM property")
74 if not value:
75 raise ValueError("must specify the OEM value")
Tao Bao3910ebf2015-03-22 14:20:48 -070076 cmd = ('file_getprop("/oem/oem.prop", "{name}") == "{value}" || '
77 'abort("This package expects the value \\"{value}\\" for '
78 '\\"{name}\\" on the OEM partition; this has value \\"" + '
Dan Albert8b72aef2015-03-23 19:13:21 -070079 'file_getprop("/oem/oem.prop", "{name}") + "\\".");').format(
80 name=name, value=value)
Michael Runge6e836112014-04-15 17:40:21 -070081 self.script.append(cmd)
82
Doug Zongkerc494d7c2009-06-18 08:43:44 -070083 def AssertSomeFingerprint(self, *fp):
Doug Zongkeraf845252014-05-09 08:29:05 -070084 """Assert that the current recovery build fingerprint is one of *fp."""
Doug Zongkerc494d7c2009-06-18 08:43:44 -070085 if not fp:
86 raise ValueError("must specify some fingerprints")
Dan Albert8b72aef2015-03-23 19:13:21 -070087 cmd = (' ||\n '.join([('getprop("ro.build.fingerprint") == "%s"') % i
88 for i in fp]) +
Doug Zongker0d92f1f2013-06-03 12:07:12 -070089 ' ||\n abort("Package expects build fingerprint of %s; this '
Dan Albert8b72aef2015-03-23 19:13:21 -070090 'device has " + getprop("ro.build.fingerprint") + ".");') % (
91 " or ".join(fp))
Doug Zongker0d92f1f2013-06-03 12:07:12 -070092 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -070093
Michael Runge6e836112014-04-15 17:40:21 -070094 def AssertSomeThumbprint(self, *fp):
Doug Zongkeraf845252014-05-09 08:29:05 -070095 """Assert that the current recovery build thumbprint is one of *fp."""
Geremy Condra36bd3652014-02-06 19:45:10 -080096 if not fp:
Michael Runge6e836112014-04-15 17:40:21 -070097 raise ValueError("must specify some thumbprints")
Dan Albert8b72aef2015-03-23 19:13:21 -070098 cmd = (' ||\n '.join([('getprop("ro.build.thumbprint") == "%s"') % i
99 for i in fp]) +
Michael Runge6e836112014-04-15 17:40:21 -0700100 ' ||\n abort("Package expects build thumbprint of %s; this '
Dan Albert8b72aef2015-03-23 19:13:21 -0700101 'device has " + getprop("ro.build.thumbprint") + ".");') % (
102 " or ".join(fp))
Geremy Condra36bd3652014-02-06 19:45:10 -0800103 self.script.append(cmd)
104
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700105 def AssertOlderBuild(self, timestamp, timestamp_text):
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700106 """Assert that the build on the device is older (or the same as)
107 the given timestamp."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700108 self.script.append(
109 ('(!less_than_int(%s, getprop("ro.build.date.utc"))) || '
110 'abort("Can\'t install this package (%s) over newer '
Dan Albert8b72aef2015-03-23 19:13:21 -0700111 'build (" + getprop("ro.build.date") + ").");') % (timestamp,
112 timestamp_text))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700113
114 def AssertDevice(self, device):
115 """Assert that the device identifier is the given string."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700116 cmd = ('getprop("ro.product.device") == "%s" || '
117 'abort("This package is for \\"%s\\" devices; '
Dan Albert8b72aef2015-03-23 19:13:21 -0700118 'this is a \\"" + getprop("ro.product.device") + "\\".");') % (
119 device, device)
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700120 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700121
122 def AssertSomeBootloader(self, *bootloaders):
123 """Asert that the bootloader version is one of *bootloaders."""
124 cmd = ("assert(" +
125 " ||\0".join(['getprop("ro.bootloader") == "%s"' % (b,)
126 for b in bootloaders]) +
127 ");")
Dan Albert8b72aef2015-03-23 19:13:21 -0700128 self.script.append(self.WordWrap(cmd))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700129
130 def ShowProgress(self, frac, dur):
131 """Update the progress bar, advancing it over 'frac' over the next
Doug Zongker881dd402009-09-20 14:03:55 -0700132 'dur' seconds. 'dur' may be zero to advance it via SetProgress
133 commands instead of by time."""
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700134 self.script.append("show_progress(%f, %d);" % (frac, int(dur)))
135
Doug Zongker881dd402009-09-20 14:03:55 -0700136 def SetProgress(self, frac):
137 """Set the position of the progress bar within the chunk defined
138 by the most recent ShowProgress call. 'frac' should be in
139 [0,1]."""
140 self.script.append("set_progress(%f);" % (frac,))
141
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700142 def PatchCheck(self, filename, *sha1):
143 """Check that the given file (or MTD reference) has one of the
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800144 given *sha1 hashes, checking the version saved in cache if the
145 file does not match."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700146 self.script.append(
147 'apply_patch_check("%s"' % (filename,) +
148 "".join([', "%s"' % (i,) for i in sha1]) +
149 ') || abort("\\"%s\\" has unexpected contents.");' % (filename,))
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800150
151 def FileCheck(self, filename, *sha1):
152 """Check that the given file (or MTD reference) has one of the
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700153 given *sha1 hashes."""
Doug Zongker5a482092010-02-17 16:09:18 -0800154 self.script.append('assert(sha1_check(read_file("%s")' % (filename,) +
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700155 "".join([', "%s"' % (i,) for i in sha1]) +
156 '));')
157
158 def CacheFreeSpaceCheck(self, amount):
159 """Check that there's at least 'amount' space that can be made
160 available on /cache."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700161 self.script.append(('apply_patch_space(%d) || abort("Not enough free space '
162 'on /system to apply patches.");') % (amount,))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700163
Michael Runge7cd99ba2014-10-22 17:21:48 -0700164 def Mount(self, mount_point, mount_options_by_format=""):
165 """Mount the partition with the given mount_point.
166 mount_options_by_format:
167 [fs_type=option[,option]...[|fs_type=option[,option]...]...]
168 where option is optname[=optvalue]
169 E.g. ext4=barrier=1,nodelalloc,errors=panic|f2fs=errors=recover
170 """
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700171 fstab = self.info.get("fstab", None)
172 if fstab:
173 p = fstab[mount_point]
Michael Runge7cd99ba2014-10-22 17:21:48 -0700174 mount_dict = {}
175 if mount_options_by_format is not None:
176 for option in mount_options_by_format.split("|"):
177 if "=" in option:
178 key, value = option.split("=", 1)
179 mount_dict[key] = value
Dan Albert8b72aef2015-03-23 19:13:21 -0700180 self.script.append('mount("%s", "%s", "%s", "%s", "%s");' % (
181 p.fs_type, common.PARTITION_TYPES[p.fs_type], p.device,
182 p.mount_point, mount_dict.get(p.fs_type, "")))
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700183 self.mounts.add(p.mount_point)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700184
185 def UnpackPackageDir(self, src, dst):
186 """Unpack a given directory from the OTA package into the given
187 destination directory."""
188 self.script.append('package_extract_dir("%s", "%s");' % (src, dst))
189
190 def Comment(self, comment):
191 """Write a comment into the update script."""
192 self.script.append("")
193 for i in comment.split("\n"):
194 self.script.append("# " + i)
195 self.script.append("")
196
197 def Print(self, message):
198 """Log a message to the screen (if the logs are visible)."""
199 self.script.append('ui_print("%s");' % (message,))
200
Michael Runge3e286642014-11-21 00:46:03 -0800201 def TunePartition(self, partition, *options):
202 fstab = self.info.get("fstab", None)
203 if fstab:
204 p = fstab[partition]
Dan Albert8b72aef2015-03-23 19:13:21 -0700205 if p.fs_type not in ("ext2", "ext3", "ext4"):
Michael Runge3e286642014-11-21 00:46:03 -0800206 raise ValueError("Partition %s cannot be tuned\n" % (partition,))
Dan Albert8b72aef2015-03-23 19:13:21 -0700207 self.script.append(
208 'tune2fs(' + "".join(['"%s", ' % (i,) for i in options]) +
209 '"%s") || abort("Failed to tune partition %s");' % (
210 p.device, partition))
Michael Runge3e286642014-11-21 00:46:03 -0800211
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700212 def FormatPartition(self, partition):
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700213 """Format the given partition, specified by its mount point (eg,
214 "/system")."""
215
216 fstab = self.info.get("fstab", None)
217 if fstab:
218 p = fstab[partition]
Doug Zongkerdf2056e2012-04-09 12:27:43 -0700219 self.script.append('format("%s", "%s", "%s", "%s", "%s");' %
Doug Zongker086cbb02011-02-17 15:54:20 -0800220 (p.fs_type, common.PARTITION_TYPES[p.fs_type],
Doug Zongkerdf2056e2012-04-09 12:27:43 -0700221 p.device, p.length, p.mount_point))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700222
Doug Zongker5fad2032014-02-24 08:13:45 -0800223 def WipeBlockDevice(self, partition):
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700224 if partition not in ("/system", "/vendor"):
225 raise ValueError(("WipeBlockDevice doesn't work on %s\n") % (partition,))
Doug Zongker5fad2032014-02-24 08:13:45 -0800226 fstab = self.info.get("fstab", None)
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700227 size = self.info.get(partition.lstrip("/") + "_size", None)
Doug Zongker5fad2032014-02-24 08:13:45 -0800228 device = fstab[partition].device
229
230 self.script.append('wipe_block_device("%s", %s);' % (device, size))
231
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700232 def DeleteFiles(self, file_list):
233 """Delete all files in file_list."""
Dan Albert8b72aef2015-03-23 19:13:21 -0700234 if not file_list:
235 return
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700236 cmd = "delete(" + ",\0".join(['"%s"' % (i,) for i in file_list]) + ");"
Dan Albert8b72aef2015-03-23 19:13:21 -0700237 self.script.append(self.WordWrap(cmd))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700238
Michael Runge4038aa82013-12-13 18:06:28 -0800239 def RenameFile(self, srcfile, tgtfile):
240 """Moves a file from one location to another."""
241 if self.info.get("update_rename_support", False):
242 self.script.append('rename("%s", "%s");' % (srcfile, tgtfile))
243 else:
244 raise ValueError("Rename not supported by update binary")
245
246 def SkipNextActionIfTargetExists(self, tgtfile, tgtsha1):
247 """Prepend an action with an apply_patch_check in order to
248 skip the action if the file exists. Used when a patch
249 is later renamed."""
250 cmd = ('sha1_check(read_file("%s"), %s) || ' % (tgtfile, tgtsha1))
Dan Albert8b72aef2015-03-23 19:13:21 -0700251 self.script.append(self.WordWrap(cmd))
Michael Runge4038aa82013-12-13 18:06:28 -0800252
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700253 def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
254 """Apply binary patches (in *patchpairs) to the given srcfile to
255 produce tgtfile (which may be "-" to indicate overwriting the
256 source file."""
257 if len(patchpairs) % 2 != 0 or len(patchpairs) == 0:
258 raise ValueError("bad patches given to ApplyPatch")
259 cmd = ['apply_patch("%s",\0"%s",\0%s,\0%d'
260 % (srcfile, tgtfile, tgtsha1, tgtsize)]
261 for i in range(0, len(patchpairs), 2):
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800262 cmd.append(',\0%s, package_extract_file("%s")' % patchpairs[i:i+2])
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700263 cmd.append(');')
264 cmd = "".join(cmd)
Dan Albert8b72aef2015-03-23 19:13:21 -0700265 self.script.append(self.WordWrap(cmd))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700266
Doug Zongker5fad2032014-02-24 08:13:45 -0800267 def WriteRawImage(self, mount_point, fn, mapfn=None):
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700268 """Write the given package file into the partition for the given
269 mount point."""
Doug Zongkerb4c7d322010-07-01 15:30:11 -0700270
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700271 fstab = self.info["fstab"]
272 if fstab:
273 p = fstab[mount_point]
Doug Zongker96a57e72010-09-26 14:57:41 -0700274 partition_type = common.PARTITION_TYPES[p.fs_type]
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700275 args = {'device': p.device, 'fn': fn}
276 if partition_type == "MTD":
277 self.script.append(
Doug Zongker02da2102011-04-12 15:50:17 -0700278 'write_raw_image(package_extract_file("%(fn)s"), "%(device)s");'
279 % args)
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700280 elif partition_type == "EMMC":
Doug Zongker5fad2032014-02-24 08:13:45 -0800281 if mapfn:
282 args["map"] = mapfn
283 self.script.append(
284 'package_extract_file("%(fn)s", "%(device)s", "%(map)s");' % args)
285 else:
286 self.script.append(
287 'package_extract_file("%(fn)s", "%(device)s");' % args)
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700288 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700289 raise ValueError(
290 "don't know how to write \"%s\" partitions" % p.fs_type)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700291
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700292 def SetPermissions(self, fn, uid, gid, mode, selabel, capabilities):
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700293 """Set file ownership and permissions."""
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700294 if not self.info.get("use_set_metadata", False):
295 self.script.append('set_perm(%d, %d, 0%o, "%s");' % (uid, gid, mode, fn))
296 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700297 if capabilities is None:
298 capabilities = "0x0"
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700299 cmd = 'set_metadata("%s", "uid", %d, "gid", %d, "mode", 0%o, ' \
300 '"capabilities", %s' % (fn, uid, gid, mode, capabilities)
301 if selabel is not None:
Dan Albert8b72aef2015-03-23 19:13:21 -0700302 cmd += ', "selabel", "%s"' % selabel
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700303 cmd += ');'
304 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700305
Dan Albert8b72aef2015-03-23 19:13:21 -0700306 def SetPermissionsRecursive(self, fn, uid, gid, dmode, fmode, selabel,
307 capabilities):
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700308 """Recursively set path ownership and permissions."""
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700309 if not self.info.get("use_set_metadata", False):
310 self.script.append('set_perm_recursive(%d, %d, 0%o, 0%o, "%s");'
311 % (uid, gid, dmode, fmode, fn))
312 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700313 if capabilities is None:
314 capabilities = "0x0"
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700315 cmd = 'set_metadata_recursive("%s", "uid", %d, "gid", %d, ' \
316 '"dmode", 0%o, "fmode", 0%o, "capabilities", %s' \
317 % (fn, uid, gid, dmode, fmode, capabilities)
318 if selabel is not None:
Dan Albert8b72aef2015-03-23 19:13:21 -0700319 cmd += ', "selabel", "%s"' % selabel
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700320 cmd += ');'
321 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700322
323 def MakeSymlinks(self, symlink_list):
324 """Create symlinks, given a list of (dest, link) pairs."""
325 by_dest = {}
326 for d, l in symlink_list:
327 by_dest.setdefault(d, []).append(l)
328
329 for dest, links in sorted(by_dest.iteritems()):
330 cmd = ('symlink("%s", ' % (dest,) +
331 ",\0".join(['"' + i + '"' for i in sorted(links)]) + ");")
Dan Albert8b72aef2015-03-23 19:13:21 -0700332 self.script.append(self.WordWrap(cmd))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700333
334 def AppendExtra(self, extra):
335 """Append text verbatim to the output script."""
336 self.script.append(extra)
337
Michael Runge63f01de2014-10-28 19:24:19 -0700338 def Unmount(self, mount_point):
Dan Albert8b72aef2015-03-23 19:13:21 -0700339 self.script.append('unmount("%s");' % mount_point)
340 self.mounts.remove(mount_point)
Michael Runge63f01de2014-10-28 19:24:19 -0700341
Doug Zongker14833602010-02-02 13:12:04 -0800342 def UnmountAll(self):
343 for p in sorted(self.mounts):
344 self.script.append('unmount("%s");' % (p,))
345 self.mounts = set()
346
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700347 def AddToZip(self, input_zip, output_zip, input_path=None):
348 """Write the accumulated script to the output_zip file. input_zip
349 is used as the source for the 'updater' binary needed to run
350 script. If input_path is not None, it will be used as a local
351 path for the binary instead of input_zip."""
352
Doug Zongker14833602010-02-02 13:12:04 -0800353 self.UnmountAll()
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700354
355 common.ZipWriteStr(output_zip, "META-INF/com/google/android/updater-script",
356 "\n".join(self.script) + "\n")
357
358 if input_path is None:
359 data = input_zip.read("OTA/bin/updater")
360 else:
Doug Zongker25568482014-03-03 10:21:27 -0800361 data = open(input_path, "rb").read()
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700362 common.ZipWriteStr(output_zip, "META-INF/com/google/android/update-binary",
Dan Albert8b72aef2015-03-23 19:13:21 -0700363 data, perms=0o755)