summaryrefslogtreecommitdiffstats
path: root/tools/releasetools/img_from_target_files
blob: c5b98868b5041d11a3f276b00e1925c1af125b61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python
#
# Copyright (C) 2008 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Given a target-files zipfile, produces an image zipfile suitable for
use with 'fastboot update'.

Usage:  img_from_target_files [flags] input_target_files output_image_zip

  -b  (--board_config)  <file>
      Deprecated.

  -z  (--bootable_zip)
      Include only the bootable images (eg 'boot' and 'recovery') in
      the output.

"""

import sys

if sys.hexversion < 0x02040000:
  print >> sys.stderr, "Python 2.4 or newer is required."
  sys.exit(1)

import errno
import os
import re
import shutil
import subprocess
import tempfile
import zipfile

# missing in Python 2.4 and before
if not hasattr(os, "SEEK_SET"):
  os.SEEK_SET = 0

import common

OPTIONS = common.OPTIONS

def AddUserdata(output_zip):
  """Create an empty userdata image and store it in output_zip."""

  print "creating userdata.img..."

  # The name of the directory it is making an image out of matters to
  # mkyaffs2image.  So we create a temp dir, and within it we create an
  # empty dir named "data", and build the image from that.
  temp_dir = tempfile.mkdtemp()
  user_dir = os.path.join(temp_dir, "data")
  os.mkdir(user_dir)
  img = tempfile.NamedTemporaryFile()

  build_command = []
  fstab = OPTIONS.info_dict["fstab"]
  if fstab and fstab["/data"].fs_type.startswith("ext"):
    build_command = ["mkuserimg.sh"]
    if "extfs_sparse_flag" in OPTIONS.info_dict:
      build_command.append(OPTIONS.info_dict["extfs_sparse_flag"])
    build_command.extend([user_dir, img.name,
                     fstab["/data"].fs_type, "data"])
    if "userdata_size" in OPTIONS.info_dict:
      build_command.append(str(OPTIONS.info_dict["userdata_size"]))
  else:
    build_command = ["mkyaffs2image", "-f"]
    extra = OPTIONS.info_dict.get("mkyaffs2_extra_flags", None)
    if extra:
      build_command.extend(extra.split())
    build_command.append(user_dir)
    build_command.append(img.name)

  p = common.Run(build_command);
  p.communicate()
  assert p.returncode == 0, "build userdata.img image failed"

  common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
  output_zip.write(img.name, "userdata.img")
  img.close()
  os.rmdir(user_dir)
  os.rmdir(temp_dir)


def AddSystem(output_zip):
  """Turn the contents of SYSTEM into a system image and store it in
  output_zip."""

  print "creating system.img..."

  img = tempfile.NamedTemporaryFile()

  # The name of the directory it is making an image out of matters to
  # mkyaffs2image.  It wants "system" but we have a directory named
  # "SYSTEM", so create a symlink.
  try:
    os.symlink(os.path.join(OPTIONS.input_tmp, "SYSTEM"),
               os.path.join(OPTIONS.input_tmp, "system"))
  except OSError, e:
      # bogus error on my mac version?
      #   File "./build/tools/releasetools/img_from_target_files", line 86, in AddSystem
      #     os.path.join(OPTIONS.input_tmp, "system"))
      # OSError: [Errno 17] File exists
    if (e.errno == errno.EEXIST):
      pass

  build_command = []
  fstab = OPTIONS.info_dict["fstab"]
  if fstab and fstab["/system"].fs_type.startswith("ext"):

    build_command = ["mkuserimg.sh"]
    if "extfs_sparse_flag" in OPTIONS.info_dict:
      build_command.append(OPTIONS.info_dict["extfs_sparse_flag"])
    build_command.extend([os.path.join(OPTIONS.input_tmp, "system"), img.name,
                     fstab["/system"].fs_type, "system"])
    if "system_size" in OPTIONS.info_dict:
      build_command.append(str(OPTIONS.info_dict["system_size"]))
  else:
    build_command = ["mkyaffs2image", "-f"]
    extra = OPTIONS.info_dict.get("mkyaffs2_extra_flags", None)
    if extra:
      build_command.extend(extra.split())
    build_command.append(os.path.join(OPTIONS.input_tmp, "system"))
    build_command.append(img.name)

  p = common.Run(build_command)
  p.communicate()
  assert p.returncode == 0, "build system.img image failed"

  img.seek(os.SEEK_SET, 0)
  data = img.read()
  img.close()

  common.CheckSize(data, "system.img", OPTIONS.info_dict)
  common.ZipWriteStr(output_zip, "system.img", data)


def CopyInfo(output_zip):
  """Copy the android-info.txt file from the input to the output."""
  output_zip.write(os.path.join(OPTIONS.input_tmp, "OTA", "android-info.txt"),
                   "android-info.txt")


def main(argv):
  bootable_only = [False]

  def option_handler(o, a):
    if o in ("-b", "--board_config"):
      pass       # deprecated
    if o in ("-z", "--bootable_zip"):
      bootable_only[0] = True
    else:
      return False
    return True

  args = common.ParseOptions(argv, __doc__,
                             extra_opts="b:z",
                             extra_long_opts=["board_config=",
                                              "bootable_zip"],
                             extra_option_handler=option_handler)

  bootable_only = bootable_only[0]

  if len(args) != 2:
    common.Usage(__doc__)
    sys.exit(1)

  OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])
  OPTIONS.info_dict = common.LoadInfoDict(input_zip)

  output_zip = zipfile.ZipFile(args[1], "w", compression=zipfile.ZIP_DEFLATED)

  common.GetBootableImage(
      "boot.img", "boot.img", OPTIONS.input_tmp, "BOOT").AddToZip(output_zip)
  common.GetBootableImage(
      "recovery.img", "recovery.img", OPTIONS.input_tmp,
      "RECOVERY").AddToZip(output_zip)

  if not bootable_only:
    AddSystem(output_zip)
    AddUserdata(output_zip)
    CopyInfo(output_zip)

  print "cleaning up..."
  output_zip.close()
  shutil.rmtree(OPTIONS.input_tmp)

  print "done."


if __name__ == '__main__':
  try:
    common.CloseInheritedPipes()
    main(sys.argv[1:])
  except common.ExternalError, e:
    print
    print "   ERROR: %s" % (e,)
    print
    sys.exit(1)