blob: b90e7b3042f911956f7f2d0e85f139504ff841f8 [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>
Adam Lesinskic6284372017-12-04 13:46:23 -080018#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019
Adam Lesinskice5e56e2016-10-21 17:56:45 -070020#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 Lesinski2427dce2017-11-30 15:10:28 -080040#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080041#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070042#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070043#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/binary/TableFlattener.h"
45#include "format/binary/XmlFlattener.h"
46#include "format/proto/ProtoDeserialize.h"
47#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070048#include "io/BigBufferStream.h"
49#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080050#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070051#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070053#include "java/JavaClassGenerator.h"
54#include "java/ManifestClassGenerator.h"
55#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070056#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070057#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080058#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080059#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070061#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080062#include "optimize/ResourceDeduper.h"
63#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "process/IResourceTableConsumer.h"
65#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080066#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080068#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070070using ::aapt::io::FileInputStream;
71using ::android::StringPiece;
72using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070073
Adam Lesinski1ab598f2015-08-14 14:26:04 -070074namespace aapt {
75
Adam Lesinskie59f0d82017-10-13 09:36:53 -070076enum class OutputFormat {
77 kApk,
78 kProto,
79};
80
Adam Lesinski1ab598f2015-08-14 14:26:04 -070081struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070082 std::string output_path;
83 std::string manifest_path;
84 std::vector<std::string> include_paths;
85 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070086 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070087 bool output_to_directory = false;
88 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070089 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070090
Adam Lesinskicacb28f2016-10-19 12:18:14 -070091 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070092 Maybe<std::string> generate_java_class_path;
93 Maybe<std::string> custom_java_package;
94 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070095 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070096 Maybe<std::string> generate_proguard_rules_path;
97 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070098 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070099 bool generate_non_final_ids = false;
100 std::vector<std::string> javadoc_annotations;
101 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700102
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700103 // Optimizations/features.
104 bool no_auto_version = false;
105 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900106 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700107 bool no_resource_deduping = false;
108 bool no_xml_namespaces = false;
109 bool do_not_compress_anything = false;
110 std::unordered_set<std::string> extensions_to_not_compress;
111
112 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 bool no_static_lib_packages = false;
114
115 // AndroidManifest.xml massaging options.
116 ManifestFixerOptions manifest_fixer_options;
117
118 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700119 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700120
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800121 // Flattening options.
122 TableFlattenerOptions table_flattener_options;
123
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700124 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700125 TableSplitterOptions table_splitter_options;
126 std::vector<SplitConstraints> split_constraints;
127 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700128
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700129 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700130 std::unordered_map<ResourceName, ResourceId> stable_id_map;
131 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700132};
133
Adam Lesinski64587af2016-02-18 18:33:06 -0800134class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700135 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100136 LinkContext(IDiagnostics* diagnostics)
137 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700138 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139
Adam Lesinskib522f042017-04-21 16:57:59 -0700140 PackageType GetPackageType() override {
141 return package_type_;
142 }
143
144 void SetPackageType(PackageType type) {
145 package_type_ = type;
146 }
147
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700148 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100149 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700150 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700151
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700152 NameMangler* GetNameMangler() override {
153 return &name_mangler_;
154 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700155
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700156 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
157 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700158 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800159
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700160 const std::string& GetCompilationPackage() override {
161 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700162 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700163
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700164 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800165 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700166 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800167
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700168 uint8_t GetPackageId() override {
169 return package_id_;
170 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700171
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700172 void SetPackageId(uint8_t id) {
173 package_id_ = id;
174 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800175
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700176 SymbolTable* GetExternalSymbols() override {
177 return &symbols_;
178 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800179
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700180 bool IsVerbose() override {
181 return verbose_;
182 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800183
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700184 void SetVerbose(bool val) {
185 verbose_ = val;
186 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800187
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700188 int GetMinSdkVersion() override {
189 return min_sdk_version_;
190 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700191
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700192 void SetMinSdkVersion(int minSdk) {
193 min_sdk_version_ = minSdk;
194 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700195
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700196 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700197 DISALLOW_COPY_AND_ASSIGN(LinkContext);
198
Adam Lesinskib522f042017-04-21 16:57:59 -0700199 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100200 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700201 NameMangler name_mangler_;
202 std::string compilation_package_;
203 uint8_t package_id_ = 0x0;
204 SymbolTable symbols_;
205 bool verbose_ = false;
206 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700207};
208
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700209// A custom delegate that generates compatible pre-O IDs for use with feature splits.
210// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
211// is interpreted as a negative number. Some verification was wrongly assuming negative values
212// were invalid.
213//
214// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
215// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
216// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800217//
218// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700219class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
220 public:
221 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
222 }
223
224 virtual ~FeatureSplitSymbolTableDelegate() = default;
225
226 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
227 const ResourceName& name,
228 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
229 std::unique_ptr<SymbolTable::Symbol> symbol =
230 DefaultSymbolTableDelegate::FindByName(name, sources);
231 if (symbol == nullptr) {
232 return {};
233 }
234
235 // Check to see if this is an 'id' with the target package.
236 if (name.type == ResourceType::kId && symbol->id) {
237 ResourceId* id = &symbol->id.value();
238 if (id->package_id() > kAppPackageId) {
239 // Rewrite the resource ID to be compatible pre-O.
240 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
241
242 // Check that this doesn't overlap another resource.
243 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
244 // The ID overlaps, so log a message (since this is a weird failure) and fail.
245 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
246 << " for pre-O feature split support");
247 return {};
248 }
249
250 if (context_->IsVerbose()) {
251 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
252 << ") -> (" << rewritten_id << ")");
253 }
254
255 *id = rewritten_id;
256 }
257 }
258 return symbol;
259 }
260
261 private:
262 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
263
264 IAaptContext* context_;
265};
266
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700267static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
268 const StringPiece& path, bool keep_raw_values, bool utf16,
269 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700270 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700271 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
272 << (keep_raw_values ? "true" : "false")
273 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700274 }
275
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700276 switch (format) {
277 case OutputFormat::kApk: {
278 BigBuffer buffer(1024);
279 XmlFlattenerOptions options = {};
280 options.keep_raw_values = keep_raw_values;
281 options.use_utf16 = utf16;
282 XmlFlattener flattener(&buffer, options);
283 if (!flattener.Consume(context, &xml_res)) {
284 return false;
285 }
286
287 io::BigBufferInputStream input_stream(&buffer);
288 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
289 ArchiveEntry::kCompress, writer);
290 } break;
291
292 case OutputFormat::kProto: {
293 pb::XmlNode pb_node;
294 SerializeXmlResourceToPb(xml_res, &pb_node);
295 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
296 writer);
297 } break;
298 }
299 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800300}
301
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700302// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700303static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700304 FileInputStream fin(path);
305 if (fin.HadError()) {
306 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700307 return {};
308 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700309 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800310}
311
Adam Lesinski355f2852016-02-13 20:26:45 -0800312struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700313 bool no_auto_version = false;
314 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900315 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700316 bool no_xml_namespaces = false;
317 bool keep_raw_values = false;
318 bool do_not_compress_anything = false;
319 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700320 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700321 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800322};
323
Adam Lesinskic744ae82017-05-17 19:28:38 -0700324// A sampling of public framework resource IDs.
325struct R {
326 struct attr {
327 enum : uint32_t {
328 paddingLeft = 0x010100d6u,
329 paddingRight = 0x010100d8u,
330 paddingHorizontal = 0x0101053du,
331
332 paddingTop = 0x010100d7u,
333 paddingBottom = 0x010100d9u,
334 paddingVertical = 0x0101053eu,
335
336 layout_marginLeft = 0x010100f7u,
337 layout_marginRight = 0x010100f9u,
338 layout_marginHorizontal = 0x0101053bu,
339
340 layout_marginTop = 0x010100f8u,
341 layout_marginBottom = 0x010100fau,
342 layout_marginVertical = 0x0101053cu,
343 };
344 };
345};
346
Adam Lesinski355f2852016-02-13 20:26:45 -0800347class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700348 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700349 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700350 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800351
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700352 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800353
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 private:
355 struct FileOperation {
356 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700357
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700358 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700359 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700362 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700365 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700366
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700368 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800370
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700371 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800372
Adam Lesinskic744ae82017-05-17 19:28:38 -0700373 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
374 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800375
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700376 ResourceFileFlattenerOptions options_;
377 IAaptContext* context_;
378 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700379 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800380};
381
Adam Lesinskic744ae82017-05-17 19:28:38 -0700382ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
383 IAaptContext* context, proguard::KeepSet* keep_set)
384 : options_(options), context_(context), keep_set_(keep_set) {
385 SymbolTable* symm = context_->GetExternalSymbols();
386
387 // Build up the rules for degrading newer attributes to older ones.
388 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
389 // generated from the attribute definitions themselves (b/62028956).
390 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
391 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800392 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
393 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700394 };
395 rules_[R::attr::paddingHorizontal] =
396 util::make_unique<DegradeToManyRule>(std::move(replacements));
397 }
398
399 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
400 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800401 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
402 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700403 };
404 rules_[R::attr::paddingVertical] =
405 util::make_unique<DegradeToManyRule>(std::move(replacements));
406 }
407
408 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
409 std::vector<ReplacementAttr> replacements{
410 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800411 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700412 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800413 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700414 };
415 rules_[R::attr::layout_marginHorizontal] =
416 util::make_unique<DegradeToManyRule>(std::move(replacements));
417 }
418
419 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
420 std::vector<ReplacementAttr> replacements{
421 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800422 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700423 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800424 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700425 };
426 rules_[R::attr::layout_marginVertical] =
427 util::make_unique<DegradeToManyRule>(std::move(replacements));
428 }
429}
430
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700431uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
432 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700433 return 0;
434 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800435
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700436 for (const std::string& extension : options_.extensions_to_not_compress) {
437 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700438 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800439 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700440 }
441 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800442}
443
Adam Lesinskibb94f322017-07-12 07:41:55 -0700444static bool IsTransitionElement(const std::string& name) {
445 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
446 name == "changeImageTransform" || name == "changeTransform" ||
447 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
448 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
449 name == "transitionManager";
450}
451
452static bool IsVectorElement(const std::string& name) {
453 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000454 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700455}
456
Adam Lesinskic744ae82017-05-17 19:28:38 -0700457template <typename T>
458std::vector<T> make_singleton_vec(T&& val) {
459 std::vector<T> vec;
460 vec.emplace_back(std::forward<T>(val));
461 return vec;
462}
463
464std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
465 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700466 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700467 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700468
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700469 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700470 context_->GetDiagnostics()->Note(DiagMessage()
471 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 }
473
Adam Lesinski00451162017-10-03 07:44:08 -0700474 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
475 // that existing projects have out-of-date references which pass compilation.
476 xml::StripAndroidStudioAttributes(doc->root.get());
477
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700478 XmlReferenceLinker xml_linker;
479 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700480 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700481 }
482
Adam Koskidc21dea2017-07-21 10:55:27 -0700483 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700484 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700485 }
486
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700487 if (options_.no_xml_namespaces) {
488 XmlNamespaceRemover namespace_remover;
489 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700490 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800491 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800493
Adam Lesinskibb94f322017-07-12 07:41:55 -0700494 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700495 return make_singleton_vec(std::move(file_op->xml_to_flatten));
496 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700497
Adam Lesinskibb94f322017-07-12 07:41:55 -0700498 if (options_.no_version_vectors || options_.no_version_transitions) {
499 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700500 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700501 if (el && el->namespace_uri.empty()) {
502 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
503 (options_.no_version_transitions && IsTransitionElement(el->name))) {
504 return make_singleton_vec(std::move(file_op->xml_to_flatten));
505 }
506 }
507 }
508
Adam Lesinskic744ae82017-05-17 19:28:38 -0700509 const ConfigDescription& config = file_op->config;
510 ResourceEntry* entry = file_op->entry;
511
512 XmlCompatVersioner xml_compat_versioner(&rules_);
513 const util::Range<ApiVersion> api_range{config.sdkVersion,
514 FindNextApiVersionForConfig(entry, config)};
515 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800516}
517
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800518ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
519 switch (format) {
520 case OutputFormat::kApk:
521 return ResourceFile::Type::kBinaryXml;
522 case OutputFormat::kProto:
523 return ResourceFile::Type::kProtoXml;
524 }
525 LOG_ALWAYS_FATAL("unreachable");
526 return ResourceFile::Type::kUnknown;
527}
528
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700529bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700530 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700531 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800532
Adam Koskidc21dea2017-07-21 10:55:27 -0700533 proguard::CollectResourceReferences(context_, table, keep_set_);
534
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700535 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700536 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
537
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700539 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700540 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700541 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800542
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 // Populate the queue with all files in the ResourceTable.
544 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700545 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700546 // WARNING! Do not insert or remove any resources while executing in this scope. It will
547 // corrupt the iteration order.
548
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700549 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700550 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700551 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700553
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700554 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700556 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700558 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559 }
560
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700561 FileOperation file_op;
562 file_op.entry = entry.get();
563 file_op.dst_path = *file_ref->path;
564 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700565 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700567 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700568 (file_ref->type == ResourceFile::Type::kBinaryXml ||
569 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700570 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700571 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700572 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573 << "failed to open file");
574 return false;
575 }
576
Adam Lesinski00451162017-10-03 07:44:08 -0700577 if (file_ref->type == ResourceFile::Type::kProtoXml) {
578 pb::XmlNode pb_xml_node;
579 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
580 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700581 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700582 return false;
583 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700584
Adam Lesinski00451162017-10-03 07:44:08 -0700585 std::string error;
586 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
587 if (file_op.xml_to_flatten == nullptr) {
588 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700589 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700590 return false;
591 }
592 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700593 std::string error_str;
594 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700595 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700596 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
597 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700598 return false;
599 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700600 }
601
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800602 // Update the type that this file will be written as.
603 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
604
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700605 file_op.xml_to_flatten->file.config = config_value->config;
606 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700607 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700609
610 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
611 // else we end up copying the string in the std::make_pair() method,
612 // then creating a StringPiece from the copy, which would cause us
613 // to end up referencing garbage in the map.
614 const StringPiece entry_name(entry->name);
615 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
616 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700617 }
618 }
619
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700620 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700621 for (auto& map_entry : config_sorted_files) {
622 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700623 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700624
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700625 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700626 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
627 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700628 if (versioned_docs.empty()) {
629 error = true;
630 continue;
631 }
632
Adam Lesinskic744ae82017-05-17 19:28:38 -0700633 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
634 std::string dst_path = file_op.dst_path;
635 if (doc->file.config != file_op.config) {
636 // Only add the new versioned configurations.
637 if (context_->IsVerbose()) {
638 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
639 << "auto-versioning resource from config '"
640 << config << "' -> '" << doc->file.config << "'");
641 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700642
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800643 const ResourceFile& file = doc->file;
644 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
645
646 std::unique_ptr<FileReference> file_ref =
647 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
648 file_ref->SetSource(doc->file.source);
649 // Update the output format of this XML file.
650 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
651 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
652 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700653 return false;
654 }
655 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700656
657 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
658 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 }
660 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700661 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
662 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700663 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700664 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700665 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700666 }
667 return !error;
668}
669
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700670static bool WriteStableIdMapToPath(IDiagnostics* diag,
671 const std::unordered_map<ResourceName, ResourceId>& id_map,
672 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800673 io::FileOutputStream fout(id_map_path);
674 if (fout.HadError()) {
675 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 return false;
677 }
678
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800679 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700680 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681 const ResourceName& name = entry.first;
682 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800683 printer.Print(name.to_string());
684 printer.Print(" = ");
685 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700686 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800687 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700688
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800689 if (fout.HadError()) {
690 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700691 return false;
692 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 return true;
694}
695
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700696static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
697 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700699 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700700 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700701 return false;
702 }
703
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700704 out_id_map->clear();
705 size_t line_no = 0;
706 for (StringPiece line : util::Tokenize(content, '\n')) {
707 line_no++;
708 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700709 if (line.empty()) {
710 continue;
711 }
712
713 auto iter = std::find(line.begin(), line.end(), '=');
714 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700715 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 return false;
717 }
718
719 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700720 StringPiece res_name_str =
721 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
722 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700723 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
724 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700725 return false;
726 }
727
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700728 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
729 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700730 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700732 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
733 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700734 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
735 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 return false;
737 }
738
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700740 }
741 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700742}
743
Adam Lesinskic6284372017-12-04 13:46:23 -0800744static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
745 using namespace android;
746
747 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
748 // we're looking for the first attribute resource in the system package.
749 const ResTable& table = assets.getResources(true);
750 Res_value val;
751 ssize_t idx = table.getResource(0x01010000, &val, true);
752 if (idx != NO_ERROR) {
753 // Try as a bag.
754 const ResTable::bag_entry* entry;
755 ssize_t cnt = table.lockBag(0x01010000, &entry);
756 if (cnt >= 0) {
757 idx = entry->stringBlock;
758 }
759 table.unlockBag(entry);
760 }
761
762 if (idx < 0) {
763 return 0;
764 }
765 return table.getTableCookie(idx);
766}
767
Adam Lesinskifb48d292015-11-07 15:52:13 -0800768class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700769 public:
770 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700771 : options_(options),
772 context_(context),
773 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700774 file_collection_(util::make_unique<io::FileCollection>()) {
775 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700776
Adam Lesinskic6284372017-12-04 13:46:23 -0800777 void ExtractCompileSdkVersions(android::AssetManager* assets) {
778 using namespace android;
779
780 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
781 if (cookie == 0) {
782 // No Framework assets loaded. Not a failure.
783 return;
784 }
785
786 std::unique_ptr<Asset> manifest(
787 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
788 if (manifest == nullptr) {
789 // No errors.
790 return;
791 }
792
793 std::string error;
794 std::unique_ptr<xml::XmlResource> manifest_xml =
795 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
796 if (manifest_xml == nullptr) {
797 // No errors.
798 return;
799 }
800
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700801 if (!options_.manifest_fixer_options.compile_sdk_version) {
802 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
803 if (attr != nullptr) {
804 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
805 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
806 switch (prim->value.dataType) {
807 case Res_value::TYPE_INT_DEC:
808 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
809 break;
810 case Res_value::TYPE_INT_HEX:
811 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
812 break;
813 default:
814 break;
815 }
816 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
817 compile_sdk_version = *str->value;
818 } else {
819 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800820 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800821 }
822 }
823
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700824 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
825 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
826 if (attr != nullptr) {
827 Maybe<std::string>& compile_sdk_version_codename =
828 options_.manifest_fixer_options.compile_sdk_version_codename;
829 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
830 compile_sdk_version_codename = *str->value;
831 } else {
832 compile_sdk_version_codename = attr->value;
833 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800834 }
835 }
836 }
837
Adam Lesinski8780eb62017-10-31 17:44:39 -0700838 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800839 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700840 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700841 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700842 for (const std::string& path : options_.include_paths) {
843 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700844 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700845 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700846
Adam Lesinski8780eb62017-10-31 17:44:39 -0700847 std::string error;
848 auto zip_collection = io::ZipFileCollection::Create(path, &error);
849 if (zip_collection == nullptr) {
850 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
851 return false;
852 }
853
854 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
855 // Load this as a static library include.
856 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
857 Source(path), std::move(zip_collection), context_->GetDiagnostics());
858 if (static_apk == nullptr) {
859 return false;
860 }
861
Adam Lesinskib522f042017-04-21 16:57:59 -0700862 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800863 // Can't include static libraries when not building a static library (they have no IDs
864 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700865 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800866 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700867 return false;
868 }
869
Adam Lesinski8780eb62017-10-31 17:44:39 -0700870 ResourceTable* table = static_apk->GetResourceTable();
871
872 // If we are using --no-static-lib-packages, we need to rename the package of this table to
873 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700874 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800875 // Since package names can differ, and multiple packages can exist in a ResourceTable,
876 // we place the requirement that all static libraries are built with the package
877 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700878 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700879 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800880 } else {
881 context_->GetDiagnostics()->Error(DiagMessage(path)
882 << "no package with ID 0x7f found in static library");
883 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700884 }
885 }
886
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700887 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700888 util::make_unique<ResourceTableSymbolSource>(table));
889 static_library_includes_.push_back(std::move(static_apk));
890 } else {
891 if (!asset_source->AddAssetPath(path)) {
892 context_->GetDiagnostics()->Error(DiagMessage()
893 << "failed to load include path " << path);
894 return false;
895 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700896 }
897 }
898
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800899 // Capture the shared libraries so that the final resource table can be properly flattened
900 // with support for shared libraries.
901 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800902 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800903 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinski490595a2017-11-07 17:08:07 -0800904 } else if (entry.first == kAppPackageId) {
905 // Capture the included base feature package.
906 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800907 } else if (entry.first == kFrameworkPackageId) {
908 // Try to embed which version of the framework we're compiling against.
909 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
910 // when linking our synthesized 'android:compileSdkVersion' attribute.
911 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
912 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
913 if (symbol != nullptr && symbol->is_public) {
914 // The symbol is present and public, extract the android:versionName and
915 // android:versionCode from the framework AndroidManifest.xml.
916 ExtractCompileSdkVersions(asset_source->GetAssetManager());
917 }
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800918 }
919 }
920
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700921 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700922 return true;
923 }
924
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800925 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700926 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800927 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
928 if (manifest_el == nullptr) {
929 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700930 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800931
932 AppInfo app_info;
933
934 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
935 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
936 return {};
937 }
938
939 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
940 if (!package_attr) {
941 diag->Error(DiagMessage(xml_res->file.source)
942 << "<manifest> must have a 'package' attribute");
943 return {};
944 }
945 app_info.package = package_attr->value;
946
947 if (xml::Attribute* version_code_attr =
948 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
949 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
950 if (!maybe_code) {
951 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
952 << "invalid android:versionCode '" << version_code_attr->value << "'");
953 return {};
954 }
955 app_info.version_code = maybe_code.value();
956 }
957
958 if (xml::Attribute* revision_code_attr =
959 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
960 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
961 if (!maybe_code) {
962 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
963 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
964 return {};
965 }
966 app_info.revision_code = maybe_code.value();
967 }
968
969 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
970 if (!split_name_attr->value.empty()) {
971 app_info.split_name = split_name_attr->value;
972 }
973 }
974
975 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
976 if (xml::Attribute* min_sdk =
977 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700978 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800979 }
980 }
981 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700982 }
983
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700984 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
985 // Postcondition: ResourceTable has only one package left. All others are
986 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700987 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700988 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700989 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
990 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700991 };
992
993 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700994 for (const auto& package : final_table_.packages) {
995 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996 // We have a package that is not related to the one we're building!
997 for (const auto& type : package->types) {
998 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700999 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001000
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001001 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001002 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001003 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001004 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1005 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1006 << "generated id '" << res_name
1007 << "' for external package '" << package->name
1008 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001009 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001010 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1011 << "defined resource '" << res_name
1012 << "' for external package '" << package->name
1013 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001014 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001015 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001016 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 }
1018 }
1019 }
1020 }
1021
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001022 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1023 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001024 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001025 return !error;
1026 }
1027
1028 /**
1029 * Returns true if no IDs have been set, false otherwise.
1030 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001031 bool VerifyNoIdsSet() {
1032 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001033 for (const auto& type : package->types) {
1034 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001035 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1036 << StringPrintf("%02x", type->id.value())
1037 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001038 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001039 }
1040
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001041 for (const auto& entry : type->entries) {
1042 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001043 ResourceNameRef res_name(package->name, type->type, entry->name);
1044 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001045 DiagMessage() << "entry " << res_name << " has ID "
1046 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001047 return false;
1048 }
1049 }
1050 }
1051 }
1052 return true;
1053 }
1054
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001055 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1056 if (options_.output_to_directory) {
1057 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001058 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001059 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001060 }
1061 }
1062
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001063 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1064 switch (format) {
1065 case OutputFormat::kApk: {
1066 BigBuffer buffer(1024);
1067 TableFlattener flattener(options_.table_flattener_options, &buffer);
1068 if (!flattener.Consume(context_, table)) {
1069 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1070 return false;
1071 }
1072
1073 io::BigBufferInputStream input_stream(&buffer);
1074 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1075 ArchiveEntry::kAlign, writer);
1076 } break;
1077
1078 case OutputFormat::kProto: {
1079 pb::ResourceTable pb_table;
Ryan Mitchell70414f22018-03-26 11:05:31 -07001080 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001081 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1082 ArchiveEntry::kCompress, writer);
1083 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001084 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001085 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001086 }
1087
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001088 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001089 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001090 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001091 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001092 return true;
1093 }
1094
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001095 std::string out_path;
1096 std::unique_ptr<io::FileOutputStream> fout;
1097 if (options_.generate_java_class_path) {
1098 out_path = options_.generate_java_class_path.value();
1099 file::AppendPath(&out_path, file::PackageToPath(out_package));
1100 if (!file::mkdirs(out_path)) {
1101 context_->GetDiagnostics()->Error(DiagMessage()
1102 << "failed to create directory '" << out_path << "'");
1103 return false;
1104 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001105
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001106 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001107
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001108 fout = util::make_unique<io::FileOutputStream>(out_path);
1109 if (fout->HadError()) {
1110 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1111 << "': " << fout->GetError());
1112 return false;
1113 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001114 }
1115
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001116 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001117 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001118 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1119 if (fout_text->HadError()) {
1120 context_->GetDiagnostics()->Error(DiagMessage()
1121 << "failed writing to '" << out_text_symbols_path.value()
1122 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001123 return false;
1124 }
1125 }
1126
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001127 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001128 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001129 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001130 return false;
1131 }
1132
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001133 return true;
1134 }
1135
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001136 bool GenerateJavaClasses() {
1137 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1138 std::vector<std::string> packages_to_callback;
1139
1140 JavaClassGeneratorOptions template_options;
1141 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1142 template_options.javadoc_annotations = options_.javadoc_annotations;
1143
1144 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1145 template_options.use_final = false;
1146 }
1147
1148 if (context_->GetPackageType() == PackageType::kSharedLib) {
1149 template_options.use_final = false;
1150 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1151 }
1152
1153 const StringPiece actual_package = context_->GetCompilationPackage();
1154 StringPiece output_package = context_->GetCompilationPackage();
1155 if (options_.custom_java_package) {
1156 // Override the output java package to the custom one.
1157 output_package = options_.custom_java_package.value();
1158 }
1159
1160 // Generate the private symbols if required.
1161 if (options_.private_symbols) {
1162 packages_to_callback.push_back(options_.private_symbols.value());
1163
1164 // If we defined a private symbols package, we only emit Public symbols
1165 // to the original package, and private and public symbols to the private package.
1166 JavaClassGeneratorOptions options = template_options;
1167 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1168 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1169 options)) {
1170 return false;
1171 }
1172 }
1173
1174 // Generate copies of the original package R class but with different package names.
1175 // This is to support non-namespaced builds.
1176 for (const std::string& extra_package : options_.extra_java_packages) {
1177 packages_to_callback.push_back(extra_package);
1178
1179 JavaClassGeneratorOptions options = template_options;
1180 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1181 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1182 return false;
1183 }
1184 }
1185
1186 // Generate R classes for each package that was merged (static library).
1187 // Use the actual package's resources only.
1188 for (const std::string& package : table_merger_->merged_packages()) {
1189 packages_to_callback.push_back(package);
1190
1191 JavaClassGeneratorOptions options = template_options;
1192 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1193 if (!WriteJavaFile(&final_table_, package, package, options)) {
1194 return false;
1195 }
1196 }
1197
1198 // Generate the main public R class.
1199 JavaClassGeneratorOptions options = template_options;
1200
1201 // Only generate public symbols if we have a private package.
1202 if (options_.private_symbols) {
1203 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1204 }
1205
1206 if (options.rewrite_callback_options) {
1207 options.rewrite_callback_options.value().packages_to_callback =
1208 std::move(packages_to_callback);
1209 }
1210
1211 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1212 options_.generate_text_symbols_path)) {
1213 return false;
1214 }
1215
1216 return true;
1217 }
1218
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001219 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1220 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 return true;
1222 }
1223
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001224 std::unique_ptr<ClassDefinition> manifest_class =
1225 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001226
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 // Something bad happened, but we already logged it, so exit.
1229 return false;
1230 }
1231
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001232 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233 // Empty Manifest class, no need to generate it.
1234 return true;
1235 }
1236
1237 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001238 for (const std::string& annotation : options_.javadoc_annotations) {
1239 std::string proper_annotation = "@";
1240 proper_annotation += annotation;
1241 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001242 }
1243
Adam Lesinski0d81f702017-06-27 15:51:09 -07001244 const std::string package_utf8 =
1245 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001246
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001247 std::string out_path = options_.generate_java_class_path.value();
1248 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001249
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001250 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001251 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1252 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253 return false;
1254 }
1255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001258 io::FileOutputStream fout(out_path);
1259 if (fout.HadError()) {
1260 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1261 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001262 return false;
1263 }
1264
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001265 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1266 fout.Flush();
1267
1268 if (fout.HadError()) {
1269 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1270 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001271 return false;
1272 }
1273 return true;
1274 }
1275
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001276 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001277 if (!out) {
1278 return true;
1279 }
1280
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001281 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001282 io::FileOutputStream fout(out_path);
1283 if (fout.HadError()) {
1284 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1285 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001286 return false;
1287 }
1288
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001289 proguard::WriteKeepSet(keep_set, &fout);
1290 fout.Flush();
1291
1292 if (fout.HadError()) {
1293 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1294 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001295 return false;
1296 }
1297 return true;
1298 }
1299
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001300 bool MergeStaticLibrary(const std::string& input, bool override) {
1301 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001302 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001303 }
1304
Adam Lesinski8780eb62017-10-31 17:44:39 -07001305 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1306 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001307 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308 return false;
1309 }
1310
Adam Lesinski8780eb62017-10-31 17:44:39 -07001311 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001312 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001313 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001314 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001315 return false;
1316 }
1317
1318 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001319 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001320 // Merge all resources as if they were in the compilation package. This is the old behavior
1321 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001322
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001323 // Add the package to the set of --extra-packages so we emit an R.java for each library
1324 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001325 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001326 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001327 }
1328
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001329 // Clear the package name, so as to make the resources look like they are coming from the
1330 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001331 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001332 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001333
1334 } else {
1335 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001336 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001337 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001338 }
1339
1340 if (!result) {
1341 return false;
1342 }
1343
1344 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001345 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001346 return true;
1347 }
1348
Adam Lesinski2427dce2017-11-30 15:10:28 -08001349 bool MergeExportedSymbols(const Source& source,
1350 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001351 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001352 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001353 ResourceName res_name = exported_symbol.name;
1354 if (res_name.package.empty()) {
1355 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001356 }
1357
Adam Lesinski00451162017-10-03 07:44:08 -07001358 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001359 if (mangled_name) {
1360 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001361 }
1362
1363 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001364 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001365 bool result =
1366 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1367 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001368 if (!result) {
1369 return false;
1370 }
1371 }
1372 return true;
1373 }
1374
Adam Lesinski2427dce2017-11-30 15:10:28 -08001375 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1376 if (context_->IsVerbose()) {
1377 context_->GetDiagnostics()->Note(DiagMessage()
1378 << "merging '" << compiled_file.name
1379 << "' from compiled file " << compiled_file.source);
1380 }
1381
1382 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1383 return false;
1384 }
1385 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1386 }
1387
Adam Lesinski00451162017-10-03 07:44:08 -07001388 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1389 // If override is true, conflicting resources are allowed to override each other, in order of last
1390 // seen.
1391 // An io::IFileCollection is created from the ZIP file and added to the set of
1392 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001393 bool MergeArchive(const std::string& input, bool override) {
1394 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001395 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001396 }
1397
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001398 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001399 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001400 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001401 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001402 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403 return false;
1404 }
1405
1406 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001407 for (auto iter = collection->Iterator(); iter->HasNext();) {
1408 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001409 error = true;
1410 }
1411 }
1412
1413 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001414 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001415 return !error;
1416 }
1417
Adam Lesinski00451162017-10-03 07:44:08 -07001418 // Takes a path to load and merge into the master ResourceTable. If override is true,
1419 // conflicting resources are allowed to override each other, in order of last seen.
1420 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1421 // as ZIP archive and the files within are merged individually.
1422 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001423 bool MergePath(const std::string& path, bool override) {
1424 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1425 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1426 return MergeArchive(path, override);
1427 } else if (util::EndsWith(path, ".apk")) {
1428 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001429 }
1430
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001431 io::IFile* file = file_collection_->InsertFile(path);
1432 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001433 }
1434
Adam Lesinski00451162017-10-03 07:44:08 -07001435 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1436 // If override is true, conflicting resources are allowed to override each other, in order of last
1437 // seen.
1438 // All other file types are ignored. This is because these files could be coming from a zip,
1439 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001440 bool MergeFile(io::IFile* file, bool override) {
1441 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001442
Adam Lesinski00451162017-10-03 07:44:08 -07001443 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001444 // Since AAPT compiles these file types and appends .flat to them, seeing
1445 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001446 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1447 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1448 << " file passed as argument. Must be "
1449 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001450 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001451 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1452 if (context_->IsVerbose()) {
1453 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1454 return true;
1455 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001456 }
1457
Adam Lesinski00451162017-10-03 07:44:08 -07001458 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1459 if (input_stream == nullptr) {
1460 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1461 return false;
1462 }
1463
1464 if (input_stream->HadError()) {
1465 context_->GetDiagnostics()->Error(DiagMessage(src)
1466 << "failed to open file: " << input_stream->GetError());
1467 return false;
1468 }
1469
1470 ContainerReaderEntry* entry;
1471 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001472
1473 if (reader.HadError()) {
1474 context_->GetDiagnostics()->Error(DiagMessage(src)
1475 << "failed to read file: " << reader.GetError());
1476 return false;
1477 }
1478
Adam Lesinski00451162017-10-03 07:44:08 -07001479 while ((entry = reader.Next()) != nullptr) {
1480 if (entry->Type() == ContainerEntryType::kResTable) {
1481 pb::ResourceTable pb_table;
1482 if (!entry->GetResTable(&pb_table)) {
1483 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1484 << entry->GetError());
1485 return false;
1486 }
1487
1488 ResourceTable table;
1489 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001490 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001491 context_->GetDiagnostics()->Error(DiagMessage(src)
1492 << "failed to deserialize resource table: " << error);
1493 return false;
1494 }
1495
1496 if (!table_merger_->Merge(src, &table, override)) {
1497 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1498 return false;
1499 }
1500 } else if (entry->Type() == ContainerEntryType::kResFile) {
1501 pb::internal::CompiledFile pb_compiled_file;
1502 off64_t offset;
1503 size_t len;
1504 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1505 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1506 << entry->GetError());
1507 return false;
1508 }
1509
1510 ResourceFile resource_file;
1511 std::string error;
1512 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1513 context_->GetDiagnostics()->Error(DiagMessage(src)
1514 << "failed to read compiled header: " << error);
1515 return false;
1516 }
1517
1518 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1519 return false;
1520 }
1521 }
1522 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001523 return true;
1524 }
1525
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001526 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1527 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1528 for (const std::string& assets_dir : options_.assets_dirs) {
1529 Maybe<std::vector<std::string>> files =
1530 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1531 if (!files) {
1532 return false;
1533 }
1534
1535 for (const std::string& file : files.value()) {
1536 std::string full_key = "assets/" + file;
1537 std::string full_path = assets_dir;
1538 file::AppendPath(&full_path, file);
1539
1540 auto iter = merged_assets.find(full_key);
1541 if (iter == merged_assets.end()) {
1542 merged_assets.emplace(std::move(full_key),
1543 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1544 } else if (context_->IsVerbose()) {
1545 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1546 << "asset file overrides '" << full_path << "'");
1547 }
1548 }
1549 }
1550
1551 for (auto& entry : merged_assets) {
1552 uint32_t compression_flags = ArchiveEntry::kCompress;
1553 std::string extension = file::GetExtension(entry.first).to_string();
1554 if (options_.extensions_to_not_compress.count(extension) > 0) {
1555 compression_flags = 0u;
1556 }
1557
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001558 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1559 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001560 return false;
1561 }
1562 }
1563 return true;
1564 }
1565
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001566 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1567 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001568 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1569 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001570 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001571 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1572 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001573 if (!result) {
1574 return false;
1575 }
1576
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001577 ResourceFileFlattenerOptions file_flattener_options;
1578 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001579 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1580 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001581 file_flattener_options.no_auto_version = options_.no_auto_version;
1582 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001583 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001584 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1585 file_flattener_options.update_proguard_spec =
1586 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001587 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001588
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001589 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001590
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001591 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001592 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001593 return false;
1594 }
1595
Adam Lesinski490595a2017-11-07 17:08:07 -08001596 // Hack to fix b/68820737.
1597 // We need to modify the ResourceTable's package name, but that should NOT affect
1598 // anything else being generated, which includes the Java classes.
1599 // If required, the package name is modifed before flattening, and then modified back
1600 // to its original name.
1601 ResourceTablePackage* package_to_rewrite = nullptr;
1602 if (context_->GetPackageId() > kAppPackageId &&
1603 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1604 // The base APK is included, and this is a feature split. If the base package is
1605 // the same as this package, then we are building an old style Android Instant Apps feature
1606 // split and must apply this workaround to avoid requiring namespaces support.
1607 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1608 if (package_to_rewrite != nullptr) {
1609 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1610
1611 std::string new_package_name =
1612 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1613 app_info_.split_name.value_or_default("feature").c_str());
1614
1615 if (context_->IsVerbose()) {
1616 context_->GetDiagnostics()->Note(
1617 DiagMessage() << "rewriting resource package name for feature split to '"
1618 << new_package_name << "'");
1619 }
1620 package_to_rewrite->name = new_package_name;
1621 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001622 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001623
1624 bool success = FlattenTable(table, options_.output_format, writer);
1625
1626 if (package_to_rewrite != nullptr) {
1627 // Change the name back.
1628 package_to_rewrite->name = context_->GetCompilationPackage();
1629 if (package_to_rewrite->id) {
1630 table->included_packages_.erase(package_to_rewrite->id.value());
1631 }
1632 }
1633
1634 if (!success) {
1635 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1636 }
1637 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001638 }
1639
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001640 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001641 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001642 std::unique_ptr<xml::XmlResource> manifest_xml =
1643 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1644 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001645 return 1;
1646 }
1647
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001648 // First extract the Package name without modifying it (via --rename-manifest-package).
1649 if (Maybe<AppInfo> maybe_app_info =
1650 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001651 const AppInfo& app_info = maybe_app_info.value();
1652 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001653 }
1654
Adam Lesinskic6284372017-12-04 13:46:23 -08001655 // Now that the compilation package is set, load the dependencies. This will also extract
1656 // the Android framework's versionCode and versionName, if they exist.
1657 if (!LoadSymbolsFromIncludePaths()) {
1658 return 1;
1659 }
1660
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001661 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1662 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001663 return 1;
1664 }
1665
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001666 Maybe<AppInfo> maybe_app_info =
1667 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001668 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001669 return 1;
1670 }
1671
Adam Lesinski490595a2017-11-07 17:08:07 -08001672 app_info_ = maybe_app_info.value();
1673 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001674
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001675 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001676
1677 // Override the package ID when it is "android".
1678 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001679 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001680
1681 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001682 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001683 context_->GetDiagnostics()->Error(
1684 DiagMessage() << "package 'android' can only be built as a regular app");
1685 return 1;
1686 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001687 }
1688
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001689 TableMergerOptions table_merger_options;
1690 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001691 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001692
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001693 if (context_->IsVerbose()) {
1694 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001695 << StringPrintf("linking package '%s' using package ID %02x",
1696 context_->GetCompilationPackage().data(),
1697 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001698 }
1699
Adam Lesinski2427dce2017-11-30 15:10:28 -08001700 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1701 // in res/**/*.
1702 {
1703 XmlIdCollector collector;
1704 if (!collector.Consume(context_, manifest_xml.get())) {
1705 return false;
1706 }
1707
1708 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1709 return false;
1710 }
1711 }
1712
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001713 for (const std::string& input : input_files) {
1714 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001715 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001716 return 1;
1717 }
1718 }
1719
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001720 for (const std::string& input : options_.overlay_files) {
1721 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001722 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001723 return 1;
1724 }
1725 }
1726
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001727 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001728 return 1;
1729 }
1730
Adam Lesinskib522f042017-04-21 16:57:59 -07001731 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001732 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001733 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001734 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001735 return 1;
1736 }
1737
1738 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001739 IdAssigner id_assigner(&options_.stable_id_map);
1740 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001741 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001742 return 1;
1743 }
1744
1745 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001746 if (options_.resource_id_map_path) {
1747 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001748 for (auto& type : package->types) {
1749 for (auto& entry : type->entries) {
1750 ResourceName name(package->name, type->type, entry->name);
1751 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001752 options_.stable_id_map[std::move(name)] =
1753 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001754 }
1755 }
1756 }
1757
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001758 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001759 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001760 return 1;
1761 }
1762 }
1763 } else {
1764 // Static libs are merged with other apps, and ID collisions are bad, so
1765 // verify that
1766 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001767 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001768 return 1;
1769 }
1770 }
1771
1772 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001773 context_->SetNameManglerPolicy(
1774 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001775
1776 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001777 context_->GetExternalSymbols()->PrependSource(
1778 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001779
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001780 // Workaround for pre-O runtime that would treat negative resource IDs
1781 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1782 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1783 // are just identifiers.
1784 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1785 if (context_->IsVerbose()) {
1786 context_->GetDiagnostics()->Note(DiagMessage()
1787 << "enabling pre-O feature split ID rewriting");
1788 }
1789 context_->GetExternalSymbols()->SetDelegate(
1790 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1791 }
1792
Adam Lesinski34a16872018-02-23 16:18:10 -08001793 // Before we process anything, remove the resources whose default values don't exist.
1794 // We want to force any references to these to fail the build.
1795 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1796 context_->GetDiagnostics()->Error(DiagMessage()
1797 << "failed removing resources with no defaults");
1798 return 1;
1799 }
1800
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001801 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001802 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001803 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001804 return 1;
1805 }
1806
Adam Lesinskib522f042017-04-21 16:57:59 -07001807 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001808 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001809 context_->GetDiagnostics()->Warn(DiagMessage()
1810 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001811 }
1812 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001813 ProductFilter product_filter(options_.products);
1814 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001815 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001816 return 1;
1817 }
1818 }
1819
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001820 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001822 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001823 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824 return 1;
1825 }
1826 }
1827
Adam Lesinskib522f042017-04-21 16:57:59 -07001828 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001829 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001830 context_->GetDiagnostics()->Note(DiagMessage()
1831 << "collapsing resource versions for minimum SDK "
1832 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001833 }
1834
1835 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001836 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001837 return 1;
1838 }
1839 }
1840
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001841 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001842 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001843 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001844 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845 return 1;
1846 }
1847 }
1848
Adam Koskidc21dea2017-07-21 10:55:27 -07001849 proguard::KeepSet proguard_keep_set =
1850 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001851 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852
Adam Lesinskib522f042017-04-21 16:57:59 -07001853 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001855 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001856 context_->GetDiagnostics()->Warn(DiagMessage()
1857 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001858 }
1859 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001860 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1861 // equal to the minSdk.
1862 options_.split_constraints =
1863 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001864
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001865 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001866 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867 return 1;
1868 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001870
1871 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001872 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001873 auto split_constraints_iter = options_.split_constraints.begin();
1874 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001875 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001876 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1877 << "generating split with configurations '"
1878 << util::Joiner(split_constraints_iter->configs, ", ")
1879 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001880 }
1881
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001882 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001883 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001884 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001885 return 1;
1886 }
1887
1888 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001889 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001890 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001891
1892 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001893 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 context_->GetDiagnostics()->Error(DiagMessage()
1895 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001896 return 1;
1897 }
1898
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001899 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1900 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001901 return 1;
1902 }
1903
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 ++path_iter;
1905 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001906 }
1907 }
1908
1909 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001910 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001911 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001912 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001913 return 1;
1914 }
1915
1916 bool error = false;
1917 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001918 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001919 // (aka, which package the AndroidManifest.xml is coming from).
1920 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001921 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001922
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001923 XmlReferenceLinker manifest_linker;
1924 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1925 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001926 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001927 error = true;
1928 }
1929
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001930 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001931 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001932 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001933 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001934 }
1935
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001936 if (options_.generate_java_class_path) {
1937 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001938 error = true;
1939 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001940 }
1941
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001942 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001943 // PackageParser will fail if URIs are removed from
1944 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001945 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1946 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001947 error = true;
1948 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001949 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001950 } else {
1951 error = true;
1952 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001953 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001954
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001955 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001956 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001957 return 1;
1958 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001959
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001960 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1961 return 1;
1962 }
1963
1964 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001965 return 1;
1966 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001967
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001968 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001969 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001970 return 1;
1971 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001972 }
1973
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001974 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975 return 1;
1976 }
1977
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001978 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1979 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001980 return 1;
1981 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001982 return 0;
1983 }
1984
1985 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001986 LinkOptions options_;
1987 LinkContext* context_;
1988 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001989
Adam Lesinski490595a2017-11-07 17:08:07 -08001990 AppInfo app_info_;
1991
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001992 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001993
1994 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001995 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001996
Adam Lesinski8780eb62017-10-31 17:44:39 -07001997 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001998 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001999 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000
Adam Lesinski8780eb62017-10-31 17:44:39 -07002001 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2002 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2003
2004 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2005 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002006
2007 // The set of shared libraries being used, mapping their assigned package ID to package name.
2008 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002009
2010 // The package name of the base application, if it is included.
2011 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002012};
2013
Chris Warrington820d72a2017-04-27 15:27:01 +01002014int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2015 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002016 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002017 std::vector<std::string> overlay_arg_list;
2018 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002019 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002020 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002021 Maybe<std::string> preferred_density;
2022 Maybe<std::string> product_list;
2023 bool legacy_x_flag = false;
2024 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002025 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002026 bool shared_lib = false;
2027 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002028 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002029 Maybe<std::string> stable_id_file_path;
2030 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002031 Flags flags =
2032 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002033 .RequiredFlag("-o", "Output path.", &options.output_path)
2034 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002035 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002036 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002037 .OptionalFlagList("-A",
2038 "An assets directory to include in the APK. These are unprocessed.",
2039 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002040 .OptionalFlagList("-R",
2041 "Compilation unit to link, using `overlay` semantics.\n"
2042 "The last conflicting resource given takes precedence.",
2043 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002044 .OptionalFlag("--package-id",
2045 "Specify the package ID to use for this app. Must be greater or equal to\n"
2046 "0x7f and can't be used with --static-lib or --shared-lib.",
2047 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002048 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002049 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002050 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002051 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002052 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002053 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002054 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002055 .OptionalSwitch("--proguard-conditional-keep-rules",
2056 "Generate conditional Proguard keep rules.",
2057 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002058 .OptionalSwitch("--no-auto-version",
2059 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002060 &options.no_auto_version)
2061 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002062 "Disables automatic versioning of vector drawables. Use this only\n"
2063 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002064 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002065 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002066 "Disables automatic versioning of transition resources. Use this only\n"
2067 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002068 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002069 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002070 "Disables automatic deduping of resources with\n"
2071 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002072 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002073 .OptionalSwitch("--enable-sparse-encoding",
2074 "Enables encoding sparse entries using a binary search tree.\n"
2075 "This decreases APK size at the cost of resource retrieval performance.",
2076 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002077 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002078 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002079 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002080 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002081 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002082 "Comma separated list of configurations to include. The default\n"
2083 "is all configurations.",
2084 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002085 .OptionalFlag("--preferred-density",
2086 "Selects the closest matching density and strips out all others.",
2087 &preferred_density)
2088 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002089 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002090 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002091 &options.output_to_directory)
2092 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002093 "Removes XML namespace prefix and URI information from\n"
2094 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002095 &options.no_xml_namespaces)
2096 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002097 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002098 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002099 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002100 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002101 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002102 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002103 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2104 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002105 &options.manifest_fixer_options.version_code_default)
2106 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002107 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002108 &options.manifest_fixer_options.version_name_default)
Todd Kennedy9f6dec12018-04-20 12:29:29 -07002109 .OptionalFlag("--compile-sdk-version-code",
2110 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2111 "present.",
2112 &options.manifest_fixer_options.compile_sdk_version)
2113 .OptionalFlag("--compile-sdk-version-name",
2114 "Version name to inject into the AndroidManifest.xml if none is present.",
2115 &options.manifest_fixer_options.compile_sdk_version_codename)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002116 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2117 &shared_lib)
2118 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002119 .OptionalSwitch("--proto-format",
2120 "Generates compiled resources in Protobuf format.\n"
2121 "Suitable as input to the bundle tool for generating an App Bundle.",
2122 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002123 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002124 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002125 &options.no_static_lib_packages)
2126 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002127 "Generates R.java without the final modifier. This is implied when\n"
2128 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002129 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002130 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002131 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002132 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002133 "Emit a file at the given path with a list of name to ID mappings,\n"
2134 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002135 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002136 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002137 "Package name to use when generating R.java for private symbols.\n"
2138 "If not specified, public and private symbols will use the application's\n"
2139 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002140 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002141 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002142 &options.custom_java_package)
2143 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002144 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002145 &extra_java_packages)
2146 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002147 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002149 .OptionalFlag("--output-text-symbols",
2150 "Generates a text file containing the resource symbols of the R class in\n"
2151 "the specified folder.",
2152 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002154 "Allows the addition of new resources in overlays without\n"
2155 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002156 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002157 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002158 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002159 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002160 "Changes the name of the target package for instrumentation. Most useful\n"
2161 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002162 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002163 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002164 &options.extensions_to_not_compress)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002165 .OptionalSwitch("--warn-manifest-validation",
2166 "Treat manifest validation errors as warnings.",
2167 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002168 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002169 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002170 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2171 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002172 &split_args)
Ryan Mitchelle5b38a62018-03-23 13:35:00 -07002173 .OptionalSwitch("-v", "Enables verbose logging.", &verbose)
2174 .OptionalSwitch("--debug-mode",
2175 "Inserts android:debuggable=\"true\" in to the application node of the\n"
2176 "manifest, making the application debuggable even on production devices.",
2177 &options.manifest_fixer_options.debug_mode);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002178
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002179 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002180 return 1;
2181 }
2182
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002183 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002184 std::vector<std::string> arg_list;
2185 for (const std::string& arg : flags.GetArgs()) {
2186 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002187 const std::string path = arg.substr(1, arg.size() - 1);
2188 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002189 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2190 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002191 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002192 }
2193 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002194 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002195 }
2196 }
2197
2198 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002199 for (const std::string& arg : overlay_arg_list) {
2200 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002201 const std::string path = arg.substr(1, arg.size() - 1);
2202 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002203 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2204 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002205 return 1;
2206 }
2207 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002208 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002209 }
2210 }
2211
2212 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002213 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002214 }
2215
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002216 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2217 context.GetDiagnostics()->Error(
2218 DiagMessage()
2219 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002220 return 1;
2221 }
2222
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002223 // The default build type.
2224 context.SetPackageType(PackageType::kApp);
2225 context.SetPackageId(kAppPackageId);
2226
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002227 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002228 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002229 context.SetPackageId(0x00);
2230 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002231 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002232 options.output_format = OutputFormat::kProto;
2233 } else if (proto_format) {
2234 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002235 }
2236
2237 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002238 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002239 context.GetDiagnostics()->Error(
2240 DiagMessage() << "can't specify --package-id when not building a regular app");
2241 return 1;
2242 }
2243
2244 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2245 if (!maybe_package_id_int) {
2246 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2247 << "' is not a valid integer");
2248 return 1;
2249 }
2250
2251 const uint32_t package_id_int = maybe_package_id_int.value();
2252 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2253 context.GetDiagnostics()->Error(
2254 DiagMessage() << StringPrintf(
2255 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2256 return 1;
2257 }
2258 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2259 }
2260
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002261 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002262 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002263 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002264 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002265 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002266 }
2267 }
2268
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002269 if (product_list) {
2270 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002271 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002272 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002273 }
2274 }
2275 }
2276
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002277 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002278 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002279 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2280 if (filter == nullptr) {
2281 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002282 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002283 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002284 }
2285
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002286 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002287 Maybe<uint16_t> density =
2288 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2289 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002290 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002291 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002292 options.table_splitter_options.preferred_densities.push_back(density.value());
2293 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002294
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002295 // Parse the split parameters.
2296 for (const std::string& split_arg : split_args) {
2297 options.split_paths.push_back({});
2298 options.split_constraints.push_back({});
2299 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2300 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002301 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002302 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002303 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002304
Adam Lesinskib522f042017-04-21 16:57:59 -07002305 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002306 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2307 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002308 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002309 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002310 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002311
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002312 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002313 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002314 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2315 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2316 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2317 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2318
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002319 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002320 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002321 options.no_auto_version = true;
2322 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002323 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002324 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002325
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002326 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002327 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002328}
2329
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002330} // namespace aapt