blob: 8ca0b1fd047ce43575ec4f55ca6377b7acce0042 [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>
18
19#include <fstream>
20#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#include "google/protobuf/io/coded_stream.h"
29
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "AppInfo.h"
31#include "Debug.h"
32#include "Flags.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 Lesinskid0f492d2017-04-03 18:12:45 -070036#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070037#include "compile/IdAssigner.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080038#include "filter/ConfigFilter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "flatten/Archive.h"
40#include "flatten/TableFlattener.h"
41#include "flatten/XmlFlattener.h"
Adam Lesinski06460ef2017-03-14 18:52:13 -070042#include "io/BigBufferInputStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080043#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070044#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080045#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070046#include "java/JavaClassGenerator.h"
47#include "java/ManifestClassGenerator.h"
48#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070049#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070050#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080051#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070052#include "link/TableMerger.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080053#include "optimize/ResourceDeduper.h"
54#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070055#include "process/IResourceTableConsumer.h"
56#include "process/SymbolTable.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080057#include "proto/ProtoSerialize.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080058#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059#include "unflatten/BinaryResourceParser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080061#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062
Adam Lesinskid5083f62017-01-16 15:07:21 -080063using android::StringPiece;
Adam Lesinskif34b6f42017-03-03 16:33:26 -080064using android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070065
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066namespace aapt {
67
68struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070069 std::string output_path;
70 std::string manifest_path;
71 std::vector<std::string> include_paths;
72 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070073 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070074 bool output_to_directory = false;
75 bool auto_add_overlay = false;
Adam Lesinski36c73a52016-08-11 13:39:24 -070076
Adam Lesinskicacb28f2016-10-19 12:18:14 -070077 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070078 Maybe<std::string> generate_java_class_path;
79 Maybe<std::string> custom_java_package;
80 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070081 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070082 Maybe<std::string> generate_proguard_rules_path;
83 Maybe<std::string> generate_main_dex_proguard_rules_path;
84 bool generate_non_final_ids = false;
85 std::vector<std::string> javadoc_annotations;
86 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -070087
Adam Lesinskice5e56e2016-10-21 17:56:45 -070088 // Optimizations/features.
89 bool no_auto_version = false;
90 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +090091 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070092 bool no_resource_deduping = false;
93 bool no_xml_namespaces = false;
94 bool do_not_compress_anything = false;
95 std::unordered_set<std::string> extensions_to_not_compress;
96
97 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070098 bool no_static_lib_packages = false;
99
100 // AndroidManifest.xml massaging options.
101 ManifestFixerOptions manifest_fixer_options;
102
103 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700104 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700105
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800106 // Flattening options.
107 TableFlattenerOptions table_flattener_options;
108
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700109 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700110 TableSplitterOptions table_splitter_options;
111 std::vector<SplitConstraints> split_constraints;
112 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700113
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700114 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700115 std::unordered_map<ResourceName, ResourceId> stable_id_map;
116 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700117};
118
Adam Lesinski64587af2016-02-18 18:33:06 -0800119class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700120 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700121 LinkContext() : name_mangler_({}), symbols_(&name_mangler_) {
122 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700123
Adam Lesinskib522f042017-04-21 16:57:59 -0700124 PackageType GetPackageType() override {
125 return package_type_;
126 }
127
128 void SetPackageType(PackageType type) {
129 package_type_ = type;
130 }
131
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700132 IDiagnostics* GetDiagnostics() override {
133 return &diagnostics_;
134 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700135
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136 NameMangler* GetNameMangler() override {
137 return &name_mangler_;
138 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700140 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
141 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700142 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800143
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700144 const std::string& GetCompilationPackage() override {
145 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700146 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700147
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700148 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800149 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700150 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800151
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700152 uint8_t GetPackageId() override {
153 return package_id_;
154 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700155
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700156 void SetPackageId(uint8_t id) {
157 package_id_ = id;
158 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800159
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700160 SymbolTable* GetExternalSymbols() override {
161 return &symbols_;
162 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800163
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700164 bool IsVerbose() override {
165 return verbose_;
166 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800167
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700168 void SetVerbose(bool val) {
169 verbose_ = val;
170 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800171
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700172 int GetMinSdkVersion() override {
173 return min_sdk_version_;
174 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700175
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700176 void SetMinSdkVersion(int minSdk) {
177 min_sdk_version_ = minSdk;
178 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700179
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700180 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700181 DISALLOW_COPY_AND_ASSIGN(LinkContext);
182
Adam Lesinskib522f042017-04-21 16:57:59 -0700183 PackageType package_type_ = PackageType::kApp;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700184 StdErrDiagnostics diagnostics_;
185 NameMangler name_mangler_;
186 std::string compilation_package_;
187 uint8_t package_id_ = 0x0;
188 SymbolTable symbols_;
189 bool verbose_ = false;
190 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700191};
192
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700193// A custom delegate that generates compatible pre-O IDs for use with feature splits.
194// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
195// is interpreted as a negative number. Some verification was wrongly assuming negative values
196// were invalid.
197//
198// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
199// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
200// an overlap exists.
201class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
202 public:
203 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
204 }
205
206 virtual ~FeatureSplitSymbolTableDelegate() = default;
207
208 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
209 const ResourceName& name,
210 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
211 std::unique_ptr<SymbolTable::Symbol> symbol =
212 DefaultSymbolTableDelegate::FindByName(name, sources);
213 if (symbol == nullptr) {
214 return {};
215 }
216
217 // Check to see if this is an 'id' with the target package.
218 if (name.type == ResourceType::kId && symbol->id) {
219 ResourceId* id = &symbol->id.value();
220 if (id->package_id() > kAppPackageId) {
221 // Rewrite the resource ID to be compatible pre-O.
222 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
223
224 // Check that this doesn't overlap another resource.
225 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
226 // The ID overlaps, so log a message (since this is a weird failure) and fail.
227 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
228 << " for pre-O feature split support");
229 return {};
230 }
231
232 if (context_->IsVerbose()) {
233 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
234 << ") -> (" << rewritten_id << ")");
235 }
236
237 *id = rewritten_id;
238 }
239 }
240 return symbol;
241 }
242
243 private:
244 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
245
246 IAaptContext* context_;
247};
248
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700249static bool FlattenXml(xml::XmlResource* xml_res, const StringPiece& path,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700250 Maybe<size_t> max_sdk_level, bool keep_raw_values, IArchiveWriter* writer,
251 IAaptContext* context) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700252 BigBuffer buffer(1024);
253 XmlFlattenerOptions options = {};
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700254 options.keep_raw_values = keep_raw_values;
255 options.max_sdk_level = max_sdk_level;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700256 XmlFlattener flattener(&buffer, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700257 if (!flattener.Consume(context, xml_res)) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800258 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700259 }
260
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700261 if (context->IsVerbose()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700262 DiagMessage msg;
263 msg << "writing " << path << " to archive";
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700264 if (max_sdk_level) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700265 msg << " maxSdkLevel=" << max_sdk_level.value() << " keepRawValues=" << keep_raw_values;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700266 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700267 context->GetDiagnostics()->Note(msg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700268 }
269
Adam Lesinski06460ef2017-03-14 18:52:13 -0700270 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700271 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
272 ArchiveEntry::kCompress, writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800273}
274
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700275static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
276 size_t len, IDiagnostics* diag) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700277 pb::ResourceTable pb_table;
278 if (!pb_table.ParseFromArray(data, len)) {
279 diag->Error(DiagMessage(source) << "invalid compiled table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700280 return {};
281 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800282
Adam Lesinski06460ef2017-03-14 18:52:13 -0700283 std::unique_ptr<ResourceTable> table = DeserializeTableFromPb(pb_table, source, diag);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700284 if (!table) {
285 return {};
286 }
287 return table;
Adam Lesinski355f2852016-02-13 20:26:45 -0800288}
289
290/**
291 * Inflates an XML file from the source path.
292 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700293static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700294 std::ifstream fin(path, std::ifstream::binary);
295 if (!fin) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700296 diag->Error(DiagMessage(path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700297 return {};
298 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700299 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800300}
301
Adam Lesinski355f2852016-02-13 20:26:45 -0800302struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700303 bool no_auto_version = false;
304 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900305 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700306 bool no_xml_namespaces = false;
307 bool keep_raw_values = false;
308 bool do_not_compress_anything = false;
309 bool update_proguard_spec = false;
310 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800311};
312
313class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700314 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700315 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
316 proguard::KeepSet* keep_set)
317 : options_(options), context_(context), keep_set_(keep_set) {
318 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800319
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700320 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800321
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700322 private:
323 struct FileOperation {
324 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700325
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700326 // The entry this file came from.
327 const ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700328
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700329 // The file to copy as-is.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700330 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700331
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700332 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700333 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700334
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700335 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700336 std::string dst_path;
337 bool skip_version = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700338 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800339
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700340 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800341
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700342 bool LinkAndVersionXmlFile(ResourceTable* table, FileOperation* file_op,
343 std::queue<FileOperation>* out_file_op_queue);
Adam Lesinski355f2852016-02-13 20:26:45 -0800344
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700345 ResourceFileFlattenerOptions options_;
346 IAaptContext* context_;
347 proguard::KeepSet* keep_set_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800348};
349
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700350uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
351 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700352 return 0;
353 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800354
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700355 for (const std::string& extension : options_.extensions_to_not_compress) {
356 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700357 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800358 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700359 }
360 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800361}
362
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900363static bool IsTransitionElement(const std::string& name) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700364 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
365 name == "changeImageTransform" || name == "changeTransform" ||
366 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
367 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
368 name == "transitionManager";
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900369}
370
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700371bool ResourceFileFlattener::LinkAndVersionXmlFile(ResourceTable* table, FileOperation* file_op,
372 std::queue<FileOperation>* out_file_op_queue) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700373 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700374 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700375
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700376 if (context_->IsVerbose()) {
377 context_->GetDiagnostics()->Note(DiagMessage() << "linking " << src.path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700378 }
379
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700380 XmlReferenceLinker xml_linker;
381 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700382 return false;
383 }
384
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700385 if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700386 return false;
387 }
388
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700389 if (options_.no_xml_namespaces) {
390 XmlNamespaceRemover namespace_remover;
391 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700392 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800393 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700394 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800395
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700396 if (!options_.no_auto_version) {
397 if (options_.no_version_vectors) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700398 // Skip this if it is a vector or animated-vector.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700399 xml::Element* el = xml::FindRootElement(doc);
400 if (el && el->namespace_uri.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700401 if (el->name == "vector" || el->name == "animated-vector") {
402 // We are NOT going to version this file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700403 file_op->skip_version = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700404 return true;
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700405 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700406 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700407 }
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900408 if (options_.no_version_transitions) {
409 // Skip this if it is a transition resource.
410 xml::Element* el = xml::FindRootElement(doc);
411 if (el && el->namespace_uri.empty()) {
412 if (IsTransitionElement(el->name)) {
413 // We are NOT going to version this file.
414 file_op->skip_version = true;
415 return true;
416 }
417 }
418 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700419
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700420 const ConfigDescription& config = file_op->config;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700421
422 // Find the first SDK level used that is higher than this defined config and
423 // not superseded by a lower or equal SDK level resource.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700424 const int min_sdk_version = context_->GetMinSdkVersion();
425 for (int sdk_level : xml_linker.sdk_levels()) {
426 if (sdk_level > min_sdk_version && sdk_level > config.sdkVersion) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700427 if (!ShouldGenerateVersionedResource(file_op->entry, config, sdk_level)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700428 // If we shouldn't generate a versioned resource, stop checking.
429 break;
Adam Lesinski626a69f2016-03-03 10:09:26 -0800430 }
431
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700432 ResourceFile versioned_file_desc = doc->file;
433 versioned_file_desc.config.sdkVersion = (uint16_t)sdk_level;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700434
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700435 FileOperation new_file_op;
Adam Lesinskiea134e02017-04-13 12:55:19 -0700436 new_file_op.xml_to_flatten = util::make_unique<xml::XmlResource>(
437 versioned_file_desc, StringPool{}, doc->root->Clone());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700438 new_file_op.config = versioned_file_desc.config;
439 new_file_op.entry = file_op->entry;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700440 new_file_op.dst_path =
441 ResourceUtils::BuildResourceFileName(versioned_file_desc, context_->GetNameMangler());
Adam Lesinski355f2852016-02-13 20:26:45 -0800442
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700443 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700444 context_->GetDiagnostics()->Note(DiagMessage(versioned_file_desc.source)
445 << "auto-versioning resource from config '" << config
446 << "' -> '" << versioned_file_desc.config << "'");
Adam Lesinski355f2852016-02-13 20:26:45 -0800447 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700448
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700449 bool added = table->AddFileReferenceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700450 versioned_file_desc.name, versioned_file_desc.config, versioned_file_desc.source,
451 new_file_op.dst_path, nullptr, context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700452 if (!added) {
453 return false;
454 }
455
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700456 out_file_op_queue->push(std::move(new_file_op));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700457 break;
458 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800459 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700460 }
461 return true;
Adam Lesinski355f2852016-02-13 20:26:45 -0800462}
463
464/**
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700465 * Do not insert or remove any resources while executing in this function. It
466 * will
Adam Lesinski355f2852016-02-13 20:26:45 -0800467 * corrupt the iteration order.
468 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700469bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700470 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700471 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800472
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700473 for (auto& pkg : table->packages) {
474 for (auto& type : pkg->types) {
475 // Sort by config and name, so that we get better locality in the zip
476 // file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700477 config_sorted_files.clear();
478 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800479
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700480 // Populate the queue with all files in the ResourceTable.
481 for (auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700482 for (auto& config_value : entry->values) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700483 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700484 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700485 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700486 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700487
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700488 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700489 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700490 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700491 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700492 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700493 }
494
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700495 FileOperation file_op;
496 file_op.entry = entry.get();
497 file_op.dst_path = *file_ref->path;
498 file_op.config = config_value->config;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700499
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700500 const StringPiece src_path = file->GetSource().path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700501 if (type->type != ResourceType::kRaw &&
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700502 (util::EndsWith(src_path, ".xml.flat") || util::EndsWith(src_path, ".xml"))) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700503 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700504 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700505 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700506 << "failed to open file");
507 return false;
508 }
509
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700510 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
511 context_->GetDiagnostics(), file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700512
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700513 if (!file_op.xml_to_flatten) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700514 return false;
515 }
516
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700517 file_op.xml_to_flatten->file.config = config_value->config;
518 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700519 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700520
521 // Enqueue the XML files to be processed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700522 file_operations.push(std::move(file_op));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700523 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700524 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700525
526 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700527 // else we end up copying the string in the std::make_pair() method,
528 // then creating a StringPiece from the copy, which would cause us
529 // to end up referencing garbage in the map.
530 const StringPiece entry_name(entry->name);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700531 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
532 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533 }
534 }
535 }
536
537 // Now process the XML queue
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700538 for (; !file_operations.empty(); file_operations.pop()) {
539 FileOperation& file_op = file_operations.front();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700540
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700541 if (!LinkAndVersionXmlFile(table, &file_op, &file_operations)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700542 error = true;
543 continue;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700544 }
545
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700546 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or else
547 // we end up copying the string in the std::make_pair() method, then
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 // creating a StringPiece from the copy, which would cause us to end up
549 // referencing garbage in the map.
550 const StringPiece entry_name(file_op.entry->name);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700551 config_sorted_files[std::make_pair(file_op.config, entry_name)] = std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 }
553
554 if (error) {
555 return false;
556 }
557
558 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700559 for (auto& map_entry : config_sorted_files) {
560 const ConfigDescription& config = map_entry.first.first;
561 const FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700563 if (file_op.xml_to_flatten) {
564 Maybe<size_t> max_sdk_level;
565 if (!options_.no_auto_version && !file_op.skip_version) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700566 max_sdk_level = std::max<size_t>(std::max<size_t>(config.sdkVersion, 1u),
567 context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700568 }
569
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700570 bool result = FlattenXml(file_op.xml_to_flatten.get(), file_op.dst_path, max_sdk_level,
571 options_.keep_raw_values, archive_writer, context_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572 if (!result) {
573 error = true;
574 }
575 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700576 bool result =
577 io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
578 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700579 if (!result) {
580 error = true;
581 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700582 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700583 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700584 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700585 }
586 return !error;
587}
588
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700589static bool WriteStableIdMapToPath(IDiagnostics* diag,
590 const std::unordered_map<ResourceName, ResourceId>& id_map,
591 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700592 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700593 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700594 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700595 return false;
596 }
597
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700598 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700599 const ResourceName& name = entry.first;
600 const ResourceId& id = entry.second;
601 fout << name << " = " << id << "\n";
602 }
603
604 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700605 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
606 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700607 return false;
608 }
609
610 return true;
611}
612
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700613static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
614 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700615 std::string content;
616 if (!android::base::ReadFileToString(path, &content)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700617 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700618 return false;
619 }
620
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700621 out_id_map->clear();
622 size_t line_no = 0;
623 for (StringPiece line : util::Tokenize(content, '\n')) {
624 line_no++;
625 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700626 if (line.empty()) {
627 continue;
628 }
629
630 auto iter = std::find(line.begin(), line.end(), '=');
631 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700632 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700633 return false;
634 }
635
636 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700637 StringPiece res_name_str =
638 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
639 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700640 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
641 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700642 return false;
643 }
644
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700645 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
646 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700647 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700649 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
650 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700651 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
652 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653 return false;
654 }
655
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700656 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700657 }
658 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700659}
660
Adam Lesinskifb48d292015-11-07 15:52:13 -0800661class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700662 public:
663 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700664 : options_(options),
665 context_(context),
666 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700667 file_collection_(util::make_unique<io::FileCollection>()) {
668 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700669
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 /**
671 * Creates a SymbolTable that loads symbols from the various APKs and caches
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700672 * the results for faster lookup.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700674 bool LoadSymbolsFromIncludePaths() {
675 std::unique_ptr<AssetManagerSymbolSource> asset_source =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700677 for (const std::string& path : options_.include_paths) {
678 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700679 context_->GetDiagnostics()->Note(DiagMessage(path) << "loading include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700681
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 // First try to load the file as a static lib.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700683 std::string error_str;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800684 std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
685 if (include_static) {
Adam Lesinskib522f042017-04-21 16:57:59 -0700686 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800687 // Can't include static libraries when not building a static library (they have no IDs
688 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700689 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800690 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700691 return false;
692 }
693
694 // If we are using --no-static-lib-packages, we need to rename the
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800695 // package of this table to our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700696 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800697 // Since package names can differ, and multiple packages can exist in a ResourceTable,
698 // we place the requirement that all static libraries are built with the package
699 // ID 0x7f. So if one is not found, this is an error.
700 if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700701 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800702 } else {
703 context_->GetDiagnostics()->Error(DiagMessage(path)
704 << "no package with ID 0x7f found in static library");
705 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 }
707 }
708
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700709 context_->GetExternalSymbols()->AppendSource(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800710 util::make_unique<ResourceTableSymbolSource>(include_static.get()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800712 static_table_includes_.push_back(std::move(include_static));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700714 } else if (!error_str.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715 // We had an error with reading, so fail.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700716 context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700717 return false;
718 }
719
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700720 if (!asset_source->AddAssetPath(path)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800721 context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700722 return false;
723 }
724 }
725
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800726 // Capture the shared libraries so that the final resource table can be properly flattened
727 // with support for shared libraries.
728 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800729 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800730 final_table_.included_packages_[entry.first] = entry.second;
731 }
732 }
733
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700735 return true;
736 }
737
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800738 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700739 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800740 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
741 if (manifest_el == nullptr) {
742 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800744
745 AppInfo app_info;
746
747 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
748 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
749 return {};
750 }
751
752 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
753 if (!package_attr) {
754 diag->Error(DiagMessage(xml_res->file.source)
755 << "<manifest> must have a 'package' attribute");
756 return {};
757 }
758 app_info.package = package_attr->value;
759
760 if (xml::Attribute* version_code_attr =
761 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
762 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
763 if (!maybe_code) {
764 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
765 << "invalid android:versionCode '" << version_code_attr->value << "'");
766 return {};
767 }
768 app_info.version_code = maybe_code.value();
769 }
770
771 if (xml::Attribute* revision_code_attr =
772 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
773 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
774 if (!maybe_code) {
775 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
776 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
777 return {};
778 }
779 app_info.revision_code = maybe_code.value();
780 }
781
782 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
783 if (!split_name_attr->value.empty()) {
784 app_info.split_name = split_name_attr->value;
785 }
786 }
787
788 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
789 if (xml::Attribute* min_sdk =
790 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700791 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800792 }
793 }
794 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700795 }
796
797 /**
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800798 * Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700799 * Postcondition: ResourceTable has only one package left. All others are
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700800 * stripped, or there is an error and false is returned.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700801 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700802 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700803 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700804 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
805 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700806 };
807
808 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700809 for (const auto& package : final_table_.packages) {
810 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700811 // We have a package that is not related to the one we're building!
812 for (const auto& type : package->types) {
813 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700814 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700815
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700816 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700817 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700818 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700819 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
820 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
821 << "generated id '" << res_name
822 << "' for external package '" << package->name
823 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700824 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700825 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
826 << "defined resource '" << res_name
827 << "' for external package '" << package->name
828 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700829 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700830 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700831 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700832 }
833 }
834 }
835 }
836
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700837 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
838 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700839 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700840 return !error;
841 }
842
843 /**
844 * Returns true if no IDs have been set, false otherwise.
845 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700846 bool VerifyNoIdsSet() {
847 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700848 for (const auto& type : package->types) {
849 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800850 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
851 << StringPrintf("%02x", type->id.value())
852 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700853 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700854 }
855
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700856 for (const auto& entry : type->entries) {
857 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700858 ResourceNameRef res_name(package->name, type->type, entry->name);
859 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800860 DiagMessage() << "entry " << res_name << " has ID "
861 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700862 return false;
863 }
864 }
865 }
866 }
867 return true;
868 }
869
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700870 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
871 if (options_.output_to_directory) {
872 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700873 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700874 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700875 }
876 }
877
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700878 bool FlattenTable(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700879 BigBuffer buffer(1024);
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800880 TableFlattener flattener(options_.table_flattener_options, &buffer);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700881 if (!flattener.Consume(context_, table)) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700882 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700883 return false;
884 }
885
Adam Lesinski06460ef2017-03-14 18:52:13 -0700886 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700887 return io::CopyInputStreamToArchive(context_, &input_stream, "resources.arsc",
888 ArchiveEntry::kAlign, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700889 }
890
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700891 bool FlattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700892 std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(table);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700893 return io::CopyProtoToArchive(context_, pb_table.get(), "resources.arsc.flat", 0, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700894 }
895
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700896 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700897 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
898 const Maybe<std::string> out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700899 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700900 return true;
901 }
902
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700903 std::string out_path = options_.generate_java_class_path.value();
904 file::AppendPath(&out_path, file::PackageToPath(out_package));
905 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700906 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
907 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700908 return false;
909 }
910
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700911 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700912
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700913 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700914 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700915 context_->GetDiagnostics()->Error(DiagMessage()
916 << "failed writing to '" << out_path
917 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700918 return false;
919 }
920
Adam Lesinski418763f2017-04-11 17:36:53 -0700921 std::unique_ptr<std::ofstream> fout_text;
922 if (out_text_symbols_path) {
923 fout_text =
924 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
925 if (!*fout_text) {
926 context_->GetDiagnostics()->Error(
927 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
928 << "': " << android::base::SystemErrorCodeToString(errno));
929 return false;
930 }
931 }
932
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700933 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -0700934 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700935 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700936 return false;
937 }
938
939 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700940 context_->GetDiagnostics()->Error(DiagMessage()
941 << "failed writing to '" << out_path
942 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700943 }
944 return true;
945 }
946
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700947 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
948 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700949 return true;
950 }
951
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700952 std::unique_ptr<ClassDefinition> manifest_class =
953 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700954
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700955 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700956 // Something bad happened, but we already logged it, so exit.
957 return false;
958 }
959
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700960 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700961 // Empty Manifest class, no need to generate it.
962 return true;
963 }
964
965 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700966 for (const std::string& annotation : options_.javadoc_annotations) {
967 std::string proper_annotation = "@";
968 proper_annotation += annotation;
969 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700970 }
971
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700972 const std::string& package_utf8 = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700973
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700974 std::string out_path = options_.generate_java_class_path.value();
975 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700976
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700977 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700978 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
979 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700980 return false;
981 }
982
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700983 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700984
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700985 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700986 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700987 context_->GetDiagnostics()->Error(DiagMessage()
988 << "failed writing to '" << out_path
989 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700990 return false;
991 }
992
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700993 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
994 context_->GetDiagnostics()->Error(DiagMessage()
995 << "failed writing to '" << out_path
996 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700997 return false;
998 }
999 return true;
1000 }
1001
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001002 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001003 if (!out) {
1004 return true;
1005 }
1006
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001007 const std::string& out_path = out.value();
1008 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001009 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001010 context_->GetDiagnostics()->Error(DiagMessage()
1011 << "failed to open '" << out_path
1012 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 return false;
1014 }
1015
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001016 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001018 context_->GetDiagnostics()->Error(DiagMessage()
1019 << "failed writing to '" << out_path
1020 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001021 return false;
1022 }
1023 return true;
1024 }
1025
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001026 std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
1027 std::string* out_error) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001028 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001029 io::ZipFileCollection::Create(input, out_error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001030 if (!collection) {
1031 return {};
1032 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001033 return LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001034 }
1035
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001036 std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001037 io::IFile* file = collection->FindFile("resources.arsc.flat");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001038 if (!file) {
1039 return {};
1040 }
1041
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001042 std::unique_ptr<io::IData> data = file->OpenAsData();
1043 return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
1044 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001045 }
1046
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001047 bool MergeStaticLibrary(const std::string& input, bool override) {
1048 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001049 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001050 }
1051
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001052 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001053 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001054 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001055 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001056 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001057 return false;
1058 }
1059
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001060 std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001061 if (!table) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001062 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001063 return false;
1064 }
1065
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001066 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001067 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001068 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001069 return false;
1070 }
1071
1072 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001073 if (options_.no_static_lib_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001074 // Merge all resources as if they were in the compilation package. This is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001075 // the old behavior of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001076
1077 // Add the package to the set of --extra-packages so we emit an R.java for
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001078 // each library package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001079 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001080 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001081 }
1082
1083 pkg->name = "";
1084 if (override) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001085 result = table_merger_->MergeOverlay(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001086 } else {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001087 result = table_merger_->Merge(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001088 }
1089
1090 } else {
1091 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001092 // preserved and resource names are mangled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001093 result =
1094 table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001095 }
1096
1097 if (!result) {
1098 return false;
1099 }
1100
1101 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001102 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001103 return true;
1104 }
1105
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001106 bool MergeResourceTable(io::IFile* file, bool override) {
1107 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001108 context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
1109 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001110 }
1111
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001112 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001113 if (!data) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001114 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001115 return false;
1116 }
1117
1118 std::unique_ptr<ResourceTable> table =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001119 LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001120 if (!table) {
1121 return false;
1122 }
1123
1124 bool result = false;
1125 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001126 result = table_merger_->MergeOverlay(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001127 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001128 result = table_merger_->Merge(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001129 }
1130 return result;
1131 }
1132
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001133 bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001134 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001135 context_->GetDiagnostics()->Note(DiagMessage() << "merging '" << file_desc->name
1136 << "' from compiled file "
1137 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001138 }
1139
1140 bool result = false;
1141 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001142 result = table_merger_->MergeFileOverlay(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001143 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001144 result = table_merger_->MergeFile(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001145 }
1146
1147 if (!result) {
1148 return false;
1149 }
1150
1151 // Add the exports of this file to the table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001152 for (SourcedResourceName& exported_symbol : file_desc->exported_symbols) {
1153 if (exported_symbol.name.package.empty()) {
1154 exported_symbol.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001155 }
1156
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001157 ResourceNameRef res_name = exported_symbol.name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001158
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001159 Maybe<ResourceName> mangled_name =
1160 context_->GetNameMangler()->MangleName(exported_symbol.name);
1161 if (mangled_name) {
1162 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001163 }
1164
1165 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001166 id->SetSource(file_desc->source.WithLine(exported_symbol.line));
1167 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001168 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1169 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001170 if (!result) {
1171 return false;
1172 }
1173 }
1174 return true;
1175 }
1176
1177 /**
1178 * Takes a path to load as a ZIP file and merges the files within into the
1179 * master ResourceTable.
1180 * If override is true, conflicting resources are allowed to override each
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001181 * other, in order of last seen.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001182 *
1183 * An io::IFileCollection is created from the ZIP file and added to the set of
1184 * io::IFileCollections that are open.
1185 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001186 bool MergeArchive(const std::string& input, bool override) {
1187 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001188 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001189 }
1190
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001191 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001192 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001193 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001194 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001195 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001196 return false;
1197 }
1198
1199 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001200 for (auto iter = collection->Iterator(); iter->HasNext();) {
1201 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202 error = true;
1203 }
1204 }
1205
1206 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001207 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001208 return !error;
1209 }
1210
1211 /**
1212 * Takes a path to load and merge into the master ResourceTable. If override
1213 * is true,
1214 * conflicting resources are allowed to override each other, in order of last
1215 * seen.
1216 *
1217 * If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1218 * as ZIP archive
1219 * and the files within are merged individually.
1220 *
1221 * Otherwise the files is processed on its own.
1222 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001223 bool MergePath(const std::string& path, bool override) {
1224 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1225 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1226 return MergeArchive(path, override);
1227 } else if (util::EndsWith(path, ".apk")) {
1228 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001229 }
1230
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001231 io::IFile* file = file_collection_->InsertFile(path);
1232 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233 }
1234
1235 /**
1236 * Takes a file to load and merge into the master ResourceTable. If override
1237 * is true,
1238 * conflicting resources are allowed to override each other, in order of last
1239 * seen.
1240 *
1241 * If the file ends with .arsc.flat, then it is loaded as a ResourceTable and
1242 * merged into the
1243 * master ResourceTable. If the file ends with .flat, then it is treated like
1244 * a compiled file
1245 * and the header data is read and merged into the final ResourceTable.
1246 *
1247 * All other file types are ignored. This is because these files could be
1248 * coming from a zip,
1249 * where we could have other files like classes.dex.
1250 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001251 bool MergeFile(io::IFile* file, bool override) {
1252 const Source& src = file->GetSource();
1253 if (util::EndsWith(src.path, ".arsc.flat")) {
1254 return MergeResourceTable(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 } else if (util::EndsWith(src.path, ".flat")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257 // Try opening the file and looking for an Export header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001258 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001260 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001261 return false;
1262 }
1263
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001264 CompiledFileInputStream input_stream(data->data(), data->size());
1265 uint32_t num_files = 0;
1266 if (!input_stream.ReadLittleEndian32(&num_files)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001267 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed read num files");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001268 return false;
1269 }
1270
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001271 for (uint32_t i = 0; i < num_files; i++) {
1272 pb::CompiledFile compiled_file;
1273 if (!input_stream.ReadCompiledFile(&compiled_file)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001274 context_->GetDiagnostics()->Error(DiagMessage(src)
1275 << "failed to read compiled file header");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001276 return false;
Adam Lesinski467f1712015-11-16 17:35:44 -08001277 }
1278
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 uint64_t offset, len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001280 if (!input_stream.ReadDataMetaData(&offset, &len)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001281 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read data meta data");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001282 return false;
1283 }
1284
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001285 std::unique_ptr<ResourceFile> resource_file = DeserializeCompiledFileFromPb(
1286 compiled_file, file->GetSource(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001287 if (!resource_file) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 return false;
1289 }
1290
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001291 if (!MergeCompiledFile(file->CreateFileSegment(offset, len), resource_file.get(),
1292 override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001293 return false;
1294 }
1295 }
1296 return true;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001297 } else if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001298 // Since AAPT compiles these file types and appends .flat to them, seeing
1299 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001300 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1301 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1302 << " file passed as argument. Must be "
1303 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001304 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001305 }
1306
1307 // Ignore non .flat files. This could be classes.dex or something else that
1308 // happens
1309 // to be in an archive.
1310 return true;
1311 }
1312
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001313 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1314 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1315 for (const std::string& assets_dir : options_.assets_dirs) {
1316 Maybe<std::vector<std::string>> files =
1317 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1318 if (!files) {
1319 return false;
1320 }
1321
1322 for (const std::string& file : files.value()) {
1323 std::string full_key = "assets/" + file;
1324 std::string full_path = assets_dir;
1325 file::AppendPath(&full_path, file);
1326
1327 auto iter = merged_assets.find(full_key);
1328 if (iter == merged_assets.end()) {
1329 merged_assets.emplace(std::move(full_key),
1330 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1331 } else if (context_->IsVerbose()) {
1332 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1333 << "asset file overrides '" << full_path << "'");
1334 }
1335 }
1336 }
1337
1338 for (auto& entry : merged_assets) {
1339 uint32_t compression_flags = ArchiveEntry::kCompress;
1340 std::string extension = file::GetExtension(entry.first).to_string();
1341 if (options_.extensions_to_not_compress.count(extension) > 0) {
1342 compression_flags = 0u;
1343 }
1344
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001345 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1346 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001347 return false;
1348 }
1349 }
1350 return true;
1351 }
1352
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001353 /**
1354 * Writes the AndroidManifest, ResourceTable, and all XML files referenced by
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001355 * the ResourceTable to the IArchiveWriter.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001356 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001357 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1358 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001359 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001360 bool result =
1361 FlattenXml(manifest, "AndroidManifest.xml", {}, keep_raw_values, writer, context_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001362 if (!result) {
1363 return false;
1364 }
1365
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001366 ResourceFileFlattenerOptions file_flattener_options;
1367 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001368 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1369 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001370 file_flattener_options.no_auto_version = options_.no_auto_version;
1371 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001372 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001373 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1374 file_flattener_options.update_proguard_spec =
1375 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001377 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001378
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001380 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001381 return false;
1382 }
1383
Adam Lesinskib522f042017-04-21 16:57:59 -07001384 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001385 if (!FlattenTableToPb(table, writer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001386 return false;
1387 }
1388 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001389 if (!FlattenTable(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001390 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001391 return false;
1392 }
1393 }
1394 return true;
1395 }
1396
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001397 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001399 std::unique_ptr<xml::XmlResource> manifest_xml =
1400 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1401 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001402 return 1;
1403 }
1404
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001405 // First extract the Package name without modifying it (via --rename-manifest-package).
1406 if (Maybe<AppInfo> maybe_app_info =
1407 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001408 const AppInfo& app_info = maybe_app_info.value();
1409 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 }
1411
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001412 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1413 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001414 return 1;
1415 }
1416
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001417 Maybe<AppInfo> maybe_app_info =
1418 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001419 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420 return 1;
1421 }
1422
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001423 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001424 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001425
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001426 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001427
1428 // Override the package ID when it is "android".
1429 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001430 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001431
1432 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001433 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001434 context_->GetDiagnostics()->Error(
1435 DiagMessage() << "package 'android' can only be built as a regular app");
1436 return 1;
1437 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001438 }
1439
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001440 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001441 return 1;
1442 }
1443
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001444 TableMergerOptions table_merger_options;
1445 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001446 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001447
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001448 if (context_->IsVerbose()) {
1449 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001450 << StringPrintf("linking package '%s' using package ID %02x",
1451 context_->GetCompilationPackage().data(),
1452 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001453 }
1454
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001455 for (const std::string& input : input_files) {
1456 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001457 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001458 return 1;
1459 }
1460 }
1461
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001462 for (const std::string& input : options_.overlay_files) {
1463 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001464 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001465 return 1;
1466 }
1467 }
1468
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001469 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001470 return 1;
1471 }
1472
Adam Lesinskib522f042017-04-21 16:57:59 -07001473 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001474 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001475 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001476 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001477 return 1;
1478 }
1479
1480 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001481 IdAssigner id_assigner(&options_.stable_id_map);
1482 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001483 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001484 return 1;
1485 }
1486
1487 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001488 if (options_.resource_id_map_path) {
1489 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001490 for (auto& type : package->types) {
1491 for (auto& entry : type->entries) {
1492 ResourceName name(package->name, type->type, entry->name);
1493 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001494 options_.stable_id_map[std::move(name)] =
1495 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001496 }
1497 }
1498 }
1499
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001500 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001501 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001502 return 1;
1503 }
1504 }
1505 } else {
1506 // Static libs are merged with other apps, and ID collisions are bad, so
1507 // verify that
1508 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001509 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001510 return 1;
1511 }
1512 }
1513
1514 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001515 context_->SetNameManglerPolicy(
1516 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001517
1518 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001519 context_->GetExternalSymbols()->PrependSource(
1520 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001522 // Workaround for pre-O runtime that would treat negative resource IDs
1523 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1524 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1525 // are just identifiers.
1526 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1527 if (context_->IsVerbose()) {
1528 context_->GetDiagnostics()->Note(DiagMessage()
1529 << "enabling pre-O feature split ID rewriting");
1530 }
1531 context_->GetExternalSymbols()->SetDelegate(
1532 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1533 }
1534
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001535 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001536 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001537 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001538 return 1;
1539 }
1540
Adam Lesinskib522f042017-04-21 16:57:59 -07001541 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001542 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001543 context_->GetDiagnostics()->Warn(DiagMessage()
1544 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001545 }
1546 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001547 ProductFilter product_filter(options_.products);
1548 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001549 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001550 return 1;
1551 }
1552 }
1553
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001554 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001555 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001556 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001557 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001558 return 1;
1559 }
1560 }
1561
Adam Lesinskib522f042017-04-21 16:57:59 -07001562 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001563 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001564 context_->GetDiagnostics()->Note(DiagMessage()
1565 << "collapsing resource versions for minimum SDK "
1566 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001567 }
1568
1569 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001570 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001571 return 1;
1572 }
1573 }
1574
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001575 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001576 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001577 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001578 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001579 return 1;
1580 }
1581 }
1582
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001583 proguard::KeepSet proguard_keep_set;
1584 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001585
Adam Lesinskib522f042017-04-21 16:57:59 -07001586 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001587 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001588 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001589 context_->GetDiagnostics()->Warn(DiagMessage()
1590 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001591 }
1592 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001593 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1594 // equal to the minSdk.
1595 options_.split_constraints =
1596 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001597
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001598 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001599 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001600 return 1;
1601 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001602 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001603
1604 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001605 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001606 auto split_constraints_iter = options_.split_constraints.begin();
1607 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001608 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001609 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1610 << "generating split with configurations '"
1611 << util::Joiner(split_constraints_iter->configs, ", ")
1612 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001613 }
1614
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001615 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001616 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001617 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001618 return 1;
1619 }
1620
1621 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001622 std::unique_ptr<xml::XmlResource> split_manifest =
1623 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001624
1625 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001626 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001627 context_->GetDiagnostics()->Error(DiagMessage()
1628 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001629 return 1;
1630 }
1631
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001632 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1633 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001634 return 1;
1635 }
1636
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001637 ++path_iter;
1638 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001639 }
1640 }
1641
1642 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001643 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001644 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001645 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001646 return 1;
1647 }
1648
1649 bool error = false;
1650 {
1651 // AndroidManifest.xml has no resource name, but the CallSite is built
1652 // from the name
1653 // (aka, which package the AndroidManifest.xml is coming from).
1654 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001655 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001656
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001657 XmlReferenceLinker manifest_linker;
1658 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1659 if (options_.generate_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001660 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1661 manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001662 error = true;
1663 }
1664
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001665 if (options_.generate_main_dex_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001666 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1667 manifest_xml.get(),
1668 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001669 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001670 }
1671
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001672 if (options_.generate_java_class_path) {
1673 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001674 error = true;
1675 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001676 }
1677
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001678 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001679 // PackageParser will fail if URIs are removed from
1680 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001681 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1682 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001683 error = true;
1684 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001685 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001686 } else {
1687 error = true;
1688 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001689 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001690
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001691 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001692 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001693 return 1;
1694 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001695
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001696 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1697 return 1;
1698 }
1699
1700 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001701 return 1;
1702 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001703
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001704 if (options_.generate_java_class_path) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001705 // The set of packages whose R class to call in the main classes
1706 // onResourcesLoaded callback.
1707 std::vector<std::string> packages_to_callback;
1708
1709 JavaClassGeneratorOptions template_options;
1710 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1711 template_options.javadoc_annotations = options_.javadoc_annotations;
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001712
Adam Lesinskib522f042017-04-21 16:57:59 -07001713 if (context_->GetPackageType() == PackageType::kStaticLib ||
1714 options_.generate_non_final_ids) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001715 template_options.use_final = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001716 }
Adam Lesinski64587af2016-02-18 18:33:06 -08001717
Adam Lesinskib522f042017-04-21 16:57:59 -07001718 if (context_->GetPackageType() == PackageType::kSharedLib) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001719 template_options.use_final = false;
1720 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001721 }
1722
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001723 const StringPiece actual_package = context_->GetCompilationPackage();
1724 StringPiece output_package = context_->GetCompilationPackage();
1725 if (options_.custom_java_package) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001726 // Override the output java package to the custom one.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001727 output_package = options_.custom_java_package.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001728 }
1729
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001730 // Generate the private symbols if required.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001731 if (options_.private_symbols) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001732 packages_to_callback.push_back(options_.private_symbols.value());
1733
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001734 // If we defined a private symbols package, we only emit Public symbols
1735 // to the original package, and private and public symbols to the
1736 // private package.
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001737 JavaClassGeneratorOptions options = template_options;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001738 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001739 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001740 options)) {
1741 return 1;
1742 }
1743 }
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001744
1745 // Generate all the symbols for all extra packages.
1746 for (const std::string& extra_package : options_.extra_java_packages) {
1747 packages_to_callback.push_back(extra_package);
1748
1749 JavaClassGeneratorOptions options = template_options;
1750 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1751 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1752 return 1;
1753 }
1754 }
1755
1756 // Generate the main public R class.
1757 JavaClassGeneratorOptions options = template_options;
1758
1759 // Only generate public symbols if we have a private package.
1760 if (options_.private_symbols) {
1761 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1762 }
1763
1764 if (options.rewrite_callback_options) {
1765 options.rewrite_callback_options.value().packages_to_callback =
1766 std::move(packages_to_callback);
1767 }
1768
Adam Lesinski418763f2017-04-11 17:36:53 -07001769 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1770 options_.generate_text_symbols_path)) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001771 return 1;
1772 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001773 }
1774
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001775 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001776 return 1;
1777 }
1778
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001779 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1780 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001781 return 1;
1782 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001783 return 0;
1784 }
1785
1786 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001787 LinkOptions options_;
1788 LinkContext* context_;
1789 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001790
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001791 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792
1793 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001794 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795
1796 // A vector of IFileCollections. This is mainly here to keep ownership of the
1797 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001798 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001799
1800 // A vector of ResourceTables. This is here to retain ownership, so that the
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001801 // SymbolTable can use these.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001802 std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001803
1804 // The set of shared libraries being used, mapping their assigned package ID to package name.
1805 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001806};
1807
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001808int Link(const std::vector<StringPiece>& args) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001809 LinkContext context;
1810 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001811 std::vector<std::string> overlay_arg_list;
1812 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001813 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001814 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001815 Maybe<std::string> preferred_density;
1816 Maybe<std::string> product_list;
1817 bool legacy_x_flag = false;
1818 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001819 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001820 bool shared_lib = false;
1821 bool static_lib = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001822 Maybe<std::string> stable_id_file_path;
1823 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824 Flags flags =
1825 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001826 .RequiredFlag("-o", "Output path.", &options.output_path)
1827 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001828 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001829 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001830 .OptionalFlagList("-A",
1831 "An assets directory to include in the APK. These are unprocessed.",
1832 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001833 .OptionalFlagList("-R",
1834 "Compilation unit to link, using `overlay` semantics.\n"
1835 "The last conflicting resource given takes precedence.",
1836 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001837 .OptionalFlag("--package-id",
1838 "Specify the package ID to use for this app. Must be greater or equal to\n"
1839 "0x7f and can't be used with --static-lib or --shared-lib.",
1840 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001841 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001842 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001843 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001844 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001845 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001846 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001847 &options.generate_main_dex_proguard_rules_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001848 .OptionalSwitch("--no-auto-version",
1849 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001850 &options.no_auto_version)
1851 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001852 "Disables automatic versioning of vector drawables. Use this only\n"
1853 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001855 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001856 "Disables automatic versioning of transition resources. Use this only\n"
1857 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001858 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001859 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001860 "Disables automatic deduping of resources with\n"
1861 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001862 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001863 .OptionalSwitch("--enable-sparse-encoding",
1864 "Enables encoding sparse entries using a binary search tree.\n"
1865 "This decreases APK size at the cost of resource retrieval performance.",
1866 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001867 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001868 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001869 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001870 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001871 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001872 "Comma separated list of configurations to include. The default\n"
1873 "is all configurations.",
1874 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001875 .OptionalFlag("--preferred-density",
1876 "Selects the closest matching density and strips out all others.",
1877 &preferred_density)
1878 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001879 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001880 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001881 &options.output_to_directory)
1882 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001883 "Removes XML namespace prefix and URI information from\n"
1884 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001885 &options.no_xml_namespaces)
1886 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001887 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001888 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001889 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001890 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001891 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001892 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001893 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1894 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 &options.manifest_fixer_options.version_code_default)
1896 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001897 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001899 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1900 &shared_lib)
1901 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001902 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001903 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 &options.no_static_lib_packages)
1905 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001906 "Generates R.java without the final modifier. This is implied when\n"
1907 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001908 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001909 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001910 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001911 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001912 "Emit a file at the given path with a list of name to ID mappings,\n"
1913 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001914 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001915 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001916 "Package name to use when generating R.java for private symbols.\n"
1917 "If not specified, public and private symbols will use the application's\n"
1918 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001919 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001920 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001921 &options.custom_java_package)
1922 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001923 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001924 &extra_java_packages)
1925 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001926 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001927 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001928 .OptionalFlag("--output-text-symbols",
1929 "Generates a text file containing the resource symbols of the R class in\n"
1930 "the specified folder.",
1931 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001932 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001933 "Allows the addition of new resources in overlays without\n"
1934 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001935 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001936 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001937 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001938 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001939 "Changes the name of the target package for instrumentation. Most useful\n"
1940 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001941 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001942 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001944 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001945 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07001946 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
1947 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001948 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001949 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001950
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001952 return 1;
1953 }
1954
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001955 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001956 std::vector<std::string> arg_list;
1957 for (const std::string& arg : flags.GetArgs()) {
1958 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001959 const std::string path = arg.substr(1, arg.size() - 1);
1960 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001961 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
1962 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001963 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001964 }
1965 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001966 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 }
1968 }
1969
1970 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001971 for (const std::string& arg : overlay_arg_list) {
1972 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001973 const std::string path = arg.substr(1, arg.size() - 1);
1974 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001975 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
1976 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001977 return 1;
1978 }
1979 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001980 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001981 }
1982 }
1983
1984 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001986 }
1987
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001988 if (shared_lib && static_lib) {
1989 context.GetDiagnostics()->Error(DiagMessage()
1990 << "only one of --shared-lib and --static-lib can be defined");
1991 return 1;
1992 }
1993
1994 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001995 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001996 context.SetPackageId(0x00);
1997 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001998 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001999 context.SetPackageId(kAppPackageId);
2000 } else {
Adam Lesinskib522f042017-04-21 16:57:59 -07002001 context.SetPackageType(PackageType::kApp);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002002 context.SetPackageId(kAppPackageId);
2003 }
2004
2005 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002006 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002007 context.GetDiagnostics()->Error(
2008 DiagMessage() << "can't specify --package-id when not building a regular app");
2009 return 1;
2010 }
2011
2012 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2013 if (!maybe_package_id_int) {
2014 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2015 << "' is not a valid integer");
2016 return 1;
2017 }
2018
2019 const uint32_t package_id_int = maybe_package_id_int.value();
2020 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2021 context.GetDiagnostics()->Error(
2022 DiagMessage() << StringPrintf(
2023 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2024 return 1;
2025 }
2026 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2027 }
2028
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002030 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002031 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002032 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002033 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002034 }
2035 }
2036
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002037 if (product_list) {
2038 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002039 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002040 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002041 }
2042 }
2043 }
2044
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002045 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002046 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002047 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2048 if (filter == nullptr) {
2049 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002050 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002051 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002052 }
2053
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002054 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002055 Maybe<uint16_t> density =
2056 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2057 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002058 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002059 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002060 options.table_splitter_options.preferred_densities.push_back(density.value());
2061 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002062
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002063 // Parse the split parameters.
2064 for (const std::string& split_arg : split_args) {
2065 options.split_paths.push_back({});
2066 options.split_constraints.push_back({});
2067 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2068 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002069 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002070 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002071 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002072
Adam Lesinskib522f042017-04-21 16:57:59 -07002073 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002074 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2075 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002076 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002077 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002078 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002079
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002080 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002081 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002082 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2083 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2084 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2085 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2086
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002088 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002089 options.no_auto_version = true;
2090 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002091 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002092 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002093
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002095 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002096}
2097
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002098} // namespace aapt