blob: 26edb762fe63f6446bbc6aef6028ee7bb5d61e1b [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;
96 bool generate_non_final_ids = false;
97 std::vector<std::string> javadoc_annotations;
98 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -070099
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700100 // Optimizations/features.
101 bool no_auto_version = false;
102 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900103 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 bool no_resource_deduping = false;
105 bool no_xml_namespaces = false;
106 bool do_not_compress_anything = false;
107 std::unordered_set<std::string> extensions_to_not_compress;
108
109 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700110 bool no_static_lib_packages = false;
111
112 // AndroidManifest.xml massaging options.
113 ManifestFixerOptions manifest_fixer_options;
114
115 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700116 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700117
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800118 // Flattening options.
119 TableFlattenerOptions table_flattener_options;
120
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700122 TableSplitterOptions table_splitter_options;
123 std::vector<SplitConstraints> split_constraints;
124 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700125
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700127 std::unordered_map<ResourceName, ResourceId> stable_id_map;
128 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700129};
130
Adam Lesinski64587af2016-02-18 18:33:06 -0800131class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700132 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100133 LinkContext(IDiagnostics* diagnostics)
134 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700135 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700136
Adam Lesinskib522f042017-04-21 16:57:59 -0700137 PackageType GetPackageType() override {
138 return package_type_;
139 }
140
141 void SetPackageType(PackageType type) {
142 package_type_ = type;
143 }
144
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700145 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100146 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700147 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700148
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 NameMangler* GetNameMangler() override {
150 return &name_mangler_;
151 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700152
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700153 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
154 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700155 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800156
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700157 const std::string& GetCompilationPackage() override {
158 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700159 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700160
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700161 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800162 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700163 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800164
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700165 uint8_t GetPackageId() override {
166 return package_id_;
167 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700168
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700169 void SetPackageId(uint8_t id) {
170 package_id_ = id;
171 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800172
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700173 SymbolTable* GetExternalSymbols() override {
174 return &symbols_;
175 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800176
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700177 bool IsVerbose() override {
178 return verbose_;
179 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800180
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700181 void SetVerbose(bool val) {
182 verbose_ = val;
183 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800184
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700185 int GetMinSdkVersion() override {
186 return min_sdk_version_;
187 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700188
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700189 void SetMinSdkVersion(int minSdk) {
190 min_sdk_version_ = minSdk;
191 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700192
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700193 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700194 DISALLOW_COPY_AND_ASSIGN(LinkContext);
195
Adam Lesinskib522f042017-04-21 16:57:59 -0700196 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100197 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700198 NameMangler name_mangler_;
199 std::string compilation_package_;
200 uint8_t package_id_ = 0x0;
201 SymbolTable symbols_;
202 bool verbose_ = false;
203 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700204};
205
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700206// A custom delegate that generates compatible pre-O IDs for use with feature splits.
207// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
208// is interpreted as a negative number. Some verification was wrongly assuming negative values
209// were invalid.
210//
211// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
212// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
213// an overlap exists.
214class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
215 public:
216 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
217 }
218
219 virtual ~FeatureSplitSymbolTableDelegate() = default;
220
221 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
222 const ResourceName& name,
223 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
224 std::unique_ptr<SymbolTable::Symbol> symbol =
225 DefaultSymbolTableDelegate::FindByName(name, sources);
226 if (symbol == nullptr) {
227 return {};
228 }
229
230 // Check to see if this is an 'id' with the target package.
231 if (name.type == ResourceType::kId && symbol->id) {
232 ResourceId* id = &symbol->id.value();
233 if (id->package_id() > kAppPackageId) {
234 // Rewrite the resource ID to be compatible pre-O.
235 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
236
237 // Check that this doesn't overlap another resource.
238 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
239 // The ID overlaps, so log a message (since this is a weird failure) and fail.
240 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
241 << " for pre-O feature split support");
242 return {};
243 }
244
245 if (context_->IsVerbose()) {
246 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
247 << ") -> (" << rewritten_id << ")");
248 }
249
250 *id = rewritten_id;
251 }
252 }
253 return symbol;
254 }
255
256 private:
257 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
258
259 IAaptContext* context_;
260};
261
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700262static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
263 const StringPiece& path, bool keep_raw_values, bool utf16,
264 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700265 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700266 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
267 << (keep_raw_values ? "true" : "false")
268 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700269 }
270
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700271 switch (format) {
272 case OutputFormat::kApk: {
273 BigBuffer buffer(1024);
274 XmlFlattenerOptions options = {};
275 options.keep_raw_values = keep_raw_values;
276 options.use_utf16 = utf16;
277 XmlFlattener flattener(&buffer, options);
278 if (!flattener.Consume(context, &xml_res)) {
279 return false;
280 }
281
282 io::BigBufferInputStream input_stream(&buffer);
283 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
284 ArchiveEntry::kCompress, writer);
285 } break;
286
287 case OutputFormat::kProto: {
288 pb::XmlNode pb_node;
289 SerializeXmlResourceToPb(xml_res, &pb_node);
290 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
291 writer);
292 } break;
293 }
294 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800295}
296
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700297// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700298static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700299 FileInputStream fin(path);
300 if (fin.HadError()) {
301 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700302 return {};
303 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700304 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800305}
306
Adam Lesinski355f2852016-02-13 20:26:45 -0800307struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700308 bool no_auto_version = false;
309 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900310 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700311 bool no_xml_namespaces = false;
312 bool keep_raw_values = false;
313 bool do_not_compress_anything = false;
314 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700315 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700316 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800317};
318
Adam Lesinskic744ae82017-05-17 19:28:38 -0700319// A sampling of public framework resource IDs.
320struct R {
321 struct attr {
322 enum : uint32_t {
323 paddingLeft = 0x010100d6u,
324 paddingRight = 0x010100d8u,
325 paddingHorizontal = 0x0101053du,
326
327 paddingTop = 0x010100d7u,
328 paddingBottom = 0x010100d9u,
329 paddingVertical = 0x0101053eu,
330
331 layout_marginLeft = 0x010100f7u,
332 layout_marginRight = 0x010100f9u,
333 layout_marginHorizontal = 0x0101053bu,
334
335 layout_marginTop = 0x010100f8u,
336 layout_marginBottom = 0x010100fau,
337 layout_marginVertical = 0x0101053cu,
338 };
339 };
340};
341
Adam Lesinski355f2852016-02-13 20:26:45 -0800342class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700343 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700344 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700345 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800346
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700347 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800348
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700349 private:
350 struct FileOperation {
351 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700352
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700353 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700354 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700355
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700356 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700357 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700358
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700359 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700360 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700361
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700362 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700363 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800365
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700366 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800367
Adam Lesinskic744ae82017-05-17 19:28:38 -0700368 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
369 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800370
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700371 ResourceFileFlattenerOptions options_;
372 IAaptContext* context_;
373 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700374 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800375};
376
Adam Lesinskic744ae82017-05-17 19:28:38 -0700377ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
378 IAaptContext* context, proguard::KeepSet* keep_set)
379 : options_(options), context_(context), keep_set_(keep_set) {
380 SymbolTable* symm = context_->GetExternalSymbols();
381
382 // Build up the rules for degrading newer attributes to older ones.
383 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
384 // generated from the attribute definitions themselves (b/62028956).
385 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
386 std::vector<ReplacementAttr> replacements{
387 {"paddingLeft", R::attr::paddingLeft,
388 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
389 {"paddingRight", R::attr::paddingRight,
390 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
391 };
392 rules_[R::attr::paddingHorizontal] =
393 util::make_unique<DegradeToManyRule>(std::move(replacements));
394 }
395
396 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
397 std::vector<ReplacementAttr> replacements{
398 {"paddingTop", R::attr::paddingTop,
399 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
400 {"paddingBottom", R::attr::paddingBottom,
401 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
402 };
403 rules_[R::attr::paddingVertical] =
404 util::make_unique<DegradeToManyRule>(std::move(replacements));
405 }
406
407 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
408 std::vector<ReplacementAttr> replacements{
409 {"layout_marginLeft", R::attr::layout_marginLeft,
410 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
411 {"layout_marginRight", R::attr::layout_marginRight,
412 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
413 };
414 rules_[R::attr::layout_marginHorizontal] =
415 util::make_unique<DegradeToManyRule>(std::move(replacements));
416 }
417
418 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
419 std::vector<ReplacementAttr> replacements{
420 {"layout_marginTop", R::attr::layout_marginTop,
421 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
422 {"layout_marginBottom", R::attr::layout_marginBottom,
423 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
424 };
425 rules_[R::attr::layout_marginVertical] =
426 util::make_unique<DegradeToManyRule>(std::move(replacements));
427 }
428}
429
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700430uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
431 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700432 return 0;
433 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800434
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700435 for (const std::string& extension : options_.extensions_to_not_compress) {
436 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700437 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800438 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700439 }
440 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800441}
442
Adam Lesinskibb94f322017-07-12 07:41:55 -0700443static bool IsTransitionElement(const std::string& name) {
444 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
445 name == "changeImageTransform" || name == "changeTransform" ||
446 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
447 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
448 name == "transitionManager";
449}
450
451static bool IsVectorElement(const std::string& name) {
452 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
ztenghuiab2a38c2017-10-13 15:56:08 -0700453 name == "objectAnimator" || name == "gradient";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700454}
455
Adam Lesinskic744ae82017-05-17 19:28:38 -0700456template <typename T>
457std::vector<T> make_singleton_vec(T&& val) {
458 std::vector<T> vec;
459 vec.emplace_back(std::forward<T>(val));
460 return vec;
461}
462
463std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
464 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700465 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700466 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700467
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700468 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700469 context_->GetDiagnostics()->Note(DiagMessage()
470 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700471 }
472
Adam Lesinski00451162017-10-03 07:44:08 -0700473 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
474 // that existing projects have out-of-date references which pass compilation.
475 xml::StripAndroidStudioAttributes(doc->root.get());
476
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700477 XmlReferenceLinker xml_linker;
478 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700479 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700480 }
481
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700482 if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700483 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700484 }
485
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700486 if (options_.no_xml_namespaces) {
487 XmlNamespaceRemover namespace_remover;
488 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700489 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800490 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700491 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800492
Adam Lesinskibb94f322017-07-12 07:41:55 -0700493 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700494 return make_singleton_vec(std::move(file_op->xml_to_flatten));
495 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700496
Adam Lesinskibb94f322017-07-12 07:41:55 -0700497 if (options_.no_version_vectors || options_.no_version_transitions) {
498 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700499 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700500 if (el && el->namespace_uri.empty()) {
501 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
502 (options_.no_version_transitions && IsTransitionElement(el->name))) {
503 return make_singleton_vec(std::move(file_op->xml_to_flatten));
504 }
505 }
506 }
507
Adam Lesinskic744ae82017-05-17 19:28:38 -0700508 const ConfigDescription& config = file_op->config;
509 ResourceEntry* entry = file_op->entry;
510
511 XmlCompatVersioner xml_compat_versioner(&rules_);
512 const util::Range<ApiVersion> api_range{config.sdkVersion,
513 FindNextApiVersionForConfig(entry, config)};
514 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800515}
516
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700517bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700518 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700519 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800520
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700521 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700522 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
523
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700524 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700525 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700526 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700527 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800528
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529 // Populate the queue with all files in the ResourceTable.
530 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700531 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700532 // WARNING! Do not insert or remove any resources while executing in this scope. It will
533 // corrupt the iteration order.
534
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700535 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700536 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700537 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700539
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700540 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700542 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700544 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700545 }
546
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700547 FileOperation file_op;
548 file_op.entry = entry.get();
549 file_op.dst_path = *file_ref->path;
550 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700551 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700553 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700554 (file_ref->type == ResourceFile::Type::kBinaryXml ||
555 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700556 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700558 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559 << "failed to open file");
560 return false;
561 }
562
Adam Lesinski00451162017-10-03 07:44:08 -0700563 if (file_ref->type == ResourceFile::Type::kProtoXml) {
564 pb::XmlNode pb_xml_node;
565 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
566 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700567 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700568 return false;
569 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700570
Adam Lesinski00451162017-10-03 07:44:08 -0700571 std::string error;
572 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
573 if (file_op.xml_to_flatten == nullptr) {
574 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700575 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700576 return false;
577 }
578 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700579 std::string error_str;
580 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700581 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700582 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
583 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700584 return false;
585 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700586 }
587
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700588 file_op.xml_to_flatten->file.config = config_value->config;
589 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700590 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700592
593 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
594 // else we end up copying the string in the std::make_pair() method,
595 // then creating a StringPiece from the copy, which would cause us
596 // to end up referencing garbage in the map.
597 const StringPiece entry_name(entry->name);
598 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
599 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700600 }
601 }
602
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700603 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700604 for (auto& map_entry : config_sorted_files) {
605 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700606 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700607
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700608 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700609 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
610 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700611 if (versioned_docs.empty()) {
612 error = true;
613 continue;
614 }
615
Adam Lesinskic744ae82017-05-17 19:28:38 -0700616 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
617 std::string dst_path = file_op.dst_path;
618 if (doc->file.config != file_op.config) {
619 // Only add the new versioned configurations.
620 if (context_->IsVerbose()) {
621 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
622 << "auto-versioning resource from config '"
623 << config << "' -> '" << doc->file.config << "'");
624 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700625
Adam Lesinskic744ae82017-05-17 19:28:38 -0700626 dst_path =
627 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
628 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
629 doc->file.source, dst_path, nullptr,
630 context_->GetDiagnostics());
631 if (!result) {
632 return false;
633 }
634 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700635
636 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
637 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700638 }
639 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700640 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
641 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700642 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700643 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700644 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700645 }
646 return !error;
647}
648
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700649static bool WriteStableIdMapToPath(IDiagnostics* diag,
650 const std::unordered_map<ResourceName, ResourceId>& id_map,
651 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700652 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700654 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700655 return false;
656 }
657
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700658 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 const ResourceName& name = entry.first;
660 const ResourceId& id = entry.second;
661 fout << name << " = " << id << "\n";
662 }
663
664 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700665 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
666 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 return false;
668 }
669
670 return true;
671}
672
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700673static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
674 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700676 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700677 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700678 return false;
679 }
680
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700681 out_id_map->clear();
682 size_t line_no = 0;
683 for (StringPiece line : util::Tokenize(content, '\n')) {
684 line_no++;
685 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700686 if (line.empty()) {
687 continue;
688 }
689
690 auto iter = std::find(line.begin(), line.end(), '=');
691 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700692 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 return false;
694 }
695
696 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700697 StringPiece res_name_str =
698 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
699 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700700 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
701 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700702 return false;
703 }
704
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700705 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
706 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700707 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700709 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
710 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700711 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
712 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 return false;
714 }
715
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700716 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700717 }
718 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700719}
720
Adam Lesinskifb48d292015-11-07 15:52:13 -0800721class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700722 public:
723 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700724 : options_(options),
725 context_(context),
726 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700727 file_collection_(util::make_unique<io::FileCollection>()) {
728 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700729
Adam Lesinski8780eb62017-10-31 17:44:39 -0700730 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700731 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700732 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700733 for (const std::string& path : options_.include_paths) {
734 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700735 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700737
Adam Lesinski8780eb62017-10-31 17:44:39 -0700738 std::string error;
739 auto zip_collection = io::ZipFileCollection::Create(path, &error);
740 if (zip_collection == nullptr) {
741 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
742 return false;
743 }
744
745 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
746 // Load this as a static library include.
747 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
748 Source(path), std::move(zip_collection), context_->GetDiagnostics());
749 if (static_apk == nullptr) {
750 return false;
751 }
752
Adam Lesinskib522f042017-04-21 16:57:59 -0700753 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800754 // Can't include static libraries when not building a static library (they have no IDs
755 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700756 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800757 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700758 return false;
759 }
760
Adam Lesinski8780eb62017-10-31 17:44:39 -0700761 ResourceTable* table = static_apk->GetResourceTable();
762
763 // If we are using --no-static-lib-packages, we need to rename the package of this table to
764 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700765 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800766 // Since package names can differ, and multiple packages can exist in a ResourceTable,
767 // we place the requirement that all static libraries are built with the package
768 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700769 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700770 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800771 } else {
772 context_->GetDiagnostics()->Error(DiagMessage(path)
773 << "no package with ID 0x7f found in static library");
774 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700775 }
776 }
777
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700778 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700779 util::make_unique<ResourceTableSymbolSource>(table));
780 static_library_includes_.push_back(std::move(static_apk));
781 } else {
782 if (!asset_source->AddAssetPath(path)) {
783 context_->GetDiagnostics()->Error(DiagMessage()
784 << "failed to load include path " << path);
785 return false;
786 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700787 }
788 }
789
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800790 // Capture the shared libraries so that the final resource table can be properly flattened
791 // with support for shared libraries.
792 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800793 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800794 final_table_.included_packages_[entry.first] = entry.second;
795 }
796 }
797
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700798 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700799 return true;
800 }
801
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800802 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700803 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800804 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
805 if (manifest_el == nullptr) {
806 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700807 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800808
809 AppInfo app_info;
810
811 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
812 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
813 return {};
814 }
815
816 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
817 if (!package_attr) {
818 diag->Error(DiagMessage(xml_res->file.source)
819 << "<manifest> must have a 'package' attribute");
820 return {};
821 }
822 app_info.package = package_attr->value;
823
824 if (xml::Attribute* version_code_attr =
825 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
826 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
827 if (!maybe_code) {
828 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
829 << "invalid android:versionCode '" << version_code_attr->value << "'");
830 return {};
831 }
832 app_info.version_code = maybe_code.value();
833 }
834
835 if (xml::Attribute* revision_code_attr =
836 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
837 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
838 if (!maybe_code) {
839 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
840 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
841 return {};
842 }
843 app_info.revision_code = maybe_code.value();
844 }
845
846 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
847 if (!split_name_attr->value.empty()) {
848 app_info.split_name = split_name_attr->value;
849 }
850 }
851
852 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
853 if (xml::Attribute* min_sdk =
854 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700855 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800856 }
857 }
858 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700859 }
860
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700861 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
862 // Postcondition: ResourceTable has only one package left. All others are
863 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700864 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700865 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700866 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
867 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700868 };
869
870 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700871 for (const auto& package : final_table_.packages) {
872 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700873 // We have a package that is not related to the one we're building!
874 for (const auto& type : package->types) {
875 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700876 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700877
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700878 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700879 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700880 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700881 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
882 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
883 << "generated id '" << res_name
884 << "' for external package '" << package->name
885 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700886 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700887 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
888 << "defined resource '" << res_name
889 << "' for external package '" << package->name
890 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700891 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700892 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700893 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700894 }
895 }
896 }
897 }
898
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700899 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
900 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700901 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700902 return !error;
903 }
904
905 /**
906 * Returns true if no IDs have been set, false otherwise.
907 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700908 bool VerifyNoIdsSet() {
909 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700910 for (const auto& type : package->types) {
911 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800912 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
913 << StringPrintf("%02x", type->id.value())
914 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700915 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700916 }
917
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700918 for (const auto& entry : type->entries) {
919 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700920 ResourceNameRef res_name(package->name, type->type, entry->name);
921 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800922 DiagMessage() << "entry " << res_name << " has ID "
923 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700924 return false;
925 }
926 }
927 }
928 }
929 return true;
930 }
931
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700932 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
933 if (options_.output_to_directory) {
934 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700935 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700936 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700937 }
938 }
939
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700940 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
941 switch (format) {
942 case OutputFormat::kApk: {
943 BigBuffer buffer(1024);
944 TableFlattener flattener(options_.table_flattener_options, &buffer);
945 if (!flattener.Consume(context_, table)) {
946 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
947 return false;
948 }
949
950 io::BigBufferInputStream input_stream(&buffer);
951 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
952 ArchiveEntry::kAlign, writer);
953 } break;
954
955 case OutputFormat::kProto: {
956 pb::ResourceTable pb_table;
957 SerializeTableToPb(*table, &pb_table);
958 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
959 ArchiveEntry::kCompress, writer);
960 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700961 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700962 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700963 }
964
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700965 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700966 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700967 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700968 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700969 return true;
970 }
971
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700972 std::string out_path = options_.generate_java_class_path.value();
973 file::AppendPath(&out_path, file::PackageToPath(out_package));
974 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700975 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
976 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700977 return false;
978 }
979
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700980 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700981
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700982 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700983 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700984 context_->GetDiagnostics()->Error(DiagMessage()
985 << "failed writing to '" << out_path
986 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700987 return false;
988 }
989
Adam Lesinski418763f2017-04-11 17:36:53 -0700990 std::unique_ptr<std::ofstream> fout_text;
991 if (out_text_symbols_path) {
992 fout_text =
993 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
994 if (!*fout_text) {
995 context_->GetDiagnostics()->Error(
996 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
997 << "': " << android::base::SystemErrorCodeToString(errno));
998 return false;
999 }
1000 }
1001
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001002 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -07001003 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -07001004 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001005 return false;
1006 }
1007
1008 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001009 context_->GetDiagnostics()->Error(DiagMessage()
1010 << "failed writing to '" << out_path
1011 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001012 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 }
1014 return true;
1015 }
1016
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001017 bool GenerateJavaClasses() {
1018 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1019 std::vector<std::string> packages_to_callback;
1020
1021 JavaClassGeneratorOptions template_options;
1022 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1023 template_options.javadoc_annotations = options_.javadoc_annotations;
1024
1025 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1026 template_options.use_final = false;
1027 }
1028
1029 if (context_->GetPackageType() == PackageType::kSharedLib) {
1030 template_options.use_final = false;
1031 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1032 }
1033
1034 const StringPiece actual_package = context_->GetCompilationPackage();
1035 StringPiece output_package = context_->GetCompilationPackage();
1036 if (options_.custom_java_package) {
1037 // Override the output java package to the custom one.
1038 output_package = options_.custom_java_package.value();
1039 }
1040
1041 // Generate the private symbols if required.
1042 if (options_.private_symbols) {
1043 packages_to_callback.push_back(options_.private_symbols.value());
1044
1045 // If we defined a private symbols package, we only emit Public symbols
1046 // to the original package, and private and public symbols to the private package.
1047 JavaClassGeneratorOptions options = template_options;
1048 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1049 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1050 options)) {
1051 return false;
1052 }
1053 }
1054
1055 // Generate copies of the original package R class but with different package names.
1056 // This is to support non-namespaced builds.
1057 for (const std::string& extra_package : options_.extra_java_packages) {
1058 packages_to_callback.push_back(extra_package);
1059
1060 JavaClassGeneratorOptions options = template_options;
1061 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1062 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1063 return false;
1064 }
1065 }
1066
1067 // Generate R classes for each package that was merged (static library).
1068 // Use the actual package's resources only.
1069 for (const std::string& package : table_merger_->merged_packages()) {
1070 packages_to_callback.push_back(package);
1071
1072 JavaClassGeneratorOptions options = template_options;
1073 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1074 if (!WriteJavaFile(&final_table_, package, package, options)) {
1075 return false;
1076 }
1077 }
1078
1079 // Generate the main public R class.
1080 JavaClassGeneratorOptions options = template_options;
1081
1082 // Only generate public symbols if we have a private package.
1083 if (options_.private_symbols) {
1084 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1085 }
1086
1087 if (options.rewrite_callback_options) {
1088 options.rewrite_callback_options.value().packages_to_callback =
1089 std::move(packages_to_callback);
1090 }
1091
1092 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1093 options_.generate_text_symbols_path)) {
1094 return false;
1095 }
1096
1097 return true;
1098 }
1099
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001100 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1101 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001102 return true;
1103 }
1104
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001105 std::unique_ptr<ClassDefinition> manifest_class =
1106 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001107
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001108 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001109 // Something bad happened, but we already logged it, so exit.
1110 return false;
1111 }
1112
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001113 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001114 // Empty Manifest class, no need to generate it.
1115 return true;
1116 }
1117
1118 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001119 for (const std::string& annotation : options_.javadoc_annotations) {
1120 std::string proper_annotation = "@";
1121 proper_annotation += annotation;
1122 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001123 }
1124
Adam Lesinski0d81f702017-06-27 15:51:09 -07001125 const std::string package_utf8 =
1126 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001127
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001128 std::string out_path = options_.generate_java_class_path.value();
1129 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001130
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001131 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001132 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1133 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001134 return false;
1135 }
1136
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001137 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001138
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001139 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001141 context_->GetDiagnostics()->Error(DiagMessage()
1142 << "failed writing to '" << out_path
1143 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001144 return false;
1145 }
1146
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001147 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1148 context_->GetDiagnostics()->Error(DiagMessage()
1149 << "failed writing to '" << out_path
1150 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001151 return false;
1152 }
1153 return true;
1154 }
1155
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001156 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001157 if (!out) {
1158 return true;
1159 }
1160
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001161 const std::string& out_path = out.value();
1162 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001163 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001164 context_->GetDiagnostics()->Error(DiagMessage()
1165 << "failed to open '" << out_path
1166 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001167 return false;
1168 }
1169
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001170 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001171 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001172 context_->GetDiagnostics()->Error(DiagMessage()
1173 << "failed writing to '" << out_path
1174 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001175 return false;
1176 }
1177 return true;
1178 }
1179
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001180 bool MergeStaticLibrary(const std::string& input, bool override) {
1181 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001182 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001183 }
1184
Adam Lesinski8780eb62017-10-31 17:44:39 -07001185 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1186 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001187 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001188 return false;
1189 }
1190
Adam Lesinski8780eb62017-10-31 17:44:39 -07001191 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001192 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001193 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001194 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001195 return false;
1196 }
1197
1198 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001199 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001200 // Merge all resources as if they were in the compilation package. This is the old behavior
1201 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001203 // Add the package to the set of --extra-packages so we emit an R.java for each library
1204 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001205 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001206 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001207 }
1208
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001209 // Clear the package name, so as to make the resources look like they are coming from the
1210 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001211 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001212 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001213
1214 } else {
1215 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001216 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001217 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 }
1219
1220 if (!result) {
1221 return false;
1222 }
1223
1224 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001225 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001226 return true;
1227 }
1228
Adam Lesinski00451162017-10-03 07:44:08 -07001229 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001230 if (context_->IsVerbose()) {
Adam Lesinski00451162017-10-03 07:44:08 -07001231 context_->GetDiagnostics()->Note(DiagMessage()
1232 << "merging '" << compiled_file.name
1233 << "' from compiled file " << compiled_file.source);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001234 }
1235
Adam Lesinski00451162017-10-03 07:44:08 -07001236 if (!table_merger_->MergeFile(compiled_file, override, file)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237 return false;
1238 }
1239
1240 // Add the exports of this file to the table.
Adam Lesinski00451162017-10-03 07:44:08 -07001241 for (const SourcedResourceName& exported_symbol : compiled_file.exported_symbols) {
1242 ResourceName res_name = exported_symbol.name;
1243 if (res_name.package.empty()) {
1244 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001245 }
1246
Adam Lesinski00451162017-10-03 07:44:08 -07001247 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001248 if (mangled_name) {
1249 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001250 }
1251
1252 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski00451162017-10-03 07:44:08 -07001253 id->SetSource(compiled_file.source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001254 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001255 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1256 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257 if (!result) {
1258 return false;
1259 }
1260 }
1261 return true;
1262 }
1263
Adam Lesinski00451162017-10-03 07:44:08 -07001264 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1265 // If override is true, conflicting resources are allowed to override each other, in order of last
1266 // seen.
1267 // An io::IFileCollection is created from the ZIP file and added to the set of
1268 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001269 bool MergeArchive(const std::string& input, bool override) {
1270 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001271 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001272 }
1273
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001274 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001275 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001276 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001277 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001278 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 return false;
1280 }
1281
1282 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001283 for (auto iter = collection->Iterator(); iter->HasNext();) {
1284 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001285 error = true;
1286 }
1287 }
1288
1289 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001290 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001291 return !error;
1292 }
1293
Adam Lesinski00451162017-10-03 07:44:08 -07001294 // Takes a path to load and merge into the master ResourceTable. If override is true,
1295 // conflicting resources are allowed to override each other, in order of last seen.
1296 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1297 // as ZIP archive and the files within are merged individually.
1298 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001299 bool MergePath(const std::string& path, bool override) {
1300 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1301 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1302 return MergeArchive(path, override);
1303 } else if (util::EndsWith(path, ".apk")) {
1304 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001305 }
1306
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001307 io::IFile* file = file_collection_->InsertFile(path);
1308 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001309 }
1310
Adam Lesinski00451162017-10-03 07:44:08 -07001311 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1312 // If override is true, conflicting resources are allowed to override each other, in order of last
1313 // seen.
1314 // All other file types are ignored. This is because these files could be coming from a zip,
1315 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001316 bool MergeFile(io::IFile* file, bool override) {
1317 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001318
Adam Lesinski00451162017-10-03 07:44:08 -07001319 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001320 // Since AAPT compiles these file types and appends .flat to them, seeing
1321 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001322 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1323 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1324 << " file passed as argument. Must be "
1325 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001326 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001327 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1328 if (context_->IsVerbose()) {
1329 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1330 return true;
1331 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001332 }
1333
Adam Lesinski00451162017-10-03 07:44:08 -07001334 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1335 if (input_stream == nullptr) {
1336 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1337 return false;
1338 }
1339
1340 if (input_stream->HadError()) {
1341 context_->GetDiagnostics()->Error(DiagMessage(src)
1342 << "failed to open file: " << input_stream->GetError());
1343 return false;
1344 }
1345
1346 ContainerReaderEntry* entry;
1347 ContainerReader reader(input_stream.get());
1348 while ((entry = reader.Next()) != nullptr) {
1349 if (entry->Type() == ContainerEntryType::kResTable) {
1350 pb::ResourceTable pb_table;
1351 if (!entry->GetResTable(&pb_table)) {
1352 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1353 << entry->GetError());
1354 return false;
1355 }
1356
1357 ResourceTable table;
1358 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001359 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001360 context_->GetDiagnostics()->Error(DiagMessage(src)
1361 << "failed to deserialize resource table: " << error);
1362 return false;
1363 }
1364
1365 if (!table_merger_->Merge(src, &table, override)) {
1366 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1367 return false;
1368 }
1369 } else if (entry->Type() == ContainerEntryType::kResFile) {
1370 pb::internal::CompiledFile pb_compiled_file;
1371 off64_t offset;
1372 size_t len;
1373 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1374 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1375 << entry->GetError());
1376 return false;
1377 }
1378
1379 ResourceFile resource_file;
1380 std::string error;
1381 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1382 context_->GetDiagnostics()->Error(DiagMessage(src)
1383 << "failed to read compiled header: " << error);
1384 return false;
1385 }
1386
1387 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1388 return false;
1389 }
1390 }
1391 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001392 return true;
1393 }
1394
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001395 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1396 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1397 for (const std::string& assets_dir : options_.assets_dirs) {
1398 Maybe<std::vector<std::string>> files =
1399 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1400 if (!files) {
1401 return false;
1402 }
1403
1404 for (const std::string& file : files.value()) {
1405 std::string full_key = "assets/" + file;
1406 std::string full_path = assets_dir;
1407 file::AppendPath(&full_path, file);
1408
1409 auto iter = merged_assets.find(full_key);
1410 if (iter == merged_assets.end()) {
1411 merged_assets.emplace(std::move(full_key),
1412 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1413 } else if (context_->IsVerbose()) {
1414 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1415 << "asset file overrides '" << full_path << "'");
1416 }
1417 }
1418 }
1419
1420 for (auto& entry : merged_assets) {
1421 uint32_t compression_flags = ArchiveEntry::kCompress;
1422 std::string extension = file::GetExtension(entry.first).to_string();
1423 if (options_.extensions_to_not_compress.count(extension) > 0) {
1424 compression_flags = 0u;
1425 }
1426
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001427 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1428 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001429 return false;
1430 }
1431 }
1432 return true;
1433 }
1434
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001435 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1436 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001437 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1438 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001439 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001440 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1441 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001442 if (!result) {
1443 return false;
1444 }
1445
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001446 ResourceFileFlattenerOptions file_flattener_options;
1447 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001448 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1449 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001450 file_flattener_options.no_auto_version = options_.no_auto_version;
1451 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001452 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001453 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1454 file_flattener_options.update_proguard_spec =
1455 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001456 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001457
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001458 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001459
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001460 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001461 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001462 return false;
1463 }
1464
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001465 if (!FlattenTable(table, options_.output_format, writer)) {
1466 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1467 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001468 }
1469 return true;
1470 }
1471
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001472 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001473 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001474 std::unique_ptr<xml::XmlResource> manifest_xml =
1475 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1476 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001477 return 1;
1478 }
1479
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001480 // First extract the Package name without modifying it (via --rename-manifest-package).
1481 if (Maybe<AppInfo> maybe_app_info =
1482 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001483 const AppInfo& app_info = maybe_app_info.value();
1484 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001485 }
1486
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001487 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1488 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001489 return 1;
1490 }
1491
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001492 Maybe<AppInfo> maybe_app_info =
1493 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001494 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001495 return 1;
1496 }
1497
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001498 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001499 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001500
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001501 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001502
1503 // Override the package ID when it is "android".
1504 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001505 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001506
1507 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001508 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001509 context_->GetDiagnostics()->Error(
1510 DiagMessage() << "package 'android' can only be built as a regular app");
1511 return 1;
1512 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001513 }
1514
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001515 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001516 return 1;
1517 }
1518
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001519 TableMergerOptions table_merger_options;
1520 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001521 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001522
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001523 if (context_->IsVerbose()) {
1524 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001525 << StringPrintf("linking package '%s' using package ID %02x",
1526 context_->GetCompilationPackage().data(),
1527 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001528 }
1529
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001530 for (const std::string& input : input_files) {
1531 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001532 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001533 return 1;
1534 }
1535 }
1536
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001537 for (const std::string& input : options_.overlay_files) {
1538 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001539 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001540 return 1;
1541 }
1542 }
1543
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001544 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001545 return 1;
1546 }
1547
Adam Lesinskib522f042017-04-21 16:57:59 -07001548 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001549 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001550 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001551 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001552 return 1;
1553 }
1554
1555 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001556 IdAssigner id_assigner(&options_.stable_id_map);
1557 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001558 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001559 return 1;
1560 }
1561
1562 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001563 if (options_.resource_id_map_path) {
1564 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001565 for (auto& type : package->types) {
1566 for (auto& entry : type->entries) {
1567 ResourceName name(package->name, type->type, entry->name);
1568 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001569 options_.stable_id_map[std::move(name)] =
1570 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001571 }
1572 }
1573 }
1574
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001575 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001576 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001577 return 1;
1578 }
1579 }
1580 } else {
1581 // Static libs are merged with other apps, and ID collisions are bad, so
1582 // verify that
1583 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001584 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001585 return 1;
1586 }
1587 }
1588
1589 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001590 context_->SetNameManglerPolicy(
1591 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001592
1593 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001594 context_->GetExternalSymbols()->PrependSource(
1595 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001596
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001597 // Workaround for pre-O runtime that would treat negative resource IDs
1598 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1599 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1600 // are just identifiers.
1601 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1602 if (context_->IsVerbose()) {
1603 context_->GetDiagnostics()->Note(DiagMessage()
1604 << "enabling pre-O feature split ID rewriting");
1605 }
1606 context_->GetExternalSymbols()->SetDelegate(
1607 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1608 }
1609
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001611 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001612 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001613 return 1;
1614 }
1615
Adam Lesinskib522f042017-04-21 16:57:59 -07001616 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001617 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001618 context_->GetDiagnostics()->Warn(DiagMessage()
1619 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001620 }
1621 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001622 ProductFilter product_filter(options_.products);
1623 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001624 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001625 return 1;
1626 }
1627 }
1628
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001629 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001630 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001631 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001632 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001633 return 1;
1634 }
1635 }
1636
Adam Lesinskib522f042017-04-21 16:57:59 -07001637 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001638 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001639 context_->GetDiagnostics()->Note(DiagMessage()
1640 << "collapsing resource versions for minimum SDK "
1641 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001642 }
1643
1644 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001645 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001646 return 1;
1647 }
1648 }
1649
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001650 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001651 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001652 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001653 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001654 return 1;
1655 }
1656 }
1657
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001658 proguard::KeepSet proguard_keep_set;
1659 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001660
Adam Lesinskib522f042017-04-21 16:57:59 -07001661 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001662 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001663 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001664 context_->GetDiagnostics()->Warn(DiagMessage()
1665 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001666 }
1667 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001668 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1669 // equal to the minSdk.
1670 options_.split_constraints =
1671 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001672
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001673 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001674 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001675 return 1;
1676 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001677 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001678
1679 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001680 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001681 auto split_constraints_iter = options_.split_constraints.begin();
1682 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001683 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001684 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1685 << "generating split with configurations '"
1686 << util::Joiner(split_constraints_iter->configs, ", ")
1687 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001688 }
1689
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001690 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001691 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001692 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001693 return 1;
1694 }
1695
1696 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001697 std::unique_ptr<xml::XmlResource> split_manifest =
1698 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001699
1700 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001701 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001702 context_->GetDiagnostics()->Error(DiagMessage()
1703 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001704 return 1;
1705 }
1706
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001707 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1708 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001709 return 1;
1710 }
1711
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001712 ++path_iter;
1713 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001714 }
1715 }
1716
1717 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001718 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001719 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001720 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001721 return 1;
1722 }
1723
1724 bool error = false;
1725 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001726 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001727 // (aka, which package the AndroidManifest.xml is coming from).
1728 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001729 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001730
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001731 XmlReferenceLinker manifest_linker;
1732 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1733 if (options_.generate_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001734 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1735 manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001736 error = true;
1737 }
1738
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001739 if (options_.generate_main_dex_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001740 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1741 manifest_xml.get(),
1742 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001744 }
1745
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001746 if (options_.generate_java_class_path) {
1747 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001748 error = true;
1749 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001750 }
1751
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001752 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 // PackageParser will fail if URIs are removed from
1754 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001755 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1756 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 error = true;
1758 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001759 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001760 } else {
1761 error = true;
1762 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001763 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001764
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001765 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001766 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001767 return 1;
1768 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001769
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001770 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1771 return 1;
1772 }
1773
1774 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001775 return 1;
1776 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001777
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001778 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001779 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001780 return 1;
1781 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001782 }
1783
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001784 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001785 return 1;
1786 }
1787
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001788 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1789 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001790 return 1;
1791 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792 return 0;
1793 }
1794
1795 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001796 LinkOptions options_;
1797 LinkContext* context_;
1798 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001799
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001800 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001801
1802 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001803 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001804
Adam Lesinski8780eb62017-10-31 17:44:39 -07001805 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001806 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001807 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001808
Adam Lesinski8780eb62017-10-31 17:44:39 -07001809 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1810 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1811
1812 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1813 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001814
1815 // The set of shared libraries being used, mapping their assigned package ID to package name.
1816 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001817};
1818
Chris Warrington820d72a2017-04-27 15:27:01 +01001819int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1820 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001822 std::vector<std::string> overlay_arg_list;
1823 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001824 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001825 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001826 Maybe<std::string> preferred_density;
1827 Maybe<std::string> product_list;
1828 bool legacy_x_flag = false;
1829 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001830 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001831 bool shared_lib = false;
1832 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001833 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001834 Maybe<std::string> stable_id_file_path;
1835 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001836 Flags flags =
1837 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001838 .RequiredFlag("-o", "Output path.", &options.output_path)
1839 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001840 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001841 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001842 .OptionalFlagList("-A",
1843 "An assets directory to include in the APK. These are unprocessed.",
1844 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001845 .OptionalFlagList("-R",
1846 "Compilation unit to link, using `overlay` semantics.\n"
1847 "The last conflicting resource given takes precedence.",
1848 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001849 .OptionalFlag("--package-id",
1850 "Specify the package ID to use for this app. Must be greater or equal to\n"
1851 "0x7f and can't be used with --static-lib or --shared-lib.",
1852 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001853 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001855 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001856 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001857 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001858 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001859 &options.generate_main_dex_proguard_rules_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001860 .OptionalSwitch("--no-auto-version",
1861 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001862 &options.no_auto_version)
1863 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001864 "Disables automatic versioning of vector drawables. Use this only\n"
1865 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001866 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001867 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001868 "Disables automatic versioning of transition resources. Use this only\n"
1869 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001870 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001871 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001872 "Disables automatic deduping of resources with\n"
1873 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001874 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001875 .OptionalSwitch("--enable-sparse-encoding",
1876 "Enables encoding sparse entries using a binary search tree.\n"
1877 "This decreases APK size at the cost of resource retrieval performance.",
1878 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001879 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001880 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001881 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001882 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001883 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001884 "Comma separated list of configurations to include. The default\n"
1885 "is all configurations.",
1886 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001887 .OptionalFlag("--preferred-density",
1888 "Selects the closest matching density and strips out all others.",
1889 &preferred_density)
1890 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001891 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001892 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001893 &options.output_to_directory)
1894 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001895 "Removes XML namespace prefix and URI information from\n"
1896 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001897 &options.no_xml_namespaces)
1898 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001899 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001900 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001901 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001902 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001903 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1906 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001907 &options.manifest_fixer_options.version_code_default)
1908 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001909 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001910 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001911 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1912 &shared_lib)
1913 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001914 .OptionalSwitch("--proto-format",
1915 "Generates compiled resources in Protobuf format.\n"
1916 "Suitable as input to the bundle tool for generating an App Bundle.",
1917 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001919 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001920 &options.no_static_lib_packages)
1921 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001922 "Generates R.java without the final modifier. This is implied when\n"
1923 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001924 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001925 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001926 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001927 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001928 "Emit a file at the given path with a list of name to ID mappings,\n"
1929 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001930 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001931 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001932 "Package name to use when generating R.java for private symbols.\n"
1933 "If not specified, public and private symbols will use the application's\n"
1934 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001935 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001936 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001937 &options.custom_java_package)
1938 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001939 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 &extra_java_packages)
1941 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001942 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001944 .OptionalFlag("--output-text-symbols",
1945 "Generates a text file containing the resource symbols of the R class in\n"
1946 "the specified folder.",
1947 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001948 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001949 "Allows the addition of new resources in overlays without\n"
1950 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001952 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001953 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001954 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001955 "Changes the name of the target package for instrumentation. Most useful\n"
1956 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001957 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001958 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001959 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001960 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001961 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07001962 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
1963 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001964 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001965 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001966
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001967 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001968 return 1;
1969 }
1970
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001971 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001972 std::vector<std::string> arg_list;
1973 for (const std::string& arg : flags.GetArgs()) {
1974 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975 const std::string path = arg.substr(1, arg.size() - 1);
1976 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001977 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
1978 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001979 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001980 }
1981 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001982 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001983 }
1984 }
1985
1986 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001987 for (const std::string& arg : overlay_arg_list) {
1988 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001989 const std::string path = arg.substr(1, arg.size() - 1);
1990 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001991 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
1992 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001993 return 1;
1994 }
1995 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001997 }
1998 }
1999
2000 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002001 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002002 }
2003
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002004 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2005 context.GetDiagnostics()->Error(
2006 DiagMessage()
2007 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002008 return 1;
2009 }
2010
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002011 // The default build type.
2012 context.SetPackageType(PackageType::kApp);
2013 context.SetPackageId(kAppPackageId);
2014
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002015 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002016 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002017 context.SetPackageId(0x00);
2018 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002019 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002020 options.output_format = OutputFormat::kProto;
2021 } else if (proto_format) {
2022 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002023 }
2024
2025 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002026 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002027 context.GetDiagnostics()->Error(
2028 DiagMessage() << "can't specify --package-id when not building a regular app");
2029 return 1;
2030 }
2031
2032 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2033 if (!maybe_package_id_int) {
2034 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2035 << "' is not a valid integer");
2036 return 1;
2037 }
2038
2039 const uint32_t package_id_int = maybe_package_id_int.value();
2040 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2041 context.GetDiagnostics()->Error(
2042 DiagMessage() << StringPrintf(
2043 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2044 return 1;
2045 }
2046 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2047 }
2048
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002049 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002050 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002051 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002052 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002053 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002054 }
2055 }
2056
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002057 if (product_list) {
2058 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002059 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002060 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002061 }
2062 }
2063 }
2064
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002065 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002066 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002067 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2068 if (filter == nullptr) {
2069 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002070 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002071 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002072 }
2073
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002074 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002075 Maybe<uint16_t> density =
2076 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2077 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002078 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002079 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002080 options.table_splitter_options.preferred_densities.push_back(density.value());
2081 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002082
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002083 // Parse the split parameters.
2084 for (const std::string& split_arg : split_args) {
2085 options.split_paths.push_back({});
2086 options.split_constraints.push_back({});
2087 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2088 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002089 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002090 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002091 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002092
Adam Lesinskib522f042017-04-21 16:57:59 -07002093 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002094 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2095 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002096 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002097 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002098 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002099
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002100 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002101 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002102 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2103 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2104 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2105 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2106
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002108 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002109 options.no_auto_version = true;
2110 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002111 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002112 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002113
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002114 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002115 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002116}
2117
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002118} // namespace aapt