blob: e94c0b42daf1b00a036679b8f85ef7254eae6792 [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 Lesinski6a008172016-02-02 17:02:58 -080039#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070040#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070041#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070042#include "format/binary/TableFlattener.h"
43#include "format/binary/XmlFlattener.h"
44#include "format/proto/ProtoDeserialize.h"
45#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070046#include "io/BigBufferStream.h"
47#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080048#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070049#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080050#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070051#include "java/JavaClassGenerator.h"
52#include "java/ManifestClassGenerator.h"
53#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070054#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070055#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080056#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070057#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070058#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080059#include "optimize/ResourceDeduper.h"
60#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070061#include "process/IResourceTableConsumer.h"
62#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080063#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080065#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070067using ::aapt::io::FileInputStream;
68using ::android::StringPiece;
69using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070070
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071namespace aapt {
72
Adam Lesinskie59f0d82017-10-13 09:36:53 -070073enum class OutputFormat {
74 kApk,
75 kProto,
76};
77
Adam Lesinski1ab598f2015-08-14 14:26:04 -070078struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070079 std::string output_path;
80 std::string manifest_path;
81 std::vector<std::string> include_paths;
82 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070083 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070084 bool output_to_directory = false;
85 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070086 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070087
Adam Lesinskicacb28f2016-10-19 12:18:14 -070088 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070089 Maybe<std::string> generate_java_class_path;
90 Maybe<std::string> custom_java_package;
91 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070092 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070093 Maybe<std::string> generate_proguard_rules_path;
94 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070095 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070096 bool generate_non_final_ids = false;
97 std::vector<std::string> javadoc_annotations;
98 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -070099
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700100 // Optimizations/features.
101 bool no_auto_version = false;
102 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900103 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 bool no_resource_deduping = false;
105 bool no_xml_namespaces = false;
106 bool do_not_compress_anything = false;
107 std::unordered_set<std::string> extensions_to_not_compress;
108
109 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700110 bool no_static_lib_packages = false;
111
112 // AndroidManifest.xml massaging options.
113 ManifestFixerOptions manifest_fixer_options;
114
115 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700116 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700117
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800118 // Flattening options.
119 TableFlattenerOptions table_flattener_options;
120
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700122 TableSplitterOptions table_splitter_options;
123 std::vector<SplitConstraints> split_constraints;
124 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700125
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700127 std::unordered_map<ResourceName, ResourceId> stable_id_map;
128 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700129};
130
Adam Lesinski64587af2016-02-18 18:33:06 -0800131class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700132 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100133 LinkContext(IDiagnostics* diagnostics)
134 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700135 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700136
Adam Lesinskib522f042017-04-21 16:57:59 -0700137 PackageType GetPackageType() override {
138 return package_type_;
139 }
140
141 void SetPackageType(PackageType type) {
142 package_type_ = type;
143 }
144
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700145 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100146 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700147 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700148
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 NameMangler* GetNameMangler() override {
150 return &name_mangler_;
151 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700152
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700153 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
154 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700155 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800156
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700157 const std::string& GetCompilationPackage() override {
158 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700159 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700160
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700161 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800162 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700163 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800164
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700165 uint8_t GetPackageId() override {
166 return package_id_;
167 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700168
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700169 void SetPackageId(uint8_t id) {
170 package_id_ = id;
171 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800172
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700173 SymbolTable* GetExternalSymbols() override {
174 return &symbols_;
175 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800176
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700177 bool IsVerbose() override {
178 return verbose_;
179 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800180
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700181 void SetVerbose(bool val) {
182 verbose_ = val;
183 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800184
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700185 int GetMinSdkVersion() override {
186 return min_sdk_version_;
187 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700188
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700189 void SetMinSdkVersion(int minSdk) {
190 min_sdk_version_ = minSdk;
191 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700192
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700193 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700194 DISALLOW_COPY_AND_ASSIGN(LinkContext);
195
Adam Lesinskib522f042017-04-21 16:57:59 -0700196 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100197 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700198 NameMangler name_mangler_;
199 std::string compilation_package_;
200 uint8_t package_id_ = 0x0;
201 SymbolTable symbols_;
202 bool verbose_ = false;
203 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700204};
205
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700206// A custom delegate that generates compatible pre-O IDs for use with feature splits.
207// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
208// is interpreted as a negative number. Some verification was wrongly assuming negative values
209// were invalid.
210//
211// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
212// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
213// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800214//
215// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700216class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
217 public:
218 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
219 }
220
221 virtual ~FeatureSplitSymbolTableDelegate() = default;
222
223 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
224 const ResourceName& name,
225 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
226 std::unique_ptr<SymbolTable::Symbol> symbol =
227 DefaultSymbolTableDelegate::FindByName(name, sources);
228 if (symbol == nullptr) {
229 return {};
230 }
231
232 // Check to see if this is an 'id' with the target package.
233 if (name.type == ResourceType::kId && symbol->id) {
234 ResourceId* id = &symbol->id.value();
235 if (id->package_id() > kAppPackageId) {
236 // Rewrite the resource ID to be compatible pre-O.
237 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
238
239 // Check that this doesn't overlap another resource.
240 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
241 // The ID overlaps, so log a message (since this is a weird failure) and fail.
242 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
243 << " for pre-O feature split support");
244 return {};
245 }
246
247 if (context_->IsVerbose()) {
248 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
249 << ") -> (" << rewritten_id << ")");
250 }
251
252 *id = rewritten_id;
253 }
254 }
255 return symbol;
256 }
257
258 private:
259 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
260
261 IAaptContext* context_;
262};
263
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700264static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
265 const StringPiece& path, bool keep_raw_values, bool utf16,
266 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700267 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700268 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
269 << (keep_raw_values ? "true" : "false")
270 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700271 }
272
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700273 switch (format) {
274 case OutputFormat::kApk: {
275 BigBuffer buffer(1024);
276 XmlFlattenerOptions options = {};
277 options.keep_raw_values = keep_raw_values;
278 options.use_utf16 = utf16;
279 XmlFlattener flattener(&buffer, options);
280 if (!flattener.Consume(context, &xml_res)) {
281 return false;
282 }
283
284 io::BigBufferInputStream input_stream(&buffer);
285 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
286 ArchiveEntry::kCompress, writer);
287 } break;
288
289 case OutputFormat::kProto: {
290 pb::XmlNode pb_node;
291 SerializeXmlResourceToPb(xml_res, &pb_node);
292 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
293 writer);
294 } break;
295 }
296 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800297}
298
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700299// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700300static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700301 FileInputStream fin(path);
302 if (fin.HadError()) {
303 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700304 return {};
305 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700306 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800307}
308
Adam Lesinski355f2852016-02-13 20:26:45 -0800309struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700310 bool no_auto_version = false;
311 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900312 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700313 bool no_xml_namespaces = false;
314 bool keep_raw_values = false;
315 bool do_not_compress_anything = false;
316 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700317 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700318 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800319};
320
Adam Lesinskic744ae82017-05-17 19:28:38 -0700321// A sampling of public framework resource IDs.
322struct R {
323 struct attr {
324 enum : uint32_t {
325 paddingLeft = 0x010100d6u,
326 paddingRight = 0x010100d8u,
327 paddingHorizontal = 0x0101053du,
328
329 paddingTop = 0x010100d7u,
330 paddingBottom = 0x010100d9u,
331 paddingVertical = 0x0101053eu,
332
333 layout_marginLeft = 0x010100f7u,
334 layout_marginRight = 0x010100f9u,
335 layout_marginHorizontal = 0x0101053bu,
336
337 layout_marginTop = 0x010100f8u,
338 layout_marginBottom = 0x010100fau,
339 layout_marginVertical = 0x0101053cu,
340 };
341 };
342};
343
Adam Lesinski355f2852016-02-13 20:26:45 -0800344class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700345 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700346 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700347 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800348
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700349 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800350
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700351 private:
352 struct FileOperation {
353 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700354
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700355 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700356 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700357
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700358 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700359 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700362 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700365 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700366 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800367
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700368 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800369
Adam Lesinskic744ae82017-05-17 19:28:38 -0700370 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
371 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800372
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700373 ResourceFileFlattenerOptions options_;
374 IAaptContext* context_;
375 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700376 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800377};
378
Adam Lesinskic744ae82017-05-17 19:28:38 -0700379ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
380 IAaptContext* context, proguard::KeepSet* keep_set)
381 : options_(options), context_(context), keep_set_(keep_set) {
382 SymbolTable* symm = context_->GetExternalSymbols();
383
384 // Build up the rules for degrading newer attributes to older ones.
385 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
386 // generated from the attribute definitions themselves (b/62028956).
387 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
388 std::vector<ReplacementAttr> replacements{
389 {"paddingLeft", R::attr::paddingLeft,
390 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
391 {"paddingRight", R::attr::paddingRight,
392 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
393 };
394 rules_[R::attr::paddingHorizontal] =
395 util::make_unique<DegradeToManyRule>(std::move(replacements));
396 }
397
398 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
399 std::vector<ReplacementAttr> replacements{
400 {"paddingTop", R::attr::paddingTop,
401 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
402 {"paddingBottom", R::attr::paddingBottom,
403 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
404 };
405 rules_[R::attr::paddingVertical] =
406 util::make_unique<DegradeToManyRule>(std::move(replacements));
407 }
408
409 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
410 std::vector<ReplacementAttr> replacements{
411 {"layout_marginLeft", R::attr::layout_marginLeft,
412 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
413 {"layout_marginRight", R::attr::layout_marginRight,
414 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
415 };
416 rules_[R::attr::layout_marginHorizontal] =
417 util::make_unique<DegradeToManyRule>(std::move(replacements));
418 }
419
420 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
421 std::vector<ReplacementAttr> replacements{
422 {"layout_marginTop", R::attr::layout_marginTop,
423 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
424 {"layout_marginBottom", R::attr::layout_marginBottom,
425 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
426 };
427 rules_[R::attr::layout_marginVertical] =
428 util::make_unique<DegradeToManyRule>(std::move(replacements));
429 }
430}
431
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700432uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
433 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700434 return 0;
435 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800436
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700437 for (const std::string& extension : options_.extensions_to_not_compress) {
438 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700439 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800440 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700441 }
442 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800443}
444
Adam Lesinskibb94f322017-07-12 07:41:55 -0700445static bool IsTransitionElement(const std::string& name) {
446 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
447 name == "changeImageTransform" || name == "changeTransform" ||
448 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
449 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
450 name == "transitionManager";
451}
452
453static bool IsVectorElement(const std::string& name) {
454 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
ztenghuiab2a38c2017-10-13 15:56:08 -0700455 name == "objectAnimator" || name == "gradient";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700456}
457
Adam Lesinskic744ae82017-05-17 19:28:38 -0700458template <typename T>
459std::vector<T> make_singleton_vec(T&& val) {
460 std::vector<T> vec;
461 vec.emplace_back(std::forward<T>(val));
462 return vec;
463}
464
465std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
466 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700467 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700468 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700469
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700470 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700471 context_->GetDiagnostics()->Note(DiagMessage()
472 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700473 }
474
Adam Lesinski00451162017-10-03 07:44:08 -0700475 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
476 // that existing projects have out-of-date references which pass compilation.
477 xml::StripAndroidStudioAttributes(doc->root.get());
478
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700479 XmlReferenceLinker xml_linker;
480 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700481 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700482 }
483
Adam Koskidc21dea2017-07-21 10:55:27 -0700484 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700485 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700486 }
487
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700488 if (options_.no_xml_namespaces) {
489 XmlNamespaceRemover namespace_remover;
490 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700491 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800492 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700493 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800494
Adam Lesinskibb94f322017-07-12 07:41:55 -0700495 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700496 return make_singleton_vec(std::move(file_op->xml_to_flatten));
497 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700498
Adam Lesinskibb94f322017-07-12 07:41:55 -0700499 if (options_.no_version_vectors || options_.no_version_transitions) {
500 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700501 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700502 if (el && el->namespace_uri.empty()) {
503 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
504 (options_.no_version_transitions && IsTransitionElement(el->name))) {
505 return make_singleton_vec(std::move(file_op->xml_to_flatten));
506 }
507 }
508 }
509
Adam Lesinskic744ae82017-05-17 19:28:38 -0700510 const ConfigDescription& config = file_op->config;
511 ResourceEntry* entry = file_op->entry;
512
513 XmlCompatVersioner xml_compat_versioner(&rules_);
514 const util::Range<ApiVersion> api_range{config.sdkVersion,
515 FindNextApiVersionForConfig(entry, config)};
516 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800517}
518
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700519bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700520 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700521 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800522
Adam Koskidc21dea2017-07-21 10:55:27 -0700523 proguard::CollectResourceReferences(context_, table, keep_set_);
524
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700525 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700526 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
527
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700528 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700529 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700530 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700531 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800532
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533 // Populate the queue with all files in the ResourceTable.
534 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700535 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700536 // WARNING! Do not insert or remove any resources while executing in this scope. It will
537 // corrupt the iteration order.
538
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700539 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700540 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700541 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700542 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700543
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700544 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700545 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700548 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 }
550
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700551 FileOperation file_op;
552 file_op.entry = entry.get();
553 file_op.dst_path = *file_ref->path;
554 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700555 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700556
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700558 (file_ref->type == ResourceFile::Type::kBinaryXml ||
559 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700560 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700561 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700562 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563 << "failed to open file");
564 return false;
565 }
566
Adam Lesinski00451162017-10-03 07:44:08 -0700567 if (file_ref->type == ResourceFile::Type::kProtoXml) {
568 pb::XmlNode pb_xml_node;
569 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
570 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700571 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700572 return false;
573 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574
Adam Lesinski00451162017-10-03 07:44:08 -0700575 std::string error;
576 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
577 if (file_op.xml_to_flatten == nullptr) {
578 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700579 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700580 return false;
581 }
582 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700583 std::string error_str;
584 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700585 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700586 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
587 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700588 return false;
589 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700590 }
591
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700592 file_op.xml_to_flatten->file.config = config_value->config;
593 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700594 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700595 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700596
597 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
598 // else we end up copying the string in the std::make_pair() method,
599 // then creating a StringPiece from the copy, which would cause us
600 // to end up referencing garbage in the map.
601 const StringPiece entry_name(entry->name);
602 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
603 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700604 }
605 }
606
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700607 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700608 for (auto& map_entry : config_sorted_files) {
609 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700610 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700611
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700612 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700613 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
614 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700615 if (versioned_docs.empty()) {
616 error = true;
617 continue;
618 }
619
Adam Lesinskic744ae82017-05-17 19:28:38 -0700620 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
621 std::string dst_path = file_op.dst_path;
622 if (doc->file.config != file_op.config) {
623 // Only add the new versioned configurations.
624 if (context_->IsVerbose()) {
625 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
626 << "auto-versioning resource from config '"
627 << config << "' -> '" << doc->file.config << "'");
628 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700629
Adam Lesinskic744ae82017-05-17 19:28:38 -0700630 dst_path =
631 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
632 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
633 doc->file.source, dst_path, nullptr,
634 context_->GetDiagnostics());
635 if (!result) {
636 return false;
637 }
638 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700639
640 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
641 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700642 }
643 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700644 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
645 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700646 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700647 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700648 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649 }
650 return !error;
651}
652
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700653static bool WriteStableIdMapToPath(IDiagnostics* diag,
654 const std::unordered_map<ResourceName, ResourceId>& id_map,
655 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800656 io::FileOutputStream fout(id_map_path);
657 if (fout.HadError()) {
658 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 return false;
660 }
661
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800662 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700663 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700664 const ResourceName& name = entry.first;
665 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800666 printer.Print(name.to_string());
667 printer.Print(" = ");
668 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700669 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800670 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700671
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800672 if (fout.HadError()) {
673 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700674 return false;
675 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 return true;
677}
678
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700679static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
680 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700682 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700683 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700684 return false;
685 }
686
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700687 out_id_map->clear();
688 size_t line_no = 0;
689 for (StringPiece line : util::Tokenize(content, '\n')) {
690 line_no++;
691 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700692 if (line.empty()) {
693 continue;
694 }
695
696 auto iter = std::find(line.begin(), line.end(), '=');
697 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700698 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700699 return false;
700 }
701
702 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700703 StringPiece res_name_str =
704 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
705 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700706 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
707 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708 return false;
709 }
710
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700711 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
712 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700713 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700714
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700715 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
716 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700717 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
718 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700719 return false;
720 }
721
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700722 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700723 }
724 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700725}
726
Adam Lesinskifb48d292015-11-07 15:52:13 -0800727class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700728 public:
729 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700730 : options_(options),
731 context_(context),
732 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700733 file_collection_(util::make_unique<io::FileCollection>()) {
734 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700735
Adam Lesinski8780eb62017-10-31 17:44:39 -0700736 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700737 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700738 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 for (const std::string& path : options_.include_paths) {
740 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700741 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700743
Adam Lesinski8780eb62017-10-31 17:44:39 -0700744 std::string error;
745 auto zip_collection = io::ZipFileCollection::Create(path, &error);
746 if (zip_collection == nullptr) {
747 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
748 return false;
749 }
750
751 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
752 // Load this as a static library include.
753 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
754 Source(path), std::move(zip_collection), context_->GetDiagnostics());
755 if (static_apk == nullptr) {
756 return false;
757 }
758
Adam Lesinskib522f042017-04-21 16:57:59 -0700759 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800760 // Can't include static libraries when not building a static library (they have no IDs
761 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700762 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800763 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700764 return false;
765 }
766
Adam Lesinski8780eb62017-10-31 17:44:39 -0700767 ResourceTable* table = static_apk->GetResourceTable();
768
769 // If we are using --no-static-lib-packages, we need to rename the package of this table to
770 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700771 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800772 // Since package names can differ, and multiple packages can exist in a ResourceTable,
773 // we place the requirement that all static libraries are built with the package
774 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700775 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700776 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800777 } else {
778 context_->GetDiagnostics()->Error(DiagMessage(path)
779 << "no package with ID 0x7f found in static library");
780 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700781 }
782 }
783
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700784 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700785 util::make_unique<ResourceTableSymbolSource>(table));
786 static_library_includes_.push_back(std::move(static_apk));
787 } else {
788 if (!asset_source->AddAssetPath(path)) {
789 context_->GetDiagnostics()->Error(DiagMessage()
790 << "failed to load include path " << path);
791 return false;
792 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700793 }
794 }
795
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800796 // Capture the shared libraries so that the final resource table can be properly flattened
797 // with support for shared libraries.
798 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800799 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800800 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinski490595a2017-11-07 17:08:07 -0800801 } else if (entry.first == kAppPackageId) {
802 // Capture the included base feature package.
803 included_feature_base_ = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800804 }
805 }
806
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700807 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700808 return true;
809 }
810
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800811 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700812 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800813 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
814 if (manifest_el == nullptr) {
815 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700816 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800817
818 AppInfo app_info;
819
820 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
821 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
822 return {};
823 }
824
825 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
826 if (!package_attr) {
827 diag->Error(DiagMessage(xml_res->file.source)
828 << "<manifest> must have a 'package' attribute");
829 return {};
830 }
831 app_info.package = package_attr->value;
832
833 if (xml::Attribute* version_code_attr =
834 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
835 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
836 if (!maybe_code) {
837 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
838 << "invalid android:versionCode '" << version_code_attr->value << "'");
839 return {};
840 }
841 app_info.version_code = maybe_code.value();
842 }
843
844 if (xml::Attribute* revision_code_attr =
845 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
846 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
847 if (!maybe_code) {
848 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
849 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
850 return {};
851 }
852 app_info.revision_code = maybe_code.value();
853 }
854
855 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
856 if (!split_name_attr->value.empty()) {
857 app_info.split_name = split_name_attr->value;
858 }
859 }
860
861 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
862 if (xml::Attribute* min_sdk =
863 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700864 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800865 }
866 }
867 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700868 }
869
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700870 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
871 // Postcondition: ResourceTable has only one package left. All others are
872 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700873 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700874 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700875 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
876 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700877 };
878
879 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700880 for (const auto& package : final_table_.packages) {
881 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700882 // We have a package that is not related to the one we're building!
883 for (const auto& type : package->types) {
884 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700885 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700886
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700887 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700888 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700889 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700890 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
891 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
892 << "generated id '" << res_name
893 << "' for external package '" << package->name
894 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700895 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700896 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
897 << "defined resource '" << res_name
898 << "' for external package '" << package->name
899 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700900 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700901 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700902 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700903 }
904 }
905 }
906 }
907
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700908 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
909 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700910 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700911 return !error;
912 }
913
914 /**
915 * Returns true if no IDs have been set, false otherwise.
916 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700917 bool VerifyNoIdsSet() {
918 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700919 for (const auto& type : package->types) {
920 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800921 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
922 << StringPrintf("%02x", type->id.value())
923 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700924 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700925 }
926
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700927 for (const auto& entry : type->entries) {
928 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700929 ResourceNameRef res_name(package->name, type->type, entry->name);
930 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800931 DiagMessage() << "entry " << res_name << " has ID "
932 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700933 return false;
934 }
935 }
936 }
937 }
938 return true;
939 }
940
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700941 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
942 if (options_.output_to_directory) {
943 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700944 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700945 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700946 }
947 }
948
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700949 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
950 switch (format) {
951 case OutputFormat::kApk: {
952 BigBuffer buffer(1024);
953 TableFlattener flattener(options_.table_flattener_options, &buffer);
954 if (!flattener.Consume(context_, table)) {
955 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
956 return false;
957 }
958
959 io::BigBufferInputStream input_stream(&buffer);
960 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
961 ArchiveEntry::kAlign, writer);
962 } break;
963
964 case OutputFormat::kProto: {
965 pb::ResourceTable pb_table;
966 SerializeTableToPb(*table, &pb_table);
967 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
968 ArchiveEntry::kCompress, writer);
969 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700970 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700971 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700972 }
973
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700974 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700975 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700976 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700977 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700978 return true;
979 }
980
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700981 std::string out_path = options_.generate_java_class_path.value();
982 file::AppendPath(&out_path, file::PackageToPath(out_package));
983 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700984 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
985 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700986 return false;
987 }
988
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700989 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700990
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800991 io::FileOutputStream fout(out_path);
992 if (fout.HadError()) {
993 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
994 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700995 return false;
996 }
997
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800998 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -0700999 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001000 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1001 if (fout_text->HadError()) {
1002 context_->GetDiagnostics()->Error(DiagMessage()
1003 << "failed writing to '" << out_text_symbols_path.value()
1004 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001005 return false;
1006 }
1007 }
1008
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001009 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -07001010 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001011 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001012 return false;
1013 }
1014
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001015 fout.Flush();
1016
1017 if (fout.HadError()) {
1018 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1019 << "': " << fout.GetError());
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001020 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001021 }
1022 return true;
1023 }
1024
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001025 bool GenerateJavaClasses() {
1026 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1027 std::vector<std::string> packages_to_callback;
1028
1029 JavaClassGeneratorOptions template_options;
1030 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1031 template_options.javadoc_annotations = options_.javadoc_annotations;
1032
1033 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1034 template_options.use_final = false;
1035 }
1036
1037 if (context_->GetPackageType() == PackageType::kSharedLib) {
1038 template_options.use_final = false;
1039 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1040 }
1041
1042 const StringPiece actual_package = context_->GetCompilationPackage();
1043 StringPiece output_package = context_->GetCompilationPackage();
1044 if (options_.custom_java_package) {
1045 // Override the output java package to the custom one.
1046 output_package = options_.custom_java_package.value();
1047 }
1048
1049 // Generate the private symbols if required.
1050 if (options_.private_symbols) {
1051 packages_to_callback.push_back(options_.private_symbols.value());
1052
1053 // If we defined a private symbols package, we only emit Public symbols
1054 // to the original package, and private and public symbols to the private package.
1055 JavaClassGeneratorOptions options = template_options;
1056 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1057 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1058 options)) {
1059 return false;
1060 }
1061 }
1062
1063 // Generate copies of the original package R class but with different package names.
1064 // This is to support non-namespaced builds.
1065 for (const std::string& extra_package : options_.extra_java_packages) {
1066 packages_to_callback.push_back(extra_package);
1067
1068 JavaClassGeneratorOptions options = template_options;
1069 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1070 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1071 return false;
1072 }
1073 }
1074
1075 // Generate R classes for each package that was merged (static library).
1076 // Use the actual package's resources only.
1077 for (const std::string& package : table_merger_->merged_packages()) {
1078 packages_to_callback.push_back(package);
1079
1080 JavaClassGeneratorOptions options = template_options;
1081 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1082 if (!WriteJavaFile(&final_table_, package, package, options)) {
1083 return false;
1084 }
1085 }
1086
1087 // Generate the main public R class.
1088 JavaClassGeneratorOptions options = template_options;
1089
1090 // Only generate public symbols if we have a private package.
1091 if (options_.private_symbols) {
1092 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1093 }
1094
1095 if (options.rewrite_callback_options) {
1096 options.rewrite_callback_options.value().packages_to_callback =
1097 std::move(packages_to_callback);
1098 }
1099
1100 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1101 options_.generate_text_symbols_path)) {
1102 return false;
1103 }
1104
1105 return true;
1106 }
1107
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001108 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1109 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001110 return true;
1111 }
1112
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001113 std::unique_ptr<ClassDefinition> manifest_class =
1114 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001115
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001116 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001117 // Something bad happened, but we already logged it, so exit.
1118 return false;
1119 }
1120
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001121 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001122 // Empty Manifest class, no need to generate it.
1123 return true;
1124 }
1125
1126 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001127 for (const std::string& annotation : options_.javadoc_annotations) {
1128 std::string proper_annotation = "@";
1129 proper_annotation += annotation;
1130 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001131 }
1132
Adam Lesinski0d81f702017-06-27 15:51:09 -07001133 const std::string package_utf8 =
1134 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001135
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001136 std::string out_path = options_.generate_java_class_path.value();
1137 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001138
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001139 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001140 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1141 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001142 return false;
1143 }
1144
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001145 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001146
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001147 io::FileOutputStream fout(out_path);
1148 if (fout.HadError()) {
1149 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1150 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001151 return false;
1152 }
1153
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001154 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1155 fout.Flush();
1156
1157 if (fout.HadError()) {
1158 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1159 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001160 return false;
1161 }
1162 return true;
1163 }
1164
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001165 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001166 if (!out) {
1167 return true;
1168 }
1169
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001170 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001171 io::FileOutputStream fout(out_path);
1172 if (fout.HadError()) {
1173 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1174 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001175 return false;
1176 }
1177
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001178 proguard::WriteKeepSet(keep_set, &fout);
1179 fout.Flush();
1180
1181 if (fout.HadError()) {
1182 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1183 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001184 return false;
1185 }
1186 return true;
1187 }
1188
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001189 bool MergeStaticLibrary(const std::string& input, bool override) {
1190 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001191 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001192 }
1193
Adam Lesinski8780eb62017-10-31 17:44:39 -07001194 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1195 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001196 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001197 return false;
1198 }
1199
Adam Lesinski8780eb62017-10-31 17:44:39 -07001200 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001201 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001203 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001204 return false;
1205 }
1206
1207 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001208 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001209 // Merge all resources as if they were in the compilation package. This is the old behavior
1210 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001211
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001212 // Add the package to the set of --extra-packages so we emit an R.java for each library
1213 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001215 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001216 }
1217
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001218 // Clear the package name, so as to make the resources look like they are coming from the
1219 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001220 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001221 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001222
1223 } else {
1224 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001225 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001226 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001227 }
1228
1229 if (!result) {
1230 return false;
1231 }
1232
1233 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001234 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235 return true;
1236 }
1237
Adam Lesinski00451162017-10-03 07:44:08 -07001238 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001239 if (context_->IsVerbose()) {
Adam Lesinski00451162017-10-03 07:44:08 -07001240 context_->GetDiagnostics()->Note(DiagMessage()
1241 << "merging '" << compiled_file.name
1242 << "' from compiled file " << compiled_file.source);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001243 }
1244
Adam Lesinski00451162017-10-03 07:44:08 -07001245 if (!table_merger_->MergeFile(compiled_file, override, file)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001246 return false;
1247 }
1248
1249 // Add the exports of this file to the table.
Adam Lesinski00451162017-10-03 07:44:08 -07001250 for (const SourcedResourceName& exported_symbol : compiled_file.exported_symbols) {
1251 ResourceName res_name = exported_symbol.name;
1252 if (res_name.package.empty()) {
1253 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001254 }
1255
Adam Lesinski00451162017-10-03 07:44:08 -07001256 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001257 if (mangled_name) {
1258 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259 }
1260
1261 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski00451162017-10-03 07:44:08 -07001262 id->SetSource(compiled_file.source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001263 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001264 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1265 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001266 if (!result) {
1267 return false;
1268 }
1269 }
1270 return true;
1271 }
1272
Adam Lesinski00451162017-10-03 07:44:08 -07001273 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1274 // If override is true, conflicting resources are allowed to override each other, in order of last
1275 // seen.
1276 // An io::IFileCollection is created from the ZIP file and added to the set of
1277 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001278 bool MergeArchive(const std::string& input, bool override) {
1279 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001280 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 }
1282
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001283 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001284 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001285 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001286 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001287 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 return false;
1289 }
1290
1291 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001292 for (auto iter = collection->Iterator(); iter->HasNext();) {
1293 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 error = true;
1295 }
1296 }
1297
1298 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001299 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001300 return !error;
1301 }
1302
Adam Lesinski00451162017-10-03 07:44:08 -07001303 // Takes a path to load and merge into the master ResourceTable. If override is true,
1304 // conflicting resources are allowed to override each other, in order of last seen.
1305 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1306 // as ZIP archive and the files within are merged individually.
1307 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001308 bool MergePath(const std::string& path, bool override) {
1309 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1310 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1311 return MergeArchive(path, override);
1312 } else if (util::EndsWith(path, ".apk")) {
1313 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001314 }
1315
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001316 io::IFile* file = file_collection_->InsertFile(path);
1317 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001318 }
1319
Adam Lesinski00451162017-10-03 07:44:08 -07001320 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1321 // If override is true, conflicting resources are allowed to override each other, in order of last
1322 // seen.
1323 // All other file types are ignored. This is because these files could be coming from a zip,
1324 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001325 bool MergeFile(io::IFile* file, bool override) {
1326 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001327
Adam Lesinski00451162017-10-03 07:44:08 -07001328 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001329 // Since AAPT compiles these file types and appends .flat to them, seeing
1330 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001331 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1332 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1333 << " file passed as argument. Must be "
1334 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001335 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001336 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1337 if (context_->IsVerbose()) {
1338 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1339 return true;
1340 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001341 }
1342
Adam Lesinski00451162017-10-03 07:44:08 -07001343 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1344 if (input_stream == nullptr) {
1345 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1346 return false;
1347 }
1348
1349 if (input_stream->HadError()) {
1350 context_->GetDiagnostics()->Error(DiagMessage(src)
1351 << "failed to open file: " << input_stream->GetError());
1352 return false;
1353 }
1354
1355 ContainerReaderEntry* entry;
1356 ContainerReader reader(input_stream.get());
1357 while ((entry = reader.Next()) != nullptr) {
1358 if (entry->Type() == ContainerEntryType::kResTable) {
1359 pb::ResourceTable pb_table;
1360 if (!entry->GetResTable(&pb_table)) {
1361 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1362 << entry->GetError());
1363 return false;
1364 }
1365
1366 ResourceTable table;
1367 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001368 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001369 context_->GetDiagnostics()->Error(DiagMessage(src)
1370 << "failed to deserialize resource table: " << error);
1371 return false;
1372 }
1373
1374 if (!table_merger_->Merge(src, &table, override)) {
1375 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1376 return false;
1377 }
1378 } else if (entry->Type() == ContainerEntryType::kResFile) {
1379 pb::internal::CompiledFile pb_compiled_file;
1380 off64_t offset;
1381 size_t len;
1382 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1383 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1384 << entry->GetError());
1385 return false;
1386 }
1387
1388 ResourceFile resource_file;
1389 std::string error;
1390 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1391 context_->GetDiagnostics()->Error(DiagMessage(src)
1392 << "failed to read compiled header: " << error);
1393 return false;
1394 }
1395
1396 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1397 return false;
1398 }
1399 }
1400 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001401 return true;
1402 }
1403
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001404 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1405 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1406 for (const std::string& assets_dir : options_.assets_dirs) {
1407 Maybe<std::vector<std::string>> files =
1408 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1409 if (!files) {
1410 return false;
1411 }
1412
1413 for (const std::string& file : files.value()) {
1414 std::string full_key = "assets/" + file;
1415 std::string full_path = assets_dir;
1416 file::AppendPath(&full_path, file);
1417
1418 auto iter = merged_assets.find(full_key);
1419 if (iter == merged_assets.end()) {
1420 merged_assets.emplace(std::move(full_key),
1421 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1422 } else if (context_->IsVerbose()) {
1423 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1424 << "asset file overrides '" << full_path << "'");
1425 }
1426 }
1427 }
1428
1429 for (auto& entry : merged_assets) {
1430 uint32_t compression_flags = ArchiveEntry::kCompress;
1431 std::string extension = file::GetExtension(entry.first).to_string();
1432 if (options_.extensions_to_not_compress.count(extension) > 0) {
1433 compression_flags = 0u;
1434 }
1435
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001436 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1437 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001438 return false;
1439 }
1440 }
1441 return true;
1442 }
1443
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001444 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1445 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001446 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1447 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001448 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001449 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1450 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001451 if (!result) {
1452 return false;
1453 }
1454
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001455 ResourceFileFlattenerOptions file_flattener_options;
1456 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001457 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1458 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001459 file_flattener_options.no_auto_version = options_.no_auto_version;
1460 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001461 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001462 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1463 file_flattener_options.update_proguard_spec =
1464 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001465 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001466
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001467 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001468
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001469 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001470 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001471 return false;
1472 }
1473
Adam Lesinski490595a2017-11-07 17:08:07 -08001474 // Hack to fix b/68820737.
1475 // We need to modify the ResourceTable's package name, but that should NOT affect
1476 // anything else being generated, which includes the Java classes.
1477 // If required, the package name is modifed before flattening, and then modified back
1478 // to its original name.
1479 ResourceTablePackage* package_to_rewrite = nullptr;
1480 if (context_->GetPackageId() > kAppPackageId &&
1481 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1482 // The base APK is included, and this is a feature split. If the base package is
1483 // the same as this package, then we are building an old style Android Instant Apps feature
1484 // split and must apply this workaround to avoid requiring namespaces support.
1485 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1486 if (package_to_rewrite != nullptr) {
1487 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1488
1489 std::string new_package_name =
1490 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1491 app_info_.split_name.value_or_default("feature").c_str());
1492
1493 if (context_->IsVerbose()) {
1494 context_->GetDiagnostics()->Note(
1495 DiagMessage() << "rewriting resource package name for feature split to '"
1496 << new_package_name << "'");
1497 }
1498 package_to_rewrite->name = new_package_name;
1499 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001500 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001501
1502 bool success = FlattenTable(table, options_.output_format, writer);
1503
1504 if (package_to_rewrite != nullptr) {
1505 // Change the name back.
1506 package_to_rewrite->name = context_->GetCompilationPackage();
1507 if (package_to_rewrite->id) {
1508 table->included_packages_.erase(package_to_rewrite->id.value());
1509 }
1510 }
1511
1512 if (!success) {
1513 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1514 }
1515 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001516 }
1517
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001518 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001519 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001520 std::unique_ptr<xml::XmlResource> manifest_xml =
1521 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1522 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001523 return 1;
1524 }
1525
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001526 // First extract the Package name without modifying it (via --rename-manifest-package).
1527 if (Maybe<AppInfo> maybe_app_info =
1528 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001529 const AppInfo& app_info = maybe_app_info.value();
1530 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001531 }
1532
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001533 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1534 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001535 return 1;
1536 }
1537
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001538 Maybe<AppInfo> maybe_app_info =
1539 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001540 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001541 return 1;
1542 }
1543
Adam Lesinski490595a2017-11-07 17:08:07 -08001544 app_info_ = maybe_app_info.value();
1545 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001546
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001547 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001548
1549 // Override the package ID when it is "android".
1550 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001551 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001552
1553 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001554 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001555 context_->GetDiagnostics()->Error(
1556 DiagMessage() << "package 'android' can only be built as a regular app");
1557 return 1;
1558 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001559 }
1560
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001561 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001562 return 1;
1563 }
1564
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001565 TableMergerOptions table_merger_options;
1566 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001567 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001568
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001569 if (context_->IsVerbose()) {
1570 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001571 << StringPrintf("linking package '%s' using package ID %02x",
1572 context_->GetCompilationPackage().data(),
1573 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001574 }
1575
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001576 for (const std::string& input : input_files) {
1577 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001578 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001579 return 1;
1580 }
1581 }
1582
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001583 for (const std::string& input : options_.overlay_files) {
1584 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001585 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001586 return 1;
1587 }
1588 }
1589
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001590 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001591 return 1;
1592 }
1593
Adam Lesinskib522f042017-04-21 16:57:59 -07001594 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001596 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001597 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001598 return 1;
1599 }
1600
1601 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001602 IdAssigner id_assigner(&options_.stable_id_map);
1603 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001604 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001605 return 1;
1606 }
1607
1608 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001609 if (options_.resource_id_map_path) {
1610 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001611 for (auto& type : package->types) {
1612 for (auto& entry : type->entries) {
1613 ResourceName name(package->name, type->type, entry->name);
1614 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001615 options_.stable_id_map[std::move(name)] =
1616 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001617 }
1618 }
1619 }
1620
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001621 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001622 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001623 return 1;
1624 }
1625 }
1626 } else {
1627 // Static libs are merged with other apps, and ID collisions are bad, so
1628 // verify that
1629 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001630 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001631 return 1;
1632 }
1633 }
1634
1635 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001636 context_->SetNameManglerPolicy(
1637 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001638
1639 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001640 context_->GetExternalSymbols()->PrependSource(
1641 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001642
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001643 // Workaround for pre-O runtime that would treat negative resource IDs
1644 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1645 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1646 // are just identifiers.
1647 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1648 if (context_->IsVerbose()) {
1649 context_->GetDiagnostics()->Note(DiagMessage()
1650 << "enabling pre-O feature split ID rewriting");
1651 }
1652 context_->GetExternalSymbols()->SetDelegate(
1653 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1654 }
1655
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001656 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001657 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001658 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001659 return 1;
1660 }
1661
Adam Lesinskib522f042017-04-21 16:57:59 -07001662 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001663 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001664 context_->GetDiagnostics()->Warn(DiagMessage()
1665 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001666 }
1667 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001668 ProductFilter product_filter(options_.products);
1669 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001670 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001671 return 1;
1672 }
1673 }
1674
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001675 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001676 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001677 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001678 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001679 return 1;
1680 }
1681 }
1682
Adam Lesinskib522f042017-04-21 16:57:59 -07001683 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001684 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001685 context_->GetDiagnostics()->Note(DiagMessage()
1686 << "collapsing resource versions for minimum SDK "
1687 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001688 }
1689
1690 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001691 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001692 return 1;
1693 }
1694 }
1695
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001696 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001698 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001699 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001700 return 1;
1701 }
1702 }
1703
Adam Koskidc21dea2017-07-21 10:55:27 -07001704 proguard::KeepSet proguard_keep_set =
1705 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001706 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001707
Adam Lesinskib522f042017-04-21 16:57:59 -07001708 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001709 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001710 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001711 context_->GetDiagnostics()->Warn(DiagMessage()
1712 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001713 }
1714 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001715 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1716 // equal to the minSdk.
1717 options_.split_constraints =
1718 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001719
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001720 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001721 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001722 return 1;
1723 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001724 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001725
1726 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001727 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001728 auto split_constraints_iter = options_.split_constraints.begin();
1729 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001730 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001731 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1732 << "generating split with configurations '"
1733 << util::Joiner(split_constraints_iter->configs, ", ")
1734 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001735 }
1736
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001737 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001738 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001739 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001740 return 1;
1741 }
1742
1743 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001744 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001745 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001746
1747 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001749 context_->GetDiagnostics()->Error(DiagMessage()
1750 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001751 return 1;
1752 }
1753
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001754 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1755 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001756 return 1;
1757 }
1758
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001759 ++path_iter;
1760 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001761 }
1762 }
1763
1764 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001765 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001766 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001767 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001768 return 1;
1769 }
1770
1771 bool error = false;
1772 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001773 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001774 // (aka, which package the AndroidManifest.xml is coming from).
1775 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001776 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001777
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001778 XmlReferenceLinker manifest_linker;
1779 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1780 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001781 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001782 error = true;
1783 }
1784
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001785 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001786 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001787 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001788 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001789 }
1790
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001791 if (options_.generate_java_class_path) {
1792 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001793 error = true;
1794 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001795 }
1796
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001797 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001798 // PackageParser will fail if URIs are removed from
1799 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001800 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1801 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001802 error = true;
1803 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001804 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001805 } else {
1806 error = true;
1807 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001808 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001809
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001810 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001811 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001812 return 1;
1813 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001814
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001815 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1816 return 1;
1817 }
1818
1819 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001820 return 1;
1821 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001822
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001823 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001824 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001825 return 1;
1826 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001827 }
1828
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001829 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001830 return 1;
1831 }
1832
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001833 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1834 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001835 return 1;
1836 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001837 return 0;
1838 }
1839
1840 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001841 LinkOptions options_;
1842 LinkContext* context_;
1843 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001844
Adam Lesinski490595a2017-11-07 17:08:07 -08001845 AppInfo app_info_;
1846
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848
1849 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001850 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001851
Adam Lesinski8780eb62017-10-31 17:44:39 -07001852 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001853 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001855
Adam Lesinski8780eb62017-10-31 17:44:39 -07001856 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1857 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1858
1859 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1860 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001861
1862 // The set of shared libraries being used, mapping their assigned package ID to package name.
1863 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08001864
1865 // The package name of the base application, if it is included.
1866 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001867};
1868
Chris Warrington820d72a2017-04-27 15:27:01 +01001869int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1870 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001871 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001872 std::vector<std::string> overlay_arg_list;
1873 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001874 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001875 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 Maybe<std::string> preferred_density;
1877 Maybe<std::string> product_list;
1878 bool legacy_x_flag = false;
1879 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001880 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001881 bool shared_lib = false;
1882 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001883 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 Maybe<std::string> stable_id_file_path;
1885 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001886 Flags flags =
1887 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001888 .RequiredFlag("-o", "Output path.", &options.output_path)
1889 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001890 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001891 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001892 .OptionalFlagList("-A",
1893 "An assets directory to include in the APK. These are unprocessed.",
1894 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001895 .OptionalFlagList("-R",
1896 "Compilation unit to link, using `overlay` semantics.\n"
1897 "The last conflicting resource given takes precedence.",
1898 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001899 .OptionalFlag("--package-id",
1900 "Specify the package ID to use for this app. Must be greater or equal to\n"
1901 "0x7f and can't be used with --static-lib or --shared-lib.",
1902 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001903 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001906 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001907 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001908 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001909 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07001910 .OptionalSwitch("--proguard-conditional-keep-rules",
1911 "Generate conditional Proguard keep rules.",
1912 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001913 .OptionalSwitch("--no-auto-version",
1914 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001915 &options.no_auto_version)
1916 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001917 "Disables automatic versioning of vector drawables. Use this only\n"
1918 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001919 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001920 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001921 "Disables automatic versioning of transition resources. Use this only\n"
1922 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001923 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001924 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001925 "Disables automatic deduping of resources with\n"
1926 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001927 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001928 .OptionalSwitch("--enable-sparse-encoding",
1929 "Enables encoding sparse entries using a binary search tree.\n"
1930 "This decreases APK size at the cost of resource retrieval performance.",
1931 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001932 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001933 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001934 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001935 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001936 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001937 "Comma separated list of configurations to include. The default\n"
1938 "is all configurations.",
1939 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001940 .OptionalFlag("--preferred-density",
1941 "Selects the closest matching density and strips out all others.",
1942 &preferred_density)
1943 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001944 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001945 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001946 &options.output_to_directory)
1947 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001948 "Removes XML namespace prefix and URI information from\n"
1949 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001950 &options.no_xml_namespaces)
1951 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001952 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001953 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001954 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001955 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001956 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001957 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001958 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1959 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001960 &options.manifest_fixer_options.version_code_default)
1961 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001962 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001963 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001964 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1965 &shared_lib)
1966 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001967 .OptionalSwitch("--proto-format",
1968 "Generates compiled resources in Protobuf format.\n"
1969 "Suitable as input to the bundle tool for generating an App Bundle.",
1970 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001971 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001972 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001973 &options.no_static_lib_packages)
1974 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001975 "Generates R.java without the final modifier. This is implied when\n"
1976 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001977 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001978 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001979 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001980 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001981 "Emit a file at the given path with a list of name to ID mappings,\n"
1982 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001983 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001984 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001985 "Package name to use when generating R.java for private symbols.\n"
1986 "If not specified, public and private symbols will use the application's\n"
1987 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001989 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001990 &options.custom_java_package)
1991 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001992 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001993 &extra_java_packages)
1994 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001995 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001997 .OptionalFlag("--output-text-symbols",
1998 "Generates a text file containing the resource symbols of the R class in\n"
1999 "the specified folder.",
2000 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002001 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002002 "Allows the addition of new resources in overlays without\n"
2003 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002004 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002005 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002006 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002007 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002008 "Changes the name of the target package for instrumentation. Most useful\n"
2009 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002010 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002011 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002012 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002013 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002014 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002015 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2016 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002017 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002018 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002019
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002020 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002021 return 1;
2022 }
2023
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002024 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002025 std::vector<std::string> arg_list;
2026 for (const std::string& arg : flags.GetArgs()) {
2027 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002028 const std::string path = arg.substr(1, arg.size() - 1);
2029 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002030 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2031 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002032 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002033 }
2034 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002035 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002036 }
2037 }
2038
2039 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002040 for (const std::string& arg : overlay_arg_list) {
2041 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002042 const std::string path = arg.substr(1, arg.size() - 1);
2043 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002044 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2045 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002046 return 1;
2047 }
2048 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002049 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002050 }
2051 }
2052
2053 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002054 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002055 }
2056
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002057 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2058 context.GetDiagnostics()->Error(
2059 DiagMessage()
2060 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002061 return 1;
2062 }
2063
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002064 // The default build type.
2065 context.SetPackageType(PackageType::kApp);
2066 context.SetPackageId(kAppPackageId);
2067
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002068 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002069 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002070 context.SetPackageId(0x00);
2071 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002072 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002073 options.output_format = OutputFormat::kProto;
2074 } else if (proto_format) {
2075 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002076 }
2077
2078 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002079 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002080 context.GetDiagnostics()->Error(
2081 DiagMessage() << "can't specify --package-id when not building a regular app");
2082 return 1;
2083 }
2084
2085 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2086 if (!maybe_package_id_int) {
2087 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2088 << "' is not a valid integer");
2089 return 1;
2090 }
2091
2092 const uint32_t package_id_int = maybe_package_id_int.value();
2093 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2094 context.GetDiagnostics()->Error(
2095 DiagMessage() << StringPrintf(
2096 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2097 return 1;
2098 }
2099 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2100 }
2101
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002102 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002103 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002104 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002105 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002106 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 }
2108 }
2109
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002110 if (product_list) {
2111 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002112 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002113 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002114 }
2115 }
2116 }
2117
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002118 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002119 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002120 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2121 if (filter == nullptr) {
2122 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002123 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002124 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002125 }
2126
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002128 Maybe<uint16_t> density =
2129 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2130 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002131 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002132 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002133 options.table_splitter_options.preferred_densities.push_back(density.value());
2134 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002135
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002136 // Parse the split parameters.
2137 for (const std::string& split_arg : split_args) {
2138 options.split_paths.push_back({});
2139 options.split_constraints.push_back({});
2140 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2141 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002142 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002143 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002144 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002145
Adam Lesinskib522f042017-04-21 16:57:59 -07002146 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002147 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2148 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002149 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002150 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002151 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002152
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002153 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002154 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002155 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2156 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2157 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2158 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2159
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002160 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002161 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002162 options.no_auto_version = true;
2163 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002164 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002165 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002166
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002167 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002168 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002169}
2170
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002171} // namespace aapt