blob: 56bf4877971b0dc5253a0da062a89540b2d505fe [file] [log] [blame]
Adam Lesinski8780eb62017-10-31 17:44:39 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <vector>
18
19#include "android-base/macros.h"
20#include "androidfw/StringPiece.h"
21
22#include "Flags.h"
23#include "LoadedApk.h"
24#include "ValueVisitor.h"
25#include "cmd/Util.h"
26#include "format/binary/TableFlattener.h"
27#include "format/binary/XmlFlattener.h"
28#include "format/proto/ProtoDeserialize.h"
Pierre Lecesned8b4bea2017-11-10 23:50:17 +000029#include "format/proto/ProtoSerialize.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070030#include "io/BigBufferStream.h"
31#include "io/Util.h"
32#include "process/IResourceTableConsumer.h"
33#include "process/SymbolTable.h"
Pierre Lecesned8b4bea2017-11-10 23:50:17 +000034#include "util/Util.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070035
36using ::android::StringPiece;
Pierre Lecesned8b4bea2017-11-10 23:50:17 +000037using ::android::base::StringPrintf;
Adam Lesinski8780eb62017-10-31 17:44:39 -070038using ::std::unique_ptr;
39using ::std::vector;
40
41namespace aapt {
42
Pierre Lecesned8b4bea2017-11-10 23:50:17 +000043class IApkSerializer {
Pierre Lecesne7e8549d2017-11-10 01:22:12 +000044 public:
Pierre Lecesned8b4bea2017-11-10 23:50:17 +000045 IApkSerializer(IAaptContext* context, const Source& source) : context_(context), source_(source) {}
Pierre Lecesne7e8549d2017-11-10 01:22:12 +000046
47 virtual bool SerializeXml(const xml::XmlResource* xml, const std::string& path, bool utf16,
48 IArchiveWriter* writer) = 0;
49 virtual bool SerializeTable(ResourceTable* table, IArchiveWriter* writer) = 0;
David Chaloupkab66db4e2018-01-15 12:35:41 +000050 virtual bool SerializeFile(FileReference* file, IArchiveWriter* writer) = 0;
Pierre Lecesne7e8549d2017-11-10 01:22:12 +000051
Pierre Lecesned8b4bea2017-11-10 23:50:17 +000052 virtual ~IApkSerializer() = default;
Pierre Lecesne7e8549d2017-11-10 01:22:12 +000053
54 protected:
55 IAaptContext* context_;
56 Source source_;
57};
Adam Lesinski8780eb62017-10-31 17:44:39 -070058
Pierre Lecesned8b4bea2017-11-10 23:50:17 +000059bool ConvertApk(IAaptContext* context, unique_ptr<LoadedApk> apk, IApkSerializer* serializer,
60 IArchiveWriter* writer) {
Pierre Lecesne7e8549d2017-11-10 01:22:12 +000061 if (!serializer->SerializeXml(apk->GetManifest(), kAndroidManifestPath, true /*utf16*/, writer)) {
62 context->GetDiagnostics()->Error(DiagMessage(apk->GetSource())
63 << "failed to serialize AndroidManifest.xml");
Adam Lesinski8780eb62017-10-31 17:44:39 -070064 return false;
65 }
66
Tom Dobek725fb122017-12-08 14:19:01 +000067 if (apk->GetResourceTable() != nullptr) {
David Chaloupkab66db4e2018-01-15 12:35:41 +000068 // The table might be modified by below code.
69 auto converted_table = apk->GetResourceTable();
Tom Dobek725fb122017-12-08 14:19:01 +000070
71 // Resources
David Chaloupkab66db4e2018-01-15 12:35:41 +000072 for (const auto& package : converted_table->packages) {
Tom Dobek725fb122017-12-08 14:19:01 +000073 for (const auto& type : package->types) {
74 for (const auto& entry : type->entries) {
75 for (const auto& config_value : entry->values) {
David Chaloupkab66db4e2018-01-15 12:35:41 +000076 FileReference* file = ValueCast<FileReference>(config_value->value.get());
Tom Dobek725fb122017-12-08 14:19:01 +000077 if (file != nullptr) {
78 if (file->file == nullptr) {
79 context->GetDiagnostics()->Error(DiagMessage(apk->GetSource())
80 << "no file associated with " << *file);
81 return false;
82 }
83
84 if (!serializer->SerializeFile(file, writer)) {
85 context->GetDiagnostics()->Error(DiagMessage(apk->GetSource())
86 << "failed to serialize file " << *file->path);
87 return false;
88 }
89 } // file
90 } // config_value
91 } // entry
92 } // type
93 } // package
David Chaloupkab66db4e2018-01-15 12:35:41 +000094
95 // Converted resource table
96 if (!serializer->SerializeTable(converted_table, writer)) {
97 context->GetDiagnostics()->Error(DiagMessage(apk->GetSource())
98 << "failed to serialize the resource table");
99 return false;
100 }
Adam Lesinski8780eb62017-10-31 17:44:39 -0700101 }
102
Pierre Lecesned55bef72017-11-10 22:31:01 +0000103 // Other files
104 std::unique_ptr<io::IFileCollectionIterator> iterator = apk->GetFileCollection()->Iterator();
105 while (iterator->HasNext()) {
106 io::IFile* file = iterator->Next();
107
108 std::string path = file->GetSource().path;
109 // The name of the path has the format "<zip-file-name>@<path-to-file>".
110 path = path.substr(path.find('@') + 1);
111
112 // Manifest, resource table and resources have already been taken care of.
113 if (path == kAndroidManifestPath ||
114 path == kApkResourceTablePath ||
115 path == kProtoResourceTablePath ||
116 path.find("res/") == 0) {
117 continue;
118 }
119
120 if (!io::CopyFileToArchivePreserveCompression(context, file, path, writer)) {
121 context->GetDiagnostics()->Error(DiagMessage(apk->GetSource())
122 << "failed to copy file " << path);
123 return false;
124 }
125 }
126
Adam Lesinski8780eb62017-10-31 17:44:39 -0700127 return true;
128}
129
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000130
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000131class BinaryApkSerializer : public IApkSerializer {
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000132 public:
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000133 BinaryApkSerializer(IAaptContext* context, const Source& source,
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000134 const TableFlattenerOptions& options)
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000135 : IApkSerializer(context, source), tableFlattenerOptions_(options) {}
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000136
137 bool SerializeXml(const xml::XmlResource* xml, const std::string& path, bool utf16,
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000138 IArchiveWriter* writer) override {
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000139 BigBuffer buffer(4096);
140 XmlFlattenerOptions options = {};
141 options.use_utf16 = utf16;
Adam Lesinskibbf42972018-02-14 13:36:09 -0800142 options.keep_raw_values = true;
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000143 XmlFlattener flattener(&buffer, options);
144 if (!flattener.Consume(context_, xml)) {
145 return false;
146 }
147
148 io::BigBufferInputStream input_stream(&buffer);
149 return io::CopyInputStreamToArchive(context_, &input_stream, path, ArchiveEntry::kCompress,
150 writer);
151 }
152
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000153 bool SerializeTable(ResourceTable* table, IArchiveWriter* writer) override {
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000154 BigBuffer buffer(4096);
155 TableFlattener table_flattener(tableFlattenerOptions_, &buffer);
156 if (!table_flattener.Consume(context_, table)) {
157 return false;
158 }
159
160 io::BigBufferInputStream input_stream(&buffer);
161 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
162 ArchiveEntry::kAlign, writer);
163 }
164
David Chaloupkab66db4e2018-01-15 12:35:41 +0000165 bool SerializeFile(FileReference* file, IArchiveWriter* writer) override {
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000166 if (file->type == ResourceFile::Type::kProtoXml) {
167 unique_ptr<io::InputStream> in = file->file->OpenInputStream();
168 if (in == nullptr) {
169 context_->GetDiagnostics()->Error(DiagMessage(source_)
170 << "failed to open file " << *file->path);
171 return false;
172 }
173
174 pb::XmlNode pb_node;
175 io::ZeroCopyInputAdaptor adaptor(in.get());
176 if (!pb_node.ParseFromZeroCopyStream(&adaptor)) {
177 context_->GetDiagnostics()->Error(DiagMessage(source_)
178 << "failed to parse proto XML " << *file->path);
179 return false;
180 }
181
182 std::string error;
183 unique_ptr<xml::XmlResource> xml = DeserializeXmlResourceFromPb(pb_node, &error);
184 if (xml == nullptr) {
185 context_->GetDiagnostics()->Error(DiagMessage(source_)
186 << "failed to deserialize proto XML "
187 << *file->path << ": " << error);
188 return false;
189 }
190
191 if (!SerializeXml(xml.get(), *file->path, false /*utf16*/, writer)) {
192 context_->GetDiagnostics()->Error(DiagMessage(source_)
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000193 << "failed to serialize to binary XML: " << *file->path);
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000194 return false;
195 }
David Chaloupkab66db4e2018-01-15 12:35:41 +0000196
197 file->type = ResourceFile::Type::kBinaryXml;
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000198 } else {
Pierre Lecesned55bef72017-11-10 22:31:01 +0000199 if (!io::CopyFileToArchivePreserveCompression(context_, file->file, *file->path, writer)) {
200 context_->GetDiagnostics()->Error(DiagMessage(source_)
201 << "failed to copy file " << *file->path);
202 return false;
203 }
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000204 }
205
206 return true;
207 }
208
209 private:
210 TableFlattenerOptions tableFlattenerOptions_;
211
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000212 DISALLOW_COPY_AND_ASSIGN(BinaryApkSerializer);
213};
214
215class ProtoApkSerializer : public IApkSerializer {
216 public:
217 ProtoApkSerializer(IAaptContext* context, const Source& source)
218 : IApkSerializer(context, source) {}
219
220 bool SerializeXml(const xml::XmlResource* xml, const std::string& path, bool utf16,
221 IArchiveWriter* writer) override {
222 pb::XmlNode pb_node;
223 SerializeXmlResourceToPb(*xml, &pb_node);
224 return io::CopyProtoToArchive(context_, &pb_node, path, ArchiveEntry::kCompress, writer);
225 }
226
227 bool SerializeTable(ResourceTable* table, IArchiveWriter* writer) override {
228 pb::ResourceTable pb_table;
229 SerializeTableToPb(*table, &pb_table);
230 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
231 ArchiveEntry::kCompress, writer);
232 }
233
David Chaloupkab66db4e2018-01-15 12:35:41 +0000234 bool SerializeFile(FileReference* file, IArchiveWriter* writer) override {
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000235 if (file->type == ResourceFile::Type::kBinaryXml) {
236 std::unique_ptr<io::IData> data = file->file->OpenAsData();
237 if (!data) {
238 context_->GetDiagnostics()->Error(DiagMessage(source_)
239 << "failed to open file " << *file->path);
240 return false;
241 }
242
243 std::string error;
244 std::unique_ptr<xml::XmlResource> xml = xml::Inflate(data->data(), data->size(), &error);
245 if (xml == nullptr) {
246 context_->GetDiagnostics()->Error(DiagMessage(source_) << "failed to parse binary XML: "
247 << error);
248 return false;
249 }
250
251 if (!SerializeXml(xml.get(), *file->path, false /*utf16*/, writer)) {
252 context_->GetDiagnostics()->Error(DiagMessage(source_)
253 << "failed to serialize to proto XML: " << *file->path);
254 return false;
255 }
David Chaloupkab66db4e2018-01-15 12:35:41 +0000256
257 file->type = ResourceFile::Type::kProtoXml;
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000258 } else {
259 if (!io::CopyFileToArchivePreserveCompression(context_, file->file, *file->path, writer)) {
260 context_->GetDiagnostics()->Error(DiagMessage(source_)
261 << "failed to copy file " << *file->path);
262 return false;
263 }
264 }
265
266 return true;
267 }
268
269 private:
270 DISALLOW_COPY_AND_ASSIGN(ProtoApkSerializer);
Pierre Lecesne7e8549d2017-11-10 01:22:12 +0000271};
272
Adam Lesinski8780eb62017-10-31 17:44:39 -0700273class Context : public IAaptContext {
274 public:
275 Context() : mangler_({}), symbols_(&mangler_) {
276 }
277
278 PackageType GetPackageType() override {
279 return PackageType::kApp;
280 }
281
282 SymbolTable* GetExternalSymbols() override {
283 return &symbols_;
284 }
285
286 IDiagnostics* GetDiagnostics() override {
287 return &diag_;
288 }
289
290 const std::string& GetCompilationPackage() override {
291 return package_;
292 }
293
294 uint8_t GetPackageId() override {
295 // Nothing should call this.
296 UNIMPLEMENTED(FATAL) << "PackageID should not be necessary";
297 return 0;
298 }
299
300 NameMangler* GetNameMangler() override {
301 UNIMPLEMENTED(FATAL);
302 return nullptr;
303 }
304
305 bool IsVerbose() override {
306 return verbose_;
307 }
308
309 int GetMinSdkVersion() override {
310 return 0u;
311 }
312
Chris Warrington481f0272018-02-06 14:03:39 +0000313 bool IsAutoNamespace() override {
314 return false;
315 }
316
Adam Lesinski8780eb62017-10-31 17:44:39 -0700317 bool verbose_ = false;
318 std::string package_;
319
320 private:
321 DISALLOW_COPY_AND_ASSIGN(Context);
322
323 NameMangler mangler_;
324 SymbolTable symbols_;
325 StdErrDiagnostics diag_;
326};
327
328int Convert(const vector<StringPiece>& args) {
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000329
330 static const char* kOutputFormatProto = "proto";
331 static const char* kOutputFormatBinary = "binary";
332
Adam Lesinski8780eb62017-10-31 17:44:39 -0700333 Context context;
334 std::string output_path;
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000335 Maybe<std::string> output_format;
Adam Lesinski8780eb62017-10-31 17:44:39 -0700336 TableFlattenerOptions options;
337 Flags flags =
338 Flags()
339 .RequiredFlag("-o", "Output path", &output_path)
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000340 .OptionalFlag("--output-format", StringPrintf("Format of the output. Accepted values are "
341 "'%s' and '%s'. When not set, defaults to '%s'.", kOutputFormatProto,
342 kOutputFormatBinary, kOutputFormatBinary), &output_format)
Adam Lesinski8780eb62017-10-31 17:44:39 -0700343 .OptionalSwitch("--enable-sparse-encoding",
344 "Enables encoding sparse entries using a binary search tree.\n"
345 "This decreases APK size at the cost of resource retrieval performance.",
346 &options.use_sparse_entries)
347 .OptionalSwitch("-v", "Enables verbose logging", &context.verbose_);
348 if (!flags.Parse("aapt2 convert", args, &std::cerr)) {
349 return 1;
350 }
351
352 if (flags.GetArgs().size() != 1) {
353 std::cerr << "must supply a single proto APK\n";
354 flags.Usage("aapt2 convert", &std::cerr);
355 return 1;
356 }
357
358 const StringPiece& path = flags.GetArgs()[0];
359 unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(path, context.GetDiagnostics());
360 if (apk == nullptr) {
361 context.GetDiagnostics()->Error(DiagMessage(path) << "failed to load APK");
362 return 1;
363 }
364
365 Maybe<AppInfo> app_info =
366 ExtractAppInfoFromBinaryManifest(*apk->GetManifest(), context.GetDiagnostics());
367 if (!app_info) {
368 return 1;
369 }
370
371 context.package_ = app_info.value().package;
372
373 unique_ptr<IArchiveWriter> writer =
374 CreateZipFileArchiveWriter(context.GetDiagnostics(), output_path);
375 if (writer == nullptr) {
376 return 1;
377 }
Pierre Lecesned8b4bea2017-11-10 23:50:17 +0000378
379 unique_ptr<IApkSerializer> serializer;
380 if (!output_format || output_format.value() == kOutputFormatBinary) {
381 serializer.reset(new BinaryApkSerializer(&context, apk->GetSource(), options));
382 } else if (output_format.value() == kOutputFormatProto) {
383 serializer.reset(new ProtoApkSerializer(&context, apk->GetSource()));
384 } else {
385 context.GetDiagnostics()->Error(DiagMessage(path)
386 << "Invalid value for flag --output-format: "
387 << output_format.value());
388 return 1;
389 }
390
391
392 return ConvertApk(&context, std::move(apk), serializer.get(), writer.get()) ? 0 : 1;
Adam Lesinski8780eb62017-10-31 17:44:39 -0700393}
394
395} // namespace aapt