blob: a9a9a0bd1dfb7482d55f7491b7677a6d2caaba92 [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 '
Tao Baoe7b10372015-06-03 09:24:08 -0700162 'on /cache 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
Tao Baodf06e962015-06-10 12:32:41 -0700180 mount_flags = mount_dict.get(p.fs_type, "")
181 if p.context is not None:
182 mount_flags = p.context + ("," + mount_flags if mount_flags else "")
Dan Albert8b72aef2015-03-23 19:13:21 -0700183 self.script.append('mount("%s", "%s", "%s", "%s", "%s");' % (
184 p.fs_type, common.PARTITION_TYPES[p.fs_type], p.device,
Tao Baodf06e962015-06-10 12:32:41 -0700185 p.mount_point, mount_flags))
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700186 self.mounts.add(p.mount_point)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700187
188 def UnpackPackageDir(self, src, dst):
189 """Unpack a given directory from the OTA package into the given
190 destination directory."""
191 self.script.append('package_extract_dir("%s", "%s");' % (src, dst))
192
193 def Comment(self, comment):
194 """Write a comment into the update script."""
195 self.script.append("")
196 for i in comment.split("\n"):
197 self.script.append("# " + i)
198 self.script.append("")
199
200 def Print(self, message):
201 """Log a message to the screen (if the logs are visible)."""
202 self.script.append('ui_print("%s");' % (message,))
203
Michael Runge3e286642014-11-21 00:46:03 -0800204 def TunePartition(self, partition, *options):
205 fstab = self.info.get("fstab", None)
206 if fstab:
207 p = fstab[partition]
Dan Albert8b72aef2015-03-23 19:13:21 -0700208 if p.fs_type not in ("ext2", "ext3", "ext4"):
Michael Runge3e286642014-11-21 00:46:03 -0800209 raise ValueError("Partition %s cannot be tuned\n" % (partition,))
Dan Albert8b72aef2015-03-23 19:13:21 -0700210 self.script.append(
211 'tune2fs(' + "".join(['"%s", ' % (i,) for i in options]) +
212 '"%s") || abort("Failed to tune partition %s");' % (
213 p.device, partition))
Michael Runge3e286642014-11-21 00:46:03 -0800214
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700215 def FormatPartition(self, partition):
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700216 """Format the given partition, specified by its mount point (eg,
217 "/system")."""
218
219 fstab = self.info.get("fstab", None)
220 if fstab:
221 p = fstab[partition]
Doug Zongkerdf2056e2012-04-09 12:27:43 -0700222 self.script.append('format("%s", "%s", "%s", "%s", "%s");' %
Doug Zongker086cbb02011-02-17 15:54:20 -0800223 (p.fs_type, common.PARTITION_TYPES[p.fs_type],
Doug Zongkerdf2056e2012-04-09 12:27:43 -0700224 p.device, p.length, p.mount_point))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700225
Doug Zongker5fad2032014-02-24 08:13:45 -0800226 def WipeBlockDevice(self, partition):
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700227 if partition not in ("/system", "/vendor"):
228 raise ValueError(("WipeBlockDevice doesn't work on %s\n") % (partition,))
Doug Zongker5fad2032014-02-24 08:13:45 -0800229 fstab = self.info.get("fstab", None)
Doug Zongkerc8b4e842014-06-16 15:16:31 -0700230 size = self.info.get(partition.lstrip("/") + "_size", None)
Doug Zongker5fad2032014-02-24 08:13:45 -0800231 device = fstab[partition].device
232
233 self.script.append('wipe_block_device("%s", %s);' % (device, size))
234
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700235 def DeleteFiles(self, file_list):
236 """Delete all files in file_list."""
Dan Albert8b72aef2015-03-23 19:13:21 -0700237 if not file_list:
238 return
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700239 cmd = "delete(" + ",\0".join(['"%s"' % (i,) for i in file_list]) + ");"
Dan Albert8b72aef2015-03-23 19:13:21 -0700240 self.script.append(self.WordWrap(cmd))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700241
Michael Runge4038aa82013-12-13 18:06:28 -0800242 def RenameFile(self, srcfile, tgtfile):
243 """Moves a file from one location to another."""
244 if self.info.get("update_rename_support", False):
245 self.script.append('rename("%s", "%s");' % (srcfile, tgtfile))
246 else:
247 raise ValueError("Rename not supported by update binary")
248
249 def SkipNextActionIfTargetExists(self, tgtfile, tgtsha1):
250 """Prepend an action with an apply_patch_check in order to
251 skip the action if the file exists. Used when a patch
252 is later renamed."""
253 cmd = ('sha1_check(read_file("%s"), %s) || ' % (tgtfile, tgtsha1))
Dan Albert8b72aef2015-03-23 19:13:21 -0700254 self.script.append(self.WordWrap(cmd))
Michael Runge4038aa82013-12-13 18:06:28 -0800255
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700256 def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
257 """Apply binary patches (in *patchpairs) to the given srcfile to
258 produce tgtfile (which may be "-" to indicate overwriting the
259 source file."""
260 if len(patchpairs) % 2 != 0 or len(patchpairs) == 0:
261 raise ValueError("bad patches given to ApplyPatch")
262 cmd = ['apply_patch("%s",\0"%s",\0%s,\0%d'
263 % (srcfile, tgtfile, tgtsha1, tgtsize)]
264 for i in range(0, len(patchpairs), 2):
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800265 cmd.append(',\0%s, package_extract_file("%s")' % patchpairs[i:i+2])
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700266 cmd.append(');')
267 cmd = "".join(cmd)
Dan Albert8b72aef2015-03-23 19:13:21 -0700268 self.script.append(self.WordWrap(cmd))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700269
Doug Zongker5fad2032014-02-24 08:13:45 -0800270 def WriteRawImage(self, mount_point, fn, mapfn=None):
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700271 """Write the given package file into the partition for the given
272 mount point."""
Doug Zongkerb4c7d322010-07-01 15:30:11 -0700273
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700274 fstab = self.info["fstab"]
275 if fstab:
276 p = fstab[mount_point]
Doug Zongker96a57e72010-09-26 14:57:41 -0700277 partition_type = common.PARTITION_TYPES[p.fs_type]
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700278 args = {'device': p.device, 'fn': fn}
279 if partition_type == "MTD":
280 self.script.append(
Doug Zongker02da2102011-04-12 15:50:17 -0700281 'write_raw_image(package_extract_file("%(fn)s"), "%(device)s");'
282 % args)
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700283 elif partition_type == "EMMC":
Doug Zongker5fad2032014-02-24 08:13:45 -0800284 if mapfn:
285 args["map"] = mapfn
286 self.script.append(
287 'package_extract_file("%(fn)s", "%(device)s", "%(map)s");' % args)
288 else:
289 self.script.append(
290 'package_extract_file("%(fn)s", "%(device)s");' % args)
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700291 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700292 raise ValueError(
293 "don't know how to write \"%s\" partitions" % p.fs_type)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700294
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700295 def SetPermissions(self, fn, uid, gid, mode, selabel, capabilities):
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700296 """Set file ownership and permissions."""
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700297 if not self.info.get("use_set_metadata", False):
298 self.script.append('set_perm(%d, %d, 0%o, "%s");' % (uid, gid, mode, fn))
299 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700300 if capabilities is None:
301 capabilities = "0x0"
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700302 cmd = 'set_metadata("%s", "uid", %d, "gid", %d, "mode", 0%o, ' \
303 '"capabilities", %s' % (fn, uid, gid, mode, capabilities)
304 if selabel is not None:
Dan Albert8b72aef2015-03-23 19:13:21 -0700305 cmd += ', "selabel", "%s"' % selabel
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700306 cmd += ');'
307 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700308
Dan Albert8b72aef2015-03-23 19:13:21 -0700309 def SetPermissionsRecursive(self, fn, uid, gid, dmode, fmode, selabel,
310 capabilities):
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700311 """Recursively set path ownership and permissions."""
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700312 if not self.info.get("use_set_metadata", False):
313 self.script.append('set_perm_recursive(%d, %d, 0%o, 0%o, "%s");'
314 % (uid, gid, dmode, fmode, fn))
315 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700316 if capabilities is None:
317 capabilities = "0x0"
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700318 cmd = 'set_metadata_recursive("%s", "uid", %d, "gid", %d, ' \
319 '"dmode", 0%o, "fmode", 0%o, "capabilities", %s' \
320 % (fn, uid, gid, dmode, fmode, capabilities)
321 if selabel is not None:
Dan Albert8b72aef2015-03-23 19:13:21 -0700322 cmd += ', "selabel", "%s"' % selabel
Nick Kralevich0eb17d92013-09-07 17:10:29 -0700323 cmd += ');'
324 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700325
326 def MakeSymlinks(self, symlink_list):
327 """Create symlinks, given a list of (dest, link) pairs."""
328 by_dest = {}
329 for d, l in symlink_list:
330 by_dest.setdefault(d, []).append(l)
331
332 for dest, links in sorted(by_dest.iteritems()):
333 cmd = ('symlink("%s", ' % (dest,) +
334 ",\0".join(['"' + i + '"' for i in sorted(links)]) + ");")
Dan Albert8b72aef2015-03-23 19:13:21 -0700335 self.script.append(self.WordWrap(cmd))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700336
337 def AppendExtra(self, extra):
338 """Append text verbatim to the output script."""
339 self.script.append(extra)
340
Michael Runge63f01de2014-10-28 19:24:19 -0700341 def Unmount(self, mount_point):
Dan Albert8b72aef2015-03-23 19:13:21 -0700342 self.script.append('unmount("%s");' % mount_point)
343 self.mounts.remove(mount_point)
Michael Runge63f01de2014-10-28 19:24:19 -0700344
Doug Zongker14833602010-02-02 13:12:04 -0800345 def UnmountAll(self):
346 for p in sorted(self.mounts):
347 self.script.append('unmount("%s");' % (p,))
348 self.mounts = set()
349
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700350 def AddToZip(self, input_zip, output_zip, input_path=None):
351 """Write the accumulated script to the output_zip file. input_zip
352 is used as the source for the 'updater' binary needed to run
353 script. If input_path is not None, it will be used as a local
354 path for the binary instead of input_zip."""
355
Doug Zongker14833602010-02-02 13:12:04 -0800356 self.UnmountAll()
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700357
358 common.ZipWriteStr(output_zip, "META-INF/com/google/android/updater-script",
359 "\n".join(self.script) + "\n")
360
361 if input_path is None:
362 data = input_zip.read("OTA/bin/updater")
363 else:
Doug Zongker25568482014-03-03 10:21:27 -0800364 data = open(input_path, "rb").read()
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700365 common.ZipWriteStr(output_zip, "META-INF/com/google/android/update-binary",
Dan Albert8b72aef2015-03-23 19:13:21 -0700366 data, perms=0o755)