blob: a61ecf506d0a065906408af6f41eb41fb4fd97e3 [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 Zongker9ce0fb62010-09-20 18:04:41 -070024 # map recovery.fstab's fs_types to mount/format "partition types"
25 PARTITION_TYPES = { "yaffs2": "MTD", "mtd": "MTD",
26 "ext4": "EMMC", "emmc": "EMMC" }
27
Doug Zongkerb4c7d322010-07-01 15:30:11 -070028 def __init__(self, version, info):
Doug Zongkerc494d7c2009-06-18 08:43:44 -070029 self.script = []
30 self.mounts = set()
31 self.version = version
Doug Zongkerb4c7d322010-07-01 15:30:11 -070032 self.info = info
Doug Zongkerc494d7c2009-06-18 08:43:44 -070033
34 def MakeTemporary(self):
35 """Make a temporary script object whose commands can latter be
36 appended to the parent script with AppendScript(). Used when the
37 caller wants to generate script commands out-of-order."""
Doug Zongker67369982010-07-07 13:53:32 -070038 x = EdifyGenerator(self.version, self.info)
Doug Zongkerc494d7c2009-06-18 08:43:44 -070039 x.mounts = self.mounts
40 return x
41
42 @staticmethod
43 def _WordWrap(cmd, linelen=80):
44 """'cmd' should be a function call with null characters after each
45 parameter (eg, "somefun(foo,\0bar,\0baz)"). This function wraps cmd
46 to a given line length, replacing nulls with spaces and/or newlines
47 to format it nicely."""
48 indent = cmd.index("(")+1
49 out = []
50 first = True
51 x = re.compile("^(.{,%d})\0" % (linelen-indent,))
52 while True:
53 if not first:
54 out.append(" " * indent)
55 first = False
56 m = x.search(cmd)
57 if not m:
58 parts = cmd.split("\0", 1)
59 out.append(parts[0]+"\n")
60 if len(parts) == 1:
61 break
62 else:
63 cmd = parts[1]
64 continue
65 out.append(m.group(1)+"\n")
66 cmd = cmd[m.end():]
67
68 return "".join(out).replace("\0", " ").rstrip("\n")
69
70 def AppendScript(self, other):
71 """Append the contents of another script (which should be created
72 with temporary=True) to this one."""
73 self.script.extend(other.script)
74
75 def AssertSomeFingerprint(self, *fp):
76 """Assert that the current system build fingerprint is one of *fp."""
77 if not fp:
78 raise ValueError("must specify some fingerprints")
79 cmd = ('assert(' +
80 ' ||\0'.join([('file_getprop("/system/build.prop", '
81 '"ro.build.fingerprint") == "%s"')
82 % i for i in fp]) +
83 ');')
84 self.script.append(self._WordWrap(cmd))
85
86 def AssertOlderBuild(self, timestamp):
87 """Assert that the build on the device is older (or the same as)
88 the given timestamp."""
89 self.script.append(('assert(!less_than_int(%s, '
90 'getprop("ro.build.date.utc")));') % (timestamp,))
91
92 def AssertDevice(self, device):
93 """Assert that the device identifier is the given string."""
94 cmd = ('assert(getprop("ro.product.device") == "%s" ||\0'
95 'getprop("ro.build.product") == "%s");' % (device, device))
96 self.script.append(self._WordWrap(cmd))
97
98 def AssertSomeBootloader(self, *bootloaders):
99 """Asert that the bootloader version is one of *bootloaders."""
100 cmd = ("assert(" +
101 " ||\0".join(['getprop("ro.bootloader") == "%s"' % (b,)
102 for b in bootloaders]) +
103 ");")
104 self.script.append(self._WordWrap(cmd))
105
106 def ShowProgress(self, frac, dur):
107 """Update the progress bar, advancing it over 'frac' over the next
Doug Zongker881dd402009-09-20 14:03:55 -0700108 'dur' seconds. 'dur' may be zero to advance it via SetProgress
109 commands instead of by time."""
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700110 self.script.append("show_progress(%f, %d);" % (frac, int(dur)))
111
Doug Zongker881dd402009-09-20 14:03:55 -0700112 def SetProgress(self, frac):
113 """Set the position of the progress bar within the chunk defined
114 by the most recent ShowProgress call. 'frac' should be in
115 [0,1]."""
116 self.script.append("set_progress(%f);" % (frac,))
117
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700118 def PatchCheck(self, filename, *sha1):
119 """Check that the given file (or MTD reference) has one of the
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800120 given *sha1 hashes, checking the version saved in cache if the
121 file does not match."""
122 self.script.append('assert(apply_patch_check("%s"' % (filename,) +
123 "".join([', "%s"' % (i,) for i in sha1]) +
124 '));')
125
126 def FileCheck(self, filename, *sha1):
127 """Check that the given file (or MTD reference) has one of the
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700128 given *sha1 hashes."""
Doug Zongker5a482092010-02-17 16:09:18 -0800129 self.script.append('assert(sha1_check(read_file("%s")' % (filename,) +
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700130 "".join([', "%s"' % (i,) for i in sha1]) +
131 '));')
132
133 def CacheFreeSpaceCheck(self, amount):
134 """Check that there's at least 'amount' space that can be made
135 available on /cache."""
136 self.script.append("assert(apply_patch_space(%d));" % (amount,))
137
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700138 def Mount(self, mount_point):
139 """Mount the partition with the given mount_point."""
140 fstab = self.info.get("fstab", None)
141 if fstab:
142 p = fstab[mount_point]
143 self.script.append('mount("%s", "%s", "%s", "%s");' %
144 (p.fs_type, self.PARTITION_TYPES[p.fs_type],
145 p.device, p.mount_point))
146 self.mounts.add(p.mount_point)
147 else:
148 what = mount_point.lstrip("/")
149 what = self.info.get("partition_path", "") + what
150 self.script.append('mount("%s", "%s", "%s", "%s");' %
151 (self.info["fs_type"], self.info["partition_type"],
152 what, mount_point))
153 self.mounts.add(mount_point)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700154
155 def UnpackPackageDir(self, src, dst):
156 """Unpack a given directory from the OTA package into the given
157 destination directory."""
158 self.script.append('package_extract_dir("%s", "%s");' % (src, dst))
159
160 def Comment(self, comment):
161 """Write a comment into the update script."""
162 self.script.append("")
163 for i in comment.split("\n"):
164 self.script.append("# " + i)
165 self.script.append("")
166
167 def Print(self, message):
168 """Log a message to the screen (if the logs are visible)."""
169 self.script.append('ui_print("%s");' % (message,))
170
171 def FormatPartition(self, partition):
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700172 """Format the given partition, specified by its mount point (eg,
173 "/system")."""
174
175 fstab = self.info.get("fstab", None)
176 if fstab:
177 p = fstab[partition]
178 self.script.append('format("%s", "%s", "%s");' %
179 (p.fs_type, self.PARTITION_TYPES[p.fs_type], p.device))
180 else:
181 # older target-files without per-partition types
182 partition = self.info.get("partition_path", "") + partition
183 self.script.append('format("%s", "%s", "%s");' %
184 (self.info["fs_type"], self.info["partition_type"],
185 partition))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700186
187 def DeleteFiles(self, file_list):
188 """Delete all files in file_list."""
189 if not file_list: return
190 cmd = "delete(" + ",\0".join(['"%s"' % (i,) for i in file_list]) + ");"
191 self.script.append(self._WordWrap(cmd))
192
193 def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
194 """Apply binary patches (in *patchpairs) to the given srcfile to
195 produce tgtfile (which may be "-" to indicate overwriting the
196 source file."""
197 if len(patchpairs) % 2 != 0 or len(patchpairs) == 0:
198 raise ValueError("bad patches given to ApplyPatch")
199 cmd = ['apply_patch("%s",\0"%s",\0%s,\0%d'
200 % (srcfile, tgtfile, tgtsha1, tgtsize)]
201 for i in range(0, len(patchpairs), 2):
Doug Zongkerc8d446b2010-02-22 15:41:53 -0800202 cmd.append(',\0%s, package_extract_file("%s")' % patchpairs[i:i+2])
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700203 cmd.append(');')
204 cmd = "".join(cmd)
205 self.script.append(self._WordWrap(cmd))
206
207 def WriteFirmwareImage(self, kind, fn):
208 """Arrange to update the given firmware image (kind must be
209 "hboot" or "radio") when recovery finishes."""
210 if self.version == 1:
211 self.script.append(
212 ('assert(package_extract_file("%(fn)s", "/tmp/%(kind)s.img"),\n'
213 ' write_firmware_image("/tmp/%(kind)s.img", "%(kind)s"));')
214 % {'kind': kind, 'fn': fn})
215 else:
216 self.script.append(
217 'write_firmware_image("PACKAGE:%s", "%s");' % (fn, kind))
218
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700219 def WriteRawImage(self, mount_point, fn):
220 """Write the given package file into the partition for the given
221 mount point."""
Doug Zongkerb4c7d322010-07-01 15:30:11 -0700222
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700223 fstab = self.info["fstab"]
224 if fstab:
225 p = fstab[mount_point]
226 partition_type = self.PARTITION_TYPES[p.fs_type]
227 args = {'device': p.device, 'fn': fn}
228 if partition_type == "MTD":
229 self.script.append(
230 ('assert(package_extract_file("%(fn)s", "/tmp/%(device)s.img"),\n'
231 ' write_raw_image("/tmp/%(device)s.img", "%(device)s"),\n'
232 ' delete("/tmp/%(device)s.img"));') % args)
233 elif partition_type == "EMMC":
234 self.script.append(
235 'package_extract_file("%(fn)s", "%(device)s");' % args)
236 else:
237 raise ValueError("don't know how to write \"%s\" partitions" % (p.fs_type,))
Doug Zongkerb4c7d322010-07-01 15:30:11 -0700238 else:
Doug Zongker9ce0fb62010-09-20 18:04:41 -0700239 # backward compatibility with older target-files that lack recovery.fstab
240 if self.info["partition_type"] == "MTD":
241 self.script.append(
242 ('assert(package_extract_file("%(fn)s", "/tmp/%(partition)s.img"),\n'
243 ' write_raw_image("/tmp/%(partition)s.img", "%(partition)s"),\n'
244 ' delete("/tmp/%(partition)s.img"));')
245 % {'partition': partition, 'fn': fn})
246 elif self.info["partition_type"] == "EMMC":
247 self.script.append(
248 ('package_extract_file("%(fn)s", "%(dir)s%(partition)s");')
249 % {'partition': partition, 'fn': fn,
250 'dir': self.info.get("partition_path", ""),
251 })
252 else:
253 raise ValueError("don't know how to write \"%s\" partitions" %
254 (self.info["partition_type"],))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700255
256 def SetPermissions(self, fn, uid, gid, mode):
257 """Set file ownership and permissions."""
258 self.script.append('set_perm(%d, %d, 0%o, "%s");' % (uid, gid, mode, fn))
259
260 def SetPermissionsRecursive(self, fn, uid, gid, dmode, fmode):
261 """Recursively set path ownership and permissions."""
262 self.script.append('set_perm_recursive(%d, %d, 0%o, 0%o, "%s");'
263 % (uid, gid, dmode, fmode, fn))
264
265 def MakeSymlinks(self, symlink_list):
266 """Create symlinks, given a list of (dest, link) pairs."""
267 by_dest = {}
268 for d, l in symlink_list:
269 by_dest.setdefault(d, []).append(l)
270
271 for dest, links in sorted(by_dest.iteritems()):
272 cmd = ('symlink("%s", ' % (dest,) +
273 ",\0".join(['"' + i + '"' for i in sorted(links)]) + ");")
274 self.script.append(self._WordWrap(cmd))
275
Hristo Bojinov96be7202010-08-02 10:26:17 -0700276 def RetouchBinaries(self, file_list):
277 """Execute the retouch instructions in files listed."""
278 cmd = ('retouch_binaries(' +
279 ', '.join(['"' + i[0] + '", "' + i[1] + '"' for i in file_list]) +
280 ');')
281 self.script.append(self._WordWrap(cmd))
282
283 def UndoRetouchBinaries(self, file_list):
284 """Undo the retouching (retouch to zero offset)."""
285 cmd = ('undo_retouch_binaries(' +
286 ', '.join(['"' + i[0] + '", "' + i[1] + '"' for i in file_list]) +
287 ');')
288 self.script.append(self._WordWrap(cmd))
289
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700290 def AppendExtra(self, extra):
291 """Append text verbatim to the output script."""
292 self.script.append(extra)
293
Doug Zongker14833602010-02-02 13:12:04 -0800294 def UnmountAll(self):
295 for p in sorted(self.mounts):
296 self.script.append('unmount("%s");' % (p,))
297 self.mounts = set()
298
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700299 def AddToZip(self, input_zip, output_zip, input_path=None):
300 """Write the accumulated script to the output_zip file. input_zip
301 is used as the source for the 'updater' binary needed to run
302 script. If input_path is not None, it will be used as a local
303 path for the binary instead of input_zip."""
304
Doug Zongker14833602010-02-02 13:12:04 -0800305 self.UnmountAll()
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700306
307 common.ZipWriteStr(output_zip, "META-INF/com/google/android/updater-script",
308 "\n".join(self.script) + "\n")
309
310 if input_path is None:
311 data = input_zip.read("OTA/bin/updater")
312 else:
313 data = open(os.path.join(input_path, "updater")).read()
314 common.ZipWriteStr(output_zip, "META-INF/com/google/android/update-binary",
315 data, perms=0755)