blob: f8f4344243b85a5e5d4989626f625c5bd74c30ef [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
16
17import common
18
19class AmendGenerator(object):
20 """Class to generate scripts in the 'amend' recovery script language
21 used up through cupcake."""
22
23 def __init__(self):
24 self.script = ['assert compatible_with("0.2") == "true"']
25 self.included_files = set()
26
27 def MakeTemporary(self):
28 """Make a temporary script object whose commands can latter be
29 appended to the parent script with AppendScript(). Used when the
30 caller wants to generate script commands out-of-order."""
31 x = AmendGenerator()
32 x.script = []
33 x.included_files = self.included_files
34 return x
35
36 @staticmethod
37 def _FileRoot(fn):
38 """Convert a file path to the 'root' notation used by amend."""
39 if fn.startswith("/system/"):
40 return "SYSTEM:" + fn[8:]
41 elif fn == "/system":
42 return "SYSTEM:"
43 elif fn.startswith("/tmp/"):
44 return "CACHE:.." + fn
45 else:
46 raise ValueError("don't know root for \"%s\"" % (fn,))
47
48 @staticmethod
49 def _PartitionRoot(partition):
50 """Convert a partition name to the 'root' notation used by amend."""
51 if partition == "userdata":
52 return "DATA:"
53 else:
54 return partition.upper() + ":"
55
56 def AppendScript(self, other):
57 """Append the contents of another script (which should be created
58 with temporary=True) to this one."""
59 self.script.extend(other.script)
60 self.included_files.update(other.included_files)
61
62 def AssertSomeFingerprint(self, *fp):
63 """Assert that the current fingerprint is one of *fp."""
64 x = [('file_contains("SYSTEM:build.prop", '
65 '"ro.build.fingerprint=%s") == "true"') % i for i in fp]
66 self.script.append("assert %s" % (" || ".join(x),))
67
68 def AssertOlderBuild(self, timestamp):
69 """Assert that the build on the device is older (or the same as)
70 the given timestamp."""
71 self.script.append("run_program PACKAGE:check_prereq %s" % (timestamp,))
72 self.included_files.add("check_prereq")
73
74 def AssertDevice(self, device):
75 """Assert that the device identifier is the given string."""
76 self.script.append('assert getprop("ro.product.device") == "%s" || '
77 'getprop("ro.build.product") == "%s"' % (device, device))
78
79 def AssertSomeBootloader(self, *bootloaders):
80 """Asert that the bootloader version is one of *bootloaders."""
81 self.script.append("assert " +
82 " || ".join(['getprop("ro.bootloader") == "%s"' % (b,)
83 for b in bootloaders]))
84
85 def ShowProgress(self, frac, dur):
86 """Update the progress bar, advancing it over 'frac' over the next
87 'dur' seconds."""
88 self.script.append("show_progress %f %d" % (frac, int(dur)))
89
Doug Zongker881dd402009-09-20 14:03:55 -070090 def SetProgress(self, frac):
91 """Not implemented in amend."""
92 pass
93
Doug Zongkerc494d7c2009-06-18 08:43:44 -070094 def PatchCheck(self, filename, *sha1):
95 """Check that the given file (or MTD reference) has one of the
96 given *sha1 hashes."""
97 out = ["run_program PACKAGE:applypatch -c %s" % (filename,)]
98 for i in sha1:
99 out.append(" " + i)
100 self.script.append("".join(out))
Doug Zongker6c770462009-07-22 18:27:31 -0700101 self.included_files.add(("applypatch_static", "applypatch"))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700102
103 def CacheFreeSpaceCheck(self, amount):
104 """Check that there's at least 'amount' space that can be made
105 available on /cache."""
106 self.script.append("run_program PACKAGE:applypatch -s %d" % (amount,))
Doug Zongker6c770462009-07-22 18:27:31 -0700107 self.included_files.add(("applypatch_static", "applypatch"))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700108
109 def Mount(self, kind, what, path):
110 # no-op; amend uses it's 'roots' system to automatically mount
111 # things when they're referred to
112 pass
113
114 def UnpackPackageDir(self, src, dst):
115 """Unpack a given directory from the OTA package into the given
116 destination directory."""
117 dst = self._FileRoot(dst)
118 self.script.append("copy_dir PACKAGE:%s %s" % (src, dst))
119
120 def Comment(self, comment):
121 """Write a comment into the update script."""
122 self.script.append("")
123 for i in comment.split("\n"):
124 self.script.append("# " + i)
125 self.script.append("")
126
127 def Print(self, message):
128 """Log a message to the screen (if the logs are visible)."""
129 # no way to do this from amend; substitute a script comment instead
130 self.Comment(message)
131
132 def FormatPartition(self, partition):
133 """Format the given MTD partition."""
134 self.script.append("format %s" % (self._PartitionRoot(partition),))
135
136 def DeleteFiles(self, file_list):
137 """Delete all files in file_list."""
138 line = []
139 t = 0
140 for i in file_list:
141 i = self._FileRoot(i)
142 line.append(i)
143 t += len(i) + 1
144 if t > 80:
145 self.script.append("delete " + " ".join(line))
146 line = []
147 t = 0
148 if line:
149 self.script.append("delete " + " ".join(line))
150
151 def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
152 """Apply binary patches (in *patchpairs) to the given srcfile to
153 produce tgtfile (which may be "-" to indicate overwriting the
154 source file."""
155 if len(patchpairs) % 2 != 0:
156 raise ValueError("bad patches given to ApplyPatch")
157 self.script.append(
158 ("run_program PACKAGE:applypatch %s %s %s %d " %
159 (srcfile, tgtfile, tgtsha1, tgtsize)) +
160 " ".join(["%s:%s" % patchpairs[i:i+2]
161 for i in range(0, len(patchpairs), 2)]))
Doug Zongker6c770462009-07-22 18:27:31 -0700162 self.included_files.add(("applypatch_static", "applypatch"))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700163
164 def WriteFirmwareImage(self, kind, fn):
165 """Arrange to update the given firmware image (kind must be
166 "hboot" or "radio") when recovery finishes."""
167 self.script.append("write_%s_image PACKAGE:%s" % (kind, fn))
168
169 def WriteRawImage(self, partition, fn):
170 """Write the given file into the given MTD partition."""
171 self.script.append("write_raw_image PACKAGE:%s %s" %
172 (fn, self._PartitionRoot(partition)))
173
174 def SetPermissions(self, fn, uid, gid, mode):
175 """Set file ownership and permissions."""
176 fn = self._FileRoot(fn)
177 self.script.append("set_perm %d %d 0%o %s" % (uid, gid, mode, fn))
178
179 def SetPermissionsRecursive(self, fn, uid, gid, dmode, fmode):
180 """Recursively set path ownership and permissions."""
181 fn = self._FileRoot(fn)
182 self.script.append("set_perm_recursive %d %d 0%o 0%o %s" %
183 (uid, gid, dmode, fmode, fn))
184
185 def MakeSymlinks(self, symlink_list):
186 """Create symlinks, given a list of (dest, link) pairs."""
Doug Zongker828bbfb2009-08-03 14:11:09 -0700187 self.DeleteFiles([i[1] for i in symlink_list])
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700188 self.script.extend(["symlink %s %s" % (i[0], self._FileRoot(i[1]))
189 for i in sorted(symlink_list)])
190
191 def AppendExtra(self, extra):
192 """Append text verbatim to the output script."""
193 self.script.append(extra)
194
195 def AddToZip(self, input_zip, output_zip, input_path=None):
196 """Write the accumulated script to the output_zip file. input_zip
197 is used as the source for any ancillary binaries needed by the
198 script. If input_path is not None, it will be used as a local
199 path for binaries instead of input_zip."""
200 common.ZipWriteStr(output_zip, "META-INF/com/google/android/update-script",
201 "\n".join(self.script) + "\n")
202 for i in self.included_files:
Doug Zongker6c770462009-07-22 18:27:31 -0700203 if isinstance(i, tuple):
204 sourcefn, targetfn = i
205 else:
206 sourcefn = i
207 targetfn = i
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700208 try:
209 if input_path is None:
Doug Zongker6c770462009-07-22 18:27:31 -0700210 data = input_zip.read(os.path.join("OTA/bin", sourcefn))
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700211 else:
Doug Zongker6c770462009-07-22 18:27:31 -0700212 data = open(os.path.join(input_path, sourcefn)).read()
213 common.ZipWriteStr(output_zip, targetfn, data, perms=0755)
Doug Zongkerc494d7c2009-06-18 08:43:44 -0700214 except (IOError, KeyError), e:
215 raise ExternalError("unable to include binary %s: %s" % (i, e))