blob: 9ef19264b0e5e9991642c377aa91fd890e86acff [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
15import os
16import re
17
18import common
19
20class EdifyGenerator(object):
21 """Class to generate scripts in the 'edify' recovery script language
22 used from donut onwards."""
23
Doug Zongkerb4c7d322010-07-01 15:30:11 -070024 def __init__(self, version, info):
Doug Zongkerc494d7c2009-06-18 08:43:44 -070025 self.script = []
26 self.mounts = set()
27 self.version = version
Doug Zongkerb4c7d322010-07-01 15:30:11 -070028 self.info = info
Doug Zongkerc494d7c2009-06-18 08:43:44 -070029
30 def MakeTemporary(self):
31 """Make a temporary script object whose commands can latter be
32 appended to the parent script with AppendScript(). Used when the
33 caller wants to generate script commands out-of-order."""
Doug Zongker67369982010-07-07 13:53:32 -070034 x = EdifyGenerator(self.version, self.info)
Doug Zongkerc494d7c2009-06-18 08:43:44 -070035 x.mounts = self.mounts
36 return x
37
38 @staticmethod
39 def _WordWrap(cmd, linelen=80):
40 """'cmd' should be a function call with null characters after each
41 parameter (eg, "somefun(foo,\0bar,\0baz)"). This function wraps cmd
42 to a given line length, replacing nulls with spaces and/or newlines
43 to format it nicely."""
44 indent = cmd.index("(")+1
45 out = []
46 first = True
47 x = re.compile("^(.{,%d})\0" % (linelen-indent,))
48 while True:
49 if not first:
50 out.append(" " * indent)
51 first = False
52 m = x.search(cmd)
53 if not m:
54 parts = cmd.split("\0", 1)
55 out.append(parts[0]+"\n")
56 if len(parts) == 1:
57 break
58 else:
59 cmd = parts[1]
60 continue
61 out.append(m.group(1)+"\n")
62 cmd = cmd[m.end():]
63
64 return "".join(out).replace("\0", " ").rstrip("\n")
65
66 def AppendScript(self, other):
67 """Append the contents of another script (which should be created
68 with temporary=True) to this one."""
69 self.script.extend(other.script)
70
71 def AssertSomeFingerprint(self, *fp):
72 """Assert that the current system build fingerprint is one of *fp."""
73 if not fp:
74 raise ValueError("must specify some fingerprints")
Doug Zongker0d92f1f2013-06-03 12:07:12 -070075 cmd = (
76 ' ||\n '.join([('file_getprop("/system/build.prop", '
Doug Zongkerc494d7c2009-06-18 08:43:44 -070077 '"ro.build.fingerprint") == "%s"')
78 % i for i in fp]) +
Doug Zongker0d92f1f2013-06-03 12:07:12 -070079 ' ||\n abort("Package expects build fingerprint of %s; this '
80 'device has " + getprop("ro.build.fingerprint") + ".");'
81 ) % (" or ".join(fp),)
82 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -070083
Doug Zongker0d92f1f2013-06-03 12:07:12 -070084 def AssertOlderBuild(self, timestamp, timestamp_text):
Doug Zongkerc494d7c2009-06-18 08:43:44 -070085 """Assert that the build on the device is older (or the same as)
86 the given timestamp."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -070087 self.script.append(
88 ('(!less_than_int(%s, getprop("ro.build.date.utc"))) || '
89 'abort("Can\'t install this package (%s) over newer '
90 'build (" + getprop("ro.build.date") + ").");'
91 ) % (timestamp, timestamp_text))
Doug Zongkerc494d7c2009-06-18 08:43:44 -070092
93 def AssertDevice(self, device):
94 """Assert that the device identifier is the given string."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -070095 cmd = ('getprop("ro.product.device") == "%s" || '
96 'abort("This package is for \\"%s\\" devices; '
97 'this is a \\"" + getprop("ro.product.device") + "\\".");'
98 ) % (device, device)
99 self.script.append(cmd)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700100
101 def AssertSomeBootloader(self, *bootloaders):
102 """Asert that the bootloader version is one of *bootloaders."""
103 cmd = ("assert(" +
104 " ||\0".join(['getprop("ro.bootloader") == "%s"' % (b,)
105 for b in bootloaders]) +
106 ");")
107 self.script.append(self._WordWrap(cmd))
108
109 def ShowProgress(self, frac, dur):
110 """Update the progress bar, advancing it over 'frac' over the next
Doug Zongker881dd402009-09-20 14:03:55 -0700111 'dur' seconds. 'dur' may be zero to advance it via SetProgress
112 commands instead of by time."""
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700113 self.script.append("show_progress(%f, %d);" % (frac, int(dur)))
114
Doug Zongker881dd402009-09-20 14:03:55 -0700115 def SetProgress(self, frac):
116 """Set the position of the progress bar within the chunk defined
117 by the most recent ShowProgress call. 'frac' should be in
118 [0,1]."""
119 self.script.append("set_progress(%f);" % (frac,))
120
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700121 def PatchCheck(self, filename, *sha1):
122 """Check that the given file (or MTD reference) has one of the
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800123 given *sha1 hashes, checking the version saved in cache if the
124 file does not match."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700125 self.script.append(
126 'apply_patch_check("%s"' % (filename,) +
127 "".join([', "%s"' % (i,) for i in sha1]) +
128 ') || abort("\\"%s\\" has unexpected contents.");' % (filename,))
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800129
130 def FileCheck(self, filename, *sha1):
131 """Check that the given file (or MTD reference) has one of the
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700132 given *sha1 hashes."""
Doug Zongker5a482092010-02-17 16:09:18 -0800133 self.script.append('assert(sha1_check(read_file("%s")' % (filename,) +
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700134 "".join([', "%s"' % (i,) for i in sha1]) +
135 '));')
136
137 def CacheFreeSpaceCheck(self, amount):
138 """Check that there's at least 'amount' space that can be made
139 available on /cache."""
Doug Zongker0d92f1f2013-06-03 12:07:12 -0700140 self.script.append(('apply_patch_space(%d) || abort("Not enough free space '
141 'on /system to apply patches.");') % (amount,))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700142
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700143 def Mount(self, mount_point):
144 """Mount the partition with the given mount_point."""
145 fstab = self.info.get("fstab", None)
146 if fstab:
147 p = fstab[mount_point]
148 self.script.append('mount("%s", "%s", "%s", "%s");' %
Doug Zongker96a57e72010-09-26 14:57:41 -0700149 (p.fs_type, common.PARTITION_TYPES[p.fs_type],
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700150 p.device, p.mount_point))
151 self.mounts.add(p.mount_point)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700152
153 def UnpackPackageDir(self, src, dst):
154 """Unpack a given directory from the OTA package into the given
155 destination directory."""
156 self.script.append('package_extract_dir("%s", "%s");' % (src, dst))
157
158 def Comment(self, comment):
159 """Write a comment into the update script."""
160 self.script.append("")
161 for i in comment.split("\n"):
162 self.script.append("# " + i)
163 self.script.append("")
164
165 def Print(self, message):
166 """Log a message to the screen (if the logs are visible)."""
167 self.script.append('ui_print("%s");' % (message,))
168
169 def FormatPartition(self, partition):
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700170 """Format the given partition, specified by its mount point (eg,
171 "/system")."""
172
Ken Sumralla67616a2011-01-19 17:08:54 -0800173 reserve_size = 0
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700174 fstab = self.info.get("fstab", None)
175 if fstab:
176 p = fstab[partition]
Doug Zongkerdf2056e2012-04-09 12:27:43 -0700177 self.script.append('format("%s", "%s", "%s", "%s", "%s");' %
Doug Zongker086cbb02011-02-17 15:54:20 -0800178 (p.fs_type, common.PARTITION_TYPES[p.fs_type],
Doug Zongkerdf2056e2012-04-09 12:27:43 -0700179 p.device, p.length, p.mount_point))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700180
181 def DeleteFiles(self, file_list):
182 """Delete all files in file_list."""
183 if not file_list: return
184 cmd = "delete(" + ",\0".join(['"%s"' % (i,) for i in file_list]) + ");"
185 self.script.append(self._WordWrap(cmd))
186
187 def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
188 """Apply binary patches (in *patchpairs) to the given srcfile to
189 produce tgtfile (which may be "-" to indicate overwriting the
190 source file."""
191 if len(patchpairs) % 2 != 0 or len(patchpairs) == 0:
192 raise ValueError("bad patches given to ApplyPatch")
193 cmd = ['apply_patch("%s",\0"%s",\0%s,\0%d'
194 % (srcfile, tgtfile, tgtsha1, tgtsize)]
195 for i in range(0, len(patchpairs), 2):
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800196 cmd.append(',\0%s, package_extract_file("%s")' % patchpairs[i:i+2])
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700197 cmd.append(');')
198 cmd = "".join(cmd)
199 self.script.append(self._WordWrap(cmd))
200
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700201 def WriteRawImage(self, mount_point, fn):
202 """Write the given package file into the partition for the given
203 mount point."""
Doug Zongkerb4c7d322010-07-01 15:30:11 -0700204
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700205 fstab = self.info["fstab"]
206 if fstab:
207 p = fstab[mount_point]
Doug Zongker96a57e72010-09-26 14:57:41 -0700208 partition_type = common.PARTITION_TYPES[p.fs_type]
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700209 args = {'device': p.device, 'fn': fn}
210 if partition_type == "MTD":
211 self.script.append(
Doug Zongker02da2102011-04-12 15:50:17 -0700212 'write_raw_image(package_extract_file("%(fn)s"), "%(device)s");'
213 % args)
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700214 elif partition_type == "EMMC":
215 self.script.append(
216 'package_extract_file("%(fn)s", "%(device)s");' % args)
217 else:
218 raise ValueError("don't know how to write \"%s\" partitions" % (p.fs_type,))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700219
Michael Rungefb9bb202013-07-22 20:42:44 +0000220 def SetPermissions(self, fn, uid, gid, mode):
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700221 """Set file ownership and permissions."""
Michael Rungefb9bb202013-07-22 20:42:44 +0000222 self.script.append('set_perm(%d, %d, 0%o, "%s");' % (uid, gid, mode, fn))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700223
Michael Rungefb9bb202013-07-22 20:42:44 +0000224 def SetPermissionsRecursive(self, fn, uid, gid, dmode, fmode):
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700225 """Recursively set path ownership and permissions."""
Michael Rungefb9bb202013-07-22 20:42:44 +0000226 self.script.append('set_perm_recursive(%d, %d, 0%o, 0%o, "%s");'
227 % (uid, gid, dmode, fmode, fn))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700228
229 def MakeSymlinks(self, symlink_list):
230 """Create symlinks, given a list of (dest, link) pairs."""
231 by_dest = {}
232 for d, l in symlink_list:
233 by_dest.setdefault(d, []).append(l)
234
235 for dest, links in sorted(by_dest.iteritems()):
236 cmd = ('symlink("%s", ' % (dest,) +
237 ",\0".join(['"' + i + '"' for i in sorted(links)]) + ");")
238 self.script.append(self._WordWrap(cmd))
239
240 def AppendExtra(self, extra):
241 """Append text verbatim to the output script."""
242 self.script.append(extra)
243
Doug Zongker14833602010-02-02 13:12:04 -0800244 def UnmountAll(self):
245 for p in sorted(self.mounts):
246 self.script.append('unmount("%s");' % (p,))
247 self.mounts = set()
248
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700249 def AddToZip(self, input_zip, output_zip, input_path=None):
250 """Write the accumulated script to the output_zip file. input_zip
251 is used as the source for the 'updater' binary needed to run
252 script. If input_path is not None, it will be used as a local
253 path for the binary instead of input_zip."""
254
Doug Zongker14833602010-02-02 13:12:04 -0800255 self.UnmountAll()
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700256
257 common.ZipWriteStr(output_zip, "META-INF/com/google/android/updater-script",
258 "\n".join(self.script) + "\n")
259
260 if input_path is None:
261 data = input_zip.read("OTA/bin/updater")
262 else:
263 data = open(os.path.join(input_path, "updater")).read()
264 common.ZipWriteStr(output_zip, "META-INF/com/google/android/update-binary",
265 data, perms=0755)