blob: b8bcef39fc8641919ed1eea3306c05da4ea70f63 [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
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <queue>
20#include <unordered_map>
21#include <vector>
22
23#include "android-base/errors.h"
24#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080025#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080026#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070027
Adam Lesinski1ab598f2015-08-14 14:26:04 -070028#include "AppInfo.h"
29#include "Debug.h"
30#include "Flags.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070031#include "LoadedApk.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080032#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070033#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080034#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070035#include "ResourceValues.h"
36#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070037#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070038#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080039#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080040#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070041#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070042#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070043#include "format/binary/TableFlattener.h"
44#include "format/binary/XmlFlattener.h"
45#include "format/proto/ProtoDeserialize.h"
46#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070047#include "io/BigBufferStream.h"
48#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080049#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070050#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080051#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070052#include "java/JavaClassGenerator.h"
53#include "java/ManifestClassGenerator.h"
54#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070055#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070056#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080057#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070059#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080060#include "optimize/ResourceDeduper.h"
61#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "process/IResourceTableConsumer.h"
63#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080064#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070065#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080066#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070068using ::aapt::io::FileInputStream;
69using ::android::StringPiece;
70using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070071
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072namespace aapt {
73
Adam Lesinskie59f0d82017-10-13 09:36:53 -070074enum class OutputFormat {
75 kApk,
76 kProto,
77};
78
Adam Lesinski1ab598f2015-08-14 14:26:04 -070079struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070080 std::string output_path;
81 std::string manifest_path;
82 std::vector<std::string> include_paths;
83 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070084 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070085 bool output_to_directory = false;
86 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070087 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070088
Adam Lesinskicacb28f2016-10-19 12:18:14 -070089 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070090 Maybe<std::string> generate_java_class_path;
91 Maybe<std::string> custom_java_package;
92 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070093 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070094 Maybe<std::string> generate_proguard_rules_path;
95 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070096 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070097 bool generate_non_final_ids = false;
98 std::vector<std::string> javadoc_annotations;
99 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700100
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700101 // Optimizations/features.
102 bool no_auto_version = false;
103 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900104 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700105 bool no_resource_deduping = false;
106 bool no_xml_namespaces = false;
107 bool do_not_compress_anything = false;
108 std::unordered_set<std::string> extensions_to_not_compress;
109
110 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700111 bool no_static_lib_packages = false;
112
113 // AndroidManifest.xml massaging options.
114 ManifestFixerOptions manifest_fixer_options;
115
116 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700117 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700118
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800119 // Flattening options.
120 TableFlattenerOptions table_flattener_options;
121
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700122 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700123 TableSplitterOptions table_splitter_options;
124 std::vector<SplitConstraints> split_constraints;
125 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700126
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700127 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700128 std::unordered_map<ResourceName, ResourceId> stable_id_map;
129 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700130};
131
Adam Lesinski64587af2016-02-18 18:33:06 -0800132class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700133 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100134 LinkContext(IDiagnostics* diagnostics)
135 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700137
Adam Lesinskib522f042017-04-21 16:57:59 -0700138 PackageType GetPackageType() override {
139 return package_type_;
140 }
141
142 void SetPackageType(PackageType type) {
143 package_type_ = type;
144 }
145
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700146 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100147 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700148 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700149
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700150 NameMangler* GetNameMangler() override {
151 return &name_mangler_;
152 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700153
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700154 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
155 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700156 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800157
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700158 const std::string& GetCompilationPackage() override {
159 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700160 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700161
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700162 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800163 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700164 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800165
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700166 uint8_t GetPackageId() override {
167 return package_id_;
168 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700169
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700170 void SetPackageId(uint8_t id) {
171 package_id_ = id;
172 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800173
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700174 SymbolTable* GetExternalSymbols() override {
175 return &symbols_;
176 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800177
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700178 bool IsVerbose() override {
179 return verbose_;
180 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800181
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700182 void SetVerbose(bool val) {
183 verbose_ = val;
184 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800185
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700186 int GetMinSdkVersion() override {
187 return min_sdk_version_;
188 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700189
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700190 void SetMinSdkVersion(int minSdk) {
191 min_sdk_version_ = minSdk;
192 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700193
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700194 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700195 DISALLOW_COPY_AND_ASSIGN(LinkContext);
196
Adam Lesinskib522f042017-04-21 16:57:59 -0700197 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100198 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700199 NameMangler name_mangler_;
200 std::string compilation_package_;
201 uint8_t package_id_ = 0x0;
202 SymbolTable symbols_;
203 bool verbose_ = false;
204 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700205};
206
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700207// A custom delegate that generates compatible pre-O IDs for use with feature splits.
208// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
209// is interpreted as a negative number. Some verification was wrongly assuming negative values
210// were invalid.
211//
212// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
213// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
214// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800215//
216// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700217class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
218 public:
219 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
220 }
221
222 virtual ~FeatureSplitSymbolTableDelegate() = default;
223
224 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
225 const ResourceName& name,
226 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
227 std::unique_ptr<SymbolTable::Symbol> symbol =
228 DefaultSymbolTableDelegate::FindByName(name, sources);
229 if (symbol == nullptr) {
230 return {};
231 }
232
233 // Check to see if this is an 'id' with the target package.
234 if (name.type == ResourceType::kId && symbol->id) {
235 ResourceId* id = &symbol->id.value();
236 if (id->package_id() > kAppPackageId) {
237 // Rewrite the resource ID to be compatible pre-O.
238 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
239
240 // Check that this doesn't overlap another resource.
241 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
242 // The ID overlaps, so log a message (since this is a weird failure) and fail.
243 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
244 << " for pre-O feature split support");
245 return {};
246 }
247
248 if (context_->IsVerbose()) {
249 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
250 << ") -> (" << rewritten_id << ")");
251 }
252
253 *id = rewritten_id;
254 }
255 }
256 return symbol;
257 }
258
259 private:
260 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
261
262 IAaptContext* context_;
263};
264
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700265static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
266 const StringPiece& path, bool keep_raw_values, bool utf16,
267 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700268 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700269 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
270 << (keep_raw_values ? "true" : "false")
271 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700272 }
273
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700274 switch (format) {
275 case OutputFormat::kApk: {
276 BigBuffer buffer(1024);
277 XmlFlattenerOptions options = {};
278 options.keep_raw_values = keep_raw_values;
279 options.use_utf16 = utf16;
280 XmlFlattener flattener(&buffer, options);
281 if (!flattener.Consume(context, &xml_res)) {
282 return false;
283 }
284
285 io::BigBufferInputStream input_stream(&buffer);
286 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
287 ArchiveEntry::kCompress, writer);
288 } break;
289
290 case OutputFormat::kProto: {
291 pb::XmlNode pb_node;
292 SerializeXmlResourceToPb(xml_res, &pb_node);
293 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
294 writer);
295 } break;
296 }
297 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800298}
299
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700300// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700301static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700302 FileInputStream fin(path);
303 if (fin.HadError()) {
304 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700305 return {};
306 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700307 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800308}
309
Adam Lesinski355f2852016-02-13 20:26:45 -0800310struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700311 bool no_auto_version = false;
312 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900313 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700314 bool no_xml_namespaces = false;
315 bool keep_raw_values = false;
316 bool do_not_compress_anything = false;
317 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700318 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700319 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800320};
321
Adam Lesinskic744ae82017-05-17 19:28:38 -0700322// A sampling of public framework resource IDs.
323struct R {
324 struct attr {
325 enum : uint32_t {
326 paddingLeft = 0x010100d6u,
327 paddingRight = 0x010100d8u,
328 paddingHorizontal = 0x0101053du,
329
330 paddingTop = 0x010100d7u,
331 paddingBottom = 0x010100d9u,
332 paddingVertical = 0x0101053eu,
333
334 layout_marginLeft = 0x010100f7u,
335 layout_marginRight = 0x010100f9u,
336 layout_marginHorizontal = 0x0101053bu,
337
338 layout_marginTop = 0x010100f8u,
339 layout_marginBottom = 0x010100fau,
340 layout_marginVertical = 0x0101053cu,
341 };
342 };
343};
344
Adam Lesinski355f2852016-02-13 20:26:45 -0800345class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700346 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700347 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700348 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800349
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700350 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800351
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700352 private:
353 struct FileOperation {
354 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700355
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700356 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700357 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700358
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700359 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700360 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700361
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700362 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700363 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700364
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700365 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700366 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800368
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700369 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800370
Adam Lesinskic744ae82017-05-17 19:28:38 -0700371 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
372 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800373
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700374 ResourceFileFlattenerOptions options_;
375 IAaptContext* context_;
376 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700377 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800378};
379
Adam Lesinskic744ae82017-05-17 19:28:38 -0700380ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
381 IAaptContext* context, proguard::KeepSet* keep_set)
382 : options_(options), context_(context), keep_set_(keep_set) {
383 SymbolTable* symm = context_->GetExternalSymbols();
384
385 // Build up the rules for degrading newer attributes to older ones.
386 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
387 // generated from the attribute definitions themselves (b/62028956).
388 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
389 std::vector<ReplacementAttr> replacements{
390 {"paddingLeft", R::attr::paddingLeft,
391 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
392 {"paddingRight", R::attr::paddingRight,
393 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
394 };
395 rules_[R::attr::paddingHorizontal] =
396 util::make_unique<DegradeToManyRule>(std::move(replacements));
397 }
398
399 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
400 std::vector<ReplacementAttr> replacements{
401 {"paddingTop", R::attr::paddingTop,
402 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
403 {"paddingBottom", R::attr::paddingBottom,
404 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
405 };
406 rules_[R::attr::paddingVertical] =
407 util::make_unique<DegradeToManyRule>(std::move(replacements));
408 }
409
410 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
411 std::vector<ReplacementAttr> replacements{
412 {"layout_marginLeft", R::attr::layout_marginLeft,
413 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
414 {"layout_marginRight", R::attr::layout_marginRight,
415 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
416 };
417 rules_[R::attr::layout_marginHorizontal] =
418 util::make_unique<DegradeToManyRule>(std::move(replacements));
419 }
420
421 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
422 std::vector<ReplacementAttr> replacements{
423 {"layout_marginTop", R::attr::layout_marginTop,
424 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
425 {"layout_marginBottom", R::attr::layout_marginBottom,
426 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
427 };
428 rules_[R::attr::layout_marginVertical] =
429 util::make_unique<DegradeToManyRule>(std::move(replacements));
430 }
431}
432
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700433uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
434 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700435 return 0;
436 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800437
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700438 for (const std::string& extension : options_.extensions_to_not_compress) {
439 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700440 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800441 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700442 }
443 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800444}
445
Adam Lesinskibb94f322017-07-12 07:41:55 -0700446static bool IsTransitionElement(const std::string& name) {
447 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
448 name == "changeImageTransform" || name == "changeTransform" ||
449 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
450 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
451 name == "transitionManager";
452}
453
454static bool IsVectorElement(const std::string& name) {
455 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
ztenghuiab2a38c2017-10-13 15:56:08 -0700456 name == "objectAnimator" || name == "gradient";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700457}
458
Adam Lesinskic744ae82017-05-17 19:28:38 -0700459template <typename T>
460std::vector<T> make_singleton_vec(T&& val) {
461 std::vector<T> vec;
462 vec.emplace_back(std::forward<T>(val));
463 return vec;
464}
465
466std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
467 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700468 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700469 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700470
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700471 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700472 context_->GetDiagnostics()->Note(DiagMessage()
473 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700474 }
475
Adam Lesinski00451162017-10-03 07:44:08 -0700476 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
477 // that existing projects have out-of-date references which pass compilation.
478 xml::StripAndroidStudioAttributes(doc->root.get());
479
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700480 XmlReferenceLinker xml_linker;
481 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700482 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700483 }
484
Adam Koskidc21dea2017-07-21 10:55:27 -0700485 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700486 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 }
488
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700489 if (options_.no_xml_namespaces) {
490 XmlNamespaceRemover namespace_remover;
491 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700492 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800493 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700494 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800495
Adam Lesinskibb94f322017-07-12 07:41:55 -0700496 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700497 return make_singleton_vec(std::move(file_op->xml_to_flatten));
498 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700499
Adam Lesinskibb94f322017-07-12 07:41:55 -0700500 if (options_.no_version_vectors || options_.no_version_transitions) {
501 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700502 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700503 if (el && el->namespace_uri.empty()) {
504 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
505 (options_.no_version_transitions && IsTransitionElement(el->name))) {
506 return make_singleton_vec(std::move(file_op->xml_to_flatten));
507 }
508 }
509 }
510
Adam Lesinskic744ae82017-05-17 19:28:38 -0700511 const ConfigDescription& config = file_op->config;
512 ResourceEntry* entry = file_op->entry;
513
514 XmlCompatVersioner xml_compat_versioner(&rules_);
515 const util::Range<ApiVersion> api_range{config.sdkVersion,
516 FindNextApiVersionForConfig(entry, config)};
517 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800518}
519
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700520bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700521 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700522 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800523
Adam Koskidc21dea2017-07-21 10:55:27 -0700524 proguard::CollectResourceReferences(context_, table, keep_set_);
525
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700526 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700527 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
528
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700530 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700531 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700532 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800533
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700534 // Populate the queue with all files in the ResourceTable.
535 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700536 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700537 // WARNING! Do not insert or remove any resources while executing in this scope. It will
538 // corrupt the iteration order.
539
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700540 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700541 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700542 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700544
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700545 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700546 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700547 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700548 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700549 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700550 }
551
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700552 FileOperation file_op;
553 file_op.entry = entry.get();
554 file_op.dst_path = *file_ref->path;
555 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700556 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700559 (file_ref->type == ResourceFile::Type::kBinaryXml ||
560 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700561 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700563 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700564 << "failed to open file");
565 return false;
566 }
567
Adam Lesinski00451162017-10-03 07:44:08 -0700568 if (file_ref->type == ResourceFile::Type::kProtoXml) {
569 pb::XmlNode pb_xml_node;
570 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
571 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700572 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700573 return false;
574 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575
Adam Lesinski00451162017-10-03 07:44:08 -0700576 std::string error;
577 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
578 if (file_op.xml_to_flatten == nullptr) {
579 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700580 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700581 return false;
582 }
583 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700584 std::string error_str;
585 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700586 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700587 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
588 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700589 return false;
590 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591 }
592
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700593 file_op.xml_to_flatten->file.config = config_value->config;
594 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700595 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700596 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700597
598 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
599 // else we end up copying the string in the std::make_pair() method,
600 // then creating a StringPiece from the copy, which would cause us
601 // to end up referencing garbage in the map.
602 const StringPiece entry_name(entry->name);
603 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
604 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700605 }
606 }
607
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700609 for (auto& map_entry : config_sorted_files) {
610 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700611 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700612
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700613 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700614 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
615 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700616 if (versioned_docs.empty()) {
617 error = true;
618 continue;
619 }
620
Adam Lesinskic744ae82017-05-17 19:28:38 -0700621 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
622 std::string dst_path = file_op.dst_path;
623 if (doc->file.config != file_op.config) {
624 // Only add the new versioned configurations.
625 if (context_->IsVerbose()) {
626 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
627 << "auto-versioning resource from config '"
628 << config << "' -> '" << doc->file.config << "'");
629 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700630
Adam Lesinskic744ae82017-05-17 19:28:38 -0700631 dst_path =
632 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
633 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
634 doc->file.source, dst_path, nullptr,
635 context_->GetDiagnostics());
636 if (!result) {
637 return false;
638 }
639 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700640
641 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
642 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700643 }
644 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700645 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
646 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700647 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700649 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700650 }
651 return !error;
652}
653
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700654static bool WriteStableIdMapToPath(IDiagnostics* diag,
655 const std::unordered_map<ResourceName, ResourceId>& id_map,
656 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800657 io::FileOutputStream fout(id_map_path);
658 if (fout.HadError()) {
659 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700660 return false;
661 }
662
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800663 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700664 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700665 const ResourceName& name = entry.first;
666 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800667 printer.Print(name.to_string());
668 printer.Print(" = ");
669 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800671 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700672
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800673 if (fout.HadError()) {
674 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675 return false;
676 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700677 return true;
678}
679
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700680static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
681 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700683 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700684 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700685 return false;
686 }
687
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700688 out_id_map->clear();
689 size_t line_no = 0;
690 for (StringPiece line : util::Tokenize(content, '\n')) {
691 line_no++;
692 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 if (line.empty()) {
694 continue;
695 }
696
697 auto iter = std::find(line.begin(), line.end(), '=');
698 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 return false;
701 }
702
703 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700704 StringPiece res_name_str =
705 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
706 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700707 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
708 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700709 return false;
710 }
711
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700712 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
713 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700714 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700716 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
717 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700718 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
719 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700720 return false;
721 }
722
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700723 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700724 }
725 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700726}
727
Adam Lesinskifb48d292015-11-07 15:52:13 -0800728class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700729 public:
730 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700731 : options_(options),
732 context_(context),
733 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700734 file_collection_(util::make_unique<io::FileCollection>()) {
735 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700736
Adam Lesinski8780eb62017-10-31 17:44:39 -0700737 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700738 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700739 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700740 for (const std::string& path : options_.include_paths) {
741 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700742 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700744
Adam Lesinski8780eb62017-10-31 17:44:39 -0700745 std::string error;
746 auto zip_collection = io::ZipFileCollection::Create(path, &error);
747 if (zip_collection == nullptr) {
748 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
749 return false;
750 }
751
752 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
753 // Load this as a static library include.
754 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
755 Source(path), std::move(zip_collection), context_->GetDiagnostics());
756 if (static_apk == nullptr) {
757 return false;
758 }
759
Adam Lesinskib522f042017-04-21 16:57:59 -0700760 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800761 // Can't include static libraries when not building a static library (they have no IDs
762 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700763 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800764 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700765 return false;
766 }
767
Adam Lesinski8780eb62017-10-31 17:44:39 -0700768 ResourceTable* table = static_apk->GetResourceTable();
769
770 // If we are using --no-static-lib-packages, we need to rename the package of this table to
771 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700772 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800773 // Since package names can differ, and multiple packages can exist in a ResourceTable,
774 // we place the requirement that all static libraries are built with the package
775 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700776 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700777 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800778 } else {
779 context_->GetDiagnostics()->Error(DiagMessage(path)
780 << "no package with ID 0x7f found in static library");
781 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700782 }
783 }
784
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700785 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700786 util::make_unique<ResourceTableSymbolSource>(table));
787 static_library_includes_.push_back(std::move(static_apk));
788 } else {
789 if (!asset_source->AddAssetPath(path)) {
790 context_->GetDiagnostics()->Error(DiagMessage()
791 << "failed to load include path " << path);
792 return false;
793 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700794 }
795 }
796
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800797 // Capture the shared libraries so that the final resource table can be properly flattened
798 // with support for shared libraries.
799 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800800 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800801 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinski490595a2017-11-07 17:08:07 -0800802 } else if (entry.first == kAppPackageId) {
803 // Capture the included base feature package.
804 included_feature_base_ = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800805 }
806 }
807
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700808 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700809 return true;
810 }
811
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800812 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700813 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800814 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
815 if (manifest_el == nullptr) {
816 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700817 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800818
819 AppInfo app_info;
820
821 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
822 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
823 return {};
824 }
825
826 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
827 if (!package_attr) {
828 diag->Error(DiagMessage(xml_res->file.source)
829 << "<manifest> must have a 'package' attribute");
830 return {};
831 }
832 app_info.package = package_attr->value;
833
834 if (xml::Attribute* version_code_attr =
835 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
836 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
837 if (!maybe_code) {
838 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
839 << "invalid android:versionCode '" << version_code_attr->value << "'");
840 return {};
841 }
842 app_info.version_code = maybe_code.value();
843 }
844
845 if (xml::Attribute* revision_code_attr =
846 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
847 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
848 if (!maybe_code) {
849 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
850 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
851 return {};
852 }
853 app_info.revision_code = maybe_code.value();
854 }
855
856 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
857 if (!split_name_attr->value.empty()) {
858 app_info.split_name = split_name_attr->value;
859 }
860 }
861
862 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
863 if (xml::Attribute* min_sdk =
864 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700865 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800866 }
867 }
868 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700869 }
870
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700871 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
872 // Postcondition: ResourceTable has only one package left. All others are
873 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700874 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700875 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700876 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
877 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700878 };
879
880 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700881 for (const auto& package : final_table_.packages) {
882 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700883 // We have a package that is not related to the one we're building!
884 for (const auto& type : package->types) {
885 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700886 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700887
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700888 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700889 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700890 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700891 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
892 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
893 << "generated id '" << res_name
894 << "' for external package '" << package->name
895 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700896 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700897 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
898 << "defined resource '" << res_name
899 << "' for external package '" << package->name
900 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700901 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700902 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700903 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700904 }
905 }
906 }
907 }
908
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700909 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
910 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700911 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700912 return !error;
913 }
914
915 /**
916 * Returns true if no IDs have been set, false otherwise.
917 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700918 bool VerifyNoIdsSet() {
919 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700920 for (const auto& type : package->types) {
921 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800922 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
923 << StringPrintf("%02x", type->id.value())
924 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700925 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700926 }
927
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700928 for (const auto& entry : type->entries) {
929 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700930 ResourceNameRef res_name(package->name, type->type, entry->name);
931 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800932 DiagMessage() << "entry " << res_name << " has ID "
933 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700934 return false;
935 }
936 }
937 }
938 }
939 return true;
940 }
941
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700942 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
943 if (options_.output_to_directory) {
944 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700945 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700946 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700947 }
948 }
949
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700950 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
951 switch (format) {
952 case OutputFormat::kApk: {
953 BigBuffer buffer(1024);
954 TableFlattener flattener(options_.table_flattener_options, &buffer);
955 if (!flattener.Consume(context_, table)) {
956 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
957 return false;
958 }
959
960 io::BigBufferInputStream input_stream(&buffer);
961 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
962 ArchiveEntry::kAlign, writer);
963 } break;
964
965 case OutputFormat::kProto: {
966 pb::ResourceTable pb_table;
967 SerializeTableToPb(*table, &pb_table);
968 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
969 ArchiveEntry::kCompress, writer);
970 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700971 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700972 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700973 }
974
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700975 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700976 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700977 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +0000978 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700979 return true;
980 }
981
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +0000982 std::string out_path;
983 std::unique_ptr<io::FileOutputStream> fout;
984 if (options_.generate_java_class_path) {
985 out_path = options_.generate_java_class_path.value();
986 file::AppendPath(&out_path, file::PackageToPath(out_package));
987 if (!file::mkdirs(out_path)) {
988 context_->GetDiagnostics()->Error(DiagMessage()
989 << "failed to create directory '" << out_path << "'");
990 return false;
991 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700992
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +0000993 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700994
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +0000995 fout = util::make_unique<io::FileOutputStream>(out_path);
996 if (fout->HadError()) {
997 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
998 << "': " << fout->GetError());
999 return false;
1000 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001001 }
1002
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001003 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001004 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001005 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1006 if (fout_text->HadError()) {
1007 context_->GetDiagnostics()->Error(DiagMessage()
1008 << "failed writing to '" << out_text_symbols_path.value()
1009 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001010 return false;
1011 }
1012 }
1013
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001014 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001015 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001016 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 return false;
1018 }
1019
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001020 return true;
1021 }
1022
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001023 bool GenerateJavaClasses() {
1024 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1025 std::vector<std::string> packages_to_callback;
1026
1027 JavaClassGeneratorOptions template_options;
1028 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1029 template_options.javadoc_annotations = options_.javadoc_annotations;
1030
1031 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1032 template_options.use_final = false;
1033 }
1034
1035 if (context_->GetPackageType() == PackageType::kSharedLib) {
1036 template_options.use_final = false;
1037 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1038 }
1039
1040 const StringPiece actual_package = context_->GetCompilationPackage();
1041 StringPiece output_package = context_->GetCompilationPackage();
1042 if (options_.custom_java_package) {
1043 // Override the output java package to the custom one.
1044 output_package = options_.custom_java_package.value();
1045 }
1046
1047 // Generate the private symbols if required.
1048 if (options_.private_symbols) {
1049 packages_to_callback.push_back(options_.private_symbols.value());
1050
1051 // If we defined a private symbols package, we only emit Public symbols
1052 // to the original package, and private and public symbols to the private package.
1053 JavaClassGeneratorOptions options = template_options;
1054 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1055 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1056 options)) {
1057 return false;
1058 }
1059 }
1060
1061 // Generate copies of the original package R class but with different package names.
1062 // This is to support non-namespaced builds.
1063 for (const std::string& extra_package : options_.extra_java_packages) {
1064 packages_to_callback.push_back(extra_package);
1065
1066 JavaClassGeneratorOptions options = template_options;
1067 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1068 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1069 return false;
1070 }
1071 }
1072
1073 // Generate R classes for each package that was merged (static library).
1074 // Use the actual package's resources only.
1075 for (const std::string& package : table_merger_->merged_packages()) {
1076 packages_to_callback.push_back(package);
1077
1078 JavaClassGeneratorOptions options = template_options;
1079 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1080 if (!WriteJavaFile(&final_table_, package, package, options)) {
1081 return false;
1082 }
1083 }
1084
1085 // Generate the main public R class.
1086 JavaClassGeneratorOptions options = template_options;
1087
1088 // Only generate public symbols if we have a private package.
1089 if (options_.private_symbols) {
1090 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1091 }
1092
1093 if (options.rewrite_callback_options) {
1094 options.rewrite_callback_options.value().packages_to_callback =
1095 std::move(packages_to_callback);
1096 }
1097
1098 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1099 options_.generate_text_symbols_path)) {
1100 return false;
1101 }
1102
1103 return true;
1104 }
1105
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001106 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1107 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001108 return true;
1109 }
1110
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001111 std::unique_ptr<ClassDefinition> manifest_class =
1112 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001113
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001114 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001115 // Something bad happened, but we already logged it, so exit.
1116 return false;
1117 }
1118
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001119 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001120 // Empty Manifest class, no need to generate it.
1121 return true;
1122 }
1123
1124 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001125 for (const std::string& annotation : options_.javadoc_annotations) {
1126 std::string proper_annotation = "@";
1127 proper_annotation += annotation;
1128 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001129 }
1130
Adam Lesinski0d81f702017-06-27 15:51:09 -07001131 const std::string package_utf8 =
1132 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001133
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001134 std::string out_path = options_.generate_java_class_path.value();
1135 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001136
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001137 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001138 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1139 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 return false;
1141 }
1142
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001143 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001144
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001145 io::FileOutputStream fout(out_path);
1146 if (fout.HadError()) {
1147 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1148 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001149 return false;
1150 }
1151
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001152 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1153 fout.Flush();
1154
1155 if (fout.HadError()) {
1156 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1157 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001158 return false;
1159 }
1160 return true;
1161 }
1162
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001163 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001164 if (!out) {
1165 return true;
1166 }
1167
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001168 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001169 io::FileOutputStream fout(out_path);
1170 if (fout.HadError()) {
1171 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1172 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001173 return false;
1174 }
1175
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001176 proguard::WriteKeepSet(keep_set, &fout);
1177 fout.Flush();
1178
1179 if (fout.HadError()) {
1180 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1181 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001182 return false;
1183 }
1184 return true;
1185 }
1186
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001187 bool MergeStaticLibrary(const std::string& input, bool override) {
1188 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001189 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001190 }
1191
Adam Lesinski8780eb62017-10-31 17:44:39 -07001192 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1193 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001194 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001195 return false;
1196 }
1197
Adam Lesinski8780eb62017-10-31 17:44:39 -07001198 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001199 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001200 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001201 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202 return false;
1203 }
1204
1205 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001206 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001207 // Merge all resources as if they were in the compilation package. This is the old behavior
1208 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001209
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001210 // Add the package to the set of --extra-packages so we emit an R.java for each library
1211 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001212 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001213 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 }
1215
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001216 // Clear the package name, so as to make the resources look like they are coming from the
1217 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001219 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001220
1221 } else {
1222 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001223 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001224 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001225 }
1226
1227 if (!result) {
1228 return false;
1229 }
1230
1231 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001232 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233 return true;
1234 }
1235
Adam Lesinski2427dce2017-11-30 15:10:28 -08001236 bool MergeExportedSymbols(const Source& source,
1237 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001238 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001239 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001240 ResourceName res_name = exported_symbol.name;
1241 if (res_name.package.empty()) {
1242 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001243 }
1244
Adam Lesinski00451162017-10-03 07:44:08 -07001245 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001246 if (mangled_name) {
1247 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001248 }
1249
1250 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001251 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001252 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001253 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1254 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255 if (!result) {
1256 return false;
1257 }
1258 }
1259 return true;
1260 }
1261
Adam Lesinski2427dce2017-11-30 15:10:28 -08001262 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1263 if (context_->IsVerbose()) {
1264 context_->GetDiagnostics()->Note(DiagMessage()
1265 << "merging '" << compiled_file.name
1266 << "' from compiled file " << compiled_file.source);
1267 }
1268
1269 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1270 return false;
1271 }
1272 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1273 }
1274
Adam Lesinski00451162017-10-03 07:44:08 -07001275 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1276 // If override is true, conflicting resources are allowed to override each other, in order of last
1277 // seen.
1278 // An io::IFileCollection is created from the ZIP file and added to the set of
1279 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001280 bool MergeArchive(const std::string& input, bool override) {
1281 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001282 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001283 }
1284
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001285 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001286 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001287 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001289 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001290 return false;
1291 }
1292
1293 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001294 for (auto iter = collection->Iterator(); iter->HasNext();) {
1295 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001296 error = true;
1297 }
1298 }
1299
1300 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001301 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001302 return !error;
1303 }
1304
Adam Lesinski00451162017-10-03 07:44:08 -07001305 // Takes a path to load and merge into the master ResourceTable. If override is true,
1306 // conflicting resources are allowed to override each other, in order of last seen.
1307 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1308 // as ZIP archive and the files within are merged individually.
1309 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001310 bool MergePath(const std::string& path, bool override) {
1311 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1312 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1313 return MergeArchive(path, override);
1314 } else if (util::EndsWith(path, ".apk")) {
1315 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001316 }
1317
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001318 io::IFile* file = file_collection_->InsertFile(path);
1319 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001320 }
1321
Adam Lesinski00451162017-10-03 07:44:08 -07001322 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1323 // If override is true, conflicting resources are allowed to override each other, in order of last
1324 // seen.
1325 // All other file types are ignored. This is because these files could be coming from a zip,
1326 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001327 bool MergeFile(io::IFile* file, bool override) {
1328 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001329
Adam Lesinski00451162017-10-03 07:44:08 -07001330 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001331 // Since AAPT compiles these file types and appends .flat to them, seeing
1332 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001333 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1334 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1335 << " file passed as argument. Must be "
1336 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001337 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001338 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1339 if (context_->IsVerbose()) {
1340 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1341 return true;
1342 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001343 }
1344
Adam Lesinski00451162017-10-03 07:44:08 -07001345 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1346 if (input_stream == nullptr) {
1347 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1348 return false;
1349 }
1350
1351 if (input_stream->HadError()) {
1352 context_->GetDiagnostics()->Error(DiagMessage(src)
1353 << "failed to open file: " << input_stream->GetError());
1354 return false;
1355 }
1356
1357 ContainerReaderEntry* entry;
1358 ContainerReader reader(input_stream.get());
1359 while ((entry = reader.Next()) != nullptr) {
1360 if (entry->Type() == ContainerEntryType::kResTable) {
1361 pb::ResourceTable pb_table;
1362 if (!entry->GetResTable(&pb_table)) {
1363 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1364 << entry->GetError());
1365 return false;
1366 }
1367
1368 ResourceTable table;
1369 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001370 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001371 context_->GetDiagnostics()->Error(DiagMessage(src)
1372 << "failed to deserialize resource table: " << error);
1373 return false;
1374 }
1375
1376 if (!table_merger_->Merge(src, &table, override)) {
1377 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1378 return false;
1379 }
1380 } else if (entry->Type() == ContainerEntryType::kResFile) {
1381 pb::internal::CompiledFile pb_compiled_file;
1382 off64_t offset;
1383 size_t len;
1384 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1385 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1386 << entry->GetError());
1387 return false;
1388 }
1389
1390 ResourceFile resource_file;
1391 std::string error;
1392 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1393 context_->GetDiagnostics()->Error(DiagMessage(src)
1394 << "failed to read compiled header: " << error);
1395 return false;
1396 }
1397
1398 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1399 return false;
1400 }
1401 }
1402 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403 return true;
1404 }
1405
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001406 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1407 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1408 for (const std::string& assets_dir : options_.assets_dirs) {
1409 Maybe<std::vector<std::string>> files =
1410 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1411 if (!files) {
1412 return false;
1413 }
1414
1415 for (const std::string& file : files.value()) {
1416 std::string full_key = "assets/" + file;
1417 std::string full_path = assets_dir;
1418 file::AppendPath(&full_path, file);
1419
1420 auto iter = merged_assets.find(full_key);
1421 if (iter == merged_assets.end()) {
1422 merged_assets.emplace(std::move(full_key),
1423 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1424 } else if (context_->IsVerbose()) {
1425 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1426 << "asset file overrides '" << full_path << "'");
1427 }
1428 }
1429 }
1430
1431 for (auto& entry : merged_assets) {
1432 uint32_t compression_flags = ArchiveEntry::kCompress;
1433 std::string extension = file::GetExtension(entry.first).to_string();
1434 if (options_.extensions_to_not_compress.count(extension) > 0) {
1435 compression_flags = 0u;
1436 }
1437
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001438 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1439 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001440 return false;
1441 }
1442 }
1443 return true;
1444 }
1445
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001446 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1447 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001448 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1449 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001450 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001451 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1452 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001453 if (!result) {
1454 return false;
1455 }
1456
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001457 ResourceFileFlattenerOptions file_flattener_options;
1458 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001459 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1460 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001461 file_flattener_options.no_auto_version = options_.no_auto_version;
1462 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001463 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001464 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1465 file_flattener_options.update_proguard_spec =
1466 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001467 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001468
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001469 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001470
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001471 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001472 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001473 return false;
1474 }
1475
Adam Lesinski490595a2017-11-07 17:08:07 -08001476 // Hack to fix b/68820737.
1477 // We need to modify the ResourceTable's package name, but that should NOT affect
1478 // anything else being generated, which includes the Java classes.
1479 // If required, the package name is modifed before flattening, and then modified back
1480 // to its original name.
1481 ResourceTablePackage* package_to_rewrite = nullptr;
1482 if (context_->GetPackageId() > kAppPackageId &&
1483 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1484 // The base APK is included, and this is a feature split. If the base package is
1485 // the same as this package, then we are building an old style Android Instant Apps feature
1486 // split and must apply this workaround to avoid requiring namespaces support.
1487 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1488 if (package_to_rewrite != nullptr) {
1489 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1490
1491 std::string new_package_name =
1492 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1493 app_info_.split_name.value_or_default("feature").c_str());
1494
1495 if (context_->IsVerbose()) {
1496 context_->GetDiagnostics()->Note(
1497 DiagMessage() << "rewriting resource package name for feature split to '"
1498 << new_package_name << "'");
1499 }
1500 package_to_rewrite->name = new_package_name;
1501 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001502 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001503
1504 bool success = FlattenTable(table, options_.output_format, writer);
1505
1506 if (package_to_rewrite != nullptr) {
1507 // Change the name back.
1508 package_to_rewrite->name = context_->GetCompilationPackage();
1509 if (package_to_rewrite->id) {
1510 table->included_packages_.erase(package_to_rewrite->id.value());
1511 }
1512 }
1513
1514 if (!success) {
1515 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1516 }
1517 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001518 }
1519
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001520 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001522 std::unique_ptr<xml::XmlResource> manifest_xml =
1523 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1524 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001525 return 1;
1526 }
1527
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001528 // First extract the Package name without modifying it (via --rename-manifest-package).
1529 if (Maybe<AppInfo> maybe_app_info =
1530 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001531 const AppInfo& app_info = maybe_app_info.value();
1532 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001533 }
1534
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001535 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1536 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001537 return 1;
1538 }
1539
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001540 Maybe<AppInfo> maybe_app_info =
1541 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001542 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001543 return 1;
1544 }
1545
Adam Lesinski490595a2017-11-07 17:08:07 -08001546 app_info_ = maybe_app_info.value();
1547 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001548
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001549 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001550
1551 // Override the package ID when it is "android".
1552 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001553 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001554
1555 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001556 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001557 context_->GetDiagnostics()->Error(
1558 DiagMessage() << "package 'android' can only be built as a regular app");
1559 return 1;
1560 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001561 }
1562
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001563 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001564 return 1;
1565 }
1566
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001567 TableMergerOptions table_merger_options;
1568 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001569 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001570
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001571 if (context_->IsVerbose()) {
1572 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001573 << StringPrintf("linking package '%s' using package ID %02x",
1574 context_->GetCompilationPackage().data(),
1575 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001576 }
1577
Adam Lesinski2427dce2017-11-30 15:10:28 -08001578 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1579 // in res/**/*.
1580 {
1581 XmlIdCollector collector;
1582 if (!collector.Consume(context_, manifest_xml.get())) {
1583 return false;
1584 }
1585
1586 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1587 return false;
1588 }
1589 }
1590
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001591 for (const std::string& input : input_files) {
1592 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001593 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001594 return 1;
1595 }
1596 }
1597
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001598 for (const std::string& input : options_.overlay_files) {
1599 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001600 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001601 return 1;
1602 }
1603 }
1604
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001605 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001606 return 1;
1607 }
1608
Adam Lesinskib522f042017-04-21 16:57:59 -07001609 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001611 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001612 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001613 return 1;
1614 }
1615
1616 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001617 IdAssigner id_assigner(&options_.stable_id_map);
1618 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001619 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001620 return 1;
1621 }
1622
1623 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001624 if (options_.resource_id_map_path) {
1625 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001626 for (auto& type : package->types) {
1627 for (auto& entry : type->entries) {
1628 ResourceName name(package->name, type->type, entry->name);
1629 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001630 options_.stable_id_map[std::move(name)] =
1631 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001632 }
1633 }
1634 }
1635
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001636 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001637 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001638 return 1;
1639 }
1640 }
1641 } else {
1642 // Static libs are merged with other apps, and ID collisions are bad, so
1643 // verify that
1644 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001645 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001646 return 1;
1647 }
1648 }
1649
1650 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001651 context_->SetNameManglerPolicy(
1652 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001653
1654 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001655 context_->GetExternalSymbols()->PrependSource(
1656 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001657
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001658 // Workaround for pre-O runtime that would treat negative resource IDs
1659 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1660 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1661 // are just identifiers.
1662 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1663 if (context_->IsVerbose()) {
1664 context_->GetDiagnostics()->Note(DiagMessage()
1665 << "enabling pre-O feature split ID rewriting");
1666 }
1667 context_->GetExternalSymbols()->SetDelegate(
1668 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1669 }
1670
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001671 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001672 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001673 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001674 return 1;
1675 }
1676
Adam Lesinskib522f042017-04-21 16:57:59 -07001677 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001678 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001679 context_->GetDiagnostics()->Warn(DiagMessage()
1680 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001681 }
1682 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001683 ProductFilter product_filter(options_.products);
1684 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001685 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001686 return 1;
1687 }
1688 }
1689
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001690 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001691 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001692 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001693 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001694 return 1;
1695 }
1696 }
1697
Adam Lesinskib522f042017-04-21 16:57:59 -07001698 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001699 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001700 context_->GetDiagnostics()->Note(DiagMessage()
1701 << "collapsing resource versions for minimum SDK "
1702 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001703 }
1704
1705 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001706 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001707 return 1;
1708 }
1709 }
1710
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001711 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001712 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001713 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001714 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001715 return 1;
1716 }
1717 }
1718
Adam Koskidc21dea2017-07-21 10:55:27 -07001719 proguard::KeepSet proguard_keep_set =
1720 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001721 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001722
Adam Lesinskib522f042017-04-21 16:57:59 -07001723 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001724 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001725 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001726 context_->GetDiagnostics()->Warn(DiagMessage()
1727 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001728 }
1729 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001730 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1731 // equal to the minSdk.
1732 options_.split_constraints =
1733 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001734
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001735 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001736 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001737 return 1;
1738 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001739 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001740
1741 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001743 auto split_constraints_iter = options_.split_constraints.begin();
1744 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001745 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001746 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1747 << "generating split with configurations '"
1748 << util::Joiner(split_constraints_iter->configs, ", ")
1749 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001750 }
1751
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001752 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001753 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001754 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001755 return 1;
1756 }
1757
1758 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001759 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001760 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001761
1762 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001763 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001764 context_->GetDiagnostics()->Error(DiagMessage()
1765 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001766 return 1;
1767 }
1768
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001769 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1770 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001771 return 1;
1772 }
1773
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001774 ++path_iter;
1775 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001776 }
1777 }
1778
1779 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001780 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001781 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001782 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001783 return 1;
1784 }
1785
1786 bool error = false;
1787 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001788 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001789 // (aka, which package the AndroidManifest.xml is coming from).
1790 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001791 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001793 XmlReferenceLinker manifest_linker;
1794 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1795 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001796 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001797 error = true;
1798 }
1799
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001800 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001801 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001802 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001803 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001804 }
1805
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001806 if (options_.generate_java_class_path) {
1807 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001808 error = true;
1809 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001810 }
1811
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001812 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001813 // PackageParser will fail if URIs are removed from
1814 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001815 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1816 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817 error = true;
1818 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001819 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001820 } else {
1821 error = true;
1822 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001823 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001824
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001825 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001826 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001827 return 1;
1828 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001829
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001830 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1831 return 1;
1832 }
1833
1834 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001835 return 1;
1836 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001837
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001838 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001839 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001840 return 1;
1841 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001842 }
1843
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001844 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845 return 1;
1846 }
1847
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001848 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1849 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001850 return 1;
1851 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852 return 0;
1853 }
1854
1855 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001856 LinkOptions options_;
1857 LinkContext* context_;
1858 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001859
Adam Lesinski490595a2017-11-07 17:08:07 -08001860 AppInfo app_info_;
1861
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001862 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001863
1864 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001865 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001866
Adam Lesinski8780eb62017-10-31 17:44:39 -07001867 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001868 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001870
Adam Lesinski8780eb62017-10-31 17:44:39 -07001871 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1872 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1873
1874 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1875 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001876
1877 // The set of shared libraries being used, mapping their assigned package ID to package name.
1878 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08001879
1880 // The package name of the base application, if it is included.
1881 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001882};
1883
Chris Warrington820d72a2017-04-27 15:27:01 +01001884int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1885 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001886 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001887 std::vector<std::string> overlay_arg_list;
1888 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001889 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001890 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001891 Maybe<std::string> preferred_density;
1892 Maybe<std::string> product_list;
1893 bool legacy_x_flag = false;
1894 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001895 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001896 bool shared_lib = false;
1897 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001898 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001899 Maybe<std::string> stable_id_file_path;
1900 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001901 Flags flags =
1902 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001903 .RequiredFlag("-o", "Output path.", &options.output_path)
1904 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001905 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001906 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001907 .OptionalFlagList("-A",
1908 "An assets directory to include in the APK. These are unprocessed.",
1909 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001910 .OptionalFlagList("-R",
1911 "Compilation unit to link, using `overlay` semantics.\n"
1912 "The last conflicting resource given takes precedence.",
1913 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001914 .OptionalFlag("--package-id",
1915 "Specify the package ID to use for this app. Must be greater or equal to\n"
1916 "0x7f and can't be used with --static-lib or --shared-lib.",
1917 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001918 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001919 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001920 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001921 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001922 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001923 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001924 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07001925 .OptionalSwitch("--proguard-conditional-keep-rules",
1926 "Generate conditional Proguard keep rules.",
1927 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001928 .OptionalSwitch("--no-auto-version",
1929 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001930 &options.no_auto_version)
1931 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001932 "Disables automatic versioning of vector drawables. Use this only\n"
1933 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001934 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001935 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001936 "Disables automatic versioning of transition resources. Use this only\n"
1937 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001938 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001939 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001940 "Disables automatic deduping of resources with\n"
1941 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001942 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001943 .OptionalSwitch("--enable-sparse-encoding",
1944 "Enables encoding sparse entries using a binary search tree.\n"
1945 "This decreases APK size at the cost of resource retrieval performance.",
1946 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001947 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001948 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001949 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001950 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001951 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001952 "Comma separated list of configurations to include. The default\n"
1953 "is all configurations.",
1954 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001955 .OptionalFlag("--preferred-density",
1956 "Selects the closest matching density and strips out all others.",
1957 &preferred_density)
1958 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001959 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001960 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001961 &options.output_to_directory)
1962 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001963 "Removes XML namespace prefix and URI information from\n"
1964 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001965 &options.no_xml_namespaces)
1966 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001967 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001969 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001970 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001971 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001972 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001973 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1974 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001975 &options.manifest_fixer_options.version_code_default)
1976 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001977 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001978 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001979 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1980 &shared_lib)
1981 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001982 .OptionalSwitch("--proto-format",
1983 "Generates compiled resources in Protobuf format.\n"
1984 "Suitable as input to the bundle tool for generating an App Bundle.",
1985 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001986 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001987 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 &options.no_static_lib_packages)
1989 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001990 "Generates R.java without the final modifier. This is implied when\n"
1991 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001992 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001993 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001994 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001995 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001996 "Emit a file at the given path with a list of name to ID mappings,\n"
1997 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001998 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001999 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002000 "Package name to use when generating R.java for private symbols.\n"
2001 "If not specified, public and private symbols will use the application's\n"
2002 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002003 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002004 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002005 &options.custom_java_package)
2006 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002007 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002008 &extra_java_packages)
2009 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002010 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002011 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002012 .OptionalFlag("--output-text-symbols",
2013 "Generates a text file containing the resource symbols of the R class in\n"
2014 "the specified folder.",
2015 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002016 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002017 "Allows the addition of new resources in overlays without\n"
2018 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002019 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002020 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002021 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002022 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002023 "Changes the name of the target package for instrumentation. Most useful\n"
2024 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002025 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002026 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002027 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002028 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002029 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002030 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2031 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002032 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002033 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002034
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002035 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002036 return 1;
2037 }
2038
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002039 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002040 std::vector<std::string> arg_list;
2041 for (const std::string& arg : flags.GetArgs()) {
2042 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002043 const std::string path = arg.substr(1, arg.size() - 1);
2044 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002045 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2046 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002047 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002048 }
2049 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002050 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002051 }
2052 }
2053
2054 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002055 for (const std::string& arg : overlay_arg_list) {
2056 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002057 const std::string path = arg.substr(1, arg.size() - 1);
2058 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002059 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2060 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002061 return 1;
2062 }
2063 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002064 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002065 }
2066 }
2067
2068 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002069 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002070 }
2071
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002072 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2073 context.GetDiagnostics()->Error(
2074 DiagMessage()
2075 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002076 return 1;
2077 }
2078
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002079 // The default build type.
2080 context.SetPackageType(PackageType::kApp);
2081 context.SetPackageId(kAppPackageId);
2082
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002083 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002084 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002085 context.SetPackageId(0x00);
2086 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002087 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002088 options.output_format = OutputFormat::kProto;
2089 } else if (proto_format) {
2090 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002091 }
2092
2093 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002094 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002095 context.GetDiagnostics()->Error(
2096 DiagMessage() << "can't specify --package-id when not building a regular app");
2097 return 1;
2098 }
2099
2100 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2101 if (!maybe_package_id_int) {
2102 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2103 << "' is not a valid integer");
2104 return 1;
2105 }
2106
2107 const uint32_t package_id_int = maybe_package_id_int.value();
2108 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2109 context.GetDiagnostics()->Error(
2110 DiagMessage() << StringPrintf(
2111 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2112 return 1;
2113 }
2114 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2115 }
2116
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002117 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002118 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002119 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002121 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002122 }
2123 }
2124
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002125 if (product_list) {
2126 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002127 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002128 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002129 }
2130 }
2131 }
2132
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002133 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002134 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002135 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2136 if (filter == nullptr) {
2137 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002138 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002139 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 }
2141
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002142 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002143 Maybe<uint16_t> density =
2144 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2145 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002146 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002147 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002148 options.table_splitter_options.preferred_densities.push_back(density.value());
2149 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002150
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002151 // Parse the split parameters.
2152 for (const std::string& split_arg : split_args) {
2153 options.split_paths.push_back({});
2154 options.split_constraints.push_back({});
2155 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2156 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002157 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002158 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002159 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002160
Adam Lesinskib522f042017-04-21 16:57:59 -07002161 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002162 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2163 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002164 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002165 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002166 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002167
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002168 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002169 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002170 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2171 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2172 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2173 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2174
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002175 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002176 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002177 options.no_auto_version = true;
2178 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002179 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002180 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002181
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002182 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002183 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002184}
2185
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002186} // namespace aapt