blob: b372923e40100bcc5e8a89c2b2fbe6d33d3d7421 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 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
Adam Lesinskice5e56e2016-10-21 17:56:45 -070017#include <sys/stat.h>
18
19#include <fstream>
20#include <queue>
21#include <unordered_map>
22#include <vector>
23
24#include "android-base/errors.h"
25#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080026#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080027#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070028
Adam Lesinski1ab598f2015-08-14 14:26:04 -070029#include "AppInfo.h"
30#include "Debug.h"
31#include "Flags.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070032#include "LoadedApk.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080033#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070034#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080035#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070036#include "ResourceValues.h"
37#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070038#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "compile/IdAssigner.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080040#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070041#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070042#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070043#include "format/binary/TableFlattener.h"
44#include "format/binary/XmlFlattener.h"
45#include "format/proto/ProtoDeserialize.h"
46#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070047#include "io/BigBufferStream.h"
48#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080049#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070050#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080051#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070052#include "java/JavaClassGenerator.h"
53#include "java/ManifestClassGenerator.h"
54#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070055#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070056#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080057#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070059#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080060#include "optimize/ResourceDeduper.h"
61#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "process/IResourceTableConsumer.h"
63#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080064#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070065#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080066#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070068using ::aapt::io::FileInputStream;
69using ::android::StringPiece;
70using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070071
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072namespace aapt {
73
Adam Lesinskie59f0d82017-10-13 09:36:53 -070074enum class OutputFormat {
75 kApk,
76 kProto,
77};
78
Adam Lesinski1ab598f2015-08-14 14:26:04 -070079struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070080 std::string output_path;
81 std::string manifest_path;
82 std::vector<std::string> include_paths;
83 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070084 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070085 bool output_to_directory = false;
86 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070087 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070088
Adam Lesinskicacb28f2016-10-19 12:18:14 -070089 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070090 Maybe<std::string> generate_java_class_path;
91 Maybe<std::string> custom_java_package;
92 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070093 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070094 Maybe<std::string> generate_proguard_rules_path;
95 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070096 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070097 bool generate_non_final_ids = false;
98 std::vector<std::string> javadoc_annotations;
99 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700100
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700101 // Optimizations/features.
102 bool no_auto_version = false;
103 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900104 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700105 bool no_resource_deduping = false;
106 bool no_xml_namespaces = false;
107 bool do_not_compress_anything = false;
108 std::unordered_set<std::string> extensions_to_not_compress;
109
110 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700111 bool no_static_lib_packages = false;
112
113 // AndroidManifest.xml massaging options.
114 ManifestFixerOptions manifest_fixer_options;
115
116 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700117 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700118
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800119 // Flattening options.
120 TableFlattenerOptions table_flattener_options;
121
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700122 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700123 TableSplitterOptions table_splitter_options;
124 std::vector<SplitConstraints> split_constraints;
125 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700126
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700127 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700128 std::unordered_map<ResourceName, ResourceId> stable_id_map;
129 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700130};
131
Adam Lesinski64587af2016-02-18 18:33:06 -0800132class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700133 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100134 LinkContext(IDiagnostics* diagnostics)
135 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700137
Adam Lesinskib522f042017-04-21 16:57:59 -0700138 PackageType GetPackageType() override {
139 return package_type_;
140 }
141
142 void SetPackageType(PackageType type) {
143 package_type_ = type;
144 }
145
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700146 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100147 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700148 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700149
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700150 NameMangler* GetNameMangler() override {
151 return &name_mangler_;
152 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700153
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700154 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
155 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700156 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800157
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700158 const std::string& GetCompilationPackage() override {
159 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700160 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700161
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700162 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800163 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700164 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800165
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700166 uint8_t GetPackageId() override {
167 return package_id_;
168 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700169
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700170 void SetPackageId(uint8_t id) {
171 package_id_ = id;
172 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800173
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700174 SymbolTable* GetExternalSymbols() override {
175 return &symbols_;
176 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800177
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700178 bool IsVerbose() override {
179 return verbose_;
180 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800181
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700182 void SetVerbose(bool val) {
183 verbose_ = val;
184 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800185
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700186 int GetMinSdkVersion() override {
187 return min_sdk_version_;
188 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700189
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700190 void SetMinSdkVersion(int minSdk) {
191 min_sdk_version_ = minSdk;
192 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700193
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700194 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700195 DISALLOW_COPY_AND_ASSIGN(LinkContext);
196
Adam Lesinskib522f042017-04-21 16:57:59 -0700197 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100198 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700199 NameMangler name_mangler_;
200 std::string compilation_package_;
201 uint8_t package_id_ = 0x0;
202 SymbolTable symbols_;
203 bool verbose_ = false;
204 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700205};
206
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700207// A custom delegate that generates compatible pre-O IDs for use with feature splits.
208// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
209// is interpreted as a negative number. Some verification was wrongly assuming negative values
210// were invalid.
211//
212// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
213// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
214// an overlap exists.
215class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
216 public:
217 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
218 }
219
220 virtual ~FeatureSplitSymbolTableDelegate() = default;
221
222 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
223 const ResourceName& name,
224 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
225 std::unique_ptr<SymbolTable::Symbol> symbol =
226 DefaultSymbolTableDelegate::FindByName(name, sources);
227 if (symbol == nullptr) {
228 return {};
229 }
230
231 // Check to see if this is an 'id' with the target package.
232 if (name.type == ResourceType::kId && symbol->id) {
233 ResourceId* id = &symbol->id.value();
234 if (id->package_id() > kAppPackageId) {
235 // Rewrite the resource ID to be compatible pre-O.
236 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
237
238 // Check that this doesn't overlap another resource.
239 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
240 // The ID overlaps, so log a message (since this is a weird failure) and fail.
241 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
242 << " for pre-O feature split support");
243 return {};
244 }
245
246 if (context_->IsVerbose()) {
247 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
248 << ") -> (" << rewritten_id << ")");
249 }
250
251 *id = rewritten_id;
252 }
253 }
254 return symbol;
255 }
256
257 private:
258 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
259
260 IAaptContext* context_;
261};
262
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700263static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
264 const StringPiece& path, bool keep_raw_values, bool utf16,
265 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700266 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700267 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
268 << (keep_raw_values ? "true" : "false")
269 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700270 }
271
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700272 switch (format) {
273 case OutputFormat::kApk: {
274 BigBuffer buffer(1024);
275 XmlFlattenerOptions options = {};
276 options.keep_raw_values = keep_raw_values;
277 options.use_utf16 = utf16;
278 XmlFlattener flattener(&buffer, options);
279 if (!flattener.Consume(context, &xml_res)) {
280 return false;
281 }
282
283 io::BigBufferInputStream input_stream(&buffer);
284 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
285 ArchiveEntry::kCompress, writer);
286 } break;
287
288 case OutputFormat::kProto: {
289 pb::XmlNode pb_node;
290 SerializeXmlResourceToPb(xml_res, &pb_node);
291 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
292 writer);
293 } break;
294 }
295 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800296}
297
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700298// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700299static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700300 FileInputStream fin(path);
301 if (fin.HadError()) {
302 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700303 return {};
304 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700305 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800306}
307
Adam Lesinski355f2852016-02-13 20:26:45 -0800308struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700309 bool no_auto_version = false;
310 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900311 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700312 bool no_xml_namespaces = false;
313 bool keep_raw_values = false;
314 bool do_not_compress_anything = false;
315 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700316 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700317 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800318};
319
Adam Lesinskic744ae82017-05-17 19:28:38 -0700320// A sampling of public framework resource IDs.
321struct R {
322 struct attr {
323 enum : uint32_t {
324 paddingLeft = 0x010100d6u,
325 paddingRight = 0x010100d8u,
326 paddingHorizontal = 0x0101053du,
327
328 paddingTop = 0x010100d7u,
329 paddingBottom = 0x010100d9u,
330 paddingVertical = 0x0101053eu,
331
332 layout_marginLeft = 0x010100f7u,
333 layout_marginRight = 0x010100f9u,
334 layout_marginHorizontal = 0x0101053bu,
335
336 layout_marginTop = 0x010100f8u,
337 layout_marginBottom = 0x010100fau,
338 layout_marginVertical = 0x0101053cu,
339 };
340 };
341};
342
Adam Lesinski355f2852016-02-13 20:26:45 -0800343class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700344 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700345 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700346 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800347
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700348 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800349
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700350 private:
351 struct FileOperation {
352 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700353
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700355 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700356
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700357 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700358 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700359
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700360 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700361 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700362
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700363 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700364 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700365 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800366
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700367 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800368
Adam Lesinskic744ae82017-05-17 19:28:38 -0700369 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
370 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800371
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700372 ResourceFileFlattenerOptions options_;
373 IAaptContext* context_;
374 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700375 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800376};
377
Adam Lesinskic744ae82017-05-17 19:28:38 -0700378ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
379 IAaptContext* context, proguard::KeepSet* keep_set)
380 : options_(options), context_(context), keep_set_(keep_set) {
381 SymbolTable* symm = context_->GetExternalSymbols();
382
383 // Build up the rules for degrading newer attributes to older ones.
384 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
385 // generated from the attribute definitions themselves (b/62028956).
386 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
387 std::vector<ReplacementAttr> replacements{
388 {"paddingLeft", R::attr::paddingLeft,
389 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
390 {"paddingRight", R::attr::paddingRight,
391 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
392 };
393 rules_[R::attr::paddingHorizontal] =
394 util::make_unique<DegradeToManyRule>(std::move(replacements));
395 }
396
397 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
398 std::vector<ReplacementAttr> replacements{
399 {"paddingTop", R::attr::paddingTop,
400 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
401 {"paddingBottom", R::attr::paddingBottom,
402 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
403 };
404 rules_[R::attr::paddingVertical] =
405 util::make_unique<DegradeToManyRule>(std::move(replacements));
406 }
407
408 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
409 std::vector<ReplacementAttr> replacements{
410 {"layout_marginLeft", R::attr::layout_marginLeft,
411 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
412 {"layout_marginRight", R::attr::layout_marginRight,
413 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
414 };
415 rules_[R::attr::layout_marginHorizontal] =
416 util::make_unique<DegradeToManyRule>(std::move(replacements));
417 }
418
419 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
420 std::vector<ReplacementAttr> replacements{
421 {"layout_marginTop", R::attr::layout_marginTop,
422 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
423 {"layout_marginBottom", R::attr::layout_marginBottom,
424 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
425 };
426 rules_[R::attr::layout_marginVertical] =
427 util::make_unique<DegradeToManyRule>(std::move(replacements));
428 }
429}
430
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700431uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
432 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700433 return 0;
434 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800435
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700436 for (const std::string& extension : options_.extensions_to_not_compress) {
437 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700438 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800439 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700440 }
441 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800442}
443
Adam Lesinskibb94f322017-07-12 07:41:55 -0700444static bool IsTransitionElement(const std::string& name) {
445 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
446 name == "changeImageTransform" || name == "changeTransform" ||
447 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
448 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
449 name == "transitionManager";
450}
451
452static bool IsVectorElement(const std::string& name) {
453 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
ztenghuiab2a38c2017-10-13 15:56:08 -0700454 name == "objectAnimator" || name == "gradient";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700455}
456
Adam Lesinskic744ae82017-05-17 19:28:38 -0700457template <typename T>
458std::vector<T> make_singleton_vec(T&& val) {
459 std::vector<T> vec;
460 vec.emplace_back(std::forward<T>(val));
461 return vec;
462}
463
464std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
465 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700466 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700467 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700468
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700469 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700470 context_->GetDiagnostics()->Note(DiagMessage()
471 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 }
473
Adam Lesinski00451162017-10-03 07:44:08 -0700474 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
475 // that existing projects have out-of-date references which pass compilation.
476 xml::StripAndroidStudioAttributes(doc->root.get());
477
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700478 XmlReferenceLinker xml_linker;
479 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700480 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700481 }
482
Adam Koskidc21dea2017-07-21 10:55:27 -0700483 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700484 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700485 }
486
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700487 if (options_.no_xml_namespaces) {
488 XmlNamespaceRemover namespace_remover;
489 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700490 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800491 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800493
Adam Lesinskibb94f322017-07-12 07:41:55 -0700494 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700495 return make_singleton_vec(std::move(file_op->xml_to_flatten));
496 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700497
Adam Lesinskibb94f322017-07-12 07:41:55 -0700498 if (options_.no_version_vectors || options_.no_version_transitions) {
499 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700500 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700501 if (el && el->namespace_uri.empty()) {
502 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
503 (options_.no_version_transitions && IsTransitionElement(el->name))) {
504 return make_singleton_vec(std::move(file_op->xml_to_flatten));
505 }
506 }
507 }
508
Adam Lesinskic744ae82017-05-17 19:28:38 -0700509 const ConfigDescription& config = file_op->config;
510 ResourceEntry* entry = file_op->entry;
511
512 XmlCompatVersioner xml_compat_versioner(&rules_);
513 const util::Range<ApiVersion> api_range{config.sdkVersion,
514 FindNextApiVersionForConfig(entry, config)};
515 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800516}
517
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700518bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700519 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700520 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800521
Adam Koskidc21dea2017-07-21 10:55:27 -0700522 proguard::CollectResourceReferences(context_, table, keep_set_);
523
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700524 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700525 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
526
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700527 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700528 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700529 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700530 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800531
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700532 // Populate the queue with all files in the ResourceTable.
533 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700534 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700535 // WARNING! Do not insert or remove any resources while executing in this scope. It will
536 // corrupt the iteration order.
537
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700538 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700539 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700540 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700542
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700543 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700545 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700546 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700547 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700548 }
549
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700550 FileOperation file_op;
551 file_op.entry = entry.get();
552 file_op.dst_path = *file_ref->path;
553 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700554 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700556 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700557 (file_ref->type == ResourceFile::Type::kBinaryXml ||
558 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700559 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700561 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562 << "failed to open file");
563 return false;
564 }
565
Adam Lesinski00451162017-10-03 07:44:08 -0700566 if (file_ref->type == ResourceFile::Type::kProtoXml) {
567 pb::XmlNode pb_xml_node;
568 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
569 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700570 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700571 return false;
572 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573
Adam Lesinski00451162017-10-03 07:44:08 -0700574 std::string error;
575 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
576 if (file_op.xml_to_flatten == nullptr) {
577 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700578 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700579 return false;
580 }
581 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700582 std::string error_str;
583 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700584 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700585 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
586 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700587 return false;
588 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700589 }
590
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700591 file_op.xml_to_flatten->file.config = config_value->config;
592 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700593 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700594 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700595
596 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
597 // else we end up copying the string in the std::make_pair() method,
598 // then creating a StringPiece from the copy, which would cause us
599 // to end up referencing garbage in the map.
600 const StringPiece entry_name(entry->name);
601 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
602 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700603 }
604 }
605
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700606 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700607 for (auto& map_entry : config_sorted_files) {
608 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700609 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700610
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700611 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700612 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
613 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700614 if (versioned_docs.empty()) {
615 error = true;
616 continue;
617 }
618
Adam Lesinskic744ae82017-05-17 19:28:38 -0700619 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
620 std::string dst_path = file_op.dst_path;
621 if (doc->file.config != file_op.config) {
622 // Only add the new versioned configurations.
623 if (context_->IsVerbose()) {
624 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
625 << "auto-versioning resource from config '"
626 << config << "' -> '" << doc->file.config << "'");
627 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700628
Adam Lesinskic744ae82017-05-17 19:28:38 -0700629 dst_path =
630 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
631 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
632 doc->file.source, dst_path, nullptr,
633 context_->GetDiagnostics());
634 if (!result) {
635 return false;
636 }
637 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700638
639 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
640 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700641 }
642 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700643 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
644 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700645 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700646 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700647 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648 }
649 return !error;
650}
651
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700652static bool WriteStableIdMapToPath(IDiagnostics* diag,
653 const std::unordered_map<ResourceName, ResourceId>& id_map,
654 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700655 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700656 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700657 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700658 return false;
659 }
660
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700661 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700662 const ResourceName& name = entry.first;
663 const ResourceId& id = entry.second;
664 fout << name << " = " << id << "\n";
665 }
666
667 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700668 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
669 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 return false;
671 }
672
673 return true;
674}
675
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700676static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
677 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700678 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700679 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700680 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681 return false;
682 }
683
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700684 out_id_map->clear();
685 size_t line_no = 0;
686 for (StringPiece line : util::Tokenize(content, '\n')) {
687 line_no++;
688 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700689 if (line.empty()) {
690 continue;
691 }
692
693 auto iter = std::find(line.begin(), line.end(), '=');
694 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696 return false;
697 }
698
699 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700700 StringPiece res_name_str =
701 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
702 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700703 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
704 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705 return false;
706 }
707
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700708 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
709 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700710 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700712 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
713 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700714 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
715 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 return false;
717 }
718
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700719 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700720 }
721 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700722}
723
Adam Lesinskifb48d292015-11-07 15:52:13 -0800724class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700725 public:
726 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700727 : options_(options),
728 context_(context),
729 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700730 file_collection_(util::make_unique<io::FileCollection>()) {
731 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700732
Adam Lesinski8780eb62017-10-31 17:44:39 -0700733 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700735 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700736 for (const std::string& path : options_.include_paths) {
737 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700738 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700739 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700740
Adam Lesinski8780eb62017-10-31 17:44:39 -0700741 std::string error;
742 auto zip_collection = io::ZipFileCollection::Create(path, &error);
743 if (zip_collection == nullptr) {
744 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
745 return false;
746 }
747
748 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
749 // Load this as a static library include.
750 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
751 Source(path), std::move(zip_collection), context_->GetDiagnostics());
752 if (static_apk == nullptr) {
753 return false;
754 }
755
Adam Lesinskib522f042017-04-21 16:57:59 -0700756 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800757 // Can't include static libraries when not building a static library (they have no IDs
758 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700759 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800760 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700761 return false;
762 }
763
Adam Lesinski8780eb62017-10-31 17:44:39 -0700764 ResourceTable* table = static_apk->GetResourceTable();
765
766 // If we are using --no-static-lib-packages, we need to rename the package of this table to
767 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700768 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800769 // Since package names can differ, and multiple packages can exist in a ResourceTable,
770 // we place the requirement that all static libraries are built with the package
771 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700772 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700773 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800774 } else {
775 context_->GetDiagnostics()->Error(DiagMessage(path)
776 << "no package with ID 0x7f found in static library");
777 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700778 }
779 }
780
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700781 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700782 util::make_unique<ResourceTableSymbolSource>(table));
783 static_library_includes_.push_back(std::move(static_apk));
784 } else {
785 if (!asset_source->AddAssetPath(path)) {
786 context_->GetDiagnostics()->Error(DiagMessage()
787 << "failed to load include path " << path);
788 return false;
789 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700790 }
791 }
792
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800793 // Capture the shared libraries so that the final resource table can be properly flattened
794 // with support for shared libraries.
795 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800796 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800797 final_table_.included_packages_[entry.first] = entry.second;
798 }
799 }
800
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700801 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700802 return true;
803 }
804
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800805 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700806 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800807 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
808 if (manifest_el == nullptr) {
809 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700810 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800811
812 AppInfo app_info;
813
814 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
815 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
816 return {};
817 }
818
819 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
820 if (!package_attr) {
821 diag->Error(DiagMessage(xml_res->file.source)
822 << "<manifest> must have a 'package' attribute");
823 return {};
824 }
825 app_info.package = package_attr->value;
826
827 if (xml::Attribute* version_code_attr =
828 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
829 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
830 if (!maybe_code) {
831 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
832 << "invalid android:versionCode '" << version_code_attr->value << "'");
833 return {};
834 }
835 app_info.version_code = maybe_code.value();
836 }
837
838 if (xml::Attribute* revision_code_attr =
839 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
840 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
841 if (!maybe_code) {
842 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
843 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
844 return {};
845 }
846 app_info.revision_code = maybe_code.value();
847 }
848
849 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
850 if (!split_name_attr->value.empty()) {
851 app_info.split_name = split_name_attr->value;
852 }
853 }
854
855 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
856 if (xml::Attribute* min_sdk =
857 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700858 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800859 }
860 }
861 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700862 }
863
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700864 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
865 // Postcondition: ResourceTable has only one package left. All others are
866 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700867 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700868 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700869 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
870 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700871 };
872
873 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700874 for (const auto& package : final_table_.packages) {
875 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700876 // We have a package that is not related to the one we're building!
877 for (const auto& type : package->types) {
878 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700879 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700880
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700881 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700882 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700883 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700884 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
885 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
886 << "generated id '" << res_name
887 << "' for external package '" << package->name
888 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700889 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700890 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
891 << "defined resource '" << res_name
892 << "' for external package '" << package->name
893 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700894 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700895 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700896 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700897 }
898 }
899 }
900 }
901
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700902 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
903 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700904 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700905 return !error;
906 }
907
908 /**
909 * Returns true if no IDs have been set, false otherwise.
910 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700911 bool VerifyNoIdsSet() {
912 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700913 for (const auto& type : package->types) {
914 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800915 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
916 << StringPrintf("%02x", type->id.value())
917 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700918 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700919 }
920
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700921 for (const auto& entry : type->entries) {
922 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700923 ResourceNameRef res_name(package->name, type->type, entry->name);
924 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800925 DiagMessage() << "entry " << res_name << " has ID "
926 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700927 return false;
928 }
929 }
930 }
931 }
932 return true;
933 }
934
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700935 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
936 if (options_.output_to_directory) {
937 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700938 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700939 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700940 }
941 }
942
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700943 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
944 switch (format) {
945 case OutputFormat::kApk: {
946 BigBuffer buffer(1024);
947 TableFlattener flattener(options_.table_flattener_options, &buffer);
948 if (!flattener.Consume(context_, table)) {
949 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
950 return false;
951 }
952
953 io::BigBufferInputStream input_stream(&buffer);
954 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
955 ArchiveEntry::kAlign, writer);
956 } break;
957
958 case OutputFormat::kProto: {
959 pb::ResourceTable pb_table;
960 SerializeTableToPb(*table, &pb_table);
961 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
962 ArchiveEntry::kCompress, writer);
963 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700964 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700965 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700966 }
967
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700968 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700969 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700970 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700971 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700972 return true;
973 }
974
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700975 std::string out_path = options_.generate_java_class_path.value();
976 file::AppendPath(&out_path, file::PackageToPath(out_package));
977 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700978 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
979 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700980 return false;
981 }
982
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700983 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700984
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700985 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700986 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700987 context_->GetDiagnostics()->Error(DiagMessage()
988 << "failed writing to '" << out_path
989 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700990 return false;
991 }
992
Adam Lesinski418763f2017-04-11 17:36:53 -0700993 std::unique_ptr<std::ofstream> fout_text;
994 if (out_text_symbols_path) {
995 fout_text =
996 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
997 if (!*fout_text) {
998 context_->GetDiagnostics()->Error(
999 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
1000 << "': " << android::base::SystemErrorCodeToString(errno));
1001 return false;
1002 }
1003 }
1004
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001005 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -07001006 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -07001007 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001008 return false;
1009 }
1010
1011 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001012 context_->GetDiagnostics()->Error(DiagMessage()
1013 << "failed writing to '" << out_path
1014 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001015 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 }
1017 return true;
1018 }
1019
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001020 bool GenerateJavaClasses() {
1021 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1022 std::vector<std::string> packages_to_callback;
1023
1024 JavaClassGeneratorOptions template_options;
1025 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1026 template_options.javadoc_annotations = options_.javadoc_annotations;
1027
1028 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1029 template_options.use_final = false;
1030 }
1031
1032 if (context_->GetPackageType() == PackageType::kSharedLib) {
1033 template_options.use_final = false;
1034 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1035 }
1036
1037 const StringPiece actual_package = context_->GetCompilationPackage();
1038 StringPiece output_package = context_->GetCompilationPackage();
1039 if (options_.custom_java_package) {
1040 // Override the output java package to the custom one.
1041 output_package = options_.custom_java_package.value();
1042 }
1043
1044 // Generate the private symbols if required.
1045 if (options_.private_symbols) {
1046 packages_to_callback.push_back(options_.private_symbols.value());
1047
1048 // If we defined a private symbols package, we only emit Public symbols
1049 // to the original package, and private and public symbols to the private package.
1050 JavaClassGeneratorOptions options = template_options;
1051 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1052 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1053 options)) {
1054 return false;
1055 }
1056 }
1057
1058 // Generate copies of the original package R class but with different package names.
1059 // This is to support non-namespaced builds.
1060 for (const std::string& extra_package : options_.extra_java_packages) {
1061 packages_to_callback.push_back(extra_package);
1062
1063 JavaClassGeneratorOptions options = template_options;
1064 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1065 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1066 return false;
1067 }
1068 }
1069
1070 // Generate R classes for each package that was merged (static library).
1071 // Use the actual package's resources only.
1072 for (const std::string& package : table_merger_->merged_packages()) {
1073 packages_to_callback.push_back(package);
1074
1075 JavaClassGeneratorOptions options = template_options;
1076 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1077 if (!WriteJavaFile(&final_table_, package, package, options)) {
1078 return false;
1079 }
1080 }
1081
1082 // Generate the main public R class.
1083 JavaClassGeneratorOptions options = template_options;
1084
1085 // Only generate public symbols if we have a private package.
1086 if (options_.private_symbols) {
1087 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1088 }
1089
1090 if (options.rewrite_callback_options) {
1091 options.rewrite_callback_options.value().packages_to_callback =
1092 std::move(packages_to_callback);
1093 }
1094
1095 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1096 options_.generate_text_symbols_path)) {
1097 return false;
1098 }
1099
1100 return true;
1101 }
1102
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001103 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1104 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001105 return true;
1106 }
1107
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001108 std::unique_ptr<ClassDefinition> manifest_class =
1109 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001110
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001111 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112 // Something bad happened, but we already logged it, so exit.
1113 return false;
1114 }
1115
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001116 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001117 // Empty Manifest class, no need to generate it.
1118 return true;
1119 }
1120
1121 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001122 for (const std::string& annotation : options_.javadoc_annotations) {
1123 std::string proper_annotation = "@";
1124 proper_annotation += annotation;
1125 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001126 }
1127
Adam Lesinski0d81f702017-06-27 15:51:09 -07001128 const std::string package_utf8 =
1129 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001130
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001131 std::string out_path = options_.generate_java_class_path.value();
1132 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001133
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001134 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001135 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1136 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001137 return false;
1138 }
1139
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001140 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001141
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001142 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001143 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001144 context_->GetDiagnostics()->Error(DiagMessage()
1145 << "failed writing to '" << out_path
1146 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001147 return false;
1148 }
1149
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001150 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1151 context_->GetDiagnostics()->Error(DiagMessage()
1152 << "failed writing to '" << out_path
1153 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001154 return false;
1155 }
1156 return true;
1157 }
1158
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001159 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001160 if (!out) {
1161 return true;
1162 }
1163
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001164 const std::string& out_path = out.value();
1165 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001166 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001167 context_->GetDiagnostics()->Error(DiagMessage()
1168 << "failed to open '" << out_path
1169 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001170 return false;
1171 }
1172
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001173 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001174 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001175 context_->GetDiagnostics()->Error(DiagMessage()
1176 << "failed writing to '" << out_path
1177 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001178 return false;
1179 }
1180 return true;
1181 }
1182
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001183 bool MergeStaticLibrary(const std::string& input, bool override) {
1184 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001185 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001186 }
1187
Adam Lesinski8780eb62017-10-31 17:44:39 -07001188 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1189 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001190 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001191 return false;
1192 }
1193
Adam Lesinski8780eb62017-10-31 17:44:39 -07001194 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001195 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001196 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001197 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001198 return false;
1199 }
1200
1201 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001202 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001203 // Merge all resources as if they were in the compilation package. This is the old behavior
1204 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001205
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001206 // Add the package to the set of --extra-packages so we emit an R.java for each library
1207 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001208 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001209 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001210 }
1211
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001212 // Clear the package name, so as to make the resources look like they are coming from the
1213 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001215 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001216
1217 } else {
1218 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001219 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001220 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 }
1222
1223 if (!result) {
1224 return false;
1225 }
1226
1227 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001228 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001229 return true;
1230 }
1231
Adam Lesinski00451162017-10-03 07:44:08 -07001232 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001233 if (context_->IsVerbose()) {
Adam Lesinski00451162017-10-03 07:44:08 -07001234 context_->GetDiagnostics()->Note(DiagMessage()
1235 << "merging '" << compiled_file.name
1236 << "' from compiled file " << compiled_file.source);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237 }
1238
Adam Lesinski00451162017-10-03 07:44:08 -07001239 if (!table_merger_->MergeFile(compiled_file, override, file)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001240 return false;
1241 }
1242
1243 // Add the exports of this file to the table.
Adam Lesinski00451162017-10-03 07:44:08 -07001244 for (const SourcedResourceName& exported_symbol : compiled_file.exported_symbols) {
1245 ResourceName res_name = exported_symbol.name;
1246 if (res_name.package.empty()) {
1247 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001248 }
1249
Adam Lesinski00451162017-10-03 07:44:08 -07001250 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001251 if (mangled_name) {
1252 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253 }
1254
1255 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski00451162017-10-03 07:44:08 -07001256 id->SetSource(compiled_file.source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001257 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001258 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1259 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001260 if (!result) {
1261 return false;
1262 }
1263 }
1264 return true;
1265 }
1266
Adam Lesinski00451162017-10-03 07:44:08 -07001267 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1268 // If override is true, conflicting resources are allowed to override each other, in order of last
1269 // seen.
1270 // An io::IFileCollection is created from the ZIP file and added to the set of
1271 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001272 bool MergeArchive(const std::string& input, bool override) {
1273 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001274 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001275 }
1276
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001277 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001278 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001279 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001280 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001281 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001282 return false;
1283 }
1284
1285 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001286 for (auto iter = collection->Iterator(); iter->HasNext();) {
1287 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 error = true;
1289 }
1290 }
1291
1292 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001293 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 return !error;
1295 }
1296
Adam Lesinski00451162017-10-03 07:44:08 -07001297 // Takes a path to load and merge into the master ResourceTable. If override is true,
1298 // conflicting resources are allowed to override each other, in order of last seen.
1299 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1300 // as ZIP archive and the files within are merged individually.
1301 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001302 bool MergePath(const std::string& path, bool override) {
1303 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1304 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1305 return MergeArchive(path, override);
1306 } else if (util::EndsWith(path, ".apk")) {
1307 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308 }
1309
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001310 io::IFile* file = file_collection_->InsertFile(path);
1311 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001312 }
1313
Adam Lesinski00451162017-10-03 07:44:08 -07001314 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1315 // If override is true, conflicting resources are allowed to override each other, in order of last
1316 // seen.
1317 // All other file types are ignored. This is because these files could be coming from a zip,
1318 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001319 bool MergeFile(io::IFile* file, bool override) {
1320 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321
Adam Lesinski00451162017-10-03 07:44:08 -07001322 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001323 // Since AAPT compiles these file types and appends .flat to them, seeing
1324 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001325 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1326 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1327 << " file passed as argument. Must be "
1328 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001329 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001330 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1331 if (context_->IsVerbose()) {
1332 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1333 return true;
1334 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335 }
1336
Adam Lesinski00451162017-10-03 07:44:08 -07001337 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1338 if (input_stream == nullptr) {
1339 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1340 return false;
1341 }
1342
1343 if (input_stream->HadError()) {
1344 context_->GetDiagnostics()->Error(DiagMessage(src)
1345 << "failed to open file: " << input_stream->GetError());
1346 return false;
1347 }
1348
1349 ContainerReaderEntry* entry;
1350 ContainerReader reader(input_stream.get());
1351 while ((entry = reader.Next()) != nullptr) {
1352 if (entry->Type() == ContainerEntryType::kResTable) {
1353 pb::ResourceTable pb_table;
1354 if (!entry->GetResTable(&pb_table)) {
1355 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1356 << entry->GetError());
1357 return false;
1358 }
1359
1360 ResourceTable table;
1361 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001362 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001363 context_->GetDiagnostics()->Error(DiagMessage(src)
1364 << "failed to deserialize resource table: " << error);
1365 return false;
1366 }
1367
1368 if (!table_merger_->Merge(src, &table, override)) {
1369 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1370 return false;
1371 }
1372 } else if (entry->Type() == ContainerEntryType::kResFile) {
1373 pb::internal::CompiledFile pb_compiled_file;
1374 off64_t offset;
1375 size_t len;
1376 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1377 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1378 << entry->GetError());
1379 return false;
1380 }
1381
1382 ResourceFile resource_file;
1383 std::string error;
1384 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1385 context_->GetDiagnostics()->Error(DiagMessage(src)
1386 << "failed to read compiled header: " << error);
1387 return false;
1388 }
1389
1390 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1391 return false;
1392 }
1393 }
1394 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001395 return true;
1396 }
1397
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001398 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1399 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1400 for (const std::string& assets_dir : options_.assets_dirs) {
1401 Maybe<std::vector<std::string>> files =
1402 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1403 if (!files) {
1404 return false;
1405 }
1406
1407 for (const std::string& file : files.value()) {
1408 std::string full_key = "assets/" + file;
1409 std::string full_path = assets_dir;
1410 file::AppendPath(&full_path, file);
1411
1412 auto iter = merged_assets.find(full_key);
1413 if (iter == merged_assets.end()) {
1414 merged_assets.emplace(std::move(full_key),
1415 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1416 } else if (context_->IsVerbose()) {
1417 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1418 << "asset file overrides '" << full_path << "'");
1419 }
1420 }
1421 }
1422
1423 for (auto& entry : merged_assets) {
1424 uint32_t compression_flags = ArchiveEntry::kCompress;
1425 std::string extension = file::GetExtension(entry.first).to_string();
1426 if (options_.extensions_to_not_compress.count(extension) > 0) {
1427 compression_flags = 0u;
1428 }
1429
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001430 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1431 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001432 return false;
1433 }
1434 }
1435 return true;
1436 }
1437
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001438 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1439 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001440 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1441 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001442 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001443 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1444 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001445 if (!result) {
1446 return false;
1447 }
1448
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001449 ResourceFileFlattenerOptions file_flattener_options;
1450 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001451 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1452 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001453 file_flattener_options.no_auto_version = options_.no_auto_version;
1454 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001455 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001456 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1457 file_flattener_options.update_proguard_spec =
1458 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001459 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001460
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001461 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001462
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001463 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001464 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001465 return false;
1466 }
1467
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001468 if (!FlattenTable(table, options_.output_format, writer)) {
1469 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1470 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001471 }
1472 return true;
1473 }
1474
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001475 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001476 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001477 std::unique_ptr<xml::XmlResource> manifest_xml =
1478 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1479 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001480 return 1;
1481 }
1482
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001483 // First extract the Package name without modifying it (via --rename-manifest-package).
1484 if (Maybe<AppInfo> maybe_app_info =
1485 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001486 const AppInfo& app_info = maybe_app_info.value();
1487 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001488 }
1489
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001490 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1491 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001492 return 1;
1493 }
1494
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001495 Maybe<AppInfo> maybe_app_info =
1496 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001497 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001498 return 1;
1499 }
1500
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001501 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001502 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001503
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001504 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001505
1506 // Override the package ID when it is "android".
1507 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001508 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001509
1510 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001511 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001512 context_->GetDiagnostics()->Error(
1513 DiagMessage() << "package 'android' can only be built as a regular app");
1514 return 1;
1515 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001516 }
1517
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001518 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001519 return 1;
1520 }
1521
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001522 TableMergerOptions table_merger_options;
1523 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001524 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001525
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001526 if (context_->IsVerbose()) {
1527 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001528 << StringPrintf("linking package '%s' using package ID %02x",
1529 context_->GetCompilationPackage().data(),
1530 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001531 }
1532
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001533 for (const std::string& input : input_files) {
1534 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001535 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001536 return 1;
1537 }
1538 }
1539
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001540 for (const std::string& input : options_.overlay_files) {
1541 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001542 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001543 return 1;
1544 }
1545 }
1546
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001547 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001548 return 1;
1549 }
1550
Adam Lesinskib522f042017-04-21 16:57:59 -07001551 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001552 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001553 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001554 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001555 return 1;
1556 }
1557
1558 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001559 IdAssigner id_assigner(&options_.stable_id_map);
1560 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001561 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001562 return 1;
1563 }
1564
1565 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001566 if (options_.resource_id_map_path) {
1567 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001568 for (auto& type : package->types) {
1569 for (auto& entry : type->entries) {
1570 ResourceName name(package->name, type->type, entry->name);
1571 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001572 options_.stable_id_map[std::move(name)] =
1573 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001574 }
1575 }
1576 }
1577
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001578 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001579 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001580 return 1;
1581 }
1582 }
1583 } else {
1584 // Static libs are merged with other apps, and ID collisions are bad, so
1585 // verify that
1586 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001587 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001588 return 1;
1589 }
1590 }
1591
1592 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001593 context_->SetNameManglerPolicy(
1594 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595
1596 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001597 context_->GetExternalSymbols()->PrependSource(
1598 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001599
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001600 // Workaround for pre-O runtime that would treat negative resource IDs
1601 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1602 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1603 // are just identifiers.
1604 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1605 if (context_->IsVerbose()) {
1606 context_->GetDiagnostics()->Note(DiagMessage()
1607 << "enabling pre-O feature split ID rewriting");
1608 }
1609 context_->GetExternalSymbols()->SetDelegate(
1610 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1611 }
1612
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001613 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001614 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001615 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001616 return 1;
1617 }
1618
Adam Lesinskib522f042017-04-21 16:57:59 -07001619 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001620 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001621 context_->GetDiagnostics()->Warn(DiagMessage()
1622 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001623 }
1624 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001625 ProductFilter product_filter(options_.products);
1626 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001627 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001628 return 1;
1629 }
1630 }
1631
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001632 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001633 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001634 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001635 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001636 return 1;
1637 }
1638 }
1639
Adam Lesinskib522f042017-04-21 16:57:59 -07001640 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001641 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001642 context_->GetDiagnostics()->Note(DiagMessage()
1643 << "collapsing resource versions for minimum SDK "
1644 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001645 }
1646
1647 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001648 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001649 return 1;
1650 }
1651 }
1652
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001653 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001654 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001655 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001656 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001657 return 1;
1658 }
1659 }
1660
Adam Koskidc21dea2017-07-21 10:55:27 -07001661 proguard::KeepSet proguard_keep_set =
1662 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001663 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001664
Adam Lesinskib522f042017-04-21 16:57:59 -07001665 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001666 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001667 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001668 context_->GetDiagnostics()->Warn(DiagMessage()
1669 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001670 }
1671 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001672 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1673 // equal to the minSdk.
1674 options_.split_constraints =
1675 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001676
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001677 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001678 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001679 return 1;
1680 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001681 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001682
1683 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001684 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001685 auto split_constraints_iter = options_.split_constraints.begin();
1686 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001687 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001688 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1689 << "generating split with configurations '"
1690 << util::Joiner(split_constraints_iter->configs, ", ")
1691 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001692 }
1693
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001694 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001695 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001696 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 return 1;
1698 }
1699
1700 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001701 std::unique_ptr<xml::XmlResource> split_manifest =
1702 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001703
1704 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001705 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001706 context_->GetDiagnostics()->Error(DiagMessage()
1707 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001708 return 1;
1709 }
1710
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001711 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1712 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001713 return 1;
1714 }
1715
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001716 ++path_iter;
1717 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001718 }
1719 }
1720
1721 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001722 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001723 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001724 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001725 return 1;
1726 }
1727
1728 bool error = false;
1729 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001730 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001731 // (aka, which package the AndroidManifest.xml is coming from).
1732 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001733 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001734
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001735 XmlReferenceLinker manifest_linker;
1736 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1737 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001738 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001739 error = true;
1740 }
1741
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001743 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001744 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001745 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001746 }
1747
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 if (options_.generate_java_class_path) {
1749 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001750 error = true;
1751 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001752 }
1753
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001754 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001755 // PackageParser will fail if URIs are removed from
1756 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001757 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1758 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001759 error = true;
1760 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001761 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001762 } else {
1763 error = true;
1764 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001765 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001766
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001767 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001768 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001769 return 1;
1770 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001771
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001772 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1773 return 1;
1774 }
1775
1776 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001777 return 1;
1778 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001779
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001780 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001781 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001782 return 1;
1783 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001784 }
1785
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001786 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001787 return 1;
1788 }
1789
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001790 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1791 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792 return 1;
1793 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001794 return 0;
1795 }
1796
1797 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001798 LinkOptions options_;
1799 LinkContext* context_;
1800 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001801
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001802 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001803
1804 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001805 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001806
Adam Lesinski8780eb62017-10-31 17:44:39 -07001807 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001808 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001809 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001810
Adam Lesinski8780eb62017-10-31 17:44:39 -07001811 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1812 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1813
1814 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1815 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001816
1817 // The set of shared libraries being used, mapping their assigned package ID to package name.
1818 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001819};
1820
Chris Warrington820d72a2017-04-27 15:27:01 +01001821int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1822 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001823 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001824 std::vector<std::string> overlay_arg_list;
1825 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001826 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001827 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001828 Maybe<std::string> preferred_density;
1829 Maybe<std::string> product_list;
1830 bool legacy_x_flag = false;
1831 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001832 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001833 bool shared_lib = false;
1834 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001835 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001836 Maybe<std::string> stable_id_file_path;
1837 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001838 Flags flags =
1839 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001840 .RequiredFlag("-o", "Output path.", &options.output_path)
1841 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001842 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001843 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001844 .OptionalFlagList("-A",
1845 "An assets directory to include in the APK. These are unprocessed.",
1846 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001847 .OptionalFlagList("-R",
1848 "Compilation unit to link, using `overlay` semantics.\n"
1849 "The last conflicting resource given takes precedence.",
1850 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001851 .OptionalFlag("--package-id",
1852 "Specify the package ID to use for this app. Must be greater or equal to\n"
1853 "0x7f and can't be used with --static-lib or --shared-lib.",
1854 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001855 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001856 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001857 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001858 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001859 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001860 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001861 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07001862 .OptionalSwitch("--proguard-conditional-keep-rules",
1863 "Generate conditional Proguard keep rules.",
1864 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001865 .OptionalSwitch("--no-auto-version",
1866 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001867 &options.no_auto_version)
1868 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001869 "Disables automatic versioning of vector drawables. Use this only\n"
1870 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001871 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001872 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001873 "Disables automatic versioning of transition resources. Use this only\n"
1874 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001875 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001877 "Disables automatic deduping of resources with\n"
1878 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001879 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001880 .OptionalSwitch("--enable-sparse-encoding",
1881 "Enables encoding sparse entries using a binary search tree.\n"
1882 "This decreases APK size at the cost of resource retrieval performance.",
1883 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001884 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001885 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001886 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001887 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001888 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001889 "Comma separated list of configurations to include. The default\n"
1890 "is all configurations.",
1891 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001892 .OptionalFlag("--preferred-density",
1893 "Selects the closest matching density and strips out all others.",
1894 &preferred_density)
1895 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001896 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001897 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 &options.output_to_directory)
1899 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001900 "Removes XML namespace prefix and URI information from\n"
1901 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001902 &options.no_xml_namespaces)
1903 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001904 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001905 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001906 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001907 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001908 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001909 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001910 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1911 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001912 &options.manifest_fixer_options.version_code_default)
1913 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001914 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001915 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001916 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1917 &shared_lib)
1918 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001919 .OptionalSwitch("--proto-format",
1920 "Generates compiled resources in Protobuf format.\n"
1921 "Suitable as input to the bundle tool for generating an App Bundle.",
1922 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001923 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001924 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001925 &options.no_static_lib_packages)
1926 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001927 "Generates R.java without the final modifier. This is implied when\n"
1928 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001930 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001931 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001932 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001933 "Emit a file at the given path with a list of name to ID mappings,\n"
1934 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001935 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001936 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001937 "Package name to use when generating R.java for private symbols.\n"
1938 "If not specified, public and private symbols will use the application's\n"
1939 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001941 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001942 &options.custom_java_package)
1943 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001944 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001945 &extra_java_packages)
1946 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001947 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001948 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001949 .OptionalFlag("--output-text-symbols",
1950 "Generates a text file containing the resource symbols of the R class in\n"
1951 "the specified folder.",
1952 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001953 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001954 "Allows the addition of new resources in overlays without\n"
1955 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001956 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001957 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001958 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001959 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001960 "Changes the name of the target package for instrumentation. Most useful\n"
1961 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001962 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001963 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001964 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001965 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001966 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07001967 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
1968 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001969 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001970 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001971
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001972 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001973 return 1;
1974 }
1975
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001976 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001977 std::vector<std::string> arg_list;
1978 for (const std::string& arg : flags.GetArgs()) {
1979 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001980 const std::string path = arg.substr(1, arg.size() - 1);
1981 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001982 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
1983 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001984 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001985 }
1986 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001987 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001988 }
1989 }
1990
1991 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001992 for (const std::string& arg : overlay_arg_list) {
1993 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001994 const std::string path = arg.substr(1, arg.size() - 1);
1995 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
1997 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001998 return 1;
1999 }
2000 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002001 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002002 }
2003 }
2004
2005 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002006 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002007 }
2008
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002009 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2010 context.GetDiagnostics()->Error(
2011 DiagMessage()
2012 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002013 return 1;
2014 }
2015
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002016 // The default build type.
2017 context.SetPackageType(PackageType::kApp);
2018 context.SetPackageId(kAppPackageId);
2019
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002020 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002021 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002022 context.SetPackageId(0x00);
2023 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002024 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002025 options.output_format = OutputFormat::kProto;
2026 } else if (proto_format) {
2027 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002028 }
2029
2030 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002031 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002032 context.GetDiagnostics()->Error(
2033 DiagMessage() << "can't specify --package-id when not building a regular app");
2034 return 1;
2035 }
2036
2037 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2038 if (!maybe_package_id_int) {
2039 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2040 << "' is not a valid integer");
2041 return 1;
2042 }
2043
2044 const uint32_t package_id_int = maybe_package_id_int.value();
2045 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2046 context.GetDiagnostics()->Error(
2047 DiagMessage() << StringPrintf(
2048 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2049 return 1;
2050 }
2051 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2052 }
2053
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002054 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002055 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002056 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002057 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002058 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002059 }
2060 }
2061
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002062 if (product_list) {
2063 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002065 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002066 }
2067 }
2068 }
2069
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002070 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002071 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002072 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2073 if (filter == nullptr) {
2074 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002075 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002076 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002077 }
2078
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002079 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002080 Maybe<uint16_t> density =
2081 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2082 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002083 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002084 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002085 options.table_splitter_options.preferred_densities.push_back(density.value());
2086 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002087
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002088 // Parse the split parameters.
2089 for (const std::string& split_arg : split_args) {
2090 options.split_paths.push_back({});
2091 options.split_constraints.push_back({});
2092 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2093 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002095 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002096 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002097
Adam Lesinskib522f042017-04-21 16:57:59 -07002098 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002099 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2100 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002101 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002102 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002103 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002104
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002105 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002106 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2108 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2109 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2110 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2111
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002112 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002113 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002114 options.no_auto_version = true;
2115 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002116 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002117 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002118
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002119 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002121}
2122
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123} // namespace aapt