blob: d2aebfd31bbf8377cb3786d6f2c651d9670fdb96 [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 = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700978 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700979 return true;
980 }
981
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700982 std::string out_path = options_.generate_java_class_path.value();
983 file::AppendPath(&out_path, file::PackageToPath(out_package));
984 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700985 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
986 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700987 return false;
988 }
989
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700990 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700991
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800992 io::FileOutputStream fout(out_path);
993 if (fout.HadError()) {
994 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
995 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996 return false;
997 }
998
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800999 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001000 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001001 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1002 if (fout_text->HadError()) {
1003 context_->GetDiagnostics()->Error(DiagMessage()
1004 << "failed writing to '" << out_text_symbols_path.value()
1005 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001006 return false;
1007 }
1008 }
1009
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001010 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -07001011 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001012 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 return false;
1014 }
1015
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001016 fout.Flush();
1017
1018 if (fout.HadError()) {
1019 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1020 << "': " << fout.GetError());
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001021 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 }
1023 return true;
1024 }
1025
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001026 bool GenerateJavaClasses() {
1027 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1028 std::vector<std::string> packages_to_callback;
1029
1030 JavaClassGeneratorOptions template_options;
1031 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1032 template_options.javadoc_annotations = options_.javadoc_annotations;
1033
1034 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1035 template_options.use_final = false;
1036 }
1037
1038 if (context_->GetPackageType() == PackageType::kSharedLib) {
1039 template_options.use_final = false;
1040 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1041 }
1042
1043 const StringPiece actual_package = context_->GetCompilationPackage();
1044 StringPiece output_package = context_->GetCompilationPackage();
1045 if (options_.custom_java_package) {
1046 // Override the output java package to the custom one.
1047 output_package = options_.custom_java_package.value();
1048 }
1049
1050 // Generate the private symbols if required.
1051 if (options_.private_symbols) {
1052 packages_to_callback.push_back(options_.private_symbols.value());
1053
1054 // If we defined a private symbols package, we only emit Public symbols
1055 // to the original package, and private and public symbols to the private package.
1056 JavaClassGeneratorOptions options = template_options;
1057 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1058 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1059 options)) {
1060 return false;
1061 }
1062 }
1063
1064 // Generate copies of the original package R class but with different package names.
1065 // This is to support non-namespaced builds.
1066 for (const std::string& extra_package : options_.extra_java_packages) {
1067 packages_to_callback.push_back(extra_package);
1068
1069 JavaClassGeneratorOptions options = template_options;
1070 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1071 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1072 return false;
1073 }
1074 }
1075
1076 // Generate R classes for each package that was merged (static library).
1077 // Use the actual package's resources only.
1078 for (const std::string& package : table_merger_->merged_packages()) {
1079 packages_to_callback.push_back(package);
1080
1081 JavaClassGeneratorOptions options = template_options;
1082 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1083 if (!WriteJavaFile(&final_table_, package, package, options)) {
1084 return false;
1085 }
1086 }
1087
1088 // Generate the main public R class.
1089 JavaClassGeneratorOptions options = template_options;
1090
1091 // Only generate public symbols if we have a private package.
1092 if (options_.private_symbols) {
1093 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1094 }
1095
1096 if (options.rewrite_callback_options) {
1097 options.rewrite_callback_options.value().packages_to_callback =
1098 std::move(packages_to_callback);
1099 }
1100
1101 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1102 options_.generate_text_symbols_path)) {
1103 return false;
1104 }
1105
1106 return true;
1107 }
1108
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001109 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1110 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001111 return true;
1112 }
1113
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001114 std::unique_ptr<ClassDefinition> manifest_class =
1115 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001116
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001117 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001118 // Something bad happened, but we already logged it, so exit.
1119 return false;
1120 }
1121
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001122 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001123 // Empty Manifest class, no need to generate it.
1124 return true;
1125 }
1126
1127 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001128 for (const std::string& annotation : options_.javadoc_annotations) {
1129 std::string proper_annotation = "@";
1130 proper_annotation += annotation;
1131 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001132 }
1133
Adam Lesinski0d81f702017-06-27 15:51:09 -07001134 const std::string package_utf8 =
1135 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001136
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001137 std::string out_path = options_.generate_java_class_path.value();
1138 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001139
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001140 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001141 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1142 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001143 return false;
1144 }
1145
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001146 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001147
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001148 io::FileOutputStream fout(out_path);
1149 if (fout.HadError()) {
1150 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1151 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001152 return false;
1153 }
1154
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001155 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1156 fout.Flush();
1157
1158 if (fout.HadError()) {
1159 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1160 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001161 return false;
1162 }
1163 return true;
1164 }
1165
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001166 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001167 if (!out) {
1168 return true;
1169 }
1170
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001171 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001172 io::FileOutputStream fout(out_path);
1173 if (fout.HadError()) {
1174 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1175 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001176 return false;
1177 }
1178
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001179 proguard::WriteKeepSet(keep_set, &fout);
1180 fout.Flush();
1181
1182 if (fout.HadError()) {
1183 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1184 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001185 return false;
1186 }
1187 return true;
1188 }
1189
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001190 bool MergeStaticLibrary(const std::string& input, bool override) {
1191 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001192 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001193 }
1194
Adam Lesinski8780eb62017-10-31 17:44:39 -07001195 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1196 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001197 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001198 return false;
1199 }
1200
Adam Lesinski8780eb62017-10-31 17:44:39 -07001201 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001202 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001203 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001204 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001205 return false;
1206 }
1207
1208 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001209 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001210 // Merge all resources as if they were in the compilation package. This is the old behavior
1211 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001212
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001213 // Add the package to the set of --extra-packages so we emit an R.java for each library
1214 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001215 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001216 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001217 }
1218
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001219 // Clear the package name, so as to make the resources look like they are coming from the
1220 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001222 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001223
1224 } else {
1225 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001226 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001227 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 }
1229
1230 if (!result) {
1231 return false;
1232 }
1233
1234 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001235 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001236 return true;
1237 }
1238
Adam Lesinski2427dce2017-11-30 15:10:28 -08001239 bool MergeExportedSymbols(const Source& source,
1240 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001241 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001242 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001243 ResourceName res_name = exported_symbol.name;
1244 if (res_name.package.empty()) {
1245 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001246 }
1247
Adam Lesinski00451162017-10-03 07:44:08 -07001248 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001249 if (mangled_name) {
1250 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001251 }
1252
1253 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001254 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001255 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001256 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1257 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001258 if (!result) {
1259 return false;
1260 }
1261 }
1262 return true;
1263 }
1264
Adam Lesinski2427dce2017-11-30 15:10:28 -08001265 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1266 if (context_->IsVerbose()) {
1267 context_->GetDiagnostics()->Note(DiagMessage()
1268 << "merging '" << compiled_file.name
1269 << "' from compiled file " << compiled_file.source);
1270 }
1271
1272 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1273 return false;
1274 }
1275 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1276 }
1277
Adam Lesinski00451162017-10-03 07:44:08 -07001278 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1279 // If override is true, conflicting resources are allowed to override each other, in order of last
1280 // seen.
1281 // An io::IFileCollection is created from the ZIP file and added to the set of
1282 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001283 bool MergeArchive(const std::string& input, bool override) {
1284 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001285 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001286 }
1287
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001288 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001289 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001290 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001291 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001292 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001293 return false;
1294 }
1295
1296 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001297 for (auto iter = collection->Iterator(); iter->HasNext();) {
1298 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001299 error = true;
1300 }
1301 }
1302
1303 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001304 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001305 return !error;
1306 }
1307
Adam Lesinski00451162017-10-03 07:44:08 -07001308 // Takes a path to load and merge into the master ResourceTable. If override is true,
1309 // conflicting resources are allowed to override each other, in order of last seen.
1310 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1311 // as ZIP archive and the files within are merged individually.
1312 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001313 bool MergePath(const std::string& path, bool override) {
1314 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1315 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1316 return MergeArchive(path, override);
1317 } else if (util::EndsWith(path, ".apk")) {
1318 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001319 }
1320
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001321 io::IFile* file = file_collection_->InsertFile(path);
1322 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001323 }
1324
Adam Lesinski00451162017-10-03 07:44:08 -07001325 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1326 // If override is true, conflicting resources are allowed to override each other, in order of last
1327 // seen.
1328 // All other file types are ignored. This is because these files could be coming from a zip,
1329 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001330 bool MergeFile(io::IFile* file, bool override) {
1331 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001332
Adam Lesinski00451162017-10-03 07:44:08 -07001333 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001334 // Since AAPT compiles these file types and appends .flat to them, seeing
1335 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001336 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1337 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1338 << " file passed as argument. Must be "
1339 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001340 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001341 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1342 if (context_->IsVerbose()) {
1343 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1344 return true;
1345 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001346 }
1347
Adam Lesinski00451162017-10-03 07:44:08 -07001348 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1349 if (input_stream == nullptr) {
1350 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1351 return false;
1352 }
1353
1354 if (input_stream->HadError()) {
1355 context_->GetDiagnostics()->Error(DiagMessage(src)
1356 << "failed to open file: " << input_stream->GetError());
1357 return false;
1358 }
1359
1360 ContainerReaderEntry* entry;
1361 ContainerReader reader(input_stream.get());
1362 while ((entry = reader.Next()) != nullptr) {
1363 if (entry->Type() == ContainerEntryType::kResTable) {
1364 pb::ResourceTable pb_table;
1365 if (!entry->GetResTable(&pb_table)) {
1366 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1367 << entry->GetError());
1368 return false;
1369 }
1370
1371 ResourceTable table;
1372 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001373 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001374 context_->GetDiagnostics()->Error(DiagMessage(src)
1375 << "failed to deserialize resource table: " << error);
1376 return false;
1377 }
1378
1379 if (!table_merger_->Merge(src, &table, override)) {
1380 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1381 return false;
1382 }
1383 } else if (entry->Type() == ContainerEntryType::kResFile) {
1384 pb::internal::CompiledFile pb_compiled_file;
1385 off64_t offset;
1386 size_t len;
1387 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1388 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1389 << entry->GetError());
1390 return false;
1391 }
1392
1393 ResourceFile resource_file;
1394 std::string error;
1395 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1396 context_->GetDiagnostics()->Error(DiagMessage(src)
1397 << "failed to read compiled header: " << error);
1398 return false;
1399 }
1400
1401 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1402 return false;
1403 }
1404 }
1405 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001406 return true;
1407 }
1408
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001409 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1410 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1411 for (const std::string& assets_dir : options_.assets_dirs) {
1412 Maybe<std::vector<std::string>> files =
1413 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1414 if (!files) {
1415 return false;
1416 }
1417
1418 for (const std::string& file : files.value()) {
1419 std::string full_key = "assets/" + file;
1420 std::string full_path = assets_dir;
1421 file::AppendPath(&full_path, file);
1422
1423 auto iter = merged_assets.find(full_key);
1424 if (iter == merged_assets.end()) {
1425 merged_assets.emplace(std::move(full_key),
1426 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1427 } else if (context_->IsVerbose()) {
1428 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1429 << "asset file overrides '" << full_path << "'");
1430 }
1431 }
1432 }
1433
1434 for (auto& entry : merged_assets) {
1435 uint32_t compression_flags = ArchiveEntry::kCompress;
1436 std::string extension = file::GetExtension(entry.first).to_string();
1437 if (options_.extensions_to_not_compress.count(extension) > 0) {
1438 compression_flags = 0u;
1439 }
1440
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001441 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1442 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001443 return false;
1444 }
1445 }
1446 return true;
1447 }
1448
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001449 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1450 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001451 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1452 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001453 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001454 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1455 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001456 if (!result) {
1457 return false;
1458 }
1459
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001460 ResourceFileFlattenerOptions file_flattener_options;
1461 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001462 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1463 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001464 file_flattener_options.no_auto_version = options_.no_auto_version;
1465 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001466 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001467 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1468 file_flattener_options.update_proguard_spec =
1469 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001470 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001471
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001472 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001473
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001474 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001475 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001476 return false;
1477 }
1478
Adam Lesinski490595a2017-11-07 17:08:07 -08001479 // Hack to fix b/68820737.
1480 // We need to modify the ResourceTable's package name, but that should NOT affect
1481 // anything else being generated, which includes the Java classes.
1482 // If required, the package name is modifed before flattening, and then modified back
1483 // to its original name.
1484 ResourceTablePackage* package_to_rewrite = nullptr;
1485 if (context_->GetPackageId() > kAppPackageId &&
1486 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1487 // The base APK is included, and this is a feature split. If the base package is
1488 // the same as this package, then we are building an old style Android Instant Apps feature
1489 // split and must apply this workaround to avoid requiring namespaces support.
1490 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1491 if (package_to_rewrite != nullptr) {
1492 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1493
1494 std::string new_package_name =
1495 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1496 app_info_.split_name.value_or_default("feature").c_str());
1497
1498 if (context_->IsVerbose()) {
1499 context_->GetDiagnostics()->Note(
1500 DiagMessage() << "rewriting resource package name for feature split to '"
1501 << new_package_name << "'");
1502 }
1503 package_to_rewrite->name = new_package_name;
1504 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001505 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001506
1507 bool success = FlattenTable(table, options_.output_format, writer);
1508
1509 if (package_to_rewrite != nullptr) {
1510 // Change the name back.
1511 package_to_rewrite->name = context_->GetCompilationPackage();
1512 if (package_to_rewrite->id) {
1513 table->included_packages_.erase(package_to_rewrite->id.value());
1514 }
1515 }
1516
1517 if (!success) {
1518 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1519 }
1520 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521 }
1522
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001523 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001524 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001525 std::unique_ptr<xml::XmlResource> manifest_xml =
1526 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1527 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001528 return 1;
1529 }
1530
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001531 // First extract the Package name without modifying it (via --rename-manifest-package).
1532 if (Maybe<AppInfo> maybe_app_info =
1533 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001534 const AppInfo& app_info = maybe_app_info.value();
1535 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001536 }
1537
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001538 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1539 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001540 return 1;
1541 }
1542
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001543 Maybe<AppInfo> maybe_app_info =
1544 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001545 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001546 return 1;
1547 }
1548
Adam Lesinski490595a2017-11-07 17:08:07 -08001549 app_info_ = maybe_app_info.value();
1550 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001551
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001552 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001553
1554 // Override the package ID when it is "android".
1555 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001556 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001557
1558 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001559 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001560 context_->GetDiagnostics()->Error(
1561 DiagMessage() << "package 'android' can only be built as a regular app");
1562 return 1;
1563 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001564 }
1565
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001566 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001567 return 1;
1568 }
1569
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001570 TableMergerOptions table_merger_options;
1571 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001572 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001573
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001574 if (context_->IsVerbose()) {
1575 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001576 << StringPrintf("linking package '%s' using package ID %02x",
1577 context_->GetCompilationPackage().data(),
1578 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001579 }
1580
Adam Lesinski2427dce2017-11-30 15:10:28 -08001581 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1582 // in res/**/*.
1583 {
1584 XmlIdCollector collector;
1585 if (!collector.Consume(context_, manifest_xml.get())) {
1586 return false;
1587 }
1588
1589 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1590 return false;
1591 }
1592 }
1593
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001594 for (const std::string& input : input_files) {
1595 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001596 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001597 return 1;
1598 }
1599 }
1600
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001601 for (const std::string& input : options_.overlay_files) {
1602 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001603 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001604 return 1;
1605 }
1606 }
1607
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001608 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001609 return 1;
1610 }
1611
Adam Lesinskib522f042017-04-21 16:57:59 -07001612 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001613 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001614 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001615 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001616 return 1;
1617 }
1618
1619 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001620 IdAssigner id_assigner(&options_.stable_id_map);
1621 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001622 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001623 return 1;
1624 }
1625
1626 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001627 if (options_.resource_id_map_path) {
1628 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001629 for (auto& type : package->types) {
1630 for (auto& entry : type->entries) {
1631 ResourceName name(package->name, type->type, entry->name);
1632 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001633 options_.stable_id_map[std::move(name)] =
1634 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001635 }
1636 }
1637 }
1638
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001639 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001640 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001641 return 1;
1642 }
1643 }
1644 } else {
1645 // Static libs are merged with other apps, and ID collisions are bad, so
1646 // verify that
1647 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001648 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001649 return 1;
1650 }
1651 }
1652
1653 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001654 context_->SetNameManglerPolicy(
1655 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001656
1657 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001658 context_->GetExternalSymbols()->PrependSource(
1659 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001660
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001661 // Workaround for pre-O runtime that would treat negative resource IDs
1662 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1663 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1664 // are just identifiers.
1665 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1666 if (context_->IsVerbose()) {
1667 context_->GetDiagnostics()->Note(DiagMessage()
1668 << "enabling pre-O feature split ID rewriting");
1669 }
1670 context_->GetExternalSymbols()->SetDelegate(
1671 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1672 }
1673
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001674 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001675 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001676 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001677 return 1;
1678 }
1679
Adam Lesinskib522f042017-04-21 16:57:59 -07001680 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001681 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001682 context_->GetDiagnostics()->Warn(DiagMessage()
1683 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001684 }
1685 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001686 ProductFilter product_filter(options_.products);
1687 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001688 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001689 return 1;
1690 }
1691 }
1692
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001693 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001694 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001695 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001696 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 return 1;
1698 }
1699 }
1700
Adam Lesinskib522f042017-04-21 16:57:59 -07001701 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001702 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001703 context_->GetDiagnostics()->Note(DiagMessage()
1704 << "collapsing resource versions for minimum SDK "
1705 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001706 }
1707
1708 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001709 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001710 return 1;
1711 }
1712 }
1713
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001714 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001715 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001716 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001717 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001718 return 1;
1719 }
1720 }
1721
Adam Koskidc21dea2017-07-21 10:55:27 -07001722 proguard::KeepSet proguard_keep_set =
1723 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001724 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001725
Adam Lesinskib522f042017-04-21 16:57:59 -07001726 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001727 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001728 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001729 context_->GetDiagnostics()->Warn(DiagMessage()
1730 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001731 }
1732 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001733 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1734 // equal to the minSdk.
1735 options_.split_constraints =
1736 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001737
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001738 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001739 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001740 return 1;
1741 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743
1744 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001745 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001746 auto split_constraints_iter = options_.split_constraints.begin();
1747 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001749 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1750 << "generating split with configurations '"
1751 << util::Joiner(split_constraints_iter->configs, ", ")
1752 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 }
1754
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001755 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001756 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001757 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001758 return 1;
1759 }
1760
1761 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001762 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001763 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001764
1765 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001766 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001767 context_->GetDiagnostics()->Error(DiagMessage()
1768 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001769 return 1;
1770 }
1771
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001772 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1773 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001774 return 1;
1775 }
1776
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001777 ++path_iter;
1778 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001779 }
1780 }
1781
1782 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001783 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001784 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001785 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001786 return 1;
1787 }
1788
1789 bool error = false;
1790 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001791 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792 // (aka, which package the AndroidManifest.xml is coming from).
1793 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001794 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001796 XmlReferenceLinker manifest_linker;
1797 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1798 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001799 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001800 error = true;
1801 }
1802
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001803 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001804 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001805 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001806 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001807 }
1808
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001809 if (options_.generate_java_class_path) {
1810 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001811 error = true;
1812 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001813 }
1814
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001815 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001816 // PackageParser will fail if URIs are removed from
1817 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001818 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1819 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001820 error = true;
1821 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001822 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001823 } else {
1824 error = true;
1825 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001826 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001827
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001828 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001829 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001830 return 1;
1831 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001832
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001833 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1834 return 1;
1835 }
1836
1837 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001838 return 1;
1839 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001840
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001841 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001842 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001843 return 1;
1844 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845 }
1846
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001847 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848 return 1;
1849 }
1850
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001851 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1852 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001853 return 1;
1854 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001855 return 0;
1856 }
1857
1858 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001859 LinkOptions options_;
1860 LinkContext* context_;
1861 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001862
Adam Lesinski490595a2017-11-07 17:08:07 -08001863 AppInfo app_info_;
1864
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001865 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001866
1867 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001868 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001869
Adam Lesinski8780eb62017-10-31 17:44:39 -07001870 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001871 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001872 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001873
Adam Lesinski8780eb62017-10-31 17:44:39 -07001874 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1875 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1876
1877 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1878 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001879
1880 // The set of shared libraries being used, mapping their assigned package ID to package name.
1881 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08001882
1883 // The package name of the base application, if it is included.
1884 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001885};
1886
Chris Warrington820d72a2017-04-27 15:27:01 +01001887int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1888 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001889 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001890 std::vector<std::string> overlay_arg_list;
1891 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001892 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001893 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001894 Maybe<std::string> preferred_density;
1895 Maybe<std::string> product_list;
1896 bool legacy_x_flag = false;
1897 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001898 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001899 bool shared_lib = false;
1900 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001901 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001902 Maybe<std::string> stable_id_file_path;
1903 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001904 Flags flags =
1905 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001906 .RequiredFlag("-o", "Output path.", &options.output_path)
1907 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001908 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001909 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001910 .OptionalFlagList("-A",
1911 "An assets directory to include in the APK. These are unprocessed.",
1912 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001913 .OptionalFlagList("-R",
1914 "Compilation unit to link, using `overlay` semantics.\n"
1915 "The last conflicting resource given takes precedence.",
1916 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001917 .OptionalFlag("--package-id",
1918 "Specify the package ID to use for this app. Must be greater or equal to\n"
1919 "0x7f and can't be used with --static-lib or --shared-lib.",
1920 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001921 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001922 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001923 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001924 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001925 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001926 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001927 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07001928 .OptionalSwitch("--proguard-conditional-keep-rules",
1929 "Generate conditional Proguard keep rules.",
1930 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 .OptionalSwitch("--no-auto-version",
1932 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 &options.no_auto_version)
1934 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001935 "Disables automatic versioning of vector drawables. Use this only\n"
1936 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001937 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001938 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001939 "Disables automatic versioning of transition resources. Use this only\n"
1940 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001941 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001942 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001943 "Disables automatic deduping of resources with\n"
1944 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001945 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001946 .OptionalSwitch("--enable-sparse-encoding",
1947 "Enables encoding sparse entries using a binary search tree.\n"
1948 "This decreases APK size at the cost of resource retrieval performance.",
1949 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001950 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001951 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001952 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001953 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001954 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001955 "Comma separated list of configurations to include. The default\n"
1956 "is all configurations.",
1957 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001958 .OptionalFlag("--preferred-density",
1959 "Selects the closest matching density and strips out all others.",
1960 &preferred_density)
1961 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001962 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001963 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001964 &options.output_to_directory)
1965 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001966 "Removes XML namespace prefix and URI information from\n"
1967 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 &options.no_xml_namespaces)
1969 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001970 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001971 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001972 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001973 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001974 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001975 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001976 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1977 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001978 &options.manifest_fixer_options.version_code_default)
1979 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001980 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001981 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001982 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1983 &shared_lib)
1984 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001985 .OptionalSwitch("--proto-format",
1986 "Generates compiled resources in Protobuf format.\n"
1987 "Suitable as input to the bundle tool for generating an App Bundle.",
1988 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001989 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001990 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001991 &options.no_static_lib_packages)
1992 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001993 "Generates R.java without the final modifier. This is implied when\n"
1994 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001995 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001996 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001997 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001998 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001999 "Emit a file at the given path with a list of name to ID mappings,\n"
2000 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002001 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002002 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002003 "Package name to use when generating R.java for private symbols.\n"
2004 "If not specified, public and private symbols will use the application's\n"
2005 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002006 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002007 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002008 &options.custom_java_package)
2009 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002010 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002011 &extra_java_packages)
2012 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002013 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002014 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002015 .OptionalFlag("--output-text-symbols",
2016 "Generates a text file containing the resource symbols of the R class in\n"
2017 "the specified folder.",
2018 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002019 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002020 "Allows the addition of new resources in overlays without\n"
2021 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002022 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002023 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002024 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002025 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002026 "Changes the name of the target package for instrumentation. Most useful\n"
2027 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002028 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002029 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002030 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002031 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002032 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002033 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2034 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002035 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002036 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002037
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002038 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002039 return 1;
2040 }
2041
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002042 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002043 std::vector<std::string> arg_list;
2044 for (const std::string& arg : flags.GetArgs()) {
2045 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002046 const std::string path = arg.substr(1, arg.size() - 1);
2047 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002048 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2049 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002050 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002051 }
2052 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002053 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002054 }
2055 }
2056
2057 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002058 for (const std::string& arg : overlay_arg_list) {
2059 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002060 const std::string path = arg.substr(1, arg.size() - 1);
2061 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002062 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2063 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 return 1;
2065 }
2066 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002067 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002068 }
2069 }
2070
2071 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002072 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002073 }
2074
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002075 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2076 context.GetDiagnostics()->Error(
2077 DiagMessage()
2078 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002079 return 1;
2080 }
2081
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002082 // The default build type.
2083 context.SetPackageType(PackageType::kApp);
2084 context.SetPackageId(kAppPackageId);
2085
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002086 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002087 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002088 context.SetPackageId(0x00);
2089 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002090 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002091 options.output_format = OutputFormat::kProto;
2092 } else if (proto_format) {
2093 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002094 }
2095
2096 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002097 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002098 context.GetDiagnostics()->Error(
2099 DiagMessage() << "can't specify --package-id when not building a regular app");
2100 return 1;
2101 }
2102
2103 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2104 if (!maybe_package_id_int) {
2105 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2106 << "' is not a valid integer");
2107 return 1;
2108 }
2109
2110 const uint32_t package_id_int = maybe_package_id_int.value();
2111 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2112 context.GetDiagnostics()->Error(
2113 DiagMessage() << StringPrintf(
2114 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2115 return 1;
2116 }
2117 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2118 }
2119
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002120 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002121 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002122 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002123 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002124 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002125 }
2126 }
2127
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002128 if (product_list) {
2129 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002130 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002131 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002132 }
2133 }
2134 }
2135
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002136 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002137 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002138 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2139 if (filter == nullptr) {
2140 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002141 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002142 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002143 }
2144
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002145 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002146 Maybe<uint16_t> density =
2147 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2148 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002149 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002150 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002151 options.table_splitter_options.preferred_densities.push_back(density.value());
2152 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002153
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002154 // Parse the split parameters.
2155 for (const std::string& split_arg : split_args) {
2156 options.split_paths.push_back({});
2157 options.split_constraints.push_back({});
2158 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2159 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002160 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002161 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002162 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002163
Adam Lesinskib522f042017-04-21 16:57:59 -07002164 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002165 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2166 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002167 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002168 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002169 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002170
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002171 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002172 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002173 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2174 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2175 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2176 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2177
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002178 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002179 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002180 options.no_auto_version = true;
2181 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002182 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002183 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002184
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002185 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002186 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002187}
2188
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002189} // namespace aapt