common.py revision 8e931bf999693cac54c99deb1ef668d0e6164ecf
1# Copyright (C) 2008 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 getopt
16import getpass
17import os
18import re
19import shutil
20import subprocess
21import sys
22import tempfile
23
24# missing in Python 2.4 and before
25if not hasattr(os, "SEEK_SET"):
26  os.SEEK_SET = 0
27
28class Options(object): pass
29OPTIONS = Options()
30OPTIONS.signapk_jar = "out/host/linux-x86/framework/signapk.jar"
31OPTIONS.dumpkey_jar = "out/host/linux-x86/framework/dumpkey.jar"
32OPTIONS.max_image_size = {}
33OPTIONS.verbose = False
34OPTIONS.tempfiles = []
35
36
37class ExternalError(RuntimeError): pass
38
39
40def Run(args, **kwargs):
41  """Create and return a subprocess.Popen object, printing the command
42  line on the terminal if -v was specified."""
43  if OPTIONS.verbose:
44    print "  running: ", " ".join(args)
45  return subprocess.Popen(args, **kwargs)
46
47
48def LoadBoardConfig(fn):
49  """Parse a board_config.mk file looking for lines that specify the
50  maximum size of various images, and parse them into the
51  OPTIONS.max_image_size dict."""
52  OPTIONS.max_image_size = {}
53  for line in open(fn):
54    line = line.strip()
55    m = re.match(r"BOARD_(BOOT|RECOVERY|SYSTEM|USERDATA)IMAGE_MAX_SIZE"
56                 r"\s*:=\s*(\d+)", line)
57    if not m: continue
58
59    OPTIONS.max_image_size[m.group(1).lower() + ".img"] = int(m.group(2))
60
61
62def BuildAndAddBootableImage(sourcedir, targetname, output_zip):
63  """Take a kernel, cmdline, and ramdisk directory from the input (in
64  'sourcedir'), and turn them into a boot image.  Put the boot image
65  into the output zip file under the name 'targetname'."""
66
67  print "creating %s..." % (targetname,)
68
69  img = BuildBootableImage(sourcedir)
70
71  CheckSize(img, targetname)
72  output_zip.writestr(targetname, img)
73
74def BuildBootableImage(sourcedir):
75  """Take a kernel, cmdline, and ramdisk directory from the input (in
76  'sourcedir'), and turn them into a boot image.  Return the image data."""
77
78  ramdisk_img = tempfile.NamedTemporaryFile()
79  img = tempfile.NamedTemporaryFile()
80
81  p1 = Run(["mkbootfs", os.path.join(sourcedir, "RAMDISK")],
82           stdout=subprocess.PIPE)
83  p2 = Run(["gzip", "-n"], stdin=p1.stdout, stdout=ramdisk_img.file.fileno())
84
85  p2.wait()
86  p1.wait()
87  assert p1.returncode == 0, "mkbootfs of %s ramdisk failed" % (targetname,)
88  assert p2.returncode == 0, "gzip of %s ramdisk failed" % (targetname,)
89
90  cmdline = open(os.path.join(sourcedir, "cmdline")).read().rstrip("\n")
91  p = Run(["mkbootimg",
92           "--kernel", os.path.join(sourcedir, "kernel"),
93           "--cmdline", cmdline,
94           "--ramdisk", ramdisk_img.name,
95           "--output", img.name],
96          stdout=subprocess.PIPE)
97  p.communicate()
98  assert p.returncode == 0, "mkbootimg of %s image failed" % (targetname,)
99
100  img.seek(os.SEEK_SET, 0)
101  data = img.read()
102
103  ramdisk_img.close()
104  img.close()
105
106  return data
107
108
109def AddRecovery(output_zip):
110  BuildAndAddBootableImage(os.path.join(OPTIONS.input_tmp, "RECOVERY"),
111                           "recovery.img", output_zip)
112
113def AddBoot(output_zip):
114  BuildAndAddBootableImage(os.path.join(OPTIONS.input_tmp, "BOOT"),
115                           "boot.img", output_zip)
116
117def UnzipTemp(filename):
118  """Unzip the given archive into a temporary directory and return the name."""
119
120  tmp = tempfile.mkdtemp(prefix="targetfiles-")
121  OPTIONS.tempfiles.append(tmp)
122  p = Run(["unzip", "-q", filename, "-d", tmp], stdout=subprocess.PIPE)
123  p.communicate()
124  if p.returncode != 0:
125    raise ExternalError("failed to unzip input target-files \"%s\"" %
126                        (filename,))
127  return tmp
128
129
130def GetKeyPasswords(keylist):
131  """Given a list of keys, prompt the user to enter passwords for
132  those which require them.  Return a {key: password} dict.  password
133  will be None if the key has no password."""
134
135  key_passwords = {}
136  devnull = open("/dev/null", "w+b")
137  for k in sorted(keylist):
138    p = subprocess.Popen(["openssl", "pkcs8", "-in", k+".pk8",
139                          "-inform", "DER", "-nocrypt"],
140                         stdin=devnull.fileno(),
141                         stdout=devnull.fileno(),
142                         stderr=subprocess.STDOUT)
143    p.communicate()
144    if p.returncode == 0:
145      print "%s.pk8 does not require a password" % (k,)
146      key_passwords[k] = None
147    else:
148      key_passwords[k] = getpass.getpass("Enter password for %s.pk8> " % (k,))
149  devnull.close()
150  print
151  return key_passwords
152
153
154def SignFile(input_name, output_name, key, password, align=None):
155  """Sign the input_name zip/jar/apk, producing output_name.  Use the
156  given key and password (the latter may be None if the key does not
157  have a password.
158
159  If align is an integer > 1, zipalign is run to align stored files in
160  the output zip on 'align'-byte boundaries.
161  """
162  if align == 0 or align == 1:
163    align = None
164
165  if align:
166    temp = tempfile.NamedTemporaryFile()
167    sign_name = temp.name
168  else:
169    sign_name = output_name
170
171  p = subprocess.Popen(["java", "-jar", OPTIONS.signapk_jar,
172                        key + ".x509.pem",
173                        key + ".pk8",
174                        input_name, sign_name],
175                       stdin=subprocess.PIPE,
176                       stdout=subprocess.PIPE)
177  if password is not None:
178    password += "\n"
179  p.communicate(password)
180  if p.returncode != 0:
181    raise ExternalError("signapk.jar failed: return code %s" % (p.returncode,))
182
183  if align:
184    p = subprocess.Popen(["zipalign", "-f", str(align), sign_name, output_name])
185    p.communicate()
186    if p.returncode != 0:
187      raise ExternalError("zipalign failed: return code %s" % (p.returncode,))
188    temp.close()
189
190
191def CheckSize(data, target):
192  """Check the data string passed against the max size limit, if
193  any, for the given target.  Raise exception if the data is too big.
194  Print a warning if the data is nearing the maximum size."""
195  limit = OPTIONS.max_image_size.get(target, None)
196  if limit is None: return
197
198  size = len(data)
199  pct = float(size) * 100.0 / limit
200  msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit)
201  if pct >= 99.0:
202    raise ExternalError(msg)
203  elif pct >= 95.0:
204    print
205    print "  WARNING: ", msg
206    print
207  elif OPTIONS.verbose:
208    print "  ", msg
209
210
211COMMON_DOCSTRING = """
212  -p  (--path)  <dir>
213      Prepend <dir> to the list of places to search for binaries run
214      by this script.
215
216  -v  (--verbose)
217      Show command lines being executed.
218
219  -h  (--help)
220      Display this usage message and exit.
221"""
222
223def Usage(docstring):
224  print docstring.rstrip("\n")
225  print COMMON_DOCSTRING
226
227
228def ParseOptions(argv,
229                 docstring,
230                 extra_opts="", extra_long_opts=(),
231                 extra_option_handler=None):
232  """Parse the options in argv and return any arguments that aren't
233  flags.  docstring is the calling module's docstring, to be displayed
234  for errors and -h.  extra_opts and extra_long_opts are for flags
235  defined by the caller, which are processed by passing them to
236  extra_option_handler."""
237
238  try:
239    opts, args = getopt.getopt(
240        argv, "hvp:" + extra_opts,
241        ["help", "verbose", "path="] + list(extra_long_opts))
242  except getopt.GetoptError, err:
243    Usage(docstring)
244    print "**", str(err), "**"
245    sys.exit(2)
246
247  path_specified = False
248
249  for o, a in opts:
250    if o in ("-h", "--help"):
251      Usage(docstring)
252      sys.exit()
253    elif o in ("-v", "--verbose"):
254      OPTIONS.verbose = True
255    elif o in ("-p", "--path"):
256      os.environ["PATH"] = a + os.pathsep + os.environ["PATH"]
257      path_specified = True
258    else:
259      if extra_option_handler is None or not extra_option_handler(o, a):
260        assert False, "unknown option \"%s\"" % (o,)
261
262  if not path_specified:
263    os.environ["PATH"] = ("out/host/linux-x86/bin" + os.pathsep +
264                          os.environ["PATH"])
265
266  return args
267
268
269def Cleanup():
270  for i in OPTIONS.tempfiles:
271    if os.path.isdir(i):
272      shutil.rmtree(i)
273    else:
274      os.remove(i)
275