blob: 55a4c438755c628522de271163ccaf182a935895 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Adam Lesinskice5e56e2016-10-21 17:56:45 -070017#include <sys/stat.h>
18
19#include <fstream>
20#include <queue>
21#include <unordered_map>
22#include <vector>
23
24#include "android-base/errors.h"
25#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080026#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080027#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070028
Adam Lesinski1ab598f2015-08-14 14:26:04 -070029#include "AppInfo.h"
30#include "Debug.h"
31#include "Flags.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/BinaryResourceParser.h"
43#include "format/binary/TableFlattener.h"
44#include "format/binary/XmlFlattener.h"
45#include "format/proto/ProtoDeserialize.h"
46#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070047#include "io/BigBufferStream.h"
48#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080049#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070050#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080051#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070052#include "java/JavaClassGenerator.h"
53#include "java/ManifestClassGenerator.h"
54#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070055#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070056#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080057#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070059#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080060#include "optimize/ResourceDeduper.h"
61#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "process/IResourceTableConsumer.h"
63#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080064#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070065#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080066#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070068using ::aapt::io::FileInputStream;
69using ::android::StringPiece;
70using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070071
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072namespace aapt {
73
Adam Lesinskie59f0d82017-10-13 09:36:53 -070074constexpr static const char kApkResourceTablePath[] = "resources.arsc";
75constexpr static const char kProtoResourceTablePath[] = "resources.pb";
76
77enum class OutputFormat {
78 kApk,
79 kProto,
80};
81
Adam Lesinski1ab598f2015-08-14 14:26:04 -070082struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070083 std::string output_path;
84 std::string manifest_path;
85 std::vector<std::string> include_paths;
86 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070087 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070088 bool output_to_directory = false;
89 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070090 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070091
Adam Lesinskicacb28f2016-10-19 12:18:14 -070092 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070093 Maybe<std::string> generate_java_class_path;
94 Maybe<std::string> custom_java_package;
95 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070096 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070097 Maybe<std::string> generate_proguard_rules_path;
98 Maybe<std::string> generate_main_dex_proguard_rules_path;
99 bool generate_non_final_ids = false;
100 std::vector<std::string> javadoc_annotations;
101 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700102
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700103 // Optimizations/features.
104 bool no_auto_version = false;
105 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900106 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700107 bool no_resource_deduping = false;
108 bool no_xml_namespaces = false;
109 bool do_not_compress_anything = false;
110 std::unordered_set<std::string> extensions_to_not_compress;
111
112 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 bool no_static_lib_packages = false;
114
115 // AndroidManifest.xml massaging options.
116 ManifestFixerOptions manifest_fixer_options;
117
118 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700119 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700120
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800121 // Flattening options.
122 TableFlattenerOptions table_flattener_options;
123
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700124 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700125 TableSplitterOptions table_splitter_options;
126 std::vector<SplitConstraints> split_constraints;
127 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700128
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700129 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700130 std::unordered_map<ResourceName, ResourceId> stable_id_map;
131 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700132};
133
Adam Lesinski64587af2016-02-18 18:33:06 -0800134class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700135 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100136 LinkContext(IDiagnostics* diagnostics)
137 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700138 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139
Adam Lesinskib522f042017-04-21 16:57:59 -0700140 PackageType GetPackageType() override {
141 return package_type_;
142 }
143
144 void SetPackageType(PackageType type) {
145 package_type_ = type;
146 }
147
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700148 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100149 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700150 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700151
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700152 NameMangler* GetNameMangler() override {
153 return &name_mangler_;
154 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700155
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700156 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
157 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700158 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800159
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700160 const std::string& GetCompilationPackage() override {
161 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700162 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700163
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700164 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800165 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700166 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800167
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700168 uint8_t GetPackageId() override {
169 return package_id_;
170 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700171
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700172 void SetPackageId(uint8_t id) {
173 package_id_ = id;
174 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800175
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700176 SymbolTable* GetExternalSymbols() override {
177 return &symbols_;
178 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800179
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700180 bool IsVerbose() override {
181 return verbose_;
182 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800183
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700184 void SetVerbose(bool val) {
185 verbose_ = val;
186 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800187
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700188 int GetMinSdkVersion() override {
189 return min_sdk_version_;
190 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700191
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700192 void SetMinSdkVersion(int minSdk) {
193 min_sdk_version_ = minSdk;
194 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700195
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700196 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700197 DISALLOW_COPY_AND_ASSIGN(LinkContext);
198
Adam Lesinskib522f042017-04-21 16:57:59 -0700199 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100200 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700201 NameMangler name_mangler_;
202 std::string compilation_package_;
203 uint8_t package_id_ = 0x0;
204 SymbolTable symbols_;
205 bool verbose_ = false;
206 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700207};
208
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700209// A custom delegate that generates compatible pre-O IDs for use with feature splits.
210// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
211// is interpreted as a negative number. Some verification was wrongly assuming negative values
212// were invalid.
213//
214// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
215// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
216// an overlap exists.
217class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
218 public:
219 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
220 }
221
222 virtual ~FeatureSplitSymbolTableDelegate() = default;
223
224 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
225 const ResourceName& name,
226 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
227 std::unique_ptr<SymbolTable::Symbol> symbol =
228 DefaultSymbolTableDelegate::FindByName(name, sources);
229 if (symbol == nullptr) {
230 return {};
231 }
232
233 // Check to see if this is an 'id' with the target package.
234 if (name.type == ResourceType::kId && symbol->id) {
235 ResourceId* id = &symbol->id.value();
236 if (id->package_id() > kAppPackageId) {
237 // Rewrite the resource ID to be compatible pre-O.
238 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
239
240 // Check that this doesn't overlap another resource.
241 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
242 // The ID overlaps, so log a message (since this is a weird failure) and fail.
243 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
244 << " for pre-O feature split support");
245 return {};
246 }
247
248 if (context_->IsVerbose()) {
249 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
250 << ") -> (" << rewritten_id << ")");
251 }
252
253 *id = rewritten_id;
254 }
255 }
256 return symbol;
257 }
258
259 private:
260 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
261
262 IAaptContext* context_;
263};
264
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700265static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
266 const StringPiece& path, bool keep_raw_values, bool utf16,
267 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700268 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700269 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
270 << (keep_raw_values ? "true" : "false")
271 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700272 }
273
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700274 switch (format) {
275 case OutputFormat::kApk: {
276 BigBuffer buffer(1024);
277 XmlFlattenerOptions options = {};
278 options.keep_raw_values = keep_raw_values;
279 options.use_utf16 = utf16;
280 XmlFlattener flattener(&buffer, options);
281 if (!flattener.Consume(context, &xml_res)) {
282 return false;
283 }
284
285 io::BigBufferInputStream input_stream(&buffer);
286 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
287 ArchiveEntry::kCompress, writer);
288 } break;
289
290 case OutputFormat::kProto: {
291 pb::XmlNode pb_node;
292 SerializeXmlResourceToPb(xml_res, &pb_node);
293 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
294 writer);
295 } break;
296 }
297 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800298}
299
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700300static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
301 size_t len, IDiagnostics* diag) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700302 pb::ResourceTable pb_table;
303 if (!pb_table.ParseFromArray(data, len)) {
304 diag->Error(DiagMessage(source) << "invalid compiled table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700305 return {};
306 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800307
Adam Lesinski8cdca1b2017-09-28 15:50:03 -0700308 std::unique_ptr<ResourceTable> table = util::make_unique<ResourceTable>();
309 std::string error;
310 if (!DeserializeTableFromPb(pb_table, table.get(), &error)) {
311 diag->Error(DiagMessage(source) << "invalid compiled table: " << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700312 return {};
313 }
314 return table;
Adam Lesinski355f2852016-02-13 20:26:45 -0800315}
316
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700317// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700318static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700319 FileInputStream fin(path);
320 if (fin.HadError()) {
321 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700322 return {};
323 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700324 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800325}
326
Adam Lesinski355f2852016-02-13 20:26:45 -0800327struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700328 bool no_auto_version = false;
329 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900330 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700331 bool no_xml_namespaces = false;
332 bool keep_raw_values = false;
333 bool do_not_compress_anything = false;
334 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700335 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700336 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800337};
338
Adam Lesinskic744ae82017-05-17 19:28:38 -0700339// A sampling of public framework resource IDs.
340struct R {
341 struct attr {
342 enum : uint32_t {
343 paddingLeft = 0x010100d6u,
344 paddingRight = 0x010100d8u,
345 paddingHorizontal = 0x0101053du,
346
347 paddingTop = 0x010100d7u,
348 paddingBottom = 0x010100d9u,
349 paddingVertical = 0x0101053eu,
350
351 layout_marginLeft = 0x010100f7u,
352 layout_marginRight = 0x010100f9u,
353 layout_marginHorizontal = 0x0101053bu,
354
355 layout_marginTop = 0x010100f8u,
356 layout_marginBottom = 0x010100fau,
357 layout_marginVertical = 0x0101053cu,
358 };
359 };
360};
361
Adam Lesinski355f2852016-02-13 20:26:45 -0800362class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700363 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700364 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700365 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800366
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700367 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800368
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 private:
370 struct FileOperation {
371 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700372
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700373 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700374 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700375
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700376 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700377 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700378
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700379 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700380 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700381
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700382 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700383 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700384 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800385
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700386 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800387
Adam Lesinskic744ae82017-05-17 19:28:38 -0700388 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
389 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800390
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700391 ResourceFileFlattenerOptions options_;
392 IAaptContext* context_;
393 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700394 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800395};
396
Adam Lesinskic744ae82017-05-17 19:28:38 -0700397ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
398 IAaptContext* context, proguard::KeepSet* keep_set)
399 : options_(options), context_(context), keep_set_(keep_set) {
400 SymbolTable* symm = context_->GetExternalSymbols();
401
402 // Build up the rules for degrading newer attributes to older ones.
403 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
404 // generated from the attribute definitions themselves (b/62028956).
405 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
406 std::vector<ReplacementAttr> replacements{
407 {"paddingLeft", R::attr::paddingLeft,
408 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
409 {"paddingRight", R::attr::paddingRight,
410 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
411 };
412 rules_[R::attr::paddingHorizontal] =
413 util::make_unique<DegradeToManyRule>(std::move(replacements));
414 }
415
416 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
417 std::vector<ReplacementAttr> replacements{
418 {"paddingTop", R::attr::paddingTop,
419 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
420 {"paddingBottom", R::attr::paddingBottom,
421 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
422 };
423 rules_[R::attr::paddingVertical] =
424 util::make_unique<DegradeToManyRule>(std::move(replacements));
425 }
426
427 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
428 std::vector<ReplacementAttr> replacements{
429 {"layout_marginLeft", R::attr::layout_marginLeft,
430 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
431 {"layout_marginRight", R::attr::layout_marginRight,
432 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
433 };
434 rules_[R::attr::layout_marginHorizontal] =
435 util::make_unique<DegradeToManyRule>(std::move(replacements));
436 }
437
438 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
439 std::vector<ReplacementAttr> replacements{
440 {"layout_marginTop", R::attr::layout_marginTop,
441 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
442 {"layout_marginBottom", R::attr::layout_marginBottom,
443 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
444 };
445 rules_[R::attr::layout_marginVertical] =
446 util::make_unique<DegradeToManyRule>(std::move(replacements));
447 }
448}
449
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700450uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
451 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700452 return 0;
453 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800454
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700455 for (const std::string& extension : options_.extensions_to_not_compress) {
456 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700457 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800458 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700459 }
460 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800461}
462
Adam Lesinskibb94f322017-07-12 07:41:55 -0700463static bool IsTransitionElement(const std::string& name) {
464 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
465 name == "changeImageTransform" || name == "changeTransform" ||
466 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
467 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
468 name == "transitionManager";
469}
470
471static bool IsVectorElement(const std::string& name) {
472 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
ztenghuiab2a38c2017-10-13 15:56:08 -0700473 name == "objectAnimator" || name == "gradient";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700474}
475
Adam Lesinskic744ae82017-05-17 19:28:38 -0700476template <typename T>
477std::vector<T> make_singleton_vec(T&& val) {
478 std::vector<T> vec;
479 vec.emplace_back(std::forward<T>(val));
480 return vec;
481}
482
483std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
484 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700485 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700486 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700487
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700488 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700489 context_->GetDiagnostics()->Note(DiagMessage()
490 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700491 }
492
Adam Lesinski00451162017-10-03 07:44:08 -0700493 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
494 // that existing projects have out-of-date references which pass compilation.
495 xml::StripAndroidStudioAttributes(doc->root.get());
496
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700497 XmlReferenceLinker xml_linker;
498 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700499 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700500 }
501
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700502 if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700503 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700504 }
505
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700506 if (options_.no_xml_namespaces) {
507 XmlNamespaceRemover namespace_remover;
508 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700509 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800510 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700511 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800512
Adam Lesinskibb94f322017-07-12 07:41:55 -0700513 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700514 return make_singleton_vec(std::move(file_op->xml_to_flatten));
515 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700516
Adam Lesinskibb94f322017-07-12 07:41:55 -0700517 if (options_.no_version_vectors || options_.no_version_transitions) {
518 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700519 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700520 if (el && el->namespace_uri.empty()) {
521 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
522 (options_.no_version_transitions && IsTransitionElement(el->name))) {
523 return make_singleton_vec(std::move(file_op->xml_to_flatten));
524 }
525 }
526 }
527
Adam Lesinskic744ae82017-05-17 19:28:38 -0700528 const ConfigDescription& config = file_op->config;
529 ResourceEntry* entry = file_op->entry;
530
531 XmlCompatVersioner xml_compat_versioner(&rules_);
532 const util::Range<ApiVersion> api_range{config.sdkVersion,
533 FindNextApiVersionForConfig(entry, config)};
534 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800535}
536
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700537bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700539 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800540
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700542 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
543
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700545 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700547 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800548
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 // Populate the queue with all files in the ResourceTable.
550 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700551 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700552 // WARNING! Do not insert or remove any resources while executing in this scope. It will
553 // corrupt the iteration order.
554
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700555 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700556 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700557 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700559
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700560 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700561 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700562 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700564 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 }
566
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700567 FileOperation file_op;
568 file_op.entry = entry.get();
569 file_op.dst_path = *file_ref->path;
570 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700571 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700574 (file_ref->type == ResourceFile::Type::kBinaryXml ||
575 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700576 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700577 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700578 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700579 << "failed to open file");
580 return false;
581 }
582
Adam Lesinski00451162017-10-03 07:44:08 -0700583 if (file_ref->type == ResourceFile::Type::kProtoXml) {
584 pb::XmlNode pb_xml_node;
585 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
586 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
587 << "failed to parse proto xml");
588 return false;
589 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700590
Adam Lesinski00451162017-10-03 07:44:08 -0700591 std::string error;
592 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
593 if (file_op.xml_to_flatten == nullptr) {
594 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
595 << "failed to deserialize proto xml: " << error);
596 return false;
597 }
598 } else {
599 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
600 context_->GetDiagnostics(), file->GetSource());
601 if (file_op.xml_to_flatten == nullptr) {
602 return false;
603 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700604 }
605
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700606 file_op.xml_to_flatten->file.config = config_value->config;
607 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700608 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700609 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700610
611 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
612 // else we end up copying the string in the std::make_pair() method,
613 // then creating a StringPiece from the copy, which would cause us
614 // to end up referencing garbage in the map.
615 const StringPiece entry_name(entry->name);
616 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
617 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700618 }
619 }
620
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700621 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700622 for (auto& map_entry : config_sorted_files) {
623 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700624 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700625
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700626 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700627 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
628 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700629 if (versioned_docs.empty()) {
630 error = true;
631 continue;
632 }
633
Adam Lesinskic744ae82017-05-17 19:28:38 -0700634 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
635 std::string dst_path = file_op.dst_path;
636 if (doc->file.config != file_op.config) {
637 // Only add the new versioned configurations.
638 if (context_->IsVerbose()) {
639 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
640 << "auto-versioning resource from config '"
641 << config << "' -> '" << doc->file.config << "'");
642 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700643
Adam Lesinskic744ae82017-05-17 19:28:38 -0700644 dst_path =
645 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
646 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
647 doc->file.source, dst_path, nullptr,
648 context_->GetDiagnostics());
649 if (!result) {
650 return false;
651 }
652 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700653
654 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
655 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700656 }
657 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700658 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
659 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700660 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700661 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700662 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700663 }
664 return !error;
665}
666
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700667static bool WriteStableIdMapToPath(IDiagnostics* diag,
668 const std::unordered_map<ResourceName, ResourceId>& id_map,
669 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700670 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700671 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700672 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673 return false;
674 }
675
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700676 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700677 const ResourceName& name = entry.first;
678 const ResourceId& id = entry.second;
679 fout << name << " = " << id << "\n";
680 }
681
682 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700683 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
684 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700685 return false;
686 }
687
688 return true;
689}
690
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700691static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
692 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700694 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696 return false;
697 }
698
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 out_id_map->clear();
700 size_t line_no = 0;
701 for (StringPiece line : util::Tokenize(content, '\n')) {
702 line_no++;
703 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700704 if (line.empty()) {
705 continue;
706 }
707
708 auto iter = std::find(line.begin(), line.end(), '=');
709 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700710 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711 return false;
712 }
713
714 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700715 StringPiece res_name_str =
716 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
717 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700718 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
719 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700720 return false;
721 }
722
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700723 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
724 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700725 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700726
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700727 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
728 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700729 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
730 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731 return false;
732 }
733
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700735 }
736 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700737}
738
Adam Lesinskifb48d292015-11-07 15:52:13 -0800739class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700740 public:
741 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700742 : options_(options),
743 context_(context),
744 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700745 file_collection_(util::make_unique<io::FileCollection>()) {
746 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700747
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700748 /**
749 * Creates a SymbolTable that loads symbols from the various APKs and caches
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700750 * the results for faster lookup.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700751 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700752 bool LoadSymbolsFromIncludePaths() {
753 std::unique_ptr<AssetManagerSymbolSource> asset_source =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700754 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700755 for (const std::string& path : options_.include_paths) {
756 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700757 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700758 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700759
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700760 // First try to load the file as a static lib.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700761 std::string error_str;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800762 std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
763 if (include_static) {
Adam Lesinskib522f042017-04-21 16:57:59 -0700764 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800765 // Can't include static libraries when not building a static library (they have no IDs
766 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700767 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800768 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700769 return false;
770 }
771
772 // If we are using --no-static-lib-packages, we need to rename the
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800773 // package of this table to our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700774 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800775 // Since package names can differ, and multiple packages can exist in a ResourceTable,
776 // we place the requirement that all static libraries are built with the package
777 // ID 0x7f. So if one is not found, this is an error.
778 if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700779 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800780 } else {
781 context_->GetDiagnostics()->Error(DiagMessage(path)
782 << "no package with ID 0x7f found in static library");
783 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700784 }
785 }
786
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700787 context_->GetExternalSymbols()->AppendSource(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800788 util::make_unique<ResourceTableSymbolSource>(include_static.get()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700789
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800790 static_table_includes_.push_back(std::move(include_static));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700791
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700792 } else if (!error_str.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700793 // We had an error with reading, so fail.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700794 context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700795 return false;
796 }
797
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700798 if (!asset_source->AddAssetPath(path)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800799 context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700800 return false;
801 }
802 }
803
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800804 // Capture the shared libraries so that the final resource table can be properly flattened
805 // with support for shared libraries.
806 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800807 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800808 final_table_.included_packages_[entry.first] = entry.second;
809 }
810 }
811
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700812 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700813 return true;
814 }
815
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800816 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700817 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800818 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
819 if (manifest_el == nullptr) {
820 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700821 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800822
823 AppInfo app_info;
824
825 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
826 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
827 return {};
828 }
829
830 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
831 if (!package_attr) {
832 diag->Error(DiagMessage(xml_res->file.source)
833 << "<manifest> must have a 'package' attribute");
834 return {};
835 }
836 app_info.package = package_attr->value;
837
838 if (xml::Attribute* version_code_attr =
839 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
840 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
841 if (!maybe_code) {
842 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
843 << "invalid android:versionCode '" << version_code_attr->value << "'");
844 return {};
845 }
846 app_info.version_code = maybe_code.value();
847 }
848
849 if (xml::Attribute* revision_code_attr =
850 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
851 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
852 if (!maybe_code) {
853 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
854 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
855 return {};
856 }
857 app_info.revision_code = maybe_code.value();
858 }
859
860 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
861 if (!split_name_attr->value.empty()) {
862 app_info.split_name = split_name_attr->value;
863 }
864 }
865
866 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
867 if (xml::Attribute* min_sdk =
868 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700869 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800870 }
871 }
872 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700873 }
874
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700875 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
876 // Postcondition: ResourceTable has only one package left. All others are
877 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700878 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700879 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700880 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
881 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700882 };
883
884 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700885 for (const auto& package : final_table_.packages) {
886 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700887 // We have a package that is not related to the one we're building!
888 for (const auto& type : package->types) {
889 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700890 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700891
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700892 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700893 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700894 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700895 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
896 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
897 << "generated id '" << res_name
898 << "' for external package '" << package->name
899 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700900 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700901 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
902 << "defined resource '" << res_name
903 << "' for external package '" << package->name
904 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700905 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700906 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700907 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700908 }
909 }
910 }
911 }
912
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700913 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
914 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700915 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700916 return !error;
917 }
918
919 /**
920 * Returns true if no IDs have been set, false otherwise.
921 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700922 bool VerifyNoIdsSet() {
923 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700924 for (const auto& type : package->types) {
925 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800926 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
927 << StringPrintf("%02x", type->id.value())
928 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700929 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700930 }
931
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700932 for (const auto& entry : type->entries) {
933 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700934 ResourceNameRef res_name(package->name, type->type, entry->name);
935 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800936 DiagMessage() << "entry " << res_name << " has ID "
937 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700938 return false;
939 }
940 }
941 }
942 }
943 return true;
944 }
945
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700946 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
947 if (options_.output_to_directory) {
948 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700949 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700950 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700951 }
952 }
953
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700954 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
955 switch (format) {
956 case OutputFormat::kApk: {
957 BigBuffer buffer(1024);
958 TableFlattener flattener(options_.table_flattener_options, &buffer);
959 if (!flattener.Consume(context_, table)) {
960 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
961 return false;
962 }
963
964 io::BigBufferInputStream input_stream(&buffer);
965 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
966 ArchiveEntry::kAlign, writer);
967 } break;
968
969 case OutputFormat::kProto: {
970 pb::ResourceTable pb_table;
971 SerializeTableToPb(*table, &pb_table);
972 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
973 ArchiveEntry::kCompress, writer);
974 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700975 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700976 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700977 }
978
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700979 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700980 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700981 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700982 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700983 return true;
984 }
985
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700986 std::string out_path = options_.generate_java_class_path.value();
987 file::AppendPath(&out_path, file::PackageToPath(out_package));
988 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700989 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
990 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700991 return false;
992 }
993
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700994 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700995
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700996 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700997 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700998 context_->GetDiagnostics()->Error(DiagMessage()
999 << "failed writing to '" << out_path
1000 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001001 return false;
1002 }
1003
Adam Lesinski418763f2017-04-11 17:36:53 -07001004 std::unique_ptr<std::ofstream> fout_text;
1005 if (out_text_symbols_path) {
1006 fout_text =
1007 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
1008 if (!*fout_text) {
1009 context_->GetDiagnostics()->Error(
1010 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
1011 << "': " << android::base::SystemErrorCodeToString(errno));
1012 return false;
1013 }
1014 }
1015
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001016 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -07001017 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -07001018 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001019 return false;
1020 }
1021
1022 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001023 context_->GetDiagnostics()->Error(DiagMessage()
1024 << "failed writing to '" << out_path
1025 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001026 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001027 }
1028 return true;
1029 }
1030
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001031 bool GenerateJavaClasses() {
1032 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1033 std::vector<std::string> packages_to_callback;
1034
1035 JavaClassGeneratorOptions template_options;
1036 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1037 template_options.javadoc_annotations = options_.javadoc_annotations;
1038
1039 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1040 template_options.use_final = false;
1041 }
1042
1043 if (context_->GetPackageType() == PackageType::kSharedLib) {
1044 template_options.use_final = false;
1045 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1046 }
1047
1048 const StringPiece actual_package = context_->GetCompilationPackage();
1049 StringPiece output_package = context_->GetCompilationPackage();
1050 if (options_.custom_java_package) {
1051 // Override the output java package to the custom one.
1052 output_package = options_.custom_java_package.value();
1053 }
1054
1055 // Generate the private symbols if required.
1056 if (options_.private_symbols) {
1057 packages_to_callback.push_back(options_.private_symbols.value());
1058
1059 // If we defined a private symbols package, we only emit Public symbols
1060 // to the original package, and private and public symbols to the private package.
1061 JavaClassGeneratorOptions options = template_options;
1062 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1063 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1064 options)) {
1065 return false;
1066 }
1067 }
1068
1069 // Generate copies of the original package R class but with different package names.
1070 // This is to support non-namespaced builds.
1071 for (const std::string& extra_package : options_.extra_java_packages) {
1072 packages_to_callback.push_back(extra_package);
1073
1074 JavaClassGeneratorOptions options = template_options;
1075 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1076 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1077 return false;
1078 }
1079 }
1080
1081 // Generate R classes for each package that was merged (static library).
1082 // Use the actual package's resources only.
1083 for (const std::string& package : table_merger_->merged_packages()) {
1084 packages_to_callback.push_back(package);
1085
1086 JavaClassGeneratorOptions options = template_options;
1087 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1088 if (!WriteJavaFile(&final_table_, package, package, options)) {
1089 return false;
1090 }
1091 }
1092
1093 // Generate the main public R class.
1094 JavaClassGeneratorOptions options = template_options;
1095
1096 // Only generate public symbols if we have a private package.
1097 if (options_.private_symbols) {
1098 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1099 }
1100
1101 if (options.rewrite_callback_options) {
1102 options.rewrite_callback_options.value().packages_to_callback =
1103 std::move(packages_to_callback);
1104 }
1105
1106 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1107 options_.generate_text_symbols_path)) {
1108 return false;
1109 }
1110
1111 return true;
1112 }
1113
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001114 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1115 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001116 return true;
1117 }
1118
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001119 std::unique_ptr<ClassDefinition> manifest_class =
1120 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001121
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001122 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001123 // Something bad happened, but we already logged it, so exit.
1124 return false;
1125 }
1126
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001127 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001128 // Empty Manifest class, no need to generate it.
1129 return true;
1130 }
1131
1132 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001133 for (const std::string& annotation : options_.javadoc_annotations) {
1134 std::string proper_annotation = "@";
1135 proper_annotation += annotation;
1136 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001137 }
1138
Adam Lesinski0d81f702017-06-27 15:51:09 -07001139 const std::string package_utf8 =
1140 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001141
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001142 std::string out_path = options_.generate_java_class_path.value();
1143 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001144
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001145 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001146 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1147 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001148 return false;
1149 }
1150
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001151 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001152
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001153 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001154 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001155 context_->GetDiagnostics()->Error(DiagMessage()
1156 << "failed writing to '" << out_path
1157 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001158 return false;
1159 }
1160
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001161 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1162 context_->GetDiagnostics()->Error(DiagMessage()
1163 << "failed writing to '" << out_path
1164 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001165 return false;
1166 }
1167 return true;
1168 }
1169
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001170 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001171 if (!out) {
1172 return true;
1173 }
1174
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001175 const std::string& out_path = out.value();
1176 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001177 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001178 context_->GetDiagnostics()->Error(DiagMessage()
1179 << "failed to open '" << out_path
1180 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001181 return false;
1182 }
1183
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001184 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001185 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001186 context_->GetDiagnostics()->Error(DiagMessage()
1187 << "failed writing to '" << out_path
1188 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001189 return false;
1190 }
1191 return true;
1192 }
1193
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001194 std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
1195 std::string* out_error) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001196 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001197 io::ZipFileCollection::Create(input, out_error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001198 if (!collection) {
1199 return {};
1200 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001201 return LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202 }
1203
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001204 std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001205 io::IFile* file = collection->FindFile(kProtoResourceTablePath);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001206 if (!file) {
1207 return {};
1208 }
1209
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001210 std::unique_ptr<io::IData> data = file->OpenAsData();
1211 return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
1212 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001213 }
1214
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001215 bool MergeStaticLibrary(const std::string& input, bool override) {
1216 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001217 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 }
1219
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001220 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001222 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001223 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001224 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001225 return false;
1226 }
1227
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001228 std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001229 if (!table) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001230 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001231 return false;
1232 }
1233
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001234 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001236 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237 return false;
1238 }
1239
1240 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001241 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001242 // Merge all resources as if they were in the compilation package. This is the old behavior
1243 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001244
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001245 // Add the package to the set of --extra-packages so we emit an R.java for each library
1246 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001247 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001248 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001249 }
1250
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001251 // Clear the package name, so as to make the resources look like they are coming from the
1252 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253 pkg->name = "";
Adam Lesinski00451162017-10-03 07:44:08 -07001254 result = table_merger_->Merge(Source(input), table.get(), override, collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255
1256 } else {
1257 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001258 // preserved and resource names are mangled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001259 result =
1260 table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001261 }
1262
1263 if (!result) {
1264 return false;
1265 }
1266
1267 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001268 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001269 return true;
1270 }
1271
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001272 bool MergeResourceTable(io::IFile* file, bool override) {
1273 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001274 context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
1275 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001276 }
1277
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001278 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 if (!data) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001280 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 return false;
1282 }
1283
1284 std::unique_ptr<ResourceTable> table =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001285 LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001286 if (!table) {
1287 return false;
1288 }
1289
Adam Lesinski00451162017-10-03 07:44:08 -07001290 return table_merger_->Merge(file->GetSource(), table.get(), override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001291 }
1292
Adam Lesinski00451162017-10-03 07:44:08 -07001293 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001294 if (context_->IsVerbose()) {
Adam Lesinski00451162017-10-03 07:44:08 -07001295 context_->GetDiagnostics()->Note(DiagMessage()
1296 << "merging '" << compiled_file.name
1297 << "' from compiled file " << compiled_file.source);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001298 }
1299
Adam Lesinski00451162017-10-03 07:44:08 -07001300 if (!table_merger_->MergeFile(compiled_file, override, file)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001301 return false;
1302 }
1303
1304 // Add the exports of this file to the table.
Adam Lesinski00451162017-10-03 07:44:08 -07001305 for (const SourcedResourceName& exported_symbol : compiled_file.exported_symbols) {
1306 ResourceName res_name = exported_symbol.name;
1307 if (res_name.package.empty()) {
1308 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001309 }
1310
Adam Lesinski00451162017-10-03 07:44:08 -07001311 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001312 if (mangled_name) {
1313 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001314 }
1315
1316 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski00451162017-10-03 07:44:08 -07001317 id->SetSource(compiled_file.source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001318 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001319 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1320 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321 if (!result) {
1322 return false;
1323 }
1324 }
1325 return true;
1326 }
1327
Adam Lesinski00451162017-10-03 07:44:08 -07001328 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1329 // If override is true, conflicting resources are allowed to override each other, in order of last
1330 // seen.
1331 // An io::IFileCollection is created from the ZIP file and added to the set of
1332 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001333 bool MergeArchive(const std::string& input, bool override) {
1334 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001335 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001336 }
1337
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001338 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001339 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001340 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001341 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001342 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001343 return false;
1344 }
1345
1346 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001347 for (auto iter = collection->Iterator(); iter->HasNext();) {
1348 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001349 error = true;
1350 }
1351 }
1352
1353 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001354 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001355 return !error;
1356 }
1357
Adam Lesinski00451162017-10-03 07:44:08 -07001358 // Takes a path to load and merge into the master ResourceTable. If override is true,
1359 // conflicting resources are allowed to override each other, in order of last seen.
1360 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1361 // as ZIP archive and the files within are merged individually.
1362 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001363 bool MergePath(const std::string& path, bool override) {
1364 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1365 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1366 return MergeArchive(path, override);
1367 } else if (util::EndsWith(path, ".apk")) {
1368 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001369 }
1370
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001371 io::IFile* file = file_collection_->InsertFile(path);
1372 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001373 }
1374
Adam Lesinski00451162017-10-03 07:44:08 -07001375 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1376 // If override is true, conflicting resources are allowed to override each other, in order of last
1377 // seen.
1378 // All other file types are ignored. This is because these files could be coming from a zip,
1379 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001380 bool MergeFile(io::IFile* file, bool override) {
1381 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001382
Adam Lesinski00451162017-10-03 07:44:08 -07001383 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001384 // Since AAPT compiles these file types and appends .flat to them, seeing
1385 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001386 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1387 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1388 << " file passed as argument. Must be "
1389 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001390 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001391 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1392 if (context_->IsVerbose()) {
1393 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1394 return true;
1395 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001396 }
1397
Adam Lesinski00451162017-10-03 07:44:08 -07001398 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1399 if (input_stream == nullptr) {
1400 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1401 return false;
1402 }
1403
1404 if (input_stream->HadError()) {
1405 context_->GetDiagnostics()->Error(DiagMessage(src)
1406 << "failed to open file: " << input_stream->GetError());
1407 return false;
1408 }
1409
1410 ContainerReaderEntry* entry;
1411 ContainerReader reader(input_stream.get());
1412 while ((entry = reader.Next()) != nullptr) {
1413 if (entry->Type() == ContainerEntryType::kResTable) {
1414 pb::ResourceTable pb_table;
1415 if (!entry->GetResTable(&pb_table)) {
1416 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1417 << entry->GetError());
1418 return false;
1419 }
1420
1421 ResourceTable table;
1422 std::string error;
1423 if (!DeserializeTableFromPb(pb_table, &table, &error)) {
1424 context_->GetDiagnostics()->Error(DiagMessage(src)
1425 << "failed to deserialize resource table: " << error);
1426 return false;
1427 }
1428
1429 if (!table_merger_->Merge(src, &table, override)) {
1430 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1431 return false;
1432 }
1433 } else if (entry->Type() == ContainerEntryType::kResFile) {
1434 pb::internal::CompiledFile pb_compiled_file;
1435 off64_t offset;
1436 size_t len;
1437 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1438 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1439 << entry->GetError());
1440 return false;
1441 }
1442
1443 ResourceFile resource_file;
1444 std::string error;
1445 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1446 context_->GetDiagnostics()->Error(DiagMessage(src)
1447 << "failed to read compiled header: " << error);
1448 return false;
1449 }
1450
1451 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1452 return false;
1453 }
1454 }
1455 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001456 return true;
1457 }
1458
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001459 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1460 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1461 for (const std::string& assets_dir : options_.assets_dirs) {
1462 Maybe<std::vector<std::string>> files =
1463 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1464 if (!files) {
1465 return false;
1466 }
1467
1468 for (const std::string& file : files.value()) {
1469 std::string full_key = "assets/" + file;
1470 std::string full_path = assets_dir;
1471 file::AppendPath(&full_path, file);
1472
1473 auto iter = merged_assets.find(full_key);
1474 if (iter == merged_assets.end()) {
1475 merged_assets.emplace(std::move(full_key),
1476 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1477 } else if (context_->IsVerbose()) {
1478 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1479 << "asset file overrides '" << full_path << "'");
1480 }
1481 }
1482 }
1483
1484 for (auto& entry : merged_assets) {
1485 uint32_t compression_flags = ArchiveEntry::kCompress;
1486 std::string extension = file::GetExtension(entry.first).to_string();
1487 if (options_.extensions_to_not_compress.count(extension) > 0) {
1488 compression_flags = 0u;
1489 }
1490
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001491 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1492 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001493 return false;
1494 }
1495 }
1496 return true;
1497 }
1498
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001499 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1500 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001501 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1502 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001503 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001504 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1505 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001506 if (!result) {
1507 return false;
1508 }
1509
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001510 ResourceFileFlattenerOptions file_flattener_options;
1511 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001512 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1513 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001514 file_flattener_options.no_auto_version = options_.no_auto_version;
1515 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001516 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001517 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1518 file_flattener_options.update_proguard_spec =
1519 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001520 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001522 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001523
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001524 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001525 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001526 return false;
1527 }
1528
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001529 if (!FlattenTable(table, options_.output_format, writer)) {
1530 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1531 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001532 }
1533 return true;
1534 }
1535
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001536 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001537 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001538 std::unique_ptr<xml::XmlResource> manifest_xml =
1539 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1540 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001541 return 1;
1542 }
1543
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001544 // First extract the Package name without modifying it (via --rename-manifest-package).
1545 if (Maybe<AppInfo> maybe_app_info =
1546 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001547 const AppInfo& app_info = maybe_app_info.value();
1548 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001549 }
1550
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001551 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1552 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001553 return 1;
1554 }
1555
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001556 Maybe<AppInfo> maybe_app_info =
1557 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001558 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001559 return 1;
1560 }
1561
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001562 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001563 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001564
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001565 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001566
1567 // Override the package ID when it is "android".
1568 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001569 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001570
1571 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001572 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001573 context_->GetDiagnostics()->Error(
1574 DiagMessage() << "package 'android' can only be built as a regular app");
1575 return 1;
1576 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001577 }
1578
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001579 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001580 return 1;
1581 }
1582
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001583 TableMergerOptions table_merger_options;
1584 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001585 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001586
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001587 if (context_->IsVerbose()) {
1588 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001589 << StringPrintf("linking package '%s' using package ID %02x",
1590 context_->GetCompilationPackage().data(),
1591 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001592 }
1593
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001594 for (const std::string& input : input_files) {
1595 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001596 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001597 return 1;
1598 }
1599 }
1600
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001601 for (const std::string& input : options_.overlay_files) {
1602 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001603 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001604 return 1;
1605 }
1606 }
1607
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001608 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001609 return 1;
1610 }
1611
Adam Lesinskib522f042017-04-21 16:57:59 -07001612 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001613 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001614 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001615 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001616 return 1;
1617 }
1618
1619 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001620 IdAssigner id_assigner(&options_.stable_id_map);
1621 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001622 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001623 return 1;
1624 }
1625
1626 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001627 if (options_.resource_id_map_path) {
1628 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001629 for (auto& type : package->types) {
1630 for (auto& entry : type->entries) {
1631 ResourceName name(package->name, type->type, entry->name);
1632 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001633 options_.stable_id_map[std::move(name)] =
1634 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001635 }
1636 }
1637 }
1638
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001639 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001640 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001641 return 1;
1642 }
1643 }
1644 } else {
1645 // Static libs are merged with other apps, and ID collisions are bad, so
1646 // verify that
1647 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001648 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001649 return 1;
1650 }
1651 }
1652
1653 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001654 context_->SetNameManglerPolicy(
1655 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001656
1657 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001658 context_->GetExternalSymbols()->PrependSource(
1659 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001660
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001661 // Workaround for pre-O runtime that would treat negative resource IDs
1662 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1663 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1664 // are just identifiers.
1665 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1666 if (context_->IsVerbose()) {
1667 context_->GetDiagnostics()->Note(DiagMessage()
1668 << "enabling pre-O feature split ID rewriting");
1669 }
1670 context_->GetExternalSymbols()->SetDelegate(
1671 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1672 }
1673
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001674 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001675 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001676 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001677 return 1;
1678 }
1679
Adam Lesinskib522f042017-04-21 16:57:59 -07001680 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001681 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001682 context_->GetDiagnostics()->Warn(DiagMessage()
1683 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001684 }
1685 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001686 ProductFilter product_filter(options_.products);
1687 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001688 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001689 return 1;
1690 }
1691 }
1692
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001693 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001694 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001695 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001696 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 return 1;
1698 }
1699 }
1700
Adam Lesinskib522f042017-04-21 16:57:59 -07001701 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001702 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001703 context_->GetDiagnostics()->Note(DiagMessage()
1704 << "collapsing resource versions for minimum SDK "
1705 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001706 }
1707
1708 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001709 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001710 return 1;
1711 }
1712 }
1713
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001714 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001715 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001716 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001717 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001718 return 1;
1719 }
1720 }
1721
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001722 proguard::KeepSet proguard_keep_set;
1723 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001724
Adam Lesinskib522f042017-04-21 16:57:59 -07001725 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001726 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001727 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001728 context_->GetDiagnostics()->Warn(DiagMessage()
1729 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001730 }
1731 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001732 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1733 // equal to the minSdk.
1734 options_.split_constraints =
1735 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001736
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001737 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001738 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001739 return 1;
1740 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001741 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001742
1743 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001744 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001745 auto split_constraints_iter = options_.split_constraints.begin();
1746 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001747 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001748 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1749 << "generating split with configurations '"
1750 << util::Joiner(split_constraints_iter->configs, ", ")
1751 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001752 }
1753
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001754 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001755 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001756 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 return 1;
1758 }
1759
1760 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001761 std::unique_ptr<xml::XmlResource> split_manifest =
1762 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001763
1764 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001765 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001766 context_->GetDiagnostics()->Error(DiagMessage()
1767 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001768 return 1;
1769 }
1770
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001771 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1772 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001773 return 1;
1774 }
1775
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001776 ++path_iter;
1777 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001778 }
1779 }
1780
1781 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001782 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001783 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001784 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001785 return 1;
1786 }
1787
1788 bool error = false;
1789 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001790 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001791 // (aka, which package the AndroidManifest.xml is coming from).
1792 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001793 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001794
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001795 XmlReferenceLinker manifest_linker;
1796 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1797 if (options_.generate_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001798 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1799 manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001800 error = true;
1801 }
1802
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001803 if (options_.generate_main_dex_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001804 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1805 manifest_xml.get(),
1806 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001807 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001808 }
1809
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001810 if (options_.generate_java_class_path) {
1811 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001812 error = true;
1813 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001814 }
1815
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001816 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817 // PackageParser will fail if URIs are removed from
1818 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001819 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1820 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 error = true;
1822 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001823 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824 } else {
1825 error = true;
1826 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001827 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001828
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001830 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001831 return 1;
1832 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001833
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001834 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1835 return 1;
1836 }
1837
1838 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001839 return 1;
1840 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001841
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001842 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001843 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001844 return 1;
1845 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001846 }
1847
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001848 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001849 return 1;
1850 }
1851
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001852 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1853 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001854 return 1;
1855 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001856 return 0;
1857 }
1858
1859 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001860 LinkOptions options_;
1861 LinkContext* context_;
1862 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001863
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001864 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001865
1866 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001867 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001868
1869 // A vector of IFileCollections. This is mainly here to keep ownership of the
1870 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001871 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001872
1873 // A vector of ResourceTables. This is here to retain ownership, so that the
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001874 // SymbolTable can use these.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001875 std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001876
1877 // The set of shared libraries being used, mapping their assigned package ID to package name.
1878 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001879};
1880
Chris Warrington820d72a2017-04-27 15:27:01 +01001881int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1882 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001883 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 std::vector<std::string> overlay_arg_list;
1885 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001886 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001887 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001888 Maybe<std::string> preferred_density;
1889 Maybe<std::string> product_list;
1890 bool legacy_x_flag = false;
1891 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001892 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001893 bool shared_lib = false;
1894 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001895 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001896 Maybe<std::string> stable_id_file_path;
1897 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001898 Flags flags =
1899 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001900 .RequiredFlag("-o", "Output path.", &options.output_path)
1901 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001902 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001903 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001904 .OptionalFlagList("-A",
1905 "An assets directory to include in the APK. These are unprocessed.",
1906 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001907 .OptionalFlagList("-R",
1908 "Compilation unit to link, using `overlay` semantics.\n"
1909 "The last conflicting resource given takes precedence.",
1910 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001911 .OptionalFlag("--package-id",
1912 "Specify the package ID to use for this app. Must be greater or equal to\n"
1913 "0x7f and can't be used with --static-lib or --shared-lib.",
1914 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001915 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001916 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001917 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001919 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001920 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001921 &options.generate_main_dex_proguard_rules_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001922 .OptionalSwitch("--no-auto-version",
1923 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001924 &options.no_auto_version)
1925 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001926 "Disables automatic versioning of vector drawables. Use this only\n"
1927 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001928 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001929 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001930 "Disables automatic versioning of transition resources. Use this only\n"
1931 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001932 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001934 "Disables automatic deduping of resources with\n"
1935 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001936 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001937 .OptionalSwitch("--enable-sparse-encoding",
1938 "Enables encoding sparse entries using a binary search tree.\n"
1939 "This decreases APK size at the cost of resource retrieval performance.",
1940 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001941 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001942 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001943 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001944 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001945 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001946 "Comma separated list of configurations to include. The default\n"
1947 "is all configurations.",
1948 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001949 .OptionalFlag("--preferred-density",
1950 "Selects the closest matching density and strips out all others.",
1951 &preferred_density)
1952 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001953 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001954 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001955 &options.output_to_directory)
1956 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001957 "Removes XML namespace prefix and URI information from\n"
1958 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001959 &options.no_xml_namespaces)
1960 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001961 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001962 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001963 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001964 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001965 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001966 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001967 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1968 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001969 &options.manifest_fixer_options.version_code_default)
1970 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001971 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001972 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001973 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1974 &shared_lib)
1975 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001976 .OptionalSwitch("--proto-format",
1977 "Generates compiled resources in Protobuf format.\n"
1978 "Suitable as input to the bundle tool for generating an App Bundle.",
1979 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001980 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001981 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001982 &options.no_static_lib_packages)
1983 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001984 "Generates R.java without the final modifier. This is implied when\n"
1985 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001986 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001987 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001989 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001990 "Emit a file at the given path with a list of name to ID mappings,\n"
1991 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001992 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001993 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001994 "Package name to use when generating R.java for private symbols.\n"
1995 "If not specified, public and private symbols will use the application's\n"
1996 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001997 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001998 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001999 &options.custom_java_package)
2000 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002001 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002002 &extra_java_packages)
2003 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002004 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002005 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002006 .OptionalFlag("--output-text-symbols",
2007 "Generates a text file containing the resource symbols of the R class in\n"
2008 "the specified folder.",
2009 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002010 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002011 "Allows the addition of new resources in overlays without\n"
2012 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002013 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002014 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002015 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002016 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002017 "Changes the name of the target package for instrumentation. Most useful\n"
2018 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002019 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002020 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002021 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002022 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002023 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002024 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2025 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002026 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002027 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002028
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002029 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030 return 1;
2031 }
2032
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002033 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002034 std::vector<std::string> arg_list;
2035 for (const std::string& arg : flags.GetArgs()) {
2036 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002037 const std::string path = arg.substr(1, arg.size() - 1);
2038 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002039 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2040 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002041 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002042 }
2043 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002044 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002045 }
2046 }
2047
2048 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002049 for (const std::string& arg : overlay_arg_list) {
2050 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002051 const std::string path = arg.substr(1, arg.size() - 1);
2052 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002053 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2054 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002055 return 1;
2056 }
2057 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002058 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002059 }
2060 }
2061
2062 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002063 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 }
2065
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002066 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2067 context.GetDiagnostics()->Error(
2068 DiagMessage()
2069 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002070 return 1;
2071 }
2072
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002073 // The default build type.
2074 context.SetPackageType(PackageType::kApp);
2075 context.SetPackageId(kAppPackageId);
2076
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002077 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002078 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002079 context.SetPackageId(0x00);
2080 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002081 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002082 options.output_format = OutputFormat::kProto;
2083 } else if (proto_format) {
2084 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002085 }
2086
2087 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002088 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002089 context.GetDiagnostics()->Error(
2090 DiagMessage() << "can't specify --package-id when not building a regular app");
2091 return 1;
2092 }
2093
2094 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2095 if (!maybe_package_id_int) {
2096 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2097 << "' is not a valid integer");
2098 return 1;
2099 }
2100
2101 const uint32_t package_id_int = maybe_package_id_int.value();
2102 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2103 context.GetDiagnostics()->Error(
2104 DiagMessage() << StringPrintf(
2105 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2106 return 1;
2107 }
2108 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2109 }
2110
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002111 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002112 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002113 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002114 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002115 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002116 }
2117 }
2118
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002119 if (product_list) {
2120 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002121 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002122 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123 }
2124 }
2125 }
2126
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002127 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002128 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002129 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2130 if (filter == nullptr) {
2131 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002132 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002133 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002134 }
2135
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002136 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002137 Maybe<uint16_t> density =
2138 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2139 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002141 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002142 options.table_splitter_options.preferred_densities.push_back(density.value());
2143 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002144
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002145 // Parse the split parameters.
2146 for (const std::string& split_arg : split_args) {
2147 options.split_paths.push_back({});
2148 options.split_constraints.push_back({});
2149 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2150 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002151 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002152 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002153 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002154
Adam Lesinskib522f042017-04-21 16:57:59 -07002155 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002156 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2157 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002158 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002159 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002160 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002161
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002162 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002163 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002164 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2165 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2166 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2167 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2168
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002169 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002170 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002171 options.no_auto_version = true;
2172 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002173 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002174 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002175
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002176 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002177 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002178}
2179
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002180} // namespace aapt