blob: 512a5944ff739128f85e0d7c3668064bcb0e6a95 [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;
109 bool no_xml_namespaces = false;
110 bool do_not_compress_anything = false;
111 std::unordered_set<std::string> extensions_to_not_compress;
112
113 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700114 bool no_static_lib_packages = false;
115
116 // AndroidManifest.xml massaging options.
117 ManifestFixerOptions manifest_fixer_options;
118
119 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700120 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700121
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800122 // Flattening options.
123 TableFlattenerOptions table_flattener_options;
124
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700125 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700126 TableSplitterOptions table_splitter_options;
127 std::vector<SplitConstraints> split_constraints;
128 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700129
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700130 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700131 std::unordered_map<ResourceName, ResourceId> stable_id_map;
132 Maybe<std::string> resource_id_map_path;
Todd Kennedy32512992018-04-25 16:45:59 -0700133
134 // When 'true', allow reserved package IDs to be used for applications. Pre-O, the platform
135 // treats negative resource IDs [those with a package ID of 0x80 or higher] as invalid.
136 // In order to work around this limitation, we allow the use of traditionally reserved
137 // resource IDs [those between 0x02 and 0x7E].
138 bool allow_reserved_package_id = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139};
140
Adam Lesinski64587af2016-02-18 18:33:06 -0800141class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700142 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100143 LinkContext(IDiagnostics* diagnostics)
144 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700145 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700146
Adam Lesinskib522f042017-04-21 16:57:59 -0700147 PackageType GetPackageType() override {
148 return package_type_;
149 }
150
151 void SetPackageType(PackageType type) {
152 package_type_ = type;
153 }
154
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700155 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100156 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700157 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700158
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700159 NameMangler* GetNameMangler() override {
160 return &name_mangler_;
161 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700162
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700163 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
164 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700165 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800166
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700167 const std::string& GetCompilationPackage() override {
168 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700169 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700170
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700171 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800172 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700173 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800174
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700175 uint8_t GetPackageId() override {
176 return package_id_;
177 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700178
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700179 void SetPackageId(uint8_t id) {
180 package_id_ = id;
181 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800182
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700183 SymbolTable* GetExternalSymbols() override {
184 return &symbols_;
185 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800186
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700187 bool IsVerbose() override {
188 return verbose_;
189 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800190
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700191 void SetVerbose(bool val) {
192 verbose_ = val;
193 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800194
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700195 int GetMinSdkVersion() override {
196 return min_sdk_version_;
197 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700198
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700199 void SetMinSdkVersion(int minSdk) {
200 min_sdk_version_ = minSdk;
201 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700202
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700203 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700204 DISALLOW_COPY_AND_ASSIGN(LinkContext);
205
Adam Lesinskib522f042017-04-21 16:57:59 -0700206 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100207 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700208 NameMangler name_mangler_;
209 std::string compilation_package_;
210 uint8_t package_id_ = 0x0;
211 SymbolTable symbols_;
212 bool verbose_ = false;
213 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700214};
215
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700216// A custom delegate that generates compatible pre-O IDs for use with feature splits.
217// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
218// is interpreted as a negative number. Some verification was wrongly assuming negative values
219// were invalid.
220//
221// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
222// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
223// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800224//
225// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700226class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
227 public:
228 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
229 }
230
231 virtual ~FeatureSplitSymbolTableDelegate() = default;
232
233 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
234 const ResourceName& name,
235 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
236 std::unique_ptr<SymbolTable::Symbol> symbol =
237 DefaultSymbolTableDelegate::FindByName(name, sources);
238 if (symbol == nullptr) {
239 return {};
240 }
241
242 // Check to see if this is an 'id' with the target package.
243 if (name.type == ResourceType::kId && symbol->id) {
244 ResourceId* id = &symbol->id.value();
245 if (id->package_id() > kAppPackageId) {
246 // Rewrite the resource ID to be compatible pre-O.
247 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
248
249 // Check that this doesn't overlap another resource.
250 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
251 // The ID overlaps, so log a message (since this is a weird failure) and fail.
252 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
253 << " for pre-O feature split support");
254 return {};
255 }
256
257 if (context_->IsVerbose()) {
258 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
259 << ") -> (" << rewritten_id << ")");
260 }
261
262 *id = rewritten_id;
263 }
264 }
265 return symbol;
266 }
267
268 private:
269 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
270
271 IAaptContext* context_;
272};
273
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700274static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
275 const StringPiece& path, bool keep_raw_values, bool utf16,
276 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700277 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700278 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
279 << (keep_raw_values ? "true" : "false")
280 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700281 }
282
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700283 switch (format) {
284 case OutputFormat::kApk: {
285 BigBuffer buffer(1024);
286 XmlFlattenerOptions options = {};
287 options.keep_raw_values = keep_raw_values;
288 options.use_utf16 = utf16;
289 XmlFlattener flattener(&buffer, options);
290 if (!flattener.Consume(context, &xml_res)) {
291 return false;
292 }
293
294 io::BigBufferInputStream input_stream(&buffer);
295 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
296 ArchiveEntry::kCompress, writer);
297 } break;
298
299 case OutputFormat::kProto: {
300 pb::XmlNode pb_node;
301 SerializeXmlResourceToPb(xml_res, &pb_node);
302 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
303 writer);
304 } break;
305 }
306 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800307}
308
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700309// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700310static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700311 FileInputStream fin(path);
312 if (fin.HadError()) {
313 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700314 return {};
315 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700316 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800317}
318
Adam Lesinski355f2852016-02-13 20:26:45 -0800319struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700320 bool no_auto_version = false;
321 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900322 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700323 bool no_xml_namespaces = false;
324 bool keep_raw_values = false;
325 bool do_not_compress_anything = false;
326 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700327 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700328 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800329};
330
Adam Lesinskic744ae82017-05-17 19:28:38 -0700331// A sampling of public framework resource IDs.
332struct R {
333 struct attr {
334 enum : uint32_t {
335 paddingLeft = 0x010100d6u,
336 paddingRight = 0x010100d8u,
337 paddingHorizontal = 0x0101053du,
338
339 paddingTop = 0x010100d7u,
340 paddingBottom = 0x010100d9u,
341 paddingVertical = 0x0101053eu,
342
343 layout_marginLeft = 0x010100f7u,
344 layout_marginRight = 0x010100f9u,
345 layout_marginHorizontal = 0x0101053bu,
346
347 layout_marginTop = 0x010100f8u,
348 layout_marginBottom = 0x010100fau,
349 layout_marginVertical = 0x0101053cu,
350 };
351 };
352};
353
Adam Lesinski355f2852016-02-13 20:26:45 -0800354class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700355 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700356 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700357 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800358
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700359 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 private:
362 struct FileOperation {
363 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700364
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700365 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700366 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700367
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700368 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700369 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700370
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700371 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700372 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700373
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700374 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700375 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700376 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800377
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700378 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800379
Adam Lesinskic744ae82017-05-17 19:28:38 -0700380 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
381 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800382
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700383 ResourceFileFlattenerOptions options_;
384 IAaptContext* context_;
385 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700386 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800387};
388
Adam Lesinskic744ae82017-05-17 19:28:38 -0700389ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
390 IAaptContext* context, proguard::KeepSet* keep_set)
391 : options_(options), context_(context), keep_set_(keep_set) {
392 SymbolTable* symm = context_->GetExternalSymbols();
393
394 // Build up the rules for degrading newer attributes to older ones.
395 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
396 // generated from the attribute definitions themselves (b/62028956).
397 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
398 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800399 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
400 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700401 };
402 rules_[R::attr::paddingHorizontal] =
403 util::make_unique<DegradeToManyRule>(std::move(replacements));
404 }
405
406 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
407 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800408 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
409 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700410 };
411 rules_[R::attr::paddingVertical] =
412 util::make_unique<DegradeToManyRule>(std::move(replacements));
413 }
414
415 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
416 std::vector<ReplacementAttr> replacements{
417 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800418 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700419 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800420 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700421 };
422 rules_[R::attr::layout_marginHorizontal] =
423 util::make_unique<DegradeToManyRule>(std::move(replacements));
424 }
425
426 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
427 std::vector<ReplacementAttr> replacements{
428 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800429 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700430 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800431 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700432 };
433 rules_[R::attr::layout_marginVertical] =
434 util::make_unique<DegradeToManyRule>(std::move(replacements));
435 }
436}
437
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700438uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
439 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700440 return 0;
441 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800442
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700443 for (const std::string& extension : options_.extensions_to_not_compress) {
444 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700445 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800446 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700447 }
448 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800449}
450
Adam Lesinskibb94f322017-07-12 07:41:55 -0700451static bool IsTransitionElement(const std::string& name) {
452 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
453 name == "changeImageTransform" || name == "changeTransform" ||
454 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
455 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
456 name == "transitionManager";
457}
458
459static bool IsVectorElement(const std::string& name) {
460 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000461 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700462}
463
Adam Lesinskic744ae82017-05-17 19:28:38 -0700464template <typename T>
465std::vector<T> make_singleton_vec(T&& val) {
466 std::vector<T> vec;
467 vec.emplace_back(std::forward<T>(val));
468 return vec;
469}
470
471std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
472 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700473 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700474 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700475
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700476 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700477 context_->GetDiagnostics()->Note(DiagMessage()
478 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700479 }
480
Adam Lesinski00451162017-10-03 07:44:08 -0700481 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
482 // that existing projects have out-of-date references which pass compilation.
483 xml::StripAndroidStudioAttributes(doc->root.get());
484
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700485 XmlReferenceLinker xml_linker;
486 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700487 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700488 }
489
Adam Koskidc21dea2017-07-21 10:55:27 -0700490 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700491 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492 }
493
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700494 if (options_.no_xml_namespaces) {
495 XmlNamespaceRemover namespace_remover;
496 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700497 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800498 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700499 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800500
Adam Lesinskibb94f322017-07-12 07:41:55 -0700501 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700502 return make_singleton_vec(std::move(file_op->xml_to_flatten));
503 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700504
Adam Lesinskibb94f322017-07-12 07:41:55 -0700505 if (options_.no_version_vectors || options_.no_version_transitions) {
506 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700507 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700508 if (el && el->namespace_uri.empty()) {
509 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
510 (options_.no_version_transitions && IsTransitionElement(el->name))) {
511 return make_singleton_vec(std::move(file_op->xml_to_flatten));
512 }
513 }
514 }
515
Adam Lesinskic744ae82017-05-17 19:28:38 -0700516 const ConfigDescription& config = file_op->config;
517 ResourceEntry* entry = file_op->entry;
518
519 XmlCompatVersioner xml_compat_versioner(&rules_);
520 const util::Range<ApiVersion> api_range{config.sdkVersion,
521 FindNextApiVersionForConfig(entry, config)};
522 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800523}
524
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800525ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
526 switch (format) {
527 case OutputFormat::kApk:
528 return ResourceFile::Type::kBinaryXml;
529 case OutputFormat::kProto:
530 return ResourceFile::Type::kProtoXml;
531 }
532 LOG_ALWAYS_FATAL("unreachable");
533 return ResourceFile::Type::kUnknown;
534}
535
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700536bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700537 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700538 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800539
Adam Koskidc21dea2017-07-21 10:55:27 -0700540 proguard::CollectResourceReferences(context_, table, keep_set_);
541
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700542 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700543 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
544
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700545 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700546 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700547 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700548 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800549
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700550 // Populate the queue with all files in the ResourceTable.
551 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700552 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700553 // WARNING! Do not insert or remove any resources while executing in this scope. It will
554 // corrupt the iteration order.
555
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700556 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700557 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700558 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700560
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700561 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700563 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700564 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700565 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566 }
567
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700568 FileOperation file_op;
569 file_op.entry = entry.get();
570 file_op.dst_path = *file_ref->path;
571 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700572 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700575 (file_ref->type == ResourceFile::Type::kBinaryXml ||
576 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700577 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700578 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700579 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700580 << "failed to open file");
581 return false;
582 }
583
Adam Lesinski00451162017-10-03 07:44:08 -0700584 if (file_ref->type == ResourceFile::Type::kProtoXml) {
585 pb::XmlNode pb_xml_node;
586 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
587 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700588 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700589 return false;
590 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591
Adam Lesinski00451162017-10-03 07:44:08 -0700592 std::string error;
593 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
594 if (file_op.xml_to_flatten == nullptr) {
595 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700596 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700597 return false;
598 }
599 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700600 std::string error_str;
601 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700602 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700603 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
604 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700605 return false;
606 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700607 }
608
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800609 // Update the type that this file will be written as.
610 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
611
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700612 file_op.xml_to_flatten->file.config = config_value->config;
613 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700614 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700615 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700616
617 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
618 // else we end up copying the string in the std::make_pair() method,
619 // then creating a StringPiece from the copy, which would cause us
620 // to end up referencing garbage in the map.
621 const StringPiece entry_name(entry->name);
622 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
623 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700624 }
625 }
626
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700627 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700628 for (auto& map_entry : config_sorted_files) {
629 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700630 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700631
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700632 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700633 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
634 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700635 if (versioned_docs.empty()) {
636 error = true;
637 continue;
638 }
639
Adam Lesinskic744ae82017-05-17 19:28:38 -0700640 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
641 std::string dst_path = file_op.dst_path;
642 if (doc->file.config != file_op.config) {
643 // Only add the new versioned configurations.
644 if (context_->IsVerbose()) {
645 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
646 << "auto-versioning resource from config '"
647 << config << "' -> '" << doc->file.config << "'");
648 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800650 const ResourceFile& file = doc->file;
651 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
652
653 std::unique_ptr<FileReference> file_ref =
654 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
655 file_ref->SetSource(doc->file.source);
656 // Update the output format of this XML file.
657 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
658 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
659 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700660 return false;
661 }
662 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700663
664 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
665 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700666 }
667 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700668 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
669 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700670 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700671 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700672 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673 }
674 return !error;
675}
676
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700677static bool WriteStableIdMapToPath(IDiagnostics* diag,
678 const std::unordered_map<ResourceName, ResourceId>& id_map,
679 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800680 io::FileOutputStream fout(id_map_path);
681 if (fout.HadError()) {
682 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683 return false;
684 }
685
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800686 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700687 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700688 const ResourceName& name = entry.first;
689 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800690 printer.Print(name.to_string());
691 printer.Print(" = ");
692 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800694 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700695
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800696 if (fout.HadError()) {
697 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 return false;
699 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 return true;
701}
702
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700703static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
704 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700706 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700707 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708 return false;
709 }
710
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700711 out_id_map->clear();
712 size_t line_no = 0;
713 for (StringPiece line : util::Tokenize(content, '\n')) {
714 line_no++;
715 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 if (line.empty()) {
717 continue;
718 }
719
720 auto iter = std::find(line.begin(), line.end(), '=');
721 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700722 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700723 return false;
724 }
725
726 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700727 StringPiece res_name_str =
728 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
729 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700730 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
731 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700732 return false;
733 }
734
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700735 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
736 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700737 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700738
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
740 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700741 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
742 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743 return false;
744 }
745
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700746 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700747 }
748 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700749}
750
Adam Lesinskic6284372017-12-04 13:46:23 -0800751static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
752 using namespace android;
753
754 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
755 // we're looking for the first attribute resource in the system package.
756 const ResTable& table = assets.getResources(true);
757 Res_value val;
758 ssize_t idx = table.getResource(0x01010000, &val, true);
759 if (idx != NO_ERROR) {
760 // Try as a bag.
761 const ResTable::bag_entry* entry;
762 ssize_t cnt = table.lockBag(0x01010000, &entry);
763 if (cnt >= 0) {
764 idx = entry->stringBlock;
765 }
766 table.unlockBag(entry);
767 }
768
769 if (idx < 0) {
770 return 0;
771 }
772 return table.getTableCookie(idx);
773}
774
Adam Lesinskifb48d292015-11-07 15:52:13 -0800775class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700776 public:
777 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700778 : options_(options),
779 context_(context),
780 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700781 file_collection_(util::make_unique<io::FileCollection>()) {
782 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700783
Adam Lesinskic6284372017-12-04 13:46:23 -0800784 void ExtractCompileSdkVersions(android::AssetManager* assets) {
785 using namespace android;
786
787 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
788 if (cookie == 0) {
789 // No Framework assets loaded. Not a failure.
790 return;
791 }
792
793 std::unique_ptr<Asset> manifest(
794 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
795 if (manifest == nullptr) {
796 // No errors.
797 return;
798 }
799
800 std::string error;
801 std::unique_ptr<xml::XmlResource> manifest_xml =
802 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
803 if (manifest_xml == nullptr) {
804 // No errors.
805 return;
806 }
807
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700808 if (!options_.manifest_fixer_options.compile_sdk_version) {
809 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
810 if (attr != nullptr) {
811 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
812 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
813 switch (prim->value.dataType) {
814 case Res_value::TYPE_INT_DEC:
815 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
816 break;
817 case Res_value::TYPE_INT_HEX:
818 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
819 break;
820 default:
821 break;
822 }
823 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
824 compile_sdk_version = *str->value;
825 } else {
826 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800827 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800828 }
829 }
830
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700831 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
832 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
833 if (attr != nullptr) {
834 Maybe<std::string>& compile_sdk_version_codename =
835 options_.manifest_fixer_options.compile_sdk_version_codename;
836 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
837 compile_sdk_version_codename = *str->value;
838 } else {
839 compile_sdk_version_codename = attr->value;
840 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800841 }
842 }
843 }
844
Adam Lesinski8780eb62017-10-31 17:44:39 -0700845 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800846 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700847 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700848 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700849 for (const std::string& path : options_.include_paths) {
850 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700851 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700852 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700853
Adam Lesinski8780eb62017-10-31 17:44:39 -0700854 std::string error;
855 auto zip_collection = io::ZipFileCollection::Create(path, &error);
856 if (zip_collection == nullptr) {
857 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
858 return false;
859 }
860
861 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
862 // Load this as a static library include.
863 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
864 Source(path), std::move(zip_collection), context_->GetDiagnostics());
865 if (static_apk == nullptr) {
866 return false;
867 }
868
Adam Lesinskib522f042017-04-21 16:57:59 -0700869 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800870 // Can't include static libraries when not building a static library (they have no IDs
871 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700872 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800873 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700874 return false;
875 }
876
Adam Lesinski8780eb62017-10-31 17:44:39 -0700877 ResourceTable* table = static_apk->GetResourceTable();
878
879 // If we are using --no-static-lib-packages, we need to rename the package of this table to
880 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700881 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800882 // Since package names can differ, and multiple packages can exist in a ResourceTable,
883 // we place the requirement that all static libraries are built with the package
884 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700885 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700886 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800887 } else {
888 context_->GetDiagnostics()->Error(DiagMessage(path)
889 << "no package with ID 0x7f found in static library");
890 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700891 }
892 }
893
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700894 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700895 util::make_unique<ResourceTableSymbolSource>(table));
896 static_library_includes_.push_back(std::move(static_apk));
897 } else {
898 if (!asset_source->AddAssetPath(path)) {
899 context_->GetDiagnostics()->Error(DiagMessage()
900 << "failed to load include path " << path);
901 return false;
902 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700903 }
904 }
905
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800906 // Capture the shared libraries so that the final resource table can be properly flattened
907 // with support for shared libraries.
908 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700909 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800910 // Capture the included base feature package.
911 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800912 } else if (entry.first == kFrameworkPackageId) {
913 // Try to embed which version of the framework we're compiling against.
914 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
915 // when linking our synthesized 'android:compileSdkVersion' attribute.
916 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
917 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
918 if (symbol != nullptr && symbol->is_public) {
919 // The symbol is present and public, extract the android:versionName and
920 // android:versionCode from the framework AndroidManifest.xml.
921 ExtractCompileSdkVersions(asset_source->GetAssetManager());
922 }
Todd Kennedy32512992018-04-25 16:45:59 -0700923 } else if (asset_source->IsPackageDynamic(entry.first)) {
924 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800925 }
926 }
927
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700928 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700929 return true;
930 }
931
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800932 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700933 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800934 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
935 if (manifest_el == nullptr) {
936 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700937 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800938
939 AppInfo app_info;
940
941 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
942 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
943 return {};
944 }
945
946 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
947 if (!package_attr) {
948 diag->Error(DiagMessage(xml_res->file.source)
949 << "<manifest> must have a 'package' attribute");
950 return {};
951 }
952 app_info.package = package_attr->value;
953
954 if (xml::Attribute* version_code_attr =
955 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
956 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
957 if (!maybe_code) {
958 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
959 << "invalid android:versionCode '" << version_code_attr->value << "'");
960 return {};
961 }
962 app_info.version_code = maybe_code.value();
963 }
964
965 if (xml::Attribute* revision_code_attr =
966 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
967 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
968 if (!maybe_code) {
969 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
970 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
971 return {};
972 }
973 app_info.revision_code = maybe_code.value();
974 }
975
976 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
977 if (!split_name_attr->value.empty()) {
978 app_info.split_name = split_name_attr->value;
979 }
980 }
981
982 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
983 if (xml::Attribute* min_sdk =
984 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700985 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800986 }
987 }
988 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700989 }
990
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700991 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
992 // Postcondition: ResourceTable has only one package left. All others are
993 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700994 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700995 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700996 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
997 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700998 };
999
1000 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001001 for (const auto& package : final_table_.packages) {
1002 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001003 // We have a package that is not related to the one we're building!
1004 for (const auto& type : package->types) {
1005 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001006 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001007
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001008 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001009 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001010 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001011 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1012 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1013 << "generated id '" << res_name
1014 << "' for external package '" << package->name
1015 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001017 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1018 << "defined resource '" << res_name
1019 << "' for external package '" << package->name
1020 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001021 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001023 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001024 }
1025 }
1026 }
1027 }
1028
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001029 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1030 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001031 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001032 return !error;
1033 }
1034
1035 /**
1036 * Returns true if no IDs have been set, false otherwise.
1037 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001038 bool VerifyNoIdsSet() {
1039 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001040 for (const auto& type : package->types) {
1041 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001042 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1043 << StringPrintf("%02x", type->id.value())
1044 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001045 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001046 }
1047
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001048 for (const auto& entry : type->entries) {
1049 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001050 ResourceNameRef res_name(package->name, type->type, entry->name);
1051 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001052 DiagMessage() << "entry " << res_name << " has ID "
1053 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001054 return false;
1055 }
1056 }
1057 }
1058 }
1059 return true;
1060 }
1061
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001062 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1063 if (options_.output_to_directory) {
1064 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001065 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001066 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001067 }
1068 }
1069
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001070 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1071 switch (format) {
1072 case OutputFormat::kApk: {
1073 BigBuffer buffer(1024);
1074 TableFlattener flattener(options_.table_flattener_options, &buffer);
1075 if (!flattener.Consume(context_, table)) {
1076 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1077 return false;
1078 }
1079
1080 io::BigBufferInputStream input_stream(&buffer);
1081 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1082 ArchiveEntry::kAlign, writer);
1083 } break;
1084
1085 case OutputFormat::kProto: {
1086 pb::ResourceTable pb_table;
Ryan Mitchell70414f22018-03-26 11:05:31 -07001087 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001088 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1089 ArchiveEntry::kCompress, writer);
1090 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001091 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001092 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093 }
1094
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001095 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001096 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001097 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001098 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001099 return true;
1100 }
1101
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001102 std::string out_path;
1103 std::unique_ptr<io::FileOutputStream> fout;
1104 if (options_.generate_java_class_path) {
1105 out_path = options_.generate_java_class_path.value();
1106 file::AppendPath(&out_path, file::PackageToPath(out_package));
1107 if (!file::mkdirs(out_path)) {
1108 context_->GetDiagnostics()->Error(DiagMessage()
1109 << "failed to create directory '" << out_path << "'");
1110 return false;
1111 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001113 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001114
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001115 fout = util::make_unique<io::FileOutputStream>(out_path);
1116 if (fout->HadError()) {
1117 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1118 << "': " << fout->GetError());
1119 return false;
1120 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001121 }
1122
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001123 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001124 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001125 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1126 if (fout_text->HadError()) {
1127 context_->GetDiagnostics()->Error(DiagMessage()
1128 << "failed writing to '" << out_text_symbols_path.value()
1129 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001130 return false;
1131 }
1132 }
1133
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001134 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001135 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001136 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001137 return false;
1138 }
1139
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 return true;
1141 }
1142
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001143 bool GenerateJavaClasses() {
1144 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1145 std::vector<std::string> packages_to_callback;
1146
1147 JavaClassGeneratorOptions template_options;
1148 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1149 template_options.javadoc_annotations = options_.javadoc_annotations;
1150
1151 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1152 template_options.use_final = false;
1153 }
1154
1155 if (context_->GetPackageType() == PackageType::kSharedLib) {
1156 template_options.use_final = false;
1157 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1158 }
1159
1160 const StringPiece actual_package = context_->GetCompilationPackage();
1161 StringPiece output_package = context_->GetCompilationPackage();
1162 if (options_.custom_java_package) {
1163 // Override the output java package to the custom one.
1164 output_package = options_.custom_java_package.value();
1165 }
1166
1167 // Generate the private symbols if required.
1168 if (options_.private_symbols) {
1169 packages_to_callback.push_back(options_.private_symbols.value());
1170
1171 // If we defined a private symbols package, we only emit Public symbols
1172 // to the original package, and private and public symbols to the private package.
1173 JavaClassGeneratorOptions options = template_options;
1174 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1175 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1176 options)) {
1177 return false;
1178 }
1179 }
1180
1181 // Generate copies of the original package R class but with different package names.
1182 // This is to support non-namespaced builds.
1183 for (const std::string& extra_package : options_.extra_java_packages) {
1184 packages_to_callback.push_back(extra_package);
1185
1186 JavaClassGeneratorOptions options = template_options;
1187 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1188 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1189 return false;
1190 }
1191 }
1192
1193 // Generate R classes for each package that was merged (static library).
1194 // Use the actual package's resources only.
1195 for (const std::string& package : table_merger_->merged_packages()) {
1196 packages_to_callback.push_back(package);
1197
1198 JavaClassGeneratorOptions options = template_options;
1199 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1200 if (!WriteJavaFile(&final_table_, package, package, options)) {
1201 return false;
1202 }
1203 }
1204
1205 // Generate the main public R class.
1206 JavaClassGeneratorOptions options = template_options;
1207
1208 // Only generate public symbols if we have a private package.
1209 if (options_.private_symbols) {
1210 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1211 }
1212
1213 if (options.rewrite_callback_options) {
1214 options.rewrite_callback_options.value().packages_to_callback =
1215 std::move(packages_to_callback);
1216 }
1217
1218 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1219 options_.generate_text_symbols_path)) {
1220 return false;
1221 }
1222
1223 return true;
1224 }
1225
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001226 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1227 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 return true;
1229 }
1230
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001231 std::unique_ptr<ClassDefinition> manifest_class =
1232 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001234 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235 // Something bad happened, but we already logged it, so exit.
1236 return false;
1237 }
1238
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001239 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001240 // Empty Manifest class, no need to generate it.
1241 return true;
1242 }
1243
1244 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001245 for (const std::string& annotation : options_.javadoc_annotations) {
1246 std::string proper_annotation = "@";
1247 proper_annotation += annotation;
1248 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001249 }
1250
Adam Lesinski0d81f702017-06-27 15:51:09 -07001251 const std::string package_utf8 =
1252 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001254 std::string out_path = options_.generate_java_class_path.value();
1255 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001256
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001257 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001258 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1259 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001260 return false;
1261 }
1262
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001263 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001264
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001265 io::FileOutputStream fout(out_path);
1266 if (fout.HadError()) {
1267 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1268 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001269 return false;
1270 }
1271
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001272 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1273 fout.Flush();
1274
1275 if (fout.HadError()) {
1276 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1277 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001278 return false;
1279 }
1280 return true;
1281 }
1282
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001283 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001284 if (!out) {
1285 return true;
1286 }
1287
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001288 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001289 io::FileOutputStream fout(out_path);
1290 if (fout.HadError()) {
1291 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1292 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001293 return false;
1294 }
1295
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001296 proguard::WriteKeepSet(keep_set, &fout);
1297 fout.Flush();
1298
1299 if (fout.HadError()) {
1300 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1301 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001302 return false;
1303 }
1304 return true;
1305 }
1306
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001307 bool MergeStaticLibrary(const std::string& input, bool override) {
1308 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001309 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001310 }
1311
Adam Lesinski8780eb62017-10-31 17:44:39 -07001312 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1313 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001314 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001315 return false;
1316 }
1317
Adam Lesinski8780eb62017-10-31 17:44:39 -07001318 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001319 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001320 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001321 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001322 return false;
1323 }
1324
1325 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001326 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001327 // Merge all resources as if they were in the compilation package. This is the old behavior
1328 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001329
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001330 // Add the package to the set of --extra-packages so we emit an R.java for each library
1331 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001332 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001333 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001334 }
1335
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001336 // Clear the package name, so as to make the resources look like they are coming from the
1337 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001338 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001339 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340
1341 } else {
1342 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001343 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001344 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001345 }
1346
1347 if (!result) {
1348 return false;
1349 }
1350
1351 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001352 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001353 return true;
1354 }
1355
Adam Lesinski2427dce2017-11-30 15:10:28 -08001356 bool MergeExportedSymbols(const Source& source,
1357 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001358 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001359 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001360 ResourceName res_name = exported_symbol.name;
1361 if (res_name.package.empty()) {
1362 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001363 }
1364
Adam Lesinski00451162017-10-03 07:44:08 -07001365 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001366 if (mangled_name) {
1367 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001368 }
1369
1370 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001371 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001372 bool result =
1373 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1374 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375 if (!result) {
1376 return false;
1377 }
1378 }
1379 return true;
1380 }
1381
Adam Lesinski2427dce2017-11-30 15:10:28 -08001382 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1383 if (context_->IsVerbose()) {
1384 context_->GetDiagnostics()->Note(DiagMessage()
1385 << "merging '" << compiled_file.name
1386 << "' from compiled file " << compiled_file.source);
1387 }
1388
1389 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1390 return false;
1391 }
1392 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1393 }
1394
Adam Lesinski00451162017-10-03 07:44:08 -07001395 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1396 // If override is true, conflicting resources are allowed to override each other, in order of last
1397 // seen.
1398 // An io::IFileCollection is created from the ZIP file and added to the set of
1399 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001400 bool MergeArchive(const std::string& input, bool override) {
1401 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001402 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403 }
1404
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001405 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001406 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001407 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001408 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001409 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 return false;
1411 }
1412
1413 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001414 for (auto iter = collection->Iterator(); iter->HasNext();) {
1415 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001416 error = true;
1417 }
1418 }
1419
1420 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001421 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001422 return !error;
1423 }
1424
Adam Lesinski00451162017-10-03 07:44:08 -07001425 // Takes a path to load and merge into the master ResourceTable. If override is true,
1426 // conflicting resources are allowed to override each other, in order of last seen.
1427 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1428 // as ZIP archive and the files within are merged individually.
1429 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001430 bool MergePath(const std::string& path, bool override) {
1431 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1432 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1433 return MergeArchive(path, override);
1434 } else if (util::EndsWith(path, ".apk")) {
1435 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001436 }
1437
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001438 io::IFile* file = file_collection_->InsertFile(path);
1439 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001440 }
1441
Adam Lesinski00451162017-10-03 07:44:08 -07001442 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1443 // If override is true, conflicting resources are allowed to override each other, in order of last
1444 // seen.
1445 // All other file types are ignored. This is because these files could be coming from a zip,
1446 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001447 bool MergeFile(io::IFile* file, bool override) {
1448 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001449
Adam Lesinski00451162017-10-03 07:44:08 -07001450 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001451 // Since AAPT compiles these file types and appends .flat to them, seeing
1452 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001453 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1454 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1455 << " file passed as argument. Must be "
1456 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001457 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001458 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1459 if (context_->IsVerbose()) {
1460 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1461 return true;
1462 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001463 }
1464
Adam Lesinski00451162017-10-03 07:44:08 -07001465 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1466 if (input_stream == nullptr) {
1467 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1468 return false;
1469 }
1470
1471 if (input_stream->HadError()) {
1472 context_->GetDiagnostics()->Error(DiagMessage(src)
1473 << "failed to open file: " << input_stream->GetError());
1474 return false;
1475 }
1476
1477 ContainerReaderEntry* entry;
1478 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001479
1480 if (reader.HadError()) {
1481 context_->GetDiagnostics()->Error(DiagMessage(src)
1482 << "failed to read file: " << reader.GetError());
1483 return false;
1484 }
1485
Adam Lesinski00451162017-10-03 07:44:08 -07001486 while ((entry = reader.Next()) != nullptr) {
1487 if (entry->Type() == ContainerEntryType::kResTable) {
1488 pb::ResourceTable pb_table;
1489 if (!entry->GetResTable(&pb_table)) {
1490 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1491 << entry->GetError());
1492 return false;
1493 }
1494
1495 ResourceTable table;
1496 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001497 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001498 context_->GetDiagnostics()->Error(DiagMessage(src)
1499 << "failed to deserialize resource table: " << error);
1500 return false;
1501 }
1502
1503 if (!table_merger_->Merge(src, &table, override)) {
1504 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1505 return false;
1506 }
1507 } else if (entry->Type() == ContainerEntryType::kResFile) {
1508 pb::internal::CompiledFile pb_compiled_file;
1509 off64_t offset;
1510 size_t len;
1511 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1512 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1513 << entry->GetError());
1514 return false;
1515 }
1516
1517 ResourceFile resource_file;
1518 std::string error;
1519 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1520 context_->GetDiagnostics()->Error(DiagMessage(src)
1521 << "failed to read compiled header: " << error);
1522 return false;
1523 }
1524
1525 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1526 return false;
1527 }
1528 }
1529 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001530 return true;
1531 }
1532
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001533 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1534 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1535 for (const std::string& assets_dir : options_.assets_dirs) {
1536 Maybe<std::vector<std::string>> files =
1537 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1538 if (!files) {
1539 return false;
1540 }
1541
1542 for (const std::string& file : files.value()) {
1543 std::string full_key = "assets/" + file;
1544 std::string full_path = assets_dir;
1545 file::AppendPath(&full_path, file);
1546
1547 auto iter = merged_assets.find(full_key);
1548 if (iter == merged_assets.end()) {
1549 merged_assets.emplace(std::move(full_key),
1550 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1551 } else if (context_->IsVerbose()) {
1552 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1553 << "asset file overrides '" << full_path << "'");
1554 }
1555 }
1556 }
1557
1558 for (auto& entry : merged_assets) {
1559 uint32_t compression_flags = ArchiveEntry::kCompress;
1560 std::string extension = file::GetExtension(entry.first).to_string();
1561 if (options_.extensions_to_not_compress.count(extension) > 0) {
1562 compression_flags = 0u;
1563 }
1564
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001565 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1566 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001567 return false;
1568 }
1569 }
1570 return true;
1571 }
1572
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001573 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1574 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001575 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1576 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001577 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001578 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1579 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001580 if (!result) {
1581 return false;
1582 }
1583
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001584 ResourceFileFlattenerOptions file_flattener_options;
1585 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001586 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1587 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001588 file_flattener_options.no_auto_version = options_.no_auto_version;
1589 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001590 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001591 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1592 file_flattener_options.update_proguard_spec =
1593 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001594 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001596 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001597
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001598 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001599 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001600 return false;
1601 }
1602
Adam Lesinski490595a2017-11-07 17:08:07 -08001603 // Hack to fix b/68820737.
1604 // We need to modify the ResourceTable's package name, but that should NOT affect
1605 // anything else being generated, which includes the Java classes.
1606 // If required, the package name is modifed before flattening, and then modified back
1607 // to its original name.
1608 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001609 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1610 // or higher] as invalid. In order to work around this limitation, we allow the use
1611 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1612 // definition of what a valid "split" package ID is to account for this.
1613 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1614 context_->GetPackageId() != kAppPackageId &&
1615 context_->GetPackageId() != kFrameworkPackageId)
1616 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1617 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001618 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1619 // The base APK is included, and this is a feature split. If the base package is
1620 // the same as this package, then we are building an old style Android Instant Apps feature
1621 // split and must apply this workaround to avoid requiring namespaces support.
1622 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1623 if (package_to_rewrite != nullptr) {
1624 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1625
1626 std::string new_package_name =
1627 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1628 app_info_.split_name.value_or_default("feature").c_str());
1629
1630 if (context_->IsVerbose()) {
1631 context_->GetDiagnostics()->Note(
1632 DiagMessage() << "rewriting resource package name for feature split to '"
1633 << new_package_name << "'");
1634 }
1635 package_to_rewrite->name = new_package_name;
1636 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001637 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001638
1639 bool success = FlattenTable(table, options_.output_format, writer);
1640
1641 if (package_to_rewrite != nullptr) {
1642 // Change the name back.
1643 package_to_rewrite->name = context_->GetCompilationPackage();
1644 if (package_to_rewrite->id) {
1645 table->included_packages_.erase(package_to_rewrite->id.value());
1646 }
1647 }
1648
1649 if (!success) {
1650 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1651 }
1652 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001653 }
1654
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001655 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001656 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001657 std::unique_ptr<xml::XmlResource> manifest_xml =
1658 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1659 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001660 return 1;
1661 }
1662
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001663 // First extract the Package name without modifying it (via --rename-manifest-package).
1664 if (Maybe<AppInfo> maybe_app_info =
1665 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001666 const AppInfo& app_info = maybe_app_info.value();
1667 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001668 }
1669
Adam Lesinskic6284372017-12-04 13:46:23 -08001670 // Now that the compilation package is set, load the dependencies. This will also extract
1671 // the Android framework's versionCode and versionName, if they exist.
1672 if (!LoadSymbolsFromIncludePaths()) {
1673 return 1;
1674 }
1675
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001676 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1677 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001678 return 1;
1679 }
1680
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001681 Maybe<AppInfo> maybe_app_info =
1682 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001683 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001684 return 1;
1685 }
1686
Adam Lesinski490595a2017-11-07 17:08:07 -08001687 app_info_ = maybe_app_info.value();
1688 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001689
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001690 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001691
1692 // Override the package ID when it is "android".
1693 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001694 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001695
1696 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001697 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001698 context_->GetDiagnostics()->Error(
1699 DiagMessage() << "package 'android' can only be built as a regular app");
1700 return 1;
1701 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001702 }
1703
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001704 TableMergerOptions table_merger_options;
1705 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001706 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001707
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001708 if (context_->IsVerbose()) {
1709 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001710 << StringPrintf("linking package '%s' using package ID %02x",
1711 context_->GetCompilationPackage().data(),
1712 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001713 }
1714
Adam Lesinski2427dce2017-11-30 15:10:28 -08001715 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1716 // in res/**/*.
1717 {
1718 XmlIdCollector collector;
1719 if (!collector.Consume(context_, manifest_xml.get())) {
1720 return false;
1721 }
1722
1723 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1724 return false;
1725 }
1726 }
1727
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001728 for (const std::string& input : input_files) {
1729 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001730 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001731 return 1;
1732 }
1733 }
1734
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001735 for (const std::string& input : options_.overlay_files) {
1736 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001737 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001738 return 1;
1739 }
1740 }
1741
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743 return 1;
1744 }
1745
Adam Lesinskib522f042017-04-21 16:57:59 -07001746 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001747 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001749 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001750 return 1;
1751 }
1752
1753 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001754 IdAssigner id_assigner(&options_.stable_id_map);
1755 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001756 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 return 1;
1758 }
1759
1760 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001761 if (options_.resource_id_map_path) {
1762 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001763 for (auto& type : package->types) {
1764 for (auto& entry : type->entries) {
1765 ResourceName name(package->name, type->type, entry->name);
1766 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001767 options_.stable_id_map[std::move(name)] =
1768 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001769 }
1770 }
1771 }
1772
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001773 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001774 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001775 return 1;
1776 }
1777 }
1778 } else {
1779 // Static libs are merged with other apps, and ID collisions are bad, so
1780 // verify that
1781 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001782 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001783 return 1;
1784 }
1785 }
1786
1787 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001788 context_->SetNameManglerPolicy(
1789 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001790
1791 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001792 context_->GetExternalSymbols()->PrependSource(
1793 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001794
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001795 // Workaround for pre-O runtime that would treat negative resource IDs
1796 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1797 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1798 // are just identifiers.
1799 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1800 if (context_->IsVerbose()) {
1801 context_->GetDiagnostics()->Note(DiagMessage()
1802 << "enabling pre-O feature split ID rewriting");
1803 }
1804 context_->GetExternalSymbols()->SetDelegate(
1805 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1806 }
1807
Adam Lesinski34a16872018-02-23 16:18:10 -08001808 // Before we process anything, remove the resources whose default values don't exist.
1809 // We want to force any references to these to fail the build.
1810 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1811 context_->GetDiagnostics()->Error(DiagMessage()
1812 << "failed removing resources with no defaults");
1813 return 1;
1814 }
1815
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001816 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001817 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001818 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001819 return 1;
1820 }
1821
Adam Lesinskib522f042017-04-21 16:57:59 -07001822 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001823 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001824 context_->GetDiagnostics()->Warn(DiagMessage()
1825 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 }
1827 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001828 ProductFilter product_filter(options_.products);
1829 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001830 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001831 return 1;
1832 }
1833 }
1834
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001835 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001836 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001837 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001838 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001839 return 1;
1840 }
1841 }
1842
Adam Lesinskib522f042017-04-21 16:57:59 -07001843 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001844 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001845 context_->GetDiagnostics()->Note(DiagMessage()
1846 << "collapsing resource versions for minimum SDK "
1847 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848 }
1849
1850 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001851 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852 return 1;
1853 }
1854 }
1855
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001856 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001857 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001858 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001859 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001860 return 1;
1861 }
1862 }
1863
Adam Koskidc21dea2017-07-21 10:55:27 -07001864 proguard::KeepSet proguard_keep_set =
1865 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001866 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867
Adam Lesinskib522f042017-04-21 16:57:59 -07001868 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001870 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001871 context_->GetDiagnostics()->Warn(DiagMessage()
1872 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001873 }
1874 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001875 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1876 // equal to the minSdk.
1877 options_.split_constraints =
1878 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001879
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001880 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001881 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001882 return 1;
1883 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001885
1886 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001887 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001888 auto split_constraints_iter = options_.split_constraints.begin();
1889 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001890 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001891 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1892 << "generating split with configurations '"
1893 << util::Joiner(split_constraints_iter->configs, ", ")
1894 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001895 }
1896
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001897 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001899 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001900 return 1;
1901 }
1902
1903 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001905 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001906
1907 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001908 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001909 context_->GetDiagnostics()->Error(DiagMessage()
1910 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001911 return 1;
1912 }
1913
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001914 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1915 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001916 return 1;
1917 }
1918
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001919 ++path_iter;
1920 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001921 }
1922 }
1923
1924 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001925 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001926 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001927 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001928 return 1;
1929 }
1930
1931 bool error = false;
1932 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001933 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001934 // (aka, which package the AndroidManifest.xml is coming from).
1935 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001936 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001937
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001938 XmlReferenceLinker manifest_linker;
1939 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1940 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001941 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001942 error = true;
1943 }
1944
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001945 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001946 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001947 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001948 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001949 }
1950
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 if (options_.generate_java_class_path) {
1952 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001953 error = true;
1954 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001955 }
1956
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001957 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001958 // PackageParser will fail if URIs are removed from
1959 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001960 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1961 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001962 error = true;
1963 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001964 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001965 } else {
1966 error = true;
1967 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001968 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001969
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001970 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001971 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001972 return 1;
1973 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001974
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001975 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1976 return 1;
1977 }
1978
1979 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001980 return 1;
1981 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001982
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001983 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001984 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001985 return 1;
1986 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001987 }
1988
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001989 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001990 return 1;
1991 }
1992
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001993 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1994 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001995 return 1;
1996 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001997 return 0;
1998 }
1999
2000 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002001 LinkOptions options_;
2002 LinkContext* context_;
2003 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002004
Adam Lesinski490595a2017-11-07 17:08:07 -08002005 AppInfo app_info_;
2006
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002007 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002008
2009 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002010 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011
Adam Lesinski8780eb62017-10-31 17:44:39 -07002012 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002013 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002014 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002015
Adam Lesinski8780eb62017-10-31 17:44:39 -07002016 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2017 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2018
2019 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2020 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002021
2022 // The set of shared libraries being used, mapping their assigned package ID to package name.
2023 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002024
2025 // The package name of the base application, if it is included.
2026 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002027};
2028
Chris Warrington820d72a2017-04-27 15:27:01 +01002029int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2030 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002031 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002032 std::vector<std::string> overlay_arg_list;
2033 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002034 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002035 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002036 Maybe<std::string> preferred_density;
2037 Maybe<std::string> product_list;
2038 bool legacy_x_flag = false;
2039 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002040 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002041 bool shared_lib = false;
2042 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002043 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002044 Maybe<std::string> stable_id_file_path;
2045 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002046 Flags flags =
2047 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002048 .RequiredFlag("-o", "Output path.", &options.output_path)
2049 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002050 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002051 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002052 .OptionalFlagList("-A",
2053 "An assets directory to include in the APK. These are unprocessed.",
2054 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002055 .OptionalFlagList("-R",
2056 "Compilation unit to link, using `overlay` semantics.\n"
2057 "The last conflicting resource given takes precedence.",
2058 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002059 .OptionalFlag("--package-id",
2060 "Specify the package ID to use for this app. Must be greater or equal to\n"
2061 "0x7f and can't be used with --static-lib or --shared-lib.",
2062 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002063 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002064 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002065 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002066 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002067 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002068 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002069 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002070 .OptionalSwitch("--proguard-conditional-keep-rules",
2071 "Generate conditional Proguard keep rules.",
2072 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002073 .OptionalSwitch("--no-auto-version",
2074 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002075 &options.no_auto_version)
2076 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002077 "Disables automatic versioning of vector drawables. Use this only\n"
2078 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002079 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002080 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002081 "Disables automatic versioning of transition resources. Use this only\n"
2082 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002083 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002084 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002085 "Disables automatic deduping of resources with\n"
2086 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002087 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002088 .OptionalSwitch("--enable-sparse-encoding",
2089 "Enables encoding sparse entries using a binary search tree.\n"
2090 "This decreases APK size at the cost of resource retrieval performance.",
2091 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002092 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002093 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002094 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002095 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002096 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002097 "Comma separated list of configurations to include. The default\n"
2098 "is all configurations.",
2099 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002100 .OptionalFlag("--preferred-density",
2101 "Selects the closest matching density and strips out all others.",
2102 &preferred_density)
2103 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002104 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002105 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002106 &options.output_to_directory)
2107 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002108 "Removes XML namespace prefix and URI information from\n"
2109 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002110 &options.no_xml_namespaces)
2111 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002112 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002113 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002114 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002115 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002116 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002117 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002118 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2119 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 &options.manifest_fixer_options.version_code_default)
2121 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002122 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002123 &options.manifest_fixer_options.version_name_default)
Colin Crossda02fea2018-05-25 22:46:35 -07002124 .OptionalSwitch("--replace-version",
2125 "If --version-code and/or --version-name are specified, these\n"
2126 "values will replace any value already in the manifest. By\n"
2127 "default, nothing is changed if the manifest already defines\n"
2128 "these attributes.",
2129 &options.manifest_fixer_options.replace_version)
Todd Kennedy9f6dec12018-04-20 12:29:29 -07002130 .OptionalFlag("--compile-sdk-version-code",
2131 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2132 "present.",
2133 &options.manifest_fixer_options.compile_sdk_version)
2134 .OptionalFlag("--compile-sdk-version-name",
2135 "Version name to inject into the AndroidManifest.xml if none is present.",
2136 &options.manifest_fixer_options.compile_sdk_version_codename)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002137 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2138 &shared_lib)
2139 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002140 .OptionalSwitch("--proto-format",
2141 "Generates compiled resources in Protobuf format.\n"
2142 "Suitable as input to the bundle tool for generating an App Bundle.",
2143 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002144 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002145 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002146 &options.no_static_lib_packages)
2147 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002148 "Generates R.java without the final modifier. This is implied when\n"
2149 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002150 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002151 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002152 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002153 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002154 "Emit a file at the given path with a list of name to ID mappings,\n"
2155 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002156 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002157 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002158 "Package name to use when generating R.java for private symbols.\n"
2159 "If not specified, public and private symbols will use the application's\n"
2160 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002161 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002162 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002163 &options.custom_java_package)
2164 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002165 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002166 &extra_java_packages)
2167 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002168 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002169 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002170 .OptionalFlag("--output-text-symbols",
2171 "Generates a text file containing the resource symbols of the R class in\n"
2172 "the specified folder.",
2173 &options.generate_text_symbols_path)
Todd Kennedy32512992018-04-25 16:45:59 -07002174 .OptionalSwitch("--allow-reserved-package-id",
2175 "Allows the use of a reserved package ID. This should on be used for\n"
2176 "packages with a pre-O min-sdk\n",
2177 &options.allow_reserved_package_id)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002178 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002179 "Allows the addition of new resources in overlays without\n"
2180 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002181 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002182 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002183 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002184 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002185 "Changes the name of the target package for instrumentation. Most useful\n"
2186 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002187 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002188 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002189 &options.extensions_to_not_compress)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002190 .OptionalSwitch("--warn-manifest-validation",
2191 "Treat manifest validation errors as warnings.",
2192 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002193 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002194 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002195 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2196 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002197 &split_args)
Ryan Mitchelle5b38a62018-03-23 13:35:00 -07002198 .OptionalSwitch("-v", "Enables verbose logging.", &verbose)
2199 .OptionalSwitch("--debug-mode",
2200 "Inserts android:debuggable=\"true\" in to the application node of the\n"
2201 "manifest, making the application debuggable even on production devices.",
2202 &options.manifest_fixer_options.debug_mode);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002203
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002204 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002205 return 1;
2206 }
2207
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002208 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002209 std::vector<std::string> arg_list;
2210 for (const std::string& arg : flags.GetArgs()) {
2211 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002212 const std::string path = arg.substr(1, arg.size() - 1);
2213 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002214 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2215 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002216 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002217 }
2218 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002219 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002220 }
2221 }
2222
2223 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002224 for (const std::string& arg : overlay_arg_list) {
2225 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002226 const std::string path = arg.substr(1, arg.size() - 1);
2227 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002228 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2229 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002230 return 1;
2231 }
2232 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002233 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002234 }
2235 }
2236
2237 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002238 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002239 }
2240
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002241 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2242 context.GetDiagnostics()->Error(
2243 DiagMessage()
2244 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002245 return 1;
2246 }
2247
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002248 // The default build type.
2249 context.SetPackageType(PackageType::kApp);
2250 context.SetPackageId(kAppPackageId);
2251
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002252 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002253 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002254 context.SetPackageId(0x00);
2255 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002256 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002257 options.output_format = OutputFormat::kProto;
2258 } else if (proto_format) {
2259 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002260 }
2261
2262 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002263 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002264 context.GetDiagnostics()->Error(
2265 DiagMessage() << "can't specify --package-id when not building a regular app");
2266 return 1;
2267 }
2268
2269 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2270 if (!maybe_package_id_int) {
2271 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2272 << "' is not a valid integer");
2273 return 1;
2274 }
2275
2276 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002277 if (package_id_int > std::numeric_limits<uint8_t>::max()
2278 || package_id_int == kFrameworkPackageId
2279 || (!options.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002280 context.GetDiagnostics()->Error(
2281 DiagMessage() << StringPrintf(
2282 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2283 return 1;
2284 }
2285 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2286 }
2287
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002288 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002289 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002290 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002291 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002292 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002293 }
2294 }
2295
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002296 if (product_list) {
2297 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002298 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002299 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002300 }
2301 }
2302 }
2303
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002304 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002305 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002306 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2307 if (filter == nullptr) {
2308 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002309 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002310 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002311 }
2312
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002313 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002314 Maybe<uint16_t> density =
2315 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2316 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002317 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002318 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002319 options.table_splitter_options.preferred_densities.push_back(density.value());
2320 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002321
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002322 // Parse the split parameters.
2323 for (const std::string& split_arg : split_args) {
2324 options.split_paths.push_back({});
2325 options.split_constraints.push_back({});
2326 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2327 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002328 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002329 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002330 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002331
Adam Lesinskib522f042017-04-21 16:57:59 -07002332 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002333 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2334 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002335 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002336 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002337 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002338
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002339 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002340 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002341 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2342 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2343 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2344 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2345
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002346 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002347 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002348 options.no_auto_version = true;
2349 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002350 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002351 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002352
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002353 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002354 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002355}
2356
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002357} // namespace aapt