blob: 75eba9e7f5daaffe3889ffcfa9eca2c1eb69f85a [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
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050020#include <algorithm>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021#include <queue>
22#include <unordered_map>
23#include <vector>
24
25#include "android-base/errors.h"
26#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080027#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080028#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070029
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "AppInfo.h"
31#include "Debug.h"
32#include "Flags.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070033#include "LoadedApk.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080034#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070035#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080036#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070037#include "ResourceValues.h"
38#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070039#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070040#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080041#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080042#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070043#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070044#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070045#include "format/binary/TableFlattener.h"
46#include "format/binary/XmlFlattener.h"
47#include "format/proto/ProtoDeserialize.h"
48#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070049#include "io/BigBufferStream.h"
50#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080051#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070052#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080053#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070054#include "java/JavaClassGenerator.h"
55#include "java/ManifestClassGenerator.h"
56#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070057#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070058#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080059#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080060#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070061#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070062#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080063#include "optimize/ResourceDeduper.h"
64#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070065#include "process/IResourceTableConsumer.h"
66#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080067#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080069#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070070
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070071using ::aapt::io::FileInputStream;
72using ::android::StringPiece;
73using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070074
Adam Lesinski1ab598f2015-08-14 14:26:04 -070075namespace aapt {
76
Adam Lesinskie59f0d82017-10-13 09:36:53 -070077enum class OutputFormat {
78 kApk,
79 kProto,
80};
81
Adam Lesinski1ab598f2015-08-14 14:26:04 -070082struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070083 std::string output_path;
84 std::string manifest_path;
85 std::vector<std::string> include_paths;
86 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070087 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070088 bool output_to_directory = false;
89 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070090 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070091
Adam Lesinskicacb28f2016-10-19 12:18:14 -070092 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070093 Maybe<std::string> generate_java_class_path;
94 Maybe<std::string> custom_java_package;
95 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070096 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070097 Maybe<std::string> generate_proguard_rules_path;
98 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070099 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700100 bool generate_non_final_ids = false;
101 std::vector<std::string> javadoc_annotations;
102 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700103
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 // Optimizations/features.
105 bool no_auto_version = false;
106 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900107 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700108 bool no_resource_deduping = false;
109 bool no_xml_namespaces = false;
110 bool do_not_compress_anything = false;
111 std::unordered_set<std::string> extensions_to_not_compress;
112
113 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700114 bool no_static_lib_packages = false;
Chris Warrington481f0272018-02-06 14:03:39 +0000115 bool auto_namespace_static_lib = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700116
117 // AndroidManifest.xml massaging options.
118 ManifestFixerOptions manifest_fixer_options;
119
120 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700122
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800123 // Flattening options.
124 TableFlattenerOptions table_flattener_options;
125
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700127 TableSplitterOptions table_splitter_options;
128 std::vector<SplitConstraints> split_constraints;
129 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700130
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700131 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700132 std::unordered_map<ResourceName, ResourceId> stable_id_map;
133 Maybe<std::string> resource_id_map_path;
Todd Kennedy32512992018-04-25 16:45:59 -0700134
135 // When 'true', allow reserved package IDs to be used for applications. Pre-O, the platform
136 // treats negative resource IDs [those with a package ID of 0x80 or higher] as invalid.
137 // In order to work around this limitation, we allow the use of traditionally reserved
138 // resource IDs [those between 0x02 and 0x7E].
139 bool allow_reserved_package_id = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700140};
141
Adam Lesinski64587af2016-02-18 18:33:06 -0800142class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700143 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100144 LinkContext(IDiagnostics* diagnostics)
145 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700146 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700147
Adam Lesinskib522f042017-04-21 16:57:59 -0700148 PackageType GetPackageType() override {
149 return package_type_;
150 }
151
152 void SetPackageType(PackageType type) {
153 package_type_ = type;
154 }
155
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700156 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100157 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700158 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700159
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700160 NameMangler* GetNameMangler() override {
161 return &name_mangler_;
162 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700163
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700164 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
165 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700166 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800167
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700168 const std::string& GetCompilationPackage() override {
169 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700170 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700171
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700172 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800173 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700174 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800175
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700176 uint8_t GetPackageId() override {
177 return package_id_;
178 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700179
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700180 void SetPackageId(uint8_t id) {
181 package_id_ = id;
182 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800183
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700184 SymbolTable* GetExternalSymbols() override {
185 return &symbols_;
186 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800187
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700188 bool IsVerbose() override {
189 return verbose_;
190 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800191
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700192 void SetVerbose(bool val) {
193 verbose_ = val;
194 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800195
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700196 int GetMinSdkVersion() override {
197 return min_sdk_version_;
198 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700199
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700200 void SetMinSdkVersion(int minSdk) {
201 min_sdk_version_ = minSdk;
202 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700203
Chris Warrington481f0272018-02-06 14:03:39 +0000204 bool IsAutoNamespace() override {
205 return auto_namespace_;
206 }
207
208 void SetAutoNamespace(bool val) {
209 auto_namespace_ = val;
210 }
211
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700212 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700213 DISALLOW_COPY_AND_ASSIGN(LinkContext);
214
Adam Lesinskib522f042017-04-21 16:57:59 -0700215 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100216 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700217 NameMangler name_mangler_;
218 std::string compilation_package_;
219 uint8_t package_id_ = 0x0;
220 SymbolTable symbols_;
221 bool verbose_ = false;
222 int min_sdk_version_ = 0;
Chris Warrington481f0272018-02-06 14:03:39 +0000223 bool auto_namespace_ = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700224};
225
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700226// A custom delegate that generates compatible pre-O IDs for use with feature splits.
227// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
228// is interpreted as a negative number. Some verification was wrongly assuming negative values
229// were invalid.
230//
231// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
232// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
233// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800234//
235// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700236class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
237 public:
238 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
239 }
240
241 virtual ~FeatureSplitSymbolTableDelegate() = default;
242
243 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
244 const ResourceName& name,
245 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
246 std::unique_ptr<SymbolTable::Symbol> symbol =
247 DefaultSymbolTableDelegate::FindByName(name, sources);
248 if (symbol == nullptr) {
249 return {};
250 }
251
252 // Check to see if this is an 'id' with the target package.
253 if (name.type == ResourceType::kId && symbol->id) {
254 ResourceId* id = &symbol->id.value();
255 if (id->package_id() > kAppPackageId) {
256 // Rewrite the resource ID to be compatible pre-O.
257 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
258
259 // Check that this doesn't overlap another resource.
260 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
261 // The ID overlaps, so log a message (since this is a weird failure) and fail.
262 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
263 << " for pre-O feature split support");
264 return {};
265 }
266
267 if (context_->IsVerbose()) {
268 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
269 << ") -> (" << rewritten_id << ")");
270 }
271
272 *id = rewritten_id;
273 }
274 }
275 return symbol;
276 }
277
278 private:
279 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
280
281 IAaptContext* context_;
282};
283
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700284static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
285 const StringPiece& path, bool keep_raw_values, bool utf16,
286 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700287 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700288 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
289 << (keep_raw_values ? "true" : "false")
290 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700291 }
292
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700293 switch (format) {
294 case OutputFormat::kApk: {
295 BigBuffer buffer(1024);
296 XmlFlattenerOptions options = {};
297 options.keep_raw_values = keep_raw_values;
298 options.use_utf16 = utf16;
299 XmlFlattener flattener(&buffer, options);
300 if (!flattener.Consume(context, &xml_res)) {
301 return false;
302 }
303
304 io::BigBufferInputStream input_stream(&buffer);
305 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
306 ArchiveEntry::kCompress, writer);
307 } break;
308
309 case OutputFormat::kProto: {
310 pb::XmlNode pb_node;
311 SerializeXmlResourceToPb(xml_res, &pb_node);
312 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
313 writer);
314 } break;
315 }
316 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800317}
318
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700319// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700320static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700321 FileInputStream fin(path);
322 if (fin.HadError()) {
323 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700324 return {};
325 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700326 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800327}
328
Adam Lesinski355f2852016-02-13 20:26:45 -0800329struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700330 bool no_auto_version = false;
331 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900332 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700333 bool no_xml_namespaces = false;
334 bool keep_raw_values = false;
335 bool do_not_compress_anything = false;
336 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700337 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700338 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800339};
340
Adam Lesinskic744ae82017-05-17 19:28:38 -0700341// A sampling of public framework resource IDs.
342struct R {
343 struct attr {
344 enum : uint32_t {
345 paddingLeft = 0x010100d6u,
346 paddingRight = 0x010100d8u,
347 paddingHorizontal = 0x0101053du,
348
349 paddingTop = 0x010100d7u,
350 paddingBottom = 0x010100d9u,
351 paddingVertical = 0x0101053eu,
352
353 layout_marginLeft = 0x010100f7u,
354 layout_marginRight = 0x010100f9u,
355 layout_marginHorizontal = 0x0101053bu,
356
357 layout_marginTop = 0x010100f8u,
358 layout_marginBottom = 0x010100fau,
359 layout_marginVertical = 0x0101053cu,
360 };
361 };
362};
363
Adam Lesinski355f2852016-02-13 20:26:45 -0800364class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700365 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700366 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700367 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800368
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700369 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800370
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700371 private:
372 struct FileOperation {
373 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700374
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700375 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700376 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700377
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700378 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700379 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700380
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700381 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700382 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700383
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700384 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700385 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700386 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800387
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700388 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800389
Adam Lesinskic744ae82017-05-17 19:28:38 -0700390 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
391 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800392
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700393 ResourceFileFlattenerOptions options_;
394 IAaptContext* context_;
395 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700396 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800397};
398
Adam Lesinskic744ae82017-05-17 19:28:38 -0700399ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
400 IAaptContext* context, proguard::KeepSet* keep_set)
401 : options_(options), context_(context), keep_set_(keep_set) {
402 SymbolTable* symm = context_->GetExternalSymbols();
403
404 // Build up the rules for degrading newer attributes to older ones.
405 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
406 // generated from the attribute definitions themselves (b/62028956).
407 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
408 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800409 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
410 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700411 };
412 rules_[R::attr::paddingHorizontal] =
413 util::make_unique<DegradeToManyRule>(std::move(replacements));
414 }
415
416 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
417 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800418 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
419 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700420 };
421 rules_[R::attr::paddingVertical] =
422 util::make_unique<DegradeToManyRule>(std::move(replacements));
423 }
424
425 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
426 std::vector<ReplacementAttr> replacements{
427 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800428 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700429 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800430 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700431 };
432 rules_[R::attr::layout_marginHorizontal] =
433 util::make_unique<DegradeToManyRule>(std::move(replacements));
434 }
435
436 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
437 std::vector<ReplacementAttr> replacements{
438 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800439 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700440 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800441 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700442 };
443 rules_[R::attr::layout_marginVertical] =
444 util::make_unique<DegradeToManyRule>(std::move(replacements));
445 }
446}
447
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700448uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
449 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700450 return 0;
451 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800452
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700453 for (const std::string& extension : options_.extensions_to_not_compress) {
454 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700455 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800456 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700457 }
458 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800459}
460
Adam Lesinskibb94f322017-07-12 07:41:55 -0700461static bool IsTransitionElement(const std::string& name) {
462 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
463 name == "changeImageTransform" || name == "changeTransform" ||
464 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
465 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
466 name == "transitionManager";
467}
468
469static bool IsVectorElement(const std::string& name) {
470 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000471 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700472}
473
Adam Lesinskic744ae82017-05-17 19:28:38 -0700474template <typename T>
475std::vector<T> make_singleton_vec(T&& val) {
476 std::vector<T> vec;
477 vec.emplace_back(std::forward<T>(val));
478 return vec;
479}
480
481std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
482 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700483 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700484 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700485
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700486 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700487 context_->GetDiagnostics()->Note(DiagMessage()
488 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700489 }
490
Adam Lesinski00451162017-10-03 07:44:08 -0700491 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
492 // that existing projects have out-of-date references which pass compilation.
493 xml::StripAndroidStudioAttributes(doc->root.get());
494
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700495 XmlReferenceLinker xml_linker;
496 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700497 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700498 }
499
Adam Koskidc21dea2017-07-21 10:55:27 -0700500 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700501 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700502 }
503
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700504 if (options_.no_xml_namespaces) {
505 XmlNamespaceRemover namespace_remover;
506 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700507 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800508 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700509 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800510
Adam Lesinskibb94f322017-07-12 07:41:55 -0700511 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700512 return make_singleton_vec(std::move(file_op->xml_to_flatten));
513 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700514
Adam Lesinskibb94f322017-07-12 07:41:55 -0700515 if (options_.no_version_vectors || options_.no_version_transitions) {
516 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700517 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700518 if (el && el->namespace_uri.empty()) {
519 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
520 (options_.no_version_transitions && IsTransitionElement(el->name))) {
521 return make_singleton_vec(std::move(file_op->xml_to_flatten));
522 }
523 }
524 }
525
Adam Lesinskic744ae82017-05-17 19:28:38 -0700526 const ConfigDescription& config = file_op->config;
527 ResourceEntry* entry = file_op->entry;
528
529 XmlCompatVersioner xml_compat_versioner(&rules_);
530 const util::Range<ApiVersion> api_range{config.sdkVersion,
531 FindNextApiVersionForConfig(entry, config)};
532 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800533}
534
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800535ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
536 switch (format) {
537 case OutputFormat::kApk:
538 return ResourceFile::Type::kBinaryXml;
539 case OutputFormat::kProto:
540 return ResourceFile::Type::kProtoXml;
541 }
542 LOG_ALWAYS_FATAL("unreachable");
543 return ResourceFile::Type::kUnknown;
544}
545
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700546bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700548 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800549
Adam Koskidc21dea2017-07-21 10:55:27 -0700550 proguard::CollectResourceReferences(context_, table, keep_set_);
551
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700553 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
554
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700556 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700557 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700558 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800559
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560 // Populate the queue with all files in the ResourceTable.
561 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700562 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700563 // WARNING! Do not insert or remove any resources while executing in this scope. It will
564 // corrupt the iteration order.
565
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700566 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700567 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700568 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700570
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700571 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700573 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700575 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700576 }
577
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700578 FileOperation file_op;
579 file_op.entry = entry.get();
580 file_op.dst_path = *file_ref->path;
581 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700582 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700583
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700584 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700585 (file_ref->type == ResourceFile::Type::kBinaryXml ||
586 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700587 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700588 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700589 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700590 << "failed to open file");
591 return false;
592 }
593
Adam Lesinski00451162017-10-03 07:44:08 -0700594 if (file_ref->type == ResourceFile::Type::kProtoXml) {
595 pb::XmlNode pb_xml_node;
596 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
597 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700598 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700599 return false;
600 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700601
Adam Lesinski00451162017-10-03 07:44:08 -0700602 std::string error;
603 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
604 if (file_op.xml_to_flatten == nullptr) {
605 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700606 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700607 return false;
608 }
609 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700610 std::string error_str;
611 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700612 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700613 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
614 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700615 return false;
616 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700617 }
618
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800619 // Update the type that this file will be written as.
620 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
621
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700622 file_op.xml_to_flatten->file.config = config_value->config;
623 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700624 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700625 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700626
627 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
628 // else we end up copying the string in the std::make_pair() method,
629 // then creating a StringPiece from the copy, which would cause us
630 // to end up referencing garbage in the map.
631 const StringPiece entry_name(entry->name);
632 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
633 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700634 }
635 }
636
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700637 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700638 for (auto& map_entry : config_sorted_files) {
639 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700640 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700641
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700642 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700643 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
644 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700645 if (versioned_docs.empty()) {
646 error = true;
647 continue;
648 }
649
Adam Lesinskic744ae82017-05-17 19:28:38 -0700650 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
651 std::string dst_path = file_op.dst_path;
652 if (doc->file.config != file_op.config) {
653 // Only add the new versioned configurations.
654 if (context_->IsVerbose()) {
655 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
656 << "auto-versioning resource from config '"
657 << config << "' -> '" << doc->file.config << "'");
658 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800660 const ResourceFile& file = doc->file;
661 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
662
663 std::unique_ptr<FileReference> file_ref =
664 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
665 file_ref->SetSource(doc->file.source);
666 // Update the output format of this XML file.
667 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
668 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
669 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700670 return false;
671 }
672 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700673
674 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
675 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 }
677 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700678 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
679 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700680 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700682 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683 }
684 return !error;
685}
686
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700687static bool WriteStableIdMapToPath(IDiagnostics* diag,
688 const std::unordered_map<ResourceName, ResourceId>& id_map,
689 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800690 io::FileOutputStream fout(id_map_path);
691 if (fout.HadError()) {
692 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 return false;
694 }
695
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800696 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700697 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 const ResourceName& name = entry.first;
699 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800700 printer.Print(name.to_string());
701 printer.Print(" = ");
702 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800704 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800706 if (fout.HadError()) {
707 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708 return false;
709 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700710 return true;
711}
712
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700713static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
714 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700716 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700717 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700718 return false;
719 }
720
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700721 out_id_map->clear();
722 size_t line_no = 0;
723 for (StringPiece line : util::Tokenize(content, '\n')) {
724 line_no++;
725 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700726 if (line.empty()) {
727 continue;
728 }
729
730 auto iter = std::find(line.begin(), line.end(), '=');
731 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700732 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700733 return false;
734 }
735
736 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700737 StringPiece res_name_str =
738 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
739 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700740 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
741 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742 return false;
743 }
744
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700745 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
746 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700747 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700748
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700749 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
750 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700751 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
752 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700753 return false;
754 }
755
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700756 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700757 }
758 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700759}
760
Adam Lesinskic6284372017-12-04 13:46:23 -0800761static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
762 using namespace android;
763
764 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
765 // we're looking for the first attribute resource in the system package.
766 const ResTable& table = assets.getResources(true);
767 Res_value val;
768 ssize_t idx = table.getResource(0x01010000, &val, true);
769 if (idx != NO_ERROR) {
770 // Try as a bag.
771 const ResTable::bag_entry* entry;
772 ssize_t cnt = table.lockBag(0x01010000, &entry);
773 if (cnt >= 0) {
774 idx = entry->stringBlock;
775 }
776 table.unlockBag(entry);
777 }
778
779 if (idx < 0) {
780 return 0;
781 }
782 return table.getTableCookie(idx);
783}
784
Adam Lesinskifb48d292015-11-07 15:52:13 -0800785class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700786 public:
787 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700788 : options_(options),
789 context_(context),
790 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700791 file_collection_(util::make_unique<io::FileCollection>()) {
792 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700793
Adam Lesinskic6284372017-12-04 13:46:23 -0800794 void ExtractCompileSdkVersions(android::AssetManager* assets) {
795 using namespace android;
796
797 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
798 if (cookie == 0) {
799 // No Framework assets loaded. Not a failure.
800 return;
801 }
802
803 std::unique_ptr<Asset> manifest(
804 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
805 if (manifest == nullptr) {
806 // No errors.
807 return;
808 }
809
810 std::string error;
811 std::unique_ptr<xml::XmlResource> manifest_xml =
812 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
813 if (manifest_xml == nullptr) {
814 // No errors.
815 return;
816 }
817
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700818 if (!options_.manifest_fixer_options.compile_sdk_version) {
819 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
820 if (attr != nullptr) {
821 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
822 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
823 switch (prim->value.dataType) {
824 case Res_value::TYPE_INT_DEC:
825 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
826 break;
827 case Res_value::TYPE_INT_HEX:
828 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
829 break;
830 default:
831 break;
832 }
833 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
834 compile_sdk_version = *str->value;
835 } else {
836 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800837 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800838 }
839 }
840
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700841 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
842 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
843 if (attr != nullptr) {
844 Maybe<std::string>& compile_sdk_version_codename =
845 options_.manifest_fixer_options.compile_sdk_version_codename;
846 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
847 compile_sdk_version_codename = *str->value;
848 } else {
849 compile_sdk_version_codename = attr->value;
850 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800851 }
852 }
853 }
854
Adam Lesinski8780eb62017-10-31 17:44:39 -0700855 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800856 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700857 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700858 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700859 for (const std::string& path : options_.include_paths) {
860 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700861 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700862 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700863
Adam Lesinski8780eb62017-10-31 17:44:39 -0700864 std::string error;
865 auto zip_collection = io::ZipFileCollection::Create(path, &error);
866 if (zip_collection == nullptr) {
867 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
868 return false;
869 }
870
871 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
872 // Load this as a static library include.
873 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
874 Source(path), std::move(zip_collection), context_->GetDiagnostics());
875 if (static_apk == nullptr) {
876 return false;
877 }
878
Adam Lesinskib522f042017-04-21 16:57:59 -0700879 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800880 // Can't include static libraries when not building a static library (they have no IDs
881 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700882 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800883 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700884 return false;
885 }
886
Adam Lesinski8780eb62017-10-31 17:44:39 -0700887 ResourceTable* table = static_apk->GetResourceTable();
888
889 // If we are using --no-static-lib-packages, we need to rename the package of this table to
890 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700891 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800892 // Since package names can differ, and multiple packages can exist in a ResourceTable,
893 // we place the requirement that all static libraries are built with the package
894 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700895 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700896 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800897 } else {
898 context_->GetDiagnostics()->Error(DiagMessage(path)
899 << "no package with ID 0x7f found in static library");
900 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700901 }
902 }
903
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700904 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700905 util::make_unique<ResourceTableSymbolSource>(table));
906 static_library_includes_.push_back(std::move(static_apk));
907 } else {
908 if (!asset_source->AddAssetPath(path)) {
909 context_->GetDiagnostics()->Error(DiagMessage()
910 << "failed to load include path " << path);
911 return false;
912 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700913 }
914 }
915
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800916 // Capture the shared libraries so that the final resource table can be properly flattened
917 // with support for shared libraries.
918 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700919 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800920 // Capture the included base feature package.
921 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800922 } else if (entry.first == kFrameworkPackageId) {
923 // Try to embed which version of the framework we're compiling against.
924 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
925 // when linking our synthesized 'android:compileSdkVersion' attribute.
926 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
927 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
928 if (symbol != nullptr && symbol->is_public) {
929 // The symbol is present and public, extract the android:versionName and
930 // android:versionCode from the framework AndroidManifest.xml.
931 ExtractCompileSdkVersions(asset_source->GetAssetManager());
932 }
Todd Kennedy32512992018-04-25 16:45:59 -0700933 } else if (asset_source->IsPackageDynamic(entry.first)) {
934 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800935 }
936 }
937
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700938 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700939 return true;
940 }
941
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800942 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700943 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800944 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
945 if (manifest_el == nullptr) {
946 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700947 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800948
949 AppInfo app_info;
950
951 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
952 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
953 return {};
954 }
955
956 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
957 if (!package_attr) {
958 diag->Error(DiagMessage(xml_res->file.source)
959 << "<manifest> must have a 'package' attribute");
960 return {};
961 }
962 app_info.package = package_attr->value;
963
964 if (xml::Attribute* version_code_attr =
965 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
966 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
967 if (!maybe_code) {
968 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
969 << "invalid android:versionCode '" << version_code_attr->value << "'");
970 return {};
971 }
972 app_info.version_code = maybe_code.value();
973 }
974
975 if (xml::Attribute* revision_code_attr =
976 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
977 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
978 if (!maybe_code) {
979 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
980 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
981 return {};
982 }
983 app_info.revision_code = maybe_code.value();
984 }
985
986 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
987 if (!split_name_attr->value.empty()) {
988 app_info.split_name = split_name_attr->value;
989 }
990 }
991
992 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
993 if (xml::Attribute* min_sdk =
994 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700995 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800996 }
997 }
998 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700999 }
1000
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001001 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1002 // Postcondition: ResourceTable has only one package left. All others are
1003 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001004 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001005 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001006 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
1007 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001008 };
1009
1010 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001011 for (const auto& package : final_table_.packages) {
1012 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 // We have a package that is not related to the one we're building!
1014 for (const auto& type : package->types) {
1015 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001016 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001018 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001019 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001020 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001021 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1022 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1023 << "generated id '" << res_name
1024 << "' for external package '" << package->name
1025 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001026 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001027 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1028 << "defined resource '" << res_name
1029 << "' for external package '" << package->name
1030 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001031 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001032 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001033 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001034 }
1035 }
1036 }
1037 }
1038
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001039 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1040 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001041 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001042 return !error;
1043 }
1044
1045 /**
1046 * Returns true if no IDs have been set, false otherwise.
1047 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001048 bool VerifyNoIdsSet() {
1049 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001050 for (const auto& type : package->types) {
1051 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001052 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1053 << StringPrintf("%02x", type->id.value())
1054 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001055 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001056 }
1057
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001058 for (const auto& entry : type->entries) {
1059 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001060 ResourceNameRef res_name(package->name, type->type, entry->name);
1061 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001062 DiagMessage() << "entry " << res_name << " has ID "
1063 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001064 return false;
1065 }
1066 }
1067 }
1068 }
1069 return true;
1070 }
1071
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001072 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1073 if (options_.output_to_directory) {
1074 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001075 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001076 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001077 }
1078 }
1079
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001080 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1081 switch (format) {
1082 case OutputFormat::kApk: {
1083 BigBuffer buffer(1024);
1084 TableFlattener flattener(options_.table_flattener_options, &buffer);
1085 if (!flattener.Consume(context_, table)) {
1086 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1087 return false;
1088 }
1089
1090 io::BigBufferInputStream input_stream(&buffer);
1091 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1092 ArchiveEntry::kAlign, writer);
1093 } break;
1094
1095 case OutputFormat::kProto: {
1096 pb::ResourceTable pb_table;
Ryan Mitchella15c2a82018-03-26 11:05:31 -07001097 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001098 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1099 ArchiveEntry::kCompress, writer);
1100 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001101 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001102 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001103 }
1104
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001105 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001106 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001107 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001108 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001109 return true;
1110 }
1111
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001112 std::string out_path;
1113 std::unique_ptr<io::FileOutputStream> fout;
1114 if (options_.generate_java_class_path) {
1115 out_path = options_.generate_java_class_path.value();
1116 file::AppendPath(&out_path, file::PackageToPath(out_package));
1117 if (!file::mkdirs(out_path)) {
1118 context_->GetDiagnostics()->Error(DiagMessage()
1119 << "failed to create directory '" << out_path << "'");
1120 return false;
1121 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001122
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001123 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001124
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001125 fout = util::make_unique<io::FileOutputStream>(out_path);
1126 if (fout->HadError()) {
1127 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1128 << "': " << fout->GetError());
1129 return false;
1130 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001131 }
1132
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001133 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001134 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001135 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1136 if (fout_text->HadError()) {
1137 context_->GetDiagnostics()->Error(DiagMessage()
1138 << "failed writing to '" << out_text_symbols_path.value()
1139 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001140 return false;
1141 }
1142 }
1143
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001144 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001145 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001146 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001147 return false;
1148 }
1149
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001150 return true;
1151 }
1152
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001153 bool GenerateJavaClasses() {
1154 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1155 std::vector<std::string> packages_to_callback;
1156
1157 JavaClassGeneratorOptions template_options;
1158 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1159 template_options.javadoc_annotations = options_.javadoc_annotations;
1160
1161 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1162 template_options.use_final = false;
1163 }
1164
1165 if (context_->GetPackageType() == PackageType::kSharedLib) {
1166 template_options.use_final = false;
1167 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1168 }
1169
1170 const StringPiece actual_package = context_->GetCompilationPackage();
1171 StringPiece output_package = context_->GetCompilationPackage();
1172 if (options_.custom_java_package) {
1173 // Override the output java package to the custom one.
1174 output_package = options_.custom_java_package.value();
1175 }
1176
1177 // Generate the private symbols if required.
1178 if (options_.private_symbols) {
1179 packages_to_callback.push_back(options_.private_symbols.value());
1180
1181 // If we defined a private symbols package, we only emit Public symbols
1182 // to the original package, and private and public symbols to the private package.
1183 JavaClassGeneratorOptions options = template_options;
1184 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1185 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1186 options)) {
1187 return false;
1188 }
1189 }
1190
1191 // Generate copies of the original package R class but with different package names.
1192 // This is to support non-namespaced builds.
1193 for (const std::string& extra_package : options_.extra_java_packages) {
1194 packages_to_callback.push_back(extra_package);
1195
1196 JavaClassGeneratorOptions options = template_options;
1197 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1198 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1199 return false;
1200 }
1201 }
1202
1203 // Generate R classes for each package that was merged (static library).
1204 // Use the actual package's resources only.
1205 for (const std::string& package : table_merger_->merged_packages()) {
1206 packages_to_callback.push_back(package);
1207
1208 JavaClassGeneratorOptions options = template_options;
1209 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1210 if (!WriteJavaFile(&final_table_, package, package, options)) {
1211 return false;
1212 }
1213 }
1214
1215 // Generate the main public R class.
1216 JavaClassGeneratorOptions options = template_options;
1217
1218 // Only generate public symbols if we have a private package.
1219 if (options_.private_symbols) {
1220 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1221 }
1222
1223 if (options.rewrite_callback_options) {
1224 options.rewrite_callback_options.value().packages_to_callback =
1225 std::move(packages_to_callback);
1226 }
1227
1228 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1229 options_.generate_text_symbols_path)) {
1230 return false;
1231 }
1232
1233 return true;
1234 }
1235
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001236 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1237 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001238 return true;
1239 }
1240
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001241 std::unique_ptr<ClassDefinition> manifest_class =
1242 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001243
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001244 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001245 // Something bad happened, but we already logged it, so exit.
1246 return false;
1247 }
1248
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001249 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001250 // Empty Manifest class, no need to generate it.
1251 return true;
1252 }
1253
1254 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001255 for (const std::string& annotation : options_.javadoc_annotations) {
1256 std::string proper_annotation = "@";
1257 proper_annotation += annotation;
1258 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259 }
1260
Adam Lesinski0d81f702017-06-27 15:51:09 -07001261 const std::string package_utf8 =
1262 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001263
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001264 std::string out_path = options_.generate_java_class_path.value();
1265 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001266
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001267 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001268 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1269 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001270 return false;
1271 }
1272
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001273 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001274
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001275 io::FileOutputStream fout(out_path);
1276 if (fout.HadError()) {
1277 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1278 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 return false;
1280 }
1281
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001282 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1283 fout.Flush();
1284
1285 if (fout.HadError()) {
1286 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1287 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 return false;
1289 }
1290 return true;
1291 }
1292
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001293 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 if (!out) {
1295 return true;
1296 }
1297
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001298 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001299 io::FileOutputStream fout(out_path);
1300 if (fout.HadError()) {
1301 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1302 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001303 return false;
1304 }
1305
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001306 proguard::WriteKeepSet(keep_set, &fout);
1307 fout.Flush();
1308
1309 if (fout.HadError()) {
1310 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1311 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001312 return false;
1313 }
1314 return true;
1315 }
1316
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001317 bool MergeStaticLibrary(const std::string& input, bool override) {
1318 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001319 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001320 }
1321
Adam Lesinski8780eb62017-10-31 17:44:39 -07001322 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1323 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001324 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001325 return false;
1326 }
1327
Adam Lesinski8780eb62017-10-31 17:44:39 -07001328 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001329 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001330 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001331 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001332 return false;
1333 }
1334
1335 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001336 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001337 // Merge all resources as if they were in the compilation package. This is the old behavior
1338 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001339
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001340 // Add the package to the set of --extra-packages so we emit an R.java for each library
1341 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001342 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001343 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001344 }
1345
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001346 // Clear the package name, so as to make the resources look like they are coming from the
1347 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001348 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001349 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001350
1351 } else {
1352 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001353 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001354 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001355 }
1356
1357 if (!result) {
1358 return false;
1359 }
1360
1361 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001362 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001363 return true;
1364 }
1365
Adam Lesinski2427dce2017-11-30 15:10:28 -08001366 bool MergeExportedSymbols(const Source& source,
1367 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001368 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001369 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001370 ResourceName res_name = exported_symbol.name;
1371 if (res_name.package.empty()) {
1372 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001373 }
1374
Adam Lesinski00451162017-10-03 07:44:08 -07001375 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001376 if (mangled_name) {
1377 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001378 }
1379
1380 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001381 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001382 bool result =
1383 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1384 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001385 if (!result) {
1386 return false;
1387 }
1388 }
1389 return true;
1390 }
1391
Adam Lesinski2427dce2017-11-30 15:10:28 -08001392 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1393 if (context_->IsVerbose()) {
1394 context_->GetDiagnostics()->Note(DiagMessage()
1395 << "merging '" << compiled_file.name
1396 << "' from compiled file " << compiled_file.source);
1397 }
1398
1399 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1400 return false;
1401 }
1402 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1403 }
1404
Adam Lesinski00451162017-10-03 07:44:08 -07001405 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1406 // If override is true, conflicting resources are allowed to override each other, in order of last
1407 // seen.
1408 // An io::IFileCollection is created from the ZIP file and added to the set of
1409 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001410 bool MergeArchive(const std::string& input, bool override) {
1411 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001412 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001413 }
1414
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001415 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001416 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001417 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001418 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001419 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420 return false;
1421 }
1422
1423 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001424 for (auto iter = collection->Iterator(); iter->HasNext();) {
1425 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001426 error = true;
1427 }
1428 }
1429
1430 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001431 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001432 return !error;
1433 }
1434
Adam Lesinski00451162017-10-03 07:44:08 -07001435 // Takes a path to load and merge into the master ResourceTable. If override is true,
1436 // conflicting resources are allowed to override each other, in order of last seen.
1437 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1438 // as ZIP archive and the files within are merged individually.
1439 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001440 bool MergePath(const std::string& path, bool override) {
1441 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1442 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1443 return MergeArchive(path, override);
1444 } else if (util::EndsWith(path, ".apk")) {
1445 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001446 }
1447
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001448 io::IFile* file = file_collection_->InsertFile(path);
1449 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001450 }
1451
Adam Lesinski00451162017-10-03 07:44:08 -07001452 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1453 // If override is true, conflicting resources are allowed to override each other, in order of last
1454 // seen.
1455 // All other file types are ignored. This is because these files could be coming from a zip,
1456 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001457 bool MergeFile(io::IFile* file, bool override) {
1458 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001459
Adam Lesinski00451162017-10-03 07:44:08 -07001460 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001461 // Since AAPT compiles these file types and appends .flat to them, seeing
1462 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001463 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1464 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1465 << " file passed as argument. Must be "
1466 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001467 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001468 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1469 if (context_->IsVerbose()) {
1470 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1471 return true;
1472 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001473 }
1474
Adam Lesinski00451162017-10-03 07:44:08 -07001475 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1476 if (input_stream == nullptr) {
1477 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1478 return false;
1479 }
1480
1481 if (input_stream->HadError()) {
1482 context_->GetDiagnostics()->Error(DiagMessage(src)
1483 << "failed to open file: " << input_stream->GetError());
1484 return false;
1485 }
1486
1487 ContainerReaderEntry* entry;
1488 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001489
1490 if (reader.HadError()) {
1491 context_->GetDiagnostics()->Error(DiagMessage(src)
1492 << "failed to read file: " << reader.GetError());
1493 return false;
1494 }
1495
Adam Lesinski00451162017-10-03 07:44:08 -07001496 while ((entry = reader.Next()) != nullptr) {
1497 if (entry->Type() == ContainerEntryType::kResTable) {
1498 pb::ResourceTable pb_table;
1499 if (!entry->GetResTable(&pb_table)) {
1500 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1501 << entry->GetError());
1502 return false;
1503 }
1504
1505 ResourceTable table;
1506 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001507 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001508 context_->GetDiagnostics()->Error(DiagMessage(src)
1509 << "failed to deserialize resource table: " << error);
1510 return false;
1511 }
1512
1513 if (!table_merger_->Merge(src, &table, override)) {
1514 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1515 return false;
1516 }
1517 } else if (entry->Type() == ContainerEntryType::kResFile) {
1518 pb::internal::CompiledFile pb_compiled_file;
1519 off64_t offset;
1520 size_t len;
1521 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1522 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1523 << entry->GetError());
1524 return false;
1525 }
1526
1527 ResourceFile resource_file;
1528 std::string error;
1529 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1530 context_->GetDiagnostics()->Error(DiagMessage(src)
1531 << "failed to read compiled header: " << error);
1532 return false;
1533 }
1534
1535 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1536 return false;
1537 }
1538 }
1539 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001540 return true;
1541 }
1542
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001543 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1544 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1545 for (const std::string& assets_dir : options_.assets_dirs) {
1546 Maybe<std::vector<std::string>> files =
1547 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1548 if (!files) {
1549 return false;
1550 }
1551
1552 for (const std::string& file : files.value()) {
1553 std::string full_key = "assets/" + file;
1554 std::string full_path = assets_dir;
1555 file::AppendPath(&full_path, file);
1556
1557 auto iter = merged_assets.find(full_key);
1558 if (iter == merged_assets.end()) {
1559 merged_assets.emplace(std::move(full_key),
1560 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1561 } else if (context_->IsVerbose()) {
1562 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1563 << "asset file overrides '" << full_path << "'");
1564 }
1565 }
1566 }
1567
1568 for (auto& entry : merged_assets) {
1569 uint32_t compression_flags = ArchiveEntry::kCompress;
1570 std::string extension = file::GetExtension(entry.first).to_string();
1571 if (options_.extensions_to_not_compress.count(extension) > 0) {
1572 compression_flags = 0u;
1573 }
1574
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001575 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1576 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001577 return false;
1578 }
1579 }
1580 return true;
1581 }
1582
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001583 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1584 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001585 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1586 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001587 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001588 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1589 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001590 if (!result) {
1591 return false;
1592 }
1593
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001594 ResourceFileFlattenerOptions file_flattener_options;
1595 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001596 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1597 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001598 file_flattener_options.no_auto_version = options_.no_auto_version;
1599 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001600 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001601 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1602 file_flattener_options.update_proguard_spec =
1603 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001604 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001605
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001606 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001607
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001608 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001609 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610 return false;
1611 }
1612
Adam Lesinski490595a2017-11-07 17:08:07 -08001613 // Hack to fix b/68820737.
1614 // We need to modify the ResourceTable's package name, but that should NOT affect
1615 // anything else being generated, which includes the Java classes.
1616 // If required, the package name is modifed before flattening, and then modified back
1617 // to its original name.
1618 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001619 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1620 // or higher] as invalid. In order to work around this limitation, we allow the use
1621 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1622 // definition of what a valid "split" package ID is to account for this.
1623 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1624 context_->GetPackageId() != kAppPackageId &&
1625 context_->GetPackageId() != kFrameworkPackageId)
1626 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1627 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001628 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1629 // The base APK is included, and this is a feature split. If the base package is
1630 // the same as this package, then we are building an old style Android Instant Apps feature
1631 // split and must apply this workaround to avoid requiring namespaces support.
1632 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1633 if (package_to_rewrite != nullptr) {
1634 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1635
1636 std::string new_package_name =
1637 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1638 app_info_.split_name.value_or_default("feature").c_str());
1639
1640 if (context_->IsVerbose()) {
1641 context_->GetDiagnostics()->Note(
1642 DiagMessage() << "rewriting resource package name for feature split to '"
1643 << new_package_name << "'");
1644 }
1645 package_to_rewrite->name = new_package_name;
1646 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001647 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001648
1649 bool success = FlattenTable(table, options_.output_format, writer);
1650
1651 if (package_to_rewrite != nullptr) {
1652 // Change the name back.
1653 package_to_rewrite->name = context_->GetCompilationPackage();
1654 if (package_to_rewrite->id) {
1655 table->included_packages_.erase(package_to_rewrite->id.value());
1656 }
1657 }
1658
1659 if (!success) {
1660 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1661 }
1662 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001663 }
1664
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001665 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001666 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001667 std::unique_ptr<xml::XmlResource> manifest_xml =
1668 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1669 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001670 return 1;
1671 }
1672
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001673 // First extract the Package name without modifying it (via --rename-manifest-package).
1674 if (Maybe<AppInfo> maybe_app_info =
1675 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001676 const AppInfo& app_info = maybe_app_info.value();
1677 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001678 }
1679
Adam Lesinskic6284372017-12-04 13:46:23 -08001680 // Now that the compilation package is set, load the dependencies. This will also extract
1681 // the Android framework's versionCode and versionName, if they exist.
1682 if (!LoadSymbolsFromIncludePaths()) {
1683 return 1;
1684 }
1685
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001686 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1687 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001688 return 1;
1689 }
1690
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001691 Maybe<AppInfo> maybe_app_info =
1692 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001693 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001694 return 1;
1695 }
1696
Adam Lesinski490595a2017-11-07 17:08:07 -08001697 app_info_ = maybe_app_info.value();
1698 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001699
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001700 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001701
1702 // Override the package ID when it is "android".
1703 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001704 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001705
1706 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001707 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001708 context_->GetDiagnostics()->Error(
1709 DiagMessage() << "package 'android' can only be built as a regular app");
1710 return 1;
1711 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001712 }
1713
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001714 TableMergerOptions table_merger_options;
1715 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001716 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001717
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001718 if (context_->IsVerbose()) {
1719 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001720 << StringPrintf("linking package '%s' using package ID %02x",
1721 context_->GetCompilationPackage().data(),
1722 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001723 }
1724
Adam Lesinski2427dce2017-11-30 15:10:28 -08001725 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1726 // in res/**/*.
1727 {
1728 XmlIdCollector collector;
1729 if (!collector.Consume(context_, manifest_xml.get())) {
1730 return false;
1731 }
1732
1733 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1734 return false;
1735 }
1736 }
1737
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001738 for (const std::string& input : input_files) {
1739 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001740 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001741 return 1;
1742 }
1743 }
1744
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001745 for (const std::string& input : options_.overlay_files) {
1746 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001747 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001748 return 1;
1749 }
1750 }
1751
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001752 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 return 1;
1754 }
1755
Adam Lesinskib522f042017-04-21 16:57:59 -07001756 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001758 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001759 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001760 return 1;
1761 }
1762
1763 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001764 IdAssigner id_assigner(&options_.stable_id_map);
1765 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001766 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001767 return 1;
1768 }
1769
1770 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001771 if (options_.resource_id_map_path) {
1772 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001773 for (auto& type : package->types) {
1774 for (auto& entry : type->entries) {
1775 ResourceName name(package->name, type->type, entry->name);
1776 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001777 options_.stable_id_map[std::move(name)] =
1778 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001779 }
1780 }
1781 }
1782
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001783 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001784 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001785 return 1;
1786 }
1787 }
1788 } else {
1789 // Static libs are merged with other apps, and ID collisions are bad, so
1790 // verify that
1791 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001792 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001793 return 1;
1794 }
1795 }
1796
1797 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001798 context_->SetNameManglerPolicy(
1799 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001800
1801 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001802 context_->GetExternalSymbols()->PrependSource(
1803 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001804
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001805 // Workaround for pre-O runtime that would treat negative resource IDs
1806 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1807 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1808 // are just identifiers.
1809 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1810 if (context_->IsVerbose()) {
1811 context_->GetDiagnostics()->Note(DiagMessage()
1812 << "enabling pre-O feature split ID rewriting");
1813 }
1814 context_->GetExternalSymbols()->SetDelegate(
1815 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1816 }
1817
Adam Lesinski34a16872018-02-23 16:18:10 -08001818 // Before we process anything, remove the resources whose default values don't exist.
1819 // We want to force any references to these to fail the build.
1820 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1821 context_->GetDiagnostics()->Error(DiagMessage()
1822 << "failed removing resources with no defaults");
1823 return 1;
1824 }
1825
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001827 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001828 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 return 1;
1830 }
1831
Adam Lesinskib522f042017-04-21 16:57:59 -07001832 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001833 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001834 context_->GetDiagnostics()->Warn(DiagMessage()
1835 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001836 }
1837 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001838 ProductFilter product_filter(options_.products);
1839 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001840 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001841 return 1;
1842 }
1843 }
1844
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001845 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001846 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001848 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001849 return 1;
1850 }
1851 }
1852
Adam Lesinskib522f042017-04-21 16:57:59 -07001853 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001855 context_->GetDiagnostics()->Note(DiagMessage()
1856 << "collapsing resource versions for minimum SDK "
1857 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001858 }
1859
1860 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001861 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001862 return 1;
1863 }
1864 }
1865
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001866 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001868 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001869 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001870 return 1;
1871 }
1872 }
1873
Adam Koskidc21dea2017-07-21 10:55:27 -07001874 proguard::KeepSet proguard_keep_set =
1875 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001877
Adam Lesinskib522f042017-04-21 16:57:59 -07001878 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001879 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001880 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001881 context_->GetDiagnostics()->Warn(DiagMessage()
1882 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001883 }
1884 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001885 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1886 // equal to the minSdk.
1887 options_.split_constraints =
1888 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001889
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001890 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001891 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001892 return 1;
1893 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001894 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001895
1896 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001897 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001898 auto split_constraints_iter = options_.split_constraints.begin();
1899 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001900 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001901 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1902 << "generating split with configurations '"
1903 << util::Joiner(split_constraints_iter->configs, ", ")
1904 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001905 }
1906
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001907 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001908 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001909 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001910 return 1;
1911 }
1912
1913 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001914 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001915 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001916
1917 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001919 context_->GetDiagnostics()->Error(DiagMessage()
1920 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001921 return 1;
1922 }
1923
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001924 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1925 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001926 return 1;
1927 }
1928
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 ++path_iter;
1930 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001931 }
1932 }
1933
1934 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001935 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001936 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001937 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001938 return 1;
1939 }
1940
1941 bool error = false;
1942 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001943 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001944 // (aka, which package the AndroidManifest.xml is coming from).
1945 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001946 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001947
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001948 XmlReferenceLinker manifest_linker;
1949 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1950 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001951 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001952 error = true;
1953 }
1954
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001955 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001956 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001957 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001958 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001959 }
1960
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001961 if (options_.generate_java_class_path) {
1962 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001963 error = true;
1964 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001965 }
1966
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001967 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001968 // PackageParser will fail if URIs are removed from
1969 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001970 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1971 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001972 error = true;
1973 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001974 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975 } else {
1976 error = true;
1977 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001978 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001979
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001980 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001981 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001982 return 1;
1983 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001984
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001985 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1986 return 1;
1987 }
1988
1989 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001990 return 1;
1991 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001992
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001993 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001994 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001995 return 1;
1996 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001997 }
1998
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001999 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000 return 1;
2001 }
2002
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002003 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2004 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002005 return 1;
2006 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002007 return 0;
2008 }
2009
2010 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002011 LinkOptions options_;
2012 LinkContext* context_;
2013 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002014
Adam Lesinski490595a2017-11-07 17:08:07 -08002015 AppInfo app_info_;
2016
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002017 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002018
2019 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002020 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002021
Adam Lesinski8780eb62017-10-31 17:44:39 -07002022 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002023 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002024 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002025
Adam Lesinski8780eb62017-10-31 17:44:39 -07002026 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2027 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2028
2029 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2030 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002031
2032 // The set of shared libraries being used, mapping their assigned package ID to package name.
2033 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002034
2035 // The package name of the base application, if it is included.
2036 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002037};
2038
Chris Warrington820d72a2017-04-27 15:27:01 +01002039int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2040 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002041 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002042 std::vector<std::string> overlay_arg_list;
2043 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002044 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002045 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002046 Maybe<std::string> preferred_density;
2047 Maybe<std::string> product_list;
2048 bool legacy_x_flag = false;
2049 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002050 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002051 bool shared_lib = false;
2052 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002053 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002054 Maybe<std::string> stable_id_file_path;
2055 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002056 Flags flags =
2057 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002058 .RequiredFlag("-o", "Output path.", &options.output_path)
2059 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002060 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002061 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002062 .OptionalFlagList("-A",
2063 "An assets directory to include in the APK. These are unprocessed.",
2064 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002065 .OptionalFlagList("-R",
2066 "Compilation unit to link, using `overlay` semantics.\n"
2067 "The last conflicting resource given takes precedence.",
2068 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002069 .OptionalFlag("--package-id",
2070 "Specify the package ID to use for this app. Must be greater or equal to\n"
2071 "0x7f and can't be used with --static-lib or --shared-lib.",
2072 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002073 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002074 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002075 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002076 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002077 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002078 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002079 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002080 .OptionalSwitch("--proguard-conditional-keep-rules",
2081 "Generate conditional Proguard keep rules.",
2082 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002083 .OptionalSwitch("--no-auto-version",
2084 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002085 &options.no_auto_version)
2086 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002087 "Disables automatic versioning of vector drawables. Use this only\n"
2088 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002089 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002090 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002091 "Disables automatic versioning of transition resources. Use this only\n"
2092 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002093 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002094 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002095 "Disables automatic deduping of resources with\n"
2096 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002097 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002098 .OptionalSwitch("--enable-sparse-encoding",
2099 "Enables encoding sparse entries using a binary search tree.\n"
2100 "This decreases APK size at the cost of resource retrieval performance.",
2101 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002102 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002103 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002104 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002105 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002106 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002107 "Comma separated list of configurations to include. The default\n"
2108 "is all configurations.",
2109 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002110 .OptionalFlag("--preferred-density",
2111 "Selects the closest matching density and strips out all others.",
2112 &preferred_density)
2113 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002114 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002115 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002116 &options.output_to_directory)
2117 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002118 "Removes XML namespace prefix and URI information from\n"
2119 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 &options.no_xml_namespaces)
2121 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002122 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002123 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002124 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002125 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002126 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002128 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2129 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002130 &options.manifest_fixer_options.version_code_default)
2131 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002132 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002133 &options.manifest_fixer_options.version_name_default)
Todd Kennedy9f6dec12018-04-20 12:29:29 -07002134 .OptionalFlag("--compile-sdk-version-code",
2135 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2136 "present.",
2137 &options.manifest_fixer_options.compile_sdk_version)
2138 .OptionalFlag("--compile-sdk-version-name",
2139 "Version name to inject into the AndroidManifest.xml if none is present.",
2140 &options.manifest_fixer_options.compile_sdk_version_codename)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002141 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2142 &shared_lib)
2143 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002144 .OptionalSwitch("--proto-format",
2145 "Generates compiled resources in Protobuf format.\n"
2146 "Suitable as input to the bundle tool for generating an App Bundle.",
2147 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002149 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002150 &options.no_static_lib_packages)
Chris Warrington481f0272018-02-06 14:03:39 +00002151 .OptionalSwitch("--auto-namespace-static-lib",
2152 "Automatically namespace resource references when building a static\n"
2153 "library.",
2154 &options.auto_namespace_static_lib)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002155 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002156 "Generates R.java without the final modifier. This is implied when\n"
2157 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002158 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002159 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002160 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002161 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002162 "Emit a file at the given path with a list of name to ID mappings,\n"
2163 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002164 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002165 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002166 "Package name to use when generating R.java for private symbols.\n"
2167 "If not specified, public and private symbols will use the application's\n"
2168 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002169 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002170 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002171 &options.custom_java_package)
2172 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002173 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002174 &extra_java_packages)
2175 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002176 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002177 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002178 .OptionalFlag("--output-text-symbols",
2179 "Generates a text file containing the resource symbols of the R class in\n"
2180 "the specified folder.",
2181 &options.generate_text_symbols_path)
Todd Kennedy32512992018-04-25 16:45:59 -07002182 .OptionalSwitch("--allow-reserved-package-id",
2183 "Allows the use of a reserved package ID. This should on be used for\n"
2184 "packages with a pre-O min-sdk\n",
2185 &options.allow_reserved_package_id)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002186 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002187 "Allows the addition of new resources in overlays without\n"
2188 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002189 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002190 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002191 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002192 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002193 "Changes the name of the target package for instrumentation. Most useful\n"
2194 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002195 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002196 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002197 &options.extensions_to_not_compress)
Izabela Orlowska6f34e0d2018-03-05 14:19:43 +00002198 .OptionalSwitch("--no-compress", "Do not compress any resources.",
Chris Warrington481f0272018-02-06 14:03:39 +00002199 &options.do_not_compress_anything)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002200 .OptionalSwitch("--warn-manifest-validation",
2201 "Treat manifest validation errors as warnings.",
2202 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002203 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002204 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002205 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2206 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002207 &split_args)
Ryan Mitchell444f9bb2018-03-23 13:35:00 -07002208 .OptionalSwitch("-v", "Enables verbose logging.", &verbose)
2209 .OptionalSwitch("--debug-mode",
2210 "Inserts android:debuggable=\"true\" in to the application node of the\n"
2211 "manifest, making the application debuggable even on production devices.",
2212 &options.manifest_fixer_options.debug_mode);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002213
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002214 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002215 return 1;
2216 }
2217
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002218 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002219 std::vector<std::string> arg_list;
2220 for (const std::string& arg : flags.GetArgs()) {
2221 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002222 const std::string path = arg.substr(1, arg.size() - 1);
2223 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002224 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2225 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002226 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002227 }
2228 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002229 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002230 }
2231 }
2232
2233 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002234 for (const std::string& arg : overlay_arg_list) {
2235 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002236 const std::string path = arg.substr(1, arg.size() - 1);
2237 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002238 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2239 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002240 return 1;
2241 }
2242 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002243 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002244 }
2245 }
2246
2247 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002248 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002249 }
2250
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002251 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2252 context.GetDiagnostics()->Error(
2253 DiagMessage()
2254 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002255 return 1;
2256 }
2257
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002258 // The default build type.
2259 context.SetPackageType(PackageType::kApp);
2260 context.SetPackageId(kAppPackageId);
2261
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002262 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002263 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002264 context.SetPackageId(0x00);
2265 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002266 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002267 options.output_format = OutputFormat::kProto;
2268 } else if (proto_format) {
2269 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002270 }
2271
Chris Warrington481f0272018-02-06 14:03:39 +00002272 if (options.auto_namespace_static_lib) {
2273 if (!static_lib) {
2274 context.GetDiagnostics()->Error(
2275 DiagMessage() << "--auto-namespace-static-lib can only be used with --static-lib");
2276 return 1;
2277 }
2278 context.SetAutoNamespace(true);
2279 }
2280
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002281 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002282 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002283 context.GetDiagnostics()->Error(
2284 DiagMessage() << "can't specify --package-id when not building a regular app");
2285 return 1;
2286 }
2287
2288 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2289 if (!maybe_package_id_int) {
2290 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2291 << "' is not a valid integer");
2292 return 1;
2293 }
2294
2295 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002296 if (package_id_int > std::numeric_limits<uint8_t>::max()
2297 || package_id_int == kFrameworkPackageId
2298 || (!options.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002299 context.GetDiagnostics()->Error(
2300 DiagMessage() << StringPrintf(
2301 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2302 return 1;
2303 }
2304 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2305 }
2306
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002307 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002308 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002309 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002310 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002311 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002312 }
2313 }
2314
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002315 if (product_list) {
2316 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002317 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002318 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002319 }
2320 }
2321 }
2322
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002323 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002324 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002325 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2326 if (filter == nullptr) {
2327 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002328 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002329 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002330 }
2331
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002332 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002333 Maybe<uint16_t> density =
2334 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2335 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002336 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002337 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002338 options.table_splitter_options.preferred_densities.push_back(density.value());
2339 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002340
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002341 // Parse the split parameters.
2342 for (const std::string& split_arg : split_args) {
2343 options.split_paths.push_back({});
2344 options.split_constraints.push_back({});
2345 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2346 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002347 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002348 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002349 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002350
Adam Lesinskib522f042017-04-21 16:57:59 -07002351 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002352 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2353 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002354 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002355 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002356 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002357
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002358 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002359 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002360 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2361 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2362 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2363 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2364
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002365 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002366 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002367 options.no_auto_version = true;
2368 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002369 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002370 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002371
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002372 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002373 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002374}
2375
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002376} // namespace aapt