blob: 12ab88345411120c462dd17c336012aa102e956f [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Adam Lesinskice5e56e2016-10-21 17:56:45 -070017#include <sys/stat.h>
Adam Lesinskic6284372017-12-04 13:46:23 -080018#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019
Adam Lesinskice5e56e2016-10-21 17:56:45 -070020#include <queue>
21#include <unordered_map>
22#include <vector>
23
24#include "android-base/errors.h"
25#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080026#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080027#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070028
Adam Lesinski1ab598f2015-08-14 14:26:04 -070029#include "AppInfo.h"
30#include "Debug.h"
31#include "Flags.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070032#include "LoadedApk.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080033#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070034#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080035#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070036#include "ResourceValues.h"
37#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070038#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080040#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080041#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070042#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070043#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/binary/TableFlattener.h"
45#include "format/binary/XmlFlattener.h"
46#include "format/proto/ProtoDeserialize.h"
47#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070048#include "io/BigBufferStream.h"
49#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080050#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070051#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070053#include "java/JavaClassGenerator.h"
54#include "java/ManifestClassGenerator.h"
55#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070056#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070057#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080058#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070060#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080061#include "optimize/ResourceDeduper.h"
62#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070063#include "process/IResourceTableConsumer.h"
64#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080065#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080067#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070069using ::aapt::io::FileInputStream;
70using ::android::StringPiece;
71using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070072
Adam Lesinski1ab598f2015-08-14 14:26:04 -070073namespace aapt {
74
Adam Lesinskie59f0d82017-10-13 09:36:53 -070075enum class OutputFormat {
76 kApk,
77 kProto,
78};
79
Adam Lesinski1ab598f2015-08-14 14:26:04 -070080struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070081 std::string output_path;
82 std::string manifest_path;
83 std::vector<std::string> include_paths;
84 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070085 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070086 bool output_to_directory = false;
87 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070088 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070089
Adam Lesinskicacb28f2016-10-19 12:18:14 -070090 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070091 Maybe<std::string> generate_java_class_path;
92 Maybe<std::string> custom_java_package;
93 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070094 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070095 Maybe<std::string> generate_proguard_rules_path;
96 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070097 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070098 bool generate_non_final_ids = false;
99 std::vector<std::string> javadoc_annotations;
100 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700101
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700102 // Optimizations/features.
103 bool no_auto_version = false;
104 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900105 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700106 bool no_resource_deduping = false;
107 bool no_xml_namespaces = false;
108 bool do_not_compress_anything = false;
109 std::unordered_set<std::string> extensions_to_not_compress;
110
111 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700112 bool no_static_lib_packages = false;
113
114 // AndroidManifest.xml massaging options.
115 ManifestFixerOptions manifest_fixer_options;
116
117 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700118 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700119
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800120 // Flattening options.
121 TableFlattenerOptions table_flattener_options;
122
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700124 TableSplitterOptions table_splitter_options;
125 std::vector<SplitConstraints> split_constraints;
126 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700127
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700128 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700129 std::unordered_map<ResourceName, ResourceId> stable_id_map;
130 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700131};
132
Adam Lesinski64587af2016-02-18 18:33:06 -0800133class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700134 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100135 LinkContext(IDiagnostics* diagnostics)
136 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700138
Adam Lesinskib522f042017-04-21 16:57:59 -0700139 PackageType GetPackageType() override {
140 return package_type_;
141 }
142
143 void SetPackageType(PackageType type) {
144 package_type_ = type;
145 }
146
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700147 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100148 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700150
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700151 NameMangler* GetNameMangler() override {
152 return &name_mangler_;
153 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700154
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700155 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
156 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700157 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800158
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700159 const std::string& GetCompilationPackage() override {
160 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700161 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700162
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700163 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800164 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700165 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800166
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700167 uint8_t GetPackageId() override {
168 return package_id_;
169 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700170
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700171 void SetPackageId(uint8_t id) {
172 package_id_ = id;
173 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800174
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700175 SymbolTable* GetExternalSymbols() override {
176 return &symbols_;
177 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800178
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700179 bool IsVerbose() override {
180 return verbose_;
181 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800182
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700183 void SetVerbose(bool val) {
184 verbose_ = val;
185 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800186
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700187 int GetMinSdkVersion() override {
188 return min_sdk_version_;
189 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700190
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700191 void SetMinSdkVersion(int minSdk) {
192 min_sdk_version_ = minSdk;
193 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700194
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700195 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700196 DISALLOW_COPY_AND_ASSIGN(LinkContext);
197
Adam Lesinskib522f042017-04-21 16:57:59 -0700198 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100199 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700200 NameMangler name_mangler_;
201 std::string compilation_package_;
202 uint8_t package_id_ = 0x0;
203 SymbolTable symbols_;
204 bool verbose_ = false;
205 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700206};
207
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700208// A custom delegate that generates compatible pre-O IDs for use with feature splits.
209// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
210// is interpreted as a negative number. Some verification was wrongly assuming negative values
211// were invalid.
212//
213// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
214// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
215// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800216//
217// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700218class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
219 public:
220 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
221 }
222
223 virtual ~FeatureSplitSymbolTableDelegate() = default;
224
225 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
226 const ResourceName& name,
227 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
228 std::unique_ptr<SymbolTable::Symbol> symbol =
229 DefaultSymbolTableDelegate::FindByName(name, sources);
230 if (symbol == nullptr) {
231 return {};
232 }
233
234 // Check to see if this is an 'id' with the target package.
235 if (name.type == ResourceType::kId && symbol->id) {
236 ResourceId* id = &symbol->id.value();
237 if (id->package_id() > kAppPackageId) {
238 // Rewrite the resource ID to be compatible pre-O.
239 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
240
241 // Check that this doesn't overlap another resource.
242 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
243 // The ID overlaps, so log a message (since this is a weird failure) and fail.
244 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
245 << " for pre-O feature split support");
246 return {};
247 }
248
249 if (context_->IsVerbose()) {
250 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
251 << ") -> (" << rewritten_id << ")");
252 }
253
254 *id = rewritten_id;
255 }
256 }
257 return symbol;
258 }
259
260 private:
261 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
262
263 IAaptContext* context_;
264};
265
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700266static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
267 const StringPiece& path, bool keep_raw_values, bool utf16,
268 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700269 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700270 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
271 << (keep_raw_values ? "true" : "false")
272 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700273 }
274
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700275 switch (format) {
276 case OutputFormat::kApk: {
277 BigBuffer buffer(1024);
278 XmlFlattenerOptions options = {};
279 options.keep_raw_values = keep_raw_values;
280 options.use_utf16 = utf16;
281 XmlFlattener flattener(&buffer, options);
282 if (!flattener.Consume(context, &xml_res)) {
283 return false;
284 }
285
286 io::BigBufferInputStream input_stream(&buffer);
287 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
288 ArchiveEntry::kCompress, writer);
289 } break;
290
291 case OutputFormat::kProto: {
292 pb::XmlNode pb_node;
293 SerializeXmlResourceToPb(xml_res, &pb_node);
294 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
295 writer);
296 } break;
297 }
298 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800299}
300
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700301// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700302static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700303 FileInputStream fin(path);
304 if (fin.HadError()) {
305 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700306 return {};
307 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700308 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800309}
310
Adam Lesinski355f2852016-02-13 20:26:45 -0800311struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700312 bool no_auto_version = false;
313 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900314 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700315 bool no_xml_namespaces = false;
316 bool keep_raw_values = false;
317 bool do_not_compress_anything = false;
318 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700319 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700320 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800321};
322
Adam Lesinskic744ae82017-05-17 19:28:38 -0700323// A sampling of public framework resource IDs.
324struct R {
325 struct attr {
326 enum : uint32_t {
327 paddingLeft = 0x010100d6u,
328 paddingRight = 0x010100d8u,
329 paddingHorizontal = 0x0101053du,
330
331 paddingTop = 0x010100d7u,
332 paddingBottom = 0x010100d9u,
333 paddingVertical = 0x0101053eu,
334
335 layout_marginLeft = 0x010100f7u,
336 layout_marginRight = 0x010100f9u,
337 layout_marginHorizontal = 0x0101053bu,
338
339 layout_marginTop = 0x010100f8u,
340 layout_marginBottom = 0x010100fau,
341 layout_marginVertical = 0x0101053cu,
342 };
343 };
344};
345
Adam Lesinski355f2852016-02-13 20:26:45 -0800346class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700347 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700348 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700349 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800350
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700351 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800352
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700353 private:
354 struct FileOperation {
355 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700356
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700357 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700358 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700359
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700360 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700361 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700362
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700363 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700364 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700365
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700366 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700367 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700368 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800369
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700370 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800371
Adam Lesinskic744ae82017-05-17 19:28:38 -0700372 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
373 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800374
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700375 ResourceFileFlattenerOptions options_;
376 IAaptContext* context_;
377 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700378 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800379};
380
Adam Lesinskic744ae82017-05-17 19:28:38 -0700381ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
382 IAaptContext* context, proguard::KeepSet* keep_set)
383 : options_(options), context_(context), keep_set_(keep_set) {
384 SymbolTable* symm = context_->GetExternalSymbols();
385
386 // Build up the rules for degrading newer attributes to older ones.
387 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
388 // generated from the attribute definitions themselves (b/62028956).
389 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
390 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800391 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
392 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700393 };
394 rules_[R::attr::paddingHorizontal] =
395 util::make_unique<DegradeToManyRule>(std::move(replacements));
396 }
397
398 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
399 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800400 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
401 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700402 };
403 rules_[R::attr::paddingVertical] =
404 util::make_unique<DegradeToManyRule>(std::move(replacements));
405 }
406
407 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
408 std::vector<ReplacementAttr> replacements{
409 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800410 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700411 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800412 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700413 };
414 rules_[R::attr::layout_marginHorizontal] =
415 util::make_unique<DegradeToManyRule>(std::move(replacements));
416 }
417
418 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
419 std::vector<ReplacementAttr> replacements{
420 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800421 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700422 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800423 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700424 };
425 rules_[R::attr::layout_marginVertical] =
426 util::make_unique<DegradeToManyRule>(std::move(replacements));
427 }
428}
429
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700430uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
431 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700432 return 0;
433 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800434
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700435 for (const std::string& extension : options_.extensions_to_not_compress) {
436 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700437 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800438 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700439 }
440 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800441}
442
Adam Lesinskibb94f322017-07-12 07:41:55 -0700443static bool IsTransitionElement(const std::string& name) {
444 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
445 name == "changeImageTransform" || name == "changeTransform" ||
446 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
447 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
448 name == "transitionManager";
449}
450
451static bool IsVectorElement(const std::string& name) {
452 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000453 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700454}
455
Adam Lesinskic744ae82017-05-17 19:28:38 -0700456template <typename T>
457std::vector<T> make_singleton_vec(T&& val) {
458 std::vector<T> vec;
459 vec.emplace_back(std::forward<T>(val));
460 return vec;
461}
462
463std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
464 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700465 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700466 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700467
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700468 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700469 context_->GetDiagnostics()->Note(DiagMessage()
470 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700471 }
472
Adam Lesinski00451162017-10-03 07:44:08 -0700473 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
474 // that existing projects have out-of-date references which pass compilation.
475 xml::StripAndroidStudioAttributes(doc->root.get());
476
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700477 XmlReferenceLinker xml_linker;
478 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700479 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700480 }
481
Adam Koskidc21dea2017-07-21 10:55:27 -0700482 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700483 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700484 }
485
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700486 if (options_.no_xml_namespaces) {
487 XmlNamespaceRemover namespace_remover;
488 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700489 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800490 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700491 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800492
Adam Lesinskibb94f322017-07-12 07:41:55 -0700493 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700494 return make_singleton_vec(std::move(file_op->xml_to_flatten));
495 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700496
Adam Lesinskibb94f322017-07-12 07:41:55 -0700497 if (options_.no_version_vectors || options_.no_version_transitions) {
498 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700499 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700500 if (el && el->namespace_uri.empty()) {
501 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
502 (options_.no_version_transitions && IsTransitionElement(el->name))) {
503 return make_singleton_vec(std::move(file_op->xml_to_flatten));
504 }
505 }
506 }
507
Adam Lesinskic744ae82017-05-17 19:28:38 -0700508 const ConfigDescription& config = file_op->config;
509 ResourceEntry* entry = file_op->entry;
510
511 XmlCompatVersioner xml_compat_versioner(&rules_);
512 const util::Range<ApiVersion> api_range{config.sdkVersion,
513 FindNextApiVersionForConfig(entry, config)};
514 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800515}
516
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800517ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
518 switch (format) {
519 case OutputFormat::kApk:
520 return ResourceFile::Type::kBinaryXml;
521 case OutputFormat::kProto:
522 return ResourceFile::Type::kProtoXml;
523 }
524 LOG_ALWAYS_FATAL("unreachable");
525 return ResourceFile::Type::kUnknown;
526}
527
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700528bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700530 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800531
Adam Koskidc21dea2017-07-21 10:55:27 -0700532 proguard::CollectResourceReferences(context_, table, keep_set_);
533
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700534 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700535 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
536
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700537 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700538 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700539 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700540 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800541
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700542 // Populate the queue with all files in the ResourceTable.
543 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700544 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700545 // WARNING! Do not insert or remove any resources while executing in this scope. It will
546 // corrupt the iteration order.
547
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700548 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700549 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700550 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700552
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700553 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700554 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700555 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700556 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700557 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558 }
559
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700560 FileOperation file_op;
561 file_op.entry = entry.get();
562 file_op.dst_path = *file_ref->path;
563 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700564 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700567 (file_ref->type == ResourceFile::Type::kBinaryXml ||
568 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700569 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700570 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700571 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572 << "failed to open file");
573 return false;
574 }
575
Adam Lesinski00451162017-10-03 07:44:08 -0700576 if (file_ref->type == ResourceFile::Type::kProtoXml) {
577 pb::XmlNode pb_xml_node;
578 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
579 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700580 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700581 return false;
582 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700583
Adam Lesinski00451162017-10-03 07:44:08 -0700584 std::string error;
585 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
586 if (file_op.xml_to_flatten == nullptr) {
587 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700588 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700589 return false;
590 }
591 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700592 std::string error_str;
593 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700594 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700595 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
596 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700597 return false;
598 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700599 }
600
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800601 // Update the type that this file will be written as.
602 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
603
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700604 file_op.xml_to_flatten->file.config = config_value->config;
605 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700606 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700607 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700608
609 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
610 // else we end up copying the string in the std::make_pair() method,
611 // then creating a StringPiece from the copy, which would cause us
612 // to end up referencing garbage in the map.
613 const StringPiece entry_name(entry->name);
614 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
615 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616 }
617 }
618
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700620 for (auto& map_entry : config_sorted_files) {
621 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700622 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700624 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700625 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
626 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700627 if (versioned_docs.empty()) {
628 error = true;
629 continue;
630 }
631
Adam Lesinskic744ae82017-05-17 19:28:38 -0700632 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
633 std::string dst_path = file_op.dst_path;
634 if (doc->file.config != file_op.config) {
635 // Only add the new versioned configurations.
636 if (context_->IsVerbose()) {
637 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
638 << "auto-versioning resource from config '"
639 << config << "' -> '" << doc->file.config << "'");
640 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700641
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800642 const ResourceFile& file = doc->file;
643 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
644
645 std::unique_ptr<FileReference> file_ref =
646 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
647 file_ref->SetSource(doc->file.source);
648 // Update the output format of this XML file.
649 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
650 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
651 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700652 return false;
653 }
654 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700655
656 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
657 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700658 }
659 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700660 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
661 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700662 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700663 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700664 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700665 }
666 return !error;
667}
668
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700669static bool WriteStableIdMapToPath(IDiagnostics* diag,
670 const std::unordered_map<ResourceName, ResourceId>& id_map,
671 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800672 io::FileOutputStream fout(id_map_path);
673 if (fout.HadError()) {
674 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675 return false;
676 }
677
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800678 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700679 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 const ResourceName& name = entry.first;
681 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800682 printer.Print(name.to_string());
683 printer.Print(" = ");
684 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700685 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800686 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700687
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800688 if (fout.HadError()) {
689 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700690 return false;
691 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700692 return true;
693}
694
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700695static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
696 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700697 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700698 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 return false;
701 }
702
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700703 out_id_map->clear();
704 size_t line_no = 0;
705 for (StringPiece line : util::Tokenize(content, '\n')) {
706 line_no++;
707 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708 if (line.empty()) {
709 continue;
710 }
711
712 auto iter = std::find(line.begin(), line.end(), '=');
713 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700714 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715 return false;
716 }
717
718 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700719 StringPiece res_name_str =
720 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
721 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700722 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
723 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700724 return false;
725 }
726
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700727 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
728 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700729 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700730
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700731 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
732 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700733 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
734 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700735 return false;
736 }
737
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700738 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700739 }
740 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700741}
742
Adam Lesinskic6284372017-12-04 13:46:23 -0800743static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
744 using namespace android;
745
746 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
747 // we're looking for the first attribute resource in the system package.
748 const ResTable& table = assets.getResources(true);
749 Res_value val;
750 ssize_t idx = table.getResource(0x01010000, &val, true);
751 if (idx != NO_ERROR) {
752 // Try as a bag.
753 const ResTable::bag_entry* entry;
754 ssize_t cnt = table.lockBag(0x01010000, &entry);
755 if (cnt >= 0) {
756 idx = entry->stringBlock;
757 }
758 table.unlockBag(entry);
759 }
760
761 if (idx < 0) {
762 return 0;
763 }
764 return table.getTableCookie(idx);
765}
766
Adam Lesinskifb48d292015-11-07 15:52:13 -0800767class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700768 public:
769 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700770 : options_(options),
771 context_(context),
772 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700773 file_collection_(util::make_unique<io::FileCollection>()) {
774 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700775
Adam Lesinskic6284372017-12-04 13:46:23 -0800776 void ExtractCompileSdkVersions(android::AssetManager* assets) {
777 using namespace android;
778
779 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
780 if (cookie == 0) {
781 // No Framework assets loaded. Not a failure.
782 return;
783 }
784
785 std::unique_ptr<Asset> manifest(
786 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
787 if (manifest == nullptr) {
788 // No errors.
789 return;
790 }
791
792 std::string error;
793 std::unique_ptr<xml::XmlResource> manifest_xml =
794 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
795 if (manifest_xml == nullptr) {
796 // No errors.
797 return;
798 }
799
800 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
801 if (attr != nullptr) {
802 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
803 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
804 switch (prim->value.dataType) {
805 case Res_value::TYPE_INT_DEC:
806 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
807 break;
808 case Res_value::TYPE_INT_HEX:
809 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
810 break;
811 default:
812 break;
813 }
814 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
815 compile_sdk_version = *str->value;
816 } else {
817 compile_sdk_version = attr->value;
818 }
819 }
820
821 attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
822 if (attr != nullptr) {
823 Maybe<std::string>& compile_sdk_version_codename =
824 options_.manifest_fixer_options.compile_sdk_version_codename;
825 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
826 compile_sdk_version_codename = *str->value;
827 } else {
828 compile_sdk_version_codename = attr->value;
829 }
830 }
831 }
832
Adam Lesinski8780eb62017-10-31 17:44:39 -0700833 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800834 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700835 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700836 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700837 for (const std::string& path : options_.include_paths) {
838 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700839 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700840 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700841
Adam Lesinski8780eb62017-10-31 17:44:39 -0700842 std::string error;
843 auto zip_collection = io::ZipFileCollection::Create(path, &error);
844 if (zip_collection == nullptr) {
845 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
846 return false;
847 }
848
849 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
850 // Load this as a static library include.
851 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
852 Source(path), std::move(zip_collection), context_->GetDiagnostics());
853 if (static_apk == nullptr) {
854 return false;
855 }
856
Adam Lesinskib522f042017-04-21 16:57:59 -0700857 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800858 // Can't include static libraries when not building a static library (they have no IDs
859 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700860 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800861 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700862 return false;
863 }
864
Adam Lesinski8780eb62017-10-31 17:44:39 -0700865 ResourceTable* table = static_apk->GetResourceTable();
866
867 // If we are using --no-static-lib-packages, we need to rename the package of this table to
868 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700869 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800870 // Since package names can differ, and multiple packages can exist in a ResourceTable,
871 // we place the requirement that all static libraries are built with the package
872 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700873 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700874 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800875 } else {
876 context_->GetDiagnostics()->Error(DiagMessage(path)
877 << "no package with ID 0x7f found in static library");
878 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700879 }
880 }
881
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700882 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700883 util::make_unique<ResourceTableSymbolSource>(table));
884 static_library_includes_.push_back(std::move(static_apk));
885 } else {
886 if (!asset_source->AddAssetPath(path)) {
887 context_->GetDiagnostics()->Error(DiagMessage()
888 << "failed to load include path " << path);
889 return false;
890 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700891 }
892 }
893
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800894 // Capture the shared libraries so that the final resource table can be properly flattened
895 // with support for shared libraries.
896 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800897 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800898 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinski490595a2017-11-07 17:08:07 -0800899 } else if (entry.first == kAppPackageId) {
900 // Capture the included base feature package.
901 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800902 } else if (entry.first == kFrameworkPackageId) {
903 // Try to embed which version of the framework we're compiling against.
904 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
905 // when linking our synthesized 'android:compileSdkVersion' attribute.
906 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
907 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
908 if (symbol != nullptr && symbol->is_public) {
909 // The symbol is present and public, extract the android:versionName and
910 // android:versionCode from the framework AndroidManifest.xml.
911 ExtractCompileSdkVersions(asset_source->GetAssetManager());
912 }
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800913 }
914 }
915
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700916 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700917 return true;
918 }
919
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800920 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700921 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800922 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
923 if (manifest_el == nullptr) {
924 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700925 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800926
927 AppInfo app_info;
928
929 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
930 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
931 return {};
932 }
933
934 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
935 if (!package_attr) {
936 diag->Error(DiagMessage(xml_res->file.source)
937 << "<manifest> must have a 'package' attribute");
938 return {};
939 }
940 app_info.package = package_attr->value;
941
942 if (xml::Attribute* version_code_attr =
943 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
944 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
945 if (!maybe_code) {
946 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
947 << "invalid android:versionCode '" << version_code_attr->value << "'");
948 return {};
949 }
950 app_info.version_code = maybe_code.value();
951 }
952
953 if (xml::Attribute* revision_code_attr =
954 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
955 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
956 if (!maybe_code) {
957 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
958 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
959 return {};
960 }
961 app_info.revision_code = maybe_code.value();
962 }
963
964 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
965 if (!split_name_attr->value.empty()) {
966 app_info.split_name = split_name_attr->value;
967 }
968 }
969
970 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
971 if (xml::Attribute* min_sdk =
972 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700973 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800974 }
975 }
976 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700977 }
978
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700979 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
980 // Postcondition: ResourceTable has only one package left. All others are
981 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700982 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700983 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700984 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
985 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700986 };
987
988 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700989 for (const auto& package : final_table_.packages) {
990 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700991 // We have a package that is not related to the one we're building!
992 for (const auto& type : package->types) {
993 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700994 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700995
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700996 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700997 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700998 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700999 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1000 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1001 << "generated id '" << res_name
1002 << "' for external package '" << package->name
1003 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001005 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1006 << "defined resource '" << res_name
1007 << "' for external package '" << package->name
1008 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001009 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001010 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001011 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001012 }
1013 }
1014 }
1015 }
1016
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001017 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1018 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001019 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001020 return !error;
1021 }
1022
1023 /**
1024 * Returns true if no IDs have been set, false otherwise.
1025 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001026 bool VerifyNoIdsSet() {
1027 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001028 for (const auto& type : package->types) {
1029 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001030 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1031 << StringPrintf("%02x", type->id.value())
1032 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001033 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001034 }
1035
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001036 for (const auto& entry : type->entries) {
1037 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001038 ResourceNameRef res_name(package->name, type->type, entry->name);
1039 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001040 DiagMessage() << "entry " << res_name << " has ID "
1041 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001042 return false;
1043 }
1044 }
1045 }
1046 }
1047 return true;
1048 }
1049
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001050 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1051 if (options_.output_to_directory) {
1052 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001053 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001054 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001055 }
1056 }
1057
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001058 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1059 switch (format) {
1060 case OutputFormat::kApk: {
1061 BigBuffer buffer(1024);
1062 TableFlattener flattener(options_.table_flattener_options, &buffer);
1063 if (!flattener.Consume(context_, table)) {
1064 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1065 return false;
1066 }
1067
1068 io::BigBufferInputStream input_stream(&buffer);
1069 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1070 ArchiveEntry::kAlign, writer);
1071 } break;
1072
1073 case OutputFormat::kProto: {
1074 pb::ResourceTable pb_table;
1075 SerializeTableToPb(*table, &pb_table);
1076 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1077 ArchiveEntry::kCompress, writer);
1078 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001079 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001080 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001081 }
1082
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001083 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001084 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001085 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001086 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001087 return true;
1088 }
1089
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001090 std::string out_path;
1091 std::unique_ptr<io::FileOutputStream> fout;
1092 if (options_.generate_java_class_path) {
1093 out_path = options_.generate_java_class_path.value();
1094 file::AppendPath(&out_path, file::PackageToPath(out_package));
1095 if (!file::mkdirs(out_path)) {
1096 context_->GetDiagnostics()->Error(DiagMessage()
1097 << "failed to create directory '" << out_path << "'");
1098 return false;
1099 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001100
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001101 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001102
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001103 fout = util::make_unique<io::FileOutputStream>(out_path);
1104 if (fout->HadError()) {
1105 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1106 << "': " << fout->GetError());
1107 return false;
1108 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001109 }
1110
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001111 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001112 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001113 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1114 if (fout_text->HadError()) {
1115 context_->GetDiagnostics()->Error(DiagMessage()
1116 << "failed writing to '" << out_text_symbols_path.value()
1117 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001118 return false;
1119 }
1120 }
1121
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001122 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001123 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001124 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001125 return false;
1126 }
1127
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001128 return true;
1129 }
1130
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001131 bool GenerateJavaClasses() {
1132 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1133 std::vector<std::string> packages_to_callback;
1134
1135 JavaClassGeneratorOptions template_options;
1136 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1137 template_options.javadoc_annotations = options_.javadoc_annotations;
1138
1139 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1140 template_options.use_final = false;
1141 }
1142
1143 if (context_->GetPackageType() == PackageType::kSharedLib) {
1144 template_options.use_final = false;
1145 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1146 }
1147
1148 const StringPiece actual_package = context_->GetCompilationPackage();
1149 StringPiece output_package = context_->GetCompilationPackage();
1150 if (options_.custom_java_package) {
1151 // Override the output java package to the custom one.
1152 output_package = options_.custom_java_package.value();
1153 }
1154
1155 // Generate the private symbols if required.
1156 if (options_.private_symbols) {
1157 packages_to_callback.push_back(options_.private_symbols.value());
1158
1159 // If we defined a private symbols package, we only emit Public symbols
1160 // to the original package, and private and public symbols to the private package.
1161 JavaClassGeneratorOptions options = template_options;
1162 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1163 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1164 options)) {
1165 return false;
1166 }
1167 }
1168
1169 // Generate copies of the original package R class but with different package names.
1170 // This is to support non-namespaced builds.
1171 for (const std::string& extra_package : options_.extra_java_packages) {
1172 packages_to_callback.push_back(extra_package);
1173
1174 JavaClassGeneratorOptions options = template_options;
1175 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1176 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1177 return false;
1178 }
1179 }
1180
1181 // Generate R classes for each package that was merged (static library).
1182 // Use the actual package's resources only.
1183 for (const std::string& package : table_merger_->merged_packages()) {
1184 packages_to_callback.push_back(package);
1185
1186 JavaClassGeneratorOptions options = template_options;
1187 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1188 if (!WriteJavaFile(&final_table_, package, package, options)) {
1189 return false;
1190 }
1191 }
1192
1193 // Generate the main public R class.
1194 JavaClassGeneratorOptions options = template_options;
1195
1196 // Only generate public symbols if we have a private package.
1197 if (options_.private_symbols) {
1198 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1199 }
1200
1201 if (options.rewrite_callback_options) {
1202 options.rewrite_callback_options.value().packages_to_callback =
1203 std::move(packages_to_callback);
1204 }
1205
1206 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1207 options_.generate_text_symbols_path)) {
1208 return false;
1209 }
1210
1211 return true;
1212 }
1213
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001214 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1215 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001216 return true;
1217 }
1218
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001219 std::unique_ptr<ClassDefinition> manifest_class =
1220 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001222 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001223 // Something bad happened, but we already logged it, so exit.
1224 return false;
1225 }
1226
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 // Empty Manifest class, no need to generate it.
1229 return true;
1230 }
1231
1232 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001233 for (const std::string& annotation : options_.javadoc_annotations) {
1234 std::string proper_annotation = "@";
1235 proper_annotation += annotation;
1236 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237 }
1238
Adam Lesinski0d81f702017-06-27 15:51:09 -07001239 const std::string package_utf8 =
1240 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001241
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001242 std::string out_path = options_.generate_java_class_path.value();
1243 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001244
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001245 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001246 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1247 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001248 return false;
1249 }
1250
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001251 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001252
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001253 io::FileOutputStream fout(out_path);
1254 if (fout.HadError()) {
1255 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1256 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257 return false;
1258 }
1259
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001260 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1261 fout.Flush();
1262
1263 if (fout.HadError()) {
1264 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1265 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001266 return false;
1267 }
1268 return true;
1269 }
1270
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001271 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001272 if (!out) {
1273 return true;
1274 }
1275
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001276 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001277 io::FileOutputStream fout(out_path);
1278 if (fout.HadError()) {
1279 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1280 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 return false;
1282 }
1283
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001284 proguard::WriteKeepSet(keep_set, &fout);
1285 fout.Flush();
1286
1287 if (fout.HadError()) {
1288 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1289 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001290 return false;
1291 }
1292 return true;
1293 }
1294
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001295 bool MergeStaticLibrary(const std::string& input, bool override) {
1296 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001297 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001298 }
1299
Adam Lesinski8780eb62017-10-31 17:44:39 -07001300 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1301 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001302 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001303 return false;
1304 }
1305
Adam Lesinski8780eb62017-10-31 17:44:39 -07001306 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001307 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001309 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001310 return false;
1311 }
1312
1313 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001314 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001315 // Merge all resources as if they were in the compilation package. This is the old behavior
1316 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001318 // Add the package to the set of --extra-packages so we emit an R.java for each library
1319 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001320 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001321 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001322 }
1323
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001324 // Clear the package name, so as to make the resources look like they are coming from the
1325 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001326 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001327 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001328
1329 } else {
1330 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001331 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001332 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001333 }
1334
1335 if (!result) {
1336 return false;
1337 }
1338
1339 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001340 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001341 return true;
1342 }
1343
Adam Lesinski2427dce2017-11-30 15:10:28 -08001344 bool MergeExportedSymbols(const Source& source,
1345 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001346 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001347 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001348 ResourceName res_name = exported_symbol.name;
1349 if (res_name.package.empty()) {
1350 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001351 }
1352
Adam Lesinski00451162017-10-03 07:44:08 -07001353 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001354 if (mangled_name) {
1355 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001356 }
1357
1358 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001359 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001360 bool result =
1361 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1362 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001363 if (!result) {
1364 return false;
1365 }
1366 }
1367 return true;
1368 }
1369
Adam Lesinski2427dce2017-11-30 15:10:28 -08001370 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1371 if (context_->IsVerbose()) {
1372 context_->GetDiagnostics()->Note(DiagMessage()
1373 << "merging '" << compiled_file.name
1374 << "' from compiled file " << compiled_file.source);
1375 }
1376
1377 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1378 return false;
1379 }
1380 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1381 }
1382
Adam Lesinski00451162017-10-03 07:44:08 -07001383 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1384 // If override is true, conflicting resources are allowed to override each other, in order of last
1385 // seen.
1386 // An io::IFileCollection is created from the ZIP file and added to the set of
1387 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001388 bool MergeArchive(const std::string& input, bool override) {
1389 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001390 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001391 }
1392
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001393 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001394 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001395 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001396 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001397 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398 return false;
1399 }
1400
1401 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001402 for (auto iter = collection->Iterator(); iter->HasNext();) {
1403 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001404 error = true;
1405 }
1406 }
1407
1408 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001409 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 return !error;
1411 }
1412
Adam Lesinski00451162017-10-03 07:44:08 -07001413 // Takes a path to load and merge into the master ResourceTable. If override is true,
1414 // conflicting resources are allowed to override each other, in order of last seen.
1415 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1416 // as ZIP archive and the files within are merged individually.
1417 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001418 bool MergePath(const std::string& path, bool override) {
1419 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1420 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1421 return MergeArchive(path, override);
1422 } else if (util::EndsWith(path, ".apk")) {
1423 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001424 }
1425
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001426 io::IFile* file = file_collection_->InsertFile(path);
1427 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001428 }
1429
Adam Lesinski00451162017-10-03 07:44:08 -07001430 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1431 // If override is true, conflicting resources are allowed to override each other, in order of last
1432 // seen.
1433 // All other file types are ignored. This is because these files could be coming from a zip,
1434 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001435 bool MergeFile(io::IFile* file, bool override) {
1436 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001437
Adam Lesinski00451162017-10-03 07:44:08 -07001438 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001439 // Since AAPT compiles these file types and appends .flat to them, seeing
1440 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001441 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1442 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1443 << " file passed as argument. Must be "
1444 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001445 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001446 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1447 if (context_->IsVerbose()) {
1448 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1449 return true;
1450 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001451 }
1452
Adam Lesinski00451162017-10-03 07:44:08 -07001453 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1454 if (input_stream == nullptr) {
1455 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1456 return false;
1457 }
1458
1459 if (input_stream->HadError()) {
1460 context_->GetDiagnostics()->Error(DiagMessage(src)
1461 << "failed to open file: " << input_stream->GetError());
1462 return false;
1463 }
1464
1465 ContainerReaderEntry* entry;
1466 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001467
1468 if (reader.HadError()) {
1469 context_->GetDiagnostics()->Error(DiagMessage(src)
1470 << "failed to read file: " << reader.GetError());
1471 return false;
1472 }
1473
Adam Lesinski00451162017-10-03 07:44:08 -07001474 while ((entry = reader.Next()) != nullptr) {
1475 if (entry->Type() == ContainerEntryType::kResTable) {
1476 pb::ResourceTable pb_table;
1477 if (!entry->GetResTable(&pb_table)) {
1478 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1479 << entry->GetError());
1480 return false;
1481 }
1482
1483 ResourceTable table;
1484 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001485 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001486 context_->GetDiagnostics()->Error(DiagMessage(src)
1487 << "failed to deserialize resource table: " << error);
1488 return false;
1489 }
1490
1491 if (!table_merger_->Merge(src, &table, override)) {
1492 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1493 return false;
1494 }
1495 } else if (entry->Type() == ContainerEntryType::kResFile) {
1496 pb::internal::CompiledFile pb_compiled_file;
1497 off64_t offset;
1498 size_t len;
1499 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1500 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1501 << entry->GetError());
1502 return false;
1503 }
1504
1505 ResourceFile resource_file;
1506 std::string error;
1507 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1508 context_->GetDiagnostics()->Error(DiagMessage(src)
1509 << "failed to read compiled header: " << error);
1510 return false;
1511 }
1512
1513 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1514 return false;
1515 }
1516 }
1517 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001518 return true;
1519 }
1520
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001521 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1522 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1523 for (const std::string& assets_dir : options_.assets_dirs) {
1524 Maybe<std::vector<std::string>> files =
1525 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1526 if (!files) {
1527 return false;
1528 }
1529
1530 for (const std::string& file : files.value()) {
1531 std::string full_key = "assets/" + file;
1532 std::string full_path = assets_dir;
1533 file::AppendPath(&full_path, file);
1534
1535 auto iter = merged_assets.find(full_key);
1536 if (iter == merged_assets.end()) {
1537 merged_assets.emplace(std::move(full_key),
1538 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1539 } else if (context_->IsVerbose()) {
1540 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1541 << "asset file overrides '" << full_path << "'");
1542 }
1543 }
1544 }
1545
1546 for (auto& entry : merged_assets) {
1547 uint32_t compression_flags = ArchiveEntry::kCompress;
1548 std::string extension = file::GetExtension(entry.first).to_string();
1549 if (options_.extensions_to_not_compress.count(extension) > 0) {
1550 compression_flags = 0u;
1551 }
1552
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001553 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1554 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001555 return false;
1556 }
1557 }
1558 return true;
1559 }
1560
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001561 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1562 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001563 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1564 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001565 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001566 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1567 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001568 if (!result) {
1569 return false;
1570 }
1571
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001572 ResourceFileFlattenerOptions file_flattener_options;
1573 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001574 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1575 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001576 file_flattener_options.no_auto_version = options_.no_auto_version;
1577 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001578 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001579 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1580 file_flattener_options.update_proguard_spec =
1581 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001582 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001583
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001584 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001585
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001586 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001587 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001588 return false;
1589 }
1590
Adam Lesinski490595a2017-11-07 17:08:07 -08001591 // Hack to fix b/68820737.
1592 // We need to modify the ResourceTable's package name, but that should NOT affect
1593 // anything else being generated, which includes the Java classes.
1594 // If required, the package name is modifed before flattening, and then modified back
1595 // to its original name.
1596 ResourceTablePackage* package_to_rewrite = nullptr;
1597 if (context_->GetPackageId() > kAppPackageId &&
1598 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1599 // The base APK is included, and this is a feature split. If the base package is
1600 // the same as this package, then we are building an old style Android Instant Apps feature
1601 // split and must apply this workaround to avoid requiring namespaces support.
1602 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1603 if (package_to_rewrite != nullptr) {
1604 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1605
1606 std::string new_package_name =
1607 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1608 app_info_.split_name.value_or_default("feature").c_str());
1609
1610 if (context_->IsVerbose()) {
1611 context_->GetDiagnostics()->Note(
1612 DiagMessage() << "rewriting resource package name for feature split to '"
1613 << new_package_name << "'");
1614 }
1615 package_to_rewrite->name = new_package_name;
1616 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001617 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001618
1619 bool success = FlattenTable(table, options_.output_format, writer);
1620
1621 if (package_to_rewrite != nullptr) {
1622 // Change the name back.
1623 package_to_rewrite->name = context_->GetCompilationPackage();
1624 if (package_to_rewrite->id) {
1625 table->included_packages_.erase(package_to_rewrite->id.value());
1626 }
1627 }
1628
1629 if (!success) {
1630 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1631 }
1632 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001633 }
1634
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001635 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001636 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001637 std::unique_ptr<xml::XmlResource> manifest_xml =
1638 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1639 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001640 return 1;
1641 }
1642
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001643 // First extract the Package name without modifying it (via --rename-manifest-package).
1644 if (Maybe<AppInfo> maybe_app_info =
1645 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001646 const AppInfo& app_info = maybe_app_info.value();
1647 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001648 }
1649
Adam Lesinskic6284372017-12-04 13:46:23 -08001650 // Now that the compilation package is set, load the dependencies. This will also extract
1651 // the Android framework's versionCode and versionName, if they exist.
1652 if (!LoadSymbolsFromIncludePaths()) {
1653 return 1;
1654 }
1655
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001656 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1657 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001658 return 1;
1659 }
1660
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001661 Maybe<AppInfo> maybe_app_info =
1662 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001663 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001664 return 1;
1665 }
1666
Adam Lesinski490595a2017-11-07 17:08:07 -08001667 app_info_ = maybe_app_info.value();
1668 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001669
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001670 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001671
1672 // Override the package ID when it is "android".
1673 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001674 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001675
1676 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001677 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001678 context_->GetDiagnostics()->Error(
1679 DiagMessage() << "package 'android' can only be built as a regular app");
1680 return 1;
1681 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001682 }
1683
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001684 TableMergerOptions table_merger_options;
1685 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001686 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001687
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001688 if (context_->IsVerbose()) {
1689 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001690 << StringPrintf("linking package '%s' using package ID %02x",
1691 context_->GetCompilationPackage().data(),
1692 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001693 }
1694
Adam Lesinski2427dce2017-11-30 15:10:28 -08001695 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1696 // in res/**/*.
1697 {
1698 XmlIdCollector collector;
1699 if (!collector.Consume(context_, manifest_xml.get())) {
1700 return false;
1701 }
1702
1703 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1704 return false;
1705 }
1706 }
1707
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001708 for (const std::string& input : input_files) {
1709 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001710 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001711 return 1;
1712 }
1713 }
1714
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001715 for (const std::string& input : options_.overlay_files) {
1716 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001717 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001718 return 1;
1719 }
1720 }
1721
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001722 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001723 return 1;
1724 }
1725
Adam Lesinskib522f042017-04-21 16:57:59 -07001726 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001727 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001728 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001729 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001730 return 1;
1731 }
1732
1733 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001734 IdAssigner id_assigner(&options_.stable_id_map);
1735 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001736 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001737 return 1;
1738 }
1739
1740 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001741 if (options_.resource_id_map_path) {
1742 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743 for (auto& type : package->types) {
1744 for (auto& entry : type->entries) {
1745 ResourceName name(package->name, type->type, entry->name);
1746 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001747 options_.stable_id_map[std::move(name)] =
1748 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001749 }
1750 }
1751 }
1752
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001753 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001754 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001755 return 1;
1756 }
1757 }
1758 } else {
1759 // Static libs are merged with other apps, and ID collisions are bad, so
1760 // verify that
1761 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001762 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001763 return 1;
1764 }
1765 }
1766
1767 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001768 context_->SetNameManglerPolicy(
1769 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001770
1771 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001772 context_->GetExternalSymbols()->PrependSource(
1773 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001774
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001775 // Workaround for pre-O runtime that would treat negative resource IDs
1776 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1777 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1778 // are just identifiers.
1779 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1780 if (context_->IsVerbose()) {
1781 context_->GetDiagnostics()->Note(DiagMessage()
1782 << "enabling pre-O feature split ID rewriting");
1783 }
1784 context_->GetExternalSymbols()->SetDelegate(
1785 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1786 }
1787
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001788 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001789 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001790 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001791 return 1;
1792 }
1793
Adam Lesinskib522f042017-04-21 16:57:59 -07001794 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001795 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001796 context_->GetDiagnostics()->Warn(DiagMessage()
1797 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001798 }
1799 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001800 ProductFilter product_filter(options_.products);
1801 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001802 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001803 return 1;
1804 }
1805 }
1806
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001807 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001808 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001809 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001810 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001811 return 1;
1812 }
1813 }
1814
Adam Lesinskib522f042017-04-21 16:57:59 -07001815 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001816 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001817 context_->GetDiagnostics()->Note(DiagMessage()
1818 << "collapsing resource versions for minimum SDK "
1819 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001820 }
1821
1822 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001823 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824 return 1;
1825 }
1826 }
1827
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001828 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001830 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001831 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001832 return 1;
1833 }
1834 }
1835
Adam Koskidc21dea2017-07-21 10:55:27 -07001836 proguard::KeepSet proguard_keep_set =
1837 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001838 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001839
Adam Lesinskib522f042017-04-21 16:57:59 -07001840 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001841 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001842 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001843 context_->GetDiagnostics()->Warn(DiagMessage()
1844 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845 }
1846 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001847 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1848 // equal to the minSdk.
1849 options_.split_constraints =
1850 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001851
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001852 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001853 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001854 return 1;
1855 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001856 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001857
1858 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001859 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001860 auto split_constraints_iter = options_.split_constraints.begin();
1861 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001862 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001863 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1864 << "generating split with configurations '"
1865 << util::Joiner(split_constraints_iter->configs, ", ")
1866 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867 }
1868
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001869 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001870 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001871 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001872 return 1;
1873 }
1874
1875 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001877 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001878
1879 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001880 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001881 context_->GetDiagnostics()->Error(DiagMessage()
1882 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001883 return 1;
1884 }
1885
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001886 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1887 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001888 return 1;
1889 }
1890
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001891 ++path_iter;
1892 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001893 }
1894 }
1895
1896 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001897 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001899 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001900 return 1;
1901 }
1902
1903 bool error = false;
1904 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001905 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001906 // (aka, which package the AndroidManifest.xml is coming from).
1907 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001908 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001909
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001910 XmlReferenceLinker manifest_linker;
1911 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1912 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001913 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001914 error = true;
1915 }
1916
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001917 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001918 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001919 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001920 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001921 }
1922
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001923 if (options_.generate_java_class_path) {
1924 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001925 error = true;
1926 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001927 }
1928
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001930 // PackageParser will fail if URIs are removed from
1931 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001932 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1933 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001934 error = true;
1935 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001936 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001937 } else {
1938 error = true;
1939 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001940 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001941
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001942 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001943 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001944 return 1;
1945 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001946
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001947 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1948 return 1;
1949 }
1950
1951 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001952 return 1;
1953 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001954
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001955 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001956 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001957 return 1;
1958 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001959 }
1960
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001961 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001962 return 1;
1963 }
1964
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001965 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1966 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 return 1;
1968 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001969 return 0;
1970 }
1971
1972 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001973 LinkOptions options_;
1974 LinkContext* context_;
1975 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001976
Adam Lesinski490595a2017-11-07 17:08:07 -08001977 AppInfo app_info_;
1978
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001979 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001980
1981 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001982 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001983
Adam Lesinski8780eb62017-10-31 17:44:39 -07001984 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001985 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001986 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001987
Adam Lesinski8780eb62017-10-31 17:44:39 -07001988 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1989 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1990
1991 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1992 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001993
1994 // The set of shared libraries being used, mapping their assigned package ID to package name.
1995 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08001996
1997 // The package name of the base application, if it is included.
1998 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001999};
2000
Chris Warrington820d72a2017-04-27 15:27:01 +01002001int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2002 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002003 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002004 std::vector<std::string> overlay_arg_list;
2005 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002006 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002007 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002008 Maybe<std::string> preferred_density;
2009 Maybe<std::string> product_list;
2010 bool legacy_x_flag = false;
2011 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002013 bool shared_lib = false;
2014 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002015 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002016 Maybe<std::string> stable_id_file_path;
2017 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002018 Flags flags =
2019 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002020 .RequiredFlag("-o", "Output path.", &options.output_path)
2021 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002022 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002023 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002024 .OptionalFlagList("-A",
2025 "An assets directory to include in the APK. These are unprocessed.",
2026 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002027 .OptionalFlagList("-R",
2028 "Compilation unit to link, using `overlay` semantics.\n"
2029 "The last conflicting resource given takes precedence.",
2030 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002031 .OptionalFlag("--package-id",
2032 "Specify the package ID to use for this app. Must be greater or equal to\n"
2033 "0x7f and can't be used with --static-lib or --shared-lib.",
2034 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002035 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002036 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002037 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002038 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002039 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002040 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002041 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002042 .OptionalSwitch("--proguard-conditional-keep-rules",
2043 "Generate conditional Proguard keep rules.",
2044 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002045 .OptionalSwitch("--no-auto-version",
2046 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002047 &options.no_auto_version)
2048 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002049 "Disables automatic versioning of vector drawables. Use this only\n"
2050 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002051 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002052 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002053 "Disables automatic versioning of transition resources. Use this only\n"
2054 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002055 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002056 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002057 "Disables automatic deduping of resources with\n"
2058 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002059 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002060 .OptionalSwitch("--enable-sparse-encoding",
2061 "Enables encoding sparse entries using a binary search tree.\n"
2062 "This decreases APK size at the cost of resource retrieval performance.",
2063 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002064 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002065 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002066 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002067 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002068 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002069 "Comma separated list of configurations to include. The default\n"
2070 "is all configurations.",
2071 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002072 .OptionalFlag("--preferred-density",
2073 "Selects the closest matching density and strips out all others.",
2074 &preferred_density)
2075 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002076 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002077 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002078 &options.output_to_directory)
2079 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002080 "Removes XML namespace prefix and URI information from\n"
2081 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002082 &options.no_xml_namespaces)
2083 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002084 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002085 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002086 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002087 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002088 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002089 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002090 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2091 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002092 &options.manifest_fixer_options.version_code_default)
2093 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002094 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002095 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002096 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2097 &shared_lib)
2098 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002099 .OptionalSwitch("--proto-format",
2100 "Generates compiled resources in Protobuf format.\n"
2101 "Suitable as input to the bundle tool for generating an App Bundle.",
2102 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002103 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002104 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002105 &options.no_static_lib_packages)
2106 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002107 "Generates R.java without the final modifier. This is implied when\n"
2108 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002109 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002110 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002111 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002112 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002113 "Emit a file at the given path with a list of name to ID mappings,\n"
2114 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002115 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002116 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002117 "Package name to use when generating R.java for private symbols.\n"
2118 "If not specified, public and private symbols will use the application's\n"
2119 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002121 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002122 &options.custom_java_package)
2123 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002124 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002125 &extra_java_packages)
2126 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002127 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002128 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002129 .OptionalFlag("--output-text-symbols",
2130 "Generates a text file containing the resource symbols of the R class in\n"
2131 "the specified folder.",
2132 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002133 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002134 "Allows the addition of new resources in overlays without\n"
2135 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002136 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002137 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002138 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002139 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002140 "Changes the name of the target package for instrumentation. Most useful\n"
2141 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002142 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002143 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002144 &options.extensions_to_not_compress)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002145 .OptionalSwitch("--warn-manifest-validation",
2146 "Treat manifest validation errors as warnings.",
2147 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002148 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002149 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002150 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2151 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002152 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002153 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002154
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002155 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002156 return 1;
2157 }
2158
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002159 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002160 std::vector<std::string> arg_list;
2161 for (const std::string& arg : flags.GetArgs()) {
2162 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002163 const std::string path = arg.substr(1, arg.size() - 1);
2164 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002165 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2166 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002167 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002168 }
2169 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002170 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002171 }
2172 }
2173
2174 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002175 for (const std::string& arg : overlay_arg_list) {
2176 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002177 const std::string path = arg.substr(1, arg.size() - 1);
2178 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002179 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2180 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002181 return 1;
2182 }
2183 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002184 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002185 }
2186 }
2187
2188 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002189 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002190 }
2191
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002192 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2193 context.GetDiagnostics()->Error(
2194 DiagMessage()
2195 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002196 return 1;
2197 }
2198
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002199 // The default build type.
2200 context.SetPackageType(PackageType::kApp);
2201 context.SetPackageId(kAppPackageId);
2202
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002203 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002204 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002205 context.SetPackageId(0x00);
2206 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002207 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002208 options.output_format = OutputFormat::kProto;
2209 } else if (proto_format) {
2210 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002211 }
2212
2213 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002214 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002215 context.GetDiagnostics()->Error(
2216 DiagMessage() << "can't specify --package-id when not building a regular app");
2217 return 1;
2218 }
2219
2220 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2221 if (!maybe_package_id_int) {
2222 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2223 << "' is not a valid integer");
2224 return 1;
2225 }
2226
2227 const uint32_t package_id_int = maybe_package_id_int.value();
2228 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2229 context.GetDiagnostics()->Error(
2230 DiagMessage() << StringPrintf(
2231 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2232 return 1;
2233 }
2234 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2235 }
2236
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002237 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002238 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002239 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002240 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002241 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002242 }
2243 }
2244
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002245 if (product_list) {
2246 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002247 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002248 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002249 }
2250 }
2251 }
2252
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002253 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002254 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002255 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2256 if (filter == nullptr) {
2257 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002258 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002259 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002260 }
2261
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002262 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002263 Maybe<uint16_t> density =
2264 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2265 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002266 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002267 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002268 options.table_splitter_options.preferred_densities.push_back(density.value());
2269 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002270
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002271 // Parse the split parameters.
2272 for (const std::string& split_arg : split_args) {
2273 options.split_paths.push_back({});
2274 options.split_constraints.push_back({});
2275 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2276 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002277 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002278 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002279 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002280
Adam Lesinskib522f042017-04-21 16:57:59 -07002281 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002282 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2283 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002284 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002285 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002286 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002287
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002288 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002289 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002290 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2291 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2292 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2293 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2294
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002295 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002296 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002297 options.no_auto_version = true;
2298 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002299 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002300 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002301
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002302 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002303 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002304}
2305
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002306} // namespace aapt