blob: 74edf6e803643b9a7b97ac7f42e3b793de2c0ad6 [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>
Adam Lesinskic6284372017-12-04 13:46:23 -080018#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050020#include <algorithm>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021#include <queue>
22#include <unordered_map>
23#include <vector>
24
25#include "android-base/errors.h"
26#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080027#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080028#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070029
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "AppInfo.h"
31#include "Debug.h"
32#include "Flags.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070033#include "LoadedApk.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080034#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070035#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080036#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070037#include "ResourceValues.h"
38#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070039#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070040#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080041#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080042#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070043#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070044#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070045#include "format/binary/TableFlattener.h"
46#include "format/binary/XmlFlattener.h"
47#include "format/proto/ProtoDeserialize.h"
48#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070049#include "io/BigBufferStream.h"
50#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080051#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070052#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080053#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070054#include "java/JavaClassGenerator.h"
55#include "java/ManifestClassGenerator.h"
56#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070057#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070058#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080059#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080060#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070061#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070062#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080063#include "optimize/ResourceDeduper.h"
64#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070065#include "process/IResourceTableConsumer.h"
66#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080067#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080069#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070070
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070071using ::aapt::io::FileInputStream;
72using ::android::StringPiece;
73using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070074
Adam Lesinski1ab598f2015-08-14 14:26:04 -070075namespace aapt {
76
Adam Lesinskie59f0d82017-10-13 09:36:53 -070077enum 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;
Chris Warrington481f0272018-02-06 14:03:39 +0000115 bool auto_namespace_static_lib = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700116
117 // AndroidManifest.xml massaging options.
118 ManifestFixerOptions manifest_fixer_options;
119
120 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700122
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800123 // Flattening options.
124 TableFlattenerOptions table_flattener_options;
125
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700127 TableSplitterOptions table_splitter_options;
128 std::vector<SplitConstraints> split_constraints;
129 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700130
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700131 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700132 std::unordered_map<ResourceName, ResourceId> stable_id_map;
133 Maybe<std::string> resource_id_map_path;
Todd Kennedy32512992018-04-25 16:45:59 -0700134
135 // When 'true', allow reserved package IDs to be used for applications. Pre-O, the platform
136 // treats negative resource IDs [those with a package ID of 0x80 or higher] as invalid.
137 // In order to work around this limitation, we allow the use of traditionally reserved
138 // resource IDs [those between 0x02 and 0x7E].
139 bool allow_reserved_package_id = false;
Izabela Orlowskad51efe82018-04-24 18:18:29 +0100140
141 // Whether we should fail on definitions of a resource with conflicting visibility.
142 bool strict_visibility = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700143};
144
Adam Lesinski64587af2016-02-18 18:33:06 -0800145class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700146 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100147 LinkContext(IDiagnostics* diagnostics)
148 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700150
Adam Lesinskib522f042017-04-21 16:57:59 -0700151 PackageType GetPackageType() override {
152 return package_type_;
153 }
154
155 void SetPackageType(PackageType type) {
156 package_type_ = type;
157 }
158
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700159 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100160 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700161 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700162
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700163 NameMangler* GetNameMangler() override {
164 return &name_mangler_;
165 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700166
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700167 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
168 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700169 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800170
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700171 const std::string& GetCompilationPackage() override {
172 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700173 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700174
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700175 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800176 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700177 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800178
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700179 uint8_t GetPackageId() override {
180 return package_id_;
181 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700182
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700183 void SetPackageId(uint8_t id) {
184 package_id_ = id;
185 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800186
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700187 SymbolTable* GetExternalSymbols() override {
188 return &symbols_;
189 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800190
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700191 bool IsVerbose() override {
192 return verbose_;
193 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800194
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700195 void SetVerbose(bool val) {
196 verbose_ = val;
197 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800198
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700199 int GetMinSdkVersion() override {
200 return min_sdk_version_;
201 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700202
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700203 void SetMinSdkVersion(int minSdk) {
204 min_sdk_version_ = minSdk;
205 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700206
Chris Warrington481f0272018-02-06 14:03:39 +0000207 bool IsAutoNamespace() override {
208 return auto_namespace_;
209 }
210
211 void SetAutoNamespace(bool val) {
212 auto_namespace_ = val;
213 }
214
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700215 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700216 DISALLOW_COPY_AND_ASSIGN(LinkContext);
217
Adam Lesinskib522f042017-04-21 16:57:59 -0700218 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100219 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700220 NameMangler name_mangler_;
221 std::string compilation_package_;
222 uint8_t package_id_ = 0x0;
223 SymbolTable symbols_;
224 bool verbose_ = false;
225 int min_sdk_version_ = 0;
Chris Warrington481f0272018-02-06 14:03:39 +0000226 bool auto_namespace_ = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700227};
228
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700229// A custom delegate that generates compatible pre-O IDs for use with feature splits.
230// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
231// is interpreted as a negative number. Some verification was wrongly assuming negative values
232// were invalid.
233//
234// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
235// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
236// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800237//
238// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700239class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
240 public:
241 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
242 }
243
244 virtual ~FeatureSplitSymbolTableDelegate() = default;
245
246 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
247 const ResourceName& name,
248 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
249 std::unique_ptr<SymbolTable::Symbol> symbol =
250 DefaultSymbolTableDelegate::FindByName(name, sources);
251 if (symbol == nullptr) {
252 return {};
253 }
254
255 // Check to see if this is an 'id' with the target package.
256 if (name.type == ResourceType::kId && symbol->id) {
257 ResourceId* id = &symbol->id.value();
258 if (id->package_id() > kAppPackageId) {
259 // Rewrite the resource ID to be compatible pre-O.
260 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
261
262 // Check that this doesn't overlap another resource.
263 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
264 // The ID overlaps, so log a message (since this is a weird failure) and fail.
265 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
266 << " for pre-O feature split support");
267 return {};
268 }
269
270 if (context_->IsVerbose()) {
271 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
272 << ") -> (" << rewritten_id << ")");
273 }
274
275 *id = rewritten_id;
276 }
277 }
278 return symbol;
279 }
280
281 private:
282 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
283
284 IAaptContext* context_;
285};
286
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700287static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
288 const StringPiece& path, bool keep_raw_values, bool utf16,
289 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700290 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700291 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
292 << (keep_raw_values ? "true" : "false")
293 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700294 }
295
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700296 switch (format) {
297 case OutputFormat::kApk: {
298 BigBuffer buffer(1024);
299 XmlFlattenerOptions options = {};
300 options.keep_raw_values = keep_raw_values;
301 options.use_utf16 = utf16;
302 XmlFlattener flattener(&buffer, options);
303 if (!flattener.Consume(context, &xml_res)) {
304 return false;
305 }
306
307 io::BigBufferInputStream input_stream(&buffer);
308 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
309 ArchiveEntry::kCompress, writer);
310 } break;
311
312 case OutputFormat::kProto: {
313 pb::XmlNode pb_node;
314 SerializeXmlResourceToPb(xml_res, &pb_node);
315 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
316 writer);
317 } break;
318 }
319 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800320}
321
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700322// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700323static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700324 FileInputStream fin(path);
325 if (fin.HadError()) {
326 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700327 return {};
328 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700329 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800330}
331
Adam Lesinski355f2852016-02-13 20:26:45 -0800332struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700333 bool no_auto_version = false;
334 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900335 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700336 bool no_xml_namespaces = false;
337 bool keep_raw_values = false;
338 bool do_not_compress_anything = false;
339 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700340 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700341 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800342};
343
Adam Lesinskic744ae82017-05-17 19:28:38 -0700344// A sampling of public framework resource IDs.
345struct R {
346 struct attr {
347 enum : uint32_t {
348 paddingLeft = 0x010100d6u,
349 paddingRight = 0x010100d8u,
350 paddingHorizontal = 0x0101053du,
351
352 paddingTop = 0x010100d7u,
353 paddingBottom = 0x010100d9u,
354 paddingVertical = 0x0101053eu,
355
356 layout_marginLeft = 0x010100f7u,
357 layout_marginRight = 0x010100f9u,
358 layout_marginHorizontal = 0x0101053bu,
359
360 layout_marginTop = 0x010100f8u,
361 layout_marginBottom = 0x010100fau,
362 layout_marginVertical = 0x0101053cu,
363 };
364 };
365};
366
Adam Lesinski355f2852016-02-13 20:26:45 -0800367class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700368 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700369 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700370 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800371
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700372 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800373
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700374 private:
375 struct FileOperation {
376 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700377
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700378 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700379 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700380
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700381 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700382 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700383
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700384 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700385 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700386
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700387 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700388 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700389 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800390
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700391 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800392
Adam Lesinskic744ae82017-05-17 19:28:38 -0700393 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
394 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800395
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700396 ResourceFileFlattenerOptions options_;
397 IAaptContext* context_;
398 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700399 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800400};
401
Adam Lesinskic744ae82017-05-17 19:28:38 -0700402ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
403 IAaptContext* context, proguard::KeepSet* keep_set)
404 : options_(options), context_(context), keep_set_(keep_set) {
405 SymbolTable* symm = context_->GetExternalSymbols();
406
407 // Build up the rules for degrading newer attributes to older ones.
408 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
409 // generated from the attribute definitions themselves (b/62028956).
410 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
411 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800412 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
413 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700414 };
415 rules_[R::attr::paddingHorizontal] =
416 util::make_unique<DegradeToManyRule>(std::move(replacements));
417 }
418
419 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
420 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800421 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
422 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700423 };
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,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800431 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700432 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800433 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700434 };
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,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800442 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700443 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800444 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700445 };
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" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000474 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
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 Lesinskia65bbdf2018-02-15 12:39:44 -0800538ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
539 switch (format) {
540 case OutputFormat::kApk:
541 return ResourceFile::Type::kBinaryXml;
542 case OutputFormat::kProto:
543 return ResourceFile::Type::kProtoXml;
544 }
545 LOG_ALWAYS_FATAL("unreachable");
546 return ResourceFile::Type::kUnknown;
547}
548
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700549bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700550 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700551 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800552
Adam Koskidc21dea2017-07-21 10:55:27 -0700553 proguard::CollectResourceReferences(context_, table, keep_set_);
554
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700556 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
557
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700559 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700560 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700561 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800562
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563 // Populate the queue with all files in the ResourceTable.
564 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700565 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700566 // WARNING! Do not insert or remove any resources while executing in this scope. It will
567 // corrupt the iteration order.
568
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700569 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700570 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700571 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700573
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700574 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700576 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700577 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700578 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700579 }
580
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700581 FileOperation file_op;
582 file_op.entry = entry.get();
583 file_op.dst_path = *file_ref->path;
584 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700585 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700586
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700587 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700588 (file_ref->type == ResourceFile::Type::kBinaryXml ||
589 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700590 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700592 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700593 << "failed to open file");
594 return false;
595 }
596
Adam Lesinski00451162017-10-03 07:44:08 -0700597 if (file_ref->type == ResourceFile::Type::kProtoXml) {
598 pb::XmlNode pb_xml_node;
599 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
600 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700601 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700602 return false;
603 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700604
Adam Lesinski00451162017-10-03 07:44:08 -0700605 std::string error;
606 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
607 if (file_op.xml_to_flatten == nullptr) {
608 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700609 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700610 return false;
611 }
612 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700613 std::string error_str;
614 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700615 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700616 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
617 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700618 return false;
619 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700620 }
621
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800622 // Update the type that this file will be written as.
623 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
624
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700625 file_op.xml_to_flatten->file.config = config_value->config;
626 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700627 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700628 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700629
630 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
631 // else we end up copying the string in the std::make_pair() method,
632 // then creating a StringPiece from the copy, which would cause us
633 // to end up referencing garbage in the map.
634 const StringPiece entry_name(entry->name);
635 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
636 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700637 }
638 }
639
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700640 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700641 for (auto& map_entry : config_sorted_files) {
642 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700643 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700644
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700645 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700646 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
647 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700648 if (versioned_docs.empty()) {
649 error = true;
650 continue;
651 }
652
Adam Lesinskic744ae82017-05-17 19:28:38 -0700653 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
654 std::string dst_path = file_op.dst_path;
655 if (doc->file.config != file_op.config) {
656 // Only add the new versioned configurations.
657 if (context_->IsVerbose()) {
658 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
659 << "auto-versioning resource from config '"
660 << config << "' -> '" << doc->file.config << "'");
661 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700662
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800663 const ResourceFile& file = doc->file;
664 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
665
666 std::unique_ptr<FileReference> file_ref =
667 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
668 file_ref->SetSource(doc->file.source);
669 // Update the output format of this XML file.
670 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
671 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
672 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700673 return false;
674 }
675 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700676
677 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
678 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700679 }
680 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700681 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
682 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700683 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700684 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700685 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700686 }
687 return !error;
688}
689
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700690static bool WriteStableIdMapToPath(IDiagnostics* diag,
691 const std::unordered_map<ResourceName, ResourceId>& id_map,
692 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800693 io::FileOutputStream fout(id_map_path);
694 if (fout.HadError()) {
695 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696 return false;
697 }
698
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800699 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700700 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700701 const ResourceName& name = entry.first;
702 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800703 printer.Print(name.to_string());
704 printer.Print(" = ");
705 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800707 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800709 if (fout.HadError()) {
710 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711 return false;
712 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 return true;
714}
715
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700716static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
717 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700718 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700719 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700720 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700721 return false;
722 }
723
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700724 out_id_map->clear();
725 size_t line_no = 0;
726 for (StringPiece line : util::Tokenize(content, '\n')) {
727 line_no++;
728 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700729 if (line.empty()) {
730 continue;
731 }
732
733 auto iter = std::find(line.begin(), line.end(), '=');
734 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700735 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 return false;
737 }
738
739 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700740 StringPiece res_name_str =
741 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
742 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700743 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
744 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700745 return false;
746 }
747
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700748 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
749 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700750 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700751
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700752 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
753 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700754 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
755 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700756 return false;
757 }
758
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700759 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700760 }
761 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700762}
763
Adam Lesinskic6284372017-12-04 13:46:23 -0800764static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
765 using namespace android;
766
767 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
768 // we're looking for the first attribute resource in the system package.
769 const ResTable& table = assets.getResources(true);
770 Res_value val;
771 ssize_t idx = table.getResource(0x01010000, &val, true);
772 if (idx != NO_ERROR) {
773 // Try as a bag.
774 const ResTable::bag_entry* entry;
775 ssize_t cnt = table.lockBag(0x01010000, &entry);
776 if (cnt >= 0) {
777 idx = entry->stringBlock;
778 }
779 table.unlockBag(entry);
780 }
781
782 if (idx < 0) {
783 return 0;
784 }
785 return table.getTableCookie(idx);
786}
787
Adam Lesinskifb48d292015-11-07 15:52:13 -0800788class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700789 public:
790 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700791 : options_(options),
792 context_(context),
793 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700794 file_collection_(util::make_unique<io::FileCollection>()) {
795 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700796
Adam Lesinskic6284372017-12-04 13:46:23 -0800797 void ExtractCompileSdkVersions(android::AssetManager* assets) {
798 using namespace android;
799
800 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
801 if (cookie == 0) {
802 // No Framework assets loaded. Not a failure.
803 return;
804 }
805
806 std::unique_ptr<Asset> manifest(
807 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
808 if (manifest == nullptr) {
809 // No errors.
810 return;
811 }
812
813 std::string error;
814 std::unique_ptr<xml::XmlResource> manifest_xml =
815 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
816 if (manifest_xml == nullptr) {
817 // No errors.
818 return;
819 }
820
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700821 if (!options_.manifest_fixer_options.compile_sdk_version) {
822 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
823 if (attr != nullptr) {
824 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
825 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
826 switch (prim->value.dataType) {
827 case Res_value::TYPE_INT_DEC:
828 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
829 break;
830 case Res_value::TYPE_INT_HEX:
831 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
832 break;
833 default:
834 break;
835 }
836 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
837 compile_sdk_version = *str->value;
838 } else {
839 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800840 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800841 }
842 }
843
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700844 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
845 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
846 if (attr != nullptr) {
847 Maybe<std::string>& compile_sdk_version_codename =
848 options_.manifest_fixer_options.compile_sdk_version_codename;
849 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
850 compile_sdk_version_codename = *str->value;
851 } else {
852 compile_sdk_version_codename = attr->value;
853 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800854 }
855 }
856 }
857
Adam Lesinski8780eb62017-10-31 17:44:39 -0700858 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800859 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700860 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700861 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700862 for (const std::string& path : options_.include_paths) {
863 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700864 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700865 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700866
Adam Lesinski8780eb62017-10-31 17:44:39 -0700867 std::string error;
868 auto zip_collection = io::ZipFileCollection::Create(path, &error);
869 if (zip_collection == nullptr) {
870 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
871 return false;
872 }
873
874 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
875 // Load this as a static library include.
876 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
877 Source(path), std::move(zip_collection), context_->GetDiagnostics());
878 if (static_apk == nullptr) {
879 return false;
880 }
881
Adam Lesinskib522f042017-04-21 16:57:59 -0700882 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800883 // Can't include static libraries when not building a static library (they have no IDs
884 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700885 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800886 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700887 return false;
888 }
889
Adam Lesinski8780eb62017-10-31 17:44:39 -0700890 ResourceTable* table = static_apk->GetResourceTable();
891
892 // If we are using --no-static-lib-packages, we need to rename the package of this table to
893 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700894 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800895 // Since package names can differ, and multiple packages can exist in a ResourceTable,
896 // we place the requirement that all static libraries are built with the package
897 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700898 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700899 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800900 } else {
901 context_->GetDiagnostics()->Error(DiagMessage(path)
902 << "no package with ID 0x7f found in static library");
903 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700904 }
905 }
906
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700907 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700908 util::make_unique<ResourceTableSymbolSource>(table));
909 static_library_includes_.push_back(std::move(static_apk));
910 } else {
911 if (!asset_source->AddAssetPath(path)) {
912 context_->GetDiagnostics()->Error(DiagMessage()
913 << "failed to load include path " << path);
914 return false;
915 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700916 }
917 }
918
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800919 // Capture the shared libraries so that the final resource table can be properly flattened
920 // with support for shared libraries.
921 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700922 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800923 // Capture the included base feature package.
924 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800925 } else if (entry.first == kFrameworkPackageId) {
926 // Try to embed which version of the framework we're compiling against.
927 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
928 // when linking our synthesized 'android:compileSdkVersion' attribute.
929 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
930 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
931 if (symbol != nullptr && symbol->is_public) {
932 // The symbol is present and public, extract the android:versionName and
933 // android:versionCode from the framework AndroidManifest.xml.
934 ExtractCompileSdkVersions(asset_source->GetAssetManager());
935 }
Todd Kennedy32512992018-04-25 16:45:59 -0700936 } else if (asset_source->IsPackageDynamic(entry.first)) {
937 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800938 }
939 }
940
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700941 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700942 return true;
943 }
944
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800945 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700946 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800947 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
948 if (manifest_el == nullptr) {
949 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700950 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800951
952 AppInfo app_info;
953
954 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
955 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
956 return {};
957 }
958
959 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
960 if (!package_attr) {
961 diag->Error(DiagMessage(xml_res->file.source)
962 << "<manifest> must have a 'package' attribute");
963 return {};
964 }
965 app_info.package = package_attr->value;
966
967 if (xml::Attribute* version_code_attr =
968 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
969 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
970 if (!maybe_code) {
971 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
972 << "invalid android:versionCode '" << version_code_attr->value << "'");
973 return {};
974 }
975 app_info.version_code = maybe_code.value();
976 }
977
978 if (xml::Attribute* revision_code_attr =
979 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
980 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
981 if (!maybe_code) {
982 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
983 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
984 return {};
985 }
986 app_info.revision_code = maybe_code.value();
987 }
988
989 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
990 if (!split_name_attr->value.empty()) {
991 app_info.split_name = split_name_attr->value;
992 }
993 }
994
995 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
996 if (xml::Attribute* min_sdk =
997 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700998 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800999 }
1000 }
1001 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001002 }
1003
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001004 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1005 // Postcondition: ResourceTable has only one package left. All others are
1006 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001007 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001008 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001009 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
1010 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001011 };
1012
1013 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001014 for (const auto& package : final_table_.packages) {
1015 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 // We have a package that is not related to the one we're building!
1017 for (const auto& type : package->types) {
1018 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001019 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001020
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001021 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001023 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001024 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1025 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1026 << "generated id '" << res_name
1027 << "' for external package '" << package->name
1028 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001029 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001030 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1031 << "defined resource '" << res_name
1032 << "' for external package '" << package->name
1033 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001034 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001035 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001036 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001037 }
1038 }
1039 }
1040 }
1041
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001042 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1043 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001044 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001045 return !error;
1046 }
1047
1048 /**
1049 * Returns true if no IDs have been set, false otherwise.
1050 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001051 bool VerifyNoIdsSet() {
1052 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001053 for (const auto& type : package->types) {
1054 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001055 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1056 << StringPrintf("%02x", type->id.value())
1057 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001058 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001059 }
1060
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001061 for (const auto& entry : type->entries) {
1062 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001063 ResourceNameRef res_name(package->name, type->type, entry->name);
1064 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001065 DiagMessage() << "entry " << res_name << " has ID "
1066 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001067 return false;
1068 }
1069 }
1070 }
1071 }
1072 return true;
1073 }
1074
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001075 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1076 if (options_.output_to_directory) {
1077 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001078 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001079 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001080 }
1081 }
1082
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001083 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1084 switch (format) {
1085 case OutputFormat::kApk: {
1086 BigBuffer buffer(1024);
1087 TableFlattener flattener(options_.table_flattener_options, &buffer);
1088 if (!flattener.Consume(context_, table)) {
1089 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1090 return false;
1091 }
1092
1093 io::BigBufferInputStream input_stream(&buffer);
1094 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1095 ArchiveEntry::kAlign, writer);
1096 } break;
1097
1098 case OutputFormat::kProto: {
1099 pb::ResourceTable pb_table;
Ryan Mitchella15c2a82018-03-26 11:05:31 -07001100 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001101 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1102 ArchiveEntry::kCompress, writer);
1103 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001104 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001105 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001106 }
1107
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001108 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001109 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001110 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001111 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112 return true;
1113 }
1114
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001115 std::string out_path;
1116 std::unique_ptr<io::FileOutputStream> fout;
1117 if (options_.generate_java_class_path) {
1118 out_path = options_.generate_java_class_path.value();
1119 file::AppendPath(&out_path, file::PackageToPath(out_package));
1120 if (!file::mkdirs(out_path)) {
1121 context_->GetDiagnostics()->Error(DiagMessage()
1122 << "failed to create directory '" << out_path << "'");
1123 return false;
1124 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001125
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001126 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001127
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001128 fout = util::make_unique<io::FileOutputStream>(out_path);
1129 if (fout->HadError()) {
1130 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1131 << "': " << fout->GetError());
1132 return false;
1133 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001134 }
1135
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001136 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001137 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001138 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1139 if (fout_text->HadError()) {
1140 context_->GetDiagnostics()->Error(DiagMessage()
1141 << "failed writing to '" << out_text_symbols_path.value()
1142 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001143 return false;
1144 }
1145 }
1146
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001147 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001148 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001149 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001150 return false;
1151 }
1152
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001153 return true;
1154 }
1155
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001156 bool GenerateJavaClasses() {
1157 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1158 std::vector<std::string> packages_to_callback;
1159
1160 JavaClassGeneratorOptions template_options;
1161 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1162 template_options.javadoc_annotations = options_.javadoc_annotations;
1163
1164 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1165 template_options.use_final = false;
1166 }
1167
1168 if (context_->GetPackageType() == PackageType::kSharedLib) {
1169 template_options.use_final = false;
1170 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1171 }
1172
1173 const StringPiece actual_package = context_->GetCompilationPackage();
1174 StringPiece output_package = context_->GetCompilationPackage();
1175 if (options_.custom_java_package) {
1176 // Override the output java package to the custom one.
1177 output_package = options_.custom_java_package.value();
1178 }
1179
1180 // Generate the private symbols if required.
1181 if (options_.private_symbols) {
1182 packages_to_callback.push_back(options_.private_symbols.value());
1183
1184 // If we defined a private symbols package, we only emit Public symbols
1185 // to the original package, and private and public symbols to the private package.
1186 JavaClassGeneratorOptions options = template_options;
1187 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1188 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1189 options)) {
1190 return false;
1191 }
1192 }
1193
1194 // Generate copies of the original package R class but with different package names.
1195 // This is to support non-namespaced builds.
1196 for (const std::string& extra_package : options_.extra_java_packages) {
1197 packages_to_callback.push_back(extra_package);
1198
1199 JavaClassGeneratorOptions options = template_options;
1200 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1201 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1202 return false;
1203 }
1204 }
1205
1206 // Generate R classes for each package that was merged (static library).
1207 // Use the actual package's resources only.
1208 for (const std::string& package : table_merger_->merged_packages()) {
1209 packages_to_callback.push_back(package);
1210
1211 JavaClassGeneratorOptions options = template_options;
1212 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1213 if (!WriteJavaFile(&final_table_, package, package, options)) {
1214 return false;
1215 }
1216 }
1217
1218 // Generate the main public R class.
1219 JavaClassGeneratorOptions options = template_options;
1220
1221 // Only generate public symbols if we have a private package.
1222 if (options_.private_symbols) {
1223 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1224 }
1225
1226 if (options.rewrite_callback_options) {
1227 options.rewrite_callback_options.value().packages_to_callback =
1228 std::move(packages_to_callback);
1229 }
1230
1231 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1232 options_.generate_text_symbols_path)) {
1233 return false;
1234 }
1235
1236 return true;
1237 }
1238
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001239 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1240 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001241 return true;
1242 }
1243
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001244 std::unique_ptr<ClassDefinition> manifest_class =
1245 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001246
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001247 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001248 // Something bad happened, but we already logged it, so exit.
1249 return false;
1250 }
1251
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001252 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253 // Empty Manifest class, no need to generate it.
1254 return true;
1255 }
1256
1257 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001258 for (const std::string& annotation : options_.javadoc_annotations) {
1259 std::string proper_annotation = "@";
1260 proper_annotation += annotation;
1261 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001262 }
1263
Adam Lesinski0d81f702017-06-27 15:51:09 -07001264 const std::string package_utf8 =
1265 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001266
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001267 std::string out_path = options_.generate_java_class_path.value();
1268 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001269
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001270 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001271 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1272 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001273 return false;
1274 }
1275
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001276 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001277
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001278 io::FileOutputStream fout(out_path);
1279 if (fout.HadError()) {
1280 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1281 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001282 return false;
1283 }
1284
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001285 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1286 fout.Flush();
1287
1288 if (fout.HadError()) {
1289 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1290 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001291 return false;
1292 }
1293 return true;
1294 }
1295
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001296 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001297 if (!out) {
1298 return true;
1299 }
1300
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001301 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001302 io::FileOutputStream fout(out_path);
1303 if (fout.HadError()) {
1304 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1305 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001306 return false;
1307 }
1308
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001309 proguard::WriteKeepSet(keep_set, &fout);
1310 fout.Flush();
1311
1312 if (fout.HadError()) {
1313 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1314 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001315 return false;
1316 }
1317 return true;
1318 }
1319
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001320 bool MergeStaticLibrary(const std::string& input, bool override) {
1321 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001322 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001323 }
1324
Adam Lesinski8780eb62017-10-31 17:44:39 -07001325 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1326 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001327 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001328 return false;
1329 }
1330
Adam Lesinski8780eb62017-10-31 17:44:39 -07001331 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001332 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001333 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001334 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335 return false;
1336 }
1337
1338 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001339 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001340 // Merge all resources as if they were in the compilation package. This is the old behavior
1341 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001342
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001343 // Add the package to the set of --extra-packages so we emit an R.java for each library
1344 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001345 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001346 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001347 }
1348
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001349 // Clear the package name, so as to make the resources look like they are coming from the
1350 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001351 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001352 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001353
1354 } else {
1355 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001356 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001357 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001358 }
1359
1360 if (!result) {
1361 return false;
1362 }
1363
1364 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001365 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001366 return true;
1367 }
1368
Adam Lesinski2427dce2017-11-30 15:10:28 -08001369 bool MergeExportedSymbols(const Source& source,
1370 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001371 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001372 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001373 ResourceName res_name = exported_symbol.name;
1374 if (res_name.package.empty()) {
1375 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376 }
1377
Adam Lesinski00451162017-10-03 07:44:08 -07001378 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 if (mangled_name) {
1380 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001381 }
1382
1383 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001384 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001385 bool result =
1386 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1387 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001388 if (!result) {
1389 return false;
1390 }
1391 }
1392 return true;
1393 }
1394
Adam Lesinski2427dce2017-11-30 15:10:28 -08001395 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1396 if (context_->IsVerbose()) {
1397 context_->GetDiagnostics()->Note(DiagMessage()
1398 << "merging '" << compiled_file.name
1399 << "' from compiled file " << compiled_file.source);
1400 }
1401
1402 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1403 return false;
1404 }
1405 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1406 }
1407
Adam Lesinski00451162017-10-03 07:44:08 -07001408 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1409 // If override is true, conflicting resources are allowed to override each other, in order of last
1410 // seen.
1411 // An io::IFileCollection is created from the ZIP file and added to the set of
1412 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001413 bool MergeArchive(const std::string& input, bool override) {
1414 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001415 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001416 }
1417
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001418 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001419 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001420 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001421 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001422 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001423 return false;
1424 }
1425
1426 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001427 for (auto iter = collection->Iterator(); iter->HasNext();) {
1428 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001429 error = true;
1430 }
1431 }
1432
1433 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001434 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001435 return !error;
1436 }
1437
Adam Lesinski00451162017-10-03 07:44:08 -07001438 // Takes a path to load and merge into the master ResourceTable. If override is true,
1439 // conflicting resources are allowed to override each other, in order of last seen.
1440 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1441 // as ZIP archive and the files within are merged individually.
1442 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001443 bool MergePath(const std::string& path, bool override) {
1444 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1445 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1446 return MergeArchive(path, override);
1447 } else if (util::EndsWith(path, ".apk")) {
1448 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001449 }
1450
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001451 io::IFile* file = file_collection_->InsertFile(path);
1452 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001453 }
1454
Adam Lesinski00451162017-10-03 07:44:08 -07001455 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1456 // If override is true, conflicting resources are allowed to override each other, in order of last
1457 // seen.
1458 // All other file types are ignored. This is because these files could be coming from a zip,
1459 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001460 bool MergeFile(io::IFile* file, bool override) {
1461 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001462
Adam Lesinski00451162017-10-03 07:44:08 -07001463 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001464 // Since AAPT compiles these file types and appends .flat to them, seeing
1465 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001466 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1467 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1468 << " file passed as argument. Must be "
1469 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001470 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001471 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1472 if (context_->IsVerbose()) {
1473 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1474 return true;
1475 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001476 }
1477
Adam Lesinski00451162017-10-03 07:44:08 -07001478 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1479 if (input_stream == nullptr) {
1480 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1481 return false;
1482 }
1483
1484 if (input_stream->HadError()) {
1485 context_->GetDiagnostics()->Error(DiagMessage(src)
1486 << "failed to open file: " << input_stream->GetError());
1487 return false;
1488 }
1489
1490 ContainerReaderEntry* entry;
1491 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001492
1493 if (reader.HadError()) {
1494 context_->GetDiagnostics()->Error(DiagMessage(src)
1495 << "failed to read file: " << reader.GetError());
1496 return false;
1497 }
1498
Adam Lesinski00451162017-10-03 07:44:08 -07001499 while ((entry = reader.Next()) != nullptr) {
1500 if (entry->Type() == ContainerEntryType::kResTable) {
1501 pb::ResourceTable pb_table;
1502 if (!entry->GetResTable(&pb_table)) {
1503 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1504 << entry->GetError());
1505 return false;
1506 }
1507
1508 ResourceTable table;
1509 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001510 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001511 context_->GetDiagnostics()->Error(DiagMessage(src)
1512 << "failed to deserialize resource table: " << error);
1513 return false;
1514 }
1515
1516 if (!table_merger_->Merge(src, &table, override)) {
1517 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1518 return false;
1519 }
1520 } else if (entry->Type() == ContainerEntryType::kResFile) {
1521 pb::internal::CompiledFile pb_compiled_file;
1522 off64_t offset;
1523 size_t len;
1524 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1525 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1526 << entry->GetError());
1527 return false;
1528 }
1529
1530 ResourceFile resource_file;
1531 std::string error;
1532 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1533 context_->GetDiagnostics()->Error(DiagMessage(src)
1534 << "failed to read compiled header: " << error);
1535 return false;
1536 }
1537
1538 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1539 return false;
1540 }
1541 }
1542 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001543 return true;
1544 }
1545
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001546 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1547 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1548 for (const std::string& assets_dir : options_.assets_dirs) {
1549 Maybe<std::vector<std::string>> files =
1550 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1551 if (!files) {
1552 return false;
1553 }
1554
1555 for (const std::string& file : files.value()) {
1556 std::string full_key = "assets/" + file;
1557 std::string full_path = assets_dir;
1558 file::AppendPath(&full_path, file);
1559
1560 auto iter = merged_assets.find(full_key);
1561 if (iter == merged_assets.end()) {
1562 merged_assets.emplace(std::move(full_key),
1563 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1564 } else if (context_->IsVerbose()) {
1565 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1566 << "asset file overrides '" << full_path << "'");
1567 }
1568 }
1569 }
1570
1571 for (auto& entry : merged_assets) {
1572 uint32_t compression_flags = ArchiveEntry::kCompress;
1573 std::string extension = file::GetExtension(entry.first).to_string();
1574 if (options_.extensions_to_not_compress.count(extension) > 0) {
1575 compression_flags = 0u;
1576 }
1577
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001578 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1579 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001580 return false;
1581 }
1582 }
1583 return true;
1584 }
1585
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001586 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1587 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001588 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1589 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001590 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001591 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1592 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001593 if (!result) {
1594 return false;
1595 }
1596
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001597 ResourceFileFlattenerOptions file_flattener_options;
1598 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001599 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1600 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001601 file_flattener_options.no_auto_version = options_.no_auto_version;
1602 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001603 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001604 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1605 file_flattener_options.update_proguard_spec =
1606 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001607 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001608
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001609 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001611 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001612 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001613 return false;
1614 }
1615
Adam Lesinski490595a2017-11-07 17:08:07 -08001616 // Hack to fix b/68820737.
1617 // We need to modify the ResourceTable's package name, but that should NOT affect
1618 // anything else being generated, which includes the Java classes.
1619 // If required, the package name is modifed before flattening, and then modified back
1620 // to its original name.
1621 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001622 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1623 // or higher] as invalid. In order to work around this limitation, we allow the use
1624 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1625 // definition of what a valid "split" package ID is to account for this.
1626 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1627 context_->GetPackageId() != kAppPackageId &&
1628 context_->GetPackageId() != kFrameworkPackageId)
1629 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1630 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001631 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1632 // The base APK is included, and this is a feature split. If the base package is
1633 // the same as this package, then we are building an old style Android Instant Apps feature
1634 // split and must apply this workaround to avoid requiring namespaces support.
1635 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1636 if (package_to_rewrite != nullptr) {
1637 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1638
1639 std::string new_package_name =
1640 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1641 app_info_.split_name.value_or_default("feature").c_str());
1642
1643 if (context_->IsVerbose()) {
1644 context_->GetDiagnostics()->Note(
1645 DiagMessage() << "rewriting resource package name for feature split to '"
1646 << new_package_name << "'");
1647 }
1648 package_to_rewrite->name = new_package_name;
1649 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001650 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001651
1652 bool success = FlattenTable(table, options_.output_format, writer);
1653
1654 if (package_to_rewrite != nullptr) {
1655 // Change the name back.
1656 package_to_rewrite->name = context_->GetCompilationPackage();
1657 if (package_to_rewrite->id) {
1658 table->included_packages_.erase(package_to_rewrite->id.value());
1659 }
1660 }
1661
1662 if (!success) {
1663 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1664 }
1665 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001666 }
1667
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001668 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001669 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001670 std::unique_ptr<xml::XmlResource> manifest_xml =
1671 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1672 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001673 return 1;
1674 }
1675
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001676 // First extract the Package name without modifying it (via --rename-manifest-package).
1677 if (Maybe<AppInfo> maybe_app_info =
1678 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001679 const AppInfo& app_info = maybe_app_info.value();
1680 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001681 }
1682
Adam Lesinskic6284372017-12-04 13:46:23 -08001683 // Now that the compilation package is set, load the dependencies. This will also extract
1684 // the Android framework's versionCode and versionName, if they exist.
1685 if (!LoadSymbolsFromIncludePaths()) {
1686 return 1;
1687 }
1688
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001689 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1690 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001691 return 1;
1692 }
1693
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001694 Maybe<AppInfo> maybe_app_info =
1695 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001696 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 return 1;
1698 }
1699
Adam Lesinski490595a2017-11-07 17:08:07 -08001700 app_info_ = maybe_app_info.value();
1701 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001702
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001703 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001704
1705 // Override the package ID when it is "android".
1706 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001707 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001708
1709 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001710 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001711 context_->GetDiagnostics()->Error(
1712 DiagMessage() << "package 'android' can only be built as a regular app");
1713 return 1;
1714 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001715 }
1716
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001717 TableMergerOptions table_merger_options;
1718 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001719 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001720 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001721
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001722 if (context_->IsVerbose()) {
1723 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001724 << StringPrintf("linking package '%s' using package ID %02x",
1725 context_->GetCompilationPackage().data(),
1726 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001727 }
1728
Adam Lesinski2427dce2017-11-30 15:10:28 -08001729 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1730 // in res/**/*.
1731 {
1732 XmlIdCollector collector;
1733 if (!collector.Consume(context_, manifest_xml.get())) {
1734 return false;
1735 }
1736
1737 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1738 return false;
1739 }
1740 }
1741
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 for (const std::string& input : input_files) {
1743 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001744 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001745 return 1;
1746 }
1747 }
1748
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001749 for (const std::string& input : options_.overlay_files) {
1750 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001751 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001752 return 1;
1753 }
1754 }
1755
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001756 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 return 1;
1758 }
1759
Adam Lesinskib522f042017-04-21 16:57:59 -07001760 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001761 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001762 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001763 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001764 return 1;
1765 }
1766
1767 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001768 IdAssigner id_assigner(&options_.stable_id_map);
1769 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001770 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001771 return 1;
1772 }
1773
1774 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001775 if (options_.resource_id_map_path) {
1776 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001777 for (auto& type : package->types) {
1778 for (auto& entry : type->entries) {
1779 ResourceName name(package->name, type->type, entry->name);
1780 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001781 options_.stable_id_map[std::move(name)] =
1782 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001783 }
1784 }
1785 }
1786
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001787 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001788 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001789 return 1;
1790 }
1791 }
1792 } else {
1793 // Static libs are merged with other apps, and ID collisions are bad, so
1794 // verify that
1795 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001796 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001797 return 1;
1798 }
1799 }
1800
1801 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001802 context_->SetNameManglerPolicy(
1803 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001804
1805 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001806 context_->GetExternalSymbols()->PrependSource(
1807 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001808
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001809 // Workaround for pre-O runtime that would treat negative resource IDs
1810 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1811 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1812 // are just identifiers.
1813 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1814 if (context_->IsVerbose()) {
1815 context_->GetDiagnostics()->Note(DiagMessage()
1816 << "enabling pre-O feature split ID rewriting");
1817 }
1818 context_->GetExternalSymbols()->SetDelegate(
1819 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1820 }
1821
Adam Lesinski34a16872018-02-23 16:18:10 -08001822 // Before we process anything, remove the resources whose default values don't exist.
1823 // We want to force any references to these to fail the build.
1824 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1825 context_->GetDiagnostics()->Error(DiagMessage()
1826 << "failed removing resources with no defaults");
1827 return 1;
1828 }
1829
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001830 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001831 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001832 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001833 return 1;
1834 }
1835
Adam Lesinskib522f042017-04-21 16:57:59 -07001836 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001837 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001838 context_->GetDiagnostics()->Warn(DiagMessage()
1839 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001840 }
1841 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001842 ProductFilter product_filter(options_.products);
1843 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001844 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845 return 1;
1846 }
1847 }
1848
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001849 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001850 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001851 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001852 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001853 return 1;
1854 }
1855 }
1856
Adam Lesinskib522f042017-04-21 16:57:59 -07001857 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001858 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001859 context_->GetDiagnostics()->Note(DiagMessage()
1860 << "collapsing resource versions for minimum SDK "
1861 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001862 }
1863
1864 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001865 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001866 return 1;
1867 }
1868 }
1869
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001870 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001871 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001872 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001873 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001874 return 1;
1875 }
1876 }
1877
Adam Koskidc21dea2017-07-21 10:55:27 -07001878 proguard::KeepSet proguard_keep_set =
1879 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001880 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001881
Adam Lesinskib522f042017-04-21 16:57:59 -07001882 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001883 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001884 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001885 context_->GetDiagnostics()->Warn(DiagMessage()
1886 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001887 }
1888 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001889 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1890 // equal to the minSdk.
1891 options_.split_constraints =
1892 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001893
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001896 return 1;
1897 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001899
1900 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001901 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001902 auto split_constraints_iter = options_.split_constraints.begin();
1903 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1906 << "generating split with configurations '"
1907 << util::Joiner(split_constraints_iter->configs, ", ")
1908 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001909 }
1910
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001911 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001912 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001913 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001914 return 1;
1915 }
1916
1917 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001919 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001920
1921 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001922 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001923 context_->GetDiagnostics()->Error(DiagMessage()
1924 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001925 return 1;
1926 }
1927
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001928 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1929 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001930 return 1;
1931 }
1932
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 ++path_iter;
1934 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001935 }
1936 }
1937
1938 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001939 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001941 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001942 return 1;
1943 }
1944
1945 bool error = false;
1946 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001947 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001948 // (aka, which package the AndroidManifest.xml is coming from).
1949 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001950 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001951
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001952 XmlReferenceLinker manifest_linker;
1953 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1954 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001955 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001956 error = true;
1957 }
1958
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001959 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001960 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001961 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001962 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001963 }
1964
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001965 if (options_.generate_java_class_path) {
1966 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 error = true;
1968 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001969 }
1970
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001971 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001972 // PackageParser will fail if URIs are removed from
1973 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001974 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1975 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001976 error = true;
1977 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001978 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001979 } else {
1980 error = true;
1981 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001982 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001983
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001984 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001985 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001986 return 1;
1987 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001988
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001989 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1990 return 1;
1991 }
1992
1993 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001994 return 1;
1995 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001996
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001997 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001998 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001999 return 1;
2000 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002001 }
2002
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002003 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002004 return 1;
2005 }
2006
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002007 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2008 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002009 return 1;
2010 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011 return 0;
2012 }
2013
2014 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002015 LinkOptions options_;
2016 LinkContext* context_;
2017 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002018
Adam Lesinski490595a2017-11-07 17:08:07 -08002019 AppInfo app_info_;
2020
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002021 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002022
2023 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002024 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002025
Adam Lesinski8780eb62017-10-31 17:44:39 -07002026 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002027 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002028 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029
Adam Lesinski8780eb62017-10-31 17:44:39 -07002030 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2031 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2032
2033 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2034 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002035
2036 // The set of shared libraries being used, mapping their assigned package ID to package name.
2037 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002038
2039 // The package name of the base application, if it is included.
2040 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002041};
2042
Chris Warrington820d72a2017-04-27 15:27:01 +01002043int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2044 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002045 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002046 std::vector<std::string> overlay_arg_list;
2047 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002048 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002049 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002050 Maybe<std::string> preferred_density;
2051 Maybe<std::string> product_list;
2052 bool legacy_x_flag = false;
2053 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002054 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002055 bool shared_lib = false;
2056 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002057 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002058 Maybe<std::string> stable_id_file_path;
2059 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002060 Flags flags =
2061 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002062 .RequiredFlag("-o", "Output path.", &options.output_path)
2063 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002064 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002065 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002066 .OptionalFlagList("-A",
2067 "An assets directory to include in the APK. These are unprocessed.",
2068 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002069 .OptionalFlagList("-R",
2070 "Compilation unit to link, using `overlay` semantics.\n"
2071 "The last conflicting resource given takes precedence.",
2072 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002073 .OptionalFlag("--package-id",
2074 "Specify the package ID to use for this app. Must be greater or equal to\n"
2075 "0x7f and can't be used with --static-lib or --shared-lib.",
2076 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002077 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002078 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002079 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002080 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002081 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002082 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002083 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002084 .OptionalSwitch("--proguard-conditional-keep-rules",
2085 "Generate conditional Proguard keep rules.",
2086 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002087 .OptionalSwitch("--no-auto-version",
2088 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002089 &options.no_auto_version)
2090 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002091 "Disables automatic versioning of vector drawables. Use this only\n"
2092 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002093 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002094 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002095 "Disables automatic versioning of transition resources. Use this only\n"
2096 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002097 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002098 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002099 "Disables automatic deduping of resources with\n"
2100 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002101 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002102 .OptionalSwitch("--enable-sparse-encoding",
2103 "Enables encoding sparse entries using a binary search tree.\n"
2104 "This decreases APK size at the cost of resource retrieval performance.",
2105 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002106 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002107 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002108 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002109 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002110 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002111 "Comma separated list of configurations to include. The default\n"
2112 "is all configurations.",
2113 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002114 .OptionalFlag("--preferred-density",
2115 "Selects the closest matching density and strips out all others.",
2116 &preferred_density)
2117 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002118 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002119 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 &options.output_to_directory)
2121 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002122 "Removes XML namespace prefix and URI information from\n"
2123 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002124 &options.no_xml_namespaces)
2125 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002126 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002128 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002129 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002130 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002131 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002132 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2133 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002134 &options.manifest_fixer_options.version_code_default)
2135 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002136 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002137 &options.manifest_fixer_options.version_name_default)
Todd Kennedy9f6dec12018-04-20 12:29:29 -07002138 .OptionalFlag("--compile-sdk-version-code",
2139 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2140 "present.",
2141 &options.manifest_fixer_options.compile_sdk_version)
2142 .OptionalFlag("--compile-sdk-version-name",
2143 "Version name to inject into the AndroidManifest.xml if none is present.",
2144 &options.manifest_fixer_options.compile_sdk_version_codename)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002145 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2146 &shared_lib)
2147 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002148 .OptionalSwitch("--proto-format",
2149 "Generates compiled resources in Protobuf format.\n"
2150 "Suitable as input to the bundle tool for generating an App Bundle.",
2151 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002152 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002153 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002154 &options.no_static_lib_packages)
Chris Warrington481f0272018-02-06 14:03:39 +00002155 .OptionalSwitch("--auto-namespace-static-lib",
2156 "Automatically namespace resource references when building a static\n"
2157 "library.",
2158 &options.auto_namespace_static_lib)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002159 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002160 "Generates R.java without the final modifier. This is implied when\n"
2161 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002162 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002163 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002164 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002165 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002166 "Emit a file at the given path with a list of name to ID mappings,\n"
2167 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002168 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002169 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002170 "Package name to use when generating R.java for private symbols.\n"
2171 "If not specified, public and private symbols will use the application's\n"
2172 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002173 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002174 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002175 &options.custom_java_package)
2176 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002177 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002178 &extra_java_packages)
2179 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002180 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002181 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002182 .OptionalFlag("--output-text-symbols",
2183 "Generates a text file containing the resource symbols of the R class in\n"
2184 "the specified folder.",
2185 &options.generate_text_symbols_path)
Todd Kennedy32512992018-04-25 16:45:59 -07002186 .OptionalSwitch("--allow-reserved-package-id",
2187 "Allows the use of a reserved package ID. This should on be used for\n"
2188 "packages with a pre-O min-sdk\n",
2189 &options.allow_reserved_package_id)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002190 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002191 "Allows the addition of new resources in overlays without\n"
2192 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002193 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002194 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002195 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002196 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002197 "Changes the name of the target package for instrumentation. Most useful\n"
2198 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002199 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002200 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002201 &options.extensions_to_not_compress)
Izabela Orlowska6f34e0d2018-03-05 14:19:43 +00002202 .OptionalSwitch("--no-compress", "Do not compress any resources.",
Chris Warrington481f0272018-02-06 14:03:39 +00002203 &options.do_not_compress_anything)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002204 .OptionalSwitch("--warn-manifest-validation",
2205 "Treat manifest validation errors as warnings.",
2206 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002207 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002208 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002209 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2210 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002211 &split_args)
Ryan Mitchell444f9bb2018-03-23 13:35:00 -07002212 .OptionalSwitch("-v", "Enables verbose logging.", &verbose)
2213 .OptionalSwitch("--debug-mode",
2214 "Inserts android:debuggable=\"true\" in to the application node of the\n"
2215 "manifest, making the application debuggable even on production devices.",
Izabela Orlowskad51efe82018-04-24 18:18:29 +01002216 &options.manifest_fixer_options.debug_mode)
2217 .OptionalSwitch("--strict-visibility",
2218 "Do not allow overlays with different visibility levels.",
2219 &options.strict_visibility);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002220
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002221 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002222 return 1;
2223 }
2224
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002225 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002226 std::vector<std::string> arg_list;
2227 for (const std::string& arg : flags.GetArgs()) {
2228 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002229 const std::string path = arg.substr(1, arg.size() - 1);
2230 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002231 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2232 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002233 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002234 }
2235 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002236 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002237 }
2238 }
2239
2240 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002241 for (const std::string& arg : overlay_arg_list) {
2242 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002243 const std::string path = arg.substr(1, arg.size() - 1);
2244 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002245 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2246 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002247 return 1;
2248 }
2249 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002250 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002251 }
2252 }
2253
2254 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002255 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002256 }
2257
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002258 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2259 context.GetDiagnostics()->Error(
2260 DiagMessage()
2261 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002262 return 1;
2263 }
2264
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002265 // The default build type.
2266 context.SetPackageType(PackageType::kApp);
2267 context.SetPackageId(kAppPackageId);
2268
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002269 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002270 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002271 context.SetPackageId(0x00);
2272 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002273 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002274 options.output_format = OutputFormat::kProto;
2275 } else if (proto_format) {
2276 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002277 }
2278
Chris Warrington481f0272018-02-06 14:03:39 +00002279 if (options.auto_namespace_static_lib) {
2280 if (!static_lib) {
2281 context.GetDiagnostics()->Error(
2282 DiagMessage() << "--auto-namespace-static-lib can only be used with --static-lib");
2283 return 1;
2284 }
2285 context.SetAutoNamespace(true);
2286 }
2287
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002288 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002289 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002290 context.GetDiagnostics()->Error(
2291 DiagMessage() << "can't specify --package-id when not building a regular app");
2292 return 1;
2293 }
2294
2295 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2296 if (!maybe_package_id_int) {
2297 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2298 << "' is not a valid integer");
2299 return 1;
2300 }
2301
2302 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002303 if (package_id_int > std::numeric_limits<uint8_t>::max()
2304 || package_id_int == kFrameworkPackageId
2305 || (!options.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002306 context.GetDiagnostics()->Error(
2307 DiagMessage() << StringPrintf(
2308 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2309 return 1;
2310 }
2311 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2312 }
2313
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002314 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002315 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002316 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002317 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002318 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002319 }
2320 }
2321
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002322 if (product_list) {
2323 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002324 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002325 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002326 }
2327 }
2328 }
2329
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002330 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002331 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002332 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2333 if (filter == nullptr) {
2334 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002335 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002336 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002337 }
2338
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002339 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002340 Maybe<uint16_t> density =
2341 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2342 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002343 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002344 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002345 options.table_splitter_options.preferred_densities.push_back(density.value());
2346 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002347
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002348 // Parse the split parameters.
2349 for (const std::string& split_arg : split_args) {
2350 options.split_paths.push_back({});
2351 options.split_constraints.push_back({});
2352 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2353 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002354 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002355 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002356 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002357
Adam Lesinskib522f042017-04-21 16:57:59 -07002358 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002359 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2360 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002361 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002362 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002363 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002364
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002365 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002366 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002367 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2368 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2369 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2370 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2371
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002372 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002373 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002374 options.no_auto_version = true;
2375 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002376 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002377 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002378
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002379 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002380 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002381}
2382
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002383} // namespace aapt