blob: e0dae1b7ed4eb6f3262fb5ff5498674203c552ab [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;
Adam Koskidc21dea2017-07-21 10:55:27 -070099 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700100 bool generate_non_final_ids = false;
101 std::vector<std::string> javadoc_annotations;
102 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700103
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 // Optimizations/features.
105 bool no_auto_version = false;
106 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900107 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700108 bool no_resource_deduping = false;
109 bool no_xml_namespaces = false;
110 bool do_not_compress_anything = false;
111 std::unordered_set<std::string> extensions_to_not_compress;
112
113 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700114 bool no_static_lib_packages = false;
115
116 // AndroidManifest.xml massaging options.
117 ManifestFixerOptions manifest_fixer_options;
118
119 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700120 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700121
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800122 // Flattening options.
123 TableFlattenerOptions table_flattener_options;
124
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700125 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700126 TableSplitterOptions table_splitter_options;
127 std::vector<SplitConstraints> split_constraints;
128 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700129
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700130 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700131 std::unordered_map<ResourceName, ResourceId> stable_id_map;
132 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700133};
134
Adam Lesinski64587af2016-02-18 18:33:06 -0800135class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700136 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100137 LinkContext(IDiagnostics* diagnostics)
138 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700139 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700140
Adam Lesinskib522f042017-04-21 16:57:59 -0700141 PackageType GetPackageType() override {
142 return package_type_;
143 }
144
145 void SetPackageType(PackageType type) {
146 package_type_ = type;
147 }
148
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100150 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700151 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700152
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700153 NameMangler* GetNameMangler() override {
154 return &name_mangler_;
155 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700156
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700157 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
158 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700159 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800160
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700161 const std::string& GetCompilationPackage() override {
162 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700163 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700164
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700165 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800166 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700167 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800168
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700169 uint8_t GetPackageId() override {
170 return package_id_;
171 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700172
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700173 void SetPackageId(uint8_t id) {
174 package_id_ = id;
175 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800176
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700177 SymbolTable* GetExternalSymbols() override {
178 return &symbols_;
179 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800180
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700181 bool IsVerbose() override {
182 return verbose_;
183 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800184
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700185 void SetVerbose(bool val) {
186 verbose_ = val;
187 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800188
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700189 int GetMinSdkVersion() override {
190 return min_sdk_version_;
191 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700192
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700193 void SetMinSdkVersion(int minSdk) {
194 min_sdk_version_ = minSdk;
195 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700196
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700197 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700198 DISALLOW_COPY_AND_ASSIGN(LinkContext);
199
Adam Lesinskib522f042017-04-21 16:57:59 -0700200 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100201 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700202 NameMangler name_mangler_;
203 std::string compilation_package_;
204 uint8_t package_id_ = 0x0;
205 SymbolTable symbols_;
206 bool verbose_ = false;
207 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700208};
209
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700210// A custom delegate that generates compatible pre-O IDs for use with feature splits.
211// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
212// is interpreted as a negative number. Some verification was wrongly assuming negative values
213// were invalid.
214//
215// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
216// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
217// an overlap exists.
218class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
219 public:
220 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
221 }
222
223 virtual ~FeatureSplitSymbolTableDelegate() = default;
224
225 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
226 const ResourceName& name,
227 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
228 std::unique_ptr<SymbolTable::Symbol> symbol =
229 DefaultSymbolTableDelegate::FindByName(name, sources);
230 if (symbol == nullptr) {
231 return {};
232 }
233
234 // Check to see if this is an 'id' with the target package.
235 if (name.type == ResourceType::kId && symbol->id) {
236 ResourceId* id = &symbol->id.value();
237 if (id->package_id() > kAppPackageId) {
238 // Rewrite the resource ID to be compatible pre-O.
239 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
240
241 // Check that this doesn't overlap another resource.
242 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
243 // The ID overlaps, so log a message (since this is a weird failure) and fail.
244 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
245 << " for pre-O feature split support");
246 return {};
247 }
248
249 if (context_->IsVerbose()) {
250 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
251 << ") -> (" << rewritten_id << ")");
252 }
253
254 *id = rewritten_id;
255 }
256 }
257 return symbol;
258 }
259
260 private:
261 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
262
263 IAaptContext* context_;
264};
265
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700266static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
267 const StringPiece& path, bool keep_raw_values, bool utf16,
268 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700269 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700270 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
271 << (keep_raw_values ? "true" : "false")
272 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700273 }
274
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700275 switch (format) {
276 case OutputFormat::kApk: {
277 BigBuffer buffer(1024);
278 XmlFlattenerOptions options = {};
279 options.keep_raw_values = keep_raw_values;
280 options.use_utf16 = utf16;
281 XmlFlattener flattener(&buffer, options);
282 if (!flattener.Consume(context, &xml_res)) {
283 return false;
284 }
285
286 io::BigBufferInputStream input_stream(&buffer);
287 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
288 ArchiveEntry::kCompress, writer);
289 } break;
290
291 case OutputFormat::kProto: {
292 pb::XmlNode pb_node;
293 SerializeXmlResourceToPb(xml_res, &pb_node);
294 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
295 writer);
296 } break;
297 }
298 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800299}
300
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700301static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
302 size_t len, IDiagnostics* diag) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700303 pb::ResourceTable pb_table;
304 if (!pb_table.ParseFromArray(data, len)) {
305 diag->Error(DiagMessage(source) << "invalid compiled table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700306 return {};
307 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800308
Adam Lesinski8cdca1b2017-09-28 15:50:03 -0700309 std::unique_ptr<ResourceTable> table = util::make_unique<ResourceTable>();
310 std::string error;
311 if (!DeserializeTableFromPb(pb_table, table.get(), &error)) {
312 diag->Error(DiagMessage(source) << "invalid compiled table: " << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700313 return {};
314 }
315 return table;
Adam Lesinski355f2852016-02-13 20:26:45 -0800316}
317
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700318// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700319static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700320 FileInputStream fin(path);
321 if (fin.HadError()) {
322 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700323 return {};
324 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700325 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800326}
327
Adam Lesinski355f2852016-02-13 20:26:45 -0800328struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700329 bool no_auto_version = false;
330 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900331 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700332 bool no_xml_namespaces = false;
333 bool keep_raw_values = false;
334 bool do_not_compress_anything = false;
335 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700336 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700337 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800338};
339
Adam Lesinskic744ae82017-05-17 19:28:38 -0700340// A sampling of public framework resource IDs.
341struct R {
342 struct attr {
343 enum : uint32_t {
344 paddingLeft = 0x010100d6u,
345 paddingRight = 0x010100d8u,
346 paddingHorizontal = 0x0101053du,
347
348 paddingTop = 0x010100d7u,
349 paddingBottom = 0x010100d9u,
350 paddingVertical = 0x0101053eu,
351
352 layout_marginLeft = 0x010100f7u,
353 layout_marginRight = 0x010100f9u,
354 layout_marginHorizontal = 0x0101053bu,
355
356 layout_marginTop = 0x010100f8u,
357 layout_marginBottom = 0x010100fau,
358 layout_marginVertical = 0x0101053cu,
359 };
360 };
361};
362
Adam Lesinski355f2852016-02-13 20:26:45 -0800363class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700365 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700366 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800367
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700368 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800369
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700370 private:
371 struct FileOperation {
372 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700373
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700374 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700375 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700376
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700377 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700378 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700379
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700380 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700381 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700382
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700383 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700384 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700385 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800386
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700387 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800388
Adam Lesinskic744ae82017-05-17 19:28:38 -0700389 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
390 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800391
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700392 ResourceFileFlattenerOptions options_;
393 IAaptContext* context_;
394 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700395 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800396};
397
Adam Lesinskic744ae82017-05-17 19:28:38 -0700398ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
399 IAaptContext* context, proguard::KeepSet* keep_set)
400 : options_(options), context_(context), keep_set_(keep_set) {
401 SymbolTable* symm = context_->GetExternalSymbols();
402
403 // Build up the rules for degrading newer attributes to older ones.
404 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
405 // generated from the attribute definitions themselves (b/62028956).
406 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
407 std::vector<ReplacementAttr> replacements{
408 {"paddingLeft", R::attr::paddingLeft,
409 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
410 {"paddingRight", R::attr::paddingRight,
411 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
412 };
413 rules_[R::attr::paddingHorizontal] =
414 util::make_unique<DegradeToManyRule>(std::move(replacements));
415 }
416
417 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
418 std::vector<ReplacementAttr> replacements{
419 {"paddingTop", R::attr::paddingTop,
420 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
421 {"paddingBottom", R::attr::paddingBottom,
422 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
423 };
424 rules_[R::attr::paddingVertical] =
425 util::make_unique<DegradeToManyRule>(std::move(replacements));
426 }
427
428 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
429 std::vector<ReplacementAttr> replacements{
430 {"layout_marginLeft", R::attr::layout_marginLeft,
431 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
432 {"layout_marginRight", R::attr::layout_marginRight,
433 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
434 };
435 rules_[R::attr::layout_marginHorizontal] =
436 util::make_unique<DegradeToManyRule>(std::move(replacements));
437 }
438
439 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
440 std::vector<ReplacementAttr> replacements{
441 {"layout_marginTop", R::attr::layout_marginTop,
442 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
443 {"layout_marginBottom", R::attr::layout_marginBottom,
444 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
445 };
446 rules_[R::attr::layout_marginVertical] =
447 util::make_unique<DegradeToManyRule>(std::move(replacements));
448 }
449}
450
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700451uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
452 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700453 return 0;
454 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800455
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700456 for (const std::string& extension : options_.extensions_to_not_compress) {
457 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700458 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800459 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700460 }
461 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800462}
463
Adam Lesinskibb94f322017-07-12 07:41:55 -0700464static bool IsTransitionElement(const std::string& name) {
465 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
466 name == "changeImageTransform" || name == "changeTransform" ||
467 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
468 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
469 name == "transitionManager";
470}
471
472static bool IsVectorElement(const std::string& name) {
473 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
ztenghuiab2a38c2017-10-13 15:56:08 -0700474 name == "objectAnimator" || name == "gradient";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700475}
476
Adam Lesinskic744ae82017-05-17 19:28:38 -0700477template <typename T>
478std::vector<T> make_singleton_vec(T&& val) {
479 std::vector<T> vec;
480 vec.emplace_back(std::forward<T>(val));
481 return vec;
482}
483
484std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
485 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700486 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700488
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700489 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700490 context_->GetDiagnostics()->Note(DiagMessage()
491 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492 }
493
Adam Lesinski00451162017-10-03 07:44:08 -0700494 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
495 // that existing projects have out-of-date references which pass compilation.
496 xml::StripAndroidStudioAttributes(doc->root.get());
497
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700498 XmlReferenceLinker xml_linker;
499 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700500 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700501 }
502
Adam Koskidc21dea2017-07-21 10:55:27 -0700503 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700504 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700505 }
506
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700507 if (options_.no_xml_namespaces) {
508 XmlNamespaceRemover namespace_remover;
509 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700510 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800511 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700512 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800513
Adam Lesinskibb94f322017-07-12 07:41:55 -0700514 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700515 return make_singleton_vec(std::move(file_op->xml_to_flatten));
516 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700517
Adam Lesinskibb94f322017-07-12 07:41:55 -0700518 if (options_.no_version_vectors || options_.no_version_transitions) {
519 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700520 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700521 if (el && el->namespace_uri.empty()) {
522 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
523 (options_.no_version_transitions && IsTransitionElement(el->name))) {
524 return make_singleton_vec(std::move(file_op->xml_to_flatten));
525 }
526 }
527 }
528
Adam Lesinskic744ae82017-05-17 19:28:38 -0700529 const ConfigDescription& config = file_op->config;
530 ResourceEntry* entry = file_op->entry;
531
532 XmlCompatVersioner xml_compat_versioner(&rules_);
533 const util::Range<ApiVersion> api_range{config.sdkVersion,
534 FindNextApiVersionForConfig(entry, config)};
535 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800536}
537
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700538bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700539 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700540 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800541
Adam Koskidc21dea2017-07-21 10:55:27 -0700542 proguard::CollectResourceReferences(context_, table, keep_set_);
543
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700545 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
546
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700548 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700549 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700550 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800551
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 // Populate the queue with all files in the ResourceTable.
553 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700554 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700555 // WARNING! Do not insert or remove any resources while executing in this scope. It will
556 // corrupt the iteration order.
557
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700558 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700559 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700560 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700561 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700562
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700563 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700564 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700565 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700567 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700568 }
569
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700570 FileOperation file_op;
571 file_op.entry = entry.get();
572 file_op.dst_path = *file_ref->path;
573 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700574 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700576 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700577 (file_ref->type == ResourceFile::Type::kBinaryXml ||
578 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700579 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700580 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700581 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700582 << "failed to open file");
583 return false;
584 }
585
Adam Lesinski00451162017-10-03 07:44:08 -0700586 if (file_ref->type == ResourceFile::Type::kProtoXml) {
587 pb::XmlNode pb_xml_node;
588 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
589 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
590 << "failed to parse proto xml");
591 return false;
592 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700593
Adam Lesinski00451162017-10-03 07:44:08 -0700594 std::string error;
595 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
596 if (file_op.xml_to_flatten == nullptr) {
597 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
598 << "failed to deserialize proto xml: " << error);
599 return false;
600 }
601 } else {
602 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
603 context_->GetDiagnostics(), file->GetSource());
604 if (file_op.xml_to_flatten == nullptr) {
605 return false;
606 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700607 }
608
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700609 file_op.xml_to_flatten->file.config = config_value->config;
610 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700611 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700612 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700613
614 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
615 // else we end up copying the string in the std::make_pair() method,
616 // then creating a StringPiece from the copy, which would cause us
617 // to end up referencing garbage in the map.
618 const StringPiece entry_name(entry->name);
619 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
620 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700621 }
622 }
623
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700624 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700625 for (auto& map_entry : config_sorted_files) {
626 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700627 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700628
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700629 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700630 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
631 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700632 if (versioned_docs.empty()) {
633 error = true;
634 continue;
635 }
636
Adam Lesinskic744ae82017-05-17 19:28:38 -0700637 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
638 std::string dst_path = file_op.dst_path;
639 if (doc->file.config != file_op.config) {
640 // Only add the new versioned configurations.
641 if (context_->IsVerbose()) {
642 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
643 << "auto-versioning resource from config '"
644 << config << "' -> '" << doc->file.config << "'");
645 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700646
Adam Lesinskic744ae82017-05-17 19:28:38 -0700647 dst_path =
648 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
649 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
650 doc->file.source, dst_path, nullptr,
651 context_->GetDiagnostics());
652 if (!result) {
653 return false;
654 }
655 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700656
657 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
658 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 }
660 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700661 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
662 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700663 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700664 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700665 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700666 }
667 return !error;
668}
669
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700670static bool WriteStableIdMapToPath(IDiagnostics* diag,
671 const std::unordered_map<ResourceName, ResourceId>& id_map,
672 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700673 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700674 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700675 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 return false;
677 }
678
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700679 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 const ResourceName& name = entry.first;
681 const ResourceId& id = entry.second;
682 fout << name << " = " << id << "\n";
683 }
684
685 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700686 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
687 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700688 return false;
689 }
690
691 return true;
692}
693
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700694static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
695 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700697 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700698 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700699 return false;
700 }
701
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700702 out_id_map->clear();
703 size_t line_no = 0;
704 for (StringPiece line : util::Tokenize(content, '\n')) {
705 line_no++;
706 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707 if (line.empty()) {
708 continue;
709 }
710
711 auto iter = std::find(line.begin(), line.end(), '=');
712 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700713 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700714 return false;
715 }
716
717 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700718 StringPiece res_name_str =
719 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
720 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700721 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
722 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700723 return false;
724 }
725
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700726 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
727 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700728 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700729
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700730 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
731 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700732 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
733 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700734 return false;
735 }
736
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700737 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700738 }
739 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700740}
741
Adam Lesinskifb48d292015-11-07 15:52:13 -0800742class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743 public:
744 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700745 : options_(options),
746 context_(context),
747 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700748 file_collection_(util::make_unique<io::FileCollection>()) {
749 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700750
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700751 /**
752 * Creates a SymbolTable that loads symbols from the various APKs and caches
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700753 * the results for faster lookup.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700754 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700755 bool LoadSymbolsFromIncludePaths() {
756 std::unique_ptr<AssetManagerSymbolSource> asset_source =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700757 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700758 for (const std::string& path : options_.include_paths) {
759 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700760 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700761 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700762
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700763 // First try to load the file as a static lib.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700764 std::string error_str;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800765 std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
766 if (include_static) {
Adam Lesinskib522f042017-04-21 16:57:59 -0700767 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800768 // Can't include static libraries when not building a static library (they have no IDs
769 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700770 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800771 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700772 return false;
773 }
774
775 // If we are using --no-static-lib-packages, we need to rename the
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800776 // package of this table to our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700777 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800778 // Since package names can differ, and multiple packages can exist in a ResourceTable,
779 // we place the requirement that all static libraries are built with the package
780 // ID 0x7f. So if one is not found, this is an error.
781 if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700782 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800783 } else {
784 context_->GetDiagnostics()->Error(DiagMessage(path)
785 << "no package with ID 0x7f found in static library");
786 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700787 }
788 }
789
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700790 context_->GetExternalSymbols()->AppendSource(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800791 util::make_unique<ResourceTableSymbolSource>(include_static.get()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700792
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800793 static_table_includes_.push_back(std::move(include_static));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700794
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700795 } else if (!error_str.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700796 // We had an error with reading, so fail.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700797 context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700798 return false;
799 }
800
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700801 if (!asset_source->AddAssetPath(path)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800802 context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700803 return false;
804 }
805 }
806
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800807 // Capture the shared libraries so that the final resource table can be properly flattened
808 // with support for shared libraries.
809 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800810 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800811 final_table_.included_packages_[entry.first] = entry.second;
812 }
813 }
814
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700815 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700816 return true;
817 }
818
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800819 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700820 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800821 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
822 if (manifest_el == nullptr) {
823 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700824 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800825
826 AppInfo app_info;
827
828 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
829 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
830 return {};
831 }
832
833 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
834 if (!package_attr) {
835 diag->Error(DiagMessage(xml_res->file.source)
836 << "<manifest> must have a 'package' attribute");
837 return {};
838 }
839 app_info.package = package_attr->value;
840
841 if (xml::Attribute* version_code_attr =
842 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
843 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
844 if (!maybe_code) {
845 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
846 << "invalid android:versionCode '" << version_code_attr->value << "'");
847 return {};
848 }
849 app_info.version_code = maybe_code.value();
850 }
851
852 if (xml::Attribute* revision_code_attr =
853 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
854 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
855 if (!maybe_code) {
856 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
857 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
858 return {};
859 }
860 app_info.revision_code = maybe_code.value();
861 }
862
863 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
864 if (!split_name_attr->value.empty()) {
865 app_info.split_name = split_name_attr->value;
866 }
867 }
868
869 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
870 if (xml::Attribute* min_sdk =
871 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700872 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800873 }
874 }
875 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700876 }
877
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700878 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
879 // Postcondition: ResourceTable has only one package left. All others are
880 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700881 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700882 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700883 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
884 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700885 };
886
887 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700888 for (const auto& package : final_table_.packages) {
889 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700890 // We have a package that is not related to the one we're building!
891 for (const auto& type : package->types) {
892 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700893 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700894
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700895 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700896 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700897 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700898 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
899 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
900 << "generated id '" << res_name
901 << "' for external package '" << package->name
902 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700903 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700904 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
905 << "defined resource '" << res_name
906 << "' for external package '" << package->name
907 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700908 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700909 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700910 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700911 }
912 }
913 }
914 }
915
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700916 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
917 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700918 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700919 return !error;
920 }
921
922 /**
923 * Returns true if no IDs have been set, false otherwise.
924 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700925 bool VerifyNoIdsSet() {
926 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700927 for (const auto& type : package->types) {
928 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800929 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
930 << StringPrintf("%02x", type->id.value())
931 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700932 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700933 }
934
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700935 for (const auto& entry : type->entries) {
936 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700937 ResourceNameRef res_name(package->name, type->type, entry->name);
938 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800939 DiagMessage() << "entry " << res_name << " has ID "
940 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700941 return false;
942 }
943 }
944 }
945 }
946 return true;
947 }
948
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700949 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
950 if (options_.output_to_directory) {
951 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700952 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700953 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700954 }
955 }
956
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700957 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
958 switch (format) {
959 case OutputFormat::kApk: {
960 BigBuffer buffer(1024);
961 TableFlattener flattener(options_.table_flattener_options, &buffer);
962 if (!flattener.Consume(context_, table)) {
963 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
964 return false;
965 }
966
967 io::BigBufferInputStream input_stream(&buffer);
968 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
969 ArchiveEntry::kAlign, writer);
970 } break;
971
972 case OutputFormat::kProto: {
973 pb::ResourceTable pb_table;
974 SerializeTableToPb(*table, &pb_table);
975 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
976 ArchiveEntry::kCompress, writer);
977 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700978 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700979 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700980 }
981
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700982 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700983 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700984 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700985 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700986 return true;
987 }
988
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700989 std::string out_path = options_.generate_java_class_path.value();
990 file::AppendPath(&out_path, file::PackageToPath(out_package));
991 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700992 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
993 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700994 return false;
995 }
996
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700997 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700998
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700999 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001000 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001001 context_->GetDiagnostics()->Error(DiagMessage()
1002 << "failed writing to '" << out_path
1003 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 return false;
1005 }
1006
Adam Lesinski418763f2017-04-11 17:36:53 -07001007 std::unique_ptr<std::ofstream> fout_text;
1008 if (out_text_symbols_path) {
1009 fout_text =
1010 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
1011 if (!*fout_text) {
1012 context_->GetDiagnostics()->Error(
1013 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
1014 << "': " << android::base::SystemErrorCodeToString(errno));
1015 return false;
1016 }
1017 }
1018
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001019 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -07001020 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -07001021 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 return false;
1023 }
1024
1025 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001026 context_->GetDiagnostics()->Error(DiagMessage()
1027 << "failed writing to '" << out_path
1028 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001029 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001030 }
1031 return true;
1032 }
1033
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001034 bool GenerateJavaClasses() {
1035 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1036 std::vector<std::string> packages_to_callback;
1037
1038 JavaClassGeneratorOptions template_options;
1039 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1040 template_options.javadoc_annotations = options_.javadoc_annotations;
1041
1042 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1043 template_options.use_final = false;
1044 }
1045
1046 if (context_->GetPackageType() == PackageType::kSharedLib) {
1047 template_options.use_final = false;
1048 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1049 }
1050
1051 const StringPiece actual_package = context_->GetCompilationPackage();
1052 StringPiece output_package = context_->GetCompilationPackage();
1053 if (options_.custom_java_package) {
1054 // Override the output java package to the custom one.
1055 output_package = options_.custom_java_package.value();
1056 }
1057
1058 // Generate the private symbols if required.
1059 if (options_.private_symbols) {
1060 packages_to_callback.push_back(options_.private_symbols.value());
1061
1062 // If we defined a private symbols package, we only emit Public symbols
1063 // to the original package, and private and public symbols to the private package.
1064 JavaClassGeneratorOptions options = template_options;
1065 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1066 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1067 options)) {
1068 return false;
1069 }
1070 }
1071
1072 // Generate copies of the original package R class but with different package names.
1073 // This is to support non-namespaced builds.
1074 for (const std::string& extra_package : options_.extra_java_packages) {
1075 packages_to_callback.push_back(extra_package);
1076
1077 JavaClassGeneratorOptions options = template_options;
1078 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1079 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1080 return false;
1081 }
1082 }
1083
1084 // Generate R classes for each package that was merged (static library).
1085 // Use the actual package's resources only.
1086 for (const std::string& package : table_merger_->merged_packages()) {
1087 packages_to_callback.push_back(package);
1088
1089 JavaClassGeneratorOptions options = template_options;
1090 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1091 if (!WriteJavaFile(&final_table_, package, package, options)) {
1092 return false;
1093 }
1094 }
1095
1096 // Generate the main public R class.
1097 JavaClassGeneratorOptions options = template_options;
1098
1099 // Only generate public symbols if we have a private package.
1100 if (options_.private_symbols) {
1101 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1102 }
1103
1104 if (options.rewrite_callback_options) {
1105 options.rewrite_callback_options.value().packages_to_callback =
1106 std::move(packages_to_callback);
1107 }
1108
1109 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1110 options_.generate_text_symbols_path)) {
1111 return false;
1112 }
1113
1114 return true;
1115 }
1116
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001117 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1118 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001119 return true;
1120 }
1121
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001122 std::unique_ptr<ClassDefinition> manifest_class =
1123 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001124
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001125 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001126 // Something bad happened, but we already logged it, so exit.
1127 return false;
1128 }
1129
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001130 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001131 // Empty Manifest class, no need to generate it.
1132 return true;
1133 }
1134
1135 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001136 for (const std::string& annotation : options_.javadoc_annotations) {
1137 std::string proper_annotation = "@";
1138 proper_annotation += annotation;
1139 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 }
1141
Adam Lesinski0d81f702017-06-27 15:51:09 -07001142 const std::string package_utf8 =
1143 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001144
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001145 std::string out_path = options_.generate_java_class_path.value();
1146 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001147
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001148 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001149 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1150 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001151 return false;
1152 }
1153
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001154 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001155
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001156 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001157 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001158 context_->GetDiagnostics()->Error(DiagMessage()
1159 << "failed writing to '" << out_path
1160 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001161 return false;
1162 }
1163
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001164 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1165 context_->GetDiagnostics()->Error(DiagMessage()
1166 << "failed writing to '" << out_path
1167 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001168 return false;
1169 }
1170 return true;
1171 }
1172
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001173 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001174 if (!out) {
1175 return true;
1176 }
1177
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001178 const std::string& out_path = out.value();
1179 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001180 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001181 context_->GetDiagnostics()->Error(DiagMessage()
1182 << "failed to open '" << out_path
1183 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001184 return false;
1185 }
1186
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001187 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001188 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001189 context_->GetDiagnostics()->Error(DiagMessage()
1190 << "failed writing to '" << out_path
1191 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001192 return false;
1193 }
1194 return true;
1195 }
1196
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001197 std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
1198 std::string* out_error) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001199 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001200 io::ZipFileCollection::Create(input, out_error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001201 if (!collection) {
1202 return {};
1203 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001204 return LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001205 }
1206
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001207 std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001208 io::IFile* file = collection->FindFile(kProtoResourceTablePath);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001209 if (!file) {
1210 return {};
1211 }
1212
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001213 std::unique_ptr<io::IData> data = file->OpenAsData();
1214 return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
1215 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001216 }
1217
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001218 bool MergeStaticLibrary(const std::string& input, bool override) {
1219 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001220 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 }
1222
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001223 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001224 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001225 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001226 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 return false;
1229 }
1230
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001231 std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001232 if (!table) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001233 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001234 return false;
1235 }
1236
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001237 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001238 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001239 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001240 return false;
1241 }
1242
1243 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001244 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001245 // Merge all resources as if they were in the compilation package. This is the old behavior
1246 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001247
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001248 // Add the package to the set of --extra-packages so we emit an R.java for each library
1249 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001250 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001251 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001252 }
1253
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001254 // Clear the package name, so as to make the resources look like they are coming from the
1255 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001256 pkg->name = "";
Adam Lesinski00451162017-10-03 07:44:08 -07001257 result = table_merger_->Merge(Source(input), table.get(), override, collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001258
1259 } else {
1260 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001261 // preserved and resource names are mangled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001262 result =
1263 table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001264 }
1265
1266 if (!result) {
1267 return false;
1268 }
1269
1270 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001271 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001272 return true;
1273 }
1274
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001275 bool MergeResourceTable(io::IFile* file, bool override) {
1276 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001277 context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
1278 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 }
1280
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001281 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001282 if (!data) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001283 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001284 return false;
1285 }
1286
1287 std::unique_ptr<ResourceTable> table =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001288 LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001289 if (!table) {
1290 return false;
1291 }
1292
Adam Lesinski00451162017-10-03 07:44:08 -07001293 return table_merger_->Merge(file->GetSource(), table.get(), override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 }
1295
Adam Lesinski00451162017-10-03 07:44:08 -07001296 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001297 if (context_->IsVerbose()) {
Adam Lesinski00451162017-10-03 07:44:08 -07001298 context_->GetDiagnostics()->Note(DiagMessage()
1299 << "merging '" << compiled_file.name
1300 << "' from compiled file " << compiled_file.source);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001301 }
1302
Adam Lesinski00451162017-10-03 07:44:08 -07001303 if (!table_merger_->MergeFile(compiled_file, override, file)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001304 return false;
1305 }
1306
1307 // Add the exports of this file to the table.
Adam Lesinski00451162017-10-03 07:44:08 -07001308 for (const SourcedResourceName& exported_symbol : compiled_file.exported_symbols) {
1309 ResourceName res_name = exported_symbol.name;
1310 if (res_name.package.empty()) {
1311 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001312 }
1313
Adam Lesinski00451162017-10-03 07:44:08 -07001314 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001315 if (mangled_name) {
1316 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317 }
1318
1319 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski00451162017-10-03 07:44:08 -07001320 id->SetSource(compiled_file.source.WithLine(exported_symbol.line));
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001321 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001322 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1323 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001324 if (!result) {
1325 return false;
1326 }
1327 }
1328 return true;
1329 }
1330
Adam Lesinski00451162017-10-03 07:44:08 -07001331 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1332 // If override is true, conflicting resources are allowed to override each other, in order of last
1333 // seen.
1334 // An io::IFileCollection is created from the ZIP file and added to the set of
1335 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001336 bool MergeArchive(const std::string& input, bool override) {
1337 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001338 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001339 }
1340
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001341 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001342 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001343 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001344 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001345 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001346 return false;
1347 }
1348
1349 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001350 for (auto iter = collection->Iterator(); iter->HasNext();) {
1351 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001352 error = true;
1353 }
1354 }
1355
1356 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001357 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001358 return !error;
1359 }
1360
Adam Lesinski00451162017-10-03 07:44:08 -07001361 // Takes a path to load and merge into the master ResourceTable. If override is true,
1362 // conflicting resources are allowed to override each other, in order of last seen.
1363 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1364 // as ZIP archive and the files within are merged individually.
1365 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001366 bool MergePath(const std::string& path, bool override) {
1367 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1368 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1369 return MergeArchive(path, override);
1370 } else if (util::EndsWith(path, ".apk")) {
1371 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001372 }
1373
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001374 io::IFile* file = file_collection_->InsertFile(path);
1375 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376 }
1377
Adam Lesinski00451162017-10-03 07:44:08 -07001378 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1379 // If override is true, conflicting resources are allowed to override each other, in order of last
1380 // seen.
1381 // All other file types are ignored. This is because these files could be coming from a zip,
1382 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001383 bool MergeFile(io::IFile* file, bool override) {
1384 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001385
Adam Lesinski00451162017-10-03 07:44:08 -07001386 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001387 // Since AAPT compiles these file types and appends .flat to them, seeing
1388 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001389 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1390 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1391 << " file passed as argument. Must be "
1392 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001393 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001394 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1395 if (context_->IsVerbose()) {
1396 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1397 return true;
1398 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001399 }
1400
Adam Lesinski00451162017-10-03 07:44:08 -07001401 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1402 if (input_stream == nullptr) {
1403 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1404 return false;
1405 }
1406
1407 if (input_stream->HadError()) {
1408 context_->GetDiagnostics()->Error(DiagMessage(src)
1409 << "failed to open file: " << input_stream->GetError());
1410 return false;
1411 }
1412
1413 ContainerReaderEntry* entry;
1414 ContainerReader reader(input_stream.get());
1415 while ((entry = reader.Next()) != nullptr) {
1416 if (entry->Type() == ContainerEntryType::kResTable) {
1417 pb::ResourceTable pb_table;
1418 if (!entry->GetResTable(&pb_table)) {
1419 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1420 << entry->GetError());
1421 return false;
1422 }
1423
1424 ResourceTable table;
1425 std::string error;
1426 if (!DeserializeTableFromPb(pb_table, &table, &error)) {
1427 context_->GetDiagnostics()->Error(DiagMessage(src)
1428 << "failed to deserialize resource table: " << error);
1429 return false;
1430 }
1431
1432 if (!table_merger_->Merge(src, &table, override)) {
1433 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1434 return false;
1435 }
1436 } else if (entry->Type() == ContainerEntryType::kResFile) {
1437 pb::internal::CompiledFile pb_compiled_file;
1438 off64_t offset;
1439 size_t len;
1440 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1441 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1442 << entry->GetError());
1443 return false;
1444 }
1445
1446 ResourceFile resource_file;
1447 std::string error;
1448 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1449 context_->GetDiagnostics()->Error(DiagMessage(src)
1450 << "failed to read compiled header: " << error);
1451 return false;
1452 }
1453
1454 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1455 return false;
1456 }
1457 }
1458 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001459 return true;
1460 }
1461
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001462 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1463 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1464 for (const std::string& assets_dir : options_.assets_dirs) {
1465 Maybe<std::vector<std::string>> files =
1466 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1467 if (!files) {
1468 return false;
1469 }
1470
1471 for (const std::string& file : files.value()) {
1472 std::string full_key = "assets/" + file;
1473 std::string full_path = assets_dir;
1474 file::AppendPath(&full_path, file);
1475
1476 auto iter = merged_assets.find(full_key);
1477 if (iter == merged_assets.end()) {
1478 merged_assets.emplace(std::move(full_key),
1479 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1480 } else if (context_->IsVerbose()) {
1481 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1482 << "asset file overrides '" << full_path << "'");
1483 }
1484 }
1485 }
1486
1487 for (auto& entry : merged_assets) {
1488 uint32_t compression_flags = ArchiveEntry::kCompress;
1489 std::string extension = file::GetExtension(entry.first).to_string();
1490 if (options_.extensions_to_not_compress.count(extension) > 0) {
1491 compression_flags = 0u;
1492 }
1493
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001494 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1495 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001496 return false;
1497 }
1498 }
1499 return true;
1500 }
1501
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001502 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1503 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001504 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1505 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001506 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001507 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1508 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001509 if (!result) {
1510 return false;
1511 }
1512
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001513 ResourceFileFlattenerOptions file_flattener_options;
1514 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001515 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1516 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001517 file_flattener_options.no_auto_version = options_.no_auto_version;
1518 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001519 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001520 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1521 file_flattener_options.update_proguard_spec =
1522 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001523 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001524
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001525 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001526
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001527 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001528 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001529 return false;
1530 }
1531
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001532 if (!FlattenTable(table, options_.output_format, writer)) {
1533 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1534 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001535 }
1536 return true;
1537 }
1538
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001539 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001540 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001541 std::unique_ptr<xml::XmlResource> manifest_xml =
1542 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1543 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001544 return 1;
1545 }
1546
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001547 // First extract the Package name without modifying it (via --rename-manifest-package).
1548 if (Maybe<AppInfo> maybe_app_info =
1549 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001550 const AppInfo& app_info = maybe_app_info.value();
1551 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001552 }
1553
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001554 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1555 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001556 return 1;
1557 }
1558
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001559 Maybe<AppInfo> maybe_app_info =
1560 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001561 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001562 return 1;
1563 }
1564
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001565 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001566 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001567
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001568 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001569
1570 // Override the package ID when it is "android".
1571 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001572 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001573
1574 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001575 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001576 context_->GetDiagnostics()->Error(
1577 DiagMessage() << "package 'android' can only be built as a regular app");
1578 return 1;
1579 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001580 }
1581
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001582 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001583 return 1;
1584 }
1585
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001586 TableMergerOptions table_merger_options;
1587 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001588 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001589
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001590 if (context_->IsVerbose()) {
1591 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001592 << StringPrintf("linking package '%s' using package ID %02x",
1593 context_->GetCompilationPackage().data(),
1594 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595 }
1596
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001597 for (const std::string& input : input_files) {
1598 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001599 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001600 return 1;
1601 }
1602 }
1603
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001604 for (const std::string& input : options_.overlay_files) {
1605 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001606 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001607 return 1;
1608 }
1609 }
1610
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001611 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001612 return 1;
1613 }
1614
Adam Lesinskib522f042017-04-21 16:57:59 -07001615 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001616 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001617 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001618 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001619 return 1;
1620 }
1621
1622 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001623 IdAssigner id_assigner(&options_.stable_id_map);
1624 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001625 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001626 return 1;
1627 }
1628
1629 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001630 if (options_.resource_id_map_path) {
1631 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001632 for (auto& type : package->types) {
1633 for (auto& entry : type->entries) {
1634 ResourceName name(package->name, type->type, entry->name);
1635 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001636 options_.stable_id_map[std::move(name)] =
1637 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001638 }
1639 }
1640 }
1641
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001642 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001643 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001644 return 1;
1645 }
1646 }
1647 } else {
1648 // Static libs are merged with other apps, and ID collisions are bad, so
1649 // verify that
1650 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001651 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001652 return 1;
1653 }
1654 }
1655
1656 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001657 context_->SetNameManglerPolicy(
1658 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001659
1660 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001661 context_->GetExternalSymbols()->PrependSource(
1662 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001663
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001664 // Workaround for pre-O runtime that would treat negative resource IDs
1665 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1666 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1667 // are just identifiers.
1668 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1669 if (context_->IsVerbose()) {
1670 context_->GetDiagnostics()->Note(DiagMessage()
1671 << "enabling pre-O feature split ID rewriting");
1672 }
1673 context_->GetExternalSymbols()->SetDelegate(
1674 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1675 }
1676
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001677 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001678 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001679 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001680 return 1;
1681 }
1682
Adam Lesinskib522f042017-04-21 16:57:59 -07001683 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001684 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001685 context_->GetDiagnostics()->Warn(DiagMessage()
1686 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001687 }
1688 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001689 ProductFilter product_filter(options_.products);
1690 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001691 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001692 return 1;
1693 }
1694 }
1695
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001696 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001698 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001699 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001700 return 1;
1701 }
1702 }
1703
Adam Lesinskib522f042017-04-21 16:57:59 -07001704 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001705 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001706 context_->GetDiagnostics()->Note(DiagMessage()
1707 << "collapsing resource versions for minimum SDK "
1708 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001709 }
1710
1711 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001712 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001713 return 1;
1714 }
1715 }
1716
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001717 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001718 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001719 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001720 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001721 return 1;
1722 }
1723 }
1724
Adam Koskidc21dea2017-07-21 10:55:27 -07001725 proguard::KeepSet proguard_keep_set =
1726 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001727 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001728
Adam Lesinskib522f042017-04-21 16:57:59 -07001729 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001730 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001731 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001732 context_->GetDiagnostics()->Warn(DiagMessage()
1733 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001734 }
1735 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001736 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1737 // equal to the minSdk.
1738 options_.split_constraints =
1739 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001740
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001741 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743 return 1;
1744 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001745 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001746
1747 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001749 auto split_constraints_iter = options_.split_constraints.begin();
1750 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001751 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001752 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1753 << "generating split with configurations '"
1754 << util::Joiner(split_constraints_iter->configs, ", ")
1755 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001756 }
1757
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001758 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001759 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001760 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001761 return 1;
1762 }
1763
1764 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001765 std::unique_ptr<xml::XmlResource> split_manifest =
1766 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001767
1768 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001769 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001770 context_->GetDiagnostics()->Error(DiagMessage()
1771 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001772 return 1;
1773 }
1774
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001775 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1776 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001777 return 1;
1778 }
1779
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001780 ++path_iter;
1781 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001782 }
1783 }
1784
1785 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001786 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001787 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001788 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001789 return 1;
1790 }
1791
1792 bool error = false;
1793 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001794 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795 // (aka, which package the AndroidManifest.xml is coming from).
1796 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001797 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001798
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001799 XmlReferenceLinker manifest_linker;
1800 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1801 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001802 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001803 error = true;
1804 }
1805
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001806 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001807 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001808 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001809 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001810 }
1811
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001812 if (options_.generate_java_class_path) {
1813 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001814 error = true;
1815 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001816 }
1817
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001818 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001819 // PackageParser will fail if URIs are removed from
1820 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001821 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1822 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001823 error = true;
1824 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001825 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 } else {
1827 error = true;
1828 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001829 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001830
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001831 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001832 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001833 return 1;
1834 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001835
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001836 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1837 return 1;
1838 }
1839
1840 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001841 return 1;
1842 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001843
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001844 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001845 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001846 return 1;
1847 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848 }
1849
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001850 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001851 return 1;
1852 }
1853
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1855 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001856 return 1;
1857 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001858 return 0;
1859 }
1860
1861 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001862 LinkOptions options_;
1863 LinkContext* context_;
1864 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001865
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001866 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867
1868 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001870
1871 // A vector of IFileCollections. This is mainly here to keep ownership of the
1872 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001873 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001874
1875 // A vector of ResourceTables. This is here to retain ownership, so that the
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001876 // SymbolTable can use these.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001877 std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001878
1879 // The set of shared libraries being used, mapping their assigned package ID to package name.
1880 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001881};
1882
Chris Warrington820d72a2017-04-27 15:27:01 +01001883int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1884 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001885 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001886 std::vector<std::string> overlay_arg_list;
1887 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001888 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001889 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001890 Maybe<std::string> preferred_density;
1891 Maybe<std::string> product_list;
1892 bool legacy_x_flag = false;
1893 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001894 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001895 bool shared_lib = false;
1896 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001897 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 Maybe<std::string> stable_id_file_path;
1899 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001900 Flags flags =
1901 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001902 .RequiredFlag("-o", "Output path.", &options.output_path)
1903 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001906 .OptionalFlagList("-A",
1907 "An assets directory to include in the APK. These are unprocessed.",
1908 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001909 .OptionalFlagList("-R",
1910 "Compilation unit to link, using `overlay` semantics.\n"
1911 "The last conflicting resource given takes precedence.",
1912 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001913 .OptionalFlag("--package-id",
1914 "Specify the package ID to use for this app. Must be greater or equal to\n"
1915 "0x7f and can't be used with --static-lib or --shared-lib.",
1916 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001917 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001919 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001920 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001921 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001922 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001923 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07001924 .OptionalSwitch("--proguard-conditional-keep-rules",
1925 "Generate conditional Proguard keep rules.",
1926 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001927 .OptionalSwitch("--no-auto-version",
1928 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 &options.no_auto_version)
1930 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 "Disables automatic versioning of vector drawables. Use this only\n"
1932 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001934 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001935 "Disables automatic versioning of transition resources. Use this only\n"
1936 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001937 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001938 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001939 "Disables automatic deduping of resources with\n"
1940 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001941 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001942 .OptionalSwitch("--enable-sparse-encoding",
1943 "Enables encoding sparse entries using a binary search tree.\n"
1944 "This decreases APK size at the cost of resource retrieval performance.",
1945 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001946 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001947 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001948 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001949 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001950 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001951 "Comma separated list of configurations to include. The default\n"
1952 "is all configurations.",
1953 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001954 .OptionalFlag("--preferred-density",
1955 "Selects the closest matching density and strips out all others.",
1956 &preferred_density)
1957 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001958 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001959 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001960 &options.output_to_directory)
1961 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001962 "Removes XML namespace prefix and URI information from\n"
1963 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001964 &options.no_xml_namespaces)
1965 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001966 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001967 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001968 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001969 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001970 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001971 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001972 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1973 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001974 &options.manifest_fixer_options.version_code_default)
1975 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001976 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001977 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001978 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1979 &shared_lib)
1980 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001981 .OptionalSwitch("--proto-format",
1982 "Generates compiled resources in Protobuf format.\n"
1983 "Suitable as input to the bundle tool for generating an App Bundle.",
1984 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001986 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001987 &options.no_static_lib_packages)
1988 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001989 "Generates R.java without the final modifier. This is implied when\n"
1990 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001991 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001992 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001993 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001994 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001995 "Emit a file at the given path with a list of name to ID mappings,\n"
1996 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001997 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001998 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001999 "Package name to use when generating R.java for private symbols.\n"
2000 "If not specified, public and private symbols will use the application's\n"
2001 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002002 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002003 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002004 &options.custom_java_package)
2005 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002006 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002007 &extra_java_packages)
2008 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002009 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002010 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002011 .OptionalFlag("--output-text-symbols",
2012 "Generates a text file containing the resource symbols of the R class in\n"
2013 "the specified folder.",
2014 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002015 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002016 "Allows the addition of new resources in overlays without\n"
2017 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002018 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002019 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002020 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002021 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002022 "Changes the name of the target package for instrumentation. Most useful\n"
2023 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002024 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002025 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002026 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002027 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002028 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002029 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2030 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002031 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002032 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002033
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002034 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002035 return 1;
2036 }
2037
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002038 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002039 std::vector<std::string> arg_list;
2040 for (const std::string& arg : flags.GetArgs()) {
2041 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002042 const std::string path = arg.substr(1, arg.size() - 1);
2043 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002044 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2045 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002046 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002047 }
2048 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002049 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002050 }
2051 }
2052
2053 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002054 for (const std::string& arg : overlay_arg_list) {
2055 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002056 const std::string path = arg.substr(1, arg.size() - 1);
2057 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002058 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2059 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002060 return 1;
2061 }
2062 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002063 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 }
2065 }
2066
2067 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002068 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002069 }
2070
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002071 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2072 context.GetDiagnostics()->Error(
2073 DiagMessage()
2074 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002075 return 1;
2076 }
2077
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002078 // The default build type.
2079 context.SetPackageType(PackageType::kApp);
2080 context.SetPackageId(kAppPackageId);
2081
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002082 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002083 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002084 context.SetPackageId(0x00);
2085 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002086 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002087 options.output_format = OutputFormat::kProto;
2088 } else if (proto_format) {
2089 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002090 }
2091
2092 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002093 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002094 context.GetDiagnostics()->Error(
2095 DiagMessage() << "can't specify --package-id when not building a regular app");
2096 return 1;
2097 }
2098
2099 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2100 if (!maybe_package_id_int) {
2101 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2102 << "' is not a valid integer");
2103 return 1;
2104 }
2105
2106 const uint32_t package_id_int = maybe_package_id_int.value();
2107 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2108 context.GetDiagnostics()->Error(
2109 DiagMessage() << StringPrintf(
2110 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2111 return 1;
2112 }
2113 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2114 }
2115
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002116 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002117 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002118 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002119 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002120 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002121 }
2122 }
2123
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002124 if (product_list) {
2125 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002126 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002127 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002128 }
2129 }
2130 }
2131
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002132 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002133 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002134 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2135 if (filter == nullptr) {
2136 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002137 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002138 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002139 }
2140
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002141 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002142 Maybe<uint16_t> density =
2143 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2144 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002145 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002146 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002147 options.table_splitter_options.preferred_densities.push_back(density.value());
2148 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002149
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002150 // Parse the split parameters.
2151 for (const std::string& split_arg : split_args) {
2152 options.split_paths.push_back({});
2153 options.split_constraints.push_back({});
2154 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2155 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002156 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002157 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002158 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002159
Adam Lesinskib522f042017-04-21 16:57:59 -07002160 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002161 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2162 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002163 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002164 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002165 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002166
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002167 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002168 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002169 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2170 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2171 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2172 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2173
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002174 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002175 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002176 options.no_auto_version = true;
2177 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002178 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002179 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002180
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002181 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002182 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002183}
2184
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002185} // namespace aapt