blob: 623ba120903db2f40091d915e2125f0c276b6483 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Adam Lesinskice5e56e2016-10-21 17:56:45 -070017#include <sys/stat.h>
Adam Lesinskic6284372017-12-04 13:46:23 -080018#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019
Adam Lesinskice5e56e2016-10-21 17:56:45 -070020#include <queue>
21#include <unordered_map>
22#include <vector>
23
24#include "android-base/errors.h"
25#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080026#include "android-base/stringprintf.h"
Mårten Kongstad5c541f62018-06-20 08:46:41 +020027#include "androidfw/Locale.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 Lesinski1ab598f2015-08-14 14:26:04 -070034#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080035#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070036#include "ResourceValues.h"
37#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070038#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080040#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080041#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070042#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070043#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/binary/TableFlattener.h"
45#include "format/binary/XmlFlattener.h"
46#include "format/proto/ProtoDeserialize.h"
47#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070048#include "io/BigBufferStream.h"
49#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080050#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070051#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070053#include "java/JavaClassGenerator.h"
54#include "java/ManifestClassGenerator.h"
55#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070056#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070057#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080058#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080059#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070061#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080062#include "optimize/ResourceDeduper.h"
63#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "process/IResourceTableConsumer.h"
65#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080066#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080068#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070070using ::aapt::io::FileInputStream;
Mårten Kongstad5c541f62018-06-20 08:46:41 +020071using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070072using ::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;
Mårten Kongstadf99eda42018-06-11 14:13:37 +0200109 bool no_resource_removal = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700110 bool no_xml_namespaces = false;
111 bool do_not_compress_anything = false;
112 std::unordered_set<std::string> extensions_to_not_compress;
113
114 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700115 bool no_static_lib_packages = false;
116
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:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800144 explicit LinkContext(IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +0100145 : 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
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700204 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700205 DISALLOW_COPY_AND_ASSIGN(LinkContext);
206
Adam Lesinskib522f042017-04-21 16:57:59 -0700207 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100208 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700209 NameMangler name_mangler_;
210 std::string compilation_package_;
211 uint8_t package_id_ = 0x0;
212 SymbolTable symbols_;
213 bool verbose_ = false;
214 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700215};
216
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700217// A custom delegate that generates compatible pre-O IDs for use with feature splits.
218// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
219// is interpreted as a negative number. Some verification was wrongly assuming negative values
220// were invalid.
221//
222// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
223// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
224// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800225//
226// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700227class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
228 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800229 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700230 }
231
232 virtual ~FeatureSplitSymbolTableDelegate() = default;
233
234 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
235 const ResourceName& name,
236 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
237 std::unique_ptr<SymbolTable::Symbol> symbol =
238 DefaultSymbolTableDelegate::FindByName(name, sources);
239 if (symbol == nullptr) {
240 return {};
241 }
242
243 // Check to see if this is an 'id' with the target package.
244 if (name.type == ResourceType::kId && symbol->id) {
245 ResourceId* id = &symbol->id.value();
246 if (id->package_id() > kAppPackageId) {
247 // Rewrite the resource ID to be compatible pre-O.
248 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
249
250 // Check that this doesn't overlap another resource.
251 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
252 // The ID overlaps, so log a message (since this is a weird failure) and fail.
253 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
254 << " for pre-O feature split support");
255 return {};
256 }
257
258 if (context_->IsVerbose()) {
259 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
260 << ") -> (" << rewritten_id << ")");
261 }
262
263 *id = rewritten_id;
264 }
265 }
266 return symbol;
267 }
268
269 private:
270 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
271
272 IAaptContext* context_;
273};
274
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700275static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
276 const StringPiece& path, bool keep_raw_values, bool utf16,
277 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700278 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700279 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
280 << (keep_raw_values ? "true" : "false")
281 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700282 }
283
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700284 switch (format) {
285 case OutputFormat::kApk: {
286 BigBuffer buffer(1024);
287 XmlFlattenerOptions options = {};
288 options.keep_raw_values = keep_raw_values;
289 options.use_utf16 = utf16;
290 XmlFlattener flattener(&buffer, options);
291 if (!flattener.Consume(context, &xml_res)) {
292 return false;
293 }
294
295 io::BigBufferInputStream input_stream(&buffer);
296 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
297 ArchiveEntry::kCompress, writer);
298 } break;
299
300 case OutputFormat::kProto: {
301 pb::XmlNode pb_node;
302 SerializeXmlResourceToPb(xml_res, &pb_node);
303 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
304 writer);
305 } break;
306 }
307 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800308}
309
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700310// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700311static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700312 FileInputStream fin(path);
313 if (fin.HadError()) {
314 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700315 return {};
316 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700317 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800318}
319
Adam Lesinski355f2852016-02-13 20:26:45 -0800320struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700321 bool no_auto_version = false;
322 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900323 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700324 bool no_xml_namespaces = false;
325 bool keep_raw_values = false;
326 bool do_not_compress_anything = false;
327 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700328 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700329 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800330};
331
Adam Lesinskic744ae82017-05-17 19:28:38 -0700332// A sampling of public framework resource IDs.
333struct R {
334 struct attr {
335 enum : uint32_t {
336 paddingLeft = 0x010100d6u,
337 paddingRight = 0x010100d8u,
338 paddingHorizontal = 0x0101053du,
339
340 paddingTop = 0x010100d7u,
341 paddingBottom = 0x010100d9u,
342 paddingVertical = 0x0101053eu,
343
344 layout_marginLeft = 0x010100f7u,
345 layout_marginRight = 0x010100f9u,
346 layout_marginHorizontal = 0x0101053bu,
347
348 layout_marginTop = 0x010100f8u,
349 layout_marginBottom = 0x010100fau,
350 layout_marginVertical = 0x0101053cu,
351 };
352 };
353};
354
Adam Lesinski355f2852016-02-13 20:26:45 -0800355class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700356 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700357 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700358 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800359
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700360 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800361
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700362 private:
363 struct FileOperation {
364 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700365
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700366 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700367 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700368
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700370 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700371
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700372 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700373 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700374
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700375 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700376 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700377 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800378
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700379 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800380
Adam Lesinskic744ae82017-05-17 19:28:38 -0700381 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
382 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800383
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700384 ResourceFileFlattenerOptions options_;
385 IAaptContext* context_;
386 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700387 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800388};
389
Adam Lesinskic744ae82017-05-17 19:28:38 -0700390ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
391 IAaptContext* context, proguard::KeepSet* keep_set)
392 : options_(options), context_(context), keep_set_(keep_set) {
393 SymbolTable* symm = context_->GetExternalSymbols();
394
395 // Build up the rules for degrading newer attributes to older ones.
396 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
397 // generated from the attribute definitions themselves (b/62028956).
398 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
399 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800400 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
401 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700402 };
403 rules_[R::attr::paddingHorizontal] =
404 util::make_unique<DegradeToManyRule>(std::move(replacements));
405 }
406
407 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
408 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800409 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
410 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700411 };
412 rules_[R::attr::paddingVertical] =
413 util::make_unique<DegradeToManyRule>(std::move(replacements));
414 }
415
416 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
417 std::vector<ReplacementAttr> replacements{
418 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800419 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700420 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800421 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700422 };
423 rules_[R::attr::layout_marginHorizontal] =
424 util::make_unique<DegradeToManyRule>(std::move(replacements));
425 }
426
427 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
428 std::vector<ReplacementAttr> replacements{
429 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800430 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700431 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800432 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700433 };
434 rules_[R::attr::layout_marginVertical] =
435 util::make_unique<DegradeToManyRule>(std::move(replacements));
436 }
437}
438
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700439uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
440 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700441 return 0;
442 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800443
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700444 for (const std::string& extension : options_.extensions_to_not_compress) {
445 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700446 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800447 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700448 }
449 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800450}
451
Adam Lesinskibb94f322017-07-12 07:41:55 -0700452static bool IsTransitionElement(const std::string& name) {
453 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
454 name == "changeImageTransform" || name == "changeTransform" ||
455 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
456 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
457 name == "transitionManager";
458}
459
460static bool IsVectorElement(const std::string& name) {
461 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000462 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700463}
464
Adam Lesinskic744ae82017-05-17 19:28:38 -0700465template <typename T>
466std::vector<T> make_singleton_vec(T&& val) {
467 std::vector<T> vec;
468 vec.emplace_back(std::forward<T>(val));
469 return vec;
470}
471
472std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
473 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700474 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700475 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700476
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700477 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700478 context_->GetDiagnostics()->Note(DiagMessage()
479 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700480 }
481
Adam Lesinski00451162017-10-03 07:44:08 -0700482 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
483 // that existing projects have out-of-date references which pass compilation.
484 xml::StripAndroidStudioAttributes(doc->root.get());
485
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700486 XmlReferenceLinker xml_linker;
487 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700488 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700489 }
490
Adam Koskidc21dea2017-07-21 10:55:27 -0700491 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700492 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700493 }
494
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700495 if (options_.no_xml_namespaces) {
496 XmlNamespaceRemover namespace_remover;
497 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700498 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800499 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700500 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800501
Adam Lesinskibb94f322017-07-12 07:41:55 -0700502 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700503 return make_singleton_vec(std::move(file_op->xml_to_flatten));
504 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700505
Adam Lesinskibb94f322017-07-12 07:41:55 -0700506 if (options_.no_version_vectors || options_.no_version_transitions) {
507 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700508 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700509 if (el && el->namespace_uri.empty()) {
510 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
511 (options_.no_version_transitions && IsTransitionElement(el->name))) {
512 return make_singleton_vec(std::move(file_op->xml_to_flatten));
513 }
514 }
515 }
516
Adam Lesinskic744ae82017-05-17 19:28:38 -0700517 const ConfigDescription& config = file_op->config;
518 ResourceEntry* entry = file_op->entry;
519
520 XmlCompatVersioner xml_compat_versioner(&rules_);
521 const util::Range<ApiVersion> api_range{config.sdkVersion,
522 FindNextApiVersionForConfig(entry, config)};
523 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800524}
525
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800526ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
527 switch (format) {
528 case OutputFormat::kApk:
529 return ResourceFile::Type::kBinaryXml;
530 case OutputFormat::kProto:
531 return ResourceFile::Type::kProtoXml;
532 }
533 LOG_ALWAYS_FATAL("unreachable");
534 return ResourceFile::Type::kUnknown;
535}
536
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700537bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700539 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800540
Adam Koskidc21dea2017-07-21 10:55:27 -0700541 proguard::CollectResourceReferences(context_, table, keep_set_);
542
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700544 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
545
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700546 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700547 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700549 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800550
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 // Populate the queue with all files in the ResourceTable.
552 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700553 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700554 // WARNING! Do not insert or remove any resources while executing in this scope. It will
555 // corrupt the iteration order.
556
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700557 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700558 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700559 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700561
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700562 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700564 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700566 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700567 }
568
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700569 FileOperation file_op;
570 file_op.entry = entry.get();
571 file_op.dst_path = *file_ref->path;
572 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700573 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700576 (file_ref->type == ResourceFile::Type::kBinaryXml ||
577 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700578 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700579 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700580 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700581 << "failed to open file");
582 return false;
583 }
584
Adam Lesinski00451162017-10-03 07:44:08 -0700585 if (file_ref->type == ResourceFile::Type::kProtoXml) {
586 pb::XmlNode pb_xml_node;
587 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
588 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700589 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700590 return false;
591 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700592
Adam Lesinski00451162017-10-03 07:44:08 -0700593 std::string error;
594 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
595 if (file_op.xml_to_flatten == nullptr) {
596 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700597 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700598 return false;
599 }
600 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700601 std::string error_str;
602 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700603 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700604 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
605 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700606 return false;
607 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 }
609
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800610 // Update the type that this file will be written as.
611 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
612
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700613 file_op.xml_to_flatten->file.config = config_value->config;
614 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700615 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700617
618 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
619 // else we end up copying the string in the std::make_pair() method,
620 // then creating a StringPiece from the copy, which would cause us
621 // to end up referencing garbage in the map.
622 const StringPiece entry_name(entry->name);
623 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
624 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700625 }
626 }
627
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700628 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700629 for (auto& map_entry : config_sorted_files) {
630 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700631 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700633 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700634 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
635 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700636 if (versioned_docs.empty()) {
637 error = true;
638 continue;
639 }
640
Adam Lesinskic744ae82017-05-17 19:28:38 -0700641 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
642 std::string dst_path = file_op.dst_path;
643 if (doc->file.config != file_op.config) {
644 // Only add the new versioned configurations.
645 if (context_->IsVerbose()) {
646 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
647 << "auto-versioning resource from config '"
648 << config << "' -> '" << doc->file.config << "'");
649 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700650
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800651 const ResourceFile& file = doc->file;
652 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
653
654 std::unique_ptr<FileReference> file_ref =
655 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
656 file_ref->SetSource(doc->file.source);
657 // Update the output format of this XML file.
658 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
659 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
660 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700661 return false;
662 }
663 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700664
665 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
666 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 }
668 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700669 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
670 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700671 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700672 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700673 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700674 }
675 return !error;
676}
677
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700678static bool WriteStableIdMapToPath(IDiagnostics* diag,
679 const std::unordered_map<ResourceName, ResourceId>& id_map,
680 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800681 io::FileOutputStream fout(id_map_path);
682 if (fout.HadError()) {
683 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700684 return false;
685 }
686
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800687 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700688 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700689 const ResourceName& name = entry.first;
690 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800691 printer.Print(name.to_string());
692 printer.Print(" = ");
693 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700694 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800695 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800697 if (fout.HadError()) {
698 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700699 return false;
700 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700701 return true;
702}
703
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700704static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
705 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700707 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700708 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700709 return false;
710 }
711
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700712 out_id_map->clear();
713 size_t line_no = 0;
714 for (StringPiece line : util::Tokenize(content, '\n')) {
715 line_no++;
716 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700717 if (line.empty()) {
718 continue;
719 }
720
721 auto iter = std::find(line.begin(), line.end(), '=');
722 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700723 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700724 return false;
725 }
726
727 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700728 StringPiece res_name_str =
729 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
730 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700731 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
732 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700733 return false;
734 }
735
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700736 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
737 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700738 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700739
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700740 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
741 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700742 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
743 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700744 return false;
745 }
746
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700747 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700748 }
749 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700750}
751
Adam Lesinskic6284372017-12-04 13:46:23 -0800752static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
753 using namespace android;
754
755 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
756 // we're looking for the first attribute resource in the system package.
757 const ResTable& table = assets.getResources(true);
758 Res_value val;
759 ssize_t idx = table.getResource(0x01010000, &val, true);
760 if (idx != NO_ERROR) {
761 // Try as a bag.
762 const ResTable::bag_entry* entry;
763 ssize_t cnt = table.lockBag(0x01010000, &entry);
764 if (cnt >= 0) {
765 idx = entry->stringBlock;
766 }
767 table.unlockBag(entry);
768 }
769
770 if (idx < 0) {
771 return 0;
772 }
773 return table.getTableCookie(idx);
774}
775
Adam Lesinskifb48d292015-11-07 15:52:13 -0800776class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700777 public:
778 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700779 : options_(options),
780 context_(context),
781 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700782 file_collection_(util::make_unique<io::FileCollection>()) {
783 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700784
Adam Lesinskic6284372017-12-04 13:46:23 -0800785 void ExtractCompileSdkVersions(android::AssetManager* assets) {
786 using namespace android;
787
788 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
789 if (cookie == 0) {
790 // No Framework assets loaded. Not a failure.
791 return;
792 }
793
794 std::unique_ptr<Asset> manifest(
795 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
796 if (manifest == nullptr) {
797 // No errors.
798 return;
799 }
800
801 std::string error;
802 std::unique_ptr<xml::XmlResource> manifest_xml =
803 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
804 if (manifest_xml == nullptr) {
805 // No errors.
806 return;
807 }
808
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700809 if (!options_.manifest_fixer_options.compile_sdk_version) {
810 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
811 if (attr != nullptr) {
812 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
813 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
814 switch (prim->value.dataType) {
815 case Res_value::TYPE_INT_DEC:
816 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
817 break;
818 case Res_value::TYPE_INT_HEX:
819 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
820 break;
821 default:
822 break;
823 }
824 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
825 compile_sdk_version = *str->value;
826 } else {
827 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800828 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800829 }
830 }
831
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700832 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
833 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
834 if (attr != nullptr) {
835 Maybe<std::string>& compile_sdk_version_codename =
836 options_.manifest_fixer_options.compile_sdk_version_codename;
837 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
838 compile_sdk_version_codename = *str->value;
839 } else {
840 compile_sdk_version_codename = attr->value;
841 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800842 }
843 }
844 }
845
Adam Lesinski8780eb62017-10-31 17:44:39 -0700846 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800847 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700848 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700849 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700850 for (const std::string& path : options_.include_paths) {
851 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700852 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700853 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700854
Adam Lesinski8780eb62017-10-31 17:44:39 -0700855 std::string error;
856 auto zip_collection = io::ZipFileCollection::Create(path, &error);
857 if (zip_collection == nullptr) {
858 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
859 return false;
860 }
861
862 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
863 // Load this as a static library include.
864 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
865 Source(path), std::move(zip_collection), context_->GetDiagnostics());
866 if (static_apk == nullptr) {
867 return false;
868 }
869
Adam Lesinskib522f042017-04-21 16:57:59 -0700870 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800871 // Can't include static libraries when not building a static library (they have no IDs
872 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700873 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800874 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700875 return false;
876 }
877
Adam Lesinski8780eb62017-10-31 17:44:39 -0700878 ResourceTable* table = static_apk->GetResourceTable();
879
880 // If we are using --no-static-lib-packages, we need to rename the package of this table to
881 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700882 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800883 // Since package names can differ, and multiple packages can exist in a ResourceTable,
884 // we place the requirement that all static libraries are built with the package
885 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700886 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700887 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800888 } else {
889 context_->GetDiagnostics()->Error(DiagMessage(path)
890 << "no package with ID 0x7f found in static library");
891 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700892 }
893 }
894
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700895 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700896 util::make_unique<ResourceTableSymbolSource>(table));
897 static_library_includes_.push_back(std::move(static_apk));
898 } else {
899 if (!asset_source->AddAssetPath(path)) {
900 context_->GetDiagnostics()->Error(DiagMessage()
901 << "failed to load include path " << path);
902 return false;
903 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700904 }
905 }
906
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800907 // Capture the shared libraries so that the final resource table can be properly flattened
908 // with support for shared libraries.
909 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700910 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800911 // Capture the included base feature package.
912 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800913 } else if (entry.first == kFrameworkPackageId) {
914 // Try to embed which version of the framework we're compiling against.
915 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
916 // when linking our synthesized 'android:compileSdkVersion' attribute.
917 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
918 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
919 if (symbol != nullptr && symbol->is_public) {
920 // The symbol is present and public, extract the android:versionName and
921 // android:versionCode from the framework AndroidManifest.xml.
922 ExtractCompileSdkVersions(asset_source->GetAssetManager());
923 }
Todd Kennedy32512992018-04-25 16:45:59 -0700924 } else if (asset_source->IsPackageDynamic(entry.first)) {
925 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800926 }
927 }
928
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700929 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700930 return true;
931 }
932
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800933 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700934 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800935 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
936 if (manifest_el == nullptr) {
937 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700938 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800939
940 AppInfo app_info;
941
942 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
943 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
944 return {};
945 }
946
947 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
948 if (!package_attr) {
949 diag->Error(DiagMessage(xml_res->file.source)
950 << "<manifest> must have a 'package' attribute");
951 return {};
952 }
953 app_info.package = package_attr->value;
954
955 if (xml::Attribute* version_code_attr =
956 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
957 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
958 if (!maybe_code) {
959 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
960 << "invalid android:versionCode '" << version_code_attr->value << "'");
961 return {};
962 }
963 app_info.version_code = maybe_code.value();
964 }
965
966 if (xml::Attribute* revision_code_attr =
967 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
968 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
969 if (!maybe_code) {
970 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
971 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
972 return {};
973 }
974 app_info.revision_code = maybe_code.value();
975 }
976
977 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
978 if (!split_name_attr->value.empty()) {
979 app_info.split_name = split_name_attr->value;
980 }
981 }
982
983 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
984 if (xml::Attribute* min_sdk =
985 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700986 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800987 }
988 }
989 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700990 }
991
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700992 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
993 // Postcondition: ResourceTable has only one package left. All others are
994 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700995 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700996 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700997 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
998 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700999 };
1000
1001 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001002 for (const auto& package : final_table_.packages) {
1003 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 // We have a package that is not related to the one we're building!
1005 for (const auto& type : package->types) {
1006 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001007 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001008
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001009 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001010 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001011 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001012 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1013 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1014 << "generated id '" << res_name
1015 << "' for external package '" << package->name
1016 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001018 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1019 << "defined resource '" << res_name
1020 << "' for external package '" << package->name
1021 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001022 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001023 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001024 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001025 }
1026 }
1027 }
1028 }
1029
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001030 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1031 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001032 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001033 return !error;
1034 }
1035
1036 /**
1037 * Returns true if no IDs have been set, false otherwise.
1038 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001039 bool VerifyNoIdsSet() {
1040 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001041 for (const auto& type : package->types) {
1042 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001043 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1044 << StringPrintf("%02x", type->id.value())
1045 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001046 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001047 }
1048
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001049 for (const auto& entry : type->entries) {
1050 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001051 ResourceNameRef res_name(package->name, type->type, entry->name);
1052 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001053 DiagMessage() << "entry " << res_name << " has ID "
1054 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001055 return false;
1056 }
1057 }
1058 }
1059 }
1060 return true;
1061 }
1062
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001063 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1064 if (options_.output_to_directory) {
1065 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001066 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001067 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001068 }
1069 }
1070
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001071 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1072 switch (format) {
1073 case OutputFormat::kApk: {
1074 BigBuffer buffer(1024);
1075 TableFlattener flattener(options_.table_flattener_options, &buffer);
1076 if (!flattener.Consume(context_, table)) {
1077 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1078 return false;
1079 }
1080
1081 io::BigBufferInputStream input_stream(&buffer);
1082 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1083 ArchiveEntry::kAlign, writer);
1084 } break;
1085
1086 case OutputFormat::kProto: {
1087 pb::ResourceTable pb_table;
Ryan Mitchell70414f22018-03-26 11:05:31 -07001088 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001089 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1090 ArchiveEntry::kCompress, writer);
1091 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001092 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001093 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001094 }
1095
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001096 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001097 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001098 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001099 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001100 return true;
1101 }
1102
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001103 std::string out_path;
1104 std::unique_ptr<io::FileOutputStream> fout;
1105 if (options_.generate_java_class_path) {
1106 out_path = options_.generate_java_class_path.value();
1107 file::AppendPath(&out_path, file::PackageToPath(out_package));
1108 if (!file::mkdirs(out_path)) {
1109 context_->GetDiagnostics()->Error(DiagMessage()
1110 << "failed to create directory '" << out_path << "'");
1111 return false;
1112 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001113
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001114 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001115
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001116 fout = util::make_unique<io::FileOutputStream>(out_path);
1117 if (fout->HadError()) {
1118 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1119 << "': " << fout->GetError());
1120 return false;
1121 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001122 }
1123
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001124 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001125 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001126 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1127 if (fout_text->HadError()) {
1128 context_->GetDiagnostics()->Error(DiagMessage()
1129 << "failed writing to '" << out_text_symbols_path.value()
1130 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001131 return false;
1132 }
1133 }
1134
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001135 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001136 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001137 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001138 return false;
1139 }
1140
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001141 return true;
1142 }
1143
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001144 bool GenerateJavaClasses() {
1145 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1146 std::vector<std::string> packages_to_callback;
1147
1148 JavaClassGeneratorOptions template_options;
1149 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1150 template_options.javadoc_annotations = options_.javadoc_annotations;
1151
1152 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1153 template_options.use_final = false;
1154 }
1155
1156 if (context_->GetPackageType() == PackageType::kSharedLib) {
1157 template_options.use_final = false;
1158 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1159 }
1160
1161 const StringPiece actual_package = context_->GetCompilationPackage();
1162 StringPiece output_package = context_->GetCompilationPackage();
1163 if (options_.custom_java_package) {
1164 // Override the output java package to the custom one.
1165 output_package = options_.custom_java_package.value();
1166 }
1167
1168 // Generate the private symbols if required.
1169 if (options_.private_symbols) {
1170 packages_to_callback.push_back(options_.private_symbols.value());
1171
1172 // If we defined a private symbols package, we only emit Public symbols
1173 // to the original package, and private and public symbols to the private package.
1174 JavaClassGeneratorOptions options = template_options;
1175 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1176 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1177 options)) {
1178 return false;
1179 }
1180 }
1181
1182 // Generate copies of the original package R class but with different package names.
1183 // This is to support non-namespaced builds.
1184 for (const std::string& extra_package : options_.extra_java_packages) {
1185 packages_to_callback.push_back(extra_package);
1186
1187 JavaClassGeneratorOptions options = template_options;
1188 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1189 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1190 return false;
1191 }
1192 }
1193
1194 // Generate R classes for each package that was merged (static library).
1195 // Use the actual package's resources only.
1196 for (const std::string& package : table_merger_->merged_packages()) {
1197 packages_to_callback.push_back(package);
1198
1199 JavaClassGeneratorOptions options = template_options;
1200 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1201 if (!WriteJavaFile(&final_table_, package, package, options)) {
1202 return false;
1203 }
1204 }
1205
1206 // Generate the main public R class.
1207 JavaClassGeneratorOptions options = template_options;
1208
1209 // Only generate public symbols if we have a private package.
1210 if (options_.private_symbols) {
1211 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1212 }
1213
1214 if (options.rewrite_callback_options) {
1215 options.rewrite_callback_options.value().packages_to_callback =
1216 std::move(packages_to_callback);
1217 }
1218
1219 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1220 options_.generate_text_symbols_path)) {
1221 return false;
1222 }
1223
1224 return true;
1225 }
1226
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1228 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001229 return true;
1230 }
1231
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001232 std::unique_ptr<ClassDefinition> manifest_class =
1233 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001234
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001235 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001236 // Something bad happened, but we already logged it, so exit.
1237 return false;
1238 }
1239
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001240 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001241 // Empty Manifest class, no need to generate it.
1242 return true;
1243 }
1244
1245 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001246 for (const std::string& annotation : options_.javadoc_annotations) {
1247 std::string proper_annotation = "@";
1248 proper_annotation += annotation;
1249 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001250 }
1251
Adam Lesinski0d81f702017-06-27 15:51:09 -07001252 const std::string package_utf8 =
1253 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001254
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001255 std::string out_path = options_.generate_java_class_path.value();
1256 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001258 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001259 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1260 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001261 return false;
1262 }
1263
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001264 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001265
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001266 io::FileOutputStream fout(out_path);
1267 if (fout.HadError()) {
1268 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1269 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001270 return false;
1271 }
1272
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001273 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1274 fout.Flush();
1275
1276 if (fout.HadError()) {
1277 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1278 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 return false;
1280 }
1281 return true;
1282 }
1283
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001284 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001285 if (!out) {
1286 return true;
1287 }
1288
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001289 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001290 io::FileOutputStream fout(out_path);
1291 if (fout.HadError()) {
1292 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1293 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 return false;
1295 }
1296
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001297 proguard::WriteKeepSet(keep_set, &fout);
1298 fout.Flush();
1299
1300 if (fout.HadError()) {
1301 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1302 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001303 return false;
1304 }
1305 return true;
1306 }
1307
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001308 bool MergeStaticLibrary(const std::string& input, bool override) {
1309 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001310 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001311 }
1312
Adam Lesinski8780eb62017-10-31 17:44:39 -07001313 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1314 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001315 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001316 return false;
1317 }
1318
Adam Lesinski8780eb62017-10-31 17:44:39 -07001319 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001320 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001322 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001323 return false;
1324 }
1325
1326 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001327 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001328 // Merge all resources as if they were in the compilation package. This is the old behavior
1329 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001330
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001331 // Add the package to the set of --extra-packages so we emit an R.java for each library
1332 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001333 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001334 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335 }
1336
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001337 // Clear the package name, so as to make the resources look like they are coming from the
1338 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001339 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001340 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001341
1342 } else {
1343 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001344 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001345 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001346 }
1347
1348 if (!result) {
1349 return false;
1350 }
1351
1352 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001353 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001354 return true;
1355 }
1356
Adam Lesinski2427dce2017-11-30 15:10:28 -08001357 bool MergeExportedSymbols(const Source& source,
1358 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001359 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001360 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001361 ResourceName res_name = exported_symbol.name;
1362 if (res_name.package.empty()) {
1363 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001364 }
1365
Adam Lesinski00451162017-10-03 07:44:08 -07001366 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001367 if (mangled_name) {
1368 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001369 }
1370
1371 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001372 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001373 bool result =
1374 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1375 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376 if (!result) {
1377 return false;
1378 }
1379 }
1380 return true;
1381 }
1382
Adam Lesinski2427dce2017-11-30 15:10:28 -08001383 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1384 if (context_->IsVerbose()) {
1385 context_->GetDiagnostics()->Note(DiagMessage()
1386 << "merging '" << compiled_file.name
1387 << "' from compiled file " << compiled_file.source);
1388 }
1389
1390 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1391 return false;
1392 }
1393 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1394 }
1395
Adam Lesinski00451162017-10-03 07:44:08 -07001396 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1397 // If override is true, conflicting resources are allowed to override each other, in order of last
1398 // seen.
1399 // An io::IFileCollection is created from the ZIP file and added to the set of
1400 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001401 bool MergeArchive(const std::string& input, bool override) {
1402 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001403 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001404 }
1405
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001406 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001407 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001408 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001409 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001410 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001411 return false;
1412 }
1413
1414 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001415 for (auto iter = collection->Iterator(); iter->HasNext();) {
1416 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417 error = true;
1418 }
1419 }
1420
1421 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001422 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001423 return !error;
1424 }
1425
Adam Lesinski00451162017-10-03 07:44:08 -07001426 // Takes a path to load and merge into the master ResourceTable. If override is true,
1427 // conflicting resources are allowed to override each other, in order of last seen.
1428 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1429 // as ZIP archive and the files within are merged individually.
1430 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001431 bool MergePath(const std::string& path, bool override) {
1432 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1433 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1434 return MergeArchive(path, override);
1435 } else if (util::EndsWith(path, ".apk")) {
1436 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001437 }
1438
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001439 io::IFile* file = file_collection_->InsertFile(path);
1440 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001441 }
1442
Adam Lesinski00451162017-10-03 07:44:08 -07001443 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1444 // If override is true, conflicting resources are allowed to override each other, in order of last
1445 // seen.
1446 // All other file types are ignored. This is because these files could be coming from a zip,
1447 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001448 bool MergeFile(io::IFile* file, bool override) {
1449 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001450
Adam Lesinski00451162017-10-03 07:44:08 -07001451 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001452 // Since AAPT compiles these file types and appends .flat to them, seeing
1453 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001454 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1455 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1456 << " file passed as argument. Must be "
1457 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001458 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001459 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1460 if (context_->IsVerbose()) {
1461 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1462 return true;
1463 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001464 }
1465
Adam Lesinski00451162017-10-03 07:44:08 -07001466 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1467 if (input_stream == nullptr) {
1468 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1469 return false;
1470 }
1471
1472 if (input_stream->HadError()) {
1473 context_->GetDiagnostics()->Error(DiagMessage(src)
1474 << "failed to open file: " << input_stream->GetError());
1475 return false;
1476 }
1477
1478 ContainerReaderEntry* entry;
1479 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001480
1481 if (reader.HadError()) {
1482 context_->GetDiagnostics()->Error(DiagMessage(src)
1483 << "failed to read file: " << reader.GetError());
1484 return false;
1485 }
1486
Adam Lesinski00451162017-10-03 07:44:08 -07001487 while ((entry = reader.Next()) != nullptr) {
1488 if (entry->Type() == ContainerEntryType::kResTable) {
1489 pb::ResourceTable pb_table;
1490 if (!entry->GetResTable(&pb_table)) {
1491 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1492 << entry->GetError());
1493 return false;
1494 }
1495
1496 ResourceTable table;
1497 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001498 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001499 context_->GetDiagnostics()->Error(DiagMessage(src)
1500 << "failed to deserialize resource table: " << error);
1501 return false;
1502 }
1503
1504 if (!table_merger_->Merge(src, &table, override)) {
1505 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1506 return false;
1507 }
1508 } else if (entry->Type() == ContainerEntryType::kResFile) {
1509 pb::internal::CompiledFile pb_compiled_file;
1510 off64_t offset;
1511 size_t len;
1512 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1513 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1514 << entry->GetError());
1515 return false;
1516 }
1517
1518 ResourceFile resource_file;
1519 std::string error;
1520 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1521 context_->GetDiagnostics()->Error(DiagMessage(src)
1522 << "failed to read compiled header: " << error);
1523 return false;
1524 }
1525
1526 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1527 return false;
1528 }
1529 }
1530 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001531 return true;
1532 }
1533
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001534 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1535 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1536 for (const std::string& assets_dir : options_.assets_dirs) {
1537 Maybe<std::vector<std::string>> files =
1538 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1539 if (!files) {
1540 return false;
1541 }
1542
1543 for (const std::string& file : files.value()) {
1544 std::string full_key = "assets/" + file;
1545 std::string full_path = assets_dir;
1546 file::AppendPath(&full_path, file);
1547
1548 auto iter = merged_assets.find(full_key);
1549 if (iter == merged_assets.end()) {
1550 merged_assets.emplace(std::move(full_key),
1551 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1552 } else if (context_->IsVerbose()) {
1553 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1554 << "asset file overrides '" << full_path << "'");
1555 }
1556 }
1557 }
1558
1559 for (auto& entry : merged_assets) {
1560 uint32_t compression_flags = ArchiveEntry::kCompress;
1561 std::string extension = file::GetExtension(entry.first).to_string();
1562 if (options_.extensions_to_not_compress.count(extension) > 0) {
1563 compression_flags = 0u;
1564 }
1565
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001566 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1567 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001568 return false;
1569 }
1570 }
1571 return true;
1572 }
1573
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001574 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1575 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001576 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1577 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001578 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001579 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1580 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001581 if (!result) {
1582 return false;
1583 }
1584
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001585 ResourceFileFlattenerOptions file_flattener_options;
1586 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001587 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1588 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001589 file_flattener_options.no_auto_version = options_.no_auto_version;
1590 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001591 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001592 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1593 file_flattener_options.update_proguard_spec =
1594 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001595 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001596
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001597 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001598
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001599 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001600 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001601 return false;
1602 }
1603
Adam Lesinski490595a2017-11-07 17:08:07 -08001604 // Hack to fix b/68820737.
1605 // We need to modify the ResourceTable's package name, but that should NOT affect
1606 // anything else being generated, which includes the Java classes.
1607 // If required, the package name is modifed before flattening, and then modified back
1608 // to its original name.
1609 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001610 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1611 // or higher] as invalid. In order to work around this limitation, we allow the use
1612 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1613 // definition of what a valid "split" package ID is to account for this.
1614 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1615 context_->GetPackageId() != kAppPackageId &&
1616 context_->GetPackageId() != kFrameworkPackageId)
1617 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1618 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001619 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1620 // The base APK is included, and this is a feature split. If the base package is
1621 // the same as this package, then we are building an old style Android Instant Apps feature
1622 // split and must apply this workaround to avoid requiring namespaces support.
1623 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1624 if (package_to_rewrite != nullptr) {
1625 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1626
1627 std::string new_package_name =
1628 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1629 app_info_.split_name.value_or_default("feature").c_str());
1630
1631 if (context_->IsVerbose()) {
1632 context_->GetDiagnostics()->Note(
1633 DiagMessage() << "rewriting resource package name for feature split to '"
1634 << new_package_name << "'");
1635 }
1636 package_to_rewrite->name = new_package_name;
1637 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001638 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001639
1640 bool success = FlattenTable(table, options_.output_format, writer);
1641
1642 if (package_to_rewrite != nullptr) {
1643 // Change the name back.
1644 package_to_rewrite->name = context_->GetCompilationPackage();
1645 if (package_to_rewrite->id) {
1646 table->included_packages_.erase(package_to_rewrite->id.value());
1647 }
1648 }
1649
1650 if (!success) {
1651 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1652 }
1653 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001654 }
1655
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001656 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001657 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001658 std::unique_ptr<xml::XmlResource> manifest_xml =
1659 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1660 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001661 return 1;
1662 }
1663
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001664 // First extract the Package name without modifying it (via --rename-manifest-package).
1665 if (Maybe<AppInfo> maybe_app_info =
1666 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001667 const AppInfo& app_info = maybe_app_info.value();
1668 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001669 }
1670
Adam Lesinskic6284372017-12-04 13:46:23 -08001671 // Now that the compilation package is set, load the dependencies. This will also extract
1672 // the Android framework's versionCode and versionName, if they exist.
1673 if (!LoadSymbolsFromIncludePaths()) {
1674 return 1;
1675 }
1676
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001677 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1678 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001679 return 1;
1680 }
1681
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001682 Maybe<AppInfo> maybe_app_info =
1683 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001684 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001685 return 1;
1686 }
1687
Adam Lesinski490595a2017-11-07 17:08:07 -08001688 app_info_ = maybe_app_info.value();
1689 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001690
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001691 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001692
1693 // Override the package ID when it is "android".
1694 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001695 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001696
1697 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001698 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001699 context_->GetDiagnostics()->Error(
1700 DiagMessage() << "package 'android' can only be built as a regular app");
1701 return 1;
1702 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001703 }
1704
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001705 TableMergerOptions table_merger_options;
1706 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001707 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001708
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001709 if (context_->IsVerbose()) {
1710 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001711 << StringPrintf("linking package '%s' using package ID %02x",
1712 context_->GetCompilationPackage().data(),
1713 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001714 }
1715
Adam Lesinski2427dce2017-11-30 15:10:28 -08001716 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1717 // in res/**/*.
1718 {
1719 XmlIdCollector collector;
1720 if (!collector.Consume(context_, manifest_xml.get())) {
1721 return false;
1722 }
1723
1724 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1725 return false;
1726 }
1727 }
1728
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001729 for (const std::string& input : input_files) {
1730 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001731 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001732 return 1;
1733 }
1734 }
1735
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001736 for (const std::string& input : options_.overlay_files) {
1737 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001738 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001739 return 1;
1740 }
1741 }
1742
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001743 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001744 return 1;
1745 }
1746
Adam Lesinskib522f042017-04-21 16:57:59 -07001747 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001748 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001749 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001750 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001751 return 1;
1752 }
1753
1754 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001755 IdAssigner id_assigner(&options_.stable_id_map);
1756 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001757 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001758 return 1;
1759 }
1760
1761 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001762 if (options_.resource_id_map_path) {
1763 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001764 for (auto& type : package->types) {
1765 for (auto& entry : type->entries) {
1766 ResourceName name(package->name, type->type, entry->name);
1767 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001768 options_.stable_id_map[std::move(name)] =
1769 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001770 }
1771 }
1772 }
1773
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001774 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001775 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001776 return 1;
1777 }
1778 }
1779 } else {
1780 // Static libs are merged with other apps, and ID collisions are bad, so
1781 // verify that
1782 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001783 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001784 return 1;
1785 }
1786 }
1787
1788 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001789 context_->SetNameManglerPolicy(
1790 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001791
1792 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001793 context_->GetExternalSymbols()->PrependSource(
1794 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001796 // Workaround for pre-O runtime that would treat negative resource IDs
1797 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1798 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1799 // are just identifiers.
1800 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1801 if (context_->IsVerbose()) {
1802 context_->GetDiagnostics()->Note(DiagMessage()
1803 << "enabling pre-O feature split ID rewriting");
1804 }
1805 context_->GetExternalSymbols()->SetDelegate(
1806 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1807 }
1808
Adam Lesinski34a16872018-02-23 16:18:10 -08001809 // Before we process anything, remove the resources whose default values don't exist.
1810 // We want to force any references to these to fail the build.
Mårten Kongstadf99eda42018-06-11 14:13:37 +02001811 if (!options_.no_resource_removal) {
1812 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1813 context_->GetDiagnostics()->Error(DiagMessage()
1814 << "failed removing resources with no defaults");
1815 return 1;
1816 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001817 }
1818
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001819 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001820 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001821 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001822 return 1;
1823 }
1824
Adam Lesinskib522f042017-04-21 16:57:59 -07001825 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001826 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001827 context_->GetDiagnostics()->Warn(DiagMessage()
1828 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 }
1830 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001831 ProductFilter product_filter(options_.products);
1832 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001833 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001834 return 1;
1835 }
1836 }
1837
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001838 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001839 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001840 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001841 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001842 return 1;
1843 }
1844 }
1845
Adam Lesinskib522f042017-04-21 16:57:59 -07001846 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001848 context_->GetDiagnostics()->Note(DiagMessage()
1849 << "collapsing resource versions for minimum SDK "
1850 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001851 }
1852
1853 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001855 return 1;
1856 }
1857 }
1858
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001859 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001860 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001861 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001862 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001863 return 1;
1864 }
1865 }
1866
Adam Koskidc21dea2017-07-21 10:55:27 -07001867 proguard::KeepSet proguard_keep_set =
1868 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001870
Adam Lesinskib522f042017-04-21 16:57:59 -07001871 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001872 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001873 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001874 context_->GetDiagnostics()->Warn(DiagMessage()
1875 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001876 }
1877 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001878 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1879 // equal to the minSdk.
1880 options_.split_constraints =
1881 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001882
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001883 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001885 return 1;
1886 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001887 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001888
1889 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001890 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001891 auto split_constraints_iter = options_.split_constraints.begin();
1892 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001893 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1895 << "generating split with configurations '"
1896 << util::Joiner(split_constraints_iter->configs, ", ")
1897 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001898 }
1899
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001900 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001901 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001902 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001903 return 1;
1904 }
1905
1906 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001907 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001908 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001909
1910 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001911 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001912 context_->GetDiagnostics()->Error(DiagMessage()
1913 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001914 return 1;
1915 }
1916
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001917 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1918 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001919 return 1;
1920 }
1921
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001922 ++path_iter;
1923 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001924 }
1925 }
1926
1927 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001928 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001930 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001931 return 1;
1932 }
1933
1934 bool error = false;
1935 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001936 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001937 // (aka, which package the AndroidManifest.xml is coming from).
1938 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001939 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001940
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001941 XmlReferenceLinker manifest_linker;
1942 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1943 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001944 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001945 error = true;
1946 }
1947
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001948 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001949 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001950 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001951 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001952 }
1953
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001954 if (options_.generate_java_class_path) {
1955 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001956 error = true;
1957 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001958 }
1959
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001960 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001961 // PackageParser will fail if URIs are removed from
1962 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001963 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1964 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001965 error = true;
1966 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001967 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001968 } else {
1969 error = true;
1970 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001971 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001972
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001973 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001974 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975 return 1;
1976 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001977
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001978 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1979 return 1;
1980 }
1981
1982 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001983 return 1;
1984 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001985
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001986 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001987 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001988 return 1;
1989 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001990 }
1991
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001992 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001993 return 1;
1994 }
1995
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1997 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001998 return 1;
1999 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000 return 0;
2001 }
2002
2003 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002004 LinkOptions options_;
2005 LinkContext* context_;
2006 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002007
Adam Lesinski490595a2017-11-07 17:08:07 -08002008 AppInfo app_info_;
2009
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002010 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011
2012 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002013 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002014
Adam Lesinski8780eb62017-10-31 17:44:39 -07002015 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002016 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002017 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002018
Adam Lesinski8780eb62017-10-31 17:44:39 -07002019 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2020 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2021
2022 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2023 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002024
2025 // The set of shared libraries being used, mapping their assigned package ID to package name.
2026 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002027
2028 // The package name of the base application, if it is included.
2029 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002030};
2031
Chris Warrington820d72a2017-04-27 15:27:01 +01002032int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2033 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002034 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002035 std::vector<std::string> overlay_arg_list;
2036 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002037 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002038 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002039 Maybe<std::string> preferred_density;
2040 Maybe<std::string> product_list;
2041 bool legacy_x_flag = false;
2042 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002043 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002044 bool shared_lib = false;
2045 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002046 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002047 Maybe<std::string> stable_id_file_path;
2048 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002049 Flags flags =
2050 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002051 .RequiredFlag("-o", "Output path.", &options.output_path)
2052 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002053 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002054 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002055 .OptionalFlagList("-A",
2056 "An assets directory to include in the APK. These are unprocessed.",
2057 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002058 .OptionalFlagList("-R",
2059 "Compilation unit to link, using `overlay` semantics.\n"
2060 "The last conflicting resource given takes precedence.",
2061 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002062 .OptionalFlag("--package-id",
2063 "Specify the package ID to use for this app. Must be greater or equal to\n"
2064 "0x7f and can't be used with --static-lib or --shared-lib.",
2065 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002066 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002067 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002068 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002069 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002070 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002071 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002072 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002073 .OptionalSwitch("--proguard-conditional-keep-rules",
2074 "Generate conditional Proguard keep rules.",
2075 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002076 .OptionalSwitch("--no-auto-version",
2077 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002078 &options.no_auto_version)
2079 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002080 "Disables automatic versioning of vector drawables. Use this only\n"
2081 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002082 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002083 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002084 "Disables automatic versioning of transition resources. Use this only\n"
2085 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002086 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002087 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002088 "Disables automatic deduping of resources with\n"
2089 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002090 &options.no_resource_deduping)
Mårten Kongstadf99eda42018-06-11 14:13:37 +02002091 .OptionalSwitch("--no-resource-removal",
2092 "Disables automatic removal of resources without defaults. Use this only\n"
2093 "when building runtime resource overlay packages.",
2094 &options.no_resource_removal)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002095 .OptionalSwitch("--enable-sparse-encoding",
2096 "Enables encoding sparse entries using a binary search tree.\n"
2097 "This decreases APK size at the cost of resource retrieval performance.",
2098 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002099 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002100 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002101 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002102 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002103 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002104 "Comma separated list of configurations to include. The default\n"
2105 "is all configurations.",
2106 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002107 .OptionalFlag("--preferred-density",
2108 "Selects the closest matching density and strips out all others.",
2109 &preferred_density)
2110 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002111 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002112 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002113 &options.output_to_directory)
2114 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002115 "Removes XML namespace prefix and URI information from\n"
2116 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002117 &options.no_xml_namespaces)
2118 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002119 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002121 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002122 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002123 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002124 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002125 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2126 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 &options.manifest_fixer_options.version_code_default)
2128 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002129 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002130 &options.manifest_fixer_options.version_name_default)
Colin Crossda02fea2018-05-25 22:46:35 -07002131 .OptionalSwitch("--replace-version",
2132 "If --version-code and/or --version-name are specified, these\n"
2133 "values will replace any value already in the manifest. By\n"
2134 "default, nothing is changed if the manifest already defines\n"
2135 "these attributes.",
2136 &options.manifest_fixer_options.replace_version)
Todd Kennedy9f6dec12018-04-20 12:29:29 -07002137 .OptionalFlag("--compile-sdk-version-code",
2138 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2139 "present.",
2140 &options.manifest_fixer_options.compile_sdk_version)
2141 .OptionalFlag("--compile-sdk-version-name",
2142 "Version name to inject into the AndroidManifest.xml if none is present.",
2143 &options.manifest_fixer_options.compile_sdk_version_codename)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002144 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2145 &shared_lib)
2146 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002147 .OptionalSwitch("--proto-format",
2148 "Generates compiled resources in Protobuf format.\n"
2149 "Suitable as input to the bundle tool for generating an App Bundle.",
2150 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002151 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002152 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 &options.no_static_lib_packages)
2154 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002155 "Generates R.java without the final modifier. This is implied when\n"
2156 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002157 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002158 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002159 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002160 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002161 "Emit a file at the given path with a list of name to ID mappings,\n"
2162 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002163 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002164 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002165 "Package name to use when generating R.java for private symbols.\n"
2166 "If not specified, public and private symbols will use the application's\n"
2167 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002168 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002169 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002170 &options.custom_java_package)
2171 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002172 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002173 &extra_java_packages)
2174 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002175 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002176 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002177 .OptionalFlag("--output-text-symbols",
2178 "Generates a text file containing the resource symbols of the R class in\n"
2179 "the specified folder.",
2180 &options.generate_text_symbols_path)
Todd Kennedy32512992018-04-25 16:45:59 -07002181 .OptionalSwitch("--allow-reserved-package-id",
2182 "Allows the use of a reserved package ID. This should on be used for\n"
2183 "packages with a pre-O min-sdk\n",
2184 &options.allow_reserved_package_id)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002185 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002186 "Allows the addition of new resources in overlays without\n"
2187 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002188 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002189 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002190 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002191 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002192 "Changes the name of the target package for instrumentation. Most useful\n"
2193 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002194 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002195 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002196 &options.extensions_to_not_compress)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002197 .OptionalSwitch("--warn-manifest-validation",
2198 "Treat manifest validation errors as warnings.",
2199 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002200 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002201 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002202 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2203 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002204 &split_args)
Ryan Mitchelle5b38a62018-03-23 13:35:00 -07002205 .OptionalSwitch("-v", "Enables verbose logging.", &verbose)
2206 .OptionalSwitch("--debug-mode",
2207 "Inserts android:debuggable=\"true\" in to the application node of the\n"
2208 "manifest, making the application debuggable even on production devices.",
2209 &options.manifest_fixer_options.debug_mode);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002210
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002211 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002212 return 1;
2213 }
2214
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002215 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002216 std::vector<std::string> arg_list;
2217 for (const std::string& arg : flags.GetArgs()) {
2218 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002219 const std::string path = arg.substr(1, arg.size() - 1);
2220 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002221 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2222 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002223 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002224 }
2225 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002226 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002227 }
2228 }
2229
2230 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002231 for (const std::string& arg : overlay_arg_list) {
2232 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002233 const std::string path = arg.substr(1, arg.size() - 1);
2234 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002235 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2236 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002237 return 1;
2238 }
2239 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002240 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002241 }
2242 }
2243
2244 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002245 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002246 }
2247
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002248 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2249 context.GetDiagnostics()->Error(
2250 DiagMessage()
2251 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002252 return 1;
2253 }
2254
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002255 // The default build type.
2256 context.SetPackageType(PackageType::kApp);
2257 context.SetPackageId(kAppPackageId);
2258
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002259 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002260 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002261 context.SetPackageId(0x00);
2262 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002263 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002264 options.output_format = OutputFormat::kProto;
2265 } else if (proto_format) {
2266 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002267 }
2268
2269 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002270 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002271 context.GetDiagnostics()->Error(
2272 DiagMessage() << "can't specify --package-id when not building a regular app");
2273 return 1;
2274 }
2275
2276 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2277 if (!maybe_package_id_int) {
2278 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2279 << "' is not a valid integer");
2280 return 1;
2281 }
2282
2283 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002284 if (package_id_int > std::numeric_limits<uint8_t>::max()
2285 || package_id_int == kFrameworkPackageId
2286 || (!options.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002287 context.GetDiagnostics()->Error(
2288 DiagMessage() << StringPrintf(
2289 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2290 return 1;
2291 }
2292 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2293 }
2294
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002295 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002296 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002297 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002298 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002299 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002300 }
2301 }
2302
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002303 if (product_list) {
2304 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002305 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002306 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002307 }
2308 }
2309 }
2310
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002311 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002312 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002313 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2314 if (filter == nullptr) {
2315 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002316 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002317 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002318 }
2319
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002320 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002321 Maybe<uint16_t> density =
2322 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2323 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002324 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002325 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002326 options.table_splitter_options.preferred_densities.push_back(density.value());
2327 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002328
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002329 // Parse the split parameters.
2330 for (const std::string& split_arg : split_args) {
2331 options.split_paths.push_back({});
2332 options.split_constraints.push_back({});
2333 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2334 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002335 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002336 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002337 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002338
Adam Lesinskib522f042017-04-21 16:57:59 -07002339 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002340 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2341 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002342 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002343 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002344 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002345
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002346 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002347 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002348 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2349 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2350 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2351 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2352
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002353 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002354 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002355 options.no_auto_version = true;
2356 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002357 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002358 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002359
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002360 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002361 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002362}
2363
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002364} // namespace aapt