blob: 66b5a7af36779bf1f2ded192c596bbc7a1b28f68 [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;
Adam Lesinski490595a2017-11-07 17:08:07 -0800798 } else if (entry.first == kAppPackageId) {
799 // Capture the included base feature package.
800 included_feature_base_ = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800801 }
802 }
803
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700804 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700805 return true;
806 }
807
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800808 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700809 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800810 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
811 if (manifest_el == nullptr) {
812 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700813 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800814
815 AppInfo app_info;
816
817 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
818 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
819 return {};
820 }
821
822 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
823 if (!package_attr) {
824 diag->Error(DiagMessage(xml_res->file.source)
825 << "<manifest> must have a 'package' attribute");
826 return {};
827 }
828 app_info.package = package_attr->value;
829
830 if (xml::Attribute* version_code_attr =
831 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
832 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
833 if (!maybe_code) {
834 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
835 << "invalid android:versionCode '" << version_code_attr->value << "'");
836 return {};
837 }
838 app_info.version_code = maybe_code.value();
839 }
840
841 if (xml::Attribute* revision_code_attr =
842 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
843 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
844 if (!maybe_code) {
845 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
846 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
847 return {};
848 }
849 app_info.revision_code = maybe_code.value();
850 }
851
852 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
853 if (!split_name_attr->value.empty()) {
854 app_info.split_name = split_name_attr->value;
855 }
856 }
857
858 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
859 if (xml::Attribute* min_sdk =
860 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700861 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800862 }
863 }
864 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700865 }
866
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700867 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
868 // Postcondition: ResourceTable has only one package left. All others are
869 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700870 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700871 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700872 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
873 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700874 };
875
876 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700877 for (const auto& package : final_table_.packages) {
878 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700879 // We have a package that is not related to the one we're building!
880 for (const auto& type : package->types) {
881 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700882 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700883
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700884 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700885 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700886 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700887 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
888 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
889 << "generated id '" << res_name
890 << "' for external package '" << package->name
891 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700892 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700893 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
894 << "defined resource '" << res_name
895 << "' for external package '" << package->name
896 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700897 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700898 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700899 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700900 }
901 }
902 }
903 }
904
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700905 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
906 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700907 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700908 return !error;
909 }
910
911 /**
912 * Returns true if no IDs have been set, false otherwise.
913 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700914 bool VerifyNoIdsSet() {
915 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700916 for (const auto& type : package->types) {
917 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800918 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
919 << StringPrintf("%02x", type->id.value())
920 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700921 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700922 }
923
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700924 for (const auto& entry : type->entries) {
925 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700926 ResourceNameRef res_name(package->name, type->type, entry->name);
927 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800928 DiagMessage() << "entry " << res_name << " has ID "
929 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700930 return false;
931 }
932 }
933 }
934 }
935 return true;
936 }
937
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700938 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
939 if (options_.output_to_directory) {
940 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700941 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700942 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700943 }
944 }
945
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700946 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
947 switch (format) {
948 case OutputFormat::kApk: {
949 BigBuffer buffer(1024);
950 TableFlattener flattener(options_.table_flattener_options, &buffer);
951 if (!flattener.Consume(context_, table)) {
952 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
953 return false;
954 }
955
956 io::BigBufferInputStream input_stream(&buffer);
957 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
958 ArchiveEntry::kAlign, writer);
959 } break;
960
961 case OutputFormat::kProto: {
962 pb::ResourceTable pb_table;
963 SerializeTableToPb(*table, &pb_table);
964 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
965 ArchiveEntry::kCompress, writer);
966 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700967 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700968 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700969 }
970
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700971 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700972 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700973 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700974 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700975 return true;
976 }
977
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700978 std::string out_path = options_.generate_java_class_path.value();
979 file::AppendPath(&out_path, file::PackageToPath(out_package));
980 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700981 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
982 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700983 return false;
984 }
985
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700986 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700987
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700988 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700989 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700990 context_->GetDiagnostics()->Error(DiagMessage()
991 << "failed writing to '" << out_path
992 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700993 return false;
994 }
995
Adam Lesinski418763f2017-04-11 17:36:53 -0700996 std::unique_ptr<std::ofstream> fout_text;
997 if (out_text_symbols_path) {
998 fout_text =
999 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
1000 if (!*fout_text) {
1001 context_->GetDiagnostics()->Error(
1002 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
1003 << "': " << android::base::SystemErrorCodeToString(errno));
1004 return false;
1005 }
1006 }
1007
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001008 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -07001009 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -07001010 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001011 return false;
1012 }
1013
1014 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001015 context_->GetDiagnostics()->Error(DiagMessage()
1016 << "failed writing to '" << out_path
1017 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001018 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001019 }
1020 return true;
1021 }
1022
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001023 bool GenerateJavaClasses() {
1024 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1025 std::vector<std::string> packages_to_callback;
1026
1027 JavaClassGeneratorOptions template_options;
1028 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1029 template_options.javadoc_annotations = options_.javadoc_annotations;
1030
1031 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1032 template_options.use_final = false;
1033 }
1034
1035 if (context_->GetPackageType() == PackageType::kSharedLib) {
1036 template_options.use_final = false;
1037 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1038 }
1039
1040 const StringPiece actual_package = context_->GetCompilationPackage();
1041 StringPiece output_package = context_->GetCompilationPackage();
1042 if (options_.custom_java_package) {
1043 // Override the output java package to the custom one.
1044 output_package = options_.custom_java_package.value();
1045 }
1046
1047 // Generate the private symbols if required.
1048 if (options_.private_symbols) {
1049 packages_to_callback.push_back(options_.private_symbols.value());
1050
1051 // If we defined a private symbols package, we only emit Public symbols
1052 // to the original package, and private and public symbols to the private package.
1053 JavaClassGeneratorOptions options = template_options;
1054 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1055 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1056 options)) {
1057 return false;
1058 }
1059 }
1060
1061 // Generate copies of the original package R class but with different package names.
1062 // This is to support non-namespaced builds.
1063 for (const std::string& extra_package : options_.extra_java_packages) {
1064 packages_to_callback.push_back(extra_package);
1065
1066 JavaClassGeneratorOptions options = template_options;
1067 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1068 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1069 return false;
1070 }
1071 }
1072
1073 // Generate R classes for each package that was merged (static library).
1074 // Use the actual package's resources only.
1075 for (const std::string& package : table_merger_->merged_packages()) {
1076 packages_to_callback.push_back(package);
1077
1078 JavaClassGeneratorOptions options = template_options;
1079 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1080 if (!WriteJavaFile(&final_table_, package, package, options)) {
1081 return false;
1082 }
1083 }
1084
1085 // Generate the main public R class.
1086 JavaClassGeneratorOptions options = template_options;
1087
1088 // Only generate public symbols if we have a private package.
1089 if (options_.private_symbols) {
1090 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1091 }
1092
1093 if (options.rewrite_callback_options) {
1094 options.rewrite_callback_options.value().packages_to_callback =
1095 std::move(packages_to_callback);
1096 }
1097
1098 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1099 options_.generate_text_symbols_path)) {
1100 return false;
1101 }
1102
1103 return true;
1104 }
1105
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001106 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1107 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001108 return true;
1109 }
1110
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001111 std::unique_ptr<ClassDefinition> manifest_class =
1112 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001113
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001114 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001115 // Something bad happened, but we already logged it, so exit.
1116 return false;
1117 }
1118
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001119 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001120 // Empty Manifest class, no need to generate it.
1121 return true;
1122 }
1123
1124 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001125 for (const std::string& annotation : options_.javadoc_annotations) {
1126 std::string proper_annotation = "@";
1127 proper_annotation += annotation;
1128 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001129 }
1130
Adam Lesinski0d81f702017-06-27 15:51:09 -07001131 const std::string package_utf8 =
1132 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001133
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001134 std::string out_path = options_.generate_java_class_path.value();
1135 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001136
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001137 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001138 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1139 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 return false;
1141 }
1142
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001143 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001144
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001145 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001146 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001147 context_->GetDiagnostics()->Error(DiagMessage()
1148 << "failed writing to '" << out_path
1149 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001150 return false;
1151 }
1152
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001153 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1154 context_->GetDiagnostics()->Error(DiagMessage()
1155 << "failed writing to '" << out_path
1156 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001157 return false;
1158 }
1159 return true;
1160 }
1161
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001162 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001163 if (!out) {
1164 return true;
1165 }
1166
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001167 const std::string& out_path = out.value();
1168 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001169 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001170 context_->GetDiagnostics()->Error(DiagMessage()
1171 << "failed to open '" << out_path
1172 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001173 return false;
1174 }
1175
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001176 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001177 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001178 context_->GetDiagnostics()->Error(DiagMessage()
1179 << "failed writing to '" << out_path
1180 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001181 return false;
1182 }
1183 return true;
1184 }
1185
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001186 bool MergeStaticLibrary(const std::string& input, bool override) {
1187 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001188 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001189 }
1190
Adam Lesinski8780eb62017-10-31 17:44:39 -07001191 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1192 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001193 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001194 return false;
1195 }
1196
Adam Lesinski8780eb62017-10-31 17:44:39 -07001197 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001198 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001199 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001200 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001201 return false;
1202 }
1203
1204 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001205 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001206 // Merge all resources as if they were in the compilation package. This is the old behavior
1207 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001208
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001209 // Add the package to the set of --extra-packages so we emit an R.java for each library
1210 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001211 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001212 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001213 }
1214
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001215 // Clear the package name, so as to make the resources look like they are coming from the
1216 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001217 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001218 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001219
1220 } else {
1221 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001222 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001223 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001224 }
1225
1226 if (!result) {
1227 return false;
1228 }
1229
1230 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001231 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001232 return true;
1233 }
1234
Adam Lesinski00451162017-10-03 07:44:08 -07001235 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001236 if (context_->IsVerbose()) {
Adam Lesinski00451162017-10-03 07:44:08 -07001237 context_->GetDiagnostics()->Note(DiagMessage()
1238 << "merging '" << compiled_file.name
1239 << "' from compiled file " << compiled_file.source);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001240 }
1241
Adam Lesinski00451162017-10-03 07:44:08 -07001242 if (!table_merger_->MergeFile(compiled_file, override, file)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001243 return false;
1244 }
1245
1246 // Add the exports of this file to the table.
Adam Lesinski00451162017-10-03 07:44:08 -07001247 for (const SourcedResourceName& exported_symbol : compiled_file.exported_symbols) {
1248 ResourceName res_name = exported_symbol.name;
1249 if (res_name.package.empty()) {
1250 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001251 }
1252
Adam Lesinski00451162017-10-03 07:44:08 -07001253 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001254 if (mangled_name) {
1255 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001256 }
1257
1258 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski00451162017-10-03 07:44:08 -07001259 id->SetSource(compiled_file.source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001260 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001261 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1262 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001263 if (!result) {
1264 return false;
1265 }
1266 }
1267 return true;
1268 }
1269
Adam Lesinski00451162017-10-03 07:44:08 -07001270 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1271 // If override is true, conflicting resources are allowed to override each other, in order of last
1272 // seen.
1273 // An io::IFileCollection is created from the ZIP file and added to the set of
1274 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001275 bool MergeArchive(const std::string& input, bool override) {
1276 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001277 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001278 }
1279
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001280 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001282 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001283 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001284 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001285 return false;
1286 }
1287
1288 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001289 for (auto iter = collection->Iterator(); iter->HasNext();) {
1290 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001291 error = true;
1292 }
1293 }
1294
1295 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001296 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001297 return !error;
1298 }
1299
Adam Lesinski00451162017-10-03 07:44:08 -07001300 // Takes a path to load and merge into the master ResourceTable. If override is true,
1301 // conflicting resources are allowed to override each other, in order of last seen.
1302 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1303 // as ZIP archive and the files within are merged individually.
1304 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001305 bool MergePath(const std::string& path, bool override) {
1306 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1307 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1308 return MergeArchive(path, override);
1309 } else if (util::EndsWith(path, ".apk")) {
1310 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001311 }
1312
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001313 io::IFile* file = file_collection_->InsertFile(path);
1314 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001315 }
1316
Adam Lesinski00451162017-10-03 07:44:08 -07001317 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1318 // If override is true, conflicting resources are allowed to override each other, in order of last
1319 // seen.
1320 // All other file types are ignored. This is because these files could be coming from a zip,
1321 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001322 bool MergeFile(io::IFile* file, bool override) {
1323 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001324
Adam Lesinski00451162017-10-03 07:44:08 -07001325 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001326 // Since AAPT compiles these file types and appends .flat to them, seeing
1327 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001328 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1329 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1330 << " file passed as argument. Must be "
1331 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001332 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001333 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1334 if (context_->IsVerbose()) {
1335 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1336 return true;
1337 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001338 }
1339
Adam Lesinski00451162017-10-03 07:44:08 -07001340 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1341 if (input_stream == nullptr) {
1342 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1343 return false;
1344 }
1345
1346 if (input_stream->HadError()) {
1347 context_->GetDiagnostics()->Error(DiagMessage(src)
1348 << "failed to open file: " << input_stream->GetError());
1349 return false;
1350 }
1351
1352 ContainerReaderEntry* entry;
1353 ContainerReader reader(input_stream.get());
1354 while ((entry = reader.Next()) != nullptr) {
1355 if (entry->Type() == ContainerEntryType::kResTable) {
1356 pb::ResourceTable pb_table;
1357 if (!entry->GetResTable(&pb_table)) {
1358 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1359 << entry->GetError());
1360 return false;
1361 }
1362
1363 ResourceTable table;
1364 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001365 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001366 context_->GetDiagnostics()->Error(DiagMessage(src)
1367 << "failed to deserialize resource table: " << error);
1368 return false;
1369 }
1370
1371 if (!table_merger_->Merge(src, &table, override)) {
1372 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1373 return false;
1374 }
1375 } else if (entry->Type() == ContainerEntryType::kResFile) {
1376 pb::internal::CompiledFile pb_compiled_file;
1377 off64_t offset;
1378 size_t len;
1379 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1380 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1381 << entry->GetError());
1382 return false;
1383 }
1384
1385 ResourceFile resource_file;
1386 std::string error;
1387 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1388 context_->GetDiagnostics()->Error(DiagMessage(src)
1389 << "failed to read compiled header: " << error);
1390 return false;
1391 }
1392
1393 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1394 return false;
1395 }
1396 }
1397 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398 return true;
1399 }
1400
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001401 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1402 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1403 for (const std::string& assets_dir : options_.assets_dirs) {
1404 Maybe<std::vector<std::string>> files =
1405 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1406 if (!files) {
1407 return false;
1408 }
1409
1410 for (const std::string& file : files.value()) {
1411 std::string full_key = "assets/" + file;
1412 std::string full_path = assets_dir;
1413 file::AppendPath(&full_path, file);
1414
1415 auto iter = merged_assets.find(full_key);
1416 if (iter == merged_assets.end()) {
1417 merged_assets.emplace(std::move(full_key),
1418 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1419 } else if (context_->IsVerbose()) {
1420 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1421 << "asset file overrides '" << full_path << "'");
1422 }
1423 }
1424 }
1425
1426 for (auto& entry : merged_assets) {
1427 uint32_t compression_flags = ArchiveEntry::kCompress;
1428 std::string extension = file::GetExtension(entry.first).to_string();
1429 if (options_.extensions_to_not_compress.count(extension) > 0) {
1430 compression_flags = 0u;
1431 }
1432
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001433 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1434 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001435 return false;
1436 }
1437 }
1438 return true;
1439 }
1440
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001441 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1442 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001443 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1444 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001445 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001446 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1447 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001448 if (!result) {
1449 return false;
1450 }
1451
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001452 ResourceFileFlattenerOptions file_flattener_options;
1453 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001454 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1455 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001456 file_flattener_options.no_auto_version = options_.no_auto_version;
1457 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001458 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001459 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1460 file_flattener_options.update_proguard_spec =
1461 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001462 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001463
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001464 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001465
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001466 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001467 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001468 return false;
1469 }
1470
Adam Lesinski490595a2017-11-07 17:08:07 -08001471 // Hack to fix b/68820737.
1472 // We need to modify the ResourceTable's package name, but that should NOT affect
1473 // anything else being generated, which includes the Java classes.
1474 // If required, the package name is modifed before flattening, and then modified back
1475 // to its original name.
1476 ResourceTablePackage* package_to_rewrite = nullptr;
1477 if (context_->GetPackageId() > kAppPackageId &&
1478 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1479 // The base APK is included, and this is a feature split. If the base package is
1480 // the same as this package, then we are building an old style Android Instant Apps feature
1481 // split and must apply this workaround to avoid requiring namespaces support.
1482 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1483 if (package_to_rewrite != nullptr) {
1484 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1485
1486 std::string new_package_name =
1487 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1488 app_info_.split_name.value_or_default("feature").c_str());
1489
1490 if (context_->IsVerbose()) {
1491 context_->GetDiagnostics()->Note(
1492 DiagMessage() << "rewriting resource package name for feature split to '"
1493 << new_package_name << "'");
1494 }
1495 package_to_rewrite->name = new_package_name;
1496 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001497 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001498
1499 bool success = FlattenTable(table, options_.output_format, writer);
1500
1501 if (package_to_rewrite != nullptr) {
1502 // Change the name back.
1503 package_to_rewrite->name = context_->GetCompilationPackage();
1504 if (package_to_rewrite->id) {
1505 table->included_packages_.erase(package_to_rewrite->id.value());
1506 }
1507 }
1508
1509 if (!success) {
1510 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1511 }
1512 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001513 }
1514
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001515 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001516 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001517 std::unique_ptr<xml::XmlResource> manifest_xml =
1518 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1519 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001520 return 1;
1521 }
1522
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001523 // First extract the Package name without modifying it (via --rename-manifest-package).
1524 if (Maybe<AppInfo> maybe_app_info =
1525 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001526 const AppInfo& app_info = maybe_app_info.value();
1527 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001528 }
1529
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001530 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1531 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001532 return 1;
1533 }
1534
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001535 Maybe<AppInfo> maybe_app_info =
1536 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001537 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001538 return 1;
1539 }
1540
Adam Lesinski490595a2017-11-07 17:08:07 -08001541 app_info_ = maybe_app_info.value();
1542 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001543
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001544 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001545
1546 // Override the package ID when it is "android".
1547 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001548 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001549
1550 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001551 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001552 context_->GetDiagnostics()->Error(
1553 DiagMessage() << "package 'android' can only be built as a regular app");
1554 return 1;
1555 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001556 }
1557
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001558 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001559 return 1;
1560 }
1561
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001562 TableMergerOptions table_merger_options;
1563 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001564 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001565
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001566 if (context_->IsVerbose()) {
1567 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001568 << StringPrintf("linking package '%s' using package ID %02x",
1569 context_->GetCompilationPackage().data(),
1570 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001571 }
1572
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001573 for (const std::string& input : input_files) {
1574 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001575 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001576 return 1;
1577 }
1578 }
1579
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001580 for (const std::string& input : options_.overlay_files) {
1581 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001582 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001583 return 1;
1584 }
1585 }
1586
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001587 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001588 return 1;
1589 }
1590
Adam Lesinskib522f042017-04-21 16:57:59 -07001591 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001592 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001593 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001594 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595 return 1;
1596 }
1597
1598 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001599 IdAssigner id_assigner(&options_.stable_id_map);
1600 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001601 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001602 return 1;
1603 }
1604
1605 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001606 if (options_.resource_id_map_path) {
1607 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001608 for (auto& type : package->types) {
1609 for (auto& entry : type->entries) {
1610 ResourceName name(package->name, type->type, entry->name);
1611 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001612 options_.stable_id_map[std::move(name)] =
1613 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001614 }
1615 }
1616 }
1617
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001618 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001619 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001620 return 1;
1621 }
1622 }
1623 } else {
1624 // Static libs are merged with other apps, and ID collisions are bad, so
1625 // verify that
1626 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001627 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001628 return 1;
1629 }
1630 }
1631
1632 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001633 context_->SetNameManglerPolicy(
1634 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001635
1636 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001637 context_->GetExternalSymbols()->PrependSource(
1638 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001639
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001640 // Workaround for pre-O runtime that would treat negative resource IDs
1641 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1642 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1643 // are just identifiers.
1644 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1645 if (context_->IsVerbose()) {
1646 context_->GetDiagnostics()->Note(DiagMessage()
1647 << "enabling pre-O feature split ID rewriting");
1648 }
1649 context_->GetExternalSymbols()->SetDelegate(
1650 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1651 }
1652
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001653 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001654 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001655 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001656 return 1;
1657 }
1658
Adam Lesinskib522f042017-04-21 16:57:59 -07001659 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001660 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001661 context_->GetDiagnostics()->Warn(DiagMessage()
1662 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001663 }
1664 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001665 ProductFilter product_filter(options_.products);
1666 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001667 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001668 return 1;
1669 }
1670 }
1671
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001672 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001673 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001674 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001675 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001676 return 1;
1677 }
1678 }
1679
Adam Lesinskib522f042017-04-21 16:57:59 -07001680 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001681 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001682 context_->GetDiagnostics()->Note(DiagMessage()
1683 << "collapsing resource versions for minimum SDK "
1684 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001685 }
1686
1687 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001688 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001689 return 1;
1690 }
1691 }
1692
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001693 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001694 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001695 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001696 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 return 1;
1698 }
1699 }
1700
Adam Koskidc21dea2017-07-21 10:55:27 -07001701 proguard::KeepSet proguard_keep_set =
1702 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001703 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001704
Adam Lesinskib522f042017-04-21 16:57:59 -07001705 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001706 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001707 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001708 context_->GetDiagnostics()->Warn(DiagMessage()
1709 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001710 }
1711 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001712 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1713 // equal to the minSdk.
1714 options_.split_constraints =
1715 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001716
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001717 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001718 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001719 return 1;
1720 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001721 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001722
1723 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001724 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001725 auto split_constraints_iter = options_.split_constraints.begin();
1726 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001727 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001728 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1729 << "generating split with configurations '"
1730 << util::Joiner(split_constraints_iter->configs, ", ")
1731 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001732 }
1733
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001734 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001735 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001736 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001737 return 1;
1738 }
1739
1740 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001741 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001742 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743
1744 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001745 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001746 context_->GetDiagnostics()->Error(DiagMessage()
1747 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001748 return 1;
1749 }
1750
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001751 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1752 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 return 1;
1754 }
1755
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001756 ++path_iter;
1757 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001758 }
1759 }
1760
1761 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001762 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001763 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001764 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001765 return 1;
1766 }
1767
1768 bool error = false;
1769 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001770 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001771 // (aka, which package the AndroidManifest.xml is coming from).
1772 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001773 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001774
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001775 XmlReferenceLinker manifest_linker;
1776 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1777 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001778 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001779 error = true;
1780 }
1781
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001782 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001783 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001784 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001785 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001786 }
1787
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001788 if (options_.generate_java_class_path) {
1789 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001790 error = true;
1791 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001792 }
1793
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001794 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795 // PackageParser will fail if URIs are removed from
1796 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001797 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1798 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001799 error = true;
1800 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001801 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001802 } else {
1803 error = true;
1804 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001805 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001806
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001807 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001808 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001809 return 1;
1810 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001811
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001812 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1813 return 1;
1814 }
1815
1816 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817 return 1;
1818 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001819
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001820 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001821 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001822 return 1;
1823 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824 }
1825
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001826 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001827 return 1;
1828 }
1829
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001830 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1831 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001832 return 1;
1833 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001834 return 0;
1835 }
1836
1837 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001838 LinkOptions options_;
1839 LinkContext* context_;
1840 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001841
Adam Lesinski490595a2017-11-07 17:08:07 -08001842 AppInfo app_info_;
1843
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001844 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845
1846 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848
Adam Lesinski8780eb62017-10-31 17:44:39 -07001849 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001850 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001851 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852
Adam Lesinski8780eb62017-10-31 17:44:39 -07001853 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1854 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1855
1856 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1857 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001858
1859 // The set of shared libraries being used, mapping their assigned package ID to package name.
1860 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08001861
1862 // The package name of the base application, if it is included.
1863 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001864};
1865
Chris Warrington820d72a2017-04-27 15:27:01 +01001866int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1867 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001868 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 std::vector<std::string> overlay_arg_list;
1870 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001871 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001872 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001873 Maybe<std::string> preferred_density;
1874 Maybe<std::string> product_list;
1875 bool legacy_x_flag = false;
1876 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001877 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001878 bool shared_lib = false;
1879 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001880 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001881 Maybe<std::string> stable_id_file_path;
1882 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001883 Flags flags =
1884 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001885 .RequiredFlag("-o", "Output path.", &options.output_path)
1886 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001887 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001888 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001889 .OptionalFlagList("-A",
1890 "An assets directory to include in the APK. These are unprocessed.",
1891 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001892 .OptionalFlagList("-R",
1893 "Compilation unit to link, using `overlay` semantics.\n"
1894 "The last conflicting resource given takes precedence.",
1895 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001896 .OptionalFlag("--package-id",
1897 "Specify the package ID to use for this app. Must be greater or equal to\n"
1898 "0x7f and can't be used with --static-lib or --shared-lib.",
1899 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001900 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001901 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001902 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001903 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001904 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001906 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07001907 .OptionalSwitch("--proguard-conditional-keep-rules",
1908 "Generate conditional Proguard keep rules.",
1909 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001910 .OptionalSwitch("--no-auto-version",
1911 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001912 &options.no_auto_version)
1913 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001914 "Disables automatic versioning of vector drawables. Use this only\n"
1915 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001916 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001917 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001918 "Disables automatic versioning of transition resources. Use this only\n"
1919 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001920 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001921 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001922 "Disables automatic deduping of resources with\n"
1923 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001924 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001925 .OptionalSwitch("--enable-sparse-encoding",
1926 "Enables encoding sparse entries using a binary search tree.\n"
1927 "This decreases APK size at the cost of resource retrieval performance.",
1928 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001929 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001930 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001932 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001933 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001934 "Comma separated list of configurations to include. The default\n"
1935 "is all configurations.",
1936 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001937 .OptionalFlag("--preferred-density",
1938 "Selects the closest matching density and strips out all others.",
1939 &preferred_density)
1940 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001941 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001942 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 &options.output_to_directory)
1944 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001945 "Removes XML namespace prefix and URI information from\n"
1946 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001947 &options.no_xml_namespaces)
1948 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001949 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001950 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001951 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001952 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001953 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001954 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001955 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1956 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001957 &options.manifest_fixer_options.version_code_default)
1958 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001959 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001960 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001961 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1962 &shared_lib)
1963 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001964 .OptionalSwitch("--proto-format",
1965 "Generates compiled resources in Protobuf format.\n"
1966 "Suitable as input to the bundle tool for generating an App Bundle.",
1967 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001969 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001970 &options.no_static_lib_packages)
1971 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001972 "Generates R.java without the final modifier. This is implied when\n"
1973 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001974 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001975 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001976 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001977 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001978 "Emit a file at the given path with a list of name to ID mappings,\n"
1979 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001980 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001981 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001982 "Package name to use when generating R.java for private symbols.\n"
1983 "If not specified, public and private symbols will use the application's\n"
1984 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001986 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001987 &options.custom_java_package)
1988 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001989 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001990 &extra_java_packages)
1991 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001992 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001993 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001994 .OptionalFlag("--output-text-symbols",
1995 "Generates a text file containing the resource symbols of the R class in\n"
1996 "the specified folder.",
1997 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001998 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001999 "Allows the addition of new resources in overlays without\n"
2000 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002001 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002002 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002003 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002004 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002005 "Changes the name of the target package for instrumentation. Most useful\n"
2006 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002007 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002008 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002009 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002010 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002011 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002012 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2013 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002014 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002015 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002016
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002017 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002018 return 1;
2019 }
2020
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002021 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002022 std::vector<std::string> arg_list;
2023 for (const std::string& arg : flags.GetArgs()) {
2024 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002025 const std::string path = arg.substr(1, arg.size() - 1);
2026 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002027 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2028 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002029 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030 }
2031 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002032 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002033 }
2034 }
2035
2036 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002037 for (const std::string& arg : overlay_arg_list) {
2038 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002039 const std::string path = arg.substr(1, arg.size() - 1);
2040 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002041 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2042 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002043 return 1;
2044 }
2045 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002046 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002047 }
2048 }
2049
2050 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002051 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002052 }
2053
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002054 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2055 context.GetDiagnostics()->Error(
2056 DiagMessage()
2057 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002058 return 1;
2059 }
2060
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002061 // The default build type.
2062 context.SetPackageType(PackageType::kApp);
2063 context.SetPackageId(kAppPackageId);
2064
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002065 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002066 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002067 context.SetPackageId(0x00);
2068 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002069 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002070 options.output_format = OutputFormat::kProto;
2071 } else if (proto_format) {
2072 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002073 }
2074
2075 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002076 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002077 context.GetDiagnostics()->Error(
2078 DiagMessage() << "can't specify --package-id when not building a regular app");
2079 return 1;
2080 }
2081
2082 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2083 if (!maybe_package_id_int) {
2084 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2085 << "' is not a valid integer");
2086 return 1;
2087 }
2088
2089 const uint32_t package_id_int = maybe_package_id_int.value();
2090 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2091 context.GetDiagnostics()->Error(
2092 DiagMessage() << StringPrintf(
2093 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2094 return 1;
2095 }
2096 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2097 }
2098
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002099 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002100 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002101 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002102 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002103 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002104 }
2105 }
2106
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002107 if (product_list) {
2108 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002109 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002110 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002111 }
2112 }
2113 }
2114
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002115 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002116 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002117 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2118 if (filter == nullptr) {
2119 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002120 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002121 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002122 }
2123
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002124 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002125 Maybe<uint16_t> density =
2126 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2127 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002128 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002129 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002130 options.table_splitter_options.preferred_densities.push_back(density.value());
2131 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002132
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002133 // Parse the split parameters.
2134 for (const std::string& split_arg : split_args) {
2135 options.split_paths.push_back({});
2136 options.split_constraints.push_back({});
2137 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2138 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002139 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002140 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002141 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002142
Adam Lesinskib522f042017-04-21 16:57:59 -07002143 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002144 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2145 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002146 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002147 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002148 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002149
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002150 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002151 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002152 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2153 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2154 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2155 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2156
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002157 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002158 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002159 options.no_auto_version = true;
2160 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002161 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002162 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002163
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002164 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002165 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002166}
2167
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002168} // namespace aapt